diff --git a/History.txt b/History.txt index 432eae10..ada4fdc4 100644 --- a/History.txt +++ b/History.txt @@ -7,7 +7,7 @@ ******************************************************************************** - 11.07.2023 + 16.08.2023 deviceServiceVersion = 1013700 [-] Fixed errors with receipt duplicate diff --git a/Source/Core/src/com/shtrih/fiscalprinter/SMFiscalPrinterNull.java b/Source/Core/src/com/shtrih/fiscalprinter/SMFiscalPrinterNull.java index 454fdda8..90278a7f 100644 --- a/Source/Core/src/com/shtrih/fiscalprinter/SMFiscalPrinterNull.java +++ b/Source/Core/src/com/shtrih/fiscalprinter/SMFiscalPrinterNull.java @@ -46,6 +46,7 @@ public class SMFiscalPrinterNull implements SMFiscalPrinter { private final PrinterPort port; private final FptrParameters params; private final PrinterImages printerImages = new PrinterImages(); + public final PrinterTables tables = new PrinterTables(); private int resultCode = 0; public SMFiscalPrinterNull( @@ -76,7 +77,14 @@ public SMFiscalPrinterNull( printerStatus.setSubmode(submode); shortStatus.setSubmode(submode); longStatus.setSubmode(submode); - + + deviceMetrics.setDeviceType(1); + deviceMetrics.setDeviceSubType(2); + deviceMetrics.setProtocolVersion(3); + deviceMetrics.setProtocolSubVersion(4); + deviceMetrics.setModel(5); + deviceMetrics.setLanguage(0); + deviceMetrics.setDeviceName("DeviceName"); } public boolean getCapFiscalStorage() { @@ -245,16 +253,22 @@ public int writeTable(int tableNumber, int rowNumber, int fieldNumber, } public int readTable(int tableNumber, int rowNumber, int fieldNumber, - String[] fieldValue) throws Exception { - return 0; - } - - public int readTableInfo(int tableNumber, Object[] out) throws Exception { - return 0; - } - - public ReadTableInfo readTableInfo(int tableNumber) throws Exception { - return new ReadTableInfo(); + String[] fieldValue) throws Exception + { + PrinterTable table = tables.find(tableNumber); + if (table == null) return 0x33; + PrinterField field = table.getFields().find(tableNumber, rowNumber, fieldNumber); + if (field == null) return 0x33; + fieldValue[0] = field.getValue(); + return 0; + } + + public ReadTableInfo readTableInfo(int tableNumber) throws Exception + { + PrinterTable table = tables.find(tableNumber); + ReadTableInfo result = new ReadTableInfo(); + result.setTable(table); + return result; } public PrintCashIn printCashIn(long sum) throws Exception { diff --git a/Source/Core/src/com/shtrih/fiscalprinter/command/LongPrinterStatus.java b/Source/Core/src/com/shtrih/fiscalprinter/command/LongPrinterStatus.java index 01a4fdad..c0cf4941 100644 --- a/Source/Core/src/com/shtrih/fiscalprinter/command/LongPrinterStatus.java +++ b/Source/Core/src/com/shtrih/fiscalprinter/command/LongPrinterStatus.java @@ -30,8 +30,8 @@ public class LongPrinterStatus implements PrinterConst { private String fmFirmwareVersion = ""; private int fmFirmwareBuild = 0; private PrinterDate fmFirmwareDate = new PrinterDate(); - private PrinterDate date = new PrinterDate(); - private PrinterTime time = new PrinterTime(); + private PrinterDate date = new PrinterDate(1, 2, 3); + private PrinterTime time = new PrinterTime(1, 2, 3); private int fmFlags = 0; private int serialNumber = 0; private int dayNumber = 0; diff --git a/Source/Core/src/com/shtrih/fiscalprinter/command/ReadTableInfo.java b/Source/Core/src/com/shtrih/fiscalprinter/command/ReadTableInfo.java index 8262afb0..38778390 100644 --- a/Source/Core/src/com/shtrih/fiscalprinter/command/ReadTableInfo.java +++ b/Source/Core/src/com/shtrih/fiscalprinter/command/ReadTableInfo.java @@ -64,6 +64,10 @@ public PrinterTable getTable() { return table; } + public void setTable(PrinterTable table) { + this.table = table; + } + public boolean getIsRepeatable() { return true; } diff --git a/Source/Core/src/com/shtrih/fiscalprinter/command/TextGenerator.java b/Source/Core/src/com/shtrih/fiscalprinter/command/TextGenerator.java index e04b7755..8df7020f 100644 --- a/Source/Core/src/com/shtrih/fiscalprinter/command/TextGenerator.java +++ b/Source/Core/src/com/shtrih/fiscalprinter/command/TextGenerator.java @@ -55,59 +55,76 @@ public class TextGenerator implements ReceiptVisitor { private List lines = new Vector(); private static CompositeLogger logger = CompositeLogger.getLogger(TextGenerator.class); - public TextGenerator(SMFiscalPrinter printer) throws Exception { + public TextGenerator(SMFiscalPrinter printer) { this.printer = printer; } - public void visitCustomReceipt(Object element) { + public void visitCustomReceipt(Object element) throws Exception { } - public void visitSalesReceipt(Object element) { + public void visitCashInReceipt(Object element) throws Exception{ + if (!(element instanceof CashInReceipt)) { + return; + } + CashInReceipt receipt = (CashInReceipt) element; + + printReceiptHeader(); + add(PrinterConst.SCashInText, amountToStr(receipt.getSubtotal())); + // Change + if (receipt.getChange() > 0) { + add(PrinterConst.SChangeText, summToStr(receipt.getChange())); + } + } + + public void visitCashOutReceipt(Object element) throws Exception{ + if (!(element instanceof CashOutReceipt)) { + return; + } + CashOutReceipt receipt = (CashOutReceipt) element; + + printReceiptHeader(); + add(PrinterConst.SCashOutText, amountToStr(receipt.getSubtotal())); + // Change + if (receipt.getChange() > 0) { + add(PrinterConst.SChangeText, summToStr(receipt.getChange())); + } + } + + public void visitSalesReceipt(Object element) throws Exception { if (!(element instanceof FSSalesReceipt)) { return; } FSSalesReceipt receipt = (FSSalesReceipt) element; - try { - connect(); - operatorNumber = printer.getOperatorNumber(); + connect(); + operatorNumber = printer.getOperatorNumber(); - lines.clear(); - printReceiptHeader(); - for (int i = 0; i < receipt.items.size(); i++) { - process((Object) receipt.items.get(i)); - } - if (receipt.discounts.getTotal() > 0) { - add(PrinterConst.STotalText, summToStr(receipt.getSubtotal())); - /* - if (receipt.isRounded()){ - add(PrinterConst.SRoundingText, summToStr(receipt.getRounding())); - } - */ - } - - add(PrinterConst.SReceiptTotal, summToStr(receipt.getSubtotal())); - // payments - long[] payments = receipt.getPayments(); - for (int i = 0; i < payments.length; i++) - { - if (payments[i] > 0) - { - String paymentName = printer.readTable(PrinterConst.SMFP_TABLE_PAYTYPE, i + 1, 1); - add(paymentName, summToStr(payments[i])); - } + lines.clear(); + printReceiptHeader(); + for (int i = 0; i < receipt.items.size(); i++) { + process((Object) receipt.items.get(i)); + } + if (receipt.getDiscountsTotal() > 0) { + add(PrinterConst.STotalText, summToStr(receipt.getSubtotal())); + if (receipt.isRounded()) { + add(PrinterConst.SRoundingText, summToStr(receipt.getDiscountsTotal())); } - // Change - if (receipt.getChange() > 0) - { - add(PrinterConst.SChangeText, summToStr(receipt.getChange())); + } + add(PrinterConst.SReceiptTotal, summToStr(receipt.getSubtotal())); + // payments + long[] payments = receipt.getPayments(); + for (int i = 0; i < payments.length; i++) { + if (payments[i] > 0) { + String paymentName = printer.readTable(PrinterConst.SMFP_TABLE_PAYTYPE, i + 1, 1); + add(paymentName, summToStr(payments[i])); } - - } catch (Exception e) { - logger.error("Failed duplicate receipt", e); } + // Change + if (receipt.getChange() > 0) { + add(PrinterConst.SChangeText, summToStr(receipt.getChange())); + } + } - public void addFiscalSign() { try { printer.waitForPrinting(); @@ -228,11 +245,11 @@ private void process(FSSaleReceiptItem item) throws Exception { add(item.getText()); line = String.format("%s X %s", - quantityToStr(item.getQuantity() / 1000000.0), + quantityToStr(item.getQuantity()), amountToStr(item.getPrice())); add("", line); - line = summToStr(item.getPrice(), item.getQuantity() / 1000000.0) + line = summToStr(item.getPrice(), item.getQuantity()) + getTaxData(item.getTax1(), 0, 0, 0); add(String.format("%02d", item.getDepartment()), line); @@ -298,6 +315,13 @@ private int getLineLength() throws Exception { } private void add(String s1, String s2) throws Exception { + if (s1 == null) { + return; + } + if (s2 == null) { + return; + } + int len = getLineLength() - s1.length() - s2.length(); String line = s1 + StringUtils.stringOfChar(' ', len) + s2; add(line); diff --git a/Source/Core/src/com/shtrih/fiscalprinter/table/PrinterField.java b/Source/Core/src/com/shtrih/fiscalprinter/table/PrinterField.java index addf3f3f..1e13dac4 100644 --- a/Source/Core/src/com/shtrih/fiscalprinter/table/PrinterField.java +++ b/Source/Core/src/com/shtrih/fiscalprinter/table/PrinterField.java @@ -34,6 +34,12 @@ public PrinterField(FieldInfo fieldInfo, int row) { this.row = row; } + public PrinterField(FieldInfo fieldInfo, int row, String value) { + this.fieldInfo = fieldInfo; + this.row = row; + this.value = value; + } + public PrinterField getCopy() throws Exception { PrinterField res = new PrinterField(getFieldInfo(), getRow()); res.setValue(value); @@ -70,8 +76,8 @@ public void checkValue(String value) throws Exception { } - public void setValue(String value) throws Exception { - checkValue(value); + public void setValue(String value) { + //checkValue(value); this.value = value; } diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/FiscalPrinterImpl.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/FiscalPrinterImpl.java index 195a88b3..a86a203b 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/FiscalPrinterImpl.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/FiscalPrinterImpl.java @@ -60,7 +60,6 @@ import com.shtrih.jpos.fiscalprinter.receipt.GlobusSalesReceipt; import com.shtrih.jpos.fiscalprinter.receipt.NonfiscalReceipt; import com.shtrih.jpos.fiscalprinter.receipt.NullReceipt; -import com.shtrih.jpos.fiscalprinter.receipt.ReceiptContext; import com.shtrih.jpos.fiscalprinter.receipt.SalesReceipt; import com.shtrih.jpos.fiscalprinter.request.FiscalPrinterRequest; import com.shtrih.jpos.fiscalprinter.request.PrintNormalRequest; @@ -130,9 +129,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; @@ -273,54 +272,53 @@ public class FiscalPrinterImpl extends DeviceService implements PrinterConst, private JsonUpdateService jsonUpdateService = null; 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(); } @@ -343,11 +341,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; @@ -368,14 +366,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; @@ -389,7 +387,7 @@ private void initializeData() { capSlpFiscalDocument = false; capSlpFullSlip = false; capSlpValidation = false; - + capSubtotal = true; capTrainingMode = false; capValidateJournal = false; @@ -403,7 +401,7 @@ private void initializeData() { capFiscalReceiptType = true; capMultiContractor = false; capOnlyVoidLastItem = false; - + capPostPreLine = true; capSetCurrency = false; capTotalizerType = true; @@ -448,34 +446,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(); } @@ -487,16 +485,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) { @@ -504,15 +502,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; @@ -521,7 +519,7 @@ public void setPowerState(int powerState) { } this.powerState = powerState; } - + private void setState(int value) { if (value != state) { state = value; @@ -531,38 +529,38 @@ 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 (isInReceiptTrailer) { printEndNonFiscal(); @@ -571,10 +569,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 +587,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 +604,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 +665,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 +673,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 +691,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 +710,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 +729,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 +748,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 +760,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 +772,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 +785,7 @@ private void setCoverState(boolean isCoverOpened) throws Exception { } } } - + public void execute(FiscalPrinterRequest request) throws Exception { if (asyncMode) { setState(JPOS_S_BUSY); @@ -800,14 +798,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 +814,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 +842,7 @@ public void eventProc() { synchronized (events) { while (!events.isEmpty()) { ((Runnable) events.remove(0)).run(); - + } events.wait(); } @@ -853,7 +851,7 @@ public void eventProc() { Thread.currentThread().interrupt(); } } - + public void asyncProc() { try { while (!Thread.currentThread().isInterrupted()) { @@ -871,16 +869,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 +887,7 @@ private void startPoll() throws Exception { deviceThread.start(); } } - + private void stopPoll() throws Exception { if (deviceThread != null) { logger.debug("Poll thread stopping..."); @@ -899,7 +897,7 @@ private void stopPoll() throws Exception { deviceThread = null; } } - + public void setDeviceEnabled(boolean deviceEnabled) throws Exception { logger.debug("setDeviceEnabled(" + deviceEnabled + ")"); checkClaimed(); @@ -908,24 +906,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 +931,7 @@ public void setDeviceEnabled(boolean deviceEnabled) throws Exception { loadProperties(); updateCommandTimeouts(); } - + isTablesRead = false; capSetVatTable = getPrinter().getCapSetVatTable(); capUpdateFirmware = getPrinter().getCapUpdateFirmware(); @@ -958,14 +956,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(); @@ -981,7 +979,7 @@ public void setDeviceEnabled(boolean deviceEnabled) throws Exception { logger.debug("setDeviceEnabled: OK"); } } - + public void updateCommandTimeouts() { try { String[] value = new String[1]; @@ -998,75 +996,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; @@ -1074,24 +1072,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)); } @@ -1100,12 +1098,12 @@ public void setPrinterFDOMode(int mode) { logger.error("setPrinterFDOMode ", e); } } - + public void stopFDOService() { if (fdoService == null) { return; } - + try { fdoService.stop(); fdoService = null; @@ -1113,7 +1111,7 @@ public void stopFDOService() { logger.error("Failed to stop fsSenderService", e); } } - + public void stopFirmwareUpdaterService() { if (firmwareUpdaterService == null) { return; @@ -1127,33 +1125,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(); @@ -1166,25 +1164,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"; @@ -1215,9 +1213,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++) { @@ -1227,7 +1225,7 @@ public static String bytesToHex(byte[] bytes) { } return new String(hexChars); } - + public void setPollEnabled(boolean value) throws Exception { if (value != params.pollEnabled) { if (value) { @@ -1240,22 +1238,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()) { @@ -1267,7 +1265,7 @@ public void setFreezeEvents(boolean freezeEvents) throws Exception { } } } - + private void stopEventThread() throws Exception { if (eventThread != null) { synchronized (events) { @@ -1279,7 +1277,7 @@ private void stopEventThread() throws Exception { eventThread = null; } } - + private void startEventThread() throws Exception { if (eventThread == null) { eventStopFlag = false; @@ -1287,19 +1285,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; } @@ -1311,31 +1309,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( @@ -1345,165 +1343,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, @@ -1511,20 +1509,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) { @@ -1538,20 +1536,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()) { @@ -1560,12 +1558,12 @@ public boolean getCoverOpen() throws Exception { return coverOpened; } } - + public boolean getDayOpened() throws Exception { checkEnabled(); - + PrinterMode mode = getPrinter().readPrinterStatus().getPrinterMode(); - + if (!params.openReceiptOnBegin) { // Эта логика должна выполняться, только если beginFiscalReceipt не открывает чек, // во всех остальных случаях нужно обращаться к устройству @@ -1573,46 +1571,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; @@ -1631,55 +1629,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()) { @@ -1688,7 +1686,7 @@ public boolean getRecEmpty() throws Exception { return false; } } - + public boolean getRecNearEnd() throws Exception { checkEnabled(); if (getCapRecNearEndSensor()) { @@ -1696,31 +1694,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) { @@ -1731,67 +1729,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; } @@ -1801,7 +1799,7 @@ public int getActualCurrency() throws Exception { checkEnabled(); return actualCurrency; } - + public String getAdditionalHeader() throws Exception { checkEnabled(); if (!getCapAdditionalHeader()) { @@ -1810,7 +1808,7 @@ public String getAdditionalHeader() throws Exception { } return encodeText(additionalHeader); } - + public void setAdditionalHeader(String value) throws Exception { checkEnabled(); if (!getCapAdditionalHeader()) { @@ -1819,7 +1817,7 @@ public void setAdditionalHeader(String value) throws Exception { } additionalHeader = decodeText(value); } - + public String getAdditionalTrailer() throws Exception { checkEnabled(); if (!getCapAdditionalTrailer()) { @@ -1829,7 +1827,7 @@ public String getAdditionalTrailer() throws Exception { } return encodeText(additionalTrailer); } - + public void setAdditionalTrailer(String value) throws Exception { checkEnabled(); if (!getCapAdditionalTrailer()) { @@ -1839,7 +1837,7 @@ public void setAdditionalTrailer(String value) throws Exception { } additionalTrailer = decodeText(value); } - + public String getChangeDue() throws Exception { if (!getCapChangeDue()) { throw new JposException(JPOS_E_ILLEGAL, @@ -1847,7 +1845,7 @@ public String getChangeDue() throws Exception { } return encodeText(changeDue); } - + public void setChangeDue(String value) throws Exception { if (!getCapChangeDue()) { throw new JposException(JPOS_E_ILLEGAL, @@ -1855,12 +1853,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()) { @@ -1871,18 +1869,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: @@ -1891,23 +1889,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, @@ -1920,16 +1918,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; @@ -1938,32 +1936,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) { @@ -1973,13 +1971,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"); @@ -1992,7 +1990,7 @@ private void writeFieldsFile() { try { if (params.fieldsFilesPath.length() != 0) { writeFieldsFileFromPath(); - + } else if (params.fieldsFileName.length() != 0) { writeFieldsFileFromFileName(); } @@ -2000,7 +1998,7 @@ private void writeFieldsFile() { logger.error(e); } } - + private void writeFieldsFileFromPath() throws Exception { logger.debug("writeFieldsFileFromPath"); File dir = new File(params.fieldsFilesPath); @@ -2021,7 +2019,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 @@ -2035,11 +2033,11 @@ private void writeFieldsFileFromPath() throws Exception { break; } } - + } } } - + private void writeFieldsFileFromFileName() throws Exception { File file = new File(SysUtils.getFilesPath() + params.fieldsFileName); if (!file.exists()) { @@ -2049,18 +2047,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(); @@ -2076,12 +2074,12 @@ private void writePaymentNames() throws Exception { } } } - + private void writeTables() throws Exception { writeFieldsFile(); writePaymentNames(); } - + public void readTables() { try { // load tax names @@ -2096,19 +2094,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(); } @@ -2118,33 +2116,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; @@ -2166,7 +2164,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); @@ -2197,7 +2195,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) { @@ -2206,11 +2204,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); @@ -2219,7 +2217,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: " @@ -2233,7 +2231,7 @@ 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()); @@ -2241,11 +2239,11 @@ public void open(String logicalName, EventCallbacks cb) throws Exception { 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)); @@ -2253,81 +2251,81 @@ 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()); - + + receipt = new NullReceipt(printer); + state = JPOS_S_IDLE; setFreezeEvents(false); } - + private class PortEventsNotifier implements PrinterPort.IPortEvents { - + public PortEventsNotifier() { } - + public void onConnect() { setPowerState(JPOS_PS_ONLINE); } - + 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); } } - + public void release() throws Exception { setDeviceEnabled(false); claimed = false; @@ -2340,17 +2338,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(); @@ -2364,13 +2362,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); @@ -2383,27 +2381,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); @@ -2415,31 +2413,31 @@ public void endRemoval() throws Exception { public void beginNonFiscal() throws Exception { checkEnabled(); checkPrinterState(FPTR_PS_MONITOR); - receipt = new NonfiscalReceipt(getReceiptContext()); + receipt = new NonfiscalReceipt(printer); 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) { @@ -2450,23 +2448,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; @@ -2478,19 +2476,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; @@ -2502,7 +2500,7 @@ public void printEndNonFiscal() { logger.error(e.toString()); } } - + public void printDocStart() throws Exception { synchronized (printer) { isInReceiptTrailer = true; @@ -2510,10 +2508,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(); @@ -2531,7 +2529,7 @@ public void printNonFiscalDoc(String text) throws Exception { getPrinter().clearReceiptCommands(); } } - + public void endNonFiscal() throws Exception { synchronized (printer) { checkEnabled(); @@ -2549,7 +2547,7 @@ public void beginTraining() throws Exception { checkPrinterState(FPTR_PS_MONITOR); trainingModeActive = true; } - + public void endTraining() throws Exception { checkEnabled(); if (trainingModeActive) { @@ -2563,7 +2561,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 @@ -2583,7 +2581,7 @@ public void clearOutput() throws Exception { } setState(JPOS_S_IDLE); } - + private String getDataFirmware(int[] optArgs) throws Exception { LongPrinterStatus status = readLongStatus(); String result = ""; @@ -2607,7 +2605,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()); @@ -2619,7 +2617,7 @@ private String getDataFirmware(int[] optArgs) throws Exception { } return result; } - + public String getTenderData(int optArg) throws Exception { switch (optArg) { // Cash @@ -2664,14 +2662,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. @@ -2719,14 +2717,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 @@ -2754,19 +2752,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: @@ -2823,15 +2821,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. @@ -2841,7 +2839,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(); @@ -2854,7 +2852,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; @@ -2917,51 +2915,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) @@ -2970,20 +2968,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(); @@ -2992,7 +2990,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(); @@ -3009,7 +3007,7 @@ public String readGrandTotal(int[] optArgs) throws Exception { } return result; } - + public long getDailyTotal(int mode) throws Exception { long amount = 0; switch (mode) { @@ -3023,7 +3021,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); @@ -3032,34 +3030,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 = ""; @@ -3068,7 +3066,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: @@ -3088,14 +3086,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) @@ -3104,7 +3102,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(); @@ -3121,7 +3119,7 @@ public void getTotalizer(int vatID, int optArgs, String[] data) * } */ } - + private boolean isSalesReceipt() { switch (fiscalReceiptType) { case FPTR_RT_SALES: @@ -3134,12 +3132,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(); @@ -3160,13 +3158,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()) { @@ -3196,14 +3194,14 @@ public void beginFiscalReceipt(boolean printHeader) throws Exception { receipt.printRecMessage(line.getStation(), line.getFont(), line.getLine()); } } - + } catch (Exception e) { - receipt = new NullReceipt(getReceiptContext()); + receipt = new NullReceipt(printer); setPrinterState(FPTR_PS_MONITOR); throw e; } } - + public void cancelReceipt2() { try { getPrinter().waitForPrinting(); @@ -3212,20 +3210,31 @@ public void cancelReceipt2() { logger.error(e); } } - + public void endFiscalReceipt(boolean printHeader) throws Exception { logger.debug("endFiscalReceipt"); - + + if (receipt.isCancelled()) { + fiscalDay.cancelFiscalRec(); + } else { + fiscalDay.closeFiscalRec(); + } + synchronized (printer) { checkEnabled(); checkPrinterState(FPTR_PS_FISCAL_RECEIPT_ENDING); if (receipt instanceof FSSalesReceipt) { - if (textGenerator != null) { - receipt.accept(textGenerator); + if (textGenerator != null) + { + try{ + receipt.accept(textGenerator); + } catch (Exception e) { + logger.error("Failed duplicate receipt", e); + } setDocumentLines(textGenerator.getLines()); } } - + try { receipt.endFiscalReceipt(printHeader); } catch (DeviceException e) { @@ -3234,9 +3243,9 @@ public void endFiscalReceipt(boolean printHeader) throws Exception { } throw e; } - + getPrinter().stopSaveCommands(); - + try { Time.delay(getParams().recCloseSleepTime); if (!receipt.getCapAutoCut()) { @@ -3250,21 +3259,20 @@ public void endFiscalReceipt(boolean printHeader) throws Exception { startFDOService(); setPrinterState(FPTR_PS_MONITOR); filter.endFiscalReceipt(); - + setDocumentLines(filter.getLines()); - if ((textGenerator != null)&&(receipt instanceof FSSalesReceipt)) - { + 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); @@ -3283,7 +3291,7 @@ public void printDuplicateReceipt() throws Exception { 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)); @@ -3309,17 +3317,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 { @@ -3328,25 +3336,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) { @@ -3360,11 +3368,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, @@ -3372,22 +3380,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); @@ -3397,7 +3405,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(); @@ -3409,68 +3417,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); @@ -3483,24 +3491,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); @@ -3510,98 +3518,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(); @@ -3614,7 +3622,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) @@ -3626,26 +3634,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); } @@ -3660,10 +3668,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) { @@ -3671,9 +3679,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 { @@ -3681,7 +3689,7 @@ public void printReport(int reportType, String startNum, String endNum) } printEndFiscal(); break; - + case FPTR_RT_DATE: PrinterDate date1; PrinterDate date2; @@ -3691,7 +3699,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 { @@ -3699,14 +3707,14 @@ 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(); @@ -3717,22 +3725,22 @@ public void printXReport() throws Exception { 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(); @@ -3751,7 +3759,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 { @@ -3761,16 +3769,16 @@ private void sendDocumentsZReport() { } } } - + private void printCalcReport() { if (!params.calcReportEnabled) { return; } - + if (!printer.getCapFiscalStorage()) { return; } - + try { printer.waitForPrinting(); FSReadCommStatus status = printer.fsReadCommStatus(); @@ -3782,7 +3790,7 @@ private void printCalcReport() { logger.error(e); } } - + private void saveZReportXml() throws Exception { if (params.xmlZReportEnabled || params.csvZReportEnabled) { try { @@ -3809,7 +3817,7 @@ private void saveZReportXml() throws Exception { } } } - + private String getXmlZReportFileName(int dayNumber) throws Exception { String fileName = params.xmlZReportFileName; if (params.ZReportDayNumber) { @@ -3820,7 +3828,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) { @@ -3831,7 +3839,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++) { @@ -3839,7 +3847,7 @@ private String getDayNumberText(int dayNumber) { } return result; } - + public void resetPrinter() throws Exception { params.cancelIO = false; checkEnabled(); @@ -3849,21 +3857,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); @@ -3871,7 +3879,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)); @@ -3891,20 +3899,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) { @@ -3920,7 +3928,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())) { @@ -3932,12 +3940,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); @@ -3969,117 +3977,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); @@ -4087,28 +4095,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); @@ -4116,58 +4124,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()) { @@ -4184,9 +4192,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) { @@ -4209,16 +4217,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); @@ -4227,18 +4235,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); @@ -4252,11 +4260,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)) { @@ -4265,7 +4273,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); @@ -4276,7 +4284,7 @@ private int stringParamToInt(String s, String paramName) throws Exception { + paramName); } } - + private String checkHealthExternal() throws Exception { PrinterStatus status = getPrinter().waitForPrinting(); if (!status.getPrinterMode().isTestMode()) { @@ -4287,14 +4295,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(); @@ -4305,7 +4313,7 @@ public void cancelReceipt() throws Exception { } } } - + public int getPayType(String key) throws Exception { // logger.debug("getPayType(" + String.valueOf(userPayType) + ")"); @@ -4316,7 +4324,7 @@ public int getPayType(String key) throws Exception { return payType.getValue(); } } - + public FontNumber getFont(boolean doubleWidth) { if (doubleWidth) { return doubleWidthFont; @@ -4324,7 +4332,7 @@ public FontNumber getFont(boolean doubleWidth) { return getFont(); } } - + public String encodeText(String text) { String result; if (getStringEncoding().length() == 0) { @@ -4340,7 +4348,7 @@ public String encodeText(String text) { } return result; } - + public String decodeText(String text) { String result; if (getStringEncoding().length() == 0) { @@ -4354,17 +4362,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; @@ -4372,11 +4380,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++) { @@ -4388,45 +4396,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) { @@ -4440,7 +4448,7 @@ public void checkDeviceStatus() throws Exception { logger.error("checkDeviceStatus", e); } } - + public void deviceProc() { logger.debug("Poll thread started"); try { @@ -4455,33 +4463,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 { @@ -4489,32 +4497,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 { @@ -4522,16 +4530,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(); @@ -4542,7 +4550,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(); @@ -4553,17 +4561,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); @@ -4577,10 +4585,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(); @@ -4591,15 +4599,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(); @@ -4608,7 +4616,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); @@ -4622,124 +4630,116 @@ 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()); - + return new CashInReceipt(printer); + case FPTR_RT_CASH_OUT: - return new CashOutReceipt(getReceiptContext()); - + return new CashOutReceipt(printer); + 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()) { - result = new FSSalesReceipt(getReceiptContext(), receiptType); + result = new FSSalesReceipt(printer, receiptType); } else if (params.salesReceiptType == SmFptrConst.SMFPTR_RECEIPT_NORMAL) { - result = new SalesReceipt(getReceiptContext(), receiptType); + result = new SalesReceipt(printer, receiptType); } else { if (!isTablesRead) { readTables(); isTablesRead = true; } - result = new GlobusSalesReceipt(getReceiptContext(), PrinterConst.SMFP_RECTYPE_SALE); + result = new GlobusSalesReceipt(printer, PrinterConst.SMFP_RECTYPE_SALE); } return result; } - - private ReceiptContext getReceiptContext() { - if (receiptContext == null) { - receiptContext = new ReceiptContext(printer, params, - fiscalDay, printerState, this); - } - return receiptContext; - } - + public FptrParameters getParams() { return params; } - + 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)) { @@ -4750,15 +4750,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) @@ -4769,11 +4769,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); @@ -4791,37 +4791,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(); @@ -4829,55 +4829,55 @@ 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 addItemCode(ItemCode itemCode) throws Exception { receipt.addItemCode(itemCode); } - + 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()); @@ -4886,8 +4886,7 @@ private void saveLastDocument() { } PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file, true))); try { - for (int i = 0; i < documentLines.size(); i++) - { + for (int i = 0; i < documentLines.size(); i++) { String line = documentLines.get(i); writer.println(line); } @@ -4899,7 +4898,7 @@ private void saveLastDocument() { logger.error("Failed to save last document, ", e); } } - + private void readLastDocument() { try { documentLines.clear(); @@ -4908,7 +4907,7 @@ private void readLastDocument() { logger.debug("Last document not found"); return; } - + BufferedReader reader = new BufferedReader(new FileReader(file)); try { String line; @@ -4922,12 +4921,11 @@ private void readLastDocument() { logger.error("Failed to read last document, ", e); } } - + /* - private final PrinterReceipt printerReceipt = new PrinterReceipt(); - public PrinterReceipt getReceipt() { - return printerReceipt; - } - */ - + private final PrinterReceipt printerReceipt = new PrinterReceipt(); + public PrinterReceipt getReceipt() { + return printerReceipt; + } + */ } diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/FptrParameters.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/FptrParameters.java index 1ed49c23..74498f72 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/FptrParameters.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/FptrParameters.java @@ -138,11 +138,11 @@ public class FptrParameters { public int FSTagsPlacement = 0; public boolean textReportEmptyLinesEnabled = true; public boolean ReceiptTemplateEnabled = false; - public String ItemTableHeader = null; - public String ItemTableTrailer = null; - public String ItemRowFormat = null; - public String discountFormat = null; - public String chargeFormat = null; + public String ItemTableHeader = ""; + public String ItemTableTrailer = ""; + public String ItemRowFormat = "%TITLE% %QUAN% X %PRICE%"; + public String discountFormat = ""; + public String chargeFormat = ""; public boolean capJrnPresent = true; public boolean nonFiscalHeaderEnabled = false; public boolean fsHeaderEnabled = false; @@ -215,7 +215,7 @@ public class FptrParameters { public boolean processTag1256 = false; - public FptrParameters() throws Exception { + public FptrParameters() { font = new FontNumber(PrinterConst.FONT_NUMBER_NORMAL); subtotalFont = new FontNumber(PrinterConst.FONT_NUMBER_NORMAL); discountFont = new FontNumber(PrinterConst.FONT_NUMBER_NORMAL); 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 f746fd81..5ff963a0 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashInReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashInReceipt.java @@ -8,6 +8,7 @@ * * @author V.Kravtsov */ +import com.shtrih.fiscalprinter.SMFiscalPrinter; import com.shtrih.util.CompositeLogger; public class CashInReceipt extends CustomReceipt implements FiscalReceipt { @@ -16,8 +17,8 @@ public class CashInReceipt extends CustomReceipt implements FiscalReceipt { private long payment = 0; // paied total private static CompositeLogger logger = CompositeLogger.getLogger(CashInReceipt.class); - public CashInReceipt(ReceiptContext context) { - super(context); + public CashInReceipt(SMFiscalPrinter printer) { + super(printer); } public void printRecCash(long amount) throws Exception { @@ -47,9 +48,19 @@ public boolean getCapAutoCut() throws Exception { } public long getSubtotal() throws Exception { - return 0; + return total; + } + + public long getPayment() { + return payment; + } + + public long getChange(){ + return payment - total; } public void accept(ReceiptVisitor visitor) throws Exception{ + visitor.visitCashInReceipt(this); } + } 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 1ecb712d..95086497 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashOutReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CashOutReceipt.java @@ -8,6 +8,7 @@ * * @author V.Kravtsov */ +import com.shtrih.fiscalprinter.SMFiscalPrinter; import com.shtrih.util.CompositeLogger; public class CashOutReceipt extends CustomReceipt implements FiscalReceipt { @@ -16,8 +17,8 @@ public class CashOutReceipt extends CustomReceipt implements FiscalReceipt { private long payment = 0; // paied total private static CompositeLogger logger = CompositeLogger.getLogger(CashInReceipt.class); - public CashOutReceipt(ReceiptContext context) { - super(context); + public CashOutReceipt(SMFiscalPrinter printer) { + super(printer); } public void printRecCash(long amount) throws Exception { @@ -47,9 +48,14 @@ public boolean getCapAutoCut() throws Exception { } public long getSubtotal() throws Exception { - return 0; + return total; + } + + public long getChange() { + return payment - total; } public void accept(ReceiptVisitor visitor) throws Exception{ + visitor.visitCashOutReceipt(this); } } 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 709325f8..f555d795 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CustomReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/CustomReceipt.java @@ -37,33 +37,21 @@ public abstract class CustomReceipt implements FiscalReceipt { protected boolean cancelled = false; - private final ReceiptContext context; + private final SMFiscalPrinter printer; private static CompositeLogger logger = CompositeLogger.getLogger(CustomReceipt.class); - public CustomReceipt(ReceiptContext context) { - this.context = context; + public CustomReceipt(SMFiscalPrinter printer) { + this.printer = printer; } public FptrParameters getParams() { - return context.getParams(); + return printer.getParams(); } public SMFiscalPrinter getPrinter() { - return context.getPrinter(); + return printer; } - public FiscalDay getFiscalDay() { - return context.getFiscalDay(); - } - - public ReceiptContext getContext() { - return context; - } - - public FiscalPrinterImpl getService() { - return context.getService(); - } - public PrinterModel getModel() throws Exception { return getPrinter().getModel(); } @@ -83,7 +71,7 @@ public void checkTotal(long recTotal, long appTotal) throws Exception { return; } - if (!getService().getCheckTotal()) { + if (!getParams().checkTotal) { return; } @@ -92,7 +80,6 @@ public void checkTotal(long recTotal, long appTotal) throws Exception { logger.debug("Receipt total: " + recTotal); logger.debug("Application total: " + appTotal); - setPrinterState(FPTR_PS_MONITOR); throw new JposException(JPOS_E_EXTENDED, JPOS_EFPTR_BAD_ITEM_AMOUNT); } @@ -115,11 +102,6 @@ public long getSubtotal() throws Exception { return total; } - - public void setPrinterState(int state) { - context.setPrinterState(state); - } - public boolean getCapAutoCut() throws Exception { return false; @@ -137,6 +119,10 @@ public boolean isCancelled() { return cancelled; } + public boolean isEnding() throws Exception{ + return isPayed() || isCancelled(); + } + public void notSupported() throws Exception { throw new JposException(JposConst.JPOS_E_ILLEGAL, "Receipt method is not supported"); @@ -278,7 +264,7 @@ public void accept(ReceiptVisitor visitor) throws Exception{ public void checkZeroReceipt() throws Exception { - if (!context.getParams().getZeroReceiptEnabled()) { + if (!getParams().getZeroReceiptEnabled()) { if (getSubtotal() == 0) { throw new JposException(JposConst.JPOS_E_ILLEGAL, "Zero receipts sre disabled"); @@ -365,4 +351,5 @@ private String formatStrings(String line1, String line2) throws Exception { public void printStrings(String line1, String line2) throws Exception { printText(formatStrings(line1, line2)); } + } 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 6bd6eb57..0b156aa7 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/FSSalesReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/FSSalesReceipt.java @@ -59,11 +59,12 @@ public class FSSalesReceipt extends CustomReceipt implements FiscalReceipt { private List itemCodes = new Vector(); private Vector itemTags = new Vector(); private boolean itemDiscountsApplied = false; + public static final int maximumRounding = 99; - public FSSalesReceipt(ReceiptContext context, int receiptType) throws Exception { - super(context); + public FSSalesReceipt(SMFiscalPrinter printer, int receiptType) throws Exception { + super(printer); this.receiptType = receiptType; - receiptTemplate = new ReceiptTemplate(context); + receiptTemplate = new ReceiptTemplate(printer); } public boolean isSaleReceipt() { @@ -134,6 +135,14 @@ public void printRecItem(String description, long price, double quantity, vatInfo, description, unitName); } + public boolean isRounded(){ + return discounts.getTotal() <= maximumRounding; + } + + public long getDiscountsTotal(){ + return discounts.getTotal(); + } + // pack discounts public void addItemsDiscounts() throws Exception { @@ -155,7 +164,7 @@ public void addItemsDiscounts() throws Exception { saleItem.addDiscount(discount); return; } - if (discountTotal < 100) { + if (discountTotal <= maximumRounding) { return; } @@ -515,7 +524,6 @@ public void endFiscalReceipt(boolean printHeader) throws Exception { } catch (Exception e) { logger.error("Cancel receipt", e); } - getFiscalDay().cancelFiscalRec(); clearReceipt(); } else { FSCloseReceipt closeReceipt = new FSCloseReceipt(); @@ -556,7 +564,6 @@ public void endFiscalReceipt(boolean printHeader) throws Exception { rc = getDevice().closeReceipt(command); } getDevice().check(rc); - getFiscalDay().closeFiscalRec(); } } discounts.clear(); @@ -812,7 +819,7 @@ public void printRecRefund(String description, long amount, int vatInfo) private void addTextItem(String text, FontNumber font) throws Exception { FSTextReceiptItem item = new FSTextReceiptItem(text, getPreLine(), getPostLine(), font); - if (getContext().getPrinterState().isEnding()) { + if (isEnding()) { endingItems.add(item); } else { items.add(item); @@ -1422,7 +1429,7 @@ public String formatLines(String line1, String line2) throws Exception { } public void printBarcode(PrinterBarcode barcode) throws Exception { - if (getContext().getPrinterState().isEnding()) { + if (isEnding()) { endingItems.add(barcode); } else { items.add(barcode); diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/GlobusSalesReceipt.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/GlobusSalesReceipt.java index 51a50308..c887c15e 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/GlobusSalesReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/GlobusSalesReceipt.java @@ -70,8 +70,8 @@ public int getStation() { private boolean endSeparatorPrinted = false; private final PrinterReceipt receipt = new PrinterReceipt(); - public GlobusSalesReceipt(ReceiptContext context, int receiptType) { - super(context); + public GlobusSalesReceipt(SMFiscalPrinter printer, int receiptType) { + super(printer); this.receiptType = receiptType; } @@ -214,7 +214,6 @@ public void endFiscalReceipt(boolean printHeader) throws Exception { if (status.getPrinterMode().isReceiptOpened()) { if (getReceipt().isCancelled()) { getPrinter().cancelReceipt(); - getFiscalDay().cancelFiscalRec(); } else { checkZeroReceipt(); printEndSeparator(); diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/NonfiscalReceipt.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/NonfiscalReceipt.java index 383f3db1..ad8c6f10 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/NonfiscalReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/NonfiscalReceipt.java @@ -4,13 +4,15 @@ */ package com.shtrih.jpos.fiscalprinter.receipt; +import com.shtrih.fiscalprinter.SMFiscalPrinter; + /** * @author V.Kravtsov */ public class NonfiscalReceipt extends CustomReceipt implements FiscalReceipt { - public NonfiscalReceipt(ReceiptContext context) { - super(context); + public NonfiscalReceipt(SMFiscalPrinter printer) { + super(printer); } } 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 767d5aa5..35a76fbc 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/NullReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/NullReceipt.java @@ -34,12 +34,8 @@ public Vector getMessages() { return messages; } - public NullReceipt(ReceiptContext context) { - super(context); - } - - public FptrParameters getParams() { - return getContext().getParams(); + public NullReceipt(SMFiscalPrinter printer) { + super(printer); } public boolean getCapAutoCut() throws Exception { @@ -180,7 +176,7 @@ public void printRecMessage(int station, FontNumber font, String message) } public void printNormal(int station, String data) throws Exception { - if (getContext() != null) { + if (getPrinter() != null) { getPrinter().printText(getStation(station), data, getParams().font); } } diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptContext.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptContext.java deleted file mode 100644 index 5445143d..00000000 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptContext.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.shtrih.jpos.fiscalprinter.receipt; - -/** - * - * @author V.Kravtsov - */ -import com.shtrih.fiscalprinter.SMFiscalPrinter; -import com.shtrih.fiscalprinter.receipt.PrinterReceipt; -import com.shtrih.jpos.fiscalprinter.FiscalDay; -import com.shtrih.jpos.fiscalprinter.FiscalPrinterState; -import com.shtrih.jpos.fiscalprinter.FptrParameters; -import com.shtrih.jpos.fiscalprinter.FiscalPrinterImpl; - -public class ReceiptContext { - - private final SMFiscalPrinter printer; - private final FptrParameters params; - private final FiscalDay fiscalDay; - private final FiscalPrinterState printerState; - private final FiscalPrinterImpl service; - - public ReceiptContext( - SMFiscalPrinter printer, - FptrParameters params, - FiscalDay fiscalDay, - FiscalPrinterState printerState, - FiscalPrinterImpl service) - { - this.printer = printer; - this.params = params; - this.fiscalDay = fiscalDay; - this.printerState = printerState; - this.service = service; - } - - public FiscalPrinterImpl getService(){ - return service; - } - - public FiscalPrinterState getPrinterState() { - return printerState; - } - - public void setPrinterState(int printerState) { - this.printerState.setValue(printerState); - } - - public SMFiscalPrinter getPrinter() { - return printer; - } - - public FptrParameters getParams() { - return params; - } - - public FiscalDay getFiscalDay() { - return fiscalDay; - } - -} diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptTemplate.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptTemplate.java index fae8a38e..016ce67f 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptTemplate.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptTemplate.java @@ -6,6 +6,7 @@ package com.shtrih.jpos.fiscalprinter.receipt; import com.shtrih.fiscalprinter.FontNumber; +import com.shtrih.fiscalprinter.SMFiscalPrinter; import com.shtrih.fiscalprinter.TLVItem; import com.shtrih.fiscalprinter.TLVItems; import com.shtrih.fiscalprinter.TLVReader; @@ -29,7 +30,7 @@ */ public class ReceiptTemplate { - private final ReceiptContext context; + private final SMFiscalPrinter printer; private String[] headerLines = new String[0]; private String[] trailerLines = new String[0]; private TemplateLine[] itemTemplate = null; @@ -37,13 +38,13 @@ public class ReceiptTemplate { private TemplateLine[] chargeTemplate = null; private long m_position_count = 0; - public ReceiptTemplate(ReceiptContext context) throws Exception { - this.context = context; + public ReceiptTemplate(SMFiscalPrinter printer) throws Exception { + this.printer = printer; parseFormatLines(); } public FptrParameters getParams() { - return context.getParams(); + return printer.getParams(); } public boolean hasPreLine() { @@ -346,11 +347,11 @@ private String getTagText(Field f, FSSaleReceiptItem item) throws Exception { static String taxLetters = "АБВГДЕ"; private String getTaxName(int tax) throws Exception { - return context.getPrinter().getTaxName(tax); + return printer.getTaxName(tax); } private String getTaxAmount(FSSaleReceiptItem item) throws Exception { - long taxAmount = context.getPrinter().getTaxAmount(item.getTax1(), item.getTotal()); + long taxAmount = printer.getTaxAmount(item.getTax1(), item.getTotal()); return StringUtils.amountToString(taxAmount); } @@ -398,8 +399,7 @@ private String[] getDiscountLines2(AmountItem item) throws Exception { private String formatStrings(FontNumber font, String line1, String line2) throws Exception { int len; StringBuilder sb = new StringBuilder(); - len = context.getService().getPrinter().getMessageLength(font) - - line2.length(); + len = printer.getMessageLength(font) - line2.length(); for (int i = 0; i < len; i++) { if (i < line1.length()) { diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptVisitor.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptVisitor.java index 597e5490..9adb2d42 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptVisitor.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/ReceiptVisitor.java @@ -11,6 +11,8 @@ */ public interface ReceiptVisitor { - public void visitSalesReceipt(Object element); - public void visitCustomReceipt(Object element); + public void visitSalesReceipt(Object element) throws Exception; + public void visitCashInReceipt(Object element) throws Exception; + public void visitCashOutReceipt(Object element) throws Exception; + public void visitCustomReceipt(Object element) throws Exception; } diff --git a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/SalesReceipt.java b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/SalesReceipt.java index 92a2db54..1dc9b313 100644 --- a/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/SalesReceipt.java +++ b/Source/Core/src/com/shtrih/jpos/fiscalprinter/receipt/SalesReceipt.java @@ -8,6 +8,7 @@ * * @author V.Kravtsov */ +import com.shtrih.fiscalprinter.SMFiscalPrinter; import jpos.JposConst; import jpos.JposException; import jpos.FiscalPrinterConst; @@ -46,8 +47,8 @@ public class SalesReceipt extends CustomReceipt implements FiscalReceipt { private final PrinterReceipt receipt = new PrinterReceipt(); private static CompositeLogger logger = CompositeLogger.getLogger(SalesReceipt.class); - public SalesReceipt(ReceiptContext context, int receiptType) { - super(context); + public SalesReceipt(SMFiscalPrinter printer, int receiptType) { + super(printer); this.receiptType = receiptType; } @@ -142,7 +143,6 @@ public void endFiscalReceipt(boolean printHeader) throws Exception { if (status.getPrinterMode().isReceiptOpened()) { if (getReceipt().isCancelled()) { getPrinter().cancelReceipt(); - getFiscalDay().cancelFiscalRec(); } else { checkZeroReceipt(); long[] sum = getReceipt().getPayments(); @@ -158,7 +158,6 @@ public void endFiscalReceipt(boolean printHeader) throws Exception { closeParams.setDiscount(0); closeParams.setText(getParams().closeReceiptText); getPrinter().closeReceipt(closeParams); - getFiscalDay().closeFiscalRec(); // Print may not respond for some time Time.delay(getParams().recCloseSleepTime); } diff --git a/Source/FiscalPrinterService/src/com/shtrih/util/ServiceVersion.java b/Source/FiscalPrinterService/src/com/shtrih/util/ServiceVersion.java index a7ddc58f..e98065b2 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 = "699"; + public static final String VERSION = "699-1-gdc1a9a7"; } \ No newline at end of file diff --git a/Source/FiscalPrinterService/test/com/shtrih/fiscalprinter/command/TextGeneratorTest.java b/Source/FiscalPrinterService/test/com/shtrih/fiscalprinter/command/TextGeneratorTest.java index cb88c4e5..8545a911 100644 --- a/Source/FiscalPrinterService/test/com/shtrih/fiscalprinter/command/TextGeneratorTest.java +++ b/Source/FiscalPrinterService/test/com/shtrih/fiscalprinter/command/TextGeneratorTest.java @@ -7,13 +7,21 @@ import java.util.List; import org.junit.Test; +import org.junit.Before; import static org.junit.Assert.*; import com.shtrih.fiscalprinter.SMFiscalPrinter; import com.shtrih.fiscalprinter.SMFiscalPrinterNull; +import com.shtrih.jpos.fiscalprinter.FptrParameters; +import com.shtrih.jpos.fiscalprinter.SmFptrConst; import com.shtrih.jpos.fiscalprinter.receipt.FSTLVItem; import com.shtrih.jpos.fiscalprinter.receipt.FSSalesReceipt; -import com.shtrih.jpos.fiscalprinter.receipt.ReceiptContext; +import com.shtrih.fiscalprinter.table.PrinterField; +import com.shtrih.fiscalprinter.table.PrinterFields; +import com.shtrih.fiscalprinter.table.PrinterTable; +import com.shtrih.fiscalprinter.table.PrinterTables; +import com.shtrih.jpos.fiscalprinter.receipt.CashInReceipt; +import com.shtrih.jpos.fiscalprinter.receipt.CashOutReceipt; /** @@ -22,22 +30,142 @@ */ public class TextGeneratorTest { + private SMFiscalPrinterNull printer; + public TextGeneratorTest() { } + + @Before + public void setUp() + { + PrinterTable table; + PrinterField field; + FieldInfo fieldInfo; + + FptrParameters params = new FptrParameters(); + printer = new SMFiscalPrinterNull(null, null, params); + + printer.getLongStatus().setSerialNumber(12345); + printer.getLongStatus().setDocumentNumber(1233); + printer.getLongStatus().setFiscalID(9876); + // + table = new PrinterTable(PrinterConst.SMFP_TABLE_PAYTYPE, "Наименование типов оплаты", 16, 1); + fieldInfo = new FieldInfo(PrinterConst.SMFP_TABLE_PAYTYPE, 1, 64, 1, 0, 99999999, "Запрограммированные типы оплаты"); + table.getFields().add(new PrinterField(fieldInfo, 1, "НАЛИЧНЫМИ")); + table.getFields().add(new PrinterField(fieldInfo, 2, "CREDIT")); + table.getFields().add(new PrinterField(fieldInfo, 3, "КАРТА")); + table.getFields().add(new PrinterField(fieldInfo, 4, "СКИДКА")); + + table = new PrinterTable(PrinterConst.SMFP_TABLE_CASHIER, "Наименования операторов", 10, 2); + fieldInfo = new FieldInfo(2, 1, 4, 0, 0, 99999999, "Пароли кассиров"); + for (int i=1;i<31;i++) + { + field = new PrinterField(fieldInfo, i); + field.setValue(String.valueOf(i)); + table.getFields().add(field); + } + fieldInfo = new FieldInfo(2, 2, 64, 1, 0, 99999999, "Должности и фамилии кассиров"); + for (int i=1;i<31;i++) + { + field = new PrinterField(fieldInfo, i); + field.setValue("Кассир " + i); + table.getFields().add(field); + } + printer.tables.add(table); + } + + /** * Test of visitSalesReceipt method, of class TextGenerator. */ @Test public void testVisitSalesReceipt() { System.out.println("visitSalesReceipt"); - /* - ReceiptContext context = new ReceiptContext(); - FSSalesReceipt receipt = new FSSalesReceipt(context, PrinterConst.SMFP_RECTYPE_SALE); - SMFiscalPrinter printer = new SMFiscalPrinterNull(null, null, null); - TextGenerator instance = new TextGenerator(printer); - instance.visitSalesReceipt(receipt); - */ + try{ + FSSalesReceipt receipt = new FSSalesReceipt(printer, PrinterConst.SMFP_RECTYPE_SALE); + TextGenerator instance = new TextGenerator(printer); + + receipt.beginFiscalReceipt(true); + receipt.printRecItem("Приём платежа", 12300, 0, 0, 0, ""); + receipt.printRecItem("Размер вознаграждения", 123, 0, 3, 0, ""); + receipt.printRecTotal(12423, 12423, 0, "0"); + receipt.endFiscalReceipt(false); + + assertEquals("size != 0", 0, instance.getLines().size()); + instance.visitSalesReceipt(receipt); + assertEquals(10, instance.getLines().size()); + assertEquals("ККМ 12345 ИНН 9876 №1234", instance.getLines().get(0)); + assertEquals("01.02.2003 01:02 Кассир 1", instance.getLines().get(1)); + assertEquals("Приём платежа", instance.getLines().get(2)); + assertEquals(" 1.000 X 123.00", instance.getLines().get(3)); + assertEquals("01 =123.00_Г", instance.getLines().get(4)); + assertEquals("Размер вознаграждения", instance.getLines().get(5)); + assertEquals(" 1.000 X 1.23", instance.getLines().get(6)); + assertEquals("01 =1.23_В", instance.getLines().get(7)); + assertEquals("ИТОГ =124.23", instance.getLines().get(8)); + assertEquals(" =124.23", instance.getLines().get(9)); + + } + catch(Exception e){ + fail(e.getMessage()); + } } - + + /** + * Test of visitCashInReceipt method, of class TextGenerator. + */ + @Test + public void testVisitCashInReceipt() { + System.out.println("visitCashInReceipt"); + try{ + CashInReceipt receipt = new CashInReceipt(printer); + TextGenerator instance = new TextGenerator(printer); + + receipt.printRecCash(12300); + receipt.printRecTotal(12423, 12423, 0, "0"); + receipt.endFiscalReceipt(false); + + assertEquals("size != 0", 0, instance.getLines().size()); + instance.visitCashInReceipt(receipt); + assertEquals(4, instance.getLines().size()); + assertEquals("ККМ 12345 ИНН 9876 №1234", instance.getLines().get(0)); + assertEquals("01.02.2003 01:02 Кассир 1", instance.getLines().get(1)); + assertEquals("ВНЕСЕНИЕ 123.00", instance.getLines().get(2)); + assertEquals("СДАЧА =1.23", instance.getLines().get(3)); + + } + catch(Exception e){ + fail(e.getMessage()); + } + } + + /** + * Test of visitCashInReceipt method, of class TextGenerator. + */ + @Test + public void testVisitCashOutReceipt() { + System.out.println("visitCashOutReceipt"); + try{ + CashOutReceipt receipt = new CashOutReceipt(printer); + TextGenerator instance = new TextGenerator(printer); + + receipt.printRecCash(12300); + receipt.printRecTotal(12423, 12423, 0, "0"); + receipt.endFiscalReceipt(false); + + assertEquals("size != 0", 0, instance.getLines().size()); + instance.visitCashOutReceipt(receipt); + assertEquals(4, instance.getLines().size()); + assertEquals("ККМ 12345 ИНН 9876 №1234", instance.getLines().get(0)); + assertEquals("01.02.2003 01:02 Кассир 1", instance.getLines().get(1)); + assertEquals("ВЫПЛАТА 123.00", instance.getLines().get(2)); + assertEquals("СДАЧА =1.23", instance.getLines().get(3)); + + } + catch(Exception e){ + fail(e.getMessage()); + } + } + } diff --git a/Source/FiscalPrinterService/test/com/shtrih/jpos/fiscalprinter/receipt/FSSalesReceiptTest.java b/Source/FiscalPrinterService/test/com/shtrih/jpos/fiscalprinter/receipt/FSSalesReceiptTest.java index dad6a8af..b023f8a1 100644 --- a/Source/FiscalPrinterService/test/com/shtrih/jpos/fiscalprinter/receipt/FSSalesReceiptTest.java +++ b/Source/FiscalPrinterService/test/com/shtrih/jpos/fiscalprinter/receipt/FSSalesReceiptTest.java @@ -43,13 +43,7 @@ private FSSalesReceipt createReceipt() throws Exception PrinterPort port = PrinterPortFactory.createInstance(params); PrinterProtocol device = ProtocolFactory.getProtocol(params, port); SMFiscalPrinter printer = new SMFiscalPrinterNull(port, device, params); - FiscalDay fiscalDay = new FiscalDay(); - FiscalPrinterState printerState = new FiscalPrinterState(); - FiscalPrinterImpl impl = new FiscalPrinterImpl(); - ReceiptContext context = new ReceiptContext( - printer, params, fiscalDay, printerState, impl); - - return new FSSalesReceipt(context, PrinterConst.SMFP_RECTYPE_SALE); + return new FSSalesReceipt(printer, PrinterConst.SMFP_RECTYPE_SALE); } /**