From e92957b06d99cc7e628ef1da121b02bffcf2dd64 Mon Sep 17 00:00:00 2001 From: Carlos Ruiz Date: Fri, 29 Aug 2008 22:57:30 +0000 Subject: [PATCH] Synchronizing some unsync classes from zkwebui 341 to stable --- .../src/org/adempiere/webui/apps/AEnv.java | 22 +- .../org/adempiere/webui/apps/form/WMatch.java | 1914 +++++---- .../adempiere/webui/apps/form/WPayment.java | 3462 ++++++++--------- .../adempiere/webui/component/Listbox.java | 43 +- .../webui/component/ListboxFactory.java | 10 + .../adempiere/webui/editor/WNumberEditor.java | 54 +- .../adempiere/webui/editor/WSearchEditor.java | 40 + 7 files changed, 2569 insertions(+), 2976 deletions(-) diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/AEnv.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/AEnv.java index caa4f676a4..9fad755e13 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/AEnv.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/AEnv.java @@ -29,7 +29,6 @@ import java.util.Enumeration; import java.util.logging.Level; import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; import org.adempiere.webui.component.Window; import org.adempiere.webui.session.SessionManager; @@ -48,6 +47,7 @@ import org.compiere.util.DB; import org.compiere.util.Env; import org.compiere.util.Ini; import org.zkoss.web.servlet.Servlets; +import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Execution; import org.zkoss.zk.ui.Executions; @@ -715,4 +715,24 @@ public final class AEnv return false; } } + + /** + * + * @param parent + * @param child + * @return boolean + */ + public static boolean contains(Component parent, Component child) { + if (child == parent) + return true; + + Component c = child.getParent(); + while (c != null) { + if (c == parent) + return true; + c = c.getParent(); + } + + return false; + } } // AEnv diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WMatch.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WMatch.java index 33729e10ba..533d5946e1 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WMatch.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WMatch.java @@ -1,1039 +1,875 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ - -/** - * 2007, Modified by Posterita Ltd. - */ - -package org.adempiere.webui.apps.form; - -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.Date; -import java.util.Vector; -import java.util.logging.Level; - -import org.adempiere.webui.component.Button; -import org.adempiere.webui.component.Checkbox; -import org.adempiere.webui.component.Datebox; -import org.adempiere.webui.component.Grid; -import org.adempiere.webui.component.Label; -import org.adempiere.webui.component.ListItem; -import org.adempiere.webui.component.Listbox; -import org.adempiere.webui.component.Row; -import org.adempiere.webui.component.Rows; -import org.adempiere.webui.component.Textbox; -import org.adempiere.webui.component.WListbox; -import org.adempiere.webui.editor.WEditor; -import org.adempiere.webui.editor.WSearchEditor; -import org.adempiere.webui.event.ValueChangeEvent; -import org.adempiere.webui.event.ValueChangeListener; -import org.adempiere.webui.event.WTableModelEvent; -import org.adempiere.webui.event.WTableModelListener; -import org.adempiere.webui.panel.ADForm; -import org.compiere.minigrid.ColumnInfo; -import org.compiere.minigrid.IDColumn; -import org.compiere.model.MInOutLine; -import org.compiere.model.MInvoiceLine; -import org.compiere.model.MLookup; -import org.compiere.model.MLookupFactory; -import org.compiere.model.MMatchInv; -import org.compiere.model.MMatchPO; -import org.compiere.model.MOrderLine; -import org.compiere.model.MRole; -import org.compiere.model.MStorage; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.DisplayType; -import org.compiere.util.Env; -import org.compiere.util.KeyNamePair; -import org.compiere.util.Msg; -import org.zkoss.zk.ui.event.Event; -import org.zkoss.zk.ui.event.EventListener; -import org.zkoss.zk.ui.event.Events; -import org.zkoss.zul.Hbox; -import org.zkoss.zul.Separator; - -/** - * Match PO-Invoice-Receipt Custom Form : Based on VMatch - * - * @author Niraj Sohun - * @date Jul 2, 2007 - */ - -public class WMatch extends ADForm implements EventListener, ValueChangeListener, WTableModelListener -{ - private static final long serialVersionUID = 1L; - - private Grid grdParameters; - private Grid grdMatch; - private Grid grdProcess; - - private Rows rows; - private Row row; - - private Listbox lstInvoice; - private Listbox lstReceipt; - - private Button cmdSearch; - private Button cmdProcess; - - private Datebox dateFrom; - private Datebox dateTo; - - private Listbox lstMatchFrom; - private Listbox lstMatchTo; - private Listbox lstSearchMode; - - private Checkbox chkSameBP; - private Checkbox chkSameProduct; - private Checkbox chkSameQty; - - private Textbox txtToBeMatched; - private Textbox txtMatching; - private Textbox txtDifference; - - private Label lblMatchFrom; - private Label lblMatchTo; - private Label lblStatus; - - private String[] m_matchOptions = new String[] { - Msg.getElement(Env.getCtx(), "C_Invoice_ID", false), - Msg.getElement(Env.getCtx(), "M_InOut_ID", false), - Msg.getElement(Env.getCtx(), "C_Order_ID", false) }; - - private static final int MATCH_INVOICE = 0; - private static final int MATCH_SHIPMENT = 1; - private static final int MATCH_ORDER = 2; - - private String[] m_matchMode = new String[] { - Msg.translate(Env.getCtx(), "NotMatched"), - Msg.translate(Env.getCtx(), "Matched")}; - - private static final int MODE_NOTMATCHED = 0; - private static final int MODE_MATCHED = 1; - - private static final int I_BPartner = 3; - private static final int I_Line = 4; - private static final int I_Product = 5; - private static final int I_QTY = 6; - private static final int I_MATCHED = 7; - - private StringBuffer m_sql = null; - private String m_dateColumn = ""; - private String m_qtyColumn = ""; - private String m_groupBy = ""; - - private BigDecimal m_xMatched = Env.ZERO; - private BigDecimal m_xMatchedTo = Env.ZERO; - - private WEditor bPartnerSearch = null; - private WEditor productSearch = null; - - //private int m_C_BPartner_ID; - //private int productID; - - private WListbox xMatchedTable; - private WListbox xMatchedToTable; - - @SuppressWarnings("unused") - private String strMatchedTable; - - @SuppressWarnings("unused") - private String strMatchedToTable; - - private static CLogger log = CLogger.getCLogger(WMatch.class); - - public WMatch() - { - } - - protected void initForm() - { - try - { - new Thread() - { - public void run() - { - log.info("Starting ..."); - MMatchPO.consolidate(Env.getCtx()); - log.info("... Done"); - } - }.start(); - } - catch(Exception e) - { - log.log(Level.SEVERE, "", e); - } - - grdParameters = new Grid(); - grdParameters.setWidth("700px"); - - grdMatch = new Grid(); - grdMatch.setWidth("700px"); - - grdProcess = new Grid(); - grdProcess.setWidth("700px"); - - lstInvoice = new Listbox(); - lstInvoice.setWidth("700px"); - - lstReceipt = new Listbox(); - lstReceipt.setWidth("700px"); - - cmdSearch = new Button(); - cmdSearch.setImage("/images/FindX24.png"); - cmdSearch.addEventListener(Events.ON_CLICK, this); - - cmdProcess = new Button(); - cmdProcess.setImage("/images/Process24.png"); - cmdProcess.addEventListener(Events.ON_CLICK, this); - - dateFrom = new Datebox(); - dateTo = new Datebox(); - - lstMatchFrom = new Listbox(); - lstMatchFrom.setRows(0); - lstMatchFrom.setMold("select"); - lstMatchFrom.addEventListener(Events.ON_SELECT, this); - - lstMatchTo = new Listbox(); - lstMatchTo.setRows(0); - lstMatchTo.setMold("select"); - lstMatchTo.addEventListener(Events.ON_SELECT, this); - - lstSearchMode = new Listbox(); - lstSearchMode.setRows(1); - lstSearchMode.setMold("select"); - //lstSearchMode.addEventListener(Events.ON_SELECT, this); - - chkSameBP = new Checkbox(); - chkSameBP.setLabel("Same Business Partner"); - chkSameBP.setChecked(true); - chkSameBP.addEventListener(Events.ON_CHECK, this); - - chkSameProduct = new Checkbox(); - chkSameProduct.setLabel("Same Product"); - chkSameProduct.setChecked(true); - chkSameProduct.addEventListener(Events.ON_CHECK, this); - - chkSameQty = new Checkbox(); - chkSameQty.setLabel("Same Quantity"); - chkSameQty.setChecked(false); - chkSameQty.addEventListener(Events.ON_CHECK, this); - - txtToBeMatched = new Textbox(); - txtToBeMatched.setEnabled(false); - - txtMatching = new Textbox(); - txtMatching.setEnabled(false); - - txtDifference = new Textbox(); - txtDifference.setEnabled(false); - - lblMatchFrom = new Label(" "); - - lblMatchTo = new Label(" "); - - lblStatus = new Label("Invoice#"); - lblStatus.setWidth("700px"); - - xMatchedTable = new WListbox(); - xMatchedTable.setWidth("700px"); - xMatchedTable.setHeight("150px"); - xMatchedTable.getModel().addTableModelListener(this); - xMatchedTable.addEventListener(Events.ON_SELECT, this); - - xMatchedToTable = new WListbox(); - xMatchedToTable.setWidth("700px"); - xMatchedToTable.setHeight("150px"); - xMatchedToTable.getModel().addTableModelListener(this); - xMatchedToTable.addEventListener(Events.ON_SELECT, this); - - initComponents(); - } - - private void initComponents() - { - this.setWidth("710px"); - this.setHeight("100%"); - //this.setBorder("normal"); - - rows = new Rows(); - - // Row 1 - row = new Row(); - row.appendChild(new Label("Match From")); - row.appendChild(lstMatchFrom); - row.appendChild(new Label("Match To")); - row.appendChild(lstMatchTo); - rows.appendChild(row); - - // Row 2 - row = new Row(); - row.appendChild(new Label("Search Mode")); - row.appendChild(lstSearchMode); - rows.appendChild(row); - - // Row 3 - row = new Row(); - row.appendChild(new Label("Business Partner")); - showBusinessPartner(); - row.appendChild(bPartnerSearch.getComponent()); - row.appendChild(new Label("Product")); - showProduct(); - row.appendChild(productSearch.getComponent()); - rows.appendChild(row); - - // Row 4 - row = new Row(); - row.appendChild(new Label("Date From")); - row.appendChild(dateFrom); - row.appendChild(new Label("Date To")); - row.appendChild(dateTo); - rows.appendChild(row); - - grdParameters.appendChild(rows); - this.appendChild(grdParameters); - this.appendChild(new Separator()); - - Hbox hbox = new Hbox(); - hbox.appendChild(cmdSearch); - hbox.appendChild(cmdProcess); - - this.appendChild(hbox); - this.appendChild(new Separator()); - - // Listbox Invoice - - this.appendChild(new Label(" ")); - this.appendChild(lblMatchFrom); - this.appendChild(new Separator()); - this.appendChild(new Label(" ")); - this.appendChild(xMatchedTable); - this.appendChild(new Separator()); - - // Match Parameters - - rows = new Rows(); - - this.appendChild(new Label(" ")); - row = new Row(); - row.appendChild(chkSameBP); - row.appendChild(chkSameProduct); - row.appendChild(chkSameQty); - rows.appendChild(row); - - grdMatch.appendChild(rows); - this.appendChild(grdMatch); - this.appendChild(new Separator()); - - // Listbox Receipt - this.appendChild(new Label(" ")); - this.appendChild(lblMatchTo); - this.appendChild(new Separator()); - this.appendChild(new Label(" ")); - this.appendChild(xMatchedToTable); - this.appendChild(new Separator()); - - // Process Parameters - - rows = new Rows(); - - row = new Row(); - row.appendChild(new Label("To Be Matched")); - row.appendChild(txtToBeMatched); - row.appendChild(new Label("Matching")); - row.appendChild(txtMatching); - row.appendChild(new Label("Difference")); - row.appendChild(txtDifference); - rows.appendChild(row); - - grdProcess.appendChild(rows); - this.appendChild(grdProcess); - - this.appendChild(new Separator()); - this.appendChild(lblStatus); - - populateMatchFrom(); - populateMatchTo(); - populateSearchMode(); - prepareTable(); - } - - private void populateMatchFrom() - { - for (int i = 0; i < m_matchOptions.length; i++) - { - String temp = m_matchOptions[i]; - lstMatchFrom.appendItem(temp, temp); - } - - lstMatchFrom.setSelectedIndex(0); - lblMatchFrom.setValue(m_matchOptions[0]); - } - - private void populateMatchTo() - { - lstMatchTo.getChildren().clear(); - - ListItem lstIteMatchFromSelection = lstMatchFrom.getSelectedItem(); - String selection = (String)lstIteMatchFromSelection.getValue(); - - Vector vector = new Vector(2); - - if (selection.equals(m_matchOptions[MATCH_INVOICE])) - vector.add(m_matchOptions[MATCH_SHIPMENT]); - else if (selection.equals(m_matchOptions[MATCH_ORDER])) - vector.add(m_matchOptions[MATCH_SHIPMENT]); - else - { - vector.add(m_matchOptions[MATCH_INVOICE]); - vector.add(m_matchOptions[MATCH_ORDER]); - } - - for (int i = 0; i < vector.size(); i++) - { - String temp = vector.get(i).toString(); - lstMatchTo.appendItem(temp, temp); - } - - lstMatchTo.setSelectedIndex(0); - lblMatchTo.setValue(vector.get(0).toString()); - - // Reset Table - - //xMatchedTable.setRowCount(0); - //xMatchedToTable.setRowCount(0); - } - - private void populateSearchMode() - { - for (int i = 0; i < m_matchMode.length; i++) - { - lstSearchMode.appendItem(m_matchMode[i], m_matchMode[i]); - } - - lstSearchMode.setSelectedIndex(0); - } - - private void showBusinessPartner() - { - final int AD_Column_ID = 3499; - - MLookup lookupBP = MLookupFactory.get(Env.getCtx(), m_WindowNo, - 0, AD_Column_ID, DisplayType.Search); - - bPartnerSearch = new WSearchEditor(lookupBP, Msg.translate( - Env.getCtx(), "C_BPartner_ID"), "", true, false, true); - - bPartnerSearch.addValueChangeListener(this); - } - - private void showProduct() - { - final int AD_Column_ID = 3840; - - MLookup lookupP = MLookupFactory.get(Env.getCtx(), m_WindowNo, - 0, AD_Column_ID, DisplayType.Search); - - productSearch = new WSearchEditor(lookupP, Msg.translate( - Env.getCtx(), "M_Product_ID"), "", true, false, true); - - productSearch.addValueChangeListener(this); - } - - private void prepareTable() - { - ColumnInfo[] layout = new ColumnInfo[] { - new ColumnInfo(" ", ".", IDColumn.class, false, false, ""), - new ColumnInfo(Msg.translate(Env.getCtx(), "DocumentNo"), ".", String.class), // 1 - new ColumnInfo(Msg.translate(Env.getCtx(), "Date"), ".", Timestamp.class), - new ColumnInfo(Msg.translate(Env.getCtx(), "C_BPartner_ID"),".", KeyNamePair.class, "."), // 3 - new ColumnInfo(Msg.translate(Env.getCtx(), "Line"), ".", KeyNamePair.class, "."), - new ColumnInfo(Msg.translate(Env.getCtx(), "M_Product_ID"), ".", KeyNamePair.class, "."), // 5 - new ColumnInfo(Msg.translate(Env.getCtx(), "Qty"), ".", Double.class), - new ColumnInfo(Msg.translate(Env.getCtx(), "Matched"), ".", Double.class) - }; - - strMatchedTable = xMatchedTable.prepareTable(layout, "", "", false, ""); - strMatchedToTable = xMatchedToTable.prepareTable(layout, "", "", true, ""); - } - - private void searchRecords() - { - int display = lstMatchFrom.getSelectedIndex(); - - ListItem lstIteMatchTo = lstMatchTo.getSelectedItem(); - String matchToString = (String)lstIteMatchTo.getValue(); - int matchToType = MATCH_INVOICE; - - if (matchToString.equals(m_matchOptions[MATCH_SHIPMENT])) - matchToType = MATCH_SHIPMENT; - else if (matchToString.equals(m_matchOptions[MATCH_ORDER])) - matchToType = MATCH_ORDER; - - tableInit(display, matchToType); // sets m_sql - - // Where Clause - // Product - - if (productSearch.getDisplay() != "") - { - Integer Product = (Integer)productSearch.getValue(); - m_sql.append(" AND lin.M_Product_ID=").append(Product); - } - - // Business Partner - - if (bPartnerSearch.getDisplay() != "") - { - Integer Vendor = (Integer)bPartnerSearch.getValue(); - m_sql.append(" AND hdr.C_BPartner_ID=").append(Vendor); - } - - Date f =null; - Timestamp from =null; - - if (dateFrom.getValue() != null) - { - f = dateFrom.getValue(); - from = new Timestamp(f.getTime()); - } - - Date t = null; - Timestamp to = null; - - if (dateTo.getValue() != null) - { - t = dateTo.getValue(); - to = new Timestamp(t.getTime()); - } - - if (from != null && to != null) - m_sql.append(" AND ").append(m_dateColumn).append(" BETWEEN ") - .append(DB.TO_DATE(from)).append(" AND ").append(DB.TO_DATE(to)); - else if (from != null) - m_sql.append(" AND ").append(m_dateColumn).append(" >= ").append(DB.TO_DATE(from)); - else if (to != null) - m_sql.append(" AND ").append(m_dateColumn).append(" <= ").append(DB.TO_DATE(to)); - - // Load Table - tableLoad (xMatchedTable); - txtMatching.setText(Env.ZERO.toString()); - - // Status Info - ListItem lstIteMatchFrom = lstMatchFrom.getSelectedItem(); - Integer rowCount = xMatchedTable.getItemCount(); - - lblStatus.setValue(lstIteMatchFrom.getLabel() + "# = " + rowCount.toString()); - // xMatchedTable.getRowCount() == 0); - //statusBar.setStatusDB(0); - } - - private void process() - { - // Matched From - int matchedRow = xMatchedTable.getSelectedRow(); - - if (matchedRow < 0) - return; - - //KeyNamePair BPartner = (KeyNamePair)xMatchedTable.getValueAt(matchedRow, I_BPartner); - KeyNamePair lineMatched = (KeyNamePair)xMatchedTable.getValueAt(matchedRow, I_Line); - KeyNamePair Product = (KeyNamePair)xMatchedTable.getValueAt(matchedRow, I_Product); - - //int M_Product_ID = Product.getKey(); - double totalQty = m_xMatched.doubleValue(); - - // Matched To - for (int row = 0; row < xMatchedToTable.getItemCount(); row++) - { - IDColumn id = (IDColumn)xMatchedToTable.getValueAt(row, 0); - if (id != null && id.isSelected()) - { - // Need to be the same product - KeyNamePair ProductCompare = (KeyNamePair)xMatchedToTable.getValueAt(row, I_Product); - - if (Product.getKey() != ProductCompare.getKey()) - continue; - - KeyNamePair lineMatchedTo = (KeyNamePair)xMatchedToTable.getValueAt(row, I_Line); - - // Qty - double qty = 0.0; - - if (lstSearchMode.getSelectedIndex() == MODE_NOTMATCHED) - qty = ((Double)xMatchedToTable.getValueAt(row, I_QTY)).doubleValue(); // doc - - qty -= ((Double)xMatchedToTable.getValueAt(row, I_MATCHED)).doubleValue(); // matched - - if (qty > totalQty) - qty = totalQty; - - totalQty -= qty; - - // Invoice or PO - boolean invoice = true; - if (lstMatchFrom.getSelectedIndex() == MATCH_ORDER || - lstMatchTo.getSelectedItem().equals(m_matchOptions[MATCH_ORDER])) - invoice = false; - - // Get Shipment_ID - int M_InOutLine_ID = 0; - int Line_ID = 0; - - if (lstMatchFrom.getSelectedIndex() == MATCH_SHIPMENT) - { - M_InOutLine_ID = lineMatched.getKey(); // upper table - Line_ID = lineMatchedTo.getKey(); - } - else - { - M_InOutLine_ID = lineMatchedTo.getKey(); // lower table - Line_ID = lineMatched.getKey(); - } - - // Create it - createMatchRecord(invoice, M_InOutLine_ID, Line_ID, new BigDecimal(qty)); - } - } - // Requery - searchRecords(); - } - - public void tableChanged(WTableModelEvent e) - { - if (e.getColumn() != 0) - return; - - log.config("Row=" + e.getFirstRow() + "-" + e.getLastRow() + ", Col=" + e.getColumn() - + ", Type=" + e.getType()); - //setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - - // Matched From - int matchedRow = xMatchedTable.getSelectedRow(); - if (matchedRow == -1) - { - return; - } - KeyNamePair Product = (KeyNamePair)xMatchedTable.getValueAt(matchedRow, 5); - - // Matched To - double qty = 0.0; - Integer noRows = 0; - - for (int row = 0; row < xMatchedToTable.getItemCount(); row++) - { - IDColumn id = (IDColumn)xMatchedToTable.getValueAt(row, 0); - - if (id != null && id.isSelected()) - { - KeyNamePair ProductCompare = (KeyNamePair)xMatchedToTable.getValueAt(row, 5); - if (Product.getKey() != ProductCompare.getKey()) - { - id.setSelected(false); - } - else - { - if (lstSearchMode.getSelectedIndex() == MODE_NOTMATCHED) - qty += ((Double)xMatchedToTable.getValueAt(row, I_QTY)).doubleValue(); // doc - - qty -= ((Double)xMatchedToTable.getValueAt(row, I_MATCHED)).doubleValue(); // matched - noRows++; - } - } - } - - // Update qualtities - m_xMatchedTo = new BigDecimal(qty); - txtMatching.setValue(m_xMatchedTo.toString()); - txtDifference.setValue(m_xMatched.subtract(m_xMatchedTo).toString()); - cmdProcess.setEnabled(noRows != 0); - - //setCursor(Cursor.getDefaultCursor()); - // Status - //lblStatus.setValue(noRows.toString()); - } - - private void tableInit(int display, int matchToType) - { - boolean matched = lstSearchMode.getSelectedIndex() == MODE_MATCHED; - - m_sql = new StringBuffer (); - - if (display == MATCH_INVOICE) - { - m_dateColumn = "hdr.DateInvoiced"; - m_qtyColumn = "lin.QtyInvoiced"; - m_sql.append("SELECT hdr.C_Invoice_ID,hdr.DocumentNo, hdr.DateInvoiced, bp.Name,hdr.C_BPartner_ID," - + " lin.Line,lin.C_InvoiceLine_ID, p.Name,lin.M_Product_ID," - + " lin.QtyInvoiced,SUM(NVL(mi.Qty,0)) " - + "FROM C_Invoice hdr" - + " INNER JOIN C_BPartner bp ON (hdr.C_BPartner_ID=bp.C_BPartner_ID)" - + " INNER JOIN C_InvoiceLine lin ON (hdr.C_Invoice_ID=lin.C_Invoice_ID)" - + " INNER JOIN M_Product p ON (lin.M_Product_ID=p.M_Product_ID)" - + " INNER JOIN C_DocType dt ON (hdr.C_DocType_ID=dt.C_DocType_ID AND dt.DocBaseType IN ('API','APC'))" - + " FULL JOIN M_MatchInv mi ON (lin.C_InvoiceLine_ID=mi.C_InvoiceLine_ID) " - + "WHERE hdr.DocStatus IN ('CO','CL')"); - m_groupBy = " GROUP BY hdr.C_Invoice_ID,hdr.DocumentNo,hdr.DateInvoiced,bp.Name,hdr.C_BPartner_ID," - + " lin.Line,lin.C_InvoiceLine_ID,p.Name,lin.M_Product_ID,lin.QtyInvoiced " - + "HAVING " - + (matched ? "0" : "lin.QtyInvoiced") - + "<>SUM(NVL(mi.Qty,0))"; - } - else if (display == MATCH_ORDER) - { - m_dateColumn = "hdr.DateOrdered"; - m_qtyColumn = "lin.QtyOrdered"; - m_sql.append("SELECT hdr.C_Order_ID,hdr.DocumentNo, hdr.DateOrdered, bp.Name,hdr.C_BPartner_ID," - + " lin.Line,lin.C_OrderLine_ID, p.Name,lin.M_Product_ID," - + " lin.QtyOrdered,SUM(COALESCE(mo.Qty,0)) " - + "FROM C_Order hdr" - + " INNER JOIN C_BPartner bp ON (hdr.C_BPartner_ID=bp.C_BPartner_ID)" - + " INNER JOIN C_OrderLine lin ON (hdr.C_Order_ID=lin.C_Order_ID)" - + " INNER JOIN M_Product p ON (lin.M_Product_ID=p.M_Product_ID)" - + " INNER JOIN C_DocType dt ON (hdr.C_DocType_ID=dt.C_DocType_ID AND dt.DocBaseType='POO')" - + " FULL JOIN M_MatchPO mo ON (lin.C_OrderLine_ID=mo.C_OrderLine_ID) " - + "WHERE mo.") - .append(matchToType == MATCH_SHIPMENT ? "M_InOutLine_ID" : "C_InvoiceLine_ID") - .append(matched ? " IS NOT NULL" : " IS NULL" - + " AND hdr.DocStatus IN ('CO','CL')"); - m_groupBy = " GROUP BY hdr.C_Order_ID,hdr.DocumentNo,hdr.DateOrdered,bp.Name,hdr.C_BPartner_ID," - + " lin.Line,lin.C_OrderLine_ID,p.Name,lin.M_Product_ID,lin.QtyOrdered " - + "HAVING " - + (matched ? "0" : "lin.QtyOrdered") - + "<>SUM(COALESCE(mo.Qty,0))"; - } - else // Shipment - { - m_dateColumn = "hdr.MovementDate"; - m_qtyColumn = "lin.MovementQty"; - m_sql.append("SELECT hdr.M_InOut_ID,hdr.DocumentNo, hdr.MovementDate, bp.Name,hdr.C_BPartner_ID," - + " lin.Line,lin.M_InOutLine_ID, p.Name,lin.M_Product_ID," - + " lin.MovementQty,SUM(NVL(m.Qty,0)) " - + "FROM M_InOut hdr" - + " INNER JOIN C_BPartner bp ON (hdr.C_BPartner_ID=bp.C_BPartner_ID)" - + " INNER JOIN M_InOutLine lin ON (hdr.M_InOut_ID=lin.M_InOut_ID)" - + " INNER JOIN M_Product p ON (lin.M_Product_ID=p.M_Product_ID)" - + " INNER JOIN C_DocType dt ON (hdr.C_DocType_ID = dt.C_DocType_ID AND dt.DocBaseType='MMR')" - + " FULL JOIN ") - .append(matchToType == MATCH_ORDER ? "M_MatchPO" : "M_MatchInv") - .append(" m ON (lin.M_InOutLine_ID=m.M_InOutLine_ID) " - + "WHERE hdr.DocStatus IN ('CO','CL')"); - m_groupBy = " GROUP BY hdr.M_InOut_ID,hdr.DocumentNo,hdr.MovementDate,bp.Name,hdr.C_BPartner_ID," - + " lin.Line,lin.M_InOutLine_ID,p.Name,lin.M_Product_ID,lin.MovementQty " - + "HAVING " - + (matched ? "0" : "lin.MovementQty") - + "<>SUM(NVL(m.Qty,0))"; - } - } - - private void tableLoad(WListbox table) - { - log.finest(m_sql + " - " + m_groupBy); - String sql = MRole.getDefault().addAccessSQL( - m_sql.toString(), "hdr", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO) - + m_groupBy; - log.finest(sql); - - try - { - Statement stmt = DB.createStatement(); - ResultSet rs = stmt.executeQuery(sql); - table.loadTable(rs); - stmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - } - - private boolean createMatchRecord (boolean invoice, int M_InOutLine_ID, int Line_ID, - BigDecimal qty) - { - if (qty.compareTo(Env.ZERO) == 0) - return true; - - log.fine("IsInvoice=" + invoice - + ", M_InOutLine_ID=" + M_InOutLine_ID + ", Line_ID=" + Line_ID - + ", Qty=" + qty); - - boolean success = false; - MInOutLine sLine = new MInOutLine (Env.getCtx(), M_InOutLine_ID, null); - - if (invoice) // Shipment - Invoice - { - // Update Invoice Line - - MInvoiceLine iLine = new MInvoiceLine (Env.getCtx(), Line_ID, null); - iLine.setM_InOutLine_ID(M_InOutLine_ID); - - if (sLine.getC_OrderLine_ID() != 0) - iLine.setC_OrderLine_ID(sLine.getC_OrderLine_ID()); - - iLine.save(); - - // Create Shipment - Invoice Link - if (iLine.getM_Product_ID() != 0) - { - MMatchInv match = new MMatchInv (iLine, null, qty); - match.setM_InOutLine_ID(M_InOutLine_ID); - if (match.save()) - success = true; - else - log.log(Level.SEVERE, "Inv Match not created: " + match); - } - else - success = true; - - // Create PO - Invoice Link = corrects PO - if (iLine.getC_OrderLine_ID() != 0 && iLine.getM_Product_ID() != 0) - { - MMatchPO matchPO = MMatchPO.create(iLine, sLine, null, qty); - matchPO.setC_InvoiceLine_ID(iLine); - matchPO.setM_InOutLine_ID(M_InOutLine_ID); - - if (!matchPO.save()) - { - log.log(Level.SEVERE, "PO(Inv) Match not created: " + matchPO); - } - } - } - else // Shipment - Order - { - // Update Shipment Line - sLine.setC_OrderLine_ID(Line_ID); - sLine.save(); - - // Update Order Line - MOrderLine oLine = new MOrderLine(Env.getCtx(), Line_ID, null); - - if (oLine.get_ID() != 0) // other in MInOut.completeIt - { - oLine.setQtyReserved(oLine.getQtyReserved().subtract(qty)); - if(!oLine.save()) - ;//log.severe("QtyReserved not updated - C_OrderLine_ID=" + Line_ID); - } - - // Create PO - Shipment Link - if (sLine.getM_Product_ID() != 0) - { - MMatchPO match = new MMatchPO (sLine, null, qty); - if (!match.save()) - ;// log.log(Level.SEVERE, "PO Match not created: " + match); - else - { - success = true; - - // Correct Ordered Qty for Stocked Products (see MOrder.reserveStock / MInOut.processIt) - if (sLine.getProduct() != null && sLine.getProduct().isStocked()) - success = MStorage.add (Env.getCtx(), sLine.getM_Warehouse_ID(), - sLine.getM_Locator_ID(), - sLine.getM_Product_ID(), - sLine.getM_AttributeSetInstance_ID(), oLine.getM_AttributeSetInstance_ID(), - null, null, qty.negate(), null); - } - } - else - success = true; - } - return success; - } - - private void searchTo() - { - int row = xMatchedTable.getSelectedRow(); - log.config("Row=" + row); - - double qty = 0.0; - - if (row < 0) - { - xMatchedToTable.setRowCount(0); - } - else - { - // ** Create SQL ** - ListItem lstIteDisplayStr = lstMatchTo.getSelectedItem(); - String displayString = (String)lstIteDisplayStr.getValue(); - int display = MATCH_INVOICE; - - if (displayString.equals(m_matchOptions[MATCH_SHIPMENT])) - display = MATCH_SHIPMENT; - else if (displayString.equals(m_matchOptions[MATCH_ORDER])) - display = MATCH_ORDER; - - int matchToType = lstMatchFrom.getSelectedIndex(); - - tableInit (display, matchToType); // sets m_sql - - // ** Add Where Clause ** - KeyNamePair BPartner = (KeyNamePair)xMatchedTable.getValueAt(row, I_BPartner); - KeyNamePair Product = (KeyNamePair)xMatchedTable.getValueAt(row, I_Product); - log.fine("BPartner=" + BPartner + " - Product=" + Product); - - if (chkSameBP.isChecked()) - m_sql.append(" AND hdr.C_BPartner_ID=").append(BPartner.getKey()); - - if (chkSameProduct.isChecked()) - m_sql.append(" AND lin.M_Product_ID=").append(Product.getKey()); - - // Calculate qty - double docQty = ((Double)xMatchedTable.getValueAt(row, I_QTY)).doubleValue(); - double matchedQty = ((Double)xMatchedTable.getValueAt(row, I_MATCHED)).doubleValue(); - qty = docQty - matchedQty; - - if (chkSameQty.isChecked()) - m_sql.append(" AND ").append(m_qtyColumn).append("=").append(docQty); - - // ** Load Table ** - tableLoad (xMatchedToTable); - } - - // Display To be Matched Qty - m_xMatched = new BigDecimal (qty); - txtToBeMatched.setValue(m_xMatched.toString()); - txtMatching.setValue(Env.ZERO.toString()); - txtDifference.setValue(m_xMatched.toString()); - - // Status Info - ListItem lstIteMatchFrom = lstMatchFrom.getSelectedItem(); - ListItem lstIteMatchTo = lstMatchTo.getSelectedItem(); - - Integer matchedRowCount = xMatchedTable.getItemCount(); - Integer matchToRowCount = xMatchedToTable.getItemCount(); - - String stat = lstIteMatchFrom.getLabel() + "# = " + matchedRowCount.toString() + " - " - + lstIteMatchTo.getLabel() + "# = " + matchToRowCount.toString(); - - lblStatus.setValue(stat); - // xMatchedToTable.getRowCount() == 0); - //statusBar.setStatusDB(0); - } - - public void onEvent(Event evt) throws Exception - { - if (evt != null) - { - if (evt.getTarget() == lstMatchFrom) - { - populateMatchTo(); - - ListItem lstIteMatchFrom = lstMatchFrom.getSelectedItem(); - lblMatchFrom.setValue(lstIteMatchFrom.getLabel()); - - ListItem lstIteMatchTo = lstMatchTo.getSelectedItem(); - lblMatchTo.setValue(lstIteMatchTo.getLabel()); - - xMatchedTable.clear(); - xMatchedToTable.clear(); - } - - if (evt.getTarget() == lstMatchTo) - { - ListItem lstIteMatchTo = lstMatchTo.getSelectedItem(); - lblMatchTo.setValue(lstIteMatchTo.getLabel()); - - xMatchedTable.clear(); - xMatchedToTable.clear(); - } - - if (evt.getTarget() == chkSameBP) - { - searchTo(); - } - - if (evt.getTarget() == chkSameProduct) - { - searchTo(); - } - - if (evt.getTarget() == chkSameQty) - { - searchTo(); - } - - if (evt.getTarget() == cmdSearch) - { - xMatchedTable.clear(); - xMatchedToTable.clear(); - searchRecords(); - } - - if (evt.getTarget() == cmdProcess) - { - process(); - - xMatchedTable.clear(); - xMatchedToTable.clear(); - - txtMatching.setValue(""); - txtToBeMatched.setValue(""); - txtDifference.setValue(""); - - lblStatus.setValue(""); - - searchRecords(); - } - - if (evt.getTarget() == xMatchedTable) - { - searchTo(); - } - } - } - - //public void tableChanged(WTableModelEvent event) - //{ - //if (event.getColumn() == 0) - //{ - // searchTo(); - //} - //} - - public void valueChange(ValueChangeEvent evt) - { - if (evt == null) - return; - - if (evt.getSource() instanceof WEditor) - { - String name = evt.getPropertyName(); - Object value = evt.getNewValue() == null ? "" : evt.getNewValue(); - - xMatchedTable.clear(); - xMatchedToTable.clear(); - - if (name.equals("C_BPartner_ID")) - { - bPartnerSearch.setValue(value); - //m_C_BPartner_ID = ((Integer) value).intValue(); - } - else if (name.equals("M_Product_ID")) - { - productSearch.setValue(value); - //productID = new Integer(value); - } - } - } -} +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.adempiere.webui.apps.form; + +import java.math.*; +import java.sql.*; +import java.util.*; +import java.util.logging.*; + +import org.adempiere.webui.LayoutUtils; +import org.adempiere.webui.apps.AEnv; +import org.adempiere.webui.component.Button; +import org.adempiere.webui.component.Checkbox; +import org.adempiere.webui.component.Grid; +import org.adempiere.webui.component.GridFactory; +import org.adempiere.webui.component.Label; +import org.adempiere.webui.component.ListModelTable; +import org.adempiere.webui.component.Listbox; +import org.adempiere.webui.component.ListboxFactory; +import org.adempiere.webui.component.Panel; +import org.adempiere.webui.component.Row; +import org.adempiere.webui.component.Rows; +import org.adempiere.webui.component.SimpleListModel; +import org.adempiere.webui.component.WListbox; +import org.adempiere.webui.editor.WDateEditor; +import org.adempiere.webui.editor.WNumberEditor; +import org.adempiere.webui.editor.WSearchEditor; +import org.adempiere.webui.event.WTableModelEvent; +import org.adempiere.webui.event.WTableModelListener; +import org.adempiere.webui.panel.ADForm; +import org.adempiere.webui.panel.StatusBarPanel; +import org.adempiere.webui.session.SessionManager; +import org.compiere.minigrid.ColumnInfo; +import org.compiere.minigrid.IDColumn; +import org.compiere.model.*; +import org.compiere.util.*; +import org.zkoss.zk.ui.event.Event; +import org.zkoss.zk.ui.event.EventListener; +import org.zkoss.zk.ui.event.Events; +import org.zkoss.zkex.zul.Borderlayout; +import org.zkoss.zkex.zul.Center; +import org.zkoss.zkex.zul.North; +import org.zkoss.zkex.zul.South; +import org.zkoss.zul.ListModel; +import org.zkoss.zul.Separator; +import org.zkoss.zul.Space; + +/** + * Manual Matching + * + * @author Jorg Janke + * @version $Id: VMatch.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ + */ +public class WMatch extends ADForm + implements EventListener, WTableModelListener +{ + /** + * Initialize Panel + */ + protected void initForm() + { + log.info("WinNo=" + m_WindowNo + + " - AD_Client_ID=" + m_AD_Client_ID + ", AD_Org_ID=" + m_AD_Org_ID + ", By=" + m_by); + Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", "N"); + + try + { + // UI + onlyVendor = WSearchEditor.createBPartner(m_WindowNo); + onlyProduct = WSearchEditor.createProduct(m_WindowNo); + zkInit(); + // + dynInit(); + southPanel.appendChild(new Separator()); + southPanel.appendChild(statusBar); + LayoutUtils.addSclass("status-border", statusBar); + // + new Thread() + { + public void run() + { + log.info("Starting ..."); + MMatchPO.consolidate(Env.getCtx()); + log.info("... Done"); + } + }.start(); + } + catch(Exception e) + { + log.log(Level.SEVERE, "", e); + } + } // init + + /** Logger */ + private static CLogger log = CLogger.getCLogger(WMatch.class); + + private int m_AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); + private int m_AD_Org_ID = Env.getAD_Org_ID(Env.getCtx()); + private int m_by = Env.getAD_User_ID(Env.getCtx()); + + /** Match Options */ + private String[] m_matchOptions = new String[] { + Msg.getElement(Env.getCtx(), "C_Invoice_ID", false), + Msg.getElement(Env.getCtx(), "M_InOut_ID", false), + Msg.getElement(Env.getCtx(), "C_Order_ID", false) }; + private static final int MATCH_INVOICE = 0; + private static final int MATCH_SHIPMENT = 1; + private static final int MATCH_ORDER = 2; + + /** Match Mode */ + private String[] m_matchMode = new String[] { + Msg.translate(Env.getCtx(), "NotMatched"), + Msg.translate(Env.getCtx(), "Matched")}; + private static final int MODE_NOTMATCHED = 0; + private static final int MODE_MATCHED = 1; + + /** Indexes in Table */ + private static final int I_BPartner = 3; + private static final int I_Line = 4; + private static final int I_Product = 5; + private static final int I_QTY = 6; + private static final int I_MATCHED = 7; + + + private StringBuffer m_sql = null; + private String m_dateColumn = ""; + private String m_qtyColumn = ""; + private String m_groupBy = ""; + private StringBuffer m_linetype = null; + private BigDecimal m_xMatched = Env.ZERO; + private BigDecimal m_xMatchedTo = Env.ZERO; + + // + private Panel mainPanel = new Panel(); + private StatusBarPanel statusBar = new StatusBarPanel(); + private Borderlayout mainLayout = new Borderlayout(); + private Panel northPanel = new Panel(); + private Grid northLayout = GridFactory.newGridLayout(); + private Label matchFromLabel = new Label(); + private Listbox matchFrom = ListboxFactory.newDropdownListbox(m_matchOptions); + private Label matchToLabel = new Label(); + private Listbox matchTo = ListboxFactory.newDropdownListbox(); + private Label matchModeLabel = new Label(); + private Listbox matchMode = ListboxFactory.newDropdownListbox(m_matchMode); + private WSearchEditor onlyVendor = null; + private WSearchEditor onlyProduct = null; + private Label onlyVendorLabel = new Label(); + private Label onlyProductLabel = new Label(); + private Label dateFromLabel = new Label(); + private Label dateToLabel = new Label(); + private WDateEditor dateFrom = new WDateEditor("DateFrom", false, false, true, DisplayType.Date, "DateFrom"); + private WDateEditor dateTo = new WDateEditor("DateTo", false, false, true, DisplayType.Date, "DateTo"); + private Button bSearch = new Button(); + private Panel southPanel = new Panel(); + private Grid southLayout = GridFactory.newGridLayout(); + private Label xMatchedLabel = new Label(); + private Label xMatchedToLabel = new Label(); + private Label differenceLabel = new Label(); + private WNumberEditor xMatched = new WNumberEditor("xMatched", false, true, false, DisplayType.Quantity, "xMatched"); + private WNumberEditor xMatchedTo = new WNumberEditor("xMatchedTo", false, true, false, DisplayType.Quantity, "xMatchedTo"); + private WNumberEditor difference = new WNumberEditor("Difference", false, true, false, DisplayType.Quantity, "Difference"); + private Button bProcess = new Button(); + private Panel centerPanel = new Panel(); + private Borderlayout centerLayout = new Borderlayout(); +// private JScrollPane xMatchedScrollPane = new JScrollPane(); + private Label xMatchedBorder = new Label("xMatched"); + private WListbox xMatchedTable = ListboxFactory.newDataTable(); +// private JScrollPane xMatchedToScrollPane = new JScrollPane(); + private Label xMatchedToBorder = new Label("xMatchedTo"); + private WListbox xMatchedToTable = ListboxFactory.newDataTable(); + private Panel xPanel = new Panel(); + private Checkbox sameProduct = new Checkbox(); + private Checkbox sameBPartner = new Checkbox(); + private Checkbox sameQty = new Checkbox(); +// private FlowLayout xLayout = new FlowLayout(FlowLayout.CENTER, 10, 0); + + /** + * Static Init. + *
+	 *  mainPanel
+	 *      northPanel
+	 *      centerPanel
+	 *          xMatched
+	 *          xPanel
+	 *          xMathedTo
+	 *      southPanel
+	 *  
+ * @throws Exception + */ + private void zkInit() throws Exception + { + this.appendChild(mainPanel); + mainPanel.setStyle("width: 99%; height: 100%; padding: 0; margin: 0"); + mainPanel.appendChild(mainLayout); + mainLayout.setWidth("100%"); + mainLayout.setHeight("100%"); + northPanel.appendChild(northLayout); + matchFromLabel.setText(Msg.translate(Env.getCtx(), "MatchFrom")); + matchToLabel.setText(Msg.translate(Env.getCtx(), "MatchTo")); + matchModeLabel.setText(Msg.translate(Env.getCtx(), "MatchMode")); + onlyVendorLabel.setText(Msg.translate(Env.getCtx(), "C_BPartner_ID")); + onlyProductLabel.setText(Msg.translate(Env.getCtx(), "M_Product_ID")); + dateFromLabel.setText(Msg.translate(Env.getCtx(), "DateFrom")); + dateToLabel.setText(Msg.translate(Env.getCtx(), "DateTo")); + bSearch.setLabel(Msg.translate(Env.getCtx(), "Search")); + southPanel.appendChild(southLayout); + xMatchedLabel.setText(Msg.translate(Env.getCtx(), "ToBeMatched")); + xMatchedToLabel.setText(Msg.translate(Env.getCtx(), "Matching")); + differenceLabel.setText(Msg.translate(Env.getCtx(), "Difference")); + bProcess.setLabel(Msg.translate(Env.getCtx(), "Process")); + centerPanel.appendChild(centerLayout); +// xMatchedScrollPane.setBorder(xMatchedBorder); +// xMatchedScrollPane.setPreferredSize(new Dimension(450, 200)); +// xMatchedToScrollPane.setBorder(xMatchedToBorder); +// xMatchedToScrollPane.setPreferredSize(new Dimension(450, 200)); + sameProduct.setSelected(true); + sameProduct.setText(Msg.translate(Env.getCtx(), "SameProduct")); + sameBPartner.setSelected(true); + sameBPartner.setText(Msg.translate(Env.getCtx(), "SameBPartner")); + sameQty.setSelected(false); + sameQty.setText(Msg.translate(Env.getCtx(), "SameQty")); +// xPanel.setLayout(xLayout); + + North north = new North(); + mainLayout.appendChild(north); + north.appendChild(northPanel); + + Rows rows = northLayout.newRows(); + Row row = rows.newRow(); + row.appendChild(matchFromLabel.rightAlign()); + row.appendChild(matchFrom); + row.appendChild(matchToLabel.rightAlign()); + row.appendChild(matchTo); + row.appendChild(new Space()); + + row = rows.newRow(); + row.setSpans("1,1,3"); + row.appendChild(matchModeLabel.rightAlign()); + row.appendChild(matchMode); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(onlyVendorLabel.rightAlign()); + row.appendChild(onlyVendor.getComponent()); + row.appendChild(onlyProductLabel.rightAlign()); + row.appendChild(onlyProduct.getComponent()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(dateFromLabel.rightAlign()); + row.appendChild(dateFrom.getComponent()); + row.appendChild(dateToLabel.rightAlign()); + row.appendChild(dateTo.getComponent()); + row.appendChild(bSearch); + + South south = new South(); + mainLayout.appendChild(south); + south.appendChild(southPanel); + + rows = southLayout.newRows(); + + row = rows.newRow(); + row.appendChild(xMatchedLabel.rightAlign()); + row.appendChild(xMatched.getComponent()); + row.appendChild(xMatchedToLabel.rightAlign()); + row.appendChild(xMatchedTo.getComponent()); + row.appendChild(differenceLabel.rightAlign()); + row.appendChild(difference.getComponent()); + row.appendChild(bProcess); + + Center center = new Center(); + mainLayout.appendChild(center); + center.appendChild(centerPanel); + center.setFlex(true); + centerLayout.setWidth("100%"); + centerLayout.setHeight("100%"); + north = new North(); + centerLayout.appendChild(north); + north.setStyle("border: none"); + Panel p = new Panel(); + p.appendChild(xMatchedBorder); + p.appendChild(xMatchedTable); + xMatchedTable.setWidth("99%"); + xMatchedTable.setHeight("85%"); + p.setStyle("width: 100%; height: 100%; padding: 0; margin: 0"); + north.appendChild(p); + north.setHeight("44%"); + + south = new South(); + centerLayout.appendChild(south); + south.setStyle("border: none"); + xMatchedToTable.setWidth("99%"); + xMatchedToTable.setHeight("99%"); + south.appendChild(xMatchedToTable); + south.setHeight("44%"); + + center = new Center(); + centerLayout.appendChild(center); + center.setStyle("border: none"); + center.setFlex(false); +// center.setHeight("6%"); + center.appendChild(xPanel); + xPanel.appendChild(sameBPartner); + xPanel.appendChild(new Space()); + xPanel.appendChild(sameProduct); + xPanel.appendChild(new Space()); + xPanel.appendChild(sameQty); + xPanel.setHeight("50px"); + xPanel.appendChild(new Separator()); + xPanel.appendChild(xMatchedToBorder); + } // jbInit + + /** + * Dynamic Init. + * Table Layout, Visual, Listener + */ + private void dynInit() + { + ColumnInfo[] layout = new ColumnInfo[] { + new ColumnInfo(" ", ".", IDColumn.class, false, false, ""), + new ColumnInfo(Msg.translate(Env.getCtx(), "DocumentNo"), ".", String.class), // 1 + new ColumnInfo(Msg.translate(Env.getCtx(), "Date"), ".", Timestamp.class), + new ColumnInfo(Msg.translate(Env.getCtx(), "C_BPartner_ID"),".", KeyNamePair.class, "."), // 3 + new ColumnInfo(Msg.translate(Env.getCtx(), "Line"), ".", KeyNamePair.class, "."), + new ColumnInfo(Msg.translate(Env.getCtx(), "M_Product_ID"), ".", KeyNamePair.class, "."), // 5 + new ColumnInfo(Msg.translate(Env.getCtx(), "Qty"), ".", Double.class), + new ColumnInfo(Msg.translate(Env.getCtx(), "Matched"), ".", Double.class) + }; + + xMatchedTable.prepareTable(layout, "", "", false, ""); + xMatchedToTable.prepareTable(layout, "", "", true, ""); + + matchFrom.setSelectedIndex(0); + // Listener + matchFrom.addActionListener(this); + matchTo.addActionListener(this); + bSearch.addActionListener(this); + xMatchedTable.addEventListener(Events.ON_SELECT, this); + xMatchedToTable.getModel().addTableModelListener(this); + bProcess.addActionListener(this); + sameBPartner.addActionListener(this); + sameProduct.addActionListener(this); + sameQty.addActionListener(this); + // Init + cmd_matchFrom(); + statusBar.setStatusLine(""); + statusBar.setStatusDB("0"); + } // dynInit + + /** + * Dispose + */ + public void dispose() + { + SessionManager.getAppDesktop().removeWindow(); + } // dispose + + + /************************************************************************** + * Action Listener + * @param e event + */ + public void onEvent (Event e) + { + if (e.getTarget() == matchFrom) + cmd_matchFrom(); + else if (e.getTarget() == matchTo) + cmd_matchTo(); + else if (e.getTarget() == bSearch) + cmd_search(); + else if (e.getTarget() == bProcess) + cmd_process(); + else if (e.getTarget() == sameBPartner + || e.getTarget() == sameProduct + || e.getTarget() == sameQty) + cmd_searchTo(); + else if (AEnv.contains(xMatchedTable, e.getTarget())) + cmd_searchTo(); + } // actionPerformed + + /** + * Match From Changed - Fill Match To + */ + private void cmd_matchFrom() + { + // log.fine( "VMatch.cmd_matchFrom"); + String selection = (String)matchFrom.getSelectedItem().getValue(); + Vector vector = new Vector(2); + if (selection.equals(m_matchOptions[MATCH_INVOICE])) + vector.add(m_matchOptions[MATCH_SHIPMENT]); + else if (selection.equals(m_matchOptions[MATCH_ORDER])) + vector.add(m_matchOptions[MATCH_SHIPMENT]); + else // shipment + { + vector.add(m_matchOptions[MATCH_INVOICE]); + vector.add(m_matchOptions[MATCH_ORDER]); + } + SimpleListModel model = new SimpleListModel(vector); + matchTo.setItemRenderer(model); + matchTo.setModel(model); + // Set Title + xMatchedBorder.setValue(selection); + // Reset Table + xMatchedTable.setRowCount(0); + // sync To + matchTo.setSelectedIndex(0); + cmd_matchTo(); + } // cmd_matchFrom + + /** + * Match To Changed - set Title + */ + private void cmd_matchTo() + { + // log.fine( "VMatch.cmd_matchTo"); + int index = matchTo.getSelectedIndex(); + String selection = (String)matchTo.getModel().getElementAt(index); + xMatchedToBorder.setValue(selection); + // Reset Table + xMatchedToTable.setRowCount(0); + } // cmd_matchTo + + /** + * Search Button Pressed - Fill xMatched + */ + private void cmd_search() + { + // ** Create SQL ** + int display = matchFrom.getSelectedIndex(); + String matchToString = (String)matchTo.getSelectedItem().getLabel(); + int matchToType = MATCH_INVOICE; + if (matchToString.equals(m_matchOptions[MATCH_SHIPMENT])) + matchToType = MATCH_SHIPMENT; + else if (matchToString.equals(m_matchOptions[MATCH_ORDER])) + matchToType = MATCH_ORDER; + // + tableInit(display, matchToType); // sets m_sql + + // ** Add Where Clause ** + // Product + if (onlyProduct.getValue() != null) + { + Integer Product = (Integer)onlyProduct.getValue(); + m_sql.append(" AND lin.M_Product_ID=").append(Product); + } + // BPartner + if (onlyVendor.getValue() != null) + { + Integer Vendor = (Integer)onlyVendor.getValue(); + m_sql.append(" AND hdr.C_BPartner_ID=").append(Vendor); + } + // Date + Timestamp from = (Timestamp)dateFrom.getValue(); + Timestamp to = (Timestamp)dateTo.getValue(); + if (from != null && to != null) + m_sql.append(" AND ").append(m_dateColumn).append(" BETWEEN ") + .append(DB.TO_DATE(from)).append(" AND ").append(DB.TO_DATE(to)); + else if (from != null) + m_sql.append(" AND ").append(m_dateColumn).append(" >= ").append(DB.TO_DATE(from)); + else if (to != null) + m_sql.append(" AND ").append(m_dateColumn).append(" <= ").append(DB.TO_DATE(to)); + + // ** Load Table ** + tableLoad (xMatchedTable); + xMatched.setValue(Env.ZERO); + // Status Info + statusBar.setStatusLine(matchFrom.getSelectedItem().getLabel() + + "# = " + xMatchedTable.getRowCount(), + xMatchedTable.getRowCount() == 0); + statusBar.setStatusDB("0"); + } // cmd_search + + /** + * Process Button Pressed - Process Matching + */ + private void cmd_process() + { + log.config(""); + // Matched From + int matchedRow = xMatchedTable.getSelectedRow(); + if (matchedRow < 0) + return; + // KeyNamePair BPartner = (KeyNamePair)xMatchedTable.getValueAt(matchedRow, I_BPartner); + KeyNamePair lineMatched = (KeyNamePair)xMatchedTable.getValueAt(matchedRow, I_Line); + KeyNamePair Product = (KeyNamePair)xMatchedTable.getValueAt(matchedRow, I_Product); + + int M_Product_ID = Product.getKey(); + double totalQty = m_xMatched.doubleValue(); + + // Matched To + for (int row = 0; row < xMatchedToTable.getRowCount(); row++) + { + IDColumn id = (IDColumn)xMatchedToTable.getValueAt(row, 0); + if (id != null && id.isSelected()) + { + // need to be the same product + KeyNamePair ProductCompare = (KeyNamePair)xMatchedToTable.getValueAt(row, I_Product); + if (Product.getKey() != ProductCompare.getKey()) + continue; + + KeyNamePair lineMatchedTo = (KeyNamePair)xMatchedToTable.getValueAt(row, I_Line); + + // Qty + double qty = 0.0; + if (matchMode.getSelectedIndex() == MODE_NOTMATCHED) + qty = ((Double)xMatchedToTable.getValueAt(row, I_QTY)).doubleValue(); // doc + qty -= ((Double)xMatchedToTable.getValueAt(row, I_MATCHED)).doubleValue(); // matched + if (qty > totalQty) + qty = totalQty; + totalQty -= qty; + + // Invoice or PO + boolean invoice = true; + if (matchFrom.getSelectedIndex() == MATCH_ORDER || + matchTo.getSelectedItem().equals(m_matchOptions[MATCH_ORDER])) + invoice = false; + // Get Shipment_ID + int M_InOutLine_ID = 0; + int Line_ID = 0; + if (matchFrom.getSelectedIndex() == MATCH_SHIPMENT) + { + M_InOutLine_ID = lineMatched.getKey(); // upper table + Line_ID = lineMatchedTo.getKey(); + } + else + { + M_InOutLine_ID = lineMatchedTo.getKey(); // lower table + Line_ID = lineMatched.getKey(); + } + + // Create it + createMatchRecord(invoice, M_InOutLine_ID, Line_ID, new BigDecimal(qty)); + } + } + // requery + cmd_search(); + } // cmd_process + + /** + * Fill xMatchedTo + */ + private void cmd_searchTo() + { + int row = xMatchedTable.getSelectedRow(); + log.config("Row=" + row); + + double qty = 0.0; + if (row < 0) + { + xMatchedToTable.setRowCount(0); + } + else + { + // ** Create SQL ** + String displayString = (String)matchTo.getSelectedItem().getLabel(); + int display = MATCH_INVOICE; + if (displayString.equals(m_matchOptions[MATCH_SHIPMENT])) + display = MATCH_SHIPMENT; + else if (displayString.equals(m_matchOptions[MATCH_ORDER])) + display = MATCH_ORDER; + int matchToType = matchFrom.getSelectedIndex(); + tableInit (display, matchToType); // sets m_sql + // ** Add Where Clause ** + KeyNamePair BPartner = (KeyNamePair)xMatchedTable.getValueAt(row, I_BPartner); + KeyNamePair Product = (KeyNamePair)xMatchedTable.getValueAt(row, I_Product); + log.fine("BPartner=" + BPartner + " - Product=" + Product); + // + if (sameBPartner.isSelected()) + m_sql.append(" AND hdr.C_BPartner_ID=").append(BPartner.getKey()); + if (sameProduct.isSelected()) + m_sql.append(" AND lin.M_Product_ID=").append(Product.getKey()); + + // calculate qty + double docQty = ((Double)xMatchedTable.getValueAt(row, I_QTY)).doubleValue(); + double matchedQty = ((Double)xMatchedTable.getValueAt(row, I_MATCHED)).doubleValue(); + qty = docQty - matchedQty; + if (sameQty.isSelected()) + m_sql.append(" AND ").append(m_qtyColumn).append("=").append(docQty); + // ** Load Table ** + tableLoad (xMatchedToTable); + } + // Display To be Matched Qty + m_xMatched = new BigDecimal (qty); + xMatched.setValue(m_xMatched); + xMatchedTo.setValue(Env.ZERO); + difference.setValue(m_xMatched); + // Status Info + statusBar.setStatusLine(matchFrom.getSelectedItem().getLabel() + + "# = " + xMatchedTable.getRowCount() + " - " + + getMatchToLabel() + + "# = " + xMatchedToTable.getRowCount(), + xMatchedToTable.getRowCount() == 0); + statusBar.setStatusDB("0"); + } // cmd_seachTo + + + private String getMatchToLabel() { + int index = matchTo.getSelectedIndex(); + return matchTo.getModel().getElementAt(index).toString(); + } + + /*************************************************************************** + * Table Model Listener - calculate matchd Qty + * @param e event + */ + public void tableChanged (WTableModelEvent e) + { + if (e.getColumn() != 0) + return; + log.config("Row=" + e.getFirstRow() + "-" + e.getLastRow() + ", Col=" + e.getColumn() + + ", Type=" + e.getType()); + + // Matched From + int matchedRow = xMatchedTable.getSelectedRow(); + KeyNamePair Product = (KeyNamePair)xMatchedTable.getValueAt(matchedRow, 5); + + // Matched To + double qty = 0.0; + int noRows = 0; + for (int row = 0; row < xMatchedToTable.getRowCount(); row++) + { + IDColumn id = (IDColumn)xMatchedToTable.getValueAt(row, 0); + if (id != null && id.isSelected()) + { + KeyNamePair ProductCompare = (KeyNamePair)xMatchedToTable.getValueAt(row, 5); + if (Product.getKey() != ProductCompare.getKey()) + { + id.setSelected(false); + } + else + { + if (matchMode.getSelectedIndex() == MODE_NOTMATCHED) + qty += ((Double)xMatchedToTable.getValueAt(row, I_QTY)).doubleValue(); // doc + qty -= ((Double)xMatchedToTable.getValueAt(row, I_MATCHED)).doubleValue(); // matched + noRows++; + } + } + } + // update qualtities + m_xMatchedTo = new BigDecimal(qty); + xMatchedTo.setValue(m_xMatchedTo); + difference.setValue(m_xMatched.subtract(m_xMatchedTo)); + bProcess.setEnabled(noRows != 0); + // Status + statusBar.setStatusDB(noRows + ""); + } // tableChanged + + + /************************************************************************** + * Initialise Table access - create SQL, dateColumn. + *
+ * The driving table is "hdr", e.g. for hdr.C_BPartner_ID=.. + * The line table is "lin", e.g. for lin.M_Product_ID=.. + * You use the dateColumn/qtyColumn variable directly as it is table specific. + *
+ * The sql is dependent on MatchMode: + * - If Matched - all (fully or partially) matched records are listed + * - If Not Matched - all not fully matched records are listed + * @param display (Invoice, Shipment, Order) see MATCH_* + * @param matchToType (Invoice, Shipment, Order) see MATCH_* + */ + private void tableInit (int display, int matchToType) + { + boolean matched = matchMode.getSelectedIndex() == MODE_MATCHED; + log.config("Display=" + m_matchOptions[display] + + ", MatchTo=" + m_matchOptions[matchToType] + + ", Matched=" + matched); + + m_sql = new StringBuffer (); + if (display == MATCH_INVOICE) + { + m_dateColumn = "hdr.DateInvoiced"; + m_qtyColumn = "lin.QtyInvoiced"; + m_sql.append("SELECT hdr.C_Invoice_ID,hdr.DocumentNo, hdr.DateInvoiced, bp.Name,hdr.C_BPartner_ID," + + " lin.Line,lin.C_InvoiceLine_ID, p.Name,lin.M_Product_ID," + + " lin.QtyInvoiced,SUM(NVL(mi.Qty,0)) " + + "FROM C_Invoice hdr" + + " INNER JOIN C_BPartner bp ON (hdr.C_BPartner_ID=bp.C_BPartner_ID)" + + " INNER JOIN C_InvoiceLine lin ON (hdr.C_Invoice_ID=lin.C_Invoice_ID)" + + " INNER JOIN M_Product p ON (lin.M_Product_ID=p.M_Product_ID)" + + " INNER JOIN C_DocType dt ON (hdr.C_DocType_ID=dt.C_DocType_ID AND dt.DocBaseType IN ('API','APC'))" + + " FULL JOIN M_MatchInv mi ON (lin.C_InvoiceLine_ID=mi.C_InvoiceLine_ID) " + + "WHERE hdr.DocStatus IN ('CO','CL')"); + m_groupBy = " GROUP BY hdr.C_Invoice_ID,hdr.DocumentNo,hdr.DateInvoiced,bp.Name,hdr.C_BPartner_ID," + + " lin.Line,lin.C_InvoiceLine_ID,p.Name,lin.M_Product_ID,lin.QtyInvoiced " + + "HAVING " + + (matched ? "0" : "lin.QtyInvoiced") + + "<>SUM(NVL(mi.Qty,0))"; + } + else if (display == MATCH_ORDER) + { + m_dateColumn = "hdr.DateOrdered"; + m_qtyColumn = "lin.QtyOrdered"; + m_sql.append("SELECT hdr.C_Order_ID,hdr.DocumentNo, hdr.DateOrdered, bp.Name,hdr.C_BPartner_ID," + + " lin.Line,lin.C_OrderLine_ID, p.Name,lin.M_Product_ID," + + " lin.QtyOrdered,SUM(COALESCE(mo.Qty,0)) " + + "FROM C_Order hdr" + + " INNER JOIN C_BPartner bp ON (hdr.C_BPartner_ID=bp.C_BPartner_ID)" + + " INNER JOIN C_OrderLine lin ON (hdr.C_Order_ID=lin.C_Order_ID)" + + " INNER JOIN M_Product p ON (lin.M_Product_ID=p.M_Product_ID)" + + " INNER JOIN C_DocType dt ON (hdr.C_DocType_ID=dt.C_DocType_ID AND dt.DocBaseType='POO')" + + " FULL JOIN M_MatchPO mo ON (lin.C_OrderLine_ID=mo.C_OrderLine_ID) " + + " WHERE " ) ; //[ 1876972 ] Can't match partially matched PO with an unmatched receipt SOLVED BY BOJANA, AGENDA_GM + m_linetype = new StringBuffer(); + m_linetype.append( matchToType == MATCH_SHIPMENT ? "M_InOutLine_ID" : "C_InvoiceLine_ID") ; + if ( matched ) { + m_sql.append( " mo." + m_linetype + " IS NOT NULL " ) ; + } else { + m_sql.append( " ( mo." + m_linetype + " IS NULL OR " + + " (lin.QtyOrdered <> (SELECT sum(mo1.Qty) AS Qty" + + " FROM m_matchpo mo1 WHERE " + + " mo1.C_ORDERLINE_ID=lin.C_ORDERLINE_ID AND " + + " hdr.C_ORDER_ID=lin.C_ORDER_ID AND " + + " mo1." + m_linetype + + " IS NOT NULL group by mo1.C_ORDERLINE_ID))) " ); + } + m_sql.append( " AND hdr.DocStatus IN ('CO','CL')" ); + m_groupBy = " GROUP BY hdr.C_Order_ID,hdr.DocumentNo,hdr.DateOrdered,bp.Name,hdr.C_BPartner_ID," + + " lin.Line,lin.C_OrderLine_ID,p.Name,lin.M_Product_ID,lin.QtyOrdered " + + "HAVING " + + (matched ? "0" : "lin.QtyOrdered") + + "<>SUM(COALESCE(mo.Qty,0))"; + } + else // Shipment + { + m_dateColumn = "hdr.MovementDate"; + m_qtyColumn = "lin.MovementQty"; + m_sql.append("SELECT hdr.M_InOut_ID,hdr.DocumentNo, hdr.MovementDate, bp.Name,hdr.C_BPartner_ID," + + " lin.Line,lin.M_InOutLine_ID, p.Name,lin.M_Product_ID," + + " lin.MovementQty,SUM(NVL(m.Qty,0)) " + + "FROM M_InOut hdr" + + " INNER JOIN C_BPartner bp ON (hdr.C_BPartner_ID=bp.C_BPartner_ID)" + + " INNER JOIN M_InOutLine lin ON (hdr.M_InOut_ID=lin.M_InOut_ID)" + + " INNER JOIN M_Product p ON (lin.M_Product_ID=p.M_Product_ID)" + + " INNER JOIN C_DocType dt ON (hdr.C_DocType_ID = dt.C_DocType_ID AND dt.DocBaseType='MMR')" + + " FULL JOIN ") + .append(matchToType == MATCH_ORDER ? "M_MatchPO" : "M_MatchInv") + .append(" m ON (lin.M_InOutLine_ID=m.M_InOutLine_ID) " + + "WHERE hdr.DocStatus IN ('CO','CL')"); + m_groupBy = " GROUP BY hdr.M_InOut_ID,hdr.DocumentNo,hdr.MovementDate,bp.Name,hdr.C_BPartner_ID," + + " lin.Line,lin.M_InOutLine_ID,p.Name,lin.M_Product_ID,lin.MovementQty " + + "HAVING " + + (matched ? "0" : "lin.MovementQty") + + "<>SUM(NVL(m.Qty,0))"; + } + // Log.trace(7, "VMatch.tableInit", m_sql + "\n" + m_groupBy); + } // tableInit + + + /** + * Fill the table using m_sql + * @param table table + */ + private void tableLoad (WListbox table) + { + // log.finest(m_sql + " - " + m_groupBy); + String sql = MRole.getDefault().addAccessSQL( + m_sql.toString(), "hdr", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO) + + m_groupBy; + log.finest(sql); + try + { + Statement stmt = DB.createStatement(); + ResultSet rs = stmt.executeQuery(sql); + table.loadTable(rs); + stmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + } // tableLoad + + /** + * Create Matching Record + * @param invoice true if matching invoice false if matching PO + * @param M_InOutLine_ID shipment line + * @param Line_ID C_InvoiceLine_ID or C_OrderLine_ID + * @param qty quantity + * @return true if created + */ + private boolean createMatchRecord (boolean invoice, int M_InOutLine_ID, int Line_ID, + BigDecimal qty) + { + if (qty.compareTo(Env.ZERO) == 0) + return true; + log.fine("IsInvoice=" + invoice + + ", M_InOutLine_ID=" + M_InOutLine_ID + ", Line_ID=" + Line_ID + + ", Qty=" + qty); + // + boolean success = false; + MInOutLine sLine = new MInOutLine (Env.getCtx(), M_InOutLine_ID, null); + if (invoice) // Shipment - Invoice + { + // Update Invoice Line + MInvoiceLine iLine = new MInvoiceLine (Env.getCtx(), Line_ID, null); + iLine.setM_InOutLine_ID(M_InOutLine_ID); + if (sLine.getC_OrderLine_ID() != 0) + iLine.setC_OrderLine_ID(sLine.getC_OrderLine_ID()); + iLine.save(); + // Create Shipment - Invoice Link + if (iLine.getM_Product_ID() != 0) + { + MMatchInv match = new MMatchInv (iLine, null, qty); + match.setM_InOutLine_ID(M_InOutLine_ID); + if (match.save()) + success = true; + else + log.log(Level.SEVERE, "Inv Match not created: " + match); + } + else + success = true; + // Create PO - Invoice Link = corrects PO + if (iLine.getC_OrderLine_ID() != 0 && iLine.getM_Product_ID() != 0) + { + MMatchPO matchPO = MMatchPO.create(iLine, sLine, null, qty); + matchPO.setC_InvoiceLine_ID(iLine); + matchPO.setM_InOutLine_ID(M_InOutLine_ID); + if (!matchPO.save()) + log.log(Level.SEVERE, "PO(Inv) Match not created: " + matchPO); + } + } + else // Shipment - Order + { + // Update Shipment Line + sLine.setC_OrderLine_ID(Line_ID); + sLine.save(); + // Update Order Line + MOrderLine oLine = new MOrderLine(Env.getCtx(), Line_ID, null); + if (oLine.get_ID() != 0) // other in MInOut.completeIt + { + oLine.setQtyReserved(oLine.getQtyReserved().subtract(qty)); + if(!oLine.save()) + log.severe("QtyReserved not updated - C_OrderLine_ID=" + Line_ID); + } + + // Create PO - Shipment Link + if (sLine.getM_Product_ID() != 0) + { + MMatchPO match = new MMatchPO (sLine, null, qty); + if (!match.save()) + log.log(Level.SEVERE, "PO Match not created: " + match); + else + { + success = true; + // Correct Ordered Qty for Stocked Products (see MOrder.reserveStock / MInOut.processIt) + if (sLine.getProduct() != null && sLine.getProduct().isStocked()) + success = MStorage.add (Env.getCtx(), sLine.getM_Warehouse_ID(), + sLine.getM_Locator_ID(), + sLine.getM_Product_ID(), + sLine.getM_AttributeSetInstance_ID(), oLine.getM_AttributeSetInstance_ID(), + null, null, qty.negate(), null); + } + } + else + success = true; + } + return success; + } // createMatchRecord + +} // VMatch diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WPayment.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WPayment.java index ed85c62661..21350478f5 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WPayment.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WPayment.java @@ -1,1931 +1,1531 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ - -/** - * 2007, Modified by Posterita Ltd. - */ - -package org.adempiere.webui.apps.form; - -import java.math.BigDecimal; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.text.DecimalFormat; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.logging.Level; - -import org.adempiere.webui.component.Button; -import org.adempiere.webui.component.Datebox; -import org.adempiere.webui.component.Label; -import org.adempiere.webui.component.ListItem; -import org.adempiere.webui.component.Listbox; -import org.adempiere.webui.component.Textbox; -import org.adempiere.webui.component.VerticalBox; -import org.adempiere.webui.component.Window; -import org.adempiere.webui.editor.WButtonEditor; -import org.adempiere.webui.window.FDialog; -import org.compiere.model.GridTab; -import org.compiere.model.MCash; -import org.compiere.model.MCashLine; -import org.compiere.model.MConversionRate; -import org.compiere.model.MInvoice; -import org.compiere.model.MOrder; -import org.compiere.model.MPayment; -import org.compiere.model.MPaymentValidate; -import org.compiere.model.MRole; -import org.compiere.model.X_C_Order; -import org.compiere.process.DocAction; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.DisplayType; -import org.compiere.util.Env; -import org.compiere.util.KeyNamePair; -import org.compiere.util.Msg; -import org.compiere.util.TimeUtil; -import org.compiere.util.ValueNamePair; -import org.zkoss.zk.ui.event.Event; -import org.zkoss.zk.ui.event.EventListener; -import org.zkoss.zk.ui.event.Events; -import org.zkoss.zul.Hbox; -import org.zkoss.zul.Separator; - -/** - * Display (and process) Payment Options. - *
- *  Payment Rule
- *  -B- Cash          (Date)          -> Cash Entry
- *  -P- Payment Term  (Term)
- *  -S- Check         (Routing, ..)   -> Payment Entry
- *  -K- CreditCard    (No)            -> Payment Entry
- *  -U- ACH Transfer  (Routing)       -> Payment Entry
- *
- *  When processing:
- *  - If an invoice is a S/K/U, but has no Payment Entry, it is changed to P
- *  - If an invoive is B and has no Cash Entry, it is created
- *  - An invoice is "Open" if it is "P" and no Payment
- *
- *  Entry:
- *  - If not processed, an invoice has no Cash or Payment entry
- *  - The entry is created, during "Online" and when Saving
- *
- *  Changes/Reversals:
- *  - existing Cash Entries are reversed and newly created
- *  - existing Payment Entries are not changed and then "hang there" and need to be allocated
- *  
- * - * @author Niraj Sohun - * Payment Rule : Based on VPayment - */ - -public class WPayment extends Window implements EventListener -{ - private static final long serialVersionUID = 1L; - - /** Window */ - private int m_WindowNo = 0; - - /** Tab */ - private GridTab m_mTab; - - // Data from Order/Invoice - private String m_DocStatus = null; - - /** Start Payment Rule */ - private String m_PaymentRule = ""; - - /** Start Payment Term */ - private int m_C_PaymentTerm_ID = 0; - - /** Start Acct Date */ - private Timestamp m_DateAcct = null; - - /** Start Payment */ - private int m_C_Payment_ID = 0; - - private MPayment m_mPayment = null; - private MPayment m_mPaymentOriginal = null; - - /** Start CashBook Line */ - private int m_C_CashLine_ID = 0; - - private MCashLine m_cashLine = null; - - /** Start CreditCard */ - private String m_CCType = ""; - - /** Start Bank Account */ - private int m_C_BankAccount_ID = 0; - - /** Start CashBook */ - private int m_C_CashBook_ID = 0; - - /** Is SOTrx */ - private boolean m_isSOTrx = true; - - /** Invoice Currency */ - private int m_C_Currency_ID = 0; - - private int m_AD_Client_ID = 0; - private int m_AD_Org_ID = 0; - private int m_C_BPartner_ID = 0; - - // Payment Amount - private BigDecimal m_Amount = Env.ZERO; - - private boolean m_initOK = false; - - /** Only allow changing Rule */ - private boolean m_onlyRule = false; - - private DecimalFormat m_Format = DisplayType.getNumberFormat(DisplayType.Amount); - - // EMU Currencies - private static Hashtable s_Currencies = null; - - private boolean m_needSave = false; - - /** Logger */ - private static CLogger log = CLogger.getCLogger(WPayment.class); - - /** Date Editor */ - Datebox bDateField = new Datebox(); - - private Textbox bAmountField = new Textbox(); - private Textbox sAmountField = new Textbox(); - private Textbox kAmountField = new Textbox(); - private Textbox kNumberField = new Textbox(); - private Textbox kExpField = new Textbox(); - private Textbox kApprovalField = new Textbox(); - private Textbox sRoutingField = new Textbox(); - private Textbox sNumberField = new Textbox(); - private Textbox sCheckField = new Textbox(); - private Textbox tRoutingField = new Textbox(); - private Textbox tNumberField = new Textbox(); - - private Label kStatus = new Label(); - private Label sStatus = new Label(); - private Label tStatus = new Label(); - private Label bCurrencyLabel = new Label(); - private Label sCurrencyLabel = new Label(); - private Label paymentLabel = new Label(); - private Label kNumberLabel = new Label(); - private Label kExpLabel = new Label(); - private Label kApprovalLabel = new Label(); - private Label kAmountLabel = new Label(); - private Label kTypeLabel = new Label(); - private Label tRoutingText = new Label(); - private Label tNumberText = new Label(); - private Label tAccountLabel = new Label(); - private Label sBankAccountLabel = new Label(); - private Label sAmountLabel = new Label(); - private Label sRoutingLabel = new Label(); - private Label sNumberLabel = new Label(); - private Label sCheckLabel = new Label(); - private Label pTermLabel = new Label(); - private Label bAmountLabel = new Label(); - private Label bDateLabel = new Label(); - private Label bCashBookLabel = new Label(); - - private Listbox kTypeCombo = new Listbox(); - private Listbox bCurrencyCombo = new Listbox(); - private Listbox sCurrencyCombo = new Listbox(); - private Listbox paymentCombo = new Listbox(); - private Listbox pTermCombo = new Listbox(); - private Listbox tAccountCombo = new Listbox(); - private Listbox sBankAccountCombo = new Listbox(); - private Listbox bCashBookCombo = new Listbox(); - - private Button kOnline = new Button(); - private Button sOnline = new Button(); - private Button btnOk = new Button(); - private Button btnCancel = new Button(); - private Button tOnline = new Button(); - - private VerticalBox mainPanel = new VerticalBox(); - private Hbox northPanel = new Hbox(); - private VerticalBox centerPanel = new VerticalBox(); - private VerticalBox kPanel = new VerticalBox(); - private VerticalBox tPanel = new VerticalBox(); - private VerticalBox sPanel = new VerticalBox(); - private Hbox pPanel = new Hbox(); - private VerticalBox bPanel = new VerticalBox(); - - /** - * Constructor - * - * @param WindowNo owning window - * @param mTab owning tab - * @param button button with access information - */ - - public WPayment (int WindowNo, GridTab mTab, WButtonEditor button) - { - super(); - - m_WindowNo = WindowNo; - m_isSOTrx = "Y".equals(Env.getContext(Env.getCtx(), WindowNo, "IsSOTrx")); - m_mTab = mTab; - - try - { - //bDateField = new WDateEditor("DateAcc", "", false, false, true); - bDateField.setValue(new Date(System.currentTimeMillis())); - - jbInit(); - m_initOK = dynInit(button); // Null Pointer if order/invoice not saved yet - } - catch(Exception ex) - { - log.log(Level.SEVERE, "WPayment", ex); - m_initOK = false; - } - - this.setVisible(true); - //show - } // VPayment - - /** - * Static Init - * @throws Exception - */ - - private void jbInit() throws Exception - { - this.setBorder("normal"); - this.setWidth("400px"); - this.setTitle("Payment"); - this.setClosable(true); - this.appendChild(mainPanel); - - centerPanel.setWidth("100%"); - - mainPanel.setWidth("100%"); - mainPanel.appendChild(northPanel); - mainPanel.appendChild(new Separator()); - mainPanel.appendChild(centerPanel); - - paymentLabel.setValue(Msg.translate(Env.getCtx(), "PaymentRule")); - - paymentCombo.setRows(0); - paymentCombo.setMold("select"); - paymentCombo.addEventListener(Events.ON_SELECT, this); - - northPanel.setWidth("100%"); - northPanel.setWidths("40%, 60%"); - northPanel.appendChild(paymentLabel); - northPanel.appendChild(paymentCombo); - - // Credit Card - - kPanel.setWidth("100%"); - - kTypeLabel.setValue(Msg.translate(Env.getCtx(), "CreditCardType")); - kNumberLabel.setValue(Msg.translate(Env.getCtx(), "CreditCardNumber")); - kExpLabel.setValue(Msg.getMsg(Env.getCtx(), "Expires")); - kApprovalLabel.setValue(Msg.translate(Env.getCtx(), "VoiceAuthCode")); - kAmountLabel.setValue(Msg.getMsg(Env.getCtx(), "Amount")); - kAmountField.setText(""); - kOnline.setLabel(Msg.getMsg(Env.getCtx(), "Online")); - kOnline.addEventListener(Events.ON_CLICK, this); - kStatus.setValue(" "); - centerPanel.appendChild(kPanel); - - Hbox boxKType = new Hbox(); - - kTypeCombo.setRows(0); - kTypeCombo.setMold("select"); - kTypeCombo.addEventListener(Events.ON_SELECT, this); - - boxKType.setWidth("100%"); - boxKType.setWidths("50%, 50%"); - boxKType.appendChild(kTypeLabel); - boxKType.appendChild(kTypeCombo); - kPanel.appendChild(boxKType); - - Hbox boxKNumber = new Hbox(); - boxKNumber.setWidth("100%"); - boxKNumber.setWidths("50%, 50%"); - boxKNumber.appendChild(kNumberLabel); - boxKNumber.appendChild(kNumberField); - kPanel.appendChild(boxKNumber); - - Hbox boxKExp = new Hbox(); - boxKExp.setWidth("100%"); - boxKExp.setWidths("50%, 50%"); - boxKExp.appendChild(kExpLabel); - boxKExp.appendChild(kExpField); - kPanel.appendChild(boxKExp); - - Hbox boxKAmount = new Hbox(); - boxKAmount.setWidth("100%"); - boxKAmount.setWidths("50%, 50%"); - boxKAmount.appendChild(kAmountLabel); - boxKAmount.appendChild(kAmountField); - kPanel.appendChild(boxKAmount); - - Hbox boxKApproval = new Hbox(); - boxKApproval.setWidth("100%"); - boxKApproval.setWidths("50%, 50%"); - boxKApproval.appendChild(kApprovalLabel); - boxKApproval.appendChild(kApprovalField); - kPanel.appendChild(boxKApproval); - - kPanel.appendChild(kStatus); - kPanel.appendChild(kOnline); - - // Direct Debit/Credit - - tPanel.setWidth("100%"); - - tAccountLabel.setValue(Msg.translate(Env.getCtx(), "C_BP_BankAccount_ID")); - //tRoutingField.setColumns(8); - //tNumberField.setColumns(10); - tRoutingText.setValue(Msg.translate(Env.getCtx(), "RoutingNo")); - tNumberText.setValue(Msg.translate(Env.getCtx(), "AccountNo")); - tOnline.setLabel(Msg.getMsg(Env.getCtx(), "Online")); - tOnline.addEventListener(Events.ON_CLICK, this); - tStatus.setValue(" "); - centerPanel.appendChild(tPanel); - - Hbox boxTAccount = new Hbox(); - - tAccountCombo.setRows(0); - tAccountCombo.setMold("select"); - tAccountCombo.addEventListener(Events.ON_SELECT, this); - - boxTAccount.setWidth("100%"); - boxTAccount.setWidths("45%, 55%"); - boxTAccount.appendChild(tAccountLabel); - boxTAccount.appendChild(tAccountCombo); - tPanel.appendChild(boxTAccount); - - Hbox boxTRouting = new Hbox(); - boxTRouting.setWidth("100%"); - boxTRouting.setWidths("45%, 55%"); - boxTRouting.appendChild(tRoutingText); - boxTRouting.appendChild(tRoutingField); - tPanel.appendChild(boxTRouting); - - Hbox boxTNumber = new Hbox(); - boxTNumber.setWidth("100%"); - boxTNumber.setWidths("45%, 55%"); - boxTNumber.appendChild(tNumberText); - boxTNumber.appendChild(tNumberField); - tPanel.appendChild(boxTNumber); - - tPanel.appendChild(tStatus); - tPanel.appendChild(tOnline); - - // Cheque - - sPanel.setWidth("100%"); - - sBankAccountLabel.setValue(Msg.translate(Env.getCtx(), "C_BankAccount_ID")); - sAmountLabel.setValue(Msg.getMsg(Env.getCtx(), "Amount")); - sAmountField.setText(""); - sRoutingLabel.setValue(Msg.translate(Env.getCtx(), "RoutingNo")); - sNumberLabel.setValue(Msg.translate(Env.getCtx(), "AccountNo")); - sCheckLabel.setValue(Msg.translate(Env.getCtx(), "CheckNo")); - //sCheckField.setColumns(8); - sCurrencyLabel.setValue(Msg.translate(Env.getCtx(), "C_Currency_ID")); - //sNumberField.setPreferredSize(new Dimension(100, 21)); - //sRoutingField.setPreferredSize(new Dimension(70, 21)); - sStatus.setValue(" "); - sOnline.setLabel(Msg.getMsg(Env.getCtx(), "Online")); - sOnline.addEventListener(Events.ON_CLICK, this); - centerPanel.appendChild(sPanel); - - Hbox boxSBankAccount = new Hbox(); - - sBankAccountCombo.setRows(0); - sBankAccountCombo.setMold("select"); - sBankAccountCombo.addEventListener(Events.ON_SELECT, this); - - boxSBankAccount.setWidth("100%"); - boxSBankAccount.setWidths("40%, 60%"); - boxSBankAccount.appendChild(sBankAccountLabel); - boxSBankAccount.appendChild(sBankAccountCombo); - sPanel.appendChild(boxSBankAccount); - - Hbox boxSCurrency = new Hbox(); - - sCurrencyCombo.setRows(0); - sCurrencyCombo.setMold("select"); - sCurrencyCombo.addEventListener(Events.ON_SELECT, this); - - boxSCurrency.setWidth("100%"); - boxSCurrency.setWidths("40%, 60%"); - boxSCurrency.appendChild(sCurrencyLabel); - boxSCurrency.appendChild(sCurrencyCombo); - sPanel.appendChild(boxSCurrency); - - Hbox boxSAmount = new Hbox(); - boxSAmount.setWidth("100%"); - boxSAmount.setWidths("40%, 60%"); - boxSAmount.appendChild(sAmountLabel); - boxSAmount.appendChild(sAmountField); - sPanel.appendChild(boxSAmount); - - Hbox boxSRouting = new Hbox(); - boxSRouting.setWidth("100%"); - boxSRouting.setWidths("40%, 60%"); - boxSRouting.appendChild(sRoutingLabel); - boxSRouting.appendChild(sRoutingField); - sPanel.appendChild(boxSRouting); - - Hbox boxSNumber = new Hbox(); - boxSNumber.setWidth("100%"); - boxSNumber.setWidths("40%, 60%"); - boxSNumber.appendChild(sNumberLabel); - boxSNumber.appendChild(sNumberField); - sPanel.appendChild(boxSNumber); - - Hbox boxSCheck = new Hbox(); - boxSCheck.setWidth("100%"); - boxSCheck.setWidths("40%, 60%"); - boxSCheck.appendChild(sCheckLabel); - boxSCheck.appendChild(sCheckField); - sPanel.appendChild(boxSCheck); - - sPanel.appendChild(sOnline); - sPanel.appendChild(sStatus); - - // Cash - - pPanel.setWidth("100%"); - pPanel.setWidths("40%, 60%"); - - pTermLabel.setValue(Msg.translate(Env.getCtx(), "C_PaymentTerm_ID")); - centerPanel.appendChild(pPanel); - - pTermCombo.setRows(0); - pTermCombo.setMold("select"); - pTermCombo.addEventListener(Events.ON_SELECT, this); - - pPanel.appendChild(pTermLabel); - pPanel.appendChild(pTermCombo); - - // - - bPanel.setWidth("100%"); - - bCashBookLabel.setValue(Msg.translate(Env.getCtx(), "C_CashBook_ID")); - bCurrencyLabel.setValue(Msg.translate(Env.getCtx(), "C_Currency_ID")); - bAmountLabel.setValue(Msg.getMsg(Env.getCtx(), "Amount")); - bAmountField.setText(""); - bDateLabel.setValue(Msg.translate(Env.getCtx(), "DateAcct")); - centerPanel.appendChild(bPanel); - - Hbox boxBCashBook = new Hbox(); - - bCashBookCombo.setRows(0); - bCashBookCombo.setMold("select"); - bCashBookCombo.addEventListener(Events.ON_SELECT, this); - - boxBCashBook.setWidth("100%"); - boxBCashBook.setWidths("40%, 60%"); - boxBCashBook.appendChild(bCashBookLabel); - boxBCashBook.appendChild(bCashBookCombo); - bPanel.appendChild(boxBCashBook); - - Hbox boxBCurrency = new Hbox(); - - bCurrencyCombo.setRows(0); - bCurrencyCombo.setMold("select"); - bCurrencyCombo.addEventListener(Events.ON_SELECT, this); - - boxBCurrency.setWidth("100%"); - boxBCurrency.setWidths("40%, 60%"); - boxBCurrency.appendChild(bCurrencyLabel); - boxBCurrency.appendChild(bCurrencyCombo); - bPanel.appendChild(boxBCurrency); - - Hbox boxBDate = new Hbox(); - boxBDate.setWidth("100%"); - boxBDate.setWidths("40%, 60%"); - boxBDate.appendChild(bDateLabel); - boxBDate.appendChild(bDateField); - bPanel.appendChild(boxBDate); - - Hbox boxBAmount = new Hbox(); - boxBAmount.setWidth("100%"); - boxBAmount.setWidths("40%, 60%"); - boxBAmount.appendChild(bAmountLabel); - boxBAmount.appendChild(bAmountField); - bPanel.appendChild(boxBAmount); - - Hbox boxButtons = new Hbox(); - - btnCancel.setImage("/images/Cancel24.png"); - btnCancel.addEventListener(Events.ON_CLICK, this); - btnOk.setImage("/images/Ok24.png"); - btnOk.addEventListener(Events.ON_CLICK, this); - - boxButtons.appendChild(btnCancel); - boxButtons.appendChild(btnOk); - mainPanel.appendChild(new Separator()); - mainPanel.appendChild(boxButtons); - } - - /************************************************************************** - * Dynamic Init. - * B (Cash) (Currency) - * K (CreditCard) Type, Number, Exp, Approval - * L (DirectDebit) BPartner_Bank - * P (PaymentTerm) PaymentTerm - * S (Check) (Currency) CheckNo, Routing - * - * Currencies are shown, if member of EMU - * @param button payment type button - * @return true if init OK - * @throws Exception - */ - - private boolean dynInit (WButtonEditor button) throws Exception - { - m_DocStatus = (String)m_mTab.getValue("DocStatus"); - log.config(m_DocStatus); - - if (m_mTab.getValue("C_BPartner_ID") == null) - { - FDialog.error(0, this, "SaveErrorRowNotFound"); - return false; - } - - // Is the Trx posted? - // String Posted = (String)m_mTab.getValue("Posted"); - // if (Posted != null && Posted.equals("Y")) - // return false; - - // DocStatus - - m_DocStatus = (String)m_mTab.getValue("DocStatus"); - - if (m_DocStatus == null) - m_DocStatus = ""; - - // Is the Trx closed? Reversed / Voided / Cloased - - if (m_DocStatus.equals("RE") || m_DocStatus.equals("VO") || m_DocStatus.equals("CL")) - return false; - - // Document is not complete - allow to change the Payment Rule only - if (m_DocStatus.equals("CO") || m_DocStatus.equals("WP") ) - m_onlyRule = false; - else - m_onlyRule = true; - - // PO only Rule - - if (!m_onlyRule // Only order has Warehouse - && !m_isSOTrx && m_mTab.getValue("M_Warehouse_ID") != null) - m_onlyRule = true; - - centerPanel.setVisible(!m_onlyRule); - - // Amount - - m_Amount = (BigDecimal)m_mTab.getValue("GrandTotal"); - - if (!m_onlyRule && m_Amount.compareTo(Env.ZERO) == 0) - { - FDialog.error(m_WindowNo, this, "PaymentZero"); - return false; - } - - bAmountField.setText(m_Format.format(m_Amount)); - sAmountField.setText(m_Format.format(m_Amount)); - kAmountField.setText(m_Format.format(m_Amount)); - - /** - * Get Data from Grid - */ - - m_AD_Client_ID = ((Integer)m_mTab.getValue("AD_Client_ID")).intValue(); - m_AD_Org_ID = ((Integer)m_mTab.getValue("AD_Org_ID")).intValue(); - m_C_BPartner_ID = ((Integer)m_mTab.getValue("C_BPartner_ID")).intValue(); - m_PaymentRule = (String)m_mTab.getValue("PaymentRule"); - m_C_Currency_ID = ((Integer)m_mTab.getValue("C_Currency_ID")).intValue(); - m_DateAcct = (Timestamp)m_mTab.getValue("DateAcct"); - - if (m_mTab.getValue("C_PaymentTerm_ID") != null) - m_C_PaymentTerm_ID = ((Integer)m_mTab.getValue("C_PaymentTerm_ID")).intValue(); - - // Existing Payment - - if (m_mTab.getValue("C_Payment_ID") != null) - { - m_C_Payment_ID = ((Integer)m_mTab.getValue("C_Payment_ID")).intValue(); - - if (m_C_Payment_ID != 0) - { - m_mPayment = new MPayment(Env.getCtx(), m_C_Payment_ID, null); - m_mPaymentOriginal = new MPayment(Env.getCtx(), m_C_Payment_ID, null); // full copy - - // CreditCard - m_CCType = m_mPayment.getCreditCardType(); - kNumberField.setText(m_mPayment.getCreditCardNumber()); - kExpField.setText(m_mPayment.getCreditCardExp(null)); - kApprovalField.setText(m_mPayment.getVoiceAuthCode()); - kStatus.setValue(m_mPayment.getR_PnRef()); - kAmountField.setText(m_Format.format(m_mPayment.getPayAmt())); - - // if approved/paid, don't let it change - - kTypeCombo.setEnabled(!m_mPayment.isApproved()); - kNumberField.setEnabled(!m_mPayment.isApproved()); - kExpField.setEnabled(!m_mPayment.isApproved()); - kApprovalField.setEnabled(!m_mPayment.isApproved()); - kOnline.setEnabled(!m_mPayment.isApproved()); - kAmountField.setEnabled(!m_mPayment.isApproved()); - - // Check - - m_C_BankAccount_ID = m_mPayment.getC_BankAccount_ID(); - sRoutingField.setText(m_mPayment.getRoutingNo()); - sNumberField.setText(m_mPayment.getAccountNo()); - sCheckField.setText(m_mPayment.getCheckNo()); - sStatus.setValue(m_mPayment.getR_PnRef()); - sAmountField.setText(m_Format.format(m_mPayment.getPayAmt())); - - // Transfer - - tRoutingField.setText(m_mPayment.getRoutingNo()); - tNumberField.setText(m_mPayment.getAccountNo()); - tStatus.setValue(m_mPayment.getR_PnRef()); - } - } - if (m_mPayment == null) - { - m_mPayment = new MPayment (Env.getCtx (), 0, null); - m_mPayment.setAD_Org_ID(m_AD_Org_ID); - m_mPayment.setAmount (m_C_Currency_ID, m_Amount); - } - - // Existing Cashbook entry - - m_cashLine = null; - m_C_CashLine_ID = 0; - - if (m_mTab.getValue("C_CashLine_ID") != null) - { - m_C_CashLine_ID = ((Integer)m_mTab.getValue("C_CashLine_ID")).intValue(); - - if (m_C_CashLine_ID == 0) - m_cashLine = null; - else - { - m_cashLine = new MCashLine (Env.getCtx(), m_C_CashLine_ID, null); - m_DateAcct = m_cashLine.getStatementDate(); - bAmountField.setText(m_cashLine.getAmount().toString()); - } - } - - // Accounting Date - - bDateField.setValue(m_DateAcct); - - if (s_Currencies == null) - loadCurrencies(); - - // Is the currency an EMU currency? - - Integer C_Currency_ID = new Integer(m_C_Currency_ID); - - if (s_Currencies.containsKey(C_Currency_ID)) - { - Enumeration en = s_Currencies.keys(); - while (en.hasMoreElements()) - { - Object key = en.nextElement(); - bCurrencyCombo.appendItem(key.toString(), s_Currencies.get(key)); - sCurrencyCombo.appendItem(key.toString(), s_Currencies.get(key)); - } - - ListItem listitem = new ListItem(); - listitem.setValue(s_Currencies.get(C_Currency_ID)); - - sCurrencyCombo.addEventListener(Events.ON_SELECT, this); - sCurrencyCombo.setSelectedItem(listitem); - - bCurrencyCombo.addEventListener(Events.ON_SELECT, this); - bCurrencyCombo.setSelectedItem(listitem); - } - else // No EMU Currency - { - bCurrencyLabel.setVisible(false); // Cash - bCurrencyCombo.setVisible(false); - sCurrencyLabel.setVisible(false); // Check - sCurrencyCombo.setVisible(false); - } - - /** - * Payment Combo - */ - - if (m_PaymentRule == null) - m_PaymentRule = ""; - - ValueNamePair vp = null; - HashMap values = button.getValues(); - Object[] a = values.keySet().toArray(); - - for (int i = 0; i < a.length; i++) - { - String PaymentRule = (String)a[i]; // used for Panel selection - - if (X_C_Order.PAYMENTRULE_DirectDebit.equals(PaymentRule) // SO - && !m_isSOTrx) - continue; - else if (X_C_Order.PAYMENTRULE_DirectDeposit.equals(PaymentRule) // PO - && m_isSOTrx) - continue; - - ValueNamePair pp = new ValueNamePair(PaymentRule, (String)values.get(a[i])); - paymentCombo.appendItem(pp.getName(), pp); - - if (PaymentRule.toString().equals(m_PaymentRule)) // to select - vp = pp; - } - - // Set PaymentRule - - paymentCombo.addEventListener(Events.ON_SELECT, this); - - if (vp != null) - { - for (int i = 0; i < paymentCombo.getItemCount(); i++) - { - ListItem item = paymentCombo.getItemAtIndex(i); - ValueNamePair v = (ValueNamePair)item.getValue(); - - if (v == vp) - { - paymentCombo.setSelectedIndex(i); - break; - } - } - } - - Event evt = new Event(Events.ON_SELECT, paymentCombo); - onEvent(evt); - - /** - * Load Payment Terms - */ - - String SQL = MRole.getDefault().addAccessSQL( - "SELECT C_PaymentTerm_ID, Name FROM C_PaymentTerm WHERE IsActive='Y' ORDER BY Name", - "C_PaymentTerm", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); - - KeyNamePair kp = null; - - try - { - PreparedStatement pstmt = DB.prepareStatement(SQL, null); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - int key = rs.getInt(1); - String name = rs.getString(2); - KeyNamePair pp = new KeyNamePair(key, name); - pTermCombo.appendItem(pp.getName(), pp); - - if (key == m_C_PaymentTerm_ID) - kp = pp; - } - rs.close(); - pstmt.close(); - } - catch (SQLException ept) - { - log.log(Level.SEVERE, SQL, ept); - } - - // Set Selection - - if (kp != null) - { - for (int i = 0; i < pTermCombo.getItemCount(); i++) - { - ListItem item = pTermCombo.getItemAtIndex(i); - KeyNamePair k = (KeyNamePair)item.getValue(); - - if (k == kp) - { - pTermCombo.setSelectedIndex(i); - break; - } - } - } - - /** - * Load Accounts - */ - - SQL = "SELECT a.C_BP_BankAccount_ID, NVL(b.Name, ' ')||a.AccountNo AS Acct " - + "FROM C_BP_BankAccount a,C_Bank b " - + "WHERE C_BPartner_ID=? AND a.IsActive='Y'"; - - kp = null; - - try - { - PreparedStatement pstmt = DB.prepareStatement(SQL, null); - pstmt.setInt(1, m_C_BPartner_ID); - ResultSet rs = pstmt.executeQuery(); - - while (rs.next()) - { - int key = rs.getInt(1); - String name = rs.getString(2); - KeyNamePair pp = new KeyNamePair(key, name); - tAccountCombo.appendItem(pp.getName(), pp); - // kp = pp; - } - rs.close(); - pstmt.close(); - } - catch (SQLException eac) - { - log.log(Level.SEVERE, SQL, eac); - } - - // Set Selection - - if (kp != null) - { - for (int i = 0; i < tAccountCombo.getItemCount(); i++) - { - ListItem item = tAccountCombo.getItemAtIndex(i); - KeyNamePair k = (KeyNamePair)item.getValue(); - - if (k == kp) - { - tAccountCombo.setSelectedIndex(i); - break; - } - } - } - - /** - * Load Credit Cards - */ - - ValueNamePair[] ccs = m_mPayment.getCreditCards(); - vp = null; - - for (int i = 0; i < ccs.length; i++) - { - kTypeCombo.appendItem(ccs[i].getName(), ccs[i]); - - if (ccs[i].getValue().equals(m_CCType)) - vp = ccs[i]; - } - - // Set Selection - - if (vp != null) - { - for (int i = 0; i < kTypeCombo.getItemCount(); i++) - { - ListItem item = kTypeCombo.getItemAtIndex(i); - ValueNamePair v = (ValueNamePair)item.getValue(); - - if (v == vp) - { - kTypeCombo.setSelectedIndex(i); - break; - } - } - } - - /** - * Load Bank Accounts - */ - - SQL = MRole.getDefault().addAccessSQL( - "SELECT C_BankAccount_ID, Name || ' ' || AccountNo, IsDefault " - + "FROM C_BankAccount ba" - + " INNER JOIN C_Bank b ON (ba.C_Bank_ID=b.C_Bank_ID) " - + "WHERE b.IsActive='Y'", - "ba", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO); - - kp = null; - - try - { - PreparedStatement pstmt = DB.prepareStatement(SQL, null); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - int key = rs.getInt(1); - String name = rs.getString(2); - KeyNamePair pp = new KeyNamePair(key, name); - sBankAccountCombo.appendItem(pp.getName(), pp); - - if (key == m_C_BankAccount_ID) - kp = pp; - - if (kp == null && rs.getString(3).equals("Y")) // Default - kp = pp; - } - rs.close(); - pstmt.close(); - } - catch (SQLException ept) - { - log.log(Level.SEVERE, SQL, ept); - } - - // Set Selection - - if (kp != null) - { - for (int i = 0; i < sBankAccountCombo.getItemCount(); i++) - { - ListItem item = sBankAccountCombo.getItemAtIndex(i); - KeyNamePair k = (KeyNamePair)item.getValue(); - - if (k == kp) - { - sBankAccountCombo.setSelectedIndex(i); - break; - } - } - } - - /** - * Load Cash Books - */ - - SQL = MRole.getDefault().addAccessSQL( - "SELECT C_CashBook_ID, Name, AD_Org_ID FROM C_CashBook WHERE IsActive='Y'", - "C_CashBook", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); - - kp = null; - - try - { - PreparedStatement pstmt = DB.prepareStatement(SQL, null); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - int key = rs.getInt(1); - String name = rs.getString(2); - KeyNamePair pp = new KeyNamePair(key, name); - bCashBookCombo.appendItem(pp.getName(), pp); - - if (key == m_C_CashBook_ID) - kp = pp; - - if (kp == null && key == m_AD_Org_ID) // Default Org - kp = pp; - } - rs.close(); - pstmt.close(); - } - catch (SQLException epc) - { - log.log(Level.SEVERE, SQL, epc); - } - - // Set Selection - - if (kp != null) - { - for (int i = 0; i < bCashBookCombo.getItemCount(); i++) - { - ListItem item = bCashBookCombo.getItemAtIndex(i); - KeyNamePair k = (KeyNamePair)item.getValue(); - - if (k == kp) - { - bCashBookCombo.setSelectedIndex(i); - break; - } - } - - if (m_C_CashBook_ID == 0) - m_C_CashBook_ID = kp.getKey(); // set to default to avoid 'cashbook changed' message - } - - return true; - } // dynInit - - /** - * Init OK to be able to make changes? - * @return true if init OK - */ - - public boolean isInitOK() - { - return m_initOK; - } // isInitOK - - /** - * Fill s_Currencies with EMU currencies - */ - - private void loadCurrencies() - { - s_Currencies = new Hashtable(12); // Currenly only 10+1 - String SQL = "SELECT C_Currency_ID, ISO_Code FROM C_Currency " - + "WHERE (IsEMUMember='Y' AND EMUEntryDate " + newPaymentRule); - - // We had a CashBook Entry - - if (m_PaymentRule.equals(X_C_Order.PAYMENTRULE_Cash)) - { - log.fine("Old Cash - " + m_cashLine); - - if (m_cashLine != null) - { - MCashLine cl = m_cashLine.createReversal(); - - if (cl.save()) - log.config( "CashCancelled"); - else - FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCancelled"); - } - newC_CashLine_ID = 0; // reset - } - - // We had a change in Payment type (e.g. Check to CC) - - else if ("KTSD".indexOf(m_PaymentRule) != -1 && "KTSD".indexOf(newPaymentRule) != -1 && m_mPaymentOriginal != null) - { - log.fine("Old Payment(1) - " + m_mPaymentOriginal); - m_mPaymentOriginal.setDocAction(DocAction.ACTION_Reverse_Correct); - boolean ok = m_mPaymentOriginal.processIt(DocAction.ACTION_Reverse_Correct); - m_mPaymentOriginal.save(); - - if (ok) - log.info( "Payment Canecelled - " + m_mPaymentOriginal); - else - FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCancelled " + m_mPaymentOriginal.getDocumentNo()); - - m_mPayment.resetNew(); - } - // We had a Payment and something else (e.g. Check to Cash) - - else if ("KTSD".indexOf(m_PaymentRule) != -1 && "KTSD".indexOf(newPaymentRule) == -1) - { - log.fine("Old Payment(2) - " + m_mPaymentOriginal); - - if (m_mPaymentOriginal != null) - { - m_mPaymentOriginal.setDocAction(DocAction.ACTION_Reverse_Correct); - boolean ok = m_mPaymentOriginal.processIt(DocAction.ACTION_Reverse_Correct); - m_mPaymentOriginal.save(); - - if (ok) // Cancel Payment - { - log.fine("PaymentCancelled " + m_mPayment.getDocumentNo ()); - m_mTab.getTableModel().dataSave(true); - m_mPayment.resetNew(); - m_mPayment.setAmount(m_C_Currency_ID, m_Amount); - } - else - FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCancelled " + m_mPayment.getDocumentNo()); - } - } - } - - // Get Order and optionally Invoice - - int C_Order_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Order_ID"); - int C_Invoice_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Invoice_ID"); - if (C_Invoice_ID == 0 && m_DocStatus.equals("CO")) - C_Invoice_ID = getInvoiceID (C_Order_ID); - - // Amount sign negative, if ARC (Credit Memo) or API (AP Invoice) - - boolean negateAmt = false; - MInvoice invoice = null; - - if (C_Invoice_ID != 0) - { - invoice = new MInvoice (Env.getCtx(), C_Invoice_ID, null); - negateAmt = invoice.isCreditMemo(); - } - - MOrder order = null; - - if (invoice == null && C_Order_ID != 0) - order = new MOrder (Env.getCtx(), C_Order_ID, null); - - BigDecimal payAmount = m_Amount; - - if (negateAmt) - payAmount = m_Amount.negate(); - - // Info - - log.config("C_Order_ID=" + C_Order_ID + ", C_Invoice_ID=" + C_Invoice_ID + ", NegateAmt=" + negateAmt); - - /*********************** - * CashBook - */ - - if (newPaymentRule.equals(X_C_Order.PAYMENTRULE_Cash)) - { - log.fine("Cash"); - String description = (String)m_mTab.getValue("DocumentNo"); - - if (C_Invoice_ID == 0 && order == null) - { - log.config("No Invoice!"); - FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); - } - else - { - payAmount = new BigDecimal(bAmountField.getText()); - - // Changed Amount - - if (m_cashLine != null - && payAmount.compareTo(m_cashLine.getAmount()) != 0) - { - log.config("Changed CashBook Amount"); - - //m_cashLine.setAmount(payAmount); - - m_cashLine.setAmount(new BigDecimal(bAmountField.getText())); - - // ADialog.info(m_WindowNo, this, "m_cashLine - Changed Amount", "Amount: "+m_cashLine.getAmount()); - - if (m_cashLine.save()) - log.config("CashAmt Changed"); - } - - // Different Date/CashBook - - if (m_cashLine != null - && (newC_CashBook_ID != m_C_CashBook_ID - || !TimeUtil.isSameDay(m_cashLine.getStatementDate(), newDateAcct))) - { - log.config("Changed CashBook/Date: " + m_C_CashBook_ID + "->" + newC_CashBook_ID); - MCashLine reverse = m_cashLine.createReversal(); - - if (!reverse.save()) - FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCancelled"); - - m_cashLine = null; - } - - // Create new - - if (m_cashLine == null) - { - log.config("New CashBook"); - int C_Currency_ID = 0; - - if (invoice != null) - C_Currency_ID = invoice.getC_Currency_ID(); - - if (C_Currency_ID == 0 && order != null) - C_Currency_ID = order.getC_Currency_ID(); - - MCash cash = null; - - if (newC_CashBook_ID != 0) - cash = MCash.get (Env.getCtx(), newC_CashBook_ID, newDateAcct, null); - else // Default - cash = MCash.get (Env.getCtx(), m_AD_Org_ID, newDateAcct, C_Currency_ID, null); - - if (cash == null || cash.get_ID() == 0) - FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); - else - { - MCashLine cl = new MCashLine (cash); - - // cl.setAmount(new BigDecimal(bAmountField.getText())); - //ADialog.info(m_WindowNo, this, "m_cashLine - New Cashbook", "Amount: "+cl.getAmount()); - - if (invoice != null) - cl.setInvoice(invoice); // overrides amount - if (order != null) - { - cl.setOrder(order, null); // overrides amount - m_needSave = true; - } - - cl.setAmount(new BigDecimal(bAmountField.getText())); - - if (cl.save()) - { - log.config("CashCreated"); - - if (invoice == null && C_Invoice_ID != 0) - { - invoice = new MInvoice (Env.getCtx(), C_Invoice_ID, null); - } - - if (invoice != null) - { - invoice.setC_CashLine_ID(cl.getC_CashLine_ID()); - invoice.save(); - } - - if (order == null && C_Order_ID != 0) - { - order = new MOrder (Env.getCtx(), C_Order_ID, null); - } - - if (order != null) - { - order.setC_CashLine_ID(cl.getC_CashLine_ID()); - order.save(); - } - - log.config("Update Order & Invoice with CashLine"); - } - else - FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); - } - } - } // have invoice - } - - /*********************** - * Payments - */ - - if ("KS".indexOf(newPaymentRule) != -1) - { - log.fine("Payment - " + newPaymentRule); - - // Set Amount - - m_mPayment.setAmount(m_C_Currency_ID, payAmount); - - if (newPaymentRule.equals(MOrder.PAYMENTRULE_CreditCard)) - { - m_mPayment.setCreditCard(MPayment.TRXTYPE_Sales, newCCType, - kNumberField.getText(), "", kExpField.getText()); - - // Get changes to credit card amount - - m_mPayment.setAmount(m_C_Currency_ID, new BigDecimal(kAmountField.getText())); - m_mPayment.setPaymentProcessor(); - } - else if (newPaymentRule.equals(MOrder.PAYMENTRULE_DirectDeposit) - || newPaymentRule.equals(MOrder.PAYMENTRULE_DirectDebit)) - { - m_mPayment.setBankACH(newC_BankAccount_ID, m_isSOTrx, newPaymentRule, - tRoutingField.getText(), tNumberField.getText()); - - m_mPayment.setAmount(m_C_Currency_ID, payAmount); - } - else if (newPaymentRule.equals(MOrder.PAYMENTRULE_Check)) - { - m_mPayment.setBankCheck(newC_BankAccount_ID, m_isSOTrx, sRoutingField.getText(), - sNumberField.getText(), sCheckField.getText()); - - // Get changes to check amount - - m_mPayment.setAmount(m_C_Currency_ID, new BigDecimal(sAmountField.getText())); - } - - m_mPayment.setC_BPartner_ID(m_C_BPartner_ID); - m_mPayment.setC_Invoice_ID(C_Invoice_ID); - - if (order != null) - { - m_mPayment.setC_Order_ID(C_Order_ID); - m_needSave = true; - } - - m_mPayment.setDateTrx(m_DateAcct); - m_mPayment.setDateAcct(m_DateAcct); - m_mPayment.save(); - - // Save/Post - - if (MPayment.DOCSTATUS_Drafted.equals(m_mPayment.getDocStatus())) - { - boolean ok = m_mPayment.processIt(DocAction.ACTION_Complete); - m_mPayment.save(); - - if (ok) - FDialog.info(m_WindowNo, this, "PaymentCreated", m_mPayment.getDocumentNo()); - else - FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated"); - } - else - log.fine("NotDraft " + m_mPayment); - } - - - /********************** - * Save Values to mTab - */ - - log.config("Saving changes"); - - if (!newPaymentRule.equals(m_PaymentRule)) - m_mTab.setValue("PaymentRule", newPaymentRule); - - if (!newDateAcct.equals(m_DateAcct)) - m_mTab.setValue("DateAcct", newDateAcct); - - if (newC_PaymentTerm_ID != m_C_PaymentTerm_ID) - m_mTab.setValue("C_PaymentTerm_ID", new Integer(newC_PaymentTerm_ID)); - - // Set Payment - - if (m_mPayment.getC_Payment_ID() != m_C_Payment_ID) - { - if (m_mPayment.getC_Payment_ID() == 0) - m_mTab.setValue("C_Payment_ID", null); - else - m_mTab.setValue("C_Payment_ID", new Integer(m_mPayment.getC_Payment_ID())); - } - - // Set Cash - - if (newC_CashLine_ID != m_C_CashLine_ID) - { - if (newC_CashLine_ID == 0) - m_mTab.setValue("C_CashLine_ID", null); - else - m_mTab.setValue("C_CashLine_ID", new Integer(newC_CashLine_ID)); - } - return true; - } // saveChanges - - /** - * Check Mandatory - * @return true if all mandatory items are OK - */ - - private boolean checkMandatory() - { - log.config( "WPayment.checkMandatory"); - - ListItem listitem = new ListItem(); - listitem = paymentCombo.getSelectedItem(); - ValueNamePair vp = (ValueNamePair)listitem.getValue(); - String PaymentRule = vp.getValue(); - - // only Payment Rule - - if (m_onlyRule) - return true; - - Timestamp DateAcct = m_DateAcct; - int C_PaymentTerm_ID = m_C_PaymentTerm_ID; - int C_CashBook_ID = m_C_CashBook_ID; - String CCType = m_CCType; - int C_BankAccount_ID = 0; - - /*********************** - * Mandatory Data Check - */ - - boolean dataOK = true; - - // B (Cash) (Currency) - - if (PaymentRule.equals(MOrder.PAYMENTRULE_Cash)) - { - listitem = new ListItem(); - listitem = bCashBookCombo.getSelectedItem(); - - KeyNamePair kp = null; - - if (listitem != null) - kp = (KeyNamePair)listitem.getValue(); - - if (kp != null) - C_CashBook_ID = kp.getKey(); - - DateAcct = (Timestamp)bDateField.getValue(); - } - - // K (CreditCard) Type, Number, Exp, Approval - - else if (PaymentRule.equals(MOrder.PAYMENTRULE_CreditCard)) - { - listitem = kTypeCombo.getSelectedItem(); - - if (listitem != null) - vp = (ValueNamePair)listitem.getValue(); - else - vp = null; - - if (vp != null) - CCType = vp.getValue(); - - String error = MPaymentValidate.validateCreditCardNumber(kNumberField.getText(), CCType); - - if (error.length() != 0) - { - //kNumberField.setBackground(AdempierePLAF.getFieldBackground_Error()); - - if (error.indexOf('?') == -1) - { - FDialog.error(m_WindowNo, this, error); - dataOK = false; - } - else // warning - { - if (!FDialog.ask(m_WindowNo, this, error)) - dataOK = false; - } - } - - error = MPaymentValidate.validateCreditCardExp(kExpField.getText()); - - if (error.length() != 0) - { - //kExpField.setBackground(AdempierePLAF.getFieldBackground_Error()); - FDialog.error(m_WindowNo, this, error); - dataOK = false; - } - } - - // T (Transfer) BPartner_Bank - - else if (PaymentRule.equals(X_C_Order.PAYMENTRULE_DirectDeposit) - || PaymentRule.equals(X_C_Order.PAYMENTRULE_DirectDebit)) - { - listitem = tAccountCombo.getSelectedItem(); - - KeyNamePair bpba = null; - - if (listitem != null) - bpba = (KeyNamePair)listitem.getValue(); - - if (bpba == null) - { - //tAccountCombo.setBackground(AdempierePLAF.getFieldBackground_Error()); - FDialog.error(m_WindowNo, this, "PaymentBPBankNotFound"); - dataOK = false; - } - } // Direct - - // P (PaymentTerm) PaymentTerm - - else if (PaymentRule.equals(X_C_Order.PAYMENTRULE_OnCredit)) - { - listitem = pTermCombo.getSelectedItem(); - - KeyNamePair kp = null; - - if (listitem != null) - kp = (KeyNamePair)listitem.getValue(); - - if (kp != null) - C_PaymentTerm_ID = kp.getKey(); - } - - // S (Check) (Currency) CheckNo, Routing - - else if (PaymentRule.equals(MOrder.PAYMENTRULE_Check)) - { - // sCurrencyCombo.getSelectedItem(); - listitem = sBankAccountCombo.getSelectedItem(); - - KeyNamePair kp = null; - - if (listitem != null) - kp = (KeyNamePair)listitem.getValue(); - - if (kp != null) - C_BankAccount_ID = kp.getKey(); - - String error = MPaymentValidate.validateRoutingNo(sRoutingField.getText()); - - if (error.length() != 0) - { - //sRoutingField.setBackground(AdempierePLAF.getFieldBackground_Error()); - FDialog.error(m_WindowNo, this, error); - dataOK = false; - } - - error = MPaymentValidate.validateAccountNo(sNumberField.getText()); - - if (error.length() != 0) - { - //sNumberField.setBackground(AdempierePLAF.getFieldBackground_Error()); - FDialog.error(m_WindowNo, this, error); - dataOK = false; - } - - error = MPaymentValidate.validateCheckNo(sCheckField.getText()); - - if (error.length() != 0) - { - //sCheckField.setBackground(AdempierePLAF.getFieldBackground_Error()); - FDialog.error(m_WindowNo, this, error); - dataOK = false; - } - } - else - { - log.log(Level.SEVERE, "Unknown PaymentRule " + PaymentRule); - return false; - } - - // find Bank Account if not qualified yet - - if ("KTSD".indexOf(PaymentRule) != -1 && C_BankAccount_ID == 0) - { - String tender = MPayment.TENDERTYPE_CreditCard; - - if (PaymentRule.equals(MOrder.PAYMENTRULE_DirectDeposit)) - tender = MPayment.TENDERTYPE_DirectDeposit; - else if (PaymentRule.equals(MOrder.PAYMENTRULE_DirectDebit)) - tender = MPayment.TENDERTYPE_DirectDebit; - else if (PaymentRule.equals(MOrder.PAYMENTRULE_Check)) - tender = MPayment.TENDERTYPE_Check; - - // Check must have a bank account - - if (C_BankAccount_ID == 0 && "S".equals(PaymentRule)) - { - FDialog.error(m_WindowNo, this, "PaymentNoProcessor"); - dataOK = false; - } - } - - log.config("OK=" + dataOK); - return dataOK; - } // checkMandatory - - /** - * Get Invoice ID for Order - * @param C_Order_ID order - * @return C_Invoice_ID or 0 if not found - */ - - private static int getInvoiceID (int C_Order_ID) - { - int retValue = 0; - String sql = "SELECT C_Invoice_ID FROM C_Invoice WHERE C_Order_ID=? " - + "ORDER BY C_Invoice_ID DESC"; // last invoice - - try - { - PreparedStatement pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, C_Order_ID); - ResultSet rs = pstmt.executeQuery(); - - if (rs.next()) - retValue = rs.getInt(1); - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - return retValue; - } // getInvoiceID - - /************************************************************************** - * Process Online (sales only) - if approved - exit - */ - - private void processOnline() - { - log.config(""); - - if (!checkMandatory()) - return; - - boolean approved = false; - String info = ""; - - ListItem listitem = new ListItem(); - listitem = paymentCombo.getSelectedItem(); - ValueNamePair vp = (ValueNamePair)listitem.getValue(); - String PaymentRule = vp.getValue(); - - // -- CreditCard - - if (PaymentRule.equals(X_C_Order.PAYMENTRULE_CreditCard)) - { - listitem = kTypeCombo.getSelectedItem(); - vp = (ValueNamePair)listitem.getValue(); - String CCType = vp.getValue(); - - m_mPayment.setCreditCard(MPayment.TRXTYPE_Sales, CCType, - kNumberField.getText(), "", kExpField.getText()); - m_mPayment.setAmount(m_C_Currency_ID, m_Amount); - m_mPayment.setPaymentProcessor(); - m_mPayment.setC_BPartner_ID(m_C_BPartner_ID); - - int C_Invoice_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Invoice_ID"); - - if (C_Invoice_ID == 0 && m_DocStatus.equals("CO")) - { - int C_Order_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Order_ID"); - C_Invoice_ID = getInvoiceID (C_Order_ID); - } - - m_mPayment.setC_Invoice_ID(C_Invoice_ID); - m_mPayment.setDateTrx(m_DateAcct); - - // Set Amount - - m_mPayment.setAmount(m_C_Currency_ID, m_Amount); - - approved = m_mPayment.processOnline(); - info = m_mPayment.getR_RespMsg() + " (" + m_mPayment.getR_AuthCode() - + ") ID=" + m_mPayment.getR_PnRef(); - boolean saved = m_mPayment.save(); - - if (approved) - { - boolean ok = m_mPayment.processIt(DocAction.ACTION_Complete); - m_mPayment.save(); - - if (ok) - FDialog.info(m_WindowNo, this, "PaymentProcessed", info + "\n" + m_mPayment.getDocumentNo()); - else - FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated"); - - saveChanges(); - //dispose(); - } - else - { - FDialog.error(m_WindowNo, this, "PaymentNotProcessed", info); - } - } - else - FDialog.error(m_WindowNo, this, "PaymentNoProcessor"); - } // online - - /** - * Need Save record (payment with waiting order) - * @return true if payment with waiting order - */ - - public boolean needSave() - { - return m_needSave; - } // needSave -} +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.adempiere.webui.apps.form; + +import java.math.*; +import java.sql.*; +import java.text.*; +import java.util.*; +import java.util.logging.*; + +import org.adempiere.webui.apps.AEnv; +import org.adempiere.webui.component.Button; +import org.adempiere.webui.component.ConfirmPanel; +import org.adempiere.webui.component.Grid; +import org.adempiere.webui.component.GridFactory; +import org.adempiere.webui.component.Label; +import org.adempiere.webui.component.Listbox; +import org.adempiere.webui.component.ListboxFactory; +import org.adempiere.webui.component.Panel; +import org.adempiere.webui.component.Row; +import org.adempiere.webui.component.Rows; +import org.adempiere.webui.component.Textbox; +import org.adempiere.webui.component.Window; +import org.adempiere.webui.editor.WButtonEditor; +import org.adempiere.webui.editor.WDateEditor; +import org.adempiere.webui.editor.WNumberEditor; +import org.adempiere.webui.window.FDialog; +import org.compiere.model.*; +import org.compiere.process.*; +import org.compiere.util.*; +import org.zkoss.zk.ui.event.Event; +import org.zkoss.zk.ui.event.EventListener; +import org.zkoss.zkex.zul.Borderlayout; +import org.zkoss.zkex.zul.Center; +import org.zkoss.zkex.zul.North; +import org.zkoss.zkex.zul.South; +import org.zkoss.zul.Space; + +/** + * Display (and process) Payment Options. + *
+ *  Payment Rule
+ *  -B- Cash          (Date)          -> Cash Entry
+ *  -P- Payment Term  (Term)
+ *  -S- Check         (Routing, ..)   -> Payment Entry
+ *  -K- CreditCard    (No)            -> Payment Entry
+ *  -U- ACH Transfer  (Routing)       -> Payment Entry
+ *
+ *  When processing:
+ *  - If an invoice is a S/K/U, but has no Payment Entry, it is changed to P
+ *  - If an invoive is B and has no Cash Entry, it is created
+ *  - An invoice is "Open" if it is "P" and no Payment
+ *
+ *  Entry:
+ *  - If not processed, an invoice has no Cash or Payment entry
+ *  - The entry is created, during "Online" and when Saving
+ *
+ *  Changes/Reversals:
+ *  - existing Cash Entries are reversed and newly created
+ *  - existing Payment Entries are not changed and then "hang there" and need to be allocated
+ *  
+ * + * @author Jorg Janke + * @version $Id: VPayment.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ + * + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1763488 ] Error on cash payment + *
  • BF [ 1789949 ] VPayment: is displaying just "CashNotCreated" + */ +public class WPayment extends Window + implements EventListener +{ + /** + * Constructor + * + * @param WindowNo owning window + * @param mTab owning tab + * @param button button with access information + */ + public WPayment (int WindowNo, GridTab mTab, WButtonEditor button) + { + super(); + this.setTitle(Msg.getMsg(Env.getCtx(), "Payment")); + this.setAttribute("mode", "modal"); + m_WindowNo = WindowNo; + m_isSOTrx = "Y".equals(Env.getContext(Env.getCtx(), WindowNo, "IsSOTrx")); + m_mTab = mTab; + try + { + bDateField = new WDateEditor("DateAcct", false, false, true, DisplayType.Date, "DateAcct"); + zkInit(); + m_initOK = dynInit(button); // Null Pointer if order/invoice not saved yet + } + catch(Exception ex) + { + log.log(Level.SEVERE, "VPayment", ex); + m_initOK = false; + } + // + this.setHeight("400px"); + this.setWidth("500px"); + this.setBorder("normal"); + } // VPayment + + /** Window */ + private int m_WindowNo = 0; + /** Tab */ + private GridTab m_mTab; + + // Data from Order/Invoice + private String m_DocStatus = null; + /** Start Payment Rule */ + private String m_PaymentRule = ""; + /** Start Payment Term */ + private int m_C_PaymentTerm_ID = 0; + /** Start Acct Date */ + private Timestamp m_DateAcct = null; + /** Start Payment */ + private int m_C_Payment_ID = 0; + private MPayment m_mPayment = null; + private MPayment m_mPaymentOriginal = null; + /** Start CashBook Line */ + private int m_C_CashLine_ID = 0; + private MCashLine m_cashLine = null; + /** Start CreditCard */ + private String m_CCType = ""; + /** Start Bank Account */ + private int m_C_BankAccount_ID = 0; + /** Start CashBook */ + private int m_C_CashBook_ID = 0; + + /** Is SOTrx */ + private boolean m_isSOTrx = true; + + /** Invoice Currency */ + private int m_C_Currency_ID = 0; + private int m_AD_Client_ID = 0; + private int m_AD_Org_ID = 0; + private int m_C_BPartner_ID = 0; + private BigDecimal m_Amount = Env.ZERO; // Payment Amount + // + private boolean m_initOK = false; + /** Only allow changing Rule */ + private boolean m_onlyRule = false; + private DecimalFormat m_Format = DisplayType.getNumberFormat(DisplayType.Amount); + private static Hashtable s_Currencies = null; // EMU Currencies + + private boolean m_needSave = false; + /** Logger */ + private static CLogger log = CLogger.getCLogger(WPayment.class); + + // + private Panel mainPanel = new Panel(); + private Borderlayout mainLayout = new Borderlayout(); + private Panel northPanel = new Panel(); + private Panel centerPanel = new Panel(); +// private FlowLayout northLayout = new FlowLayout(); + private Listbox paymentCombo = ListboxFactory.newDropdownListbox(); + private Label paymentLabel = new Label(); + private List centerLayout = new ArrayList(); + private Panel bPanel = new Panel(); + private Panel kPanel = new Panel(); + private Grid kLayout = GridFactory.newGridLayout(); + private Label kTypeLabel = new Label(); + private Listbox kTypeCombo = ListboxFactory.newDropdownListbox(); + private Label kNumberLabel = new Label(); + private Textbox kNumberField = new Textbox(); + private Label kExpLabel = new Label(); + private Textbox kExpField = new Textbox(); + private Label kApprovalLabel = new Label(); + private Textbox kApprovalField = new Textbox(); + private Label kAmountLabel = new Label(); + private WNumberEditor kAmountField = new WNumberEditor(); + private Panel tPanel = new Panel(); + private Label tAccountLabel = new Label(); + private Listbox tAccountCombo = ListboxFactory.newDropdownListbox(); + private Panel sPanel = new Panel(); + private Grid sPanelLayout = GridFactory.newGridLayout(); + private Label sNumberLabel = new Label(); + private Textbox sNumberField = new Textbox(); + private Label sRoutingLabel = new Label(); + private Textbox sRoutingField = new Textbox(); + private Label sCurrencyLabel = new Label(); + private Listbox sCurrencyCombo = ListboxFactory.newDropdownListbox(); + private Label bCurrencyLabel = new Label(); + private Listbox bCurrencyCombo = ListboxFactory.newDropdownListbox(); + private Panel pPanel = new Panel(); + private Label pTermLabel = new Label(); + private Listbox pTermCombo = ListboxFactory.newDropdownListbox(); + private Grid bPanelLayout = GridFactory.newGridLayout(); + private Label bAmountLabel = new Label(); + private WNumberEditor bAmountField = new WNumberEditor(); + private Label sAmountLabel = new Label(); + private WNumberEditor sAmountField = new WNumberEditor(); + private WDateEditor bDateField; + private Label bDateLabel = new Label(); + private ConfirmPanel confirmPanel = new ConfirmPanel(true); + private Textbox sCheckField = new Textbox(); + private Label sCheckLabel = new Label(); + private Button kOnline = new Button(); + private Button sOnline = new Button(); + private Listbox sBankAccountCombo = ListboxFactory.newDropdownListbox(); + private Label sBankAccountLabel = new Label(); + private Grid pPanelLayout = GridFactory.newGridLayout(); + private Label bCashBookLabel = new Label(); + private Listbox bCashBookCombo = ListboxFactory.newDropdownListbox(); + private Grid tPanelLayout = GridFactory.newGridLayout(); + private Button tOnline = new Button(); + private Label kStatus = new Label(); + private Textbox tRoutingField = new Textbox(); + private Textbox tNumberField = new Textbox(); + private Label tStatus = new Label(); + private Label tRoutingText = new Label(); + private Label tNumberText = new Label(); + private Label sStatus = new Label(); + + /** + * Static Init + * @throws Exception + */ + private void zkInit() throws Exception + { + this.appendChild(mainPanel); + mainPanel.appendChild(mainLayout); + mainPanel.setStyle("width: 100%; height: 100%; padding: 0; margin: 0"); + mainLayout.setHeight("100%"); + mainLayout.setWidth("100%"); + Center center = new Center(); + mainLayout.appendChild(center); + center.appendChild(centerPanel); + // +// northPanel.setLayout(northLayout); + paymentLabel.setText(Msg.translate(Env.getCtx(), "PaymentRule")); + North north = new North(); + north.setStyle("border: none"); + mainLayout.appendChild(north); + north.appendChild(northPanel); + northPanel.appendChild(paymentLabel); + northPanel.appendChild(new Space()); + northPanel.appendChild(paymentCombo); + // + // CreditCard + kPanel.appendChild(kLayout); + kNumberField.setWidth("160pt"); +// kNumberField.setHeight("21em"); + kExpField.setWidth("40pt"); +// kExpField.setHeight("21em"); + kApprovalField.setWidth("120pt"); +// kApprovalField.setHeight("21em"); + kTypeLabel.setText(Msg.translate(Env.getCtx(), "CreditCardType")); + kNumberLabel.setText(Msg.translate(Env.getCtx(), "CreditCardNumber")); + kExpLabel.setText(Msg.getMsg(Env.getCtx(), "Expires")); + kApprovalLabel.setText(Msg.translate(Env.getCtx(), "VoiceAuthCode")); + kAmountLabel.setText(Msg.getMsg(Env.getCtx(), "Amount")); + kOnline.setLabel(Msg.getMsg(Env.getCtx(), "Online")); + kOnline.setSclass("action-text-button"); + kOnline.addActionListener(this); + kStatus.setText(" "); + kPanel.setId("kPanel"); + centerPanel.appendChild(kPanel); + centerLayout.add(kPanel); + + Rows rows = kLayout.newRows(); + Row row = rows.newRow(); + row.appendChild(kTypeLabel.rightAlign()); + row.appendChild(kTypeCombo); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(kNumberLabel.rightAlign()); + row.appendChild(kNumberField); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(kExpLabel.rightAlign()); + row.appendChild(kExpField); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(kAmountLabel.rightAlign()); + row.appendChild(kAmountField.getComponent()); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(kApprovalLabel.rightAlign()); + row.appendChild(kApprovalField); + row.appendChild(new Space()); + row.appendChild(kOnline); + + row = rows.newRow(); + row.setSpans("3,1"); + row.appendChild(kStatus); + row.appendChild(new Space()); + + // DircetDebit/Credit + tPanel.appendChild(tPanelLayout); + tAccountLabel.setText(Msg.translate(Env.getCtx(), "C_BP_BankAccount_ID")); + tRoutingField.setCols(8); + tNumberField.setCols(10); + tRoutingText.setText(Msg.translate(Env.getCtx(), "RoutingNo")); + tNumberText.setText(Msg.translate(Env.getCtx(), "AccountNo")); + tOnline.setLabel(Msg.getMsg(Env.getCtx(), "Online")); + tOnline.setSclass("action-text-button"); + tStatus.setText(" "); + tPanel.setId("tPanel"); + centerPanel.appendChild(tPanel); + centerLayout.add(tPanel); + + rows = tPanelLayout.newRows(); + row = rows.newRow(); + row.appendChild(tAccountLabel.rightAlign()); + row.appendChild(tAccountCombo); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(tRoutingText.rightAlign()); + row.appendChild(tRoutingField); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(tNumberText.rightAlign()); + row.appendChild(tNumberField); + row.appendChild(new Space()); + row.appendChild(tOnline); + + row = rows.newRow(); + row.setSpans("3,1"); + row.appendChild(tStatus); + row.appendChild(new Space()); + + // Cheque + sPanel.appendChild(sPanelLayout); + sBankAccountLabel.setText(Msg.translate(Env.getCtx(), "C_BankAccount_ID")); + sAmountLabel.setText(Msg.getMsg(Env.getCtx(), "Amount")); + //sAmountField.setText(""); + sRoutingLabel.setText(Msg.translate(Env.getCtx(), "RoutingNo")); + sNumberLabel.setText(Msg.translate(Env.getCtx(), "AccountNo")); + sCheckLabel.setText(Msg.translate(Env.getCtx(), "CheckNo")); + sCheckField.setCols(8); + sCurrencyLabel.setText(Msg.translate(Env.getCtx(), "C_Currency_ID")); + sNumberField.setWidth("100pt"); +// sNumberField.setHeight("100em"); + sRoutingField.setWidth("70pt"); +// sRoutingField.setHeight("21em"); + sStatus.setText(" "); + sOnline.setLabel(Msg.getMsg(Env.getCtx(), "Online")); + sOnline.setSclass("action-text-button"); + sPanel.setId("sPanel"); + centerPanel.appendChild(sPanel); + centerLayout.add(sPanel); + + rows = sPanelLayout.newRows(); + row = rows.newRow(); + row.appendChild(sBankAccountLabel.rightAlign()); + row.appendChild(sBankAccountCombo); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(sCurrencyLabel.rightAlign()); + row.appendChild(sCurrencyCombo); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(sAmountLabel.rightAlign()); + row.appendChild(sAmountField.getComponent()); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(sRoutingLabel.rightAlign()); + row.appendChild(sRoutingField); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(sNumberLabel.rightAlign()); + row.appendChild(sNumberField); + row.appendChild(new Space()); + row.appendChild(new Space()); + + row = rows.newRow(); + row.appendChild(sCheckLabel.rightAlign()); + row.appendChild(sCheckField); + row.appendChild(new Space()); + row.appendChild(sOnline); + + row = rows.newRow(); + row.setSpans("3,1"); + row.appendChild(sStatus); + row.appendChild(new Space()); + + // Cash + pPanel.appendChild(pPanelLayout); + pTermLabel.setText(Msg.translate(Env.getCtx(), "C_PaymentTerm_ID")); + pPanel.setId("pPanel"); + centerPanel.appendChild(pPanel); + centerLayout.add(pPanel); + + rows = pPanelLayout.newRows(); + row = rows.newRow(); + row.appendChild(pTermLabel.rightAlign()); + row.appendChild(pTermCombo); + // + bCashBookLabel.setText(Msg.translate(Env.getCtx(), "C_CashBook_ID")); + bCurrencyLabel.setText(Msg.translate(Env.getCtx(), "C_Currency_ID")); + bPanel.appendChild(bPanelLayout); + bAmountLabel.setText(Msg.getMsg(Env.getCtx(), "Amount")); + //bAmountField.setText(""); + bDateLabel.setText(Msg.translate(Env.getCtx(), "DateAcct")); + bPanel.setId("bPanel"); + centerPanel.appendChild(bPanel); + centerLayout.add(bPanel); + + rows = bPanelLayout.newRows(); + row = rows.newRow(); + row.appendChild(bCashBookLabel.rightAlign()); + row.appendChild(bCashBookCombo); + + row = rows.newRow(); + row.appendChild(bCurrencyLabel.rightAlign()); + row.appendChild(bCurrencyCombo); + + row = rows.newRow(); + row.appendChild(bDateLabel.rightAlign()); + row.appendChild(bDateField.getComponent()); + + row = rows.newRow(); + row.appendChild(bAmountLabel.rightAlign()); + row.appendChild(bAmountField.getComponent()); + // + South south = new South(); + south.setStyle("border: none"); + mainLayout.appendChild(south); + south.appendChild(confirmPanel); + confirmPanel.addActionListener(this); + } // jbInit + + + /************************************************************************** + * Dynamic Init. + * B (Cash) (Currency) + * K (CreditCard) Type, Number, Exp, Approval + * L (DirectDebit) BPartner_Bank + * P (PaymentTerm) PaymentTerm + * S (Check) (Currency) CheckNo, Routing + * + * Currencies are shown, if member of EMU + * @param button payment type button + * @return true if init OK + * @throws Exception + */ + private boolean dynInit (WButtonEditor button) throws Exception + { + m_DocStatus = (String)m_mTab.getValue("DocStatus"); + log.config(m_DocStatus); + + if (m_mTab.getValue("C_BPartner_ID") == null) + { + FDialog.error(0, this, "SaveErrorRowNotFound"); + return false; + } + + // Is the Trx posted? + // String Posted = (String)m_mTab.getValue("Posted"); + // if (Posted != null && Posted.equals("Y")) + // return false; + + // DocStatus + m_DocStatus = (String)m_mTab.getValue("DocStatus"); + if (m_DocStatus == null) + m_DocStatus = ""; + // Is the Trx closed? Reversed / Voided / Cloased + if (m_DocStatus.equals("RE") || m_DocStatus.equals("VO") || m_DocStatus.equals("CL")) + return false; + // Document is not complete - allow to change the Payment Rule only + if (m_DocStatus.equals("CO") || m_DocStatus.equals("WP") ) + m_onlyRule = false; + else + m_onlyRule = true; + // PO only Rule + if (!m_onlyRule // Only order has Warehouse + && !m_isSOTrx && m_mTab.getValue("M_Warehouse_ID") != null) + m_onlyRule = true; + + centerPanel.setVisible(!m_onlyRule); + + + // Amount + m_Amount = (BigDecimal)m_mTab.getValue("GrandTotal"); + if (!m_onlyRule && m_Amount.compareTo(Env.ZERO) == 0) + { + FDialog.error(m_WindowNo, this, "PaymentZero"); + return false; + } + + + bAmountField.setValue(m_Amount); + sAmountField.setValue(m_Amount); + kAmountField.setValue(m_Amount); + + + /** + * Get Data from Grid + */ + m_AD_Client_ID = ((Integer)m_mTab.getValue("AD_Client_ID")).intValue(); + m_AD_Org_ID = ((Integer)m_mTab.getValue("AD_Org_ID")).intValue(); + m_C_BPartner_ID = ((Integer)m_mTab.getValue("C_BPartner_ID")).intValue(); + m_PaymentRule = (String)m_mTab.getValue("PaymentRule"); + m_C_Currency_ID = ((Integer)m_mTab.getValue("C_Currency_ID")).intValue(); + m_DateAcct = (Timestamp)m_mTab.getValue("DateAcct"); + if (m_mTab.getValue("C_PaymentTerm_ID") != null) + m_C_PaymentTerm_ID = ((Integer)m_mTab.getValue("C_PaymentTerm_ID")).intValue(); + // Existing Payment + if (m_mTab.getValue("C_Payment_ID") != null) + { + m_C_Payment_ID = ((Integer)m_mTab.getValue("C_Payment_ID")).intValue(); + if (m_C_Payment_ID != 0) + { + m_mPayment = new MPayment(Env.getCtx(), m_C_Payment_ID, null); + m_mPaymentOriginal = new MPayment(Env.getCtx(), m_C_Payment_ID, null); // full copy + // CreditCard + m_CCType = m_mPayment.getCreditCardType(); + kNumberField.setText(m_mPayment.getCreditCardNumber()); + kExpField.setText(m_mPayment.getCreditCardExp(null)); + kApprovalField.setText(m_mPayment.getVoiceAuthCode()); + kStatus.setText(m_mPayment.getR_PnRef()); + kAmountField.setValue(m_mPayment.getPayAmt()); + + // if approved/paid, don't let it change + kTypeCombo.setEnabled(!m_mPayment.isApproved()); + kNumberField.setReadonly(m_mPayment.isApproved()); + kExpField.setReadonly(m_mPayment.isApproved()); + kApprovalField.setReadonly(m_mPayment.isApproved()); + kOnline.setEnabled(!m_mPayment.isApproved()); + kAmountField.setReadWrite(!m_mPayment.isApproved()); + // Check + m_C_BankAccount_ID = m_mPayment.getC_BankAccount_ID(); + sRoutingField.setText(m_mPayment.getRoutingNo()); + sNumberField.setText(m_mPayment.getAccountNo()); + sCheckField.setText(m_mPayment.getCheckNo()); + sStatus.setText(m_mPayment.getR_PnRef()); + sAmountField.setValue(m_mPayment.getPayAmt()); + // Transfer + tRoutingField.setText(m_mPayment.getRoutingNo()); + tNumberField.setText(m_mPayment.getAccountNo()); + tStatus.setText(m_mPayment.getR_PnRef()); + } + } + if (m_mPayment == null) + { + m_mPayment = new MPayment (Env.getCtx (), 0, null); + m_mPayment.setAD_Org_ID(m_AD_Org_ID); + m_mPayment.setAmount (m_C_Currency_ID, m_Amount); + } + + // Existing Cashbook entry + m_cashLine = null; + m_C_CashLine_ID = 0; + if (m_mTab.getValue("C_CashLine_ID") != null) + { + m_C_CashLine_ID = ((Integer)m_mTab.getValue("C_CashLine_ID")).intValue(); + if (m_C_CashLine_ID == 0) + m_cashLine = null; + else + { + m_cashLine = new MCashLine (Env.getCtx(), m_C_CashLine_ID, null); + m_DateAcct = m_cashLine.getStatementDate(); + m_C_CashBook_ID = m_cashLine.getCashBook().getC_CashBook_ID(); + bAmountField.setValue(m_cashLine.getAmount()); + } + } + + // Accounting Date + bDateField.setValue(m_DateAcct); + + if (s_Currencies == null) + loadCurrencies(); + + // Is the currency an EMU currency? + Integer C_Currency_ID = new Integer(m_C_Currency_ID); + if (s_Currencies.containsKey(C_Currency_ID)) + { + Enumeration en = s_Currencies.keys(); + while (en.hasMoreElements()) + { + Object key = en.nextElement(); + bCurrencyCombo.addItem(s_Currencies.get(key)); + sCurrencyCombo.addItem(s_Currencies.get(key)); + } + sCurrencyCombo.addActionListener(this); + sCurrencyCombo.setSelectedKeyNamePair(s_Currencies.get(C_Currency_ID)); + bCurrencyCombo.addActionListener(this); + bCurrencyCombo.setSelectedKeyNamePair(s_Currencies.get(C_Currency_ID)); + } + else // No EMU Currency + { + bCurrencyLabel.setVisible(false); // Cash + bCurrencyCombo.setVisible(false); + sCurrencyLabel.setVisible(false); // Check + sCurrencyCombo.setVisible(false); + } + + /** + * Payment Combo + */ + if (m_PaymentRule == null) + m_PaymentRule = ""; + ValueNamePair vp = null; + HashMap values = button.getValues(); + Object[] a = values.keySet().toArray(); + for (int i = 0; i < a.length; i++) + { + String PaymentRule = (String)a[i]; // used for Panel selection + if (X_C_Order.PAYMENTRULE_DirectDebit.equals(PaymentRule) // SO + && !m_isSOTrx) + continue; + else if (X_C_Order.PAYMENTRULE_DirectDeposit.equals(PaymentRule) // PO + && m_isSOTrx) + continue; + + ValueNamePair pp = new ValueNamePair(PaymentRule, (String)values.get(a[i])); + paymentCombo.addItem(pp); + if (PaymentRule.toString().equals(m_PaymentRule)) // to select + vp = pp; + } + + // Set PaymentRule + paymentCombo.addActionListener(this); + if (vp != null) { + paymentCombo.setSelectedValueNamePair(vp); + onPaymentComboSelection(); + } + + /** + * Load Payment Terms + */ + String SQL = MRole.getDefault().addAccessSQL( + "SELECT C_PaymentTerm_ID, Name FROM C_PaymentTerm WHERE IsActive='Y' ORDER BY Name", + "C_PaymentTerm", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); + KeyNamePair kp = null; + try + { + PreparedStatement pstmt = DB.prepareStatement(SQL, null); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + int key = rs.getInt(1); + String name = rs.getString(2); + KeyNamePair pp = new KeyNamePair(key, name); + pTermCombo.addItem(pp); + if (key == m_C_PaymentTerm_ID) + kp = pp; + } + rs.close(); + pstmt.close(); + } + catch (SQLException ept) + { + log.log(Level.SEVERE, SQL, ept); + } + // Set Selection + if (kp != null) + pTermCombo.setSelectedKeyNamePair(kp); + + /** + * Load Accounts + */ + SQL = "SELECT a.C_BP_BankAccount_ID, NVL(b.Name, ' ')||a.AccountNo AS Acct " + + "FROM C_BP_BankAccount a,C_Bank b " + + "WHERE C_BPartner_ID=? AND a.IsActive='Y'"; + kp = null; + try + { + PreparedStatement pstmt = DB.prepareStatement(SQL, null); + pstmt.setInt(1, m_C_BPartner_ID); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + int key = rs.getInt(1); + String name = rs.getString(2); + KeyNamePair pp = new KeyNamePair(key, name); + tAccountCombo.addItem(pp); + // kp = pp; + } + rs.close(); + pstmt.close(); + } + catch (SQLException eac) + { + log.log(Level.SEVERE, SQL, eac); + } + // Set Selection + if (kp != null) + tAccountCombo.setSelectedKeyNamePair(kp); + + /** + * Load Credit Cards + */ + ValueNamePair[] ccs = m_mPayment.getCreditCards(); + vp = null; + for (int i = 0; i < ccs.length; i++) + { + kTypeCombo.addItem(ccs[i]); + if (ccs[i].getValue().equals(m_CCType)) + vp = ccs[i]; + } + // Set Selection + if (vp != null) + kTypeCombo.setSelectedValueNamePair(vp); + + /** + * Load Bank Accounts + */ + SQL = MRole.getDefault().addAccessSQL( + "SELECT C_BankAccount_ID, Name || ' ' || AccountNo, IsDefault " + + "FROM C_BankAccount ba" + + " INNER JOIN C_Bank b ON (ba.C_Bank_ID=b.C_Bank_ID) " + + "WHERE b.IsActive='Y'", + "ba", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO); + kp = null; + try + { + PreparedStatement pstmt = DB.prepareStatement(SQL, null); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + int key = rs.getInt(1); + String name = rs.getString(2); + KeyNamePair pp = new KeyNamePair(key, name); + sBankAccountCombo.addItem(pp); + if (key == m_C_BankAccount_ID) + kp = pp; + if (kp == null && rs.getString(3).equals("Y")) // Default + kp = pp; + } + rs.close(); + pstmt.close(); + } + catch (SQLException ept) + { + log.log(Level.SEVERE, SQL, ept); + } + // Set Selection + if (kp != null) + sBankAccountCombo.setSelectedKeyNamePair(kp); + + + /** + * Load Cash Books + */ + SQL = MRole.getDefault().addAccessSQL( + "SELECT C_CashBook_ID, Name, AD_Org_ID FROM C_CashBook WHERE IsActive='Y'", + "C_CashBook", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); + kp = null; + try + { + PreparedStatement pstmt = DB.prepareStatement(SQL, null); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + int key = rs.getInt(1); + String name = rs.getString(2); + KeyNamePair pp = new KeyNamePair(key, name); + bCashBookCombo.addItem(pp); + if (key == m_C_CashBook_ID) + kp = pp; + if (kp == null && key == m_AD_Org_ID) // Default Org + kp = pp; + } + rs.close(); + pstmt.close(); + } + catch (SQLException epc) + { + log.log(Level.SEVERE, SQL, epc); + } + // Set Selection + if (kp != null) + { + bCashBookCombo.setSelectedKeyNamePair(kp); + if (m_C_CashBook_ID == 0) + m_C_CashBook_ID = kp.getKey(); // set to default to avoid 'cashbook changed' message + } + + // + return true; + } // dynInit + + /** + * Init OK to be able to make changes? + * @return true if init OK + */ + public boolean isInitOK() + { + return m_initOK; + } // isInitOK + + + /** + * Fill s_Currencies with EMU currencies + */ + private void loadCurrencies() + { + s_Currencies = new Hashtable(12); // Currenly only 10+1 + String SQL = "SELECT C_Currency_ID, ISO_Code FROM C_Currency " + + "WHERE (IsEMUMember='Y' AND EMUEntryDate " + newPaymentRule); + // We had a CashBook Entry + if (m_PaymentRule.equals(X_C_Order.PAYMENTRULE_Cash)) + { + log.fine("Old Cash - " + m_cashLine); + if (m_cashLine != null) + { + MCashLine cl = m_cashLine.createReversal(); + if (cl.save()) + log.config( "CashCancelled"); + else + FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCancelled"); + } + newC_CashLine_ID = 0; // reset + } + // We had a change in Payment type (e.g. Check to CC) + else if ("KTSD".indexOf(m_PaymentRule) != -1 && "KTSD".indexOf(newPaymentRule) != -1 && m_mPaymentOriginal != null) + { + log.fine("Old Payment(1) - " + m_mPaymentOriginal); + m_mPaymentOriginal.setDocAction(DocAction.ACTION_Reverse_Correct); + boolean ok = m_mPaymentOriginal.processIt(DocAction.ACTION_Reverse_Correct); + m_mPaymentOriginal.save(); + if (ok) + log.info( "Payment Canecelled - " + m_mPaymentOriginal); + else + FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCancelled " + m_mPaymentOriginal.getDocumentNo()); + m_mPayment.resetNew(); + } + // We had a Payment and something else (e.g. Check to Cash) + else if ("KTSD".indexOf(m_PaymentRule) != -1 && "KTSD".indexOf(newPaymentRule) == -1) + { + log.fine("Old Payment(2) - " + m_mPaymentOriginal); + if (m_mPaymentOriginal != null) + { + m_mPaymentOriginal.setDocAction(DocAction.ACTION_Reverse_Correct); + boolean ok = m_mPaymentOriginal.processIt(DocAction.ACTION_Reverse_Correct); + m_mPaymentOriginal.save(); + if (ok) // Cancel Payment + { + log.fine("PaymentCancelled " + m_mPayment.getDocumentNo ()); + m_mTab.getTableModel().dataSave(true); + m_mPayment.resetNew(); + m_mPayment.setAmount(m_C_Currency_ID, m_Amount); + } + else + FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCancelled " + m_mPayment.getDocumentNo()); + } + } + } + + // Get Order and optionally Invoice + int C_Order_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Order_ID"); + int C_Invoice_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Invoice_ID"); + if (C_Invoice_ID == 0 && m_DocStatus.equals("CO")) + C_Invoice_ID = getInvoiceID (C_Order_ID); + + // Amount sign negative, if ARC (Credit Memo) or API (AP Invoice) + boolean negateAmt = false; + MInvoice invoice = null; + if (C_Invoice_ID != 0) + { + invoice = new MInvoice (Env.getCtx(), C_Invoice_ID, null); + negateAmt = invoice.isCreditMemo(); + } + MOrder order = null; + if (invoice == null && C_Order_ID != 0) + order = new MOrder (Env.getCtx(), C_Order_ID, null); + + BigDecimal payAmount = m_Amount; + + + if (negateAmt) + payAmount = m_Amount.negate(); + // Info + log.config("C_Order_ID=" + C_Order_ID + ", C_Invoice_ID=" + C_Invoice_ID + ", NegateAmt=" + negateAmt); + + /*********************** + * CashBook + */ + if (newPaymentRule.equals(X_C_Order.PAYMENTRULE_Cash)) + { + log.fine("Cash"); + String description = (String)m_mTab.getValue("DocumentNo"); + + if (C_Invoice_ID == 0 && order == null) + { + log.config("No Invoice!"); + FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); + } + else + { + payAmount = (BigDecimal) bAmountField.getValue(); + // Changed Amount + if (m_cashLine != null + && payAmount.compareTo(m_cashLine.getAmount()) != 0) + { + log.config("Changed CashBook Amount"); + //m_cashLine.setAmount(payAmount); + m_cashLine.setAmount((BigDecimal) bAmountField.getValue()); + // ADialog.info(m_WindowNo, this, "m_cashLine - Changed Amount", "Amount: "+m_cashLine.getAmount()); + if (m_cashLine.save()) + log.config("CashAmt Changed"); + } + // Different Date/CashBook + if (m_cashLine != null + && (newC_CashBook_ID != m_C_CashBook_ID + || !TimeUtil.isSameDay(m_cashLine.getStatementDate(), newDateAcct))) + { + log.config("Changed CashBook/Date: " + m_C_CashBook_ID + "->" + newC_CashBook_ID); + MCashLine reverse = m_cashLine.createReversal(); + if (!reverse.save()) + FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCancelled"); + m_cashLine = null; + } + + // Create new + if (m_cashLine == null) + { + log.config("New CashBook"); + int C_Currency_ID = 0; + if (invoice != null) + C_Currency_ID = invoice.getC_Currency_ID(); + if (C_Currency_ID == 0 && order != null) + C_Currency_ID = order.getC_Currency_ID(); + MCash cash = null; + if (newC_CashBook_ID != 0) + cash = MCash.get (Env.getCtx(), newC_CashBook_ID, newDateAcct, null); + else // Default + cash = MCash.get (Env.getCtx(), m_AD_Org_ID, newDateAcct, C_Currency_ID, null); + if (cash == null || cash.get_ID() == 0) + FDialog.error(m_WindowNo, this, "PaymentError", CLogger.retrieveErrorString("CashNotCreated")); + else + { + MCashLine cl = new MCashLine (cash); + // cl.setAmount(new BigDecimal(bAmountField.getText())); + //ADialog.info(m_WindowNo, this, "m_cashLine - New Cashbook", "Amount: "+cl.getAmount()); + if (invoice != null) + cl.setInvoice(invoice); // overrides amount + if (order != null) + { + cl.setOrder(order, null); // overrides amount + m_needSave = true; + } + cl.setAmount((BigDecimal)bAmountField.getValue()); + if (cl.save()) + { + log.config("CashCreated"); + if (invoice == null && C_Invoice_ID != 0) + { + invoice = new MInvoice (Env.getCtx(), C_Invoice_ID, null); + } + if (invoice != null) { + invoice.setC_CashLine_ID(cl.getC_CashLine_ID()); + invoice.save(); + } + if (order == null && C_Order_ID != 0) + { + order = new MOrder (Env.getCtx(), C_Order_ID, null); + } + if (order != null) { + order.setC_CashLine_ID(cl.getC_CashLine_ID()); + order.save(); + } + log.config("Update Order & Invoice with CashLine"); + } + else + FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); + } + } + } // have invoice + } + /*********************** + * Payments + */ + if ("KS".indexOf(newPaymentRule) != -1) + { + log.fine("Payment - " + newPaymentRule); + // Set Amount + m_mPayment.setAmount(m_C_Currency_ID, payAmount); + if (newPaymentRule.equals(MOrder.PAYMENTRULE_CreditCard)) + { + m_mPayment.setCreditCard(MPayment.TRXTYPE_Sales, newCCType, + kNumberField.getText(), "", kExpField.getText()); + // Get changes to credit card amount + m_mPayment.setAmount(m_C_Currency_ID, (BigDecimal) kAmountField.getValue()); + m_mPayment.setPaymentProcessor(); + } + else if (newPaymentRule.equals(MOrder.PAYMENTRULE_DirectDeposit) + || newPaymentRule.equals(MOrder.PAYMENTRULE_DirectDebit)) + { + m_mPayment.setBankACH(newC_BankAccount_ID, m_isSOTrx, newPaymentRule, + tRoutingField.getText(), tNumberField.getText()); + m_mPayment.setAmount(m_C_Currency_ID, payAmount); + } + else if (newPaymentRule.equals(MOrder.PAYMENTRULE_Check)) + { + m_mPayment.setBankCheck(newC_BankAccount_ID, m_isSOTrx, sRoutingField.getText(), + sNumberField.getText(), sCheckField.getText()); + // Get changes to check amount + m_mPayment.setAmount(m_C_Currency_ID, (BigDecimal) sAmountField.getValue()); + } + m_mPayment.setC_BPartner_ID(m_C_BPartner_ID); + m_mPayment.setC_Invoice_ID(C_Invoice_ID); + if (order != null) + { + m_mPayment.setC_Order_ID(C_Order_ID); + m_needSave = true; + } + m_mPayment.setDateTrx(m_DateAcct); + m_mPayment.setDateAcct(m_DateAcct); + if (!m_mPayment.save()) + FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated");; + + // Save/Post + if (m_mPayment.get_ID() > 0 && MPayment.DOCSTATUS_Drafted.equals(m_mPayment.getDocStatus())) + { + boolean ok = m_mPayment.processIt(DocAction.ACTION_Complete); + m_mPayment.save(); + if (ok) + FDialog.info(m_WindowNo, this, "PaymentCreated", m_mPayment.getDocumentNo()); + else + FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated"); + } + else + log.fine("NotDraft " + m_mPayment); + } + + + /********************** + * Save Values to mTab + */ + log.config("Saving changes"); + // + if (!newPaymentRule.equals(m_PaymentRule)) + m_mTab.setValue("PaymentRule", newPaymentRule); + // + if (!newDateAcct.equals(m_DateAcct)) + m_mTab.setValue("DateAcct", newDateAcct); + // + if (newC_PaymentTerm_ID != m_C_PaymentTerm_ID) + m_mTab.setValue("C_PaymentTerm_ID", new Integer(newC_PaymentTerm_ID)); + // Set Payment + if (m_mPayment.getC_Payment_ID() != m_C_Payment_ID) + { + if (m_mPayment.getC_Payment_ID() == 0) + m_mTab.setValue("C_Payment_ID", null); + else + m_mTab.setValue("C_Payment_ID", new Integer(m_mPayment.getC_Payment_ID())); + } + // Set Cash + if (newC_CashLine_ID != m_C_CashLine_ID) + { + if (newC_CashLine_ID == 0) + m_mTab.setValue("C_CashLine_ID", null); + else + m_mTab.setValue("C_CashLine_ID", new Integer(newC_CashLine_ID)); + } + return true; + } // saveChanges + + /** + * Check Mandatory + * @return true if all mandatory items are OK + */ + private boolean checkMandatory() + { + log.config( "VPayment.checkMandatory"); + + ValueNamePair vp = paymentCombo.getSelectedItem().toValueNamePair(); + String PaymentRule = vp.getValue(); + // only Payment Rule + if (m_onlyRule) + return true; + + Timestamp DateAcct = m_DateAcct; + int C_PaymentTerm_ID = m_C_PaymentTerm_ID; + int C_CashBook_ID = m_C_CashBook_ID; + String CCType = m_CCType; + // + int C_BankAccount_ID = 0; + + /*********************** + * Mandatory Data Check + */ + boolean dataOK = true; + // B (Cash) (Currency) + if (PaymentRule.equals(MOrder.PAYMENTRULE_Cash)) + { + KeyNamePair kp = bCashBookCombo.getSelectedItem().toKeyNamePair(); + if (kp != null) + C_CashBook_ID = kp.getKey(); + DateAcct = (Timestamp)bDateField.getValue(); + } + + // K (CreditCard) Type, Number, Exp, Approval + else if (PaymentRule.equals(MOrder.PAYMENTRULE_CreditCard)) + { + vp = kTypeCombo.getSelectedItem().toValueNamePair(); + if (vp != null) + CCType = vp.getValue(); + // + String error = MPaymentValidate.validateCreditCardNumber(kNumberField.getText(), CCType); + if (error.length() != 0) + { + if (error.indexOf('?') == -1) + { + FDialog.error(m_WindowNo, this, error); + dataOK = false; + } + else // warning + { + if (!FDialog.ask(m_WindowNo, this, error)) + dataOK = false; + } + } + error = MPaymentValidate.validateCreditCardExp(kExpField.getText()); + if(error.length() != 0) + { + FDialog.error(m_WindowNo, this, error); + dataOK = false; + } + } + + // T (Transfer) BPartner_Bank + else if (PaymentRule.equals(X_C_Order.PAYMENTRULE_DirectDeposit) + || PaymentRule.equals(X_C_Order.PAYMENTRULE_DirectDebit)) + { + KeyNamePair bpba = tAccountCombo.getSelectedItem().toKeyNamePair(); + if (bpba == null) + + { + FDialog.error(m_WindowNo, this, "PaymentBPBankNotFound"); + dataOK = false; + } + } // Direct + + // P (PaymentTerm) PaymentTerm + else if (PaymentRule.equals(X_C_Order.PAYMENTRULE_OnCredit)) + { + KeyNamePair kp = pTermCombo.getSelectedItem().toKeyNamePair(); + if (kp != null) + C_PaymentTerm_ID = kp.getKey(); + } + + // S (Check) (Currency) CheckNo, Routing + else if (PaymentRule.equals(MOrder.PAYMENTRULE_Check)) + { + // sCurrencyCombo.getSelectedItem(); + KeyNamePair kp = sBankAccountCombo.getSelectedItem().toKeyNamePair(); + if (kp != null) + C_BankAccount_ID = kp.getKey(); + String error = MPaymentValidate.validateRoutingNo(sRoutingField.getText()); + if (error.length() != 0) + { + FDialog.error(m_WindowNo, this, error); + dataOK = false; + } + error = MPaymentValidate.validateAccountNo(sNumberField.getText()); + if (error.length() != 0) + { + FDialog.error(m_WindowNo, this, error); + dataOK = false; + } + error = MPaymentValidate.validateCheckNo(sCheckField.getText()); + if (error.length() != 0) + { + FDialog.error(m_WindowNo, this, error); + dataOK = false; + } + } + else + { + log.log(Level.SEVERE, "Unknown PaymentRule " + PaymentRule); + return false; + } + + // find Bank Account if not qualified yet + if ("KTSD".indexOf(PaymentRule) != -1 && C_BankAccount_ID == 0) + { + String tender = MPayment.TENDERTYPE_CreditCard; + if (PaymentRule.equals(MOrder.PAYMENTRULE_DirectDeposit)) + tender = MPayment.TENDERTYPE_DirectDeposit; + else if (PaymentRule.equals(MOrder.PAYMENTRULE_DirectDebit)) + tender = MPayment.TENDERTYPE_DirectDebit; + else if (PaymentRule.equals(MOrder.PAYMENTRULE_Check)) + tender = MPayment.TENDERTYPE_Check; + // Check must have a bank account + if (C_BankAccount_ID == 0 && "S".equals(PaymentRule)) + { + FDialog.error(m_WindowNo, this, "PaymentNoProcessor"); + dataOK = false; + } + } + // + log.config("OK=" + dataOK); + return dataOK; + } // checkMandatory + + /** + * Get Invoice ID for Order + * @param C_Order_ID order + * @return C_Invoice_ID or 0 if not found + */ + private static int getInvoiceID (int C_Order_ID) + { + int retValue = 0; + String sql = "SELECT C_Invoice_ID FROM C_Invoice WHERE C_Order_ID=? " + + "ORDER BY C_Invoice_ID DESC"; // last invoice + try + { + PreparedStatement pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, C_Order_ID); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getInt(1); + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + return retValue; + } // getInvoiceID + + + /************************************************************************** + * Process Online (sales only) - if approved - exit + */ + private void processOnline() + { + log.config(""); + if (!checkMandatory()) + return; + + boolean approved = false; + String info = ""; + // + ValueNamePair vp = paymentCombo.getSelectedItem().toValueNamePair(); + String PaymentRule = vp.getValue(); + + // -- CreditCard + if (PaymentRule.equals(X_C_Order.PAYMENTRULE_CreditCard)) + { + vp = kTypeCombo.getSelectedItem().toValueNamePair(); + String CCType = vp.getValue(); + + m_mPayment.setCreditCard(MPayment.TRXTYPE_Sales, CCType, + kNumberField.getText(), "", kExpField.getText()); + m_mPayment.setAmount(m_C_Currency_ID, m_Amount); + m_mPayment.setPaymentProcessor(); + m_mPayment.setC_BPartner_ID(m_C_BPartner_ID); + // + int C_Invoice_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Invoice_ID"); + if (C_Invoice_ID == 0 && m_DocStatus.equals("CO")) + { + int C_Order_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Order_ID"); + C_Invoice_ID = getInvoiceID (C_Order_ID); + } + m_mPayment.setC_Invoice_ID(C_Invoice_ID); + m_mPayment.setDateTrx(m_DateAcct); + // Set Amount + m_mPayment.setAmount(m_C_Currency_ID, m_Amount); + if (!m_mPayment.save()) { + FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated"); + } else { + approved = m_mPayment.processOnline(); + info = m_mPayment.getR_RespMsg() + " (" + m_mPayment.getR_AuthCode() + + ") ID=" + m_mPayment.getR_PnRef(); + m_mPayment.save(); + + if (approved) + { + boolean ok = m_mPayment.processIt(DocAction.ACTION_Complete); + m_mPayment.save(); + if (ok) + FDialog.info(m_WindowNo, this, "PaymentProcessed", info + "\n" + m_mPayment.getDocumentNo()); + else + FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated"); + saveChanges(); + dispose(); + } + else + { + FDialog.error(m_WindowNo, this, "PaymentNotProcessed", info); + } + } + } + else + FDialog.error(m_WindowNo, this, "PaymentNoProcessor"); + } // online + + /** + * Need Save record (payment with waiting order) + * @return true if payment with waiting order + */ + public boolean needSave() + { + return m_needSave; + } // needSave + +} // VPayment diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/component/Listbox.java b/zkwebui/WEB-INF/src/org/adempiere/webui/component/Listbox.java index dbf005a625..b4334a2a63 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/component/Listbox.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/component/Listbox.java @@ -23,8 +23,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; -import org.adempiere.webui.apps.form.WCreateFrom; import org.compiere.util.KeyNamePair; +import org.compiere.util.ValueNamePair; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; @@ -239,5 +239,46 @@ public class Listbox extends org.zkoss.zul.Listbox implements EventListener */ public void addActionListener(EventListener listener) { addEventListener(Events.ON_SELECT, listener); + } + + /** + * shortcut for appendItem(pp.getName(), pp.getValue()), to ease porting of swing form + * @param pp + */ + public void addItem(ValueNamePair pp) { + appendItem(pp.getName(), pp.getValue()); + } + + /** + * select selected item base on vp.getValue, to ease porting of swing form + * @param vp + */ + public void setSelectedValueNamePair(ValueNamePair vp) { + int count = this.getItemCount(); + for(int i = 0; i < count; i++) { + ListItem item = getItemAtIndex(i); + if (vp.getValue().equals(item.getValue())) { + setSelectedIndex(i); + break; + } + } + } + + + /** + * select selected item base on kp.getKey, to ease porting of swing form + * @param kp + */ + public void setSelectedKeyNamePair(KeyNamePair kp) { + int count = this.getItemCount(); + for(int i = 0; i < count; i++) { + ListItem item = getItemAtIndex(i); + if (item.getValue() instanceof Integer) { + if (kp.getKey() == (Integer)item.getValue()) { + setSelectedIndex(i); + break; + } + } + } } } diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/component/ListboxFactory.java b/zkwebui/WEB-INF/src/org/adempiere/webui/component/ListboxFactory.java index 493a194900..5df2f35b2a 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/component/ListboxFactory.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/component/ListboxFactory.java @@ -42,4 +42,14 @@ public class ListboxFactory { return dataTable; } + + public static Listbox newDropdownListbox(String[] items) { + Listbox listbox = newDropdownListbox(); + if (items != null && items.length > 0) { + for(int i = 0; i < items.length; i++) { + listbox.appendChild(new ListItem(items[i], items[i])); + } + } + return listbox; + } } diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/editor/WNumberEditor.java b/zkwebui/WEB-INF/src/org/adempiere/webui/editor/WNumberEditor.java index 7248d1cb5c..fa5a43ec8e 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/editor/WNumberEditor.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/editor/WNumberEditor.java @@ -34,6 +34,8 @@ import org.zkoss.zk.ui.event.Events; * @author Ashley G Ramdass * @date Mar 11, 2007 * @version $Revision: 0.10 $ + * + * @author Low Heng Sin */ public class WNumberEditor extends WEditor { @@ -45,6 +47,15 @@ public class WNumberEditor extends WEditor private boolean mandatory = false; + public WNumberEditor() + { + this("Number", false, false, true, DisplayType.Number, ""); + } + + /** + * + * @param gridField + */ public WNumberEditor(GridField gridField) { super(new NumberBox(gridField.getDisplayType() == DisplayType.Integer), @@ -52,19 +63,49 @@ public class WNumberEditor extends WEditor init(); } + /** + * + * @param gridField + * @param integral + */ public WNumberEditor(GridField gridField, boolean integral) { super(new NumberBox(integral), gridField); init(); } - private void init() + /** + * + * @param columnName + * @param mandatory + * @param readonly + * @param updateable + * @param displayType + * @param title + */ + public WNumberEditor(String columnName, boolean mandatory, boolean readonly, boolean updateable, + int displayType, String title) { - getComponent().setMaxlength(gridField.getFieldLength()); + super(new NumberBox(displayType == DisplayType.Integer), columnName, title, null, mandatory, + readonly, updateable); + init(); + } + + private void init() + { + if (gridField != null) + { + getComponent().setMaxlength(gridField.getFieldLength()); + getComponent().setTooltiptext(gridField.getDescription()); + } + getComponent().setCols(MAX_DISPLAY_LENGTH); - getComponent().setTooltiptext(gridField.getDescription()); } + /** + * Event handler + * @param event + */ public void onEvent(Event event) { String newValue = getComponent().getValue(); @@ -131,14 +172,19 @@ public class WNumberEditor extends WEditor } } + @Override public String[] getEvents() { return LISTENER_EVENTS; } + /** + * Handle context menu events + * @param evt + */ public void onMenu(ContextMenuEvent evt) { - if (WEditorPopupMenu.PREFERENCE_EVENT.equals(evt.getContextEvent())) + if (WEditorPopupMenu.PREFERENCE_EVENT.equals(evt.getContextEvent()) && gridField != null) { if (MRole.getDefault().isShowPreference()) ValuePreference.start (this.getGridField(), getValue()); diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/editor/WSearchEditor.java b/zkwebui/WEB-INF/src/org/adempiere/webui/editor/WSearchEditor.java index e16f6650c7..ba32675ca4 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/editor/WSearchEditor.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/editor/WSearchEditor.java @@ -37,9 +37,11 @@ import org.adempiere.webui.panel.InfoProductPanel; import org.compiere.model.GridField; import org.compiere.model.Lookup; import org.compiere.model.MLookup; +import org.compiere.model.MLookupFactory; import org.compiere.model.MRole; import org.compiere.util.CLogger; import org.compiere.util.DB; +import org.compiere.util.DisplayType; import org.compiere.util.Env; import org.compiere.util.Msg; import org.zkoss.zk.ui.event.Event; @@ -840,4 +842,42 @@ public class WSearchEditor extends WEditor implements ContextMenuListener, Value } } + + /** + * @param windowNo + * @return WSearchEditor + */ + public static WSearchEditor createBPartner(int windowNo) { + int AD_Column_ID = 3499; // C_Invoice.C_BPartner_ID + try + { + Lookup lookup = MLookupFactory.get (Env.getCtx(), windowNo, + 0, AD_Column_ID, DisplayType.Search); + return new WSearchEditor ("C_BPartner_ID", false, false, true, lookup); + } + catch (Exception e) + { + log.log(Level.SEVERE, "", e); + } + return null; + } + + /** + * @param windowNo + * @return WSearchEditor + */ + public static WSearchEditor createProduct(int windowNo) { + int AD_Column_ID = 3840; // C_InvoiceLine.M_Product_ID + try + { + Lookup lookup = MLookupFactory.get (Env.getCtx(), windowNo, 0, + AD_Column_ID, DisplayType.Search); + return new WSearchEditor("M_Product_ID", false, false, true, lookup); + } + catch (Exception e) + { + log.log(Level.SEVERE, "", e); + } + return null; + } }