diff --git a/History.txt b/History.txt index 2e79ad47..6337e9df 100644 --- a/History.txt +++ b/History.txt @@ -5,6 +5,13 @@ Company : SHTRIH-M www.shtrih-m.ru (495) 787-6090 Url : https://github.com/shtrih-m/javapos_shtrih +******************************************************************************** + + 05.06.2023 + deviceServiceVersion = 1013697 + + [-] Fixed error with socket connection + ******************************************************************************** 14.04.2023 diff --git a/Source/Core/src/com/shtrih/fiscalprinter/command/AmountItem.java b/Source/Core/src/com/shtrih/fiscalprinter/command/AmountItem.java index 38dff247..39aee043 100644 --- a/Source/Core/src/com/shtrih/fiscalprinter/command/AmountItem.java +++ b/Source/Core/src/com/shtrih/fiscalprinter/command/AmountItem.java @@ -19,7 +19,7 @@ public class AmountItem { private int tax2; private int tax3; private int tax4; - private String text; + private String text = ""; /** Creates a new instance of AmountItem */ public AmountItem() { diff --git a/Source/Core/src/com/shtrih/fiscalprinter/command/PrinterConst.java b/Source/Core/src/com/shtrih/fiscalprinter/command/PrinterConst.java index 764ab094..a6bda283 100644 --- a/Source/Core/src/com/shtrih/fiscalprinter/command/PrinterConst.java +++ b/Source/Core/src/com/shtrih/fiscalprinter/command/PrinterConst.java @@ -16,6 +16,32 @@ public interface PrinterConst { + // /////////////////////////////////////////////////////////////////// + // Duplicate document text + + public static final String SFiscalSign = "ФП"; + public static final String SSaleText = "ПРОДАЖА"; + public static final String SBuyText = "ПОКУПКА"; + public static final String SRetSaleText = "ВОЗВРАТ ПРОДАЖИ"; + public static final String SRetBuyText = "ВОЗВРАТ ПОКУПКИ"; + public static final String SCashInText = "ВНЕСЕНИЕ"; + public static final String SCashOutText = "ВЫПЛАТА"; + public static final String SStornoText = "СТОРНО"; + public static final String STotalText = "ВСЕГО"; + public static final String SRoundingText = "ОКРУГЛЕНИЕ"; + public static final String SDiscountText = "СКИДКА"; + public static final String SChargeText = "НАДБАВКА"; + public static final String SReceiptTotal = "ИТОГ"; + public static final String SChangeText = "СДАЧА"; + public static final String SReceiptCancelled = "ЧЕК АННУЛИРОВАН"; + public static final String SDiscountStornoText = "СТОРНО СКИДКИ"; + public static final String SChargeStornoText = "СТОРНО НАДБАВКИ"; + public static final String SXReportText = "СУТОЧНЫЙ ОТЧЕТ БЕЗ ГАШЕНИЯ"; + public static final String SZReportText = "СУТОЧНЫЙ ОТЧЕТ С ГАШЕНИЕМ"; + public static final String SDayClosed = "СМЕНА ЗАКРЫТА"; + public static final String SINN = "ИНН"; + public static final String[] docNames = {SSaleText, SBuyText, SRetSaleText, SRetBuyText}; + // /////////////////////////////////////////////////////////////////// // Print mode diff --git a/Source/Core/src/com/shtrih/fiscalprinter/command/TextDocumentFilter.java b/Source/Core/src/com/shtrih/fiscalprinter/command/TextDocumentFilter.java index a0c3e89d..9b9d79ff 100644 --- a/Source/Core/src/com/shtrih/fiscalprinter/command/TextDocumentFilter.java +++ b/Source/Core/src/com/shtrih/fiscalprinter/command/TextDocumentFilter.java @@ -43,7 +43,6 @@ public class TextDocumentFilter implements IPrinterEvents { private XReport report = new XReport(); private final String[] paymentNames = new String[16]; private final List operators = new ArrayList(); - private List docLines = new Vector(); private SKLStorage storage; private SKLStorage lastDoc; @@ -69,6 +68,10 @@ public class TextDocumentFilter implements IPrinterEvents { private static String SDayClosed = "СМЕНА ЗАКРЫТА"; public static final String SINN = "ИНН"; private static String[] docNames = {SSaleText, SBuyText, SRetSaleText, SRetBuyText}; + public boolean receiptEnabled = false; + public boolean isDocumentActive = false; + private final List lines = new ArrayList(); + public TextDocumentFilter() { } @@ -78,7 +81,6 @@ public void init(SMFiscalPrinter printer) throws Exception this.printer = printer; saveToStorage = printer.getParams().textReportEnabled; lineLength = printer.getMessageLength(FontNumber.getNormalFont()); - readLastDoc(); } public boolean getEnabled() { @@ -139,11 +141,15 @@ public void afterCommand(PrinterCommand command) throws Exception { switch (command.getCode()) { case 0x17: - add(((PrintString) command).getLine()); + if (isDocumentActive){ + add(((PrintString) command).getLine()); + } break; case 0x2F: + if (isDocumentActive){ add(((PrintStringFont) command).getLine()); + } break; case 0x40: @@ -226,15 +232,6 @@ public void afterCommand(PrinterCommand command) throws Exception { private void openReceipt(OpenReceipt command) throws Exception { openReceipt2(command.getReceiptType()); - clearLastDoc(); - } - - private void clearLastDoc() { - docLines.clear(); - File file = new File(getLastDocFilePath()); - if (!file.delete()){ - logger.error("Failed to delete file, " + getLastDocFilePath()); - } } private void openReceipt2(int receiptType) throws Exception { @@ -396,34 +393,40 @@ private String getPaymentName(int paymentIndex) throws Exception } private void printSale(PrintSale command) throws Exception { + if (!receiptEnabled) return; operatorNumber = command.getOperator(); openReceipt2(PrinterConst.SMFP_RECTYPE_SALE); printReceiptItem(command.getItem()); } private void printSale(FSPrintRecItem command) throws Exception { + if (!receiptEnabled) return; printReceiptItem(command.getItem()); } private void printRefund(PrintRefund command) throws Exception { + if (!receiptEnabled) return; operatorNumber = command.getOperator(); openReceipt2(PrinterConst.SMFP_RECTYPE_BUY); printReceiptItem(command.getItem()); } private void printVoidSale(PrintVoidSale command) throws Exception { + if (!receiptEnabled) return; operatorNumber = command.getOperator(); openReceipt2(PrinterConst.SMFP_RECTYPE_RETSALE); printReceiptItem(command.getItem()); } private void printVoidRefund(PrintVoidRefund command) throws Exception { + if (!receiptEnabled) return; operatorNumber = command.getOperator(); openReceipt2(PrinterConst.SMFP_RECTYPE_RETBUY); printReceiptItem(command.getItem()); } private void printVoidItem(PrintVoidItem command) throws Exception { + if (!receiptEnabled) return; operatorNumber = command.getOperator(); PriceItem item = command.getItem(); // Line 1 @@ -628,7 +631,6 @@ public void connect() throws Exception { } public XReport readXReport() throws Exception { - clearLastDoc(); XReport report = new XReport(); FMTotals totals = printer.readFPTotals(1); report.salesAmountBefore = totals.getSalesAmount(); @@ -669,7 +671,6 @@ public XReport readXReport() throws Exception { } public void printCashIn(PrintCashIn command) throws Exception { - clearLastDoc(); isDocumentPrinted = true; operatorNumber = command.getOperator(); long docNumber = printer.readCashRegister(155); @@ -682,7 +683,6 @@ public void printCashIn(PrintCashIn command) throws Exception { } public void printCashOut(PrintCashOut command) throws Exception { - clearLastDoc(); isDocumentPrinted = true; operatorNumber = command.getOperator(); long docNumber = printer.readCashRegister(156); @@ -704,9 +704,12 @@ public void add(String text, long value) throws Exception { private void beginDocument() throws Exception { printReceiptHeader(); + isDocumentActive = true; + lines.clear(); } private void endDocument() throws Exception { + isDocumentActive = false; } private void printReceiptHeader() throws Exception { @@ -968,10 +971,6 @@ public void add(String line) throws Exception } } - public List getDocLines() { - return docLines; - } - private SKLStorage getStorage() throws Exception { if (storage == null) { String filePath = SysUtils.getFilesPath() + printer.getParams().textReportFileName; @@ -980,44 +979,13 @@ private SKLStorage getStorage() throws Exception { return storage; } - public static String getLastDocFilePath() { - return SysUtils.getFilesPath() + "document.txt"; + public List getLines(){ + return lines; } - - private void readLastDoc() { - try - { - docLines.clear(); - File file = new File(getLastDocFilePath()); - if (!file.exists()) { - logger.debug("Last document not found"); - return; - } - - BufferedReader reader = new BufferedReader(new FileReader(file)); - try { - String line; - while ((line = reader.readLine()) != null) { - docLines.add(line); - } - } finally { - reader.close(); - } - } catch (Exception e) { - logger.error("Failed to read last document, ", e); - } - } - - private SKLStorage getLastDoc() throws Exception { - if (lastDoc == null) { - lastDoc = new FileSKLStorage(getLastDocFilePath()); - } - return lastDoc; - } - - private void writeLn(String line) throws Exception { - docLines.add(line); - getLastDoc().writeLine(line); + + private void writeLn(String line) throws Exception + { + lines.add(line); if (saveToStorage) { getStorage().writeLine(line); } diff --git a/Source/Core/src/com/shtrih/fiscalprinter/command/TextGenerator.java b/Source/Core/src/com/shtrih/fiscalprinter/command/TextGenerator.java new file mode 100644 index 00000000..3d6eebb3 --- /dev/null +++ b/Source/Core/src/com/shtrih/fiscalprinter/command/TextGenerator.java @@ -0,0 +1,296 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.shtrih.fiscalprinter.command; + +import com.shtrih.jpos.fiscalprinter.receipt.ReceiptVisitor; +import com.shtrih.barcode.PrinterBarcode; +import com.shtrih.fiscalprinter.FontNumber; +import com.shtrih.fiscalprinter.SMFiscalPrinter; +import static com.shtrih.fiscalprinter.command.TextDocumentFilter.quantityToStr; +import com.shtrih.fiscalprinter.skl.FileSKLStorage; +import com.shtrih.fiscalprinter.skl.SKLStorage; +import com.shtrih.jpos.fiscalprinter.PrintItem; +import com.shtrih.jpos.fiscalprinter.SmFptrConst; +import com.shtrih.jpos.fiscalprinter.receipt.CashInReceipt; +import com.shtrih.jpos.fiscalprinter.receipt.CashOutReceipt; +import com.shtrih.jpos.fiscalprinter.receipt.FSSalesReceipt; +import com.shtrih.jpos.fiscalprinter.receipt.FSTextReceiptItem; +import com.shtrih.jpos.fiscalprinter.receipt.FSSaleReceiptItem; +import com.shtrih.util.CompositeLogger; +import com.shtrih.util.StringUtils; +import com.shtrih.util.SysUtils; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Vector; +import java.util.Map; +import java.util.HashMap; + +/** + * + * @author Виталий + */ +public class TextGenerator implements ReceiptVisitor { + + private int lineLength = 0; + private int operatorNumber = 1; + private boolean connected = false; + private String deviceName = "ККМ"; + private final SMFiscalPrinter printer; + private final Map operators = new HashMap(); + private List lines = new Vector(); + private static CompositeLogger logger = CompositeLogger.getLogger(TextGenerator.class); + + public TextGenerator(SMFiscalPrinter printer) throws Exception { + this.printer = printer; + } + + public void visitCustomReceipt(Object element){ + } + + public void visitSalesReceipt(Object element) + { + if (!(element instanceof FSSalesReceipt)) return; + FSSalesReceipt receipt = (FSSalesReceipt)element; + try + { + connect(); + lines.clear(); + printReceiptHeader(); + for (int i = 0; i < receipt.items.size(); i++) { + process((Object) receipt.items.get(i)); + } + + /* + if (receipt.discounts.getTotal() > 0) + { + add(STotalText, summToStr(receipt.getSubtotal())); + // ОКРУГЛЕНИЕ + //add(SRoundingText, summToStr(command.getDiscount())); + } + add(SReceiptTotal, summToStr(receipt.getTotal())); + receipt.getPaymentAmount() + long[] payments = params.getPayments(); + + for (int i = 0; i < payments.length; i++) { + if (payments[i] > 0) { + add(getPaymentName(i), summToStr(payments[i])); + } + } + + // Change + if (command.getChange() > 0) { + add(SChangeText, summToStr(command.getChange())); + } + + addFiscalSign(); + readEJReport(true); + endDocument(); + } + */ + + } + catch(Exception e){ + logger.error("Failed duplicate receipt", e); + } + } + + public void addFiscalSign() + { + try{ + printer.waitForPrinting(); + long docNumber = printer.fsReadStatus().getDocNumber(); + long docSign = printer.fsFindDocument(docNumber).getDocument().getDocSign(); + add(String.format("ФД:%d ФП:%10d", docNumber, docSign)); + } + catch(Exception e){ + logger.error("addFiscalSign", e); + } + } + + private void connect() throws Exception { + if (!connected) { + printer.check(printer.readDeviceMetrics()); //! + deviceName = printer.getDeviceMetrics().getDeviceName(); + if (deviceName.equals("ШТРИХ-МОБАЙЛ-Ф")) { // TODO: move deviceName to model.xml + deviceName = "ККТ"; + } else if (deviceName.contains("ПТК")) { + deviceName = "ПТК"; + } else { + deviceName = "ККМ"; + } + connected = true; + } + } + + private String getOperatorName() throws Exception { + String operatorName = operators.get(operatorNumber); + if (operatorName == null) + { + String[] fieldValue = new String[1]; + printer.check(printer.readTable(PrinterConst.SMFP_TABLE_CASHIER, operatorNumber, 2, fieldValue)); + operatorName = fieldValue[0]; + operators.put(operatorNumber, operatorName); + } + return operatorName; + } + + private void printReceiptHeader() throws Exception { + LongPrinterStatus status = printer.readLongStatus(); + int documentNumber = status.getDocumentNumber() + 1; + // ККМ + String s1 = String.format("%s %s", deviceName, status.getSerial()); + String s2 = String.format("ИНН %s №%04d", status.getFiscalIDText(), documentNumber); + add(s1, s2); + // Кассир + PrinterDate date = status.getDate(); + PrinterTime time = status.getTime(); + String s = String.format("%02d.%02d.%02d %02d:%02d", date.getDay(), date.getMonth(), date.getYear(), + time.getHour(), time.getMin()); + add(s, getOperatorName()); + } + + private void process(Object item) throws Exception { + try { + if (item instanceof FSSaleReceiptItem) { + process((FSSaleReceiptItem) item); + } + if (item instanceof FSTextReceiptItem) { + process((FSTextReceiptItem) item); + } + if (item instanceof PrinterBarcode) { + process((PrinterBarcode) item); + } + + if (item instanceof AmountItem) { + process((AmountItem) item); + } + + if (item instanceof PrintItem) { + process((PrintItem) item); + } + } catch (Exception e) { + logger.error(e); + } + } + + private String amountToStr(long value) { + DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault()); + symbols.setDecimalSeparator('.'); + DecimalFormat formatter = new DecimalFormat("0.00", symbols); + return formatter.format(value / 100.0); + } + + private String summToStr(long price, double quantity) { + return summToStr(Math.round(quantity * price)); + } + + private String summToStr(long amount) { + return "=" + amountToStr(amount); + } + + private String getTaxData(int tax1, int tax2, int tax3, int tax4) throws Exception { + String result = ""; + String taxLetters = " АБВГДЕ"; + if (tax1 > 0) { + result += taxLetters.charAt(tax1); + } + if (tax2 > 0) { + result += taxLetters.charAt(tax2); + } + if (tax3 > 0) { + result += taxLetters.charAt(tax3); + } + if (tax4 > 0) { + result += taxLetters.charAt(tax4); + } + if (result.length() > 0) { + result = "_" + result; + } + return result; + } + + private void process(FSSaleReceiptItem item) throws Exception { + String line = ""; + add(item.getText()); + + line = String.format("%s X %s", + quantityToStr(item.getQuantity() / 1000000.0), + amountToStr(item.getPrice())); + add("", line); + + line = summToStr(item.getPrice(), item.getQuantity() / 1000000.0) + + getTaxData(item.getTax1(), 0, 0, 0); + add(String.format("%02d", item.getDepartment()), line); + } + + private void process(FSTextReceiptItem item) throws Exception { + add(item.preLine); + add(item.text); + add(item.postLine); + } + + private void process(PrinterBarcode item) throws Exception { + add("BARCODE"); + add(item.getLabel()); + add(item.getText()); + } + + private void process(AmountItem item) throws Exception + { + if (item.getAmount() > 0) + { + if (item.getText().isEmpty()) + { + add("СКИДКА", "=" + amountToStr(item.getAmount())); + } else + { + add("СКИДКА"); + add(item.getText(), "=" + amountToStr(item.getAmount())); + } + } else{ + if (item.getText().isEmpty()) + { + add("НАДБАВКА", "=" + amountToStr(Math.abs(item.getAmount()))); + } else + { + add("НАДБАВКА"); + add(item.getText(), "=" + amountToStr(Math.abs(item.getAmount()))); + } + } + } + + private int getLineLength() throws Exception{ + if (lineLength == 0) { + lineLength = printer.getMessageLength(); + } + return lineLength; + } + + private void add(String s1, String s2) throws Exception { + int len = getLineLength() - s1.length() - s2.length(); + String line = s1 + StringUtils.stringOfChar(' ', len) + s2; + add(line); + + } + + public List getLines(){ + return lines; + } + + private void add(String line) throws Exception { + if (line == null) { + return; + } + lines.add(line); + } + +} \ No newline at end of file diff --git a/Source/Core/src/com/shtrih/fiscalprinter/port/SocketPort.java b/Source/Core/src/com/shtrih/fiscalprinter/port/SocketPort.java index 7cd91f21..c04c150c 100644 --- a/Source/Core/src/com/shtrih/fiscalprinter/port/SocketPort.java +++ b/Source/Core/src/com/shtrih/fiscalprinter/port/SocketPort.java @@ -17,6 +17,8 @@ public class SocketPort implements PrinterPort2 { private final String portName; private int readTimeout; private int openTimeout; + private InputStream inputStream = null; + private OutputStream outputStream = null; public static synchronized SocketPort getInstance(String portName, int openTimeout) { SocketPort item = items.get(portName); @@ -31,7 +33,7 @@ private SocketPort(String portName, int openTimeout) { this.portName = portName; this.openTimeout = openTimeout; this.readTimeout = openTimeout; - logger.debug("SocketPort(" + portName + ")"); + logger.debug("SocketPort(" + portName + ", " + openTimeout + ")"); } public void open() throws Exception { @@ -56,6 +58,8 @@ public void open(int timeout) throws Exception { String host = tokenizer.nextToken(); int port = Integer.parseInt(tokenizer.nextToken()); socket.connect(new InetSocketAddress(host, port), openTimeout); + inputStream = socket.getInputStream(); + outputStream = socket.getOutputStream(); } public void close() { @@ -70,6 +74,8 @@ public void close() { } catch (Exception e) { } socket = null; + inputStream = null; + outputStream = null; } public int readByte() throws Exception { @@ -109,14 +115,7 @@ public void write(byte[] b) throws Exception { for (int i = 0; i < 2; i++) { try { open(); - OutputStream os = socket.getOutputStream(); - try { - os.write(b); - os.flush(); - } - finally{ - os.close(); - } + outputStream.write(b); return; } catch (Exception e) { close(); @@ -137,12 +136,13 @@ public void write(int b) throws Exception { public void setBaudRate(int baudRate) throws Exception { } - public void setTimeout(int timeout) throws Exception { - + public void setTimeout(int timeout) throws Exception + { + //logger.debug("setTimeout(" + timeout + ")"); this.readTimeout = timeout; - - if (isConnected()) + if (isConnected()){ socket.setSoTimeout(readTimeout); + } } public String getPortName() { @@ -175,7 +175,7 @@ public int available() throws Exception{ public byte[] read(int len) throws Exception{ byte[] buffer = new byte[len]; - socket.getInputStream().read(buffer, 0, len); + inputStream.read(buffer, 0, len); return buffer; } diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/FiscalPrinterImpl.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/FiscalPrinterImpl.java index 06f415ea..829a44e4 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/FiscalPrinterImpl.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/FiscalPrinterImpl.java @@ -103,9 +103,12 @@ import com.shtrih.jpos.fiscalprinter.receipt.FSTextReceiptItem; import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; +import java.io.FileWriter; import java.io.IOException; +import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.text.SimpleDateFormat; @@ -129,9 +132,9 @@ public class FiscalPrinterImpl extends DeviceService implements PrinterConst, JposConst, JposEntryConst, FiscalPrinterConst, IPrinterEvents { - + private CompositeLogger logger = CompositeLogger.getLogger(FiscalPrinterImpl.class); - + public int logoPosition = SmFptrConst.SMFPTR_LOGO_PRINT; private final FptrParameters params; private boolean setPrinterFDOMode = true; @@ -275,51 +278,53 @@ public class FiscalPrinterImpl extends DeviceService implements PrinterConst, private volatile boolean pollStopFlag = false; private volatile boolean eventStopFlag = false; private ReceiptContext receiptContext = null; - + private TextGenerator textGenerator = null; + private List documentLines = new Vector(); + public TextDocumentFilter getTextDocumentFilter() { return filter; } - + public void setFirmwareUpdateObserver(FirmwareUpdateObserver observer) { if (firmwareUpdaterService != null) { firmwareUpdaterService.setListener(observer); } } - + class DeviceTarget implements Runnable { - + private final FiscalPrinterImpl fiscalPrinter; - + public DeviceTarget(FiscalPrinterImpl fiscalPrinter) { this.fiscalPrinter = fiscalPrinter; } - + public void run() { fiscalPrinter.deviceProc(); } } - + class EventTarget implements Runnable { - + private final FiscalPrinterImpl fiscalPrinter; - + public EventTarget(FiscalPrinterImpl fiscalPrinter) { this.fiscalPrinter = fiscalPrinter; } - + public void run() { fiscalPrinter.eventProc(); } } - + class AsyncTarget implements Runnable { - + private final FiscalPrinterImpl fiscalPrinter; - + public AsyncTarget(FiscalPrinterImpl fiscalPrinter) { this.fiscalPrinter = fiscalPrinter; } - + public void run() { fiscalPrinter.asyncProc(); } @@ -342,11 +347,11 @@ public FiscalPrinterImpl() throws Exception { statistics.installationDate = ""; initializeData(); } - + private void initializeData() { state = JPOS_S_CLOSED; if (printer != null && printer.getCapFiscalStorage() && !params.FSDiscountEnabled) { - + capPositiveSubtotalAdjustment = false; capAmountAdjustment = false; capOrderAdjustmentFirst = false; @@ -367,14 +372,14 @@ private void initializeData() { } deviceServiceDescription = "Fiscal Printer Service , SHTRIH-M, 2016"; capAdditionalLines = true; - + capAmountNotPaid = false; capCheckTotal = true; capFixedOutput = false; capIndependentHeader = true; capItemList = false; capNonFiscalMode = true; - + capPowerLossReport = false; capPredefinedPaymentLines = true; capReceiptNotPaid = false; @@ -388,7 +393,7 @@ private void initializeData() { capSlpFiscalDocument = false; capSlpFullSlip = false; capSlpValidation = false; - + capSubtotal = true; capTrainingMode = false; capValidateJournal = false; @@ -402,7 +407,7 @@ private void initializeData() { capFiscalReceiptType = true; capMultiContractor = false; capOnlyVoidLastItem = false; - + capPostPreLine = true; capSetCurrency = false; capTotalizerType = true; @@ -447,34 +452,34 @@ private void initializeData() { capStatisticsReporting = true; deviceServiceVersion = deviceVersion113 + ServiceVersionUtil.getVersionInt(); } - + public SMFiscalPrinter getPrinter() throws Exception { if (printer == null) { throw new Exception("Printer is not initialized"); } return printer; } - + public String[] parseText(String text) throws Exception { return getPrinter().splitText(text, params.font); } - + public void setPrinter(SMFiscalPrinter printer) { this.printer = printer; } - + public void handleException(Throwable e) throws JposException { JposExceptionHandler.handleException(e); } - + public PrinterStatus readPrinterStatus() throws Exception { return getPrinter().readPrinterStatus(); } - + public FlexCommands getCommands() throws Exception { return printer.getCommands(); } - + public PrinterModel getModel() throws Exception { return getPrinter().getModel(); } @@ -486,16 +491,16 @@ public String getCheckHealthText() throws Exception { checkOpened(); return encodeText(checkHealthText); } - + public boolean getClaimed() throws Exception { checkOpened(); return claimed; } - + public boolean getDeviceEnabled() throws Exception { return deviceEnabled; } - + public void setPowerState(int powerState) { if (powerNotify == JPOS_PN_ENABLED) { if (powerState != this.powerState) { @@ -503,15 +508,15 @@ public void setPowerState(int powerState) { case JPOS_PS_ONLINE: statusUpdateEvent(JPOS_SUE_POWER_ONLINE); break; - + case JPOS_PS_OFF: statusUpdateEvent(JPOS_SUE_POWER_OFF); break; - + case JPOS_PS_OFFLINE: statusUpdateEvent(JPOS_SUE_POWER_OFFLINE); break; - + case JPOS_PS_OFF_OFFLINE: statusUpdateEvent(JPOS_SUE_POWER_OFF_OFFLINE); break; @@ -520,7 +525,7 @@ public void setPowerState(int powerState) { } this.powerState = powerState; } - + private void setState(int value) { if (value != state) { state = value; @@ -530,40 +535,39 @@ private void setState(int value) { } } } - + private void addEvent(Runnable event) { synchronized (events) { events.add(event); events.notifyAll(); } } - + private void statusUpdateEvent(int value) { logger.debug("statusUpdateEvent(" + StatusUpdateEventHelper.getName(value) + ")"); - + addEvent(new StatusUpdateEventRequest(cb, new StatusUpdateEvent(this, value))); } - + private void outputCompleteEvent(int outputID) { logger.debug("outputCompleteEvent(" + String.valueOf(outputID) + ")"); - + addEvent(new OutputCompleteEventRequest(cb, new OutputCompleteEvent( this, outputID))); } - + public void disableDocEnd() throws Exception { docEndEnabled = false; } - + private void checkPaperStatus(PrinterStatus status) throws Exception { if (isRecPresent) { isRecPresent = status.getPrinterFlags().isRecPresent(); } - - if (status.getPrinterFlags().isRecPresent()) - { + + if (status.getPrinterFlags().isRecPresent()) { if (isInReceiptTrailer) { printEndNonFiscal(); isInReceiptTrailer = false; @@ -571,10 +575,10 @@ private void checkPaperStatus(PrinterStatus status) throws Exception { } } } - + public void beforeCommand(PrinterCommand command) throws Exception { } - + public void afterCommand(PrinterCommand command) throws Exception { if (!filterEnabled) { return; @@ -589,7 +593,7 @@ public void afterCommand(PrinterCommand command) throws Exception { errorCode, JPOS_EL_OUTPUT, 0); addEvent(new ErrorEventRequest(cb, event)); } - + if (command.isSucceeded()) { switch (command.getCode()) { case 0x10: { @@ -606,60 +610,60 @@ public void afterCommand(PrinterCommand command) throws Exception { } } break; - + } } - + switch (command.getResultCode()) { case SMFP_EFPTR_FS_INVALID_STATE: if (getPrinter().getCapFiscalStorage()) { getPrinter().fsReadStatus(); } break; - + case SMFP_EFPTR_NO_REC_PAPER: isRecPresent = false; setRecPaperState(true, recNearEnd); break; - + case SMFP_EFPTR_NO_JRN_PAPER: setJrnPaperState(true, jrnNearEnd); break; - + case SMFP_EFPTR_NO_SLP_PAPER: setSlpPaperState(true, slpNearEnd); break; - + case SMFP_EFPTR_WAIT_PRINT_CONTINUE: getPrinter().continuePrint(); PrinterStatus status = getPrinter().waitForPrinting(); checkPaperStatus(status); command.setRepeatNeeded(true); break; - + case SMFP_EFPTR_FS_DATE_TIME: FSReadStatus fsStatus = printer.fsReadStatus(); logger.debug("FS document date: " + fsStatus.getDate().toString()); logger.debug("FS document time: " + fsStatus.getTime().toString()); break; - + case SMFP_EFPTR_PREVCOMMAND: printer.waitForPrinting(); command.setRepeatNeeded(true); break; - + case SMFP_EFPTR_INVALID_MODE: case SMFP_EFPTR_INVALID_SUBMODE: status = getPrinter().readPrinterStatus(); logger.debug("Mode: " + status.getPrinterMode().getText() + ", submode: " + status.getPrinterSubmode().getText()); break; - + case SMFP_EFPTR_FM_CONNECT_ERROR: printer.waitForFiscalMemory(); command.setRepeatNeeded(true); break; - + case SMFP_EFPTR_EJ_CONNECT_ERROR: case SMFP_EFPTR_EJ_MISSING: if (!printer.getCapFiscalStorage()) { @@ -667,7 +671,7 @@ public void afterCommand(PrinterCommand command) throws Exception { command.setRepeatNeeded(true); } break; - + case SMFP_EFPTR_RECBUF_OVERFLOW: boolean recOpened = printer.readPrinterStatus().getPrinterMode().isReceiptOpened(); if (!recOpened) { @@ -675,16 +679,16 @@ public void afterCommand(PrinterCommand command) throws Exception { command.setRepeatNeeded(true); } break; - + } } finally { filterEnabled = true; } } - + public void setRecPaperState(boolean recEmpty, boolean recNearEnd) throws Exception { - + int state = getRecPaperState(recEmpty, recNearEnd); int curState = getRecPaperState(this.recEmpty, this.recNearEnd); if (state != curState) { @@ -693,7 +697,7 @@ public void setRecPaperState(boolean recEmpty, boolean recNearEnd) this.recEmpty = recEmpty; this.recNearEnd = recNearEnd; } - + public int getRecPaperState(boolean recEmpty, boolean recNearEnd) throws Exception { if (getCapRecPresent()) { @@ -712,7 +716,7 @@ public int getRecPaperState(boolean recEmpty, boolean recNearEnd) } return FiscalPrinterConst.FPTR_SUE_REC_PAPEROK; } - + public int getJrnPaperState(boolean jrnEmpty, boolean jrnNearEnd) throws Exception { if (getCapJrnPresent()) { @@ -731,7 +735,7 @@ public int getJrnPaperState(boolean jrnEmpty, boolean jrnNearEnd) } return FiscalPrinterConst.FPTR_SUE_JRN_PAPEROK; } - + public int getSlpPaperState(boolean slpEmpty, boolean slpNearEnd) throws Exception { if (getCapSlpPresent()) { @@ -750,10 +754,10 @@ public int getSlpPaperState(boolean slpEmpty, boolean slpNearEnd) } return FiscalPrinterConst.FPTR_SUE_SLP_PAPEROK; } - + public void setJrnPaperState(boolean jrnEmpty, boolean jrnNearEnd) throws Exception { - + int state = getJrnPaperState(jrnEmpty, jrnNearEnd); int curState = getJrnPaperState(this.jrnEmpty, this.jrnNearEnd); if (state != curState) { @@ -762,10 +766,10 @@ public void setJrnPaperState(boolean jrnEmpty, boolean jrnNearEnd) this.jrnEmpty = jrnEmpty; this.jrnNearEnd = jrnNearEnd; } - + public void setSlpPaperState(boolean slpEmpty, boolean slpNearEnd) throws Exception { - + int state = getSlpPaperState(slpEmpty, slpNearEnd); int curState = getSlpPaperState(this.slpEmpty, this.slpNearEnd); if (state != curState) { @@ -774,7 +778,7 @@ public void setSlpPaperState(boolean slpEmpty, boolean slpNearEnd) this.slpEmpty = slpEmpty; this.slpNearEnd = slpNearEnd; } - + private void setCoverState(boolean isCoverOpened) throws Exception { if (getCapCoverSensor()) { if (isCoverOpened != coverOpened) { @@ -787,7 +791,7 @@ private void setCoverState(boolean isCoverOpened) throws Exception { } } } - + public void execute(FiscalPrinterRequest request) throws Exception { if (asyncMode) { setState(JPOS_S_BUSY); @@ -800,14 +804,14 @@ public void execute(FiscalPrinterRequest request) throws Exception { if (state == JPOS_S_BUSY) { throw new JposException(JPOS_E_BUSY); } - + checkEnabled(); synchronized (printer) { request.execute(this); } } } - + private void executePrinterRequest(FiscalPrinterRequest request) { while (true) { try { @@ -816,14 +820,14 @@ private void executePrinterRequest(FiscalPrinterRequest request) { break; } catch (Exception e) { JposException jpose = JposExceptionHandler.getJposException(e); - + setState(JPOS_S_ERROR); switch (jpose.getErrorCode()) { case JPOS_E_TIMEOUT: setPowerState(JPOS_PS_OFFLINE); break; } - + ErrorEvent event = new ErrorEvent(this, jpose.getErrorCode(), jpose.getErrorCodeExtended(), JPOS_EL_OUTPUT, JPOS_ER_CLEAR); @@ -844,7 +848,7 @@ public void eventProc() { synchronized (events) { while (!events.isEmpty()) { ((Runnable) events.remove(0)).run(); - + } events.wait(); } @@ -853,7 +857,7 @@ public void eventProc() { Thread.currentThread().interrupt(); } } - + public void asyncProc() { try { while (!Thread.currentThread().isInterrupted()) { @@ -871,16 +875,16 @@ public void asyncProc() { Thread.currentThread().interrupt(); } } - + public void updateStatus(PrinterStatus status) throws Exception { - + PrinterFlags flags = status.getPrinterFlags(); setRecPaperState(flags.isRecEmpty(), flags.isRecNearEnd()); setJrnPaperState(flags.isJrnEmpty(), flags.isJrnNearEnd()); setSlpPaperState(flags.isSlpEmpty(), flags.isSlpNearEnd()); setCoverState(flags.isCoverOpened()); } - + private void startPoll() throws Exception { if (deviceThread == null) { logger.debug("Poll thread starting..."); @@ -889,7 +893,7 @@ private void startPoll() throws Exception { deviceThread.start(); } } - + private void stopPoll() throws Exception { if (deviceThread != null) { logger.debug("Poll thread stopping..."); @@ -899,7 +903,7 @@ private void stopPoll() throws Exception { deviceThread = null; } } - + public void setDeviceEnabled(boolean deviceEnabled) throws Exception { logger.debug("setDeviceEnabled(" + deviceEnabled + ")"); checkClaimed(); @@ -908,24 +912,24 @@ public void setDeviceEnabled(boolean deviceEnabled) throws Exception { if (deviceEnabled) { physicalDeviceDescription = null; physicalDeviceName = null; - + LongPrinterStatus longStatus = getPrinter().searchDevice(); - + connected = true; setPowerState(JPOS_PS_ONLINE); setJrnPaperState(true, true); - + updateDeviceMetrics(longStatus); - + getPrinterImages().setMaxSize(getMaxGraphicsHeight()); - + cancelReceipt(); getPrinter().initialize(); - + if (!params.fastConnect) { writeTables(); } - + header = createHeader(); header.initDevice(); // TODO: make lazy @@ -933,7 +937,7 @@ public void setDeviceEnabled(boolean deviceEnabled) throws Exception { loadProperties(); updateCommandTimeouts(); } - + isTablesRead = false; capSetVatTable = getPrinter().getCapSetVatTable(); capUpdateFirmware = getPrinter().getCapUpdateFirmware(); @@ -958,13 +962,14 @@ public void setDeviceEnabled(boolean deviceEnabled) throws Exception { } catch (Exception e) { logger.error("Failed to start JsonUpdateService", e); } - + filter.init(getPrinter()); + readLastDocument(); getPrinter().addEvents(filter); if (params.textReportEnabled || (params.duplicateReceipt == SmFptrConst.DUPLICATE_RECEIPT_DRIVER)) { filter.setEnabled(true); } - + } else { saveProperties(); stopPoll(); @@ -980,7 +985,7 @@ public void setDeviceEnabled(boolean deviceEnabled) throws Exception { logger.debug("setDeviceEnabled: OK"); } } - + public void updateCommandTimeouts() { try { String[] value = new String[1]; @@ -997,75 +1002,75 @@ public void updateCommandTimeouts() { logger.error(e); } } - + public void startFDOService() { if (fdoService != null) { return; } - + if (isFDOServiceEnabled()) { fdoService = new FDOService(printer); fdoService.start(); } } - + public boolean isFDOServiceEnabled() { if (!printer.capFDOSupport()) { logger.debug("FDO commands not supported, capFDOSupport=false"); return false; } - + if (params.fdoMode != SmFptrConst.FDO_MODE_ENABLED) { logger.debug("FDO mode not enabled, fdoMode=" + params.fdoMode); return false; } return true; } - + public void startFirmwareUpdaterService() throws Exception { if (firmwareUpdaterService != null) { return; } - + if (!params.capScocUpdateFirmware) { return; } - + if (!printer.getCapFiscalStorage()) { return; } - + if (!printer.isDesktop() && !printer.isShtrihNano() && !printer.isCashCore()) { logger.debug("FirmwareUpdaterService stopped, unsupported device"); return; } - + firmwareUpdaterService = new FirmwareUpdaterService(printer); firmwareUpdaterService.start(); } - + public void startJsonUpdateService() throws Exception { if (jsonUpdateService != null) { return; } - + if (!params.jsonUpdateEnabled) { return; } - + if (!printer.getCapFiscalStorage()) { return; } - + jsonUpdateService = new JsonUpdateService(printer); jsonUpdateService.start(); } - + public void stopJsonUpdateService() { if (jsonUpdateService == null) { return; } - + try { jsonUpdateService.stop(); jsonUpdateService = null; @@ -1073,24 +1078,24 @@ public void stopJsonUpdateService() { logger.error("Failed to stop jsonUpdateService", e); } } - + public boolean isPPP() { int[] data = new int[1]; data[0] = 0; port.directIO(PrinterPort.DIO_REPORT_IS_PPP, data, null); return data[0] == 1; } - + public void setPrinterFDOMode(int mode) { try { if (!setPrinterFDOMode) { return; } - + if (params.fdoMode != SmFptrConst.FDO_MODE_DISABLE_IN_REC) { return; } - + if (isPPP()) { printer.writeTable(21, 1, 2, String.valueOf(mode)); } @@ -1099,12 +1104,12 @@ public void setPrinterFDOMode(int mode) { logger.error("setPrinterFDOMode ", e); } } - + public void stopFDOService() { if (fdoService == null) { return; } - + try { fdoService.stop(); fdoService = null; @@ -1112,7 +1117,7 @@ public void stopFDOService() { logger.error("Failed to stop fsSenderService", e); } } - + public void stopFirmwareUpdaterService() { if (firmwareUpdaterService == null) { return; @@ -1126,33 +1131,33 @@ public void stopFirmwareUpdaterService() { logger.error("Failed to stop firmwareUpdaterService", e); } } - + public boolean isFSServiceRunning() { return (fdoService != null) && (fdoService.isStarted()); } - + public boolean isFirmwareUpdaterServiceRunning() { return firmwareUpdaterService != null; } - + public void setNumHeaderLines(int numHeaderLines) throws Exception { header.setNumHeaderLines(numHeaderLines); } - + public void setNumTrailerLines(int numTrailerLines) throws Exception { header.setNumTrailerLines(numTrailerLines); } - + public LongPrinterStatus readLongStatus() throws Exception { return getPrinter().readLongStatus(); } - + private void updateDeviceMetrics(LongPrinterStatus longStatus) throws Exception { - + LogWriter.write(longStatus); LogWriter.write(getDeviceMetrics()); LogWriter.writeSeparator(); - + physicalDeviceName = getDeviceMetrics().getDeviceName() + ", № " + longStatus.getSerial(); @@ -1165,25 +1170,25 @@ private void updateDeviceMetrics(LongPrinterStatus longStatus) throws Exception + longStatus.getFMFirmwareVersion() + "." + String.valueOf(longStatus.getFMFirmwareBuild()) + ", " + longStatus.getFMFirmwareDate().toString(); - + logger.debug("PhysicalDeviceName: " + physicalDeviceName); logger.debug("PhysicalDeviceDescription: " + physicalDeviceDescription); // update device parameters statistics.serialNumber = longStatus.getSerial(); statistics.firmwareRevision = longStatus.getFirmwareRevision(); - + checkLicense(longStatus.getSerial()); } - + private void checkLicense(String serial) throws Exception { - + if ((getModel().getModelID() == PrinterConst.PRINTER_MODEL_SHTRIH_MINI_FRK) || (getModel().getModelID() == PrinterConst.PRINTER_MODEL_SHTRIH_MINI_FRK2)) { if (isLicenseValid) { return; } - + logger.debug("Reading license file..."); try { String fileName = SysUtils.getFilesPath() + "shtrihjavapos.lic"; @@ -1214,9 +1219,9 @@ private void checkLicense(String serial) throws Exception { } } } - + final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); - + public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { @@ -1226,7 +1231,7 @@ public static String bytesToHex(byte[] bytes) { } return new String(hexChars); } - + public void setPollEnabled(boolean value) throws Exception { if (value != params.pollEnabled) { if (value) { @@ -1239,22 +1244,22 @@ public void setPollEnabled(boolean value) throws Exception { } params.pollEnabled = value; } - + public String getDeviceServiceDescription() throws Exception { checkOpened(); return encodeText(deviceServiceDescription); } - + public int getDeviceServiceVersion() throws Exception { checkOpened(); return deviceServiceVersion; } - + public boolean getFreezeEvents() throws Exception { checkOpened(); return freezeEvents; } - + public void setFreezeEvents(boolean freezeEvents) throws Exception { checkOpened(); if (freezeEvents != getFreezeEvents()) { @@ -1266,7 +1271,7 @@ public void setFreezeEvents(boolean freezeEvents) throws Exception { } } } - + private void stopEventThread() throws Exception { if (eventThread != null) { synchronized (events) { @@ -1278,7 +1283,7 @@ private void stopEventThread() throws Exception { eventThread = null; } } - + private void startEventThread() throws Exception { if (eventThread == null) { eventStopFlag = false; @@ -1286,19 +1291,19 @@ private void startEventThread() throws Exception { eventThread.start(); } } - + public String getPhysicalDeviceDescription() throws Exception { checkOpened(); - + return encodeText(physicalDeviceDescription); } - + public String getPhysicalDeviceName() throws Exception { checkOpened(); - + return encodeText(physicalDeviceName); } - + public int getState() throws Exception { return state; } @@ -1310,31 +1315,31 @@ public int getState() throws Exception { public boolean getCapAdditionalLines() throws Exception { return capAdditionalLines; } - + public boolean getCapAmountAdjustment() throws Exception { return capAmountAdjustment; } - + public boolean getCapAmountNotPaid() throws Exception { return capAmountNotPaid; } - + public boolean getCapCheckTotal() throws Exception { return capCheckTotal; } - + public boolean getCapCoverSensor() throws Exception { return getModel().getCapCoverSensor(); } - + public boolean getCapDoubleWidth() throws Exception { return getModel().getCapDoubleWidth(); } - + public boolean getCapDuplicateReceipt() throws Exception { return getModel().getCapDuplicateReceipt(); } - + public void setDuplicateReceipt(boolean aduplicateReceipt) throws Exception { if (!getCapDuplicateReceipt()) { throw new JposException( @@ -1344,165 +1349,165 @@ public void setDuplicateReceipt(boolean aduplicateReceipt) throws Exception { } duplicateReceipt = aduplicateReceipt; } - + public boolean getCapFixedOutput() throws Exception { return capFixedOutput; } - + public boolean getCapHasVatTable() throws Exception { return getModel().getCapHasVatTable(); } - + public boolean getCapIndependentHeader() throws Exception { return capIndependentHeader; } - + public boolean getCapItemList() throws Exception { return capItemList; } - + public boolean getCapJrnEmptySensor() throws Exception { return getModel().getCapJrnEmptySensor(); } - + public boolean getCapJrnNearEndSensor() throws Exception { return getModel().getCapJrnNearEndSensor(); } - + public boolean getCapJrnPresent() throws Exception { return params.capJrnPresent && getModel().getCapJrnPresent(); } - + public boolean getCapNonFiscalMode() throws Exception { return capNonFiscalMode; } - + public boolean getCapOrderAdjustmentFirst() throws Exception { return capOrderAdjustmentFirst; } - + public boolean getCapPercentAdjustment() throws Exception { return capPercentAdjustment; } - + public boolean getCapPositiveAdjustment() throws Exception { return capPositiveAdjustment; } - + public boolean getCapPowerLossReport() throws Exception { return capPowerLossReport; } - + public int getCapPowerReporting() throws Exception { return JPOS_PR_STANDARD; } - + public boolean getCapPredefinedPaymentLines() throws Exception { return capPredefinedPaymentLines; } - + public boolean getCapReceiptNotPaid() throws Exception { return capReceiptNotPaid; } - + public boolean getCapRecEmptySensor() throws Exception { return getModel().getCapRecEmptySensor(); } - + public boolean getCapRecNearEndSensor() throws Exception { return getModel().getCapRecNearEndSensor(); } - + public boolean getCapRecPresent() throws Exception { return getModel().getCapRecPresent(); } - + public boolean getCapRemainingFiscalMemory() throws Exception { return capRemainingFiscalMemory; } - + public boolean getCapReservedWord() throws Exception { return capReservedWord; } - + public boolean getCapSetHeader() throws Exception { return capSetHeader; } - + public boolean getCapSetPOSID() throws Exception { return capSetPOSID; } - + public boolean getCapSetStoreFiscalID() throws Exception { return capSetStoreFiscalID; } - + public boolean getCapSetTrailer() throws Exception { return capSetTrailer; } - + public boolean getCapSetVatTable() throws Exception { return capSetVatTable; } - + public boolean getCapSlpEmptySensor() throws Exception { return getModel().getCapSlpEmptySensor(); } - + public boolean getCapSlpFiscalDocument() throws Exception { return capSlpFiscalDocument; } - + public boolean getCapSlpFullSlip() throws Exception { return capSlpFullSlip; } - + public boolean getCapSlpNearEndSensor() throws Exception { return getModel().getCapSlpNearEndSensor(); } - + public boolean getCapSlpPresent() throws Exception { return getModel().getCapSlpPresent(); } - + public boolean getCapSlpValidation() throws Exception { return capSlpValidation; } - + public boolean getCapSubAmountAdjustment() throws Exception { return capSubAmountAdjustment; } - + public boolean getCapSubPercentAdjustment() throws Exception { return capSubPercentAdjustment; } - + public boolean getCapSubtotal() throws Exception { return capSubtotal; } - + public boolean getCapTrainingMode() throws Exception { return capTrainingMode; } - + public boolean getCapValidateJournal() throws Exception { return capValidateJournal; } - + public boolean getCapXReport() throws Exception { return capXReport; } - + public int getOutputID() throws Exception { checkOpened(); return outputID; } - + public int getPowerNotify() throws Exception { checkOpened(); return powerNotify; } - + public void setPowerNotify(int powerNotify) throws Exception { if (deviceEnabled) { throw new JposException(JPOS_E_ILLEGAL, @@ -1510,20 +1515,20 @@ public void setPowerNotify(int powerNotify) throws Exception { } this.powerNotify = powerNotify; } - + public int getPowerState() throws Exception { checkOpened(); return powerState; } - + public int getAmountDecimalPlace() throws Exception { return getModel().getAmountDecimalPlace(); } - + public boolean getAsyncMode() throws Exception { return asyncMode; } - + public void setAsyncMode(boolean asyncMode) throws Exception { if (asyncMode != this.asyncMode) { if (asyncMode) { @@ -1537,20 +1542,20 @@ public void setAsyncMode(boolean asyncMode) throws Exception { this.asyncMode = asyncMode; } } - + public boolean getCheckTotal() throws Exception { return params.checkTotal; } - + public void setCheckTotal(boolean value) throws Exception { params.checkTotal = value; } - + public int getCountryCode() throws Exception { checkEnabled(); return countryCode; } - + public boolean getCoverOpen() throws Exception { checkEnabled(); if (!getCapCoverSensor()) { @@ -1559,12 +1564,12 @@ public boolean getCoverOpen() throws Exception { return coverOpened; } } - + public boolean getDayOpened() throws Exception { checkEnabled(); - + PrinterMode mode = getPrinter().readPrinterStatus().getPrinterMode(); - + if (!params.openReceiptOnBegin) { // Эта логика должна выполняться, только если beginFiscalReceipt не открывает чек, // во всех остальных случаях нужно обращаться к устройству @@ -1572,46 +1577,46 @@ public boolean getDayOpened() throws Exception { return true; } } - + return mode.isDayOpened() || mode.isReceiptOpened(); } - + public int getDescriptionLength() throws Exception { return getPrinter().getMessageLength(); } - + public boolean getDuplicateReceipt() throws Exception { if (!getCapDuplicateReceipt()) { return false; } return duplicateReceipt; } - + public int getErrorLevel() throws Exception { return errorLevel; } - + public int getErrorOutID() throws Exception { checkEnabled(); return errorOutID; } - + public int getErrorState() throws Exception { return errorState; } - + public int getErrorStation() throws Exception { return errorStation; } - + public String getErrorString() throws Exception { return encodeText(errorString); } - + public boolean getFlagWhenIdle() throws Exception { return flagWhenIdle; } - + public void setFlagWhenIdle(boolean value) throws Exception { if (value != flagWhenIdle) { flagWhenIdle = value; @@ -1630,55 +1635,55 @@ public void setFlagWhenIdle(boolean value) throws Exception { } } } - + public boolean getJrnEmpty() throws Exception { checkEnabled(); return jrnEmpty; } - + public boolean getJrnNearEnd() throws Exception { checkEnabled(); return jrnNearEnd; } - + public int getMessageLength() throws Exception { return getPrinter().getMessageLength(); } - + public int getNumHeaderLines() throws Exception { checkEnabled(); return header.getNumHeaderLines(); } - + public int getNumTrailerLines() throws Exception { checkEnabled(); return header.getNumTrailerLines(); } - + public int getNumVatRates() throws Exception { PrinterTable table = getPrinter().getTable(PrinterConst.SMFP_TABLE_TAX); return table.getRowCount(); } - + public String getPredefinedPaymentLines() throws Exception { return encodeText(predefinedPaymentLines); } - + public int getPrinterState() throws Exception { checkEnabled(); return printerState.getValue(); } - + public int getQuantityDecimalPlaces() throws Exception { checkEnabled(); return quantityDecimalPlaces; } - + public int getQuantityLength() throws Exception { checkEnabled(); return quantityLength; } - + public boolean getRecEmpty() throws Exception { checkEnabled(); if (getCapRecEmptySensor()) { @@ -1687,7 +1692,7 @@ public boolean getRecEmpty() throws Exception { return false; } } - + public boolean getRecNearEnd() throws Exception { checkEnabled(); if (getCapRecNearEndSensor()) { @@ -1695,31 +1700,31 @@ public boolean getRecNearEnd() throws Exception { } return false; } - + public int getRemainingFiscalMemory() throws Exception { checkEnabled(); return readLongStatus().getFMFreeRecords(); } - + public String getReservedWord() throws Exception { return encodeText(reservedWord); } - + public boolean getSlpEmpty() throws Exception { checkEnabled(); return slpEmpty; } - + public boolean getSlpNearEnd() throws Exception { checkEnabled(); return slpNearEnd; } - + public int getSlipSelection() throws Exception { checkEnabled(); return slipSelection; } - + public void setSlipSelection(int value) throws Exception { checkEnabled(); if (value == FPTR_SS_FULL_LENGTH) { @@ -1730,67 +1735,67 @@ public void setSlipSelection(int value) throws Exception { + "SlipSelection"); } } - + public boolean getTrainingModeActive() throws Exception { checkEnabled(); return trainingModeActive; } - + public boolean getCapAdditionalHeader() throws Exception { return capAdditionalHeader; } - + public boolean getCapAdditionalTrailer() throws Exception { return capAdditionalTrailer; } - + public boolean getCapChangeDue() throws Exception { return capChangeDue; } - + public boolean getCapEmptyReceiptIsVoidable() throws Exception { return capEmptyReceiptIsVoidable; } - + public boolean getCapFiscalReceiptStation() throws Exception { switch (fiscalReceiptStation) { case FPTR_RS_RECEIPT: return capFiscalReceiptStation; - + case FPTR_RS_SLIP: return capFiscalSlipStation; - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidPropertyValue) + "fiscalReceiptStation"); } } - + public boolean getCapFiscalReceiptType() throws Exception { return capFiscalReceiptType; } - + public boolean getCapMultiContractor() throws Exception { return capMultiContractor; } - + public boolean getCapOnlyVoidLastItem() throws Exception { return capOnlyVoidLastItem; } - + public boolean getCapPackageAdjustment() throws Exception { return capPackageAdjustment; } - + public boolean getCapPostPreLine() throws Exception { return capPostPreLine; } - + public boolean getCapSetCurrency() throws Exception { return capSetCurrency; } - + public boolean getCapTotalizerType() throws Exception { return capTotalizerType; } @@ -1800,7 +1805,7 @@ public int getActualCurrency() throws Exception { checkEnabled(); return actualCurrency; } - + public String getAdditionalHeader() throws Exception { checkEnabled(); if (!getCapAdditionalHeader()) { @@ -1809,7 +1814,7 @@ public String getAdditionalHeader() throws Exception { } return encodeText(additionalHeader); } - + public void setAdditionalHeader(String value) throws Exception { checkEnabled(); if (!getCapAdditionalHeader()) { @@ -1818,7 +1823,7 @@ public void setAdditionalHeader(String value) throws Exception { } additionalHeader = decodeText(value); } - + public String getAdditionalTrailer() throws Exception { checkEnabled(); if (!getCapAdditionalTrailer()) { @@ -1828,7 +1833,7 @@ public String getAdditionalTrailer() throws Exception { } return encodeText(additionalTrailer); } - + public void setAdditionalTrailer(String value) throws Exception { checkEnabled(); if (!getCapAdditionalTrailer()) { @@ -1838,7 +1843,7 @@ public void setAdditionalTrailer(String value) throws Exception { } additionalTrailer = decodeText(value); } - + public String getChangeDue() throws Exception { if (!getCapChangeDue()) { throw new JposException(JPOS_E_ILLEGAL, @@ -1846,7 +1851,7 @@ public String getChangeDue() throws Exception { } return encodeText(changeDue); } - + public void setChangeDue(String value) throws Exception { if (!getCapChangeDue()) { throw new JposException(JPOS_E_ILLEGAL, @@ -1854,12 +1859,12 @@ public void setChangeDue(String value) throws Exception { } changeDue = decodeText(value); } - + public int getContractorId() throws Exception { checkEnabled(); return contractorId; } - + public void setContractorId(int value) throws Exception { checkEnabled(); if (!getCapMultiContractor()) { @@ -1870,18 +1875,18 @@ public void setContractorId(int value) throws Exception { } contractorId = value; } - + public int getDateType() throws Exception { checkEnabled(); return dateType; } - + public void setDateType(int value) throws Exception { checkEnabled(); switch (value) { case FPTR_DT_EOD: case FPTR_DT_RTC: - + dateType = value; break; default: @@ -1890,23 +1895,23 @@ public void setDateType(int value) throws Exception { + "DateType"); } } - + public int getFiscalReceiptStation() throws Exception { checkEnabled(); return fiscalReceiptStation; } - + public void setFiscalReceiptStation(int value) throws Exception { checkEnabled(); // Check if the Fiscal Printer is currently in the Monitor State checkPrinterState(FPTR_PS_MONITOR); - + switch (value) { case FPTR_RS_RECEIPT: - + fiscalReceiptStation = value; break; - + case FPTR_RS_SLIP: if (!capFiscalSlipStation) { throw new JposException(JPOS_E_ILLEGAL, @@ -1919,16 +1924,16 @@ public void setFiscalReceiptStation(int value) throws Exception { Localizer.getString(Localizer.invalidParameterValue)); } } - + public int getFiscalReceiptType() throws Exception { checkEnabled(); return fiscalReceiptType; } - + public int getMessageType() throws Exception { return messageType; } - + public void setMessageType(int value) throws Exception { if (value == FPTR_MT_FREE_TEXT) { messageType = value; @@ -1937,32 +1942,32 @@ public void setMessageType(int value) throws Exception { Localizer.getString(Localizer.messageTypeNotSupported)); } } - + public String getPostLine() throws Exception { checkEnabled(); return encodeText(params.postLine); } - + public void setPostLine(String value) throws Exception { checkEnabled(); params.postLine = params.postLinePrefix + decodeText(value); } - + public String getPreLine() throws Exception { checkEnabled(); return encodeText(params.preLine); } - + public void setPreLine(String value) throws Exception { checkEnabled(); params.preLine = params.preLinePrefix + decodeText(value); } - + public int getTotalizerType() throws Exception { checkEnabled(); return totalizerType; } - + public void setTotalizerType(int value) throws Exception { checkEnabled(); switch (value) { @@ -1972,13 +1977,13 @@ public void setTotalizerType(int value) throws Exception { case FPTR_TT_GRAND: // Grand totalizer totalizerType = value; break; - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidParameterValue)); } } - + private void checkOpened() throws Exception { if (state == JPOS_S_CLOSED) { throw new JposException(JPOS_E_CLOSED, "Service is closed"); @@ -1991,7 +1996,7 @@ private void writeFieldsFile() { try { if (params.fieldsFilesPath.length() != 0) { writeFieldsFileFromPath(); - + } else if (params.fieldsFileName.length() != 0) { writeFieldsFileFromFileName(); } @@ -1999,7 +2004,7 @@ private void writeFieldsFile() { logger.error(e); } } - + private void writeFieldsFileFromPath() throws Exception { logger.debug("writeFieldsFileFromPath"); File dir = new File(params.fieldsFilesPath); @@ -2020,7 +2025,7 @@ private void writeFieldsFileFromPath() throws Exception { PrinterFields fields = new PrinterFields(); CsvTablesReader reader = new CsvTablesReader(); reader.load(file.getAbsolutePath(), fields); - + if (fields.validModelName(getPrinter().getDeviceMetrics().getDeviceName())) { logger.debug("Write fields values from file '" + file.getAbsolutePath() + "')"); // set font for driver text @@ -2034,11 +2039,11 @@ private void writeFieldsFileFromPath() throws Exception { break; } } - + } } } - + private void writeFieldsFileFromFileName() throws Exception { File file = new File(SysUtils.getFilesPath() + params.fieldsFileName); if (!file.exists()) { @@ -2048,18 +2053,18 @@ private void writeFieldsFileFromFileName() throws Exception { PrinterFields fields = new PrinterFields(); CsvTablesReader reader = new CsvTablesReader(); reader.load(file.getAbsolutePath(), fields); - + String deviceModelName = getPrinter().getDeviceMetrics().getDeviceName(); if (fields.validModelName(deviceModelName)) { logger.error("File model name does not match device name"); logger.error("'" + fields.getModelName() + "' <> '" + deviceModelName + "'"); return; - + } logger.debug("Write fields values from file '" + file.getAbsolutePath() + "')"); writeTables(fields); } - + private void writePaymentNames() throws Exception { // payment names Vector paymentNames = params.getPaymentNames(); @@ -2075,12 +2080,12 @@ private void writePaymentNames() throws Exception { } } } - + private void writeTables() throws Exception { writeFieldsFile(); writePaymentNames(); } - + public void readTables() { try { // load tax names @@ -2095,19 +2100,19 @@ public void readTables() { logger.error(e); } } - + public void claim(int timeout) throws Exception { checkOpened(); if (!claimed) { claimed = true; } } - + public void close() throws Exception { checkOpened(); setEventCallbacks(null); setFreezeEvents(true); - + if (claimed) { release(); } @@ -2117,33 +2122,33 @@ public void close() throws Exception { } monitoringServer.stop(); } - + public void checkHealth(int level) throws Exception { checkEnabled(); switch (level) { case JPOS_CH_INTERNAL: checkHealthText = InternalCheckHelthReport.getReport(printer); break; - + case JPOS_CH_EXTERNAL: checkHealthText = checkHealthExternal(); break; - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidParameterValue) + ", level"); } } - + public PrinterImages getPrinterImages() throws Exception { return getPrinter().getPrinterImages(); } - + public void printImage(int index) throws Exception { printImage(getPrinterImages().get(index)); } - + public void printImage(PrinterImage image) throws Exception { if (image == null) { return; @@ -2165,7 +2170,7 @@ public void writeTables(String fileName) throws Exception { reader.load(fileName, fields); writeTables(fields); } - + public void writeTables(PrinterFields fields) throws Exception { for (int i = 0; i < fields.size(); i++) { PrinterField field = fields.get(i); @@ -2196,7 +2201,7 @@ public void readTables(String fileName) throws Exception { CsvTablesWriter writer = new CsvTablesWriter(); writer.save(SysUtils.getFilesPath() + fileName, tables); } - + public void directIO(int command, int[] data, Object object) throws Exception { if (params.compatibilityLevel == SmFptrConst.SMFPTR_COMPAT_LEVEL_NONE) { @@ -2205,11 +2210,11 @@ public void directIO(int command, int[] data, Object object) (new DirectIOHandler2(this)).directIO(command, data, object); } } - + public void setEventCallbacks(EventCallbacks cb) { this.cb = cb; } - + public void open(String logicalName, EventCallbacks cb) throws Exception { initializeData(); logicalName = decodeText(logicalName); @@ -2218,7 +2223,7 @@ public void open(String logicalName, EventCallbacks cb) throws Exception { if (jposEntry != null) { params.loadLogEnabled(jposEntry); logger.setEnabled(params.logEnabled); - + logger.debug("-----------------------------------------------"); logger.debug("SHTRIH-M JavaPos FiscalPrinter service"); logger.debug("DeviceServiceVersion: " @@ -2232,18 +2237,19 @@ public void open(String logicalName, EventCallbacks cb) throws Exception { logger.debug("OS Version: " + System.getProperty("os.version")); logger.debug("Library path: " + System.getProperty("java.library.path")); logger.debug("-----------------------------------------------"); - + params.load(jposEntry); port = PrinterPortFactory.createInstance(params); port.setPortEvents(new PortEventsNotifier()); device = ProtocolFactory.getProtocol(params, port); printer = new SMFiscalPrinterImpl(port, device, params); + textGenerator = new TextGenerator(printer); header = new NullHeader(printer); - + if (params.escCommandsEnabled) { printer.setEscPrinter(new NCR7167Printer(this)); } - + getPrinter().addEvents(this); if (params.receiptReportEnabled) { getPrinter().addEvents(new ReceiptReportFilter(printer, params)); @@ -2252,87 +2258,86 @@ public void open(String logicalName, EventCallbacks cb) throws Exception { getPrinter().setTaxPassword(params.taxPassword); getPrinter().setUsrPassword(params.usrPassword); getPrinter().setSysPassword(params.sysPassword); - + if (params.statisticEnabled) { statistics.load(params.statisticFileName); } Localizer.init(params.messagesFileName); getPrinter().setWrapText(params.wrapText); createFilters(); - + if (params.monitoringEnabled) { monitoringServer.start(params.getMonitoringPort()); } - + JposExceptionHandler.setStripExceptionDetails(params.stripExceptionDetails); } - + receipt = new NullReceipt(getReceiptContext()); - + state = JPOS_S_IDLE; setFreezeEvents(false); } - + private class PortEventsNotifier implements PrinterPort.IPortEvents { - + public PortEventsNotifier() { } - + public void onConnect() { setPowerState(JPOS_PS_ONLINE); } - - public void onDisconnect() - { + + public void onDisconnect() { setPowerState(JPOS_PS_OFFLINE); if (device != null) { device.disconnect(); } } - + } - + private PrinterHeader createHeader() throws Exception { switch (params.headerMode) { case SmFptrConst.SMFPTR_HEADER_MODE_PRINTER: return new DeviceHeader(printer); - + case SmFptrConst.SMFPTR_HEADER_MODE_DRIVER: return new DriverHeader(printer); - + case SmFptrConst.SMFPTR_HEADER_MODE_DRIVER2: return new DriverHeader2(printer); - + case SmFptrConst.SMFPTR_HEADER_MODE_NULL: return new NullHeader(printer); - + default: return new DriverHeader(printer); } } - + private void createFilters() throws Exception { - + filters.clear(); - + if (params.zeroPriceFilterEnabled) { SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); Date time1 = timeFormat.parse(params.zeroPriceFilterTime1); Date time2 = timeFormat.parse(params.zeroPriceFilterTime2); - + FiscalPrinterFilter113 filter = new ZeroPriceFilter( params.zeroPriceFilterEnabled, time1, time2, params.zeroPriceFilterErrorText); - + filters.add(filter); } - + if (params.discountFilterEnabled) { FiscalPrinterFilter113 filter = new DiscountFilter(this); filters.add(filter); } } - + public void release() throws Exception { setDeviceEnabled(false); claimed = false; @@ -2345,17 +2350,17 @@ private void noSlipStationError() throws Exception { throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.slipStationNotPresent)); } - + public void beginFiscalDocument(int documentAmount) throws Exception { checkEnabled(); noSlipStationError(); } - + public void printFiscalDocumentLine(String documentLine) throws Exception { checkEnabled(); noSlipStationError(); } - + public void endFiscalDocument() throws Exception { checkEnabled(); noSlipStationError(); @@ -2369,13 +2374,13 @@ public void beginFixedOutput(int station, int documentType) checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void printFixedOutput(int documentType, int lineNumber, String data) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void endFixedOutput() throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); @@ -2388,27 +2393,27 @@ public void beginInsertion(int timeout) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void beginItemList(int vatID) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void beginRemoval(int timeout) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void endInsertion() throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void endItemList() throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void endRemoval() throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); @@ -2423,28 +2428,28 @@ public void beginNonFiscal() throws Exception { receipt = new NonfiscalReceipt(getReceiptContext()); printDocStart(); printHeaderDriver(); - + setPrinterState(FPTR_PS_NONFISCAL); } - + public void printHeaderDriver() throws Exception { if (params.nonFiscalHeaderEnabled) { printer.printReceiptHeader("Нефискальный документ"); } } - + public void printNormalAsync(int station, String data) throws Exception { checkEnabled(); data = decodeText(data); logoPosition = SmFptrConst.SMFPTR_LOGO_PRINT; receipt.printNormal(station, data); } - + public void printNormal(int station, String data) throws Exception { checkEnabled(); execute(new PrintNormalRequest(station, data)); } - + private PrinterImage getPrinterImage(int position) throws Exception { ReceiptImage image = getReceiptImages().imageByPosition(position); if (image != null) { @@ -2455,23 +2460,23 @@ private PrinterImage getPrinterImage(int position) throws Exception { } return null; } - + public void printRecLine(String line) throws Exception { getPrinter().printLine(SMFP_STATION_REC, line, params.font); } - + public void printEndFiscal() { try { if (getPrinter().getPrintMode() == PrinterConst.PRINT_MODE_DISABLE_ONCE) { getPrinter().enablePrint(); return; } - + if (!docEndEnabled) { docEndEnabled = true; return; } - + synchronized (printer) { docEndEnabled = true; isInReceiptTrailer = true; @@ -2483,19 +2488,19 @@ public void printEndFiscal() { logger.error(e.toString()); } } - + public void printEndNonFiscal() { try { if (getPrinter().getPrintMode() == PrinterConst.PRINT_MODE_DISABLE_ONCE) { getPrinter().enablePrint(); return; } - + if (!docEndEnabled && params.canDisableNonFiscalEnding) { docEndEnabled = true; return; } - + synchronized (printer) { docEndEnabled = true; isInReceiptTrailer = true; @@ -2507,7 +2512,7 @@ public void printEndNonFiscal() { logger.error(e.toString()); } } - + public void printDocStart() throws Exception { synchronized (printer) { isInReceiptTrailer = true; @@ -2515,10 +2520,10 @@ public void printDocStart() throws Exception { isInReceiptTrailer = false; } } - + public void printNonFiscalDoc(String text) throws Exception { getPrinter().stopSaveCommands(); - + boolean isReceiptOpened = false; PrinterStatus status = getPrinter().waitForPrinting(); isReceiptOpened = status.getPrinterMode().isReceiptOpened(); @@ -2536,7 +2541,7 @@ public void printNonFiscalDoc(String text) throws Exception { getPrinter().clearReceiptCommands(); } } - + public void endNonFiscal() throws Exception { synchronized (printer) { checkEnabled(); @@ -2554,7 +2559,7 @@ public void beginTraining() throws Exception { checkPrinterState(FPTR_PS_MONITOR); trainingModeActive = true; } - + public void endTraining() throws Exception { checkEnabled(); if (trainingModeActive) { @@ -2568,7 +2573,7 @@ public void endTraining() throws Exception { public void clearError() throws Exception { checkEnabled(); } - + public void clearOutput() throws Exception { checkClaimed(); // Clears all buffered output data, including all asynchronous output @@ -2588,7 +2593,7 @@ public void clearOutput() throws Exception { } setState(JPOS_S_IDLE); } - + private String getDataFirmware(int[] optArgs) throws Exception { LongPrinterStatus status = readLongStatus(); String result = ""; @@ -2612,7 +2617,7 @@ private String getDataFirmware(int[] optArgs) throws Exception { case 3: result = Long.toString(status.getFMFirmwareBuild()); break; - + default: result += "Printer firmware : " + status.getFirmwareVersion(); result += ", build " + String.valueOf(status.getFirmwareBuild()); @@ -2624,7 +2629,7 @@ private String getDataFirmware(int[] optArgs) throws Exception { } return result; } - + public String getTenderData(int optArg) throws Exception { switch (optArg) { // Cash @@ -2669,14 +2674,14 @@ public String getTenderData(int optArg) throws Exception { // Voucher. case FPTR_PDL_VOUCHER: return "0"; - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidParameterValue) + ", OptArgs"); } } - + public int getLineCountData(int optArg) throws Exception { switch (optArg) { // Number of item lines. @@ -2724,14 +2729,14 @@ public int getLineCountData(int optArg) throws Exception { // Number of total lines. case FPTR_LC_TOTAL: return 2; - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidParameterValue) + ", OptArgs"); } } - + public int getDataDescriptionLength(int optArg) throws Exception { switch (optArg) { // printRecItem method @@ -2759,19 +2764,19 @@ public int getDataDescriptionLength(int optArg) throws Exception { // printRecItemVoid and printRecItemAdjustmentVoid methods. case FPTR_DL_VOID_ITEM: return getPrinter().getMessageLength(); - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidParameterValue) + ", OptArgs"); } } - + public String getDataItemText(int dataItem) { switch (dataItem) { case FPTR_GD_CURRENT_TOTAL: return "FPTR_GD_CURRENT_TOTAL"; - + case FPTR_GD_DAILY_TOTAL: return "FPTR_GD_DAILY_TOTAL"; case FPTR_GD_RECEIPT_NUMBER: @@ -2828,15 +2833,15 @@ public String getDataItemText(int dataItem) { return "FPTR_GD_DESCRIPTION_LENGTH"; default: return String.valueOf(dataItem); - + } } - + public void getData(int dataItem, int[] optArgs, String[] data) throws Exception { checkEnabled(); String result = ""; - + long number; switch (dataItem) { // Get the Fiscal Printer’s firmware release number. @@ -2846,7 +2851,7 @@ public void getData(int dataItem, int[] optArgs, String[] data) // Get the Fiscal Printer’s fiscal ID. case FPTR_GD_PRINTER_ID: - + if (params.printerIDMode == PrinterConst.PRINTER_ID_FS_SERIAL) { if (printer.getCapFiscalStorage()) { result = printer.fsReadSerial().getSerial(); @@ -2859,7 +2864,7 @@ public void getData(int dataItem, int[] optArgs, String[] data) result = readLongStatus().getSerial(); } break; - + case FPTR_GD_CURRENT_TOTAL: result = StringUtils.amountToString(receipt.getSubtotal()); break; @@ -2922,51 +2927,51 @@ public void getData(int dataItem, int[] optArgs, String[] data) + getPrinter().readOperationRegister(145) + getPrinter().readOperationRegister(146) + getPrinter().readOperationRegister(147); - + result = Long.toString(number); break; - + case FPTR_GD_FISCAL_REC_VOID: number = getPrinter().readOperationRegister(179) + getPrinter().readOperationRegister(180) + getPrinter().readOperationRegister(181) + getPrinter().readOperationRegister(182); - + result = Long.toString(number); break; - + case FPTR_GD_NONFISCAL_DOC: result = Long.toString(fiscalDay.getNonFiscalDocNumber()); break; - + case FPTR_GD_NONFISCAL_DOC_VOID: result = Long.toString(fiscalDay.getNonFiscalDocVoidNumber()); break; - + case FPTR_GD_NONFISCAL_REC: result = Long.toString(fiscalDay.getNonFiscalRecNumber()); break; - + case FPTR_GD_SIMP_INVOICE: result = Long.toString(fiscalDay.getSimpInvoiceNumber()); break; - + case FPTR_GD_Z_REPORT: result = Long.toString(printer.readDayNumber()); break; - + case FPTR_GD_TENDER: result = getTenderData(optArgs[0]); break; - + case FPTR_GD_LINECOUNT: result = String.valueOf(getLineCountData(optArgs[0])); break; - + case FPTR_GD_DESCRIPTION_LENGTH: result = String.valueOf(getDataDescriptionLength(optArgs[0])); break; - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidParameterValue) @@ -2975,20 +2980,20 @@ public void getData(int dataItem, int[] optArgs, String[] data) data[0] = encodeText(result); logger.debug("getData(" + getDataItemText(dataItem) + ")=" + result); } - + public long readReceiptNumber() throws Exception { long number = 0; switch (params.receiptNumberRequest) { case SmFptrConst.SMFPTR_RN_FP_DOCUMENT_NUMBER: number = printer.readDocNumber(); break; - + case SmFptrConst.SMFPTR_RN_FS_DOCUMENT_NUMBER: if (printer.getCapFiscalStorage()) { number = printer.fsReadStatus().getDocNumber(); } break; - + case SmFptrConst.SMFPTR_RN_FS_RECEIPT_NUMBER: if (printer.getCapFiscalStorage()) { number = printer.fsReadDayParameters().getReceiptNumber(); @@ -2997,7 +3002,7 @@ public long readReceiptNumber() throws Exception { } return number; } - + public String readGrandTotal(int[] optArgs) throws Exception { String result = "0;0;0;0"; boolean isFiscalized = printer.readLongStatus().isFiscalized(); @@ -3014,7 +3019,7 @@ public String readGrandTotal(int[] optArgs) throws Exception { } return result; } - + public long getDailyTotal(int mode) throws Exception { long amount = 0; switch (mode) { @@ -3028,7 +3033,7 @@ public long getDailyTotal(int mode) throws Exception { amount += printer.readCashRegister(242); amount -= printer.readCashRegister(243); break; - + case SmFptrConst.SMFPTR_DAILY_TOTAL_CASH: amount += printer.readCashRegister(193); amount -= printer.readCashRegister(194); @@ -3037,34 +3042,34 @@ public long getDailyTotal(int mode) throws Exception { amount += printer.readCashRegister(242); amount -= printer.readCashRegister(243); break; - + case SmFptrConst.SMFPTR_DAILY_TOTAL_PT2: amount += printer.readCashRegister(197); amount -= printer.readCashRegister(198); amount -= printer.readCashRegister(199); amount += printer.readCashRegister(200); break; - + case SmFptrConst.SMFPTR_DAILY_TOTAL_PT3: amount += printer.readCashRegister(201); amount -= printer.readCashRegister(202); amount -= printer.readCashRegister(203); amount += printer.readCashRegister(204); break; - + case SmFptrConst.SMFPTR_DAILY_TOTAL_PT4: amount += printer.readCashRegister(205); amount -= printer.readCashRegister(206); amount -= printer.readCashRegister(207); amount += printer.readCashRegister(208); break; - + default: throw new Exception("Invalid optional parameter"); } return amount; } - + public void getDate(String[] Date) throws Exception { checkEnabled(); String result = ""; @@ -3073,7 +3078,7 @@ public void getDate(String[] Date) throws Exception { Localizer.getString(Localizer.invalidParameterValue) + "Date"); } - + switch (dateType) { // Date of last end of day. case FPTR_DT_EOD: @@ -3093,14 +3098,14 @@ public void getDate(String[] Date) throws Exception { LongPrinterStatus status = readLongStatus(); PrinterDate printerDate = status.getDate(); PrinterTime printerTime = status.getTime(); - + JposFiscalPrinterDate jposDate = new JposFiscalPrinterDate( printerDate.getDay(), printerDate.getMonth(), printerDate.getYear(), printerTime.getHour(), printerTime.getMin(), printerTime.getSec()); result = jposDate.toString(); break; - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidParameterValue) @@ -3109,7 +3114,7 @@ public void getDate(String[] Date) throws Exception { Date[0] = encodeText(result); logger.debug("getDate: " + Date[0]); } - + public void getTotalizer(int vatID, int optArgs, String[] data) throws Exception { checkEnabled(); @@ -3126,7 +3131,7 @@ public void getTotalizer(int vatID, int optArgs, String[] data) * } */ } - + private boolean isSalesReceipt() { switch (fiscalReceiptType) { case FPTR_RT_SALES: @@ -3139,12 +3144,12 @@ private boolean isSalesReceipt() { return false; } } - + private void dayEndRequiredError() throws Exception { throw new JposException(JPOS_E_EXTENDED, JPOS_EFPTR_DAY_END_REQUIRED, "Day end required"); } - + public void openFiscalDay() throws Exception { if (printer.getCapOpenFiscalDay() && printer.isDayClosed()) { stopFDOService(); @@ -3165,13 +3170,13 @@ public void beginFiscalReceipt(boolean printHeader) throws Exception { setPrinterFDOMode(0); logger.debug("DeviceServiceVersion: " + String.valueOf(deviceServiceVersion)); try { - + Vector messages = null; if ((receipt != null) && (receipt instanceof NullReceipt)) { messages = ((NullReceipt) receipt).getMessages(); } receipt = createReceipt(fiscalReceiptType); - + PrinterStatus status = getPrinter().waitForPrinting(); // Cancel receipt if it opened if (status.getPrinterMode().isReceiptOpened()) { @@ -3201,14 +3206,14 @@ public void beginFiscalReceipt(boolean printHeader) throws Exception { receipt.printRecMessage(line.getStation(), line.getFont(), line.getLine()); } } - + } catch (Exception e) { receipt = new NullReceipt(getReceiptContext()); setPrinterState(FPTR_PS_MONITOR); throw e; } } - + public void cancelReceipt2() { try { getPrinter().waitForPrinting(); @@ -3217,14 +3222,20 @@ public void cancelReceipt2() { logger.error(e); } } - + public void endFiscalReceipt(boolean printHeader) throws Exception { logger.debug("endFiscalReceipt"); - + synchronized (printer) { checkEnabled(); checkPrinterState(FPTR_PS_FISCAL_RECEIPT_ENDING); - + if (receipt instanceof FSSalesReceipt) { + if (textGenerator != null) { + receipt.accept(textGenerator); + setDocumentLines(textGenerator.getLines()); + } + } + try { receipt.endFiscalReceipt(printHeader); } catch (DeviceException e) { @@ -3233,9 +3244,9 @@ public void endFiscalReceipt(boolean printHeader) throws Exception { } throw e; } - + getPrinter().stopSaveCommands(); - + try { Time.delay(getParams().recCloseSleepTime); if (!receipt.getCapAutoCut()) { @@ -3249,11 +3260,21 @@ public void endFiscalReceipt(boolean printHeader) throws Exception { startFDOService(); setPrinterState(FPTR_PS_MONITOR); filter.endFiscalReceipt(); + + setDocumentLines(filter.getLines()); + if ((textGenerator != null)&&(receipt instanceof FSSalesReceipt)) + { + textGenerator.addFiscalSign(); + setDocumentLines(textGenerator.getLines()); + } else { + setDocumentLines(filter.getLines()); + } + params.nonFiscalDocNumber++; saveProperties(); } } - + public void printDuplicateReceipt() throws Exception { boolean filterEnabled = filter.getEnabled(); filter.setEnabled(false); @@ -3268,11 +3289,11 @@ public void printDuplicateReceipt() throws Exception { receipt.printReceiptEnding(); printEndFiscal(); } else { - List lines = filter.getDocLines(); + List lines = documentLines; if (lines.size() == 0) { throw new JposException(JPOS_E_ILLEGAL, "There is no documents to print"); } - + printDocStart(); for (int i = 0; i < lines.size(); i++) { printer.printText(lines.get(i)); @@ -3298,17 +3319,17 @@ public void printPeriodicTotalsReport(String date1, String date2) checkEnabled(); checkStateBusy(); checkPrinterState(FPTR_PS_MONITOR); - + date1 = decodeText(date1); date2 = decodeText(date2); - + PrinterDate printerDate1 = JposFiscalPrinterDate.parseDateTime(date1) .getPrinterDate(); PrinterDate printerDate2 = JposFiscalPrinterDate.parseDateTime(date2) .getPrinterDate(); - + printDocStart(); - + if (params.reportDevice == SmFptrConst.SMFPTR_REPORT_DEVICE_EJ) { getPrinter().printEJDayReportOnDates(printerDate1, printerDate2, params.reportType); } else { @@ -3317,25 +3338,25 @@ public void printPeriodicTotalsReport(String date1, String date2) } printEndFiscal(); } - + public void printPowerLossReport() throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + private void checkQuantity(int value) throws Exception { if (value < 0) { throw new JposException(JPOS_E_EXTENDED, JPOS_EFPTR_BAD_ITEM_QUANTITY); } } - + private void checkPrice(long value) throws Exception { if (value < 0) { throw new JposException(JPOS_E_EXTENDED, JPOS_EFPTR_BAD_PRICE); } } - + private void checkLongParam(long Value, long minValue, long maxValue, String propName) throws Exception { if (Value < minValue) { @@ -3349,11 +3370,11 @@ private void checkLongParam(long Value, long minValue, long maxValue, + propName); } } - + private void checkVatInfo(long value) throws Exception { checkLongParam(value, 0, 6, "VatInfo"); } - + private void checkReceiptStation() throws Exception { if (fiscalReceiptStation != FPTR_RS_RECEIPT) { throw new JposException(JPOS_E_ILLEGAL, @@ -3361,22 +3382,22 @@ private void checkReceiptStation() throws Exception { + "fiscalReceiptStation"); } } - + private long convertAmount(long value) { return Math.abs((long) (value * params.amountFactor)); } - + private double convertQuantity(int value) { return value * params.quantityFactor / 1000000.0; } - + public void printRecItemAsync(String description, long price, int quantity, int vatInfo, long unitPrice, String unitName) throws Exception { unitName = decodeText(unitName); description = decodeText(description); price = convertAmount(price); unitPrice = convertAmount(unitPrice); - + checkEnabled(); checkReceiptStation(); checkQuantity(quantity); @@ -3386,7 +3407,7 @@ public void printRecItemAsync(String description, long price, int quantity, description = updateDescription(description); receipt.printRecItem(description, price, convertQuantity(quantity), vatInfo, unitPrice, unitName); } - + public String updateDescription(String description) throws Exception { if (params.postLineAsItemTextEnabled) { String postLine = getPostLine(); @@ -3398,68 +3419,68 @@ public String updateDescription(String description) throws Exception { } return description; } - + public void printRecItem(String description, long price, int quantity, int vatInfo, long unitPrice, String unitName) throws Exception { filters.printRecItem(description, price, quantity, vatInfo, unitPrice, unitName); - + checkEnabled(); checkPrinterState(FPTR_PS_FISCAL_RECEIPT); execute(new PrintRecItemRequest(description, price, quantity, vatInfo, unitPrice, unitName)); } - + public void printRecMessageAsync(int station, FontNumber font, String message) throws Exception { message = decodeText(message); receipt.printRecMessage(station, font, message); } - + public boolean isReceiptEnding() { return printerState.isEnding(); } - + public void printRecMessageAsync(String message) throws Exception { printRecMessageAsync(PrinterConst.SMFP_STATION_RECJRN, getFont(), message); } - + public void printRecMessage(String message) throws Exception { checkEnabled(); execute(new PrintRecMessageRequest(message)); } - + private void checkPercents(long amount) throws Exception { if ((amount < 0) || (amount > 10000)) { throw new JposException(JPOS_E_EXTENDED, JPOS_EFPTR_BAD_ITEM_AMOUNT); } } - + public void checkAdjustment(int adjustmentType, long amount) throws Exception { switch (adjustmentType) { case FPTR_AT_AMOUNT_DISCOUNT: case FPTR_AT_AMOUNT_SURCHARGE: break; - + case FPTR_AT_PERCENTAGE_DISCOUNT: case FPTR_AT_PERCENTAGE_SURCHARGE: checkPercents(amount); break; - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidParameterValue) + "adjustmentType"); } } - + public void printRecItemAdjustmentAsync(int adjustmentType, String description, long amount, int vatInfo) throws Exception { description = decodeText(description); amount = convertAmount(amount); - + checkEnabled(); checkVatInfo(vatInfo); checkAdjustment(adjustmentType, amount); @@ -3472,24 +3493,24 @@ public void printRecItemAdjustmentAsync(int adjustmentType, description = request.getDescription(); amount = request.getAmount(); vatInfo = request.getVatInfo(); - + checkPrinterState(FPTR_PS_FISCAL_RECEIPT); receipt.printRecItemAdjustment(adjustmentType, description, amount, vatInfo); } - + public void printRecItemAdjustment(int adjustmentType, String description, long amount, int vatInfo) throws Exception { checkEnabled(); execute(new PrintRecItemAdjustmentRequest(adjustmentType, description, amount, vatInfo)); } - + private String formatStrings(String line1, String line2) throws Exception { int len; String S = ""; len = getPrinter().getMessageLength() - line2.length(); - + for (int i = 0; i < len; i++) { if (i < line1.length()) { S = S + line1.charAt(i); @@ -3499,98 +3520,98 @@ private String formatStrings(String line1, String line2) throws Exception { } return S + line2; } - + private void printStrings(String line1, String line2) throws Exception { checkEnabled(); getPrinter().printText(SMFP_STATION_REC, formatStrings(line1, line2), getFont()); } - + public void printRecItemFuelAsync(String description, long price, int quantity, int vatInfo, long unitPrice, String unitName, long specialTax, String specialTaxName) throws Exception { } - + public void printRecItemFuelVoidAsync(String description, long price, int vatInfo, long specialTax) throws Exception { } - + public void printRecNotPaidAsync(String description, long amount) throws Exception { } - + public void printRecNotPaid(String description, long amount) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.notPaidReceiptsNotSupported)); } - + public void printRecRefund(String description, long amount, int vatInfo) throws Exception { checkEnabled(); execute(new PrintRecRefundRequest(description, amount, vatInfo)); } - + public void printRecRefundAsync(String description, long amount, int vatInfo) throws Exception { description = decodeText(description); amount = convertAmount(amount); - + checkEnabled(); checkVatInfo(vatInfo); - + checkPrinterState(FPTR_PS_FISCAL_RECEIPT); receipt.printRecRefund(description, amount, vatInfo); } - + public void printRecSubtotal(long amount) throws Exception { checkEnabled(); execute(new PrintRecSubtotalRequest(amount)); } - + public void printRecSubtotalAsync(long amount) throws Exception { amount = convertAmount(amount); - + checkEnabled(); checkPrinterState(FPTR_PS_FISCAL_RECEIPT); receipt.printRecSubtotal(amount); } - + public void printRecSubtotalAdjustment(int adjustmentType, String description, long amount) throws Exception { checkEnabled(); execute(new PrintRecSubtotalAdjustmentRequest(adjustmentType, description, amount)); } - + public void printRecSubtotalAdjustmentAsync(int adjustmentType, String description, long amount) throws Exception { description = decodeText(description); amount = convertAmount(amount); - + checkEnabled(); checkAdjustment(adjustmentType, amount); checkPrinterState(FPTR_PS_FISCAL_RECEIPT); receipt.printRecSubtotalAdjustment(adjustmentType, description, amount); } - + public void printRecTotal(long total, long payment, String description) throws Exception { checkEnabled(); execute(new PrintRecTotalRequest(total, payment, description)); } - + public void printRecTotalAsync(long total, long payment, String description) throws Exception { logger.debug("printRecTotal"); - + total = convertAmount(total); payment = convertAmount(payment); description = decodeText(description); - + checkEnabled(); - + if ((printerState.getValue() != FPTR_PS_FISCAL_RECEIPT) && (printerState.getValue() != FPTR_PS_FISCAL_RECEIPT_TOTAL)) { throwWrongStateError(); @@ -3603,7 +3624,7 @@ public void printRecTotalAsync(long total, long payment, String description) setPrinterState(FPTR_PS_FISCAL_RECEIPT_TOTAL); } } - + public void printRecVoidAsync(String description) throws Exception { description = decodeText(description); if ((printerState.getValue() == FPTR_PS_FISCAL_RECEIPT) @@ -3615,26 +3636,26 @@ public void printRecVoidAsync(String description) throws Exception { throwWrongStateError(); } } - + public void printRecVoid(String description) throws Exception { checkEnabled(); execute(new PrintRecVoidRequest(description)); } - + public void printRecVoidItem(String description, long amount, int quantity, int adjustmentType, long adjustment, int vatInfo) throws Exception { checkEnabled(); description = decodeText(description); amount = convertAmount(amount); - + checkPrinterState(FPTR_PS_FISCAL_RECEIPT); checkQuantity(quantity); checkVatInfo(vatInfo); - + if (getParams().printRecVoidItemAmount) { quantity = 1000; } - + receipt.printRecVoidItem(description, amount, convertQuantity(quantity), adjustmentType, adjustment, vatInfo); } @@ -3649,10 +3670,10 @@ public void printReport(int reportType, String startNum, String endNum) checkEnabled(); startNum = decodeText(startNum); endNum = decodeText(endNum); - + checkEnabled(); checkPrinterState(FPTR_PS_MONITOR); - + int day1 = 0; int day2 = 0; switch (reportType) { @@ -3660,9 +3681,9 @@ public void printReport(int reportType, String startNum, String endNum) // case FPTR_RT_EOD_ORDINAL: day1 = stringParamToInt(startNum, "startNum"); day2 = stringParamToInt(endNum, "endNum"); - + printDocStart(); - + if (params.reportDevice == SmFptrConst.SMFPTR_REPORT_DEVICE_EJ) { getPrinter().printEJReportDays(day1, day2, params.reportType); } else { @@ -3670,7 +3691,7 @@ public void printReport(int reportType, String startNum, String endNum) } printEndFiscal(); break; - + case FPTR_RT_DATE: PrinterDate date1; PrinterDate date2; @@ -3680,7 +3701,7 @@ public void printReport(int reportType, String startNum, String endNum) // print report printDocStart(); - + if (params.reportDevice == SmFptrConst.SMFPTR_REPORT_DEVICE_EJ) { getPrinter().printEJDayReportOnDates(date1, date2, params.reportType); } else { @@ -3688,43 +3709,45 @@ public void printReport(int reportType, String startNum, String endNum) } printEndFiscal(); break; - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidParameterValue) + "reportType"); } } - + public void printXReport() throws Exception { checkEnabled(); checkStateBusy(); checkPrinterState(FPTR_PS_MONITOR); printDocStart(); getPrinter().printXReport(); + setDocumentLines(filter.getLines()); filter.printXReport(); printEndFiscal(); } - + public void printZReport() throws Exception { checkEnabled(); checkStateBusy(); checkPrinterState(FPTR_PS_MONITOR); - + sendDocumentsZReport(); stopFDOService(); - + if (getParams().forceOpenShiftOnZReport) { openFiscalDay(); } - + PrinterStatus status = readPrinterStatus(); if (status.getPrinterMode().canPrintZReport()) { - + saveZReportXml(); printDocStart(); getPrinter().printZReport(); filter.printZReport(); + setDocumentLines(filter.getLines()); fiscalDay.close(); try { printCalcReport(); @@ -3738,7 +3761,7 @@ public void printZReport() throws Exception { throw new JposException(JPOS_E_ILLEGAL, "Day is closed"); } } - + private void sendDocumentsZReport() { if (params.fdoMode == SmFptrConst.FDO_MODE_ZREPORT) { try { @@ -3748,16 +3771,16 @@ private void sendDocumentsZReport() { } } } - + private void printCalcReport() { if (!params.calcReportEnabled) { return; } - + if (!printer.getCapFiscalStorage()) { return; } - + try { printer.waitForPrinting(); FSReadCommStatus status = printer.fsReadCommStatus(); @@ -3769,7 +3792,7 @@ private void printCalcReport() { logger.error(e); } } - + private void saveZReportXml() throws Exception { if (params.xmlZReportEnabled || params.csvZReportEnabled) { try { @@ -3796,7 +3819,7 @@ private void saveZReportXml() throws Exception { } } } - + private String getXmlZReportFileName(int dayNumber) throws Exception { String fileName = params.xmlZReportFileName; if (params.ZReportDayNumber) { @@ -3807,7 +3830,7 @@ private String getXmlZReportFileName(int dayNumber) throws Exception { fileName = SysUtils.getFilesPath() + fileName; return fileName; } - + private String getCsvZReportFileName(int dayNumber) throws Exception { String fileName = params.csvZReportFileName; if (params.ZReportDayNumber) { @@ -3818,7 +3841,7 @@ private String getCsvZReportFileName(int dayNumber) throws Exception { fileName = SysUtils.getFilesPath() + fileName; return fileName; } - + private String getDayNumberText(int dayNumber) { String result = String.valueOf(dayNumber); for (int i = result.length(); i < 4; i++) { @@ -3826,7 +3849,7 @@ private String getDayNumberText(int dayNumber) { } return result; } - + public void resetPrinter() throws Exception { params.cancelIO = false; checkEnabled(); @@ -3836,21 +3859,21 @@ public void resetPrinter() throws Exception { isReceiptOpened = false; startFDOService(); } - + public void setDate(String date) throws Exception { checkEnabled(); date = decodeText(date); - + checkEnabled(); LongPrinterStatus status = getPrinter().readLongStatus(); if (!status.getPrinterMode().isDayClosed()) { dayEndRequiredError(); } - + JposFiscalPrinterDate jposDate = JposFiscalPrinterDate.parseDateTime(date); PrinterDate printerDate = jposDate.getPrinterDate(); PrinterTime printerTime = jposDate.getPrinterTime(); - + if (!printerDate.isEqual(status.getDate())) { getPrinter().check(printer.writeDate(printerDate)); int resultCode = getPrinter().confirmDate(printerDate); @@ -3858,7 +3881,7 @@ public void setDate(String date) throws Exception { // try to set date back printerDate = readLongStatus().getDate(); getPrinter().check(printer.confirmDate(printerDate)); - + throw new Exception( Localizer.getString(Localizer.failedConfirmDate) + printer.getErrorText(resultCode)); @@ -3878,20 +3901,20 @@ public void setDate(String date) throws Exception { + PrinterTime.toString(status.getTime())); } } - + public String getHeaderLine(int index) throws Exception { return header.getHeaderLine(index + 1).getText(); } - + public String getTrailerLine(int index) throws Exception { return header.getTrailerLine(index + 1).getText(); } - + public void setHeaderLine(int lineNumber, String text, boolean doubleWidth) throws Exception { checkEnabled(); text = decodeText(text); logger.debug("setHeaderLine: " + text); - + checkEnabled(); // reset graphic info if (lineNumber == 1) { @@ -3907,7 +3930,7 @@ public void setHeaderLine(int lineNumber, String text, boolean doubleWidth) thro saveProperties(); logoPosition = SmFptrConst.SMFPTR_LOGO_PRINT; } - + public void setPOSID(String POSID, String cashierID) throws Exception { checkEnabled(); if ((POSID != null) && (!POSID.isEmpty())) { @@ -3919,12 +3942,12 @@ public void setPOSID(String POSID, String cashierID) throws Exception { getPrinter().writeCasierName(cashierID); } } - + public void setStoreFiscalID(String ID) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void setTrailerLine(int lineNumber, String text, boolean doubleWidth) throws Exception { checkEnabled(); text = decodeText(text); @@ -3956,117 +3979,117 @@ public void getVatEntry(int vatID, int optArgs, int[] vatRate) checkParamValue(vatID, 1, getNumVatRates(), "vatID"); String[] vatValue = new String[1]; vatValue[0] = ""; - + getPrinter().check( printer.readTable(SMFP_TABLE_TAX, vatID, 1, vatValue)); vatRate[0] = Integer.parseInt(vatValue[0]); } - + public void setVatTable() throws Exception { checkEnabled(); checkCapHasVatTable(); checkCapSetVatTable(); - + if (vatValues == null) { return; } - + for (int i = 0; i < vatValues.length; i++) { getPrinter().check( printer.writeTable(SMFP_TABLE_TAX, i + 1, 1, String.valueOf(vatValues[i]))); } } - + public void checkCapHasVatTable() throws Exception { if (!getCapHasVatTable()) { throw new JposException(JPOS_E_ILLEGAL, "CapHasVatTable = false, vat table is not supported"); } } - + public void checkCapSetVatTable() throws Exception { checkCapHasVatTable(); if (!capSetVatTable) { throw new JposException(JPOS_E_ILLEGAL, "CapSetVatTable = false, setting vat table is not supported"); } } - + public void setVatValue(int vatID, String vatValue) throws Exception { checkEnabled(); checkCapHasVatTable(); checkCapSetVatTable(); - + vatValue = decodeText(vatValue); - + if (vatValues == null) { vatValues = new int[getNumVatRates()]; } - + checkParamValue(vatID, 1, vatValues.length, "vatID"); int intVatValue = Integer.parseInt(vatValue); checkParamValue(intVatValue, 0, 10000, "vatValue"); vatValues[vatID - 1] = intVatValue; } - + public void verifyItem(String itemName, int vatID) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void setCurrency(int newCurrency) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void printRecCashAsync(long amount) throws Exception { amount = convertAmount(amount); checkEnabled(); checkPrinterState(FPTR_PS_FISCAL_RECEIPT); receipt.printRecCash(amount); } - + public void printRecCash(long amount) throws Exception { checkEnabled(); execute(new PrintRecCashRequest(amount)); } - + public void printRecItemFuel(String description, long price, int quantity, int vatInfo, long unitPrice, String unitName, long specialTax, String specialTaxName) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void printRecItemFuelVoid(String description, long price, int vatInfo, long specialTax) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public void printRecPackageAdjustment(int adjustmentType, String description, String vatAdjustment) throws Exception { checkEnabled(); execute(new PrintRecPackageAdjustmentRequest(adjustmentType, description, vatAdjustment)); } - + public void printRecPackageAdjustmentAsync(int adjustmentType, String description, String vatAdjustment) throws Exception { description = decodeText(description); vatAdjustment = decodeText(vatAdjustment); - + checkEnabled(); checkPrinterState(FPTR_PS_FISCAL_RECEIPT); receipt.printRecPackageAdjustment(adjustmentType, description, vatAdjustment); } - + public void printRecPackageAdjustVoid(int adjustmentType, String vatAdjustment) throws Exception { execute(new PrintRecPackageAdjustVoidRequest(adjustmentType, vatAdjustment)); } - + public void printRecPackageAdjustVoidAsync(int adjustmentType, String vatAdjustment) throws Exception { vatAdjustment = decodeText(vatAdjustment); @@ -4074,28 +4097,28 @@ public void printRecPackageAdjustVoidAsync(int adjustmentType, checkPrinterState(FPTR_PS_FISCAL_RECEIPT); receipt.printRecPackageAdjustVoid(adjustmentType, vatAdjustment); } - + public void printRecRefundVoid(String description, long amount, int vatInfo) throws Exception { execute(new PrintRecRefundVoidRequest(description, amount, vatInfo)); } - + public void printRecRefundVoidAsync(String description, long amount, int vatInfo) throws Exception { description = decodeText(description); amount = convertAmount(amount); - + checkEnabled(); checkVatInfo(vatInfo); checkPrinterState(FPTR_PS_FISCAL_RECEIPT); receipt.printRecRefundVoid(description, amount, vatInfo); } - + public void printRecSubtotalAdjustVoid(int adjustmentType, long amount) throws Exception { execute(new PrintRecSubtotalAdjustVoidRequest(adjustmentType, amount)); } - + public void printRecSubtotalAdjustVoidAsync(int adjustmentType, long amount) throws Exception { amount = convertAmount(amount); @@ -4103,58 +4126,58 @@ public void printRecSubtotalAdjustVoidAsync(int adjustmentType, long amount) checkPrinterState(FPTR_PS_FISCAL_RECEIPT); receipt.printRecSubtotalAdjustVoid(adjustmentType, amount); } - + public void printRecTaxID(String taxID) throws Exception { execute(new PrintRecTaxIDRequest(taxID)); } - + public void printRecTaxIDAsync(String taxID) throws Exception { checkEnabled(); checkPrinterState(FPTR_PS_FISCAL_RECEIPT_ENDING); getPrinter().printText(SMFP_STATION_REC, decodeText(taxID), getFont()); } - + public int getAmountDecimalPlaces() throws Exception { checkEnabled(); return getModel().getAmountDecimalPlace(); } - + public boolean getCapStatisticsReporting() throws Exception { checkOpened(); return capStatisticsReporting; } - + public boolean getCapUpdateStatistics() throws Exception { checkOpened(); return capUpdateStatistics; } - + public void resetStatistics(String statisticsBuffer) throws Exception { statisticsBuffer = decodeText(statisticsBuffer); checkEnabled(); statistics.reset(statisticsBuffer); } - + public void retrieveStatistics(String[] statisticsBuffer) throws Exception { checkEnabled(); statistics.retrieve(statisticsBuffer); } - + public void updateStatistics(String statisticsBuffer) throws Exception { checkEnabled(); statistics.update(statisticsBuffer); } - + public boolean getCapCompareFirmwareVersion() throws Exception { checkOpened(); return capCompareFirmwareVersion; } - + public boolean getCapUpdateFirmware() throws Exception { checkOpened(); return capUpdateFirmware; } - + public void compareFirmwareVersion(String firmwareFileName, int[] result) throws Exception { if (!getCapCompareFirmwareVersion()) { @@ -4171,9 +4194,9 @@ public void compareFirmwareVersion(String firmwareFileName, int[] result) if (rc == -1) { result[0] = JposConst.JPOS_CFV_FIRMWARE_OLDER; } - + } - + public void updateFirmware(String firmwareFileName) throws Exception { checkEnabled(); if (!capUpdateFirmware) { @@ -4196,16 +4219,16 @@ public void printRecItemVoidAsync(String description, long price, unitPrice = convertAmount(unitPrice); description = decodeText(description); unitName = decodeText(unitName); - + checkEnabled(); checkQuantity(quantity); checkVatInfo(vatInfo); - + description = updateDescription(description); receipt.printRecItemVoid(description, price, convertQuantity(quantity), vatInfo, unitPrice, unitName); } - + public void printRecItemVoid(String description, long price, int quantity, int vatInfo, long unitPrice, String unitName) throws Exception { checkPrinterState(FPTR_PS_FISCAL_RECEIPT); @@ -4214,18 +4237,18 @@ public void printRecItemVoid(String description, long price, int quantity, request = filters.printRecItemVoid(request); execute(request); } - + public void printRecItemAdjustmentVoidAsync(int adjustmentType, String description, long amount, int vatInfo) throws Exception { description = decodeText(description); amount = convertAmount(amount); - + checkEnabled(); checkVatInfo(vatInfo); receipt.printRecItemAdjustmentVoid(adjustmentType, description, amount, vatInfo); } - + public void printRecItemAdjustmentVoid(int adjustmentType, String description, long amount, int vatInfo) throws Exception { checkPrinterState(FPTR_PS_FISCAL_RECEIPT); @@ -4239,11 +4262,11 @@ private void checkPrinterState(int value) throws Exception { throwWrongStateError(); } } - + private void setPrinterState(int newState) { printerState.setValue(newState); } - + private void checkParamValue(int value, int minValue, int maxValue, String paramText) throws Exception { if ((value < minValue) || (value > maxValue)) { @@ -4252,7 +4275,7 @@ private void checkParamValue(int value, int minValue, int maxValue, + paramText); } } - + private int stringParamToInt(String s, String paramName) throws Exception { try { int result = Integer.parseInt(s); @@ -4263,7 +4286,7 @@ private int stringParamToInt(String s, String paramName) throws Exception { + paramName); } } - + private String checkHealthExternal() throws Exception { PrinterStatus status = getPrinter().waitForPrinting(); if (!status.getPrinterMode().isTestMode()) { @@ -4274,14 +4297,14 @@ private String checkHealthExternal() throws Exception { getPrinter().waitForPrinting(); return "External HCheck: OK"; } - + private void checkStateBusy() throws Exception { if (state == JPOS_S_BUSY) { logger.error("JPOS_E_BUSY"); throw new JposException(JPOS_E_BUSY); } } - + public void cancelReceipt() throws Exception { setPrinterState(FPTR_PS_MONITOR); PrinterStatus status = getPrinter().waitForPrinting(); @@ -4292,7 +4315,7 @@ public void cancelReceipt() throws Exception { } } } - + public int getPayType(String key) throws Exception { // logger.debug("getPayType(" + String.valueOf(userPayType) + ")"); @@ -4303,7 +4326,7 @@ public int getPayType(String key) throws Exception { return payType.getValue(); } } - + public FontNumber getFont(boolean doubleWidth) { if (doubleWidth) { return doubleWidthFont; @@ -4311,7 +4334,7 @@ public FontNumber getFont(boolean doubleWidth) { return getFont(); } } - + public String encodeText(String text) { String result; if (getStringEncoding().length() == 0) { @@ -4327,7 +4350,7 @@ public String encodeText(String text) { } return result; } - + public String decodeText(String text) { String result; if (getStringEncoding().length() == 0) { @@ -4341,17 +4364,17 @@ public String decodeText(String text) { } } return result; - + } - + class PackageAdjustment { - + public int vat; public long amount; } - + class PackageAdjustments extends Vector { - + public PackageAdjustment addItem(int vat, long amount) { PackageAdjustment result = new PackageAdjustment(); result.vat = vat; @@ -4359,11 +4382,11 @@ public PackageAdjustment addItem(int vat, long amount) { add(result); return result; } - + public PackageAdjustment getItem(int Index) { return (PackageAdjustment) get(Index); } - + public void parse(String s) { String[] items = StringUtils.split(s, ';'); for (int i = 0; i < items.length; i++) { @@ -4375,45 +4398,45 @@ public void parse(String s) { } } } - + private void checkClaimed() throws Exception { if (!claimed) { throw new JposException(JPOS_E_NOTCLAIMED, "Service is not claimed"); } } - + public void checkEnabled() throws Exception { checkClaimed(); if (!deviceEnabled) { throw new JposException(JPOS_E_DISABLED, "Service is not enabled"); } } - + public void printFiscalDocumentLineAsync(String documentLine) throws Exception { checkEnabled(); noSlipStationError(); } - + public void printFixedOutputAsync(int documentType, int lineNumber, String data) throws Exception { checkEnabled(); throw new JposException(JPOS_E_ILLEGAL); } - + public int getMaxGraphicsHeight() throws Exception { return getModel().getMaxGraphicsHeight(); } - + public void loadGraphics(int lineNumber, int lineCount, byte[] data) throws Exception { getPrinter().loadGraphics(lineNumber, lineCount, data); } - + public void throwTestError() throws Exception { throw new DeviceException(0x71, "Cutter failure"); } - + public void checkDeviceStatus() throws Exception { try { synchronized (printer) { @@ -4427,7 +4450,7 @@ public void checkDeviceStatus() throws Exception { logger.error("checkDeviceStatus", e); } } - + public void deviceProc() { logger.debug("Poll thread started"); try { @@ -4442,33 +4465,33 @@ public void deviceProc() { } logger.debug("Poll thread stopped"); } - + public DeviceMetrics getDeviceMetrics() throws Exception { return getPrinter().getDeviceMetrics(); } - + public void printBarcode(PrinterBarcode barcode) throws Exception { receipt.printBarcode(barcode); } - + public void printRawGraphics(byte[][] data) throws Exception { PrinterGraphics graphics = new PrinterGraphics(data); receipt.printGraphics(graphics); } - + public void printRecItemRefund(String description, long amount, int quantity, int vatInfo, long unitAmount, String unitName) throws Exception { checkEnabled(); checkPrinterState(FPTR_PS_FISCAL_RECEIPT); - + filters.printRecItemRefund(description, amount, quantity, vatInfo, unitAmount, unitName); - + execute(new PrintRecItemRefundRequest(description, amount, quantity, vatInfo, unitAmount, unitName)); } - + public void printRecItemRefundAsync(String description, long amount, int quantity, int vatInfo, long unitAmount, String unitName) throws Exception { @@ -4476,32 +4499,32 @@ public void printRecItemRefundAsync(String description, long amount, description = decodeText(description); amount = convertAmount(amount); unitAmount = convertAmount(unitAmount); - + checkEnabled(); checkReceiptStation(); checkQuantity(quantity); checkPrice(amount); checkPrice(unitAmount); checkVatInfo(vatInfo); - + description = updateDescription(description); receipt.printRecItemRefund(description, amount, convertQuantity(quantity), vatInfo, unitAmount, unitName); } - + public void printRecItemRefundVoid(String description, long amount, int quantity, int vatInfo, long unitAmount, String unitName) throws Exception { checkEnabled(); checkPrinterState(FPTR_PS_FISCAL_RECEIPT); - + filters.printRecItemRefundVoid(description, amount, quantity, vatInfo, unitAmount, unitName); - + execute(new PrintRecItemRefundVoidRequest(description, amount, quantity, vatInfo, unitAmount, unitName)); } - + public void printRecItemRefundVoidAsync(String description, long amount, int quantity, int vatInfo, long unitAmount, String unitName) throws Exception { @@ -4509,16 +4532,16 @@ public void printRecItemRefundVoidAsync(String description, long amount, unitAmount = convertAmount(unitAmount); description = decodeText(description); unitName = decodeText(unitName); - + checkEnabled(); checkQuantity(quantity); checkVatInfo(vatInfo); - + description = updateDescription(description); receipt.printRecItemRefundVoid(description, amount, convertQuantity(quantity), vatInfo, unitAmount, unitName); } - + public void saveXmlZReport(String fileName) throws JposException { try { RegisterReport report = new RegisterReport(); @@ -4529,7 +4552,7 @@ public void saveXmlZReport(String fileName) throws JposException { throw new JposException(JPOS_E_FAILURE, e.getMessage()); } } - + public void saveCsvZReport(String fileName) throws JposException { try { RegisterReport report = new RegisterReport(); @@ -4540,17 +4563,17 @@ public void saveCsvZReport(String fileName) throws JposException { throw new JposException(JPOS_E_FAILURE, e.getMessage()); } } - + private String getPropsFileName() throws Exception { return SysUtils.getFilesPath() + "shtrihjavapos.xml"; } - + protected JposEntry createJposEntry(String logicalName, String factoryClass, String serviceClass, String vendorName, String vendorURL, String deviceCategory, String jposVersion, String productName, String productDescription, String productURL) { JposEntry jposEntry = new SimpleEntry(); - + jposEntry.addProperty(JposEntry.LOGICAL_NAME_PROP_NAME, logicalName); jposEntry.addProperty(JposEntry.SI_FACTORY_CLASS_PROP_NAME, factoryClass); @@ -4564,10 +4587,10 @@ protected JposEntry createJposEntry(String logicalName, jposEntry.addProperty(JposEntry.PRODUCT_DESCRIPTION_PROP_NAME, productDescription); jposEntry.addProperty(JposEntry.PRODUCT_URL_PROP_NAME, productURL); - + return jposEntry; } - + public void saveProperties() { try { String serial = "FiscalPrinter_" + getPrinter().getFullSerial(); @@ -4578,15 +4601,15 @@ public void saveProperties() { writer.writePrinterHeader(header); writer.writeNonFiscalDocNumber(params.nonFiscalDocNumber); writer.writeParameterBool("isTableTextCleared", params.isTableTextCleared); - + writer.save(getPropsFileName()); } catch (Exception e) { logger.error("saveProperties", e); } } - + private void loadProperties() throws Exception { - + logger.debug("loadProperties"); try { String serial = "FiscalPrinter_" + getPrinter().readFullSerial(); @@ -4595,7 +4618,7 @@ private void loadProperties() throws Exception { if (f.exists()) { XmlPropReader reader = new XmlPropReader(); reader.load("FiscalPrinter", serial, fileName); - + reader.read(getPrinterImages()); reader.read(printer.getReceiptImages()); reader.readPrinterHeader(header); @@ -4609,88 +4632,88 @@ private void loadProperties() throws Exception { logger.error("Failed to load properties", e); } } - + private void throwWrongStateError() throws Exception { throw new JposException(JPOS_E_EXTENDED, JPOS_EFPTR_WRONG_STATE, Localizer.getString(Localizer.wrongPrinterState) + "(" + String.valueOf(printerState) + ", " + "\"" + PrinterState.getText(printerState.getValue()) + "\""); } - + public void writeParameter(String paramName, int value) throws Exception { getPrinter().writeParameter(paramName, value); } - + public void writeParameter(String paramName, boolean value) throws Exception { getPrinter().writeParameter(paramName, value); } - + public void writeParameter(String paramName, String value) throws Exception { getPrinter().writeParameter(paramName, value); } - + public String readParameter(String paramName) throws Exception { return getPrinter().readParameter(paramName); } - + public void setFiscalReceiptType(int value) throws Exception { fiscalReceiptType = value; } - + public FiscalReceipt createReceipt(int fiscalReceiptType) throws Exception { checkEnabled(); checkPrinterState(FPTR_PS_MONITOR); switch (fiscalReceiptType) { case FPTR_RT_CASH_IN: return new CashInReceipt(getReceiptContext()); - + case FPTR_RT_CASH_OUT: return new CashOutReceipt(getReceiptContext()); - + case FPTR_RT_GENERIC: case FPTR_RT_SALES: case FPTR_RT_SERVICE: case FPTR_RT_SIMPLE_INVOICE: // case FPTR_RT_REFUND: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_SALE); - + case FPTR_RT_REFUND: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_RETSALE); - + case SmFptrConst.SMFPTR_RT_SALE: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_SALE); - + case SmFptrConst.SMFPTR_RT_BUY: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_BUY); - + case SmFptrConst.SMFPTR_RT_RETSALE: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_RETSALE); - + case SmFptrConst.SMFPTR_RT_RETBUY: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_RETBUY); - + case SmFptrConst.SMFPTR_RT_CORRECTION: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_CORRECTION_SALE); - + case SmFptrConst.SMFPTR_RT_CORRECTION_SALE: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_CORRECTION_SALE); - + case SmFptrConst.SMFPTR_RT_CORRECTION_BUY: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_CORRECTION_BUY); - + case SmFptrConst.SMFPTR_RT_CORRECTION_RETSALE: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_CORRECTION_RETSALE); - + case SmFptrConst.SMFPTR_RT_CORRECTION_RETBUY: return createSalesReceipt(PrinterConst.SMFP_RECTYPE_CORRECTION_RETBUY); - + default: throw new JposException(JPOS_E_ILLEGAL, Localizer.getString(Localizer.invalidParameterValue)); } } - + private boolean isTablesRead = false; - + private FiscalReceipt createSalesReceipt(int receiptType) throws Exception { FiscalReceipt result; if (printer.getCapFiscalStorage()) { @@ -4706,7 +4729,7 @@ private FiscalReceipt createSalesReceipt(int receiptType) throws Exception { } return result; } - + private ReceiptContext getReceiptContext() { if (receiptContext == null) { receiptContext = new ReceiptContext(receiptPrinter, params, @@ -4714,23 +4737,23 @@ private ReceiptContext getReceiptContext() { } return receiptContext; } - + public FptrParameters getParams() { return params; } - + public PrinterReceipt getReceipt() { return printerReceipt; } - + public FontNumber getFont() { return params.getFont(); } - + public String getStringEncoding() { return params.stringEncoding; } - + public boolean handleDeviceException(Exception e) throws Exception { if (connected && (params.searchMode == SmFptrConst.SMFPTR_SEARCH_ON_ERROR)) { @@ -4741,15 +4764,15 @@ public boolean handleDeviceException(Exception e) throws Exception { return false; } } - + public int getFontNumber() { return params.getFont().getValue(); } - + public void setFontNumber(int value) throws Exception { params.setFont(new FontNumber(value)); } - + public EJActivation getEJActivation() throws Exception { LongPrinterStatus longStatus = readLongStatus(); if ((longStatus.getRegistrationNumber() > 0) @@ -4760,11 +4783,11 @@ public EJActivation getEJActivation() throws Exception { return new EJActivation(); } } - + public int loadLogo(String fileName) throws Exception { return loadLogo(fileName, logoPosition); } - + public int loadLogo(String fileName, int logoPosition) throws Exception { int imageIndex = -1; PrinterImage image = new PrinterImage(fileName); @@ -4782,37 +4805,37 @@ public int loadLogo(String fileName, int logoPosition) throws Exception { } return imageIndex; } - + public ReceiptImages getReceiptImages() { return printer.getReceiptImages(); } - + public void fsWriteTLV(byte[] data, boolean print) throws Exception { logger.debug("fsWriteTLV: " + Hex.toHex(data)); receipt.fsWriteTLV(data, print); } - + public void fsWriteOperationTLV(byte[] data, boolean print) throws Exception { receipt.fsWriteOperationTLV(data, print); } - + public void disablePrintOnce() throws Exception { getPrinter().disablePrintOnce(); } - + public void disablePrint() throws Exception { getPrinter().disablePrint(); } - + public void enablePrint() throws Exception { getPrinter().enablePrint(); } - + public void fsPrintCalcReport() throws Exception { printDocStart(); FSPrintCalcReport command = new FSPrintCalcReport(printer.getSysPassword()); printer.execute(command); - + try { printer.waitForPrinting(); printEndFiscal(); @@ -4820,47 +4843,102 @@ public void fsPrintCalcReport() throws Exception { logger.error("fsPrintCalcReport", e); } } - + public void setDiscountAmount(int amount) throws Exception { if ((printerState.getValue() != FPTR_PS_FISCAL_RECEIPT) && (printerState.getValue() != FPTR_PS_FISCAL_RECEIPT_TOTAL)) { throwWrongStateError(); } - + receipt.setDiscountAmount(amount); - + if (receipt.isPayed()) { setPrinterState(FPTR_PS_FISCAL_RECEIPT_ENDING); } else { setPrinterState(FPTR_PS_FISCAL_RECEIPT_TOTAL); } } - + public String getReceiptName(int receiptType) { return ""; } - + public void setItemBarcode(String barcode) throws Exception { receipt.setItemBarcode(barcode); } - + public void addItemCode(byte[] mcdata) throws Exception { receipt.addItemCode(mcdata); } - + public void saveMCNotifications(String fileName) throws Exception { MCNotifications items = printer.readNotifications(); MCNotificationsReport report = new MCNotificationsReport(); report.save(items, fileName); printer.confirmNotifications(items); } - + public int mcClearBuffer() throws Exception { return printer.mcClearBuffer(); } - + public PrinterPort getPort() { return port; } - + + public void setDocumentLines(List lines) { + documentLines.clear(); + documentLines.addAll(lines); + saveLastDocument(); + } + + public static String getLastDocFilePath() { + return SysUtils.getFilesPath() + "document.txt"; + } + + private void saveLastDocument() { + try { + File file = new File(getLastDocFilePath()); + if (file.exists()) { + file.delete(); + } + PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file, true))); + try { + for (int i = 0; i < documentLines.size(); i++) + { + String line = documentLines.get(i); + writer.println(line); + } + writer.flush(); + } finally { + writer.close(); + } + } catch (Exception e) { + logger.error("Failed to save last document, ", e); + } + } + + private void readLastDocument() { + try { + documentLines.clear(); + File file = new File(getLastDocFilePath()); + if (!file.exists()) { + logger.debug("Last document not found"); + return; + } + + BufferedReader reader = new BufferedReader(new FileReader(file)); + try { + String line; + while ((line = reader.readLine()) != null) { + documentLines.add(line); + } + } finally { + reader.close(); + } + } catch (Exception e) { + logger.error("Failed to read last document, ", e); + } + } + } diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashInReceipt.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashInReceipt.java index abc7a6b8..9526e3be 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashInReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashInReceipt.java @@ -49,4 +49,7 @@ public boolean getCapAutoCut() throws Exception { public long getSubtotal() throws Exception { return 0; } + + public void accept(ReceiptVisitor visitor) throws Exception{ + } } diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashOutReceipt.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashOutReceipt.java index 3cb04cdb..3097324f 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashOutReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashOutReceipt.java @@ -50,4 +50,6 @@ public long getSubtotal() throws Exception { return 0; } + public void accept(ReceiptVisitor visitor) throws Exception{ + } } diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CustomReceipt.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CustomReceipt.java index d79f50a5..22242d57 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CustomReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CustomReceipt.java @@ -271,4 +271,8 @@ public long getSubtotal() throws Exception { public void printReceiptEnding() throws Exception{ } + + public void accept(ReceiptVisitor visitor) throws Exception{ + visitor.visitCustomReceipt(this); + } } diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/FSSalesReceipt.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/FSSalesReceipt.java index 87a47b08..d70d4f3c 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/FSSalesReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/FSSalesReceipt.java @@ -47,7 +47,7 @@ public class FSSalesReceipt extends CustomReceipt implements FiscalReceipt { private int receiptType = 0; private boolean isOpened = false; private String voidDescription = ""; - public Vector items = new Vector(); + public Vector items = new Vector(); private final Vector endingItems = new Vector(); private final long[] payments = new long[16]; // payment amounts public final FSDiscounts discounts = new FSDiscounts(); @@ -1533,31 +1533,8 @@ public double getItemQuantity(long price, double quantity, long total, long amou return result / 1000000.0; } -} - -/* - long amount = Math.round(item.getPriceWithDiscount() * item.getQuantity()); - long discountAmount = amount - item.getTotal(); - if (discountAmount > 0) - { - if ((discounts.getTotal() + discountAmount-1) > 99){ - throw new Exception("Discount cannot be applied"); - } - printTotalDiscount(discountAmount-1, 0, ""); - item.setTotal(amount-1); - item.getDiscounts().clear(); - } - - public long calcPriceWithDiscount() { - if (quantity == 0) { - return 0; - } - if ((discounts.getTotal() == 0)||(discounts.getTotal() == 1)) { - return price; - } - long price1 = (long)Math.abs((totalAmount - discounts.getTotal()) / (double)quantity); - return price1; - } - - - */ + public void accept(ReceiptVisitor visitor) throws Exception{ + visitor.visitSalesReceipt(this); + } + +} \ No newline at end of file diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/FiscalReceipt.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/FiscalReceipt.java index 9d73519d..232ff8b2 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/FiscalReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/FiscalReceipt.java @@ -113,4 +113,6 @@ public void printRecItemRefundVoid(String description, long amount, public long getSubtotal() throws Exception; public void printReceiptEnding() throws Exception; + + public void accept(ReceiptVisitor visitor) throws Exception; } \ No newline at end of file diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/NullReceipt.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/NullReceipt.java index 82d7297e..0620293b 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/NullReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/NullReceipt.java @@ -235,4 +235,8 @@ public long getSubtotal() throws Exception { public void printReceiptEnding() throws Exception{ } + + public void accept(ReceiptVisitor visitor) throws Exception{ + visitor.visitCustomReceipt(this); + } } diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptVisitor.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptVisitor.java new file mode 100644 index 00000000..597e5490 --- /dev/null +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptVisitor.java @@ -0,0 +1,16 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.shtrih.jpos.fiscalprinter.receipt; + +/** + * + * @author Виталий + */ +public interface ReceiptVisitor { + + public void visitSalesReceipt(Object element); + public void visitCustomReceipt(Object element); +} diff --git a/Source/FiscalPrinterService/src/com/shtrih/util/ServiceVersion.java b/Source/FiscalPrinterService/src/com/shtrih/util/ServiceVersion.java index 2f2058da..253ff02a 100644 --- a/Source/FiscalPrinterService/src/com/shtrih/util/ServiceVersion.java +++ b/Source/FiscalPrinterService/src/com/shtrih/util/ServiceVersion.java @@ -1,5 +1,5 @@ package com.shtrih.util; public class ServiceVersion { - public static final String VERSION = "696-1-gabb1a9d"; + public static final String VERSION = "696-2-gc646619"; } \ No newline at end of file diff --git a/Source/FiscalPrinterTest/Res/jpos.xml b/Source/FiscalPrinterTest/Res/jpos.xml index 369f52f5..fcb21530 100644 --- a/Source/FiscalPrinterTest/Res/jpos.xml +++ b/Source/FiscalPrinterTest/Res/jpos.xml @@ -21,7 +21,7 @@ - + @@ -31,7 +31,8 @@ - + + @@ -47,9 +48,9 @@ - + - +