From 1b2007ed3b1db09fc678dc6ef3b59300615e19d0 Mon Sep 17 00:00:00 2001 From: Carlos Ruiz Date: Mon, 21 Jan 2019 15:37:14 +0100 Subject: [PATCH] IDEMPIERE-3876 Encoding and line delimiter issues / convert sources to unix line delimiter --- .../org/compiere/model/CalloutPayment.java | 992 +-- .../org/compiere/process/DunningPrint.java | 212 +- .../org/compiere/process/ImportBPartner.java | 664 +- .../src/org/compiere/process/InvoiceNGL.java | 342 +- .../process/PaySelectionCreateFrom.java | 184 +- .../compiere/process/YearCreatePeriods.java | 146 +- .../src/org/compiere/acct/DocLine.java | 2336 +++--- .../org/compiere/acct/Doc_AllocationHdr.java | 2006 ++--- .../src/org/compiere/acct/Doc_GLJournal.java | 348 +- .../src/org/compiere/acct/Doc_Order.java | 630 +- .../src/org/compiere/db/DBRes_hu.java | 126 +- .../compiere/model/MAcctSchemaElement.java | 1132 +-- .../src/org/compiere/model/MAcctSchemaGL.java | 260 +- .../src/org/compiere/model/MAsset.java | 1224 ++-- .../src/org/compiere/model/MAssetChange.java | 296 +- .../org/compiere/model/MBPBankAccount.java | 370 +- .../src/org/compiere/model/MCash.java | 1720 ++--- .../src/org/compiere/model/MChat.java | 126 +- .../src/org/compiere/model/MChatEntry.java | 108 +- .../src/org/compiere/model/MChatType.java | 44 +- .../src/org/compiere/model/MClient.java | 1168 +-- .../src/org/compiere/model/MContainer.java | 240 +- .../org/compiere/model/MContainerElement.java | 70 +- .../compiere/model/MDepreciationWorkfile.java | 1574 ++-- .../src/org/compiere/model/MDunningLevel.java | 174 +- .../org/compiere/model/MDunningRunLine.java | 210 +- .../src/org/compiere/model/MInterestArea.java | 218 +- .../src/org/compiere/model/MNewsItem.java | 36 +- .../org/compiere/model/MPaySelectionLine.java | 106 +- .../org/compiere/model/MPaymentValidate.java | 144 +- .../src/org/compiere/model/MPeriod.java | 1750 ++--- .../src/org/compiere/model/MRole.java | 2838 ++++---- .../src/org/compiere/model/MSchedulerLog.java | 54 +- .../src/org/compiere/model/MSequence.java | 1842 ++--- .../org/compiere/model/MWebProjectDomain.java | 134 +- .../src/org/compiere/model/M_Element.java | 430 +- .../org/compiere/model/TranslationTable.java | 52 +- .../src/org/compiere/print/DataEngine.java | 2458 +++---- .../org/compiere/report/MReportColumn.java | 970 +-- .../src/org/compiere/util/AmtInWords_IN.java | 326 +- .../src/org/compiere/util/AmtInWords_SR.java | 522 +- .../src/org/compiere/util/CLogger.java | 680 +- .../src/org/compiere/util/IniRes_hu.java | 94 +- .../src/org/compiere/util/Login.java | 1838 ++--- .../src/org/compiere/util/Msg.java | 202 +- .../src/test/functional/MBPGroupTest.java | 38 +- .../functional/MBPartnerLocationTest.java | 44 +- .../src/test/functional/MBPartnerTest.java | 38 +- .../src/test/functional/MProductTest.java | 58 +- .../src/test/functional/MUserTest.java | 44 +- org.adempiere.install/build.xml | 114 +- .../src/org/compiere/install/SetupRes_hu.java | 236 +- .../org/compiere/install/util/AppsAction.java | 96 +- .../handler/SQLStatementElementHandler.java | 336 +- .../pipo/AbstractElementHandler.java | 38 +- .../src/org/adempiere/pipo/PackOut.java | 1786 ++--- .../pipo/handler/WorkflowElementHandler.java | 904 +-- .../src/test/functional/PackOutTest.java | 72 +- .../pipo2/AbstractElementHandler.java | 2 +- .../report/jasper/ReportStarter.java | 2976 ++++---- .../postgresql/ImportIdempiere.bat | 100 +- .../compiere/ldap/LdapConnectionHandler.java | 198 +- .../server/org/compiere/ldap/LdapMessage.java | 100 +- .../server/org/compiere/ldap/LdapResult.java | 68 +- org.adempiere.server/standard.css | 296 +- .../src/org/compiere/apps/AppsAction.java | 98 +- .../src/org/compiere/apps/ProcessDialog.java | 1372 ++-- .../src/org/compiere/apps/form/FormFrame.java | 962 +-- .../src/org/compiere/minigrid/MiniTable.java | 654 +- .../src/org/compiere/plaf/PlafRes_hu.java | 264 +- .../src/org/compiere/print/Viewer.java | 2774 +++---- .../org/adempiere/webui/panel/RolePanel.java | 48 +- org.adempiere.ui.zk/WEB-INF/xsd/zul.xsd | 6420 ++++++++--------- org.adempiere.ui.zk/WEB-INF/zk.xml | 4 +- org.adempiere.ui.zk/gif.jsp | 40 +- org.adempiere.ui.zk/labeldata.jsp | 86 +- .../org/compiere/apps/form/TrxMaterial.java | 304 +- 77 files changed, 25983 insertions(+), 25983 deletions(-) diff --git a/org.adempiere.base.callout/src/org/compiere/model/CalloutPayment.java b/org.adempiere.base.callout/src/org/compiere/model/CalloutPayment.java index 1e46f97b1c..63fa4d3f3e 100644 --- a/org.adempiere.base.callout/src/org/compiere/model/CalloutPayment.java +++ b/org.adempiere.base.callout/src/org/compiere/model/CalloutPayment.java @@ -1,500 +1,500 @@ -/****************************************************************************** - * 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.compiere.model; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.Properties; -import java.util.logging.Level; - -import org.compiere.util.DB; -import org.compiere.util.Env; - -/** - * Payment Callouts. org.compiere.model.CalloutPayment.* - * @author Jorg Janke - * @version $Id: CalloutPayment.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $ - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - *
  • BF [ 1803316 ] CalloutPayment: use C_Order.Bill_BPartner_ID - * @author j2garcia - GlobalQSS - *
  • BF [ 2021745 ] Cannot assign project to payment with charge - * @author Carlos Ruiz - GlobalQSS - *
  • BF [ 1933948 ] CalloutPayment working just with Draft Status - */ -public class CalloutPayment extends CalloutEngine -{ - - /** - * Payment_Invoice. when Invoice selected - set C_Currency_ID - - * C_BPartner_ID - DiscountAmt = C_Invoice_Discount (ID, DateTrx) - PayAmt = - * invoiceOpen (ID) - Discount - WriteOffAmt = 0 - * @param ctx context - * @param WindowNo current Window No - * @param mTab Grid Tab - * @param mField Grid Field - * @param value New Value - * @return null or error message - */ - public String invoice(Properties ctx, int WindowNo, GridTab mTab, - GridField mField, Object value) - { - Integer C_Invoice_ID = (Integer)value; - if (isCalloutActive () // assuming it is resetting value - || C_Invoice_ID == null || C_Invoice_ID.intValue () == 0) - return ""; - mTab.setValue ("C_Order_ID", null); - mTab.setValue ("C_Charge_ID", null); - mTab.setValue ("IsPrepayment", Boolean.FALSE); - // - mTab.setValue ("DiscountAmt", Env.ZERO); - mTab.setValue ("WriteOffAmt", Env.ZERO); - // mTab.setValue ("IsOverUnderPayment", Boolean.FALSE); - mTab.setValue ("OverUnderAmt", Env.ZERO); - int C_InvoicePaySchedule_ID = 0; - if (Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_Invoice_ID") == C_Invoice_ID.intValue () - && Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_InvoicePaySchedule_ID") != 0) - { - C_InvoicePaySchedule_ID = Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_InvoicePaySchedule_ID"); - } - // Payment Date - Timestamp ts = (Timestamp)mTab.getValue ("DateTrx"); - if (ts == null) - ts = new Timestamp (System.currentTimeMillis ()); - // - String sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2 - + " invoiceOpen(C_Invoice_ID, ?)," // 3 #1 - + " invoiceDiscount(C_Invoice_ID,?,?), IsSOTrx " // 4..5 #2/3 - + "FROM C_Invoice WHERE C_Invoice_ID=?"; // #4 - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement (sql, null); - pstmt.setInt (1, C_InvoicePaySchedule_ID); - pstmt.setTimestamp (2, ts); - pstmt.setInt (3, C_InvoicePaySchedule_ID); - pstmt.setInt (4, C_Invoice_ID.intValue ()); - rs = pstmt.executeQuery (); - if (rs.next ()) - { - mTab.setValue ("C_BPartner_ID", Integer.valueOf(rs.getInt (1))); - int C_Currency_ID = rs.getInt (2); // Set Invoice Currency - mTab.setValue ("C_Currency_ID", Integer.valueOf(C_Currency_ID)); - // - BigDecimal InvoiceOpen = rs.getBigDecimal (3); // Set Invoice - // OPen Amount - if (InvoiceOpen == null) - InvoiceOpen = Env.ZERO; - BigDecimal DiscountAmt = rs.getBigDecimal (4); // Set Discount - // Amt - if (DiscountAmt == null) - DiscountAmt = Env.ZERO; - mTab.setValue ("PayAmt", InvoiceOpen.subtract (DiscountAmt)); - mTab.setValue ("DiscountAmt", DiscountAmt); - // reset as dependent fields get reset - Env.setContext (ctx, WindowNo, "C_Invoice_ID", C_Invoice_ID - .toString ()); - mTab.setValue ("C_Invoice_ID", C_Invoice_ID); - } - } - catch (SQLException e) - { - log.log (Level.SEVERE, sql, e); - return e.getLocalizedMessage (); - } - finally - { - DB.close (rs, pstmt); - } - return docType (ctx, WindowNo, mTab, mField, value); - } // invoice - - /** - * Payment_Order. when Waiting Payment Order selected - set C_Currency_ID - - * C_BPartner_ID - DiscountAmt = C_Invoice_Discount (ID, DateTrx) - PayAmt = - * invoiceOpen (ID) - Discount - WriteOffAmt = 0 - * @param ctx context - * @param WindowNo current Window No - * @param mTab Grid Tab - * @param mField Grid Field - * @param value New Value - * @return null or error message - */ - public String order(Properties ctx, int WindowNo, GridTab mTab, - GridField mField, Object value) - { - Integer C_Order_ID = (Integer)value; - if (isCalloutActive () // assuming it is resetting value - || C_Order_ID == null || C_Order_ID.intValue () == 0) - return ""; - mTab.setValue ("C_Invoice_ID", null); - mTab.setValue ("C_Charge_ID", null); - mTab.setValue ("IsPrepayment", Boolean.TRUE); - // - mTab.setValue ("DiscountAmt", Env.ZERO); - mTab.setValue ("WriteOffAmt", Env.ZERO); - mTab.setValue ("IsOverUnderPayment", Boolean.FALSE); - mTab.setValue ("OverUnderAmt", Env.ZERO); - // Payment Date - Timestamp ts = (Timestamp)mTab.getValue ("DateTrx"); - if (ts == null) - ts = new Timestamp (System.currentTimeMillis ()); - // - String sql = "SELECT COALESCE(Bill_BPartner_ID, C_BPartner_ID) as C_BPartner_ID " - + ", C_Currency_ID " - + ", GrandTotal " - + "FROM C_Order WHERE C_Order_ID=?"; // #1 - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement (sql, null); - pstmt.setInt (1, C_Order_ID.intValue ()); - rs = pstmt.executeQuery (); - if (rs.next ()) - { - mTab.setValue ("C_BPartner_ID", Integer.valueOf(rs.getInt (1))); - int C_Currency_ID = rs.getInt (2); // Set Order Currency - mTab.setValue ("C_Currency_ID", Integer.valueOf(C_Currency_ID)); - // - BigDecimal GrandTotal = rs.getBigDecimal (3); // Set Pay - // Amount - if (GrandTotal == null) - GrandTotal = Env.ZERO; - mTab.setValue ("PayAmt", GrandTotal); - } - } - catch (SQLException e) - { - log.log (Level.SEVERE, sql, e); - return e.getLocalizedMessage (); - } - finally - { - DB.close (rs, pstmt); - } - return docType (ctx, WindowNo, mTab, mField, value); - } // order - +/****************************************************************************** + * 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.compiere.model; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.Properties; +import java.util.logging.Level; + +import org.compiere.util.DB; +import org.compiere.util.Env; + +/** + * Payment Callouts. org.compiere.model.CalloutPayment.* + * @author Jorg Janke + * @version $Id: CalloutPayment.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $ + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1803316 ] CalloutPayment: use C_Order.Bill_BPartner_ID + * @author j2garcia - GlobalQSS + *
  • BF [ 2021745 ] Cannot assign project to payment with charge + * @author Carlos Ruiz - GlobalQSS + *
  • BF [ 1933948 ] CalloutPayment working just with Draft Status + */ +public class CalloutPayment extends CalloutEngine +{ + + /** + * Payment_Invoice. when Invoice selected - set C_Currency_ID - + * C_BPartner_ID - DiscountAmt = C_Invoice_Discount (ID, DateTrx) - PayAmt = + * invoiceOpen (ID) - Discount - WriteOffAmt = 0 + * @param ctx context + * @param WindowNo current Window No + * @param mTab Grid Tab + * @param mField Grid Field + * @param value New Value + * @return null or error message + */ + public String invoice(Properties ctx, int WindowNo, GridTab mTab, + GridField mField, Object value) + { + Integer C_Invoice_ID = (Integer)value; + if (isCalloutActive () // assuming it is resetting value + || C_Invoice_ID == null || C_Invoice_ID.intValue () == 0) + return ""; + mTab.setValue ("C_Order_ID", null); + mTab.setValue ("C_Charge_ID", null); + mTab.setValue ("IsPrepayment", Boolean.FALSE); + // + mTab.setValue ("DiscountAmt", Env.ZERO); + mTab.setValue ("WriteOffAmt", Env.ZERO); + // mTab.setValue ("IsOverUnderPayment", Boolean.FALSE); + mTab.setValue ("OverUnderAmt", Env.ZERO); + int C_InvoicePaySchedule_ID = 0; + if (Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_Invoice_ID") == C_Invoice_ID.intValue () + && Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_InvoicePaySchedule_ID") != 0) + { + C_InvoicePaySchedule_ID = Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_InvoicePaySchedule_ID"); + } + // Payment Date + Timestamp ts = (Timestamp)mTab.getValue ("DateTrx"); + if (ts == null) + ts = new Timestamp (System.currentTimeMillis ()); + // + String sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2 + + " invoiceOpen(C_Invoice_ID, ?)," // 3 #1 + + " invoiceDiscount(C_Invoice_ID,?,?), IsSOTrx " // 4..5 #2/3 + + "FROM C_Invoice WHERE C_Invoice_ID=?"; // #4 + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement (sql, null); + pstmt.setInt (1, C_InvoicePaySchedule_ID); + pstmt.setTimestamp (2, ts); + pstmt.setInt (3, C_InvoicePaySchedule_ID); + pstmt.setInt (4, C_Invoice_ID.intValue ()); + rs = pstmt.executeQuery (); + if (rs.next ()) + { + mTab.setValue ("C_BPartner_ID", Integer.valueOf(rs.getInt (1))); + int C_Currency_ID = rs.getInt (2); // Set Invoice Currency + mTab.setValue ("C_Currency_ID", Integer.valueOf(C_Currency_ID)); + // + BigDecimal InvoiceOpen = rs.getBigDecimal (3); // Set Invoice + // OPen Amount + if (InvoiceOpen == null) + InvoiceOpen = Env.ZERO; + BigDecimal DiscountAmt = rs.getBigDecimal (4); // Set Discount + // Amt + if (DiscountAmt == null) + DiscountAmt = Env.ZERO; + mTab.setValue ("PayAmt", InvoiceOpen.subtract (DiscountAmt)); + mTab.setValue ("DiscountAmt", DiscountAmt); + // reset as dependent fields get reset + Env.setContext (ctx, WindowNo, "C_Invoice_ID", C_Invoice_ID + .toString ()); + mTab.setValue ("C_Invoice_ID", C_Invoice_ID); + } + } + catch (SQLException e) + { + log.log (Level.SEVERE, sql, e); + return e.getLocalizedMessage (); + } + finally + { + DB.close (rs, pstmt); + } + return docType (ctx, WindowNo, mTab, mField, value); + } // invoice + + /** + * Payment_Order. when Waiting Payment Order selected - set C_Currency_ID - + * C_BPartner_ID - DiscountAmt = C_Invoice_Discount (ID, DateTrx) - PayAmt = + * invoiceOpen (ID) - Discount - WriteOffAmt = 0 + * @param ctx context + * @param WindowNo current Window No + * @param mTab Grid Tab + * @param mField Grid Field + * @param value New Value + * @return null or error message + */ + public String order(Properties ctx, int WindowNo, GridTab mTab, + GridField mField, Object value) + { + Integer C_Order_ID = (Integer)value; + if (isCalloutActive () // assuming it is resetting value + || C_Order_ID == null || C_Order_ID.intValue () == 0) + return ""; + mTab.setValue ("C_Invoice_ID", null); + mTab.setValue ("C_Charge_ID", null); + mTab.setValue ("IsPrepayment", Boolean.TRUE); + // + mTab.setValue ("DiscountAmt", Env.ZERO); + mTab.setValue ("WriteOffAmt", Env.ZERO); + mTab.setValue ("IsOverUnderPayment", Boolean.FALSE); + mTab.setValue ("OverUnderAmt", Env.ZERO); + // Payment Date + Timestamp ts = (Timestamp)mTab.getValue ("DateTrx"); + if (ts == null) + ts = new Timestamp (System.currentTimeMillis ()); + // + String sql = "SELECT COALESCE(Bill_BPartner_ID, C_BPartner_ID) as C_BPartner_ID " + + ", C_Currency_ID " + + ", GrandTotal " + + "FROM C_Order WHERE C_Order_ID=?"; // #1 + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement (sql, null); + pstmt.setInt (1, C_Order_ID.intValue ()); + rs = pstmt.executeQuery (); + if (rs.next ()) + { + mTab.setValue ("C_BPartner_ID", Integer.valueOf(rs.getInt (1))); + int C_Currency_ID = rs.getInt (2); // Set Order Currency + mTab.setValue ("C_Currency_ID", Integer.valueOf(C_Currency_ID)); + // + BigDecimal GrandTotal = rs.getBigDecimal (3); // Set Pay + // Amount + if (GrandTotal == null) + GrandTotal = Env.ZERO; + mTab.setValue ("PayAmt", GrandTotal); + } + } + catch (SQLException e) + { + log.log (Level.SEVERE, sql, e); + return e.getLocalizedMessage (); + } + finally + { + DB.close (rs, pstmt); + } + return docType (ctx, WindowNo, mTab, mField, value); + } // order + // 2008/07/18 Globalqss [ 2021745 ] // Deleted project method - - /** - * Payment_Charge. - reset - C_BPartner_ID, Invoice, Order, Project, - * Discount, WriteOff - * @param ctx context - * @param WindowNo current Window No - * @param mTab Grid Tab - * @param mField Grid Field - * @param value New Value - * @return null or error message - */ - public String charge(Properties ctx, int WindowNo, GridTab mTab, - GridField mField, Object value) - { - Integer C_Charge_ID = (Integer)value; - if (isCalloutActive () // assuming it is resetting value - || C_Charge_ID == null || C_Charge_ID.intValue () == 0) - return ""; - mTab.setValue ("C_Invoice_ID", null); - mTab.setValue ("C_Order_ID", null); + + /** + * Payment_Charge. - reset - C_BPartner_ID, Invoice, Order, Project, + * Discount, WriteOff + * @param ctx context + * @param WindowNo current Window No + * @param mTab Grid Tab + * @param mField Grid Field + * @param value New Value + * @return null or error message + */ + public String charge(Properties ctx, int WindowNo, GridTab mTab, + GridField mField, Object value) + { + Integer C_Charge_ID = (Integer)value; + if (isCalloutActive () // assuming it is resetting value + || C_Charge_ID == null || C_Charge_ID.intValue () == 0) + return ""; + mTab.setValue ("C_Invoice_ID", null); + mTab.setValue ("C_Order_ID", null); // 2008/07/18 Globalqss [ 2021745 ] // mTab.setValue ("C_Project_ID", null); - mTab.setValue ("IsPrepayment", Boolean.FALSE); - // - mTab.setValue ("DiscountAmt", Env.ZERO); - mTab.setValue ("WriteOffAmt", Env.ZERO); - mTab.setValue ("IsOverUnderPayment", Boolean.FALSE); - mTab.setValue ("OverUnderAmt", Env.ZERO); - return ""; - } // charge - - /** - * Payment_Document Type. Verify that Document Type (AP/AR) and Invoice - * (SO/PO) are in sync - * @param ctx context - * @param WindowNo current Window No - * @param mTab Grid Tab - * @param mField Grid Field - * @param value New Value - * @return null or error message - */ - public String docType(Properties ctx, int WindowNo, GridTab mTab, - GridField mField, Object value) - { - int C_Invoice_ID = Env.getContextAsInt (ctx, WindowNo, "C_Invoice_ID"); - int C_Order_ID = Env.getContextAsInt (ctx, WindowNo, "C_Order_ID"); - int C_DocType_ID = Env.getContextAsInt (ctx, WindowNo, "C_DocType_ID"); - if (log.isLoggable(Level.FINE)) log.fine ("Payment_DocType - C_Invoice_ID=" + C_Invoice_ID - + ", C_DocType_ID=" + C_DocType_ID); - MDocType dt = null; - if (C_DocType_ID != 0) - { - dt = MDocType.get (ctx, C_DocType_ID); - Env - .setContext (ctx, WindowNo, "IsSOTrx", dt.isSOTrx () ? "Y" - : "N"); - } - // Invoice - if (C_Invoice_ID != 0) - { - MInvoice inv = new MInvoice (ctx, C_Invoice_ID, null); - if (dt != null) - { - if (inv.isSOTrx () != dt.isSOTrx ()) - return "PaymentDocTypeInvoiceInconsistent"; - } - } - // globalqss - Allow prepayment to Purchase Orders - // Order Waiting Payment (can only be SO) - // if (C_Order_ID != 0 && dt != null && !dt.isSOTrx()) - // return "PaymentDocTypeInvoiceInconsistent"; - // Order - if (C_Order_ID != 0) - { - MOrder ord = new MOrder (ctx, C_Order_ID, null); - if (dt != null) - { - if (ord.isSOTrx () != dt.isSOTrx ()) - return "PaymentDocTypeInvoiceInconsistent"; - } - } - return ""; - } // docType - - /** - * Payment_Amounts. Change of: - IsOverUnderPayment -> set OverUnderAmt to 0 - - * C_Currency_ID, C_ConvesionRate_ID -> convert all - PayAmt, DiscountAmt, - * WriteOffAmt, OverUnderAmt -> PayAmt make sure that add up to - * InvoiceOpenAmt - * @param ctx context - * @param WindowNo current Window No - * @param mTab Grid Tab - * @param mField Grid Field - * @param value New Value - * @param oldValue Old Value - * @return null or error message - */ - public String amounts(Properties ctx, int WindowNo, GridTab mTab, - GridField mField, Object value, Object oldValue) - { - if (isCalloutActive ()) // assuming it is resetting value - return ""; - int C_Invoice_ID = Env.getContextAsInt (ctx, WindowNo, "C_Invoice_ID"); - // New Payment - if (Env.getContextAsInt (ctx, WindowNo, "C_Payment_ID") == 0 - && Env.getContextAsInt (ctx, WindowNo, "C_BPartner_ID") == 0 - && C_Invoice_ID == 0) - return ""; - // Changed Column - String colName = mField.getColumnName (); - if (colName.equals ("IsOverUnderPayment") // Set Over/Under Amt to - // Zero - || !"Y".equals (Env - .getContext (ctx, WindowNo, "IsOverUnderPayment"))) - mTab.setValue ("OverUnderAmt", Env.ZERO); - int C_InvoicePaySchedule_ID = 0; - if (Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_Invoice_ID") == C_Invoice_ID - && Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_InvoicePaySchedule_ID") != 0) - { - C_InvoicePaySchedule_ID = Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_InvoicePaySchedule_ID"); - } - // Get Open Amount & Invoice Currency - BigDecimal InvoiceOpenAmt = Env.ZERO; - int C_Currency_Invoice_ID = 0; - if (C_Invoice_ID != 0) - { - Timestamp ts = (Timestamp)mTab.getValue ("DateTrx"); - if (ts == null) - ts = new Timestamp (System.currentTimeMillis ()); - String sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2 - + " invoiceOpen(C_Invoice_ID,?)," // 3 #1 - + " invoiceDiscount(C_Invoice_ID,?,?), IsSOTrx " // 4..5 #2/3 - + "FROM C_Invoice WHERE C_Invoice_ID=?"; // #4 - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement (sql, null); - pstmt.setInt (1, C_InvoicePaySchedule_ID); - pstmt.setTimestamp (2, ts); - pstmt.setInt (3, C_InvoicePaySchedule_ID); - pstmt.setInt (4, C_Invoice_ID); - rs = pstmt.executeQuery (); - if (rs.next ()) - { - C_Currency_Invoice_ID = rs.getInt (2); - InvoiceOpenAmt = rs.getBigDecimal (3); // Set Invoice Open - // Amount - if (InvoiceOpenAmt == null) - InvoiceOpenAmt = Env.ZERO; - } - } - catch (SQLException e) - { - log.log (Level.SEVERE, sql, e); - return e.getLocalizedMessage (); - } - finally - { - DB.close (rs, pstmt); - rs = null; - pstmt = null; - } - } // get Invoice Info - if (log.isLoggable(Level.FINE)) log.fine ("Open=" + InvoiceOpenAmt + ", C_Invoice_ID=" + C_Invoice_ID - + ", C_Currency_ID=" + C_Currency_Invoice_ID); - // Get Info from Tab - BigDecimal PayAmt = (BigDecimal)mTab.getValue ("PayAmt"); - if (PayAmt == null) - PayAmt = Env.ZERO; - BigDecimal DiscountAmt = (BigDecimal)mTab.getValue ("DiscountAmt"); - if (DiscountAmt == null) - DiscountAmt = Env.ZERO; - BigDecimal WriteOffAmt = (BigDecimal)mTab.getValue ("WriteOffAmt"); - if (WriteOffAmt == null) - WriteOffAmt = Env.ZERO; - BigDecimal OverUnderAmt = (BigDecimal)mTab.getValue ("OverUnderAmt"); - if (OverUnderAmt == null) - OverUnderAmt = Env.ZERO; - if (log.isLoggable(Level.FINE)) log.fine ("Pay=" + PayAmt + ", Discount=" + DiscountAmt + ", WriteOff=" - + WriteOffAmt + ", OverUnderAmt=" + OverUnderAmt); - // Get Currency Info - Integer curr_int = (Integer) mTab.getValue ("C_Currency_ID"); - if (curr_int == null) - curr_int = Integer.valueOf(0); - int C_Currency_ID = curr_int.intValue (); - MCurrency currency = MCurrency.get (ctx, C_Currency_ID); - Timestamp ConvDate = (Timestamp)mTab.getValue ("DateTrx"); - int C_ConversionType_ID = 0; - Integer ii = (Integer)mTab.getValue ("C_ConversionType_ID"); - if (ii != null) - C_ConversionType_ID = ii.intValue (); - int AD_Client_ID = Env.getContextAsInt (ctx, WindowNo, "AD_Client_ID"); - int AD_Org_ID = Env.getContextAsInt (ctx, WindowNo, "AD_Org_ID"); - // Get Currency Rate - BigDecimal CurrencyRate = Env.ONE; - if ((C_Currency_ID > 0 && C_Currency_Invoice_ID > 0 && C_Currency_ID != C_Currency_Invoice_ID) - || colName.equals ("C_Currency_ID") - || colName.equals ("C_ConversionType_ID")) - { - if (log.isLoggable(Level.FINE)) log.fine ("InvCurrency=" + C_Currency_Invoice_ID + ", PayCurrency=" - + C_Currency_ID + ", Date=" + ConvDate + ", Type=" - + C_ConversionType_ID); - CurrencyRate = MConversionRate.getRate (C_Currency_Invoice_ID, - C_Currency_ID, ConvDate, C_ConversionType_ID, AD_Client_ID, - AD_Org_ID); - if (CurrencyRate == null || CurrencyRate.compareTo (Env.ZERO) == 0) - { - // mTab.setValue("C_Currency_ID", new - // Integer(C_Currency_Invoice_ID)); // does not work - if (C_Currency_Invoice_ID == 0) - return ""; // no error message when no invoice is selected - return "NoCurrencyConversion"; - } - // - InvoiceOpenAmt = InvoiceOpenAmt.multiply (CurrencyRate).setScale ( - currency.getStdPrecision (), RoundingMode.HALF_UP); - if (log.isLoggable(Level.FINE)) log.fine ("Rate=" + CurrencyRate + ", InvoiceOpenAmt=" - + InvoiceOpenAmt); - } - // Currency Changed - convert all - if (colName.equals ("C_Currency_ID") - || colName.equals ("C_ConversionType_ID")) - { - PayAmt = PayAmt.multiply (CurrencyRate).setScale ( - currency.getStdPrecision (), RoundingMode.HALF_UP); - mTab.setValue ("PayAmt", PayAmt); - DiscountAmt = DiscountAmt.multiply (CurrencyRate).setScale ( - currency.getStdPrecision (), RoundingMode.HALF_UP); - mTab.setValue ("DiscountAmt", DiscountAmt); - WriteOffAmt = WriteOffAmt.multiply (CurrencyRate).setScale ( - currency.getStdPrecision (), RoundingMode.HALF_UP); - mTab.setValue ("WriteOffAmt", WriteOffAmt); - OverUnderAmt = OverUnderAmt.multiply (CurrencyRate).setScale ( - currency.getStdPrecision (), RoundingMode.HALF_UP); - mTab.setValue ("OverUnderAmt", OverUnderAmt); - } - // No Invoice - Set Discount, Writeoff, Under/Over to 0 - else if (C_Invoice_ID == 0) - { - if (Env.ZERO.compareTo (DiscountAmt) != 0) - mTab.setValue ("DiscountAmt", Env.ZERO); - if (Env.ZERO.compareTo (WriteOffAmt) != 0) - mTab.setValue ("WriteOffAmt", Env.ZERO); - if (Env.ZERO.compareTo (OverUnderAmt) != 0) - mTab.setValue ("OverUnderAmt", Env.ZERO); - } else { - boolean processed = mTab.getValueAsBoolean(MPayment.COLUMNNAME_Processed); - if (colName.equals ("PayAmt") - && (!processed) - && "Y".equals (Env.getContext (ctx, WindowNo, "IsOverUnderPayment"))) - { - OverUnderAmt = InvoiceOpenAmt.subtract (PayAmt).subtract(DiscountAmt).subtract (WriteOffAmt); - if (OverUnderAmt.signum() > 0) { // no discount because is not paid in full - DiscountAmt = Env.ZERO; - mTab.setValue ("DiscountAmt", DiscountAmt); - OverUnderAmt = InvoiceOpenAmt.subtract (PayAmt).subtract(DiscountAmt).subtract (WriteOffAmt); - } - mTab.setValue ("OverUnderAmt", OverUnderAmt); - } - else if (colName.equals ("PayAmt") - && (!processed)) - { - WriteOffAmt = InvoiceOpenAmt.subtract (PayAmt).subtract ( - DiscountAmt).subtract (OverUnderAmt); - mTab.setValue ("WriteOffAmt", WriteOffAmt); - } - else if (colName.equals ("IsOverUnderPayment") - && (!processed)) - { - boolean overUnderPaymentActive = "Y".equals (Env.getContext (ctx, - WindowNo, "IsOverUnderPayment")); - if (overUnderPaymentActive) - { - OverUnderAmt = InvoiceOpenAmt.subtract (PayAmt).subtract ( - DiscountAmt); - mTab.setValue ("WriteOffAmt", Env.ZERO); - mTab.setValue ("OverUnderAmt", OverUnderAmt); - }else{ - WriteOffAmt = InvoiceOpenAmt.subtract (PayAmt).subtract ( - DiscountAmt); - mTab.setValue ("WriteOffAmt", WriteOffAmt); - mTab.setValue ("OverUnderAmt", Env.ZERO); - } - } - // Added Lines By Goodwill (02-03-2006) - // Reason: we must make the callout is called just when docstatus is - // draft - // Old Code : else // calculate PayAmt - // New Code : - else if ((!processed)) // calculate - // PayAmt - // End By Goodwill - { - PayAmt = InvoiceOpenAmt.subtract (DiscountAmt).subtract ( - WriteOffAmt).subtract (OverUnderAmt); - mTab.setValue ("PayAmt", PayAmt); - } - } - return ""; - } // amounts -} // CalloutPayment + mTab.setValue ("IsPrepayment", Boolean.FALSE); + // + mTab.setValue ("DiscountAmt", Env.ZERO); + mTab.setValue ("WriteOffAmt", Env.ZERO); + mTab.setValue ("IsOverUnderPayment", Boolean.FALSE); + mTab.setValue ("OverUnderAmt", Env.ZERO); + return ""; + } // charge + + /** + * Payment_Document Type. Verify that Document Type (AP/AR) and Invoice + * (SO/PO) are in sync + * @param ctx context + * @param WindowNo current Window No + * @param mTab Grid Tab + * @param mField Grid Field + * @param value New Value + * @return null or error message + */ + public String docType(Properties ctx, int WindowNo, GridTab mTab, + GridField mField, Object value) + { + int C_Invoice_ID = Env.getContextAsInt (ctx, WindowNo, "C_Invoice_ID"); + int C_Order_ID = Env.getContextAsInt (ctx, WindowNo, "C_Order_ID"); + int C_DocType_ID = Env.getContextAsInt (ctx, WindowNo, "C_DocType_ID"); + if (log.isLoggable(Level.FINE)) log.fine ("Payment_DocType - C_Invoice_ID=" + C_Invoice_ID + + ", C_DocType_ID=" + C_DocType_ID); + MDocType dt = null; + if (C_DocType_ID != 0) + { + dt = MDocType.get (ctx, C_DocType_ID); + Env + .setContext (ctx, WindowNo, "IsSOTrx", dt.isSOTrx () ? "Y" + : "N"); + } + // Invoice + if (C_Invoice_ID != 0) + { + MInvoice inv = new MInvoice (ctx, C_Invoice_ID, null); + if (dt != null) + { + if (inv.isSOTrx () != dt.isSOTrx ()) + return "PaymentDocTypeInvoiceInconsistent"; + } + } + // globalqss - Allow prepayment to Purchase Orders + // Order Waiting Payment (can only be SO) + // if (C_Order_ID != 0 && dt != null && !dt.isSOTrx()) + // return "PaymentDocTypeInvoiceInconsistent"; + // Order + if (C_Order_ID != 0) + { + MOrder ord = new MOrder (ctx, C_Order_ID, null); + if (dt != null) + { + if (ord.isSOTrx () != dt.isSOTrx ()) + return "PaymentDocTypeInvoiceInconsistent"; + } + } + return ""; + } // docType + + /** + * Payment_Amounts. Change of: - IsOverUnderPayment -> set OverUnderAmt to 0 - + * C_Currency_ID, C_ConvesionRate_ID -> convert all - PayAmt, DiscountAmt, + * WriteOffAmt, OverUnderAmt -> PayAmt make sure that add up to + * InvoiceOpenAmt + * @param ctx context + * @param WindowNo current Window No + * @param mTab Grid Tab + * @param mField Grid Field + * @param value New Value + * @param oldValue Old Value + * @return null or error message + */ + public String amounts(Properties ctx, int WindowNo, GridTab mTab, + GridField mField, Object value, Object oldValue) + { + if (isCalloutActive ()) // assuming it is resetting value + return ""; + int C_Invoice_ID = Env.getContextAsInt (ctx, WindowNo, "C_Invoice_ID"); + // New Payment + if (Env.getContextAsInt (ctx, WindowNo, "C_Payment_ID") == 0 + && Env.getContextAsInt (ctx, WindowNo, "C_BPartner_ID") == 0 + && C_Invoice_ID == 0) + return ""; + // Changed Column + String colName = mField.getColumnName (); + if (colName.equals ("IsOverUnderPayment") // Set Over/Under Amt to + // Zero + || !"Y".equals (Env + .getContext (ctx, WindowNo, "IsOverUnderPayment"))) + mTab.setValue ("OverUnderAmt", Env.ZERO); + int C_InvoicePaySchedule_ID = 0; + if (Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_Invoice_ID") == C_Invoice_ID + && Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_InvoicePaySchedule_ID") != 0) + { + C_InvoicePaySchedule_ID = Env.getContextAsInt (ctx, WindowNo, Env.TAB_INFO, "C_InvoicePaySchedule_ID"); + } + // Get Open Amount & Invoice Currency + BigDecimal InvoiceOpenAmt = Env.ZERO; + int C_Currency_Invoice_ID = 0; + if (C_Invoice_ID != 0) + { + Timestamp ts = (Timestamp)mTab.getValue ("DateTrx"); + if (ts == null) + ts = new Timestamp (System.currentTimeMillis ()); + String sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2 + + " invoiceOpen(C_Invoice_ID,?)," // 3 #1 + + " invoiceDiscount(C_Invoice_ID,?,?), IsSOTrx " // 4..5 #2/3 + + "FROM C_Invoice WHERE C_Invoice_ID=?"; // #4 + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement (sql, null); + pstmt.setInt (1, C_InvoicePaySchedule_ID); + pstmt.setTimestamp (2, ts); + pstmt.setInt (3, C_InvoicePaySchedule_ID); + pstmt.setInt (4, C_Invoice_ID); + rs = pstmt.executeQuery (); + if (rs.next ()) + { + C_Currency_Invoice_ID = rs.getInt (2); + InvoiceOpenAmt = rs.getBigDecimal (3); // Set Invoice Open + // Amount + if (InvoiceOpenAmt == null) + InvoiceOpenAmt = Env.ZERO; + } + } + catch (SQLException e) + { + log.log (Level.SEVERE, sql, e); + return e.getLocalizedMessage (); + } + finally + { + DB.close (rs, pstmt); + rs = null; + pstmt = null; + } + } // get Invoice Info + if (log.isLoggable(Level.FINE)) log.fine ("Open=" + InvoiceOpenAmt + ", C_Invoice_ID=" + C_Invoice_ID + + ", C_Currency_ID=" + C_Currency_Invoice_ID); + // Get Info from Tab + BigDecimal PayAmt = (BigDecimal)mTab.getValue ("PayAmt"); + if (PayAmt == null) + PayAmt = Env.ZERO; + BigDecimal DiscountAmt = (BigDecimal)mTab.getValue ("DiscountAmt"); + if (DiscountAmt == null) + DiscountAmt = Env.ZERO; + BigDecimal WriteOffAmt = (BigDecimal)mTab.getValue ("WriteOffAmt"); + if (WriteOffAmt == null) + WriteOffAmt = Env.ZERO; + BigDecimal OverUnderAmt = (BigDecimal)mTab.getValue ("OverUnderAmt"); + if (OverUnderAmt == null) + OverUnderAmt = Env.ZERO; + if (log.isLoggable(Level.FINE)) log.fine ("Pay=" + PayAmt + ", Discount=" + DiscountAmt + ", WriteOff=" + + WriteOffAmt + ", OverUnderAmt=" + OverUnderAmt); + // Get Currency Info + Integer curr_int = (Integer) mTab.getValue ("C_Currency_ID"); + if (curr_int == null) + curr_int = Integer.valueOf(0); + int C_Currency_ID = curr_int.intValue (); + MCurrency currency = MCurrency.get (ctx, C_Currency_ID); + Timestamp ConvDate = (Timestamp)mTab.getValue ("DateTrx"); + int C_ConversionType_ID = 0; + Integer ii = (Integer)mTab.getValue ("C_ConversionType_ID"); + if (ii != null) + C_ConversionType_ID = ii.intValue (); + int AD_Client_ID = Env.getContextAsInt (ctx, WindowNo, "AD_Client_ID"); + int AD_Org_ID = Env.getContextAsInt (ctx, WindowNo, "AD_Org_ID"); + // Get Currency Rate + BigDecimal CurrencyRate = Env.ONE; + if ((C_Currency_ID > 0 && C_Currency_Invoice_ID > 0 && C_Currency_ID != C_Currency_Invoice_ID) + || colName.equals ("C_Currency_ID") + || colName.equals ("C_ConversionType_ID")) + { + if (log.isLoggable(Level.FINE)) log.fine ("InvCurrency=" + C_Currency_Invoice_ID + ", PayCurrency=" + + C_Currency_ID + ", Date=" + ConvDate + ", Type=" + + C_ConversionType_ID); + CurrencyRate = MConversionRate.getRate (C_Currency_Invoice_ID, + C_Currency_ID, ConvDate, C_ConversionType_ID, AD_Client_ID, + AD_Org_ID); + if (CurrencyRate == null || CurrencyRate.compareTo (Env.ZERO) == 0) + { + // mTab.setValue("C_Currency_ID", new + // Integer(C_Currency_Invoice_ID)); // does not work + if (C_Currency_Invoice_ID == 0) + return ""; // no error message when no invoice is selected + return "NoCurrencyConversion"; + } + // + InvoiceOpenAmt = InvoiceOpenAmt.multiply (CurrencyRate).setScale ( + currency.getStdPrecision (), RoundingMode.HALF_UP); + if (log.isLoggable(Level.FINE)) log.fine ("Rate=" + CurrencyRate + ", InvoiceOpenAmt=" + + InvoiceOpenAmt); + } + // Currency Changed - convert all + if (colName.equals ("C_Currency_ID") + || colName.equals ("C_ConversionType_ID")) + { + PayAmt = PayAmt.multiply (CurrencyRate).setScale ( + currency.getStdPrecision (), RoundingMode.HALF_UP); + mTab.setValue ("PayAmt", PayAmt); + DiscountAmt = DiscountAmt.multiply (CurrencyRate).setScale ( + currency.getStdPrecision (), RoundingMode.HALF_UP); + mTab.setValue ("DiscountAmt", DiscountAmt); + WriteOffAmt = WriteOffAmt.multiply (CurrencyRate).setScale ( + currency.getStdPrecision (), RoundingMode.HALF_UP); + mTab.setValue ("WriteOffAmt", WriteOffAmt); + OverUnderAmt = OverUnderAmt.multiply (CurrencyRate).setScale ( + currency.getStdPrecision (), RoundingMode.HALF_UP); + mTab.setValue ("OverUnderAmt", OverUnderAmt); + } + // No Invoice - Set Discount, Writeoff, Under/Over to 0 + else if (C_Invoice_ID == 0) + { + if (Env.ZERO.compareTo (DiscountAmt) != 0) + mTab.setValue ("DiscountAmt", Env.ZERO); + if (Env.ZERO.compareTo (WriteOffAmt) != 0) + mTab.setValue ("WriteOffAmt", Env.ZERO); + if (Env.ZERO.compareTo (OverUnderAmt) != 0) + mTab.setValue ("OverUnderAmt", Env.ZERO); + } else { + boolean processed = mTab.getValueAsBoolean(MPayment.COLUMNNAME_Processed); + if (colName.equals ("PayAmt") + && (!processed) + && "Y".equals (Env.getContext (ctx, WindowNo, "IsOverUnderPayment"))) + { + OverUnderAmt = InvoiceOpenAmt.subtract (PayAmt).subtract(DiscountAmt).subtract (WriteOffAmt); + if (OverUnderAmt.signum() > 0) { // no discount because is not paid in full + DiscountAmt = Env.ZERO; + mTab.setValue ("DiscountAmt", DiscountAmt); + OverUnderAmt = InvoiceOpenAmt.subtract (PayAmt).subtract(DiscountAmt).subtract (WriteOffAmt); + } + mTab.setValue ("OverUnderAmt", OverUnderAmt); + } + else if (colName.equals ("PayAmt") + && (!processed)) + { + WriteOffAmt = InvoiceOpenAmt.subtract (PayAmt).subtract ( + DiscountAmt).subtract (OverUnderAmt); + mTab.setValue ("WriteOffAmt", WriteOffAmt); + } + else if (colName.equals ("IsOverUnderPayment") + && (!processed)) + { + boolean overUnderPaymentActive = "Y".equals (Env.getContext (ctx, + WindowNo, "IsOverUnderPayment")); + if (overUnderPaymentActive) + { + OverUnderAmt = InvoiceOpenAmt.subtract (PayAmt).subtract ( + DiscountAmt); + mTab.setValue ("WriteOffAmt", Env.ZERO); + mTab.setValue ("OverUnderAmt", OverUnderAmt); + }else{ + WriteOffAmt = InvoiceOpenAmt.subtract (PayAmt).subtract ( + DiscountAmt); + mTab.setValue ("WriteOffAmt", WriteOffAmt); + mTab.setValue ("OverUnderAmt", Env.ZERO); + } + } + // Added Lines By Goodwill (02-03-2006) + // Reason: we must make the callout is called just when docstatus is + // draft + // Old Code : else // calculate PayAmt + // New Code : + else if ((!processed)) // calculate + // PayAmt + // End By Goodwill + { + PayAmt = InvoiceOpenAmt.subtract (DiscountAmt).subtract ( + WriteOffAmt).subtract (OverUnderAmt); + mTab.setValue ("PayAmt", PayAmt); + } + } + return ""; + } // amounts +} // CalloutPayment diff --git a/org.adempiere.base.process/src/org/compiere/process/DunningPrint.java b/org.adempiere.base.process/src/org/compiere/process/DunningPrint.java index 3ca5c296f2..054485c37d 100644 --- a/org.adempiere.base.process/src/org/compiere/process/DunningPrint.java +++ b/org.adempiere.base.process/src/org/compiere/process/DunningPrint.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,31 +16,31 @@ *****************************************************************************/ package org.compiere.process; -import java.io.File; -import java.util.logging.Level; - -import org.compiere.model.MBPartner; -import org.compiere.model.MClient; -import org.compiere.model.MDunningLevel; -import org.compiere.model.MDunningRun; -import org.compiere.model.MDunningRunEntry; -import org.compiere.model.MMailText; -import org.compiere.model.MQuery; -import org.compiere.model.MUser; -import org.compiere.model.MUserMail; -import org.compiere.model.PrintInfo; -import org.compiere.print.MPrintFormat; -import org.compiere.print.ReportEngine; -import org.compiere.util.AdempiereUserError; -import org.compiere.util.EMail; +import java.io.File; +import java.util.logging.Level; + +import org.compiere.model.MBPartner; +import org.compiere.model.MClient; +import org.compiere.model.MDunningLevel; +import org.compiere.model.MDunningRun; +import org.compiere.model.MDunningRunEntry; +import org.compiere.model.MMailText; +import org.compiere.model.MQuery; +import org.compiere.model.MUser; +import org.compiere.model.MUserMail; +import org.compiere.model.PrintInfo; +import org.compiere.print.MPrintFormat; +import org.compiere.print.ReportEngine; +import org.compiere.util.AdempiereUserError; +import org.compiere.util.EMail; /** * Dunning Letter Print * * @author Jorg Janke * @version $Id: DunningPrint.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $ - * - * FR 2872010 - Dunning Run for a complete Dunning (not just level) - Developer: Carlos Ruiz - globalqss - Sponsor: Metas + * + * FR 2872010 - Dunning Run for a complete Dunning (not just level) - Developer: Carlos Ruiz - globalqss - Sponsor: Metas */ public class DunningPrint extends SvrProcess { @@ -51,8 +51,8 @@ public class DunningPrint extends SvrProcess /** Dunning Run */ private int p_C_DunningRun_ID = 0; /** Print only Outstanding */ - private boolean p_IsOnlyIfBPBalance = true; - /** Print only unprocessed lines */ + private boolean p_IsOnlyIfBPBalance = true; + /** Print only unprocessed lines */ private boolean p_PrintUnprocessedOnly = true; @@ -74,8 +74,8 @@ public class DunningPrint extends SvrProcess else if (name.equals("C_DunningRun_ID")) p_C_DunningRun_ID = para[i].getParameterAsInt(); else if (name.equals("IsOnlyIfBPBalance")) - p_IsOnlyIfBPBalance = "Y".equals(para[i].getParameter()); - else if (name.equals("PrintUnprocessedOnly")) + p_IsOnlyIfBPBalance = "Y".equals(para[i].getParameter()); + else if (name.equals("PrintUnprocessedOnly")) p_PrintUnprocessedOnly = "Y".equals(para[i].getParameter()); else log.log(Level.SEVERE, "Unknown Parameter: " + name); @@ -89,26 +89,26 @@ public class DunningPrint extends SvrProcess */ protected String doIt () throws Exception { - if (log.isLoggable(Level.INFO)) log.info("C_DunningRun_ID=" + p_C_DunningRun_ID + ",R_MailText_ID=" + p_R_MailText_ID - + ", EmailPDF=" + p_EMailPDF + ",IsOnlyIfBPBalance=" + p_IsOnlyIfBPBalance + if (log.isLoggable(Level.INFO)) log.info("C_DunningRun_ID=" + p_C_DunningRun_ID + ",R_MailText_ID=" + p_R_MailText_ID + + ", EmailPDF=" + p_EMailPDF + ",IsOnlyIfBPBalance=" + p_IsOnlyIfBPBalance + ",PrintUnprocessedOnly=" + p_PrintUnprocessedOnly); - - // Need to have Template - if (p_EMailPDF && p_R_MailText_ID == 0) - throw new AdempiereUserError ("@NotFound@: @R_MailText_ID@"); -// String subject = ""; - MMailText mText = null; - if (p_EMailPDF) - { - mText = new MMailText (getCtx(), p_R_MailText_ID, get_TrxName()); - if (p_EMailPDF && mText.get_ID() == 0) - throw new AdempiereUserError ("@NotFound@: @R_MailText_ID@ - " + p_R_MailText_ID); -// subject = mText.getMailHeader(); - } - // - MDunningRun run = new MDunningRun (getCtx(), p_C_DunningRun_ID, get_TrxName()); - if (run.get_ID() == 0) - throw new AdempiereUserError ("@NotFound@: @C_DunningRun_ID@ - " + p_C_DunningRun_ID); + + // Need to have Template + if (p_EMailPDF && p_R_MailText_ID == 0) + throw new AdempiereUserError ("@NotFound@: @R_MailText_ID@"); +// String subject = ""; + MMailText mText = null; + if (p_EMailPDF) + { + mText = new MMailText (getCtx(), p_R_MailText_ID, get_TrxName()); + if (p_EMailPDF && mText.get_ID() == 0) + throw new AdempiereUserError ("@NotFound@: @R_MailText_ID@ - " + p_R_MailText_ID); +// subject = mText.getMailHeader(); + } + // + MDunningRun run = new MDunningRun (getCtx(), p_C_DunningRun_ID, get_TrxName()); + if (run.get_ID() == 0) + throw new AdempiereUserError ("@NotFound@: @C_DunningRun_ID@ - " + p_C_DunningRun_ID); MClient client = MClient.get(getCtx()); int count = 0; @@ -117,23 +117,23 @@ public class DunningPrint extends SvrProcess for (int i = 0; i < entries.length; i++) { MDunningRunEntry entry = entries[i]; - - // Print Format on Dunning Level - MDunningLevel level = new MDunningLevel (getCtx(), entry.getC_DunningLevel_ID(), get_TrxName()); - MPrintFormat format = null; - if (level.getDunning_PrintFormat_ID() > 0) - format = MPrintFormat.get (getCtx(), level.getDunning_PrintFormat_ID(), false); - + + // Print Format on Dunning Level + MDunningLevel level = new MDunningLevel (getCtx(), entry.getC_DunningLevel_ID(), get_TrxName()); + MPrintFormat format = null; + if (level.getDunning_PrintFormat_ID() > 0) + format = MPrintFormat.get (getCtx(), level.getDunning_PrintFormat_ID(), false); + if (p_IsOnlyIfBPBalance && entry.getAmt().signum() <= 0) - continue; - if (p_PrintUnprocessedOnly && entry.isProcessed()) + continue; + if (p_PrintUnprocessedOnly && entry.isProcessed()) continue; // To BPartner MBPartner bp = new MBPartner (getCtx(), entry.getC_BPartner_ID(), get_TrxName()); if (bp.get_ID() == 0) { - StringBuilder msglog = new StringBuilder("@NotFound@: @C_BPartner_ID@ ").append(entry.getC_BPartner_ID()); - addLog (entry.get_ID(), null, null,msglog.toString() ); + StringBuilder msglog = new StringBuilder("@NotFound@: @C_BPartner_ID@ ").append(entry.getC_BPartner_ID()); + addLog (entry.get_ID(), null, null,msglog.toString() ); errors++; continue; } @@ -143,15 +143,15 @@ public class DunningPrint extends SvrProcess { if (to.get_ID() == 0) { - StringBuilder msglog = new StringBuilder("@NotFound@: @AD_User_ID@ - ").append(bp.getName()); - addLog (entry.get_ID(), null, null,msglog.toString()); + StringBuilder msglog = new StringBuilder("@NotFound@: @AD_User_ID@ - ").append(bp.getName()); + addLog (entry.get_ID(), null, null,msglog.toString()); errors++; continue; } else if (to.getEMail() == null || to.getEMail().length() == 0) { - StringBuilder msglog = new StringBuilder("@NotFound@: @EMail@ - ").append(to.getName()); - addLog (entry.get_ID(), null, null, msglog.toString()); + StringBuilder msglog = new StringBuilder("@NotFound@: @EMail@ - ").append(to.getName()); + addLog (entry.get_ID(), null, null, msglog.toString()); errors++; continue; } @@ -164,23 +164,23 @@ public class DunningPrint extends SvrProcess // Engine PrintInfo info = new PrintInfo( bp.getName(), - MDunningRunEntry.Table_ID, + MDunningRunEntry.Table_ID, entry.getC_DunningRunEntry_ID(), - entry.getC_BPartner_ID()); - StringBuilder msginfo = new StringBuilder().append(bp.getName()).append(", Amt=").append(entry.getAmt()); - info.setDescription(msginfo.toString()); - ReportEngine re = null; - if (format != null) - re = new ReportEngine(getCtx(), format, query, info); + entry.getC_BPartner_ID()); + StringBuilder msginfo = new StringBuilder().append(bp.getName()).append(", Amt=").append(entry.getAmt()); + info.setDescription(msginfo.toString()); + ReportEngine re = null; + if (format != null) + re = new ReportEngine(getCtx(), format, query, info); boolean printed = false; if (p_EMailPDF) { EMail email = client.createEMail(to.getEMail(), null, null); if (!email.isValid()) { - StringBuilder msglog = new StringBuilder( - "@RequestActionEMailError@ Invalid EMail: ").append(to); - addLog (entry.get_ID(), null, null,msglog.toString() ); + StringBuilder msglog = new StringBuilder( + "@RequestActionEMailError@ Invalid EMail: ").append(to); + addLog (entry.get_ID(), null, null,msglog.toString() ); errors++; continue; } @@ -196,56 +196,56 @@ public class DunningPrint extends SvrProcess email.setMessageText (message); } // - if (re != null) { - File attachment = re.getPDF(File.createTempFile("Dunning", ".pdf")); - StringBuilder msglog = new StringBuilder().append(to.toString()).append(" - ").append(attachment); - if (log.isLoggable(Level.FINE)) log.fine(msglog.toString()); - email.addAttachment(attachment); - } + if (re != null) { + File attachment = re.getPDF(File.createTempFile("Dunning", ".pdf")); + StringBuilder msglog = new StringBuilder().append(to.toString()).append(" - ").append(attachment); + if (log.isLoggable(Level.FINE)) log.fine(msglog.toString()); + email.addAttachment(attachment); + } // String msg = email.send(); MUserMail um = new MUserMail(mText, entry.getAD_User_ID(), email); um.saveEx(); if (msg.equals(EMail.SENT_OK)) { - StringBuilder msglog = new StringBuilder() - .append(bp.getName()).append(" @RequestActionEMailOK@"); - addLog (entry.get_ID(), null, null,msglog.toString()); + StringBuilder msglog = new StringBuilder() + .append(bp.getName()).append(" @RequestActionEMailOK@"); + addLog (entry.get_ID(), null, null,msglog.toString()); count++; printed = true; } else { - StringBuilder msglog = new StringBuilder().append(bp.getName()).append(" @RequestActionEMailError@ ").append(msg); - addLog (entry.get_ID(), null, null,msglog.toString() ); + StringBuilder msglog = new StringBuilder().append(bp.getName()).append(" @RequestActionEMailError@ ").append(msg); + addLog (entry.get_ID(), null, null,msglog.toString() ); errors++; } } else { - if (re != null) { - re.print (); - count++; - printed = true; - } - } - if (printed) - { - entry.setProcessed (true); - entry.saveEx(); - } - - } // for all dunning letters - if (errors==0) { - run.setProcessed(true); - run.saveEx(); - } - if (p_EMailPDF){ - StringBuilder msgreturn = new StringBuilder("@Sent@=").append(count).append(" - @Errors@=").append(errors); - return msgreturn.toString(); - } - StringBuilder msgreturn = new StringBuilder("@Printed@=").append(count); - return msgreturn.toString(); + if (re != null) { + re.print (); + count++; + printed = true; + } + } + if (printed) + { + entry.setProcessed (true); + entry.saveEx(); + } + + } // for all dunning letters + if (errors==0) { + run.setProcessed(true); + run.saveEx(); + } + if (p_EMailPDF){ + StringBuilder msgreturn = new StringBuilder("@Sent@=").append(count).append(" - @Errors@=").append(errors); + return msgreturn.toString(); + } + StringBuilder msgreturn = new StringBuilder("@Printed@=").append(count); + return msgreturn.toString(); } // doIt } // DunningPrint diff --git a/org.adempiere.base.process/src/org/compiere/process/ImportBPartner.java b/org.adempiere.base.process/src/org/compiere/process/ImportBPartner.java index 792a1e0292..1786a3956c 100644 --- a/org.adempiere.base.process/src/org/compiere/process/ImportBPartner.java +++ b/org.adempiere.base.process/src/org/compiere/process/ImportBPartner.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -10,53 +10,53 @@ * 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 * - * Contributor: Carlos Ruiz - globalqss * - *****************************************************************************/ -package org.compiere.process; - -import java.math.BigDecimal; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.logging.Level; - -import org.adempiere.exceptions.DBException; -import org.adempiere.model.ImportValidator; -import org.adempiere.process.ImportProcess; -import org.compiere.model.MBPartner; -import org.compiere.model.MBPartnerLocation; -import org.compiere.model.MContactInterest; -import org.compiere.model.MLocation; -import org.compiere.model.MUser; -import org.compiere.model.ModelValidationEngine; -import org.compiere.model.X_I_BPartner; -import org.compiere.util.DB; + * 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 * + * Contributor: Carlos Ruiz - globalqss * + *****************************************************************************/ +package org.compiere.process; + +import java.math.BigDecimal; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.logging.Level; + +import org.adempiere.exceptions.DBException; +import org.adempiere.model.ImportValidator; +import org.adempiere.process.ImportProcess; +import org.compiere.model.MBPartner; +import org.compiere.model.MBPartnerLocation; +import org.compiere.model.MContactInterest; +import org.compiere.model.MLocation; +import org.compiere.model.MUser; +import org.compiere.model.ModelValidationEngine; +import org.compiere.model.X_I_BPartner; +import org.compiere.util.DB; /** * Import BPartners from I_BPartner * * @author Jorg Janke * @version $Id: ImportBPartner.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $ - * - * @author Teo Sarca, www.arhipac.ro - *
  • FR [ 2788074 ] ImportBPartner: add IsValidateOnly option - * https://sourceforge.net/tracker/?func=detail&aid=2788074&group_id=176962&atid=879335 - *
  • FR [ 2788278 ] Data Import Validator - migrate core processes - * https://sourceforge.net/tracker/?func=detail&aid=2788278&group_id=176962&atid=879335 + * + * @author Teo Sarca, www.arhipac.ro + *
  • FR [ 2788074 ] ImportBPartner: add IsValidateOnly option + * https://sourceforge.net/tracker/?func=detail&aid=2788074&group_id=176962&atid=879335 + *
  • FR [ 2788278 ] Data Import Validator - migrate core processes + * https://sourceforge.net/tracker/?func=detail&aid=2788278&group_id=176962&atid=879335 */ public class ImportBPartner extends SvrProcess -implements ImportProcess +implements ImportProcess { /** Client to be imported to */ private int m_AD_Client_ID = 0; /** Delete old Imported */ private boolean m_deleteOldImported = false; - /** Only validate, don't import */ - private boolean p_IsValidateOnly = false; + /** Only validate, don't import */ + private boolean p_IsValidateOnly = false; /** Effective */ private Timestamp m_DateValue = null; @@ -74,8 +74,8 @@ implements ImportProcess m_AD_Client_ID = ((BigDecimal)para[i].getParameter()).intValue(); else if (name.equals("DeleteOldImported")) m_deleteOldImported = "Y".equals(para[i].getParameter()); - else if (name.equals("IsValidateOnly")) - p_IsValidateOnly = para[i].getParameterAsBoolean(); + else if (name.equals("IsValidateOnly")) + p_IsValidateOnly = para[i].getParameterAsBoolean(); else log.log(Level.SEVERE, "Unknown Parameter: " + name); } @@ -91,7 +91,7 @@ implements ImportProcess */ protected String doIt() throws java.lang.Exception { - StringBuilder sql = null; + StringBuilder sql = null; int no = 0; String clientCheck = getWhereClause(); @@ -100,52 +100,52 @@ implements ImportProcess // Delete Old Imported if (m_deleteOldImported) { - sql = new StringBuilder ("DELETE I_BPartner ") - .append("WHERE I_IsImported='Y'").append(clientCheck); + sql = new StringBuilder ("DELETE I_BPartner ") + .append("WHERE I_IsImported='Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Delete Old Impored =" + no); + if (log.isLoggable(Level.FINE)) log.fine("Delete Old Impored =" + no); } // Set Client, Org, IsActive, Created/Updated - sql = new StringBuilder ("UPDATE I_BPartner ") - .append("SET AD_Client_ID = COALESCE (AD_Client_ID, ").append(m_AD_Client_ID).append("),") - .append(" AD_Org_ID = COALESCE (AD_Org_ID, 0),") - .append(" IsActive = COALESCE (IsActive, 'Y'),") - .append(" Created = COALESCE (Created, SysDate),") - .append(" CreatedBy = COALESCE (CreatedBy, 0),") - .append(" Updated = COALESCE (Updated, SysDate),") - .append(" UpdatedBy = COALESCE (UpdatedBy, 0),") - .append(" I_ErrorMsg = ' ',") - .append(" I_IsImported = 'N' ") - .append("WHERE I_IsImported<>'Y' OR I_IsImported IS NULL"); + sql = new StringBuilder ("UPDATE I_BPartner ") + .append("SET AD_Client_ID = COALESCE (AD_Client_ID, ").append(m_AD_Client_ID).append("),") + .append(" AD_Org_ID = COALESCE (AD_Org_ID, 0),") + .append(" IsActive = COALESCE (IsActive, 'Y'),") + .append(" Created = COALESCE (Created, SysDate),") + .append(" CreatedBy = COALESCE (CreatedBy, 0),") + .append(" Updated = COALESCE (Updated, SysDate),") + .append(" UpdatedBy = COALESCE (UpdatedBy, 0),") + .append(" I_ErrorMsg = ' ',") + .append(" I_IsImported = 'N' ") + .append("WHERE I_IsImported<>'Y' OR I_IsImported IS NULL"); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Reset=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Reset=" + no); - ModelValidationEngine.get().fireImportValidate(this, null, null, ImportValidator.TIMING_BEFORE_VALIDATE); - + ModelValidationEngine.get().fireImportValidate(this, null, null, ImportValidator.TIMING_BEFORE_VALIDATE); + // Set BP_Group - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET GroupValue=(SELECT MAX(Value) FROM C_BP_Group g WHERE g.IsDefault='Y'") - .append(" AND g.AD_Client_ID=i.AD_Client_ID) "); - sql.append("WHERE GroupValue IS NULL AND C_BP_Group_ID IS NULL") - .append(" AND I_IsImported<>'Y'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET GroupValue=(SELECT MAX(Value) FROM C_BP_Group g WHERE g.IsDefault='Y'") + .append(" AND g.AD_Client_ID=i.AD_Client_ID) "); + sql.append("WHERE GroupValue IS NULL AND C_BP_Group_ID IS NULL") + .append(" AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Set Group Default=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Set Group Default=" + no); // - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET C_BP_Group_ID=(SELECT C_BP_Group_ID FROM C_BP_Group g") - .append(" WHERE i.GroupValue=g.Value AND g.AD_Client_ID=i.AD_Client_ID) ") - .append("WHERE C_BP_Group_ID IS NULL") - .append(" AND I_IsImported<>'Y'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET C_BP_Group_ID=(SELECT C_BP_Group_ID FROM C_BP_Group g") + .append(" WHERE i.GroupValue=g.Value AND g.AD_Client_ID=i.AD_Client_ID) ") + .append("WHERE C_BP_Group_ID IS NULL") + .append(" AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Set Group=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Set Group=" + no); // - sql = new StringBuilder ("UPDATE I_BPartner ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Group, ' ") - .append("WHERE C_BP_Group_ID IS NULL") - .append(" AND I_IsImported<>'Y'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Group, ' ") + .append("WHERE C_BP_Group_ID IS NULL") + .append(" AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.CONFIG)) log.config("Invalid Group=" + no); + if (log.isLoggable(Level.CONFIG)) log.config("Invalid Group=" + no); // Set Country /** @@ -158,195 +158,195 @@ implements ImportProcess log.fine("Set Country Default=" + no); **/ // - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET C_Country_ID=(SELECT C_Country_ID FROM C_Country c") - .append(" WHERE i.CountryCode=c.CountryCode AND c.AD_Client_ID IN (0, i.AD_Client_ID)) ") - .append("WHERE C_Country_ID IS NULL") - .append(" AND I_IsImported<>'Y'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET C_Country_ID=(SELECT C_Country_ID FROM C_Country c") + .append(" WHERE i.CountryCode=c.CountryCode AND c.AD_Client_ID IN (0, i.AD_Client_ID)) ") + .append("WHERE C_Country_ID IS NULL") + .append(" AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Set Country=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Set Country=" + no); // - sql = new StringBuilder ("UPDATE I_BPartner ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Country, ' ") - .append("WHERE C_Country_ID IS NULL AND (City IS NOT NULL OR Address1 IS NOT NULL)") - .append(" AND I_IsImported<>'Y'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Country, ' ") + .append("WHERE C_Country_ID IS NULL AND (City IS NOT NULL OR Address1 IS NOT NULL)") + .append(" AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.CONFIG)) log.config("Invalid Country=" + no); + if (log.isLoggable(Level.CONFIG)) log.config("Invalid Country=" + no); - // Set Region - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("Set RegionName=(SELECT MAX(Name) FROM C_Region r") - .append(" WHERE r.IsDefault='Y' AND r.C_Country_ID=i.C_Country_ID") - .append(" AND r.AD_Client_ID IN (0, i.AD_Client_ID)) " ); - sql.append("WHERE RegionName IS NULL AND C_Region_ID IS NULL") - .append(" AND I_IsImported<>'Y'").append(clientCheck); - no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Set Region Default=" + no); - // - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("Set C_Region_ID=(SELECT C_Region_ID FROM C_Region r") - .append(" WHERE r.Name=i.RegionName AND r.C_Country_ID=i.C_Country_ID") - .append(" AND r.AD_Client_ID IN (0, i.AD_Client_ID)) ") - .append("WHERE C_Region_ID IS NULL") - .append(" AND I_IsImported<>'Y'").append(clientCheck); + // Set Region + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("Set RegionName=(SELECT MAX(Name) FROM C_Region r") + .append(" WHERE r.IsDefault='Y' AND r.C_Country_ID=i.C_Country_ID") + .append(" AND r.AD_Client_ID IN (0, i.AD_Client_ID)) " ); + sql.append("WHERE RegionName IS NULL AND C_Region_ID IS NULL") + .append(" AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Set Region=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Set Region Default=" + no); // - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Region, ' ") - .append("WHERE C_Region_ID IS NULL ") - .append(" AND EXISTS (SELECT * FROM C_Country c") - .append(" WHERE c.C_Country_ID=i.C_Country_ID AND c.HasRegion='Y')") - .append(" AND I_IsImported<>'Y'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("Set C_Region_ID=(SELECT C_Region_ID FROM C_Region r") + .append(" WHERE r.Name=i.RegionName AND r.C_Country_ID=i.C_Country_ID") + .append(" AND r.AD_Client_ID IN (0, i.AD_Client_ID)) ") + .append("WHERE C_Region_ID IS NULL") + .append(" AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.CONFIG)) log.config("Invalid Region=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Set Region=" + no); + // + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Region, ' ") + .append("WHERE C_Region_ID IS NULL ") + .append(" AND EXISTS (SELECT * FROM C_Country c") + .append(" WHERE c.C_Country_ID=i.C_Country_ID AND c.HasRegion='Y')") + .append(" AND I_IsImported<>'Y'").append(clientCheck); + no = DB.executeUpdateEx(sql.toString(), get_TrxName()); + if (log.isLoggable(Level.CONFIG)) log.config("Invalid Region=" + no); // Set Greeting - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET C_Greeting_ID=(SELECT C_Greeting_ID FROM C_Greeting g") - .append(" WHERE i.BPContactGreeting=g.Name AND g.AD_Client_ID IN (0, i.AD_Client_ID)) ") - .append("WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL") - .append(" AND I_IsImported<>'Y'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET C_Greeting_ID=(SELECT C_Greeting_ID FROM C_Greeting g") + .append(" WHERE i.BPContactGreeting=g.Name AND g.AD_Client_ID IN (0, i.AD_Client_ID)) ") + .append("WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL") + .append(" AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Set Greeting=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Set Greeting=" + no); // - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Greeting, ' ") - .append("WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL") - .append(" AND I_IsImported<>'Y'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Greeting, ' ") + .append("WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL") + .append(" AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.CONFIG)) log.config("Invalid Greeting=" + no); + if (log.isLoggable(Level.CONFIG)) log.config("Invalid Greeting=" + no); // Existing User ? - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET (C_BPartner_ID,AD_User_ID)=") - .append("(SELECT C_BPartner_ID,AD_User_ID FROM AD_User u ") - .append("WHERE i.EMail=u.EMail AND u.AD_Client_ID=i.AD_Client_ID) ") - .append("WHERE i.EMail IS NOT NULL AND I_IsImported='N'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET (C_BPartner_ID,AD_User_ID)=") + .append("(SELECT C_BPartner_ID,AD_User_ID FROM AD_User u ") + .append("WHERE i.EMail=u.EMail AND u.AD_Client_ID=i.AD_Client_ID) ") + .append("WHERE i.EMail IS NOT NULL AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Found EMail User=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Found EMail User=" + no); // Existing BPartner ? Match Value - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET C_BPartner_ID=(SELECT C_BPartner_ID FROM C_BPartner p") - .append(" WHERE i.Value=p.Value AND p.AD_Client_ID=i.AD_Client_ID) ") - .append("WHERE C_BPartner_ID IS NULL AND Value IS NOT NULL") - .append(" AND I_IsImported='N'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET C_BPartner_ID=(SELECT C_BPartner_ID FROM C_BPartner p") + .append(" WHERE i.Value=p.Value AND p.AD_Client_ID=i.AD_Client_ID) ") + .append("WHERE C_BPartner_ID IS NULL AND Value IS NOT NULL") + .append(" AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Found BPartner=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Found BPartner=" + no); // Existing Contact ? Match Name - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET AD_User_ID=(SELECT AD_User_ID FROM AD_User c") - .append(" WHERE i.ContactName=c.Name AND i.C_BPartner_ID=c.C_BPartner_ID AND c.AD_Client_ID=i.AD_Client_ID) ") - .append("WHERE C_BPartner_ID IS NOT NULL AND AD_User_ID IS NULL AND ContactName IS NOT NULL") - .append(" AND I_IsImported='N'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET AD_User_ID=(SELECT AD_User_ID FROM AD_User c") + .append(" WHERE i.ContactName=c.Name AND i.C_BPartner_ID=c.C_BPartner_ID AND c.AD_Client_ID=i.AD_Client_ID) ") + .append("WHERE C_BPartner_ID IS NOT NULL AND AD_User_ID IS NULL AND ContactName IS NOT NULL") + .append(" AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Found Contact=" + no); - -// Existing Location ? Exact Match - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET C_BPartner_Location_ID=(SELECT C_BPartner_Location_ID") - .append(" FROM C_BPartner_Location bpl INNER JOIN C_Location l ON (bpl.C_Location_ID=l.C_Location_ID)") - .append(" WHERE i.C_BPartner_ID=bpl.C_BPartner_ID AND bpl.AD_Client_ID=i.AD_Client_ID") - .append(" AND (i.Address1=l.Address1 OR (i.Address1 IS NULL AND l.Address1 IS NULL))") - .append(" AND (i.Address2=l.Address2 OR (i.Address2 IS NULL AND l.Address2 IS NULL))") - .append(" AND (i.City=l.City OR (i.City IS NULL AND l.City IS NULL))") - .append(" AND (i.Postal=l.Postal OR (i.Postal IS NULL AND l.Postal IS NULL))") - .append(" AND (i.Postal_Add=l.Postal_Add OR (l.Postal_Add IS NULL AND l.Postal_Add IS NULL))") - .append(" AND (i.C_Region_ID=l.C_Region_ID OR (l.C_Region_ID IS NULL AND i.C_Region_ID IS NULL))") - .append(" AND i.C_Country_ID=l.C_Country_ID) ") - .append("WHERE C_BPartner_ID IS NOT NULL AND C_BPartner_Location_ID IS NULL") - .append(" AND I_IsImported='N'").append(clientCheck); - no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Found Location=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Found Contact=" + no); + +// Existing Location ? Exact Match + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET C_BPartner_Location_ID=(SELECT C_BPartner_Location_ID") + .append(" FROM C_BPartner_Location bpl INNER JOIN C_Location l ON (bpl.C_Location_ID=l.C_Location_ID)") + .append(" WHERE i.C_BPartner_ID=bpl.C_BPartner_ID AND bpl.AD_Client_ID=i.AD_Client_ID") + .append(" AND (i.Address1=l.Address1 OR (i.Address1 IS NULL AND l.Address1 IS NULL))") + .append(" AND (i.Address2=l.Address2 OR (i.Address2 IS NULL AND l.Address2 IS NULL))") + .append(" AND (i.City=l.City OR (i.City IS NULL AND l.City IS NULL))") + .append(" AND (i.Postal=l.Postal OR (i.Postal IS NULL AND l.Postal IS NULL))") + .append(" AND (i.Postal_Add=l.Postal_Add OR (l.Postal_Add IS NULL AND l.Postal_Add IS NULL))") + .append(" AND (i.C_Region_ID=l.C_Region_ID OR (l.C_Region_ID IS NULL AND i.C_Region_ID IS NULL))") + .append(" AND i.C_Country_ID=l.C_Country_ID) ") + .append("WHERE C_BPartner_ID IS NOT NULL AND C_BPartner_Location_ID IS NULL") + .append(" AND I_IsImported='N'").append(clientCheck); + no = DB.executeUpdateEx(sql.toString(), get_TrxName()); + if (log.isLoggable(Level.FINE)) log.fine("Found Location=" + no); // Interest Area - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET R_InterestArea_ID=(SELECT R_InterestArea_ID FROM R_InterestArea ia ") - .append("WHERE i.InterestAreaName=ia.Name AND ia.AD_Client_ID=i.AD_Client_ID) ") - .append("WHERE R_InterestArea_ID IS NULL AND InterestAreaName IS NOT NULL") - .append(" AND I_IsImported='N'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET R_InterestArea_ID=(SELECT R_InterestArea_ID FROM R_InterestArea ia ") + .append("WHERE i.InterestAreaName=ia.Name AND ia.AD_Client_ID=i.AD_Client_ID) ") + .append("WHERE R_InterestArea_ID IS NULL AND InterestAreaName IS NOT NULL") + .append(" AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Set Interest Area=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Set Interest Area=" + no); - // Value is mandatory error - sql = new StringBuilder ("UPDATE I_BPartner ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Value is mandatory, ' ") - .append("WHERE Value IS NULL ") - .append(" AND I_IsImported<>'Y'").append(clientCheck); - no = DB.executeUpdateEx(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.CONFIG)) log.config("Value is mandatory=" + no); - - ModelValidationEngine.get().fireImportValidate(this, null, null, ImportValidator.TIMING_AFTER_VALIDATE); + // Value is mandatory error + sql = new StringBuilder ("UPDATE I_BPartner ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Value is mandatory, ' ") + .append("WHERE Value IS NULL ") + .append(" AND I_IsImported<>'Y'").append(clientCheck); + no = DB.executeUpdateEx(sql.toString(), get_TrxName()); + if (log.isLoggable(Level.CONFIG)) log.config("Value is mandatory=" + no); + + ModelValidationEngine.get().fireImportValidate(this, null, null, ImportValidator.TIMING_AFTER_VALIDATE); commitEx(); - if (p_IsValidateOnly) - { - return "Validated"; - } + if (p_IsValidateOnly) + { + return "Validated"; + } // ------------------------------------------------------------------- int noInsert = 0; int noUpdate = 0; // Go through Records - sql = new StringBuilder ("SELECT * FROM I_BPartner ") - .append("WHERE I_IsImported='N'").append(clientCheck); - // gody: 20070113 - Order so the same values are consecutive. - sql.append(" ORDER BY Value, I_BPartner_ID"); - PreparedStatement pstmt = null; - ResultSet rs = null; + sql = new StringBuilder ("SELECT * FROM I_BPartner ") + .append("WHERE I_IsImported='N'").append(clientCheck); + // gody: 20070113 - Order so the same values are consecutive. + sql.append(" ORDER BY Value, I_BPartner_ID"); + PreparedStatement pstmt = null; + ResultSet rs = null; try { pstmt = DB.prepareStatement(sql.toString(), get_TrxName()); - rs = pstmt.executeQuery(); - - // Remember Previous BP Value BP is only first one, others are contacts. - // All contacts share BP location. - // bp and bpl declarations before loop, we need them for data. - String Old_BPValue = "" ; - MBPartner bp = null; - MBPartnerLocation bpl = null; + rs = pstmt.executeQuery(); + + // Remember Previous BP Value BP is only first one, others are contacts. + // All contacts share BP location. + // bp and bpl declarations before loop, we need them for data. + String Old_BPValue = "" ; + MBPartner bp = null; + MBPartnerLocation bpl = null; while (rs.next()) - { - // Remember Value - only first occurance of the value is BP - String New_BPValue = rs.getString("Value") ; - - X_I_BPartner impBP = new X_I_BPartner (getCtx(), rs, get_TrxName()); - StringBuilder msglog = new StringBuilder("I_BPartner_ID=") .append(impBP.getI_BPartner_ID()) - .append(", C_BPartner_ID=").append(impBP.getC_BPartner_ID()) - .append(", C_BPartner_Location_ID=").append(impBP.getC_BPartner_Location_ID()) - .append(", AD_User_ID=").append(impBP.getAD_User_ID()); - if (log.isLoggable(Level.FINE)) log.fine(msglog.toString()); + { + // Remember Value - only first occurance of the value is BP + String New_BPValue = rs.getString("Value") ; + + X_I_BPartner impBP = new X_I_BPartner (getCtx(), rs, get_TrxName()); + StringBuilder msglog = new StringBuilder("I_BPartner_ID=") .append(impBP.getI_BPartner_ID()) + .append(", C_BPartner_ID=").append(impBP.getC_BPartner_ID()) + .append(", C_BPartner_Location_ID=").append(impBP.getC_BPartner_Location_ID()) + .append(", AD_User_ID=").append(impBP.getAD_User_ID()); + if (log.isLoggable(Level.FINE)) log.fine(msglog.toString()); - if ( ! New_BPValue.equals(Old_BPValue)) { - // **** Create/Update BPartner **** - bp = null; - + if ( ! New_BPValue.equals(Old_BPValue)) { + // **** Create/Update BPartner **** + bp = null; + if (impBP.getC_BPartner_ID() == 0) // Insert new BPartner { bp = new MBPartner(impBP); - ModelValidationEngine.get().fireImportValidate(this, impBP, bp, ImportValidator.TIMING_AFTER_IMPORT); - - setTypeOfBPartner(impBP,bp); - + ModelValidationEngine.get().fireImportValidate(this, impBP, bp, ImportValidator.TIMING_AFTER_IMPORT); + + setTypeOfBPartner(impBP,bp); + if (bp.save()) { - impBP.setC_BPartner_ID(bp.getC_BPartner_ID()); - msglog = new StringBuilder("Insert BPartner - ").append(bp.getC_BPartner_ID()); - if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); + impBP.setC_BPartner_ID(bp.getC_BPartner_ID()); + msglog = new StringBuilder("Insert BPartner - ").append(bp.getC_BPartner_ID()); + if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); noInsert++; } else - { - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") - .append("'Cannot Insert BPartner, ' ") - .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); - DB.executeUpdateEx(sql.toString(), get_TrxName()); - continue; + { + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + .append("'Cannot Insert BPartner, ' ") + .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); + DB.executeUpdateEx(sql.toString(), get_TrxName()); + continue; } } else // Update existing BPartner @@ -364,30 +364,30 @@ implements ImportProcess if (impBP.getTaxID() != null) bp.setTaxID(impBP.getTaxID()); if (impBP.getNAICS() != null) - bp.setNAICS(impBP.getNAICS()); - if (impBP.getDescription() != null) - bp.setDescription(impBP.getDescription()); + bp.setNAICS(impBP.getNAICS()); + if (impBP.getDescription() != null) + bp.setDescription(impBP.getDescription()); if (impBP.getC_BP_Group_ID() != 0) bp.setC_BP_Group_ID(impBP.getC_BP_Group_ID()); - ModelValidationEngine.get().fireImportValidate(this, impBP, bp, ImportValidator.TIMING_AFTER_IMPORT); - - setTypeOfBPartner(impBP,bp); - + ModelValidationEngine.get().fireImportValidate(this, impBP, bp, ImportValidator.TIMING_AFTER_IMPORT); + + setTypeOfBPartner(impBP,bp); + // if (bp.save()) { - msglog = new StringBuilder("Update BPartner - ").append(bp.getC_BPartner_ID()); - if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); + msglog = new StringBuilder("Update BPartner - ").append(bp.getC_BPartner_ID()); + if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); noUpdate++; } else - { - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") - .append("'Cannot Update BPartner, ' ") - .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); - DB.executeUpdateEx(sql.toString(), get_TrxName()); - continue; + { + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + .append("'Cannot Update BPartner, ' ") + .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); + DB.executeUpdateEx(sql.toString(), get_TrxName()); + continue; } } @@ -414,7 +414,7 @@ implements ImportProcess bpl.setPhone2(impBP.getPhone2()); if (impBP.getFax() != null) bpl.setFax(impBP.getFax()); - ModelValidationEngine.get().fireImportValidate(this, impBP, bpl, ImportValidator.TIMING_AFTER_IMPORT); + ModelValidationEngine.get().fireImportValidate(this, impBP, bpl, ImportValidator.TIMING_AFTER_IMPORT); bpl.saveEx(); } else // New Location @@ -428,20 +428,20 @@ implements ImportProcess location.setAddress2(impBP.getAddress2()); location.setPostal(impBP.getPostal()); location.setPostal_Add(impBP.getPostal_Add()); - if (location.save()){ - msglog = new StringBuilder("Insert Location - ").append(location.getC_Location_ID()); - if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); - } + if (location.save()){ + msglog = new StringBuilder("Insert Location - ").append(location.getC_Location_ID()); + if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); + } else { rollback(); - noInsert--; - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") - .append("'Cannot Insert Location, ' ") - .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); - DB.executeUpdateEx(sql.toString(), get_TrxName()); - continue; + noInsert--; + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + .append("'Cannot Insert Location, ' ") + .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); + DB.executeUpdateEx(sql.toString(), get_TrxName()); + continue; } // bpl = new MBPartnerLocation (bp); @@ -449,28 +449,28 @@ implements ImportProcess bpl.setPhone(impBP.getPhone()); bpl.setPhone2(impBP.getPhone2()); bpl.setFax(impBP.getFax()); - ModelValidationEngine.get().fireImportValidate(this, impBP, bpl, ImportValidator.TIMING_AFTER_IMPORT); + ModelValidationEngine.get().fireImportValidate(this, impBP, bpl, ImportValidator.TIMING_AFTER_IMPORT); if (bpl.save()) { - msglog = new StringBuilder("Insert BP Location - ").append(bpl.getC_BPartner_Location_ID()); - if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); + msglog = new StringBuilder("Insert BP Location - ").append(bpl.getC_BPartner_Location_ID()); + if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); impBP.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID()); } else { rollback(); - noInsert--; - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") - .append("'Cannot Insert BPLocation, ' ") - .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); - DB.executeUpdateEx(sql.toString(), get_TrxName()); - continue; + noInsert--; + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + .append("'Cannot Insert BPLocation, ' ") + .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); + DB.executeUpdateEx(sql.toString(), get_TrxName()); + continue; } - } - } - - Old_BPValue = New_BPValue ; + } + } + + Old_BPValue = New_BPValue ; // **** Create/Update Contact **** MUser user = null; @@ -482,13 +482,13 @@ implements ImportProcess else if (user.getC_BPartner_ID() != bp.getC_BPartner_ID()) { rollback(); - noInsert--; - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") - .append("'BP of User <> BP, ' ") - .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); - DB.executeUpdateEx(sql.toString(), get_TrxName()); - continue; + noInsert--; + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + .append("'BP of User <> BP, ' ") + .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); + DB.executeUpdateEx(sql.toString(), get_TrxName()); + continue; } if (impBP.getC_Greeting_ID() != 0) user.setC_Greeting_ID(impBP.getC_Greeting_ID()); @@ -514,22 +514,22 @@ implements ImportProcess user.setBirthday(impBP.getBirthday()); if (bpl != null) user.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID()); - ModelValidationEngine.get().fireImportValidate(this, impBP, user, ImportValidator.TIMING_AFTER_IMPORT); + ModelValidationEngine.get().fireImportValidate(this, impBP, user, ImportValidator.TIMING_AFTER_IMPORT); if (user.save()) { - msglog = new StringBuilder("Update BP Contact - ").append(user.getAD_User_ID()); - if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); + msglog = new StringBuilder("Update BP Contact - ").append(user.getAD_User_ID()); + if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); } else { rollback(); - noInsert--; - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") - .append("'Cannot Update BP Contact, ' ") - .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); - DB.executeUpdateEx(sql.toString(), get_TrxName()); - continue; + noInsert--; + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + .append("'Cannot Update BP Contact, ' ") + .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); + DB.executeUpdateEx(sql.toString(), get_TrxName()); + continue; } } else // New Contact @@ -552,23 +552,23 @@ implements ImportProcess user.setBirthday(impBP.getBirthday()); if (bpl != null) user.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID()); - ModelValidationEngine.get().fireImportValidate(this, impBP, user, ImportValidator.TIMING_AFTER_IMPORT); + ModelValidationEngine.get().fireImportValidate(this, impBP, user, ImportValidator.TIMING_AFTER_IMPORT); if (user.save()) { - msglog = new StringBuilder("Insert BP Contact - ").append(user.getAD_User_ID()); - if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); + msglog = new StringBuilder("Insert BP Contact - ").append(user.getAD_User_ID()); + if (log.isLoggable(Level.FINEST)) log.finest(msglog.toString()); impBP.setAD_User_ID(user.getAD_User_ID()); } else { rollback(); - noInsert--; - sql = new StringBuilder ("UPDATE I_BPartner i ") - .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") - .append("'Cannot Insert BPContact, ' ") - .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); - DB.executeUpdateEx(sql.toString(), get_TrxName()); - continue; + noInsert--; + sql = new StringBuilder ("UPDATE I_BPartner i ") + .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + .append("'Cannot Insert BPContact, ' ") + .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); + DB.executeUpdateEx(sql.toString(), get_TrxName()); + continue; } } @@ -592,59 +592,59 @@ implements ImportProcess catch (SQLException e) { rollback(); - //log.log(Level.SEVERE, "", e); - throw new DBException(e, sql.toString()); + //log.log(Level.SEVERE, "", e); + throw new DBException(e, sql.toString()); } - finally + finally { - DB.close(rs, pstmt); - rs = null; pstmt = null; + DB.close(rs, pstmt); + rs = null; pstmt = null; // Set Error to indicator to not imported - sql = new StringBuilder ("UPDATE I_BPartner ") - .append("SET I_IsImported='N', Updated=SysDate ") - .append("WHERE I_IsImported<>'Y'").append(clientCheck); + sql = new StringBuilder ("UPDATE I_BPartner ") + .append("SET I_IsImported='N', Updated=SysDate ") + .append("WHERE I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdateEx(sql.toString(), get_TrxName()); addLog (0, null, new BigDecimal (no), "@Errors@"); addLog (0, null, new BigDecimal (noInsert), "@C_BPartner_ID@: @Inserted@"); addLog (0, null, new BigDecimal (noUpdate), "@C_BPartner_ID@: @Updated@"); - } + } return ""; } // doIt - - //@Override - public String getWhereClause() - { - StringBuilder msgreturn = new StringBuilder(" AND AD_Client_ID=").append(m_AD_Client_ID); - return msgreturn.toString(); - } - - - //@Override - public String getImportTableName() - { - return X_I_BPartner.Table_Name; - } - - /** - * Set type of Business Partner - * - * @param X_I_BPartner impBP - * @param MBPartner bp - */ - private void setTypeOfBPartner(X_I_BPartner impBP, MBPartner bp){ - if (impBP.isVendor()){ - bp.setIsVendor(true); - bp.setIsCustomer(false); // It is put to false since by default in C_BPartner is true - } - if (impBP.isEmployee()){ - bp.setIsEmployee(true); - bp.setIsCustomer(false); // It is put to false since by default in C_BPartner is true - } - // it has to be the last if, to subscribe the bp.setIsCustomer (false) of the other two - if (impBP.isCustomer()){ - bp.setIsCustomer(true); - } - } // setTypeOfBPartner - + + //@Override + public String getWhereClause() + { + StringBuilder msgreturn = new StringBuilder(" AND AD_Client_ID=").append(m_AD_Client_ID); + return msgreturn.toString(); + } + + + //@Override + public String getImportTableName() + { + return X_I_BPartner.Table_Name; + } + + /** + * Set type of Business Partner + * + * @param X_I_BPartner impBP + * @param MBPartner bp + */ + private void setTypeOfBPartner(X_I_BPartner impBP, MBPartner bp){ + if (impBP.isVendor()){ + bp.setIsVendor(true); + bp.setIsCustomer(false); // It is put to false since by default in C_BPartner is true + } + if (impBP.isEmployee()){ + bp.setIsEmployee(true); + bp.setIsCustomer(false); // It is put to false since by default in C_BPartner is true + } + // it has to be the last if, to subscribe the bp.setIsCustomer (false) of the other two + if (impBP.isCustomer()){ + bp.setIsCustomer(true); + } + } // setTypeOfBPartner + } // ImportBPartner diff --git a/org.adempiere.base.process/src/org/compiere/process/InvoiceNGL.java b/org.adempiere.base.process/src/org/compiere/process/InvoiceNGL.java index a253180bc0..7d3405f1f5 100644 --- a/org.adempiere.base.process/src/org/compiere/process/InvoiceNGL.java +++ b/org.adempiere.base.process/src/org/compiere/process/InvoiceNGL.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,33 +16,33 @@ *****************************************************************************/ package org.compiere.process; -import java.math.BigDecimal; -import java.sql.Timestamp; -import java.util.List; -import java.util.logging.Level; - -import org.compiere.model.MAccount; -import org.compiere.model.MAcctSchema; -import org.compiere.model.MAcctSchemaDefault; -import org.compiere.model.MDocType; -import org.compiere.model.MFactAcct; -import org.compiere.model.MGLCategory; -import org.compiere.model.MInvoice; -import org.compiere.model.MJournal; -import org.compiere.model.MJournalLine; -import org.compiere.model.MOrg; -import org.compiere.model.Query; -import org.compiere.model.X_T_InvoiceGL; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.Msg; +import java.math.BigDecimal; +import java.sql.Timestamp; +import java.util.List; +import java.util.logging.Level; + +import org.compiere.model.MAccount; +import org.compiere.model.MAcctSchema; +import org.compiere.model.MAcctSchemaDefault; +import org.compiere.model.MDocType; +import org.compiere.model.MFactAcct; +import org.compiere.model.MGLCategory; +import org.compiere.model.MInvoice; +import org.compiere.model.MJournal; +import org.compiere.model.MJournalLine; +import org.compiere.model.MOrg; +import org.compiere.model.Query; +import org.compiere.model.X_T_InvoiceGL; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Msg; /** * Invoice Not realized Gain & Loss. * The actual data shown is T_InvoiceGL_v * @author Jorg Janke * @version $Id: InvoiceNGL.java,v 1.3 2006/08/04 03:53:59 jjanke Exp $ - * FR: [ 2214883 ] Remove SQL code and Replace for Query - red1 + * FR: [ 2214883 ] Remove SQL code and Replace for Query - red1 */ public class InvoiceNGL extends SvrProcess { @@ -102,7 +102,7 @@ public class InvoiceNGL extends SvrProcess { if (p_IsAllCurrencies) p_C_Currency_ID = 0; - if (log.isLoggable(Level.INFO)) log.info("C_AcctSchema_ID=" + p_C_AcctSchema_ID + if (log.isLoggable(Level.INFO)) log.info("C_AcctSchema_ID=" + p_C_AcctSchema_ID + ",C_ConversionTypeReval_ID=" + p_C_ConversionTypeReval_ID + ",DateReval=" + p_DateReval + ", APAR=" + p_APAR @@ -115,87 +115,87 @@ public class InvoiceNGL extends SvrProcess p_DateReval = new Timestamp(System.currentTimeMillis()); // Delete - just to be sure - StringBuilder sql = new StringBuilder("DELETE T_InvoiceGL WHERE AD_PInstance_ID=").append(getAD_PInstance_ID()); - int no = DB.executeUpdate(sql.toString(), get_TrxName()); + StringBuilder sql = new StringBuilder("DELETE T_InvoiceGL WHERE AD_PInstance_ID=").append(getAD_PInstance_ID()); + int no = DB.executeUpdate(sql.toString(), get_TrxName()); if (no > 0) - if (log.isLoggable(Level.INFO)) log.info("Deleted #" + no); + if (log.isLoggable(Level.INFO)) log.info("Deleted #" + no); // Insert Trx String dateStr = DB.TO_DATE(p_DateReval, true); - sql = new StringBuilder("INSERT INTO T_InvoiceGL (AD_Client_ID, AD_Org_ID, IsActive, Created,CreatedBy, Updated,UpdatedBy,") - .append(" AD_PInstance_ID, C_Invoice_ID, GrandTotal, OpenAmt, ") - .append(" Fact_Acct_ID, AmtSourceBalance, AmtAcctBalance, ") - .append(" AmtRevalDr, AmtRevalCr, C_DocTypeReval_ID, IsAllCurrencies, ") - .append(" DateReval, C_ConversionTypeReval_ID, AmtRevalDrDiff, AmtRevalCrDiff, APAR) ") + sql = new StringBuilder("INSERT INTO T_InvoiceGL (AD_Client_ID, AD_Org_ID, IsActive, Created,CreatedBy, Updated,UpdatedBy,") + .append(" AD_PInstance_ID, C_Invoice_ID, GrandTotal, OpenAmt, ") + .append(" Fact_Acct_ID, AmtSourceBalance, AmtAcctBalance, ") + .append(" AmtRevalDr, AmtRevalCr, C_DocTypeReval_ID, IsAllCurrencies, ") + .append(" DateReval, C_ConversionTypeReval_ID, AmtRevalDrDiff, AmtRevalCrDiff, APAR) ") // -- - .append("SELECT i.AD_Client_ID, i.AD_Org_ID, i.IsActive, i.Created,i.CreatedBy, i.Updated,i.UpdatedBy,") - .append( getAD_PInstance_ID()).append(", i.C_Invoice_ID, i.GrandTotal, invoiceOpen(i.C_Invoice_ID, 0), ") - .append(" fa.Fact_Acct_ID, fa.AmtSourceDr-fa.AmtSourceCr, fa.AmtAcctDr-fa.AmtAcctCr, ") + .append("SELECT i.AD_Client_ID, i.AD_Org_ID, i.IsActive, i.Created,i.CreatedBy, i.Updated,i.UpdatedBy,") + .append( getAD_PInstance_ID()).append(", i.C_Invoice_ID, i.GrandTotal, invoiceOpen(i.C_Invoice_ID, 0), ") + .append(" fa.Fact_Acct_ID, fa.AmtSourceDr-fa.AmtSourceCr, fa.AmtAcctDr-fa.AmtAcctCr, ") // AmtRevalDr, AmtRevalCr, - .append(" currencyConvert(fa.AmtSourceDr, i.C_Currency_ID, a.C_Currency_ID, ").append(dateStr).append(", ").append(p_C_ConversionTypeReval_ID).append(", i.AD_Client_ID, i.AD_Org_ID),") - .append(" currencyConvert(fa.AmtSourceCr, i.C_Currency_ID, a.C_Currency_ID, ").append(dateStr).append(", ").append(p_C_ConversionTypeReval_ID).append(", i.AD_Client_ID, i.AD_Org_ID),") - .append((p_C_DocTypeReval_ID==0 ? "NULL" : String.valueOf(p_C_DocTypeReval_ID))).append(", ") - .append((p_IsAllCurrencies ? "'Y'," : "'N',")) - .append(dateStr).append(", ").append(p_C_ConversionTypeReval_ID).append(", 0, 0, '").append(p_APAR).append("' ") + .append(" currencyConvert(fa.AmtSourceDr, i.C_Currency_ID, a.C_Currency_ID, ").append(dateStr).append(", ").append(p_C_ConversionTypeReval_ID).append(", i.AD_Client_ID, i.AD_Org_ID),") + .append(" currencyConvert(fa.AmtSourceCr, i.C_Currency_ID, a.C_Currency_ID, ").append(dateStr).append(", ").append(p_C_ConversionTypeReval_ID).append(", i.AD_Client_ID, i.AD_Org_ID),") + .append((p_C_DocTypeReval_ID==0 ? "NULL" : String.valueOf(p_C_DocTypeReval_ID))).append(", ") + .append((p_IsAllCurrencies ? "'Y'," : "'N',")) + .append(dateStr).append(", ").append(p_C_ConversionTypeReval_ID).append(", 0, 0, '").append(p_APAR).append("' ") // - .append("FROM C_Invoice_v i") - .append(" INNER JOIN Fact_Acct fa ON (fa.AD_Table_ID=318 AND fa.Record_ID=i.C_Invoice_ID") - .append(" AND (i.GrandTotal=fa.AmtSourceDr OR i.GrandTotal=fa.AmtSourceCr))") - .append(" INNER JOIN C_AcctSchema a ON (fa.C_AcctSchema_ID=a.C_AcctSchema_ID) ") - .append("WHERE i.IsPaid='N'") - .append(" AND EXISTS (SELECT * FROM C_ElementValue ev ") - .append("WHERE ev.C_ElementValue_ID=fa.Account_ID AND (ev.AccountType='A' OR ev.AccountType='L'))") - .append(" AND fa.C_AcctSchema_ID=").append(p_C_AcctSchema_ID); - if (p_IsAllCurrencies) - sql.append(" AND i.C_Currency_ID<>a.C_Currency_ID"); + .append("FROM C_Invoice_v i") + .append(" INNER JOIN Fact_Acct fa ON (fa.AD_Table_ID=318 AND fa.Record_ID=i.C_Invoice_ID") + .append(" AND (i.GrandTotal=fa.AmtSourceDr OR i.GrandTotal=fa.AmtSourceCr))") + .append(" INNER JOIN C_AcctSchema a ON (fa.C_AcctSchema_ID=a.C_AcctSchema_ID) ") + .append("WHERE i.IsPaid='N'") + .append(" AND EXISTS (SELECT * FROM C_ElementValue ev ") + .append("WHERE ev.C_ElementValue_ID=fa.Account_ID AND (ev.AccountType='A' OR ev.AccountType='L'))") + .append(" AND fa.C_AcctSchema_ID=").append(p_C_AcctSchema_ID); + if (p_IsAllCurrencies) + sql.append(" AND i.C_Currency_ID<>a.C_Currency_ID"); if (ONLY_AR.equals(p_APAR)) - sql.append(" AND i.IsSOTrx='Y'"); + sql.append(" AND i.IsSOTrx='Y'"); else if (ONLY_AP.equals(p_APAR)) - sql.append(" AND i.IsSOTrx='N'"); + sql.append(" AND i.IsSOTrx='N'"); if (!p_IsAllCurrencies && p_C_Currency_ID != 0) - sql.append(" AND i.C_Currency_ID=").append(p_C_Currency_ID); + sql.append(" AND i.C_Currency_ID=").append(p_C_Currency_ID); - no = DB.executeUpdate(sql.toString(), get_TrxName()); - if (no != 0) { - if (log.isLoggable(Level.INFO)) log.info("Inserted #" + no); - } else if (log.isLoggable(Level.FINER)) { - log.warning("Inserted #" + no + " - " + sql); - } else { - log.warning("Inserted #" + no); + no = DB.executeUpdate(sql.toString(), get_TrxName()); + if (no != 0) { + if (log.isLoggable(Level.INFO)) log.info("Inserted #" + no); + } else if (log.isLoggable(Level.FINER)) { + log.warning("Inserted #" + no + " - " + sql); + } else { + log.warning("Inserted #" + no); } // Calculate Difference - sql = new StringBuilder("UPDATE T_InvoiceGL gl ") - .append("SET (AmtRevalDrDiff,AmtRevalCrDiff)=") - .append("(SELECT gl.AmtRevalDr-fa.AmtAcctDr, gl.AmtRevalCr-fa.AmtAcctCr ") - .append("FROM Fact_Acct fa ") - .append("WHERE gl.Fact_Acct_ID=fa.Fact_Acct_ID) ") - .append("WHERE AD_PInstance_ID=").append(getAD_PInstance_ID()); - int noT = DB.executeUpdate(sql.toString(), get_TrxName()); + sql = new StringBuilder("UPDATE T_InvoiceGL gl ") + .append("SET (AmtRevalDrDiff,AmtRevalCrDiff)=") + .append("(SELECT gl.AmtRevalDr-fa.AmtAcctDr, gl.AmtRevalCr-fa.AmtAcctCr ") + .append("FROM Fact_Acct fa ") + .append("WHERE gl.Fact_Acct_ID=fa.Fact_Acct_ID) ") + .append("WHERE AD_PInstance_ID=").append(getAD_PInstance_ID()); + int noT = DB.executeUpdate(sql.toString(), get_TrxName()); if (noT > 0) - if (log.isLoggable(Level.CONFIG)) log.config("Difference #" + noT); + if (log.isLoggable(Level.CONFIG)) log.config("Difference #" + noT); // Percentage - sql = new StringBuilder("UPDATE T_InvoiceGL SET Percent = 100 ") - .append("WHERE GrandTotal=OpenAmt AND AD_PInstance_ID=").append(getAD_PInstance_ID()); - no = DB.executeUpdate(sql.toString(), get_TrxName()); - if (no > 0) - if (log.isLoggable(Level.INFO)) log.info("Not Paid #" + no); - - sql = new StringBuilder("UPDATE T_InvoiceGL SET Percent = ROUND(OpenAmt*100/GrandTotal,6) ") - .append("WHERE GrandTotal<>OpenAmt AND GrandTotal <> 0 AND AD_PInstance_ID=").append(getAD_PInstance_ID()); - no = DB.executeUpdate(sql.toString(), get_TrxName()); - if (no > 0) - if (log.isLoggable(Level.INFO)) log.info("Partial Paid #" + no); - - sql = new StringBuilder("UPDATE T_InvoiceGL SET AmtRevalDr = AmtRevalDr * Percent/100,") - .append(" AmtRevalCr = AmtRevalCr * Percent/100,") - .append(" AmtRevalDrDiff = AmtRevalDrDiff * Percent/100,") - .append(" AmtRevalCrDiff = AmtRevalCrDiff * Percent/100 ") - .append("WHERE Percent <> 100 AND AD_PInstance_ID=").append(getAD_PInstance_ID()); - no = DB.executeUpdate(sql.toString(), get_TrxName()); + sql = new StringBuilder("UPDATE T_InvoiceGL SET Percent = 100 ") + .append("WHERE GrandTotal=OpenAmt AND AD_PInstance_ID=").append(getAD_PInstance_ID()); + no = DB.executeUpdate(sql.toString(), get_TrxName()); if (no > 0) - if (log.isLoggable(Level.CONFIG)) log.config("Partial Calc #" + no); + if (log.isLoggable(Level.INFO)) log.info("Not Paid #" + no); + + sql = new StringBuilder("UPDATE T_InvoiceGL SET Percent = ROUND(OpenAmt*100/GrandTotal,6) ") + .append("WHERE GrandTotal<>OpenAmt AND GrandTotal <> 0 AND AD_PInstance_ID=").append(getAD_PInstance_ID()); + no = DB.executeUpdate(sql.toString(), get_TrxName()); + if (no > 0) + if (log.isLoggable(Level.INFO)) log.info("Partial Paid #" + no); + + sql = new StringBuilder("UPDATE T_InvoiceGL SET AmtRevalDr = AmtRevalDr * Percent/100,") + .append(" AmtRevalCr = AmtRevalCr * Percent/100,") + .append(" AmtRevalDrDiff = AmtRevalDrDiff * Percent/100,") + .append(" AmtRevalCrDiff = AmtRevalCrDiff * Percent/100 ") + .append("WHERE Percent <> 100 AND AD_PInstance_ID=").append(getAD_PInstance_ID()); + no = DB.executeUpdate(sql.toString(), get_TrxName()); + if (no > 0) + if (log.isLoggable(Level.CONFIG)) log.config("Partial Calc #" + no); // Create Document String info = ""; @@ -205,9 +205,9 @@ public class InvoiceNGL extends SvrProcess log.warning("Can create Journal only for all currencies"); else info = createGLJournal(); - } - StringBuilder msgreturn = new StringBuilder("#").append(noT).append(info); - return msgreturn.toString(); + } + StringBuilder msgreturn = new StringBuilder("#").append(noT).append(info); + return msgreturn.toString(); } // doIt /** @@ -216,13 +216,13 @@ public class InvoiceNGL extends SvrProcess */ private String createGLJournal() { - //FR: [ 2214883 ] Remove SQL code and Replace for Query - final String whereClause = "AD_PInstance_ID=?"; - List list = new Query(getCtx(), X_T_InvoiceGL.Table_Name, whereClause, get_TrxName()) - .setParameters(getAD_PInstance_ID()) - .setOrderBy("AD_Org_ID") - .list(); - //FR: [ 2214883 ] Remove SQL code and Replace for Query + //FR: [ 2214883 ] Remove SQL code and Replace for Query + final String whereClause = "AD_PInstance_ID=?"; + List list = new Query(getCtx(), X_T_InvoiceGL.Table_Name, whereClause, get_TrxName()) + .setParameters(getAD_PInstance_ID()) + .setOrderBy("AD_Org_ID") + .list(); + //FR: [ 2214883 ] Remove SQL code and Replace for Query if (list.size() == 0) return " - No Records found"; @@ -237,23 +237,23 @@ public class InvoiceNGL extends SvrProcess cat = MGLCategory.get(getCtx(), docType.getGL_Category_ID()); } // - MJournal journal = new MJournal (getCtx(), 0, get_TrxName()); - journal.setC_DocType_ID(p_C_DocTypeReval_ID); - journal.setPostingType(MJournal.POSTINGTYPE_Actual); - journal.setDateDoc(p_DateReval); - journal.setDateAcct(p_DateReval); // sets the period too - journal.setC_Currency_ID(as.getC_Currency_ID()); - journal.setC_AcctSchema_ID (as.getC_AcctSchema_ID()); - journal.setC_ConversionType_ID(p_C_ConversionTypeReval_ID); - journal.setGL_Category_ID (cat.getGL_Category_ID()); - journal.setDescription(getName()); // updated below - if (!journal.save()) - return " - Could not create Journal"; - // + MJournal journal = new MJournal (getCtx(), 0, get_TrxName()); + journal.setC_DocType_ID(p_C_DocTypeReval_ID); + journal.setPostingType(MJournal.POSTINGTYPE_Actual); + journal.setDateDoc(p_DateReval); + journal.setDateAcct(p_DateReval); // sets the period too + journal.setC_Currency_ID(as.getC_Currency_ID()); + journal.setC_AcctSchema_ID (as.getC_AcctSchema_ID()); + journal.setC_ConversionType_ID(p_C_ConversionTypeReval_ID); + journal.setGL_Category_ID (cat.getGL_Category_ID()); + journal.setDescription(getName()); // updated below + if (!journal.save()) + return " - Could not create Journal"; + // BigDecimal gainTotal = Env.ZERO; BigDecimal lossTotal = Env.ZERO; int AD_Org_ID = 0; - MOrg org = null; + MOrg org = null; for (int i = 0; i < list.size(); i++) { X_T_InvoiceGL gl = list.get(i); @@ -261,65 +261,65 @@ public class InvoiceNGL extends SvrProcess continue; MInvoice invoice = new MInvoice(getCtx(), gl.getC_Invoice_ID(), null); if (invoice.getC_Currency_ID() == as.getC_Currency_ID()) - continue; - // - if (AD_Org_ID == 0) // invoice org id - AD_Org_ID = gl.getAD_Org_ID(); - // Change in Org - if (AD_Org_ID != gl.getAD_Org_ID()) - { - createBalancing (asDefaultAccts, journal, gainTotal, lossTotal, AD_Org_ID, (i+1) * 10); - // - AD_Org_ID = gl.getAD_Org_ID(); - gainTotal = Env.ZERO; - lossTotal = Env.ZERO; - journal = null; - } - // - if (org == null) { - org = MOrg.get(getCtx(), gl.getAD_Org_ID()); - journal.setDescription (getName() + " - " + org.getName()); - if (!journal.save()) - return " - Could not set Description for Journal"; + continue; + // + if (AD_Org_ID == 0) // invoice org id + AD_Org_ID = gl.getAD_Org_ID(); + // Change in Org + if (AD_Org_ID != gl.getAD_Org_ID()) + { + createBalancing (asDefaultAccts, journal, gainTotal, lossTotal, AD_Org_ID, (i+1) * 10); + // + AD_Org_ID = gl.getAD_Org_ID(); + gainTotal = Env.ZERO; + lossTotal = Env.ZERO; + journal = null; + } + // + if (org == null) { + org = MOrg.get(getCtx(), gl.getAD_Org_ID()); + journal.setDescription (getName() + " - " + org.getName()); + if (!journal.save()) + return " - Could not set Description for Journal"; } // MJournalLine line = new MJournalLine(journal); line.setLine((i+1) * 10); line.setDescription(invoice.getSummary()); // - MFactAcct fa = new MFactAcct (getCtx(), gl.getFact_Acct_ID(), null); + MFactAcct fa = new MFactAcct (getCtx(), gl.getFact_Acct_ID(), null); MAccount acct = MAccount.get(fa); line.setC_ValidCombination_ID(acct); BigDecimal dr = gl.getAmtRevalDrDiff(); - BigDecimal cr = gl.getAmtRevalCrDiff(); - // Check if acct.IsActiva to differentiate gain and loss -> - // acct.isActiva negative dr or positive cr -> loss - // acct.isActiva positive dr or negative cr -> gain - // acct.isPassiva negative cr or positive dr -> gain - // acct.isPassiva positive cr or negative dr -> loss - if (acct.isActiva()) { - if (dr.signum() < 0) { - lossTotal = lossTotal.add(dr.negate()); - } else if (dr.signum() > 0) { - gainTotal = gainTotal.add(dr); - } - if (cr.signum() > 0) { - lossTotal = lossTotal.add(cr); - } if (cr.signum() < 0) { - gainTotal = gainTotal.add(cr.negate()); - } - } else { // isPassiva - if (cr.signum() < 0) { - gainTotal = gainTotal.add(cr.negate()); - } else if (cr.signum() > 0) { - lossTotal = lossTotal.add(cr); - } - if (dr.signum() > 0) { - gainTotal = gainTotal.add(dr); - } else if (dr.signum() < 0) { - lossTotal = lossTotal.add(dr.negate()); - } - } + BigDecimal cr = gl.getAmtRevalCrDiff(); + // Check if acct.IsActiva to differentiate gain and loss -> + // acct.isActiva negative dr or positive cr -> loss + // acct.isActiva positive dr or negative cr -> gain + // acct.isPassiva negative cr or positive dr -> gain + // acct.isPassiva positive cr or negative dr -> loss + if (acct.isActiva()) { + if (dr.signum() < 0) { + lossTotal = lossTotal.add(dr.negate()); + } else if (dr.signum() > 0) { + gainTotal = gainTotal.add(dr); + } + if (cr.signum() > 0) { + lossTotal = lossTotal.add(cr); + } if (cr.signum() < 0) { + gainTotal = gainTotal.add(cr.negate()); + } + } else { // isPassiva + if (cr.signum() < 0) { + gainTotal = gainTotal.add(cr.negate()); + } else if (cr.signum() > 0) { + lossTotal = lossTotal.add(cr); + } + if (dr.signum() > 0) { + gainTotal = gainTotal.add(dr); + } else if (dr.signum() < 0) { + lossTotal = lossTotal.add(dr.negate()); + } + } line.setAmtSourceDr (dr); line.setAmtAcctDr (dr); line.setAmtSourceCr (cr); @@ -327,10 +327,10 @@ public class InvoiceNGL extends SvrProcess line.saveEx(); } createBalancing (asDefaultAccts, journal, gainTotal, lossTotal, AD_Org_ID, (list.size()+1) * 10); - - StringBuilder msgreturn = new StringBuilder(" - ").append(journal.getDocumentNo()).append(" #").append(list.size()); - addLog(journal.getGL_Journal_ID(), null, null, msgreturn.toString(), MJournal.Table_ID, journal.getGL_Journal_ID()); - return "OK"; + + StringBuilder msgreturn = new StringBuilder(" - ").append(journal.getDocumentNo()).append(" #").append(list.size()); + addLog(journal.getGL_Journal_ID(), null, null, msgreturn.toString(), MJournal.Table_ID, journal.getGL_Journal_ID()); + return "OK"; } // createGLJournal /** @@ -346,7 +346,7 @@ public class InvoiceNGL extends SvrProcess BigDecimal gainTotal, BigDecimal lossTotal, int AD_Org_ID, int lineNo) { if (journal == null) - throw new IllegalArgumentException("Journal is null"); + throw new IllegalArgumentException("Journal is null"); // CR Entry = Gain if (gainTotal.signum() != 0) { @@ -358,7 +358,7 @@ public class InvoiceNGL extends SvrProcess base.getM_Product_ID(), base.getC_BPartner_ID(), base.getAD_OrgTrx_ID(), base.getC_LocFrom_ID(), base.getC_LocTo_ID(), base.getC_SalesRegion_ID(), base.getC_Project_ID(), base.getC_Campaign_ID(), base.getC_Activity_ID(), - base.getUser1_ID(), base.getUser2_ID(), base.getUserElement1_ID(), base.getUserElement2_ID(), + base.getUser1_ID(), base.getUser2_ID(), base.getUserElement1_ID(), base.getUserElement2_ID(), get_TrxName()); line.setDescription(Msg.getElement(getCtx(), "UnrealizedGain_Acct")); line.setC_ValidCombination_ID(acct.getC_ValidCombination_ID()); @@ -377,7 +377,7 @@ public class InvoiceNGL extends SvrProcess base.getM_Product_ID(), base.getC_BPartner_ID(), base.getAD_OrgTrx_ID(), base.getC_LocFrom_ID(), base.getC_LocTo_ID(), base.getC_SalesRegion_ID(), base.getC_Project_ID(), base.getC_Campaign_ID(), base.getC_Activity_ID(), - base.getUser1_ID(), base.getUser2_ID(), base.getUserElement1_ID(), base.getUserElement2_ID(), + base.getUser1_ID(), base.getUser2_ID(), base.getUserElement1_ID(), base.getUserElement2_ID(), get_TrxName()); line.setDescription(Msg.getElement(getCtx(), "UnrealizedLoss_Acct")); line.setC_ValidCombination_ID(acct.getC_ValidCombination_ID()); diff --git a/org.adempiere.base.process/src/org/compiere/process/PaySelectionCreateFrom.java b/org.adempiere.base.process/src/org/compiere/process/PaySelectionCreateFrom.java index 400d057630..f388ffbd6b 100644 --- a/org.adempiere.base.process/src/org/compiere/process/PaySelectionCreateFrom.java +++ b/org.adempiere.base.process/src/org/compiere/process/PaySelectionCreateFrom.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,20 +16,20 @@ *****************************************************************************/ package org.compiere.process; -import java.math.BigDecimal; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.logging.Level; - -import org.adempiere.exceptions.AdempiereException; -import org.adempiere.exceptions.DBException; -import org.compiere.model.MPaySelection; -import org.compiere.model.MPaySelectionLine; -import org.compiere.model.X_C_Order; -import org.compiere.util.DB; -import org.compiere.util.Env; +import java.math.BigDecimal; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.logging.Level; + +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.exceptions.DBException; +import org.compiere.model.MPaySelection; +import org.compiere.model.MPaySelectionLine; +import org.compiere.model.X_C_Order; +import org.compiere.util.DB; +import org.compiere.util.Env; /** @@ -84,7 +84,7 @@ public class PaySelectionCreateFrom extends SvrProcess p_C_BPartner_ID = para[i].getParameterAsInt(); else if (name.equals("C_BP_Group_ID")) p_C_BP_Group_ID = para[i].getParameterAsInt(); - else if (name.equals("DueDate")) + else if (name.equals("DueDate")) p_DueDate = (Timestamp) para[i].getParameter(); else log.log(Level.SEVERE, "Unknown Parameter: " + name); @@ -99,7 +99,7 @@ public class PaySelectionCreateFrom extends SvrProcess */ protected String doIt() throws Exception { - if (log.isLoggable(Level.INFO)) log.info ("C_PaySelection_ID=" + p_C_PaySelection_ID + if (log.isLoggable(Level.INFO)) log.info ("C_PaySelection_ID=" + p_C_PaySelection_ID + ", OnlyDiscount=" + p_OnlyDiscount + ", OnlyDue=" + p_OnlyDue + ", IncludeInDispute=" + p_IncludeInDispute + ", MatchRequirement=" + p_MatchRequirement @@ -112,95 +112,95 @@ public class PaySelectionCreateFrom extends SvrProcess if (psel.isProcessed()) throw new IllegalArgumentException("@Processed@"); - if ( p_DueDate == null ) - p_DueDate = psel.getPayDate(); + if ( p_DueDate == null ) + p_DueDate = psel.getPayDate(); // psel.getPayDate(); - StringBuilder sql = new StringBuilder("SELECT C_Invoice_ID,") // 1 + StringBuilder sql = new StringBuilder("SELECT C_Invoice_ID,") // 1 // Open - .append(" currencyConvert(invoiceOpen(i.C_Invoice_ID, i.C_InvoicePaySchedule_ID)") - .append(",i.C_Currency_ID, ?,?, i.C_ConversionType_ID,i.AD_Client_ID,i.AD_Org_ID) AS PayAmt,") // 2 ##p1/p2 Currency_To,PayDate - // Discount - .append(" currencyConvert(invoiceDiscount(i.C_Invoice_ID,?,i.C_InvoicePaySchedule_ID)") // ##p3 PayDate - .append(",i.C_Currency_ID, ?,?,i.C_ConversionType_ID,i.AD_Client_ID,i.AD_Org_ID) AS DiscountAmt,") // 3 ##p4/p5 Currency_To,PayDate - .append(" PaymentRule, IsSOTrx, ") // 4..5 - .append(" currencyConvert(invoiceWriteOff(i.C_Invoice_ID) ") - .append(",i.C_Currency_ID, ?,?,i.C_ConversionType_ID,i.AD_Client_ID,i.AD_Org_ID) AS WriteOffAmt ") // 6 ##p6/p7 Currency_To,PayDate - .append("FROM C_Invoice_v i WHERE "); - if (X_C_Order.PAYMENTRULE_DirectDebit.equals(p_PaymentRule)) - sql.append("IsSOTrx='Y'"); - else - sql.append("IsSOTrx='N'"); - sql.append(" AND IsPaid='N' AND DocStatus IN ('CO','CL')") - .append(" AND AD_Client_ID=?") // ##p8 - // Existing Payments - Will reselect Invoice if prepared but not paid - .append(" AND NOT EXISTS (SELECT * FROM C_PaySelectionLine psl") - .append(" INNER JOIN C_PaySelectionCheck psc ON (psl.C_PaySelectionCheck_ID=psc.C_PaySelectionCheck_ID)") - .append(" LEFT OUTER JOIN C_Payment pmt ON (pmt.C_Payment_ID=psc.C_Payment_ID)") - .append(" WHERE i.C_Invoice_ID=psl.C_Invoice_ID AND psl.IsActive='Y'") - .append(" AND (pmt.DocStatus IS NULL OR pmt.DocStatus NOT IN ('VO','RE')) )") - // Don't generate again invoices already on this payment selection - .append(" AND i.C_Invoice_ID NOT IN (SELECT i.C_Invoice_ID FROM C_PaySelectionLine psl WHERE psl.C_PaySelection_ID=?)"); // ##p9 + .append(" currencyConvert(invoiceOpen(i.C_Invoice_ID, i.C_InvoicePaySchedule_ID)") + .append(",i.C_Currency_ID, ?,?, i.C_ConversionType_ID,i.AD_Client_ID,i.AD_Org_ID) AS PayAmt,") // 2 ##p1/p2 Currency_To,PayDate + // Discount + .append(" currencyConvert(invoiceDiscount(i.C_Invoice_ID,?,i.C_InvoicePaySchedule_ID)") // ##p3 PayDate + .append(",i.C_Currency_ID, ?,?,i.C_ConversionType_ID,i.AD_Client_ID,i.AD_Org_ID) AS DiscountAmt,") // 3 ##p4/p5 Currency_To,PayDate + .append(" PaymentRule, IsSOTrx, ") // 4..5 + .append(" currencyConvert(invoiceWriteOff(i.C_Invoice_ID) ") + .append(",i.C_Currency_ID, ?,?,i.C_ConversionType_ID,i.AD_Client_ID,i.AD_Org_ID) AS WriteOffAmt ") // 6 ##p6/p7 Currency_To,PayDate + .append("FROM C_Invoice_v i WHERE "); + if (X_C_Order.PAYMENTRULE_DirectDebit.equals(p_PaymentRule)) + sql.append("IsSOTrx='Y'"); + else + sql.append("IsSOTrx='N'"); + sql.append(" AND IsPaid='N' AND DocStatus IN ('CO','CL')") + .append(" AND AD_Client_ID=?") // ##p8 + // Existing Payments - Will reselect Invoice if prepared but not paid + .append(" AND NOT EXISTS (SELECT * FROM C_PaySelectionLine psl") + .append(" INNER JOIN C_PaySelectionCheck psc ON (psl.C_PaySelectionCheck_ID=psc.C_PaySelectionCheck_ID)") + .append(" LEFT OUTER JOIN C_Payment pmt ON (pmt.C_Payment_ID=psc.C_Payment_ID)") + .append(" WHERE i.C_Invoice_ID=psl.C_Invoice_ID AND psl.IsActive='Y'") + .append(" AND (pmt.DocStatus IS NULL OR pmt.DocStatus NOT IN ('VO','RE')) )") + // Don't generate again invoices already on this payment selection + .append(" AND i.C_Invoice_ID NOT IN (SELECT i.C_Invoice_ID FROM C_PaySelectionLine psl WHERE psl.C_PaySelection_ID=?)"); // ##p9 // Disputed if (!p_IncludeInDispute) - sql.append(" AND i.IsInDispute='N'"); + sql.append(" AND i.IsInDispute='N'"); // PaymentRule (optional) if (p_PaymentRule != null) - sql.append(" AND PaymentRule=?"); // ## + sql.append(" AND PaymentRule=?"); // ## // OnlyDiscount if (p_OnlyDiscount) { if (p_OnlyDue) - sql.append(" AND ("); + sql.append(" AND ("); else - sql.append(" AND "); - sql.append("invoiceDiscount(i.C_Invoice_ID,?,i.C_InvoicePaySchedule_ID) > 0"); // ## + sql.append(" AND "); + sql.append("invoiceDiscount(i.C_Invoice_ID,?,i.C_InvoicePaySchedule_ID) > 0"); // ## } // OnlyDue if (p_OnlyDue) { if (p_OnlyDiscount) - sql.append(" OR "); + sql.append(" OR "); else - sql.append(" AND "); - // sql.append("paymentTermDueDays(C_PaymentTerm_ID, DateInvoiced, ?) >= 0"); // ## - sql.append("i.DueDate<=?"); // ## + sql.append(" AND "); + // sql.append("paymentTermDueDays(C_PaymentTerm_ID, DateInvoiced, ?) >= 0"); // ## + sql.append("i.DueDate<=?"); // ## if (p_OnlyDiscount) - sql.append(")"); + sql.append(")"); } // Business Partner if (p_C_BPartner_ID != 0) - sql.append(" AND C_BPartner_ID=?"); // ## + sql.append(" AND C_BPartner_ID=?"); // ## // Business Partner Group else if (p_C_BP_Group_ID != 0) - sql.append(" AND EXISTS (SELECT * FROM C_BPartner bp ") - .append("WHERE bp.C_BPartner_ID=i.C_BPartner_ID AND bp.C_BP_Group_ID=?)"); // ## + sql.append(" AND EXISTS (SELECT * FROM C_BPartner bp ") + .append("WHERE bp.C_BPartner_ID=i.C_BPartner_ID AND bp.C_BP_Group_ID=?)"); // ## // PO Matching Requirement if (p_MatchRequirement.equals("P") || p_MatchRequirement.equals("B")) { - sql.append(" AND EXISTS (SELECT * FROM C_InvoiceLine il ") - .append("WHERE i.C_Invoice_ID=il.C_Invoice_ID") - .append(" AND QtyInvoiced=(SELECT SUM(Qty) FROM M_MatchPO m ") - .append("WHERE il.C_InvoiceLine_ID=m.C_InvoiceLine_ID))"); + sql.append(" AND EXISTS (SELECT * FROM C_InvoiceLine il ") + .append("WHERE i.C_Invoice_ID=il.C_Invoice_ID") + .append(" AND QtyInvoiced=(SELECT SUM(Qty) FROM M_MatchPO m ") + .append("WHERE il.C_InvoiceLine_ID=m.C_InvoiceLine_ID))"); } // Receipt Matching Requirement if (p_MatchRequirement.equals("R") || p_MatchRequirement.equals("B")) { - sql.append(" AND EXISTS (SELECT * FROM C_InvoiceLine il ") - .append("WHERE i.C_Invoice_ID=il.C_Invoice_ID") - .append(" AND QtyInvoiced=(SELECT SUM(Qty) FROM M_MatchInv m ") - .append("WHERE il.C_InvoiceLine_ID=m.C_InvoiceLine_ID))"); + sql.append(" AND EXISTS (SELECT * FROM C_InvoiceLine il ") + .append("WHERE i.C_Invoice_ID=il.C_Invoice_ID") + .append(" AND QtyInvoiced=(SELECT SUM(Qty) FROM M_MatchInv m ") + .append("WHERE il.C_InvoiceLine_ID=m.C_InvoiceLine_ID))"); } // int lines = 0; int C_CurrencyTo_ID = psel.getC_Currency_ID(); - PreparedStatement pstmt = null; - ResultSet rs = null; + PreparedStatement pstmt = null; + ResultSet rs = null; try { - pstmt = DB.prepareStatement (sql.toString(), get_TrxName()); + pstmt = DB.prepareStatement (sql.toString(), get_TrxName()); int index = 1; pstmt.setInt (index++, C_CurrencyTo_ID); pstmt.setTimestamp(index++, psel.getPayDate()); @@ -208,11 +208,11 @@ public class PaySelectionCreateFrom extends SvrProcess pstmt.setTimestamp(index++, psel.getPayDate()); pstmt.setInt (index++, C_CurrencyTo_ID); pstmt.setTimestamp(index++, psel.getPayDate()); - pstmt.setInt (index++, C_CurrencyTo_ID); - pstmt.setTimestamp(index++, psel.getPayDate()); + pstmt.setInt (index++, C_CurrencyTo_ID); + pstmt.setTimestamp(index++, psel.getPayDate()); // pstmt.setInt(index++, psel.getAD_Client_ID()); - pstmt.setInt(index++, p_C_PaySelection_ID); + pstmt.setInt(index++, p_C_PaySelection_ID); if (p_PaymentRule != null) pstmt.setString(index++, p_PaymentRule); if (p_OnlyDiscount) @@ -224,7 +224,7 @@ public class PaySelectionCreateFrom extends SvrProcess else if (p_C_BP_Group_ID != 0) pstmt.setInt (index++, p_C_BP_Group_ID); // - rs = pstmt.executeQuery (); + rs = pstmt.executeQuery (); while (rs.next ()) { int C_Invoice_ID = rs.getInt(1); @@ -232,7 +232,7 @@ public class PaySelectionCreateFrom extends SvrProcess if (C_Invoice_ID == 0 || Env.ZERO.compareTo(PayAmt) == 0) continue; BigDecimal DiscountAmt = rs.getBigDecimal(3); - BigDecimal WriteOffAmt = rs.getBigDecimal(6); + BigDecimal WriteOffAmt = rs.getBigDecimal(6); String PaymentRule = rs.getString(4); boolean isSOTrx = "Y".equals(rs.getString(5)); // @@ -245,23 +245,23 @@ public class PaySelectionCreateFrom extends SvrProcess throw new IllegalStateException ("Cannot save MPaySelectionLine"); } } - } - catch (SQLException e) - { - throw new DBException(e); - } - catch (Exception e) - { - throw new AdempiereException(e); - } - finally - { - DB.close(rs, pstmt); - rs = null; - pstmt = null; } - StringBuilder msgreturn = new StringBuilder("@C_PaySelectionLine_ID@ - #").append(lines); - return msgreturn.toString(); + catch (SQLException e) + { + throw new DBException(e); + } + catch (Exception e) + { + throw new AdempiereException(e); + } + finally + { + DB.close(rs, pstmt); + rs = null; + pstmt = null; + } + StringBuilder msgreturn = new StringBuilder("@C_PaySelectionLine_ID@ - #").append(lines); + return msgreturn.toString(); } // doIt } // PaySelectionCreateFrom diff --git a/org.adempiere.base.process/src/org/compiere/process/YearCreatePeriods.java b/org.adempiere.base.process/src/org/compiere/process/YearCreatePeriods.java index a867a58420..0ad5cfab2f 100644 --- a/org.adempiere.base.process/src/org/compiere/process/YearCreatePeriods.java +++ b/org.adempiere.base.process/src/org/compiere/process/YearCreatePeriods.java @@ -1,77 +1,77 @@ -/****************************************************************************** - * 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.compiere.process; +/****************************************************************************** + * 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.compiere.process; -import java.sql.Timestamp; -import java.util.logging.Level; - -import org.compiere.model.MYear; +import java.sql.Timestamp; +import java.util.logging.Level; + +import org.compiere.model.MYear; import org.compiere.util.AdempiereUserError; - -/** - * Create Periods of year - * - * @author Jorg Janke - * @version $Id: YearCreatePeriods.java,v 1.2 2006/07/30 00:51:01 jjanke Exp $ - */ -public class YearCreatePeriods extends SvrProcess -{ - private int p_C_Year_ID = 0; - private Timestamp p_StartDate; - private String p_DateFormat; - - /** - * Prepare - */ - protected void prepare () - { - - ProcessInfoParameter[] para = getParameter(); - for (int i = 0; i < para.length; i++) - { - String name = para[i].getParameterName(); - if (para[i].getParameter() == null) - ; - else if (name.equals("StartDate")) - p_StartDate = (Timestamp) para[i].getParameter(); - else if (name.equals("DateFormat")) - p_DateFormat = (String) para[i].getParameter(); - else - log.log(Level.SEVERE, "Unknown Parameter: " + name); - } - p_C_Year_ID = getRecord_ID(); - } // prepare - - /** - * Process - * @return info - * @throws Exception - */ - protected String doIt () - throws Exception - { - MYear year = new MYear (getCtx(), p_C_Year_ID, get_TrxName()); - if (p_C_Year_ID == 0 || year.get_ID() != p_C_Year_ID) - throw new AdempiereUserError ("@NotFound@: @C_Year_ID@ - " + p_C_Year_ID); - if (log.isLoggable(Level.INFO)) log.info(year.toString()); + +/** + * Create Periods of year + * + * @author Jorg Janke + * @version $Id: YearCreatePeriods.java,v 1.2 2006/07/30 00:51:01 jjanke Exp $ + */ +public class YearCreatePeriods extends SvrProcess +{ + private int p_C_Year_ID = 0; + private Timestamp p_StartDate; + private String p_DateFormat; + + /** + * Prepare + */ + protected void prepare () + { + + ProcessInfoParameter[] para = getParameter(); + for (int i = 0; i < para.length; i++) + { + String name = para[i].getParameterName(); + if (para[i].getParameter() == null) + ; + else if (name.equals("StartDate")) + p_StartDate = (Timestamp) para[i].getParameter(); + else if (name.equals("DateFormat")) + p_DateFormat = (String) para[i].getParameter(); + else + log.log(Level.SEVERE, "Unknown Parameter: " + name); + } + p_C_Year_ID = getRecord_ID(); + } // prepare + + /** + * Process + * @return info + * @throws Exception + */ + protected String doIt () + throws Exception + { + MYear year = new MYear (getCtx(), p_C_Year_ID, get_TrxName()); + if (p_C_Year_ID == 0 || year.get_ID() != p_C_Year_ID) + throw new AdempiereUserError ("@NotFound@: @C_Year_ID@ - " + p_C_Year_ID); + if (log.isLoggable(Level.INFO)) log.info(year.toString()); // - if (year.createStdPeriods(null, p_StartDate, p_DateFormat)) - return "@OK@"; + if (year.createStdPeriods(null, p_StartDate, p_DateFormat)) + return "@OK@"; return "@Error@"; - } // doIt - -} // YearCreatePeriods + } // doIt + +} // YearCreatePeriods diff --git a/org.adempiere.base/src/org/compiere/acct/DocLine.java b/org.adempiere.base/src/org/compiere/acct/DocLine.java index cc793ed1bd..59be3f1a90 100644 --- a/org.adempiere.base/src/org/compiere/acct/DocLine.java +++ b/org.adempiere.base/src/org/compiere/acct/DocLine.java @@ -1,1169 +1,1169 @@ -/****************************************************************************** - * 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.compiere.acct; - -import java.math.BigDecimal; -import java.sql.Timestamp; -import java.util.logging.Level; - -import org.compiere.model.MAccount; -import org.compiere.model.MAcctSchema; -import org.compiere.model.MCharge; -import org.compiere.model.MCostDetail; -import org.compiere.model.MProduct; -import org.compiere.model.PO; -import org.compiere.model.ProductCost; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; - -/** - * Standard Document Line - * - * @author Jorg Janke - * @author Armen Rizal, Goodwill Consulting - *
  • BF [ 1745154 ] Cost in Reversing Material Related Docs - * @version $Id: DocLine.java,v 1.2 2006/07/30 00:53:33 jjanke Exp $ - */ -public class DocLine -{ - /** - * Create Document Line - * @param po line persistent object - * @param doc header - */ - public DocLine (PO po, Doc doc) - { - if (po == null) - throw new IllegalArgumentException("PO is null"); - p_po = po; - m_doc = doc; - // - // Document Consistency - if (p_po.getAD_Org_ID() == 0) - p_po.setAD_Org_ID(m_doc.getAD_Org_ID()); - } // DocLine - - /** Persistent Object */ - protected PO p_po = null; - /** Parent */ - private Doc m_doc = null; - /** Log */ - protected CLogger log = CLogger.getCLogger(getClass()); - - /** Qty */ - private BigDecimal m_qty = null; - - // -- GL Amounts - /** Debit Journal Amt */ - private BigDecimal m_AmtSourceDr = Env.ZERO; - /** Credit Journal Amt */ - private BigDecimal m_AmtSourceCr = Env.ZERO; - /** Net Line Amt */ - private BigDecimal m_LineNetAmt = null; - /** List Amount */ - private BigDecimal m_ListAmt = Env.ZERO; - /** Discount Amount */ - private BigDecimal m_DiscountAmt = Env.ZERO; - - /** Converted Amounts */ - private BigDecimal m_AmtAcctDr = null; - private BigDecimal m_AmtAcctCr = null; - /** Acct Schema */ - private int m_C_AcctSchema_ID = 0; - - /** Product Costs */ - private ProductCost m_productCost = null; - /** Production indicator */ - private boolean m_productionBOM = false; - /** Outside Processing */ - private int m_PP_Cost_Collector_ID = 0; - /** Account used only for GL Journal */ - private MAccount m_account = null; - - /** Accounting Date */ - private Timestamp m_DateAcct = null; - /** Document Date */ - private Timestamp m_DateDoc = null; - /** Sales Region */ - private int m_C_SalesRegion_ID = -1; - /** Sales Region */ - private int m_C_BPartner_ID = -1; - /** Location From */ - private int m_C_LocFrom_ID = 0; - /** Location To */ - private int m_C_LocTo_ID = 0; - /** Item */ - private Boolean m_isItem = null; - /** Currency */ - private int m_C_Currency_ID = -1; - /** Conversion Type */ - private int m_C_ConversionType_ID = -1; - /** Period */ - private int m_C_Period_ID = -1; - - /** - * Get Currency - * @return c_Currency_ID - */ - public int getC_Currency_ID () - { - if (m_C_Currency_ID == -1) - { - int index = p_po.get_ColumnIndex("C_Currency_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - m_C_Currency_ID = ii.intValue(); - } - if (m_C_Currency_ID <= 0) - m_C_Currency_ID = m_doc.getC_Currency_ID(); - } - return m_C_Currency_ID; - } // getC_Currency_ID - - /** - * Get Conversion Type - * @return C_ConversionType_ID - */ - public int getC_ConversionType_ID () - { - if (m_C_ConversionType_ID == -1) - { - int index = p_po.get_ColumnIndex("C_ConversionType_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - m_C_ConversionType_ID = ii.intValue(); - } - if (m_C_ConversionType_ID <= 0) - m_C_ConversionType_ID = m_doc.getC_ConversionType_ID(); - } - return m_C_ConversionType_ID; - } // getC_ConversionType_ID - - /** - * Set C_ConversionType_ID - * @param C_ConversionType_ID id - */ - protected void setC_ConversionType_ID(int C_ConversionType_ID) - { - m_C_ConversionType_ID = C_ConversionType_ID; - } // setC_ConversionType_ID - - /** - * Set Amount (DR) - * @param sourceAmt source amt - */ - public void setAmount (BigDecimal sourceAmt) - { - m_AmtSourceDr = sourceAmt == null ? Env.ZERO : sourceAmt; - m_AmtSourceCr = Env.ZERO; - } // setAmounts - - /** - * Set Amounts - * @param amtSourceDr source amount dr - * @param amtSourceCr source amount cr - */ - public void setAmount (BigDecimal amtSourceDr, BigDecimal amtSourceCr) - { - m_AmtSourceDr = amtSourceDr == null ? Env.ZERO : amtSourceDr; - m_AmtSourceCr = amtSourceCr == null ? Env.ZERO : amtSourceCr; - } // setAmounts - - /** - * Set Converted Amounts - * @param C_AcctSchema_ID acct schema - * @param amtAcctDr acct amount dr - * @param amtAcctCr acct amount cr - */ - public void setConvertedAmt (int C_AcctSchema_ID, BigDecimal amtAcctDr, BigDecimal amtAcctCr) - { - m_C_AcctSchema_ID = C_AcctSchema_ID; - m_AmtAcctDr = amtAcctDr; - m_AmtAcctCr = amtAcctCr; - } // setConvertedAmt - - /** - * Line Net Amount or Dr-Cr - * @return balance - */ - public BigDecimal getAmtSource() - { - return m_AmtSourceDr.subtract(m_AmtSourceCr); - } // getAmount - - /** - * Get (Journal) Line Source Dr Amount - * @return DR source amount - */ - public BigDecimal getAmtSourceDr() - { - return m_AmtSourceDr; - } // getAmtSourceDr - - /** - * Get (Journal) Line Source Cr Amount - * @return CR source amount - */ - public BigDecimal getAmtSourceCr() - { - return m_AmtSourceCr; - } // getAmtSourceCr - - /** - * Line Journal Accounted Dr Amount - * @return DR accounted amount - */ - public BigDecimal getAmtAcctDr() - { - return m_AmtAcctDr; - } // getAmtAcctDr - - /** - * Line Journal Accounted Cr Amount - * @return CR accounted amount - */ - public BigDecimal getAmtAcctCr() - { - return m_AmtAcctCr; - } // getAmtAccrCr - - /** - * Charge Amount - * @return charge amount - */ - public BigDecimal getChargeAmt() - { - int index = p_po.get_ColumnIndex("ChargeAmt"); - if (index != -1) - { - BigDecimal bd = (BigDecimal)p_po.get_Value(index); - if (bd != null) - return bd; - } - return Env.ZERO; - } // getChargeAmt - - /** - * Set Product Amounts - * @param LineNetAmt Line Net Amt - * @param PriceList Price List - * @param Qty Qty for discount calc - */ - public void setAmount (BigDecimal LineNetAmt, BigDecimal PriceList, BigDecimal Qty) - { - m_LineNetAmt = LineNetAmt == null ? Env.ZERO : LineNetAmt; - - if (PriceList != null && Qty != null) - m_ListAmt = PriceList.multiply(Qty); +/****************************************************************************** + * 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.compiere.acct; + +import java.math.BigDecimal; +import java.sql.Timestamp; +import java.util.logging.Level; + +import org.compiere.model.MAccount; +import org.compiere.model.MAcctSchema; +import org.compiere.model.MCharge; +import org.compiere.model.MCostDetail; +import org.compiere.model.MProduct; +import org.compiere.model.PO; +import org.compiere.model.ProductCost; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; + +/** + * Standard Document Line + * + * @author Jorg Janke + * @author Armen Rizal, Goodwill Consulting + *
  • BF [ 1745154 ] Cost in Reversing Material Related Docs + * @version $Id: DocLine.java,v 1.2 2006/07/30 00:53:33 jjanke Exp $ + */ +public class DocLine +{ + /** + * Create Document Line + * @param po line persistent object + * @param doc header + */ + public DocLine (PO po, Doc doc) + { + if (po == null) + throw new IllegalArgumentException("PO is null"); + p_po = po; + m_doc = doc; + // + // Document Consistency + if (p_po.getAD_Org_ID() == 0) + p_po.setAD_Org_ID(m_doc.getAD_Org_ID()); + } // DocLine + + /** Persistent Object */ + protected PO p_po = null; + /** Parent */ + private Doc m_doc = null; + /** Log */ + protected CLogger log = CLogger.getCLogger(getClass()); + + /** Qty */ + private BigDecimal m_qty = null; + + // -- GL Amounts + /** Debit Journal Amt */ + private BigDecimal m_AmtSourceDr = Env.ZERO; + /** Credit Journal Amt */ + private BigDecimal m_AmtSourceCr = Env.ZERO; + /** Net Line Amt */ + private BigDecimal m_LineNetAmt = null; + /** List Amount */ + private BigDecimal m_ListAmt = Env.ZERO; + /** Discount Amount */ + private BigDecimal m_DiscountAmt = Env.ZERO; + + /** Converted Amounts */ + private BigDecimal m_AmtAcctDr = null; + private BigDecimal m_AmtAcctCr = null; + /** Acct Schema */ + private int m_C_AcctSchema_ID = 0; + + /** Product Costs */ + private ProductCost m_productCost = null; + /** Production indicator */ + private boolean m_productionBOM = false; + /** Outside Processing */ + private int m_PP_Cost_Collector_ID = 0; + /** Account used only for GL Journal */ + private MAccount m_account = null; + + /** Accounting Date */ + private Timestamp m_DateAcct = null; + /** Document Date */ + private Timestamp m_DateDoc = null; + /** Sales Region */ + private int m_C_SalesRegion_ID = -1; + /** Sales Region */ + private int m_C_BPartner_ID = -1; + /** Location From */ + private int m_C_LocFrom_ID = 0; + /** Location To */ + private int m_C_LocTo_ID = 0; + /** Item */ + private Boolean m_isItem = null; + /** Currency */ + private int m_C_Currency_ID = -1; + /** Conversion Type */ + private int m_C_ConversionType_ID = -1; + /** Period */ + private int m_C_Period_ID = -1; + + /** + * Get Currency + * @return c_Currency_ID + */ + public int getC_Currency_ID () + { + if (m_C_Currency_ID == -1) + { + int index = p_po.get_ColumnIndex("C_Currency_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + m_C_Currency_ID = ii.intValue(); + } + if (m_C_Currency_ID <= 0) + m_C_Currency_ID = m_doc.getC_Currency_ID(); + } + return m_C_Currency_ID; + } // getC_Currency_ID + + /** + * Get Conversion Type + * @return C_ConversionType_ID + */ + public int getC_ConversionType_ID () + { + if (m_C_ConversionType_ID == -1) + { + int index = p_po.get_ColumnIndex("C_ConversionType_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + m_C_ConversionType_ID = ii.intValue(); + } + if (m_C_ConversionType_ID <= 0) + m_C_ConversionType_ID = m_doc.getC_ConversionType_ID(); + } + return m_C_ConversionType_ID; + } // getC_ConversionType_ID + + /** + * Set C_ConversionType_ID + * @param C_ConversionType_ID id + */ + protected void setC_ConversionType_ID(int C_ConversionType_ID) + { + m_C_ConversionType_ID = C_ConversionType_ID; + } // setC_ConversionType_ID + + /** + * Set Amount (DR) + * @param sourceAmt source amt + */ + public void setAmount (BigDecimal sourceAmt) + { + m_AmtSourceDr = sourceAmt == null ? Env.ZERO : sourceAmt; + m_AmtSourceCr = Env.ZERO; + } // setAmounts + + /** + * Set Amounts + * @param amtSourceDr source amount dr + * @param amtSourceCr source amount cr + */ + public void setAmount (BigDecimal amtSourceDr, BigDecimal amtSourceCr) + { + m_AmtSourceDr = amtSourceDr == null ? Env.ZERO : amtSourceDr; + m_AmtSourceCr = amtSourceCr == null ? Env.ZERO : amtSourceCr; + } // setAmounts + + /** + * Set Converted Amounts + * @param C_AcctSchema_ID acct schema + * @param amtAcctDr acct amount dr + * @param amtAcctCr acct amount cr + */ + public void setConvertedAmt (int C_AcctSchema_ID, BigDecimal amtAcctDr, BigDecimal amtAcctCr) + { + m_C_AcctSchema_ID = C_AcctSchema_ID; + m_AmtAcctDr = amtAcctDr; + m_AmtAcctCr = amtAcctCr; + } // setConvertedAmt + + /** + * Line Net Amount or Dr-Cr + * @return balance + */ + public BigDecimal getAmtSource() + { + return m_AmtSourceDr.subtract(m_AmtSourceCr); + } // getAmount + + /** + * Get (Journal) Line Source Dr Amount + * @return DR source amount + */ + public BigDecimal getAmtSourceDr() + { + return m_AmtSourceDr; + } // getAmtSourceDr + + /** + * Get (Journal) Line Source Cr Amount + * @return CR source amount + */ + public BigDecimal getAmtSourceCr() + { + return m_AmtSourceCr; + } // getAmtSourceCr + + /** + * Line Journal Accounted Dr Amount + * @return DR accounted amount + */ + public BigDecimal getAmtAcctDr() + { + return m_AmtAcctDr; + } // getAmtAcctDr + + /** + * Line Journal Accounted Cr Amount + * @return CR accounted amount + */ + public BigDecimal getAmtAcctCr() + { + return m_AmtAcctCr; + } // getAmtAccrCr + + /** + * Charge Amount + * @return charge amount + */ + public BigDecimal getChargeAmt() + { + int index = p_po.get_ColumnIndex("ChargeAmt"); + if (index != -1) + { + BigDecimal bd = (BigDecimal)p_po.get_Value(index); + if (bd != null) + return bd; + } + return Env.ZERO; + } // getChargeAmt + + /** + * Set Product Amounts + * @param LineNetAmt Line Net Amt + * @param PriceList Price List + * @param Qty Qty for discount calc + */ + public void setAmount (BigDecimal LineNetAmt, BigDecimal PriceList, BigDecimal Qty) + { + m_LineNetAmt = LineNetAmt == null ? Env.ZERO : LineNetAmt; + + if (PriceList != null && Qty != null) + m_ListAmt = PriceList.multiply(Qty); if (m_ListAmt.compareTo(Env.ZERO) == 0) - m_ListAmt = m_LineNetAmt; - m_DiscountAmt = m_ListAmt.subtract(m_LineNetAmt); - // - setAmount (m_ListAmt, m_DiscountAmt); - // Log.trace(this,Log.l6_Database, "DocLine_Invoice.setAmount", - // "LineNet=" + m_LineNetAmt + ", List=" + m_ListAmt + ", Discount=" + m_DiscountAmt - // + " => Amount=" + getAmount()); - } // setAmounts - - /** - * Line Discount - * @return discount amount - */ - public BigDecimal getDiscount() - { - return m_DiscountAmt; - } // getDiscount - - /** - * Line List Amount - * @return list amount - */ - public BigDecimal getListAmount() - { - return m_ListAmt; - } // getListAmount - - /** - * Set Line Net Amt Difference - * @param diff difference (to be subtracted) - */ - public void setLineNetAmtDifference (BigDecimal diff) - { - String msg = "Diff=" + diff - + " - LineNetAmt=" + m_LineNetAmt; - m_LineNetAmt = m_LineNetAmt.subtract(diff); - m_DiscountAmt = m_ListAmt.subtract(m_LineNetAmt); - setAmount (m_ListAmt, m_DiscountAmt); - msg += " -> " + m_LineNetAmt; - log.fine(msg); - } // setLineNetAmtDifference - - /************************************************************************** - * Set Accounting Date - * @param dateAcct acct date - */ - public void setDateAcct (Timestamp dateAcct) - { - m_DateAcct = dateAcct; - } // setDateAcct - - /** - * Get Accounting Date - * @return accounting date - */ - public Timestamp getDateAcct () - { - if (m_DateAcct != null) - return m_DateAcct; - int index = p_po.get_ColumnIndex("DateAcct"); - if (index != -1) - { - m_DateAcct = (Timestamp)p_po.get_Value(index); - if (m_DateAcct != null) - return m_DateAcct; - } - m_DateAcct = m_doc.getDateAcct(); - return m_DateAcct; - } // getDateAcct - - /** - * Get FX Conversion Date - * - * The foreign exchange rate conversion date may be different from the accounting posting date in some cases (e.g. bank statement) - * - * @return FX conversion date - */ - public Timestamp getDateConv () - { - Timestamp dateConv = null; - int index = p_po.get_ColumnIndex("DateAcct"); - if (index != -1) - { - dateConv = (Timestamp)p_po.get_Value(index); - } - - - if (dateConv == null) - dateConv = getDateAcct(); - - return dateConv; - } // getDateAcct - - /** - * Set Document Date - * @param dateDoc doc date - */ - public void setDateDoc (Timestamp dateDoc) - { - m_DateDoc = dateDoc; - } // setDateDoc - - /** - * Get Document Date - * @return document date - */ - public Timestamp getDateDoc () - { - if (m_DateDoc != null) - return m_DateDoc; - int index = p_po.get_ColumnIndex("DateDoc"); - if (index != -1) - { - m_DateDoc = (Timestamp)p_po.get_Value(index); - if (m_DateDoc != null) - return m_DateDoc; - } - m_DateDoc = m_doc.getDateDoc(); - return m_DateDoc; - } // getDateDoc - - - /************************************************************************** - * Set GL Journal Account - * @param acct account - */ - public void setAccount (MAccount acct) - { - m_account = acct; - } // setAccount - - /** - * Get GL Journal Account - * @return account - */ - public MAccount getAccount() - { - return m_account; - } // getAccount - - /** - * Line Account from Product (or Charge). - * - * @param AcctType see ProductCost.ACCTTYPE_* (0..3) - * @param as Accounting schema - * @return Requested Product Account - */ - public MAccount getAccount (int AcctType, MAcctSchema as) - { - // Charge Account - if (getM_Product_ID() == 0 && getC_Charge_ID() != 0) - { - BigDecimal amt = new BigDecimal (-1); // Revenue (-) - if (!m_doc.isSOTrx()) - amt = new BigDecimal (+1); // Expense (+) - MAccount acct = getChargeAccount(as, amt); - if (acct != null) - return acct; - } - // Product Account - return getProductCost().getAccount (AcctType, as); - } // getAccount - - /** - * Get Charge - * @return C_Charge_ID - */ - protected int getC_Charge_ID() - { - int index = p_po.get_ColumnIndex("C_Charge_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getC_Charge_ID - - /** - * Get Charge Account - * @param as account schema - * @param amount amount for expense(+)/revenue(-) - * @return Charge Account or null - */ - public MAccount getChargeAccount (MAcctSchema as, BigDecimal amount) - { - int C_Charge_ID = getC_Charge_ID(); - if (C_Charge_ID == 0) - return null; - return MCharge.getAccount(C_Charge_ID, as); - } // getChargeAccount - - /** - * Get Period - * @return C_Period_ID - */ - protected int getC_Period_ID() - { - if (m_C_Period_ID == -1) - { - int index = p_po.get_ColumnIndex("C_Period_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - m_C_Period_ID = ii.intValue(); - } - if (m_C_Period_ID == -1) - m_C_Period_ID = 0; - } - return m_C_Period_ID; - } // getC_Period_ID - - /** - * Set C_Period_ID - * @param C_Period_ID id - */ - protected void setC_Period_ID (int C_Period_ID) - { - m_C_Period_ID = C_Period_ID; - } // setC_Period_ID - - /************************************************************************** - * Get (Journal) AcctSchema - * @return C_AcctSchema_ID - */ - public int getC_AcctSchema_ID() - { - return m_C_AcctSchema_ID; - } // getC_AcctSchema_ID - - /** - * Get Line ID - * @return id - */ - public int get_ID() - { - return p_po.get_ID(); - } // get_ID - - /** - * Get AD_Org_ID - * @return org - */ - public int getAD_Org_ID() - { - return p_po.getAD_Org_ID(); - } // getAD_Org_ID - - /** - * Get Order AD_Org_ID - * @return order org if defined - */ - public int getOrder_Org_ID() - { - int C_OrderLine_ID = getC_OrderLine_ID(); - if (C_OrderLine_ID != 0) - { - String sql = "SELECT AD_Org_ID FROM C_OrderLine WHERE C_OrderLine_ID=?"; - int AD_Org_ID = DB.getSQLValue(null, sql, C_OrderLine_ID); - if (AD_Org_ID > 0) - return AD_Org_ID; - } - return getAD_Org_ID(); - } // getOrder_Org_ID - - /** - * Product - * @return M_Product_ID - */ - public int getM_Product_ID() - { - int index = p_po.get_ColumnIndex("M_Product_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getM_Product_ID - - /** - * Is this an Item Product (vs. not a Service, a charge) - * @return true if product - */ - public boolean isItem() - { - if (m_isItem != null) - return m_isItem.booleanValue(); - - m_isItem = Boolean.FALSE; - if (getM_Product_ID() != 0) - { - MProduct product = MProduct.get(Env.getCtx(), getM_Product_ID()); - if (product.get_ID() == getM_Product_ID() && product.isItem()) - m_isItem = Boolean.TRUE; - } - return m_isItem.booleanValue(); - } // isItem - - /** - * ASI - * @return M_AttributeSetInstance_ID - */ - public int getM_AttributeSetInstance_ID() - { - int index = p_po.get_ColumnIndex("M_AttributeSetInstance_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getM_AttributeSetInstance_ID - - /** - * Get Warehouse Locator (from) - * @return M_Locator_ID - */ - public int getM_Locator_ID() - { - int index = p_po.get_ColumnIndex("M_Locator_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getM_Locator_ID - - /** - * Get Warehouse Locator To - * @return M_Locator_ID - */ - public int getM_LocatorTo_ID() - { - int index = p_po.get_ColumnIndex("M_LocatorTo_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getM_LocatorTo_ID - - /** - * Set Production BOM flag - * @param productionBOM flag - */ - public void setProductionBOM(boolean productionBOM) - { - m_productionBOM = productionBOM; - } // setProductionBOM - - /** - * Is this the BOM to be produced - * @return true if BOM - */ - public boolean isProductionBOM() - { - return m_productionBOM; - } // isProductionBOM - - /** - * Get Production Header - * @return M_Production_ID - */ - public int getM_Production_ID() - { - int index = p_po.get_ColumnIndex("M_Production_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getM_Production_ID - - /** - * Get Order Line Reference - * @return C_OrderLine_ID - */ - public int getC_OrderLine_ID() - { - int index = p_po.get_ColumnIndex("C_OrderLine_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getC_OrderLine_ID - - /** - * Get C_LocFrom_ID - * @return loc from - */ - public int getC_LocFrom_ID() - { - return m_C_LocFrom_ID; - } // getC_LocFrom_ID - - /** - * Set C_LocFrom_ID - * @param C_LocFrom_ID loc from - */ - public void setC_LocFrom_ID(int C_LocFrom_ID) - { - m_C_LocFrom_ID = C_LocFrom_ID; - } // setC_LocFrom_ID - - /** - * Get PP_Cost_Collector_ID - * @return Cost Collector ID - */ - public int getPP_Cost_Collector_ID() - { - return m_PP_Cost_Collector_ID; - } // getC_LocFrom_ID - - /** - * Get PP_Cost_Collector_ID - * @return Cost Collector ID - */ - public int setPP_Cost_Collector_ID(int PP_Cost_Collector_ID) - { - return m_PP_Cost_Collector_ID; - } // getC_LocFrom_ID - - /** - * Get C_LocTo_ID - * @return loc to - */ - public int getC_LocTo_ID() - { - return m_C_LocTo_ID; - } // getC_LocTo_ID - - /** - * Set C_LocTo_ID - * @param C_LocTo_ID loc to - */ - public void setC_LocTo_ID(int C_LocTo_ID) - { - m_C_LocTo_ID = C_LocTo_ID; - } // setC_LocTo_ID - - /** - * Get Product Cost Info - * @return product cost - */ - public ProductCost getProductCost() - { - if (m_productCost == null) - m_productCost = new ProductCost (Env.getCtx(), - getM_Product_ID(), getM_AttributeSetInstance_ID(), p_po.get_TrxName()); - return m_productCost; - } // getProductCost - - // MZ Goodwill - /** - * Get Total Product Costs from Cost Detail or from Current Cost - * @param as accounting schema - * @param AD_Org_ID trx org - * @param zeroCostsOK zero/no costs are OK - * @param whereClause null are OK - * @return costs - */ - public BigDecimal getProductCosts (MAcctSchema as, int AD_Org_ID, boolean zeroCostsOK, String whereClause) - { - if (whereClause != null && !as.getCostingMethod().equals(MAcctSchema.COSTINGMETHOD_StandardCosting)) - { - MCostDetail cd = MCostDetail.get (Env.getCtx(), whereClause, - get_ID(), getM_AttributeSetInstance_ID(), as.getC_AcctSchema_ID(), p_po.get_TrxName()); - if (cd != null) - return cd.getAmt(); - } - return getProductCosts(as, AD_Org_ID, zeroCostsOK); - } // getProductCosts - // end MZ - - /** - * Get Total Product Costs - * @param as accounting schema - * @param AD_Org_ID trx org - * @param zeroCostsOK zero/no costs are OK - * @return costs - */ - public BigDecimal getProductCosts (MAcctSchema as, int AD_Org_ID, boolean zeroCostsOK) - { - ProductCost pc = getProductCost(); - int C_OrderLine_ID = getC_OrderLine_ID(); - String costingMethod = null; - BigDecimal costs = pc.getProductCosts(as, AD_Org_ID, costingMethod, - C_OrderLine_ID, zeroCostsOK); - if (costs != null) - return costs; - return Env.ZERO; - } // getProductCosts - - /** - * Get Product - * @return product or null if no product - */ - public MProduct getProduct() - { - if (m_productCost == null) - m_productCost = new ProductCost (Env.getCtx(), - getM_Product_ID(), getM_AttributeSetInstance_ID(), p_po.get_TrxName()); - if (m_productCost != null) - return m_productCost.getProduct(); - return null; - } // getProduct - - /** - * Get Revenue Recognition - * @return C_RevenueRecognition_ID or 0 - */ - public int getC_RevenueRecognition_ID() - { - MProduct product = getProduct(); - if (product != null) - return product.getC_RevenueRecognition_ID(); - return 0; - } // getC_RevenueRecognition_ID - - /** - * Quantity UOM - * @return Transaction or Storage M_UOM_ID - */ - public int getC_UOM_ID() - { - // Trx UOM - int index = p_po.get_ColumnIndex("C_UOM_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - // Storage UOM - MProduct product = getProduct(); - if (product != null) - return product.getC_UOM_ID(); - // - return 0; - } // getC_UOM - - /** - * Quantity - * @param qty transaction Qty - * @param isSOTrx SL order trx (i.e. negative qty) - */ - public void setQty (BigDecimal qty, boolean isSOTrx) - { - if (qty == null) - m_qty = Env.ZERO; - else if (isSOTrx) - m_qty = qty.negate(); - else - m_qty = qty; - getProductCost().setQty (qty); - } // setQty - - /** - * Quantity - * @return transaction Qty - */ - public BigDecimal getQty() - { - return m_qty; - } // getQty - - - - /** - * Description - * @return doc line description - */ - public String getDescription() - { - int index = p_po.get_ColumnIndex("Description"); - if (index != -1) - return (String)p_po.get_Value(index); - return null; - } // getDescription - - /** - * Line Tax - * @return C_Tax_ID - */ - public int getC_Tax_ID() - { - int index = p_po.get_ColumnIndex("C_Tax_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getC_Tax_ID - - /** - * Get Line Number - * @return line no - */ - public int getLine() - { - int index = p_po.get_ColumnIndex("Line"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getLine - - /** - * Get BPartner - * @return C_BPartner_ID - */ - public int getC_BPartner_ID() - { - if (m_C_BPartner_ID == -1) - { - int index = p_po.get_ColumnIndex("C_BPartner_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - m_C_BPartner_ID = ii.intValue(); - } - if (m_C_BPartner_ID <= 0) - m_C_BPartner_ID = m_doc.getC_BPartner_ID(); - } - return m_C_BPartner_ID; - } // getC_BPartner_ID - - /** - * Set C_BPartner_ID - * @param C_BPartner_ID id - */ - protected void setC_BPartner_ID (int C_BPartner_ID) - { - m_C_BPartner_ID = C_BPartner_ID; - } // setC_BPartner_ID - - - /** - * Get C_BPartner_Location_ID - * @return BPartner Location - */ - public int getC_BPartner_Location_ID() - { - int index = p_po.get_ColumnIndex("C_BPartner_Location_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return m_doc.getC_BPartner_Location_ID(); - } // getC_BPartner_Location_ID - - /** - * Get TrxOrg - * @return AD_OrgTrx_ID - */ - public int getAD_OrgTrx_ID() - { - int index = p_po.get_ColumnIndex("AD_OrgTrx_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getAD_OrgTrx_ID - - /** - * Get SalesRegion. - * - get Sales Region from BPartner - * @return C_SalesRegion_ID - */ - public int getC_SalesRegion_ID() - { - if (m_C_SalesRegion_ID == -1) // never tried - { - if (getC_BPartner_Location_ID() != 0) - // && m_acctSchema.isAcctSchemaElement(MAcctSchemaElement.ELEMENTTYPE_SalesRegion)) - { - String sql = "SELECT COALESCE(C_SalesRegion_ID,0) FROM C_BPartner_Location WHERE C_BPartner_Location_ID=?"; - m_C_SalesRegion_ID = DB.getSQLValue (null, - sql, getC_BPartner_Location_ID()); - if (log.isLoggable(Level.FINE)) log.fine("C_SalesRegion_ID=" + m_C_SalesRegion_ID + " (from BPL)" ); - if (m_C_SalesRegion_ID == 0) - m_C_SalesRegion_ID = -2; // don't try again - } - else - m_C_SalesRegion_ID = -2; // don't try again - } - if (m_C_SalesRegion_ID < 0) // invalid - return 0; - return m_C_SalesRegion_ID; - } // getC_SalesRegion_ID - - /** - * Get Project - * @return C_Project_ID - */ - public int getC_Project_ID() - { - int index = p_po.get_ColumnIndex("C_Project_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getC_Project_ID - - /** - * Get Project Phase - * @return C_ProjectPhase_ID - */ - public int getC_ProjectPhase_ID() - { - int index = p_po.get_ColumnIndex("C_ProjectPhase_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getC_ProjectPhase_ID - - /** - * Get Project Task - * @return C_ProjectTask_ID - */ - public int getC_ProjectTask_ID() - { - int index = p_po.get_ColumnIndex("C_ProjectTask_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getC_ProjectTask_ID - - /** - * Get Campaign - * @return C_Campaign_ID - */ - public int getC_Campaign_ID() - { - int index = p_po.get_ColumnIndex("C_Campaign_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getC_Campaign_ID - - /** - * Get Activity - * @return C_Activity_ID - */ - public int getC_Activity_ID() - { - int index = p_po.get_ColumnIndex("C_Activity_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getC_Activity_ID - - /** - * Get User 1 - * @return user defined 1 - */ - public int getUser1_ID() - { - int index = p_po.get_ColumnIndex("User1_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getUser1_ID - - /** - * Get User 2 - * @return user defined 2 - */ - public int getUser2_ID() - { - int index = p_po.get_ColumnIndex("User2_ID"); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getUser2_ID - - /** - * Get User Defined Column - * @param ColumnName column name - * @return user defined column value - */ - public int getValue(String ColumnName) - { - int index = p_po.get_ColumnIndex(ColumnName); - if (index != -1) - { - Integer ii = (Integer)p_po.get_Value(index); - if (ii != null) - return ii.intValue(); - } - return 0; - } // getValue - - //AZ Goodwill - private int m_ReversalLine_ID = 0; - /** - * Set ReversalLine_ID - * store original (voided/reversed) document line - * @param ReversalLine_ID - */ - public void setReversalLine_ID (int ReversalLine_ID) - { - m_ReversalLine_ID = ReversalLine_ID; - } // setReversalLine_ID - - /** - * Get ReversalLine_ID - * get original (voided/reversed) document line - * @return ReversalLine_ID - */ - public int getReversalLine_ID() - { - return m_ReversalLine_ID; - } // getReversalLine_ID - //end AZ Goodwill - - public PO getPO() - { - return p_po; - } - - /** - * String representation - * @return String - */ - public String toString() - { - StringBuilder sb = new StringBuilder("DocLine=["); - sb.append(p_po.get_ID()); - if (getDescription() != null) - sb.append(",").append(getDescription()); - if (getM_Product_ID() != 0) - sb.append(",M_Product_ID=").append(getM_Product_ID()); - sb.append(",Qty=").append(m_qty) - .append(",Amt=").append(getAmtSource()) - .append("]"); - return sb.toString(); - } // toString - -} // DocumentLine + m_ListAmt = m_LineNetAmt; + m_DiscountAmt = m_ListAmt.subtract(m_LineNetAmt); + // + setAmount (m_ListAmt, m_DiscountAmt); + // Log.trace(this,Log.l6_Database, "DocLine_Invoice.setAmount", + // "LineNet=" + m_LineNetAmt + ", List=" + m_ListAmt + ", Discount=" + m_DiscountAmt + // + " => Amount=" + getAmount()); + } // setAmounts + + /** + * Line Discount + * @return discount amount + */ + public BigDecimal getDiscount() + { + return m_DiscountAmt; + } // getDiscount + + /** + * Line List Amount + * @return list amount + */ + public BigDecimal getListAmount() + { + return m_ListAmt; + } // getListAmount + + /** + * Set Line Net Amt Difference + * @param diff difference (to be subtracted) + */ + public void setLineNetAmtDifference (BigDecimal diff) + { + String msg = "Diff=" + diff + + " - LineNetAmt=" + m_LineNetAmt; + m_LineNetAmt = m_LineNetAmt.subtract(diff); + m_DiscountAmt = m_ListAmt.subtract(m_LineNetAmt); + setAmount (m_ListAmt, m_DiscountAmt); + msg += " -> " + m_LineNetAmt; + log.fine(msg); + } // setLineNetAmtDifference + + /************************************************************************** + * Set Accounting Date + * @param dateAcct acct date + */ + public void setDateAcct (Timestamp dateAcct) + { + m_DateAcct = dateAcct; + } // setDateAcct + + /** + * Get Accounting Date + * @return accounting date + */ + public Timestamp getDateAcct () + { + if (m_DateAcct != null) + return m_DateAcct; + int index = p_po.get_ColumnIndex("DateAcct"); + if (index != -1) + { + m_DateAcct = (Timestamp)p_po.get_Value(index); + if (m_DateAcct != null) + return m_DateAcct; + } + m_DateAcct = m_doc.getDateAcct(); + return m_DateAcct; + } // getDateAcct + + /** + * Get FX Conversion Date + * + * The foreign exchange rate conversion date may be different from the accounting posting date in some cases (e.g. bank statement) + * + * @return FX conversion date + */ + public Timestamp getDateConv () + { + Timestamp dateConv = null; + int index = p_po.get_ColumnIndex("DateAcct"); + if (index != -1) + { + dateConv = (Timestamp)p_po.get_Value(index); + } + + + if (dateConv == null) + dateConv = getDateAcct(); + + return dateConv; + } // getDateAcct + + /** + * Set Document Date + * @param dateDoc doc date + */ + public void setDateDoc (Timestamp dateDoc) + { + m_DateDoc = dateDoc; + } // setDateDoc + + /** + * Get Document Date + * @return document date + */ + public Timestamp getDateDoc () + { + if (m_DateDoc != null) + return m_DateDoc; + int index = p_po.get_ColumnIndex("DateDoc"); + if (index != -1) + { + m_DateDoc = (Timestamp)p_po.get_Value(index); + if (m_DateDoc != null) + return m_DateDoc; + } + m_DateDoc = m_doc.getDateDoc(); + return m_DateDoc; + } // getDateDoc + + + /************************************************************************** + * Set GL Journal Account + * @param acct account + */ + public void setAccount (MAccount acct) + { + m_account = acct; + } // setAccount + + /** + * Get GL Journal Account + * @return account + */ + public MAccount getAccount() + { + return m_account; + } // getAccount + + /** + * Line Account from Product (or Charge). + * + * @param AcctType see ProductCost.ACCTTYPE_* (0..3) + * @param as Accounting schema + * @return Requested Product Account + */ + public MAccount getAccount (int AcctType, MAcctSchema as) + { + // Charge Account + if (getM_Product_ID() == 0 && getC_Charge_ID() != 0) + { + BigDecimal amt = new BigDecimal (-1); // Revenue (-) + if (!m_doc.isSOTrx()) + amt = new BigDecimal (+1); // Expense (+) + MAccount acct = getChargeAccount(as, amt); + if (acct != null) + return acct; + } + // Product Account + return getProductCost().getAccount (AcctType, as); + } // getAccount + + /** + * Get Charge + * @return C_Charge_ID + */ + protected int getC_Charge_ID() + { + int index = p_po.get_ColumnIndex("C_Charge_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getC_Charge_ID + + /** + * Get Charge Account + * @param as account schema + * @param amount amount for expense(+)/revenue(-) + * @return Charge Account or null + */ + public MAccount getChargeAccount (MAcctSchema as, BigDecimal amount) + { + int C_Charge_ID = getC_Charge_ID(); + if (C_Charge_ID == 0) + return null; + return MCharge.getAccount(C_Charge_ID, as); + } // getChargeAccount + + /** + * Get Period + * @return C_Period_ID + */ + protected int getC_Period_ID() + { + if (m_C_Period_ID == -1) + { + int index = p_po.get_ColumnIndex("C_Period_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + m_C_Period_ID = ii.intValue(); + } + if (m_C_Period_ID == -1) + m_C_Period_ID = 0; + } + return m_C_Period_ID; + } // getC_Period_ID + + /** + * Set C_Period_ID + * @param C_Period_ID id + */ + protected void setC_Period_ID (int C_Period_ID) + { + m_C_Period_ID = C_Period_ID; + } // setC_Period_ID + + /************************************************************************** + * Get (Journal) AcctSchema + * @return C_AcctSchema_ID + */ + public int getC_AcctSchema_ID() + { + return m_C_AcctSchema_ID; + } // getC_AcctSchema_ID + + /** + * Get Line ID + * @return id + */ + public int get_ID() + { + return p_po.get_ID(); + } // get_ID + + /** + * Get AD_Org_ID + * @return org + */ + public int getAD_Org_ID() + { + return p_po.getAD_Org_ID(); + } // getAD_Org_ID + + /** + * Get Order AD_Org_ID + * @return order org if defined + */ + public int getOrder_Org_ID() + { + int C_OrderLine_ID = getC_OrderLine_ID(); + if (C_OrderLine_ID != 0) + { + String sql = "SELECT AD_Org_ID FROM C_OrderLine WHERE C_OrderLine_ID=?"; + int AD_Org_ID = DB.getSQLValue(null, sql, C_OrderLine_ID); + if (AD_Org_ID > 0) + return AD_Org_ID; + } + return getAD_Org_ID(); + } // getOrder_Org_ID + + /** + * Product + * @return M_Product_ID + */ + public int getM_Product_ID() + { + int index = p_po.get_ColumnIndex("M_Product_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getM_Product_ID + + /** + * Is this an Item Product (vs. not a Service, a charge) + * @return true if product + */ + public boolean isItem() + { + if (m_isItem != null) + return m_isItem.booleanValue(); + + m_isItem = Boolean.FALSE; + if (getM_Product_ID() != 0) + { + MProduct product = MProduct.get(Env.getCtx(), getM_Product_ID()); + if (product.get_ID() == getM_Product_ID() && product.isItem()) + m_isItem = Boolean.TRUE; + } + return m_isItem.booleanValue(); + } // isItem + + /** + * ASI + * @return M_AttributeSetInstance_ID + */ + public int getM_AttributeSetInstance_ID() + { + int index = p_po.get_ColumnIndex("M_AttributeSetInstance_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getM_AttributeSetInstance_ID + + /** + * Get Warehouse Locator (from) + * @return M_Locator_ID + */ + public int getM_Locator_ID() + { + int index = p_po.get_ColumnIndex("M_Locator_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getM_Locator_ID + + /** + * Get Warehouse Locator To + * @return M_Locator_ID + */ + public int getM_LocatorTo_ID() + { + int index = p_po.get_ColumnIndex("M_LocatorTo_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getM_LocatorTo_ID + + /** + * Set Production BOM flag + * @param productionBOM flag + */ + public void setProductionBOM(boolean productionBOM) + { + m_productionBOM = productionBOM; + } // setProductionBOM + + /** + * Is this the BOM to be produced + * @return true if BOM + */ + public boolean isProductionBOM() + { + return m_productionBOM; + } // isProductionBOM + + /** + * Get Production Header + * @return M_Production_ID + */ + public int getM_Production_ID() + { + int index = p_po.get_ColumnIndex("M_Production_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getM_Production_ID + + /** + * Get Order Line Reference + * @return C_OrderLine_ID + */ + public int getC_OrderLine_ID() + { + int index = p_po.get_ColumnIndex("C_OrderLine_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getC_OrderLine_ID + + /** + * Get C_LocFrom_ID + * @return loc from + */ + public int getC_LocFrom_ID() + { + return m_C_LocFrom_ID; + } // getC_LocFrom_ID + + /** + * Set C_LocFrom_ID + * @param C_LocFrom_ID loc from + */ + public void setC_LocFrom_ID(int C_LocFrom_ID) + { + m_C_LocFrom_ID = C_LocFrom_ID; + } // setC_LocFrom_ID + + /** + * Get PP_Cost_Collector_ID + * @return Cost Collector ID + */ + public int getPP_Cost_Collector_ID() + { + return m_PP_Cost_Collector_ID; + } // getC_LocFrom_ID + + /** + * Get PP_Cost_Collector_ID + * @return Cost Collector ID + */ + public int setPP_Cost_Collector_ID(int PP_Cost_Collector_ID) + { + return m_PP_Cost_Collector_ID; + } // getC_LocFrom_ID + + /** + * Get C_LocTo_ID + * @return loc to + */ + public int getC_LocTo_ID() + { + return m_C_LocTo_ID; + } // getC_LocTo_ID + + /** + * Set C_LocTo_ID + * @param C_LocTo_ID loc to + */ + public void setC_LocTo_ID(int C_LocTo_ID) + { + m_C_LocTo_ID = C_LocTo_ID; + } // setC_LocTo_ID + + /** + * Get Product Cost Info + * @return product cost + */ + public ProductCost getProductCost() + { + if (m_productCost == null) + m_productCost = new ProductCost (Env.getCtx(), + getM_Product_ID(), getM_AttributeSetInstance_ID(), p_po.get_TrxName()); + return m_productCost; + } // getProductCost + + // MZ Goodwill + /** + * Get Total Product Costs from Cost Detail or from Current Cost + * @param as accounting schema + * @param AD_Org_ID trx org + * @param zeroCostsOK zero/no costs are OK + * @param whereClause null are OK + * @return costs + */ + public BigDecimal getProductCosts (MAcctSchema as, int AD_Org_ID, boolean zeroCostsOK, String whereClause) + { + if (whereClause != null && !as.getCostingMethod().equals(MAcctSchema.COSTINGMETHOD_StandardCosting)) + { + MCostDetail cd = MCostDetail.get (Env.getCtx(), whereClause, + get_ID(), getM_AttributeSetInstance_ID(), as.getC_AcctSchema_ID(), p_po.get_TrxName()); + if (cd != null) + return cd.getAmt(); + } + return getProductCosts(as, AD_Org_ID, zeroCostsOK); + } // getProductCosts + // end MZ + + /** + * Get Total Product Costs + * @param as accounting schema + * @param AD_Org_ID trx org + * @param zeroCostsOK zero/no costs are OK + * @return costs + */ + public BigDecimal getProductCosts (MAcctSchema as, int AD_Org_ID, boolean zeroCostsOK) + { + ProductCost pc = getProductCost(); + int C_OrderLine_ID = getC_OrderLine_ID(); + String costingMethod = null; + BigDecimal costs = pc.getProductCosts(as, AD_Org_ID, costingMethod, + C_OrderLine_ID, zeroCostsOK); + if (costs != null) + return costs; + return Env.ZERO; + } // getProductCosts + + /** + * Get Product + * @return product or null if no product + */ + public MProduct getProduct() + { + if (m_productCost == null) + m_productCost = new ProductCost (Env.getCtx(), + getM_Product_ID(), getM_AttributeSetInstance_ID(), p_po.get_TrxName()); + if (m_productCost != null) + return m_productCost.getProduct(); + return null; + } // getProduct + + /** + * Get Revenue Recognition + * @return C_RevenueRecognition_ID or 0 + */ + public int getC_RevenueRecognition_ID() + { + MProduct product = getProduct(); + if (product != null) + return product.getC_RevenueRecognition_ID(); + return 0; + } // getC_RevenueRecognition_ID + + /** + * Quantity UOM + * @return Transaction or Storage M_UOM_ID + */ + public int getC_UOM_ID() + { + // Trx UOM + int index = p_po.get_ColumnIndex("C_UOM_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + // Storage UOM + MProduct product = getProduct(); + if (product != null) + return product.getC_UOM_ID(); + // + return 0; + } // getC_UOM + + /** + * Quantity + * @param qty transaction Qty + * @param isSOTrx SL order trx (i.e. negative qty) + */ + public void setQty (BigDecimal qty, boolean isSOTrx) + { + if (qty == null) + m_qty = Env.ZERO; + else if (isSOTrx) + m_qty = qty.negate(); + else + m_qty = qty; + getProductCost().setQty (qty); + } // setQty + + /** + * Quantity + * @return transaction Qty + */ + public BigDecimal getQty() + { + return m_qty; + } // getQty + + + + /** + * Description + * @return doc line description + */ + public String getDescription() + { + int index = p_po.get_ColumnIndex("Description"); + if (index != -1) + return (String)p_po.get_Value(index); + return null; + } // getDescription + + /** + * Line Tax + * @return C_Tax_ID + */ + public int getC_Tax_ID() + { + int index = p_po.get_ColumnIndex("C_Tax_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getC_Tax_ID + + /** + * Get Line Number + * @return line no + */ + public int getLine() + { + int index = p_po.get_ColumnIndex("Line"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getLine + + /** + * Get BPartner + * @return C_BPartner_ID + */ + public int getC_BPartner_ID() + { + if (m_C_BPartner_ID == -1) + { + int index = p_po.get_ColumnIndex("C_BPartner_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + m_C_BPartner_ID = ii.intValue(); + } + if (m_C_BPartner_ID <= 0) + m_C_BPartner_ID = m_doc.getC_BPartner_ID(); + } + return m_C_BPartner_ID; + } // getC_BPartner_ID + + /** + * Set C_BPartner_ID + * @param C_BPartner_ID id + */ + protected void setC_BPartner_ID (int C_BPartner_ID) + { + m_C_BPartner_ID = C_BPartner_ID; + } // setC_BPartner_ID + + + /** + * Get C_BPartner_Location_ID + * @return BPartner Location + */ + public int getC_BPartner_Location_ID() + { + int index = p_po.get_ColumnIndex("C_BPartner_Location_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return m_doc.getC_BPartner_Location_ID(); + } // getC_BPartner_Location_ID + + /** + * Get TrxOrg + * @return AD_OrgTrx_ID + */ + public int getAD_OrgTrx_ID() + { + int index = p_po.get_ColumnIndex("AD_OrgTrx_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getAD_OrgTrx_ID + + /** + * Get SalesRegion. + * - get Sales Region from BPartner + * @return C_SalesRegion_ID + */ + public int getC_SalesRegion_ID() + { + if (m_C_SalesRegion_ID == -1) // never tried + { + if (getC_BPartner_Location_ID() != 0) + // && m_acctSchema.isAcctSchemaElement(MAcctSchemaElement.ELEMENTTYPE_SalesRegion)) + { + String sql = "SELECT COALESCE(C_SalesRegion_ID,0) FROM C_BPartner_Location WHERE C_BPartner_Location_ID=?"; + m_C_SalesRegion_ID = DB.getSQLValue (null, + sql, getC_BPartner_Location_ID()); + if (log.isLoggable(Level.FINE)) log.fine("C_SalesRegion_ID=" + m_C_SalesRegion_ID + " (from BPL)" ); + if (m_C_SalesRegion_ID == 0) + m_C_SalesRegion_ID = -2; // don't try again + } + else + m_C_SalesRegion_ID = -2; // don't try again + } + if (m_C_SalesRegion_ID < 0) // invalid + return 0; + return m_C_SalesRegion_ID; + } // getC_SalesRegion_ID + + /** + * Get Project + * @return C_Project_ID + */ + public int getC_Project_ID() + { + int index = p_po.get_ColumnIndex("C_Project_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getC_Project_ID + + /** + * Get Project Phase + * @return C_ProjectPhase_ID + */ + public int getC_ProjectPhase_ID() + { + int index = p_po.get_ColumnIndex("C_ProjectPhase_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getC_ProjectPhase_ID + + /** + * Get Project Task + * @return C_ProjectTask_ID + */ + public int getC_ProjectTask_ID() + { + int index = p_po.get_ColumnIndex("C_ProjectTask_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getC_ProjectTask_ID + + /** + * Get Campaign + * @return C_Campaign_ID + */ + public int getC_Campaign_ID() + { + int index = p_po.get_ColumnIndex("C_Campaign_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getC_Campaign_ID + + /** + * Get Activity + * @return C_Activity_ID + */ + public int getC_Activity_ID() + { + int index = p_po.get_ColumnIndex("C_Activity_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getC_Activity_ID + + /** + * Get User 1 + * @return user defined 1 + */ + public int getUser1_ID() + { + int index = p_po.get_ColumnIndex("User1_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getUser1_ID + + /** + * Get User 2 + * @return user defined 2 + */ + public int getUser2_ID() + { + int index = p_po.get_ColumnIndex("User2_ID"); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getUser2_ID + + /** + * Get User Defined Column + * @param ColumnName column name + * @return user defined column value + */ + public int getValue(String ColumnName) + { + int index = p_po.get_ColumnIndex(ColumnName); + if (index != -1) + { + Integer ii = (Integer)p_po.get_Value(index); + if (ii != null) + return ii.intValue(); + } + return 0; + } // getValue + + //AZ Goodwill + private int m_ReversalLine_ID = 0; + /** + * Set ReversalLine_ID + * store original (voided/reversed) document line + * @param ReversalLine_ID + */ + public void setReversalLine_ID (int ReversalLine_ID) + { + m_ReversalLine_ID = ReversalLine_ID; + } // setReversalLine_ID + + /** + * Get ReversalLine_ID + * get original (voided/reversed) document line + * @return ReversalLine_ID + */ + public int getReversalLine_ID() + { + return m_ReversalLine_ID; + } // getReversalLine_ID + //end AZ Goodwill + + public PO getPO() + { + return p_po; + } + + /** + * String representation + * @return String + */ + public String toString() + { + StringBuilder sb = new StringBuilder("DocLine=["); + sb.append(p_po.get_ID()); + if (getDescription() != null) + sb.append(",").append(getDescription()); + if (getM_Product_ID() != 0) + sb.append(",M_Product_ID=").append(getM_Product_ID()); + sb.append(",Qty=").append(m_qty) + .append(",Amt=").append(getAmtSource()) + .append("]"); + return sb.toString(); + } // toString + +} // DocumentLine diff --git a/org.adempiere.base/src/org/compiere/acct/Doc_AllocationHdr.java b/org.adempiere.base/src/org/compiere/acct/Doc_AllocationHdr.java index 8eaad8c421..f159087158 100644 --- a/org.adempiere.base/src/org/compiere/acct/Doc_AllocationHdr.java +++ b/org.adempiere.base/src/org/compiere/acct/Doc_AllocationHdr.java @@ -1,724 +1,724 @@ -/****************************************************************************** - * 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.compiere.acct; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.sql.PreparedStatement; -import java.sql.ResultSet; +/****************************************************************************** + * 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.compiere.acct; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; -import java.util.logging.Level; - -import org.compiere.model.MAccount; -import org.compiere.model.MAcctSchema; -import org.compiere.model.MAcctSchemaElement; -import org.compiere.model.MAllocationHdr; -import org.compiere.model.MAllocationLine; -import org.compiere.model.MCashLine; +import java.util.logging.Level; + +import org.compiere.model.MAccount; +import org.compiere.model.MAcctSchema; +import org.compiere.model.MAcctSchemaElement; +import org.compiere.model.MAllocationHdr; +import org.compiere.model.MAllocationLine; +import org.compiere.model.MCashLine; import org.compiere.model.MConversionRate; import org.compiere.model.MCurrency; -import org.compiere.model.MFactAcct; -import org.compiere.model.MInvoice; -import org.compiere.model.MInvoiceLine; -import org.compiere.model.MOrder; -import org.compiere.model.MPayment; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; - -/** - * Post Allocation Documents. - *
    - *  Table:              C_AllocationHdr
    - *  Document Types:     CMA
    - *  
    - * @author Jorg Janke - * @version $Id: Doc_Allocation.java,v 1.6 2006/07/30 00:53:33 jjanke Exp $ - * - * FR [ 1840016 ] Avoid usage of clearing accounts - subject to C_AcctSchema.IsPostIfClearingEqual - * Avoid posting if Receipt and both accounts Unallocated Cash and Receivable are equal - * Avoid posting if Payment and both accounts Payment Select and Liability are equal - * - * @author phib - * BF [ 2019262 ] Allocation posting currency gain/loss omits line reference - * - */ -public class Doc_AllocationHdr extends Doc -{ - /** - * Constructor - * @param as accounting schema - * @param rs record - * @param trxName trx - */ - public Doc_AllocationHdr (MAcctSchema as, ResultSet rs, String trxName) - { - super (as, MAllocationHdr.class, rs, DOCTYPE_Allocation, trxName); - } // Doc_Allocation - - /** Tolerance G&L */ - private static final BigDecimal TOLERANCE = BigDecimal.valueOf(0.02); - /** Facts */ - private ArrayList m_facts = null; - - - /** - * Load Specific Document Details - * @return error message or null - */ - protected String loadDocumentDetails () - { - MAllocationHdr alloc = (MAllocationHdr)getPO(); - setDateDoc(alloc.getDateTrx()); - // Contained Objects - p_lines = loadLines(alloc); - return null; - } // loadDocumentDetails - - /** - * Load Invoice Line - * @param alloc header - * @return DocLine Array - */ - private DocLine[] loadLines(MAllocationHdr alloc) - { - ArrayList list = new ArrayList(); - MAllocationLine[] lines = alloc.getLines(false); - for (int i = 0; i < lines.length; i++) - { - MAllocationLine line = lines[i]; - DocLine_Allocation docLine = new DocLine_Allocation(line, this); - // - if (log.isLoggable(Level.FINE)) log.fine(docLine.toString()); - list.add (docLine); - } - - // Return Array - DocLine[] dls = new DocLine[list.size()]; - list.toArray(dls); - return dls; - } // loadLines - - - /************************************************************************** - * Get Source Currency Balance - subtracts line and tax amounts from total - no rounding - * @return positive amount, if total invoice is bigger than lines - */ - public BigDecimal getBalance() - { - BigDecimal retValue = Env.ZERO; - return retValue; - } // getBalance - - /** - * Create Facts (the accounting logic) for - * CMA. - *
    -	 *  AR_Invoice_Payment
    -	 *      UnAllocatedCash DR
    -	 *      or C_Prepayment
    -	 *      DiscountExp     DR
    -	 *      WriteOff        DR
    -	 *      Receivables             CR
    -	 *  AR_Invoice_Cash
    -	 *      CashTransfer    DR
    -	 *      DiscountExp     DR
    -	 *      WriteOff        DR
    -	 *      Receivables             CR
    -	 *
    -	 *  AP_Invoice_Payment
    -	 *      Liability       DR
    -	 *      DiscountRev             CR
    -	 *      WriteOff                CR
    -	 *      PaymentSelect           CR
    -	 *      or V_Prepayment
    -	 *  AP_Invoice_Cash
    -	 *      Liability       DR
    -	 *      DiscountRev             CR
    -	 *      WriteOff                CR
    -	 *      CashTransfer            CR
    -	 *  CashBankTransfer
    -	 *      -
    -	 *  ==============================
    -	 *  Realized Gain & Loss
    -	 * 		AR/AP			DR		CR
    -	 * 		Realized G/L	DR		CR
    -	 *
    -	 *
    -	 *  
    - * Tax needs to be corrected for discount & write-off; - * Currency gain & loss is realized here. - * @param as accounting schema - * @return Fact - */ - public ArrayList createFacts (MAcctSchema as) - { - m_facts = new ArrayList(); - - // create Fact Header - Fact fact = new Fact(this, as, Fact.POST_Actual); - Fact factForRGL = new Fact(this, as, Fact.POST_Actual); // dummy fact (not posted) to calculate Realized Gain & Loss - boolean isInterOrg = isInterOrg(as); - - for (int i = 0; i < p_lines.length; i++) - { - DocLine_Allocation line = (DocLine_Allocation)p_lines[i]; - setC_BPartner_ID(line.getC_BPartner_ID()); - - // CashBankTransfer - all references null and Discount/WriteOff = 0 - if (line.getC_Payment_ID() != 0 - && line.getC_Invoice_ID() == 0 && line.getC_Order_ID() == 0 - && line.getC_CashLine_ID() == 0 && line.getC_BPartner_ID() == 0 - && Env.ZERO.compareTo(line.getDiscountAmt()) == 0 - && Env.ZERO.compareTo(line.getWriteOffAmt()) == 0) - continue; - - // Receivables/Liability Amt - BigDecimal allocationSource = line.getAmtSource() - .add(line.getDiscountAmt()) - .add(line.getWriteOffAmt()); - BigDecimal allocationSourceForRGL = allocationSource; // for realized gain & loss purposes - BigDecimal allocationAccounted = Env.ZERO; // AR/AP balance corrected - @SuppressWarnings("unused") - BigDecimal allocationAccountedForRGL = Env.ZERO; // for realized gain & loss purposes - - FactLine fl = null; - FactLine flForRGL = null; - MAccount bpAcct = null; // Liability/Receivables +import org.compiere.model.MFactAcct; +import org.compiere.model.MInvoice; +import org.compiere.model.MInvoiceLine; +import org.compiere.model.MOrder; +import org.compiere.model.MPayment; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; + +/** + * Post Allocation Documents. + *
    + *  Table:              C_AllocationHdr
    + *  Document Types:     CMA
    + *  
    + * @author Jorg Janke + * @version $Id: Doc_Allocation.java,v 1.6 2006/07/30 00:53:33 jjanke Exp $ + * + * FR [ 1840016 ] Avoid usage of clearing accounts - subject to C_AcctSchema.IsPostIfClearingEqual + * Avoid posting if Receipt and both accounts Unallocated Cash and Receivable are equal + * Avoid posting if Payment and both accounts Payment Select and Liability are equal + * + * @author phib + * BF [ 2019262 ] Allocation posting currency gain/loss omits line reference + * + */ +public class Doc_AllocationHdr extends Doc +{ + /** + * Constructor + * @param as accounting schema + * @param rs record + * @param trxName trx + */ + public Doc_AllocationHdr (MAcctSchema as, ResultSet rs, String trxName) + { + super (as, MAllocationHdr.class, rs, DOCTYPE_Allocation, trxName); + } // Doc_Allocation + + /** Tolerance G&L */ + private static final BigDecimal TOLERANCE = BigDecimal.valueOf(0.02); + /** Facts */ + private ArrayList m_facts = null; + + + /** + * Load Specific Document Details + * @return error message or null + */ + protected String loadDocumentDetails () + { + MAllocationHdr alloc = (MAllocationHdr)getPO(); + setDateDoc(alloc.getDateTrx()); + // Contained Objects + p_lines = loadLines(alloc); + return null; + } // loadDocumentDetails + + /** + * Load Invoice Line + * @param alloc header + * @return DocLine Array + */ + private DocLine[] loadLines(MAllocationHdr alloc) + { + ArrayList list = new ArrayList(); + MAllocationLine[] lines = alloc.getLines(false); + for (int i = 0; i < lines.length; i++) + { + MAllocationLine line = lines[i]; + DocLine_Allocation docLine = new DocLine_Allocation(line, this); + // + if (log.isLoggable(Level.FINE)) log.fine(docLine.toString()); + list.add (docLine); + } + + // Return Array + DocLine[] dls = new DocLine[list.size()]; + list.toArray(dls); + return dls; + } // loadLines + + + /************************************************************************** + * Get Source Currency Balance - subtracts line and tax amounts from total - no rounding + * @return positive amount, if total invoice is bigger than lines + */ + public BigDecimal getBalance() + { + BigDecimal retValue = Env.ZERO; + return retValue; + } // getBalance + + /** + * Create Facts (the accounting logic) for + * CMA. + *
    +	 *  AR_Invoice_Payment
    +	 *      UnAllocatedCash DR
    +	 *      or C_Prepayment
    +	 *      DiscountExp     DR
    +	 *      WriteOff        DR
    +	 *      Receivables             CR
    +	 *  AR_Invoice_Cash
    +	 *      CashTransfer    DR
    +	 *      DiscountExp     DR
    +	 *      WriteOff        DR
    +	 *      Receivables             CR
    +	 *
    +	 *  AP_Invoice_Payment
    +	 *      Liability       DR
    +	 *      DiscountRev             CR
    +	 *      WriteOff                CR
    +	 *      PaymentSelect           CR
    +	 *      or V_Prepayment
    +	 *  AP_Invoice_Cash
    +	 *      Liability       DR
    +	 *      DiscountRev             CR
    +	 *      WriteOff                CR
    +	 *      CashTransfer            CR
    +	 *  CashBankTransfer
    +	 *      -
    +	 *  ==============================
    +	 *  Realized Gain & Loss
    +	 * 		AR/AP			DR		CR
    +	 * 		Realized G/L	DR		CR
    +	 *
    +	 *
    +	 *  
    + * Tax needs to be corrected for discount & write-off; + * Currency gain & loss is realized here. + * @param as accounting schema + * @return Fact + */ + public ArrayList createFacts (MAcctSchema as) + { + m_facts = new ArrayList(); + + // create Fact Header + Fact fact = new Fact(this, as, Fact.POST_Actual); + Fact factForRGL = new Fact(this, as, Fact.POST_Actual); // dummy fact (not posted) to calculate Realized Gain & Loss + boolean isInterOrg = isInterOrg(as); + + for (int i = 0; i < p_lines.length; i++) + { + DocLine_Allocation line = (DocLine_Allocation)p_lines[i]; + setC_BPartner_ID(line.getC_BPartner_ID()); + + // CashBankTransfer - all references null and Discount/WriteOff = 0 + if (line.getC_Payment_ID() != 0 + && line.getC_Invoice_ID() == 0 && line.getC_Order_ID() == 0 + && line.getC_CashLine_ID() == 0 && line.getC_BPartner_ID() == 0 + && Env.ZERO.compareTo(line.getDiscountAmt()) == 0 + && Env.ZERO.compareTo(line.getWriteOffAmt()) == 0) + continue; + + // Receivables/Liability Amt + BigDecimal allocationSource = line.getAmtSource() + .add(line.getDiscountAmt()) + .add(line.getWriteOffAmt()); + BigDecimal allocationSourceForRGL = allocationSource; // for realized gain & loss purposes + BigDecimal allocationAccounted = Env.ZERO; // AR/AP balance corrected + @SuppressWarnings("unused") + BigDecimal allocationAccountedForRGL = Env.ZERO; // for realized gain & loss purposes + + FactLine fl = null; + FactLine flForRGL = null; + MAccount bpAcct = null; // Liability/Receivables MAccount payAcct = null; // Payment Selection - // - MPayment payment = null; - if (line.getC_Payment_ID() != 0) - payment = new MPayment (getCtx(), line.getC_Payment_ID(), getTrxName()); - MInvoice invoice = null; - if (line.getC_Invoice_ID() != 0) - invoice = new MInvoice (getCtx(), line.getC_Invoice_ID(), getTrxName()); - - // No Invoice - if (invoice == null) - { - // adaxa-pb: allocate to charges - // Charge Only - if (line.getC_Invoice_ID() == 0 && line.getC_Payment_ID() == 0 && line.getC_Charge_ID() != 0 ) - { - fl = fact.createLine (line, line.getChargeAccount(as, line.getAmtSource()), - getC_Currency_ID(), line.getAmtSource()); - } - // Payment Only - else if (line.getC_Invoice_ID() == 0 && line.getC_Payment_ID() != 0) - { - fl = fact.createLine (line, getPaymentAcct(as, line.getC_Payment_ID()), - getC_Currency_ID(), line.getAmtSource(), null); - if (fl != null && payment != null) - fl.setAD_Org_ID(payment.getAD_Org_ID()); - } - else - { - p_Error = "Cannot determine SO/PO"; - log.log(Level.SEVERE, p_Error); - return null; - } - } - // Sales Invoice - else if (invoice.isSOTrx()) - { - - // Avoid usage of clearing accounts - // If both accounts Unallocated Cash and Receivable are equal - // then don't post - - MAccount acct_unallocated_cash = null; - if (line.getC_Payment_ID() != 0) - acct_unallocated_cash = getPaymentAcct(as, line.getC_Payment_ID()); - else if (line.getC_CashLine_ID() != 0) - acct_unallocated_cash = getCashAcct(as, line.getC_CashLine_ID()); - MAccount acct_receivable = getAccount(Doc.ACCTTYPE_C_Receivable, as); - - if ((!as.isPostIfClearingEqual()) && acct_unallocated_cash != null && acct_unallocated_cash.equals(acct_receivable) && (!isInterOrg)) { - - // if not using clearing accounts, then don't post amtsource - // change the allocationsource to be writeoff + discount - allocationSource = line.getDiscountAmt().add(line.getWriteOffAmt()); - - - } else { - - // Normal behavior -- unchanged if using clearing accounts - - // Payment/Cash DR - if (line.getC_Payment_ID() != 0) + // + MPayment payment = null; + if (line.getC_Payment_ID() != 0) + payment = new MPayment (getCtx(), line.getC_Payment_ID(), getTrxName()); + MInvoice invoice = null; + if (line.getC_Invoice_ID() != 0) + invoice = new MInvoice (getCtx(), line.getC_Invoice_ID(), getTrxName()); + + // No Invoice + if (invoice == null) + { + // adaxa-pb: allocate to charges + // Charge Only + if (line.getC_Invoice_ID() == 0 && line.getC_Payment_ID() == 0 && line.getC_Charge_ID() != 0 ) + { + fl = fact.createLine (line, line.getChargeAccount(as, line.getAmtSource()), + getC_Currency_ID(), line.getAmtSource()); + } + // Payment Only + else if (line.getC_Invoice_ID() == 0 && line.getC_Payment_ID() != 0) + { + fl = fact.createLine (line, getPaymentAcct(as, line.getC_Payment_ID()), + getC_Currency_ID(), line.getAmtSource(), null); + if (fl != null && payment != null) + fl.setAD_Org_ID(payment.getAD_Org_ID()); + } + else + { + p_Error = "Cannot determine SO/PO"; + log.log(Level.SEVERE, p_Error); + return null; + } + } + // Sales Invoice + else if (invoice.isSOTrx()) + { + + // Avoid usage of clearing accounts + // If both accounts Unallocated Cash and Receivable are equal + // then don't post + + MAccount acct_unallocated_cash = null; + if (line.getC_Payment_ID() != 0) + acct_unallocated_cash = getPaymentAcct(as, line.getC_Payment_ID()); + else if (line.getC_CashLine_ID() != 0) + acct_unallocated_cash = getCashAcct(as, line.getC_CashLine_ID()); + MAccount acct_receivable = getAccount(Doc.ACCTTYPE_C_Receivable, as); + + if ((!as.isPostIfClearingEqual()) && acct_unallocated_cash != null && acct_unallocated_cash.equals(acct_receivable) && (!isInterOrg)) { + + // if not using clearing accounts, then don't post amtsource + // change the allocationsource to be writeoff + discount + allocationSource = line.getDiscountAmt().add(line.getWriteOffAmt()); + + + } else { + + // Normal behavior -- unchanged if using clearing accounts + + // Payment/Cash DR + if (line.getC_Payment_ID() != 0) { - payAcct = getPaymentAcct(as, line.getC_Payment_ID()); - fl = fact.createLine (line, payAcct, - getC_Currency_ID(), line.getAmtSource(), null); - if (fl != null && payment != null) - fl.setAD_Org_ID(payment.getAD_Org_ID()); - } - else if (line.getC_CashLine_ID() != 0) - { - fl = fact.createLine (line, getCashAcct(as, line.getC_CashLine_ID()), - getC_Currency_ID(), line.getAmtSource(), null); - MCashLine cashLine = new MCashLine (getCtx(), line.getC_CashLine_ID(), getTrxName()); - if (fl != null && cashLine.get_ID() != 0) - fl.setAD_Org_ID(cashLine.getAD_Org_ID()); - } - - } - // End Avoid usage of clearing accounts - - // Discount DR - if (Env.ZERO.compareTo(line.getDiscountAmt()) != 0) - { - fl = fact.createLine (line, getAccount(Doc.ACCTTYPE_DiscountExp, as), - getC_Currency_ID(), line.getDiscountAmt(), null); - if (fl != null && payment != null) - fl.setAD_Org_ID(payment.getAD_Org_ID()); - } - // Write off DR - if (Env.ZERO.compareTo(line.getWriteOffAmt()) != 0) - { - fl = fact.createLine (line, getAccount(Doc.ACCTTYPE_WriteOff, as), - getC_Currency_ID(), line.getWriteOffAmt(), null); - if (fl != null && payment != null) - fl.setAD_Org_ID(payment.getAD_Org_ID()); - } - - // AR Invoice Amount CR - if (as.isAccrual()) - { - bpAcct = getAccount(Doc.ACCTTYPE_C_Receivable, as); - fl = fact.createLine (line, bpAcct, - getC_Currency_ID(), null, allocationSource); // payment currency - if (fl != null) - allocationAccounted = fl.getAcctBalance().negate(); - if (fl != null && invoice != null) - fl.setAD_Org_ID(invoice.getAD_Org_ID()); - - // for Realized Gain & Loss - flForRGL = factForRGL.createLine (line, bpAcct, - getC_Currency_ID(), null, allocationSourceForRGL); // payment currency - if (flForRGL != null) - allocationAccountedForRGL = flForRGL.getAcctBalance().negate(); - } - else // Cash Based - { - allocationAccounted = createCashBasedAcct (as, fact, - invoice, allocationSource); - allocationAccountedForRGL = allocationAccounted; - } - } - // Purchase Invoice - else - { - // Avoid usage of clearing accounts - // If both accounts Payment Select and Liability are equal - // then don't post - - MAccount acct_payment_select = null; - if (line.getC_Payment_ID() != 0) - acct_payment_select = getPaymentAcct(as, line.getC_Payment_ID()); - else if (line.getC_CashLine_ID() != 0) - acct_payment_select = getCashAcct(as, line.getC_CashLine_ID()); - MAccount acct_liability = getAccount(Doc.ACCTTYPE_V_Liability, as); - boolean isUsingClearing = true; - - // Save original allocation source for realized gain & loss purposes - allocationSourceForRGL = allocationSourceForRGL.negate(); - - if ((!as.isPostIfClearingEqual()) && acct_payment_select != null && acct_payment_select.equals(acct_liability) && (!isInterOrg)) { - - // if not using clearing accounts, then don't post amtsource - // change the allocationsource to be writeoff + discount - allocationSource = line.getDiscountAmt().add(line.getWriteOffAmt()); - isUsingClearing = false; - - } - // End Avoid usage of clearing accounts - - allocationSource = allocationSource.negate(); // allocation is negative - // AP Invoice Amount DR - if (as.isAccrual()) - { - bpAcct = getAccount(Doc.ACCTTYPE_V_Liability, as); - fl = fact.createLine (line, bpAcct, - getC_Currency_ID(), allocationSource, null); // payment currency - if (fl != null) - allocationAccounted = fl.getAcctBalance(); - if (fl != null && invoice != null) - fl.setAD_Org_ID(invoice.getAD_Org_ID()); - - // for Realized Gain & Loss - flForRGL = factForRGL.createLine (line, bpAcct, - getC_Currency_ID(), allocationSourceForRGL, null); // payment currency - if (flForRGL != null) - allocationAccountedForRGL = flForRGL.getAcctBalance(); - } - else // Cash Based - { - allocationAccounted = createCashBasedAcct (as, fact, - invoice, allocationSource); - allocationAccountedForRGL = allocationAccounted; - } - - // Discount CR - if (Env.ZERO.compareTo(line.getDiscountAmt()) != 0) - { - fl = fact.createLine (line, getAccount(Doc.ACCTTYPE_DiscountRev, as), - getC_Currency_ID(), null, line.getDiscountAmt().negate()); - if (fl != null && payment != null) - fl.setAD_Org_ID(payment.getAD_Org_ID()); - } - // Write off CR - if (Env.ZERO.compareTo(line.getWriteOffAmt()) != 0) - { - fl = fact.createLine (line, getAccount(Doc.ACCTTYPE_WriteOff, as), - getC_Currency_ID(), null, line.getWriteOffAmt().negate()); - if (fl != null && payment != null) - fl.setAD_Org_ID(payment.getAD_Org_ID()); - } - // Payment/Cash CR - if (isUsingClearing && line.getC_Payment_ID() != 0) // Avoid usage of clearing accounts + payAcct = getPaymentAcct(as, line.getC_Payment_ID()); + fl = fact.createLine (line, payAcct, + getC_Currency_ID(), line.getAmtSource(), null); + if (fl != null && payment != null) + fl.setAD_Org_ID(payment.getAD_Org_ID()); + } + else if (line.getC_CashLine_ID() != 0) + { + fl = fact.createLine (line, getCashAcct(as, line.getC_CashLine_ID()), + getC_Currency_ID(), line.getAmtSource(), null); + MCashLine cashLine = new MCashLine (getCtx(), line.getC_CashLine_ID(), getTrxName()); + if (fl != null && cashLine.get_ID() != 0) + fl.setAD_Org_ID(cashLine.getAD_Org_ID()); + } + + } + // End Avoid usage of clearing accounts + + // Discount DR + if (Env.ZERO.compareTo(line.getDiscountAmt()) != 0) + { + fl = fact.createLine (line, getAccount(Doc.ACCTTYPE_DiscountExp, as), + getC_Currency_ID(), line.getDiscountAmt(), null); + if (fl != null && payment != null) + fl.setAD_Org_ID(payment.getAD_Org_ID()); + } + // Write off DR + if (Env.ZERO.compareTo(line.getWriteOffAmt()) != 0) + { + fl = fact.createLine (line, getAccount(Doc.ACCTTYPE_WriteOff, as), + getC_Currency_ID(), line.getWriteOffAmt(), null); + if (fl != null && payment != null) + fl.setAD_Org_ID(payment.getAD_Org_ID()); + } + + // AR Invoice Amount CR + if (as.isAccrual()) + { + bpAcct = getAccount(Doc.ACCTTYPE_C_Receivable, as); + fl = fact.createLine (line, bpAcct, + getC_Currency_ID(), null, allocationSource); // payment currency + if (fl != null) + allocationAccounted = fl.getAcctBalance().negate(); + if (fl != null && invoice != null) + fl.setAD_Org_ID(invoice.getAD_Org_ID()); + + // for Realized Gain & Loss + flForRGL = factForRGL.createLine (line, bpAcct, + getC_Currency_ID(), null, allocationSourceForRGL); // payment currency + if (flForRGL != null) + allocationAccountedForRGL = flForRGL.getAcctBalance().negate(); + } + else // Cash Based + { + allocationAccounted = createCashBasedAcct (as, fact, + invoice, allocationSource); + allocationAccountedForRGL = allocationAccounted; + } + } + // Purchase Invoice + else + { + // Avoid usage of clearing accounts + // If both accounts Payment Select and Liability are equal + // then don't post + + MAccount acct_payment_select = null; + if (line.getC_Payment_ID() != 0) + acct_payment_select = getPaymentAcct(as, line.getC_Payment_ID()); + else if (line.getC_CashLine_ID() != 0) + acct_payment_select = getCashAcct(as, line.getC_CashLine_ID()); + MAccount acct_liability = getAccount(Doc.ACCTTYPE_V_Liability, as); + boolean isUsingClearing = true; + + // Save original allocation source for realized gain & loss purposes + allocationSourceForRGL = allocationSourceForRGL.negate(); + + if ((!as.isPostIfClearingEqual()) && acct_payment_select != null && acct_payment_select.equals(acct_liability) && (!isInterOrg)) { + + // if not using clearing accounts, then don't post amtsource + // change the allocationsource to be writeoff + discount + allocationSource = line.getDiscountAmt().add(line.getWriteOffAmt()); + isUsingClearing = false; + + } + // End Avoid usage of clearing accounts + + allocationSource = allocationSource.negate(); // allocation is negative + // AP Invoice Amount DR + if (as.isAccrual()) + { + bpAcct = getAccount(Doc.ACCTTYPE_V_Liability, as); + fl = fact.createLine (line, bpAcct, + getC_Currency_ID(), allocationSource, null); // payment currency + if (fl != null) + allocationAccounted = fl.getAcctBalance(); + if (fl != null && invoice != null) + fl.setAD_Org_ID(invoice.getAD_Org_ID()); + + // for Realized Gain & Loss + flForRGL = factForRGL.createLine (line, bpAcct, + getC_Currency_ID(), allocationSourceForRGL, null); // payment currency + if (flForRGL != null) + allocationAccountedForRGL = flForRGL.getAcctBalance(); + } + else // Cash Based + { + allocationAccounted = createCashBasedAcct (as, fact, + invoice, allocationSource); + allocationAccountedForRGL = allocationAccounted; + } + + // Discount CR + if (Env.ZERO.compareTo(line.getDiscountAmt()) != 0) + { + fl = fact.createLine (line, getAccount(Doc.ACCTTYPE_DiscountRev, as), + getC_Currency_ID(), null, line.getDiscountAmt().negate()); + if (fl != null && payment != null) + fl.setAD_Org_ID(payment.getAD_Org_ID()); + } + // Write off CR + if (Env.ZERO.compareTo(line.getWriteOffAmt()) != 0) + { + fl = fact.createLine (line, getAccount(Doc.ACCTTYPE_WriteOff, as), + getC_Currency_ID(), null, line.getWriteOffAmt().negate()); + if (fl != null && payment != null) + fl.setAD_Org_ID(payment.getAD_Org_ID()); + } + // Payment/Cash CR + if (isUsingClearing && line.getC_Payment_ID() != 0) // Avoid usage of clearing accounts { payAcct = getPaymentAcct(as, line.getC_Payment_ID()); - fl = fact.createLine (line, payAcct, - getC_Currency_ID(), null, line.getAmtSource().negate()); - if (fl != null && payment != null) - fl.setAD_Org_ID(payment.getAD_Org_ID()); - } - else if (isUsingClearing && line.getC_CashLine_ID() != 0) // Avoid usage of clearing accounts - { - fl = fact.createLine (line, getCashAcct(as, line.getC_CashLine_ID()), - getC_Currency_ID(), null, line.getAmtSource().negate()); - MCashLine cashLine = new MCashLine (getCtx(), line.getC_CashLine_ID(), getTrxName()); - if (fl != null && cashLine.get_ID() != 0) - fl.setAD_Org_ID(cashLine.getAD_Org_ID()); - } - } - - // VAT Tax Correction - if (invoice != null && as.isTaxCorrection()) - { - BigDecimal taxCorrectionAmt = Env.ZERO; - if (as.isTaxCorrectionDiscount()) - taxCorrectionAmt = line.getDiscountAmt(); - if (as.isTaxCorrectionWriteOff()) - taxCorrectionAmt = taxCorrectionAmt.add(line.getWriteOffAmt()); - // - if (taxCorrectionAmt.signum() != 0) - { - if (!createTaxCorrection(as, fact, line, - getAccount(invoice.isSOTrx() ? Doc.ACCTTYPE_DiscountExp : Doc.ACCTTYPE_DiscountRev, as), - getAccount(Doc.ACCTTYPE_WriteOff, as), invoice.isSOTrx())) - { - p_Error = "Cannot create Tax correction"; - return null; - } - } - } - - // Realized Gain & Loss - if (invoice != null - && (getC_Currency_ID() != as.getC_Currency_ID() // payment allocation in foreign currency - || getC_Currency_ID() != line.getInvoiceC_Currency_ID())) // allocation <> invoice currency - { - p_Error = createRealizedGainLoss (line, as, fact, bpAcct, invoice, payAcct, payment, - allocationSource, allocationAccounted); - if (p_Error != null) - return null; - } - - } // for all lines - - // FR [ 1840016 ] Avoid usage of clearing accounts - subject to C_AcctSchema.IsPostIfClearingEqual - if ( (!as.isPostIfClearingEqual()) && p_lines.length > 0 && (!isInterOrg)) { - boolean allEquals = true; - // more than one line (i.e. crossing one payment+ with a payment-, or an invoice against a credit memo) - // verify if the sum of all facts is zero net - FactLine[] factlines = fact.getLines(); - BigDecimal netBalance = Env.ZERO; - FactLine prevFactLine = null; - for (FactLine factLine : factlines) { - netBalance = netBalance.add(factLine.getAmtSourceDr()).subtract(factLine.getAmtSourceCr()); - if (prevFactLine != null) { - if (! equalFactLineIDs(prevFactLine, factLine)) { - allEquals = false; - break; - } - } - prevFactLine = factLine; - } - if (netBalance.compareTo(Env.ZERO) == 0 && allEquals) { - // delete the postings - for (FactLine factline : factlines) - fact.remove(factline); - } - } - - // reset line info - setC_BPartner_ID(0); - // - m_facts.add(fact); - return m_facts; - } // createFact - - /** Verify if the posting involves two or more organizations - @return true if there are more than one org involved on the posting - */ - private boolean isInterOrg(MAcctSchema as) { - MAcctSchemaElement elementorg = as.getAcctSchemaElement(MAcctSchemaElement.ELEMENTTYPE_Organization); - if (elementorg == null || !elementorg.isBalanced()) { - // no org element or not need to be balanced - return false; - } - - if (p_lines.length <= 0) { - // no lines - return false; - } - - int startorg = p_lines[0].getAD_Org_ID(); - // validate if the allocation involves more than one org - for (int i = 0; i < p_lines.length; i++) { - DocLine_Allocation line = (DocLine_Allocation)p_lines[i]; - int orgpayment = startorg; - MPayment payment = null; - if (line.getC_Payment_ID() != 0) { - payment = new MPayment (getCtx(), line.getC_Payment_ID(), getTrxName()); - orgpayment = payment.getAD_Org_ID(); - } - int orginvoice = startorg; - MInvoice invoice = null; - if (line.getC_Invoice_ID() != 0) { - invoice = new MInvoice (getCtx(), line.getC_Invoice_ID(), getTrxName()); - orginvoice = invoice.getAD_Org_ID(); - } - int orgcashline = startorg; - MCashLine cashline = null; - if (line.getC_CashLine_ID() != 0) { - cashline = new MCashLine (getCtx(), line.getC_CashLine_ID(), getTrxName()); - orgcashline = cashline.getAD_Org_ID(); - } - int orgorder = startorg; - MOrder order = null; - if (line.getC_Order_ID() != 0) { - order = new MOrder (getCtx(), line.getC_Order_ID(), getTrxName()); - orgorder = order.getAD_Org_ID(); - } - - if ( line.getAD_Org_ID() != startorg - || orgpayment != startorg - || orginvoice != startorg - || orgcashline != startorg - || orgorder != startorg) - return true; - } - - return false; - } - - /** - * Compare the dimension ID's from two factlines - * @param allEquals - * @param prevFactLine - * @param factLine - * @return boolean indicating if both dimension ID's are equal - */ - private boolean equalFactLineIDs(FactLine prevFactLine, FactLine factLine) { - return (factLine.getA_Asset_ID() == prevFactLine.getA_Asset_ID() - && factLine.getAccount_ID() == prevFactLine.getAccount_ID() - && factLine.getAD_Client_ID() == prevFactLine.getAD_Client_ID() - && factLine.getAD_Org_ID() == prevFactLine.getAD_Org_ID() - && factLine.getAD_OrgTrx_ID() == prevFactLine.getAD_OrgTrx_ID() - && factLine.getC_AcctSchema_ID() == prevFactLine.getC_AcctSchema_ID() - && factLine.getC_Activity_ID() == prevFactLine.getC_Activity_ID() - && factLine.getC_BPartner_ID() == prevFactLine.getC_BPartner_ID() - && factLine.getC_Campaign_ID() == prevFactLine.getC_Campaign_ID() - && factLine.getC_Currency_ID() == prevFactLine.getC_Currency_ID() - && factLine.getC_LocFrom_ID() == prevFactLine.getC_LocFrom_ID() - && factLine.getC_LocTo_ID() == prevFactLine.getC_LocTo_ID() - && factLine.getC_Period_ID() == prevFactLine.getC_Period_ID() - && factLine.getC_Project_ID() == prevFactLine.getC_Project_ID() - && factLine.getC_ProjectPhase_ID() == prevFactLine.getC_ProjectPhase_ID() - && factLine.getC_ProjectTask_ID() == prevFactLine.getC_ProjectTask_ID() - && factLine.getC_SalesRegion_ID() == prevFactLine.getC_SalesRegion_ID() - && factLine.getC_SubAcct_ID() == prevFactLine.getC_SubAcct_ID() - && factLine.getC_Tax_ID() == prevFactLine.getC_Tax_ID() - && factLine.getC_UOM_ID() == prevFactLine.getC_UOM_ID() - && factLine.getGL_Budget_ID() == prevFactLine.getGL_Budget_ID() - && factLine.getGL_Category_ID() == prevFactLine.getGL_Category_ID() - && factLine.getM_Locator_ID() == prevFactLine.getM_Locator_ID() - && factLine.getM_Product_ID() == prevFactLine.getM_Product_ID() - && factLine.getUserElement1_ID() == prevFactLine.getUserElement1_ID() - && factLine.getUserElement2_ID() == prevFactLine.getUserElement2_ID() - && factLine.getUser1_ID() == prevFactLine.getUser1_ID() - && factLine.getUser2_ID() == prevFactLine.getUser2_ID()); - } - - /** - * Create Cash Based Acct - * @param as accounting schema - * @param fact fact - * @param invoice invoice - * @param allocationSource allocation amount (incl discount, writeoff) - * @return Accounted Amt - */ - private BigDecimal createCashBasedAcct (MAcctSchema as, Fact fact, MInvoice invoice, - BigDecimal allocationSource) - { - BigDecimal allocationAccounted = Env.ZERO; - // Multiplier - double percent = invoice.getGrandTotal().doubleValue() / allocationSource.doubleValue(); - if (percent > 0.99 && percent < 1.01) - percent = 1.0; - if (log.isLoggable(Level.CONFIG)) log.config("Multiplier=" + percent + " - GrandTotal=" + invoice.getGrandTotal() - + " - Allocation Source=" + allocationSource); - - // Get Invoice Postings - Doc_Invoice docInvoice = (Doc_Invoice)Doc.get(as, - MInvoice.Table_ID, invoice.getC_Invoice_ID(), getTrxName()); - docInvoice.loadDocumentDetails(); - allocationAccounted = docInvoice.createFactCash(as, fact, BigDecimal.valueOf(percent)); - if (log.isLoggable(Level.CONFIG)) log.config("Allocation Accounted=" + allocationAccounted); - - // Cash Based Commitment Release - if (as.isCreatePOCommitment() && !invoice.isSOTrx()) - { - MInvoiceLine[] lines = invoice.getLines(); - for (int i = 0; i < lines.length; i++) - { - Fact factC = Doc_Order.getCommitmentRelease(as, this, - lines[i].getQtyInvoiced(), lines[i].getC_InvoiceLine_ID(), BigDecimal.valueOf(percent)); - if (factC == null) - return null; - m_facts.add(factC); - } - } // Commitment - - return allocationAccounted; - } // createCashBasedAcct - - - /** - * Get Payment (Unallocated Payment or Payment Selection) Acct of Bank Account - * @param as accounting schema - * @param C_Payment_ID payment - * @return acct - */ - private MAccount getPaymentAcct (MAcctSchema as, int C_Payment_ID) - { - setC_BankAccount_ID(0); - // Doc.ACCTTYPE_UnallocatedCash (AR) or C_Prepayment - // or Doc.ACCTTYPE_PaymentSelect (AP) or V_Prepayment - int accountType = Doc.ACCTTYPE_UnallocatedCash; - // - String sql = "SELECT p.C_BankAccount_ID, d.DocBaseType, p.IsReceipt, p.IsPrepayment " - + "FROM C_Payment p INNER JOIN C_DocType d ON (p.C_DocType_ID=d.C_DocType_ID) " - + "WHERE C_Payment_ID=?"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement (sql, getTrxName()); - pstmt.setInt (1, C_Payment_ID); - rs = pstmt.executeQuery (); - if (rs.next ()) - { - setC_BankAccount_ID(rs.getInt(1)); - if (DOCTYPE_APPayment.equals(rs.getString(2))) - accountType = Doc.ACCTTYPE_PaymentSelect; - // Prepayment - if ("Y".equals(rs.getString(4))) // Prepayment - { - if ("Y".equals(rs.getString(3))) // Receipt - accountType = Doc.ACCTTYPE_C_Prepayment; - else - accountType = Doc.ACCTTYPE_V_Prepayment; - } - } - } - catch (Exception e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - - // - if (getC_BankAccount_ID() <= 0) - { - log.log(Level.SEVERE, "NONE for C_Payment_ID=" + C_Payment_ID); - return null; - } - return getAccount (accountType, as); - } // getPaymentAcct - - /** - * Get Cash (Transfer) Acct of CashBook - * @param as accounting schema - * @param C_CashLine_ID - * @return acct - */ - private MAccount getCashAcct (MAcctSchema as, int C_CashLine_ID) - { - String sql = "SELECT c.C_CashBook_ID " - + "FROM C_Cash c, C_CashLine cl " - + "WHERE c.C_Cash_ID=cl.C_Cash_ID AND cl.C_CashLine_ID=?"; - setC_CashBook_ID(DB.getSQLValue(null, sql, C_CashLine_ID)); - - if (getC_CashBook_ID() <= 0) - { - log.log(Level.SEVERE, "NONE for C_CashLine_ID=" + C_CashLine_ID); - return null; - } - return getAccount(Doc.ACCTTYPE_CashTransfer, as); - } // getCashAcct - - - /************************************************************************** - * Create Realized Gain & Loss. - * Compares the Accounted Amount of the Invoice to the - * Accounted Amount of the Allocation - * @param as accounting schema - * @param fact fact - * @param invAcct invoice account - * @param invoice invoice + fl = fact.createLine (line, payAcct, + getC_Currency_ID(), null, line.getAmtSource().negate()); + if (fl != null && payment != null) + fl.setAD_Org_ID(payment.getAD_Org_ID()); + } + else if (isUsingClearing && line.getC_CashLine_ID() != 0) // Avoid usage of clearing accounts + { + fl = fact.createLine (line, getCashAcct(as, line.getC_CashLine_ID()), + getC_Currency_ID(), null, line.getAmtSource().negate()); + MCashLine cashLine = new MCashLine (getCtx(), line.getC_CashLine_ID(), getTrxName()); + if (fl != null && cashLine.get_ID() != 0) + fl.setAD_Org_ID(cashLine.getAD_Org_ID()); + } + } + + // VAT Tax Correction + if (invoice != null && as.isTaxCorrection()) + { + BigDecimal taxCorrectionAmt = Env.ZERO; + if (as.isTaxCorrectionDiscount()) + taxCorrectionAmt = line.getDiscountAmt(); + if (as.isTaxCorrectionWriteOff()) + taxCorrectionAmt = taxCorrectionAmt.add(line.getWriteOffAmt()); + // + if (taxCorrectionAmt.signum() != 0) + { + if (!createTaxCorrection(as, fact, line, + getAccount(invoice.isSOTrx() ? Doc.ACCTTYPE_DiscountExp : Doc.ACCTTYPE_DiscountRev, as), + getAccount(Doc.ACCTTYPE_WriteOff, as), invoice.isSOTrx())) + { + p_Error = "Cannot create Tax correction"; + return null; + } + } + } + + // Realized Gain & Loss + if (invoice != null + && (getC_Currency_ID() != as.getC_Currency_ID() // payment allocation in foreign currency + || getC_Currency_ID() != line.getInvoiceC_Currency_ID())) // allocation <> invoice currency + { + p_Error = createRealizedGainLoss (line, as, fact, bpAcct, invoice, payAcct, payment, + allocationSource, allocationAccounted); + if (p_Error != null) + return null; + } + + } // for all lines + + // FR [ 1840016 ] Avoid usage of clearing accounts - subject to C_AcctSchema.IsPostIfClearingEqual + if ( (!as.isPostIfClearingEqual()) && p_lines.length > 0 && (!isInterOrg)) { + boolean allEquals = true; + // more than one line (i.e. crossing one payment+ with a payment-, or an invoice against a credit memo) + // verify if the sum of all facts is zero net + FactLine[] factlines = fact.getLines(); + BigDecimal netBalance = Env.ZERO; + FactLine prevFactLine = null; + for (FactLine factLine : factlines) { + netBalance = netBalance.add(factLine.getAmtSourceDr()).subtract(factLine.getAmtSourceCr()); + if (prevFactLine != null) { + if (! equalFactLineIDs(prevFactLine, factLine)) { + allEquals = false; + break; + } + } + prevFactLine = factLine; + } + if (netBalance.compareTo(Env.ZERO) == 0 && allEquals) { + // delete the postings + for (FactLine factline : factlines) + fact.remove(factline); + } + } + + // reset line info + setC_BPartner_ID(0); + // + m_facts.add(fact); + return m_facts; + } // createFact + + /** Verify if the posting involves two or more organizations + @return true if there are more than one org involved on the posting + */ + private boolean isInterOrg(MAcctSchema as) { + MAcctSchemaElement elementorg = as.getAcctSchemaElement(MAcctSchemaElement.ELEMENTTYPE_Organization); + if (elementorg == null || !elementorg.isBalanced()) { + // no org element or not need to be balanced + return false; + } + + if (p_lines.length <= 0) { + // no lines + return false; + } + + int startorg = p_lines[0].getAD_Org_ID(); + // validate if the allocation involves more than one org + for (int i = 0; i < p_lines.length; i++) { + DocLine_Allocation line = (DocLine_Allocation)p_lines[i]; + int orgpayment = startorg; + MPayment payment = null; + if (line.getC_Payment_ID() != 0) { + payment = new MPayment (getCtx(), line.getC_Payment_ID(), getTrxName()); + orgpayment = payment.getAD_Org_ID(); + } + int orginvoice = startorg; + MInvoice invoice = null; + if (line.getC_Invoice_ID() != 0) { + invoice = new MInvoice (getCtx(), line.getC_Invoice_ID(), getTrxName()); + orginvoice = invoice.getAD_Org_ID(); + } + int orgcashline = startorg; + MCashLine cashline = null; + if (line.getC_CashLine_ID() != 0) { + cashline = new MCashLine (getCtx(), line.getC_CashLine_ID(), getTrxName()); + orgcashline = cashline.getAD_Org_ID(); + } + int orgorder = startorg; + MOrder order = null; + if (line.getC_Order_ID() != 0) { + order = new MOrder (getCtx(), line.getC_Order_ID(), getTrxName()); + orgorder = order.getAD_Org_ID(); + } + + if ( line.getAD_Org_ID() != startorg + || orgpayment != startorg + || orginvoice != startorg + || orgcashline != startorg + || orgorder != startorg) + return true; + } + + return false; + } + + /** + * Compare the dimension ID's from two factlines + * @param allEquals + * @param prevFactLine + * @param factLine + * @return boolean indicating if both dimension ID's are equal + */ + private boolean equalFactLineIDs(FactLine prevFactLine, FactLine factLine) { + return (factLine.getA_Asset_ID() == prevFactLine.getA_Asset_ID() + && factLine.getAccount_ID() == prevFactLine.getAccount_ID() + && factLine.getAD_Client_ID() == prevFactLine.getAD_Client_ID() + && factLine.getAD_Org_ID() == prevFactLine.getAD_Org_ID() + && factLine.getAD_OrgTrx_ID() == prevFactLine.getAD_OrgTrx_ID() + && factLine.getC_AcctSchema_ID() == prevFactLine.getC_AcctSchema_ID() + && factLine.getC_Activity_ID() == prevFactLine.getC_Activity_ID() + && factLine.getC_BPartner_ID() == prevFactLine.getC_BPartner_ID() + && factLine.getC_Campaign_ID() == prevFactLine.getC_Campaign_ID() + && factLine.getC_Currency_ID() == prevFactLine.getC_Currency_ID() + && factLine.getC_LocFrom_ID() == prevFactLine.getC_LocFrom_ID() + && factLine.getC_LocTo_ID() == prevFactLine.getC_LocTo_ID() + && factLine.getC_Period_ID() == prevFactLine.getC_Period_ID() + && factLine.getC_Project_ID() == prevFactLine.getC_Project_ID() + && factLine.getC_ProjectPhase_ID() == prevFactLine.getC_ProjectPhase_ID() + && factLine.getC_ProjectTask_ID() == prevFactLine.getC_ProjectTask_ID() + && factLine.getC_SalesRegion_ID() == prevFactLine.getC_SalesRegion_ID() + && factLine.getC_SubAcct_ID() == prevFactLine.getC_SubAcct_ID() + && factLine.getC_Tax_ID() == prevFactLine.getC_Tax_ID() + && factLine.getC_UOM_ID() == prevFactLine.getC_UOM_ID() + && factLine.getGL_Budget_ID() == prevFactLine.getGL_Budget_ID() + && factLine.getGL_Category_ID() == prevFactLine.getGL_Category_ID() + && factLine.getM_Locator_ID() == prevFactLine.getM_Locator_ID() + && factLine.getM_Product_ID() == prevFactLine.getM_Product_ID() + && factLine.getUserElement1_ID() == prevFactLine.getUserElement1_ID() + && factLine.getUserElement2_ID() == prevFactLine.getUserElement2_ID() + && factLine.getUser1_ID() == prevFactLine.getUser1_ID() + && factLine.getUser2_ID() == prevFactLine.getUser2_ID()); + } + + /** + * Create Cash Based Acct + * @param as accounting schema + * @param fact fact + * @param invoice invoice + * @param allocationSource allocation amount (incl discount, writeoff) + * @return Accounted Amt + */ + private BigDecimal createCashBasedAcct (MAcctSchema as, Fact fact, MInvoice invoice, + BigDecimal allocationSource) + { + BigDecimal allocationAccounted = Env.ZERO; + // Multiplier + double percent = invoice.getGrandTotal().doubleValue() / allocationSource.doubleValue(); + if (percent > 0.99 && percent < 1.01) + percent = 1.0; + if (log.isLoggable(Level.CONFIG)) log.config("Multiplier=" + percent + " - GrandTotal=" + invoice.getGrandTotal() + + " - Allocation Source=" + allocationSource); + + // Get Invoice Postings + Doc_Invoice docInvoice = (Doc_Invoice)Doc.get(as, + MInvoice.Table_ID, invoice.getC_Invoice_ID(), getTrxName()); + docInvoice.loadDocumentDetails(); + allocationAccounted = docInvoice.createFactCash(as, fact, BigDecimal.valueOf(percent)); + if (log.isLoggable(Level.CONFIG)) log.config("Allocation Accounted=" + allocationAccounted); + + // Cash Based Commitment Release + if (as.isCreatePOCommitment() && !invoice.isSOTrx()) + { + MInvoiceLine[] lines = invoice.getLines(); + for (int i = 0; i < lines.length; i++) + { + Fact factC = Doc_Order.getCommitmentRelease(as, this, + lines[i].getQtyInvoiced(), lines[i].getC_InvoiceLine_ID(), BigDecimal.valueOf(percent)); + if (factC == null) + return null; + m_facts.add(factC); + } + } // Commitment + + return allocationAccounted; + } // createCashBasedAcct + + + /** + * Get Payment (Unallocated Payment or Payment Selection) Acct of Bank Account + * @param as accounting schema + * @param C_Payment_ID payment + * @return acct + */ + private MAccount getPaymentAcct (MAcctSchema as, int C_Payment_ID) + { + setC_BankAccount_ID(0); + // Doc.ACCTTYPE_UnallocatedCash (AR) or C_Prepayment + // or Doc.ACCTTYPE_PaymentSelect (AP) or V_Prepayment + int accountType = Doc.ACCTTYPE_UnallocatedCash; + // + String sql = "SELECT p.C_BankAccount_ID, d.DocBaseType, p.IsReceipt, p.IsPrepayment " + + "FROM C_Payment p INNER JOIN C_DocType d ON (p.C_DocType_ID=d.C_DocType_ID) " + + "WHERE C_Payment_ID=?"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement (sql, getTrxName()); + pstmt.setInt (1, C_Payment_ID); + rs = pstmt.executeQuery (); + if (rs.next ()) + { + setC_BankAccount_ID(rs.getInt(1)); + if (DOCTYPE_APPayment.equals(rs.getString(2))) + accountType = Doc.ACCTTYPE_PaymentSelect; + // Prepayment + if ("Y".equals(rs.getString(4))) // Prepayment + { + if ("Y".equals(rs.getString(3))) // Receipt + accountType = Doc.ACCTTYPE_C_Prepayment; + else + accountType = Doc.ACCTTYPE_V_Prepayment; + } + } + } + catch (Exception e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + + // + if (getC_BankAccount_ID() <= 0) + { + log.log(Level.SEVERE, "NONE for C_Payment_ID=" + C_Payment_ID); + return null; + } + return getAccount (accountType, as); + } // getPaymentAcct + + /** + * Get Cash (Transfer) Acct of CashBook + * @param as accounting schema + * @param C_CashLine_ID + * @return acct + */ + private MAccount getCashAcct (MAcctSchema as, int C_CashLine_ID) + { + String sql = "SELECT c.C_CashBook_ID " + + "FROM C_Cash c, C_CashLine cl " + + "WHERE c.C_Cash_ID=cl.C_Cash_ID AND cl.C_CashLine_ID=?"; + setC_CashBook_ID(DB.getSQLValue(null, sql, C_CashLine_ID)); + + if (getC_CashBook_ID() <= 0) + { + log.log(Level.SEVERE, "NONE for C_CashLine_ID=" + C_CashLine_ID); + return null; + } + return getAccount(Doc.ACCTTYPE_CashTransfer, as); + } // getCashAcct + + + /************************************************************************** + * Create Realized Gain & Loss. + * Compares the Accounted Amount of the Invoice to the + * Accounted Amount of the Allocation + * @param as accounting schema + * @param fact fact + * @param invAcct invoice account + * @param invoice invoice * @param payAcct payment account * @param payment payment - * @param allocationSource source amt - * @param allocationAccounted acct amt - * @return Error Message or null if OK - */ - private String createRealizedGainLoss (DocLine line, MAcctSchema as, Fact fact, MAccount invAcct, - MInvoice invoice, MAccount payAcct, MPayment payment, BigDecimal allocationSource, BigDecimal allocationAccounted) - { - BigDecimal invoiceSource = null; - BigDecimal invoiceAccounted = null; + * @param allocationSource source amt + * @param allocationAccounted acct amt + * @return Error Message or null if OK + */ + private String createRealizedGainLoss (DocLine line, MAcctSchema as, Fact fact, MAccount invAcct, + MInvoice invoice, MAccount payAcct, MPayment payment, BigDecimal allocationSource, BigDecimal allocationAccounted) + { + BigDecimal invoiceSource = null; + BigDecimal invoiceAccounted = null; BigDecimal paymentSource = null; BigDecimal paymentAccounted = null; - // + // StringBuilder sql = new StringBuilder() - .append("SELECT SUM(AmtSourceDr), SUM(AmtAcctDr), SUM(AmtSourceCr), SUM(AmtAcctCr)") - .append(" FROM Fact_Acct ") - .append("WHERE AD_Table_ID=? AND Record_ID=?") - .append(" AND C_AcctSchema_ID=?") + .append("SELECT SUM(AmtSourceDr), SUM(AmtAcctDr), SUM(AmtSourceCr), SUM(AmtAcctCr)") + .append(" FROM Fact_Acct ") + .append("WHERE AD_Table_ID=? AND Record_ID=?") + .append(" AND C_AcctSchema_ID=?") .append(" AND PostingType='A'"); // For Invoice @@ -732,32 +732,32 @@ public class Doc_AllocationHdr extends Doc invoiceSource = (BigDecimal) valuesInv.get(2); // AmtSourceCr invoiceAccounted = (BigDecimal) valuesInv.get(3); // AmtAcctCr } - } - // Requires that Invoice is Posted - if (invoiceSource == null || invoiceAccounted == null) - return "Gain/Loss - Invoice not posted yet"; + } + // Requires that Invoice is Posted + if (invoiceSource == null || invoiceAccounted == null) + return "Gain/Loss - Invoice not posted yet"; // - String invoiceCur = MCurrency.get(getCtx(), invoice.getC_Currency_ID()).getISO_Code(); + String invoiceCur = MCurrency.get(getCtx(), invoice.getC_Currency_ID()).getISO_Code(); String allocCur = MCurrency.get(getCtx(), getC_Currency_ID()).getISO_Code(); - StringBuilder descriptionInv = new StringBuilder("Invoice=(").append(invoiceCur).append(")").append(invoiceSource).append("/").append(invoiceAccounted) - .append(" - Allocation=(").append(allocCur).append(")").append(allocationSource).append("/").append(allocationAccounted); - if (log.isLoggable(Level.FINE)) log.fine(descriptionInv.toString()); + StringBuilder descriptionInv = new StringBuilder("Invoice=(").append(invoiceCur).append(")").append(invoiceSource).append("/").append(invoiceAccounted) + .append(" - Allocation=(").append(allocCur).append(")").append(allocationSource).append("/").append(allocationAccounted); + if (log.isLoggable(Level.FINE)) log.fine(descriptionInv.toString()); // Allocation not Invoice Currency - BigDecimal allocationInvoiceSource = allocationSource; - if (getC_Currency_ID() != invoice.getC_Currency_ID()) - { - allocationInvoiceSource = MConversionRate.convert(getCtx(), - allocationSource, getC_Currency_ID(), - invoice.getC_Currency_ID(), getDateAcct(), - invoice.getC_ConversionType_ID(), invoice.getAD_Client_ID(), invoice.getAD_Org_ID()); - if (allocationInvoiceSource == null) - return "Gain/Loss - No Conversion from Allocation->Invoice"; - StringBuilder d2 = new StringBuilder("Allocation=(").append(allocCur).append(")").append(allocationSource) - .append("->(").append(invoiceCur).append(")").append(allocationInvoiceSource); - if (log.isLoggable(Level.FINE)) log.fine(d2.toString()); - descriptionInv.append(" - ").append(d2); - } - + BigDecimal allocationInvoiceSource = allocationSource; + if (getC_Currency_ID() != invoice.getC_Currency_ID()) + { + allocationInvoiceSource = MConversionRate.convert(getCtx(), + allocationSource, getC_Currency_ID(), + invoice.getC_Currency_ID(), getDateAcct(), + invoice.getC_ConversionType_ID(), invoice.getAD_Client_ID(), invoice.getAD_Org_ID()); + if (allocationInvoiceSource == null) + return "Gain/Loss - No Conversion from Allocation->Invoice"; + StringBuilder d2 = new StringBuilder("Allocation=(").append(allocCur).append(")").append(allocationSource) + .append("->(").append(invoiceCur).append(")").append(allocationInvoiceSource); + if (log.isLoggable(Level.FINE)) log.fine(d2.toString()); + descriptionInv.append(" - ").append(d2); + } + BigDecimal invoiceDifference = null; // gain is negative // Full Invoice in currency if (allocationInvoiceSource.compareTo(invoiceSource) == 0) @@ -855,17 +855,17 @@ public class Doc_AllocationHdr extends Doc } } - if (invoiceDifference.signum() == 0 && paymentDifference.signum() == 0) - { - log.fine("No Difference"); - return null; - } - - MAccount gain = MAccount.get (as.getCtx(), as.getAcctSchemaDefault().getRealizedGain_Acct()); - MAccount loss = MAccount.get (as.getCtx(), as.getAcctSchemaDefault().getRealizedLoss_Acct()); + if (invoiceDifference.signum() == 0 && paymentDifference.signum() == 0) + { + log.fine("No Difference"); + return null; + } + + MAccount gain = MAccount.get (as.getCtx(), as.getAcctSchemaDefault().getRealizedGain_Acct()); + MAccount loss = MAccount.get (as.getCtx(), as.getAcctSchemaDefault().getRealizedLoss_Acct()); // - BigDecimal acctDifference = invoiceDifference.subtract(paymentDifference); - if (invoice.isSOTrx()) + BigDecimal acctDifference = invoiceDifference.subtract(paymentDifference); + if (invoice.isSOTrx()) { if (acctDifference.signum() != 0) { FactLine fl = fact.createLine (line, loss, gain, as.getC_Currency_ID(), acctDifference); @@ -878,14 +878,14 @@ public class Doc_AllocationHdr extends Doc if (invoiceDifference.signum() != 0) { FactLine fl = fact.createLine (line, invAcct, as.getC_Currency_ID(), invoiceDifference.negate()); fl.setDescription(descriptionInv.toString()); - } + } if (paymentDifference.signum() != 0) { FactLine fl = fact.createLine (line, payAcct, as.getC_Currency_ID(), paymentDifference); fl.setDescription(descriptionPay.toString()); } - } - else - { + } + else + { if (invoiceDifference.signum() != 0) { FactLine fl = fact.createLine (line, invAcct, as.getC_Currency_ID(), invoiceDifference); fl.setDescription(descriptionInv.toString()); @@ -902,234 +902,234 @@ public class Doc_AllocationHdr extends Doc } fl.setDescription(description.toString()); } - } - return null; - } // createRealizedGainLoss - - - /************************************************************************** - * Create Tax Correction. - * Requirement: Adjust the tax amount, if you did not receive the full - * amount of the invoice (payment discount, write-off). - * Applies to many countries with VAT. - * Example: - * Invoice: Net $100 + Tax1 $15 + Tax2 $5 = Total $120 - * Payment: $115 (i.e. $5 underpayment) - * Tax Adjustment = Tax1 = 0.63 (15/120*5) Tax2 = 0.21 (5/120/5) - * - * @param as accounting schema - * @param fact fact - * @param line Allocation line - * @param DiscountAccount discount acct - * @param WriteOffAccoint write off acct - * @return true if created - */ - private boolean createTaxCorrection (MAcctSchema as, Fact fact, - DocLine_Allocation line, - MAccount DiscountAccount, MAccount WriteOffAccoint, boolean isSOTrx) - { - if (log.isLoggable(Level.INFO)) log.info (line.toString()); - BigDecimal discount = Env.ZERO; - if (as.isTaxCorrectionDiscount()) - discount = line.getDiscountAmt(); - BigDecimal writeOff = Env.ZERO; - if (as.isTaxCorrectionWriteOff()) - writeOff = line.getWriteOffAmt(); - - Doc_AllocationTax tax = new Doc_AllocationTax ( - DiscountAccount, discount, WriteOffAccoint, writeOff, isSOTrx); - - // Get Source Amounts with account - String sql = "SELECT * " - + "FROM Fact_Acct " - + "WHERE AD_Table_ID=318 AND Record_ID=?" // Invoice - + " AND C_AcctSchema_ID=?" - + " AND Line_ID IS NULL"; // header lines like tax or total - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, getTrxName()); - pstmt.setInt(1, line.getC_Invoice_ID()); - pstmt.setInt(2, as.getC_AcctSchema_ID()); - rs = pstmt.executeQuery(); - while (rs.next()) - tax.addInvoiceFact (new MFactAcct(getCtx(), rs, fact.get_TrxName())); - } - catch (Exception e) - { - log.log(Level.SEVERE, sql, e); - } - finally { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - // Invoice Not posted - if (tax.getLineCount() == 0) - { - log.warning ("Invoice not posted yet - " + line); - return false; - } - // size = 1 if no tax - if (tax.getLineCount() < 2) - return true; - return tax.createEntries (as, fact, line); - - } // createTaxCorrection - -} // Doc_Allocation - -/** - * Allocation Document Tax Handing - * - * @author Jorg Janke - * @version $Id: Doc_Allocation.java,v 1.6 2006/07/30 00:53:33 jjanke Exp $ - */ -class Doc_AllocationTax -{ - /** - * Allocation Tax Adjustment - * @param DiscountAccount discount acct - * @param DiscountAmt discount amt - * @param WriteOffAccount write off acct - * @param WriteOffAmt write off amt - */ - public Doc_AllocationTax (MAccount DiscountAccount, BigDecimal DiscountAmt, - MAccount WriteOffAccount, BigDecimal WriteOffAmt, boolean isSOTrx) - { - m_DiscountAccount = DiscountAccount; - m_DiscountAmt = DiscountAmt; - m_WriteOffAccount = WriteOffAccount; - m_WriteOffAmt = WriteOffAmt; - m_IsSOTrx = isSOTrx; - } // Doc_AllocationTax - - private CLogger log = CLogger.getCLogger(getClass()); - - private MAccount m_DiscountAccount; - private BigDecimal m_DiscountAmt; - private MAccount m_WriteOffAccount; - private BigDecimal m_WriteOffAmt; - private boolean m_IsSOTrx; - - private ArrayList m_facts = new ArrayList(); - private int m_totalIndex = 0; - - /** - * Add Invoice Fact Line - * @param fact fact line - */ - public void addInvoiceFact (MFactAcct fact) - { - m_facts.add(fact); - } // addInvoiceLine - - /** - * Get Line Count - * @return number of lines - */ - public int getLineCount() - { - return m_facts.size(); - } // getLineCount - - /** - * Create Accounting Entries - * @param as account schema - * @param fact fact to add lines - * @param line line - * @return true if created - */ - public boolean createEntries (MAcctSchema as, Fact fact, DocLine line) - { - // get total index (the Receivables/Liabilities line) - BigDecimal total = Env.ZERO; - for (int i = 0; i < m_facts.size(); i++) - { - MFactAcct factAcct = (MFactAcct)m_facts.get(i); - if (factAcct.getAmtSourceDr().compareTo(total) > 0) - { - total = factAcct.getAmtSourceDr(); - m_totalIndex = i; - } - if (factAcct.getAmtSourceCr().compareTo(total) > 0) - { - total = factAcct.getAmtSourceCr(); - m_totalIndex = i; - } - } - - MFactAcct factAcct = (MFactAcct)m_facts.get(m_totalIndex); - if (log.isLoggable(Level.INFO)) log.info ("Total Invoice = " + total + " - " + factAcct); - int precision = as.getStdPrecision(); - for (int i = 0; i < m_facts.size(); i++) - { - // No Tax Line - if (i == m_totalIndex) - continue; - - factAcct = (MFactAcct)m_facts.get(i); - if (log.isLoggable(Level.INFO)) log.info (i + ": " + factAcct); - - // Create Tax Account - MAccount taxAcct = factAcct.getMAccount(); - if (taxAcct == null || taxAcct.get_ID() == 0) - { - log.severe ("Tax Account not found/created"); - return false; - } - - -// Discount Amount - if (m_DiscountAmt.signum() != 0) - { - // Original Tax is DR - need to correct it CR - if (Env.ZERO.compareTo(factAcct.getAmtSourceDr()) != 0) - { - BigDecimal amount = calcAmount(factAcct.getAmtSourceDr(), - total, m_DiscountAmt, precision); - if (amount.signum() != 0) - { - //for sales actions - if (m_IsSOTrx) { - fact.createLine (line, m_DiscountAccount, - as.getC_Currency_ID(), amount, null); - fact.createLine (line, taxAcct, - as.getC_Currency_ID(), null, amount); - } else { - //for purchase actions - fact.createLine (line, m_DiscountAccount, - as.getC_Currency_ID(), amount.negate(), null); - fact.createLine (line, taxAcct, - as.getC_Currency_ID(), null, amount.negate()); - } - - } - } - // Original Tax is CR - need to correct it DR - else - { - BigDecimal amount = calcAmount(factAcct.getAmtSourceCr(), - total, m_DiscountAmt, precision); - if (amount.signum() != 0) - { -// for sales actions - if (m_IsSOTrx) { - fact.createLine (line, taxAcct, - as.getC_Currency_ID(), amount, null); - fact.createLine (line, m_DiscountAccount, - as.getC_Currency_ID(), null, amount); - } else { - fact.createLine (line, taxAcct, - as.getC_Currency_ID(), amount.negate(), null); - fact.createLine (line, m_DiscountAccount, - as.getC_Currency_ID(), null, amount.negate()); - } - } - } - } // Discount - - // WriteOff Amount + } + return null; + } // createRealizedGainLoss + + + /************************************************************************** + * Create Tax Correction. + * Requirement: Adjust the tax amount, if you did not receive the full + * amount of the invoice (payment discount, write-off). + * Applies to many countries with VAT. + * Example: + * Invoice: Net $100 + Tax1 $15 + Tax2 $5 = Total $120 + * Payment: $115 (i.e. $5 underpayment) + * Tax Adjustment = Tax1 = 0.63 (15/120*5) Tax2 = 0.21 (5/120/5) + * + * @param as accounting schema + * @param fact fact + * @param line Allocation line + * @param DiscountAccount discount acct + * @param WriteOffAccoint write off acct + * @return true if created + */ + private boolean createTaxCorrection (MAcctSchema as, Fact fact, + DocLine_Allocation line, + MAccount DiscountAccount, MAccount WriteOffAccoint, boolean isSOTrx) + { + if (log.isLoggable(Level.INFO)) log.info (line.toString()); + BigDecimal discount = Env.ZERO; + if (as.isTaxCorrectionDiscount()) + discount = line.getDiscountAmt(); + BigDecimal writeOff = Env.ZERO; + if (as.isTaxCorrectionWriteOff()) + writeOff = line.getWriteOffAmt(); + + Doc_AllocationTax tax = new Doc_AllocationTax ( + DiscountAccount, discount, WriteOffAccoint, writeOff, isSOTrx); + + // Get Source Amounts with account + String sql = "SELECT * " + + "FROM Fact_Acct " + + "WHERE AD_Table_ID=318 AND Record_ID=?" // Invoice + + " AND C_AcctSchema_ID=?" + + " AND Line_ID IS NULL"; // header lines like tax or total + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, getTrxName()); + pstmt.setInt(1, line.getC_Invoice_ID()); + pstmt.setInt(2, as.getC_AcctSchema_ID()); + rs = pstmt.executeQuery(); + while (rs.next()) + tax.addInvoiceFact (new MFactAcct(getCtx(), rs, fact.get_TrxName())); + } + catch (Exception e) + { + log.log(Level.SEVERE, sql, e); + } + finally { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + // Invoice Not posted + if (tax.getLineCount() == 0) + { + log.warning ("Invoice not posted yet - " + line); + return false; + } + // size = 1 if no tax + if (tax.getLineCount() < 2) + return true; + return tax.createEntries (as, fact, line); + + } // createTaxCorrection + +} // Doc_Allocation + +/** + * Allocation Document Tax Handing + * + * @author Jorg Janke + * @version $Id: Doc_Allocation.java,v 1.6 2006/07/30 00:53:33 jjanke Exp $ + */ +class Doc_AllocationTax +{ + /** + * Allocation Tax Adjustment + * @param DiscountAccount discount acct + * @param DiscountAmt discount amt + * @param WriteOffAccount write off acct + * @param WriteOffAmt write off amt + */ + public Doc_AllocationTax (MAccount DiscountAccount, BigDecimal DiscountAmt, + MAccount WriteOffAccount, BigDecimal WriteOffAmt, boolean isSOTrx) + { + m_DiscountAccount = DiscountAccount; + m_DiscountAmt = DiscountAmt; + m_WriteOffAccount = WriteOffAccount; + m_WriteOffAmt = WriteOffAmt; + m_IsSOTrx = isSOTrx; + } // Doc_AllocationTax + + private CLogger log = CLogger.getCLogger(getClass()); + + private MAccount m_DiscountAccount; + private BigDecimal m_DiscountAmt; + private MAccount m_WriteOffAccount; + private BigDecimal m_WriteOffAmt; + private boolean m_IsSOTrx; + + private ArrayList m_facts = new ArrayList(); + private int m_totalIndex = 0; + + /** + * Add Invoice Fact Line + * @param fact fact line + */ + public void addInvoiceFact (MFactAcct fact) + { + m_facts.add(fact); + } // addInvoiceLine + + /** + * Get Line Count + * @return number of lines + */ + public int getLineCount() + { + return m_facts.size(); + } // getLineCount + + /** + * Create Accounting Entries + * @param as account schema + * @param fact fact to add lines + * @param line line + * @return true if created + */ + public boolean createEntries (MAcctSchema as, Fact fact, DocLine line) + { + // get total index (the Receivables/Liabilities line) + BigDecimal total = Env.ZERO; + for (int i = 0; i < m_facts.size(); i++) + { + MFactAcct factAcct = (MFactAcct)m_facts.get(i); + if (factAcct.getAmtSourceDr().compareTo(total) > 0) + { + total = factAcct.getAmtSourceDr(); + m_totalIndex = i; + } + if (factAcct.getAmtSourceCr().compareTo(total) > 0) + { + total = factAcct.getAmtSourceCr(); + m_totalIndex = i; + } + } + + MFactAcct factAcct = (MFactAcct)m_facts.get(m_totalIndex); + if (log.isLoggable(Level.INFO)) log.info ("Total Invoice = " + total + " - " + factAcct); + int precision = as.getStdPrecision(); + for (int i = 0; i < m_facts.size(); i++) + { + // No Tax Line + if (i == m_totalIndex) + continue; + + factAcct = (MFactAcct)m_facts.get(i); + if (log.isLoggable(Level.INFO)) log.info (i + ": " + factAcct); + + // Create Tax Account + MAccount taxAcct = factAcct.getMAccount(); + if (taxAcct == null || taxAcct.get_ID() == 0) + { + log.severe ("Tax Account not found/created"); + return false; + } + + +// Discount Amount + if (m_DiscountAmt.signum() != 0) + { + // Original Tax is DR - need to correct it CR + if (Env.ZERO.compareTo(factAcct.getAmtSourceDr()) != 0) + { + BigDecimal amount = calcAmount(factAcct.getAmtSourceDr(), + total, m_DiscountAmt, precision); + if (amount.signum() != 0) + { + //for sales actions + if (m_IsSOTrx) { + fact.createLine (line, m_DiscountAccount, + as.getC_Currency_ID(), amount, null); + fact.createLine (line, taxAcct, + as.getC_Currency_ID(), null, amount); + } else { + //for purchase actions + fact.createLine (line, m_DiscountAccount, + as.getC_Currency_ID(), amount.negate(), null); + fact.createLine (line, taxAcct, + as.getC_Currency_ID(), null, amount.negate()); + } + + } + } + // Original Tax is CR - need to correct it DR + else + { + BigDecimal amount = calcAmount(factAcct.getAmtSourceCr(), + total, m_DiscountAmt, precision); + if (amount.signum() != 0) + { +// for sales actions + if (m_IsSOTrx) { + fact.createLine (line, taxAcct, + as.getC_Currency_ID(), amount, null); + fact.createLine (line, m_DiscountAccount, + as.getC_Currency_ID(), null, amount); + } else { + fact.createLine (line, taxAcct, + as.getC_Currency_ID(), amount.negate(), null); + fact.createLine (line, m_DiscountAccount, + as.getC_Currency_ID(), null, amount.negate()); + } + } + } + } // Discount + + // WriteOff Amount if (m_WriteOffAmt.signum() != 0) { // Original Tax is DR - need to correct it CR @@ -1173,33 +1173,33 @@ class Doc_AllocationTax } } } // WriteOff - - } // for all lines - return true; - } // createEntries - - /** - * Calc Amount tax / total * amt - * @param tax tax - * @param total total - * @param amt reduction amt - * @param precision precision - * @return tax / total * amt - */ - private BigDecimal calcAmount (BigDecimal tax, BigDecimal total, BigDecimal amt, int precision) - { - if (log.isLoggable(Level.FINE)) log.fine("Amt=" + amt + " - Total=" + total + ", Tax=" + tax); - if (tax.signum() == 0 - || total.signum() == 0 - || amt.signum() == 0) - return Env.ZERO; - // - BigDecimal multiplier = tax.divide(total, 10, RoundingMode.HALF_UP); - BigDecimal retValue = multiplier.multiply(amt); - if (retValue.scale() > precision) - retValue = retValue.setScale(precision, RoundingMode.HALF_UP); - if (log.isLoggable(Level.FINE)) log.fine(retValue + " (Mult=" + multiplier + "(Prec=" + precision + ")"); - return retValue; - } // calcAmount - -} // Doc_AllocationTax + + } // for all lines + return true; + } // createEntries + + /** + * Calc Amount tax / total * amt + * @param tax tax + * @param total total + * @param amt reduction amt + * @param precision precision + * @return tax / total * amt + */ + private BigDecimal calcAmount (BigDecimal tax, BigDecimal total, BigDecimal amt, int precision) + { + if (log.isLoggable(Level.FINE)) log.fine("Amt=" + amt + " - Total=" + total + ", Tax=" + tax); + if (tax.signum() == 0 + || total.signum() == 0 + || amt.signum() == 0) + return Env.ZERO; + // + BigDecimal multiplier = tax.divide(total, 10, RoundingMode.HALF_UP); + BigDecimal retValue = multiplier.multiply(amt); + if (retValue.scale() > precision) + retValue = retValue.setScale(precision, RoundingMode.HALF_UP); + if (log.isLoggable(Level.FINE)) log.fine(retValue + " (Mult=" + multiplier + "(Prec=" + precision + ")"); + return retValue; + } // calcAmount + +} // Doc_AllocationTax diff --git a/org.adempiere.base/src/org/compiere/acct/Doc_GLJournal.java b/org.adempiere.base/src/org/compiere/acct/Doc_GLJournal.java index 4400b5e625..1933dfa8f0 100644 --- a/org.adempiere.base/src/org/compiere/acct/Doc_GLJournal.java +++ b/org.adempiere.base/src/org/compiere/acct/Doc_GLJournal.java @@ -1,177 +1,177 @@ -/****************************************************************************** - * 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.compiere.acct; - -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.logging.Level; - -import org.compiere.model.MAccount; -import org.compiere.model.MAcctSchema; -import org.compiere.model.MJournal; -import org.compiere.model.MJournalLine; -import org.compiere.util.Env; - -/** - * Post GL Journal Documents. - *
    - *  Table:              GL_Journal (224)
    - *  Document Types:     GLJ
    - *  
    - * @author Jorg Janke - * @version $Id: Doc_GLJournal.java,v 1.3 2006/07/30 00:53:33 jjanke Exp $ - */ -public class Doc_GLJournal extends Doc -{ - /** - * Constructor - * @param as accounting schema - * @param rs record - * @param trxName trx - */ - public Doc_GLJournal (MAcctSchema as, ResultSet rs, String trxName) - { - super(as, MJournal.class, rs, null, trxName); - } // Doc_GL_Journal - - /** Posting Type */ - protected String m_PostingType = null; - protected int m_C_AcctSchema_ID = 0; - - /** - * Load Specific Document Details - * @return error message or null - */ - protected String loadDocumentDetails () - { - MJournal journal = (MJournal)getPO(); - m_PostingType = journal.getPostingType(); - m_C_AcctSchema_ID = journal.getC_AcctSchema_ID(); - - // Contained Objects - p_lines = loadLines(journal); - if (log.isLoggable(Level.FINE)) log.fine("Lines=" + p_lines.length); - return null; - } // loadDocumentDetails - - - /** - * Load Invoice Line - * @param journal journal - * @return DocLine Array - */ - protected DocLine[] loadLines(MJournal journal) - { - ArrayList list = new ArrayList(); - MJournalLine[] lines = journal.getLines(false); - for (int i = 0; i < lines.length; i++) - { - MJournalLine line = lines[i]; - DocLine docLine = new DocLine (line, this); - // -- Quantity - docLine.setQty(line.getQty(), false); - // -- Source Amounts - docLine.setAmount (line.getAmtSourceDr(), line.getAmtSourceCr()); - // -- Converted Amounts - docLine.setConvertedAmt (m_C_AcctSchema_ID, line.getAmtAcctDr(), line.getAmtAcctCr()); - // -- Account - MAccount account = line.getAccount_Combi(); - docLine.setAccount (account); - // -- Organization of Line was set to Org of Account +/****************************************************************************** + * 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.compiere.acct; + +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.logging.Level; + +import org.compiere.model.MAccount; +import org.compiere.model.MAcctSchema; +import org.compiere.model.MJournal; +import org.compiere.model.MJournalLine; +import org.compiere.util.Env; + +/** + * Post GL Journal Documents. + *
    + *  Table:              GL_Journal (224)
    + *  Document Types:     GLJ
    + *  
    + * @author Jorg Janke + * @version $Id: Doc_GLJournal.java,v 1.3 2006/07/30 00:53:33 jjanke Exp $ + */ +public class Doc_GLJournal extends Doc +{ + /** + * Constructor + * @param as accounting schema + * @param rs record + * @param trxName trx + */ + public Doc_GLJournal (MAcctSchema as, ResultSet rs, String trxName) + { + super(as, MJournal.class, rs, null, trxName); + } // Doc_GL_Journal + + /** Posting Type */ + protected String m_PostingType = null; + protected int m_C_AcctSchema_ID = 0; + + /** + * Load Specific Document Details + * @return error message or null + */ + protected String loadDocumentDetails () + { + MJournal journal = (MJournal)getPO(); + m_PostingType = journal.getPostingType(); + m_C_AcctSchema_ID = journal.getC_AcctSchema_ID(); + + // Contained Objects + p_lines = loadLines(journal); + if (log.isLoggable(Level.FINE)) log.fine("Lines=" + p_lines.length); + return null; + } // loadDocumentDetails + + + /** + * Load Invoice Line + * @param journal journal + * @return DocLine Array + */ + protected DocLine[] loadLines(MJournal journal) + { + ArrayList list = new ArrayList(); + MJournalLine[] lines = journal.getLines(false); + for (int i = 0; i < lines.length; i++) + { + MJournalLine line = lines[i]; + DocLine docLine = new DocLine (line, this); + // -- Quantity + docLine.setQty(line.getQty(), false); + // -- Source Amounts + docLine.setAmount (line.getAmtSourceDr(), line.getAmtSourceCr()); + // -- Converted Amounts + docLine.setConvertedAmt (m_C_AcctSchema_ID, line.getAmtAcctDr(), line.getAmtAcctCr()); + // -- Account + MAccount account = line.getAccount_Combi(); + docLine.setAccount (account); + // -- Organization of Line was set to Org of Account list.add(docLine); if (docLine.getC_Currency_ID() != getC_Currency_ID()) - setIsMultiCurrency(true); - } - // Return Array - int size = list.size(); - DocLine[] dls = new DocLine[size]; - list.toArray(dls); - return dls; - } // loadLines - - - /************************************************************************** - * Get Source Currency Balance - subtracts line and tax amounts from total - no rounding - * @return positive amount, if total invoice is bigger than lines - */ - public BigDecimal getBalance() - { - BigDecimal retValue = Env.ZERO; - StringBuilder sb = new StringBuilder (" ["); - // Lines - for (int i = 0; i < p_lines.length; i++) - { - retValue = retValue.add(p_lines[i].getAmtSource()); - sb.append("+").append(p_lines[i].getAmtSource()); - } - sb.append("]"); - // - if (log.isLoggable(Level.FINE)) log.fine(toString() + " Balance=" + retValue + sb.toString()); - return retValue; - } // getBalance - - /** - * Create Facts (the accounting logic) for - * GLJ. - * (only for the accounting scheme, it was created) - *
    -	 *      account     DR          CR
    -	 *  
    - * @param as acct schema - * @return Fact - */ - public ArrayList createFacts (MAcctSchema as) - { - ArrayList facts = new ArrayList(); - // Other Acct Schema - if (as.getC_AcctSchema_ID() != m_C_AcctSchema_ID) - return facts; - - // create Fact Header - Fact fact = new Fact (this, as, m_PostingType); - - // GLJ - if (getDocumentType().equals(DOCTYPE_GLJournal)) - { - // account DR CR - for (int i = 0; i < p_lines.length; i++) - { - if (p_lines[i].getC_AcctSchema_ID () == as.getC_AcctSchema_ID ()) - { - @SuppressWarnings("unused") - FactLine line = fact.createLine (p_lines[i], - p_lines[i].getAccount (), - p_lines[i].getC_Currency_ID(), - p_lines[i].getAmtSourceDr (), - p_lines[i].getAmtSourceCr ()); - } - } // for all lines - } - else - { - p_Error = "DocumentType unknown: " + getDocumentType(); - log.log(Level.SEVERE, p_Error); - fact = null; - } - // - facts.add(fact); - return facts; - } // createFact - -} // Doc_GLJournal + setIsMultiCurrency(true); + } + // Return Array + int size = list.size(); + DocLine[] dls = new DocLine[size]; + list.toArray(dls); + return dls; + } // loadLines + + + /************************************************************************** + * Get Source Currency Balance - subtracts line and tax amounts from total - no rounding + * @return positive amount, if total invoice is bigger than lines + */ + public BigDecimal getBalance() + { + BigDecimal retValue = Env.ZERO; + StringBuilder sb = new StringBuilder (" ["); + // Lines + for (int i = 0; i < p_lines.length; i++) + { + retValue = retValue.add(p_lines[i].getAmtSource()); + sb.append("+").append(p_lines[i].getAmtSource()); + } + sb.append("]"); + // + if (log.isLoggable(Level.FINE)) log.fine(toString() + " Balance=" + retValue + sb.toString()); + return retValue; + } // getBalance + + /** + * Create Facts (the accounting logic) for + * GLJ. + * (only for the accounting scheme, it was created) + *
    +	 *      account     DR          CR
    +	 *  
    + * @param as acct schema + * @return Fact + */ + public ArrayList createFacts (MAcctSchema as) + { + ArrayList facts = new ArrayList(); + // Other Acct Schema + if (as.getC_AcctSchema_ID() != m_C_AcctSchema_ID) + return facts; + + // create Fact Header + Fact fact = new Fact (this, as, m_PostingType); + + // GLJ + if (getDocumentType().equals(DOCTYPE_GLJournal)) + { + // account DR CR + for (int i = 0; i < p_lines.length; i++) + { + if (p_lines[i].getC_AcctSchema_ID () == as.getC_AcctSchema_ID ()) + { + @SuppressWarnings("unused") + FactLine line = fact.createLine (p_lines[i], + p_lines[i].getAccount (), + p_lines[i].getC_Currency_ID(), + p_lines[i].getAmtSourceDr (), + p_lines[i].getAmtSourceCr ()); + } + } // for all lines + } + else + { + p_Error = "DocumentType unknown: " + getDocumentType(); + log.log(Level.SEVERE, p_Error); + fact = null; + } + // + facts.add(fact); + return facts; + } // createFact + +} // Doc_GLJournal diff --git a/org.adempiere.base/src/org/compiere/acct/Doc_Order.java b/org.adempiere.base/src/org/compiere/acct/Doc_Order.java index 451a5fc74e..65556e005c 100644 --- a/org.adempiere.base/src/org/compiere/acct/Doc_Order.java +++ b/org.adempiere.base/src/org/compiere/acct/Doc_Order.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,25 +16,25 @@ *****************************************************************************/ package org.compiere.acct; -import java.math.BigDecimal; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.logging.Level; - -import org.compiere.model.MAccount; -import org.compiere.model.MAcctSchema; -import org.compiere.model.MClientInfo; -import org.compiere.model.MCurrency; -import org.compiere.model.MOrder; -import org.compiere.model.MOrderLine; -import org.compiere.model.MRequisitionLine; -import org.compiere.model.MTax; -import org.compiere.model.ProductCost; -import org.compiere.util.DB; -import org.compiere.util.Env; +import java.math.BigDecimal; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.logging.Level; + +import org.compiere.model.MAccount; +import org.compiere.model.MAcctSchema; +import org.compiere.model.MClientInfo; +import org.compiere.model.MCurrency; +import org.compiere.model.MOrder; +import org.compiere.model.MOrderLine; +import org.compiere.model.MRequisitionLine; +import org.compiere.model.MTax; +import org.compiere.model.ProductCost; +import org.compiere.util.DB; +import org.compiere.util.Env; /** * Post Order Documents. @@ -100,12 +100,12 @@ public class Doc_Order extends Doc { MOrderLine line = lines[i]; DocLine docLine = new DocLine (line, this); - BigDecimal Qty = line.getQtyOrdered(); - docLine.setQty(Qty, order.isSOTrx()); - // - BigDecimal PriceCost = null; - if (getDocumentType().equals(DOCTYPE_POrder)) // PO - PriceCost = line.getPriceCost(); + BigDecimal Qty = line.getQtyOrdered(); + docLine.setQty(Qty, order.isSOTrx()); + // + BigDecimal PriceCost = null; + if (getDocumentType().equals(DOCTYPE_POrder)) // PO + PriceCost = line.getPriceCost(); BigDecimal LineNetAmt = null; if (PriceCost != null && PriceCost.signum() != 0) LineNetAmt = Qty.multiply(PriceCost); @@ -121,7 +121,7 @@ public class Doc_Order extends Doc if (!tax.isZeroTax()) { BigDecimal LineNetAmtTax = tax.calculateTax(LineNetAmt, true, getStdPrecision()); - if (log.isLoggable(Level.FINE)) log.fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax); + if (log.isLoggable(Level.FINE)) log.fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax); LineNetAmt = LineNetAmt.subtract(LineNetAmtTax); for (int t = 0; t < m_taxes.length; t++) { @@ -163,17 +163,17 @@ public class Doc_Order extends Doc } // ArrayList list = new ArrayList(); - String sql = "SELECT * FROM M_RequisitionLine rl " - + "WHERE EXISTS (SELECT * FROM C_Order o " - + " INNER JOIN C_OrderLine ol ON (o.C_Order_ID=ol.C_Order_ID) " - + "WHERE ol.C_OrderLine_ID=rl.C_OrderLine_ID" - + " AND o.C_Order_ID=?) " - + "ORDER BY rl.C_OrderLine_ID"; - PreparedStatement pstmt = null; + String sql = "SELECT * FROM M_RequisitionLine rl " + + "WHERE EXISTS (SELECT * FROM C_Order o " + + " INNER JOIN C_OrderLine ol ON (o.C_Order_ID=ol.C_Order_ID) " + + "WHERE ol.C_OrderLine_ID=rl.C_OrderLine_ID" + + " AND o.C_Order_ID=?) " + + "ORDER BY rl.C_OrderLine_ID"; + PreparedStatement pstmt = null; ResultSet rs = null; try { - pstmt = DB.prepareStatement (sql, null); + pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, order.getC_Order_ID()); rs = pstmt.executeQuery (); while (rs.next ()) @@ -200,12 +200,12 @@ public class Doc_Order extends Doc } catch (Exception e) { - log.log (Level.SEVERE, sql, e); + log.log (Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } // Return Array @@ -233,14 +233,14 @@ public class Doc_Order extends Doc private DocTax[] loadTaxes() { ArrayList list = new ArrayList(); - StringBuilder sql = new StringBuilder("SELECT it.C_Tax_ID, t.Name, t.Rate, it.TaxBaseAmt, it.TaxAmt, t.IsSalesTax ") - .append("FROM C_Tax t, C_OrderTax it ") - .append("WHERE t.C_Tax_ID=it.C_Tax_ID AND it.C_Order_ID=?"); - PreparedStatement pstmt = null; - ResultSet rs = null; + StringBuilder sql = new StringBuilder("SELECT it.C_Tax_ID, t.Name, t.Rate, it.TaxBaseAmt, it.TaxAmt, t.IsSalesTax ") + .append("FROM C_Tax t, C_OrderTax it ") + .append("WHERE t.C_Tax_ID=it.C_Tax_ID AND it.C_Order_ID=?"); + PreparedStatement pstmt = null; + ResultSet rs = null; try { - pstmt = DB.prepareStatement(sql.toString(), getTrxName()); + pstmt = DB.prepareStatement(sql.toString(), getTrxName()); pstmt.setInt(1, get_ID()); rs = pstmt.executeQuery(); // @@ -260,11 +260,11 @@ public class Doc_Order extends Doc } catch (SQLException e) { - log.log(Level.SEVERE, sql.toString(), e); - } - finally { - DB.close(rs, pstmt); - rs = null; pstmt = null; + log.log(Level.SEVERE, sql.toString(), e); + } + finally { + DB.close(rs, pstmt); + rs = null; pstmt = null; } // Return Array @@ -281,7 +281,7 @@ public class Doc_Order extends Doc public BigDecimal getBalance() { BigDecimal retValue = Env.ZERO; - StringBuilder sb = new StringBuilder (" ["); + StringBuilder sb = new StringBuilder (" ["); // Total retValue = retValue.add(getAmount(Doc.AMTTYPE_Gross)); sb.append(getAmount(Doc.AMTTYPE_Gross)); @@ -311,11 +311,11 @@ public class Doc_Order extends Doc if (retValue.signum() != 0 // Sum of Cost(vs. Price) in lines may not add up && getDocumentType().equals(DOCTYPE_POrder)) // PO { - if (log.isLoggable(Level.FINE)) log.fine(toString() + " Balance=" + retValue + sb.toString() + " (ignored)"); + if (log.isLoggable(Level.FINE)) log.fine(toString() + " Balance=" + retValue + sb.toString() + " (ignored)"); retValue = Env.ZERO; } else - if (log.isLoggable(Level.FINE)) log.fine(toString() + " Balance=" + retValue + sb.toString()); + if (log.isLoggable(Level.FINE)) log.fine(toString() + " Balance=" + retValue + sb.toString()); return retValue; } // getBalance @@ -341,29 +341,29 @@ public class Doc_Order extends Doc // Purchase Order if (getDocumentType().equals(DOCTYPE_POrder)) { - updateProductPO(as); - - //BigDecimal grossAmt = getAmount(Doc.AMTTYPE_Gross); - - // Commitment - @SuppressWarnings("unused") - FactLine fl = null; - if (as.isCreatePOCommitment()) - { - Fact fact = new Fact(this, as, Fact.POST_Commitment); + updateProductPO(as); + + //BigDecimal grossAmt = getAmount(Doc.AMTTYPE_Gross); + + // Commitment + @SuppressWarnings("unused") + FactLine fl = null; + if (as.isCreatePOCommitment()) + { + Fact fact = new Fact(this, as, Fact.POST_Commitment); BigDecimal total = Env.ZERO; for (int i = 0; i < p_lines.length; i++) { DocLine line = p_lines[i]; BigDecimal cost = line.getAmtSource(); total = total.add(cost); - - // Account - MAccount expense = line.getAccount(ProductCost.ACCTTYPE_P_Expense, as); - fl = fact.createLine (line, expense, - getC_Currency_ID(), cost, null); - } - // Offset + + // Account + MAccount expense = line.getAccount(ProductCost.ACCTTYPE_P_Expense, as); + fl = fact.createLine (line, expense, + getC_Currency_ID(), cost, null); + } + // Offset MAccount offset = getAccount(ACCTTYPE_CommitmentOffset, as); if (offset == null) { @@ -389,15 +389,15 @@ public class Doc_Order extends Doc DocLine line = m_requisitions[i]; BigDecimal cost = line.getAmtSource(); total = total.add(cost); - - // Account - MAccount expense = line.getAccount(ProductCost.ACCTTYPE_P_Expense, as); - fl = fact.createLine (line, expense, - getC_Currency_ID(), null, cost); - } - // Offset - if (m_requisitions.length > 0) - { + + // Account + MAccount expense = line.getAccount(ProductCost.ACCTTYPE_P_Expense, as); + fl = fact.createLine (line, expense, + getC_Currency_ID(), null, cost); + } + // Offset + if (m_requisitions.length > 0) + { MAccount offset = getAccount(ACCTTYPE_CommitmentOffset, as); if (offset == null) { @@ -407,47 +407,47 @@ public class Doc_Order extends Doc } fact.createLine (null, offset, getC_Currency_ID(), total, null); - } + } // facts.add(fact); } // reservations } // SO - else if (getDocumentType().equals(DOCTYPE_SOrder)) - { - // Commitment - @SuppressWarnings("unused") - FactLine fl = null; - if (as.isCreateSOCommitment()) - { - Fact fact = new Fact(this, as, Fact.POST_Commitment); - BigDecimal total = Env.ZERO; - for (int i = 0; i < p_lines.length; i++) - { - DocLine line = p_lines[i]; - BigDecimal cost = line.getAmtSource(); - total = total.add(cost); - - // Account - MAccount revenue = line.getAccount(ProductCost.ACCTTYPE_P_Revenue, as); - fl = fact.createLine (line, revenue, - getC_Currency_ID(), null, cost); - } - // Offset - MAccount offset = getAccount(ACCTTYPE_CommitmentOffsetSales, as); - if (offset == null) - { - p_Error = "@NotFound@ @CommitmentOffsetSales_Acct@"; - log.log(Level.SEVERE, p_Error); - return null; - } - fact.createLine (null, offset, - getC_Currency_ID(), total, null); - // - facts.add(fact); - } - - } + else if (getDocumentType().equals(DOCTYPE_SOrder)) + { + // Commitment + @SuppressWarnings("unused") + FactLine fl = null; + if (as.isCreateSOCommitment()) + { + Fact fact = new Fact(this, as, Fact.POST_Commitment); + BigDecimal total = Env.ZERO; + for (int i = 0; i < p_lines.length; i++) + { + DocLine line = p_lines[i]; + BigDecimal cost = line.getAmtSource(); + total = total.add(cost); + + // Account + MAccount revenue = line.getAccount(ProductCost.ACCTTYPE_P_Revenue, as); + fl = fact.createLine (line, revenue, + getC_Currency_ID(), null, cost); + } + // Offset + MAccount offset = getAccount(ACCTTYPE_CommitmentOffsetSales, as); + if (offset == null) + { + p_Error = "@NotFound@ @CommitmentOffsetSales_Acct@"; + log.log(Level.SEVERE, p_Error); + return null; + } + fact.createLine (null, offset, + getC_Currency_ID(), total, null); + // + facts.add(fact); + } + + } return facts; } // createFact @@ -462,31 +462,31 @@ public class Doc_Order extends Doc if (ci.getC_AcctSchema1_ID() != as.getC_AcctSchema_ID()) return; - StringBuilder sql = new StringBuilder ( - "UPDATE M_Product_PO po ") - .append("SET PriceLastPO = (SELECT currencyConvert(ol.PriceActual,ol.C_Currency_ID,po.C_Currency_ID,o.DateOrdered,o.C_ConversionType_ID,o.AD_Client_ID,o.AD_Org_ID) ") - .append("FROM C_Order o, C_OrderLine ol ") - .append("WHERE o.C_Order_ID=ol.C_Order_ID") - .append(" AND po.M_Product_ID=ol.M_Product_ID AND po.C_BPartner_ID=o.C_BPartner_ID "); - //jz + " AND ROWNUM=1 AND o.C_Order_ID=").append(get_ID()).append(") ") - if (DB.isOracle()) //jz - { - sql.append(" AND ROWNUM=1 "); - } - else - sql.append(" AND ol.C_OrderLine_ID = (SELECT MIN(ol1.C_OrderLine_ID) ") - .append("FROM C_Order o1, C_OrderLine ol1 ") - .append("WHERE o1.C_Order_ID=ol1.C_Order_ID") - .append(" AND po.M_Product_ID=ol1.M_Product_ID AND po.C_BPartner_ID=o1.C_BPartner_ID") - .append(" AND o1.C_Order_ID=").append(get_ID()).append(") "); - sql.append(" AND o.C_Order_ID=").append(get_ID()).append(") ") - .append("WHERE EXISTS (SELECT * ") - .append("FROM C_Order o, C_OrderLine ol ") - .append("WHERE o.C_Order_ID=ol.C_Order_ID") - .append(" AND po.M_Product_ID=ol.M_Product_ID AND po.C_BPartner_ID=o.C_BPartner_ID") - .append(" AND o.C_Order_ID=").append(get_ID()).append(")"); + StringBuilder sql = new StringBuilder ( + "UPDATE M_Product_PO po ") + .append("SET PriceLastPO = (SELECT currencyConvert(ol.PriceActual,ol.C_Currency_ID,po.C_Currency_ID,o.DateOrdered,o.C_ConversionType_ID,o.AD_Client_ID,o.AD_Org_ID) ") + .append("FROM C_Order o, C_OrderLine ol ") + .append("WHERE o.C_Order_ID=ol.C_Order_ID") + .append(" AND po.M_Product_ID=ol.M_Product_ID AND po.C_BPartner_ID=o.C_BPartner_ID "); + //jz + " AND ROWNUM=1 AND o.C_Order_ID=").append(get_ID()).append(") ") + if (DB.isOracle()) //jz + { + sql.append(" AND ROWNUM=1 "); + } + else + sql.append(" AND ol.C_OrderLine_ID = (SELECT MIN(ol1.C_OrderLine_ID) ") + .append("FROM C_Order o1, C_OrderLine ol1 ") + .append("WHERE o1.C_Order_ID=ol1.C_Order_ID") + .append(" AND po.M_Product_ID=ol1.M_Product_ID AND po.C_BPartner_ID=o1.C_BPartner_ID") + .append(" AND o1.C_Order_ID=").append(get_ID()).append(") "); + sql.append(" AND o.C_Order_ID=").append(get_ID()).append(") ") + .append("WHERE EXISTS (SELECT * ") + .append("FROM C_Order o, C_OrderLine ol ") + .append("WHERE o.C_Order_ID=ol.C_Order_ID") + .append(" AND po.M_Product_ID=ol.M_Product_ID AND po.C_BPartner_ID=o.C_BPartner_ID") + .append(" AND o.C_Order_ID=").append(get_ID()).append(")"); int no = DB.executeUpdate(sql.toString(), getTrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Updated=" + no); + if (log.isLoggable(Level.FINE)) log.fine("Updated=" + no); } // updateProductPO @@ -502,20 +502,20 @@ public class Doc_Order extends Doc int precision = -1; // ArrayList list = new ArrayList(); - StringBuilder sql = new StringBuilder("SELECT * FROM C_OrderLine ol ") - .append("WHERE EXISTS ") - .append("(SELECT * FROM C_InvoiceLine il ") - .append("WHERE il.C_OrderLine_ID=ol.C_OrderLine_ID") - .append(" AND il.C_InvoiceLine_ID=?)") - .append(" OR EXISTS ") - .append("(SELECT * FROM M_MatchPO po ") - .append("WHERE po.C_OrderLine_ID=ol.C_OrderLine_ID") - .append(" AND po.C_InvoiceLine_ID=?)"); - PreparedStatement pstmt = null; + StringBuilder sql = new StringBuilder("SELECT * FROM C_OrderLine ol ") + .append("WHERE EXISTS ") + .append("(SELECT * FROM C_InvoiceLine il ") + .append("WHERE il.C_OrderLine_ID=ol.C_OrderLine_ID") + .append(" AND il.C_InvoiceLine_ID=?)") + .append(" OR EXISTS ") + .append("(SELECT * FROM M_MatchPO po ") + .append("WHERE po.C_OrderLine_ID=ol.C_OrderLine_ID") + .append(" AND po.C_InvoiceLine_ID=?)"); + PreparedStatement pstmt = null; ResultSet rs = null; try { - pstmt = DB.prepareStatement (sql.toString(), null); + pstmt = DB.prepareStatement (sql.toString(), null); pstmt.setInt (1, C_InvoiceLine_ID); pstmt.setInt (2, C_InvoiceLine_ID); rs = pstmt.executeQuery (); @@ -556,7 +556,7 @@ public class Doc_Order extends Doc if (!tax.isZeroTax()) { BigDecimal LineNetAmtTax = tax.calculateTax(LineNetAmt, true, precision); - if (s_log.isLoggable(Level.FINE)) s_log.fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax); + if (s_log.isLoggable(Level.FINE)) s_log.fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax); LineNetAmt = LineNetAmt.subtract(LineNetAmtTax); BigDecimal PriceListTax = tax.calculateTax(PriceList, true, precision); PriceList = PriceList.subtract(PriceListTax); @@ -569,12 +569,12 @@ public class Doc_Order extends Doc } catch (Exception e) { - s_log.log (Level.SEVERE, sql.toString(), e); + s_log.log (Level.SEVERE, sql.toString(), e); } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } // Return Array @@ -598,14 +598,14 @@ public class Doc_Order extends Doc { Fact fact = new Fact(doc, as, Fact.POST_Commitment); DocLine[] commitments = Doc_Order.getCommitments(doc, Qty, - C_InvoiceLine_ID); - - BigDecimal total = Env.ZERO; - @SuppressWarnings("unused") - FactLine fl = null; - int C_Currency_ID = -1; - for (int i = 0; i < commitments.length; i++) - { + C_InvoiceLine_ID); + + BigDecimal total = Env.ZERO; + @SuppressWarnings("unused") + FactLine fl = null; + int C_Currency_ID = -1; + for (int i = 0; i < commitments.length; i++) + { DocLine line = commitments[i]; if (C_Currency_ID == -1) C_Currency_ID = line.getC_Currency_ID(); @@ -617,13 +617,13 @@ public class Doc_Order extends Doc } BigDecimal cost = line.getAmtSource().multiply(multiplier); total = total.add(cost); - - // Account - MAccount expense = line.getAccount(ProductCost.ACCTTYPE_P_Expense, as); - fl = fact.createLine (line, expense, - C_Currency_ID, null, cost); - } - // Offset + + // Account + MAccount expense = line.getAccount(ProductCost.ACCTTYPE_P_Expense, as); + fl = fact.createLine (line, expense, + C_Currency_ID, null, cost); + } + // Offset MAccount offset = doc.getAccount(ACCTTYPE_CommitmentOffset, as); if (offset == null) { @@ -636,144 +636,144 @@ public class Doc_Order extends Doc return fact; } // getCommitmentRelease - /** - * Get Commitments Sales - * @param doc document - * @param maxQty Qty invoiced/matched - * @param C_OrderLine_ID invoice line - * @return commitments (order lines) - */ - protected static DocLine[] getCommitmentsSales(Doc doc, BigDecimal maxQty, int M_InOutLine_ID) - { - int precision = -1; - // - ArrayList list = new ArrayList(); - StringBuilder sql = new StringBuilder("SELECT * FROM C_OrderLine ol ") - .append("WHERE EXISTS ") - .append("(SELECT * FROM M_InOutLine il ") - .append("WHERE il.C_OrderLine_ID=ol.C_OrderLine_ID") - .append(" AND il.M_InOutLine_ID=?)"); - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement (sql.toString(), null); - pstmt.setInt (1, M_InOutLine_ID); - rs = pstmt.executeQuery (); - while (rs.next ()) - { - if (maxQty.signum() == 0) - continue; - MOrderLine line = new MOrderLine (doc.getCtx(), rs, null); - DocLine docLine = new DocLine (line, doc); - // Currency - if (precision == -1) - { - doc.setC_Currency_ID(docLine.getC_Currency_ID()); - precision = MCurrency.getStdPrecision(doc.getCtx(), docLine.getC_Currency_ID()); - } - // Qty - BigDecimal Qty = line.getQtyOrdered().max(maxQty); - docLine.setQty(Qty, false); - // - BigDecimal PriceActual = line.getPriceActual(); - BigDecimal PriceCost = line.getPriceCost(); - BigDecimal LineNetAmt = null; - if (PriceCost != null && PriceCost.signum() != 0) - LineNetAmt = Qty.multiply(PriceCost); - else if (Qty.equals(maxQty)) - LineNetAmt = line.getLineNetAmt(); - else - LineNetAmt = Qty.multiply(PriceActual); - maxQty = maxQty.subtract(Qty); - - docLine.setAmount (LineNetAmt); // DR - BigDecimal PriceList = line.getPriceList(); - int C_Tax_ID = docLine.getC_Tax_ID(); - // Correct included Tax - if (C_Tax_ID != 0 && line.getParent().isTaxIncluded()) - { - MTax tax = MTax.get(doc.getCtx(), C_Tax_ID); - if (!tax.isZeroTax()) - { - BigDecimal LineNetAmtTax = tax.calculateTax(LineNetAmt, true, precision); - if (s_log.isLoggable(Level.FINE)) s_log.fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax); - LineNetAmt = LineNetAmt.subtract(LineNetAmtTax); - BigDecimal PriceListTax = tax.calculateTax(PriceList, true, precision); - PriceList = PriceList.subtract(PriceListTax); - } - } // correct included Tax - - docLine.setAmount (LineNetAmt, PriceList, Qty); - list.add(docLine); - } - } - catch (Exception e) - { - s_log.log (Level.SEVERE, sql.toString(), e); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - - // Return Array - DocLine[] dl = new DocLine[list.size()]; - list.toArray(dl); - return dl; - } // getCommitmentsSales - - /** - * Get Commitment Sales Release. - * Called from InOut - * @param as accounting schema - * @param doc doc - * @param Qty qty invoiced/matched - * @param C_OrderLine_ID line - * @param multiplier 1 for accrual - * @return Fact - */ - public static Fact getCommitmentSalesRelease(MAcctSchema as, Doc doc, - BigDecimal Qty, int M_InOutLine_ID, BigDecimal multiplier) - { - Fact fact = new Fact(doc, as, Fact.POST_Commitment); - DocLine[] commitments = Doc_Order.getCommitmentsSales(doc, Qty, - M_InOutLine_ID); - - BigDecimal total = Env.ZERO; - @SuppressWarnings("unused") - FactLine fl = null; - int C_Currency_ID = -1; - for (int i = 0; i < commitments.length; i++) - { - DocLine line = commitments[i]; - if (C_Currency_ID == -1) - C_Currency_ID = line.getC_Currency_ID(); - else if (C_Currency_ID != line.getC_Currency_ID()) - { - doc.p_Error = "Different Currencies of Order Lines"; - s_log.log(Level.SEVERE, doc.p_Error); - return null; - } - BigDecimal cost = line.getAmtSource().multiply(multiplier); - total = total.add(cost); - - // Account - MAccount revenue = line.getAccount(ProductCost.ACCTTYPE_P_Revenue, as); - fl = fact.createLine (line, revenue, - C_Currency_ID, cost, null); - } - // Offset - MAccount offset = doc.getAccount(ACCTTYPE_CommitmentOffsetSales, as); - if (offset == null) - { - doc.p_Error = "@NotFound@ @CommitmentOffsetSales_Acct@"; - s_log.log(Level.SEVERE, doc.p_Error); - return null; - } - fact.createLine (null, offset, - C_Currency_ID, null, total); - return fact; + /** + * Get Commitments Sales + * @param doc document + * @param maxQty Qty invoiced/matched + * @param C_OrderLine_ID invoice line + * @return commitments (order lines) + */ + protected static DocLine[] getCommitmentsSales(Doc doc, BigDecimal maxQty, int M_InOutLine_ID) + { + int precision = -1; + // + ArrayList list = new ArrayList(); + StringBuilder sql = new StringBuilder("SELECT * FROM C_OrderLine ol ") + .append("WHERE EXISTS ") + .append("(SELECT * FROM M_InOutLine il ") + .append("WHERE il.C_OrderLine_ID=ol.C_OrderLine_ID") + .append(" AND il.M_InOutLine_ID=?)"); + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement (sql.toString(), null); + pstmt.setInt (1, M_InOutLine_ID); + rs = pstmt.executeQuery (); + while (rs.next ()) + { + if (maxQty.signum() == 0) + continue; + MOrderLine line = new MOrderLine (doc.getCtx(), rs, null); + DocLine docLine = new DocLine (line, doc); + // Currency + if (precision == -1) + { + doc.setC_Currency_ID(docLine.getC_Currency_ID()); + precision = MCurrency.getStdPrecision(doc.getCtx(), docLine.getC_Currency_ID()); + } + // Qty + BigDecimal Qty = line.getQtyOrdered().max(maxQty); + docLine.setQty(Qty, false); + // + BigDecimal PriceActual = line.getPriceActual(); + BigDecimal PriceCost = line.getPriceCost(); + BigDecimal LineNetAmt = null; + if (PriceCost != null && PriceCost.signum() != 0) + LineNetAmt = Qty.multiply(PriceCost); + else if (Qty.equals(maxQty)) + LineNetAmt = line.getLineNetAmt(); + else + LineNetAmt = Qty.multiply(PriceActual); + maxQty = maxQty.subtract(Qty); + + docLine.setAmount (LineNetAmt); // DR + BigDecimal PriceList = line.getPriceList(); + int C_Tax_ID = docLine.getC_Tax_ID(); + // Correct included Tax + if (C_Tax_ID != 0 && line.getParent().isTaxIncluded()) + { + MTax tax = MTax.get(doc.getCtx(), C_Tax_ID); + if (!tax.isZeroTax()) + { + BigDecimal LineNetAmtTax = tax.calculateTax(LineNetAmt, true, precision); + if (s_log.isLoggable(Level.FINE)) s_log.fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax); + LineNetAmt = LineNetAmt.subtract(LineNetAmtTax); + BigDecimal PriceListTax = tax.calculateTax(PriceList, true, precision); + PriceList = PriceList.subtract(PriceListTax); + } + } // correct included Tax + + docLine.setAmount (LineNetAmt, PriceList, Qty); + list.add(docLine); + } + } + catch (Exception e) + { + s_log.log (Level.SEVERE, sql.toString(), e); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + + // Return Array + DocLine[] dl = new DocLine[list.size()]; + list.toArray(dl); + return dl; + } // getCommitmentsSales + + /** + * Get Commitment Sales Release. + * Called from InOut + * @param as accounting schema + * @param doc doc + * @param Qty qty invoiced/matched + * @param C_OrderLine_ID line + * @param multiplier 1 for accrual + * @return Fact + */ + public static Fact getCommitmentSalesRelease(MAcctSchema as, Doc doc, + BigDecimal Qty, int M_InOutLine_ID, BigDecimal multiplier) + { + Fact fact = new Fact(doc, as, Fact.POST_Commitment); + DocLine[] commitments = Doc_Order.getCommitmentsSales(doc, Qty, + M_InOutLine_ID); + + BigDecimal total = Env.ZERO; + @SuppressWarnings("unused") + FactLine fl = null; + int C_Currency_ID = -1; + for (int i = 0; i < commitments.length; i++) + { + DocLine line = commitments[i]; + if (C_Currency_ID == -1) + C_Currency_ID = line.getC_Currency_ID(); + else if (C_Currency_ID != line.getC_Currency_ID()) + { + doc.p_Error = "Different Currencies of Order Lines"; + s_log.log(Level.SEVERE, doc.p_Error); + return null; + } + BigDecimal cost = line.getAmtSource().multiply(multiplier); + total = total.add(cost); + + // Account + MAccount revenue = line.getAccount(ProductCost.ACCTTYPE_P_Revenue, as); + fl = fact.createLine (line, revenue, + C_Currency_ID, cost, null); + } + // Offset + MAccount offset = doc.getAccount(ACCTTYPE_CommitmentOffsetSales, as); + if (offset == null) + { + doc.p_Error = "@NotFound@ @CommitmentOffsetSales_Acct@"; + s_log.log(Level.SEVERE, doc.p_Error); + return null; + } + fact.createLine (null, offset, + C_Currency_ID, null, total); + return fact; } // getCommitmentSalesRelease } // Doc_Order \ No newline at end of file diff --git a/org.adempiere.base/src/org/compiere/db/DBRes_hu.java b/org.adempiere.base/src/org/compiere/db/DBRes_hu.java index 5e94266ab6..66881e0a86 100644 --- a/org.adempiere.base/src/org/compiere/db/DBRes_hu.java +++ b/org.adempiere.base/src/org/compiere/db/DBRes_hu.java @@ -1,65 +1,65 @@ -/****************************************************************************** - * 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.compiere.db; - -import java.util.ListResourceBundle; - -/** - * Connection Resource Strings - * - * @author Jorg Janke - * @version $Id: DBRes.java,v 1.2 2006/07/30 00:55:13 jjanke Exp $ - */ -public class DBRes_hu extends ListResourceBundle -{ - /** Data */ - static final Object[][] contents = new String[][]{ - { "CConnectionDialog", "Adempiere szerver kapcsolat" }, - { "Name", "Név" }, - { "AppsHost", "Alkalmazás szerver" }, - { "AppsPort", "Alkalmazás port" }, - { "TestApps", "Teszt alkalmazás szerver" }, - { "DBHost", "Adatbázis szerver" }, - { "DBPort", "Adatbázis port" }, - { "DBName", "Adatbázis név" }, - { "DBUidPwd", "Felhasználó / Jelszó" }, - { "ViaFirewall", "Firewallon keresztül" }, - { "FWHost", "Firewall cím" }, - { "FWPort", "Firewall port" }, - { "TestConnection", "Test Adatbázis" }, - { "Type", "Adatbázis típus" }, - { "BequeathConnection", "Kapcsolat hagyományozása" }, - { "Overwrite", "Felülír" }, - { "ConnectionProfile", "Kapcsolat profil" }, - { "LAN", "LAN" }, - { "TerminalServer", "Terminál szerver" }, - { "VPN", "VPN" }, - { "WAN", "WAN" }, - { "ConnectionError", "Kapcsolat hiba" }, - { "ServerNotActive", "Szerver nem aktív" } - }; - - /** - * Get Contsnts - * @return contents - */ - public Object[][] getContents() - { - return contents; - } // getContent +/****************************************************************************** + * 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.compiere.db; + +import java.util.ListResourceBundle; + +/** + * Connection Resource Strings + * + * @author Jorg Janke + * @version $Id: DBRes.java,v 1.2 2006/07/30 00:55:13 jjanke Exp $ + */ +public class DBRes_hu extends ListResourceBundle +{ + /** Data */ + static final Object[][] contents = new String[][]{ + { "CConnectionDialog", "Adempiere szerver kapcsolat" }, + { "Name", "Név" }, + { "AppsHost", "Alkalmazás szerver" }, + { "AppsPort", "Alkalmazás port" }, + { "TestApps", "Teszt alkalmazás szerver" }, + { "DBHost", "Adatbázis szerver" }, + { "DBPort", "Adatbázis port" }, + { "DBName", "Adatbázis név" }, + { "DBUidPwd", "Felhasználó / Jelszó" }, + { "ViaFirewall", "Firewallon keresztül" }, + { "FWHost", "Firewall cím" }, + { "FWPort", "Firewall port" }, + { "TestConnection", "Test Adatbázis" }, + { "Type", "Adatbázis típus" }, + { "BequeathConnection", "Kapcsolat hagyományozása" }, + { "Overwrite", "Felülír" }, + { "ConnectionProfile", "Kapcsolat profil" }, + { "LAN", "LAN" }, + { "TerminalServer", "Terminál szerver" }, + { "VPN", "VPN" }, + { "WAN", "WAN" }, + { "ConnectionError", "Kapcsolat hiba" }, + { "ServerNotActive", "Szerver nem aktív" } + }; + + /** + * Get Contsnts + * @return contents + */ + public Object[][] getContents() + { + return contents; + } // getContent } // Res diff --git a/org.adempiere.base/src/org/compiere/model/MAcctSchemaElement.java b/org.adempiere.base/src/org/compiere/model/MAcctSchemaElement.java index 7e48939ad3..a978dd1a98 100644 --- a/org.adempiere.base/src/org/compiere/model/MAcctSchemaElement.java +++ b/org.adempiere.base/src/org/compiere/model/MAcctSchemaElement.java @@ -1,567 +1,567 @@ -/****************************************************************************** - * 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.compiere.model; - -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; - -import org.compiere.util.CCache; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.Language; -import org.compiere.util.Msg; - -/** - * Account Schema Element Object - * - * @author Jorg Janke - * @version $Id: MAcctSchemaElement.java,v 1.4 2006/08/10 01:00:44 jjanke Exp $ - * - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - *
  • BF [ 1795817 ] Acct Schema Elements "Account" and "Org" should be mandatory - * @author victor.perez@e-evolution.com, www.e-evolution.com - *
  • RF [ 2214883 ] Remove SQL code and Replace for Query http://sourceforge.net/tracker/index.php?func=detail&aid=2214883&group_id=176962&atid=879335 - */ -public class MAcctSchemaElement extends X_C_AcctSchema_Element -{ - - - /** - * - */ - private static final long serialVersionUID = 4215184252533527719L; - - - /** - * Factory: Return ArrayList of Account Schema Elements - * @param as Accounting Schema - * @return ArrayList with Elements - */ - public static MAcctSchemaElement[] getAcctSchemaElements (MAcctSchema as) - { - Integer key = Integer.valueOf(as.getC_AcctSchema_ID()); - MAcctSchemaElement[] retValue = (MAcctSchemaElement[]) s_cache.get (key); - if (retValue != null) - return retValue; - - if (s_log.isLoggable(Level.FINE)) s_log.fine("C_AcctSchema_ID=" + as.getC_AcctSchema_ID()); - ArrayList list = new ArrayList(); - - final String whereClause = "C_AcctSchema_ID=? AND IsActive=?"; - List elements= new Query(as.getCtx(), I_C_AcctSchema_Element.Table_Name,whereClause,as.get_TrxName()) - .setParameters(as.getC_AcctSchema_ID(),"Y") - .setOrderBy("SeqNo") - .list(); - - for(MAcctSchemaElement ase : elements) - { - if (s_log.isLoggable(Level.FINE)) s_log.fine(" - " + ase); - if (ase.isMandatory() && ase.getDefaultValue() == 0) - s_log.log(Level.SEVERE, "No default value for " + ase.getName()); - list.add(ase); - } - - retValue = new MAcctSchemaElement[list.size()]; - list.toArray(retValue); - s_cache.put (key, retValue); - return retValue; - } // getAcctSchemaElements - - /** - * Get Column Name of ELEMENTTYPE - * @param elementType ELEMENTTYPE - * @return column name or "" if not found - */ - public static String getColumnName(String elementType) - { - if (elementType.equals(ELEMENTTYPE_Organization)) - return "AD_Org_ID"; - else if (elementType.equals(ELEMENTTYPE_Account)) - return I_C_ValidCombination.COLUMNNAME_Account_ID; - else if (elementType.equals(ELEMENTTYPE_BPartner)) - return I_C_ValidCombination.COLUMNNAME_C_BPartner_ID; - else if (elementType.equals(ELEMENTTYPE_Product)) - return I_C_ValidCombination.COLUMNNAME_M_Product_ID; - else if (elementType.equals(ELEMENTTYPE_Activity)) - return I_C_ValidCombination.COLUMNNAME_C_Activity_ID; - else if (elementType.equals(ELEMENTTYPE_LocationFrom)) - return I_C_ValidCombination.COLUMNNAME_C_LocFrom_ID; - else if (elementType.equals(ELEMENTTYPE_LocationTo)) - return I_C_ValidCombination.COLUMNNAME_C_LocTo_ID; - else if (elementType.equals(ELEMENTTYPE_Campaign)) - return I_C_ValidCombination.COLUMNNAME_C_Campaign_ID; - else if (elementType.equals(ELEMENTTYPE_OrgTrx)) - return I_C_ValidCombination.COLUMNNAME_AD_OrgTrx_ID; - else if (elementType.equals(ELEMENTTYPE_Project)) - return I_C_ValidCombination.COLUMNNAME_C_Project_ID; - else if (elementType.equals(ELEMENTTYPE_SalesRegion)) - return I_C_ValidCombination.COLUMNNAME_C_SalesRegion_ID; - else if (elementType.equals(ELEMENTTYPE_UserElementList1)) - return I_C_ValidCombination.COLUMNNAME_User1_ID; - else if (elementType.equals(ELEMENTTYPE_UserElementList2)) - return I_C_ValidCombination.COLUMNNAME_User2_ID; - else if (elementType.equals(ELEMENTTYPE_UserColumn1)) - return I_C_ValidCombination.COLUMNNAME_UserElement1_ID; - else if (elementType.equals(ELEMENTTYPE_UserColumn2)) - return I_C_ValidCombination.COLUMNNAME_UserElement2_ID; - // - return ""; - } // getColumnName - - /** - * Get Value Query for ELEMENTTYPE Type - * @param elementType ELEMENTTYPE type - * @return query "SELECT Value,Name FROM Table WHERE ID=" or "" if not found - */ - public static String getValueQuery (String elementType) - { - String baseLanguage = Language.getBaseAD_Language(); - String language = Language.getLoginLanguage().getAD_Language(); - boolean translated = Env.isMultiLingualDocument(Env.getCtx()) && ! language.equalsIgnoreCase(baseLanguage); - if (elementType.equals(ELEMENTTYPE_Organization)) { - return "SELECT Value,Name FROM AD_Org WHERE AD_Org_ID="; - } else if ( elementType.equals(ELEMENTTYPE_Account) - || elementType.equals(ELEMENTTYPE_UserElementList1) - || elementType.equals(ELEMENTTYPE_UserElementList2)) { - if (translated) - return "SELECT o.Value,t.Name FROM C_ElementValue o JOIN C_ElementValue_Trl t ON (o.C_ElementValue_ID=t.C_ElementValue_ID AND t.AD_Language=" + DB.TO_STRING(language)+ ") WHERE o.C_ElementValue_ID="; - else - return "SELECT Value,Name FROM C_ElementValue WHERE C_ElementValue_ID="; - } else if (elementType.equals(ELEMENTTYPE_SubAccount)) { - return "SELECT Value,Name FROM C_SubAccount WHERE C_SubAccount_ID="; - } else if (elementType.equals(ELEMENTTYPE_BPartner)) { - return "SELECT Value,Name FROM C_BPartner WHERE C_BPartner_ID="; - } else if (elementType.equals(ELEMENTTYPE_Product)) { - if (translated) - return "SELECT o.Value,t.Name FROM M_Product o JOIN M_Product_Trl t ON (o.M_Product_ID=t.M_Product_ID AND t.AD_Language=" + DB.TO_STRING(language)+ ") WHERE o.M_Product_ID="; - else - return "SELECT Value,Name FROM M_Product WHERE M_Product_ID="; - } else if (elementType.equals(ELEMENTTYPE_Activity)) { - if (translated) - return "SELECT Value,Name FROM C_Activity o JOIN C_Activity_Trl t ON (o.C_Activity_ID=t.C_Activity_ID AND t.AD_Language=" + DB.TO_STRING(language)+ ") WHERE o.C_Activity_ID="; - else - return "SELECT Value,Name FROM C_Activity WHERE C_Activity_ID="; - } else if ( elementType.equals(ELEMENTTYPE_LocationFrom) - || elementType.equals(ELEMENTTYPE_LocationTo)) { - return "SELECT City,Address1 FROM C_Location WHERE C_Location_ID="; - } else if (elementType.equals(ELEMENTTYPE_Campaign)) { - if (translated) - return "SELECT Value,Name FROM C_Campaign o JOIN C_Campaign_Trl t ON (o.C_Campaign_ID=t.C_Campaign_ID AND t.AD_Language=" + DB.TO_STRING(language)+ ") WHERE o.C_Campaign_ID="; - else - return "SELECT Value,Name FROM C_Campaign WHERE C_Campaign_ID="; - } else if (elementType.equals(ELEMENTTYPE_OrgTrx)) { - return "SELECT Value,Name FROM AD_Org WHERE AD_Org_ID="; - } else if (elementType.equals(ELEMENTTYPE_Project)) { - return "SELECT Value,Name FROM C_Project WHERE C_Project_ID="; - } else if (elementType.equals(ELEMENTTYPE_SalesRegion)) { - if (translated) - return "SELECT Value,Name FROM C_SalesRegion o JOIN C_SalesRegion_Trl t ON (o.C_SalesRegion_ID=t.C_SalesRegion_ID AND t.AD_Language=" + DB.TO_STRING(language)+ ") WHERE o.C_SalesRegion_ID="; // ADEMPIERE-119 / Freepath - else - return "SELECT Value,Name FROM C_SalesRegion WHERE C_SalesRegion_ID="; // ADEMPIERE-119 / Freepath - // - } else if ( elementType.equals(ELEMENTTYPE_UserColumn1) - || elementType.equals(ELEMENTTYPE_UserColumn2)) { - return null; - } - // - return ""; - } // getColumnName - - /** Logger */ - private static CLogger s_log = CLogger.getCLogger (MAcctSchemaElement.class); - - /** Cache */ - private static CCache s_cache = new CCache(Table_Name, 10); - - - /************************************************************************* - * Standard Constructor - * @param ctx context - * @param C_AcctSchema_Element_ID id - * @param trxName transaction - */ - public MAcctSchemaElement (Properties ctx, int C_AcctSchema_Element_ID, String trxName) - { - super (ctx, C_AcctSchema_Element_ID, trxName); - if (C_AcctSchema_Element_ID == 0) - { - // setC_AcctSchema_Element_ID (0); - // setC_AcctSchema_ID (0); - // setC_Element_ID (0); - // setElementType (null); - setIsBalanced (false); - setIsMandatory (false); - // setName (null); - // setOrg_ID (0); - // setSeqNo (0); - } - } // MAcctSchemaElement - - /** - * Load Constructor - * @param ctx context - * @param rs result set - * @param trxName transaction - */ - public MAcctSchemaElement (Properties ctx, ResultSet rs, String trxName) - { - super(ctx, rs, trxName); - } // MAcctSchemaElement - - /** - * Parent Constructor - * @param as accounting schema - */ - public MAcctSchemaElement (MAcctSchema as) - { - this (as.getCtx(), 0, as.get_TrxName()); - setClientOrg(as); - setC_AcctSchema_ID (as.getC_AcctSchema_ID()); - - // setC_Element_ID (0); - // setElementType (null); - // setName (null); - // setSeqNo (0); - - } // MAcctSchemaElement - - /** User Element Column Name */ - private String m_ColumnName = null; - - /** - * Set Organization Type - * @param SeqNo sequence - * @param Name name - * @param Org_ID id - */ - public void setTypeOrg (int SeqNo, String Name, int Org_ID) - { - setElementType (ELEMENTTYPE_Organization); - setSeqNo(SeqNo); - setName (Name); - setOrg_ID(Org_ID); - } // setTypeOrg - - /** - * Set Type Account - * @param SeqNo squence - * @param Name name - * @param C_Element_ID element - * @param C_ElementValue_ID element value - */ - public void setTypeAccount (int SeqNo, String Name, int C_Element_ID, int C_ElementValue_ID) - { - setElementType (ELEMENTTYPE_Account); - setSeqNo(SeqNo); - setName (Name); - setC_Element_ID (C_Element_ID); - setC_ElementValue_ID(C_ElementValue_ID); - } // setTypeAccount - - /** - * Set Type BPartner - * @param SeqNo sequence - * @param Name name - * @param C_BPartner_ID id - */ - public void setTypeBPartner (int SeqNo, String Name, int C_BPartner_ID) - { - setElementType (ELEMENTTYPE_BPartner); - setSeqNo(SeqNo); - setName (Name); - setC_BPartner_ID(C_BPartner_ID); - } // setTypeBPartner - - /** - * Set Type Product - * @param SeqNo sequence - * @param Name name - * @param M_Product_ID id - */ - public void setTypeProduct (int SeqNo, String Name, int M_Product_ID) - { - setElementType (ELEMENTTYPE_Product); - setSeqNo(SeqNo); - setName (Name); - setM_Product_ID(M_Product_ID); - } // setTypeProduct - - /** - * Set Type Project - * @param SeqNo sequence - * @param Name name - * @param C_Project_ID id - */ - public void setTypeProject (int SeqNo, String Name, int C_Project_ID) - { - setElementType (ELEMENTTYPE_Project); - setSeqNo(SeqNo); - setName (Name); - setC_Project_ID(C_Project_ID); - } // setTypeProject - - /** - * Is Element Type - * @param elementType type - * @return ELEMENTTYPE type - */ - public boolean isElementType (String elementType) - { - if (elementType == null) - return false; - return elementType.equals(getElementType()); - } // isElementType - - /** - * Get Default element value - * @return default - */ - public int getDefaultValue() - { - String elementType = getElementType(); - int defaultValue = 0; - if (elementType.equals(ELEMENTTYPE_Organization)) - defaultValue = getOrg_ID(); - else if (elementType.equals(ELEMENTTYPE_Account)) - defaultValue = getC_ElementValue_ID(); - else if (elementType.equals(ELEMENTTYPE_BPartner)) - defaultValue = getC_BPartner_ID(); - else if (elementType.equals(ELEMENTTYPE_Product)) - defaultValue = getM_Product_ID(); - else if (elementType.equals(ELEMENTTYPE_Activity)) - defaultValue = getC_Activity_ID(); - else if (elementType.equals(ELEMENTTYPE_LocationFrom)) - defaultValue = getC_Location_ID(); - else if (elementType.equals(ELEMENTTYPE_LocationTo)) - defaultValue = getC_Location_ID(); - else if (elementType.equals(ELEMENTTYPE_Campaign)) - defaultValue = getC_Campaign_ID(); - else if (elementType.equals(ELEMENTTYPE_OrgTrx)) - defaultValue = getOrg_ID(); - else if (elementType.equals(ELEMENTTYPE_Project)) - defaultValue = getC_Project_ID(); - else if (elementType.equals(ELEMENTTYPE_SalesRegion)) - defaultValue = getC_SalesRegion_ID(); - else if (elementType.equals(ELEMENTTYPE_UserElementList1)) - defaultValue = getC_ElementValue_ID(); - else if (elementType.equals(ELEMENTTYPE_UserElementList2)) - defaultValue = getC_ElementValue_ID(); - else if (elementType.equals(ELEMENTTYPE_UserColumn1)) - defaultValue = 0; - else if (elementType.equals(ELEMENTTYPE_UserColumn2)) - defaultValue = 0; - return defaultValue; - } // getDefault - - - /** - * Get Acct Fact ColumnName - * @return column name - */ - public String getColumnName() - { - String et = getElementType(); - return getColumnName(et); - } // getColumnName - - /** - * Get Display ColumnName - * @return column name - */ - public String getDisplayColumnName() - { - String et = getElementType(); - if (ELEMENTTYPE_UserColumn1.equals(et) || ELEMENTTYPE_UserColumn2.equals(et)) - { - if (m_ColumnName == null) - m_ColumnName = MColumn.getColumnName(getCtx(), getAD_Column_ID()); - return m_ColumnName; - } - return getColumnName(et); +/****************************************************************************** + * 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.compiere.model; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import org.compiere.util.CCache; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Language; +import org.compiere.util.Msg; + +/** + * Account Schema Element Object + * + * @author Jorg Janke + * @version $Id: MAcctSchemaElement.java,v 1.4 2006/08/10 01:00:44 jjanke Exp $ + * + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1795817 ] Acct Schema Elements "Account" and "Org" should be mandatory + * @author victor.perez@e-evolution.com, www.e-evolution.com + *
  • RF [ 2214883 ] Remove SQL code and Replace for Query http://sourceforge.net/tracker/index.php?func=detail&aid=2214883&group_id=176962&atid=879335 + */ +public class MAcctSchemaElement extends X_C_AcctSchema_Element +{ + + + /** + * + */ + private static final long serialVersionUID = 4215184252533527719L; + + + /** + * Factory: Return ArrayList of Account Schema Elements + * @param as Accounting Schema + * @return ArrayList with Elements + */ + public static MAcctSchemaElement[] getAcctSchemaElements (MAcctSchema as) + { + Integer key = Integer.valueOf(as.getC_AcctSchema_ID()); + MAcctSchemaElement[] retValue = (MAcctSchemaElement[]) s_cache.get (key); + if (retValue != null) + return retValue; + + if (s_log.isLoggable(Level.FINE)) s_log.fine("C_AcctSchema_ID=" + as.getC_AcctSchema_ID()); + ArrayList list = new ArrayList(); + + final String whereClause = "C_AcctSchema_ID=? AND IsActive=?"; + List elements= new Query(as.getCtx(), I_C_AcctSchema_Element.Table_Name,whereClause,as.get_TrxName()) + .setParameters(as.getC_AcctSchema_ID(),"Y") + .setOrderBy("SeqNo") + .list(); + + for(MAcctSchemaElement ase : elements) + { + if (s_log.isLoggable(Level.FINE)) s_log.fine(" - " + ase); + if (ase.isMandatory() && ase.getDefaultValue() == 0) + s_log.log(Level.SEVERE, "No default value for " + ase.getName()); + list.add(ase); + } + + retValue = new MAcctSchemaElement[list.size()]; + list.toArray(retValue); + s_cache.put (key, retValue); + return retValue; + } // getAcctSchemaElements + + /** + * Get Column Name of ELEMENTTYPE + * @param elementType ELEMENTTYPE + * @return column name or "" if not found + */ + public static String getColumnName(String elementType) + { + if (elementType.equals(ELEMENTTYPE_Organization)) + return "AD_Org_ID"; + else if (elementType.equals(ELEMENTTYPE_Account)) + return I_C_ValidCombination.COLUMNNAME_Account_ID; + else if (elementType.equals(ELEMENTTYPE_BPartner)) + return I_C_ValidCombination.COLUMNNAME_C_BPartner_ID; + else if (elementType.equals(ELEMENTTYPE_Product)) + return I_C_ValidCombination.COLUMNNAME_M_Product_ID; + else if (elementType.equals(ELEMENTTYPE_Activity)) + return I_C_ValidCombination.COLUMNNAME_C_Activity_ID; + else if (elementType.equals(ELEMENTTYPE_LocationFrom)) + return I_C_ValidCombination.COLUMNNAME_C_LocFrom_ID; + else if (elementType.equals(ELEMENTTYPE_LocationTo)) + return I_C_ValidCombination.COLUMNNAME_C_LocTo_ID; + else if (elementType.equals(ELEMENTTYPE_Campaign)) + return I_C_ValidCombination.COLUMNNAME_C_Campaign_ID; + else if (elementType.equals(ELEMENTTYPE_OrgTrx)) + return I_C_ValidCombination.COLUMNNAME_AD_OrgTrx_ID; + else if (elementType.equals(ELEMENTTYPE_Project)) + return I_C_ValidCombination.COLUMNNAME_C_Project_ID; + else if (elementType.equals(ELEMENTTYPE_SalesRegion)) + return I_C_ValidCombination.COLUMNNAME_C_SalesRegion_ID; + else if (elementType.equals(ELEMENTTYPE_UserElementList1)) + return I_C_ValidCombination.COLUMNNAME_User1_ID; + else if (elementType.equals(ELEMENTTYPE_UserElementList2)) + return I_C_ValidCombination.COLUMNNAME_User2_ID; + else if (elementType.equals(ELEMENTTYPE_UserColumn1)) + return I_C_ValidCombination.COLUMNNAME_UserElement1_ID; + else if (elementType.equals(ELEMENTTYPE_UserColumn2)) + return I_C_ValidCombination.COLUMNNAME_UserElement2_ID; + // + return ""; + } // getColumnName + + /** + * Get Value Query for ELEMENTTYPE Type + * @param elementType ELEMENTTYPE type + * @return query "SELECT Value,Name FROM Table WHERE ID=" or "" if not found + */ + public static String getValueQuery (String elementType) + { + String baseLanguage = Language.getBaseAD_Language(); + String language = Language.getLoginLanguage().getAD_Language(); + boolean translated = Env.isMultiLingualDocument(Env.getCtx()) && ! language.equalsIgnoreCase(baseLanguage); + if (elementType.equals(ELEMENTTYPE_Organization)) { + return "SELECT Value,Name FROM AD_Org WHERE AD_Org_ID="; + } else if ( elementType.equals(ELEMENTTYPE_Account) + || elementType.equals(ELEMENTTYPE_UserElementList1) + || elementType.equals(ELEMENTTYPE_UserElementList2)) { + if (translated) + return "SELECT o.Value,t.Name FROM C_ElementValue o JOIN C_ElementValue_Trl t ON (o.C_ElementValue_ID=t.C_ElementValue_ID AND t.AD_Language=" + DB.TO_STRING(language)+ ") WHERE o.C_ElementValue_ID="; + else + return "SELECT Value,Name FROM C_ElementValue WHERE C_ElementValue_ID="; + } else if (elementType.equals(ELEMENTTYPE_SubAccount)) { + return "SELECT Value,Name FROM C_SubAccount WHERE C_SubAccount_ID="; + } else if (elementType.equals(ELEMENTTYPE_BPartner)) { + return "SELECT Value,Name FROM C_BPartner WHERE C_BPartner_ID="; + } else if (elementType.equals(ELEMENTTYPE_Product)) { + if (translated) + return "SELECT o.Value,t.Name FROM M_Product o JOIN M_Product_Trl t ON (o.M_Product_ID=t.M_Product_ID AND t.AD_Language=" + DB.TO_STRING(language)+ ") WHERE o.M_Product_ID="; + else + return "SELECT Value,Name FROM M_Product WHERE M_Product_ID="; + } else if (elementType.equals(ELEMENTTYPE_Activity)) { + if (translated) + return "SELECT Value,Name FROM C_Activity o JOIN C_Activity_Trl t ON (o.C_Activity_ID=t.C_Activity_ID AND t.AD_Language=" + DB.TO_STRING(language)+ ") WHERE o.C_Activity_ID="; + else + return "SELECT Value,Name FROM C_Activity WHERE C_Activity_ID="; + } else if ( elementType.equals(ELEMENTTYPE_LocationFrom) + || elementType.equals(ELEMENTTYPE_LocationTo)) { + return "SELECT City,Address1 FROM C_Location WHERE C_Location_ID="; + } else if (elementType.equals(ELEMENTTYPE_Campaign)) { + if (translated) + return "SELECT Value,Name FROM C_Campaign o JOIN C_Campaign_Trl t ON (o.C_Campaign_ID=t.C_Campaign_ID AND t.AD_Language=" + DB.TO_STRING(language)+ ") WHERE o.C_Campaign_ID="; + else + return "SELECT Value,Name FROM C_Campaign WHERE C_Campaign_ID="; + } else if (elementType.equals(ELEMENTTYPE_OrgTrx)) { + return "SELECT Value,Name FROM AD_Org WHERE AD_Org_ID="; + } else if (elementType.equals(ELEMENTTYPE_Project)) { + return "SELECT Value,Name FROM C_Project WHERE C_Project_ID="; + } else if (elementType.equals(ELEMENTTYPE_SalesRegion)) { + if (translated) + return "SELECT Value,Name FROM C_SalesRegion o JOIN C_SalesRegion_Trl t ON (o.C_SalesRegion_ID=t.C_SalesRegion_ID AND t.AD_Language=" + DB.TO_STRING(language)+ ") WHERE o.C_SalesRegion_ID="; // ADEMPIERE-119 / Freepath + else + return "SELECT Value,Name FROM C_SalesRegion WHERE C_SalesRegion_ID="; // ADEMPIERE-119 / Freepath + // + } else if ( elementType.equals(ELEMENTTYPE_UserColumn1) + || elementType.equals(ELEMENTTYPE_UserColumn2)) { + return null; + } + // + return ""; + } // getColumnName + + /** Logger */ + private static CLogger s_log = CLogger.getCLogger (MAcctSchemaElement.class); + + /** Cache */ + private static CCache s_cache = new CCache(Table_Name, 10); + + + /************************************************************************* + * Standard Constructor + * @param ctx context + * @param C_AcctSchema_Element_ID id + * @param trxName transaction + */ + public MAcctSchemaElement (Properties ctx, int C_AcctSchema_Element_ID, String trxName) + { + super (ctx, C_AcctSchema_Element_ID, trxName); + if (C_AcctSchema_Element_ID == 0) + { + // setC_AcctSchema_Element_ID (0); + // setC_AcctSchema_ID (0); + // setC_Element_ID (0); + // setElementType (null); + setIsBalanced (false); + setIsMandatory (false); + // setName (null); + // setOrg_ID (0); + // setSeqNo (0); + } + } // MAcctSchemaElement + + /** + * Load Constructor + * @param ctx context + * @param rs result set + * @param trxName transaction + */ + public MAcctSchemaElement (Properties ctx, ResultSet rs, String trxName) + { + super(ctx, rs, trxName); + } // MAcctSchemaElement + + /** + * Parent Constructor + * @param as accounting schema + */ + public MAcctSchemaElement (MAcctSchema as) + { + this (as.getCtx(), 0, as.get_TrxName()); + setClientOrg(as); + setC_AcctSchema_ID (as.getC_AcctSchema_ID()); + + // setC_Element_ID (0); + // setElementType (null); + // setName (null); + // setSeqNo (0); + + } // MAcctSchemaElement + + /** User Element Column Name */ + private String m_ColumnName = null; + + /** + * Set Organization Type + * @param SeqNo sequence + * @param Name name + * @param Org_ID id + */ + public void setTypeOrg (int SeqNo, String Name, int Org_ID) + { + setElementType (ELEMENTTYPE_Organization); + setSeqNo(SeqNo); + setName (Name); + setOrg_ID(Org_ID); + } // setTypeOrg + + /** + * Set Type Account + * @param SeqNo squence + * @param Name name + * @param C_Element_ID element + * @param C_ElementValue_ID element value + */ + public void setTypeAccount (int SeqNo, String Name, int C_Element_ID, int C_ElementValue_ID) + { + setElementType (ELEMENTTYPE_Account); + setSeqNo(SeqNo); + setName (Name); + setC_Element_ID (C_Element_ID); + setC_ElementValue_ID(C_ElementValue_ID); + } // setTypeAccount + + /** + * Set Type BPartner + * @param SeqNo sequence + * @param Name name + * @param C_BPartner_ID id + */ + public void setTypeBPartner (int SeqNo, String Name, int C_BPartner_ID) + { + setElementType (ELEMENTTYPE_BPartner); + setSeqNo(SeqNo); + setName (Name); + setC_BPartner_ID(C_BPartner_ID); + } // setTypeBPartner + + /** + * Set Type Product + * @param SeqNo sequence + * @param Name name + * @param M_Product_ID id + */ + public void setTypeProduct (int SeqNo, String Name, int M_Product_ID) + { + setElementType (ELEMENTTYPE_Product); + setSeqNo(SeqNo); + setName (Name); + setM_Product_ID(M_Product_ID); + } // setTypeProduct + + /** + * Set Type Project + * @param SeqNo sequence + * @param Name name + * @param C_Project_ID id + */ + public void setTypeProject (int SeqNo, String Name, int C_Project_ID) + { + setElementType (ELEMENTTYPE_Project); + setSeqNo(SeqNo); + setName (Name); + setC_Project_ID(C_Project_ID); + } // setTypeProject + + /** + * Is Element Type + * @param elementType type + * @return ELEMENTTYPE type + */ + public boolean isElementType (String elementType) + { + if (elementType == null) + return false; + return elementType.equals(getElementType()); + } // isElementType + + /** + * Get Default element value + * @return default + */ + public int getDefaultValue() + { + String elementType = getElementType(); + int defaultValue = 0; + if (elementType.equals(ELEMENTTYPE_Organization)) + defaultValue = getOrg_ID(); + else if (elementType.equals(ELEMENTTYPE_Account)) + defaultValue = getC_ElementValue_ID(); + else if (elementType.equals(ELEMENTTYPE_BPartner)) + defaultValue = getC_BPartner_ID(); + else if (elementType.equals(ELEMENTTYPE_Product)) + defaultValue = getM_Product_ID(); + else if (elementType.equals(ELEMENTTYPE_Activity)) + defaultValue = getC_Activity_ID(); + else if (elementType.equals(ELEMENTTYPE_LocationFrom)) + defaultValue = getC_Location_ID(); + else if (elementType.equals(ELEMENTTYPE_LocationTo)) + defaultValue = getC_Location_ID(); + else if (elementType.equals(ELEMENTTYPE_Campaign)) + defaultValue = getC_Campaign_ID(); + else if (elementType.equals(ELEMENTTYPE_OrgTrx)) + defaultValue = getOrg_ID(); + else if (elementType.equals(ELEMENTTYPE_Project)) + defaultValue = getC_Project_ID(); + else if (elementType.equals(ELEMENTTYPE_SalesRegion)) + defaultValue = getC_SalesRegion_ID(); + else if (elementType.equals(ELEMENTTYPE_UserElementList1)) + defaultValue = getC_ElementValue_ID(); + else if (elementType.equals(ELEMENTTYPE_UserElementList2)) + defaultValue = getC_ElementValue_ID(); + else if (elementType.equals(ELEMENTTYPE_UserColumn1)) + defaultValue = 0; + else if (elementType.equals(ELEMENTTYPE_UserColumn2)) + defaultValue = 0; + return defaultValue; + } // getDefault + + + /** + * Get Acct Fact ColumnName + * @return column name + */ + public String getColumnName() + { + String et = getElementType(); + return getColumnName(et); + } // getColumnName + + /** + * Get Display ColumnName + * @return column name + */ + public String getDisplayColumnName() + { + String et = getElementType(); + if (ELEMENTTYPE_UserColumn1.equals(et) || ELEMENTTYPE_UserColumn2.equals(et)) + { + if (m_ColumnName == null) + m_ColumnName = MColumn.getColumnName(getCtx(), getAD_Column_ID()); + return m_ColumnName; + } + return getColumnName(et); } // getDisplayColumnName - - - /** - * String representation - * @return info - */ - public String toString() - { - StringBuilder msgreturn = new StringBuilder("AcctSchemaElement[").append(get_ID()) - .append("-").append(getName()) - .append("(").append(getElementType()).append(")=").append(getDefaultValue()) - .append(",Pos=").append(getSeqNo()).append("]"); - return msgreturn.toString(); - } // toString - - - - /** - * Before Save - * @param newRecord new - * @return true if it can be saved - */ - @Override - protected boolean beforeSave (boolean newRecord) - { - if (getAD_Org_ID() != 0) - setAD_Org_ID(0); - String et = getElementType(); - if (isMandatory() && - (ELEMENTTYPE_UserElementList1.equals(et) || ELEMENTTYPE_UserElementList2.equals(et) - || ELEMENTTYPE_UserColumn1.equals(et) || ELEMENTTYPE_UserColumn2.equals(et))) - setIsMandatory(false); - // Acct Schema Elements "Account" and "Org" should be mandatory - teo_sarca BF [ 1795817 ] - if (ELEMENTTYPE_Account.equals(et) || ELEMENTTYPE_Organization.equals(et)) { - if (!isMandatory()) - setIsMandatory(true); - if (!isActive()) - setIsActive(true); - } - // - else if (isMandatory()) - { - String errorField = null; - if (ELEMENTTYPE_Account.equals(et) && getC_ElementValue_ID() == 0) - errorField = COLUMNNAME_C_ElementValue_ID; - else if (ELEMENTTYPE_Activity.equals(et) && getC_Activity_ID() == 0) - errorField = COLUMNNAME_C_Activity_ID; - else if (ELEMENTTYPE_BPartner.equals(et) && getC_BPartner_ID() == 0) - errorField = COLUMNNAME_C_BPartner_ID; - else if (ELEMENTTYPE_Campaign.equals(et) && getC_Campaign_ID() == 0) - errorField = COLUMNNAME_C_Campaign_ID; - else if (ELEMENTTYPE_LocationFrom.equals(et) && getC_Location_ID() == 0) - errorField = COLUMNNAME_C_Location_ID; - else if (ELEMENTTYPE_LocationTo.equals(et) && getC_Location_ID() == 0) - errorField = COLUMNNAME_C_Location_ID; - else if (ELEMENTTYPE_Organization.equals(et) && getOrg_ID() == 0) - errorField = COLUMNNAME_Org_ID; - else if (ELEMENTTYPE_OrgTrx.equals(et) && getOrg_ID() == 0) - errorField = COLUMNNAME_Org_ID; - else if (ELEMENTTYPE_Product.equals(et) && getM_Product_ID() == 0) - errorField = COLUMNNAME_M_Product_ID; - else if (ELEMENTTYPE_Project.equals(et) && getC_Project_ID() == 0) - errorField = COLUMNNAME_C_Project_ID; - else if (ELEMENTTYPE_SalesRegion.equals(et) && getC_SalesRegion_ID() == 0) - errorField = COLUMNNAME_C_SalesRegion_ID; - if (errorField != null) - { - log.saveError("Error", Msg.parseTranslation(getCtx(), "@IsMandatory@: @" + errorField + "@")); - return false; - } - } - // - if (getAD_Column_ID() == 0 - && (ELEMENTTYPE_UserColumn1.equals(et) || ELEMENTTYPE_UserColumn2.equals(et))) - { - log.saveError("Error", Msg.parseTranslation(getCtx(), "@IsMandatory@: @AD_Column_ID@")); - return false; - } - return true; - } // beforeSave - - /** - * After Save - * @param newRecord new - * @param success success - * @return success - */ - @Override - protected boolean afterSave (boolean newRecord, boolean success) - { - if (!success) - return success; - // Default Value - if (isMandatory() && is_ValueChanged(COLUMNNAME_IsMandatory)) - { - if (ELEMENTTYPE_Activity.equals(getElementType())) - updateData (COLUMNNAME_C_Activity_ID, getC_Activity_ID()); - else if (ELEMENTTYPE_BPartner.equals(getElementType())) - updateData (COLUMNNAME_C_BPartner_ID, getC_BPartner_ID()); - else if (ELEMENTTYPE_Product.equals(getElementType())) - updateData (COLUMNNAME_M_Product_ID, getM_Product_ID()); - else if (ELEMENTTYPE_Project.equals(getElementType())) - updateData (COLUMNNAME_C_Project_ID, getC_Project_ID()); - } - - // Clear Cache - s_cache.clear(); - - // Resequence - if (newRecord || is_ValueChanged(COLUMNNAME_SeqNo)){ - StringBuilder msguvd = new StringBuilder("AD_Client_ID=").append(getAD_Client_ID()); - MAccount.updateValueDescription(getCtx(), msguvd.toString(), get_TrxName()); - } - return success; - } // afterSave - - /** - * Update ValidCombination and Fact with mandatory value - * @param element element - * @param id new default - */ - private void updateData (String element, int id) - { - StringBuilder msguvd = new StringBuilder(element).append("=").append(id); - MAccount.updateValueDescription(getCtx(),msguvd.toString(), get_TrxName()); - // - StringBuilder sql = new StringBuilder("UPDATE C_ValidCombination SET ").append(element).append("=").append(id) - .append(" WHERE ").append(element).append(" IS NULL AND AD_Client_ID=").append(getAD_Client_ID()); - int noC = DB.executeUpdate(sql.toString(), get_TrxName()); - // - sql = new StringBuilder("UPDATE Fact_Acct SET ").append(element).append("=").append(id) - .append(" WHERE ").append(element).append(" IS NULL AND C_AcctSchema_ID=").append(getC_AcctSchema_ID()); - int noF = DB.executeUpdate(sql.toString(), get_TrxName()); - // - if (log.isLoggable(Level.FINE)) log.fine("ValidCombination=" + noC + ", Fact=" + noF); - } // updateData - - @Override - protected boolean beforeDelete () - { - String et = getElementType(); - // Acct Schema Elements "Account" and "Org" should be mandatory - teo_sarca BF [ 1795817 ] - if (ELEMENTTYPE_Account.equals(et) || ELEMENTTYPE_Organization.equals(et)) { - log.saveError("Error", Msg.parseTranslation(getCtx(), "@DeleteError@ @IsMandatory@")); - return false; - } - return true; - } - - /** - * After Delete - * @param success success - * @return success - */ - @Override - protected boolean afterDelete (boolean success) - { - if (!success) - return success; - // Update Account Info - StringBuilder msguvd = new StringBuilder("AD_Client_ID=").append(getAD_Client_ID()); - MAccount.updateValueDescription(getCtx(),msguvd.toString(), get_TrxName()); - // - s_cache.clear(); - return success; - } // afterDelete - -} // AcctSchemaElement + + + /** + * String representation + * @return info + */ + public String toString() + { + StringBuilder msgreturn = new StringBuilder("AcctSchemaElement[").append(get_ID()) + .append("-").append(getName()) + .append("(").append(getElementType()).append(")=").append(getDefaultValue()) + .append(",Pos=").append(getSeqNo()).append("]"); + return msgreturn.toString(); + } // toString + + + + /** + * Before Save + * @param newRecord new + * @return true if it can be saved + */ + @Override + protected boolean beforeSave (boolean newRecord) + { + if (getAD_Org_ID() != 0) + setAD_Org_ID(0); + String et = getElementType(); + if (isMandatory() && + (ELEMENTTYPE_UserElementList1.equals(et) || ELEMENTTYPE_UserElementList2.equals(et) + || ELEMENTTYPE_UserColumn1.equals(et) || ELEMENTTYPE_UserColumn2.equals(et))) + setIsMandatory(false); + // Acct Schema Elements "Account" and "Org" should be mandatory - teo_sarca BF [ 1795817 ] + if (ELEMENTTYPE_Account.equals(et) || ELEMENTTYPE_Organization.equals(et)) { + if (!isMandatory()) + setIsMandatory(true); + if (!isActive()) + setIsActive(true); + } + // + else if (isMandatory()) + { + String errorField = null; + if (ELEMENTTYPE_Account.equals(et) && getC_ElementValue_ID() == 0) + errorField = COLUMNNAME_C_ElementValue_ID; + else if (ELEMENTTYPE_Activity.equals(et) && getC_Activity_ID() == 0) + errorField = COLUMNNAME_C_Activity_ID; + else if (ELEMENTTYPE_BPartner.equals(et) && getC_BPartner_ID() == 0) + errorField = COLUMNNAME_C_BPartner_ID; + else if (ELEMENTTYPE_Campaign.equals(et) && getC_Campaign_ID() == 0) + errorField = COLUMNNAME_C_Campaign_ID; + else if (ELEMENTTYPE_LocationFrom.equals(et) && getC_Location_ID() == 0) + errorField = COLUMNNAME_C_Location_ID; + else if (ELEMENTTYPE_LocationTo.equals(et) && getC_Location_ID() == 0) + errorField = COLUMNNAME_C_Location_ID; + else if (ELEMENTTYPE_Organization.equals(et) && getOrg_ID() == 0) + errorField = COLUMNNAME_Org_ID; + else if (ELEMENTTYPE_OrgTrx.equals(et) && getOrg_ID() == 0) + errorField = COLUMNNAME_Org_ID; + else if (ELEMENTTYPE_Product.equals(et) && getM_Product_ID() == 0) + errorField = COLUMNNAME_M_Product_ID; + else if (ELEMENTTYPE_Project.equals(et) && getC_Project_ID() == 0) + errorField = COLUMNNAME_C_Project_ID; + else if (ELEMENTTYPE_SalesRegion.equals(et) && getC_SalesRegion_ID() == 0) + errorField = COLUMNNAME_C_SalesRegion_ID; + if (errorField != null) + { + log.saveError("Error", Msg.parseTranslation(getCtx(), "@IsMandatory@: @" + errorField + "@")); + return false; + } + } + // + if (getAD_Column_ID() == 0 + && (ELEMENTTYPE_UserColumn1.equals(et) || ELEMENTTYPE_UserColumn2.equals(et))) + { + log.saveError("Error", Msg.parseTranslation(getCtx(), "@IsMandatory@: @AD_Column_ID@")); + return false; + } + return true; + } // beforeSave + + /** + * After Save + * @param newRecord new + * @param success success + * @return success + */ + @Override + protected boolean afterSave (boolean newRecord, boolean success) + { + if (!success) + return success; + // Default Value + if (isMandatory() && is_ValueChanged(COLUMNNAME_IsMandatory)) + { + if (ELEMENTTYPE_Activity.equals(getElementType())) + updateData (COLUMNNAME_C_Activity_ID, getC_Activity_ID()); + else if (ELEMENTTYPE_BPartner.equals(getElementType())) + updateData (COLUMNNAME_C_BPartner_ID, getC_BPartner_ID()); + else if (ELEMENTTYPE_Product.equals(getElementType())) + updateData (COLUMNNAME_M_Product_ID, getM_Product_ID()); + else if (ELEMENTTYPE_Project.equals(getElementType())) + updateData (COLUMNNAME_C_Project_ID, getC_Project_ID()); + } + + // Clear Cache + s_cache.clear(); + + // Resequence + if (newRecord || is_ValueChanged(COLUMNNAME_SeqNo)){ + StringBuilder msguvd = new StringBuilder("AD_Client_ID=").append(getAD_Client_ID()); + MAccount.updateValueDescription(getCtx(), msguvd.toString(), get_TrxName()); + } + return success; + } // afterSave + + /** + * Update ValidCombination and Fact with mandatory value + * @param element element + * @param id new default + */ + private void updateData (String element, int id) + { + StringBuilder msguvd = new StringBuilder(element).append("=").append(id); + MAccount.updateValueDescription(getCtx(),msguvd.toString(), get_TrxName()); + // + StringBuilder sql = new StringBuilder("UPDATE C_ValidCombination SET ").append(element).append("=").append(id) + .append(" WHERE ").append(element).append(" IS NULL AND AD_Client_ID=").append(getAD_Client_ID()); + int noC = DB.executeUpdate(sql.toString(), get_TrxName()); + // + sql = new StringBuilder("UPDATE Fact_Acct SET ").append(element).append("=").append(id) + .append(" WHERE ").append(element).append(" IS NULL AND C_AcctSchema_ID=").append(getC_AcctSchema_ID()); + int noF = DB.executeUpdate(sql.toString(), get_TrxName()); + // + if (log.isLoggable(Level.FINE)) log.fine("ValidCombination=" + noC + ", Fact=" + noF); + } // updateData + + @Override + protected boolean beforeDelete () + { + String et = getElementType(); + // Acct Schema Elements "Account" and "Org" should be mandatory - teo_sarca BF [ 1795817 ] + if (ELEMENTTYPE_Account.equals(et) || ELEMENTTYPE_Organization.equals(et)) { + log.saveError("Error", Msg.parseTranslation(getCtx(), "@DeleteError@ @IsMandatory@")); + return false; + } + return true; + } + + /** + * After Delete + * @param success success + * @return success + */ + @Override + protected boolean afterDelete (boolean success) + { + if (!success) + return success; + // Update Account Info + StringBuilder msguvd = new StringBuilder("AD_Client_ID=").append(getAD_Client_ID()); + MAccount.updateValueDescription(getCtx(),msguvd.toString(), get_TrxName()); + // + s_cache.clear(); + return success; + } // afterDelete + +} // AcctSchemaElement diff --git a/org.adempiere.base/src/org/compiere/model/MAcctSchemaGL.java b/org.adempiere.base/src/org/compiere/model/MAcctSchemaGL.java index a2453a688f..63cf00d25e 100644 --- a/org.adempiere.base/src/org/compiere/model/MAcctSchemaGL.java +++ b/org.adempiere.base/src/org/compiere/model/MAcctSchemaGL.java @@ -1,134 +1,134 @@ -/****************************************************************************** - * 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.compiere.model; +/****************************************************************************** + * 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.compiere.model; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Properties; - -import org.compiere.util.CLogger; -import org.compiere.util.KeyNamePair; - +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Properties; - -/** - * Accounting Schema GL info - * - * @author Jorg Janke - * @version $Id: MAcctSchemaGL.java,v 1.3 2006/07/30 00:58:18 jjanke Exp $ - * @author victor.perez@e-evolution.com, www.e-evolution.com - *
  • RF [ 2214883 ] Remove SQL code and Replace for Query http://sourceforge.net/tracker/index.php?func=detail&aid=2214883&group_id=176962&atid=879335 - */ -public class MAcctSchemaGL extends X_C_AcctSchema_GL -{ - - - /** - * - */ - private static final long serialVersionUID = 5303102649110271896L; - - - /** - * Get Accounting Schema GL Info - * @param ctx context - * @param C_AcctSchema_ID id - * @return defaults - */ - public static MAcctSchemaGL get (Properties ctx, int C_AcctSchema_ID) +import org.compiere.util.CLogger; +import org.compiere.util.KeyNamePair; + + + +/** + * Accounting Schema GL info + * + * @author Jorg Janke + * @version $Id: MAcctSchemaGL.java,v 1.3 2006/07/30 00:58:18 jjanke Exp $ + * @author victor.perez@e-evolution.com, www.e-evolution.com + *
  • RF [ 2214883 ] Remove SQL code and Replace for Query http://sourceforge.net/tracker/index.php?func=detail&aid=2214883&group_id=176962&atid=879335 + */ +public class MAcctSchemaGL extends X_C_AcctSchema_GL +{ + + + /** + * + */ + private static final long serialVersionUID = 5303102649110271896L; + + + /** + * Get Accounting Schema GL Info + * @param ctx context + * @param C_AcctSchema_ID id + * @return defaults + */ + public static MAcctSchemaGL get (Properties ctx, int C_AcctSchema_ID) { - final String whereClause = "C_AcctSchema_ID=?"; - return new Query(ctx,I_C_AcctSchema_GL.Table_Name,whereClause,null) - .setParameters(C_AcctSchema_ID) + final String whereClause = "C_AcctSchema_ID=?"; + return new Query(ctx,I_C_AcctSchema_GL.Table_Name,whereClause,null) + .setParameters(C_AcctSchema_ID) .firstOnly(); - } // get - - /** Logger */ - protected static CLogger s_log = CLogger.getCLogger(MAcctSchemaGL.class); - - - /** - * Load Constructor - * @param ctx context - * @param C_AcctSchema_ID AcctSchema - * @param trxName transaction - */ - public MAcctSchemaGL (Properties ctx, int C_AcctSchema_ID, String trxName) - { - super(ctx, C_AcctSchema_ID, trxName); - if (C_AcctSchema_ID == 0) - { - setUseCurrencyBalancing (false); - setUseSuspenseBalancing (false); - setUseSuspenseError (false); - } - } // MAcctSchemaGL - - /** - * Load Constructor - * @param ctx context - * @param rs result set - * @param trxName transaction - */ - public MAcctSchemaGL (Properties ctx, ResultSet rs, String trxName) - { - super(ctx, rs, trxName); - } // MAcctSchemaGL - - /** - * Get Acct Info list - * @return list - */ - public ArrayList getAcctInfo() - { - ArrayList list = new ArrayList(); - for (int i = 0; i < get_ColumnCount(); i++) - { - String columnName = get_ColumnName(i); - if (columnName.endsWith("Acct")) - { - int id = ((Integer)get_Value(i)); - list.add(new KeyNamePair (id, columnName)); - } - } - return list; - } // getAcctInfo - - /** - * Set Value (don't use) - * @param columnName column name - * @param value value - * @return true if set - */ - public boolean setValue (String columnName, Integer value) - { - return super.set_Value (columnName, value); - } // setValue - - /** - * Before Save - * @param newRecord new - * @return true - */ - protected boolean beforeSave (boolean newRecord) - { - if (getAD_Org_ID() != 0) - setAD_Org_ID(0); - return true; - } // beforeSave - -} // MAcctSchemaGL + } // get + + /** Logger */ + protected static CLogger s_log = CLogger.getCLogger(MAcctSchemaGL.class); + + + /** + * Load Constructor + * @param ctx context + * @param C_AcctSchema_ID AcctSchema + * @param trxName transaction + */ + public MAcctSchemaGL (Properties ctx, int C_AcctSchema_ID, String trxName) + { + super(ctx, C_AcctSchema_ID, trxName); + if (C_AcctSchema_ID == 0) + { + setUseCurrencyBalancing (false); + setUseSuspenseBalancing (false); + setUseSuspenseError (false); + } + } // MAcctSchemaGL + + /** + * Load Constructor + * @param ctx context + * @param rs result set + * @param trxName transaction + */ + public MAcctSchemaGL (Properties ctx, ResultSet rs, String trxName) + { + super(ctx, rs, trxName); + } // MAcctSchemaGL + + /** + * Get Acct Info list + * @return list + */ + public ArrayList getAcctInfo() + { + ArrayList list = new ArrayList(); + for (int i = 0; i < get_ColumnCount(); i++) + { + String columnName = get_ColumnName(i); + if (columnName.endsWith("Acct")) + { + int id = ((Integer)get_Value(i)); + list.add(new KeyNamePair (id, columnName)); + } + } + return list; + } // getAcctInfo + + /** + * Set Value (don't use) + * @param columnName column name + * @param value value + * @return true if set + */ + public boolean setValue (String columnName, Integer value) + { + return super.set_Value (columnName, value); + } // setValue + + /** + * Before Save + * @param newRecord new + * @return true + */ + protected boolean beforeSave (boolean newRecord) + { + if (getAD_Org_ID() != 0) + setAD_Org_ID(0); + return true; + } // beforeSave + +} // MAcctSchemaGL diff --git a/org.adempiere.base/src/org/compiere/model/MAsset.java b/org.adempiere.base/src/org/compiere/model/MAsset.java index d0ee05e5b0..709abfe1b8 100644 --- a/org.adempiere.base/src/org/compiere/model/MAsset.java +++ b/org.adempiere.base/src/org/compiere/model/MAsset.java @@ -1,616 +1,616 @@ -package org.compiere.model; - -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Properties; -import java.util.logging.Level; - -import javax.servlet.http.HttpServletRequest; - -import org.compiere.util.DB; -import org.compiere.util.EMail; -import org.compiere.util.Env; -import org.compiere.util.Msg; - -/** - * Asset Model - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - */ -@SuppressWarnings("serial") -public class MAsset extends X_A_Asset - //implements MAssetType.Model //commented by @win -{ - /** ChangeType - Asset Group changed */ - public static final int CHANGETYPE_setAssetGroup = Table_ID * 100 + 1; - - /** - * Get Asset - * @param ctx context - * @param A_Asset_ID asset - * @param trxName - */ - public static MAsset get (Properties ctx, int A_Asset_ID, String trxName) - { - return (MAsset)MTable.get(ctx, MAsset.Table_Name).getPO(A_Asset_ID, trxName); - } // get - - /** - * Get Assets from given M_Product_ID and M_ASI_ID. - *

    Note: The A_Asset_Product table is not checked !!! - * @param ctx - * @param M_Product_ID (optional) - * @param M_ASI_ID - * @return array of MAsset - */ - public static Collection forASI(Properties ctx, int M_Product_ID, int M_ASI_ID) - { - ArrayList params = new ArrayList(); - String whereClause = COLUMNNAME_M_AttributeSetInstance_ID + "=?"; - params.add(M_ASI_ID); - if (M_Product_ID > 0) { - whereClause += " AND " + COLUMNNAME_M_Product_ID + "=?"; - params.add(M_Product_ID); - } - // - return new Query(ctx, MAsset.Table_Name, whereClause, null) - .setParameters(params) - .list(); - } - - /** Create constructor */ - public MAsset (Properties ctx, int A_Asset_ID, String trxName) - { - super (ctx, A_Asset_ID,trxName); - if (A_Asset_ID == 0) - { - setA_Asset_Status(A_ASSET_STATUS_New); - //commented out by @win - /* - setA_Asset_Type("MFX"); - setA_Asset_Type_ID(1); // MFX - */ - //end comment by @win - } - } // MAsset - - /** - * Load Constructor - * @param ctx context - * @param rs result set record - */ - public MAsset (Properties ctx, ResultSet rs, String trxName) - { - super (ctx, rs, trxName); - } // MAsset - - /** - * Construct from MMatchInv - * @param match match invoice - */ - protected MAsset (MMatchInv match) - { - this(match.getCtx(), 0, match.get_TrxName()); - - MInvoiceLine invoiceLine = new MInvoiceLine(getCtx(), match.getC_InvoiceLine_ID(), get_TrxName()); - MInOutLine inoutLine = new MInOutLine(getCtx(), match.getM_InOutLine_ID(), get_TrxName()); - - setIsOwned(true); - setIsInPosession(true); - setA_Asset_CreateDate(inoutLine.getM_InOut().getMovementDate()); - - // Asset Group: - int A_Asset_Group_ID = invoiceLine.getA_Asset_Group_ID(); - MProduct product = MProduct.get(getCtx(), invoiceLine.getM_Product_ID()); - if (A_Asset_Group_ID <= 0) { - A_Asset_Group_ID = product.getA_Asset_Group_ID(); +package org.compiere.model; + +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Properties; +import java.util.logging.Level; + +import javax.servlet.http.HttpServletRequest; + +import org.compiere.util.DB; +import org.compiere.util.EMail; +import org.compiere.util.Env; +import org.compiere.util.Msg; + +/** + * Asset Model + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + */ +@SuppressWarnings("serial") +public class MAsset extends X_A_Asset + //implements MAssetType.Model //commented by @win +{ + /** ChangeType - Asset Group changed */ + public static final int CHANGETYPE_setAssetGroup = Table_ID * 100 + 1; + + /** + * Get Asset + * @param ctx context + * @param A_Asset_ID asset + * @param trxName + */ + public static MAsset get (Properties ctx, int A_Asset_ID, String trxName) + { + return (MAsset)MTable.get(ctx, MAsset.Table_Name).getPO(A_Asset_ID, trxName); + } // get + + /** + * Get Assets from given M_Product_ID and M_ASI_ID. + *

    Note: The A_Asset_Product table is not checked !!! + * @param ctx + * @param M_Product_ID (optional) + * @param M_ASI_ID + * @return array of MAsset + */ + public static Collection forASI(Properties ctx, int M_Product_ID, int M_ASI_ID) + { + ArrayList params = new ArrayList(); + String whereClause = COLUMNNAME_M_AttributeSetInstance_ID + "=?"; + params.add(M_ASI_ID); + if (M_Product_ID > 0) { + whereClause += " AND " + COLUMNNAME_M_Product_ID + "=?"; + params.add(M_Product_ID); + } + // + return new Query(ctx, MAsset.Table_Name, whereClause, null) + .setParameters(params) + .list(); + } + + /** Create constructor */ + public MAsset (Properties ctx, int A_Asset_ID, String trxName) + { + super (ctx, A_Asset_ID,trxName); + if (A_Asset_ID == 0) + { + setA_Asset_Status(A_ASSET_STATUS_New); + //commented out by @win + /* + setA_Asset_Type("MFX"); + setA_Asset_Type_ID(1); // MFX + */ + //end comment by @win + } + } // MAsset + + /** + * Load Constructor + * @param ctx context + * @param rs result set record + */ + public MAsset (Properties ctx, ResultSet rs, String trxName) + { + super (ctx, rs, trxName); + } // MAsset + + /** + * Construct from MMatchInv + * @param match match invoice + */ + protected MAsset (MMatchInv match) + { + this(match.getCtx(), 0, match.get_TrxName()); + + MInvoiceLine invoiceLine = new MInvoiceLine(getCtx(), match.getC_InvoiceLine_ID(), get_TrxName()); + MInOutLine inoutLine = new MInOutLine(getCtx(), match.getM_InOutLine_ID(), get_TrxName()); + + setIsOwned(true); + setIsInPosession(true); + setA_Asset_CreateDate(inoutLine.getM_InOut().getMovementDate()); + + // Asset Group: + int A_Asset_Group_ID = invoiceLine.getA_Asset_Group_ID(); + MProduct product = MProduct.get(getCtx(), invoiceLine.getM_Product_ID()); + if (A_Asset_Group_ID <= 0) { + A_Asset_Group_ID = product.getA_Asset_Group_ID(); } setA_Asset_Group_ID(A_Asset_Group_ID); - setHelp(Msg.getMsg(MClient.get(getCtx()).getAD_Language(), "CreatedFromInvoiceLine", - new Object[] {invoiceLine.getC_Invoice().getDocumentNo(), invoiceLine.getLine()})); - - String name = ""; - if (inoutLine.getM_Product_ID()>0) - { - name += product.getName() + "-"; - setM_Product_ID(inoutLine.getM_Product_ID()); - setM_AttributeSetInstance_ID(inoutLine.getM_AttributeSetInstance_ID()); - } - MBPartner bp = new MBPartner(getCtx(), invoiceLine.getC_Invoice().getC_BPartner_ID(), null); - name += bp.getName()+"-"+invoiceLine.getC_Invoice().getDocumentNo(); - if (log.isLoggable(Level.FINE)) log.fine("name=" + name); - setValue(name); - setName(name); - setDescription(invoiceLine.getDescription()); - } - - /** - * Construct from MIFixedAsset (import) - * @param match match invoice - */ - protected MAsset (MIFixedAsset ifa) - { - this(ifa.getCtx(), 0, ifa.get_TrxName()); - - setAD_Org_ID(ifa.getAD_Org_ID()); //added by @win - setIsOwned(true); - setIsInPosession(true); - - String inventoryNo = ifa.getInventoryNo(); - if (inventoryNo != null) { - inventoryNo = inventoryNo.trim(); - setInventoryNo(inventoryNo); - setValue(inventoryNo); - } - setA_Asset_CreateDate(ifa.getAssetServiceDate()); - //setAssetServiceDate(ifa.getAssetServiceDate()); //commented by @win - /* commented by @win - setA_Asset_Class_ID(ifa.getA_Asset_Class_ID()); - */ // commented by @win - MProduct product = ifa.getProduct(); - if (product != null) { - setM_Product_ID(product.getM_Product_ID()); - setA_Asset_Group_ID(ifa.getA_Asset_Group_ID()); - MAttributeSetInstance asi = MAttributeSetInstance.create(getCtx(), product, get_TrxName()); - setM_AttributeSetInstance_ID(asi.getM_AttributeSetInstance_ID()); - } - - setDateAcct(ifa.getDateAcct()); - setName(ifa.getName()); - setDescription(ifa.getDescription()); - } - - /** - * @author Edwin Ang - * @param project - */ - protected MAsset (MProject project) - { - this(project.getCtx(), 0, project.get_TrxName()); - setIsOwned(true); - setIsInPosession(true); - setA_Asset_CreateDate(new Timestamp(System.currentTimeMillis())); - setHelp(Msg.getMsg(MClient.get(getCtx()).getAD_Language(), "CreatedFromProject", new Object[] { project.getName()})); - setDateAcct(new Timestamp(System.currentTimeMillis())); - setDescription(project.getDescription()); - } - - public MAsset(MInOut mInOut, MInOutLine sLine, int deliveryCount) { - this(mInOut.getCtx(), 0, mInOut.get_TrxName()); - setIsOwned(false); - setIsInPosession(false); - setA_Asset_CreateDate(new Timestamp(System.currentTimeMillis())); - setHelp(Msg.getMsg(MClient.get(getCtx()).getAD_Language(), "CreatedFromShipment: ", new Object[] { mInOut.getDocumentNo()})); - setDateAcct(new Timestamp(System.currentTimeMillis())); - setDescription(sLine.getDescription()); - - } - - /** - * Create Asset from Inventory - * @param inventory inventory - * @param invLine inventory line - * @param deliveryCount 0 or number of delivery - * @return A_Asset_ID - */ - - public MAsset (MInventory inventory, MInventoryLine invLine, BigDecimal qty, BigDecimal costs) - { - super(invLine.getCtx(), 0, invLine.get_TrxName()); - setClientOrg(invLine); - - MProduct product = MProduct.get(getCtx(), invLine.getM_Product_ID()); - // Defaults from group: - MAssetGroup assetGroup = MAssetGroup.get(invLine.getCtx(), invLine.getM_Product().getM_Product_Category().getA_Asset_Group_ID()); - if (assetGroup == null) - assetGroup = MAssetGroup.get(invLine.getCtx(), product.getA_Asset_Group_ID()); - setAssetGroup(assetGroup); - - - //setValue(prod) - setName(product.getName()); - setHelp(invLine.getDescription()); - // Header - setAssetServiceDate(inventory.getMovementDate()); - setIsOwned(true); - setIsInPosession(true); - - // Product - setM_Product_ID(product.getM_Product_ID()); - // Guarantee & Version - //setGuaranteeDate(TimeUtil.addDays(shipment.getMovementDate(), product.getGuaranteeDays())); - setVersionNo(product.getVersionNo()); - // ASI - if (invLine.getM_AttributeSetInstance_ID() != 0) - { - MAttributeSetInstance asi = new MAttributeSetInstance (getCtx(), invLine.getM_AttributeSetInstance_ID(), get_TrxName()); - setASI(asi); - } - //setSerNo(invLine.getSerNo()); - setQty(qty); - - // Costs: - //setA_Asset_Cost(costs); //commented by @win, set at asset addition - - // Activity - /* - if (invLine.getC_Activity_ID() > 0) - setC_Activity_ID(invLine.getC_Activity_ID()); - */ - if (inventory.getC_Activity_ID() > 0) - setC_Activity_ID(inventory.getC_Activity_ID()); - - // - - if (MAssetType.isFixedAsset(this)) { - setA_Asset_Status(A_ASSET_STATUS_New); - } - else { - setA_Asset_Status(A_ASSET_STATUS_Activated); - setProcessed(true); - } - - //added by @win - setA_Asset_Status(A_ASSET_STATUS_New); - //end added by @win - - - } - - /** - * Set Asset Group; also it sets other default fields - * @param assetGroup - */ - public void setAssetGroup(MAssetGroup assetGroup) { - setA_Asset_Group_ID(assetGroup.getA_Asset_Group_ID()); - - /* commented out by @win - setA_Asset_Type_ID(assetGroup.getA_Asset_Type_ID()); - setGZ_TipComponenta(assetGroup.getGZ_TipComponenta()); // TODO: move to GZ - MAssetType assetType = MAssetType.get(getCtx(), assetGroup.getA_Asset_Type_ID()); - assetType.update(SetGetUtil.wrap(this), true); - */ //end commet by @win - } - - public MAssetGroup getAssetGroup() { - return MAssetGroup.get(getCtx(), getA_Asset_Group_ID()); - } - - /** - * Set ASI Info (M_AttributeSetInstance_ID, Lot, SerNo) - * @param asi - */ - public void setASI(MAttributeSetInstance asi) { - setM_AttributeSetInstance_ID(asi.getM_AttributeSetInstance_ID()); - setLot(asi.getLot()); - setSerNo(asi.getSerNo()); - } - - /** - * Before Save - * @param newRecord new - * @return true - */ - - protected boolean beforeSave (boolean newRecord) - { - // Set parent asset: - if (getA_Parent_Asset_ID() <= 0) - { - setA_Parent_Asset_ID(getA_Asset_ID()); - } - // Fix inventory number: - String invNo = getInventoryNo(); - if(invNo != null) - { - setInventoryNo(invNo.trim()); - } - // If no asset group, than set the default one: - if(getA_Asset_Group_ID() <= 0) - { - setA_Asset_Group_ID(MAssetGroup.getDefault_ID(SetGetUtil.wrap(this))); - } - /* @win temporary commented out - - if (getA_Asset_Class_ID() <= 0 && getA_Asset_Group_ID() > 0) - { - MAssetGroup.updateAsset(SetGetUtil.wrap(this), getA_Asset_Group_ID()); - } - */ - //end @win comment - - // Copy fields from C_BPartner_Location - if (is_ValueChanged(COLUMNNAME_C_BPartner_Location_ID) && getC_BPartner_Location_ID() > 0) - { - // Goodwill BF: Error: org.compiere.model.MAsset cannot be cast to org.compiere.model.SetGetModel - SetGetUtil.copyValues(SetGetUtil.wrap(this), MBPartnerLocation.Table_Name, getC_BPartner_Location_ID(), - new String[]{MBPartnerLocation.COLUMNNAME_C_Location_ID} - ); - } - // - // Create ASI if not exist: - if (getM_Product_ID() > 0 && getM_AttributeSetInstance_ID() <= 0) - { - MProduct product = MProduct.get(getCtx(), getM_Product_ID()); - MAttributeSetInstance asi = new MAttributeSetInstance(getCtx(), 0, product.getM_AttributeSet_ID(), get_TrxName()); - asi.setSerNo(getSerNo()); - asi.setDescription(); - asi.saveEx(); - setM_AttributeSetInstance_ID(asi.getM_AttributeSetInstance_ID()); - } - // TODO: With the lines below, after creating the asset, the whole system goes much slower ??? -// else if (is_ValueChanged(COLUMNNAME_SerNo) && getM_AttributeSetInstance_ID() > 0) { -// asi = new MAttributeSetInstance(getCtx(), getM_AttributeSetInstance_ID(), get_TrxName()); -// asi.setSerNo(getSerNo()); -// asi.setDescription(); -// asi.saveEx(); -// } -// else if ((newRecord || is_ValueChanged(COLUMNNAME_M_AttributeSetInstance_ID)) && getM_AttributeSetInstance_ID() > 0) { -// asi = new MAttributeSetInstance(getCtx(), getM_AttributeSetInstance_ID(), get_TrxName()); -// setASI(asi); -// } - // + setHelp(Msg.getMsg(MClient.get(getCtx()).getAD_Language(), "CreatedFromInvoiceLine", + new Object[] {invoiceLine.getC_Invoice().getDocumentNo(), invoiceLine.getLine()})); - // Update status - updateStatus(); - - // Validate AssetType - //@win commented out - //MAssetType.validate(this); - //@win end - // - - return true; - } // beforeSave - - - protected boolean afterSave (boolean newRecord, boolean success) - { - if(!success) - { - return success; - } - - // - // Set parent - if(getA_Parent_Asset_ID() <= 0) - { - int A_Asset_ID = getA_Asset_ID(); - setA_Parent_Asset_ID(A_Asset_ID); - DB.executeUpdateEx("UPDATE A_Asset SET A_Parent_Asset_ID=A_Asset_ID WHERE A_Asset_ID=" + A_Asset_ID, get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("A_Parent_Asset_ID=" + getA_Parent_Asset_ID()); - } - - // - // Set inventory number: - String invNo = getInventoryNo(); - if(invNo == null || invNo.trim().length() == 0) - { - invNo = "" + get_ID(); - setInventoryNo(invNo); - DB.executeUpdateEx("UPDATE A_Asset SET InventoryNo=" + DB.TO_STRING(invNo) + " WHERE A_Asset_ID=" + getA_Asset_ID(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("InventoryNo=" + getInventoryNo()); + String name = ""; + if (inoutLine.getM_Product_ID()>0) + { + name += product.getName() + "-"; + setM_Product_ID(inoutLine.getM_Product_ID()); + setM_AttributeSetInstance_ID(inoutLine.getM_AttributeSetInstance_ID()); } - - - // If new record, create accounting and workfile - if (newRecord) - { - //@win: set value at asset group as default value for asset - MAssetGroup assetgroup = new MAssetGroup(getCtx(), getA_Asset_Group_ID(), get_TrxName()); - String isDepreciated = (assetgroup.isDepreciated()) ? "Y" : "N"; - String isOwned = (assetgroup.isOwned()) ? "Y" : "N"; - setIsDepreciated(assetgroup.isDepreciated()); - setIsOwned(assetgroup.isOwned()); - DB.executeUpdateEx("UPDATE A_Asset SET IsDepreciated='" + isDepreciated + "', isOwned ='" + isOwned + "' WHERE A_Asset_ID=" + getA_Asset_ID(), get_TrxName()); - //end @win - - // for each asset group acounting create an asset accounting and a workfile too - for (MAssetGroupAcct assetgrpacct : MAssetGroupAcct.forA_Asset_Group_ID(getCtx(), getA_Asset_Group_ID())) - { - // Asset Accounting - MAssetAcct assetacct = new MAssetAcct(this, assetgrpacct); - assetacct.setAD_Org_ID(getAD_Org_ID()); //added by @win - assetacct.saveEx(); - - // Asset Depreciation Workfile - MDepreciationWorkfile assetwk = new MDepreciationWorkfile(this, assetacct.getPostingType(), assetgrpacct); - assetwk.setAD_Org_ID(getAD_Org_ID()); //added by @win - assetwk.setUseLifeYears(0); - assetwk.setUseLifeMonths(0); - assetwk.setUseLifeYears_F(0); - assetwk.setUseLifeMonths_F(0); - assetwk.saveEx(); - - // Change Log - MAssetChange.createAndSave(getCtx(), "CRT", new PO[]{this, assetwk, assetacct}, null); - } - - } - else - { - MAssetChange.createAndSave(getCtx(), "UPD", new PO[]{this}, null); - } - - // - // Update child.IsDepreciated flag - if (!newRecord && is_ValueChanged(COLUMNNAME_IsDepreciated)) - { - final String sql = "UPDATE " + MDepreciationWorkfile.Table_Name - +" SET " + MDepreciationWorkfile.COLUMNNAME_IsDepreciated+"=?" - +" WHERE " + MDepreciationWorkfile.COLUMNNAME_A_Asset_ID+"=?"; - DB.executeUpdateEx(sql, new Object[]{isDepreciated(), getA_Asset_ID()}, get_TrxName()); - } - - return true; - } // afterSave - - - protected boolean beforeDelete() - { - // delete addition - { - String sql = "DELETE FROM "+MAssetAddition.Table_Name+" WHERE "+MAssetAddition.COLUMNNAME_Processed+"=? AND "+MAssetAddition.COLUMNNAME_A_Asset_ID+"=?"; - int no = DB.executeUpdateEx(sql, new Object[]{false, getA_Asset_ID()}, get_TrxName()); - if (log.isLoggable(Level.INFO)) log.info("@A_Asset_Addition@ @Deleted@ #" + no); - } - // - // update invoice line - { - final String sql = "UPDATE "+MInvoiceLine.Table_Name+" SET " - +" "+MInvoiceLine.COLUMNNAME_A_Asset_ID+"=?" - +","+MInvoiceLine.COLUMNNAME_A_Processed+"=?" - +" WHERE "+MInvoiceLine.COLUMNNAME_A_Asset_ID+"=?"; - int no = DB.executeUpdateEx(sql, new Object[]{null, false, getA_Asset_ID()}, get_TrxName()); - if (log.isLoggable(Level.INFO)) log.info("@C_InvoiceLine@ @Updated@ #" + no); - } - return true; - } // beforeDelete - - /** - * - * @see #beforeSave(boolean) - */ - public void updateStatus() - { - String status = getA_Asset_Status(); - setProcessed(!status.equals(A_ASSET_STATUS_New)); -// setIsDisposed(!status.equals(A_ASSET_STATUS_New) && !status.equals(A_ASSET_STATUS_Activated)); - setIsDisposed(status.equals(A_ASSET_STATUS_Disposed)); - setIsFullyDepreciated(status.equals(A_ASSET_STATUS_Depreciated)); - if(isFullyDepreciated() || status.equals(A_ASSET_STATUS_Disposed)) - { - setIsDepreciated(false); - } - /* commented by @win - MAssetClass assetClass = MAssetClass.get(getCtx(), getA_Asset_Class_ID()); - if (assetClass != null && assetClass.isDepreciated()) - { - setIsDepreciated(true); - } - */ //end comment by @win - if (status.equals(A_ASSET_STATUS_Activated) || getAssetActivationDate() == null) - { - setAssetActivationDate(getAssetServiceDate()); - } - } - - /** - * Change asset status to newStatus - * @param newStatus see A_ASSET_STATUS_ - * @param date state change date; if null context "#Date" will be used - */ - public void changeStatus(String newStatus, Timestamp date) - { - String status = getA_Asset_Status(); - if (log.isLoggable(Level.FINEST)) log.finest("Entering: " + status + "->" + newStatus + ", date=" + date); - - // - // If date is null, use context #Date - if(date == null) { - date = Env.getContextAsDate(getCtx(), "#Date"); - } - - // - // Activation/Addition - if(newStatus.equals(A_ASSET_STATUS_Activated)) - { - setAssetActivationDate(date); - } - // - // Preservation - if(newStatus.equals(A_ASSET_STATUS_Preservation)) - { - setAssetDisposalDate(date); - // TODO: move to MAsetDisposal - Collection workFiles = MDepreciationWorkfile.forA_Asset_ID(getCtx(), getA_Asset_ID(), get_TrxName()); - for(MDepreciationWorkfile assetwk : workFiles) { - assetwk.truncDepreciation(); - assetwk.saveEx(); - } - } - // Disposal - if(newStatus.equals(A_ASSET_STATUS_Disposed)) - { // casat, vandut - setAssetDisposalDate(date); - } - - // Set new status - setA_Asset_Status(newStatus); - } // changeStatus - - // Temporary used variables: - /** */ - private int m_UseLifeMonths_F = 0; - public int getUseLifeMonths_F() { return m_UseLifeMonths_F; } - public void setUseLifeMonths_F(int UseLifeMonths_F) { m_UseLifeMonths_F = UseLifeMonths_F; } - /** */ - private int m_A_Current_Period = 0; - public int getA_Current_Period() { return m_A_Current_Period; } - public void setA_Current_Period(int A_Current_Period) { m_A_Current_Period = A_Current_Period; } - /** */ - private Timestamp m_DateAcct = null; - public Timestamp getDateAcct() { return m_DateAcct; } - public void setDateAcct(Timestamp DateAcct) { m_DateAcct = DateAcct; } - /** */ - private int m_A_Depreciation_ID = 0; - public int getA_Depreciation_ID() { return m_A_Depreciation_ID; } - public void setA_Depreciation_ID(int A_Depreciation_ID) { m_A_Depreciation_ID = A_Depreciation_ID; } - /** */ - private int m_A_Depreciation_F_ID = 0; - public int getA_Depreciation_F_ID() { return m_A_Depreciation_F_ID; } - public void setA_Depreciation_F_ID(int A_Depreciation_F_ID) { m_A_Depreciation_F_ID = A_Depreciation_F_ID; } - /** */ - private BigDecimal m_A_Asset_Cost = Env.ZERO; - private BigDecimal m_A_Accumulated_Depr = Env.ZERO; - private BigDecimal m_A_Accumulated_Depr_F = Env.ZERO; - public BigDecimal getA_Asset_Cost() { return m_A_Asset_Cost; } - public void setA_Asset_Cost(BigDecimal A_Asset_Cost) { m_A_Asset_Cost = A_Asset_Cost; } - public BigDecimal getA_Accumulated_Depr() { return m_A_Accumulated_Depr; } - public void setA_Accumulated_Depr(BigDecimal A_Accumulated_Depr) { m_A_Accumulated_Depr = A_Accumulated_Depr; } - public BigDecimal getA_Accumulated_Depr_F() { return m_A_Accumulated_Depr_F; } - public void setA_Accumulated_Depr_F(BigDecimal A_Accumulated_Depr_F) { m_A_Accumulated_Depr_F = A_Accumulated_Depr_F; } - - public MAssetDelivery confirmDelivery(EMail email, int ad_User_ID) { - // TODO Auto-generated method stub - return null; - } - - public MProductDownload[] getProductDownloads() { - // TODO Auto-generated method stub - return null; - } - - public MAssetDelivery confirmDelivery(HttpServletRequest request, - int ad_User_ID) { - // TODO Auto-generated method stub - return null; - } - - public MAssetDelivery[] getDeliveries() { - // TODO Auto-generated method stub - return null; - } - - public static MAsset getFromShipment(Properties ctx, int i, String trxName) { - // TODO Auto-generated method stub - return null; - } - - public int getProductR_MailText_ID() { - // IDEMPIERE-197 Stabilize Fixed Assets - // AssetDelivery is requiring this missing column - // TODO: Adding this method to compile correctly and future research, - // but the process AssetDelivery will fail with error "** Product Mail Text" - return 0; - } - - public boolean isDownloadable() { - // IDEMPIERE-197 Stabilize Fixed Assets - // AssetServlet is requiring this missing column - // TODO: Adding this method to compile correctly and future research - return false; - } -} + MBPartner bp = new MBPartner(getCtx(), invoiceLine.getC_Invoice().getC_BPartner_ID(), null); + name += bp.getName()+"-"+invoiceLine.getC_Invoice().getDocumentNo(); + if (log.isLoggable(Level.FINE)) log.fine("name=" + name); + setValue(name); + setName(name); + setDescription(invoiceLine.getDescription()); + } + + /** + * Construct from MIFixedAsset (import) + * @param match match invoice + */ + protected MAsset (MIFixedAsset ifa) + { + this(ifa.getCtx(), 0, ifa.get_TrxName()); + + setAD_Org_ID(ifa.getAD_Org_ID()); //added by @win + setIsOwned(true); + setIsInPosession(true); + + String inventoryNo = ifa.getInventoryNo(); + if (inventoryNo != null) { + inventoryNo = inventoryNo.trim(); + setInventoryNo(inventoryNo); + setValue(inventoryNo); + } + setA_Asset_CreateDate(ifa.getAssetServiceDate()); + //setAssetServiceDate(ifa.getAssetServiceDate()); //commented by @win + /* commented by @win + setA_Asset_Class_ID(ifa.getA_Asset_Class_ID()); + */ // commented by @win + MProduct product = ifa.getProduct(); + if (product != null) { + setM_Product_ID(product.getM_Product_ID()); + setA_Asset_Group_ID(ifa.getA_Asset_Group_ID()); + MAttributeSetInstance asi = MAttributeSetInstance.create(getCtx(), product, get_TrxName()); + setM_AttributeSetInstance_ID(asi.getM_AttributeSetInstance_ID()); + } + + setDateAcct(ifa.getDateAcct()); + setName(ifa.getName()); + setDescription(ifa.getDescription()); + } + + /** + * @author Edwin Ang + * @param project + */ + protected MAsset (MProject project) + { + this(project.getCtx(), 0, project.get_TrxName()); + setIsOwned(true); + setIsInPosession(true); + setA_Asset_CreateDate(new Timestamp(System.currentTimeMillis())); + setHelp(Msg.getMsg(MClient.get(getCtx()).getAD_Language(), "CreatedFromProject", new Object[] { project.getName()})); + setDateAcct(new Timestamp(System.currentTimeMillis())); + setDescription(project.getDescription()); + } + + public MAsset(MInOut mInOut, MInOutLine sLine, int deliveryCount) { + this(mInOut.getCtx(), 0, mInOut.get_TrxName()); + setIsOwned(false); + setIsInPosession(false); + setA_Asset_CreateDate(new Timestamp(System.currentTimeMillis())); + setHelp(Msg.getMsg(MClient.get(getCtx()).getAD_Language(), "CreatedFromShipment: ", new Object[] { mInOut.getDocumentNo()})); + setDateAcct(new Timestamp(System.currentTimeMillis())); + setDescription(sLine.getDescription()); + + } + + /** + * Create Asset from Inventory + * @param inventory inventory + * @param invLine inventory line + * @param deliveryCount 0 or number of delivery + * @return A_Asset_ID + */ + + public MAsset (MInventory inventory, MInventoryLine invLine, BigDecimal qty, BigDecimal costs) + { + super(invLine.getCtx(), 0, invLine.get_TrxName()); + setClientOrg(invLine); + + MProduct product = MProduct.get(getCtx(), invLine.getM_Product_ID()); + // Defaults from group: + MAssetGroup assetGroup = MAssetGroup.get(invLine.getCtx(), invLine.getM_Product().getM_Product_Category().getA_Asset_Group_ID()); + if (assetGroup == null) + assetGroup = MAssetGroup.get(invLine.getCtx(), product.getA_Asset_Group_ID()); + setAssetGroup(assetGroup); + + + //setValue(prod) + setName(product.getName()); + setHelp(invLine.getDescription()); + // Header + setAssetServiceDate(inventory.getMovementDate()); + setIsOwned(true); + setIsInPosession(true); + + // Product + setM_Product_ID(product.getM_Product_ID()); + // Guarantee & Version + //setGuaranteeDate(TimeUtil.addDays(shipment.getMovementDate(), product.getGuaranteeDays())); + setVersionNo(product.getVersionNo()); + // ASI + if (invLine.getM_AttributeSetInstance_ID() != 0) + { + MAttributeSetInstance asi = new MAttributeSetInstance (getCtx(), invLine.getM_AttributeSetInstance_ID(), get_TrxName()); + setASI(asi); + } + //setSerNo(invLine.getSerNo()); + setQty(qty); + + // Costs: + //setA_Asset_Cost(costs); //commented by @win, set at asset addition + + // Activity + /* + if (invLine.getC_Activity_ID() > 0) + setC_Activity_ID(invLine.getC_Activity_ID()); + */ + if (inventory.getC_Activity_ID() > 0) + setC_Activity_ID(inventory.getC_Activity_ID()); + + // + + if (MAssetType.isFixedAsset(this)) { + setA_Asset_Status(A_ASSET_STATUS_New); + } + else { + setA_Asset_Status(A_ASSET_STATUS_Activated); + setProcessed(true); + } + + //added by @win + setA_Asset_Status(A_ASSET_STATUS_New); + //end added by @win + + + } + + /** + * Set Asset Group; also it sets other default fields + * @param assetGroup + */ + public void setAssetGroup(MAssetGroup assetGroup) { + setA_Asset_Group_ID(assetGroup.getA_Asset_Group_ID()); + + /* commented out by @win + setA_Asset_Type_ID(assetGroup.getA_Asset_Type_ID()); + setGZ_TipComponenta(assetGroup.getGZ_TipComponenta()); // TODO: move to GZ + MAssetType assetType = MAssetType.get(getCtx(), assetGroup.getA_Asset_Type_ID()); + assetType.update(SetGetUtil.wrap(this), true); + */ //end commet by @win + } + + public MAssetGroup getAssetGroup() { + return MAssetGroup.get(getCtx(), getA_Asset_Group_ID()); + } + + /** + * Set ASI Info (M_AttributeSetInstance_ID, Lot, SerNo) + * @param asi + */ + public void setASI(MAttributeSetInstance asi) { + setM_AttributeSetInstance_ID(asi.getM_AttributeSetInstance_ID()); + setLot(asi.getLot()); + setSerNo(asi.getSerNo()); + } + + /** + * Before Save + * @param newRecord new + * @return true + */ + + protected boolean beforeSave (boolean newRecord) + { + // Set parent asset: + if (getA_Parent_Asset_ID() <= 0) + { + setA_Parent_Asset_ID(getA_Asset_ID()); + } + // Fix inventory number: + String invNo = getInventoryNo(); + if(invNo != null) + { + setInventoryNo(invNo.trim()); + } + // If no asset group, than set the default one: + if(getA_Asset_Group_ID() <= 0) + { + setA_Asset_Group_ID(MAssetGroup.getDefault_ID(SetGetUtil.wrap(this))); + } + /* @win temporary commented out + + if (getA_Asset_Class_ID() <= 0 && getA_Asset_Group_ID() > 0) + { + MAssetGroup.updateAsset(SetGetUtil.wrap(this), getA_Asset_Group_ID()); + } + */ + //end @win comment + + // Copy fields from C_BPartner_Location + if (is_ValueChanged(COLUMNNAME_C_BPartner_Location_ID) && getC_BPartner_Location_ID() > 0) + { + // Goodwill BF: Error: org.compiere.model.MAsset cannot be cast to org.compiere.model.SetGetModel + SetGetUtil.copyValues(SetGetUtil.wrap(this), MBPartnerLocation.Table_Name, getC_BPartner_Location_ID(), + new String[]{MBPartnerLocation.COLUMNNAME_C_Location_ID} + ); + } + // + // Create ASI if not exist: + if (getM_Product_ID() > 0 && getM_AttributeSetInstance_ID() <= 0) + { + MProduct product = MProduct.get(getCtx(), getM_Product_ID()); + MAttributeSetInstance asi = new MAttributeSetInstance(getCtx(), 0, product.getM_AttributeSet_ID(), get_TrxName()); + asi.setSerNo(getSerNo()); + asi.setDescription(); + asi.saveEx(); + setM_AttributeSetInstance_ID(asi.getM_AttributeSetInstance_ID()); + } + // TODO: With the lines below, after creating the asset, the whole system goes much slower ??? +// else if (is_ValueChanged(COLUMNNAME_SerNo) && getM_AttributeSetInstance_ID() > 0) { +// asi = new MAttributeSetInstance(getCtx(), getM_AttributeSetInstance_ID(), get_TrxName()); +// asi.setSerNo(getSerNo()); +// asi.setDescription(); +// asi.saveEx(); +// } +// else if ((newRecord || is_ValueChanged(COLUMNNAME_M_AttributeSetInstance_ID)) && getM_AttributeSetInstance_ID() > 0) { +// asi = new MAttributeSetInstance(getCtx(), getM_AttributeSetInstance_ID(), get_TrxName()); +// setASI(asi); +// } + // + + // Update status + updateStatus(); + + // Validate AssetType + //@win commented out + //MAssetType.validate(this); + //@win end + // + + return true; + } // beforeSave + + + protected boolean afterSave (boolean newRecord, boolean success) + { + if(!success) + { + return success; + } + + // + // Set parent + if(getA_Parent_Asset_ID() <= 0) + { + int A_Asset_ID = getA_Asset_ID(); + setA_Parent_Asset_ID(A_Asset_ID); + DB.executeUpdateEx("UPDATE A_Asset SET A_Parent_Asset_ID=A_Asset_ID WHERE A_Asset_ID=" + A_Asset_ID, get_TrxName()); + if (log.isLoggable(Level.FINE)) log.fine("A_Parent_Asset_ID=" + getA_Parent_Asset_ID()); + } + + // + // Set inventory number: + String invNo = getInventoryNo(); + if(invNo == null || invNo.trim().length() == 0) + { + invNo = "" + get_ID(); + setInventoryNo(invNo); + DB.executeUpdateEx("UPDATE A_Asset SET InventoryNo=" + DB.TO_STRING(invNo) + " WHERE A_Asset_ID=" + getA_Asset_ID(), get_TrxName()); + if (log.isLoggable(Level.FINE)) log.fine("InventoryNo=" + getInventoryNo()); + } + + + // If new record, create accounting and workfile + if (newRecord) + { + //@win: set value at asset group as default value for asset + MAssetGroup assetgroup = new MAssetGroup(getCtx(), getA_Asset_Group_ID(), get_TrxName()); + String isDepreciated = (assetgroup.isDepreciated()) ? "Y" : "N"; + String isOwned = (assetgroup.isOwned()) ? "Y" : "N"; + setIsDepreciated(assetgroup.isDepreciated()); + setIsOwned(assetgroup.isOwned()); + DB.executeUpdateEx("UPDATE A_Asset SET IsDepreciated='" + isDepreciated + "', isOwned ='" + isOwned + "' WHERE A_Asset_ID=" + getA_Asset_ID(), get_TrxName()); + //end @win + + // for each asset group acounting create an asset accounting and a workfile too + for (MAssetGroupAcct assetgrpacct : MAssetGroupAcct.forA_Asset_Group_ID(getCtx(), getA_Asset_Group_ID())) + { + // Asset Accounting + MAssetAcct assetacct = new MAssetAcct(this, assetgrpacct); + assetacct.setAD_Org_ID(getAD_Org_ID()); //added by @win + assetacct.saveEx(); + + // Asset Depreciation Workfile + MDepreciationWorkfile assetwk = new MDepreciationWorkfile(this, assetacct.getPostingType(), assetgrpacct); + assetwk.setAD_Org_ID(getAD_Org_ID()); //added by @win + assetwk.setUseLifeYears(0); + assetwk.setUseLifeMonths(0); + assetwk.setUseLifeYears_F(0); + assetwk.setUseLifeMonths_F(0); + assetwk.saveEx(); + + // Change Log + MAssetChange.createAndSave(getCtx(), "CRT", new PO[]{this, assetwk, assetacct}, null); + } + + } + else + { + MAssetChange.createAndSave(getCtx(), "UPD", new PO[]{this}, null); + } + + // + // Update child.IsDepreciated flag + if (!newRecord && is_ValueChanged(COLUMNNAME_IsDepreciated)) + { + final String sql = "UPDATE " + MDepreciationWorkfile.Table_Name + +" SET " + MDepreciationWorkfile.COLUMNNAME_IsDepreciated+"=?" + +" WHERE " + MDepreciationWorkfile.COLUMNNAME_A_Asset_ID+"=?"; + DB.executeUpdateEx(sql, new Object[]{isDepreciated(), getA_Asset_ID()}, get_TrxName()); + } + + return true; + } // afterSave + + + protected boolean beforeDelete() + { + // delete addition + { + String sql = "DELETE FROM "+MAssetAddition.Table_Name+" WHERE "+MAssetAddition.COLUMNNAME_Processed+"=? AND "+MAssetAddition.COLUMNNAME_A_Asset_ID+"=?"; + int no = DB.executeUpdateEx(sql, new Object[]{false, getA_Asset_ID()}, get_TrxName()); + if (log.isLoggable(Level.INFO)) log.info("@A_Asset_Addition@ @Deleted@ #" + no); + } + // + // update invoice line + { + final String sql = "UPDATE "+MInvoiceLine.Table_Name+" SET " + +" "+MInvoiceLine.COLUMNNAME_A_Asset_ID+"=?" + +","+MInvoiceLine.COLUMNNAME_A_Processed+"=?" + +" WHERE "+MInvoiceLine.COLUMNNAME_A_Asset_ID+"=?"; + int no = DB.executeUpdateEx(sql, new Object[]{null, false, getA_Asset_ID()}, get_TrxName()); + if (log.isLoggable(Level.INFO)) log.info("@C_InvoiceLine@ @Updated@ #" + no); + } + return true; + } // beforeDelete + + /** + * + * @see #beforeSave(boolean) + */ + public void updateStatus() + { + String status = getA_Asset_Status(); + setProcessed(!status.equals(A_ASSET_STATUS_New)); +// setIsDisposed(!status.equals(A_ASSET_STATUS_New) && !status.equals(A_ASSET_STATUS_Activated)); + setIsDisposed(status.equals(A_ASSET_STATUS_Disposed)); + setIsFullyDepreciated(status.equals(A_ASSET_STATUS_Depreciated)); + if(isFullyDepreciated() || status.equals(A_ASSET_STATUS_Disposed)) + { + setIsDepreciated(false); + } + /* commented by @win + MAssetClass assetClass = MAssetClass.get(getCtx(), getA_Asset_Class_ID()); + if (assetClass != null && assetClass.isDepreciated()) + { + setIsDepreciated(true); + } + */ //end comment by @win + if (status.equals(A_ASSET_STATUS_Activated) || getAssetActivationDate() == null) + { + setAssetActivationDate(getAssetServiceDate()); + } + } + + /** + * Change asset status to newStatus + * @param newStatus see A_ASSET_STATUS_ + * @param date state change date; if null context "#Date" will be used + */ + public void changeStatus(String newStatus, Timestamp date) + { + String status = getA_Asset_Status(); + if (log.isLoggable(Level.FINEST)) log.finest("Entering: " + status + "->" + newStatus + ", date=" + date); + + // + // If date is null, use context #Date + if(date == null) { + date = Env.getContextAsDate(getCtx(), "#Date"); + } + + // + // Activation/Addition + if(newStatus.equals(A_ASSET_STATUS_Activated)) + { + setAssetActivationDate(date); + } + // + // Preservation + if(newStatus.equals(A_ASSET_STATUS_Preservation)) + { + setAssetDisposalDate(date); + // TODO: move to MAsetDisposal + Collection workFiles = MDepreciationWorkfile.forA_Asset_ID(getCtx(), getA_Asset_ID(), get_TrxName()); + for(MDepreciationWorkfile assetwk : workFiles) { + assetwk.truncDepreciation(); + assetwk.saveEx(); + } + } + // Disposal + if(newStatus.equals(A_ASSET_STATUS_Disposed)) + { // casat, vandut + setAssetDisposalDate(date); + } + + // Set new status + setA_Asset_Status(newStatus); + } // changeStatus + + // Temporary used variables: + /** */ + private int m_UseLifeMonths_F = 0; + public int getUseLifeMonths_F() { return m_UseLifeMonths_F; } + public void setUseLifeMonths_F(int UseLifeMonths_F) { m_UseLifeMonths_F = UseLifeMonths_F; } + /** */ + private int m_A_Current_Period = 0; + public int getA_Current_Period() { return m_A_Current_Period; } + public void setA_Current_Period(int A_Current_Period) { m_A_Current_Period = A_Current_Period; } + /** */ + private Timestamp m_DateAcct = null; + public Timestamp getDateAcct() { return m_DateAcct; } + public void setDateAcct(Timestamp DateAcct) { m_DateAcct = DateAcct; } + /** */ + private int m_A_Depreciation_ID = 0; + public int getA_Depreciation_ID() { return m_A_Depreciation_ID; } + public void setA_Depreciation_ID(int A_Depreciation_ID) { m_A_Depreciation_ID = A_Depreciation_ID; } + /** */ + private int m_A_Depreciation_F_ID = 0; + public int getA_Depreciation_F_ID() { return m_A_Depreciation_F_ID; } + public void setA_Depreciation_F_ID(int A_Depreciation_F_ID) { m_A_Depreciation_F_ID = A_Depreciation_F_ID; } + /** */ + private BigDecimal m_A_Asset_Cost = Env.ZERO; + private BigDecimal m_A_Accumulated_Depr = Env.ZERO; + private BigDecimal m_A_Accumulated_Depr_F = Env.ZERO; + public BigDecimal getA_Asset_Cost() { return m_A_Asset_Cost; } + public void setA_Asset_Cost(BigDecimal A_Asset_Cost) { m_A_Asset_Cost = A_Asset_Cost; } + public BigDecimal getA_Accumulated_Depr() { return m_A_Accumulated_Depr; } + public void setA_Accumulated_Depr(BigDecimal A_Accumulated_Depr) { m_A_Accumulated_Depr = A_Accumulated_Depr; } + public BigDecimal getA_Accumulated_Depr_F() { return m_A_Accumulated_Depr_F; } + public void setA_Accumulated_Depr_F(BigDecimal A_Accumulated_Depr_F) { m_A_Accumulated_Depr_F = A_Accumulated_Depr_F; } + + public MAssetDelivery confirmDelivery(EMail email, int ad_User_ID) { + // TODO Auto-generated method stub + return null; + } + + public MProductDownload[] getProductDownloads() { + // TODO Auto-generated method stub + return null; + } + + public MAssetDelivery confirmDelivery(HttpServletRequest request, + int ad_User_ID) { + // TODO Auto-generated method stub + return null; + } + + public MAssetDelivery[] getDeliveries() { + // TODO Auto-generated method stub + return null; + } + + public static MAsset getFromShipment(Properties ctx, int i, String trxName) { + // TODO Auto-generated method stub + return null; + } + + public int getProductR_MailText_ID() { + // IDEMPIERE-197 Stabilize Fixed Assets + // AssetDelivery is requiring this missing column + // TODO: Adding this method to compile correctly and future research, + // but the process AssetDelivery will fail with error "** Product Mail Text" + return 0; + } + + public boolean isDownloadable() { + // IDEMPIERE-197 Stabilize Fixed Assets + // AssetServlet is requiring this missing column + // TODO: Adding this method to compile correctly and future research + return false; + } +} diff --git a/org.adempiere.base/src/org/compiere/model/MAssetChange.java b/org.adempiere.base/src/org/compiere/model/MAssetChange.java index cf5fd482a6..8b6f93ade4 100644 --- a/org.adempiere.base/src/org/compiere/model/MAssetChange.java +++ b/org.adempiere.base/src/org/compiere/model/MAssetChange.java @@ -1,150 +1,150 @@ -/****************************************************************************** - * The contents of this file are subject to the Compiere License Version 1.1 - * ("License"); You may not use this file except in compliance with the License - * You may obtain a copy of the License at http://www.compiere.org/license.html - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - * the specific language governing rights and limitations under the License. - * The Original Code is Compiere ERP & CRM Smart Business Solution - * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc. - * Portions created by Jorg Janke are Copyright (C) 1999-2003 Jorg Janke, parts - * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved. - * Contributor(s): ______________________________________. - *****************************************************************************/ -package org.compiere.model; - -import java.sql.ResultSet; -import java.util.Properties; -import java.util.logging.Level; - -import org.compiere.model.MRefList; -import org.compiere.model.PO; -import org.compiere.util.CLogger; - -/** - * Asset Addition Model - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - * - */ -public class MAssetChange extends X_A_Asset_Change -{ - /** - * - */ - private static final long serialVersionUID = 4083373951793617528L; - - /** Static Logger */ - private static CLogger s_log = CLogger.getCLogger(MAssetChange.class); - - /** - * Default Constructor - * @param ctx context - * @param M_InventoryLine_ID line - */ - public MAssetChange (Properties ctx, int A_Asset_Change_ID, String trxName) - { - super (ctx, A_Asset_Change_ID, trxName); - } // MAssetChange - - /** - * Load Constructor - * @param ctx context - * @param rs result set - */ - public MAssetChange (Properties ctx, ResultSet rs, String trxName) - { - super (ctx, rs, trxName); - } // MInventoryLine - - /** - * Before Save - * @param newRecord new - * @return true - */ - protected boolean beforeSave (boolean newRecord) - { - String textDetails = getTextDetails(); - if (textDetails == null || textDetails.length() == 0) { - setTextDetails(MRefList.getListDescription (getCtx(),"A_Update_Type" , getChangeType())); - } - return true; - } // beforeSave - - public static MAssetChange createAddition(MAssetAddition assetAdd, MDepreciationWorkfile assetwk) { - MAssetChange change = new MAssetChange (assetAdd.getCtx(), 0, assetAdd.get_TrxName()); - change.setAD_Org_ID(assetAdd.getAD_Org_ID()); //@win added - change.setA_Asset_ID(assetAdd.getA_Asset_ID()); - change.setA_QTY_Current(assetAdd.getA_QTY_Current()); - change.setChangeType("ADD"); - change.setTextDetails(MRefList.getListDescription (assetAdd.getCtx(),"A_Update_Type" , "ADD")); - change.setPostingType(assetwk.getPostingType()); - change.setAssetValueAmt(assetAdd.getAssetValueAmt()); - change.setA_QTY_Current(assetAdd.getA_QTY_Current()); - change.saveEx(); - - return change; - } - - public static MAssetChange create(Properties ctx, String changeType, PO[] pos, String trxName) { - return create(ctx, changeType, pos, false, trxName); - } - - /** - * TODO - * @param ctx - * @param changeType - * @param pos - * @param trxName - * @return - */ - public static MAssetChange createAndSave(Properties ctx, String changeType, PO[] pos, String trxName) { - return null; - //~ return create(ctx, changeType, pos, true, trxName); - } - - public static MAssetChange create(Properties ctx, String changeType, PO[] pos, boolean save, String trxName) { - if (s_log.isLoggable(Level.FINE)) s_log.fine("Entering: changeType=" + changeType); - if (pos == null || pos.length == 0) { - s_log.fine("Entering/Leaving: POs is empty"); - return null; - } - MAssetChange change = new MAssetChange (ctx, 0, trxName); - change.setChangeType(changeType); - for (PO po : pos) { - change.addChanges(po); - } - if (save) { - change.saveEx(); - } - // - if (s_log.isLoggable(Level.FINE)) s_log.fine("Leaving: change=" + change); - return change; - } - - public void addChanges(PO po) { - if (log.isLoggable(Level.FINE)) log.fine("Entering: po=" + po); - if (po == null) { - return; - } - /* arhipac: teo_sarca: TODO need to integrate - for(int idx = 0; idx < po.get_ColumnCount_P(); idx++) { - //~ if(!po.is_ValueChanged(idx)) { - //~ continue; - //~ } - String colName = po.get_ColumnName_P(idx); - int idx2 = get_ColumnIndex(colName); - if(idx2 < 0) { - if(CLogMgt.isLevelFine()) log.fine("Setting " + colName + ": SKIP (idx2 < 0)"); - continue; - } - - Object value = po.get_Value(idx2); - set_Value(colName, value); - if(CLogMgt.isLevelFine()) log.fine("Setting " + colName + "=" + value + " (from " + po.getClass() + ", idx=" + idx + ", idx2=" + idx2 + ")"); - } - */ - // - if (log.isLoggable(Level.FINE)) log.fine("Leaving: po=" + po); - } +/****************************************************************************** + * The contents of this file are subject to the Compiere License Version 1.1 + * ("License"); You may not use this file except in compliance with the License + * You may obtain a copy of the License at http://www.compiere.org/license.html + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * The Original Code is Compiere ERP & CRM Smart Business Solution + * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc. + * Portions created by Jorg Janke are Copyright (C) 1999-2003 Jorg Janke, parts + * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved. + * Contributor(s): ______________________________________. + *****************************************************************************/ +package org.compiere.model; + +import java.sql.ResultSet; +import java.util.Properties; +import java.util.logging.Level; + +import org.compiere.model.MRefList; +import org.compiere.model.PO; +import org.compiere.util.CLogger; + +/** + * Asset Addition Model + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + * + */ +public class MAssetChange extends X_A_Asset_Change +{ + /** + * + */ + private static final long serialVersionUID = 4083373951793617528L; + + /** Static Logger */ + private static CLogger s_log = CLogger.getCLogger(MAssetChange.class); + + /** + * Default Constructor + * @param ctx context + * @param M_InventoryLine_ID line + */ + public MAssetChange (Properties ctx, int A_Asset_Change_ID, String trxName) + { + super (ctx, A_Asset_Change_ID, trxName); + } // MAssetChange + + /** + * Load Constructor + * @param ctx context + * @param rs result set + */ + public MAssetChange (Properties ctx, ResultSet rs, String trxName) + { + super (ctx, rs, trxName); + } // MInventoryLine + + /** + * Before Save + * @param newRecord new + * @return true + */ + protected boolean beforeSave (boolean newRecord) + { + String textDetails = getTextDetails(); + if (textDetails == null || textDetails.length() == 0) { + setTextDetails(MRefList.getListDescription (getCtx(),"A_Update_Type" , getChangeType())); + } + return true; + } // beforeSave + + public static MAssetChange createAddition(MAssetAddition assetAdd, MDepreciationWorkfile assetwk) { + MAssetChange change = new MAssetChange (assetAdd.getCtx(), 0, assetAdd.get_TrxName()); + change.setAD_Org_ID(assetAdd.getAD_Org_ID()); //@win added + change.setA_Asset_ID(assetAdd.getA_Asset_ID()); + change.setA_QTY_Current(assetAdd.getA_QTY_Current()); + change.setChangeType("ADD"); + change.setTextDetails(MRefList.getListDescription (assetAdd.getCtx(),"A_Update_Type" , "ADD")); + change.setPostingType(assetwk.getPostingType()); + change.setAssetValueAmt(assetAdd.getAssetValueAmt()); + change.setA_QTY_Current(assetAdd.getA_QTY_Current()); + change.saveEx(); + + return change; + } + + public static MAssetChange create(Properties ctx, String changeType, PO[] pos, String trxName) { + return create(ctx, changeType, pos, false, trxName); + } + + /** + * TODO + * @param ctx + * @param changeType + * @param pos + * @param trxName + * @return + */ + public static MAssetChange createAndSave(Properties ctx, String changeType, PO[] pos, String trxName) { + return null; + //~ return create(ctx, changeType, pos, true, trxName); + } + + public static MAssetChange create(Properties ctx, String changeType, PO[] pos, boolean save, String trxName) { + if (s_log.isLoggable(Level.FINE)) s_log.fine("Entering: changeType=" + changeType); + if (pos == null || pos.length == 0) { + s_log.fine("Entering/Leaving: POs is empty"); + return null; + } + MAssetChange change = new MAssetChange (ctx, 0, trxName); + change.setChangeType(changeType); + for (PO po : pos) { + change.addChanges(po); + } + if (save) { + change.saveEx(); + } + // + if (s_log.isLoggable(Level.FINE)) s_log.fine("Leaving: change=" + change); + return change; + } + + public void addChanges(PO po) { + if (log.isLoggable(Level.FINE)) log.fine("Entering: po=" + po); + if (po == null) { + return; + } + /* arhipac: teo_sarca: TODO need to integrate + for(int idx = 0; idx < po.get_ColumnCount_P(); idx++) { + //~ if(!po.is_ValueChanged(idx)) { + //~ continue; + //~ } + String colName = po.get_ColumnName_P(idx); + int idx2 = get_ColumnIndex(colName); + if(idx2 < 0) { + if(CLogMgt.isLevelFine()) log.fine("Setting " + colName + ": SKIP (idx2 < 0)"); + continue; + } + + Object value = po.get_Value(idx2); + set_Value(colName, value); + if(CLogMgt.isLevelFine()) log.fine("Setting " + colName + "=" + value + " (from " + po.getClass() + ", idx=" + idx + ", idx2=" + idx2 + ")"); + } + */ + // + if (log.isLoggable(Level.FINE)) log.fine("Leaving: po=" + po); + } /** ARHIPAC: TEO: END ------------------------------------------------------------------ */ } // MAssetChange \ No newline at end of file diff --git a/org.adempiere.base/src/org/compiere/model/MBPBankAccount.java b/org.adempiere.base/src/org/compiere/model/MBPBankAccount.java index 4a5ea08b21..042e6d1c5f 100644 --- a/org.adempiere.base/src/org/compiere/model/MBPBankAccount.java +++ b/org.adempiere.base/src/org/compiere/model/MBPBankAccount.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -15,71 +15,71 @@ * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; - -import java.sql.ResultSet; -import java.util.List; -import java.util.Properties; - -import org.adempiere.util.PaymentUtil; -import org.compiere.util.CLogger; -import org.compiere.util.Env; -import org.compiere.util.IBAN; -import org.compiere.util.Msg; -import org.compiere.util.Util; - -/** - * BP Bank Account Model + +import java.sql.ResultSet; +import java.util.List; +import java.util.Properties; + +import org.adempiere.util.PaymentUtil; +import org.compiere.util.CLogger; +import org.compiere.util.Env; +import org.compiere.util.IBAN; +import org.compiere.util.Msg; +import org.compiere.util.Util; + +/** + * BP Bank Account Model * * @author Jorg Janke * @version $Id: MBPBankAccount.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $ - */ -public class MBPBankAccount extends X_C_BP_BankAccount -{ - /** - * - */ - private static final long serialVersionUID = 6826961806519015878L; - - /** - * Get Accounts Of BPartner - * @param ctx context - * @param C_BPartner_ID bpartner - * @return - */ - public static MBPBankAccount[] getOfBPartner (Properties ctx, int C_BPartner_ID) - { - final String whereClause = MBPBankAccount.COLUMNNAME_C_BPartner_ID+"=?"; - Listlist = new Query(ctx,I_C_BP_BankAccount.Table_Name,whereClause,null) - .setParameters(C_BPartner_ID) - .setOnlyActiveRecords(true) - .list(); - - MBPBankAccount[] retValue = new MBPBankAccount[list.size()]; - list.toArray(retValue); - return retValue; - } // getOfBPartner - - /** Logger */ - @SuppressWarnings("unused") - private static CLogger s_log = CLogger.getCLogger(MBPBankAccount.class); - - /************************************************************************** - * Constructor - * @param ctx context - * @param C_BP_BankAccount_ID BP bank account + */ +public class MBPBankAccount extends X_C_BP_BankAccount +{ + /** + * + */ + private static final long serialVersionUID = 6826961806519015878L; + + /** + * Get Accounts Of BPartner + * @param ctx context + * @param C_BPartner_ID bpartner + * @return + */ + public static MBPBankAccount[] getOfBPartner (Properties ctx, int C_BPartner_ID) + { + final String whereClause = MBPBankAccount.COLUMNNAME_C_BPartner_ID+"=?"; + Listlist = new Query(ctx,I_C_BP_BankAccount.Table_Name,whereClause,null) + .setParameters(C_BPartner_ID) + .setOnlyActiveRecords(true) + .list(); + + MBPBankAccount[] retValue = new MBPBankAccount[list.size()]; + list.toArray(retValue); + return retValue; + } // getOfBPartner + + /** Logger */ + @SuppressWarnings("unused") + private static CLogger s_log = CLogger.getCLogger(MBPBankAccount.class); + + /************************************************************************** + * Constructor + * @param ctx context + * @param C_BP_BankAccount_ID BP bank account * @param trxName transaction */ public MBPBankAccount (Properties ctx, int C_BP_BankAccount_ID, String trxName) { super (ctx, C_BP_BankAccount_ID, trxName); if (C_BP_BankAccount_ID == 0) - { - // setC_BPartner_ID (0); - setIsACH (false); - setBPBankAcctUse(BPBANKACCTUSE_Both); - } - } // MBP_BankAccount - + { + // setC_BPartner_ID (0); + setIsACH (false); + setBPBankAcctUse(BPBANKACCTUSE_Both); + } + } // MBP_BankAccount + /** * Constructor * @param ctx context @@ -97,13 +97,13 @@ public class MBPBankAccount extends X_C_BP_BankAccount * @param bp BP * @param bpc BP Contact * @param location Location - */ - public MBPBankAccount (Properties ctx, MBPartner bp, MUser bpc, MLocation location) - { - this(ctx, 0, bp.get_TrxName()); - setIsACH (false); - // - setC_BPartner_ID(bp.getC_BPartner_ID()); + */ + public MBPBankAccount (Properties ctx, MBPartner bp, MUser bpc, MLocation location) + { + this(ctx, 0, bp.get_TrxName()); + setIsACH (false); + // + setC_BPartner_ID(bp.getC_BPartner_ID()); // setA_Name(bpc.getName()); setA_EMail(bpc.getEMail()); @@ -112,125 +112,125 @@ public class MBPBankAccount extends X_C_BP_BankAccount setA_City(location.getCity()); setA_Zip(location.getPostal()); setA_State(location.getRegionName(true)); - setA_Country(location.getCountryName()); - } // MBP_BankAccount - - /** Bank Link */ - private MBank m_bank = null; - - /** - * Is Direct Deposit - * @return true if dd - */ - public boolean isDirectDeposit() - { - if (!isACH()) - return false; - String s = getBPBankAcctUse(); - if (s == null) - return true; - return (s.equals(BPBANKACCTUSE_Both) || s.equals(BPBANKACCTUSE_DirectDeposit)); - } // isDirectDeposit - - /** - * Is Direct Debit - * @return true if dd - */ - public boolean isDirectDebit() - { - if (!isACH()) - return false; - String s = getBPBankAcctUse(); - if (s == null) - return true; - return (s.equals(BPBANKACCTUSE_Both) || s.equals(BPBANKACCTUSE_DirectDebit)); - } // isDirectDebit - - - /** - * Get Bank - * @return bank - */ - public MBank getBank() - { - int C_Bank_ID = getC_Bank_ID(); - if (C_Bank_ID == 0) - return null; - if (m_bank == null) - m_bank = new MBank (getCtx(), C_Bank_ID, get_TrxName()); - return m_bank; - } // getBank - - /** - * Get Routing No - * @return routing No - */ - public String getRoutingNo() - { - MBank bank = getBank(); - String rt = super.getRoutingNo(); - if (bank != null) - rt = bank.getRoutingNo(); - return rt; - } // getRoutingNo - - /** - * Get SwiftCode - * @return SwiftCode - */ - public String getSwiftCode() - { - MBank bank = getBank(); - if (bank != null) - return bank.getSwiftCode(); - return null; - } // getSwiftCode - - /** - * Before Save - * @param newRecord new - * @return true - */ - protected boolean beforeSave(boolean newRecord) - { - // maintain routing on bank level - if (isACH() && getBank() != null) - setRoutingNo(null); - // - if (getCreditCardNumber() != null) - { - String encrpytedCCNo = PaymentUtil.encrpytCreditCard(getCreditCardNumber()); - if (!encrpytedCCNo.equals(getCreditCardNumber())) - setCreditCardNumber(encrpytedCCNo); - } - - if (getCreditCardVV() != null) - { - String encrpytedCvv = PaymentUtil.encrpytCvv(getCreditCardVV()); - if (!encrpytedCvv.equals(getCreditCardVV())) - setCreditCardVV(encrpytedCvv); - } - - if (MSysConfig.getBooleanValue(MSysConfig.IBAN_VALIDATION, true, Env.getAD_Client_ID(Env.getCtx()))) { - if (!Util.isEmpty(getIBAN())) { - setIBAN(IBAN.normalizeIBAN(getIBAN())); - if (!IBAN.isValid(getIBAN())) { - log.saveError("Error", Msg.getMsg(getCtx(), "InvalidIBAN")); - return false; - } - } - } - - return true; - } // beforeSave - - /** - * String Representation - * @return info - */ + setA_Country(location.getCountryName()); + } // MBP_BankAccount + + /** Bank Link */ + private MBank m_bank = null; + + /** + * Is Direct Deposit + * @return true if dd + */ + public boolean isDirectDeposit() + { + if (!isACH()) + return false; + String s = getBPBankAcctUse(); + if (s == null) + return true; + return (s.equals(BPBANKACCTUSE_Both) || s.equals(BPBANKACCTUSE_DirectDeposit)); + } // isDirectDeposit + + /** + * Is Direct Debit + * @return true if dd + */ + public boolean isDirectDebit() + { + if (!isACH()) + return false; + String s = getBPBankAcctUse(); + if (s == null) + return true; + return (s.equals(BPBANKACCTUSE_Both) || s.equals(BPBANKACCTUSE_DirectDebit)); + } // isDirectDebit + + + /** + * Get Bank + * @return bank + */ + public MBank getBank() + { + int C_Bank_ID = getC_Bank_ID(); + if (C_Bank_ID == 0) + return null; + if (m_bank == null) + m_bank = new MBank (getCtx(), C_Bank_ID, get_TrxName()); + return m_bank; + } // getBank + + /** + * Get Routing No + * @return routing No + */ + public String getRoutingNo() + { + MBank bank = getBank(); + String rt = super.getRoutingNo(); + if (bank != null) + rt = bank.getRoutingNo(); + return rt; + } // getRoutingNo + + /** + * Get SwiftCode + * @return SwiftCode + */ + public String getSwiftCode() + { + MBank bank = getBank(); + if (bank != null) + return bank.getSwiftCode(); + return null; + } // getSwiftCode + + /** + * Before Save + * @param newRecord new + * @return true + */ + protected boolean beforeSave(boolean newRecord) + { + // maintain routing on bank level + if (isACH() && getBank() != null) + setRoutingNo(null); + // + if (getCreditCardNumber() != null) + { + String encrpytedCCNo = PaymentUtil.encrpytCreditCard(getCreditCardNumber()); + if (!encrpytedCCNo.equals(getCreditCardNumber())) + setCreditCardNumber(encrpytedCCNo); + } + + if (getCreditCardVV() != null) + { + String encrpytedCvv = PaymentUtil.encrpytCvv(getCreditCardVV()); + if (!encrpytedCvv.equals(getCreditCardVV())) + setCreditCardVV(encrpytedCvv); + } + + if (MSysConfig.getBooleanValue(MSysConfig.IBAN_VALIDATION, true, Env.getAD_Client_ID(Env.getCtx()))) { + if (!Util.isEmpty(getIBAN())) { + setIBAN(IBAN.normalizeIBAN(getIBAN())); + if (!IBAN.isValid(getIBAN())) { + log.saveError("Error", Msg.getMsg(getCtx(), "InvalidIBAN")); + return false; + } + } + } + + return true; + } // beforeSave + + /** + * String Representation + * @return info + */ public String toString () { - StringBuilder sb = new StringBuilder ("MBP_BankAccount[") + StringBuilder sb = new StringBuilder ("MBP_BankAccount[") .append (get_ID ()) .append(", Name=").append(getA_Name()) .append ("]"); diff --git a/org.adempiere.base/src/org/compiere/model/MCash.java b/org.adempiere.base/src/org/compiere/model/MCash.java index 501fc0a77a..71c8b29225 100644 --- a/org.adempiere.base/src/org/compiere/model/MCash.java +++ b/org.adempiere.base/src/org/compiere/model/MCash.java @@ -1,862 +1,862 @@ -/****************************************************************************** - * 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.compiere.model; - -import java.io.File; -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.Timestamp; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; - -import org.compiere.process.DocAction; -import org.compiere.process.DocumentEngine; -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.compiere.util.TimeUtil; - -/** - * Cash Journal Model - * - * @author Jorg Janke +/****************************************************************************** + * 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.compiere.model; + +import java.io.File; +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.sql.Timestamp; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import org.compiere.process.DocAction; +import org.compiere.process.DocumentEngine; +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.compiere.util.TimeUtil; + +/** + * Cash Journal Model + * + * @author Jorg Janke * @version $Id: MCash.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $ - * @author victor.perez@e-evolution.com, e-Evolution http://www.e-evolution.com - *
  • FR [ 1866214 ] - * @see http://sourceforge.net/tracker/index.php?func=detail&aid=1866214&group_id=176962&atid=879335 - *
  • FR [ 2520591 ] Support multiples calendar for Org - * @see http://sourceforge.net/tracker2/?func=detail&atid=879335&aid=2520591&group_id=176962 - * @author Teo Sarca, SC ARHIPAC SERVICE SRL + * @author victor.perez@e-evolution.com, e-Evolution http://www.e-evolution.com + *
  • FR [ 1866214 ] + * @see http://sourceforge.net/tracker/index.php?func=detail&aid=1866214&group_id=176962&atid=879335 + *
  • FR [ 2520591 ] Support multiples calendar for Org + * @see http://sourceforge.net/tracker2/?func=detail&atid=879335&aid=2520591&group_id=176962 + * @author Teo Sarca, SC ARHIPAC SERVICE SRL *
  • BF [ 1831997 ] Cash journal allocation reversed - *
  • BF [ 1894524 ] Pay an reversed invoice - *
  • BF [ 1899477 ] MCash.getLines should return only active lines - *
  • BF [ 2588326 ] Cash Lines are not correctly updated on voiding - */ -public class MCash extends X_C_Cash implements DocAction -{ - /** - * - */ - private static final long serialVersionUID = -7632011237765946083L; - - - /** - * Get Cash Journal for currency, org and date - * @param ctx context - * @param C_Currency_ID currency - * @param AD_Org_ID org - * @param dateAcct date - * @param trxName transaction - * @return cash - */ - public static MCash get (Properties ctx, int AD_Org_ID, - Timestamp dateAcct, int C_Currency_ID, String trxName) - { - // Existing Journal - final String whereClause = "C_Cash.AD_Org_ID=?" // #1 - + " AND TRUNC(C_Cash.StatementDate)=?" // #2 - + " AND C_Cash.Processed='N'" - + " AND EXISTS (SELECT * FROM C_CashBook cb " - + "WHERE C_Cash.C_CashBook_ID=cb.C_CashBook_ID AND cb.AD_Org_ID=C_Cash.AD_Org_ID" - + " AND cb.C_Currency_ID=?)"; // #3 - MCash retValue = new Query(ctx, I_C_Cash.Table_Name, whereClause, trxName) - .setParameters(AD_Org_ID,TimeUtil.getDay(dateAcct),C_Currency_ID) - .first() - ; - - if (retValue != null) - return retValue; - - // Get CashBook - MCashBook cb = MCashBook.get (ctx, AD_Org_ID, C_Currency_ID); - if (cb == null) - { - s_log.warning("No CashBook for AD_Org_ID=" + AD_Org_ID + ", C_Currency_ID=" + C_Currency_ID); - return null; - } - - // Create New Journal - retValue = new MCash (cb, dateAcct); - retValue.saveEx(trxName); - return retValue; - } // get - - /** - * Get Cash Journal for CashBook and date - * @param ctx context - * @param C_CashBook_ID cashbook - * @param dateAcct date - * @param trxName transaction - * @return cash - */ - public static MCash get (Properties ctx, int C_CashBook_ID, - Timestamp dateAcct, String trxName) - { - final String whereClause ="C_CashBook_ID=?" // #1 - + " AND TRUNC(StatementDate)=?" // #2 - + " AND Processed='N'"; - - MCash retValue = new Query(ctx, MCash.Table_Name, whereClause, trxName) - .setParameters(C_CashBook_ID, TimeUtil.getDay(dateAcct)) - .first() - ; - - if (retValue != null) - return retValue; - - // Get CashBook - MCashBook cb = new MCashBook (ctx, C_CashBook_ID, trxName); - if (cb.get_ID() ==0) - { - s_log.warning("Not found C_CashBook_ID=" + C_CashBook_ID); - return null; - } - - // Create New Journal - retValue = new MCash (cb, dateAcct); - retValue.saveEx(trxName); - return retValue; - } // get - - /** Static Logger */ - private static CLogger s_log = CLogger.getCLogger (MCash.class); - - - /************************************************************************** - * Standard Constructor - * @param ctx context - * @param C_Cash_ID id - * @param trxName transaction - */ - public MCash (Properties ctx, int C_Cash_ID, String trxName) - { - super (ctx, C_Cash_ID, trxName); - if (C_Cash_ID == 0) - { - // setC_CashBook_ID (0); // FK - setBeginningBalance (Env.ZERO); - setEndingBalance (Env.ZERO); - setStatementDifference(Env.ZERO); - setDocAction(DOCACTION_Complete); - setDocStatus(DOCSTATUS_Drafted); - // - Timestamp today = TimeUtil.getDay(System.currentTimeMillis()); - setStatementDate (today); // @#Date@ - setDateAcct (today); // @#Date@ - - StringBuilder name = new StringBuilder(DisplayType.getDateFormat(DisplayType.Date).format(today)) - .append(" ").append(MOrg.get(ctx, getAD_Org_ID()).getValue()); - setName (name.toString()); - setIsApproved(false); - setPosted (false); // N - setProcessed (false); - } - } // MCash - - /** - * Load Constructor - * @param ctx context - * @param rs result set - * @param trxName transaction - */ - public MCash (Properties ctx, ResultSet rs, String trxName) - { - super(ctx, rs, trxName); - } // MCash - - /** - * Parent Constructor - * @param cb cash book - * @param today date - if null today - */ - public MCash (MCashBook cb, Timestamp today) - { - this (cb.getCtx(), 0, cb.get_TrxName()); - setClientOrg(cb); - setC_CashBook_ID(cb.getC_CashBook_ID()); - if (today != null) - { - setStatementDate (today); - setDateAcct (today); - StringBuilder name = new StringBuilder(DisplayType.getDateFormat(DisplayType.Date).format(today)) - .append(" ").append(cb.getName()); - setName (name.toString()); - } - m_book = cb; - } // MCash - - /** Lines */ - protected MCashLine[] m_lines = null; - /** CashBook */ - protected MCashBook m_book = null; - - /** - * Get Lines - * @param requery requery - * @return lines - */ - public MCashLine[] getLines (boolean requery) - { - if (m_lines != null && !requery) { - set_TrxName(m_lines, get_TrxName()); - return m_lines; - } - - final String whereClause =MCashLine.COLUMNNAME_C_Cash_ID+"=?"; - List list = new Query(getCtx(),I_C_CashLine.Table_Name, whereClause, get_TrxName()) - .setParameters(getC_Cash_ID()) - .setOrderBy(I_C_CashLine.COLUMNNAME_Line) - .setOnlyActiveRecords(true) - .list(); - - m_lines = list.toArray(new MCashLine[list.size()]); - return m_lines; - } // getLines - - /** - * Get Cash Book - * @return cash book - */ - public MCashBook getCashBook() - { - if (m_book == null) - m_book = MCashBook.get(getCtx(), getC_CashBook_ID()); - return m_book; - } // getCashBook - - /** - * Get Document No - * @return name - */ - public String getDocumentNo() - { - return getName(); - } // getDocumentNo - - /** - * Get Document Info - * @return document info (untranslated) - */ - public String getDocumentInfo() - { - StringBuilder msgreturn = new StringBuilder().append(Msg.getElement(getCtx(), "C_Cash_ID")).append(" ").append(getDocumentNo()); - return msgreturn.toString(); - } // getDocumentInfo - - /** - * Create PDF - * @return File or null - */ - public File createPDF () - { - try - { - StringBuilder msgfile = new StringBuilder().append(get_TableName()).append(get_ID()).append("_"); - File temp = File.createTempFile(msgfile.toString(), ".pdf"); - return createPDF (temp); - } - catch (Exception e) - { - log.severe("Could not create PDF - " + e.getMessage()); - } - return null; - } // getPDF - - /** - * Create PDF file - * @param file output file - * @return file if success - */ - public File createPDF (File file) - { - // ReportEngine re = ReportEngine.get (getCtx(), ReportEngine.INVOICE, getC_Invoice_ID()); - // if (re == null) - return null; - // return re.getPDF(file); - } // createPDF - - /** - * Before Save - * @param newRecord - * @return true - */ - protected boolean beforeSave (boolean newRecord) - { - setAD_Org_ID(getCashBook().getAD_Org_ID()); - if (getAD_Org_ID() == 0) - { - log.saveError("Error", Msg.parseTranslation(getCtx(), "@AD_Org_ID@")); - return false; - } - // Calculate End Balance - setEndingBalance(getBeginningBalance().add(getStatementDifference())); - return true; - } // beforeSave - - - /************************************************************************** - * Process document - * @param processAction document action - * @return true if performed - */ - public boolean processIt (String processAction) - { - m_processMsg = null; - DocumentEngine engine = new DocumentEngine (this, getDocStatus()); - return engine.processIt (processAction, getDocAction()); - } // process - - /** Process Message */ - protected String m_processMsg = null; - /** Just Prepared Flag */ - protected boolean m_justPrepared = false; - - /** - * Unlock Document. - * @return true if success - */ - public boolean unlockIt() - { - if (log.isLoggable(Level.INFO)) log.info(toString()); - setProcessing(false); - return true; - } // unlockIt - - /** - * Invalidate Document - * @return true if success - */ - public boolean invalidateIt() - { - if (log.isLoggable(Level.INFO)) log.info(toString()); - setDocAction(DOCACTION_Prepare); - return true; - } // invalidateIt - - /** - * Prepare Document - * @return new status (In Progress or Invalid) - */ - public String prepareIt() - { - if (log.isLoggable(Level.INFO)) log.info(toString()); - m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_PREPARE); - if (m_processMsg != null) - return DocAction.STATUS_Invalid; - - // Std Period open? - if (!MPeriod.isOpen(getCtx(), getDateAcct(), MDocType.DOCBASETYPE_CashJournal, getAD_Org_ID())) - { - m_processMsg = "@PeriodClosed@"; - return DocAction.STATUS_Invalid; - } - MCashLine[] lines = getLines(false); - if (lines.length == 0) - { - m_processMsg = "@NoLines@"; - return DocAction.STATUS_Invalid; - } - // Add up Amounts - BigDecimal difference = Env.ZERO; - int C_Currency_ID = getC_Currency_ID(); - for (int i = 0; i < lines.length; i++) - { - MCashLine line = lines[i]; - if (!line.isActive()) - continue; - if (C_Currency_ID == line.getC_Currency_ID()) - difference = difference.add(line.getAmount()); - else - { - BigDecimal amt = MConversionRate.convert(getCtx(), line.getAmount(), - line.getC_Currency_ID(), C_Currency_ID, getDateAcct(), 0, - getAD_Client_ID(), getAD_Org_ID()); - if (amt == null) - { - m_processMsg = "No Conversion Rate found - @C_CashLine_ID@= " + line.getLine(); - return DocAction.STATUS_Invalid; - } - difference = difference.add(amt); - } - } - setStatementDifference(difference); - // setEndingBalance(getBeginningBalance().add(getStatementDifference())); - - m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_PREPARE); - if (m_processMsg != null) - return DocAction.STATUS_Invalid; - - m_justPrepared = true; - if (!DOCACTION_Complete.equals(getDocAction())) - setDocAction(DOCACTION_Complete); - return DocAction.STATUS_InProgress; - } // prepareIt - - /** - * Approve Document - * @return true if success - */ - public boolean approveIt() - { - if (log.isLoggable(Level.INFO)) log.info(toString()); - setIsApproved(true); - return true; - } // approveIt - - /** - * Reject Approval - * @return true if success - */ - public boolean rejectIt() - { - if (log.isLoggable(Level.INFO)) log.info(toString()); - setIsApproved(false); - return true; - } // rejectIt - - /** - * Complete Document - * @return new status (Complete, In Progress, Invalid, Waiting ..) - */ - public String completeIt() - { - // Re-Check - if (!m_justPrepared) - { - String status = prepareIt(); - m_justPrepared = false; - if (!DocAction.STATUS_InProgress.equals(status)) - return status; - } - - m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE); - if (m_processMsg != null) - return DocAction.STATUS_Invalid; - - - // Implicit Approval - if (!isApproved()) - approveIt(); - // - if (log.isLoggable(Level.INFO)) log.info(toString()); - - MCashLine[] lines = getLines(false); - for (int i = 0; i < lines.length; i++) - { - MCashLine line = lines[i]; - if (MCashLine.CASHTYPE_Invoice.equals(line.getCashType())) - { - // Check if the invoice is completed - teo_sarca BF [ 1894524 ] - MInvoice invoice = line.getInvoice(); - if ( !MInvoice.DOCSTATUS_Completed.equals(invoice.getDocStatus()) - && !MInvoice.DOCSTATUS_Closed.equals(invoice.getDocStatus()) - && !MInvoice.DOCSTATUS_Reversed.equals(invoice.getDocStatus()) - && !MInvoice.DOCSTATUS_Voided.equals(invoice.getDocStatus()) - ) - { - m_processMsg = "@Line@ "+line.getLine()+": @InvoiceCreateDocNotCompleted@"; - return DocAction.STATUS_Invalid; - } - // - StringBuilder name = new StringBuilder().append(Msg.translate(getCtx(), "C_Cash_ID")).append(": ").append(getName()) - .append(" - ").append(Msg.translate(getCtx(), "Line")).append(" ").append(line.getLine()); - MAllocationHdr hdr = new MAllocationHdr(getCtx(), false, - getDateAcct(), line.getC_Currency_ID(), - name.toString(), get_TrxName()); - hdr.setAD_Org_ID(getAD_Org_ID()); - if (!hdr.save()) - { - m_processMsg = CLogger.retrieveErrorString("Could not create Allocation Hdr"); - return DocAction.STATUS_Invalid; - } - // Allocation Line - MAllocationLine aLine = new MAllocationLine (hdr, line.getAmount(), - line.getDiscountAmt(), line.getWriteOffAmt(), Env.ZERO); - aLine.setC_Invoice_ID(line.getC_Invoice_ID()); - aLine.setC_CashLine_ID(line.getC_CashLine_ID()); - if (!aLine.save()) - { - m_processMsg = CLogger.retrieveErrorString("Could not create Allocation Line"); - return DocAction.STATUS_Invalid; - } - // Should start WF - if(!hdr.processIt(DocAction.ACTION_Complete)) { - m_processMsg = CLogger.retrieveErrorString("Could not process Allocation"); - return DocAction.STATUS_Invalid; - } - if (!hdr.save()) { - m_processMsg = CLogger.retrieveErrorString("Could not save Allocation"); - return DocAction.STATUS_Invalid; - } - } - else if (MCashLine.CASHTYPE_BankAccountTransfer.equals(line.getCashType())) - { - // Payment just as intermediate info - MPayment pay = new MPayment (getCtx(), 0, get_TrxName()); - pay.setAD_Org_ID(getAD_Org_ID()); - String documentNo = getName(); - pay.setDocumentNo(documentNo); - pay.setR_PnRef(documentNo); - pay.set_ValueNoCheck("TrxType", "X"); // Transfer - pay.set_ValueNoCheck("TenderType", "X"); - // - //Modification for cash payment - Posterita - pay.setC_CashBook_ID(getC_CashBook_ID()); - //End of modification - Posterita - - pay.setC_BankAccount_ID(line.getC_BankAccount_ID()); - pay.setC_DocType_ID(true); // Receipt - pay.setDateTrx(getStatementDate()); - pay.setDateAcct(getDateAcct()); - pay.setAmount(line.getC_Currency_ID(), line.getAmount().negate()); // Transfer - pay.setDescription(line.getDescription()); - pay.setDocStatus(MPayment.DOCSTATUS_Closed); - pay.setDocAction(MPayment.DOCACTION_None); - pay.setPosted(true); - pay.setIsAllocated(true); // Has No Allocation! - pay.setProcessed(true); - if (!pay.save()) - { - m_processMsg = CLogger.retrieveErrorString("Could not create Payment"); - return DocAction.STATUS_Invalid; - } - - line.setC_Payment_ID(pay.getC_Payment_ID()); - if (!line.save()) - { - m_processMsg = "Could not update Cash Line"; - return DocAction.STATUS_Invalid; - } - } - } - - // User Validation - String valid = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE); - if (valid != null) - { - m_processMsg = valid; - return DocAction.STATUS_Invalid; - } - // - setProcessed(true); - setDocAction(DOCACTION_Close); - return DocAction.STATUS_Completed; - } // completeIt - - /** - * Void Document. - * Same as Close. - * @return true if success - */ - public boolean voidIt() - { - if (log.isLoggable(Level.INFO)) log.info(toString()); - // Before Void - m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_VOID); - if (m_processMsg != null) - return false; - - //FR [ 1866214 ] - boolean retValue = reverseIt(); - - if (retValue) { - // After Void - m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_VOID); - if (m_processMsg != null) - return false; - setDocAction(DOCACTION_None); - } - - return retValue; - } // voidIt - - //FR [ 1866214 ] - /************************************************************************** - * Reverse Cash - * Period needs to be open - * @return true if reversed - */ - protected boolean reverseIt() - { - if (DOCSTATUS_Closed.equals(getDocStatus()) - || DOCSTATUS_Reversed.equals(getDocStatus()) - || DOCSTATUS_Voided.equals(getDocStatus())) - { - m_processMsg = "Document Closed: " + getDocStatus(); - setDocAction(DOCACTION_None); - return false; - } - - // Can we delete posting - if (!MPeriod.isOpen(getCtx(), this.getDateAcct(), MPeriodControl.DOCBASETYPE_CashJournal, getAD_Org_ID())) - throw new IllegalStateException("@PeriodClosed@"); - - // Reverse Allocations - MAllocationHdr[] allocations = MAllocationHdr.getOfCash(getCtx(), getC_Cash_ID(), get_TrxName()); - for(MAllocationHdr allocation : allocations) - { - allocation.reverseCorrectIt(); - if(!allocation.save()) - throw new IllegalStateException("Cannot reverse allocations"); - } - - MCashLine[] cashlines = getLines(true); - for (MCashLine cashline : cashlines ) - { - BigDecimal oldAmount = cashline.getAmount(); - BigDecimal oldDiscount = cashline.getDiscountAmt(); - BigDecimal oldWriteOff = cashline.getWriteOffAmt(); - cashline.setAmount(Env.ZERO); - cashline.setDiscountAmt(Env.ZERO); - cashline.setWriteOffAmt(Env.ZERO); - StringBuilder msgadd = new StringBuilder().append(Msg.getMsg(getCtx(), "Voided")) - .append(" (Amount=").append(oldAmount).append(", Discount=").append(oldDiscount) - .append(", WriteOff=").append(oldWriteOff).append(", )"); - cashline.addDescription(msgadd.toString()); - if (MCashLine.CASHTYPE_BankAccountTransfer.equals(cashline.getCashType())) - { - if (cashline.getC_Payment_ID() == 0) - throw new IllegalStateException("Cannot reverse payment"); - - MPayment payment = new MPayment(getCtx(), cashline.getC_Payment_ID(),get_TrxName()); - payment.reverseCorrectIt(); - payment.saveEx(); - } - cashline.saveEx(); - } - - setName(getName()+"^"); - addDescription(Msg.getMsg(getCtx(), "Voided")); - setDocStatus(DOCSTATUS_Reversed); // for direct calls - setProcessed(true); - setPosted(true); - setDocAction(DOCACTION_None); - saveEx(); - - // Delete Posting - MFactAcct.deleteEx(Table_ID, getC_Cash_ID(), get_TrxName()); - - return true; - } // reverse - - /** - * Add to Description - * @param description text - */ - public void addDescription (String description) - { - String desc = getDescription(); - if (desc == null) - setDescription(description); - else{ - StringBuilder msgd = new StringBuilder(desc).append(" | ").append(description); - setDescription(msgd.toString()); - } - } // addDescription - - /** - * Close Document. - * Cancel not delivered Quantities - * @return true if success - */ - public boolean closeIt() - { - if (log.isLoggable(Level.INFO)) log.info(toString()); - // Before Close - m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_CLOSE); - if (m_processMsg != null) - return false; - - setDocAction(DOCACTION_None); - - // After Close - m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_CLOSE); - if (m_processMsg != null) - return false; - return true; - } // closeIt - - /** - * Reverse Correction - * @return true if success - */ - public boolean reverseCorrectIt() - { - if (log.isLoggable(Level.INFO)) log.info(toString()); - // Before reverseCorrect - m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REVERSECORRECT); - if (m_processMsg != null) - return false; - - //FR [ 1866214 ] - boolean retValue = reverseIt(); - - if (retValue) { - // After reverseCorrect - m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REVERSECORRECT); - if (m_processMsg != null) - return false; - } - - return retValue; - } // reverseCorrectionIt - - /** - * Reverse Accrual - none - * @return true if success - */ - public boolean reverseAccrualIt() - { - if (log.isLoggable(Level.INFO)) log.info(toString()); - // Before reverseAccrual - m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REVERSEACCRUAL); - if (m_processMsg != null) - return false; - - // After reverseAccrual - m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REVERSEACCRUAL); - if (m_processMsg != null) - return false; - - return false; - } // reverseAccrualIt - - /** - * Re-activate - * @return true if success - */ - public boolean reActivateIt() - { - if (log.isLoggable(Level.INFO)) log.info(toString()); - // Before reActivate - m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REACTIVATE); - if (m_processMsg != null) - return false; - - setProcessed(false); - if (reverseCorrectIt()) - return true; - - // After reActivate - m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REACTIVATE); - if (m_processMsg != null) - return false; - return false; - } // reActivateIt - - /** - * Set Processed - * @param processed processed - */ - public void setProcessed (boolean processed) - { - super.setProcessed (processed); - StringBuilder sql = new StringBuilder("UPDATE C_CashLine SET Processed='") - .append((processed ? "Y" : "N")) - .append("' WHERE C_Cash_ID=").append(getC_Cash_ID()); - int noLine = DB.executeUpdate (sql.toString(), get_TrxName()); - m_lines = null; - if (log.isLoggable(Level.FINE)) log.fine(processed + " - Lines=" + noLine); - } // setProcessed - - /** - * String Representation - * @return info - */ - public String toString () - { - StringBuilder sb = new StringBuilder ("MCash["); - sb.append (get_ID ()) - .append ("-").append (getName()) - .append(", Balance=").append(getBeginningBalance()) - .append("->").append(getEndingBalance()) - .append ("]"); - return sb.toString (); - } // toString - - /************************************************************************* - * Get Summary - * @return Summary of Document - */ - public String getSummary() - { - StringBuilder sb = new StringBuilder(); - sb.append(getName()); - // : Total Lines = 123.00 (#1) - sb.append(": ") - .append(Msg.translate(getCtx(),"BeginningBalance")).append("=").append(getBeginningBalance()) - .append(",") - .append(Msg.translate(getCtx(),"EndingBalance")).append("=").append(getEndingBalance()) - .append(" (#").append(getLines(false).length).append(")"); - // - Description - if (getDescription() != null && getDescription().length() > 0) - sb.append(" - ").append(getDescription()); - return sb.toString(); - } // getSummary - - /** - * Get Process Message - * @return clear text error message - */ - public String getProcessMsg() - { - return m_processMsg; - } // getProcessMsg - - /** - * Get Document Owner (Responsible) - * @return AD_User_ID - */ - public int getDoc_User_ID() - { - return getCreatedBy(); - } // getDoc_User_ID - - /** - * Get Document Approval Amount - * @return amount difference - */ - public BigDecimal getApprovalAmt() - { - return getStatementDifference(); - } // getApprovalAmt - - /** - * Get Currency - * @return Currency - */ - public int getC_Currency_ID () - { - return getCashBook().getC_Currency_ID(); - } // getC_Currency_ID - - /** - * Document Status is Complete or Closed - * @return true if CO, CL or RE - */ - public boolean isComplete() - { - String ds = getDocStatus(); - return DOCSTATUS_Completed.equals(ds) - || DOCSTATUS_Closed.equals(ds) - || DOCSTATUS_Reversed.equals(ds); - } // isComplete - -} // MCash + *
  • BF [ 1894524 ] Pay an reversed invoice + *
  • BF [ 1899477 ] MCash.getLines should return only active lines + *
  • BF [ 2588326 ] Cash Lines are not correctly updated on voiding + */ +public class MCash extends X_C_Cash implements DocAction +{ + /** + * + */ + private static final long serialVersionUID = -7632011237765946083L; + + + /** + * Get Cash Journal for currency, org and date + * @param ctx context + * @param C_Currency_ID currency + * @param AD_Org_ID org + * @param dateAcct date + * @param trxName transaction + * @return cash + */ + public static MCash get (Properties ctx, int AD_Org_ID, + Timestamp dateAcct, int C_Currency_ID, String trxName) + { + // Existing Journal + final String whereClause = "C_Cash.AD_Org_ID=?" // #1 + + " AND TRUNC(C_Cash.StatementDate)=?" // #2 + + " AND C_Cash.Processed='N'" + + " AND EXISTS (SELECT * FROM C_CashBook cb " + + "WHERE C_Cash.C_CashBook_ID=cb.C_CashBook_ID AND cb.AD_Org_ID=C_Cash.AD_Org_ID" + + " AND cb.C_Currency_ID=?)"; // #3 + MCash retValue = new Query(ctx, I_C_Cash.Table_Name, whereClause, trxName) + .setParameters(AD_Org_ID,TimeUtil.getDay(dateAcct),C_Currency_ID) + .first() + ; + + if (retValue != null) + return retValue; + + // Get CashBook + MCashBook cb = MCashBook.get (ctx, AD_Org_ID, C_Currency_ID); + if (cb == null) + { + s_log.warning("No CashBook for AD_Org_ID=" + AD_Org_ID + ", C_Currency_ID=" + C_Currency_ID); + return null; + } + + // Create New Journal + retValue = new MCash (cb, dateAcct); + retValue.saveEx(trxName); + return retValue; + } // get + + /** + * Get Cash Journal for CashBook and date + * @param ctx context + * @param C_CashBook_ID cashbook + * @param dateAcct date + * @param trxName transaction + * @return cash + */ + public static MCash get (Properties ctx, int C_CashBook_ID, + Timestamp dateAcct, String trxName) + { + final String whereClause ="C_CashBook_ID=?" // #1 + + " AND TRUNC(StatementDate)=?" // #2 + + " AND Processed='N'"; + + MCash retValue = new Query(ctx, MCash.Table_Name, whereClause, trxName) + .setParameters(C_CashBook_ID, TimeUtil.getDay(dateAcct)) + .first() + ; + + if (retValue != null) + return retValue; + + // Get CashBook + MCashBook cb = new MCashBook (ctx, C_CashBook_ID, trxName); + if (cb.get_ID() ==0) + { + s_log.warning("Not found C_CashBook_ID=" + C_CashBook_ID); + return null; + } + + // Create New Journal + retValue = new MCash (cb, dateAcct); + retValue.saveEx(trxName); + return retValue; + } // get + + /** Static Logger */ + private static CLogger s_log = CLogger.getCLogger (MCash.class); + + + /************************************************************************** + * Standard Constructor + * @param ctx context + * @param C_Cash_ID id + * @param trxName transaction + */ + public MCash (Properties ctx, int C_Cash_ID, String trxName) + { + super (ctx, C_Cash_ID, trxName); + if (C_Cash_ID == 0) + { + // setC_CashBook_ID (0); // FK + setBeginningBalance (Env.ZERO); + setEndingBalance (Env.ZERO); + setStatementDifference(Env.ZERO); + setDocAction(DOCACTION_Complete); + setDocStatus(DOCSTATUS_Drafted); + // + Timestamp today = TimeUtil.getDay(System.currentTimeMillis()); + setStatementDate (today); // @#Date@ + setDateAcct (today); // @#Date@ + + StringBuilder name = new StringBuilder(DisplayType.getDateFormat(DisplayType.Date).format(today)) + .append(" ").append(MOrg.get(ctx, getAD_Org_ID()).getValue()); + setName (name.toString()); + setIsApproved(false); + setPosted (false); // N + setProcessed (false); + } + } // MCash + + /** + * Load Constructor + * @param ctx context + * @param rs result set + * @param trxName transaction + */ + public MCash (Properties ctx, ResultSet rs, String trxName) + { + super(ctx, rs, trxName); + } // MCash + + /** + * Parent Constructor + * @param cb cash book + * @param today date - if null today + */ + public MCash (MCashBook cb, Timestamp today) + { + this (cb.getCtx(), 0, cb.get_TrxName()); + setClientOrg(cb); + setC_CashBook_ID(cb.getC_CashBook_ID()); + if (today != null) + { + setStatementDate (today); + setDateAcct (today); + StringBuilder name = new StringBuilder(DisplayType.getDateFormat(DisplayType.Date).format(today)) + .append(" ").append(cb.getName()); + setName (name.toString()); + } + m_book = cb; + } // MCash + + /** Lines */ + protected MCashLine[] m_lines = null; + /** CashBook */ + protected MCashBook m_book = null; + + /** + * Get Lines + * @param requery requery + * @return lines + */ + public MCashLine[] getLines (boolean requery) + { + if (m_lines != null && !requery) { + set_TrxName(m_lines, get_TrxName()); + return m_lines; + } + + final String whereClause =MCashLine.COLUMNNAME_C_Cash_ID+"=?"; + List list = new Query(getCtx(),I_C_CashLine.Table_Name, whereClause, get_TrxName()) + .setParameters(getC_Cash_ID()) + .setOrderBy(I_C_CashLine.COLUMNNAME_Line) + .setOnlyActiveRecords(true) + .list(); + + m_lines = list.toArray(new MCashLine[list.size()]); + return m_lines; + } // getLines + + /** + * Get Cash Book + * @return cash book + */ + public MCashBook getCashBook() + { + if (m_book == null) + m_book = MCashBook.get(getCtx(), getC_CashBook_ID()); + return m_book; + } // getCashBook + + /** + * Get Document No + * @return name + */ + public String getDocumentNo() + { + return getName(); + } // getDocumentNo + + /** + * Get Document Info + * @return document info (untranslated) + */ + public String getDocumentInfo() + { + StringBuilder msgreturn = new StringBuilder().append(Msg.getElement(getCtx(), "C_Cash_ID")).append(" ").append(getDocumentNo()); + return msgreturn.toString(); + } // getDocumentInfo + + /** + * Create PDF + * @return File or null + */ + public File createPDF () + { + try + { + StringBuilder msgfile = new StringBuilder().append(get_TableName()).append(get_ID()).append("_"); + File temp = File.createTempFile(msgfile.toString(), ".pdf"); + return createPDF (temp); + } + catch (Exception e) + { + log.severe("Could not create PDF - " + e.getMessage()); + } + return null; + } // getPDF + + /** + * Create PDF file + * @param file output file + * @return file if success + */ + public File createPDF (File file) + { + // ReportEngine re = ReportEngine.get (getCtx(), ReportEngine.INVOICE, getC_Invoice_ID()); + // if (re == null) + return null; + // return re.getPDF(file); + } // createPDF + + /** + * Before Save + * @param newRecord + * @return true + */ + protected boolean beforeSave (boolean newRecord) + { + setAD_Org_ID(getCashBook().getAD_Org_ID()); + if (getAD_Org_ID() == 0) + { + log.saveError("Error", Msg.parseTranslation(getCtx(), "@AD_Org_ID@")); + return false; + } + // Calculate End Balance + setEndingBalance(getBeginningBalance().add(getStatementDifference())); + return true; + } // beforeSave + + + /************************************************************************** + * Process document + * @param processAction document action + * @return true if performed + */ + public boolean processIt (String processAction) + { + m_processMsg = null; + DocumentEngine engine = new DocumentEngine (this, getDocStatus()); + return engine.processIt (processAction, getDocAction()); + } // process + + /** Process Message */ + protected String m_processMsg = null; + /** Just Prepared Flag */ + protected boolean m_justPrepared = false; + + /** + * Unlock Document. + * @return true if success + */ + public boolean unlockIt() + { + if (log.isLoggable(Level.INFO)) log.info(toString()); + setProcessing(false); + return true; + } // unlockIt + + /** + * Invalidate Document + * @return true if success + */ + public boolean invalidateIt() + { + if (log.isLoggable(Level.INFO)) log.info(toString()); + setDocAction(DOCACTION_Prepare); + return true; + } // invalidateIt + + /** + * Prepare Document + * @return new status (In Progress or Invalid) + */ + public String prepareIt() + { + if (log.isLoggable(Level.INFO)) log.info(toString()); + m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_PREPARE); + if (m_processMsg != null) + return DocAction.STATUS_Invalid; + + // Std Period open? + if (!MPeriod.isOpen(getCtx(), getDateAcct(), MDocType.DOCBASETYPE_CashJournal, getAD_Org_ID())) + { + m_processMsg = "@PeriodClosed@"; + return DocAction.STATUS_Invalid; + } + MCashLine[] lines = getLines(false); + if (lines.length == 0) + { + m_processMsg = "@NoLines@"; + return DocAction.STATUS_Invalid; + } + // Add up Amounts + BigDecimal difference = Env.ZERO; + int C_Currency_ID = getC_Currency_ID(); + for (int i = 0; i < lines.length; i++) + { + MCashLine line = lines[i]; + if (!line.isActive()) + continue; + if (C_Currency_ID == line.getC_Currency_ID()) + difference = difference.add(line.getAmount()); + else + { + BigDecimal amt = MConversionRate.convert(getCtx(), line.getAmount(), + line.getC_Currency_ID(), C_Currency_ID, getDateAcct(), 0, + getAD_Client_ID(), getAD_Org_ID()); + if (amt == null) + { + m_processMsg = "No Conversion Rate found - @C_CashLine_ID@= " + line.getLine(); + return DocAction.STATUS_Invalid; + } + difference = difference.add(amt); + } + } + setStatementDifference(difference); + // setEndingBalance(getBeginningBalance().add(getStatementDifference())); + + m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_PREPARE); + if (m_processMsg != null) + return DocAction.STATUS_Invalid; + + m_justPrepared = true; + if (!DOCACTION_Complete.equals(getDocAction())) + setDocAction(DOCACTION_Complete); + return DocAction.STATUS_InProgress; + } // prepareIt + + /** + * Approve Document + * @return true if success + */ + public boolean approveIt() + { + if (log.isLoggable(Level.INFO)) log.info(toString()); + setIsApproved(true); + return true; + } // approveIt + + /** + * Reject Approval + * @return true if success + */ + public boolean rejectIt() + { + if (log.isLoggable(Level.INFO)) log.info(toString()); + setIsApproved(false); + return true; + } // rejectIt + + /** + * Complete Document + * @return new status (Complete, In Progress, Invalid, Waiting ..) + */ + public String completeIt() + { + // Re-Check + if (!m_justPrepared) + { + String status = prepareIt(); + m_justPrepared = false; + if (!DocAction.STATUS_InProgress.equals(status)) + return status; + } + + m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE); + if (m_processMsg != null) + return DocAction.STATUS_Invalid; + + + // Implicit Approval + if (!isApproved()) + approveIt(); + // + if (log.isLoggable(Level.INFO)) log.info(toString()); + + MCashLine[] lines = getLines(false); + for (int i = 0; i < lines.length; i++) + { + MCashLine line = lines[i]; + if (MCashLine.CASHTYPE_Invoice.equals(line.getCashType())) + { + // Check if the invoice is completed - teo_sarca BF [ 1894524 ] + MInvoice invoice = line.getInvoice(); + if ( !MInvoice.DOCSTATUS_Completed.equals(invoice.getDocStatus()) + && !MInvoice.DOCSTATUS_Closed.equals(invoice.getDocStatus()) + && !MInvoice.DOCSTATUS_Reversed.equals(invoice.getDocStatus()) + && !MInvoice.DOCSTATUS_Voided.equals(invoice.getDocStatus()) + ) + { + m_processMsg = "@Line@ "+line.getLine()+": @InvoiceCreateDocNotCompleted@"; + return DocAction.STATUS_Invalid; + } + // + StringBuilder name = new StringBuilder().append(Msg.translate(getCtx(), "C_Cash_ID")).append(": ").append(getName()) + .append(" - ").append(Msg.translate(getCtx(), "Line")).append(" ").append(line.getLine()); + MAllocationHdr hdr = new MAllocationHdr(getCtx(), false, + getDateAcct(), line.getC_Currency_ID(), + name.toString(), get_TrxName()); + hdr.setAD_Org_ID(getAD_Org_ID()); + if (!hdr.save()) + { + m_processMsg = CLogger.retrieveErrorString("Could not create Allocation Hdr"); + return DocAction.STATUS_Invalid; + } + // Allocation Line + MAllocationLine aLine = new MAllocationLine (hdr, line.getAmount(), + line.getDiscountAmt(), line.getWriteOffAmt(), Env.ZERO); + aLine.setC_Invoice_ID(line.getC_Invoice_ID()); + aLine.setC_CashLine_ID(line.getC_CashLine_ID()); + if (!aLine.save()) + { + m_processMsg = CLogger.retrieveErrorString("Could not create Allocation Line"); + return DocAction.STATUS_Invalid; + } + // Should start WF + if(!hdr.processIt(DocAction.ACTION_Complete)) { + m_processMsg = CLogger.retrieveErrorString("Could not process Allocation"); + return DocAction.STATUS_Invalid; + } + if (!hdr.save()) { + m_processMsg = CLogger.retrieveErrorString("Could not save Allocation"); + return DocAction.STATUS_Invalid; + } + } + else if (MCashLine.CASHTYPE_BankAccountTransfer.equals(line.getCashType())) + { + // Payment just as intermediate info + MPayment pay = new MPayment (getCtx(), 0, get_TrxName()); + pay.setAD_Org_ID(getAD_Org_ID()); + String documentNo = getName(); + pay.setDocumentNo(documentNo); + pay.setR_PnRef(documentNo); + pay.set_ValueNoCheck("TrxType", "X"); // Transfer + pay.set_ValueNoCheck("TenderType", "X"); + // + //Modification for cash payment - Posterita + pay.setC_CashBook_ID(getC_CashBook_ID()); + //End of modification - Posterita + + pay.setC_BankAccount_ID(line.getC_BankAccount_ID()); + pay.setC_DocType_ID(true); // Receipt + pay.setDateTrx(getStatementDate()); + pay.setDateAcct(getDateAcct()); + pay.setAmount(line.getC_Currency_ID(), line.getAmount().negate()); // Transfer + pay.setDescription(line.getDescription()); + pay.setDocStatus(MPayment.DOCSTATUS_Closed); + pay.setDocAction(MPayment.DOCACTION_None); + pay.setPosted(true); + pay.setIsAllocated(true); // Has No Allocation! + pay.setProcessed(true); + if (!pay.save()) + { + m_processMsg = CLogger.retrieveErrorString("Could not create Payment"); + return DocAction.STATUS_Invalid; + } + + line.setC_Payment_ID(pay.getC_Payment_ID()); + if (!line.save()) + { + m_processMsg = "Could not update Cash Line"; + return DocAction.STATUS_Invalid; + } + } + } + + // User Validation + String valid = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE); + if (valid != null) + { + m_processMsg = valid; + return DocAction.STATUS_Invalid; + } + // + setProcessed(true); + setDocAction(DOCACTION_Close); + return DocAction.STATUS_Completed; + } // completeIt + + /** + * Void Document. + * Same as Close. + * @return true if success + */ + public boolean voidIt() + { + if (log.isLoggable(Level.INFO)) log.info(toString()); + // Before Void + m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_VOID); + if (m_processMsg != null) + return false; + + //FR [ 1866214 ] + boolean retValue = reverseIt(); + + if (retValue) { + // After Void + m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_VOID); + if (m_processMsg != null) + return false; + setDocAction(DOCACTION_None); + } + + return retValue; + } // voidIt + + //FR [ 1866214 ] + /************************************************************************** + * Reverse Cash + * Period needs to be open + * @return true if reversed + */ + protected boolean reverseIt() + { + if (DOCSTATUS_Closed.equals(getDocStatus()) + || DOCSTATUS_Reversed.equals(getDocStatus()) + || DOCSTATUS_Voided.equals(getDocStatus())) + { + m_processMsg = "Document Closed: " + getDocStatus(); + setDocAction(DOCACTION_None); + return false; + } + + // Can we delete posting + if (!MPeriod.isOpen(getCtx(), this.getDateAcct(), MPeriodControl.DOCBASETYPE_CashJournal, getAD_Org_ID())) + throw new IllegalStateException("@PeriodClosed@"); + + // Reverse Allocations + MAllocationHdr[] allocations = MAllocationHdr.getOfCash(getCtx(), getC_Cash_ID(), get_TrxName()); + for(MAllocationHdr allocation : allocations) + { + allocation.reverseCorrectIt(); + if(!allocation.save()) + throw new IllegalStateException("Cannot reverse allocations"); + } + + MCashLine[] cashlines = getLines(true); + for (MCashLine cashline : cashlines ) + { + BigDecimal oldAmount = cashline.getAmount(); + BigDecimal oldDiscount = cashline.getDiscountAmt(); + BigDecimal oldWriteOff = cashline.getWriteOffAmt(); + cashline.setAmount(Env.ZERO); + cashline.setDiscountAmt(Env.ZERO); + cashline.setWriteOffAmt(Env.ZERO); + StringBuilder msgadd = new StringBuilder().append(Msg.getMsg(getCtx(), "Voided")) + .append(" (Amount=").append(oldAmount).append(", Discount=").append(oldDiscount) + .append(", WriteOff=").append(oldWriteOff).append(", )"); + cashline.addDescription(msgadd.toString()); + if (MCashLine.CASHTYPE_BankAccountTransfer.equals(cashline.getCashType())) + { + if (cashline.getC_Payment_ID() == 0) + throw new IllegalStateException("Cannot reverse payment"); + + MPayment payment = new MPayment(getCtx(), cashline.getC_Payment_ID(),get_TrxName()); + payment.reverseCorrectIt(); + payment.saveEx(); + } + cashline.saveEx(); + } + + setName(getName()+"^"); + addDescription(Msg.getMsg(getCtx(), "Voided")); + setDocStatus(DOCSTATUS_Reversed); // for direct calls + setProcessed(true); + setPosted(true); + setDocAction(DOCACTION_None); + saveEx(); + + // Delete Posting + MFactAcct.deleteEx(Table_ID, getC_Cash_ID(), get_TrxName()); + + return true; + } // reverse + + /** + * Add to Description + * @param description text + */ + public void addDescription (String description) + { + String desc = getDescription(); + if (desc == null) + setDescription(description); + else{ + StringBuilder msgd = new StringBuilder(desc).append(" | ").append(description); + setDescription(msgd.toString()); + } + } // addDescription + + /** + * Close Document. + * Cancel not delivered Quantities + * @return true if success + */ + public boolean closeIt() + { + if (log.isLoggable(Level.INFO)) log.info(toString()); + // Before Close + m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_CLOSE); + if (m_processMsg != null) + return false; + + setDocAction(DOCACTION_None); + + // After Close + m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_CLOSE); + if (m_processMsg != null) + return false; + return true; + } // closeIt + + /** + * Reverse Correction + * @return true if success + */ + public boolean reverseCorrectIt() + { + if (log.isLoggable(Level.INFO)) log.info(toString()); + // Before reverseCorrect + m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REVERSECORRECT); + if (m_processMsg != null) + return false; + + //FR [ 1866214 ] + boolean retValue = reverseIt(); + + if (retValue) { + // After reverseCorrect + m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REVERSECORRECT); + if (m_processMsg != null) + return false; + } + + return retValue; + } // reverseCorrectionIt + + /** + * Reverse Accrual - none + * @return true if success + */ + public boolean reverseAccrualIt() + { + if (log.isLoggable(Level.INFO)) log.info(toString()); + // Before reverseAccrual + m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REVERSEACCRUAL); + if (m_processMsg != null) + return false; + + // After reverseAccrual + m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REVERSEACCRUAL); + if (m_processMsg != null) + return false; + + return false; + } // reverseAccrualIt + + /** + * Re-activate + * @return true if success + */ + public boolean reActivateIt() + { + if (log.isLoggable(Level.INFO)) log.info(toString()); + // Before reActivate + m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REACTIVATE); + if (m_processMsg != null) + return false; + + setProcessed(false); + if (reverseCorrectIt()) + return true; + + // After reActivate + m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REACTIVATE); + if (m_processMsg != null) + return false; + return false; + } // reActivateIt + + /** + * Set Processed + * @param processed processed + */ + public void setProcessed (boolean processed) + { + super.setProcessed (processed); + StringBuilder sql = new StringBuilder("UPDATE C_CashLine SET Processed='") + .append((processed ? "Y" : "N")) + .append("' WHERE C_Cash_ID=").append(getC_Cash_ID()); + int noLine = DB.executeUpdate (sql.toString(), get_TrxName()); + m_lines = null; + if (log.isLoggable(Level.FINE)) log.fine(processed + " - Lines=" + noLine); + } // setProcessed + + /** + * String Representation + * @return info + */ + public String toString () + { + StringBuilder sb = new StringBuilder ("MCash["); + sb.append (get_ID ()) + .append ("-").append (getName()) + .append(", Balance=").append(getBeginningBalance()) + .append("->").append(getEndingBalance()) + .append ("]"); + return sb.toString (); + } // toString + + /************************************************************************* + * Get Summary + * @return Summary of Document + */ + public String getSummary() + { + StringBuilder sb = new StringBuilder(); + sb.append(getName()); + // : Total Lines = 123.00 (#1) + sb.append(": ") + .append(Msg.translate(getCtx(),"BeginningBalance")).append("=").append(getBeginningBalance()) + .append(",") + .append(Msg.translate(getCtx(),"EndingBalance")).append("=").append(getEndingBalance()) + .append(" (#").append(getLines(false).length).append(")"); + // - Description + if (getDescription() != null && getDescription().length() > 0) + sb.append(" - ").append(getDescription()); + return sb.toString(); + } // getSummary + + /** + * Get Process Message + * @return clear text error message + */ + public String getProcessMsg() + { + return m_processMsg; + } // getProcessMsg + + /** + * Get Document Owner (Responsible) + * @return AD_User_ID + */ + public int getDoc_User_ID() + { + return getCreatedBy(); + } // getDoc_User_ID + + /** + * Get Document Approval Amount + * @return amount difference + */ + public BigDecimal getApprovalAmt() + { + return getStatementDifference(); + } // getApprovalAmt + + /** + * Get Currency + * @return Currency + */ + public int getC_Currency_ID () + { + return getCashBook().getC_Currency_ID(); + } // getC_Currency_ID + + /** + * Document Status is Complete or Closed + * @return true if CO, CL or RE + */ + public boolean isComplete() + { + String ds = getDocStatus(); + return DOCSTATUS_Completed.equals(ds) + || DOCSTATUS_Closed.equals(ds) + || DOCSTATUS_Reversed.equals(ds); + } // isComplete + +} // MCash diff --git a/org.adempiere.base/src/org/compiere/model/MChat.java b/org.adempiere.base/src/org/compiere/model/MChat.java index b55bc34d65..0127076a39 100644 --- a/org.adempiere.base/src/org/compiere/model/MChat.java +++ b/org.adempiere.base/src/org/compiere/model/MChat.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,22 +16,22 @@ *****************************************************************************/ package org.compiere.model; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Properties; -import java.util.logging.Level; - -import org.apache.ecs.xhtml.b; -import org.apache.ecs.xhtml.hr; -import org.apache.ecs.xhtml.p; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.DisplayType; -import org.compiere.util.Env; -import org.compiere.util.Util; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Properties; +import java.util.logging.Level; + +import org.apache.ecs.xhtml.b; +import org.apache.ecs.xhtml.hr; +import org.apache.ecs.xhtml.p; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.DisplayType; +import org.compiere.util.Env; +import org.compiere.util.Util; /** * Chat Model @@ -41,11 +41,11 @@ import org.compiere.util.Util; */ public class MChat extends X_CM_Chat { - /** - * - */ - private static final long serialVersionUID = 9165439123618441913L; - + /** + * + */ + private static final long serialVersionUID = 9165439123618441913L; + /** * Get Chats Of Table - of client in context * @param ctx context @@ -59,7 +59,7 @@ public class MChat extends X_CM_Chat // String sql = "SELECT * FROM CM_Chat " + "WHERE AD_Client_ID=? AND AD_Table_ID=? ORDER BY Record_ID"; - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -76,11 +76,11 @@ public class MChat extends X_CM_Chat { s_log.log (Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } // MChat[] retValue = new MChat[list.size()]; @@ -103,13 +103,13 @@ public class MChat extends X_CM_Chat super (ctx, CM_Chat_ID, trxName); if (CM_Chat_ID == 0) { - // setAD_Table_ID (0); - // setRecord_ID (0); - setConfidentialType (CONFIDENTIALTYPE_PublicInformation); - setModerationType (MODERATIONTYPE_NotModerated); - // setDescription (null); - } - } // MChat + // setAD_Table_ID (0); + // setRecord_ID (0); + setConfidentialType (CONFIDENTIALTYPE_PublicInformation); + setModerationType (MODERATIONTYPE_NotModerated); + // setDescription (null); + } + } // MChat /** * Full Constructor @@ -156,7 +156,7 @@ public class MChat extends X_CM_Chat return m_entries; ArrayList list = new ArrayList(); String sql = "SELECT * FROM CM_ChatEntry WHERE CM_Chat_ID=? ORDER BY Created"; - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -172,11 +172,11 @@ public class MChat extends X_CM_Chat { log.log (Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } // m_entries = new MChatEntry[list.size ()]; @@ -194,10 +194,10 @@ public class MChat extends X_CM_Chat { if (Description != null && Description.length() > 0) super.setDescription (Description); - else{ - StringBuilder msgsd = new StringBuilder().append(getAD_Table_ID()).append("#").append(getRecord_ID()); - super.setDescription (msgsd.toString()); - } + else{ + StringBuilder msgsd = new StringBuilder().append(getAD_Table_ID()).append("#").append(getRecord_ID()); + super.setDescription (msgsd.toString()); + } } // setDescription /** @@ -239,19 +239,19 @@ public class MChat extends X_CM_Chat } // entry // return history; - } // getHistory - - /** - * IDEMPIERE-530 - * Get the chat ID based on table_id and record_id - * @param AD_Table_ID - * @param Record_ID - * @return CM_Chat_ID - */ - public static int getID(int Table_ID, int Record_ID) { - String sql="SELECT CM_Chat_ID FROM CM_Chat WHERE AD_Table_ID=? AND Record_ID=?"; - int chatID = DB.getSQLValueEx(null, sql, Table_ID, Record_ID); - return chatID; - } + } // getHistory + + /** + * IDEMPIERE-530 + * Get the chat ID based on table_id and record_id + * @param AD_Table_ID + * @param Record_ID + * @return CM_Chat_ID + */ + public static int getID(int Table_ID, int Record_ID) { + String sql="SELECT CM_Chat_ID FROM CM_Chat WHERE AD_Table_ID=? AND Record_ID=?"; + int chatID = DB.getSQLValueEx(null, sql, Table_ID, Record_ID); + return chatID; + } } // MChat diff --git a/org.adempiere.base/src/org/compiere/model/MChatEntry.java b/org.adempiere.base/src/org/compiere/model/MChatEntry.java index 965a0aa1d5..9a08cecd8c 100644 --- a/org.adempiere.base/src/org/compiere/model/MChatEntry.java +++ b/org.adempiere.base/src/org/compiere/model/MChatEntry.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -15,40 +15,40 @@ * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; - -import java.sql.ResultSet; -import java.util.Properties; - -/** - * Chat Entry Model + +import java.sql.ResultSet; +import java.util.Properties; + +/** + * Chat Entry Model * * @author Jorg Janke * @version $Id: MChatEntry.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $ */ public class MChatEntry extends X_CM_ChatEntry { - /** - * - */ - private static final long serialVersionUID = -158924400098841023L; - + /** + * + */ + private static final long serialVersionUID = -158924400098841023L; + /** * Standard Constructor * @param ctx cintext * @param CM_ChatEntry_ID id * @param trxName transaction */ - public MChatEntry (Properties ctx, int CM_ChatEntry_ID, String trxName) - { - super (ctx, CM_ChatEntry_ID, trxName); - if (CM_ChatEntry_ID == 0) - { - setChatEntryType (CHATENTRYTYPE_NoteFlat); // N - setConfidentialType (CONFIDENTIALTYPE_PublicInformation); - } - } // MChatEntry - - /** + public MChatEntry (Properties ctx, int CM_ChatEntry_ID, String trxName) + { + super (ctx, CM_ChatEntry_ID, trxName); + if (CM_ChatEntry_ID == 0) + { + setChatEntryType (CHATENTRYTYPE_NoteFlat); // N + setConfidentialType (CONFIDENTIALTYPE_PublicInformation); + } + } // MChatEntry + + /** * Parent Constructor * @param chat parent * @param data text @@ -56,33 +56,33 @@ public class MChatEntry extends X_CM_ChatEntry public MChatEntry (MChat chat, String data) { this (chat.getCtx(), 0, chat.get_TrxName()); - setCM_Chat_ID(chat.getCM_Chat_ID()); - setConfidentialType(chat.getConfidentialType()); - setCharacterData(data); - setChatEntryType (CHATENTRYTYPE_NoteFlat); // N - } // MChatEntry - - /** - * Thread Constructor - * @param entry peer - * @param data text - */ - public MChatEntry (MChatEntry peer, String data) - { - this (peer.getCtx(), 0, peer.get_TrxName()); - setCM_Chat_ID(peer.getCM_Chat_ID()); - setCM_ChatEntryParent_ID (peer.getCM_ChatEntryParent_ID()); - // Set GrandParent - int id = peer.getCM_ChatEntryGrandParent_ID(); - if (id == 0) - id = peer.getCM_ChatEntryParent_ID(); - setCM_ChatEntryGrandParent_ID (id); - setConfidentialType(peer.getConfidentialType()); - setCharacterData(data); - setChatEntryType (CHATENTRYTYPE_ForumThreaded); - } // MChatEntry - - /** + setCM_Chat_ID(chat.getCM_Chat_ID()); + setConfidentialType(chat.getConfidentialType()); + setCharacterData(data); + setChatEntryType (CHATENTRYTYPE_NoteFlat); // N + } // MChatEntry + + /** + * Thread Constructor + * @param entry peer + * @param data text + */ + public MChatEntry (MChatEntry peer, String data) + { + this (peer.getCtx(), 0, peer.get_TrxName()); + setCM_Chat_ID(peer.getCM_Chat_ID()); + setCM_ChatEntryParent_ID (peer.getCM_ChatEntryParent_ID()); + // Set GrandParent + int id = peer.getCM_ChatEntryGrandParent_ID(); + if (id == 0) + id = peer.getCM_ChatEntryParent_ID(); + setCM_ChatEntryGrandParent_ID (id); + setConfidentialType(peer.getConfidentialType()); + setCharacterData(data); + setChatEntryType (CHATENTRYTYPE_ForumThreaded); + } // MChatEntry + + /** * Load Constructor * @param ctx context * @param rs result set diff --git a/org.adempiere.base/src/org/compiere/model/MChatType.java b/org.adempiere.base/src/org/compiere/model/MChatType.java index 71a2daa810..d942ac8fd0 100644 --- a/org.adempiere.base/src/org/compiere/model/MChatType.java +++ b/org.adempiere.base/src/org/compiere/model/MChatType.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,10 +16,10 @@ *****************************************************************************/ package org.compiere.model; -import java.sql.ResultSet; -import java.util.Properties; - -import org.compiere.util.CCache; +import java.sql.ResultSet; +import java.util.Properties; + +import org.compiere.util.CCache; /** * Chat Type Model @@ -29,11 +29,11 @@ import org.compiere.util.CCache; */ public class MChatType extends X_CM_ChatType { - /** - * - */ - private static final long serialVersionUID = -7933150405119053730L; - + /** + * + */ + private static final long serialVersionUID = -7933150405119053730L; + /** * Get MChatType from Cache * @param ctx context @@ -62,14 +62,14 @@ public class MChatType extends X_CM_ChatType * @param CM_ChatType_ID id * @param trxName transaction */ - public MChatType (Properties ctx, int CM_ChatType_ID, String trxName) - { - super (ctx, CM_ChatType_ID, trxName); - if (CM_ChatType_ID == 0) - setModerationType (MODERATIONTYPE_NotModerated); - } // MChatType - - /** + public MChatType (Properties ctx, int CM_ChatType_ID, String trxName) + { + super (ctx, CM_ChatType_ID, trxName); + if (CM_ChatType_ID == 0) + setModerationType (MODERATIONTYPE_NotModerated); + } // MChatType + + /** * Load Constructor * @param ctx context * @param rs result set diff --git a/org.adempiere.base/src/org/compiere/model/MClient.java b/org.adempiere.base/src/org/compiere/model/MClient.java index 569744b792..8aa7bb4b82 100644 --- a/org.adempiere.base/src/org/compiere/model/MClient.java +++ b/org.adempiere.base/src/org/compiere/model/MClient.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -12,52 +12,52 @@ * 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 * + * or via info@compiere.org or http://www.compiere.org/license.html * * Contributor(s): Teo Sarca * *****************************************************************************/ package org.compiere.model; -import java.io.File; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Properties; -import java.util.logging.Level; - -import javax.mail.internet.InternetAddress; - -import org.compiere.db.CConnection; -import org.compiere.util.CCache; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.EMail; -import org.compiere.util.Env; -import org.compiere.util.Language; +import java.io.File; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.logging.Level; + +import javax.mail.internet.InternetAddress; + +import org.compiere.db.CConnection; +import org.compiere.util.CCache; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.EMail; +import org.compiere.util.Env; +import org.compiere.util.Language; /** * Client Model * * @author Jorg Janke - * @version $Id: MClient.java,v 1.2 2006/07/30 00:58:37 jjanke Exp $ - * - * @author Carlos Ruiz - globalqss - * integrate bug fix reported by Teo Sarca + * @version $Id: MClient.java,v 1.2 2006/07/30 00:58:37 jjanke Exp $ + * + * @author Carlos Ruiz - globalqss + * integrate bug fix reported by Teo Sarca * [ 1619085 ] Client setup creates duplicate trees - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - *
  • BF [ 1886480 ] Print Format Item Trl not updated even if not multilingual + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1886480 ] Print Format Item Trl not updated even if not multilingual */ public class MClient extends X_AD_Client { - /** - * - */ - private static final long serialVersionUID = 8418331925351272377L; - + /** + * + */ + private static final long serialVersionUID = 8418331925351272377L; + /** * Get client * @param ctx context @@ -82,30 +82,30 @@ public class MClient extends X_AD_Client */ public static MClient[] getAll (Properties ctx) { - return getAll(ctx, ""); - } // getAll - - /** - * Get all clients - * @param ctx context - * @param order by clause - * @return clients - */ - public static MClient[] getAll (Properties ctx, String orderBy) - { - List list = new Query(ctx,I_AD_Client.Table_Name,null,null) - .setOrderBy(orderBy) - .list(); - for(MClient client:list ){ - s_cache.put (Integer.valueOf(client.getAD_Client_ID()), client); - } - MClient[] retValue = new MClient[list.size ()]; - list.toArray (retValue); - return retValue; + return getAll(ctx, ""); } // getAll - - /** - * Get optionally cached client + + /** + * Get all clients + * @param ctx context + * @param order by clause + * @return clients + */ + public static MClient[] getAll (Properties ctx, String orderBy) + { + List list = new Query(ctx,I_AD_Client.Table_Name,null,null) + .setOrderBy(orderBy) + .list(); + for(MClient client:list ){ + s_cache.put (Integer.valueOf(client.getAD_Client_ID()), client); + } + MClient[] retValue = new MClient[list.size ()]; + list.toArray (retValue); + return retValue; + } // getAll + + /** + * Get optionally cached client * @param ctx context * @return client */ @@ -115,10 +115,10 @@ public class MClient extends X_AD_Client } // get /** Static Logger */ - @SuppressWarnings("unused") + @SuppressWarnings("unused") private static CLogger s_log = CLogger.getCLogger (MClient.class); /** Cache */ - private static CCache s_cache = new CCache(Table_Name, 3, 120, true); + private static CCache s_cache = new CCache(Table_Name, 3, 120, true); /************************************************************************** @@ -211,7 +211,7 @@ public class MClient extends X_AD_Client */ public String toString() { - StringBuilder sb = new StringBuilder ("MClient[") + StringBuilder sb = new StringBuilder ("MClient[") .append(get_ID()).append("-").append(getValue()) .append("]"); return sb.toString(); @@ -288,13 +288,13 @@ public class MClient extends X_AD_Client public boolean setupClientInfo (String language) { // Create Trees - StringBuilder sql = null; + StringBuilder sql = null; if (Env.isBaseLanguage (language, "AD_Ref_List")) // Get TreeTypes & Name - sql = new StringBuilder("SELECT Value, Name FROM AD_Ref_List WHERE AD_Reference_ID=120 AND IsActive='Y'"); + sql = new StringBuilder("SELECT Value, Name FROM AD_Ref_List WHERE AD_Reference_ID=120 AND IsActive='Y'"); else - sql = new StringBuilder("SELECT l.Value, t.Name FROM AD_Ref_List l, AD_Ref_List_Trl t ") - .append("WHERE l.AD_Reference_ID=120 AND l.AD_Ref_List_ID=t.AD_Ref_List_ID AND l.IsActive='Y'") - .append(" AND t.AD_Language=").append(DB.TO_STRING(language)); + sql = new StringBuilder("SELECT l.Value, t.Name FROM AD_Ref_List l, AD_Ref_List_Trl t ") + .append("WHERE l.AD_Reference_ID=120 AND l.AD_Ref_List_ID=t.AD_Ref_List_ID AND l.IsActive='Y'") + .append(" AND t.AD_Language=").append(DB.TO_STRING(language)); // Tree IDs int AD_Tree_Org_ID=0, AD_Tree_BPartner_ID=0, AD_Tree_Project_ID=0, @@ -302,77 +302,77 @@ public class MClient extends X_AD_Client AD_Tree_Campaign_ID=0, AD_Tree_Activity_ID=0; boolean success = false; - PreparedStatement stmt = null; - ResultSet rs = null; + PreparedStatement stmt = null; + ResultSet rs = null; try { - stmt = DB.prepareStatement(sql.toString(), get_TrxName()); - rs = stmt.executeQuery(); + stmt = DB.prepareStatement(sql.toString(), get_TrxName()); + rs = stmt.executeQuery(); MTree_Base tree = null; while (rs.next()) { - String value = rs.getString(1); - StringBuilder name = new StringBuilder().append(getName()).append(" ").append(rs.getString(2)); - // - if (value.equals(X_AD_Tree.TREETYPE_Organization)) - { - tree = new MTree_Base (this, name.toString(), value); - success = tree.save(); - AD_Tree_Org_ID = tree.getAD_Tree_ID(); - } - else if (value.equals(X_AD_Tree.TREETYPE_BPartner)) - { - tree = new MTree_Base (this, name.toString(), value); - success = tree.save(); - AD_Tree_BPartner_ID = tree.getAD_Tree_ID(); - } - else if (value.equals(X_AD_Tree.TREETYPE_Project)) - { - tree = new MTree_Base (this, name.toString(), value); - success = tree.save(); - AD_Tree_Project_ID = tree.getAD_Tree_ID(); - } - else if (value.equals(X_AD_Tree.TREETYPE_SalesRegion)) - { - tree = new MTree_Base (this, name.toString(), value); - success = tree.save(); - AD_Tree_SalesRegion_ID = tree.getAD_Tree_ID(); - } - else if (value.equals(X_AD_Tree.TREETYPE_Product)) - { - tree = new MTree_Base (this, name.toString(), value); - success = tree.save(); - AD_Tree_Product_ID = tree.getAD_Tree_ID(); - } - else if (value.equals(X_AD_Tree.TREETYPE_ElementValue)) - { - tree = new MTree_Base (this, name.toString(), value); - success = tree.save(); - m_AD_Tree_Account_ID = tree.getAD_Tree_ID(); - } - else if (value.equals(X_AD_Tree.TREETYPE_Campaign)) - { - tree = new MTree_Base (this, name.toString(), value); - success = tree.save(); - AD_Tree_Campaign_ID = tree.getAD_Tree_ID(); - } - else if (value.equals(X_AD_Tree.TREETYPE_Activity)) - { - tree = new MTree_Base (this, name.toString(), value); - success = tree.save(); - AD_Tree_Activity_ID = tree.getAD_Tree_ID(); - } - else if ( value.equals(X_AD_Tree.TREETYPE_Menu) // No Menu - || value.equals(X_AD_Tree.TREETYPE_CustomTable) // No Custom Table - || value.equals(X_AD_Tree.TREETYPE_User1) // No custom user trees - || value.equals(X_AD_Tree.TREETYPE_User2) - || value.equals(X_AD_Tree.TREETYPE_User3) - || value.equals(X_AD_Tree.TREETYPE_User4) - ) - success = true; - else // PC (Product Category), BB (BOM) - { - tree = new MTree_Base (this, name.toString(), value); + String value = rs.getString(1); + StringBuilder name = new StringBuilder().append(getName()).append(" ").append(rs.getString(2)); + // + if (value.equals(X_AD_Tree.TREETYPE_Organization)) + { + tree = new MTree_Base (this, name.toString(), value); + success = tree.save(); + AD_Tree_Org_ID = tree.getAD_Tree_ID(); + } + else if (value.equals(X_AD_Tree.TREETYPE_BPartner)) + { + tree = new MTree_Base (this, name.toString(), value); + success = tree.save(); + AD_Tree_BPartner_ID = tree.getAD_Tree_ID(); + } + else if (value.equals(X_AD_Tree.TREETYPE_Project)) + { + tree = new MTree_Base (this, name.toString(), value); + success = tree.save(); + AD_Tree_Project_ID = tree.getAD_Tree_ID(); + } + else if (value.equals(X_AD_Tree.TREETYPE_SalesRegion)) + { + tree = new MTree_Base (this, name.toString(), value); + success = tree.save(); + AD_Tree_SalesRegion_ID = tree.getAD_Tree_ID(); + } + else if (value.equals(X_AD_Tree.TREETYPE_Product)) + { + tree = new MTree_Base (this, name.toString(), value); + success = tree.save(); + AD_Tree_Product_ID = tree.getAD_Tree_ID(); + } + else if (value.equals(X_AD_Tree.TREETYPE_ElementValue)) + { + tree = new MTree_Base (this, name.toString(), value); + success = tree.save(); + m_AD_Tree_Account_ID = tree.getAD_Tree_ID(); + } + else if (value.equals(X_AD_Tree.TREETYPE_Campaign)) + { + tree = new MTree_Base (this, name.toString(), value); + success = tree.save(); + AD_Tree_Campaign_ID = tree.getAD_Tree_ID(); + } + else if (value.equals(X_AD_Tree.TREETYPE_Activity)) + { + tree = new MTree_Base (this, name.toString(), value); + success = tree.save(); + AD_Tree_Activity_ID = tree.getAD_Tree_ID(); + } + else if ( value.equals(X_AD_Tree.TREETYPE_Menu) // No Menu + || value.equals(X_AD_Tree.TREETYPE_CustomTable) // No Custom Table + || value.equals(X_AD_Tree.TREETYPE_User1) // No custom user trees + || value.equals(X_AD_Tree.TREETYPE_User2) + || value.equals(X_AD_Tree.TREETYPE_User3) + || value.equals(X_AD_Tree.TREETYPE_User4) + ) + success = true; + else // PC (Product Category), BB (BOM) + { + tree = new MTree_Base (this, name.toString(), value); success = tree.save(); } if (!success) @@ -386,12 +386,12 @@ public class MClient extends X_AD_Client { log.log(Level.SEVERE, "Trees", e1); success = false; - } - finally - { - DB.close(rs, stmt); - rs = null; - stmt = null; + } + finally + { + DB.close(rs, stmt); + rs = null; + stmt = null; } if (!success) @@ -460,33 +460,33 @@ public class MClient extends X_AD_Client */ public String testEMail() { - if (getRequestEMail() == null || getRequestEMail().length() == 0){ - StringBuilder msgreturn = new StringBuilder("No Request EMail for ").append(getName()); - return msgreturn.toString(); - } - // - String systemName = MSystem.get(getCtx()).getName(); - StringBuilder msgce = new StringBuilder(systemName).append(" EMail Test: ").append(toString()); - EMail email = createEMail (getRequestEMail(), - systemName + " EMail Test",msgce.toString()); - if (email == null){ - StringBuilder msgreturn = new StringBuilder("Could not create EMail: ").append(getName()); - return msgreturn.toString(); - } - try + if (getRequestEMail() == null || getRequestEMail().length() == 0){ + StringBuilder msgreturn = new StringBuilder("No Request EMail for ").append(getName()); + return msgreturn.toString(); + } + // + String systemName = MSystem.get(getCtx()).getName(); + StringBuilder msgce = new StringBuilder(systemName).append(" EMail Test: ").append(toString()); + EMail email = createEMail (getRequestEMail(), + systemName + " EMail Test",msgce.toString()); + if (email == null){ + StringBuilder msgreturn = new StringBuilder("Could not create EMail: ").append(getName()); + return msgreturn.toString(); + } + try { - String msg = null; - if (isServerEMail()) - { - msg = CConnection.get().getServer().sendEMail(Env.getRemoteCallCtx(Env.getCtx()), email); - } - else - { - msg = email.send(); + String msg = null; + if (isServerEMail()) + { + msg = CConnection.get().getServer().sendEMail(Env.getRemoteCallCtx(Env.getCtx()), email); + } + else + { + msg = email.send(); } if (EMail.SENT_OK.equals (msg)) { - if (log.isLoggable(Level.INFO)) log.info("Sent Test EMail to " + getRequestEMail()); + if (log.isLoggable(Level.INFO)) log.info("Sent Test EMail to " + getRequestEMail()); return "OK"; } else @@ -516,38 +516,38 @@ public class MClient extends X_AD_Client public boolean sendEMail (int AD_User_ID, String subject, String message, File attachment) { - Collection attachments = new ArrayList(); - if (attachment != null) - attachments.add(attachment); - return sendEMailAttachments(AD_User_ID, subject, message, attachments); - } - - /** - * Send EMail from Request User - with trace - * @param AD_User_ID recipient - * @param subject subject - * @param message message - * @param attachment optional collection of attachments - * @return true if sent - */ - public boolean sendEMailAttachments (int AD_User_ID, - String subject, String message, Collection attachments) - { - return sendEMailAttachments(AD_User_ID, subject, message, attachments, false); - } - - /** - * Send EMail from Request User - with trace - * @param AD_User_ID recipient - * @param subject subject - * @param message message - * @param attachment optional collection of attachments - * @param html - * @return true if sent - */ - public boolean sendEMailAttachments (int AD_User_ID, - String subject, String message, Collection attachments, boolean html) - { + Collection attachments = new ArrayList(); + if (attachment != null) + attachments.add(attachment); + return sendEMailAttachments(AD_User_ID, subject, message, attachments); + } + + /** + * Send EMail from Request User - with trace + * @param AD_User_ID recipient + * @param subject subject + * @param message message + * @param attachment optional collection of attachments + * @return true if sent + */ + public boolean sendEMailAttachments (int AD_User_ID, + String subject, String message, Collection attachments) + { + return sendEMailAttachments(AD_User_ID, subject, message, attachments, false); + } + + /** + * Send EMail from Request User - with trace + * @param AD_User_ID recipient + * @param subject subject + * @param message message + * @param attachment optional collection of attachments + * @param html + * @return true if sent + */ + public boolean sendEMailAttachments (int AD_User_ID, + String subject, String message, Collection attachments, boolean html) + { MUser to = MUser.get(getCtx(), AD_User_ID); String toEMail = to.getEMail(); if (toEMail == null || toEMail.length() == 0) @@ -569,77 +569,77 @@ public class MClient extends X_AD_Client return false; } } // sendEMail - - /** - * Send EMail from User - * @param from sender - * @param to recipient - * @param subject subject - * @param message message - * @param attachment optional attachment - * @return true if sent - */ - public boolean sendEMailAttachments (MUser from, MUser to, - String subject, String message, List attachments) - { - return sendEMailAttachments(from, to, subject, message, attachments, false); - } - - /** - * Send EMail from User - * @param from sender - * @param to recipient - * @param subject subject - * @param message message - * @param attachment optional attachment - * @param isHtml - * @return true if sent - */ - public boolean sendEMailAttachments (MUser from, MUser to, - String subject, String message, List attachments, boolean isHtml) - { - EMail email = createEMail(from, to, subject, message, isHtml); - if (email == null) - return false; - - if (attachments != null && !attachments.isEmpty()) - { - for (File attachment : attachments) - email.addAttachment(attachment); - } - InternetAddress emailFrom = email.getFrom(); - try - { - return sendEmailNow(from, to, email); - } - catch (Exception ex) - { - log.severe(getName() + " - from " + emailFrom - + " to " + to + ": " + ex.getLocalizedMessage()); - return false; - } - } // sendEMail - - /** - * Send EMail from Request User - no trace - * @param to recipient email address - * @param subject subject - * @param message message - * @param attachment optional attachment - * @return true if sent - */ - public boolean sendEMail (String to, - String subject, String message, File attachment) - { - return sendEMail(to, subject, message, attachment, false); - } + + /** + * Send EMail from User + * @param from sender + * @param to recipient + * @param subject subject + * @param message message + * @param attachment optional attachment + * @return true if sent + */ + public boolean sendEMailAttachments (MUser from, MUser to, + String subject, String message, List attachments) + { + return sendEMailAttachments(from, to, subject, message, attachments, false); + } + + /** + * Send EMail from User + * @param from sender + * @param to recipient + * @param subject subject + * @param message message + * @param attachment optional attachment + * @param isHtml + * @return true if sent + */ + public boolean sendEMailAttachments (MUser from, MUser to, + String subject, String message, List attachments, boolean isHtml) + { + EMail email = createEMail(from, to, subject, message, isHtml); + if (email == null) + return false; + + if (attachments != null && !attachments.isEmpty()) + { + for (File attachment : attachments) + email.addAttachment(attachment); + } + InternetAddress emailFrom = email.getFrom(); + try + { + return sendEmailNow(from, to, email); + } + catch (Exception ex) + { + log.severe(getName() + " - from " + emailFrom + + " to " + to + ": " + ex.getLocalizedMessage()); + return false; + } + } // sendEMail + + /** + * Send EMail from Request User - no trace + * @param to recipient email address + * @param subject subject + * @param message message + * @param attachment optional attachment + * @return true if sent + */ + public boolean sendEMail (String to, + String subject, String message, File attachment) + { + return sendEMail(to, subject, message, attachment, false); + } /** * Send EMail from Request User - no trace * @param to recipient email address * @param subject subject * @param message message - * @param attachment optional attachment + * @param attachment optional attachment * @param html * @return true if sent */ @@ -653,18 +653,18 @@ public class MClient extends X_AD_Client email.addAttachment(attachment); try { - String msg = null; - if (isServerEMail()) - { - msg = CConnection.get().getServer().sendEMail(Env.getRemoteCallCtx(Env.getCtx()), email); - } - else - { - msg = email.send(); + String msg = null; + if (isServerEMail()) + { + msg = CConnection.get().getServer().sendEMail(Env.getRemoteCallCtx(Env.getCtx()), email); + } + else + { + msg = email.send(); } if (EMail.SENT_OK.equals (msg)) { - if (log.isLoggable(Level.INFO)) log.info("Sent EMail " + subject + " to " + to); + if (log.isLoggable(Level.INFO)) log.info("Sent EMail " + subject + " to " + to); return true; } else @@ -676,27 +676,27 @@ public class MClient extends X_AD_Client } } catch (Exception ex) - { + { ex.printStackTrace(); log.log(Level.SEVERE, getName() + " - " + ex.getLocalizedMessage(), ex); return false; } } // sendEMail - /** - * Send EMail from User - * @param from sender - * @param to recipient - * @param subject subject - * @param message message - * @param attachment optional attachment - * @return true if sent - */ - public boolean sendEMail (MUser from, MUser to, - String subject, String message, File attachment) - { - return sendEMail(from, to, subject, message, attachment, false); - } + /** + * Send EMail from User + * @param from sender + * @param to recipient + * @param subject subject + * @param message message + * @param attachment optional attachment + * @return true if sent + */ + public boolean sendEMail (MUser from, MUser to, + String subject, String message, File attachment) + { + return sendEMail(from, to, subject, message, attachment, false); + } /** * Send EMail from User @@ -711,10 +711,10 @@ public class MClient extends X_AD_Client public boolean sendEMail (MUser from, MUser to, String subject, String message, File attachment, boolean isHtml) { - EMail email = createEMail(from, to, subject, message, isHtml); - if (email == null) - return false; - + EMail email = createEMail(from, to, subject, message, isHtml); + if (email == null) + return false; + if (attachment != null) email.addAttachment(attachment); InternetAddress emailFrom = email.getFrom(); @@ -739,14 +739,14 @@ public class MClient extends X_AD_Client */ public boolean sendEmailNow(MUser from, MUser to, EMail email) { - String msg = null; - if (isServerEMail()) - { - msg = CConnection.get().getServer().sendEMail(Env.getRemoteCallCtx(Env.getCtx()), email); - } - else - { - msg = email.send(); + String msg = null; + if (isServerEMail()) + { + msg = CConnection.get().getServer().sendEMail(Env.getRemoteCallCtx(Env.getCtx()), email); + } + else + { + msg = email.send(); } // X_AD_UserMail um = new X_AD_UserMail(getCtx(), 0, to.get_TrxName()); @@ -754,11 +754,11 @@ public class MClient extends X_AD_Client um.setAD_User_ID(to.getAD_User_ID()); um.setSubject(email.getSubject()); um.setMailText(email.getMessageCRLF()); - um.setMailText(email.getMessageCRLF()); - um.setEMailFrom(email.getFrom().toString()); - um.setRecipientTo(MUserMail.getRecipientWithCommaSeparator(email.getTos())); - um.setRecipientCc(MUserMail.getRecipientWithCommaSeparator(email.getCcs())); - um.setRecipientBcc(MUserMail.getRecipientWithCommaSeparator(email.getBccs())); + um.setMailText(email.getMessageCRLF()); + um.setEMailFrom(email.getFrom().toString()); + um.setRecipientTo(MUserMail.getRecipientWithCommaSeparator(email.getTos())); + um.setRecipientCc(MUserMail.getRecipientWithCommaSeparator(email.getCcs())); + um.setRecipientBcc(MUserMail.getRecipientWithCommaSeparator(email.getBccs())); if (email.isSentOK()) um.setMessageID(email.getMessageID()); else @@ -771,14 +771,14 @@ public class MClient extends X_AD_Client // if (email.isSentOK()) { - if (from != null) { - if (log.isLoggable(Level.INFO)) log.info("Sent Email: " + email.getSubject() + if (from != null) { + if (log.isLoggable(Level.INFO)) log.info("Sent Email: " + email.getSubject() + " from " + from.getEMail() + " to " + to.getEMail()); - } else { - if (log.isLoggable(Level.INFO)) log.info("Sent Email: " + email.getSubject() - + " to " + to.getEMail()); - } + } else { + if (log.isLoggable(Level.INFO)) log.info("Sent Email: " + email.getSubject() + + " to " + to.getEMail()); + } return true; } else @@ -795,25 +795,25 @@ public class MClient extends X_AD_Client return false; } } // sendEmailNow - - /************ - * Create EMail from Request User - * @param to recipient - * @param subject subject - * @param message message - * @return EMail - */ - public EMail createEMail (String to, - String subject, String message) - { - return createEMail(to, subject, message, false); - } /************ * Create EMail from Request User * @param to recipient - * @param subject subject - * @param message message + * @param subject subject + * @param message message + * @return EMail + */ + public EMail createEMail (String to, + String subject, String message) + { + return createEMail(to, subject, message, false); + } + + /************ + * Create EMail from Request User + * @param to recipient + * @param subject subject + * @param message message * @param html * @return EMail */ @@ -833,58 +833,58 @@ public class MClient extends X_AD_Client email.createAuthenticator (getRequestUser(), getRequestUserPW()); return email; } // createEMail - - /************ - * Create EMail with a specific from address - * @param from recipient - * @param to recipient - * @param subject subject - * @param message message - * @param html - * @return EMail - */ - public EMail createEMailFrom (String from, String to, - String subject, String message, boolean html) - { - if (from == null || from.length() == 0) - { - log.warning("No From"); - return null; - } - if (to == null || to.length() == 0) - { - log.warning("No To"); - return null; - } - // - EMail email = new EMail (this, - from, to, - subject, message, html); - if (isSmtpAuthorization()) - email.createAuthenticator (getRequestUser(), getRequestUserPW()); - return email; - } // createEMailFrom - - /** - * Create EMail from User - * @param from optional sender - * @param to recipient - * @param subject subject - * @param message message - * @return EMail - */ - public EMail createEMail (MUser from, MUser to, - String subject, String message) - { - return createEMail(from, to, subject, message, false); - } + + /************ + * Create EMail with a specific from address + * @param from recipient + * @param to recipient + * @param subject subject + * @param message message + * @param html + * @return EMail + */ + public EMail createEMailFrom (String from, String to, + String subject, String message, boolean html) + { + if (from == null || from.length() == 0) + { + log.warning("No From"); + return null; + } + if (to == null || to.length() == 0) + { + log.warning("No To"); + return null; + } + // + EMail email = new EMail (this, + from, to, + subject, message, html); + if (isSmtpAuthorization()) + email.createAuthenticator (getRequestUser(), getRequestUserPW()); + return email; + } // createEMailFrom /** * Create EMail from User * @param from optional sender * @param to recipient - * @param subject subject - * @param message message + * @param subject subject + * @param message message + * @return EMail + */ + public EMail createEMail (MUser from, MUser to, + String subject, String message) + { + return createEMail(from, to, subject, message, false); + } + + /** + * Create EMail from User + * @param from optional sender + * @param to recipient + * @param subject subject + * @param message message * @param html * @return EMail */ @@ -903,27 +903,27 @@ public class MClient extends X_AD_Client } return createEMail (from, to.getEMail(), subject, message, html); } // createEMail - - /** - * Create EMail from User - * @param from optional sender - * @param to recipient - * @param subject subject - * @param message message - * @return EMail - */ - public EMail createEMail (MUser from, String to, - String subject, String message) - { - return createEMail(from, to, subject, message, false); - } /** * Create EMail from User * @param from optional sender * @param to recipient - * @param subject subject - * @param message message + * @param subject subject + * @param message message + * @return EMail + */ + public EMail createEMail (MUser from, String to, + String subject, String message) + { + return createEMail(from, to, subject, message, false); + } + + /** + * Create EMail from User + * @param from optional sender + * @param to recipient + * @param subject subject + * @param message message * @param html * @return EMail */ @@ -941,11 +941,11 @@ public class MClient extends X_AD_Client // No From details - Error if (from.getEMail() == null || from.getEMailUser() == null - || (isSmtpAuthorization() && from.getEMailUserPW() == null) ) // is SMTP authorization and password is null - teo_sarca [ 1723309 ] + || (isSmtpAuthorization() && from.getEMailUserPW() == null) ) // is SMTP authorization and password is null - teo_sarca [ 1723309 ] { log.warning("From EMail incomplete: " + from + " (" + getName() + ")"); return null; - } + } // EMail email = new EMail (this, from.getEMail(), @@ -954,201 +954,201 @@ public class MClient extends X_AD_Client message, html); if (isSmtpAuthorization()) email.createAuthenticator (from.getEMailUser(), from.getEMailUserPW()); - if (from.getEMail() != null && ! from.getEMail().equalsIgnoreCase(from.getEMailUser())) { - email.setReplyTo(from.getEMail()); - } + if (from.getEMail() != null && ! from.getEMail().equalsIgnoreCase(from.getEMailUser())) { + email.setReplyTo(from.getEMail()); + } return email; - } // createEMail - - /* - * Is Client Accounting enabled? - * CLIENT_ACCOUNTING parameter allow the next values - * D - Disabled (default) - * Q - Queue (enabled to post by hand - queue documents for posterior processing) - * I - Immediate (immediate post - allow complete on errors) - * - * @return boolean representing if client accounting is enabled and it's on a client - */ - //private static final String CLIENT_ACCOUNTING_DISABLED = "D"; - private static final String CLIENT_ACCOUNTING_QUEUE = "Q"; - private static final String CLIENT_ACCOUNTING_IMMEDIATE = "I"; - - public static boolean isClientAccounting() { - String ca = MSysConfig.getValue(MSysConfig.CLIENT_ACCOUNTING, - CLIENT_ACCOUNTING_QUEUE, // default - Env.getAD_Client_ID(Env.getCtx())); - return (ca.equalsIgnoreCase(CLIENT_ACCOUNTING_IMMEDIATE) || ca.equalsIgnoreCase(CLIENT_ACCOUNTING_QUEUE)); - } - - public static boolean isClientAccountingQueue() { - String ca = MSysConfig.getValue(MSysConfig.CLIENT_ACCOUNTING, - CLIENT_ACCOUNTING_QUEUE, // default - Env.getAD_Client_ID(Env.getCtx())); - return ca.equalsIgnoreCase(CLIENT_ACCOUNTING_QUEUE); - } - - public static boolean isClientAccountingImmediate() { - String ca = MSysConfig.getValue(MSysConfig.CLIENT_ACCOUNTING, - CLIENT_ACCOUNTING_QUEUE, // default - Env.getAD_Client_ID(Env.getCtx())); - return ca.equalsIgnoreCase(CLIENT_ACCOUNTING_IMMEDIATE); - } - - /* 2870483 - SaaS too slow opening windows */ - /** Field Access */ - private ArrayList m_fieldAccess = null; - /** - * Define is a field is displayed based on ASP rules - * @param ad_field_id - * @return boolean indicating if it's displayed or not - */ - public boolean isDisplayField(int aDFieldID) { - if (! isUseASP()) - return true; - - if (m_fieldAccess == null) - { - m_fieldAccess = new ArrayList(11000); - StringBuilder sqlvalidate = new StringBuilder( - "SELECT AD_Field_ID ") - .append(" FROM AD_Field ") - .append(" WHERE ( AD_Field_ID NOT IN ( ") - // ASP subscribed fields for client) - .append(" SELECT f.AD_Field_ID ") - .append(" FROM ASP_Field f, ASP_Tab t, ASP_Window w, ASP_Level l, ASP_ClientLevel cl ") - .append(" WHERE w.ASP_Level_ID = l.ASP_Level_ID ") - .append(" AND cl.AD_Client_ID = ").append(getAD_Client_ID()) - .append(" AND cl.ASP_Level_ID = l.ASP_Level_ID ") - .append(" AND f.ASP_Tab_ID = t.ASP_Tab_ID ") - .append(" AND t.ASP_Window_ID = w.ASP_Window_ID ") - .append(" AND f.IsActive = 'Y' ") - .append(" AND t.IsActive = 'Y' ") - .append(" AND w.IsActive = 'Y' ") - .append(" AND l.IsActive = 'Y' ") - .append(" AND cl.IsActive = 'Y' ") - .append(" AND f.ASP_Status = 'H' ") - .append(" AND f.AD_Field_ID NOT IN (") - .append(" SELECT AD_Field_ID") - .append(" FROM ASP_ClientException ce") - .append(" WHERE ce.AD_Client_ID =").append(getAD_Client_ID()) - .append(" AND ce.IsActive = 'Y'") - .append(" AND ce.AD_Field_ID IS NOT NULL") - .append(" AND ce.ASP_Status <> 'H')") - .append(" UNION ALL ") - // minus ASP hide exceptions for client - .append(" SELECT AD_Field_ID ") - .append(" FROM ASP_ClientException ce ") - .append(" WHERE ce.AD_Client_ID = ").append(getAD_Client_ID()) - .append(" AND ce.IsActive = 'Y' ") - .append(" AND ce.AD_Field_ID IS NOT NULL ") - .append(" AND ce.ASP_Status = 'H'))") - .append(" ORDER BY AD_Field_ID"); - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sqlvalidate.toString(), get_TrxName()); - rs = pstmt.executeQuery(); - while (rs.next()) - m_fieldAccess.add(rs.getInt(1)); - } - catch (Exception e) - { - log.log(Level.SEVERE, sqlvalidate.toString(), e); - } - finally - { - DB.close(rs, pstmt); - } - } - return (Collections.binarySearch(m_fieldAccess, aDFieldID) > 0); - } - - @Override - public String getRequestUser() { - // IDEMPIERE-722 - if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { - MClient sysclient = MClient.get(getCtx(), 0); - return sysclient.getRequestUser(); - } - return super.getRequestUser(); - } - - @Override - public String getRequestUserPW() { - // IDEMPIERE-722 - if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { - MClient sysclient = MClient.get(getCtx(), 0); - return sysclient.getRequestUserPW(); - } - return super.getRequestUserPW(); - } - - @Override - public boolean isSmtpAuthorization() { - // IDEMPIERE-722 - if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { - MClient sysclient = MClient.get(getCtx(), 0); - return sysclient.isSmtpAuthorization(); - } - return super.isSmtpAuthorization(); - } - - @Override - public int getSMTPPort() { - // IDEMPIERE-722 - if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { - MClient sysclient = MClient.get(getCtx(), 0); - return sysclient.getSMTPPort(); - } - return super.getSMTPPort(); - } - - @Override - public boolean isSecureSMTP() { - // IDEMPIERE-722 - if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { - MClient sysclient = MClient.get(getCtx(), 0); - return sysclient.isSecureSMTP(); - } - return super.isSecureSMTP(); - } - - /** - * Get SMTP Host - * @return SMTP or loaclhost - */ - @Override - public String getSMTPHost() { - String s = null; - if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { - MClient sysclient = MClient.get(getCtx(), 0); - s = sysclient.getSMTPHost(); - } else { - s = super.getSMTPHost(); - } - if (s == null) - s = "localhost"; - return s; - } // getSMTPHost - - // IDEMPIERE-722 - private static final String MAIL_SEND_CREDENTIALS_USER = "U"; - private static final String MAIL_SEND_CREDENTIALS_CLIENT = "C"; - private static final String MAIL_SEND_CREDENTIALS_SYSTEM = "S"; - - public static boolean isSendCredentialsClient() { - String msc = MSysConfig.getValue(MSysConfig.MAIL_SEND_CREDENTIALS, - MAIL_SEND_CREDENTIALS_USER, // default - Env.getAD_Client_ID(Env.getCtx())); - return (MAIL_SEND_CREDENTIALS_CLIENT.equalsIgnoreCase(msc)); - } - - public static boolean isSendCredentialsSystem() { - String msc = MSysConfig.getValue(MSysConfig.MAIL_SEND_CREDENTIALS, - MAIL_SEND_CREDENTIALS_USER, // default - Env.getAD_Client_ID(Env.getCtx())); - return (MAIL_SEND_CREDENTIALS_SYSTEM.equalsIgnoreCase(msc)); - } - + } // createEMail + + /* + * Is Client Accounting enabled? + * CLIENT_ACCOUNTING parameter allow the next values + * D - Disabled (default) + * Q - Queue (enabled to post by hand - queue documents for posterior processing) + * I - Immediate (immediate post - allow complete on errors) + * + * @return boolean representing if client accounting is enabled and it's on a client + */ + //private static final String CLIENT_ACCOUNTING_DISABLED = "D"; + private static final String CLIENT_ACCOUNTING_QUEUE = "Q"; + private static final String CLIENT_ACCOUNTING_IMMEDIATE = "I"; + + public static boolean isClientAccounting() { + String ca = MSysConfig.getValue(MSysConfig.CLIENT_ACCOUNTING, + CLIENT_ACCOUNTING_QUEUE, // default + Env.getAD_Client_ID(Env.getCtx())); + return (ca.equalsIgnoreCase(CLIENT_ACCOUNTING_IMMEDIATE) || ca.equalsIgnoreCase(CLIENT_ACCOUNTING_QUEUE)); + } + + public static boolean isClientAccountingQueue() { + String ca = MSysConfig.getValue(MSysConfig.CLIENT_ACCOUNTING, + CLIENT_ACCOUNTING_QUEUE, // default + Env.getAD_Client_ID(Env.getCtx())); + return ca.equalsIgnoreCase(CLIENT_ACCOUNTING_QUEUE); + } + + public static boolean isClientAccountingImmediate() { + String ca = MSysConfig.getValue(MSysConfig.CLIENT_ACCOUNTING, + CLIENT_ACCOUNTING_QUEUE, // default + Env.getAD_Client_ID(Env.getCtx())); + return ca.equalsIgnoreCase(CLIENT_ACCOUNTING_IMMEDIATE); + } + + /* 2870483 - SaaS too slow opening windows */ + /** Field Access */ + private ArrayList m_fieldAccess = null; + /** + * Define is a field is displayed based on ASP rules + * @param ad_field_id + * @return boolean indicating if it's displayed or not + */ + public boolean isDisplayField(int aDFieldID) { + if (! isUseASP()) + return true; + + if (m_fieldAccess == null) + { + m_fieldAccess = new ArrayList(11000); + StringBuilder sqlvalidate = new StringBuilder( + "SELECT AD_Field_ID ") + .append(" FROM AD_Field ") + .append(" WHERE ( AD_Field_ID NOT IN ( ") + // ASP subscribed fields for client) + .append(" SELECT f.AD_Field_ID ") + .append(" FROM ASP_Field f, ASP_Tab t, ASP_Window w, ASP_Level l, ASP_ClientLevel cl ") + .append(" WHERE w.ASP_Level_ID = l.ASP_Level_ID ") + .append(" AND cl.AD_Client_ID = ").append(getAD_Client_ID()) + .append(" AND cl.ASP_Level_ID = l.ASP_Level_ID ") + .append(" AND f.ASP_Tab_ID = t.ASP_Tab_ID ") + .append(" AND t.ASP_Window_ID = w.ASP_Window_ID ") + .append(" AND f.IsActive = 'Y' ") + .append(" AND t.IsActive = 'Y' ") + .append(" AND w.IsActive = 'Y' ") + .append(" AND l.IsActive = 'Y' ") + .append(" AND cl.IsActive = 'Y' ") + .append(" AND f.ASP_Status = 'H' ") + .append(" AND f.AD_Field_ID NOT IN (") + .append(" SELECT AD_Field_ID") + .append(" FROM ASP_ClientException ce") + .append(" WHERE ce.AD_Client_ID =").append(getAD_Client_ID()) + .append(" AND ce.IsActive = 'Y'") + .append(" AND ce.AD_Field_ID IS NOT NULL") + .append(" AND ce.ASP_Status <> 'H')") + .append(" UNION ALL ") + // minus ASP hide exceptions for client + .append(" SELECT AD_Field_ID ") + .append(" FROM ASP_ClientException ce ") + .append(" WHERE ce.AD_Client_ID = ").append(getAD_Client_ID()) + .append(" AND ce.IsActive = 'Y' ") + .append(" AND ce.AD_Field_ID IS NOT NULL ") + .append(" AND ce.ASP_Status = 'H'))") + .append(" ORDER BY AD_Field_ID"); + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sqlvalidate.toString(), get_TrxName()); + rs = pstmt.executeQuery(); + while (rs.next()) + m_fieldAccess.add(rs.getInt(1)); + } + catch (Exception e) + { + log.log(Level.SEVERE, sqlvalidate.toString(), e); + } + finally + { + DB.close(rs, pstmt); + } + } + return (Collections.binarySearch(m_fieldAccess, aDFieldID) > 0); + } + + @Override + public String getRequestUser() { + // IDEMPIERE-722 + if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { + MClient sysclient = MClient.get(getCtx(), 0); + return sysclient.getRequestUser(); + } + return super.getRequestUser(); + } + + @Override + public String getRequestUserPW() { + // IDEMPIERE-722 + if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { + MClient sysclient = MClient.get(getCtx(), 0); + return sysclient.getRequestUserPW(); + } + return super.getRequestUserPW(); + } + + @Override + public boolean isSmtpAuthorization() { + // IDEMPIERE-722 + if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { + MClient sysclient = MClient.get(getCtx(), 0); + return sysclient.isSmtpAuthorization(); + } + return super.isSmtpAuthorization(); + } + + @Override + public int getSMTPPort() { + // IDEMPIERE-722 + if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { + MClient sysclient = MClient.get(getCtx(), 0); + return sysclient.getSMTPPort(); + } + return super.getSMTPPort(); + } + + @Override + public boolean isSecureSMTP() { + // IDEMPIERE-722 + if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { + MClient sysclient = MClient.get(getCtx(), 0); + return sysclient.isSecureSMTP(); + } + return super.isSecureSMTP(); + } + + /** + * Get SMTP Host + * @return SMTP or loaclhost + */ + @Override + public String getSMTPHost() { + String s = null; + if (getAD_Client_ID() != 0 && isSendCredentialsSystem()) { + MClient sysclient = MClient.get(getCtx(), 0); + s = sysclient.getSMTPHost(); + } else { + s = super.getSMTPHost(); + } + if (s == null) + s = "localhost"; + return s; + } // getSMTPHost + + // IDEMPIERE-722 + private static final String MAIL_SEND_CREDENTIALS_USER = "U"; + private static final String MAIL_SEND_CREDENTIALS_CLIENT = "C"; + private static final String MAIL_SEND_CREDENTIALS_SYSTEM = "S"; + + public static boolean isSendCredentialsClient() { + String msc = MSysConfig.getValue(MSysConfig.MAIL_SEND_CREDENTIALS, + MAIL_SEND_CREDENTIALS_USER, // default + Env.getAD_Client_ID(Env.getCtx())); + return (MAIL_SEND_CREDENTIALS_CLIENT.equalsIgnoreCase(msc)); + } + + public static boolean isSendCredentialsSystem() { + String msc = MSysConfig.getValue(MSysConfig.MAIL_SEND_CREDENTIALS, + MAIL_SEND_CREDENTIALS_USER, // default + Env.getAD_Client_ID(Env.getCtx())); + return (MAIL_SEND_CREDENTIALS_SYSTEM.equalsIgnoreCase(msc)); + } + } // MClient diff --git a/org.adempiere.base/src/org/compiere/model/MContainer.java b/org.adempiere.base/src/org/compiere/model/MContainer.java index 8406315fc3..a160abbe4a 100644 --- a/org.adempiere.base/src/org/compiere/model/MContainer.java +++ b/org.adempiere.base/src/org/compiere/model/MContainer.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,70 +16,70 @@ *****************************************************************************/ package org.compiere.model; -import java.sql.ResultSet; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; - -import org.compiere.util.CLogger; -import org.compiere.util.DB; +import java.sql.ResultSet; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import org.compiere.util.CLogger; +import org.compiere.util.DB; /** * Container Model * * @author Yves Sandfort - * @version $Id: MContainer.java,v 1.20 2006/09/05 23:22:53 comdivision Exp $ + * @version $Id: MContainer.java,v 1.20 2006/09/05 23:22:53 comdivision Exp $ * FR: [ 2214883 ] Remove SQL code and Replace for Query - red1/trifon - */ -public class MContainer extends X_CM_Container -{ - /** - * - */ - private static final long serialVersionUID = 3999588662066631303L; - - /** - * get Container by Relative URL - * @param ctx - * @param relURL - * @param CM_WebProject_Id - * @param trxName - * @return Container or null if not found - */ - public static MContainer get(Properties ctx, String relURL, int CM_WebProject_Id, String trxName) { - MContainer thisContainer = null; - //FR: [ 2214883 ] Remove SQL code and Replace for Query - red1/trifon - final String whereClause = "(RelativeURL LIKE ? OR RelativeURL LIKE ?) AND CM_WebProject_ID=?"; - thisContainer = new Query(ctx, I_CM_Container.Table_Name, whereClause, trxName) - .setParameters(relURL, relURL+"/",CM_WebProject_Id) - .first(); - - return thisContainer; - } - - - /** - * get Container - * @param ctx - * @param CM_Container_ID - * @param CM_WebProject_Id - * @param trxName - * @return Container or null if not found - */ - public static MContainer get(Properties ctx, int CM_Container_ID, int CM_WebProject_Id, String trxName) { - MContainer thisContainer = null; - //FR: [ 2214883 ] Remove SQL code and Replace for Query - red1/trifon - final String whereClause = "CM_Container_ID=? AND CM_WebProject_ID=?"; - thisContainer = new Query(ctx, I_CM_Container.Table_Name, whereClause, trxName) - .setParameters(CM_Container_ID, CM_WebProject_Id) - .first(); - // - return thisContainer; - } - - /** - * Copy Stage into Container - * + */ +public class MContainer extends X_CM_Container +{ + /** + * + */ + private static final long serialVersionUID = 3999588662066631303L; + + /** + * get Container by Relative URL + * @param ctx + * @param relURL + * @param CM_WebProject_Id + * @param trxName + * @return Container or null if not found + */ + public static MContainer get(Properties ctx, String relURL, int CM_WebProject_Id, String trxName) { + MContainer thisContainer = null; + //FR: [ 2214883 ] Remove SQL code and Replace for Query - red1/trifon + final String whereClause = "(RelativeURL LIKE ? OR RelativeURL LIKE ?) AND CM_WebProject_ID=?"; + thisContainer = new Query(ctx, I_CM_Container.Table_Name, whereClause, trxName) + .setParameters(relURL, relURL+"/",CM_WebProject_Id) + .first(); + + return thisContainer; + } + + + /** + * get Container + * @param ctx + * @param CM_Container_ID + * @param CM_WebProject_Id + * @param trxName + * @return Container or null if not found + */ + public static MContainer get(Properties ctx, int CM_Container_ID, int CM_WebProject_Id, String trxName) { + MContainer thisContainer = null; + //FR: [ 2214883 ] Remove SQL code and Replace for Query - red1/trifon + final String whereClause = "CM_Container_ID=? AND CM_WebProject_ID=?"; + thisContainer = new Query(ctx, I_CM_Container.Table_Name, whereClause, trxName) + .setParameters(CM_Container_ID, CM_WebProject_Id) + .first(); + // + return thisContainer; + } + + /** + * Copy Stage into Container + * * @param project WebProject * @param stage Stage to copy from * @param path Relative URL to it @@ -114,11 +114,11 @@ public class MContainer extends X_CM_Container String trxName) { MContainer cc = null; - //FR: [ 2214883 ] Remove SQL code and Replace for Query - red1/trifon - final String whereClause = "CM_Container_ID=?"; - cc = new Query(ctx, I_CM_Container.Table_Name, whereClause, trxName) - .setParameters(CM_Container_ID) - .first(); + //FR: [ 2214883 ] Remove SQL code and Replace for Query - red1/trifon + final String whereClause = "CM_Container_ID=?"; + cc = new Query(ctx, I_CM_Container.Table_Name, whereClause, trxName) + .setParameters(CM_Container_ID) + .first(); // return cc; } // getDirect @@ -132,12 +132,12 @@ public class MContainer extends X_CM_Container */ public static MContainer[] getContainers (MWebProject project) { - //FR: [ 2214883 ] Remove SQL code and Replace for Query - red1/trifon - final String whereClause = "CM_WebProject_ID=?"; - List list = new Query(project.getCtx(), I_CM_Container.Table_Name, whereClause, project.get_TrxName()) - .setParameters(project.getCM_WebProject_ID ()) - .setOrderBy("CM_Container_ID") - .list(); + //FR: [ 2214883 ] Remove SQL code and Replace for Query - red1/trifon + final String whereClause = "CM_WebProject_ID=?"; + List list = new Query(project.getCtx(), I_CM_Container.Table_Name, whereClause, project.get_TrxName()) + .setParameters(project.getCM_WebProject_ID ()) + .setOrderBy("CM_Container_ID") + .list(); // MContainer[] retValue = new MContainer[list.size ()]; list.toArray (retValue); @@ -145,7 +145,7 @@ public class MContainer extends X_CM_Container } // getContainers /** Logger */ - @SuppressWarnings("unused") + @SuppressWarnings("unused") private static CLogger s_log = CLogger.getCLogger (MContainer.class); @@ -276,20 +276,20 @@ public class MContainer extends X_CM_Container .getProperty ("java.naming.provider.url")), log, getCtx (), get_TrxName ()); // First update the new ones... - StringBuilder msgx = new StringBuilder("CM_CStage_ID=").append(stage.get_ID ()); + StringBuilder msgx = new StringBuilder("CM_CStage_ID=").append(stage.get_ID ()); int[] tableKeys = X_CM_CStage_Element.getAllIDs ("CM_CStage_Element", - msgx.toString(), trxName); + msgx.toString(), trxName); if (tableKeys != null && tableKeys.length > 0) { for (int i = 0; i < tableKeys.length; i++) { X_CM_CStage_Element thisStageElement = new X_CM_CStage_Element ( - project.getCtx (), tableKeys[i], trxName); - msgx = new StringBuilder("CM_Container_ID=") - .append(stage.get_ID ()).append(" AND Name LIKE '") - .append(thisStageElement.getName ()).append("'"); + project.getCtx (), tableKeys[i], trxName); + msgx = new StringBuilder("CM_Container_ID=") + .append(stage.get_ID ()).append(" AND Name LIKE '") + .append(thisStageElement.getName ()).append("'"); int[] thisContainerElementKeys = X_CM_Container_Element - .getAllIDs ("CM_Container_Element", msgx.toString(), trxName); + .getAllIDs ("CM_Container_Element", msgx.toString(), trxName); X_CM_Container_Element thisContainerElement; if (thisContainerElementKeys != null && thisContainerElementKeys.length > 0) @@ -322,20 +322,20 @@ public class MContainer extends X_CM_Container } } // Now we are checking the existing ones to delete the unneeded ones... - msgx = new StringBuilder("CM_Container_ID=").append(stage.get_ID ()); + msgx = new StringBuilder("CM_Container_ID=").append(stage.get_ID ()); tableKeys = X_CM_Container_Element.getAllIDs ("CM_Container_Element", - msgx.toString(), trxName); + msgx.toString(), trxName); if (tableKeys != null && tableKeys.length > 0) { for (int i = 0; i < tableKeys.length; i++) { X_CM_Container_Element thisContainerElement = new X_CM_Container_Element ( - project.getCtx (), tableKeys[i], trxName); - msgx = new StringBuilder("CM_CStage_ID=") - .append(stage.get_ID ()).append(" AND Name LIKE '") - .append(thisContainerElement.getName ()).append("'"); + project.getCtx (), tableKeys[i], trxName); + msgx = new StringBuilder("CM_CStage_ID=") + .append(stage.get_ID ()).append(" AND Name LIKE '") + .append(thisContainerElement.getName ()).append("'"); int[] thisCStageElementKeys = X_CM_CStage_Element - .getAllIDs ("CM_CStage_Element", msgx.toString(), trxName); + .getAllIDs ("CM_CStage_Element", msgx.toString(), trxName); // If we cannot find a representative in the Stage we will delete from production if (thisCStageElementKeys == null || thisCStageElementKeys.length < 1) @@ -362,20 +362,20 @@ public class MContainer extends X_CM_Container protected void updateTTables (MWebProject project, MCStage stage, String trxName) { - StringBuilder msgx = new StringBuilder("CM_CStage_ID=").append(stage.get_ID ()); + StringBuilder msgx = new StringBuilder("CM_CStage_ID=").append(stage.get_ID ()); int[] tableKeys = X_CM_CStageTTable.getAllIDs (I_CM_CStageTTable.Table_Name, - msgx.toString(), trxName); + msgx.toString(), trxName); if (tableKeys != null && tableKeys.length > 0) { for (int i = 0; i < tableKeys.length; i++) { X_CM_CStageTTable thisStageTTable = new X_CM_CStageTTable ( - project.getCtx (), tableKeys[i], trxName); - msgx = new StringBuilder("CM_Container_ID=").append(stage.get_ID ()) - .append(" AND CM_TemplateTable_ID=") - .append(thisStageTTable.getCM_TemplateTable_ID ()); + project.getCtx (), tableKeys[i], trxName); + msgx = new StringBuilder("CM_Container_ID=").append(stage.get_ID ()) + .append(" AND CM_TemplateTable_ID=") + .append(thisStageTTable.getCM_TemplateTable_ID ()); int[] thisContainerTTableKeys = X_CM_ContainerTTable.getAllIDs ( - I_CM_ContainerTTable.Table_Name, msgx.toString(), trxName); + I_CM_ContainerTTable.Table_Name, msgx.toString(), trxName); X_CM_ContainerTTable thisContainerTTable; if (thisContainerTTableKeys != null && thisContainerTTableKeys.length > 0) @@ -415,7 +415,7 @@ public class MContainer extends X_CM_Container */ public String toString () { - StringBuilder sb = new StringBuilder ("MContainer[").append (get_ID ()) + StringBuilder sb = new StringBuilder ("MContainer[").append (get_ID ()) .append ("-").append (getName ()).append ("]"); return sb.toString (); } // toString @@ -435,20 +435,20 @@ public class MContainer extends X_CM_Container return success; if (newRecord) { - StringBuilder sb = new StringBuilder ( - "INSERT INTO AD_TreeNodeCMC ") - .append("(AD_Client_ID,AD_Org_ID, IsActive,Created,CreatedBy,Updated,UpdatedBy, ") - .append("AD_Tree_ID, Node_ID, Parent_ID, SeqNo) ").append("VALUES (") + StringBuilder sb = new StringBuilder ( + "INSERT INTO AD_TreeNodeCMC ") + .append("(AD_Client_ID,AD_Org_ID, IsActive,Created,CreatedBy,Updated,UpdatedBy, ") + .append("AD_Tree_ID, Node_ID, Parent_ID, SeqNo) ").append("VALUES (") .append (getAD_Client_ID ()).append ( ",0, 'Y', SysDate, 0, SysDate, 0,").append ( getAD_Tree_ID ()).append (",").append (get_ID ()).append ( ", 0, 999)"); int no = DB.executeUpdate (sb.toString (), get_TrxName ()); - if (no > 0) { - if (log.isLoggable(Level.FINE)) log.fine ("#" + no + " - TreeType=CMC"); - } else { - log.warning ("#" + no + " - TreeType=CMC"); - } + if (no > 0) { + if (log.isLoggable(Level.FINE)) log.fine ("#" + no + " - TreeType=CMC"); + } else { + log.warning ("#" + no + " - TreeType=CMC"); + } return no > 0; } return success; @@ -456,8 +456,8 @@ public class MContainer extends X_CM_Container protected MContainerElement[] getAllElements() { - StringBuilder msgmc = new StringBuilder("CM_Container_ID=").append(get_ID()); - int elements[] = MContainerElement.getAllIDs("CM_Container_Element", msgmc.toString(), get_TrxName()); + StringBuilder msgmc = new StringBuilder("CM_Container_ID=").append(get_ID()); + int elements[] = MContainerElement.getAllIDs("CM_Container_Element", msgmc.toString(), get_TrxName()); if (elements.length>0) { MContainerElement[] containerElements = new MContainerElement[elements.length]; @@ -485,15 +485,15 @@ public class MContainer extends X_CM_Container } } // - StringBuilder sb = new StringBuilder ("DELETE FROM AD_TreeNodeCMC ") + StringBuilder sb = new StringBuilder ("DELETE FROM AD_TreeNodeCMC ") .append (" WHERE Node_ID=").append (get_ID ()).append ( " AND AD_Tree_ID=").append (getAD_Tree_ID ()); int no = DB.executeUpdate (sb.toString (), get_TrxName ()); - if (no > 0) { - if (log.isLoggable(Level.FINE)) log.fine ("#" + no + " - TreeType=CMC"); - } else { - log.warning ("#" + no + " - TreeType=CMC"); - } + if (no > 0) { + if (log.isLoggable(Level.FINE)) log.fine ("#" + no + " - TreeType=CMC"); + } else { + log.warning ("#" + no + " - TreeType=CMC"); + } return no > 0; } @@ -508,16 +508,16 @@ public class MContainer extends X_CM_Container if (!success) return success; // - StringBuilder sb = new StringBuilder ("DELETE FROM AD_TreeNodeCMC ") + StringBuilder sb = new StringBuilder ("DELETE FROM AD_TreeNodeCMC ") .append (" WHERE Node_ID=").append (get_IDOld ()).append ( " AND AD_Tree_ID=").append (getAD_Tree_ID ()); int no = DB.executeUpdate (sb.toString (), get_TrxName ()); // If 0 than there is nothing to delete which is okay. - if (no > 0) { - if (log.isLoggable(Level.FINE)) log.fine ("#" + no + " - TreeType=CMC"); - } else { - log.warning ("#" + no + " - TreeType=CMC"); - } + if (no > 0) { + if (log.isLoggable(Level.FINE)) log.fine ("#" + no + " - TreeType=CMC"); + } else { + log.warning ("#" + no + " - TreeType=CMC"); + } return true; } // afterDelete diff --git a/org.adempiere.base/src/org/compiere/model/MContainerElement.java b/org.adempiere.base/src/org/compiere/model/MContainerElement.java index 338778241e..e7852a98e7 100644 --- a/org.adempiere.base/src/org/compiere/model/MContainerElement.java +++ b/org.adempiere.base/src/org/compiere/model/MContainerElement.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,42 +16,42 @@ *****************************************************************************/ package org.compiere.model; -import java.sql.ResultSet; -import java.util.Properties; - -import org.compiere.util.CLogger; +import java.sql.ResultSet; +import java.util.Properties; + +import org.compiere.util.CLogger; /** * CStage Element * * @author Yves Sandfort * @version $Id$ - */ -public class MContainerElement extends X_CM_Container_Element -{ - /** - * - */ - private static final long serialVersionUID = 8487403111353473486L; - - /** Logger */ - @SuppressWarnings("unused") - private static CLogger s_log = CLogger.getCLogger (MContainerElement.class); - - /** - * get Container Element by ID - * @param ctx - * @param CM_ContainerElement_ID - * @param trxName - * @return ContainerElement - */ - public static MContainerElement get(Properties ctx, int CM_ContainerElement_ID, String trxName) { - return new MContainerElement(ctx, CM_ContainerElement_ID, trxName); - } - - /*************************************************************************** - * Standard Constructor - * + */ +public class MContainerElement extends X_CM_Container_Element +{ + /** + * + */ + private static final long serialVersionUID = 8487403111353473486L; + + /** Logger */ + @SuppressWarnings("unused") + private static CLogger s_log = CLogger.getCLogger (MContainerElement.class); + + /** + * get Container Element by ID + * @param ctx + * @param CM_ContainerElement_ID + * @param trxName + * @return ContainerElement + */ + public static MContainerElement get(Properties ctx, int CM_ContainerElement_ID, String trxName) { + return new MContainerElement(ctx, CM_ContainerElement_ID, trxName); + } + + /*************************************************************************** + * Standard Constructor + * * @param ctx context * @param CM_Container_Element_ID id * @param trxName transaction diff --git a/org.adempiere.base/src/org/compiere/model/MDepreciationWorkfile.java b/org.adempiere.base/src/org/compiere/model/MDepreciationWorkfile.java index 7199e268a2..6d7b34e866 100644 --- a/org.adempiere.base/src/org/compiere/model/MDepreciationWorkfile.java +++ b/org.adempiere.base/src/org/compiere/model/MDepreciationWorkfile.java @@ -1,789 +1,789 @@ -package org.compiere.model; - -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.Timestamp; -import java.util.Collection; -import java.util.Properties; -import java.util.logging.Level; - -import org.apache.commons.collections.keyvalue.MultiKey; -import org.compiere.util.CCache; -import org.compiere.util.CLogMgt; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.TimeUtil; -import org.idempiere.fa.feature.UseLife; -import org.idempiere.fa.feature.UseLifeImpl; - - -/** - * Depreciation Workfile Model - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - */ -public class MDepreciationWorkfile extends X_A_Depreciation_Workfile - implements UseLife -{ - /** - * - */ - private static final long serialVersionUID = -3814417671427820714L; - - /** - * Default Constructor - * @param ctx context - * @param M_InventoryLine_ID line - */ - public MDepreciationWorkfile (Properties ctx, int A_Depreciation_Workfile_ID, String trxName) - { - super (ctx,A_Depreciation_Workfile_ID, trxName); - if (A_Depreciation_Workfile_ID == 0) - { - setPostingType(POSTINGTYPE_Actual); - setA_QTY_Current(Env.ZERO); - setA_Asset_Cost(Env.ZERO); - setA_Accumulated_Depr(Env.ZERO); - setA_Period_Posted(0); - setA_Current_Period(0); - } - } // MDepreciationWorkfile - - /** - * Load Constructor - * @param ctx context - * @param rs result set - */ - public MDepreciationWorkfile (Properties ctx, ResultSet rs, String trxName) - { - super (ctx, rs, trxName); - } // MDepreciationWorkfile - - /** Asset (parent) */ - private MAsset m_asset = null; - - /** Get Asset */ - public MAsset getAsset() { - return getAsset(false); - } - - /** Get asset using this trxName - * @param requery requery asset - * @return parent asset - */ - public MAsset getAsset(boolean requery) - { - if (m_asset == null || requery) { - m_asset = MAsset.get(getCtx(), getA_Asset_ID(), get_TrxName()); - } - if (m_asset.get_ID() <= 0) { - m_asset = null; - } - return m_asset; - } - - /** Set asset - * @param asset - */ - public void setAsset(MAsset asset) - { - setA_Asset_ID(asset.get_ID()); - m_asset = asset; - } - - /** Gets asset's service date (commissioning) - * @return asset service date - */ - - public Timestamp getAssetServiceDate() - { - MAsset asset = getAsset(); - if (asset == null) { - return null; - } - return asset.getAssetServiceDate(); - } - - - /** Gets asset's class - * @return asset class id +package org.compiere.model; + +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.sql.Timestamp; +import java.util.Collection; +import java.util.Properties; +import java.util.logging.Level; + +import org.apache.commons.collections.keyvalue.MultiKey; +import org.compiere.util.CCache; +import org.compiere.util.CLogMgt; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.TimeUtil; +import org.idempiere.fa.feature.UseLife; +import org.idempiere.fa.feature.UseLifeImpl; + + +/** + * Depreciation Workfile Model + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + */ +public class MDepreciationWorkfile extends X_A_Depreciation_Workfile + implements UseLife +{ + /** + * */ - /* commented out by @win - public int getA_Asset_Class_ID() - { - MAsset asset = getAsset(); - if (asset == null) { - return 0; - } - return asset.getA_Asset_Class_ID(); + private static final long serialVersionUID = -3814417671427820714L; + + /** + * Default Constructor + * @param ctx context + * @param M_InventoryLine_ID line + */ + public MDepreciationWorkfile (Properties ctx, int A_Depreciation_Workfile_ID, String trxName) + { + super (ctx,A_Depreciation_Workfile_ID, trxName); + if (A_Depreciation_Workfile_ID == 0) + { + setPostingType(POSTINGTYPE_Actual); + setA_QTY_Current(Env.ZERO); + setA_Asset_Cost(Env.ZERO); + setA_Accumulated_Depr(Env.ZERO); + setA_Period_Posted(0); + setA_Current_Period(0); + } + } // MDepreciationWorkfile + + /** + * Load Constructor + * @param ctx context + * @param rs result set + */ + public MDepreciationWorkfile (Properties ctx, ResultSet rs, String trxName) + { + super (ctx, rs, trxName); + } // MDepreciationWorkfile + + /** Asset (parent) */ + private MAsset m_asset = null; + + /** Get Asset */ + public MAsset getAsset() { + return getAsset(false); } - */ // end comment by @win - - /** After save - * @param newRecord - * @return true on success - */ - protected boolean afterSave (boolean newRecord) - { - if(m_buildDepreciation) - { - buildDepreciation(); - } - return true; - } - - - protected boolean beforeSave (boolean newRecord) - { - if (log.isLoggable(Level.INFO)) log.info ("Entering: trxName=" + get_TrxName()); - - // copy UseLife to A_Life - if (newRecord) { //@win: should only update only if newrecord - setA_Life_Period(getUseLifeMonths()); - setA_Asset_Life_Years(getUseLifeYears()); - setA_Life_Period_F(getUseLifeMonths_F()); - setA_Asset_Life_Years_F(getUseLifeYears_F()); - } - - // If it is fully amortized, change the state's FA - MAsset asset = getAsset(true); - if (MAsset.A_ASSET_STATUS_Activated.equals(asset.getA_Asset_Status()) - && isFullyDepreciated()) - { - asset.changeStatus(MAsset.A_ASSET_STATUS_Depreciated, null); - asset.saveEx(); - } - - // Fix DateAcct - if(is_ValueChanged(COLUMNNAME_DateAcct)) - { - setDateAcct(TimeUtil.getMonthLastDay(getDateAcct())); - } - - // - BigDecimal cost = getA_Asset_Cost(); - BigDecimal accumDep_C = getA_Accumulated_Depr(); - setA_Asset_Remaining(cost.subtract(accumDep_C)); - BigDecimal accumDep_F = getA_Accumulated_Depr_F(); - setA_Asset_Remaining_F(cost.subtract(accumDep_F)); - - // Financing - { - String mainColumnName = null; - if (newRecord || is_ValueChanged(COLUMNNAME_A_Asset_Cost)) - { - mainColumnName = COLUMNNAME_A_Asset_Cost; - } - else if (is_ValueChanged(COLUMNNAME_A_Valoare_Cofinantare)) - { - mainColumnName = COLUMNNAME_A_Valoare_Cofinantare; - } - else if (is_ValueChanged(COLUMNNAME_A_Valoare_Tert)) - { - mainColumnName = COLUMNNAME_A_Valoare_Tert; - } - updateFinantare(this, mainColumnName); - } - - - if (log.isLoggable(Level.INFO)) log.info("Leaving: trxName=" + get_TrxName() + " [RETURN TRUE]"); - return true; - } // beforeSave - - /** - * Asset is fully depreciated - *
      - *
    • If PostingType != ACTUAL then return false - *
    • Do not check your current asset - *
    - * @return true if the asset is fully depreciated, false otherwise - */ - public boolean isFullyDepreciated() - { - if(!getPostingType().equals(POSTINGTYPE_Actual)) - { - return false; - } - - // check if is fully depreciated - BigDecimal remainingAmt_C = getRemainingCost(null, false); - BigDecimal remainingAmt_F = getRemainingCost(null, true); - if(remainingAmt_C.signum() == 0 && remainingAmt_F.signum() == 0) - { - //if A_Asset_Cost is 0 have a voided addition, in this case asset is not full depreciated - if (getA_Asset_Cost().signum() == 0) - { - return false; - } - // - return true; - } - - return false; - } - - /** - * - */ - public MDepreciationWorkfile(MAsset asset, String postingType, MAssetGroupAcct assetgrpacct) - { - this(asset.getCtx(), 0, asset.get_TrxName()); - setA_Asset_ID(asset.getA_Asset_ID()); - setAD_Org_ID(asset.getAD_Org_ID()); //@win added - setA_Asset_Cost(asset.getA_Asset_Cost()); - setA_Accumulated_Depr(asset.getA_Accumulated_Depr()); - setA_Accumulated_Depr_F(asset.getA_Accumulated_Depr_F()); - setA_Current_Period(asset.getA_Current_Period()); - - setIsDepreciated(asset.isDepreciated()); - setPostingType(postingType); - // - // Copy UseLife values from asset group to workfile - if (assetgrpacct == null) - { - assetgrpacct = MAssetGroupAcct.forA_Asset_Group_ID(asset.getCtx(), asset.getA_Asset_Group_ID(), postingType); - } - UseLifeImpl.copyValues(this, assetgrpacct); - - // - // Set Date Acct from Asset - Timestamp dateAcct = asset.getDateAcct(); - if (dateAcct != null) - { - dateAcct = TimeUtil.addMonths(dateAcct, 1); - setDateAcct(dateAcct); - } - // - // Set UseLife values from asset (if any) - if (asset.getUseLifeMonths() > 0) - { - UseLifeImpl.get(this, false).setUseLifeMonths(asset.getUseLifeMonths()); - } - if (asset.getUseLifeMonths_F() > 0) - { - UseLifeImpl.get(this, true).setUseLifeMonths(asset.getUseLifeMonths_F()); - } - // - dump(); - } - - /** Logger */ - private CLogger log = CLogger.getCLogger(getClass()); - - public static Collection forA_Asset_ID(Properties ctx, int asset_id, String trxName) - { - return new Query(ctx, Table_Name, MDepreciationWorkfile.COLUMNNAME_A_Asset_ID+"=?", trxName) - .setParameters(new Object[]{asset_id}) - .list(); - } - - /** - * - * @param ctx - * @param A_Asset_ID - * @param postingType - * @return workfile - * @see #get(Properties, int, String, String) - */ - public static MDepreciationWorkfile get (Properties ctx, int A_Asset_ID, String postingType) - { - return get(ctx, A_Asset_ID, postingType, null); - } - - /** - * Get/load workfile from cache (if trxName is null) - * @param ctx - * @param A_Asset_ID - * @param postingType - * @param trxName - * @return workfile - */ - public static MDepreciationWorkfile get (Properties ctx, int A_Asset_ID, String postingType, String trxName) - { - if (A_Asset_ID <= 0 || postingType == null) - { - return null; - } - - final MultiKey key = new MultiKey(A_Asset_ID, postingType); - if (trxName == null) - { - MDepreciationWorkfile wk = s_cacheAsset.get(key); - if (wk != null) - return wk; - } - /* @win temporary change as this code is causing duplicate create MDepreciationWorkfile on asset addition - final String whereClause = COLUMNNAME_A_Asset_ID+"=?" - +" AND "+COLUMNNAME_PostingType+"=? AND "+COLUMNNAME_A_QTY_Current+">?"; - MDepreciationWorkfile wk = new Query(ctx, MDepreciationWorkfile.Table_Name, whereClause, trxName) - .setParameters(new Object[]{A_Asset_ID, postingType, 0}) - .firstOnly(); - */ - final String whereClause = COLUMNNAME_A_Asset_ID+"=?" - +" AND "+COLUMNNAME_PostingType+"=? "; - MDepreciationWorkfile wk = new Query(ctx, MDepreciationWorkfile.Table_Name, whereClause, trxName) - .setParameters(new Object[]{A_Asset_ID, postingType}) - .firstOnly(); - - - if (trxName == null && wk != null) - { - s_cacheAsset.put(key, wk); - } - return wk; - } - /** Static cache: Asset/PostingType -> Workfile */ - private static CCache - s_cacheAsset = new CCache(Table_Name, Table_Name+"_Asset", 10); - - /** Returns the date of the last action - */ - public Timestamp getLastActionDate() - { - return TimeUtil.getMonthLastDay(TimeUtil.addMonths(getDateAcct(), -1)); - } - - /** Check if the asset is depreciated at the specified date - * @param date - * @return true if you amortized until the specified date, otherwise false - */ - public boolean isDepreciated(Timestamp date) - { - Timestamp lastActionDate = getLastActionDate(); - boolean isDepr = !date.after(lastActionDate); // date <= lastActionDate - - if (log.isLoggable(Level.FINE)) log.fine("LastActionDate=" + lastActionDate + ", GivenDate=" + date + " => isDepreciated=" + isDepr); - return isDepr; - } - - /** - * Get Asset Accounting for this workfile - * @return asset accounting model - */ - public MAssetAcct getA_AssetAcct(Timestamp dateAcct, String trxName) - { - return MAssetAcct.forA_Asset_ID(getCtx(), getA_Asset_ID(), getPostingType(), dateAcct, trxName); - } - - /** Returns the current cost of FAs. It is calculated as the difference between acquisition value and the value that you (A_Salvage_Value) - * @return the current cost of FAs - */ - public BigDecimal getActualCost() - { - return getActualCost(getA_Asset_Cost()); - } - - /** */ - public BigDecimal getActualCost(BigDecimal assetCost) - { - return assetCost.subtract(getA_Salvage_Value()); - } - - /** - * - * @param deltaAmt - * @param deltaQty - * @param reset - */ - public void adjustCost(BigDecimal deltaAmt, BigDecimal deltaQty, boolean reset) - { - BigDecimal newCost = Env.ZERO; - BigDecimal newQty = Env.ZERO; - if (!reset) - { - newCost = getA_Asset_Cost(); - newQty = getA_QTY_Current(); - } - newCost = newCost.add(deltaAmt); - newQty = newQty.add(deltaQty); - - // TODO: crashes if I cancel an Issue: -// if (newQty.signum() < 0) { -// throw new ArhRuntimeException(getCtx(), "@A_QTY_Current@ < 0"); -// } - - // - // There must be verified that the remaining value to be greater than the amount diminished - // total devaluation because if the entire asset value (A_Asset_Cost) must be brought to 0. -// if (deltaAmt.signum() < 0) -// { -// BigDecimal remainingAmt_C = getRemainingCost(null, false); -// if (remainingAmt_C.compareTo(deltaAmt.negate()) < 0) -// { -// throw new ArhRuntimeException(getCtx(), "@A_Asset_Remaining@ < @DeltaAmt@") -// .addInfo("@A_Asset_Cost@=", getA_Asset_Cost()) -// .addInfo("@A_Accumulated_Depr@=", getA_Accumulated_Depr()); -// } -// BigDecimal remainingAmt_F = getRemainingCost(null, true); -// if (remainingAmt_F.compareTo(deltaAmt.negate()) < 0) -// { -// throw new ArhRuntimeException(getCtx(), "@A_Asset_Remaining_F@ < @DeltaAmt@") -// .addInfo("@A_Asset_Cost=@", getA_Asset_Cost()) -// .addInfo("@A_Accumulated_Depr@=", getA_Accumulated_Depr_F()); -// } -// } - - setA_Asset_Cost(newCost); - setA_QTY_Current(newQty); - - if (log.isLoggable(Level.FINE)) log.fine("adjustCost(" + deltaAmt + ", " + deltaQty + ", reset=" + reset + ") => amt=" + getA_Asset_Cost() + ", qty=" + getA_QTY_Current()); - } - - /** - * Adjust Accumulated depreciation - * @param amt - * @param amt_F - * @param reset - * @return - */ - public boolean adjustAccumulatedDepr(BigDecimal amt, BigDecimal amt_F, boolean reset) - { - if (amt == null) - { - amt = Env.ZERO; - } - if (amt_F == null) - { - amt_F = Env.ZERO; - } - setA_Accumulated_Depr(amt.add(reset ? Env.ZERO : getA_Accumulated_Depr())); - setA_Accumulated_Depr_F(amt_F.add(reset ? Env.ZERO : getA_Accumulated_Depr_F())); - return true; - } - - /** - * Adjust use life years - */ - public void adjustUseLife(int deltaUseLifeYears, int deltaUseLifeYears_F, boolean reset) - { - if (log.isLoggable(Level.FINE)) log.fine("Entering: deltaUseLifeYears=" + deltaUseLifeYears + ", deltaUseLifeYears_F=" + deltaUseLifeYears_F); - // - UseLifeImpl.get(this, false).adjustUseLifeYears(deltaUseLifeYears, reset); - UseLifeImpl.get(this, true).adjustUseLifeYears(deltaUseLifeYears_F, reset); - // - if (log.isLoggable(Level.FINE)) log.fine("Leaving"); - } - - /** */ - public int getUseLifeMonths(boolean fiscal) - { - return fiscal ? getUseLifeMonths_F() : getUseLifeMonths(); - } - - /** */ - public BigDecimal getA_Accumulated_Depr(boolean fiscal) - { - return fiscal ? getA_Accumulated_Depr_F() : getA_Accumulated_Depr(); - } - - /** */ - public BigDecimal getAccumulatedCost() - { - return getA_Accumulated_Depr(isFiscal()); - } - - /** */ - public BigDecimal getReevaluationCost() - { - return Env.ZERO; - } - - /** - * Returns the residual (remaining) value - */ - public BigDecimal getRemainingCost(BigDecimal accumAmt, boolean fiscal) - { - BigDecimal cost = getActualCost(); - if (accumAmt == null) { - accumAmt = getA_Accumulated_Depr(fiscal); - } - return cost.subtract(accumAmt); - } - - /** - * Returns the residual (remaining) value - */ - public BigDecimal getRemainingCost(BigDecimal accumAmt) - { - return getRemainingCost(accumAmt, isFiscal()); - } - - /** */ - public int getRemainingPeriods(int A_Current_Period, MDepreciation method) - { - int useLifePeriods = getUseLifeMonths(isFiscal()); - if (method != null) { - useLifePeriods += method.getFixMonthOffset(); - } - int currentPeriod = (A_Current_Period >= 0 ? A_Current_Period : getA_Current_Period()); - return useLifePeriods - currentPeriod; - } - /** */ - public int getRemainingPeriods(int A_Current_Period) - { - return getRemainingPeriods(A_Current_Period, null); - } - - /** */ - private boolean m_isFiscal = false; - /** */ - public boolean isFiscal() - { - return m_isFiscal; - } - /** - * Set fiscal flag (temporary - is not modifing the workfile) - * @param fiscal - */ - public void setFiscal(boolean fiscal) - { - m_isFiscal = fiscal; - } - - /** Increment the current period (A_Current_Period) 1, and a month DateAcct */ - public void incA_Current_Period() - { - int old_period = getA_Current_Period(); - Timestamp old_date = getDateAcct(); - int new_period = old_period + 1; - Timestamp new_date = TimeUtil.addMonths(getDateAcct(), 1); - setA_Current_Period(new_period); - setDateAcct(new_date); - // - if (log.isLoggable(Level.FINE)) log.fine("(A_Current_Period, DateAcct)=(" + old_period + ", " + old_date + ")->(" + new_period + ", " + new_date + ")"); - } - - /** - * Set A Current Period (and Data Act) processed just after the last expense. - * Do not save. - */ - public void setA_Current_Period() - { - String whereClause = MDepreciationExp.COLUMNNAME_A_Asset_ID+"=?" - +" AND "+MDepreciationExp.COLUMNNAME_PostingType+"=?" - +" AND "+MDepreciationExp.COLUMNNAME_Processed+"=? AND IsActive=?" - ; - // - MDepreciationExp depexp = new Query(getCtx(), MDepreciationExp.Table_Name, whereClause, get_TrxName()) - .setParameters(new Object[]{getA_Asset_ID(), getPostingType(), true, true}) - .setOrderBy(MDepreciationExp.COLUMNNAME_A_Period+" DESC" - +","+MDepreciationExp.COLUMNNAME_DateAcct+" DESC") - .first(); - if (depexp != null) - { - setA_Current_Period(depexp.getA_Period()); - setDateAcct(depexp.getDateAcct()); - incA_Current_Period(); - } - else - { - log.info("There are no records from which to infer its"); - } - - } - - /** Build depreciation flag - if true, the depreciation should be built after save */ - private boolean m_buildDepreciation = false; - - /** - * Build depreciation (A_Depreciation_Exp) entries. More exactly, is deleting not Processed entries. - * and create new ones again. - * WARNING: IS NOT modifying workfile (this) - */ - - public void buildDepreciation() - { - if (!isDepreciated()) - { - return; - } - - StringBuilder sb = new StringBuilder(); - load(get_TrxName()); // reload workfile - MAssetAcct assetacct = getA_AssetAcct(null, get_TrxName()); - // TODO: teo_sarca: need to evaluate what happens when we change Depreciation method !!! - MDepreciation depreciation_C = MDepreciation.get(getCtx(), assetacct.getA_Depreciation_ID()); - MDepreciation depreciation_F = MDepreciation.get(getCtx(), assetacct.getA_Depreciation_F_ID()); - //~ int offset_C = depreciation_C.getFixMonthOffset(); - //~ int offset_F = depreciation_F.getFixMonthOffset(); - int offset_C = 0, offset_F = 0; - - BigDecimal assetCost = getActualCost(); - BigDecimal accumDep_C = getA_Accumulated_Depr(false); - BigDecimal accumDep_F = getA_Accumulated_Depr(true); - int lifePeriods_C = getUseLifeMonths(false) + offset_C; - int lifePeriods_F = getUseLifeMonths(true) + offset_F; - int lifePeriods = (lifePeriods_C > lifePeriods_F ? lifePeriods_C : lifePeriods_F); - BigDecimal exp_C = Env.ZERO; - BigDecimal exp_F = Env.ZERO; - - //logging - if(CLogMgt.isLevelFine()) - { - sb.append("currentPeriod=" + getA_Current_Period() + ", AssetServiceDate=" + getAssetDepreciationDate() + "\n"); - sb.append("offset: C|F=" + offset_C + "|" + offset_F + "\n"); - sb.append("life: C|F=" + lifePeriods_C + "|" + lifePeriods_F + " + offset =" + lifePeriods + "\n"); - } - - truncDepreciation(); - int A_Current_Period = getA_Current_Period(); - for (int currentPeriod = A_Current_Period, cnt = 1; currentPeriod <= lifePeriods; currentPeriod++, cnt++) - { - exp_C = Env.ZERO; - exp_F = Env.ZERO; - - String help = "" + accumDep_C + "|" + accumDep_F + " + "; - - if (lifePeriods_C > currentPeriod || !depreciation_C.requireLastPeriodAdjustment()) - { - setFiscal(false); - exp_C = depreciation_C.invoke(this, assetacct, currentPeriod, accumDep_C); - accumDep_C = accumDep_C.add(exp_C); - } - else if (lifePeriods_C == currentPeriod) - { // last period - exp_C = assetCost.subtract(accumDep_C); - accumDep_C = assetCost; - } - - if (lifePeriods_F > currentPeriod || !depreciation_F.requireLastPeriodAdjustment()) - { - setFiscal(true); - exp_F = depreciation_F.invoke(this, assetacct, currentPeriod, accumDep_F); - accumDep_F = accumDep_F.add(exp_F); - } - else if (lifePeriods_F == currentPeriod) - { // last period (fiscal) - exp_F = assetCost.subtract(accumDep_F); - accumDep_F = assetCost; - } - - help += "" + exp_C + "|" + exp_F + " = " + accumDep_C + "|" + accumDep_F; - - // added by zuhri - int months = 0; - - months = months + (currentPeriod - A_Current_Period); - Timestamp dateAcct = TimeUtil.getMonthLastDay(TimeUtil.addMonths(getDateAcct(), months)); - - MDepreciationExp.createDepreciation (this, currentPeriod, dateAcct, - exp_C, exp_F, - accumDep_C, accumDep_F, - help, get_TrxName()); - if (log.isLoggable(Level.FINE)) - { - String info = "" + cnt + ": period=" + currentPeriod + "/" + lifePeriods_C + "|" + lifePeriods_F - + ", exp=" + exp_C + "|" + exp_F + ", accumDep=" + accumDep_C + "|" + accumDep_F - + ", DateAcct=" + dateAcct; - log.fine("=> " + info + Env.NL + Env.NL); - sb.append(info + Env.NL); - } - } // for - if (log.isLoggable(Level.FINE)) log.fine(sb.toString()); - - m_buildDepreciation = false; - } // buildDepreciation - - - - /** - * Truncate not processed depreciation entries. - * IS NOT modifying workfile. - */ - public void truncDepreciation() - { - String trxName = get_TrxName(); - - int A_Current_Period = getA_Current_Period(); - final String sql = "DELETE FROM "+MDepreciationExp.Table_Name - +" WHERE " - +MDepreciationExp.COLUMNNAME_Processed+"=?" - +" AND "+MDepreciationExp.COLUMNNAME_A_Period+">=?" - +" AND "+MDepreciationExp.COLUMNNAME_A_Asset_ID+"=?" - +" AND "+MDepreciationExp.COLUMNNAME_PostingType+"=?" - ; - Object[] params = new Object[]{false, A_Current_Period, getA_Asset_ID(), getPostingType()}; - int no = DB.executeUpdateEx(sql, params, trxName); - if (log.isLoggable(Level.FINE)) log.fine("sql=" + sql + "\nDeleted #" + no); - } // truncDepreciation - - /** - * Update Founding Mode related fields - * @param m model - * @param changedColumnName column name that has been changed - */ - public static void updateFinantare(SetGetModel m, String changedColumnName) - { - //Own contribution: - BigDecimal valCofinantare = SetGetUtil.get_AttrValueAsBigDecimal(m, COLUMNNAME_A_Valoare_Cofinantare); - // Asset Value: - BigDecimal assetCost = SetGetUtil.get_AttrValueAsBigDecimal(m, COLUMNNAME_A_Asset_Cost); - // Third value: - BigDecimal valTert = SetGetUtil.get_AttrValueAsBigDecimal(m, COLUMNNAME_A_Valoare_Tert); - - // Calculate values - if (valCofinantare.signum() == 0 && valTert.signum() == 0) - { - // Values ​​have never been set, so put everything on their own financing - valCofinantare = assetCost; - valTert = Env.ZERO; - } - else if (COLUMNNAME_A_Asset_Cost.equals(changedColumnName)) - { - valCofinantare = assetCost.subtract(valTert); - } - else if (COLUMNNAME_A_Valoare_Cofinantare.equals(changedColumnName)) - { - valTert = assetCost.subtract(valCofinantare); - } - else if (COLUMNNAME_A_Valoare_Tert.equals(changedColumnName)) - { - valCofinantare = assetCost.subtract(valTert); - } - else - { - valTert = assetCost.subtract(valCofinantare); - } - - // Financing Type - String tipFinantare = A_TIP_FINANTARE_Cofinantare; - if (valTert.signum() == 0) - { - tipFinantare = A_TIP_FINANTARE_Proprie; - } - else if (valCofinantare.signum() == 0) - { - tipFinantare = A_TIP_FINANTARE_Terti; - } - // - // Set values - m.set_AttrValue(COLUMNNAME_A_Tip_Finantare, tipFinantare); - m.set_AttrValue(COLUMNNAME_A_Valoare_Cofinantare, valCofinantare); - m.set_AttrValue(COLUMNNAME_A_Valoare_Tert, valTert); - // - // If the method is invoked for a persistent object when reset mode of financing - if (A_TIP_FINANTARE_Proprie.equals(tipFinantare) && SetGetUtil.isPersistent(m)) - { - m.set_AttrValue(COLUMNNAME_A_FundingMode_ID, null); - } - } - - public boolean set_AttrValue(String ColumnName, Object value) { - int index = get_ColumnIndex(ColumnName); - if (index < 0) - return false; - return set_ValueNoCheck(ColumnName, value); - } - public Object get_AttrValue(String ColumnName) { - int index = get_ColumnIndex(ColumnName); - if (index < 0) - return null; - return get_Value(index); - } - public boolean is_AttrValueChanged(String ColumnName) { - int index = get_ColumnIndex(ColumnName); - if (index < 0) - return false; - return is_ValueChanged(index); - } -} // MDepreciationWorkfile + + /** Get asset using this trxName + * @param requery requery asset + * @return parent asset + */ + public MAsset getAsset(boolean requery) + { + if (m_asset == null || requery) { + m_asset = MAsset.get(getCtx(), getA_Asset_ID(), get_TrxName()); + } + if (m_asset.get_ID() <= 0) { + m_asset = null; + } + return m_asset; + } + + /** Set asset + * @param asset + */ + public void setAsset(MAsset asset) + { + setA_Asset_ID(asset.get_ID()); + m_asset = asset; + } + + /** Gets asset's service date (commissioning) + * @return asset service date + */ + + public Timestamp getAssetServiceDate() + { + MAsset asset = getAsset(); + if (asset == null) { + return null; + } + return asset.getAssetServiceDate(); + } + + + /** Gets asset's class + * @return asset class id + */ + /* commented out by @win + public int getA_Asset_Class_ID() + { + MAsset asset = getAsset(); + if (asset == null) { + return 0; + } + return asset.getA_Asset_Class_ID(); + } + */ // end comment by @win + + /** After save + * @param newRecord + * @return true on success + */ + protected boolean afterSave (boolean newRecord) + { + if(m_buildDepreciation) + { + buildDepreciation(); + } + return true; + } + + + protected boolean beforeSave (boolean newRecord) + { + if (log.isLoggable(Level.INFO)) log.info ("Entering: trxName=" + get_TrxName()); + + // copy UseLife to A_Life + if (newRecord) { //@win: should only update only if newrecord + setA_Life_Period(getUseLifeMonths()); + setA_Asset_Life_Years(getUseLifeYears()); + setA_Life_Period_F(getUseLifeMonths_F()); + setA_Asset_Life_Years_F(getUseLifeYears_F()); + } + + // If it is fully amortized, change the state's FA + MAsset asset = getAsset(true); + if (MAsset.A_ASSET_STATUS_Activated.equals(asset.getA_Asset_Status()) + && isFullyDepreciated()) + { + asset.changeStatus(MAsset.A_ASSET_STATUS_Depreciated, null); + asset.saveEx(); + } + + // Fix DateAcct + if(is_ValueChanged(COLUMNNAME_DateAcct)) + { + setDateAcct(TimeUtil.getMonthLastDay(getDateAcct())); + } + + // + BigDecimal cost = getA_Asset_Cost(); + BigDecimal accumDep_C = getA_Accumulated_Depr(); + setA_Asset_Remaining(cost.subtract(accumDep_C)); + BigDecimal accumDep_F = getA_Accumulated_Depr_F(); + setA_Asset_Remaining_F(cost.subtract(accumDep_F)); + + // Financing + { + String mainColumnName = null; + if (newRecord || is_ValueChanged(COLUMNNAME_A_Asset_Cost)) + { + mainColumnName = COLUMNNAME_A_Asset_Cost; + } + else if (is_ValueChanged(COLUMNNAME_A_Valoare_Cofinantare)) + { + mainColumnName = COLUMNNAME_A_Valoare_Cofinantare; + } + else if (is_ValueChanged(COLUMNNAME_A_Valoare_Tert)) + { + mainColumnName = COLUMNNAME_A_Valoare_Tert; + } + updateFinantare(this, mainColumnName); + } + + + if (log.isLoggable(Level.INFO)) log.info("Leaving: trxName=" + get_TrxName() + " [RETURN TRUE]"); + return true; + } // beforeSave + + /** + * Asset is fully depreciated + *
      + *
    • If PostingType != ACTUAL then return false + *
    • Do not check your current asset + *
    + * @return true if the asset is fully depreciated, false otherwise + */ + public boolean isFullyDepreciated() + { + if(!getPostingType().equals(POSTINGTYPE_Actual)) + { + return false; + } + + // check if is fully depreciated + BigDecimal remainingAmt_C = getRemainingCost(null, false); + BigDecimal remainingAmt_F = getRemainingCost(null, true); + if(remainingAmt_C.signum() == 0 && remainingAmt_F.signum() == 0) + { + //if A_Asset_Cost is 0 have a voided addition, in this case asset is not full depreciated + if (getA_Asset_Cost().signum() == 0) + { + return false; + } + // + return true; + } + + return false; + } + + /** + * + */ + public MDepreciationWorkfile(MAsset asset, String postingType, MAssetGroupAcct assetgrpacct) + { + this(asset.getCtx(), 0, asset.get_TrxName()); + setA_Asset_ID(asset.getA_Asset_ID()); + setAD_Org_ID(asset.getAD_Org_ID()); //@win added + setA_Asset_Cost(asset.getA_Asset_Cost()); + setA_Accumulated_Depr(asset.getA_Accumulated_Depr()); + setA_Accumulated_Depr_F(asset.getA_Accumulated_Depr_F()); + setA_Current_Period(asset.getA_Current_Period()); + + setIsDepreciated(asset.isDepreciated()); + setPostingType(postingType); + // + // Copy UseLife values from asset group to workfile + if (assetgrpacct == null) + { + assetgrpacct = MAssetGroupAcct.forA_Asset_Group_ID(asset.getCtx(), asset.getA_Asset_Group_ID(), postingType); + } + UseLifeImpl.copyValues(this, assetgrpacct); + + // + // Set Date Acct from Asset + Timestamp dateAcct = asset.getDateAcct(); + if (dateAcct != null) + { + dateAcct = TimeUtil.addMonths(dateAcct, 1); + setDateAcct(dateAcct); + } + // + // Set UseLife values from asset (if any) + if (asset.getUseLifeMonths() > 0) + { + UseLifeImpl.get(this, false).setUseLifeMonths(asset.getUseLifeMonths()); + } + if (asset.getUseLifeMonths_F() > 0) + { + UseLifeImpl.get(this, true).setUseLifeMonths(asset.getUseLifeMonths_F()); + } + // + dump(); + } + + /** Logger */ + private CLogger log = CLogger.getCLogger(getClass()); + + public static Collection forA_Asset_ID(Properties ctx, int asset_id, String trxName) + { + return new Query(ctx, Table_Name, MDepreciationWorkfile.COLUMNNAME_A_Asset_ID+"=?", trxName) + .setParameters(new Object[]{asset_id}) + .list(); + } + + /** + * + * @param ctx + * @param A_Asset_ID + * @param postingType + * @return workfile + * @see #get(Properties, int, String, String) + */ + public static MDepreciationWorkfile get (Properties ctx, int A_Asset_ID, String postingType) + { + return get(ctx, A_Asset_ID, postingType, null); + } + + /** + * Get/load workfile from cache (if trxName is null) + * @param ctx + * @param A_Asset_ID + * @param postingType + * @param trxName + * @return workfile + */ + public static MDepreciationWorkfile get (Properties ctx, int A_Asset_ID, String postingType, String trxName) + { + if (A_Asset_ID <= 0 || postingType == null) + { + return null; + } + + final MultiKey key = new MultiKey(A_Asset_ID, postingType); + if (trxName == null) + { + MDepreciationWorkfile wk = s_cacheAsset.get(key); + if (wk != null) + return wk; + } + /* @win temporary change as this code is causing duplicate create MDepreciationWorkfile on asset addition + final String whereClause = COLUMNNAME_A_Asset_ID+"=?" + +" AND "+COLUMNNAME_PostingType+"=? AND "+COLUMNNAME_A_QTY_Current+">?"; + MDepreciationWorkfile wk = new Query(ctx, MDepreciationWorkfile.Table_Name, whereClause, trxName) + .setParameters(new Object[]{A_Asset_ID, postingType, 0}) + .firstOnly(); + */ + final String whereClause = COLUMNNAME_A_Asset_ID+"=?" + +" AND "+COLUMNNAME_PostingType+"=? "; + MDepreciationWorkfile wk = new Query(ctx, MDepreciationWorkfile.Table_Name, whereClause, trxName) + .setParameters(new Object[]{A_Asset_ID, postingType}) + .firstOnly(); + + + if (trxName == null && wk != null) + { + s_cacheAsset.put(key, wk); + } + return wk; + } + /** Static cache: Asset/PostingType -> Workfile */ + private static CCache + s_cacheAsset = new CCache(Table_Name, Table_Name+"_Asset", 10); + + /** Returns the date of the last action + */ + public Timestamp getLastActionDate() + { + return TimeUtil.getMonthLastDay(TimeUtil.addMonths(getDateAcct(), -1)); + } + + /** Check if the asset is depreciated at the specified date + * @param date + * @return true if you amortized until the specified date, otherwise false + */ + public boolean isDepreciated(Timestamp date) + { + Timestamp lastActionDate = getLastActionDate(); + boolean isDepr = !date.after(lastActionDate); // date <= lastActionDate + + if (log.isLoggable(Level.FINE)) log.fine("LastActionDate=" + lastActionDate + ", GivenDate=" + date + " => isDepreciated=" + isDepr); + return isDepr; + } + + /** + * Get Asset Accounting for this workfile + * @return asset accounting model + */ + public MAssetAcct getA_AssetAcct(Timestamp dateAcct, String trxName) + { + return MAssetAcct.forA_Asset_ID(getCtx(), getA_Asset_ID(), getPostingType(), dateAcct, trxName); + } + + /** Returns the current cost of FAs. It is calculated as the difference between acquisition value and the value that you (A_Salvage_Value) + * @return the current cost of FAs + */ + public BigDecimal getActualCost() + { + return getActualCost(getA_Asset_Cost()); + } + + /** */ + public BigDecimal getActualCost(BigDecimal assetCost) + { + return assetCost.subtract(getA_Salvage_Value()); + } + + /** + * + * @param deltaAmt + * @param deltaQty + * @param reset + */ + public void adjustCost(BigDecimal deltaAmt, BigDecimal deltaQty, boolean reset) + { + BigDecimal newCost = Env.ZERO; + BigDecimal newQty = Env.ZERO; + if (!reset) + { + newCost = getA_Asset_Cost(); + newQty = getA_QTY_Current(); + } + newCost = newCost.add(deltaAmt); + newQty = newQty.add(deltaQty); + + // TODO: crashes if I cancel an Issue: +// if (newQty.signum() < 0) { +// throw new ArhRuntimeException(getCtx(), "@A_QTY_Current@ < 0"); +// } + + // + // There must be verified that the remaining value to be greater than the amount diminished + // total devaluation because if the entire asset value (A_Asset_Cost) must be brought to 0. +// if (deltaAmt.signum() < 0) +// { +// BigDecimal remainingAmt_C = getRemainingCost(null, false); +// if (remainingAmt_C.compareTo(deltaAmt.negate()) < 0) +// { +// throw new ArhRuntimeException(getCtx(), "@A_Asset_Remaining@ < @DeltaAmt@") +// .addInfo("@A_Asset_Cost@=", getA_Asset_Cost()) +// .addInfo("@A_Accumulated_Depr@=", getA_Accumulated_Depr()); +// } +// BigDecimal remainingAmt_F = getRemainingCost(null, true); +// if (remainingAmt_F.compareTo(deltaAmt.negate()) < 0) +// { +// throw new ArhRuntimeException(getCtx(), "@A_Asset_Remaining_F@ < @DeltaAmt@") +// .addInfo("@A_Asset_Cost=@", getA_Asset_Cost()) +// .addInfo("@A_Accumulated_Depr@=", getA_Accumulated_Depr_F()); +// } +// } + + setA_Asset_Cost(newCost); + setA_QTY_Current(newQty); + + if (log.isLoggable(Level.FINE)) log.fine("adjustCost(" + deltaAmt + ", " + deltaQty + ", reset=" + reset + ") => amt=" + getA_Asset_Cost() + ", qty=" + getA_QTY_Current()); + } + + /** + * Adjust Accumulated depreciation + * @param amt + * @param amt_F + * @param reset + * @return + */ + public boolean adjustAccumulatedDepr(BigDecimal amt, BigDecimal amt_F, boolean reset) + { + if (amt == null) + { + amt = Env.ZERO; + } + if (amt_F == null) + { + amt_F = Env.ZERO; + } + setA_Accumulated_Depr(amt.add(reset ? Env.ZERO : getA_Accumulated_Depr())); + setA_Accumulated_Depr_F(amt_F.add(reset ? Env.ZERO : getA_Accumulated_Depr_F())); + return true; + } + + /** + * Adjust use life years + */ + public void adjustUseLife(int deltaUseLifeYears, int deltaUseLifeYears_F, boolean reset) + { + if (log.isLoggable(Level.FINE)) log.fine("Entering: deltaUseLifeYears=" + deltaUseLifeYears + ", deltaUseLifeYears_F=" + deltaUseLifeYears_F); + // + UseLifeImpl.get(this, false).adjustUseLifeYears(deltaUseLifeYears, reset); + UseLifeImpl.get(this, true).adjustUseLifeYears(deltaUseLifeYears_F, reset); + // + if (log.isLoggable(Level.FINE)) log.fine("Leaving"); + } + + /** */ + public int getUseLifeMonths(boolean fiscal) + { + return fiscal ? getUseLifeMonths_F() : getUseLifeMonths(); + } + + /** */ + public BigDecimal getA_Accumulated_Depr(boolean fiscal) + { + return fiscal ? getA_Accumulated_Depr_F() : getA_Accumulated_Depr(); + } + + /** */ + public BigDecimal getAccumulatedCost() + { + return getA_Accumulated_Depr(isFiscal()); + } + + /** */ + public BigDecimal getReevaluationCost() + { + return Env.ZERO; + } + + /** + * Returns the residual (remaining) value + */ + public BigDecimal getRemainingCost(BigDecimal accumAmt, boolean fiscal) + { + BigDecimal cost = getActualCost(); + if (accumAmt == null) { + accumAmt = getA_Accumulated_Depr(fiscal); + } + return cost.subtract(accumAmt); + } + + /** + * Returns the residual (remaining) value + */ + public BigDecimal getRemainingCost(BigDecimal accumAmt) + { + return getRemainingCost(accumAmt, isFiscal()); + } + + /** */ + public int getRemainingPeriods(int A_Current_Period, MDepreciation method) + { + int useLifePeriods = getUseLifeMonths(isFiscal()); + if (method != null) { + useLifePeriods += method.getFixMonthOffset(); + } + int currentPeriod = (A_Current_Period >= 0 ? A_Current_Period : getA_Current_Period()); + return useLifePeriods - currentPeriod; + } + /** */ + public int getRemainingPeriods(int A_Current_Period) + { + return getRemainingPeriods(A_Current_Period, null); + } + + /** */ + private boolean m_isFiscal = false; + /** */ + public boolean isFiscal() + { + return m_isFiscal; + } + /** + * Set fiscal flag (temporary - is not modifing the workfile) + * @param fiscal + */ + public void setFiscal(boolean fiscal) + { + m_isFiscal = fiscal; + } + + /** Increment the current period (A_Current_Period) 1, and a month DateAcct */ + public void incA_Current_Period() + { + int old_period = getA_Current_Period(); + Timestamp old_date = getDateAcct(); + int new_period = old_period + 1; + Timestamp new_date = TimeUtil.addMonths(getDateAcct(), 1); + setA_Current_Period(new_period); + setDateAcct(new_date); + // + if (log.isLoggable(Level.FINE)) log.fine("(A_Current_Period, DateAcct)=(" + old_period + ", " + old_date + ")->(" + new_period + ", " + new_date + ")"); + } + + /** + * Set A Current Period (and Data Act) processed just after the last expense. + * Do not save. + */ + public void setA_Current_Period() + { + String whereClause = MDepreciationExp.COLUMNNAME_A_Asset_ID+"=?" + +" AND "+MDepreciationExp.COLUMNNAME_PostingType+"=?" + +" AND "+MDepreciationExp.COLUMNNAME_Processed+"=? AND IsActive=?" + ; + // + MDepreciationExp depexp = new Query(getCtx(), MDepreciationExp.Table_Name, whereClause, get_TrxName()) + .setParameters(new Object[]{getA_Asset_ID(), getPostingType(), true, true}) + .setOrderBy(MDepreciationExp.COLUMNNAME_A_Period+" DESC" + +","+MDepreciationExp.COLUMNNAME_DateAcct+" DESC") + .first(); + if (depexp != null) + { + setA_Current_Period(depexp.getA_Period()); + setDateAcct(depexp.getDateAcct()); + incA_Current_Period(); + } + else + { + log.info("There are no records from which to infer its"); + } + + } + + /** Build depreciation flag - if true, the depreciation should be built after save */ + private boolean m_buildDepreciation = false; + + /** + * Build depreciation (A_Depreciation_Exp) entries. More exactly, is deleting not Processed entries. + * and create new ones again. + * WARNING: IS NOT modifying workfile (this) + */ + + public void buildDepreciation() + { + if (!isDepreciated()) + { + return; + } + + StringBuilder sb = new StringBuilder(); + load(get_TrxName()); // reload workfile + MAssetAcct assetacct = getA_AssetAcct(null, get_TrxName()); + // TODO: teo_sarca: need to evaluate what happens when we change Depreciation method !!! + MDepreciation depreciation_C = MDepreciation.get(getCtx(), assetacct.getA_Depreciation_ID()); + MDepreciation depreciation_F = MDepreciation.get(getCtx(), assetacct.getA_Depreciation_F_ID()); + //~ int offset_C = depreciation_C.getFixMonthOffset(); + //~ int offset_F = depreciation_F.getFixMonthOffset(); + int offset_C = 0, offset_F = 0; + + BigDecimal assetCost = getActualCost(); + BigDecimal accumDep_C = getA_Accumulated_Depr(false); + BigDecimal accumDep_F = getA_Accumulated_Depr(true); + int lifePeriods_C = getUseLifeMonths(false) + offset_C; + int lifePeriods_F = getUseLifeMonths(true) + offset_F; + int lifePeriods = (lifePeriods_C > lifePeriods_F ? lifePeriods_C : lifePeriods_F); + BigDecimal exp_C = Env.ZERO; + BigDecimal exp_F = Env.ZERO; + + //logging + if(CLogMgt.isLevelFine()) + { + sb.append("currentPeriod=" + getA_Current_Period() + ", AssetServiceDate=" + getAssetDepreciationDate() + "\n"); + sb.append("offset: C|F=" + offset_C + "|" + offset_F + "\n"); + sb.append("life: C|F=" + lifePeriods_C + "|" + lifePeriods_F + " + offset =" + lifePeriods + "\n"); + } + + truncDepreciation(); + int A_Current_Period = getA_Current_Period(); + for (int currentPeriod = A_Current_Period, cnt = 1; currentPeriod <= lifePeriods; currentPeriod++, cnt++) + { + exp_C = Env.ZERO; + exp_F = Env.ZERO; + + String help = "" + accumDep_C + "|" + accumDep_F + " + "; + + if (lifePeriods_C > currentPeriod || !depreciation_C.requireLastPeriodAdjustment()) + { + setFiscal(false); + exp_C = depreciation_C.invoke(this, assetacct, currentPeriod, accumDep_C); + accumDep_C = accumDep_C.add(exp_C); + } + else if (lifePeriods_C == currentPeriod) + { // last period + exp_C = assetCost.subtract(accumDep_C); + accumDep_C = assetCost; + } + + if (lifePeriods_F > currentPeriod || !depreciation_F.requireLastPeriodAdjustment()) + { + setFiscal(true); + exp_F = depreciation_F.invoke(this, assetacct, currentPeriod, accumDep_F); + accumDep_F = accumDep_F.add(exp_F); + } + else if (lifePeriods_F == currentPeriod) + { // last period (fiscal) + exp_F = assetCost.subtract(accumDep_F); + accumDep_F = assetCost; + } + + help += "" + exp_C + "|" + exp_F + " = " + accumDep_C + "|" + accumDep_F; + + // added by zuhri + int months = 0; + + months = months + (currentPeriod - A_Current_Period); + Timestamp dateAcct = TimeUtil.getMonthLastDay(TimeUtil.addMonths(getDateAcct(), months)); + + MDepreciationExp.createDepreciation (this, currentPeriod, dateAcct, + exp_C, exp_F, + accumDep_C, accumDep_F, + help, get_TrxName()); + if (log.isLoggable(Level.FINE)) + { + String info = "" + cnt + ": period=" + currentPeriod + "/" + lifePeriods_C + "|" + lifePeriods_F + + ", exp=" + exp_C + "|" + exp_F + ", accumDep=" + accumDep_C + "|" + accumDep_F + + ", DateAcct=" + dateAcct; + log.fine("=> " + info + Env.NL + Env.NL); + sb.append(info + Env.NL); + } + } // for + if (log.isLoggable(Level.FINE)) log.fine(sb.toString()); + + m_buildDepreciation = false; + } // buildDepreciation + + + + /** + * Truncate not processed depreciation entries. + * IS NOT modifying workfile. + */ + public void truncDepreciation() + { + String trxName = get_TrxName(); + + int A_Current_Period = getA_Current_Period(); + final String sql = "DELETE FROM "+MDepreciationExp.Table_Name + +" WHERE " + +MDepreciationExp.COLUMNNAME_Processed+"=?" + +" AND "+MDepreciationExp.COLUMNNAME_A_Period+">=?" + +" AND "+MDepreciationExp.COLUMNNAME_A_Asset_ID+"=?" + +" AND "+MDepreciationExp.COLUMNNAME_PostingType+"=?" + ; + Object[] params = new Object[]{false, A_Current_Period, getA_Asset_ID(), getPostingType()}; + int no = DB.executeUpdateEx(sql, params, trxName); + if (log.isLoggable(Level.FINE)) log.fine("sql=" + sql + "\nDeleted #" + no); + } // truncDepreciation + + /** + * Update Founding Mode related fields + * @param m model + * @param changedColumnName column name that has been changed + */ + public static void updateFinantare(SetGetModel m, String changedColumnName) + { + //Own contribution: + BigDecimal valCofinantare = SetGetUtil.get_AttrValueAsBigDecimal(m, COLUMNNAME_A_Valoare_Cofinantare); + // Asset Value: + BigDecimal assetCost = SetGetUtil.get_AttrValueAsBigDecimal(m, COLUMNNAME_A_Asset_Cost); + // Third value: + BigDecimal valTert = SetGetUtil.get_AttrValueAsBigDecimal(m, COLUMNNAME_A_Valoare_Tert); + + // Calculate values + if (valCofinantare.signum() == 0 && valTert.signum() == 0) + { + // Values ​​have never been set, so put everything on their own financing + valCofinantare = assetCost; + valTert = Env.ZERO; + } + else if (COLUMNNAME_A_Asset_Cost.equals(changedColumnName)) + { + valCofinantare = assetCost.subtract(valTert); + } + else if (COLUMNNAME_A_Valoare_Cofinantare.equals(changedColumnName)) + { + valTert = assetCost.subtract(valCofinantare); + } + else if (COLUMNNAME_A_Valoare_Tert.equals(changedColumnName)) + { + valCofinantare = assetCost.subtract(valTert); + } + else + { + valTert = assetCost.subtract(valCofinantare); + } + + // Financing Type + String tipFinantare = A_TIP_FINANTARE_Cofinantare; + if (valTert.signum() == 0) + { + tipFinantare = A_TIP_FINANTARE_Proprie; + } + else if (valCofinantare.signum() == 0) + { + tipFinantare = A_TIP_FINANTARE_Terti; + } + // + // Set values + m.set_AttrValue(COLUMNNAME_A_Tip_Finantare, tipFinantare); + m.set_AttrValue(COLUMNNAME_A_Valoare_Cofinantare, valCofinantare); + m.set_AttrValue(COLUMNNAME_A_Valoare_Tert, valTert); + // + // If the method is invoked for a persistent object when reset mode of financing + if (A_TIP_FINANTARE_Proprie.equals(tipFinantare) && SetGetUtil.isPersistent(m)) + { + m.set_AttrValue(COLUMNNAME_A_FundingMode_ID, null); + } + } + + public boolean set_AttrValue(String ColumnName, Object value) { + int index = get_ColumnIndex(ColumnName); + if (index < 0) + return false; + return set_ValueNoCheck(ColumnName, value); + } + public Object get_AttrValue(String ColumnName) { + int index = get_ColumnIndex(ColumnName); + if (index < 0) + return null; + return get_Value(index); + } + public boolean is_AttrValueChanged(String ColumnName) { + int index = get_ColumnIndex(ColumnName); + if (index < 0) + return false; + return is_ValueChanged(index); + } +} // MDepreciationWorkfile diff --git a/org.adempiere.base/src/org/compiere/model/MDunningLevel.java b/org.adempiere.base/src/org/compiere/model/MDunningLevel.java index bbbc60c574..57e2e05150 100644 --- a/org.adempiere.base/src/org/compiere/model/MDunningLevel.java +++ b/org.adempiere.base/src/org/compiere/model/MDunningLevel.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -15,35 +15,35 @@ * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Properties; -import java.util.logging.Level; - -import org.compiere.util.CLogger; -import org.compiere.util.DB; - - -/** + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Properties; +import java.util.logging.Level; + +import org.compiere.util.CLogger; +import org.compiere.util.DB; + + +/** * Dunning Level Model * * @author Jorg Janke * @version $Id: MDunningLevel.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $ - */ -public class MDunningLevel extends X_C_DunningLevel -{ - /** - * - */ - private static final long serialVersionUID = 4869909989789113387L; - /** Logger */ - private static CLogger s_log = CLogger.getCLogger (MDunningLevel.class); - - /** - * Standard Constructor - * @param ctx context + */ +public class MDunningLevel extends X_C_DunningLevel +{ + /** + * + */ + private static final long serialVersionUID = 4869909989789113387L; + /** Logger */ + private static CLogger s_log = CLogger.getCLogger (MDunningLevel.class); + + /** + * Standard Constructor + * @param ctx context * @param C_DunningLevel_ID id * @param trxName transaction */ @@ -59,60 +59,60 @@ public class MDunningLevel extends X_C_DunningLevel * @param trxName transaction */ public MDunningLevel (Properties ctx, ResultSet rs, String trxName) - { - super(ctx, rs, trxName); - } // MDunningLevel - - private MDunning m_dunning = null; - - /** - * get Parent - * @return Parent Dunning - */ - public MDunning getParent() - { - if (m_dunning==null) - m_dunning = new MDunning(getCtx(), getC_Dunning_ID(), get_TrxName()); - return m_dunning; - } - - /** - * get Previous Levels - * @return Array of previous DunningLevels - */ - public MDunningLevel[] getPreviousLevels() - { - // Prevent generation if not Sequentially - if (!getParent().isCreateLevelsSequentially ()) - return null; - ArrayList list = new ArrayList(); - String sql = "SELECT * FROM C_DunningLevel WHERE C_Dunning_ID=? AND DaysAfterDue+DaysBetweenDunning list = new ArrayList(); + String sql = "SELECT * FROM C_DunningLevel WHERE C_Dunning_ID=? AND DaysAfterDue+DaysBetweenDunning list = new ArrayList(); - String sql = "SELECT * FROM R_InterestArea WHERE IsActive='Y'"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement (sql, null); - rs = pstmt.executeQuery (); - while (rs.next ()) - { - MInterestArea ia = new MInterestArea (ctx, rs, null); - list.add (ia); - } - } - catch (Exception e) - { - s_log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; - pstmt = null; - } - MInterestArea[] retValue = new MInterestArea[list.size ()]; - list.toArray (retValue); - return retValue; - } // getAll - - - /** - * Get MInterestArea from Cache - * @param ctx context - * @param R_InterestArea_ID id +public class MInterestArea extends X_R_InterestArea +{ + /** + * + */ + private static final long serialVersionUID = -6910076559329764930L; + + + /** + * Get all active interest areas + * @param ctx context + * @return interest areas + */ + public static MInterestArea[] getAll (Properties ctx) + { + ArrayList list = new ArrayList(); + String sql = "SELECT * FROM R_InterestArea WHERE IsActive='Y'"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement (sql, null); + rs = pstmt.executeQuery (); + while (rs.next ()) + { + MInterestArea ia = new MInterestArea (ctx, rs, null); + list.add (ia); + } + } + catch (Exception e) + { + s_log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; + pstmt = null; + } + MInterestArea[] retValue = new MInterestArea[list.size ()]; + list.toArray (retValue); + return retValue; + } // getAll + + + /** + * Get MInterestArea from Cache + * @param ctx context + * @param R_InterestArea_ID id * @return MInterestArea */ public static MInterestArea get (Properties ctx, int R_InterestArea_ID) @@ -97,16 +97,16 @@ public class MInterestArea extends X_R_InterestArea if (retValue.get_ID () != 0) s_cache.put (key, retValue); return retValue; - } // get - - /** Cache */ - private static CCache s_cache = - new CCache(Table_Name, 5); - /** Logger */ - private static CLogger s_log = CLogger.getCLogger (MInterestArea.class); - - - /** + } // get + + /** Cache */ + private static CCache s_cache = + new CCache(Table_Name, 5); + /** Logger */ + private static CLogger s_log = CLogger.getCLogger (MInterestArea.class); + + + /** * Constructor * @param ctx context * @param R_InterestArea_ID interest area @@ -116,13 +116,13 @@ public class MInterestArea extends X_R_InterestArea { super (ctx, R_InterestArea_ID, trxName); if (R_InterestArea_ID == 0) - { - // setName (null); - // setR_InterestArea_ID (0); - setIsSelfService (false); - } - } // MInterestArea - + { + // setName (null); + // setR_InterestArea_ID (0); + setIsSelfService (false); + } + } // MInterestArea + /** * Loader Constructor * @param ctx context @@ -131,36 +131,36 @@ public class MInterestArea extends X_R_InterestArea */ public MInterestArea (Properties ctx, ResultSet rs, String trxName) { - super(ctx, rs, trxName); - } // MInterestArea - - - /** - * Get Value - * @return value - */ - public String getValue() - { - String s = super.getValue (); - if (s != null && s.length () > 0) - return s; - return super.getName(); - } // getValue - - /** - * String representation + super(ctx, rs, trxName); + } // MInterestArea + + + /** + * Get Value + * @return value + */ + public String getValue() + { + String s = super.getValue (); + if (s != null && s.length () > 0) + return s; + return super.getName(); + } // getValue + + /** + * String representation * @return info */ public String toString () { - StringBuilder sb = new StringBuilder ("MInterestArea[") - .append (get_ID()).append(" - ").append(getName()) - .append ("]"); - return sb.toString (); - } // toString - - /*************************************************************************/ - + StringBuilder sb = new StringBuilder ("MInterestArea[") + .append (get_ID()).append(" - ").append(getName()) + .append ("]"); + return sb.toString (); + } // toString + + /*************************************************************************/ + private int m_AD_User_ID = -1; private MContactInterest m_ci = null; diff --git a/org.adempiere.base/src/org/compiere/model/MNewsItem.java b/org.adempiere.base/src/org/compiere/model/MNewsItem.java index 82380fa38f..c3785d44aa 100644 --- a/org.adempiere.base/src/org/compiere/model/MNewsItem.java +++ b/org.adempiere.base/src/org/compiere/model/MNewsItem.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,8 +16,8 @@ *****************************************************************************/ package org.compiere.model; -import java.sql.ResultSet; -import java.util.Properties; +import java.sql.ResultSet; +import java.util.Properties; /** * News ItemModel @@ -27,11 +27,11 @@ import java.util.Properties; */ public class MNewsItem extends X_CM_NewsItem { - /** - * - */ - private static final long serialVersionUID = -8217571535161436997L; - + /** + * + */ + private static final long serialVersionUID = -8217571535161436997L; + /*** * Standard Constructor * @@ -122,12 +122,12 @@ public class MNewsItem extends X_CM_NewsItem return success; } // afterSave - /** - * reIndex - * @param newRecord - */ - public void reIndex(boolean newRecord) - { + /** + * reIndex + * @param newRecord + */ + public void reIndex(boolean newRecord) + { int CMWebProjectID = 0; if (getNewsChannel()!=null) CMWebProjectID = getNewsChannel().getCM_WebProject_ID(); diff --git a/org.adempiere.base/src/org/compiere/model/MPaySelectionLine.java b/org.adempiere.base/src/org/compiere/model/MPaySelectionLine.java index 6d13f496f7..9ff1970b7b 100644 --- a/org.adempiere.base/src/org/compiere/model/MPaySelectionLine.java +++ b/org.adempiere.base/src/org/compiere/model/MPaySelectionLine.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,12 +16,12 @@ *****************************************************************************/ package org.compiere.model; -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.util.Properties; - -import org.compiere.util.DB; -import org.compiere.util.Env; +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.util.Properties; + +import org.compiere.util.DB; +import org.compiere.util.Env; /** * Payment Selection Line Model @@ -31,11 +31,11 @@ import org.compiere.util.Env; */ public class MPaySelectionLine extends X_C_PaySelectionLine { - /** - * - */ - private static final long serialVersionUID = -1880961891234637133L; - + /** + * + */ + private static final long serialVersionUID = -1880961891234637133L; + /** * Standard Constructor * @param ctx context @@ -54,9 +54,9 @@ public class MPaySelectionLine extends X_C_PaySelectionLine setIsSOTrx (false); setOpenAmt(Env.ZERO); setPayAmt (Env.ZERO); - setDiscountAmt(Env.ZERO); + setDiscountAmt(Env.ZERO); setWriteOffAmt (Env.ZERO); - setDifferenceAmt (Env.ZERO); + setDifferenceAmt (Env.ZERO); setIsManual (false); } } // MPaySelectionLine @@ -101,30 +101,30 @@ public class MPaySelectionLine extends X_C_PaySelectionLine public void xsetInvoice (int C_Invoice_ID, boolean isSOTrx, BigDecimal OpenAmt, BigDecimal PayAmt, BigDecimal DiscountAmt) { - setInvoice(C_Invoice_ID, isSOTrx, OpenAmt, PayAmt, DiscountAmt, Env.ZERO); + setInvoice(C_Invoice_ID, isSOTrx, OpenAmt, PayAmt, DiscountAmt, Env.ZERO); } // setInvoive - /** - * Set Invoice Info - * @param C_Invoice_ID invoice - * @param isSOTrx sales trx - * @param PayAmt payment - * @param OpenAmt open - * @param DiscountAmt discount - * @param WriteOffAmt writeoff - */ - public void setInvoice (int C_Invoice_ID, boolean isSOTrx, BigDecimal OpenAmt, - BigDecimal PayAmt, BigDecimal DiscountAmt, BigDecimal WriteOffAmt) - { - setC_Invoice_ID (C_Invoice_ID); - setIsSOTrx(isSOTrx); - setOpenAmt(OpenAmt); - setPayAmt (PayAmt); - setDiscountAmt(DiscountAmt); - setWriteOffAmt(WriteOffAmt); - setDifferenceAmt(OpenAmt.subtract(PayAmt).subtract(DiscountAmt).subtract(WriteOffAmt)); - } // setInvoice - + /** + * Set Invoice Info + * @param C_Invoice_ID invoice + * @param isSOTrx sales trx + * @param PayAmt payment + * @param OpenAmt open + * @param DiscountAmt discount + * @param WriteOffAmt writeoff + */ + public void setInvoice (int C_Invoice_ID, boolean isSOTrx, BigDecimal OpenAmt, + BigDecimal PayAmt, BigDecimal DiscountAmt, BigDecimal WriteOffAmt) + { + setC_Invoice_ID (C_Invoice_ID); + setIsSOTrx(isSOTrx); + setOpenAmt(OpenAmt); + setPayAmt (PayAmt); + setDiscountAmt(DiscountAmt); + setWriteOffAmt(WriteOffAmt); + setDifferenceAmt(OpenAmt.subtract(PayAmt).subtract(DiscountAmt).subtract(WriteOffAmt)); + } // setInvoice + /** * Get Invoice * @return invoice @@ -133,12 +133,12 @@ public class MPaySelectionLine extends X_C_PaySelectionLine { if (m_invoice == null) m_invoice = new MInvoice (getCtx(), getC_Invoice_ID(), get_TrxName()); - return m_invoice; - } // getInvoice - - /** - * Before Save - * @param newRecord new + return m_invoice; + } // getInvoice + + /** + * Before Save + * @param newRecord new * @return true */ protected boolean beforeSave (boolean newRecord) @@ -154,9 +154,9 @@ public class MPaySelectionLine extends X_C_PaySelectionLine * @return success */ protected boolean afterSave (boolean newRecord, boolean success) - { - if (!success) - return success; + { + if (!success) + return success; setHeader(); return success; } // afterSave @@ -167,9 +167,9 @@ public class MPaySelectionLine extends X_C_PaySelectionLine * @return sucess */ protected boolean afterDelete (boolean success) - { - if (!success) - return success; + { + if (!success) + return success; setHeader(); return success; } // afterDelete @@ -194,7 +194,7 @@ public class MPaySelectionLine extends X_C_PaySelectionLine */ public String toString() { - StringBuilder sb = new StringBuilder("MPaySelectionLine["); + StringBuilder sb = new StringBuilder("MPaySelectionLine["); sb.append(get_ID()).append(",C_Invoice_ID=").append(getC_Invoice_ID()) .append(",PayAmt=").append(getPayAmt()) .append(",DifferenceAmt=").append(getDifferenceAmt()) diff --git a/org.adempiere.base/src/org/compiere/model/MPaymentValidate.java b/org.adempiere.base/src/org/compiere/model/MPaymentValidate.java index b7572c7b94..6cefd8d3f9 100644 --- a/org.adempiere.base/src/org/compiere/model/MPaymentValidate.java +++ b/org.adempiere.base/src/org/compiere/model/MPaymentValidate.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,11 +16,11 @@ *****************************************************************************/ package org.compiere.model; -import java.util.Calendar; -import java.util.StringTokenizer; -import java.util.logging.Level; - -import org.compiere.util.CLogger; +import java.util.Calendar; +import java.util.StringTokenizer; +import java.util.logging.Level; + +import org.compiere.util.CLogger; /** @@ -166,7 +166,7 @@ public class MPaymentValidate String ccNumber1 = checkNumeric(creditCardNumber); int ccLength = ccNumber1.length(); // Reverse string - StringBuilder buf = new StringBuilder(); + StringBuilder buf = new StringBuilder(); for (int i = ccLength; i != 0; i--) buf.append(ccNumber1.charAt(i-1)); String ccNumber = buf.toString(); @@ -186,7 +186,7 @@ public class MPaymentValidate if (sum % 10 == 0) return ""; - if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardNumber - " + creditCardNumber + " -> " + if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardNumber - " + creditCardNumber + " -> " + ccNumber + ", Luhn=" + sum); return "CreditCardNumberError"; } // validateCreditCardNumber @@ -206,33 +206,33 @@ public class MPaymentValidate // http://www.beachnet.com/~hstiles/cardtype.html // http://staff.semel.fi/~kribe/document/luhn.htm - String ccStartList = ""; // comma separated list of starting numbers - String ccLengthList = ""; // comma separated list of lengths - // - if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_MasterCard)) - { - ccStartList = "51,52,53,54,55"; - ccLengthList = "16"; - } - else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Visa)) - { - ccStartList = "4"; - ccLengthList = "13,16"; - } - else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Amex)) - { - ccStartList = "34,37"; - ccLengthList = "15"; - } - else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Discover)) - { - ccStartList = "6011"; - ccLengthList = "16"; - } - else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Diners)) - { - ccStartList = "300,301,302,303,304,305,36,38"; - ccLengthList = "14"; + String ccStartList = ""; // comma separated list of starting numbers + String ccLengthList = ""; // comma separated list of lengths + // + if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_MasterCard)) + { + ccStartList = "51,52,53,54,55"; + ccLengthList = "16"; + } + else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Visa)) + { + ccStartList = "4"; + ccLengthList = "13,16"; + } + else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Amex)) + { + ccStartList = "34,37"; + ccLengthList = "15"; + } + else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Discover)) + { + ccStartList = "6011"; + ccLengthList = "16"; + } + else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Diners)) + { + ccStartList = "300,301,302,303,304,305,36,38"; + ccLengthList = "14"; } else { @@ -264,7 +264,7 @@ public class MPaymentValidate } if (!ccLengthOK) { - if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardNumber Length=" + if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardNumber Length=" + ccLength + " <> " + ccLengthList); return "CreditCardNumberError"; } @@ -280,7 +280,7 @@ public class MPaymentValidate ccIdentified = true; } if (!ccIdentified) - if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardNumber Type=" + if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardNumber Type=" + creditCardType + " <> " + ccStartList); // @@ -312,9 +312,9 @@ public class MPaymentValidate } catch (NumberFormatException ex) { - if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV - " + ex); + if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV - " + ex); } - if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV - length=" + length); + if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV - length=" + length); return "CreditCardVVError"; } // validateCreditCardVV @@ -331,13 +331,13 @@ public class MPaymentValidate || creditCardType == null || creditCardType.length() == 0) return ""; - int length = checkNumeric(creditCardVV).length(); - - // Amex = 4 digits - if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Amex)) - { - if (length == 4) - { + int length = checkNumeric(creditCardVV).length(); + + // Amex = 4 digits + if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Amex)) + { + if (length == 4) + { try { Integer.parseInt (creditCardVV); @@ -345,18 +345,18 @@ public class MPaymentValidate } catch (NumberFormatException ex) { - if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV - " + ex); + if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV - " + ex); } } - if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV(4) CC=" + creditCardType + ", length=" + length); - return "CreditCardVVError"; - } - // Visa & MasterCard - 3 digits - if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Visa) - || creditCardType.equals(X_C_Payment.CREDITCARDTYPE_MasterCard)) - { - if (length == 3) - { + if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV(4) CC=" + creditCardType + ", length=" + length); + return "CreditCardVVError"; + } + // Visa & MasterCard - 3 digits + if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Visa) + || creditCardType.equals(X_C_Payment.CREDITCARDTYPE_MasterCard)) + { + if (length == 3) + { try { Integer.parseInt (creditCardVV); @@ -364,10 +364,10 @@ public class MPaymentValidate } catch (NumberFormatException ex) { - if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV - " + ex); + if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV - " + ex); } } - if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV(3) CC=" + creditCardType + ", length=" + length); + if (s_log.isLoggable(Level.FINE)) s_log.fine("validateCreditCardVV(3) CC=" + creditCardType + ", length=" + length); return "CreditCardVVError"; } @@ -384,15 +384,15 @@ public class MPaymentValidate public static String validateRoutingNo (String routingNo) { int length = checkNumeric(routingNo).length(); - // US - length 9 - // Germany - length 8 - // Japan - 7 - // CH - 5 - // Issue: Bank account country - if (length > 0) - return ""; - return "PaymentBankRoutingNotValid"; - } // validateBankRoutingNo + // US - length 9 + // Germany - length 8 + // Japan - 7 + // CH - 5 + // Issue: Bank account country + if (length > 0) + return ""; + return "PaymentBankRoutingNotValid"; + } // validateBankRoutingNo /** * Validate Account No @@ -430,7 +430,7 @@ public class MPaymentValidate if (data == null || data.length() == 0) return ""; // Remove all non Digits - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.length(); i++) { if (Character.isDigit(data.charAt(i))) diff --git a/org.adempiere.base/src/org/compiere/model/MPeriod.java b/org.adempiere.base/src/org/compiere/model/MPeriod.java index 7f9e351c37..1bc8b69fc1 100644 --- a/org.adempiere.base/src/org/compiere/model/MPeriod.java +++ b/org.adempiere.base/src/org/compiere/model/MPeriod.java @@ -1,878 +1,878 @@ -/****************************************************************************** - * 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.compiere.model; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; - -import org.adempiere.exceptions.PeriodClosedException; -import org.compiere.util.CCache; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.DisplayType; -import org.compiere.util.Env; -import org.compiere.util.TimeUtil; -import org.compiere.util.Util; - -/** - * Calendar Period Model - * - * @author Jorg Janke - * @version $Id: MPeriod.java,v 1.4 2006/07/30 00:51:05 jjanke Exp $ - * - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - *
  • BF [ 1779438 ] Minor auto period control bug - *
  • BF [ 1893486 ] Auto Period Control return that period is always open - * - * @author victor.perez@e-evolution.com, e-Evolution http://www.e-evolution.com - *
  • FR [ 2520591 ] Support multiples calendar for Org - * @see http://sourceforge.net/tracker2/?func=detail&atid=879335&aid=2520591&group_id=176962 - */ -public class MPeriod extends X_C_Period -{ - /** - * - */ - private static final long serialVersionUID = 769103495098446073L; - - /** - * Get Period from Cache - * @param ctx context - * @param C_Period_ID id - * @return MPeriod - */ - public static MPeriod get (Properties ctx, int C_Period_ID) - { - if (C_Period_ID <= 0) - return null; - // - Integer key = Integer.valueOf(C_Period_ID); - MPeriod retValue = (MPeriod) s_cache.get (key); - if (retValue != null) - return retValue; - // - retValue = new MPeriod (ctx, C_Period_ID, null); - if (retValue.get_ID () != 0) - s_cache.put (key, retValue); - return retValue; - } // get - - /** - * Find standard Period of DateAcct based on Client Calendar - * @param ctx context - * @param DateAcct date - * @return active Period or null - * @deprecated - */ - public static MPeriod get (Properties ctx, Timestamp DateAcct) - { - return get(ctx, DateAcct, 0, null); - } // get - - /** - * Find standard Period of DateAcct based on Client Calendar - * @param ctx context - * @param DateAcct date - * @param AD_Org_ID Organization - * @return active Period or null - */ - public static MPeriod get (Properties ctx, Timestamp DateAcct, int AD_Org_ID, String trxName) - { - - if (DateAcct == null) - return null; - - int C_Calendar_ID = getC_Calendar_ID(ctx,AD_Org_ID); - - return findByCalendar(ctx, DateAcct, C_Calendar_ID, trxName); - } // get - - @Deprecated - public static MPeriod get (Properties ctx, Timestamp DateAcct, int AD_Org_ID) - { - return get(ctx, DateAcct, AD_Org_ID, null); - } - - /** - * - * @param ctx - * @param DateAcct - * @param C_Calendar_ID - * @return MPeriod - * @deprecated - */ - public static MPeriod findByCalendar(Properties ctx, Timestamp DateAcct, int C_Calendar_ID) { - return findByCalendar(ctx, DateAcct, C_Calendar_ID, null); - } - - /** - * - * @param ctx - * @param DateAcct - * @param C_Calendar_ID - * @param trxName - * @return MPeriod - */ - public static MPeriod findByCalendar(Properties ctx, Timestamp DateAcct, int C_Calendar_ID, String trxName) { - - int AD_Client_ID = Env.getAD_Client_ID(ctx); - // Search in Cache first - Iterator it = s_cache.values().iterator(); - while (it.hasNext()) - { - MPeriod period = (MPeriod)it.next(); - if (period.getC_Calendar_ID() == C_Calendar_ID && period.isStandardPeriod() && period.isInPeriod(DateAcct) - && period.getAD_Client_ID() == AD_Client_ID) // globalqss - CarlosRuiz - Fix [ 1820810 ] Wrong Period Assigned to Fact_Acct - return period; - } - - // Get it from DB - MPeriod retValue = null; - String sql = "SELECT * " - + "FROM C_Period " - + "WHERE C_Year_ID IN " - + "(SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID= ?)" - + " AND ? BETWEEN TRUNC(StartDate) AND TRUNC(EndDate)" - + " AND IsActive=? AND PeriodType=?"; - - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, trxName); - pstmt.setInt (1, C_Calendar_ID); - pstmt.setTimestamp (2, TimeUtil.getDay(DateAcct)); - pstmt.setString(3, "Y"); - pstmt.setString(4, "S"); - rs = pstmt.executeQuery(); - while (rs.next()) - { - MPeriod period = new MPeriod(ctx, rs, trxName); - Integer key = Integer.valueOf(period.getC_Period_ID()); - s_cache.put (key, period); - if (period.isStandardPeriod()) - retValue = period; - } - } - catch (SQLException e) - { - s_log.log(Level.SEVERE, "DateAcct=" + DateAcct, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - if (retValue == null) - if (s_log.isLoggable(Level.INFO)) s_log.info("No Standard Period for " + DateAcct - + " (AD_Client_ID=" + AD_Client_ID + ")"); - return retValue; - } - - /** - * Find valid standard Period of DateAcct based on Client Calendar - * @param ctx context - * @param DateAcct date - * @return C_Period_ID or 0 - * @deprecated - */ - public static int getC_Period_ID (Properties ctx, Timestamp DateAcct) - { - MPeriod period = get (ctx, DateAcct, 0, null); - if (period == null) - return 0; - return period.getC_Period_ID(); - } // getC_Period_ID - - /** - * Find valid standard Period of DateAcct based on Client Calendar - * @param ctx context - * @param DateAcct date - * @param AD_Org_ID Organization - * @return C_Period_ID or 0 - */ - public static int getC_Period_ID (Properties ctx, Timestamp DateAcct, int AD_Org_ID) - { - MPeriod period = get (ctx, DateAcct, AD_Org_ID, null); - if (period == null) - return 0; - return period.getC_Period_ID(); - } // getC_Period_ID - - /** - * Is standard Period Open for Document Base Type - * @param ctx context - * @param DateAcct date - * @param DocBaseType base type - * @return true if open - * @deprecated - */ - public static boolean isOpen (Properties ctx, Timestamp DateAcct, String DocBaseType) - { - return isOpen(ctx, DateAcct,DocBaseType, 0 ); - } // isOpen - - /** - * Is standard Period Open for Document Base Type - * @param ctx context - * @param DateAcct date - * @param DocBaseType base type - * @param AD_Org_ID Organization - * @return true if open - */ - public static boolean isOpen (Properties ctx, Timestamp DateAcct, String DocBaseType, int AD_Org_ID) - { - if (DateAcct == null) - { - s_log.warning("No DateAcct"); - return false; - } - if (DocBaseType == null) - { - s_log.warning("No DocBaseType"); - return false; - } - MPeriod period = MPeriod.get (ctx, DateAcct, AD_Org_ID, null); - if (period == null) - { - s_log.warning("No Period for " + DateAcct + " (" + DocBaseType + ")"); - return false; - } - boolean open = period.isOpen(DocBaseType, DateAcct); - if (!open) - s_log.warning(period.getName() - + ": Not open for " + DocBaseType + " (" + DateAcct + ")"); - return open; - } // isOpen - - /** - * Is standard Period Open - based on tableID+recordID (for IDEMPIERE-2392) - * @param ctx context - * @param tableID - * @param recordID - * @return true if open - */ - public static boolean isOpen (Properties ctx, int tableID, int recordID, String trxName) { - MTable table = MTable.get(ctx, tableID); - PO po = table.getPO(recordID, trxName); - - // obtain DateAcct - int idxdate = -1; - if ( tableID == MInventory.Table_ID - || tableID == MMovement.Table_ID +/****************************************************************************** + * 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.compiere.model; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import org.adempiere.exceptions.PeriodClosedException; +import org.compiere.util.CCache; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.DisplayType; +import org.compiere.util.Env; +import org.compiere.util.TimeUtil; +import org.compiere.util.Util; + +/** + * Calendar Period Model + * + * @author Jorg Janke + * @version $Id: MPeriod.java,v 1.4 2006/07/30 00:51:05 jjanke Exp $ + * + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1779438 ] Minor auto period control bug + *
  • BF [ 1893486 ] Auto Period Control return that period is always open + * + * @author victor.perez@e-evolution.com, e-Evolution http://www.e-evolution.com + *
  • FR [ 2520591 ] Support multiples calendar for Org + * @see http://sourceforge.net/tracker2/?func=detail&atid=879335&aid=2520591&group_id=176962 + */ +public class MPeriod extends X_C_Period +{ + /** + * + */ + private static final long serialVersionUID = 769103495098446073L; + + /** + * Get Period from Cache + * @param ctx context + * @param C_Period_ID id + * @return MPeriod + */ + public static MPeriod get (Properties ctx, int C_Period_ID) + { + if (C_Period_ID <= 0) + return null; + // + Integer key = Integer.valueOf(C_Period_ID); + MPeriod retValue = (MPeriod) s_cache.get (key); + if (retValue != null) + return retValue; + // + retValue = new MPeriod (ctx, C_Period_ID, null); + if (retValue.get_ID () != 0) + s_cache.put (key, retValue); + return retValue; + } // get + + /** + * Find standard Period of DateAcct based on Client Calendar + * @param ctx context + * @param DateAcct date + * @return active Period or null + * @deprecated + */ + public static MPeriod get (Properties ctx, Timestamp DateAcct) + { + return get(ctx, DateAcct, 0, null); + } // get + + /** + * Find standard Period of DateAcct based on Client Calendar + * @param ctx context + * @param DateAcct date + * @param AD_Org_ID Organization + * @return active Period or null + */ + public static MPeriod get (Properties ctx, Timestamp DateAcct, int AD_Org_ID, String trxName) + { + + if (DateAcct == null) + return null; + + int C_Calendar_ID = getC_Calendar_ID(ctx,AD_Org_ID); + + return findByCalendar(ctx, DateAcct, C_Calendar_ID, trxName); + } // get + + @Deprecated + public static MPeriod get (Properties ctx, Timestamp DateAcct, int AD_Org_ID) + { + return get(ctx, DateAcct, AD_Org_ID, null); + } + + /** + * + * @param ctx + * @param DateAcct + * @param C_Calendar_ID + * @return MPeriod + * @deprecated + */ + public static MPeriod findByCalendar(Properties ctx, Timestamp DateAcct, int C_Calendar_ID) { + return findByCalendar(ctx, DateAcct, C_Calendar_ID, null); + } + + /** + * + * @param ctx + * @param DateAcct + * @param C_Calendar_ID + * @param trxName + * @return MPeriod + */ + public static MPeriod findByCalendar(Properties ctx, Timestamp DateAcct, int C_Calendar_ID, String trxName) { + + int AD_Client_ID = Env.getAD_Client_ID(ctx); + // Search in Cache first + Iterator it = s_cache.values().iterator(); + while (it.hasNext()) + { + MPeriod period = (MPeriod)it.next(); + if (period.getC_Calendar_ID() == C_Calendar_ID && period.isStandardPeriod() && period.isInPeriod(DateAcct) + && period.getAD_Client_ID() == AD_Client_ID) // globalqss - CarlosRuiz - Fix [ 1820810 ] Wrong Period Assigned to Fact_Acct + return period; + } + + // Get it from DB + MPeriod retValue = null; + String sql = "SELECT * " + + "FROM C_Period " + + "WHERE C_Year_ID IN " + + "(SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID= ?)" + + " AND ? BETWEEN TRUNC(StartDate) AND TRUNC(EndDate)" + + " AND IsActive=? AND PeriodType=?"; + + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, trxName); + pstmt.setInt (1, C_Calendar_ID); + pstmt.setTimestamp (2, TimeUtil.getDay(DateAcct)); + pstmt.setString(3, "Y"); + pstmt.setString(4, "S"); + rs = pstmt.executeQuery(); + while (rs.next()) + { + MPeriod period = new MPeriod(ctx, rs, trxName); + Integer key = Integer.valueOf(period.getC_Period_ID()); + s_cache.put (key, period); + if (period.isStandardPeriod()) + retValue = period; + } + } + catch (SQLException e) + { + s_log.log(Level.SEVERE, "DateAcct=" + DateAcct, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + if (retValue == null) + if (s_log.isLoggable(Level.INFO)) s_log.info("No Standard Period for " + DateAcct + + " (AD_Client_ID=" + AD_Client_ID + ")"); + return retValue; + } + + /** + * Find valid standard Period of DateAcct based on Client Calendar + * @param ctx context + * @param DateAcct date + * @return C_Period_ID or 0 + * @deprecated + */ + public static int getC_Period_ID (Properties ctx, Timestamp DateAcct) + { + MPeriod period = get (ctx, DateAcct, 0, null); + if (period == null) + return 0; + return period.getC_Period_ID(); + } // getC_Period_ID + + /** + * Find valid standard Period of DateAcct based on Client Calendar + * @param ctx context + * @param DateAcct date + * @param AD_Org_ID Organization + * @return C_Period_ID or 0 + */ + public static int getC_Period_ID (Properties ctx, Timestamp DateAcct, int AD_Org_ID) + { + MPeriod period = get (ctx, DateAcct, AD_Org_ID, null); + if (period == null) + return 0; + return period.getC_Period_ID(); + } // getC_Period_ID + + /** + * Is standard Period Open for Document Base Type + * @param ctx context + * @param DateAcct date + * @param DocBaseType base type + * @return true if open + * @deprecated + */ + public static boolean isOpen (Properties ctx, Timestamp DateAcct, String DocBaseType) + { + return isOpen(ctx, DateAcct,DocBaseType, 0 ); + } // isOpen + + /** + * Is standard Period Open for Document Base Type + * @param ctx context + * @param DateAcct date + * @param DocBaseType base type + * @param AD_Org_ID Organization + * @return true if open + */ + public static boolean isOpen (Properties ctx, Timestamp DateAcct, String DocBaseType, int AD_Org_ID) + { + if (DateAcct == null) + { + s_log.warning("No DateAcct"); + return false; + } + if (DocBaseType == null) + { + s_log.warning("No DocBaseType"); + return false; + } + MPeriod period = MPeriod.get (ctx, DateAcct, AD_Org_ID, null); + if (period == null) + { + s_log.warning("No Period for " + DateAcct + " (" + DocBaseType + ")"); + return false; + } + boolean open = period.isOpen(DocBaseType, DateAcct); + if (!open) + s_log.warning(period.getName() + + ": Not open for " + DocBaseType + " (" + DateAcct + ")"); + return open; + } // isOpen + + /** + * Is standard Period Open - based on tableID+recordID (for IDEMPIERE-2392) + * @param ctx context + * @param tableID + * @param recordID + * @return true if open + */ + public static boolean isOpen (Properties ctx, int tableID, int recordID, String trxName) { + MTable table = MTable.get(ctx, tableID); + PO po = table.getPO(recordID, trxName); + + // obtain DateAcct + int idxdate = -1; + if ( tableID == MInventory.Table_ID + || tableID == MMovement.Table_ID || tableID == MProduction.Table_ID - || tableID == MProjectIssue.Table_ID) { - idxdate = po.get_ColumnIndex("MovementDate"); - } else if ( tableID == MRequisition.Table_ID) { - idxdate = po.get_ColumnIndex("DateDoc"); - } else if ( tableID == MBankStatement.Table_ID) { - idxdate = po.get_ColumnIndex("StatementDate"); - } else if ( tableID == MAllocationHdr.Table_ID - || tableID == MMatchInv.Table_ID - || tableID == MMatchPO.Table_ID) { - idxdate = po.get_ColumnIndex("DateTrx"); - } else { - idxdate = po.get_ColumnIndex("DateAcct"); - } - if (idxdate < 0) { - if (s_log.isLoggable(Level.INFO)) s_log.info("Could not find DateAcct for " + table.getTableName()); - return true; - } - Timestamp dateAcct = null; - Object objts = po.get_Value(idxdate); - if (objts != null && objts instanceof Timestamp) { - dateAcct = (Timestamp) objts; - } else { - s_log.warning("Could not find DateAcct (null or not Timestamp) for " + table.getTableName()); - return true; - } - - // obtain DocBaseType - String docBaseType = null; - int idxdoctype = po.get_ColumnIndex("C_DocType_ID"); - if (idxdoctype < 0) { - if (tableID == MInventory.Table_ID) { - docBaseType = MDocType.DOCBASETYPE_MaterialPhysicalInventory; - } else if (tableID == MProduction.Table_ID) { - docBaseType = MDocType.DOCBASETYPE_MaterialProduction; - } else if (tableID == MRequisition.Table_ID) { - docBaseType = MDocType.DOCBASETYPE_PurchaseRequisition; - } else if (tableID == MBankStatement.Table_ID) { - docBaseType = MDocType.DOCBASETYPE_BankStatement; - } else if (tableID == MAllocationHdr.Table_ID) { - docBaseType = MDocType.DOCBASETYPE_PaymentAllocation; - } else if (tableID == MMatchInv.Table_ID) { - docBaseType = MDocType.DOCBASETYPE_MatchInvoice; - } else if (tableID == MMatchPO.Table_ID) { - docBaseType = MDocType.DOCBASETYPE_MatchPO; - } else if ( tableID == MAssetAddition.Table_ID - || tableID == MAssetReval.Table_ID - || tableID == MAssetTransfer.Table_ID) { - docBaseType = MDocType.DOCBASETYPE_GLJournal; - } else if ( tableID == MAssetDisposed.Table_ID - || tableID == MDepreciationExp.Table_ID) { - docBaseType = MDocType.DOCBASETYPE_GLDocument; // seems like a bug of fixed assets - must use GLJournal instead of GLDocument? + || tableID == MProjectIssue.Table_ID) { + idxdate = po.get_ColumnIndex("MovementDate"); + } else if ( tableID == MRequisition.Table_ID) { + idxdate = po.get_ColumnIndex("DateDoc"); + } else if ( tableID == MBankStatement.Table_ID) { + idxdate = po.get_ColumnIndex("StatementDate"); + } else if ( tableID == MAllocationHdr.Table_ID + || tableID == MMatchInv.Table_ID + || tableID == MMatchPO.Table_ID) { + idxdate = po.get_ColumnIndex("DateTrx"); + } else { + idxdate = po.get_ColumnIndex("DateAcct"); + } + if (idxdate < 0) { + if (s_log.isLoggable(Level.INFO)) s_log.info("Could not find DateAcct for " + table.getTableName()); + return true; + } + Timestamp dateAcct = null; + Object objts = po.get_Value(idxdate); + if (objts != null && objts instanceof Timestamp) { + dateAcct = (Timestamp) objts; + } else { + s_log.warning("Could not find DateAcct (null or not Timestamp) for " + table.getTableName()); + return true; + } + + // obtain DocBaseType + String docBaseType = null; + int idxdoctype = po.get_ColumnIndex("C_DocType_ID"); + if (idxdoctype < 0) { + if (tableID == MInventory.Table_ID) { + docBaseType = MDocType.DOCBASETYPE_MaterialPhysicalInventory; + } else if (tableID == MProduction.Table_ID) { + docBaseType = MDocType.DOCBASETYPE_MaterialProduction; + } else if (tableID == MRequisition.Table_ID) { + docBaseType = MDocType.DOCBASETYPE_PurchaseRequisition; + } else if (tableID == MBankStatement.Table_ID) { + docBaseType = MDocType.DOCBASETYPE_BankStatement; + } else if (tableID == MAllocationHdr.Table_ID) { + docBaseType = MDocType.DOCBASETYPE_PaymentAllocation; + } else if (tableID == MMatchInv.Table_ID) { + docBaseType = MDocType.DOCBASETYPE_MatchInvoice; + } else if (tableID == MMatchPO.Table_ID) { + docBaseType = MDocType.DOCBASETYPE_MatchPO; + } else if ( tableID == MAssetAddition.Table_ID + || tableID == MAssetReval.Table_ID + || tableID == MAssetTransfer.Table_ID) { + docBaseType = MDocType.DOCBASETYPE_GLJournal; + } else if ( tableID == MAssetDisposed.Table_ID + || tableID == MDepreciationExp.Table_ID) { + docBaseType = MDocType.DOCBASETYPE_GLDocument; // seems like a bug of fixed assets - must use GLJournal instead of GLDocument? } else if (tableID == MProjectIssue.Table_ID) { docBaseType = MDocType.DOCBASETYPE_ProjectIssue; - } else { - s_log.warning("Could not find C_DocType_ID for " + table.getTableName()); - return true; - } - } else { - Integer doctypeID = null; - Object objint = po.get_Value(idxdoctype); - if (objint != null && objint instanceof Integer) { - doctypeID = (Integer) objint; - } else { - s_log.warning("Could not find C_DocType_ID (null or not Integer) for " + table.getTableName()); - return true; - } - if (doctypeID == 0 && (tableID == MOrder.Table_ID || tableID == MInvoice.Table_ID)) { - idxdoctype = po.get_ColumnIndex("C_DocTypeTarget_ID"); - objint = po.get_Value(idxdoctype); - if (objint != null && objint instanceof Integer) { - doctypeID = (Integer) objint; - } - } - MDocType dt = MDocType.get(ctx, doctypeID); - docBaseType = dt.getDocBaseType(); - } - if (Util.isEmpty(docBaseType)) { - s_log.warning("Could not find DocBaseType for " + table.getTableName()); - return true; - } - - // obtain AD_Org_ID - int orgID = 0; - int idxorg = po.get_ColumnIndex("AD_Org_ID"); - if (idxorg < 0) { - s_log.warning("Could not find AD_Org_ID for " + table.getTableName()); - } else { - orgID = po.get_ValueAsInt(idxorg); - } - - return isOpen(ctx, dateAcct, docBaseType, orgID); - } // isOpen - - /** - * Find first Year Period of DateAcct based on Client Calendar - * @param ctx context - * @param DateAcct date - * @return active first Period - * @deprecated - */ - public static MPeriod getFirstInYear (Properties ctx, Timestamp DateAcct) - { - return getFirstInYear(ctx , DateAcct, 0); - } // getFirstInYear - - /** - * Find first Year Period of DateAcct based on Client Calendar - * @param ctx context - * @param DateAcct date - * @param AD_Org_ID TODO - * @return active first Period - */ - public static MPeriod getFirstInYear (Properties ctx, Timestamp DateAcct, int AD_Org_ID) - { - MPeriod retValue = null; - int C_Calendar_ID = MPeriod.get(ctx, DateAcct, AD_Org_ID, null).getC_Calendar_ID(); - - String sql = "SELECT * " - + "FROM C_Period " - + "WHERE C_Year_ID IN " - + "(SELECT p.C_Year_ID " - + "FROM C_Year y" - + " INNER JOIN C_Period p ON (y.C_Year_ID=p.C_Year_ID) " - + "WHERE y.C_Calendar_ID=?" - + " AND ? BETWEEN StartDate AND EndDate)" - + " AND IsActive=? AND PeriodType=? " - + "ORDER BY StartDate"; - - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt (1, C_Calendar_ID); - pstmt.setTimestamp (2, DateAcct); - pstmt.setString (3, "Y"); - pstmt.setString (4, "S"); - rs = pstmt.executeQuery(); - if (rs.next()) // first only - retValue = new MPeriod(ctx, rs, null); - } - catch (SQLException e) - { - s_log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - return retValue; - } // getFirstInYear - - /** Cache */ - private static CCache s_cache = new CCache(Table_Name, 10); - - /** Logger */ - private static CLogger s_log = CLogger.getCLogger (MPeriod.class); - - /** Calendar */ - private int m_C_Calendar_ID = 0; - - - /************************************************************************** - * Standard Constructor - * @param ctx context - * @param C_Period_ID id - * @param trxName transaction - */ - public MPeriod (Properties ctx, int C_Period_ID, String trxName) - { - super (ctx, C_Period_ID, trxName); - if (C_Period_ID == 0) - { - // setC_Period_ID (0); // PK - // setC_Year_ID (0); // Parent - // setName (null); - // setPeriodNo (0); - // setStartDate (new Timestamp(System.currentTimeMillis())); - setPeriodType (PERIODTYPE_StandardCalendarPeriod); - } - } // MPeriod - - /** - * Load Constructor - * @param ctx context - * @param rs result set - * @param trxName transaction - */ - public MPeriod (Properties ctx, ResultSet rs, String trxName) - { - super(ctx, rs, trxName); - } // MPeriod - - /** - * Parent constructor - * @param year year - * @param PeriodNo no - * @param name name - * @param startDate start - * @param endDate end - */ - public MPeriod (MYear year, int PeriodNo, String name, - Timestamp startDate,Timestamp endDate) - { - this (year.getCtx(), 0, year.get_TrxName()); - setClientOrg(year); - setC_Year_ID(year.getC_Year_ID()); - setPeriodNo(PeriodNo); - setName(name); - setStartDate(startDate); - setEndDate(endDate); - } // MPeriod - - - /** Period Controls */ - private MPeriodControl[] m_controls = null; - - /** - * Get Period Control - * @param requery requery - * @return period controls - */ - public MPeriodControl[] getPeriodControls (boolean requery) - { - if (m_controls != null && !requery) - return m_controls; - // - ArrayList list = new ArrayList(); - String sql = "SELECT * FROM C_PeriodControl " - + "WHERE C_Period_ID=?"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, getC_Period_ID()); - rs = pstmt.executeQuery(); - while (rs.next()) - list.add (new MPeriodControl (getCtx(), rs, null)); - } - catch (Exception e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - // - m_controls = new MPeriodControl[list.size ()]; - list.toArray (m_controls); - return m_controls; - } // getPeriodControls - - /** - * Get Period Control - * @param DocBaseType Document Base Type - * @return period control or null - */ - public MPeriodControl getPeriodControl (String DocBaseType) - { - if (DocBaseType == null) - return null; - getPeriodControls(false); - for (int i = 0; i < m_controls.length; i++) - { - // log.fine("getPeriodControl - " + 1 + " - " + m_controls[i]); - if (DocBaseType.equals(m_controls[i].getDocBaseType())) - return m_controls[i]; - } - return null; - } // getPeriodControl - - /** - * Date In Period - * @param date date - * @return true if in period - */ - public boolean isInPeriod (Timestamp date) - { - if (date == null) - return false; - Timestamp dateOnly = TimeUtil.getDay(date); - Timestamp from = TimeUtil.getDay(getStartDate()); - if (dateOnly.before(from)) - return false; - Timestamp to = TimeUtil.getDay(getEndDate()); - if (dateOnly.after(to)) - return false; - return true; - } // isInPeriod - - /** - * Is Period Open for Doc Base Type - * @param DocBaseType document base type - * @return true if open - * @deprecated since 3.3.1b; use {@link #isOpen(String, Timestamp)} instead - */ - public boolean isOpen (String DocBaseType) - { - return isOpen(DocBaseType, null); - } - - /** - * Is Period Open for Doc Base Type - * @param DocBaseType document base type - * @param dateAcct date; - * Applies only for "Auto Period Control": - *
  • if not null, date should be in auto period range (today - OpenHistory, today+OpenHistory) - *
  • if null, this period should be in auto period range - * @return true if open - * @since 3.3.1b - */ - public boolean isOpen (String DocBaseType, Timestamp dateAcct) - { - if (!isActive()) - { - s_log.warning("Period not active: " + getName()); - return false; - } - - MAcctSchema as = MClient.get(getCtx(), getAD_Client_ID()).getAcctSchema(); - if (as != null && as.isAutoPeriodControl()) - { - Timestamp today = TimeUtil.trunc(new Timestamp (System.currentTimeMillis()), TimeUtil.TRUNC_DAY); - Timestamp first = TimeUtil.addDays(today, - as.getPeriod_OpenHistory()); - Timestamp last = TimeUtil.addDays(today, as.getPeriod_OpenFuture()); - Timestamp date1, date2; - if (dateAcct != null) { - date1 = TimeUtil.trunc(dateAcct, TimeUtil.TRUNC_DAY); - date2 = date1; - } - else { - date1 = getStartDate(); - date2 = getEndDate(); - } - // - if (date1.before(first)) - { - log.warning ("Automatic Period Control:" + date1 + " before first day - " + first); - return false; - } - if (date2.after(last)) - { - log.warning ("Automatic Period Control:" + date2 + " after last day - " + last); - return false; - } - // We are OK - if (isInPeriod(today)) - { - as.setC_Period_ID(getC_Period_ID()); - as.saveEx(); - } - return true; - } - - // Standard Period Control - if (DocBaseType == null) - { - log.warning(getName() + " - No DocBaseType"); - return false; - } - MPeriodControl pc = getPeriodControl (DocBaseType); - if (pc == null) - { - log.warning(getName() + " - Period Control not found for " + DocBaseType); - return false; - } - if (log.isLoggable(Level.FINE)) log.fine(getName() + ": " + DocBaseType); - return pc.isOpen(); - } // isOpen - - /** - * Standard Period - * @return true if standard calendar periods - */ - public boolean isStandardPeriod() - { - return PERIODTYPE_StandardCalendarPeriod.equals(getPeriodType()); - } // isStandardPeriod - - - /** - * Before Save. - * Truncate Dates - * @param newRecord new - * @return true - */ - protected boolean beforeSave (boolean newRecord) - { - // Truncate Dates - Timestamp date = getStartDate(); - if (date != null) - setStartDate(TimeUtil.getDay(date)); - else - return false; - // - date = getEndDate(); - if (date != null) - setEndDate(TimeUtil.getDay(date)); - else - setEndDate(TimeUtil.getMonthLastDay(getStartDate())); - - if (getEndDate().before(getStartDate())) - { - SimpleDateFormat df = DisplayType.getDateFormat(DisplayType.Date); - log.saveError("Error", df.format(getEndDate()) + " < " + df.format(getStartDate())); - return false; - } - - MYear year = new MYear(getCtx(), getC_Year_ID(), get_TrxName()); - - Query query = MTable.get(getCtx(), "C_Period") - .createQuery("C_Year_ID IN (SELECT y.C_Year_ID from C_Year y WHERE" + - " y.C_Calendar_ID =?)" + - " AND (? BETWEEN StartDate AND EndDate" + - " OR ? BETWEEN StartDate AND EndDate)" + - " AND PeriodType=?",get_TrxName()); - query.setParameters(year.getC_Calendar_ID(), - getStartDate(), getEndDate(), - getPeriodType()); - - List periods = query.list(); - - for ( int i=0; i < periods.size(); i++) - { - if ( periods.get(i).getC_Period_ID() != getC_Period_ID() ) - { - log.saveError("Error", "Period overlaps with: " + periods.get(i).getName()); - return false; - } - } - - return true; - } // beforeSave - - /** - * After Save - * @param newRecord new - * @param success success - * @return success - */ - protected boolean afterSave (boolean newRecord, boolean success) - { - if (!success) - return success; - if (newRecord) - { - // SELECT Value FROM AD_Ref_List WHERE AD_Reference_ID=183 - MDocType[] types = MDocType.getOfClient(getCtx()); - int count = 0; - ArrayList baseTypes = new ArrayList(); - for (int i = 0; i < types.length; i++) - { - MDocType type = types[i]; - String DocBaseType = type.getDocBaseType(); - if (baseTypes.contains(DocBaseType)) - continue; - MPeriodControl pc = new MPeriodControl(this, DocBaseType); - pc.saveEx(); - count++; - baseTypes.add (DocBaseType); - } - if (log.isLoggable(Level.FINE)) log.fine("PeriodControl #" + count); - } - return success; - } // afterSave - - - /** - * String Representation - * @return info - */ - public String toString () - { - StringBuilder sb = new StringBuilder ("MPeriod["); - sb.append (get_ID()) - .append("-").append (getName()) - .append(", ").append(getStartDate()).append("-").append(getEndDate()) - .append ("]"); - return sb.toString (); - } // toString - - /** - * Convenient method for testing if a period is open - * @param ctx - * @param dateAcct - * @param docBaseType - * @throws PeriodClosedException if period is closed - * @see #isOpen(Properties, Timestamp, String) - * @deprecated - */ - public static void testPeriodOpen(Properties ctx, Timestamp dateAcct, String docBaseType) - throws PeriodClosedException - { - if (!MPeriod.isOpen(ctx, dateAcct, docBaseType, 0)) { - throw new PeriodClosedException(dateAcct, docBaseType); - } - } - - /** - * Convenient method for testing if a period is open - * @param ctx - * @param dateAcct - * @param docBaseType - * @param AD_Org_ID Organization - * @throws PeriodClosedException if period is closed - * @see #isOpen(Properties, Timestamp, String, int) - */ - public static void testPeriodOpen(Properties ctx, Timestamp dateAcct, String docBaseType, int AD_Org_ID) - throws PeriodClosedException - { - if (!MPeriod.isOpen(ctx, dateAcct, docBaseType, AD_Org_ID)) { - throw new PeriodClosedException(dateAcct, docBaseType); - } - } - - /** - * Convenient method for testing if a period is open - * @param ctx - * @param dateAcct - * @param C_DocType_ID - * @throws PeriodClosedException - * @see {@link #isOpen(Properties, Timestamp, String)} - * @deprecated - */ - public static void testPeriodOpen(Properties ctx, Timestamp dateAcct, int C_DocType_ID) - throws PeriodClosedException - { - MDocType dt = MDocType.get(ctx, C_DocType_ID); - testPeriodOpen(ctx, dateAcct, dt.getDocBaseType(), 0); - } - - /** - * Convenient method for testing if a period is open - * @param ctx - * @param dateAcct - * @param C_DocType_ID - * @param AD_Org_ID Organization - * @throws PeriodClosedException - * @see {@link #isOpen(Properties, Timestamp, String, int)} - */ - public static void testPeriodOpen(Properties ctx, Timestamp dateAcct, int C_DocType_ID, int AD_Org_ID) - throws PeriodClosedException - { - MDocType dt = MDocType.get(ctx, C_DocType_ID); - testPeriodOpen(ctx, dateAcct, dt.getDocBaseType(), AD_Org_ID); - } - - /** - * Get Calendar of Period - * @return calendar - */ - public int getC_Calendar_ID() - { - if (m_C_Calendar_ID == 0) - { - int calId = DB.getSQLValueEx(null, "SELECT C_Calendar_ID FROM C_Year WHERE C_Year_ID=?", getC_Year_ID()); - if (calId >= 0) - m_C_Calendar_ID = calId; - else - log.severe("@NotFound@ C_Year_ID=" + getC_Year_ID()); - } - return m_C_Calendar_ID; - } // getC_Calendar_ID - - /** - * Get Calendar for Organization - * @param ctx Context - * @param AD_Org_ID Organization - * @return - */ - public static int getC_Calendar_ID(Properties ctx,int AD_Org_ID) - { - int C_Calendar_ID = 0; - if (AD_Org_ID != 0) - { - MOrgInfo info = MOrgInfo.get(ctx, AD_Org_ID, null); - C_Calendar_ID = info.getC_Calendar_ID(); - } - - if (C_Calendar_ID == 0) - { - MClientInfo cInfo = MClientInfo.get(ctx); - C_Calendar_ID = cInfo.getC_Calendar_ID(); - } - - return C_Calendar_ID; - } // getC_Calendar_ID - -} // MPeriod + } else { + s_log.warning("Could not find C_DocType_ID for " + table.getTableName()); + return true; + } + } else { + Integer doctypeID = null; + Object objint = po.get_Value(idxdoctype); + if (objint != null && objint instanceof Integer) { + doctypeID = (Integer) objint; + } else { + s_log.warning("Could not find C_DocType_ID (null or not Integer) for " + table.getTableName()); + return true; + } + if (doctypeID == 0 && (tableID == MOrder.Table_ID || tableID == MInvoice.Table_ID)) { + idxdoctype = po.get_ColumnIndex("C_DocTypeTarget_ID"); + objint = po.get_Value(idxdoctype); + if (objint != null && objint instanceof Integer) { + doctypeID = (Integer) objint; + } + } + MDocType dt = MDocType.get(ctx, doctypeID); + docBaseType = dt.getDocBaseType(); + } + if (Util.isEmpty(docBaseType)) { + s_log.warning("Could not find DocBaseType for " + table.getTableName()); + return true; + } + + // obtain AD_Org_ID + int orgID = 0; + int idxorg = po.get_ColumnIndex("AD_Org_ID"); + if (idxorg < 0) { + s_log.warning("Could not find AD_Org_ID for " + table.getTableName()); + } else { + orgID = po.get_ValueAsInt(idxorg); + } + + return isOpen(ctx, dateAcct, docBaseType, orgID); + } // isOpen + + /** + * Find first Year Period of DateAcct based on Client Calendar + * @param ctx context + * @param DateAcct date + * @return active first Period + * @deprecated + */ + public static MPeriod getFirstInYear (Properties ctx, Timestamp DateAcct) + { + return getFirstInYear(ctx , DateAcct, 0); + } // getFirstInYear + + /** + * Find first Year Period of DateAcct based on Client Calendar + * @param ctx context + * @param DateAcct date + * @param AD_Org_ID TODO + * @return active first Period + */ + public static MPeriod getFirstInYear (Properties ctx, Timestamp DateAcct, int AD_Org_ID) + { + MPeriod retValue = null; + int C_Calendar_ID = MPeriod.get(ctx, DateAcct, AD_Org_ID, null).getC_Calendar_ID(); + + String sql = "SELECT * " + + "FROM C_Period " + + "WHERE C_Year_ID IN " + + "(SELECT p.C_Year_ID " + + "FROM C_Year y" + + " INNER JOIN C_Period p ON (y.C_Year_ID=p.C_Year_ID) " + + "WHERE y.C_Calendar_ID=?" + + " AND ? BETWEEN StartDate AND EndDate)" + + " AND IsActive=? AND PeriodType=? " + + "ORDER BY StartDate"; + + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt (1, C_Calendar_ID); + pstmt.setTimestamp (2, DateAcct); + pstmt.setString (3, "Y"); + pstmt.setString (4, "S"); + rs = pstmt.executeQuery(); + if (rs.next()) // first only + retValue = new MPeriod(ctx, rs, null); + } + catch (SQLException e) + { + s_log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + return retValue; + } // getFirstInYear + + /** Cache */ + private static CCache s_cache = new CCache(Table_Name, 10); + + /** Logger */ + private static CLogger s_log = CLogger.getCLogger (MPeriod.class); + + /** Calendar */ + private int m_C_Calendar_ID = 0; + + + /************************************************************************** + * Standard Constructor + * @param ctx context + * @param C_Period_ID id + * @param trxName transaction + */ + public MPeriod (Properties ctx, int C_Period_ID, String trxName) + { + super (ctx, C_Period_ID, trxName); + if (C_Period_ID == 0) + { + // setC_Period_ID (0); // PK + // setC_Year_ID (0); // Parent + // setName (null); + // setPeriodNo (0); + // setStartDate (new Timestamp(System.currentTimeMillis())); + setPeriodType (PERIODTYPE_StandardCalendarPeriod); + } + } // MPeriod + + /** + * Load Constructor + * @param ctx context + * @param rs result set + * @param trxName transaction + */ + public MPeriod (Properties ctx, ResultSet rs, String trxName) + { + super(ctx, rs, trxName); + } // MPeriod + + /** + * Parent constructor + * @param year year + * @param PeriodNo no + * @param name name + * @param startDate start + * @param endDate end + */ + public MPeriod (MYear year, int PeriodNo, String name, + Timestamp startDate,Timestamp endDate) + { + this (year.getCtx(), 0, year.get_TrxName()); + setClientOrg(year); + setC_Year_ID(year.getC_Year_ID()); + setPeriodNo(PeriodNo); + setName(name); + setStartDate(startDate); + setEndDate(endDate); + } // MPeriod + + + /** Period Controls */ + private MPeriodControl[] m_controls = null; + + /** + * Get Period Control + * @param requery requery + * @return period controls + */ + public MPeriodControl[] getPeriodControls (boolean requery) + { + if (m_controls != null && !requery) + return m_controls; + // + ArrayList list = new ArrayList(); + String sql = "SELECT * FROM C_PeriodControl " + + "WHERE C_Period_ID=?"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, getC_Period_ID()); + rs = pstmt.executeQuery(); + while (rs.next()) + list.add (new MPeriodControl (getCtx(), rs, null)); + } + catch (Exception e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + // + m_controls = new MPeriodControl[list.size ()]; + list.toArray (m_controls); + return m_controls; + } // getPeriodControls + + /** + * Get Period Control + * @param DocBaseType Document Base Type + * @return period control or null + */ + public MPeriodControl getPeriodControl (String DocBaseType) + { + if (DocBaseType == null) + return null; + getPeriodControls(false); + for (int i = 0; i < m_controls.length; i++) + { + // log.fine("getPeriodControl - " + 1 + " - " + m_controls[i]); + if (DocBaseType.equals(m_controls[i].getDocBaseType())) + return m_controls[i]; + } + return null; + } // getPeriodControl + + /** + * Date In Period + * @param date date + * @return true if in period + */ + public boolean isInPeriod (Timestamp date) + { + if (date == null) + return false; + Timestamp dateOnly = TimeUtil.getDay(date); + Timestamp from = TimeUtil.getDay(getStartDate()); + if (dateOnly.before(from)) + return false; + Timestamp to = TimeUtil.getDay(getEndDate()); + if (dateOnly.after(to)) + return false; + return true; + } // isInPeriod + + /** + * Is Period Open for Doc Base Type + * @param DocBaseType document base type + * @return true if open + * @deprecated since 3.3.1b; use {@link #isOpen(String, Timestamp)} instead + */ + public boolean isOpen (String DocBaseType) + { + return isOpen(DocBaseType, null); + } + + /** + * Is Period Open for Doc Base Type + * @param DocBaseType document base type + * @param dateAcct date; + * Applies only for "Auto Period Control": + *
  • if not null, date should be in auto period range (today - OpenHistory, today+OpenHistory) + *
  • if null, this period should be in auto period range + * @return true if open + * @since 3.3.1b + */ + public boolean isOpen (String DocBaseType, Timestamp dateAcct) + { + if (!isActive()) + { + s_log.warning("Period not active: " + getName()); + return false; + } + + MAcctSchema as = MClient.get(getCtx(), getAD_Client_ID()).getAcctSchema(); + if (as != null && as.isAutoPeriodControl()) + { + Timestamp today = TimeUtil.trunc(new Timestamp (System.currentTimeMillis()), TimeUtil.TRUNC_DAY); + Timestamp first = TimeUtil.addDays(today, - as.getPeriod_OpenHistory()); + Timestamp last = TimeUtil.addDays(today, as.getPeriod_OpenFuture()); + Timestamp date1, date2; + if (dateAcct != null) { + date1 = TimeUtil.trunc(dateAcct, TimeUtil.TRUNC_DAY); + date2 = date1; + } + else { + date1 = getStartDate(); + date2 = getEndDate(); + } + // + if (date1.before(first)) + { + log.warning ("Automatic Period Control:" + date1 + " before first day - " + first); + return false; + } + if (date2.after(last)) + { + log.warning ("Automatic Period Control:" + date2 + " after last day - " + last); + return false; + } + // We are OK + if (isInPeriod(today)) + { + as.setC_Period_ID(getC_Period_ID()); + as.saveEx(); + } + return true; + } + + // Standard Period Control + if (DocBaseType == null) + { + log.warning(getName() + " - No DocBaseType"); + return false; + } + MPeriodControl pc = getPeriodControl (DocBaseType); + if (pc == null) + { + log.warning(getName() + " - Period Control not found for " + DocBaseType); + return false; + } + if (log.isLoggable(Level.FINE)) log.fine(getName() + ": " + DocBaseType); + return pc.isOpen(); + } // isOpen + + /** + * Standard Period + * @return true if standard calendar periods + */ + public boolean isStandardPeriod() + { + return PERIODTYPE_StandardCalendarPeriod.equals(getPeriodType()); + } // isStandardPeriod + + + /** + * Before Save. + * Truncate Dates + * @param newRecord new + * @return true + */ + protected boolean beforeSave (boolean newRecord) + { + // Truncate Dates + Timestamp date = getStartDate(); + if (date != null) + setStartDate(TimeUtil.getDay(date)); + else + return false; + // + date = getEndDate(); + if (date != null) + setEndDate(TimeUtil.getDay(date)); + else + setEndDate(TimeUtil.getMonthLastDay(getStartDate())); + + if (getEndDate().before(getStartDate())) + { + SimpleDateFormat df = DisplayType.getDateFormat(DisplayType.Date); + log.saveError("Error", df.format(getEndDate()) + " < " + df.format(getStartDate())); + return false; + } + + MYear year = new MYear(getCtx(), getC_Year_ID(), get_TrxName()); + + Query query = MTable.get(getCtx(), "C_Period") + .createQuery("C_Year_ID IN (SELECT y.C_Year_ID from C_Year y WHERE" + + " y.C_Calendar_ID =?)" + + " AND (? BETWEEN StartDate AND EndDate" + + " OR ? BETWEEN StartDate AND EndDate)" + + " AND PeriodType=?",get_TrxName()); + query.setParameters(year.getC_Calendar_ID(), + getStartDate(), getEndDate(), + getPeriodType()); + + List periods = query.list(); + + for ( int i=0; i < periods.size(); i++) + { + if ( periods.get(i).getC_Period_ID() != getC_Period_ID() ) + { + log.saveError("Error", "Period overlaps with: " + periods.get(i).getName()); + return false; + } + } + + return true; + } // beforeSave + + /** + * After Save + * @param newRecord new + * @param success success + * @return success + */ + protected boolean afterSave (boolean newRecord, boolean success) + { + if (!success) + return success; + if (newRecord) + { + // SELECT Value FROM AD_Ref_List WHERE AD_Reference_ID=183 + MDocType[] types = MDocType.getOfClient(getCtx()); + int count = 0; + ArrayList baseTypes = new ArrayList(); + for (int i = 0; i < types.length; i++) + { + MDocType type = types[i]; + String DocBaseType = type.getDocBaseType(); + if (baseTypes.contains(DocBaseType)) + continue; + MPeriodControl pc = new MPeriodControl(this, DocBaseType); + pc.saveEx(); + count++; + baseTypes.add (DocBaseType); + } + if (log.isLoggable(Level.FINE)) log.fine("PeriodControl #" + count); + } + return success; + } // afterSave + + + /** + * String Representation + * @return info + */ + public String toString () + { + StringBuilder sb = new StringBuilder ("MPeriod["); + sb.append (get_ID()) + .append("-").append (getName()) + .append(", ").append(getStartDate()).append("-").append(getEndDate()) + .append ("]"); + return sb.toString (); + } // toString + + /** + * Convenient method for testing if a period is open + * @param ctx + * @param dateAcct + * @param docBaseType + * @throws PeriodClosedException if period is closed + * @see #isOpen(Properties, Timestamp, String) + * @deprecated + */ + public static void testPeriodOpen(Properties ctx, Timestamp dateAcct, String docBaseType) + throws PeriodClosedException + { + if (!MPeriod.isOpen(ctx, dateAcct, docBaseType, 0)) { + throw new PeriodClosedException(dateAcct, docBaseType); + } + } + + /** + * Convenient method for testing if a period is open + * @param ctx + * @param dateAcct + * @param docBaseType + * @param AD_Org_ID Organization + * @throws PeriodClosedException if period is closed + * @see #isOpen(Properties, Timestamp, String, int) + */ + public static void testPeriodOpen(Properties ctx, Timestamp dateAcct, String docBaseType, int AD_Org_ID) + throws PeriodClosedException + { + if (!MPeriod.isOpen(ctx, dateAcct, docBaseType, AD_Org_ID)) { + throw new PeriodClosedException(dateAcct, docBaseType); + } + } + + /** + * Convenient method for testing if a period is open + * @param ctx + * @param dateAcct + * @param C_DocType_ID + * @throws PeriodClosedException + * @see {@link #isOpen(Properties, Timestamp, String)} + * @deprecated + */ + public static void testPeriodOpen(Properties ctx, Timestamp dateAcct, int C_DocType_ID) + throws PeriodClosedException + { + MDocType dt = MDocType.get(ctx, C_DocType_ID); + testPeriodOpen(ctx, dateAcct, dt.getDocBaseType(), 0); + } + + /** + * Convenient method for testing if a period is open + * @param ctx + * @param dateAcct + * @param C_DocType_ID + * @param AD_Org_ID Organization + * @throws PeriodClosedException + * @see {@link #isOpen(Properties, Timestamp, String, int)} + */ + public static void testPeriodOpen(Properties ctx, Timestamp dateAcct, int C_DocType_ID, int AD_Org_ID) + throws PeriodClosedException + { + MDocType dt = MDocType.get(ctx, C_DocType_ID); + testPeriodOpen(ctx, dateAcct, dt.getDocBaseType(), AD_Org_ID); + } + + /** + * Get Calendar of Period + * @return calendar + */ + public int getC_Calendar_ID() + { + if (m_C_Calendar_ID == 0) + { + int calId = DB.getSQLValueEx(null, "SELECT C_Calendar_ID FROM C_Year WHERE C_Year_ID=?", getC_Year_ID()); + if (calId >= 0) + m_C_Calendar_ID = calId; + else + log.severe("@NotFound@ C_Year_ID=" + getC_Year_ID()); + } + return m_C_Calendar_ID; + } // getC_Calendar_ID + + /** + * Get Calendar for Organization + * @param ctx Context + * @param AD_Org_ID Organization + * @return + */ + public static int getC_Calendar_ID(Properties ctx,int AD_Org_ID) + { + int C_Calendar_ID = 0; + if (AD_Org_ID != 0) + { + MOrgInfo info = MOrgInfo.get(ctx, AD_Org_ID, null); + C_Calendar_ID = info.getC_Calendar_ID(); + } + + if (C_Calendar_ID == 0) + { + MClientInfo cInfo = MClientInfo.get(ctx); + C_Calendar_ID = cInfo.getC_Calendar_ID(); + } + + return C_Calendar_ID; + } // getC_Calendar_ID + +} // MPeriod diff --git a/org.adempiere.base/src/org/compiere/model/MRole.java b/org.adempiere.base/src/org/compiere/model/MRole.java index 8238abc2d8..fedfe537fa 100644 --- a/org.adempiere.base/src/org/compiere/model/MRole.java +++ b/org.adempiere.base/src/org/compiere/model/MRole.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,53 +16,53 @@ *****************************************************************************/ package org.compiere.model; -import static org.compiere.model.SystemIDs.USER_SUPERUSER; -import static org.compiere.model.SystemIDs.USER_SYSTEM; - -import java.io.Serializable; -import java.lang.reflect.Array; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.logging.Level; - -import org.adempiere.exceptions.AdempiereException; -import org.compiere.util.CCache; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.Ini; -import org.compiere.util.KeyNamePair; -import org.compiere.util.Msg; -import org.compiere.util.Trace; +import static org.compiere.model.SystemIDs.USER_SUPERUSER; +import static org.compiere.model.SystemIDs.USER_SYSTEM; + +import java.io.Serializable; +import java.lang.reflect.Array; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.Set; +import java.util.logging.Level; + +import org.adempiere.exceptions.AdempiereException; +import org.compiere.util.CCache; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Ini; +import org.compiere.util.KeyNamePair; +import org.compiere.util.Msg; +import org.compiere.util.Trace; /** * Role Model. * Includes AD_User runtime info for Personal Access * The class is final, so that you cannot overwrite the security rules. * - * @author Jorg Janke + * @author Jorg Janke * @author Karsten Thiemann FR [ 1782412 ] - * @author Carlos Ruiz - globalqss - FR [ 1846929 ] - implement ASP - * @contributor KittiU - FR [ 3062553 ] - Duplicated action in DocAction list for Multiple Role Users + * @author Carlos Ruiz - globalqss - FR [ 1846929 ] - implement ASP + * @contributor KittiU - FR [ 3062553 ] - Duplicated action in DocAction list for Multiple Role Users * @version $Id: MRole.java,v 1.5 2006/08/09 16:38:47 jjanke Exp $ */ public final class MRole extends X_AD_Role { - /** - * - */ - private static final long serialVersionUID = 8952907008982481439L; - + /** + * + */ + private static final long serialVersionUID = 8952907008982481439L; + /** * Get Default (Client) Role * @return role @@ -84,31 +84,31 @@ public final class MRole extends X_AD_Role int AD_Role_ID = Env.getContextAsInt(ctx, "#AD_Role_ID"); int AD_User_ID = Env.getContextAsInt(ctx, "#AD_User_ID"); // if (!Ini.isClient()) // none for Server -// AD_User_ID = 0; +// AD_User_ID = 0; MRole defaultRole = getDefaultRole(); if (reload || defaultRole == null) { - defaultRole = get (ctx, AD_Role_ID, AD_User_ID, reload); + defaultRole = get (ctx, AD_Role_ID, AD_User_ID, reload); setDefaultRole(defaultRole); } else if (defaultRole.getAD_Role_ID() != AD_Role_ID || defaultRole.getAD_User_ID() != AD_User_ID) { - defaultRole = get (ctx, AD_Role_ID, AD_User_ID, reload); + defaultRole = get (ctx, AD_Role_ID, AD_User_ID, reload); setDefaultRole(defaultRole); } return defaultRole; } // getDefault - private static void setDefaultRole(MRole defaultRole) { - Env.getCtx().remove(ROLE_KEY); - Env.getCtx().put(ROLE_KEY, defaultRole); - } - - private static MRole getDefaultRole() { - return (MRole) Env.getCtx().get(ROLE_KEY); - } - + private static void setDefaultRole(MRole defaultRole) { + Env.getCtx().remove(ROLE_KEY); + Env.getCtx().put(ROLE_KEY, defaultRole); + } + + private static MRole getDefaultRole() { + return (MRole) Env.getCtx().get(ROLE_KEY); + } + /** * Get Role for User * @param ctx context @@ -119,7 +119,7 @@ public final class MRole extends X_AD_Role */ public synchronized static MRole get (Properties ctx, int AD_Role_ID, int AD_User_ID, boolean reload) { - if (s_log.isLoggable(Level.INFO)) s_log.info("AD_Role_ID=" + AD_Role_ID + ", AD_User_ID=" + AD_User_ID + ", reload=" + reload); + if (s_log.isLoggable(Level.INFO)) s_log.info("AD_Role_ID=" + AD_Role_ID + ", AD_User_ID=" + AD_User_ID + ", reload=" + reload); String key = AD_Role_ID + "_" + AD_User_ID; MRole role = (MRole)s_roles.get (key); if (role == null || reload) @@ -133,7 +133,7 @@ public final class MRole extends X_AD_Role } role.setAD_User_ID(AD_User_ID); role.loadAccess(reload); - if (s_log.isLoggable(Level.INFO)) s_log.info(role.toString()); + if (s_log.isLoggable(Level.INFO)) s_log.info(role.toString()); } return role; } // get @@ -147,8 +147,8 @@ public final class MRole extends X_AD_Role */ public static MRole get (Properties ctx, int AD_Role_ID) { - return get(ctx, AD_Role_ID, Env.getAD_User_ID(ctx), false); // metas-2009_0021_AP1_G94 - we need to use this method because we need to load/reload all accesses - /* metas-2009_0021_AP1_G94 + return get(ctx, AD_Role_ID, Env.getAD_User_ID(ctx), false); // metas-2009_0021_AP1_G94 - we need to use this method because we need to load/reload all accesses + /* metas-2009_0021_AP1_G94 String key = String.valueOf(AD_Role_ID); MRole role = (MRole)s_roles.get (key); String trxName = null; @@ -162,7 +162,7 @@ public final class MRole extends X_AD_Role } } return role; - /**/ // metas-2009_0021_AP1_G94 + /**/ // metas-2009_0021_AP1_G94 } // get /** @@ -174,7 +174,7 @@ public final class MRole extends X_AD_Role { String sql = "SELECT * FROM AD_Role WHERE AD_Client_ID=?"; ArrayList list = new ArrayList (); - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -188,10 +188,10 @@ public final class MRole extends X_AD_Role { s_log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } MRole[] retValue = new MRole[list.size ()]; list.toArray (retValue); @@ -210,7 +210,7 @@ public final class MRole extends X_AD_Role if (whereClause != null && whereClause.length() > 0) sql += " WHERE " + whereClause; ArrayList list = new ArrayList (); - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -223,10 +223,10 @@ public final class MRole extends X_AD_Role { s_log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } MRole[] retValue = new MRole[list.size ()]; list.toArray (retValue); @@ -345,13 +345,13 @@ public final class MRole extends X_AD_Role // if (newRecord || is_ValueChanged("UserLevel")) // { if (getAD_Client_ID() == 0) - setUserLevel(USERLEVEL_System); - else if (getUserLevel().equals(USERLEVEL_System)) - { + setUserLevel(USERLEVEL_System); + else if (getUserLevel().equals(USERLEVEL_System)) + { log.saveError("AccessTableNoUpdate", Msg.getElement(getCtx(), "UserLevel")); - return false; - } - // } + return false; + } + // } return true; } // beforeSave @@ -362,9 +362,9 @@ public final class MRole extends X_AD_Role * @return success */ protected boolean afterSave (boolean newRecord, boolean success) - { - if (!success) - return success; + { + if (!success) + return success; if (newRecord && success) { // Add Role to SuperUser @@ -387,40 +387,40 @@ public final class MRole extends X_AD_Role && getDefaultRole().get_ID() == get_ID()) setDefaultRole(this); return success; - } // afterSave - - /** - * Executed after Delete operation. - * @param success true if record deleted - * @return true if delete is a success - */ - protected boolean afterDelete (boolean success) - { - if(success) { - deleteAccessRecords(); - } - return success; - } // afterDelete - - /** - * Create Access Records - * @return info - */ - public String updateAccessRecords () - { - return updateAccessRecords(true); - } - - + } // afterSave + /** - * Create Access Records - * @param reset true will reset existing access + * Executed after Delete operation. + * @param success true if record deleted + * @return true if delete is a success + */ + protected boolean afterDelete (boolean success) + { + if(success) { + deleteAccessRecords(); + } + return success; + } // afterDelete + + /** + * Create Access Records * @return info */ - public String updateAccessRecords (boolean reset) - { - if (isManual()) - return "-"; + public String updateAccessRecords () + { + return updateAccessRecords(true); + } + + + /** + * Create Access Records + * @param reset true will reset existing access + * @return info + */ + public String updateAccessRecords (boolean reset) + { + if (isManual()) + return "-"; String roleClientOrgUser = getAD_Role_ID() + "," + getAD_Client_ID() + "," + getAD_Org_ID() + ",'Y', SysDate," @@ -433,69 +433,69 @@ public final class MRole extends X_AD_Role + "SELECT DISTINCT w.AD_Window_ID, " + roleClientOrgUser + "FROM AD_Window w" + " INNER JOIN AD_Tab t ON (w.AD_Window_ID=t.AD_Window_ID)" - + " INNER JOIN AD_Table tt ON (t.AD_Table_ID=tt.AD_Table_ID) " - + " LEFT JOIN AD_Window_Access wa ON " - + "(wa.AD_Role_ID=" + getAD_Role_ID() - + " AND w.AD_Window_ID = wa.AD_Window_ID) " - + "WHERE wa.AD_Window_ID IS NULL AND t.SeqNo=(SELECT MIN(SeqNo) FROM AD_Tab xt " // only check first tab + + " INNER JOIN AD_Table tt ON (t.AD_Table_ID=tt.AD_Table_ID) " + + " LEFT JOIN AD_Window_Access wa ON " + + "(wa.AD_Role_ID=" + getAD_Role_ID() + + " AND w.AD_Window_ID = wa.AD_Window_ID) " + + "WHERE wa.AD_Window_ID IS NULL AND t.SeqNo=(SELECT MIN(SeqNo) FROM AD_Tab xt " // only check first tab + "WHERE xt.AD_Window_ID=w.AD_Window_ID)" + "AND tt.AccessLevel IN "; - - String sqlProcess = "INSERT INTO AD_Process_Access " - + "(AD_Process_ID, AD_Role_ID," - + " AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, Updated, UpdatedBy, IsReadWrite) " - + "SELECT DISTINCT p.AD_Process_ID, " + roleClientOrgUser - + "FROM AD_Process p LEFT JOIN AD_Process_Access pa ON " - + "(pa.AD_Role_ID=" + getAD_Role_ID() - + " AND p.AD_Process_ID = pa.AD_Process_ID) " - + "WHERE pa.AD_Process_ID IS NULL AND AccessLevel IN "; + + String sqlProcess = "INSERT INTO AD_Process_Access " + + "(AD_Process_ID, AD_Role_ID," + + " AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, Updated, UpdatedBy, IsReadWrite) " + + "SELECT DISTINCT p.AD_Process_ID, " + roleClientOrgUser + + "FROM AD_Process p LEFT JOIN AD_Process_Access pa ON " + + "(pa.AD_Role_ID=" + getAD_Role_ID() + + " AND p.AD_Process_ID = pa.AD_Process_ID) " + + "WHERE pa.AD_Process_ID IS NULL AND AccessLevel IN "; String sqlForm = "INSERT INTO AD_Form_Access " + "(AD_Form_ID, AD_Role_ID," + " AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy,IsReadWrite) " + "SELECT f.AD_Form_ID, " + roleClientOrgUser - + "FROM AD_Form f LEFT JOIN AD_Form_Access fa ON " - + "(fa.AD_Role_ID=" + getAD_Role_ID() - + " AND f.AD_Form_ID = fa.AD_Form_ID) " - + "WHERE fa.AD_Form_ID IS NULL AND AccessLevel IN "; + + "FROM AD_Form f LEFT JOIN AD_Form_Access fa ON " + + "(fa.AD_Role_ID=" + getAD_Role_ID() + + " AND f.AD_Form_ID = fa.AD_Form_ID) " + + "WHERE fa.AD_Form_ID IS NULL AND AccessLevel IN "; String sqlWorkflow = "INSERT INTO AD_WorkFlow_Access " + "(AD_WorkFlow_ID, AD_Role_ID," + " AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy,IsReadWrite) " + "SELECT w.AD_WorkFlow_ID, " + roleClientOrgUser - + "FROM AD_WorkFlow w LEFT JOIN AD_WorkFlow_Access wa ON " - + "(wa.AD_Role_ID=" + getAD_Role_ID() - + " AND w.AD_WorkFlow_ID = wa.AD_WorkFlow_ID) " - + "WHERE w.AD_Client_ID IN (0," + getAD_Client_ID() + ") AND wa.AD_WorkFlow_ID IS NULL AND AccessLevel IN "; - - String sqlDocAction = "INSERT INTO AD_Document_Action_Access " - + "(AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," - + "C_DocType_ID , AD_Ref_List_ID, AD_Role_ID) " - + "(SELECT " - + getAD_Client_ID() + ",0,'Y', SysDate," - + getUpdatedBy() + ", SysDate," + getUpdatedBy() - + ", doctype.C_DocType_ID, action.AD_Ref_List_ID, rol.AD_Role_ID " - + "FROM AD_Client client " - + "INNER JOIN C_DocType doctype ON (doctype.AD_Client_ID=client.AD_Client_ID) " - + "INNER JOIN AD_Ref_List action ON (action.AD_Reference_ID=135) " - + "INNER JOIN AD_Role rol ON (rol.AD_Client_ID=client.AD_Client_ID " - + "AND rol.AD_Role_ID=" + getAD_Role_ID() - + ") LEFT JOIN AD_Document_Action_Access da ON " - + "(da.AD_Role_ID=" + getAD_Role_ID() - + " AND da.C_DocType_ID=doctype.C_DocType_ID AND da.AD_Ref_List_ID=action.AD_Ref_List_ID) " - + "WHERE (da.C_DocType_ID IS NULL AND da.AD_Ref_List_ID IS NULL)) "; + + "FROM AD_WorkFlow w LEFT JOIN AD_WorkFlow_Access wa ON " + + "(wa.AD_Role_ID=" + getAD_Role_ID() + + " AND w.AD_WorkFlow_ID = wa.AD_WorkFlow_ID) " + + "WHERE w.AD_Client_ID IN (0," + getAD_Client_ID() + ") AND wa.AD_WorkFlow_ID IS NULL AND AccessLevel IN "; + + String sqlDocAction = "INSERT INTO AD_Document_Action_Access " + + "(AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + + "C_DocType_ID , AD_Ref_List_ID, AD_Role_ID) " + + "(SELECT " + + getAD_Client_ID() + ",0,'Y', SysDate," + + getUpdatedBy() + ", SysDate," + getUpdatedBy() + + ", doctype.C_DocType_ID, action.AD_Ref_List_ID, rol.AD_Role_ID " + + "FROM AD_Client client " + + "INNER JOIN C_DocType doctype ON (doctype.AD_Client_ID=client.AD_Client_ID) " + + "INNER JOIN AD_Ref_List action ON (action.AD_Reference_ID=135) " + + "INNER JOIN AD_Role rol ON (rol.AD_Client_ID=client.AD_Client_ID " + + "AND rol.AD_Role_ID=" + getAD_Role_ID() + + ") LEFT JOIN AD_Document_Action_Access da ON " + + "(da.AD_Role_ID=" + getAD_Role_ID() + + " AND da.C_DocType_ID=doctype.C_DocType_ID AND da.AD_Ref_List_ID=action.AD_Ref_List_ID) " + + "WHERE (da.C_DocType_ID IS NULL AND da.AD_Ref_List_ID IS NULL)) "; + + String sqlInfo = "INSERT INTO AD_InfoWindow_Access " + + "(AD_InfoWindow_ID, AD_Role_ID," + + " AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy) " + + "SELECT i.AD_InfoWindow_ID," + getAD_Role_ID() + "," + + getAD_Client_ID() + "," + getAD_Org_ID() + ",'Y',SysDate," + + getUpdatedBy() + ", SysDate," + getUpdatedBy() + + " FROM AD_InfoWindow i LEFT JOIN AD_InfoWindow_Access ia ON " + + "(ia.AD_Role_ID=" + getAD_Role_ID() + + " AND i.AD_InfoWindow_ID = ia.AD_InfoWindow_ID) " + + "WHERE i.AD_Client_ID IN (0," + getAD_Client_ID() + ") AND ia.AD_InfoWindow_ID IS NULL"; - String sqlInfo = "INSERT INTO AD_InfoWindow_Access " - + "(AD_InfoWindow_ID, AD_Role_ID," - + " AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy) " - + "SELECT i.AD_InfoWindow_ID," + getAD_Role_ID() + "," - + getAD_Client_ID() + "," + getAD_Org_ID() + ",'Y',SysDate," - + getUpdatedBy() + ", SysDate," + getUpdatedBy() - + " FROM AD_InfoWindow i LEFT JOIN AD_InfoWindow_Access ia ON " - + "(ia.AD_Role_ID=" + getAD_Role_ID() - + " AND i.AD_InfoWindow_ID = ia.AD_InfoWindow_ID) " - + "WHERE i.AD_Client_ID IN (0," + getAD_Client_ID() + ") AND ia.AD_InfoWindow_ID IS NULL"; - /** * Fill AD_xx_Access * --------------------------------------------------------------------------- @@ -525,48 +525,48 @@ public final class MRole extends X_AD_Role + " AND w.Name NOT LIKE '%(all)%'"; } if (roleAccessLevelWin == null) - roleAccessLevelWin = roleAccessLevel; - - if (reset) - deleteAccessRecords(); - - int win = DB.executeUpdateEx(sqlWindow + roleAccessLevelWin, get_TrxName()); - int proc = DB.executeUpdateEx(sqlProcess + roleAccessLevel, get_TrxName()); - int form = DB.executeUpdateEx(sqlForm + roleAccessLevel, get_TrxName()); - int wf = DB.executeUpdateEx(sqlWorkflow + roleAccessLevel, get_TrxName()); - int docact = DB.executeUpdateEx(sqlDocAction, get_TrxName()); - int info = DB.executeUpdateEx(sqlInfo, get_TrxName()); + roleAccessLevelWin = roleAccessLevel; + + if (reset) + deleteAccessRecords(); + + int win = DB.executeUpdateEx(sqlWindow + roleAccessLevelWin, get_TrxName()); + int proc = DB.executeUpdateEx(sqlProcess + roleAccessLevel, get_TrxName()); + int form = DB.executeUpdateEx(sqlForm + roleAccessLevel, get_TrxName()); + int wf = DB.executeUpdateEx(sqlWorkflow + roleAccessLevel, get_TrxName()); + int docact = DB.executeUpdateEx(sqlDocAction, get_TrxName()); + int info = DB.executeUpdateEx(sqlInfo, get_TrxName()); loadAccess(true); return "@AD_Window_ID@ #" + win + " - @AD_Process_ID@ #" + proc + " - @AD_Form_ID@ #" + form - + " - @AD_Workflow_ID@ #" + wf - + " - @DocAction@ #" + docact - + " - @AD_InfoWindow_ID@ #" + info; + + " - @AD_Workflow_ID@ #" + wf + + " - @DocAction@ #" + docact + + " - @AD_InfoWindow_ID@ #" + info; } // createAccessRecords - /** - * Delete Access Records of the role after the role was (successfully) deleted. - */ - private void deleteAccessRecords() { - String whereDel = " WHERE AD_Role_ID=" + getAD_Role_ID(); - // - int winDel = DB.executeUpdateEx("DELETE FROM AD_Window_Access" + whereDel, get_TrxName()); - int procDel = DB.executeUpdateEx("DELETE FROM AD_Process_Access" + whereDel, get_TrxName()); - int formDel = DB.executeUpdateEx("DELETE FROM AD_Form_Access" + whereDel, get_TrxName()); - int wfDel = DB.executeUpdateEx("DELETE FROM AD_WorkFlow_Access" + whereDel, get_TrxName()); - int docactDel = DB.executeUpdateEx("DELETE FROM AD_Document_Action_Access" + whereDel, get_TrxName()); - int infoDel = DB.executeUpdateEx("DELETE FROM AD_InfoWindow_Access" + whereDel, get_TrxName()); - - if (log.isLoggable(Level.FINE)) log.fine("AD_Window_Access=" + winDel - + ", AD_Process_Access=" + procDel - + ", AD_Form_Access=" + formDel - + ", AD_Workflow_Access=" + wfDel - + ", AD_Document_Action_Access=" + docactDel - + ", AD_InfoWindow_Access=" + infoDel); - } + /** + * Delete Access Records of the role after the role was (successfully) deleted. + */ + private void deleteAccessRecords() { + String whereDel = " WHERE AD_Role_ID=" + getAD_Role_ID(); + // + int winDel = DB.executeUpdateEx("DELETE FROM AD_Window_Access" + whereDel, get_TrxName()); + int procDel = DB.executeUpdateEx("DELETE FROM AD_Process_Access" + whereDel, get_TrxName()); + int formDel = DB.executeUpdateEx("DELETE FROM AD_Form_Access" + whereDel, get_TrxName()); + int wfDel = DB.executeUpdateEx("DELETE FROM AD_WorkFlow_Access" + whereDel, get_TrxName()); + int docactDel = DB.executeUpdateEx("DELETE FROM AD_Document_Action_Access" + whereDel, get_TrxName()); + int infoDel = DB.executeUpdateEx("DELETE FROM AD_InfoWindow_Access" + whereDel, get_TrxName()); + + if (log.isLoggable(Level.FINE)) log.fine("AD_Window_Access=" + winDel + + ", AD_Process_Access=" + procDel + + ", AD_Form_Access=" + formDel + + ", AD_Workflow_Access=" + wfDel + + ", AD_Document_Action_Access=" + docactDel + + ", AD_InfoWindow_Access=" + infoDel); + } /** * String Representation @@ -574,7 +574,7 @@ public final class MRole extends X_AD_Role */ public String toString() { - StringBuilder sb = new StringBuilder("MRole["); + StringBuilder sb = new StringBuilder("MRole["); sb.append(getAD_Role_ID()).append(",").append(getName()) .append(",UserLevel=").append(getUserLevel()) .append(",").append(getClientWhere(false)) @@ -590,7 +590,7 @@ public final class MRole extends X_AD_Role */ public String toStringX (Properties ctx) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.append(Msg.translate(ctx, "AD_Role_ID")).append("=").append(getName()) .append(" - ").append(Msg.translate(ctx, "IsCanExport")).append("=").append(isCanExport()) .append(" - ").append(Msg.translate(ctx, "IsCanReport")).append("=").append(isCanReport()) @@ -642,10 +642,10 @@ public final class MRole extends X_AD_Role private HashMap m_tableAccessLevel = null; /** Table Name */ private HashMap m_tableName = null; - /** View Name */ - private Set m_viewName = null; - /** ID Column Name **/ - private HashMap m_tableIdName = null; + /** View Name */ + private Set m_viewName = null; + /** ID Column Name **/ + private HashMap m_tableIdName = null; /** Window Access */ private HashMap m_windowAccess = null; @@ -657,8 +657,8 @@ public final class MRole extends X_AD_Role private HashMap m_workflowAccess = null; /** Form Access */ private HashMap m_formAccess = null; - /** Info Windows */ - private HashMap m_infoAccess; + /** Info Windows */ + private HashMap m_infoAccess; /** * Set Logged in user @@ -698,7 +698,7 @@ public final class MRole extends X_AD_Role m_workflowAccess = null; m_formAccess = null; } - loadIncludedRoles(reload); // Load/Reload included roles - metas-2009_0021_AP1_G94 + loadIncludedRoles(reload); // Load/Reload included roles - metas-2009_0021_AP1_G94 } // loadAccess /** @@ -719,10 +719,10 @@ public final class MRole extends X_AD_Role m_orgAccess = new OrgAccess[list.size()]; list.toArray(m_orgAccess); - if (log.isLoggable(Level.FINE)) log.fine("#" + m_orgAccess.length + (reload ? " - reload" : "")); + if (log.isLoggable(Level.FINE)) log.fine("#" + m_orgAccess.length + (reload ? " - reload" : "")); if (Ini.isClient()) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < m_orgAccess.length; i++) { if (i > 0) @@ -739,7 +739,7 @@ public final class MRole extends X_AD_Role */ private void loadOrgAccessUser(ArrayList list) { - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT * FROM AD_User_OrgAccess " + "WHERE AD_User_ID=? AND IsActive='Y'"; @@ -758,9 +758,9 @@ public final class MRole extends X_AD_Role { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } } // loadOrgAccessRole @@ -770,7 +770,7 @@ public final class MRole extends X_AD_Role */ private void loadOrgAccessRole(ArrayList list) { - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT * FROM AD_Role_OrgAccess " + "WHERE AD_Role_ID=? AND IsActive='Y'"; @@ -789,9 +789,9 @@ public final class MRole extends X_AD_Role { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } } // loadOrgAccessRole @@ -818,7 +818,7 @@ public final class MRole extends X_AD_Role + "WHERE IsActive='Y' AND AD_Org_ID IN (SELECT Node_ID FROM " + tree.getNodeTableName() + " WHERE AD_Tree_ID=? AND Parent_ID=? AND IsActive='Y')"; - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -837,10 +837,10 @@ public final class MRole extends X_AD_Role { log.log (Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } } // loadOrgAccessAdd @@ -854,7 +854,7 @@ public final class MRole extends X_AD_Role if (m_tableAccess != null && !reload) return; ArrayList list = new ArrayList(); - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT * FROM AD_Table_Access " + "WHERE AD_Role_ID=? AND IsActive='Y'"; @@ -870,13 +870,13 @@ public final class MRole extends X_AD_Role { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } m_tableAccess = new MTableAccess[list.size()]; list.toArray(m_tableAccess); - if (log.isLoggable(Level.FINE)) log.fine("#" + m_tableAccess.length); + if (log.isLoggable(Level.FINE)) log.fine("#" + m_tableAccess.length); } // loadTableAccess /** @@ -888,12 +888,12 @@ public final class MRole extends X_AD_Role if (m_tableAccessLevel != null && m_tableName != null && !reload) return; m_tableAccessLevel = new HashMap(300); - m_tableName = new HashMap(300); - m_viewName = new HashSet(300); + m_tableName = new HashMap(300); + m_viewName = new HashSet(300); m_tableIdName = new HashMap(300); - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; - String sql = "SELECT AD_Table_ID, AccessLevel, TableName, IsView, " + String sql = "SELECT AD_Table_ID, AccessLevel, TableName, IsView, " + "(SELECT ColumnName FROM AD_COLUMN WHERE AD_COLUMN.AD_TABLE_ID = AD_TABLE.AD_TABLE_ID AND AD_COLUMN.COLUMNNAME = AD_TABLE.TABLENAME || '_ID') " + "FROM AD_Table WHERE IsActive='Y'"; try @@ -903,18 +903,18 @@ public final class MRole extends X_AD_Role while (rs.next()) { Integer ii = Integer.valueOf(rs.getInt(1)); - m_tableAccessLevel.put(ii, rs.getString(2)); + m_tableAccessLevel.put(ii, rs.getString(2)); String tableName = rs.getString(3); - m_tableName.put(tableName, ii); - String isView = rs.getString(4); - if ("Y".equals(isView)) - { - m_viewName.add(tableName.toUpperCase()); - } - String idColumn = rs.getString(5); - if (idColumn != null && idColumn.trim().length() > 0) - { - m_tableIdName.put(tableName.toUpperCase(), idColumn); + m_tableName.put(tableName, ii); + String isView = rs.getString(4); + if ("Y".equals(isView)) + { + m_viewName.add(tableName.toUpperCase()); + } + String idColumn = rs.getString(5); + if (idColumn != null && idColumn.trim().length() > 0) + { + m_tableIdName.put(tableName.toUpperCase(), idColumn); } } } @@ -922,28 +922,28 @@ public final class MRole extends X_AD_Role { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } - if (log.isLoggable(Level.FINE)) log.fine("#" + m_tableAccessLevel.size()); + if (log.isLoggable(Level.FINE)) log.fine("#" + m_tableAccessLevel.size()); } // loadTableAccessLevel - - /** - * Check if tableName is a view - * @param tableName - * @return boolean - */ - private boolean isView(String tableName) - { - if (m_viewName == null) - loadAccess(true); - return m_viewName.contains(tableName.toUpperCase()); - } - - private String getIdColumnName(String tableName) - { - return m_tableIdName.get(tableName.toUpperCase()); + + /** + * Check if tableName is a view + * @param tableName + * @return boolean + */ + private boolean isView(String tableName) + { + if (m_viewName == null) + loadAccess(true); + return m_viewName.contains(tableName.toUpperCase()); + } + + private String getIdColumnName(String tableName) + { + return m_tableIdName.get(tableName.toUpperCase()); } /** @@ -955,7 +955,7 @@ public final class MRole extends X_AD_Role if (m_columnAccess != null && !reload) return; ArrayList list = new ArrayList(); - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT * FROM AD_Column_Access " + "WHERE AD_Role_ID=? AND IsActive='Y'"; @@ -971,13 +971,13 @@ public final class MRole extends X_AD_Role { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } m_columnAccess = new MColumnAccess[list.size()]; list.toArray(m_columnAccess); - if (log.isLoggable(Level.FINE)) log.fine("#" + m_columnAccess.length); + if (log.isLoggable(Level.FINE)) log.fine("#" + m_columnAccess.length); } // loadColumnAccess /** @@ -990,7 +990,7 @@ public final class MRole extends X_AD_Role return; ArrayList list = new ArrayList(); ArrayList dependent = new ArrayList(); - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT * FROM AD_Record_Access " + "WHERE AD_Role_ID=? AND IsActive='Y' ORDER BY AD_Table_ID"; @@ -1011,15 +1011,15 @@ public final class MRole extends X_AD_Role { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } m_recordAccess = new MRecordAccess[list.size()]; list.toArray(m_recordAccess); m_recordDependentAccess = new MRecordAccess[dependent.size()]; dependent.toArray(m_recordDependentAccess); - if (log.isLoggable(Level.FINE)) log.fine("#" + m_recordAccess.length + " - Dependent #" + m_recordDependentAccess.length); + if (log.isLoggable(Level.FINE)) log.fine("#" + m_recordAccess.length + " - Dependent #" + m_recordDependentAccess.length); } // loadRecordAccess @@ -1048,8 +1048,8 @@ public final class MRole extends X_AD_Role for (int i = 0; i < m_orgAccess.length; i++) set.add(String.valueOf(m_orgAccess[i].AD_Client_ID)); // - StringBuilder sb = new StringBuilder(); - Iterator it = set.iterator(); + StringBuilder sb = new StringBuilder(); + Iterator it = set.iterator(); boolean oneOnly = true; while (it.hasNext()) { @@ -1083,13 +1083,13 @@ public final class MRole extends X_AD_Role { if (AD_Client_ID == 0 && !rw) // can always read System return true; - // - // Check Access All Orgs: - if (isAccessAllOrgs()) { - // User has access to given AD_Client_ID if the role is defined on that AD_Client_ID - return getAD_Client_ID() == AD_Client_ID; - } - // + // + // Check Access All Orgs: + if (isAccessAllOrgs()) { + // User has access to given AD_Client_ID if the role is defined on that AD_Client_ID + return getAD_Client_ID() == AD_Client_ID; + } + // loadOrgAccess(false); // Positive List for (int i = 0; i < m_orgAccess.length; i++) @@ -1128,8 +1128,8 @@ public final class MRole extends X_AD_Role set.add(String.valueOf(m_orgAccess[i].AD_Org_ID)); } // - StringBuilder sb = new StringBuilder(); - Iterator it = set.iterator(); + StringBuilder sb = new StringBuilder(); + Iterator it = set.iterator(); boolean oneOnly = true; while (it.hasNext()) { @@ -1196,34 +1196,34 @@ public final class MRole extends X_AD_Role return false; } if (!isTableAccess(AD_Table_ID, true)) // No R/O Access to Table - return false; + return false; //default to negative list, can report on all tables - boolean canReport = true; - for (int i = 0; i < m_tableAccess.length; i++) - { + boolean canReport = true; + for (int i = 0; i < m_tableAccess.length; i++) + { if (!X_AD_Table_Access.ACCESSTYPERULE_Reporting.equals(m_tableAccess[i].getAccessTypeRule())) - continue; - if (m_tableAccess[i].isExclude()) // Exclude - { + continue; + if (m_tableAccess[i].isExclude()) // Exclude + { if (m_tableAccess[i].getAD_Table_ID() == AD_Table_ID) { - if (log.isLoggable(Level.FINE)) log.fine("Exclude " + AD_Table_ID); + if (log.isLoggable(Level.FINE)) log.fine("Exclude " + AD_Table_ID); return false; } } else // Include - { + { //positive list, can report ONLY on included tables canReport = false; if (m_tableAccess[i].getAD_Table_ID() == AD_Table_ID) { - if (log.isLoggable(Level.FINE)) log.fine("Include " + AD_Table_ID); + if (log.isLoggable(Level.FINE)) log.fine("Include " + AD_Table_ID); return true; } } } // for all Table Access - if (log.isLoggable(Level.FINE)) log.fine(AD_Table_ID + " - " + canReport); + if (log.isLoggable(Level.FINE)) log.fine(AD_Table_ID + " - " + canReport); return canReport; } // isCanReport @@ -1243,33 +1243,33 @@ public final class MRole extends X_AD_Role return false; if (!isCanReport (AD_Table_ID)) // We cannot Export if we cannot report return false; - + //default to negative list, can report on all tables - boolean canExport = true; - for (int i = 0; i < m_tableAccess.length; i++) - { + boolean canExport = true; + for (int i = 0; i < m_tableAccess.length; i++) + { if (!X_AD_Table_Access.ACCESSTYPERULE_Exporting.equals(m_tableAccess[i].getAccessTypeRule())) - continue; - if (m_tableAccess[i].isExclude()) // Exclude - { - if (m_tableAccess[i].getAD_Table_ID() == AD_Table_ID) - { - if (log.isLoggable(Level.FINE)) log.fine("Exclude " + AD_Table_ID); - return false; + continue; + if (m_tableAccess[i].isExclude()) // Exclude + { + if (m_tableAccess[i].getAD_Table_ID() == AD_Table_ID) + { + if (log.isLoggable(Level.FINE)) log.fine("Exclude " + AD_Table_ID); + return false; } } else // Include - { + { //positive list, can export ONLY on included tables - canExport = false; - if (m_tableAccess[i].getAD_Table_ID() == AD_Table_ID) + canExport = false; + if (m_tableAccess[i].getAD_Table_ID() == AD_Table_ID) { - if (log.isLoggable(Level.FINE)) log.fine("Include " + AD_Table_ID); - return true; + if (log.isLoggable(Level.FINE)) log.fine("Include " + AD_Table_ID); + return true; } } } // for all Table Access - if (log.isLoggable(Level.FINE)) log.fine(AD_Table_ID + " - " + canExport); + if (log.isLoggable(Level.FINE)) log.fine(AD_Table_ID + " - " + canExport); return canExport; } // isCanExport @@ -1284,15 +1284,15 @@ public final class MRole extends X_AD_Role if (!isTableAccessLevel (AD_Table_ID, ro)) // Role Based Access return false; loadTableAccess(false); - + //default to negative list, can access on all tables - boolean hasAccess = true; // assuming exclusive rule - for (int i = 0; i < m_tableAccess.length; i++) - { + boolean hasAccess = true; // assuming exclusive rule + for (int i = 0; i < m_tableAccess.length; i++) + { if (!X_AD_Table_Access.ACCESSTYPERULE_Accessing.equals(m_tableAccess[i].getAccessTypeRule())) - continue; - if (m_tableAccess[i].isExclude()) // Exclude - // If you Exclude Access to a table and select Read Only, + continue; + if (m_tableAccess[i].isExclude()) // Exclude + // If you Exclude Access to a table and select Read Only, // you can only read data (otherwise no access). { if (m_tableAccess[i].getAD_Table_ID() == AD_Table_ID) @@ -1301,7 +1301,7 @@ public final class MRole extends X_AD_Role hasAccess = m_tableAccess[i].isReadOnly(); else hasAccess = false; - if (log.isLoggable(Level.FINE)) log.fine("Exclude AD_Table_ID=" + AD_Table_ID + if (log.isLoggable(Level.FINE)) log.fine("Exclude AD_Table_ID=" + AD_Table_ID + " (ro=" + ro + ",TableAccessRO=" + m_tableAccess[i].isReadOnly() + ") = " + hasAccess); return hasAccess; } @@ -1309,7 +1309,7 @@ public final class MRole extends X_AD_Role else // Include // If you Include Access to a table and select Read Only, // you can only read data (otherwise full access). - { + { //positive list, can access ONLY on included tables hasAccess = false; if (m_tableAccess[i].getAD_Table_ID() == AD_Table_ID) @@ -1318,14 +1318,14 @@ public final class MRole extends X_AD_Role hasAccess = !m_tableAccess[i].isReadOnly(); else hasAccess = true; - if (log.isLoggable(Level.FINE)) log.fine("Include AD_Table_ID=" + AD_Table_ID + if (log.isLoggable(Level.FINE)) log.fine("Include AD_Table_ID=" + AD_Table_ID + " (ro=" + ro + ",TableAccessRO=" + m_tableAccess[i].isReadOnly() + ") = " + hasAccess); return hasAccess; } } } // for all Table Access if (!hasAccess) - if (log.isLoggable(Level.FINE)) log.fine("AD_Table_ID=" + AD_Table_ID + if (log.isLoggable(Level.FINE)) log.fine("AD_Table_ID=" + AD_Table_ID + "(ro=" + ro + ") = " + hasAccess); return hasAccess; } // isTableAccess @@ -1348,7 +1348,7 @@ public final class MRole extends X_AD_Role String roleAccessLevel = (String)m_tableAccessLevel.get(Integer.valueOf(AD_Table_ID)); if (roleAccessLevel == null) { - if (log.isLoggable(Level.FINE)) log.fine("NO - No AccessLevel - AD_Table_ID=" + AD_Table_ID); + if (log.isLoggable(Level.FINE)) log.fine("NO - No AccessLevel - AD_Table_ID=" + AD_Table_ID); return false; } // Access to all User Levels @@ -1369,7 +1369,7 @@ public final class MRole extends X_AD_Role && (roleAccessLevel.equals(X_AD_Table.ACCESSLEVEL_Organization) || roleAccessLevel.equals(X_AD_Table.ACCESSLEVEL_ClientPlusOrganization))) return true; - if (log.isLoggable(Level.FINE)) log.fine("NO - AD_Table_ID=" + AD_Table_ID + if (log.isLoggable(Level.FINE)) log.fine("NO - AD_Table_ID=" + AD_Table_ID + ", UserLevel=" + userLevel + ", AccessLevel=" + roleAccessLevel); return false; } // isTableAccessLevel @@ -1403,7 +1403,7 @@ public final class MRole extends X_AD_Role else retValue = false; if (!retValue) - if (log.isLoggable(Level.FINE)) log.fine("Exclude AD_Table_ID=" + AD_Table_ID + ", AD_Column_ID=" + AD_Column_ID + if (log.isLoggable(Level.FINE)) log.fine("Exclude AD_Table_ID=" + AD_Table_ID + ", AD_Column_ID=" + AD_Column_ID + " (ro=" + ro + ",ColumnAccessRO=" + m_columnAccess[i].isReadOnly() + ") = " + retValue); return retValue; } @@ -1422,7 +1422,7 @@ public final class MRole extends X_AD_Role else retValue = true; if (!retValue) - if (log.isLoggable(Level.FINE)) log.fine("Include AD_Table_ID=" + AD_Table_ID + ", AD_Column_ID=" + AD_Column_ID + if (log.isLoggable(Level.FINE)) log.fine("Include AD_Table_ID=" + AD_Table_ID + ", AD_Column_ID=" + AD_Column_ID + " (ro=" + ro + ",ColumnAccessRO=" + m_columnAccess[i].isReadOnly() + ") = " + retValue); return retValue; } @@ -1430,7 +1430,7 @@ public final class MRole extends X_AD_Role } // include } // for all Table Access if (!retValue) - if (log.isLoggable(Level.FINE)) log.fine("AD_Table_ID=" + AD_Table_ID + ", AD_Column_ID=" + AD_Column_ID + if (log.isLoggable(Level.FINE)) log.fine("AD_Table_ID=" + AD_Table_ID + ", AD_Column_ID=" + AD_Column_ID + " (ro=" + ro + ") = " + retValue); return retValue; } // isColumnAccess @@ -1491,82 +1491,82 @@ public final class MRole extends X_AD_Role public synchronized Boolean getWindowAccess (int AD_Window_ID) { if (m_windowAccess == null) - { - m_windowAccess = new HashMap(100); - // first get the window access from the included and substitute roles - mergeIncludedAccess("m_windowAccess"); // Load included accesses - metas-2009_0021_AP1_G94 - // and now get the window access directly from this role - MClient client = MClient.get(Env.getCtx()); - String ASPFilter = ""; - if (client.isUseASP()) - ASPFilter = - " AND ( AD_Window_ID IN ( " - // Just ASP subscribed windows for client " - + " SELECT w.AD_Window_ID " - + " FROM ASP_Window w, ASP_Level l, ASP_ClientLevel cl " - + " WHERE w.ASP_Level_ID = l.ASP_Level_ID " - + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() - + " AND cl.ASP_Level_ID = l.ASP_Level_ID " - + " AND w.IsActive = 'Y' " - + " AND l.IsActive = 'Y' " - + " AND cl.IsActive = 'Y' " - + " AND w.ASP_Status = 'S') " // Show - + " OR AD_Window_ID IN ( " - // + show ASP exceptions for client - + " SELECT AD_Window_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Window_ID IS NOT NULL " - + " AND ce.AD_Tab_ID IS NULL " - + " AND ce.AD_Field_ID IS NULL " - + " AND ce.ASP_Status = 'S') " // Show - + " ) " - + " AND AD_Window_ID NOT IN ( " - // minus hide ASP exceptions for client - + " SELECT AD_Window_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Window_ID IS NOT NULL " - + " AND ce.AD_Tab_ID IS NULL " - + " AND ce.AD_Field_ID IS NULL " - + " AND ce.ASP_Status = 'H')"; // Hide - String sql = "SELECT AD_Window_ID, IsReadWrite, IsActive FROM AD_Window_Access WHERE AD_Role_ID=?" + ASPFilter; - PreparedStatement pstmt = null; + { + m_windowAccess = new HashMap(100); + // first get the window access from the included and substitute roles + mergeIncludedAccess("m_windowAccess"); // Load included accesses - metas-2009_0021_AP1_G94 + // and now get the window access directly from this role + MClient client = MClient.get(Env.getCtx()); + String ASPFilter = ""; + if (client.isUseASP()) + ASPFilter = + " AND ( AD_Window_ID IN ( " + // Just ASP subscribed windows for client " + + " SELECT w.AD_Window_ID " + + " FROM ASP_Window w, ASP_Level l, ASP_ClientLevel cl " + + " WHERE w.ASP_Level_ID = l.ASP_Level_ID " + + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() + + " AND cl.ASP_Level_ID = l.ASP_Level_ID " + + " AND w.IsActive = 'Y' " + + " AND l.IsActive = 'Y' " + + " AND cl.IsActive = 'Y' " + + " AND w.ASP_Status = 'S') " // Show + + " OR AD_Window_ID IN ( " + // + show ASP exceptions for client + + " SELECT AD_Window_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Window_ID IS NOT NULL " + + " AND ce.AD_Tab_ID IS NULL " + + " AND ce.AD_Field_ID IS NULL " + + " AND ce.ASP_Status = 'S') " // Show + + " ) " + + " AND AD_Window_ID NOT IN ( " + // minus hide ASP exceptions for client + + " SELECT AD_Window_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Window_ID IS NOT NULL " + + " AND ce.AD_Tab_ID IS NULL " + + " AND ce.AD_Field_ID IS NULL " + + " AND ce.ASP_Status = 'H')"; // Hide + String sql = "SELECT AD_Window_ID, IsReadWrite, IsActive FROM AD_Window_Access WHERE AD_Role_ID=?" + ASPFilter; + PreparedStatement pstmt = null; ResultSet rs = null; - HashMap directAccess = new HashMap(100); + HashMap directAccess = new HashMap(100); try { pstmt = DB.prepareStatement(sql, get_TrxName()); pstmt.setInt(1, getAD_Role_ID()); rs = pstmt.executeQuery(); - while (rs.next()) { - Integer winId = Integer.valueOf(rs.getInt(1)); - if ("N".equals(rs.getString(3))) { - // inactive window on direct access - if (m_windowAccess.containsKey(winId)) { - m_windowAccess.remove(winId); - } - } else { - directAccess.put(winId, Boolean.valueOf("Y".equals(rs.getString(2)))); - } - } + while (rs.next()) { + Integer winId = Integer.valueOf(rs.getInt(1)); + if ("N".equals(rs.getString(3))) { + // inactive window on direct access + if (m_windowAccess.containsKey(winId)) { + m_windowAccess.remove(winId); + } + } else { + directAccess.put(winId, Boolean.valueOf("Y".equals(rs.getString(2)))); + } + } } catch (Exception e) { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } - // - setAccessMap("m_windowAccess", mergeAccess(getAccessMap("m_windowAccess"), directAccess, true)); - if (log.isLoggable(Level.FINE)) log.fine("#" + m_windowAccess.size()); + // + setAccessMap("m_windowAccess", mergeAccess(getAccessMap("m_windowAccess"), directAccess, true)); + if (log.isLoggable(Level.FINE)) log.fine("#" + m_windowAccess.size()); } // reload - Boolean retValue = m_windowAccess.get(AD_Window_ID); - if (log.isLoggable(Level.FINE)) log.fine("getWindowAccess - AD_Window_ID=" + AD_Window_ID + " - " + retValue); + Boolean retValue = m_windowAccess.get(AD_Window_ID); + if (log.isLoggable(Level.FINE)) log.fine("getWindowAccess - AD_Window_ID=" + AD_Window_ID + " - " + retValue); return retValue; } // getWindowAccess @@ -1579,77 +1579,77 @@ public final class MRole extends X_AD_Role { if (m_processAccess == null) { - m_processAccess = new HashMap(50); - // first get the process access from the included and substitute roles - mergeIncludedAccess("m_processAccess"); // Load included accesses - metas-2009_0021_AP1_G94 - // and now get the process access directly from this role - MClient client = MClient.get(Env.getCtx()); - String ASPFilter = ""; - if (client.isUseASP()) - ASPFilter = - " AND ( AD_Process_ID IN ( " - // Just ASP subscribed processes for client " - + " SELECT p.AD_Process_ID " - + " FROM ASP_Process p, ASP_Level l, ASP_ClientLevel cl " - + " WHERE p.ASP_Level_ID = l.ASP_Level_ID " - + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() - + " AND cl.ASP_Level_ID = l.ASP_Level_ID " - + " AND p.IsActive = 'Y' " - + " AND l.IsActive = 'Y' " - + " AND cl.IsActive = 'Y' " - + " AND p.ASP_Status = 'S') " // Show - + " OR AD_Process_ID IN ( " - // + show ASP exceptions for client - + " SELECT AD_Process_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Process_ID IS NOT NULL " - + " AND ce.AD_Process_Para_ID IS NULL " - + " AND ce.ASP_Status = 'S') " // Show - + " ) " - + " AND AD_Process_ID NOT IN ( " - // minus hide ASP exceptions for client - + " SELECT AD_Process_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Process_ID IS NOT NULL " - + " AND ce.AD_Process_Para_ID IS NULL " - + " AND ce.ASP_Status = 'H')"; // Hide - String sql = "SELECT AD_Process_ID, IsReadWrite, IsActive FROM AD_Process_Access WHERE AD_Role_ID=?" + ASPFilter; - PreparedStatement pstmt = null; + m_processAccess = new HashMap(50); + // first get the process access from the included and substitute roles + mergeIncludedAccess("m_processAccess"); // Load included accesses - metas-2009_0021_AP1_G94 + // and now get the process access directly from this role + MClient client = MClient.get(Env.getCtx()); + String ASPFilter = ""; + if (client.isUseASP()) + ASPFilter = + " AND ( AD_Process_ID IN ( " + // Just ASP subscribed processes for client " + + " SELECT p.AD_Process_ID " + + " FROM ASP_Process p, ASP_Level l, ASP_ClientLevel cl " + + " WHERE p.ASP_Level_ID = l.ASP_Level_ID " + + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() + + " AND cl.ASP_Level_ID = l.ASP_Level_ID " + + " AND p.IsActive = 'Y' " + + " AND l.IsActive = 'Y' " + + " AND cl.IsActive = 'Y' " + + " AND p.ASP_Status = 'S') " // Show + + " OR AD_Process_ID IN ( " + // + show ASP exceptions for client + + " SELECT AD_Process_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Process_ID IS NOT NULL " + + " AND ce.AD_Process_Para_ID IS NULL " + + " AND ce.ASP_Status = 'S') " // Show + + " ) " + + " AND AD_Process_ID NOT IN ( " + // minus hide ASP exceptions for client + + " SELECT AD_Process_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Process_ID IS NOT NULL " + + " AND ce.AD_Process_Para_ID IS NULL " + + " AND ce.ASP_Status = 'H')"; // Hide + String sql = "SELECT AD_Process_ID, IsReadWrite, IsActive FROM AD_Process_Access WHERE AD_Role_ID=?" + ASPFilter; + PreparedStatement pstmt = null; ResultSet rs = null; - HashMap directAccess = new HashMap(100); + HashMap directAccess = new HashMap(100); try { pstmt = DB.prepareStatement(sql, get_TrxName()); pstmt.setInt(1, getAD_Role_ID()); rs = pstmt.executeQuery(); - while (rs.next()) { - Integer procId = Integer.valueOf(rs.getInt(1)); - if ("N".equals(rs.getString(3))) { - // inactive process on direct access - if (m_processAccess.containsKey(procId)) { - m_processAccess.remove(procId); - } - } else { - directAccess.put(procId, Boolean.valueOf("Y".equals(rs.getString(2)))); - } - } + while (rs.next()) { + Integer procId = Integer.valueOf(rs.getInt(1)); + if ("N".equals(rs.getString(3))) { + // inactive process on direct access + if (m_processAccess.containsKey(procId)) { + m_processAccess.remove(procId); + } + } else { + directAccess.put(procId, Boolean.valueOf("Y".equals(rs.getString(2)))); + } + } } catch (Exception e) { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } - setAccessMap("m_processAccess", mergeAccess(getAccessMap("m_processAccess"), directAccess, true)); + setAccessMap("m_processAccess", mergeAccess(getAccessMap("m_processAccess"), directAccess, true)); } // reload - Boolean retValue = m_processAccess.get(AD_Process_ID); - return retValue; + Boolean retValue = m_processAccess.get(AD_Process_ID); + return retValue; } // getProcessAccess /** @@ -1662,74 +1662,74 @@ public final class MRole extends X_AD_Role if (m_taskAccess == null) { m_taskAccess = new HashMap(10); - // first get the task access from the included and substitute roles - mergeIncludedAccess("m_taskAccess"); // Load included accesses - metas-2009_0021_AP1_G94 - // and now get the task access directly from this role - MClient client = MClient.get(Env.getCtx()); - String ASPFilter = ""; - if (client.isUseASP()) - ASPFilter = - " AND ( AD_Task_ID IN ( " - // Just ASP subscribed tasks for client " - + " SELECT t.AD_Task_ID " - + " FROM ASP_Task t, ASP_Level l, ASP_ClientLevel cl " - + " WHERE t.ASP_Level_ID = l.ASP_Level_ID " - + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() - + " AND cl.ASP_Level_ID = l.ASP_Level_ID " - + " AND t.IsActive = 'Y' " - + " AND l.IsActive = 'Y' " - + " AND cl.IsActive = 'Y' " - + " AND t.ASP_Status = 'S') " // Show - + " OR AD_Task_ID IN ( " - // + show ASP exceptions for client - + " SELECT AD_Task_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Task_ID IS NOT NULL " - + " AND ce.ASP_Status = 'S') " // Show - + " ) " - + " AND AD_Task_ID NOT IN ( " - // minus hide ASP exceptions for client - + " SELECT AD_Task_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Task_ID IS NOT NULL " - + " AND ce.ASP_Status = 'H')"; // Hide - String sql = "SELECT AD_Task_ID, IsReadWrite, IsActive FROM AD_Task_Access WHERE AD_Role_ID=?" + ASPFilter; - PreparedStatement pstmt = null; + // first get the task access from the included and substitute roles + mergeIncludedAccess("m_taskAccess"); // Load included accesses - metas-2009_0021_AP1_G94 + // and now get the task access directly from this role + MClient client = MClient.get(Env.getCtx()); + String ASPFilter = ""; + if (client.isUseASP()) + ASPFilter = + " AND ( AD_Task_ID IN ( " + // Just ASP subscribed tasks for client " + + " SELECT t.AD_Task_ID " + + " FROM ASP_Task t, ASP_Level l, ASP_ClientLevel cl " + + " WHERE t.ASP_Level_ID = l.ASP_Level_ID " + + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() + + " AND cl.ASP_Level_ID = l.ASP_Level_ID " + + " AND t.IsActive = 'Y' " + + " AND l.IsActive = 'Y' " + + " AND cl.IsActive = 'Y' " + + " AND t.ASP_Status = 'S') " // Show + + " OR AD_Task_ID IN ( " + // + show ASP exceptions for client + + " SELECT AD_Task_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Task_ID IS NOT NULL " + + " AND ce.ASP_Status = 'S') " // Show + + " ) " + + " AND AD_Task_ID NOT IN ( " + // minus hide ASP exceptions for client + + " SELECT AD_Task_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Task_ID IS NOT NULL " + + " AND ce.ASP_Status = 'H')"; // Hide + String sql = "SELECT AD_Task_ID, IsReadWrite, IsActive FROM AD_Task_Access WHERE AD_Role_ID=?" + ASPFilter; + PreparedStatement pstmt = null; ResultSet rs = null; - HashMap directAccess = new HashMap(100); + HashMap directAccess = new HashMap(100); try { pstmt = DB.prepareStatement(sql, get_TrxName()); pstmt.setInt(1, getAD_Role_ID()); rs = pstmt.executeQuery(); - while (rs.next()) { - Integer taskId = Integer.valueOf(rs.getInt(1)); - if ("N".equals(rs.getString(3))) { - // inactive task on direct access - if (m_taskAccess.containsKey(taskId)) { - m_taskAccess.remove(taskId); - } - } else { - directAccess.put(taskId, Boolean.valueOf("Y".equals(rs.getString(2)))); - } - } + while (rs.next()) { + Integer taskId = Integer.valueOf(rs.getInt(1)); + if ("N".equals(rs.getString(3))) { + // inactive task on direct access + if (m_taskAccess.containsKey(taskId)) { + m_taskAccess.remove(taskId); + } + } else { + directAccess.put(taskId, Boolean.valueOf("Y".equals(rs.getString(2)))); + } + } } catch (Exception e) { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } - setAccessMap("m_taskAccess", mergeAccess(getAccessMap("m_taskAccess"), directAccess, true)); + setAccessMap("m_taskAccess", mergeAccess(getAccessMap("m_taskAccess"), directAccess, true)); } // reload - Boolean retValue = m_taskAccess.get(AD_Task_ID); - return retValue; + Boolean retValue = m_taskAccess.get(AD_Task_ID); + return retValue; } // getTaskAccess /** @@ -1742,75 +1742,75 @@ public final class MRole extends X_AD_Role if (m_formAccess == null) { m_formAccess = new HashMap(20); - // first get the form access from the included and substitute roles - mergeIncludedAccess("m_formAccess"); // Load included accesses - metas-2009_0021_AP1_G94 - // and now get the form access directly from this role - MClient client = MClient.get(Env.getCtx()); - String ASPFilter = ""; - if (client.isUseASP()) - ASPFilter = - " AND ( AD_Form_ID IN ( " - // Just ASP subscribed forms for client " - + " SELECT f.AD_Form_ID " - + " FROM ASP_Form f, ASP_Level l, ASP_ClientLevel cl " - + " WHERE f.ASP_Level_ID = l.ASP_Level_ID " - + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() - + " AND cl.ASP_Level_ID = l.ASP_Level_ID " - + " AND f.IsActive = 'Y' " - + " AND l.IsActive = 'Y' " - + " AND cl.IsActive = 'Y' " - + " AND f.ASP_Status = 'S') " // Show - + " OR AD_Form_ID IN ( " - // + show ASP exceptions for client - + " SELECT AD_Form_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Form_ID IS NOT NULL " - + " AND ce.ASP_Status = 'S') " // Show - + " ) " - + " AND AD_Form_ID NOT IN ( " - // minus hide ASP exceptions for client - + " SELECT AD_Form_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Form_ID IS NOT NULL " - + " AND ce.ASP_Status = 'H')"; // Hide - String sql = "SELECT AD_Form_ID, IsReadWrite, IsActive FROM AD_Form_Access WHERE AD_Role_ID=?" + ASPFilter; - PreparedStatement pstmt = null; + // first get the form access from the included and substitute roles + mergeIncludedAccess("m_formAccess"); // Load included accesses - metas-2009_0021_AP1_G94 + // and now get the form access directly from this role + MClient client = MClient.get(Env.getCtx()); + String ASPFilter = ""; + if (client.isUseASP()) + ASPFilter = + " AND ( AD_Form_ID IN ( " + // Just ASP subscribed forms for client " + + " SELECT f.AD_Form_ID " + + " FROM ASP_Form f, ASP_Level l, ASP_ClientLevel cl " + + " WHERE f.ASP_Level_ID = l.ASP_Level_ID " + + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() + + " AND cl.ASP_Level_ID = l.ASP_Level_ID " + + " AND f.IsActive = 'Y' " + + " AND l.IsActive = 'Y' " + + " AND cl.IsActive = 'Y' " + + " AND f.ASP_Status = 'S') " // Show + + " OR AD_Form_ID IN ( " + // + show ASP exceptions for client + + " SELECT AD_Form_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Form_ID IS NOT NULL " + + " AND ce.ASP_Status = 'S') " // Show + + " ) " + + " AND AD_Form_ID NOT IN ( " + // minus hide ASP exceptions for client + + " SELECT AD_Form_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Form_ID IS NOT NULL " + + " AND ce.ASP_Status = 'H')"; // Hide + String sql = "SELECT AD_Form_ID, IsReadWrite, IsActive FROM AD_Form_Access WHERE AD_Role_ID=?" + ASPFilter; + PreparedStatement pstmt = null; ResultSet rs = null; - HashMap directAccess = new HashMap(100); + HashMap directAccess = new HashMap(100); try { pstmt = DB.prepareStatement(sql, get_TrxName()); pstmt.setInt(1, getAD_Role_ID()); rs = pstmt.executeQuery(); - while (rs.next()) { - Integer formId = Integer.valueOf(rs.getInt(1)); - if ("N".equals(rs.getString(3))) { - // inactive form on direct access - if (m_formAccess.containsKey(formId)) { - m_formAccess.remove(formId); - } - } else { - directAccess.put(formId, Boolean.valueOf("Y".equals(rs.getString(2)))); - } - } + while (rs.next()) { + Integer formId = Integer.valueOf(rs.getInt(1)); + if ("N".equals(rs.getString(3))) { + // inactive form on direct access + if (m_formAccess.containsKey(formId)) { + m_formAccess.remove(formId); + } + } else { + directAccess.put(formId, Boolean.valueOf("Y".equals(rs.getString(2)))); + } + } } catch (Exception e) { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } - setAccessMap("m_formAccess", mergeAccess(getAccessMap("m_formAccess"), directAccess, true)); + setAccessMap("m_formAccess", mergeAccess(getAccessMap("m_formAccess"), directAccess, true)); } // reload - Boolean retValue = m_formAccess.get(AD_Form_ID); - return retValue; - } // getFormAccess + Boolean retValue = m_formAccess.get(AD_Form_ID); + return retValue; + } // getFormAccess /** * Get Workflow Access @@ -1822,74 +1822,74 @@ public final class MRole extends X_AD_Role if (m_workflowAccess == null) { m_workflowAccess = new HashMap(20); - // first get the workflow access from the included and substitute roles - mergeIncludedAccess("m_workflowAccess"); // Load included accesses - metas-2009_0021_AP1_G94 - // and now get the workflow access directly from this role - MClient client = MClient.get(Env.getCtx()); - String ASPFilter = ""; - if (client.isUseASP()) - ASPFilter = - " AND ( AD_Workflow_ID IN ( " - // Just ASP subscribed workflows for client " - + " SELECT w.AD_Workflow_ID " - + " FROM ASP_Workflow w, ASP_Level l, ASP_ClientLevel cl " - + " WHERE w.ASP_Level_ID = l.ASP_Level_ID " - + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() - + " AND cl.ASP_Level_ID = l.ASP_Level_ID " - + " AND w.IsActive = 'Y' " - + " AND l.IsActive = 'Y' " - + " AND cl.IsActive = 'Y' " - + " AND w.ASP_Status = 'S') " // Show - + " OR AD_Workflow_ID IN ( " - // + show ASP exceptions for client - + " SELECT AD_Workflow_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Workflow_ID IS NOT NULL " - + " AND ce.ASP_Status = 'S') " // Show - + " ) " - + " AND AD_Workflow_ID NOT IN ( " - // minus hide ASP exceptions for client - + " SELECT AD_Workflow_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Workflow_ID IS NOT NULL " - + " AND ce.ASP_Status = 'H')"; // Hide - String sql = "SELECT AD_Workflow_ID, IsReadWrite, IsActive FROM AD_Workflow_Access WHERE AD_Role_ID=?" + ASPFilter; - PreparedStatement pstmt = null; + // first get the workflow access from the included and substitute roles + mergeIncludedAccess("m_workflowAccess"); // Load included accesses - metas-2009_0021_AP1_G94 + // and now get the workflow access directly from this role + MClient client = MClient.get(Env.getCtx()); + String ASPFilter = ""; + if (client.isUseASP()) + ASPFilter = + " AND ( AD_Workflow_ID IN ( " + // Just ASP subscribed workflows for client " + + " SELECT w.AD_Workflow_ID " + + " FROM ASP_Workflow w, ASP_Level l, ASP_ClientLevel cl " + + " WHERE w.ASP_Level_ID = l.ASP_Level_ID " + + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() + + " AND cl.ASP_Level_ID = l.ASP_Level_ID " + + " AND w.IsActive = 'Y' " + + " AND l.IsActive = 'Y' " + + " AND cl.IsActive = 'Y' " + + " AND w.ASP_Status = 'S') " // Show + + " OR AD_Workflow_ID IN ( " + // + show ASP exceptions for client + + " SELECT AD_Workflow_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Workflow_ID IS NOT NULL " + + " AND ce.ASP_Status = 'S') " // Show + + " ) " + + " AND AD_Workflow_ID NOT IN ( " + // minus hide ASP exceptions for client + + " SELECT AD_Workflow_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Workflow_ID IS NOT NULL " + + " AND ce.ASP_Status = 'H')"; // Hide + String sql = "SELECT AD_Workflow_ID, IsReadWrite, IsActive FROM AD_Workflow_Access WHERE AD_Role_ID=?" + ASPFilter; + PreparedStatement pstmt = null; ResultSet rs = null; - HashMap directAccess = new HashMap(100); + HashMap directAccess = new HashMap(100); try { pstmt = DB.prepareStatement(sql, get_TrxName()); pstmt.setInt(1, getAD_Role_ID()); rs = pstmt.executeQuery(); - while (rs.next()) { - Integer formId = Integer.valueOf(rs.getInt(1)); - if ("N".equals(rs.getString(3))) { - // inactive workflow on direct access - if (m_workflowAccess.containsKey(formId)) { - m_workflowAccess.remove(formId); - } - } else { - directAccess.put(formId, Boolean.valueOf("Y".equals(rs.getString(2)))); - } - } + while (rs.next()) { + Integer formId = Integer.valueOf(rs.getInt(1)); + if ("N".equals(rs.getString(3))) { + // inactive workflow on direct access + if (m_workflowAccess.containsKey(formId)) { + m_workflowAccess.remove(formId); + } + } else { + directAccess.put(formId, Boolean.valueOf("Y".equals(rs.getString(2)))); + } + } } catch (Exception e) { log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); + finally + { + DB.close(rs, pstmt); } - setAccessMap("m_workflowAccess", mergeAccess(getAccessMap("m_workflowAccess"), directAccess, true)); + setAccessMap("m_workflowAccess", mergeAccess(getAccessMap("m_workflowAccess"), directAccess, true)); } // reload - Boolean retValue = m_workflowAccess.get(AD_Workflow_ID); - return retValue; + Boolean retValue = m_workflowAccess.get(AD_Workflow_ID); + return retValue; } // getTaskAccess @@ -1905,7 +1905,7 @@ public final class MRole extends X_AD_Role public String addAccessSQL (String SQL, String TableNameIn, boolean fullyQualified, boolean rw) { - StringBuilder retSQL = new StringBuilder(); + StringBuilder retSQL = new StringBuilder(); // Cut off last ORDER BY clause String orderBy = ""; @@ -1948,39 +1948,39 @@ public final class MRole extends X_AD_Role tableName = TableNameIn; } - if (! tableName.equals(X_AD_PInstance_Log.Table_Name)) { // globalqss, bug 1662433 - // Client Access - if (fullyQualified) - retSQL.append(tableName).append("."); - retSQL.append(getClientWhere(rw)); - - // Org Access - if (!isAccessAllOrgs()) - { - retSQL.append(" AND "); - if (fullyQualified) - retSQL.append(tableName).append("."); - retSQL.append(getOrgWhere(rw)); - } - } else { - retSQL.append("1=1"); + if (! tableName.equals(X_AD_PInstance_Log.Table_Name)) { // globalqss, bug 1662433 + // Client Access + if (fullyQualified) + retSQL.append(tableName).append("."); + retSQL.append(getClientWhere(rw)); + + // Org Access + if (!isAccessAllOrgs()) + { + retSQL.append(" AND "); + if (fullyQualified) + retSQL.append(tableName).append("."); + retSQL.append(getOrgWhere(rw)); + } + } else { + retSQL.append("1=1"); } // ** Data Access ** for (int i = 0; i < ti.length; i++) - { - String TableName = ti[i].getTableName(); - - //[ 1644310 ] Rev. 1292 hangs on start - if (TableName.toUpperCase().endsWith("_TRL")) continue; - if (isView(TableName)) continue; + { + String TableName = ti[i].getTableName(); + + //[ 1644310 ] Rev. 1292 hangs on start + if (TableName.toUpperCase().endsWith("_TRL")) continue; + if (isView(TableName)) continue; int AD_Table_ID = getAD_Table_ID (TableName); // Data Table Access if (AD_Table_ID != 0 && !isTableAccess(AD_Table_ID, !rw)) { retSQL.append(" AND 1=3"); // prevent access at all - if (log.isLoggable(Level.FINE)) log.fine("No access to AD_Table_ID=" + AD_Table_ID + if (log.isLoggable(Level.FINE)) log.fine("No access to AD_Table_ID=" + AD_Table_ID + " - " + TableName + " - " + retSQL); break; // no need to check further } @@ -1998,8 +1998,8 @@ public final class MRole extends X_AD_Role keyColumnName = TableName; keyColumnName += "."; } - //keyColumnName += TableName + "_ID"; // derived from table - if (getIdColumnName(TableName) == null) continue; + //keyColumnName += TableName + "_ID"; // derived from table + if (getIdColumnName(TableName) == null) continue; keyColumnName += getIdColumnName(TableName); //log.fine("addAccessSQL - " + TableName + "(" + AD_Table_ID + ") " + keyColumnName); @@ -2007,7 +2007,7 @@ public final class MRole extends X_AD_Role if (recordWhere.length() > 0) { retSQL.append(" AND ").append(recordWhere); - if (log.isLoggable(Level.FINEST)) log.finest("Record access - " + recordWhere); + if (log.isLoggable(Level.FINEST)) log.finest("Record access - " + recordWhere); } } // for all table info @@ -2023,29 +2023,29 @@ public final class MRole extends X_AD_Role String columnName = m_recordDependentAccess[i].getKeyColumnName (asp.getTableInfo(asp.getMainSqlIndex()) ); if (columnName == null) - continue; // no key column - - if (mainSql.toUpperCase().startsWith("SELECT COUNT(*) FROM ")) { - // globalqss - Carlos Ruiz - [ 1965744 ] Dependent entities access problem - // this is the count select, it doesn't have the column but needs to be filtered - MTable table = MTable.get(getCtx(), tableName); - if (table == null) - continue; - MColumn column = table.getColumn(columnName); - if (column == null || column.isVirtualColumn() || !column.isActive()) - continue; - } else { - int posColumn = mainSql.indexOf(columnName); - if (posColumn == -1) - continue; - // we found the column name - make sure it's a column name - char charCheck = mainSql.charAt(posColumn-1); // before - if (!(charCheck == ',' || charCheck == '.' || charCheck == ' ' || charCheck == '(')) - continue; - charCheck = mainSql.charAt(posColumn+columnName.length()); // after - if (!(charCheck == ',' || charCheck == ' ' || charCheck == ')')) - continue; - } + continue; // no key column + + if (mainSql.toUpperCase().startsWith("SELECT COUNT(*) FROM ")) { + // globalqss - Carlos Ruiz - [ 1965744 ] Dependent entities access problem + // this is the count select, it doesn't have the column but needs to be filtered + MTable table = MTable.get(getCtx(), tableName); + if (table == null) + continue; + MColumn column = table.getColumn(columnName); + if (column == null || column.isVirtualColumn() || !column.isActive()) + continue; + } else { + int posColumn = mainSql.indexOf(columnName); + if (posColumn == -1) + continue; + // we found the column name - make sure it's a column name + char charCheck = mainSql.charAt(posColumn-1); // before + if (!(charCheck == ',' || charCheck == '.' || charCheck == ' ' || charCheck == '(')) + continue; + charCheck = mainSql.charAt(posColumn+columnName.length()); // after + if (!(charCheck == ',' || charCheck == ' ' || charCheck == ')')) + continue; + } if (AD_Table_ID != 0 && AD_Table_ID != m_recordDependentAccess[i].getAD_Table_ID()) retSQL.append(getDependentAccess(whereColumnName, includes, excludes)); @@ -2055,19 +2055,19 @@ public final class MRole extends X_AD_Role if (m_recordDependentAccess[i].isExclude()) { excludes.add(m_recordDependentAccess[i].getRecord_ID()); - if (log.isLoggable(Level.FINE)) log.fine("Exclude " + columnName + " - " + m_recordDependentAccess[i]); + if (log.isLoggable(Level.FINE)) log.fine("Exclude " + columnName + " - " + m_recordDependentAccess[i]); } else if (!rw || !m_recordDependentAccess[i].isReadOnly()) { includes.add(m_recordDependentAccess[i].getRecord_ID()); - if (log.isLoggable(Level.FINE)) log.fine("Include " + columnName + " - " + m_recordDependentAccess[i]); + if (log.isLoggable(Level.FINE)) log.fine("Include " + columnName + " - " + m_recordDependentAccess[i]); } whereColumnName = getDependentRecordWhereColumn (mainSql, columnName); } // for all dependent records retSQL.append(getDependentAccess(whereColumnName, includes, excludes)); // retSQL.append(orderBy); - if (log.isLoggable(Level.FINEST)) log.finest(retSQL.toString()); + if (log.isLoggable(Level.FINEST)) log.finest(retSQL.toString()); return retSQL.toString(); } // addAccessSQL @@ -2086,7 +2086,7 @@ public final class MRole extends X_AD_Role if (includes.size() != 0 && excludes.size() != 0) log.warning("Mixing Include and Excluse rules - Will not return values"); - StringBuilder where = new StringBuilder(" AND "); + StringBuilder where = new StringBuilder(" AND "); if (includes.size() == 1) where.append(whereColumnName).append("=").append(includes.get(0)); else if (includes.size() > 1) @@ -2100,14 +2100,14 @@ public final class MRole extends X_AD_Role } where.append(")"); } - else if (excludes.size() == 1) - { - where.append("(" + whereColumnName + " IS NULL OR "); - where.append(whereColumnName).append("<>").append(excludes.get(0)).append(")"); - } + else if (excludes.size() == 1) + { + where.append("(" + whereColumnName + " IS NULL OR "); + where.append(whereColumnName).append("<>").append(excludes.get(0)).append(")"); + } else if (excludes.size() > 1) - { - where.append("(" + whereColumnName + " IS NULL OR "); + { + where.append("(" + whereColumnName + " IS NULL OR "); where.append(whereColumnName).append(" NOT IN ("); for (int ii = 0; ii < excludes.size(); ii++) { @@ -2115,9 +2115,9 @@ public final class MRole extends X_AD_Role where.append(","); where.append(excludes.get(ii)); } - where.append("))"); + where.append("))"); } - if (log.isLoggable(Level.FINEST)) log.finest(where.toString()); + if (log.isLoggable(Level.FINEST)) log.finest(where.toString()); return where.toString(); } // getDependentAccess @@ -2131,15 +2131,15 @@ public final class MRole extends X_AD_Role private String getDependentRecordWhereColumn (String mainSql, String columnName) { String retValue = columnName; // if nothing else found - int index = mainSql.indexOf(columnName); - if (index == -1) + int index = mainSql.indexOf(columnName); + if (index == -1) return retValue; // see if there are table synonym int offset = index - 1; char c = mainSql.charAt(offset); if (c == '.') { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); while (c != ' ' && c != ',' && c != '(') // delimeter { sb.insert(0, c); @@ -2205,31 +2205,31 @@ public final class MRole extends X_AD_Role whatMissing += "O"; } - // Client Access: Verify if the role has access to the given client - teo_sarca, BF [ 1982398 ] - if (retValue) { - retValue = isClientAccess(AD_Client_ID, true); // r/w access - whatMissing += "C"; - } - - // Org Access: Verify if the role has access to the given organization - teo_sarca, patch [ 1628050 ] - if (retValue) { - retValue = isOrgAccess(AD_Org_ID, true); // r/w access - whatMissing="W"; - } - + // Client Access: Verify if the role has access to the given client - teo_sarca, BF [ 1982398 ] + if (retValue) { + retValue = isClientAccess(AD_Client_ID, true); // r/w access + whatMissing += "C"; + } + + // Org Access: Verify if the role has access to the given organization - teo_sarca, patch [ 1628050 ] + if (retValue) { + retValue = isOrgAccess(AD_Org_ID, true); // r/w access + whatMissing="W"; + } + // Data Access if (retValue) retValue = isTableAccess(AD_Table_ID, false); if (retValue && Record_ID != 0) retValue = isRecordAccess(AD_Table_ID, Record_ID, false); - - if (!retValue && createError) - { + + if (!retValue && createError) + { log.saveWarning("AccessTableNoUpdate", - "AD_Client_ID=" + AD_Client_ID - + ", AD_Org_ID=" + AD_Org_ID + ", UserLevel=" + userLevel - + " => missing=" + whatMissing); + "AD_Client_ID=" + AD_Client_ID + + ", AD_Org_ID=" + AD_Org_ID + ", UserLevel=" + userLevel + + " => missing=" + whatMissing); log.warning (toString()); } return retValue; @@ -2290,20 +2290,20 @@ public final class MRole extends X_AD_Role if (retValue) return retValue; - // Notification - /** - if (forInsert) - log.saveWarning("AccessTableNoUpdate", - "(Required=" + TableLevel + "(" - + getTableLevelString(Env.getAD_Language(ctx), TableLevel) - + ") != UserLevel=" + userLevel); - else - **/ - log.saveWarning("AccessTableNoView", - "Required=" + TableLevel + "(" - + getTableLevelString(Env.getAD_Language(ctx), TableLevel) - + ") != UserLevel=" + userLevel); - if (log.isLoggable(Level.INFO)) log.info (toString()); + // Notification + /** + if (forInsert) + log.saveWarning("AccessTableNoUpdate", + "(Required=" + TableLevel + "(" + + getTableLevelString(Env.getAD_Language(ctx), TableLevel) + + ") != UserLevel=" + userLevel); + else + **/ + log.saveWarning("AccessTableNoView", + "Required=" + TableLevel + "(" + + getTableLevelString(Env.getAD_Language(ctx), TableLevel) + + ") != UserLevel=" + userLevel); + if (log.isLoggable(Level.INFO)) log.info (toString()); return retValue; } // canView @@ -2369,9 +2369,9 @@ public final class MRole extends X_AD_Role // NOT IN (x) if (m_recordAccess[i].isExclude()) { - if (sbExclude.length() == 0){ - sbExclude.append("(").append(keyColumnName).append(" IS NULL OR "); - sbExclude.append(keyColumnName).append(" NOT IN ("); + if (sbExclude.length() == 0){ + sbExclude.append("(").append(keyColumnName).append(" IS NULL OR "); + sbExclude.append(keyColumnName).append(" NOT IN ("); } else sbExclude.append(","); @@ -2390,7 +2390,7 @@ public final class MRole extends X_AD_Role } } // for all Table Access - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); if (sbExclude.length() > 0) sb.append(sbExclude).append("))"); if (sbInclude.length() > 0) @@ -2407,9 +2407,9 @@ public final class MRole extends X_AD_Role if (lockedIDs != null) { if (sb.length() > 0) - sb.append(" AND "); - sb.append(" (" + keyColumnName + " IS NULL OR "); - sb.append(keyColumnName).append(lockedIDs).append(") "); + sb.append(" AND "); + sb.append(" (" + keyColumnName + " IS NULL OR "); + sb.append(keyColumnName).append(lockedIDs).append(") "); } } // @@ -2419,23 +2419,23 @@ public final class MRole extends X_AD_Role /** * Show (Value) Preference Menu * @return true if preference type is not None - */ - public boolean isShowPreference() - { - return !X_AD_Role.PREFERENCETYPE_None.equals(getPreferenceType()); - } // isShowPreference - - /** + */ + public boolean isShowPreference() + { + return !X_AD_Role.PREFERENCETYPE_None.equals(getPreferenceType()); + } // isShowPreference + + /** * Org Access Summary */ class OrgAccess implements Serializable { - /** - * - */ - private static final long serialVersionUID = -4880665261978385315L; - - + /** + * + */ + private static final long serialVersionUID = -4880665261978385315L; + + /** * Org Access constructor * @param ad_Client_ID client @@ -2494,7 +2494,7 @@ public final class MRole extends X_AD_Role String orgName = "*"; if (AD_Org_ID != 0) orgName = MOrg.get(getCtx(), AD_Org_ID).getName(); - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.append(Msg.translate(getCtx(), "AD_Client_ID")).append("=") .append(clientName).append(" - ") .append(Msg.translate(getCtx(), "AD_Org_ID")).append("=") @@ -2506,696 +2506,696 @@ public final class MRole extends X_AD_Role } // OrgAccess - /** - * Checks the access rights of the given role/client for the given document actions. - * @param clientId - * @param docTypeId - * @param options - * @param maxIndex - * @return number of valid actions in the String[] options - * @see metas-2009_0021_AP1_G94 - */ - public int checkActionAccess(int clientId, int docTypeId, String[] options, - int maxIndex) { - if (maxIndex <= 0) - return maxIndex; - // - final ArrayList validOptions = new ArrayList(); - final List optionParams = new ArrayList(); - // - final StringBuffer sql_values = new StringBuffer(); - for (int i = 0; i < maxIndex; i++) { - if (sql_values.length() > 0) - sql_values.append(","); - sql_values.append("?"); - optionParams.add(options[i]); - } - // - PreparedStatement pstmt = null; - ResultSet rs = null; - - List roles = getIncludedRoles(true); - roles.add(this); // add current role to the list of included roles - String sql = null; - try { - for (MRole role : roles) { - int idxpar = 1; - if (role.getAD_Client_ID() == 0 && role.isMasterRole()) { - // master role on system - check options based on docbasetype and docsubtypeso - MDocType doc = new MDocType(getCtx(), docTypeId, get_TrxName()); - - sql = "SELECT DISTINCT rl.Value, a.IsActive" - + " FROM AD_Document_Action_Access a" - + " INNER JOIN AD_Ref_List rl ON (rl.AD_Reference_ID=135 and rl.AD_Ref_List_ID=a.AD_Ref_List_ID)" - + " INNER JOIN AD_Role ro ON (a.AD_Role_ID=ro.AD_Role_ID)" - + " INNER JOIN C_Doctype ty ON (a.C_Doctype_ID=ty.C_Doctype_ID)" - + " WHERE ro.AD_Role_ID=?" - + " AND ty.DocBaseType=?" - + (MDocType.DOCBASETYPE_SalesOrder.equals(doc.getDocBaseType()) ? " AND ty.DocSubTypeSO=?" : "") - + (MDocType.DOCBASETYPE_PurchaseOrder.equals(doc.getDocBaseType()) && doc.getDocSubTypeSO() != null ? " AND ty.DocSubTypeSO=?" : "") - + (MDocType.DOCBASETYPE_MaterialPhysicalInventory.equals(doc.getDocBaseType()) ? " AND ty.DocSubTypeInv=?" : "") - + " AND rl.Value IN (" - + sql_values - + ")"; - - pstmt = DB.prepareStatement(sql, get_TrxName()); - pstmt.setInt(idxpar++, role.getAD_Role_ID()); - pstmt.setString(idxpar++, doc.getDocBaseType()); - if (MDocType.DOCBASETYPE_SalesOrder.equals(doc.getDocBaseType())) - pstmt.setString(idxpar++, doc.getDocSubTypeSO()); - else if (MDocType.DOCBASETYPE_PurchaseOrder.equals(doc.getDocBaseType()) && doc.getDocSubTypeSO() != null) - pstmt.setString(idxpar++, doc.getDocSubTypeSO()); - else if (MDocType.DOCBASETYPE_MaterialPhysicalInventory.equals(doc.getDocBaseType())) - pstmt.setString(idxpar++, doc.getDocSubTypeInv()); - } else { - // master role on tenant - check options based on doctypeid - sql = "SELECT DISTINCT rl.Value, a.IsActive" - + " FROM AD_Document_Action_Access a" - + " INNER JOIN AD_Ref_List rl ON (rl.AD_Reference_ID=135 and rl.AD_Ref_List_ID=a.AD_Ref_List_ID)" - + " WHERE a.AD_Client_ID=? AND a.C_DocType_ID=?" // #1,2 - + " AND a.AD_Role_ID=?" - + " AND rl.Value IN (" - + sql_values - + ")"; - pstmt = DB.prepareStatement(sql, get_TrxName()); - pstmt.setInt(idxpar++, clientId); - pstmt.setInt(idxpar++, docTypeId); - pstmt.setInt(idxpar++, role.getAD_Role_ID()); - } - for (Object param : optionParams) - pstmt.setObject(idxpar++, param); - - rs = pstmt.executeQuery(); - while (rs.next()) { - String op = rs.getString(1); - String active=rs.getString(2); - if ("N".equals(active)) { - if (validOptions.contains(op)) { - validOptions.remove(op); - } - } else { - if (!validOptions.contains(op)) { - validOptions.add(op); - } - } - } - - DB.close(rs, pstmt); - } - - validOptions.toArray(options); - } catch (SQLException e) { - log.log(Level.SEVERE, sql, e); - } finally { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - // - int newMaxIndex = validOptions.size(); - return newMaxIndex; - } - - /** List of included roles. Do not access directly */ - private List m_includedRoles = null; - - /** - * Include role permissions - * @param role - * @param seqNo - * @see metas-2009_0021_AP1_G94 - */ - private void includeRole(MRole role, int seqNo) - { - if (this.getAD_Role_ID() == role.getAD_Role_ID()) - { - return; - } - if (this.m_includedRoles == null) - { - m_includedRoles = new ArrayList(); - } - for (MRole r : this.m_includedRoles) - { - if (r.getAD_Role_ID() == role.getAD_Role_ID()) - { - return; - } - } - - if (s_log.isLoggable(Level.INFO)) s_log.info("Include "+role); - - if(role.isActive()){ - this.m_includedRoles.add(role); - role.setParentRole(this); - role.m_includedSeqNo = seqNo; - } - - } - - /** - * - * @return unmodifiable list of included roles - * @see metas-2009_0021_AP1_G94 - */ - public List getIncludedRoles(boolean recursive) - { - if (!recursive) - { - List list = this.m_includedRoles; - if (list == null) - list = new ArrayList(); - return Collections.unmodifiableList(list); - } - else - { - List list = new ArrayList(); - if (m_includedRoles != null) - { - for (MRole role : m_includedRoles) - { - list.add(role); - list.addAll(role.getIncludedRoles(true)); - } - } - return list; - } - } - - /** - * Load all included roles (direct inclusion or from user substitution) - * @param reload - * @see metas-2009_0021_AP1_G94 - */ - private void loadIncludedRoles(boolean reload) - { - loadChildRoles(reload); - loadSubstitutedRoles(reload); - // - if (this.m_parent == null) - { - mergeAccesses(reload); - } - } - - private void mergeAccesses(boolean reload) - { - OrgAccess[] orgAccess = new OrgAccess[]{}; - MTableAccess[] tableAccess = new MTableAccess[]{}; - MColumnAccess[] columnAccess = new MColumnAccess[]{}; - MRecordAccess[] recordAccess = new MRecordAccess[]{}; - MRecordAccess[] recordDependentAccess = new MRecordAccess[]{}; - // - MRole last_role = null; - for (MRole role : getIncludedRoles(false)) - { - boolean override = false; - // - // If roles have same SeqNo, then, the second role will override permissions from first role - if (last_role != null && last_role.m_includedSeqNo >= 0 - && role.m_includedSeqNo >= 0 - && last_role.m_includedSeqNo == role.m_includedSeqNo) - { - override = true; - } - // - role.loadAccess(reload); - role.mergeAccesses(reload); - orgAccess = mergeAccess(orgAccess, role.m_orgAccess, override); - tableAccess = mergeAccess(tableAccess, role.m_tableAccess, override); - columnAccess = mergeAccess(columnAccess, role.m_columnAccess, override); - recordAccess = mergeAccess(recordAccess, role.m_recordAccess, override); - recordDependentAccess = mergeAccess(recordDependentAccess, role.m_recordDependentAccess, override); - // - last_role = role; - } - // - // Merge permissions inside this role - this.m_orgAccess = mergeAccess(this.m_orgAccess, orgAccess, false); - this.m_tableAccess = mergeAccess(this.m_tableAccess, tableAccess, false); - this.m_columnAccess = mergeAccess(this.m_columnAccess, columnAccess, false); - this.m_recordAccess = mergeAccess(this.m_recordAccess, recordAccess, false); - this.m_recordDependentAccess = mergeAccess(this.m_recordDependentAccess, recordDependentAccess, false); - } - - /** - * Load Child Roles - * @param reload - * @see metas-2009_0021_AP1_G94 - */ - private void loadChildRoles(boolean reload) - { - m_includedRoles = null; // reset included roles - final int AD_User_ID = getAD_User_ID(); - if (AD_User_ID < 0) - { - //throw new IllegalStateException("AD_User_ID is not set"); - return ; - } - // - final String whereClause = X_AD_Role_Included.COLUMNNAME_AD_Role_ID+"=?"; - List list = new Query(getCtx(), X_AD_Role_Included.Table_Name, whereClause, get_TrxName()) - .setParameters(new Object[]{getAD_Role_ID()}) - .setOnlyActiveRecords(true) - .setOrderBy( - X_AD_Role_Included.COLUMNNAME_SeqNo - +","+X_AD_Role_Included.COLUMNNAME_Included_Role_ID) - .list(); - for (X_AD_Role_Included includedRole : list) - { - MRole role = MRole.get(getCtx(), includedRole.getIncluded_Role_ID()); - includeRole(role, includedRole.getSeqNo()); - } - } - - /** - * Load substituted roles - * @param reload - * @see metas-2009_0021_AP1_G94 - */ - private void loadSubstitutedRoles(boolean reload) - { - if (this.m_parent != null) - { - // load only if this is logged role (no parent roles) - return; - } - // - final int AD_User_ID = getAD_User_ID(); - if (AD_User_ID < 0) - { - //throw new IllegalStateException("AD_User_ID is not set"); - return; - } - // - final String whereClause = "EXISTS (" - +" SELECT 1 FROM AD_User_Roles ur" - +" INNER JOIN AD_User_Substitute us ON (us.AD_User_ID=ur.AD_User_ID)" - +" WHERE ur.AD_Role_ID=AD_Role.AD_Role_ID AND ur.IsActive='Y' AND us.IsActive='Y'" - +" AND (us.ValidFrom IS NULL OR us.ValidFrom <= SYSDATE)" - +" AND (us.ValidTo IS NULL OR us.ValidTo >= SYSDATE)" - +" AND us.Substitute_ID=?)"; - - List list = new Query(getCtx(), Table_Name, whereClause, get_TrxName()) - .setParameters(new Object[]{AD_User_ID}) - .setClient_ID() - .setOrderBy(COLUMNNAME_AD_Role_ID) - .list(); - for (MRole role : list) - { - includeRole(role, -1); - } - } - - /** Parent Role */ - private MRole m_parent = null; - - /** - * Set parent role. This method is called when this role is included in a parent role. - * @param parent - * @see metas-2009_0021_AP1_G94 - */ - private void setParentRole(MRole parent) - { - this.setAD_User_ID(parent.getAD_User_ID()); - this.m_parent = parent; - } - - private int m_includedSeqNo = -1; - - /** - * Merge permissions access - * @param - * @param array1 - * @param array2 - * @return array of merged values - * @see metas-2009_0021_AP1_G94 - */ - @SuppressWarnings("unchecked") - private static final T[] mergeAccess(T[] array1, T[] array2, boolean override) - { - if (array1 == null) - { - s_log.info("array1 null !!!"); - } - List list = new ArrayList(); - for (T po : array1) - { - list.add(po); - } - for (T o2 : array2) - { - boolean found = false; - for (int i = 0; i < array1.length; i++) - { - final T o1 = array1[i]; - if (o1 instanceof OrgAccess) - { - final OrgAccess oa1 = (OrgAccess)o1; - final OrgAccess oa2 = (OrgAccess)o2; - found = oa1.equals(oa2); - if (found && override) - { - // stronger permissions first - if (!oa2.readOnly) - oa1.readOnly = false; - } - } - else if (o1 instanceof MTableAccess) - { - final MTableAccess ta1 = (MTableAccess)o1; - final MTableAccess ta2 = (MTableAccess)o2; - found = ta1.getAD_Table_ID() == ta2.getAD_Table_ID(); - if (found && override) - { - // stronger permissions first - if (!ta2.isExclude()) - ta1.setIsExclude(false); - } - } - else if (o1 instanceof MColumnAccess) - { - final MColumnAccess ca1 = (MColumnAccess)o1; - final MColumnAccess ca2 = (MColumnAccess)o2; - found = ca1.getAD_Column_ID() == ca2.getAD_Column_ID(); - if (found && override) - { - // stronger permissions first - if (!ca2.isReadOnly()) - ca1.setIsReadOnly(false); - if (!ca2.isExclude()) - ca1.setIsExclude(false); - } - } - else if (o1 instanceof MRecordAccess) - { - final MRecordAccess ra1 = (MRecordAccess)o1; - final MRecordAccess ra2 = (MRecordAccess)o2; - found = ra1.getAD_Table_ID() == ra2.getAD_Table_ID() - && ra1.getRecord_ID() == ra2.getRecord_ID(); - if (found && override) - { - // stronger permissions first - if(!ra2.isReadOnly()) - ra1.setIsReadOnly(false); - if (!ra2.isDependentEntities()) - ra1.setIsDependentEntities(false); - if (!ra2.isExclude()) - ra1.setIsExclude(false); - } - } - else - { - throw new AdempiereException("Not supported objects - "+o1+", "+o2); - } - // - if (found) - { - break; - } - } // end for array1 - if (!found) - { - //s_log.info("add "+o2); - list.add(o2); - } - } - T[] arr = (T[]) Array.newInstance(array1.getClass().getComponentType(), list.size()); - return list.toArray(arr); - } - - private static final HashMap mergeAccess( - HashMap map1, HashMap map2, - boolean override) - { - final HashMap map = new HashMap(); - if (map1 != null) - { - map.putAll(map1); - } - // - for (final Entry e : map2.entrySet()) - { - final Integer key = e.getKey(); - final Boolean b2 = e.getValue(); - if (b2 == null) - { - continue; - } - final Boolean b1 = map.get(key); - if (b1 == null) - { - map.put(key, b2); - } - else - { - if (override && b2 == true && b1 == false) - { - map.put(key, b2); - } - } - } - // - return map; - } - - private void mergeIncludedAccess(String varname) - { - HashMap includedAccess = new HashMap(); - MRole last_role = null; - for (MRole role : getIncludedRoles(false)) - { - boolean override = false; - // - // If roles have same SeqNo, then, the second role will override permissions from first role - if (last_role != null && last_role.m_includedSeqNo >= 0 - && role.m_includedSeqNo >= 0 - && last_role.m_includedSeqNo == role.m_includedSeqNo) - { - override = true; - } - includedAccess = mergeAccess(includedAccess, role.getAccessMap(varname), override); - last_role = role; - } - setAccessMap(varname, mergeAccess(getAccessMap(varname), includedAccess, false)); - } - - private HashMap getAccessMap(String varname) - { - if ("m_windowAccess".equals(varname)) - { - getWindowAccess(-1); - return m_windowAccess; - } - else if ("m_processAccess".equals(varname)) - { - getProcessAccess(-1); - return m_processAccess; - } - else if ("m_taskAccess".equals(varname)) - { - getTaskAccess(-1); - return m_taskAccess; - } - else if ("m_workflowAccess".equals(varname)) - { - getWorkflowAccess(-1); - return m_workflowAccess; - } - else if ("m_formAccess".equals(varname)) - { - getFormAccess(-1); - return m_formAccess; - } - else if ("m_infoAccess".equals(varname)) - { - getInfoAccess(-1); - return m_infoAccess; - } - else - { - throw new IllegalArgumentException("varname not supported - "+varname); - } - } - private void setAccessMap(String varname, HashMap map) - { - if ("m_windowAccess".equals(varname)) - { - m_windowAccess = map; - } - else if ("m_processAccess".equals(varname)) - { - m_processAccess = map; - } - else if ("m_taskAccess".equals(varname)) - { - m_taskAccess = map; - } - else if ("m_workflowAccess".equals(varname)) - { - m_workflowAccess = map; - } - else if ("m_formAccess".equals(varname)) - { - m_formAccess = map; - } - else if ("m_infoAccess".equals(varname)) - { - m_infoAccess = map; - } - else - { - throw new IllegalArgumentException("varname not supported - "+varname); - } - } - - /** - * Get Role Where Clause. - * It will look something like myalias.AD_Role_ID IN (?, ?, ?). - * @param roleColumnSQL role columnname or role column SQL (e.g. myalias.AD_Role_ID) - * @param params a list where the method will put SQL parameters. - * If null, this method will generate a not parametrized query - * @return role SQL where clause - */ - public String getIncludedRolesWhereClause(String roleColumnSQL, List params) - { - StringBuilder whereClause = new StringBuilder(); - if (params != null) - { - whereClause.append("?"); - params.add(getAD_Role_ID()); - } - else - { - whereClause.append(getAD_Role_ID()); - } - // - for (MRole role : getIncludedRoles(true)) - { - if (params != null) - { - whereClause.append(",?"); - params.add(role.getAD_Role_ID()); - } - else - { - whereClause.append(",").append(role.getAD_Role_ID()); - } - } - // - whereClause.insert(0, roleColumnSQL+" IN (").append(")"); - return whereClause.toString(); - } - - public synchronized Boolean getInfoAccess(int AD_InfoWindow_ID) { - if (m_infoAccess == null) - { - m_infoAccess = new HashMap(20); - // first get the info access from the included and substitute roles - mergeIncludedAccess("m_infoAccess"); - // and now get the info access directly from this role - String ASPFilter = ""; - /* - MClient client = MClient.get(getCtx(), getAD_Client_ID()); - if (client.isUseASP()) - ASPFilter = - " AND ( AD_InfoWindow_ID IN ( " - // Just ASP subscribed forms for client " - + " SELECT f.AD_InfoWindow_ID " - + " FROM ASP_InfoWindow f, ASP_Level l, ASP_ClientLevel cl " - + " WHERE f.ASP_Level_ID = l.ASP_Level_ID " - + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() - + " AND cl.ASP_Level_ID = l.ASP_Level_ID " - + " AND f.IsActive = 'Y' " - + " AND l.IsActive = 'Y' " - + " AND cl.IsActive = 'Y' " - + " AND f.ASP_Status = 'S') " // Show - + " OR AD_InfoWindow_ID IN ( " - // + show ASP exceptions for client - + " SELECT AD_InfoWindow_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_InfoWindow_ID IS NOT NULL " - + " AND ce.ASP_Status = 'S') " // Show - + " ) " - + " AND AD_InfoWindow_ID NOT IN ( " - // minus hide ASP exceptions for client - + " SELECT AD_InfoWindow_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_InfoWindow_ID IS NOT NULL " - + " AND ce.ASP_Status = 'H')"; // Hide - */ - String sql = "SELECT AD_InfoWindow_ID, IsActive FROM AD_InfoWindow_Access WHERE AD_Role_ID=?" + ASPFilter; - PreparedStatement pstmt = null; - ResultSet rs = null; - HashMap directAccess = new HashMap(100); - try - { - pstmt = DB.prepareStatement(sql, get_TrxName()); - pstmt.setInt(1, getAD_Role_ID()); - rs = pstmt.executeQuery(); - while (rs.next()) { - Integer infoId = Integer.valueOf(rs.getInt(1)); - if ("N".equals(rs.getString(2))) { - // inactive info on direct access - if (m_infoAccess.containsKey(infoId)) { - m_infoAccess.remove(infoId); - } - } else { - directAccess.put(infoId, Boolean.TRUE); - } - } - } - catch (Exception e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - } - setAccessMap("m_infoAccess", mergeAccess(getAccessMap("m_infoAccess"), directAccess, true)); - } // reload - Boolean retValue = m_infoAccess.get(AD_InfoWindow_ID); - return retValue; - } - - private Boolean m_canAccess_Info_Product = null; - - public boolean canAccess_Info_Product() { - if (m_canAccess_Info_Product == null) { - String sql = "" - + "SELECT COUNT(*) " - + "FROM AD_InfoWindow iw " - + " JOIN AD_InfoWindow_Access iwa " - + " ON ( iwa.AD_InfoWindow_ID = iw.AD_InfoWindow_ID ) " - + "WHERE AD_Table_ID = ? " - + " AND iw.IsActive = 'Y' " - + " AND iwa.IsActive = 'Y' " - + " AND (iwa.AD_Role_ID = ? OR iwa.AD_Role_ID IN" - + " (SELECT ri.Included_Role_ID FROM AD_Role_Included ri WHERE ri.IsActive='Y' AND ri.AD_Role_ID=?))"; - int cnt = DB.getSQLValueEx(get_TrxName(), sql, I_M_Product.Table_ID, getAD_Role_ID(), getAD_Role_ID()); - m_canAccess_Info_Product = Boolean.valueOf(cnt > 0); - - // Verify if is excluded in the specific role (it can be allowed in included role and inactive in specific role) - if (m_canAccess_Info_Product) { - String sqlInactive = "" - + "SELECT COUNT(*) " - + "FROM AD_InfoWindow iw " - + " JOIN AD_InfoWindow_Access iwa " - + " ON ( iwa.AD_InfoWindow_ID = iw.AD_InfoWindow_ID ) " - + "WHERE AD_Table_ID = ? " - + " AND iw.IsActive = 'Y' " - + " AND iwa.IsActive = 'N' " - + " AND iwa.AD_Role_ID = ?"; - int cntInactive = DB.getSQLValueEx(get_TrxName(), sqlInactive, I_M_Product.Table_ID, getAD_Role_ID()); - if (cntInactive > 0) - m_canAccess_Info_Product = Boolean.FALSE; - } - } - return m_canAccess_Info_Product.booleanValue(); - } - + /** + * Checks the access rights of the given role/client for the given document actions. + * @param clientId + * @param docTypeId + * @param options + * @param maxIndex + * @return number of valid actions in the String[] options + * @see metas-2009_0021_AP1_G94 + */ + public int checkActionAccess(int clientId, int docTypeId, String[] options, + int maxIndex) { + if (maxIndex <= 0) + return maxIndex; + // + final ArrayList validOptions = new ArrayList(); + final List optionParams = new ArrayList(); + // + final StringBuffer sql_values = new StringBuffer(); + for (int i = 0; i < maxIndex; i++) { + if (sql_values.length() > 0) + sql_values.append(","); + sql_values.append("?"); + optionParams.add(options[i]); + } + // + PreparedStatement pstmt = null; + ResultSet rs = null; + + List roles = getIncludedRoles(true); + roles.add(this); // add current role to the list of included roles + String sql = null; + try { + for (MRole role : roles) { + int idxpar = 1; + if (role.getAD_Client_ID() == 0 && role.isMasterRole()) { + // master role on system - check options based on docbasetype and docsubtypeso + MDocType doc = new MDocType(getCtx(), docTypeId, get_TrxName()); + + sql = "SELECT DISTINCT rl.Value, a.IsActive" + + " FROM AD_Document_Action_Access a" + + " INNER JOIN AD_Ref_List rl ON (rl.AD_Reference_ID=135 and rl.AD_Ref_List_ID=a.AD_Ref_List_ID)" + + " INNER JOIN AD_Role ro ON (a.AD_Role_ID=ro.AD_Role_ID)" + + " INNER JOIN C_Doctype ty ON (a.C_Doctype_ID=ty.C_Doctype_ID)" + + " WHERE ro.AD_Role_ID=?" + + " AND ty.DocBaseType=?" + + (MDocType.DOCBASETYPE_SalesOrder.equals(doc.getDocBaseType()) ? " AND ty.DocSubTypeSO=?" : "") + + (MDocType.DOCBASETYPE_PurchaseOrder.equals(doc.getDocBaseType()) && doc.getDocSubTypeSO() != null ? " AND ty.DocSubTypeSO=?" : "") + + (MDocType.DOCBASETYPE_MaterialPhysicalInventory.equals(doc.getDocBaseType()) ? " AND ty.DocSubTypeInv=?" : "") + + " AND rl.Value IN (" + + sql_values + + ")"; + + pstmt = DB.prepareStatement(sql, get_TrxName()); + pstmt.setInt(idxpar++, role.getAD_Role_ID()); + pstmt.setString(idxpar++, doc.getDocBaseType()); + if (MDocType.DOCBASETYPE_SalesOrder.equals(doc.getDocBaseType())) + pstmt.setString(idxpar++, doc.getDocSubTypeSO()); + else if (MDocType.DOCBASETYPE_PurchaseOrder.equals(doc.getDocBaseType()) && doc.getDocSubTypeSO() != null) + pstmt.setString(idxpar++, doc.getDocSubTypeSO()); + else if (MDocType.DOCBASETYPE_MaterialPhysicalInventory.equals(doc.getDocBaseType())) + pstmt.setString(idxpar++, doc.getDocSubTypeInv()); + } else { + // master role on tenant - check options based on doctypeid + sql = "SELECT DISTINCT rl.Value, a.IsActive" + + " FROM AD_Document_Action_Access a" + + " INNER JOIN AD_Ref_List rl ON (rl.AD_Reference_ID=135 and rl.AD_Ref_List_ID=a.AD_Ref_List_ID)" + + " WHERE a.AD_Client_ID=? AND a.C_DocType_ID=?" // #1,2 + + " AND a.AD_Role_ID=?" + + " AND rl.Value IN (" + + sql_values + + ")"; + pstmt = DB.prepareStatement(sql, get_TrxName()); + pstmt.setInt(idxpar++, clientId); + pstmt.setInt(idxpar++, docTypeId); + pstmt.setInt(idxpar++, role.getAD_Role_ID()); + } + for (Object param : optionParams) + pstmt.setObject(idxpar++, param); + + rs = pstmt.executeQuery(); + while (rs.next()) { + String op = rs.getString(1); + String active=rs.getString(2); + if ("N".equals(active)) { + if (validOptions.contains(op)) { + validOptions.remove(op); + } + } else { + if (!validOptions.contains(op)) { + validOptions.add(op); + } + } + } + + DB.close(rs, pstmt); + } + + validOptions.toArray(options); + } catch (SQLException e) { + log.log(Level.SEVERE, sql, e); + } finally { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + // + int newMaxIndex = validOptions.size(); + return newMaxIndex; + } + + /** List of included roles. Do not access directly */ + private List m_includedRoles = null; + + /** + * Include role permissions + * @param role + * @param seqNo + * @see metas-2009_0021_AP1_G94 + */ + private void includeRole(MRole role, int seqNo) + { + if (this.getAD_Role_ID() == role.getAD_Role_ID()) + { + return; + } + if (this.m_includedRoles == null) + { + m_includedRoles = new ArrayList(); + } + for (MRole r : this.m_includedRoles) + { + if (r.getAD_Role_ID() == role.getAD_Role_ID()) + { + return; + } + } + + if (s_log.isLoggable(Level.INFO)) s_log.info("Include "+role); + + if(role.isActive()){ + this.m_includedRoles.add(role); + role.setParentRole(this); + role.m_includedSeqNo = seqNo; + } + + } + + /** + * + * @return unmodifiable list of included roles + * @see metas-2009_0021_AP1_G94 + */ + public List getIncludedRoles(boolean recursive) + { + if (!recursive) + { + List list = this.m_includedRoles; + if (list == null) + list = new ArrayList(); + return Collections.unmodifiableList(list); + } + else + { + List list = new ArrayList(); + if (m_includedRoles != null) + { + for (MRole role : m_includedRoles) + { + list.add(role); + list.addAll(role.getIncludedRoles(true)); + } + } + return list; + } + } + + /** + * Load all included roles (direct inclusion or from user substitution) + * @param reload + * @see metas-2009_0021_AP1_G94 + */ + private void loadIncludedRoles(boolean reload) + { + loadChildRoles(reload); + loadSubstitutedRoles(reload); + // + if (this.m_parent == null) + { + mergeAccesses(reload); + } + } + + private void mergeAccesses(boolean reload) + { + OrgAccess[] orgAccess = new OrgAccess[]{}; + MTableAccess[] tableAccess = new MTableAccess[]{}; + MColumnAccess[] columnAccess = new MColumnAccess[]{}; + MRecordAccess[] recordAccess = new MRecordAccess[]{}; + MRecordAccess[] recordDependentAccess = new MRecordAccess[]{}; + // + MRole last_role = null; + for (MRole role : getIncludedRoles(false)) + { + boolean override = false; + // + // If roles have same SeqNo, then, the second role will override permissions from first role + if (last_role != null && last_role.m_includedSeqNo >= 0 + && role.m_includedSeqNo >= 0 + && last_role.m_includedSeqNo == role.m_includedSeqNo) + { + override = true; + } + // + role.loadAccess(reload); + role.mergeAccesses(reload); + orgAccess = mergeAccess(orgAccess, role.m_orgAccess, override); + tableAccess = mergeAccess(tableAccess, role.m_tableAccess, override); + columnAccess = mergeAccess(columnAccess, role.m_columnAccess, override); + recordAccess = mergeAccess(recordAccess, role.m_recordAccess, override); + recordDependentAccess = mergeAccess(recordDependentAccess, role.m_recordDependentAccess, override); + // + last_role = role; + } + // + // Merge permissions inside this role + this.m_orgAccess = mergeAccess(this.m_orgAccess, orgAccess, false); + this.m_tableAccess = mergeAccess(this.m_tableAccess, tableAccess, false); + this.m_columnAccess = mergeAccess(this.m_columnAccess, columnAccess, false); + this.m_recordAccess = mergeAccess(this.m_recordAccess, recordAccess, false); + this.m_recordDependentAccess = mergeAccess(this.m_recordDependentAccess, recordDependentAccess, false); + } + + /** + * Load Child Roles + * @param reload + * @see metas-2009_0021_AP1_G94 + */ + private void loadChildRoles(boolean reload) + { + m_includedRoles = null; // reset included roles + final int AD_User_ID = getAD_User_ID(); + if (AD_User_ID < 0) + { + //throw new IllegalStateException("AD_User_ID is not set"); + return ; + } + // + final String whereClause = X_AD_Role_Included.COLUMNNAME_AD_Role_ID+"=?"; + List list = new Query(getCtx(), X_AD_Role_Included.Table_Name, whereClause, get_TrxName()) + .setParameters(new Object[]{getAD_Role_ID()}) + .setOnlyActiveRecords(true) + .setOrderBy( + X_AD_Role_Included.COLUMNNAME_SeqNo + +","+X_AD_Role_Included.COLUMNNAME_Included_Role_ID) + .list(); + for (X_AD_Role_Included includedRole : list) + { + MRole role = MRole.get(getCtx(), includedRole.getIncluded_Role_ID()); + includeRole(role, includedRole.getSeqNo()); + } + } + + /** + * Load substituted roles + * @param reload + * @see metas-2009_0021_AP1_G94 + */ + private void loadSubstitutedRoles(boolean reload) + { + if (this.m_parent != null) + { + // load only if this is logged role (no parent roles) + return; + } + // + final int AD_User_ID = getAD_User_ID(); + if (AD_User_ID < 0) + { + //throw new IllegalStateException("AD_User_ID is not set"); + return; + } + // + final String whereClause = "EXISTS (" + +" SELECT 1 FROM AD_User_Roles ur" + +" INNER JOIN AD_User_Substitute us ON (us.AD_User_ID=ur.AD_User_ID)" + +" WHERE ur.AD_Role_ID=AD_Role.AD_Role_ID AND ur.IsActive='Y' AND us.IsActive='Y'" + +" AND (us.ValidFrom IS NULL OR us.ValidFrom <= SYSDATE)" + +" AND (us.ValidTo IS NULL OR us.ValidTo >= SYSDATE)" + +" AND us.Substitute_ID=?)"; + + List list = new Query(getCtx(), Table_Name, whereClause, get_TrxName()) + .setParameters(new Object[]{AD_User_ID}) + .setClient_ID() + .setOrderBy(COLUMNNAME_AD_Role_ID) + .list(); + for (MRole role : list) + { + includeRole(role, -1); + } + } + + /** Parent Role */ + private MRole m_parent = null; + + /** + * Set parent role. This method is called when this role is included in a parent role. + * @param parent + * @see metas-2009_0021_AP1_G94 + */ + private void setParentRole(MRole parent) + { + this.setAD_User_ID(parent.getAD_User_ID()); + this.m_parent = parent; + } + + private int m_includedSeqNo = -1; + + /** + * Merge permissions access + * @param + * @param array1 + * @param array2 + * @return array of merged values + * @see metas-2009_0021_AP1_G94 + */ + @SuppressWarnings("unchecked") + private static final T[] mergeAccess(T[] array1, T[] array2, boolean override) + { + if (array1 == null) + { + s_log.info("array1 null !!!"); + } + List list = new ArrayList(); + for (T po : array1) + { + list.add(po); + } + for (T o2 : array2) + { + boolean found = false; + for (int i = 0; i < array1.length; i++) + { + final T o1 = array1[i]; + if (o1 instanceof OrgAccess) + { + final OrgAccess oa1 = (OrgAccess)o1; + final OrgAccess oa2 = (OrgAccess)o2; + found = oa1.equals(oa2); + if (found && override) + { + // stronger permissions first + if (!oa2.readOnly) + oa1.readOnly = false; + } + } + else if (o1 instanceof MTableAccess) + { + final MTableAccess ta1 = (MTableAccess)o1; + final MTableAccess ta2 = (MTableAccess)o2; + found = ta1.getAD_Table_ID() == ta2.getAD_Table_ID(); + if (found && override) + { + // stronger permissions first + if (!ta2.isExclude()) + ta1.setIsExclude(false); + } + } + else if (o1 instanceof MColumnAccess) + { + final MColumnAccess ca1 = (MColumnAccess)o1; + final MColumnAccess ca2 = (MColumnAccess)o2; + found = ca1.getAD_Column_ID() == ca2.getAD_Column_ID(); + if (found && override) + { + // stronger permissions first + if (!ca2.isReadOnly()) + ca1.setIsReadOnly(false); + if (!ca2.isExclude()) + ca1.setIsExclude(false); + } + } + else if (o1 instanceof MRecordAccess) + { + final MRecordAccess ra1 = (MRecordAccess)o1; + final MRecordAccess ra2 = (MRecordAccess)o2; + found = ra1.getAD_Table_ID() == ra2.getAD_Table_ID() + && ra1.getRecord_ID() == ra2.getRecord_ID(); + if (found && override) + { + // stronger permissions first + if(!ra2.isReadOnly()) + ra1.setIsReadOnly(false); + if (!ra2.isDependentEntities()) + ra1.setIsDependentEntities(false); + if (!ra2.isExclude()) + ra1.setIsExclude(false); + } + } + else + { + throw new AdempiereException("Not supported objects - "+o1+", "+o2); + } + // + if (found) + { + break; + } + } // end for array1 + if (!found) + { + //s_log.info("add "+o2); + list.add(o2); + } + } + T[] arr = (T[]) Array.newInstance(array1.getClass().getComponentType(), list.size()); + return list.toArray(arr); + } + + private static final HashMap mergeAccess( + HashMap map1, HashMap map2, + boolean override) + { + final HashMap map = new HashMap(); + if (map1 != null) + { + map.putAll(map1); + } + // + for (final Entry e : map2.entrySet()) + { + final Integer key = e.getKey(); + final Boolean b2 = e.getValue(); + if (b2 == null) + { + continue; + } + final Boolean b1 = map.get(key); + if (b1 == null) + { + map.put(key, b2); + } + else + { + if (override && b2 == true && b1 == false) + { + map.put(key, b2); + } + } + } + // + return map; + } + + private void mergeIncludedAccess(String varname) + { + HashMap includedAccess = new HashMap(); + MRole last_role = null; + for (MRole role : getIncludedRoles(false)) + { + boolean override = false; + // + // If roles have same SeqNo, then, the second role will override permissions from first role + if (last_role != null && last_role.m_includedSeqNo >= 0 + && role.m_includedSeqNo >= 0 + && last_role.m_includedSeqNo == role.m_includedSeqNo) + { + override = true; + } + includedAccess = mergeAccess(includedAccess, role.getAccessMap(varname), override); + last_role = role; + } + setAccessMap(varname, mergeAccess(getAccessMap(varname), includedAccess, false)); + } + + private HashMap getAccessMap(String varname) + { + if ("m_windowAccess".equals(varname)) + { + getWindowAccess(-1); + return m_windowAccess; + } + else if ("m_processAccess".equals(varname)) + { + getProcessAccess(-1); + return m_processAccess; + } + else if ("m_taskAccess".equals(varname)) + { + getTaskAccess(-1); + return m_taskAccess; + } + else if ("m_workflowAccess".equals(varname)) + { + getWorkflowAccess(-1); + return m_workflowAccess; + } + else if ("m_formAccess".equals(varname)) + { + getFormAccess(-1); + return m_formAccess; + } + else if ("m_infoAccess".equals(varname)) + { + getInfoAccess(-1); + return m_infoAccess; + } + else + { + throw new IllegalArgumentException("varname not supported - "+varname); + } + } + private void setAccessMap(String varname, HashMap map) + { + if ("m_windowAccess".equals(varname)) + { + m_windowAccess = map; + } + else if ("m_processAccess".equals(varname)) + { + m_processAccess = map; + } + else if ("m_taskAccess".equals(varname)) + { + m_taskAccess = map; + } + else if ("m_workflowAccess".equals(varname)) + { + m_workflowAccess = map; + } + else if ("m_formAccess".equals(varname)) + { + m_formAccess = map; + } + else if ("m_infoAccess".equals(varname)) + { + m_infoAccess = map; + } + else + { + throw new IllegalArgumentException("varname not supported - "+varname); + } + } + + /** + * Get Role Where Clause. + * It will look something like myalias.AD_Role_ID IN (?, ?, ?). + * @param roleColumnSQL role columnname or role column SQL (e.g. myalias.AD_Role_ID) + * @param params a list where the method will put SQL parameters. + * If null, this method will generate a not parametrized query + * @return role SQL where clause + */ + public String getIncludedRolesWhereClause(String roleColumnSQL, List params) + { + StringBuilder whereClause = new StringBuilder(); + if (params != null) + { + whereClause.append("?"); + params.add(getAD_Role_ID()); + } + else + { + whereClause.append(getAD_Role_ID()); + } + // + for (MRole role : getIncludedRoles(true)) + { + if (params != null) + { + whereClause.append(",?"); + params.add(role.getAD_Role_ID()); + } + else + { + whereClause.append(",").append(role.getAD_Role_ID()); + } + } + // + whereClause.insert(0, roleColumnSQL+" IN (").append(")"); + return whereClause.toString(); + } + + public synchronized Boolean getInfoAccess(int AD_InfoWindow_ID) { + if (m_infoAccess == null) + { + m_infoAccess = new HashMap(20); + // first get the info access from the included and substitute roles + mergeIncludedAccess("m_infoAccess"); + // and now get the info access directly from this role + String ASPFilter = ""; + /* + MClient client = MClient.get(getCtx(), getAD_Client_ID()); + if (client.isUseASP()) + ASPFilter = + " AND ( AD_InfoWindow_ID IN ( " + // Just ASP subscribed forms for client " + + " SELECT f.AD_InfoWindow_ID " + + " FROM ASP_InfoWindow f, ASP_Level l, ASP_ClientLevel cl " + + " WHERE f.ASP_Level_ID = l.ASP_Level_ID " + + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() + + " AND cl.ASP_Level_ID = l.ASP_Level_ID " + + " AND f.IsActive = 'Y' " + + " AND l.IsActive = 'Y' " + + " AND cl.IsActive = 'Y' " + + " AND f.ASP_Status = 'S') " // Show + + " OR AD_InfoWindow_ID IN ( " + // + show ASP exceptions for client + + " SELECT AD_InfoWindow_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_InfoWindow_ID IS NOT NULL " + + " AND ce.ASP_Status = 'S') " // Show + + " ) " + + " AND AD_InfoWindow_ID NOT IN ( " + // minus hide ASP exceptions for client + + " SELECT AD_InfoWindow_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_InfoWindow_ID IS NOT NULL " + + " AND ce.ASP_Status = 'H')"; // Hide + */ + String sql = "SELECT AD_InfoWindow_ID, IsActive FROM AD_InfoWindow_Access WHERE AD_Role_ID=?" + ASPFilter; + PreparedStatement pstmt = null; + ResultSet rs = null; + HashMap directAccess = new HashMap(100); + try + { + pstmt = DB.prepareStatement(sql, get_TrxName()); + pstmt.setInt(1, getAD_Role_ID()); + rs = pstmt.executeQuery(); + while (rs.next()) { + Integer infoId = Integer.valueOf(rs.getInt(1)); + if ("N".equals(rs.getString(2))) { + // inactive info on direct access + if (m_infoAccess.containsKey(infoId)) { + m_infoAccess.remove(infoId); + } + } else { + directAccess.put(infoId, Boolean.TRUE); + } + } + } + catch (Exception e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + } + setAccessMap("m_infoAccess", mergeAccess(getAccessMap("m_infoAccess"), directAccess, true)); + } // reload + Boolean retValue = m_infoAccess.get(AD_InfoWindow_ID); + return retValue; + } + + private Boolean m_canAccess_Info_Product = null; + + public boolean canAccess_Info_Product() { + if (m_canAccess_Info_Product == null) { + String sql = "" + + "SELECT COUNT(*) " + + "FROM AD_InfoWindow iw " + + " JOIN AD_InfoWindow_Access iwa " + + " ON ( iwa.AD_InfoWindow_ID = iw.AD_InfoWindow_ID ) " + + "WHERE AD_Table_ID = ? " + + " AND iw.IsActive = 'Y' " + + " AND iwa.IsActive = 'Y' " + + " AND (iwa.AD_Role_ID = ? OR iwa.AD_Role_ID IN" + + " (SELECT ri.Included_Role_ID FROM AD_Role_Included ri WHERE ri.IsActive='Y' AND ri.AD_Role_ID=?))"; + int cnt = DB.getSQLValueEx(get_TrxName(), sql, I_M_Product.Table_ID, getAD_Role_ID(), getAD_Role_ID()); + m_canAccess_Info_Product = Boolean.valueOf(cnt > 0); + + // Verify if is excluded in the specific role (it can be allowed in included role and inactive in specific role) + if (m_canAccess_Info_Product) { + String sqlInactive = "" + + "SELECT COUNT(*) " + + "FROM AD_InfoWindow iw " + + " JOIN AD_InfoWindow_Access iwa " + + " ON ( iwa.AD_InfoWindow_ID = iw.AD_InfoWindow_ID ) " + + "WHERE AD_Table_ID = ? " + + " AND iw.IsActive = 'Y' " + + " AND iwa.IsActive = 'N' " + + " AND iwa.AD_Role_ID = ?"; + int cntInactive = DB.getSQLValueEx(get_TrxName(), sqlInactive, I_M_Product.Table_ID, getAD_Role_ID()); + if (cntInactive > 0) + m_canAccess_Info_Product = Boolean.FALSE; + } + } + return m_canAccess_Info_Product.booleanValue(); + } + } // MRole diff --git a/org.adempiere.base/src/org/compiere/model/MSchedulerLog.java b/org.adempiere.base/src/org/compiere/model/MSchedulerLog.java index fa7b852d27..fc0577c3dc 100644 --- a/org.adempiere.base/src/org/compiere/model/MSchedulerLog.java +++ b/org.adempiere.base/src/org/compiere/model/MSchedulerLog.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,38 +16,38 @@ *****************************************************************************/ package org.compiere.model; -import java.sql.ResultSet; -import java.util.Properties; +import java.sql.ResultSet; +import java.util.Properties; /** * Scheduler Log * * @author Jorg Janke - * @version $Id: MSchedulerLog.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $ - */ -public class MSchedulerLog extends X_AD_SchedulerLog - implements AdempiereProcessorLog -{ - /** - * - */ - private static final long serialVersionUID = -8105976307507562851L; - - /** - * Standard Constructor + * @version $Id: MSchedulerLog.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $ + */ +public class MSchedulerLog extends X_AD_SchedulerLog + implements AdempiereProcessorLog +{ + /** + * + */ + private static final long serialVersionUID = -8105976307507562851L; + + /** + * Standard Constructor * @param ctx context * @param AD_SchedulerLog_ID id * @param trxName transaction */ - public MSchedulerLog (Properties ctx, int AD_SchedulerLog_ID, String trxName) - { - super (ctx, AD_SchedulerLog_ID, trxName); - if (AD_SchedulerLog_ID == 0) - setIsError(false); - } // MSchedulerLog - - /** + public MSchedulerLog (Properties ctx, int AD_SchedulerLog_ID, String trxName) + { + super (ctx, AD_SchedulerLog_ID, trxName); + if (AD_SchedulerLog_ID == 0) + setIsError(false); + } // MSchedulerLog + + /** * Load Constructor * @param ctx context * @param rs result set diff --git a/org.adempiere.base/src/org/compiere/model/MSequence.java b/org.adempiere.base/src/org/compiere/model/MSequence.java index 446fde29d3..9b61346dd7 100644 --- a/org.adempiere.base/src/org/compiere/model/MSequence.java +++ b/org.adempiere.base/src/org/compiere/model/MSequence.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,32 +16,32 @@ *****************************************************************************/ package org.compiere.model; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; - -import org.adempiere.exceptions.AdempiereException; -import org.adempiere.exceptions.DBException; -import org.compiere.db.CConnection; -import org.compiere.util.CLogMgt; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.Ini; -import org.compiere.util.Trx; -import org.compiere.util.Util; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.Properties; +import java.util.Vector; +import java.util.logging.Level; + +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.exceptions.DBException; +import org.compiere.db.CConnection; +import org.compiere.util.CLogMgt; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Ini; +import org.compiere.util.Trx; +import org.compiere.util.Util; /** * Sequence Model. @@ -49,560 +49,560 @@ import org.compiere.util.Util; * @author Jorg Janke * @version $Id: MSequence.java,v 1.3 2006/07/30 00:58:04 jjanke Exp $ */ -public class MSequence extends X_AD_Sequence -{ - /** - * - */ - private static final long serialVersionUID = 7331047665037991960L; - - /** Log Level for Next ID Call */ - private static final Level LOGLEVEL = Level.ALL; - - private static final int QUERY_TIME_OUT = 30; - - private static final String NoYearNorMonth = "-"; - - /** - * @deprecated please use DB.getNextID (int, String, String) - */ - public static int getNextID (int AD_Client_ID, String TableName) - { - return getNextID(AD_Client_ID, TableName, null); - } - - /** +public class MSequence extends X_AD_Sequence +{ + /** + * + */ + private static final long serialVersionUID = 7331047665037991960L; + + /** Log Level for Next ID Call */ + private static final Level LOGLEVEL = Level.ALL; + + private static final int QUERY_TIME_OUT = 30; + + private static final String NoYearNorMonth = "-"; + + /** + * @deprecated please use DB.getNextID (int, String, String) + */ + public static int getNextID (int AD_Client_ID, String TableName) + { + return getNextID(AD_Client_ID, TableName, null); + } + + /** * * Get next number for Key column = 0 is Error. * @param AD_Client_ID client * @param TableName table name * @param trxName deprecated (NOT USED!!) * @return next no or (-1=not found, -2=error) - * - * WARNING!! This method doesn't take into account the native sequence setting, it's just to be called from DB.getNextID() - * - * @deprecated please use DB.getNextID (int, String, String) + * + * WARNING!! This method doesn't take into account the native sequence setting, it's just to be called from DB.getNextID() + * + * @deprecated please use DB.getNextID (int, String, String) */ public static int getNextID (int AD_Client_ID, String TableName, String trxName) { if (TableName == null || TableName.length() == 0) - throw new IllegalArgumentException("TableName missing"); - - int retValue = -1; - - // Check AdempiereSys - boolean adempiereSys = false; - if (Ini.isClient()) - { - adempiereSys = Ini.isPropertyBool(Ini.P_ADEMPIERESYS); - } - else - { - String sysProperty = Env.getCtx().getProperty("AdempiereSys", "N"); - adempiereSys = "y".equalsIgnoreCase(sysProperty) || "true".equalsIgnoreCase(sysProperty); - } - - if (adempiereSys && AD_Client_ID > 11) - adempiereSys = false; - // - if (CLogMgt.isLevel(LOGLEVEL)) - s_log.log(LOGLEVEL, TableName + " - AdempiereSys=" + adempiereSys + " [" + trxName + "]"); - //begin vpj-cd e-evolution 09/02/2005 PostgreSQL - String selectSQL = null; - if (DB.isOracle() == false) - { - selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, AD_Sequence_ID " - + "FROM AD_Sequence " - + "WHERE Name=?" - + " AND IsActive='Y' AND IsTableID='Y' AND IsAutoSequence='Y' " - + " FOR UPDATE OF AD_Sequence "; - } - else - { - selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, AD_Sequence_ID " - + "FROM AD_Sequence " - + "WHERE Name=?" - + " AND IsActive='Y' AND IsTableID='Y' AND IsAutoSequence='Y' "; - - if(adempiereSys) - selectSQL += " FOR UPDATE OF CurrentNextSys"; - else - selectSQL += " FOR UPDATE OF CurrentNext"; - } - if (!DB.isOracle() && !DB.isPostgreSQL()) - selectSQL = DB.getDatabase().convertStatement(selectSQL); - - Connection conn = null; - PreparedStatement pstmt = null; - ResultSet rs = null; - for (int i = 0; i < 3; i++) - { - try + throw new IllegalArgumentException("TableName missing"); + + int retValue = -1; + + // Check AdempiereSys + boolean adempiereSys = false; + if (Ini.isClient()) + { + adempiereSys = Ini.isPropertyBool(Ini.P_ADEMPIERESYS); + } + else + { + String sysProperty = Env.getCtx().getProperty("AdempiereSys", "N"); + adempiereSys = "y".equalsIgnoreCase(sysProperty) || "true".equalsIgnoreCase(sysProperty); + } + + if (adempiereSys && AD_Client_ID > 11) + adempiereSys = false; + // + if (CLogMgt.isLevel(LOGLEVEL)) + s_log.log(LOGLEVEL, TableName + " - AdempiereSys=" + adempiereSys + " [" + trxName + "]"); + //begin vpj-cd e-evolution 09/02/2005 PostgreSQL + String selectSQL = null; + if (DB.isOracle() == false) + { + selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, AD_Sequence_ID " + + "FROM AD_Sequence " + + "WHERE Name=?" + + " AND IsActive='Y' AND IsTableID='Y' AND IsAutoSequence='Y' " + + " FOR UPDATE OF AD_Sequence "; + } + else + { + selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, AD_Sequence_ID " + + "FROM AD_Sequence " + + "WHERE Name=?" + + " AND IsActive='Y' AND IsTableID='Y' AND IsAutoSequence='Y' "; + + if(adempiereSys) + selectSQL += " FOR UPDATE OF CurrentNextSys"; + else + selectSQL += " FOR UPDATE OF CurrentNext"; + } + if (!DB.isOracle() && !DB.isPostgreSQL()) + selectSQL = DB.getDatabase().convertStatement(selectSQL); + + Connection conn = null; + PreparedStatement pstmt = null; + ResultSet rs = null; + for (int i = 0; i < 3; i++) + { + try { conn = DB.getConnectionID(); // Error - if (conn == null) - return -1; - - pstmt = conn.prepareStatement(selectSQL, - ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - pstmt.setString(1, TableName); - // - if (DB.getDatabase().isQueryTimeoutSupported()) - { - pstmt.setQueryTimeout(QUERY_TIME_OUT); - } - rs = pstmt.executeQuery(); - if (s_log.isLoggable(Level.FINEST)) s_log.finest("AC=" + conn.getAutoCommit() + ", RO=" + conn.isReadOnly() - + " - Isolation=" + conn.getTransactionIsolation() + "(" + Connection.TRANSACTION_READ_COMMITTED - + ") - RSType=" + pstmt.getResultSetType() + "(" + ResultSet.TYPE_SCROLL_SENSITIVE - + "), RSConcur=" + pstmt.getResultSetConcurrency() + "(" + ResultSet.CONCUR_UPDATABLE - + ")"); - if (rs.next()) - { - - // Get the table - MTable table = MTable.get(Env.getCtx(), TableName); + if (conn == null) + return -1; + + pstmt = conn.prepareStatement(selectSQL, + ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + pstmt.setString(1, TableName); + // + if (DB.getDatabase().isQueryTimeoutSupported()) + { + pstmt.setQueryTimeout(QUERY_TIME_OUT); + } + rs = pstmt.executeQuery(); + if (s_log.isLoggable(Level.FINEST)) s_log.finest("AC=" + conn.getAutoCommit() + ", RO=" + conn.isReadOnly() + + " - Isolation=" + conn.getTransactionIsolation() + "(" + Connection.TRANSACTION_READ_COMMITTED + + ") - RSType=" + pstmt.getResultSetType() + "(" + ResultSet.TYPE_SCROLL_SENSITIVE + + "), RSConcur=" + pstmt.getResultSetConcurrency() + "(" + ResultSet.CONCUR_UPDATABLE + + ")"); + if (rs.next()) + { + + // Get the table + MTable table = MTable.get(Env.getCtx(), TableName); + + int AD_Sequence_ID = rs.getInt(4); + boolean gotFromHTTP = false; + + // If maintaining official dictionary try to get the ID from http official server + if (adempiereSys) { + + String isUseCentralizedID = MSysConfig.getValue(MSysConfig.DICTIONARY_ID_USE_CENTRALIZED_ID, "Y"); // defaults to Y + if ( ( ! isUseCentralizedID.equals("N") ) && ( ! isExceptionCentralized(TableName) ) ) { + // get ID from http site + retValue = getNextOfficialID_HTTP(TableName); + if (retValue > 0) { + PreparedStatement updateSQL = null; + try { + updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNextSys = ? + 1 WHERE AD_Sequence_ID = ?"); + updateSQL.setInt(1, retValue); + updateSQL.setInt(2, AD_Sequence_ID); + updateSQL.executeUpdate(); + } finally { + DB.close(updateSQL); + updateSQL = null; + } + } + gotFromHTTP = true; + } - int AD_Sequence_ID = rs.getInt(4); - boolean gotFromHTTP = false; - - // If maintaining official dictionary try to get the ID from http official server - if (adempiereSys) { - - String isUseCentralizedID = MSysConfig.getValue(MSysConfig.DICTIONARY_ID_USE_CENTRALIZED_ID, "Y"); // defaults to Y - if ( ( ! isUseCentralizedID.equals("N") ) && ( ! isExceptionCentralized(TableName) ) ) { - // get ID from http site - retValue = getNextOfficialID_HTTP(TableName); - if (retValue > 0) { - PreparedStatement updateSQL = null; - try { - updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNextSys = ? + 1 WHERE AD_Sequence_ID = ?"); - updateSQL.setInt(1, retValue); - updateSQL.setInt(2, AD_Sequence_ID); - updateSQL.executeUpdate(); - } finally { - DB.close(updateSQL); - updateSQL = null; - } - } - gotFromHTTP = true; - } - - } - - boolean queryProjectServer = false; - if (table.getColumn("EntityType") != null) - queryProjectServer = true; - if (!queryProjectServer && MSequence.Table_Name.equalsIgnoreCase(TableName)) - queryProjectServer = true; - - // If not official dictionary try to get the ID from http custom server - if configured - if (queryProjectServer && ( ! adempiereSys ) && ( ! isExceptionCentralized(TableName) ) ) { - - String isUseProjectCentralizedID = MSysConfig.getValue(MSysConfig.PROJECT_ID_USE_CENTRALIZED_ID, "N"); // defaults to N - if (isUseProjectCentralizedID.equals("Y")) { - // get ID from http site - retValue = getNextProjectID_HTTP(TableName); - if (retValue > 0) { - PreparedStatement updateSQL = null; - try { - updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNext = GREATEST(CurrentNext, ? + 1) WHERE AD_Sequence_ID = ?"); - updateSQL.setInt(1, retValue); - updateSQL.setInt(2, AD_Sequence_ID); - updateSQL.executeUpdate(); - } finally { - DB.close(updateSQL); - updateSQL = null; - } - } - gotFromHTTP = true; - } - - } - - if (! gotFromHTTP) { - PreparedStatement updateSQL = null; - try - { - int incrementNo = rs.getInt(3); - if (adempiereSys) { - String updateCmd = "UPDATE AD_Sequence SET CurrentNextSys=CurrentNextSys+? WHERE AD_Sequence_ID=?"; - if (!DB.isOracle() && !DB.isPostgreSQL()) - updateCmd = DB.getDatabase().convertStatement(updateCmd); - updateSQL = conn.prepareStatement(updateCmd); - retValue = rs.getInt(2); - } else { - String updateCmd = "UPDATE AD_Sequence SET CurrentNext=CurrentNext+? WHERE AD_Sequence_ID=?"; - if (!DB.isOracle() && !DB.isPostgreSQL()) - updateCmd = DB.getDatabase().convertStatement(updateCmd); - updateSQL = conn.prepareStatement(updateCmd); - retValue = rs.getInt(1); - } - updateSQL.setInt(1, incrementNo); - updateSQL.setInt(2, AD_Sequence_ID); - updateSQL.executeUpdate(); - } finally { - DB.close(updateSQL); - updateSQL = null; - } } - + + boolean queryProjectServer = false; + if (table.getColumn("EntityType") != null) + queryProjectServer = true; + if (!queryProjectServer && MSequence.Table_Name.equalsIgnoreCase(TableName)) + queryProjectServer = true; + + // If not official dictionary try to get the ID from http custom server - if configured + if (queryProjectServer && ( ! adempiereSys ) && ( ! isExceptionCentralized(TableName) ) ) { + + String isUseProjectCentralizedID = MSysConfig.getValue(MSysConfig.PROJECT_ID_USE_CENTRALIZED_ID, "N"); // defaults to N + if (isUseProjectCentralizedID.equals("Y")) { + // get ID from http site + retValue = getNextProjectID_HTTP(TableName); + if (retValue > 0) { + PreparedStatement updateSQL = null; + try { + updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNext = GREATEST(CurrentNext, ? + 1) WHERE AD_Sequence_ID = ?"); + updateSQL.setInt(1, retValue); + updateSQL.setInt(2, AD_Sequence_ID); + updateSQL.executeUpdate(); + } finally { + DB.close(updateSQL); + updateSQL = null; + } + } + gotFromHTTP = true; + } + + } + + if (! gotFromHTTP) { + PreparedStatement updateSQL = null; + try + { + int incrementNo = rs.getInt(3); + if (adempiereSys) { + String updateCmd = "UPDATE AD_Sequence SET CurrentNextSys=CurrentNextSys+? WHERE AD_Sequence_ID=?"; + if (!DB.isOracle() && !DB.isPostgreSQL()) + updateCmd = DB.getDatabase().convertStatement(updateCmd); + updateSQL = conn.prepareStatement(updateCmd); + retValue = rs.getInt(2); + } else { + String updateCmd = "UPDATE AD_Sequence SET CurrentNext=CurrentNext+? WHERE AD_Sequence_ID=?"; + if (!DB.isOracle() && !DB.isPostgreSQL()) + updateCmd = DB.getDatabase().convertStatement(updateCmd); + updateSQL = conn.prepareStatement(updateCmd); + retValue = rs.getInt(1); + } + updateSQL.setInt(1, incrementNo); + updateSQL.setInt(2, AD_Sequence_ID); + updateSQL.executeUpdate(); + } finally { + DB.close(updateSQL); + updateSQL = null; + } + } + //if (trx == null) conn.commit(); } else s_log.severe ("No record found - " + TableName); - + // break; // EXIT } catch (Exception e) { s_log.log(Level.SEVERE, TableName + " - " + e.getMessage(), e); - try - { - if (conn != null) - conn.rollback(); + try + { + if (conn != null) + conn.rollback(); } catch (SQLException e1) { } - } - finally - { - DB.close(rs, pstmt); - pstmt = null;rs = null; - - if (conn != null) - { - try { - conn.close(); - } catch (SQLException e) {} - conn = null; - } + } + finally + { + DB.close(rs, pstmt); + pstmt = null;rs = null; + + if (conn != null) + { + try { + conn.close(); + } catch (SQLException e) {} + conn = null; + } } Thread.yield(); // give it time } - //if (s_log.isLoggable(Level.FINEST)) s_log.finest (retValue + " - Table=" + TableName + " [" + trx + "]"); + //if (s_log.isLoggable(Level.FINEST)) s_log.finest (retValue + " - Table=" + TableName + " [" + trx + "]"); return retValue; } // getNextID - /************************************************************************** - * Get Document No from table - * @param AD_Client_ID client - * @param TableName table name - * @param trxName optional Transaction Name - * @return document no or null - */ - public static String getDocumentNo (int AD_Client_ID, String TableName, String trxName) - { - return getDocumentNo(AD_Client_ID, TableName, trxName, null); - - } /************************************************************************** - * Get Document No from table (when the document doesn't have a c_doctype) + * Get Document No from table * @param AD_Client_ID client * @param TableName table name - * @param trxName optional Transaction Name - * @param PO - used to get the date, org and parse context variables + * @param trxName optional Transaction Name + * @return document no or null + */ + public static String getDocumentNo (int AD_Client_ID, String TableName, String trxName) + { + return getDocumentNo(AD_Client_ID, TableName, trxName, null); + + } + /************************************************************************** + * Get Document No from table (when the document doesn't have a c_doctype) + * @param AD_Client_ID client + * @param TableName table name + * @param trxName optional Transaction Name + * @param PO - used to get the date, org and parse context variables * @return document no or null */ public static String getDocumentNo (int AD_Client_ID, String TableName, String trxName, PO po) { - if (TableName == null || TableName.length() == 0) - throw new IllegalArgumentException("TableName missing"); - - MSequence seq = get(Env.getCtx(), TableName, trxName, /*tableID=*/false); - if (seq == null || seq.get_ID() == 0) { - if (!MSequence.createTableSequence(Env.getCtx(), TableName, trxName, /*tableID=*/false)) - throw new AdempiereException("Could not create table sequence"); - seq = get(Env.getCtx(), TableName, trxName, /*tableID=*/false); - if (seq == null || seq.get_ID() == 0) - throw new AdempiereException("Could not find table sequence"); - } - - return getDocumentNoFromSeq(seq, trxName, po); - } // getDocumentNo - - public static String getDocumentNoFromSeq(MSequence seq, String trxName, PO po) { - // Check AdempiereSys - boolean adempiereSys = false; - if (Ini.isClient()) - { - adempiereSys = Ini.isPropertyBool(Ini.P_ADEMPIERESYS); - } - else - { - String sysProperty = Env.getCtx().getProperty("AdempiereSys", "N"); - adempiereSys = "y".equalsIgnoreCase(sysProperty) || "true".equalsIgnoreCase(sysProperty); - } - if (adempiereSys && Env.getAD_Client_ID(Env.getCtx()) > 11) - adempiereSys = false; - // - - int AD_Sequence_ID = seq.getAD_Sequence_ID(); - boolean isStartNewYear = seq.isStartNewYear(); - boolean isStartNewMonth = seq.isStartNewMonth(); - String dateColumn = seq.getDateColumn(); - boolean isUseOrgLevel = seq.isOrgLevelSequence(); - String orgColumn = seq.getOrgColumn(); - int startNo = seq.getStartNo(); - int incrementNo = seq.getIncrementNo(); - String prefix = seq.getPrefix(); - String suffix = seq.getSuffix(); - String decimalPattern = seq.getDecimalPattern(); - - String selectSQL = null; - if (isStartNewYear || isUseOrgLevel) { - selectSQL = "SELECT y.CurrentNext, s.CurrentNextSys " - + "FROM AD_Sequence_No y, AD_Sequence s " - + "WHERE y.AD_Sequence_ID = s.AD_Sequence_ID " - + "AND s.AD_Sequence_ID = ? " - + "AND y.CalendarYearMonth = ? " - + "AND y.AD_Org_ID = ? " - + "AND s.IsActive='Y' AND s.IsTableID='N' AND s.IsAutoSequence='Y' " - + "ORDER BY s.AD_Client_ID DESC"; - } else { - selectSQL = "SELECT s.CurrentNext, s.CurrentNextSys " - + "FROM AD_Sequence s " - + "WHERE s.AD_Sequence_ID = ? " - + "AND s.IsActive='Y' AND s.IsTableID='N' AND s.IsAutoSequence='Y' " - + "ORDER BY s.AD_Client_ID DESC"; - } - if (DB.isOracle() == false) - { - if ( isStartNewYear || isUseOrgLevel ) { - selectSQL = selectSQL + " FOR UPDATE OF y"; - } else { - selectSQL = selectSQL + " FOR UPDATE OF s"; - } - } - else - { - if (isStartNewYear || isUseOrgLevel) { - selectSQL = selectSQL + " FOR UPDATE OF y."; - } else { - selectSQL = selectSQL + " FOR UPDATE OF s."; - } - - if(adempiereSys) - selectSQL = selectSQL + "CurrentNextSys"; - else - selectSQL = selectSQL + "CurrentNext"; - } - if (!DB.isOracle() && !DB.isPostgreSQL()) - selectSQL = DB.getDatabase().convertStatement(selectSQL); - Connection conn = null; - Trx trx = trxName == null ? null : Trx.get(trxName, true); - // - - String calendarYearMonth = NoYearNorMonth; - int docOrg_ID = 0; - int next = -1; - - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - if (trx != null) - conn = trx.getConnection(); - else - conn = DB.getConnectionID(); - // Error - if (conn == null) - return null; - - if (isStartNewYear) - { - SimpleDateFormat sdf = null; - if (isStartNewMonth) - sdf = new SimpleDateFormat("yyyyMM"); - else - sdf = new SimpleDateFormat("yyyy"); - - if (po != null && dateColumn != null && dateColumn.length() > 0) - { - Date docDate = (Date)po.get_Value(dateColumn); - calendarYearMonth = sdf.format(docDate); - } - else - { - calendarYearMonth = sdf.format(new Date()); - } - } - - if (isUseOrgLevel) - { - if (po != null && orgColumn != null && orgColumn.length() > 0) - { - docOrg_ID = po.get_ValueAsInt(orgColumn); - } - } - - pstmt = conn.prepareStatement(selectSQL, - ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - int index = 1; - pstmt.setInt(index++, AD_Sequence_ID); - if (isUseOrgLevel || isStartNewYear) { - pstmt.setString(index++, calendarYearMonth); - pstmt.setInt(index++, docOrg_ID); - } - - // - if (DB.getDatabase().isQueryTimeoutSupported()) - { - pstmt.setQueryTimeout(QUERY_TIME_OUT); - } - rs = pstmt.executeQuery(); - // s_log.fine("AC=" + conn.getAutoCommit() + " -Iso=" + conn.getTransactionIsolation() - // + " - Type=" + pstmt.getResultSetType() + " - Concur=" + pstmt.getResultSetConcurrency()); - if (rs.next()) - { - if (s_log.isLoggable(Level.FINE)) s_log.fine("AD_Sequence_ID="+AD_Sequence_ID); - - PreparedStatement updateSQL = null; - try - { - if (adempiereSys) { - String updateCmd = "UPDATE AD_Sequence SET CurrentNextSys = CurrentNextSys + ? WHERE AD_Sequence_ID = ?"; - if (!DB.isOracle() && !DB.isPostgreSQL()) - updateCmd = DB.getDatabase().convertStatement(updateCmd); - updateSQL = conn.prepareStatement(updateCmd); - next = rs.getInt(2); - } else { - String sql; - if (isStartNewYear || isUseOrgLevel) - sql = "UPDATE AD_Sequence_No SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID=? AND CalendarYearMonth=? AND AD_Org_ID=?"; - else - sql = "UPDATE AD_Sequence SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID=?"; - if (!DB.isOracle() && !DB.isPostgreSQL()) - sql = DB.getDatabase().convertStatement(sql); - updateSQL = conn.prepareStatement(sql); - next = rs.getInt(1); - } - updateSQL.setInt(1, incrementNo); - updateSQL.setInt(2, AD_Sequence_ID); - if (isStartNewYear || isUseOrgLevel) { - updateSQL.setString(3, calendarYearMonth); - updateSQL.setInt(4, docOrg_ID); - } - updateSQL.executeUpdate(); - } - finally - { - DB.close(updateSQL); - updateSQL = null; - } - } - else - { // did not find sequence no - if (isUseOrgLevel || isStartNewYear) - { // create sequence (CurrentNo = StartNo + IncrementNo) for this year/month/org and return first number (=StartNo) - next = startNo; - - X_AD_Sequence_No seqno = new X_AD_Sequence_No(Env.getCtx(), 0, trxName); - seqno.setAD_Sequence_ID(AD_Sequence_ID); - seqno.setAD_Org_ID(docOrg_ID); - seqno.setCalendarYearMonth(calendarYearMonth); - seqno.setCurrentNext(startNo + incrementNo); - seqno.saveEx(); - } - else // standard - { - s_log.warning ("(Sequence)- no record found - " + seq); - next = -2; - } - } - // Commit - if (trx == null) - { - conn.commit(); - } - } - catch (Exception e) - { - s_log.log(Level.SEVERE, "(DocType) [" + trxName + "]", e); - if (DBException.isTimeout(e)) - throw new AdempiereException("GenerateDocumentNoTimeOut", e); - else - throw new AdempiereException("GenerateDocumentNoError", e); - } - finally - { - DB.close(rs, pstmt); - pstmt = null;rs = null; - // Finish - try - { - if (trx == null && conn != null) { - conn.close(); - conn = null; - } - } - catch (Exception e) - { - s_log.log(Level.SEVERE, "(DocType) - finish", e); - } - } - // Error - if (next < 0) - return null; - - // create DocumentNo - StringBuilder doc = new StringBuilder(); - if (prefix != null && prefix.length() > 0) { - String prefixValue = Env.parseVariable(prefix, po, trxName, false); - if (!Util.isEmpty(prefixValue)) - doc.append(prefixValue); - } - - if (decimalPattern != null && decimalPattern.length() > 0) - doc.append(new DecimalFormat(decimalPattern).format(next)); - else - doc.append(next); - - if (suffix != null && suffix.length() > 0) { - String suffixValue = Env.parseVariable(suffix, po, trxName, false); - if (!Util.isEmpty(suffixValue)) - doc.append(suffixValue); - } - - String documentNo = doc.toString(); - if (s_log.isLoggable(Level.FINER)) s_log.finer (documentNo + " (" + incrementNo + ")" - + " - Sequence=" + AD_Sequence_ID + " [" + trx + "]"); - return documentNo; - } - - /** - * Get Document No based on Document Type - * @param C_DocType_ID document type - * @param trxName optional Transaction Name - * @return document no or null - * @deprecated - */ - public static String getDocumentNo(int C_DocType_ID, String trxName) - { - return getDocumentNo (C_DocType_ID, trxName, false); - } // getDocumentNo - - /** - * Get Document No based on Document Type - * @param C_DocType_ID document type - * @param trxName optional Transaction Name - * @param definite asking for a definitive or temporary sequence - * @return document no or null - */ - public static String getDocumentNo (int C_DocType_ID, String trxName, boolean definite) - { - return getDocumentNo(C_DocType_ID, trxName, definite, null); - } - + if (TableName == null || TableName.length() == 0) + throw new IllegalArgumentException("TableName missing"); + + MSequence seq = get(Env.getCtx(), TableName, trxName, /*tableID=*/false); + if (seq == null || seq.get_ID() == 0) { + if (!MSequence.createTableSequence(Env.getCtx(), TableName, trxName, /*tableID=*/false)) + throw new AdempiereException("Could not create table sequence"); + seq = get(Env.getCtx(), TableName, trxName, /*tableID=*/false); + if (seq == null || seq.get_ID() == 0) + throw new AdempiereException("Could not find table sequence"); + } + + return getDocumentNoFromSeq(seq, trxName, po); + } // getDocumentNo + + public static String getDocumentNoFromSeq(MSequence seq, String trxName, PO po) { + // Check AdempiereSys + boolean adempiereSys = false; + if (Ini.isClient()) + { + adempiereSys = Ini.isPropertyBool(Ini.P_ADEMPIERESYS); + } + else + { + String sysProperty = Env.getCtx().getProperty("AdempiereSys", "N"); + adempiereSys = "y".equalsIgnoreCase(sysProperty) || "true".equalsIgnoreCase(sysProperty); + } + if (adempiereSys && Env.getAD_Client_ID(Env.getCtx()) > 11) + adempiereSys = false; + // + + int AD_Sequence_ID = seq.getAD_Sequence_ID(); + boolean isStartNewYear = seq.isStartNewYear(); + boolean isStartNewMonth = seq.isStartNewMonth(); + String dateColumn = seq.getDateColumn(); + boolean isUseOrgLevel = seq.isOrgLevelSequence(); + String orgColumn = seq.getOrgColumn(); + int startNo = seq.getStartNo(); + int incrementNo = seq.getIncrementNo(); + String prefix = seq.getPrefix(); + String suffix = seq.getSuffix(); + String decimalPattern = seq.getDecimalPattern(); + + String selectSQL = null; + if (isStartNewYear || isUseOrgLevel) { + selectSQL = "SELECT y.CurrentNext, s.CurrentNextSys " + + "FROM AD_Sequence_No y, AD_Sequence s " + + "WHERE y.AD_Sequence_ID = s.AD_Sequence_ID " + + "AND s.AD_Sequence_ID = ? " + + "AND y.CalendarYearMonth = ? " + + "AND y.AD_Org_ID = ? " + + "AND s.IsActive='Y' AND s.IsTableID='N' AND s.IsAutoSequence='Y' " + + "ORDER BY s.AD_Client_ID DESC"; + } else { + selectSQL = "SELECT s.CurrentNext, s.CurrentNextSys " + + "FROM AD_Sequence s " + + "WHERE s.AD_Sequence_ID = ? " + + "AND s.IsActive='Y' AND s.IsTableID='N' AND s.IsAutoSequence='Y' " + + "ORDER BY s.AD_Client_ID DESC"; + } + if (DB.isOracle() == false) + { + if ( isStartNewYear || isUseOrgLevel ) { + selectSQL = selectSQL + " FOR UPDATE OF y"; + } else { + selectSQL = selectSQL + " FOR UPDATE OF s"; + } + } + else + { + if (isStartNewYear || isUseOrgLevel) { + selectSQL = selectSQL + " FOR UPDATE OF y."; + } else { + selectSQL = selectSQL + " FOR UPDATE OF s."; + } + + if(adempiereSys) + selectSQL = selectSQL + "CurrentNextSys"; + else + selectSQL = selectSQL + "CurrentNext"; + } + if (!DB.isOracle() && !DB.isPostgreSQL()) + selectSQL = DB.getDatabase().convertStatement(selectSQL); + Connection conn = null; + Trx trx = trxName == null ? null : Trx.get(trxName, true); + // + + String calendarYearMonth = NoYearNorMonth; + int docOrg_ID = 0; + int next = -1; + + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + if (trx != null) + conn = trx.getConnection(); + else + conn = DB.getConnectionID(); + // Error + if (conn == null) + return null; + + if (isStartNewYear) + { + SimpleDateFormat sdf = null; + if (isStartNewMonth) + sdf = new SimpleDateFormat("yyyyMM"); + else + sdf = new SimpleDateFormat("yyyy"); + + if (po != null && dateColumn != null && dateColumn.length() > 0) + { + Date docDate = (Date)po.get_Value(dateColumn); + calendarYearMonth = sdf.format(docDate); + } + else + { + calendarYearMonth = sdf.format(new Date()); + } + } + + if (isUseOrgLevel) + { + if (po != null && orgColumn != null && orgColumn.length() > 0) + { + docOrg_ID = po.get_ValueAsInt(orgColumn); + } + } + + pstmt = conn.prepareStatement(selectSQL, + ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + int index = 1; + pstmt.setInt(index++, AD_Sequence_ID); + if (isUseOrgLevel || isStartNewYear) { + pstmt.setString(index++, calendarYearMonth); + pstmt.setInt(index++, docOrg_ID); + } + + // + if (DB.getDatabase().isQueryTimeoutSupported()) + { + pstmt.setQueryTimeout(QUERY_TIME_OUT); + } + rs = pstmt.executeQuery(); + // s_log.fine("AC=" + conn.getAutoCommit() + " -Iso=" + conn.getTransactionIsolation() + // + " - Type=" + pstmt.getResultSetType() + " - Concur=" + pstmt.getResultSetConcurrency()); + if (rs.next()) + { + if (s_log.isLoggable(Level.FINE)) s_log.fine("AD_Sequence_ID="+AD_Sequence_ID); + + PreparedStatement updateSQL = null; + try + { + if (adempiereSys) { + String updateCmd = "UPDATE AD_Sequence SET CurrentNextSys = CurrentNextSys + ? WHERE AD_Sequence_ID = ?"; + if (!DB.isOracle() && !DB.isPostgreSQL()) + updateCmd = DB.getDatabase().convertStatement(updateCmd); + updateSQL = conn.prepareStatement(updateCmd); + next = rs.getInt(2); + } else { + String sql; + if (isStartNewYear || isUseOrgLevel) + sql = "UPDATE AD_Sequence_No SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID=? AND CalendarYearMonth=? AND AD_Org_ID=?"; + else + sql = "UPDATE AD_Sequence SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID=?"; + if (!DB.isOracle() && !DB.isPostgreSQL()) + sql = DB.getDatabase().convertStatement(sql); + updateSQL = conn.prepareStatement(sql); + next = rs.getInt(1); + } + updateSQL.setInt(1, incrementNo); + updateSQL.setInt(2, AD_Sequence_ID); + if (isStartNewYear || isUseOrgLevel) { + updateSQL.setString(3, calendarYearMonth); + updateSQL.setInt(4, docOrg_ID); + } + updateSQL.executeUpdate(); + } + finally + { + DB.close(updateSQL); + updateSQL = null; + } + } + else + { // did not find sequence no + if (isUseOrgLevel || isStartNewYear) + { // create sequence (CurrentNo = StartNo + IncrementNo) for this year/month/org and return first number (=StartNo) + next = startNo; + + X_AD_Sequence_No seqno = new X_AD_Sequence_No(Env.getCtx(), 0, trxName); + seqno.setAD_Sequence_ID(AD_Sequence_ID); + seqno.setAD_Org_ID(docOrg_ID); + seqno.setCalendarYearMonth(calendarYearMonth); + seqno.setCurrentNext(startNo + incrementNo); + seqno.saveEx(); + } + else // standard + { + s_log.warning ("(Sequence)- no record found - " + seq); + next = -2; + } + } + // Commit + if (trx == null) + { + conn.commit(); + } + } + catch (Exception e) + { + s_log.log(Level.SEVERE, "(DocType) [" + trxName + "]", e); + if (DBException.isTimeout(e)) + throw new AdempiereException("GenerateDocumentNoTimeOut", e); + else + throw new AdempiereException("GenerateDocumentNoError", e); + } + finally + { + DB.close(rs, pstmt); + pstmt = null;rs = null; + // Finish + try + { + if (trx == null && conn != null) { + conn.close(); + conn = null; + } + } + catch (Exception e) + { + s_log.log(Level.SEVERE, "(DocType) - finish", e); + } + } + // Error + if (next < 0) + return null; + + // create DocumentNo + StringBuilder doc = new StringBuilder(); + if (prefix != null && prefix.length() > 0) { + String prefixValue = Env.parseVariable(prefix, po, trxName, false); + if (!Util.isEmpty(prefixValue)) + doc.append(prefixValue); + } + + if (decimalPattern != null && decimalPattern.length() > 0) + doc.append(new DecimalFormat(decimalPattern).format(next)); + else + doc.append(next); + + if (suffix != null && suffix.length() > 0) { + String suffixValue = Env.parseVariable(suffix, po, trxName, false); + if (!Util.isEmpty(suffixValue)) + doc.append(suffixValue); + } + + String documentNo = doc.toString(); + if (s_log.isLoggable(Level.FINER)) s_log.finer (documentNo + " (" + incrementNo + ")" + + " - Sequence=" + AD_Sequence_ID + " [" + trx + "]"); + return documentNo; + } + /** * Get Document No based on Document Type * @param C_DocType_ID document type * @param trxName optional Transaction Name - * @param definite asking for a definitive or temporary sequence - * @param po + * @return document no or null + * @deprecated + */ + public static String getDocumentNo(int C_DocType_ID, String trxName) + { + return getDocumentNo (C_DocType_ID, trxName, false); + } // getDocumentNo + + /** + * Get Document No based on Document Type + * @param C_DocType_ID document type + * @param trxName optional Transaction Name + * @param definite asking for a definitive or temporary sequence + * @return document no or null + */ + public static String getDocumentNo (int C_DocType_ID, String trxName, boolean definite) + { + return getDocumentNo(C_DocType_ID, trxName, definite, null); + } + + /** + * Get Document No based on Document Type + * @param C_DocType_ID document type + * @param trxName optional Transaction Name + * @param definite asking for a definitive or temporary sequence + * @param po * @return document no or null */ public static String getDocumentNo (int C_DocType_ID, String trxName, boolean definite, PO po) @@ -611,35 +611,35 @@ public class MSequence extends X_AD_Sequence { s_log.severe ("C_DocType_ID=0"); return null; - } - + } + MDocType dt = MDocType.get (Env.getCtx(), C_DocType_ID); // wrong for SERVER, but r/o if (dt != null && !dt.isDocNoControlled()) { - if (s_log.isLoggable(Level.FINER)) s_log.finer("DocType_ID=" + C_DocType_ID + " Not DocNo controlled"); + if (s_log.isLoggable(Level.FINER)) s_log.finer("DocType_ID=" + C_DocType_ID + " Not DocNo controlled"); + return null; + } + if (definite && ! dt.isOverwriteSeqOnComplete()) { + s_log.warning("DocType_ID=" + C_DocType_ID + " Not Sequence Overwrite on Complete"); return null; - } - if (definite && ! dt.isOverwriteSeqOnComplete()) { - s_log.warning("DocType_ID=" + C_DocType_ID + " Not Sequence Overwrite on Complete"); - return null; } if (dt == null || dt.getDocNoSequence_ID() == 0) { s_log.warning ("No Sequence for DocType - " + dt); - return null; - } - if (definite && dt.getDefiniteSequence_ID() == 0) - { - s_log.warning ("No Definite Sequence for DocType - " + dt); - return null; - } - int seqID = ( definite ? dt.getDefiniteSequence_ID() : dt.getDocNoSequence_ID() ); - MSequence seq = new MSequence(Env.getCtx(), seqID, trxName); - - if (CLogMgt.isLevel(LOGLEVEL)) - s_log.log(LOGLEVEL, "DocType_ID=" + C_DocType_ID + " [" + trxName + "]"); - - return getDocumentNoFromSeq(seq, trxName, po); + return null; + } + if (definite && dt.getDefiniteSequence_ID() == 0) + { + s_log.warning ("No Definite Sequence for DocType - " + dt); + return null; + } + int seqID = ( definite ? dt.getDefiniteSequence_ID() : dt.getDocNoSequence_ID() ); + MSequence seq = new MSequence(Env.getCtx(), seqID, trxName); + + if (CLogMgt.isLevel(LOGLEVEL)) + s_log.log(LOGLEVEL, "DocType_ID=" + C_DocType_ID + " [" + trxName + "]"); + + return getDocumentNoFromSeq(seq, trxName, po); } // getDocumentNo @@ -666,7 +666,7 @@ public class MSequence extends X_AD_Sequence int counter = 0; boolean success = true; // - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -676,7 +676,7 @@ public class MSequence extends X_AD_Sequence while (rs.next()) { String tableName = rs.getString(1); - if (s_log.isLoggable(Level.FINE)) s_log.fine("Add: " + tableName); + if (s_log.isLoggable(Level.FINE)) s_log.fine("Add: " + tableName); MSequence seq = new MSequence (ctx, AD_Client_ID, tableName, trxName); if (seq.save()) counter++; @@ -692,23 +692,23 @@ public class MSequence extends X_AD_Sequence { s_log.log(Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); - rs = null; - pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; + pstmt = null; } - if (s_log.isLoggable(Level.INFO)) s_log.info ("AD_Client_ID=" + AD_Client_ID + if (s_log.isLoggable(Level.INFO)) s_log.info ("AD_Client_ID=" + AD_Client_ID + " - created #" + counter + " - success=" + success); return success; } // checkClientSequences - public static boolean createTableSequence (Properties ctx, String TableName, String trxName) { - return createTableSequence (ctx, TableName, trxName, true); - } - + public static boolean createTableSequence (Properties ctx, String TableName, String trxName) { + return createTableSequence (ctx, TableName, trxName, true); + } + /** * Create Table ID Sequence * @param ctx context @@ -716,96 +716,96 @@ public class MSequence extends X_AD_Sequence * @param trxName transaction * @return true if created */ - public static boolean createTableSequence (Properties ctx, String TableName, String trxName, boolean tableID) - { - boolean SYSTEM_NATIVE_SEQUENCE = MSysConfig.getBooleanValue(MSysConfig.SYSTEM_NATIVE_SEQUENCE,false); - - if (tableID && SYSTEM_NATIVE_SEQUENCE) - { - int next_id = DB.getSQLValueEx(trxName, "SELECT CurrentNext FROM AD_Sequence WHERE Name=? AND IsActive='Y' AND IsTableID='Y' AND IsAutoSequence='Y'", TableName); - if (next_id == -1) - { - MSequence seq = new MSequence (ctx, 0, trxName); - seq.setClientOrg(0, 0); - seq.setName(TableName); - seq.setDescription("Table " + TableName); - seq.setIsTableID(tableID); - seq.saveEx(); - next_id = INIT_NO; - } - if (! CConnection.get().getDatabase().createSequence(TableName+"_SQ", 1, INIT_NO, Integer.MAX_VALUE, next_id, trxName)) - return false; - - return true; - } - - MSequence seq = new MSequence (ctx, 0, trxName); - if (tableID) - seq.setClientOrg(0, 0); - else - seq.setClientOrg(Env.getAD_Client_ID(Env.getCtx()), 0); - - if (tableID) { - seq.setName(TableName); - seq.setDescription("Table " + TableName); - } else { - seq.setName(PREFIX_DOCSEQ + TableName); - seq.setDescription("DocumentNo/Value for Table " + TableName); - } - seq.setIsTableID(tableID); - seq.saveEx(); + public static boolean createTableSequence (Properties ctx, String TableName, String trxName, boolean tableID) + { + boolean SYSTEM_NATIVE_SEQUENCE = MSysConfig.getBooleanValue(MSysConfig.SYSTEM_NATIVE_SEQUENCE,false); - return true; + if (tableID && SYSTEM_NATIVE_SEQUENCE) + { + int next_id = DB.getSQLValueEx(trxName, "SELECT CurrentNext FROM AD_Sequence WHERE Name=? AND IsActive='Y' AND IsTableID='Y' AND IsAutoSequence='Y'", TableName); + if (next_id == -1) + { + MSequence seq = new MSequence (ctx, 0, trxName); + seq.setClientOrg(0, 0); + seq.setName(TableName); + seq.setDescription("Table " + TableName); + seq.setIsTableID(tableID); + seq.saveEx(); + next_id = INIT_NO; + } + if (! CConnection.get().getDatabase().createSequence(TableName+"_SQ", 1, INIT_NO, Integer.MAX_VALUE, next_id, trxName)) + return false; + + return true; + } + + MSequence seq = new MSequence (ctx, 0, trxName); + if (tableID) + seq.setClientOrg(0, 0); + else + seq.setClientOrg(Env.getAD_Client_ID(Env.getCtx()), 0); + + if (tableID) { + seq.setName(TableName); + seq.setDescription("Table " + TableName); + } else { + seq.setName(PREFIX_DOCSEQ + TableName); + seq.setDescription("DocumentNo/Value for Table " + TableName); + } + seq.setIsTableID(tableID); + seq.saveEx(); + + return true; } // createTableSequence - - /** - * Get Sequence - * @param ctx context - * @param tableName table name - * @return Sequence - */ - public static MSequence get (Properties ctx, String tableName) - { - return get(ctx, tableName, null); - } - - /* Get the tableID sequence based on the TableName */ - public static MSequence get (Properties ctx, String tableName, String trxName) - { - return get (ctx, tableName, trxName, true); - } - + /** * Get Sequence * @param ctx context - * @param tableName table name - * @param trxName optional transaction name - * @param tableID + * @param tableName table name * @return Sequence */ - public static MSequence get (Properties ctx, String tableName, String trxName, boolean tableID) - { - if (! tableID) { - tableName = PREFIX_DOCSEQ + tableName; - } + public static MSequence get (Properties ctx, String tableName) + { + return get(ctx, tableName, null); + } + + /* Get the tableID sequence based on the TableName */ + public static MSequence get (Properties ctx, String tableName, String trxName) + { + return get (ctx, tableName, trxName, true); + } + + /** + * Get Sequence + * @param ctx context + * @param tableName table name + * @param trxName optional transaction name + * @param tableID + * @return Sequence + */ + public static MSequence get (Properties ctx, String tableName, String trxName, boolean tableID) + { + if (! tableID) { + tableName = PREFIX_DOCSEQ + tableName; + } String sql = "SELECT * FROM AD_Sequence " + "WHERE UPPER(Name)=?" - + " AND IsTableID=?"; - if (! tableID) - sql = sql + " AND AD_Client_ID=?"; + + " AND IsTableID=?"; + if (! tableID) + sql = sql + " AND AD_Client_ID=?"; MSequence retValue = null; - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, trxName); - pstmt.setString(1, tableName.toUpperCase()); - pstmt.setString(2, ( tableID ? "Y" : "N" ) ); - if (! tableID) - pstmt.setInt (3, Env.getAD_Client_ID(Env.getCtx())); - rs = pstmt.executeQuery(); + pstmt.setString(1, tableName.toUpperCase()); + pstmt.setString(2, ( tableID ? "Y" : "N" ) ); + if (! tableID) + pstmt.setInt (3, Env.getAD_Client_ID(Env.getCtx())); + rs = pstmt.executeQuery(); if (rs.next ()) retValue = new MSequence (ctx, rs, trxName); if (rs.next()) @@ -815,11 +815,11 @@ public class MSequence extends X_AD_Sequence { throw new DBException(e); } - finally - { - DB.close(rs, pstmt); - rs = null; - pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; + pstmt = null; } return retValue; } // get @@ -827,11 +827,11 @@ public class MSequence extends X_AD_Sequence /** Sequence for Table Document No's */ private static final String PREFIX_DOCSEQ = "DocumentNo_"; /** Start Number */ - public static final int INIT_NO = 1000000; // 1M + public static final int INIT_NO = 1000000; // 1M /** Start System Number */ // public static final int INIT_SYS_NO = 100; // start number for Compiere - // public static final int INIT_SYS_NO = 50000; // start number for Adempiere - public static final int INIT_SYS_NO = 200000; // start number for iDempiere + // public static final int INIT_SYS_NO = 50000; // start number for Adempiere + public static final int INIT_SYS_NO = 200000; // start number for iDempiere /** Static Logger */ private static CLogger s_log = CLogger.getCLogger(MSequence.class); @@ -913,8 +913,8 @@ public class MSequence extends X_AD_Sequence public int getNextID() { int retValue = getCurrentNext(); - if (! (MSysConfig.getBooleanValue(MSysConfig.SYSTEM_NATIVE_SEQUENCE,false) && isTableID())) { - setCurrentNext(retValue + getIncrementNo()); + if (! (MSysConfig.getBooleanValue(MSysConfig.SYSTEM_NATIVE_SEQUENCE,false) && isTableID())) { + setCurrentNext(retValue + getIncrementNo()); } return retValue; } // getNextNo @@ -923,26 +923,26 @@ public class MSequence extends X_AD_Sequence * Validate Table Sequence Values * @return true if updated */ - public String validateTableIDValue() + public String validateTableIDValue() { if (!isTableID()) - return null; + return null; String tableName = getName(); int AD_Column_ID = DB.getSQLValue(null, "SELECT MAX(c.AD_Column_ID) " + "FROM AD_Table t" + " INNER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID) " + "WHERE t.TableName='" + tableName + "'" - + " AND t.IsView='N'" // ignore for views -- IDEMPIERE-2513 + + " AND t.IsView='N'" // ignore for views -- IDEMPIERE-2513 + " AND c.ColumnName='" + tableName + "_ID'"); if (AD_Column_ID <= 0) - return null; + return null; // MSystem system = MSystem.get(getCtx()); int IDRangeEnd = 0; if (system.getIDRangeEnd() != null) IDRangeEnd = system.getIDRangeEnd().intValue(); - - String changeMsg = null; + + String changeMsg = null; String info = null; // Current Next @@ -952,14 +952,14 @@ public class MSequence extends X_AD_Sequence int maxTableID = DB.getSQLValue(null, sql); if (maxTableID < INIT_NO) maxTableID = INIT_NO - 1; - maxTableID++; // Next - - int currentNextValue = getCurrentNext(); - if (currentNextValue < maxTableID) + maxTableID++; // Next + + int currentNextValue = getCurrentNext(); + if (currentNextValue < maxTableID) { setCurrentNext(maxTableID); info = "CurrentNext=" + maxTableID; - changeMsg = getName() + " ID " + currentNextValue + " -> " + maxTableID; + changeMsg = getName() + " ID " + currentNextValue + " -> " + maxTableID; } // Get Max System_ID used in Table @@ -968,59 +968,59 @@ public class MSequence extends X_AD_Sequence int maxTableSysID = DB.getSQLValue(null, sql); if (maxTableSysID <= 0) maxTableSysID = INIT_SYS_NO; - int currentNextSysValue = getCurrentNextSys(); - if (currentNextSysValue < maxTableSysID){ + int currentNextSysValue = getCurrentNextSys(); + if (currentNextSysValue < maxTableSysID){ setCurrentNextSys(maxTableSysID); if (info == null) info = "CurrentNextSys=" + maxTableSysID; else info += " - CurrentNextSys=" + maxTableSysID; - - if (changeMsg == null) - changeMsg = getName() + " Sys " + currentNextSysValue + " -> " + maxTableSysID; - else - changeMsg += " - " +getName() + " Sys " + currentNextSysValue + " -> " + maxTableSysID; + + if (changeMsg == null) + changeMsg = getName() + " Sys " + currentNextSysValue + " -> " + maxTableSysID; + else + changeMsg += " - " +getName() + " Sys " + currentNextSysValue + " -> " + maxTableSysID; } if (info != null) - if (log.isLoggable(Level.FINE)) log.fine(getName() + " - " + info); - - return changeMsg; + if (log.isLoggable(Level.FINE)) log.fine(getName() + " - " + info); + + return changeMsg; } // validate - @Override - public int getCurrentNext() { - if (MSysConfig.getBooleanValue(MSysConfig.SYSTEM_NATIVE_SEQUENCE,false) && isTableID()){ - return DB.getNextID (getAD_Client_ID(),getName(),get_TrxName()); - } else { - return super.getCurrentNext(); - } - } - - @Override - public void setCurrentNext(int CurrentNext) { - if (MSysConfig.getBooleanValue(MSysConfig.SYSTEM_NATIVE_SEQUENCE,false) && isTableID()){ - while (true) { - int id = DB.getNextID(getAD_Client_ID(),getName(),get_TrxName()); - if (id < 0 || id >= (CurrentNext-1)) - break; - } - }else { - super.setCurrentNext(CurrentNext); - } - } + @Override + public int getCurrentNext() { + if (MSysConfig.getBooleanValue(MSysConfig.SYSTEM_NATIVE_SEQUENCE,false) && isTableID()){ + return DB.getNextID (getAD_Client_ID(),getName(),get_TrxName()); + } else { + return super.getCurrentNext(); + } + } + + @Override + public void setCurrentNext(int CurrentNext) { + if (MSysConfig.getBooleanValue(MSysConfig.SYSTEM_NATIVE_SEQUENCE,false) && isTableID()){ + while (true) { + int id = DB.getNextID(getAD_Client_ID(),getName(),get_TrxName()); + if (id < 0 || id >= (CurrentNext-1)) + break; + } + }else { + super.setCurrentNext(CurrentNext); + } + } /************************************************************************** * Test * @param args ignored - */ - static public void main (String[] args) - { - // int id = getNextID_HTTP("AD_Column"); - // if (true) return; - - org.compiere.Adempiere.startup(true); - CLogMgt.setLevel(Level.SEVERE); - CLogMgt.setLoggerLevel(Level.SEVERE, null); - s_list = new Vector(1000); + */ + static public void main (String[] args) + { + // int id = getNextID_HTTP("AD_Column"); + // if (true) return; + + org.compiere.Adempiere.startup(true); + CLogMgt.setLevel(Level.SEVERE); + CLogMgt.setLoggerLevel(Level.SEVERE, null); + s_list = new Vector(1000); /** Lock Test ** String trxName = "test"; @@ -1094,13 +1094,13 @@ public class MSequence extends X_AD_Sequence /** ** try { - int retValue = -1; - Connection conn = DB.getConnectionRW (); - // DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); - // Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@//dev2:1521/dev2", "adempiere", "adempiere"); - - conn.setAutoCommit(false); - String sql = "SELECT CurrentNext, CurrentNextSys, IncrementNo " + int retValue = -1; + Connection conn = DB.getConnectionRW (); + // DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); + // Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@//dev2:1521/dev2", "adempiere", "adempiere"); + + conn.setAutoCommit(false); + String sql = "SELECT CurrentNext, CurrentNextSys, IncrementNo " + "FROM AD_Sequence " + "WHERE Name='AD_Sequence' "; sql += "FOR UPDATE"; @@ -1216,7 +1216,7 @@ public class MSequence extends X_AD_Sequence { m_i = i; } - @SuppressWarnings("unused") + @SuppressWarnings("unused") private int m_i; /** @@ -1239,209 +1239,209 @@ public class MSequence extends X_AD_Sequence } } } // GetIDs - - /** - * Get next number for Key column - * @param AD_Client_ID client - * @param TableName table name - * @param trxName optional Transaction Name - * @return next no or (-1=error) - */ - public static synchronized int getNextOfficialID_HTTP (String TableName) - { - String website = MSysConfig.getValue(MSysConfig.DICTIONARY_ID_WEBSITE); // "http://developer.adempiere.com/cgi-bin/get_ID"; - String prm_USER = MSysConfig.getValue(MSysConfig.DICTIONARY_ID_USER); // "globalqss"; - String prm_PASSWORD = MSysConfig.getValue(MSysConfig.DICTIONARY_ID_PASSWORD); // "password_inseguro"; - String prm_TABLE = TableName; - String prm_ALTKEY = ""; // TODO: generate alt-key based on key of table - String prm_COMMENT = MSysConfig.getValue(MSysConfig.DICTIONARY_ID_COMMENTS); - String prm_PROJECT = new String("Adempiere"); - - return getNextID_HTTP(TableName, website, prm_USER, - prm_PASSWORD, prm_TABLE, prm_ALTKEY, prm_COMMENT, prm_PROJECT); - } - /** - * Get next number for Key column - * @param AD_Client_ID client - * @param TableName table name - * @param trxName optional Transaction Name - * @return next no or (-1=error) - */ - public static synchronized int getNextProjectID_HTTP (String TableName) - { - String website = MSysConfig.getValue(MSysConfig.PROJECT_ID_WEBSITE); // "http://developer.adempiere.com/cgi-bin/get_ID"; - String prm_USER = MSysConfig.getValue(MSysConfig.PROJECT_ID_USER); // "globalqss"; - String prm_PASSWORD = MSysConfig.getValue(MSysConfig.PROJECT_ID_PASSWORD); // "password_inseguro"; - String prm_TABLE = TableName; - String prm_ALTKEY = ""; // TODO: generate alt-key based on key of table - String prm_COMMENT = MSysConfig.getValue(MSysConfig.PROJECT_ID_COMMENTS); - String prm_PROJECT = MSysConfig.getValue(MSysConfig.PROJECT_ID_PROJECT); - - return getNextID_HTTP(TableName, website, prm_USER, - prm_PASSWORD, prm_TABLE, prm_ALTKEY, prm_COMMENT, prm_PROJECT); - } - - private static int getNextID_HTTP(String TableName, - String website, String prm_USER, String prm_PASSWORD, - String prm_TABLE, String prm_ALTKEY, String prm_COMMENT, - String prm_PROJECT) { - StringBuffer read = new StringBuffer(); - int retValue = -1; - try { - String completeUrl = website + "?" + "USER=" - + URLEncoder.encode(prm_USER, "UTF-8") + "&PASSWORD=" - + URLEncoder.encode(prm_PASSWORD, "UTF-8") + "&PROJECT=" - + URLEncoder.encode(prm_PROJECT, "UTF-8") + "&TABLE=" - + URLEncoder.encode(prm_TABLE, "UTF-8") + "&ALTKEY=" - + URLEncoder.encode(prm_ALTKEY, "UTF-8") + "&COMMENT=" - + URLEncoder.encode(prm_COMMENT, "UTF-8"); - - // Now use the URL class to parse the user-specified URL into - // its various parts: protocol, host, port, filename. Check the protocol - URL url = new URL(completeUrl); - String protocol = url.getProtocol(); - if (!protocol.equals("http")) - throw new IllegalArgumentException("URL must use 'http:' protocol"); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - conn.setRequestMethod("GET"); - conn.setAllowUserInteraction(false); - InputStream is = conn.getInputStream(); - - // Now read the server's response, and write it to the file - byte[] buffer = new byte[4096]; - int bytes_read; - while((bytes_read = is.read(buffer)) != -1) { - for (int i = 0; i < bytes_read; i++) { - if (buffer[i] != 10) - read.append((char) buffer[i]); - } - } - conn.disconnect(); - retValue = Integer.parseInt(read.toString()); - if (retValue <= 0) - retValue = -1; - } - catch (Exception e) { // Report any errors that arise - System.err.println(e); - retValue = -1; - } - if (s_log.isLoggable(Level.INFO))s_log.log(Level.INFO, "getNextID_HTTP - " + TableName + "=" + read + "(" + retValue + ")"); - - return retValue; - } - - private static String [] dontUseCentralized = new String[] { - "AD_ACCESSLOG", - "AD_ALERTPROCESSORLOG", - "AD_CHANGELOG", - "AD_ISSUE", - "AD_LDAPPROCESSORLOG", - "AD_PACKAGE_IMP", - "AD_PACKAGE_IMP_BACKUP", - "AD_PACKAGE_IMP_DETAIL", - "AD_PACKAGE_IMP_INST", - "AD_PACKAGE_IMP_PROC", - "AD_PINSTANCE", - "AD_PINSTANCE_LOG", - "AD_PINSTANCE_PARA", - "AD_PREFERENCE", - "AD_RECENTITEM", - "AD_REPLICATION_LOG", - "AD_SCHEDULERLOG", - "AD_SESSION", - "AD_WORKFLOWPROCESSORLOG", - "CM_WEBACCESSLOG", - "C_ACCTPROCESSORLOG", - "K_INDEXLOG", - "R_REQUESTPROCESSORLOG", - "T_AGING", - "T_ALTER_COLUMN", - "T_DISTRIBUTIONRUNDETAIL", - "T_INVENTORYVALUE", - "T_INVOICEGL", - "T_REPLENISH", - "T_REPORT", - "T_REPORTSTATEMENT", - "T_SELECTION", - "T_SELECTION2", - "T_SPOOL", - "T_TRANSACTION", - "T_TRIALBALANCE" - }; - - private static boolean isExceptionCentralized(String tableName) { - - for (String exceptionTable : dontUseCentralized) { - if (tableName.equalsIgnoreCase(exceptionTable)) - return true; - } - - // don't log selects or insert/update for exception tables (i.e. AD_Issue, AD_ChangeLog) - return false; - } - - @Override - protected boolean beforeSave(boolean newRecord) { - if (isStartNewMonth() && !isStartNewYear()) - setStartNewMonth(false); - return true; - } - - /** - * Get preliminary document no by year - * @param tab - * @param AD_Sequence_ID - * @return Preliminary document no - */ - public static String getPreliminaryNo(GridTab tab, int AD_Sequence_ID) { - String prelim = null; - if (AD_Sequence_ID > 0) { - MSequence seq = new MSequence(Env.getCtx(), AD_Sequence_ID, null); - boolean startNewYear = seq.isStartNewYear(); - boolean startNewMonth = seq.isStartNewMonth(); - boolean orgLevelSeq = seq.isOrgLevelSequence(); - int currentNext = seq.getCurrentNext(); - if (startNewYear || orgLevelSeq) { - String cym = NoYearNorMonth; - int org = 0; - if (startNewYear || startNewMonth) { - Date d = (Date)tab.getValue(seq.getDateColumn()); - if (d == null) - d = new Date(); - SimpleDateFormat sdf = null; - if (startNewMonth) - sdf = new SimpleDateFormat("yyyyMM"); - else - sdf = new SimpleDateFormat("yyyy"); - cym = sdf.format(d); - } - if (orgLevelSeq) { - String orgColumn = seq.getOrgColumn(); - Object orgObj = tab.getValue(orgColumn); - if (orgObj != null) - org = (Integer)orgObj; - } - String sql = "SELECT CurrentNext FROM AD_Sequence_No WHERE AD_Sequence_ID=? AND CalendarYearMonth=? AND AD_Org_ID=?"; - currentNext = DB.getSQLValue(null, sql, AD_Sequence_ID, cym, org); - } - String decimalPattern = seq.getDecimalPattern(); - if (decimalPattern != null && decimalPattern.length() > 0) - prelim = new DecimalFormat(decimalPattern).format(currentNext); - else - prelim = String.valueOf(currentNext); - } - if (prelim == null) - prelim = "?"; - return "<" + prelim + ">"; - } - - @Override - public String getOrgColumn() { - if (super.getOrgColumn() == null) - return COLUMNNAME_AD_Org_ID; - else - return super.getOrgColumn(); - } - -} // MSequence + /** + * Get next number for Key column + * @param AD_Client_ID client + * @param TableName table name + * @param trxName optional Transaction Name + * @return next no or (-1=error) + */ + public static synchronized int getNextOfficialID_HTTP (String TableName) + { + String website = MSysConfig.getValue(MSysConfig.DICTIONARY_ID_WEBSITE); // "http://developer.adempiere.com/cgi-bin/get_ID"; + String prm_USER = MSysConfig.getValue(MSysConfig.DICTIONARY_ID_USER); // "globalqss"; + String prm_PASSWORD = MSysConfig.getValue(MSysConfig.DICTIONARY_ID_PASSWORD); // "password_inseguro"; + String prm_TABLE = TableName; + String prm_ALTKEY = ""; // TODO: generate alt-key based on key of table + String prm_COMMENT = MSysConfig.getValue(MSysConfig.DICTIONARY_ID_COMMENTS); + String prm_PROJECT = new String("Adempiere"); + + return getNextID_HTTP(TableName, website, prm_USER, + prm_PASSWORD, prm_TABLE, prm_ALTKEY, prm_COMMENT, prm_PROJECT); + } + + /** + * Get next number for Key column + * @param AD_Client_ID client + * @param TableName table name + * @param trxName optional Transaction Name + * @return next no or (-1=error) + */ + public static synchronized int getNextProjectID_HTTP (String TableName) + { + String website = MSysConfig.getValue(MSysConfig.PROJECT_ID_WEBSITE); // "http://developer.adempiere.com/cgi-bin/get_ID"; + String prm_USER = MSysConfig.getValue(MSysConfig.PROJECT_ID_USER); // "globalqss"; + String prm_PASSWORD = MSysConfig.getValue(MSysConfig.PROJECT_ID_PASSWORD); // "password_inseguro"; + String prm_TABLE = TableName; + String prm_ALTKEY = ""; // TODO: generate alt-key based on key of table + String prm_COMMENT = MSysConfig.getValue(MSysConfig.PROJECT_ID_COMMENTS); + String prm_PROJECT = MSysConfig.getValue(MSysConfig.PROJECT_ID_PROJECT); + + return getNextID_HTTP(TableName, website, prm_USER, + prm_PASSWORD, prm_TABLE, prm_ALTKEY, prm_COMMENT, prm_PROJECT); + } + + private static int getNextID_HTTP(String TableName, + String website, String prm_USER, String prm_PASSWORD, + String prm_TABLE, String prm_ALTKEY, String prm_COMMENT, + String prm_PROJECT) { + StringBuffer read = new StringBuffer(); + int retValue = -1; + try { + String completeUrl = website + "?" + "USER=" + + URLEncoder.encode(prm_USER, "UTF-8") + "&PASSWORD=" + + URLEncoder.encode(prm_PASSWORD, "UTF-8") + "&PROJECT=" + + URLEncoder.encode(prm_PROJECT, "UTF-8") + "&TABLE=" + + URLEncoder.encode(prm_TABLE, "UTF-8") + "&ALTKEY=" + + URLEncoder.encode(prm_ALTKEY, "UTF-8") + "&COMMENT=" + + URLEncoder.encode(prm_COMMENT, "UTF-8"); + + // Now use the URL class to parse the user-specified URL into + // its various parts: protocol, host, port, filename. Check the protocol + URL url = new URL(completeUrl); + String protocol = url.getProtocol(); + if (!protocol.equals("http")) + throw new IllegalArgumentException("URL must use 'http:' protocol"); + HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + conn.setRequestMethod("GET"); + conn.setAllowUserInteraction(false); + InputStream is = conn.getInputStream(); + + // Now read the server's response, and write it to the file + byte[] buffer = new byte[4096]; + int bytes_read; + while((bytes_read = is.read(buffer)) != -1) { + for (int i = 0; i < bytes_read; i++) { + if (buffer[i] != 10) + read.append((char) buffer[i]); + } + } + conn.disconnect(); + retValue = Integer.parseInt(read.toString()); + if (retValue <= 0) + retValue = -1; + } + catch (Exception e) { // Report any errors that arise + System.err.println(e); + retValue = -1; + } + if (s_log.isLoggable(Level.INFO))s_log.log(Level.INFO, "getNextID_HTTP - " + TableName + "=" + read + "(" + retValue + ")"); + + return retValue; + } + + private static String [] dontUseCentralized = new String[] { + "AD_ACCESSLOG", + "AD_ALERTPROCESSORLOG", + "AD_CHANGELOG", + "AD_ISSUE", + "AD_LDAPPROCESSORLOG", + "AD_PACKAGE_IMP", + "AD_PACKAGE_IMP_BACKUP", + "AD_PACKAGE_IMP_DETAIL", + "AD_PACKAGE_IMP_INST", + "AD_PACKAGE_IMP_PROC", + "AD_PINSTANCE", + "AD_PINSTANCE_LOG", + "AD_PINSTANCE_PARA", + "AD_PREFERENCE", + "AD_RECENTITEM", + "AD_REPLICATION_LOG", + "AD_SCHEDULERLOG", + "AD_SESSION", + "AD_WORKFLOWPROCESSORLOG", + "CM_WEBACCESSLOG", + "C_ACCTPROCESSORLOG", + "K_INDEXLOG", + "R_REQUESTPROCESSORLOG", + "T_AGING", + "T_ALTER_COLUMN", + "T_DISTRIBUTIONRUNDETAIL", + "T_INVENTORYVALUE", + "T_INVOICEGL", + "T_REPLENISH", + "T_REPORT", + "T_REPORTSTATEMENT", + "T_SELECTION", + "T_SELECTION2", + "T_SPOOL", + "T_TRANSACTION", + "T_TRIALBALANCE" + }; + + private static boolean isExceptionCentralized(String tableName) { + + for (String exceptionTable : dontUseCentralized) { + if (tableName.equalsIgnoreCase(exceptionTable)) + return true; + } + + // don't log selects or insert/update for exception tables (i.e. AD_Issue, AD_ChangeLog) + return false; + } + + @Override + protected boolean beforeSave(boolean newRecord) { + if (isStartNewMonth() && !isStartNewYear()) + setStartNewMonth(false); + return true; + } + + /** + * Get preliminary document no by year + * @param tab + * @param AD_Sequence_ID + * @return Preliminary document no + */ + public static String getPreliminaryNo(GridTab tab, int AD_Sequence_ID) { + String prelim = null; + if (AD_Sequence_ID > 0) { + MSequence seq = new MSequence(Env.getCtx(), AD_Sequence_ID, null); + boolean startNewYear = seq.isStartNewYear(); + boolean startNewMonth = seq.isStartNewMonth(); + boolean orgLevelSeq = seq.isOrgLevelSequence(); + int currentNext = seq.getCurrentNext(); + if (startNewYear || orgLevelSeq) { + String cym = NoYearNorMonth; + int org = 0; + if (startNewYear || startNewMonth) { + Date d = (Date)tab.getValue(seq.getDateColumn()); + if (d == null) + d = new Date(); + SimpleDateFormat sdf = null; + if (startNewMonth) + sdf = new SimpleDateFormat("yyyyMM"); + else + sdf = new SimpleDateFormat("yyyy"); + cym = sdf.format(d); + } + if (orgLevelSeq) { + String orgColumn = seq.getOrgColumn(); + Object orgObj = tab.getValue(orgColumn); + if (orgObj != null) + org = (Integer)orgObj; + } + String sql = "SELECT CurrentNext FROM AD_Sequence_No WHERE AD_Sequence_ID=? AND CalendarYearMonth=? AND AD_Org_ID=?"; + currentNext = DB.getSQLValue(null, sql, AD_Sequence_ID, cym, org); + } + String decimalPattern = seq.getDecimalPattern(); + if (decimalPattern != null && decimalPattern.length() > 0) + prelim = new DecimalFormat(decimalPattern).format(currentNext); + else + prelim = String.valueOf(currentNext); + } + if (prelim == null) + prelim = "?"; + return "<" + prelim + ">"; + } + + @Override + public String getOrgColumn() { + if (super.getOrgColumn() == null) + return COLUMNNAME_AD_Org_ID; + else + return super.getOrgColumn(); + } + +} // MSequence diff --git a/org.adempiere.base/src/org/compiere/model/MWebProjectDomain.java b/org.adempiere.base/src/org/compiere/model/MWebProjectDomain.java index 1589a282f5..6fb89b2fb4 100644 --- a/org.adempiere.base/src/org/compiere/model/MWebProjectDomain.java +++ b/org.adempiere.base/src/org/compiere/model/MWebProjectDomain.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -15,32 +15,32 @@ * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.Properties; -import java.util.logging.Level; - -import org.compiere.util.CLogger; -import org.compiere.util.DB; - -/** - * Web Project Domain + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Properties; +import java.util.logging.Level; + +import org.compiere.util.CLogger; +import org.compiere.util.DB; + +/** + * Web Project Domain * * @author Jorg Janke * @version $Id: MWebProjectDomain.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $ - */ -public class MWebProjectDomain extends X_CM_WebProject_Domain -{ - /** serialVersionUID */ - private static final long serialVersionUID = 5134789895039452551L; - - /** Logger */ - private static CLogger s_log = CLogger.getCLogger (MContainer.class); - - /** - * Web Project Domain Constructor - * @param ctx context + */ +public class MWebProjectDomain extends X_CM_WebProject_Domain +{ + /** serialVersionUID */ + private static final long serialVersionUID = 5134789895039452551L; + + /** Logger */ + private static CLogger s_log = CLogger.getCLogger (MContainer.class); + + /** + * Web Project Domain Constructor + * @param ctx context * @param CM_WebProject_Domain_ID id * @param trxName transaction */ @@ -56,42 +56,42 @@ public class MWebProjectDomain extends X_CM_WebProject_Domain * @param trxName transaction */ public MWebProjectDomain (Properties ctx, ResultSet rs, String trxName) - { - super (ctx, rs, trxName); - } // MWebProjectDomain - - /** - * get WebProjectDomain by Name - * @param ctx - * @param ServerName - * @param trxName - * @return ContainerElement - */ - public static MWebProjectDomain get(Properties ctx, String ServerName, String trxName) { - MWebProjectDomain thisWebProjectDomain = null; - String sql = "SELECT * FROM CM_WebProject_Domain WHERE lower(FQDN) LIKE ? ORDER by CM_WebProject_Domain_ID DESC"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, trxName); - pstmt.setString(1, ServerName); - rs = pstmt.executeQuery(); - if (rs.next()) - thisWebProjectDomain = (new MWebProjectDomain(ctx, rs, trxName)); - } - catch (Exception e) - { - s_log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; - pstmt = null; - } - return thisWebProjectDomain; - } - - -} // MWebProjectDomain + { + super (ctx, rs, trxName); + } // MWebProjectDomain + + /** + * get WebProjectDomain by Name + * @param ctx + * @param ServerName + * @param trxName + * @return ContainerElement + */ + public static MWebProjectDomain get(Properties ctx, String ServerName, String trxName) { + MWebProjectDomain thisWebProjectDomain = null; + String sql = "SELECT * FROM CM_WebProject_Domain WHERE lower(FQDN) LIKE ? ORDER by CM_WebProject_Domain_ID DESC"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, trxName); + pstmt.setString(1, ServerName); + rs = pstmt.executeQuery(); + if (rs.next()) + thisWebProjectDomain = (new MWebProjectDomain(ctx, rs, trxName)); + } + catch (Exception e) + { + s_log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; + pstmt = null; + } + return thisWebProjectDomain; + } + + +} // MWebProjectDomain diff --git a/org.adempiere.base/src/org/compiere/model/M_Element.java b/org.adempiere.base/src/org/compiere/model/M_Element.java index e11c4b3269..ebf130aa7e 100644 --- a/org.adempiere.base/src/org/compiere/model/M_Element.java +++ b/org.adempiere.base/src/org/compiere/model/M_Element.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,14 +16,14 @@ *****************************************************************************/ package org.compiere.model; -import java.sql.ResultSet; -import java.util.Properties; -import java.util.logging.Level; - -import org.adempiere.exceptions.DBException; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.Msg; +import java.sql.ResultSet; +import java.util.Properties; +import java.util.logging.Level; + +import org.adempiere.exceptions.DBException; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Msg; /** @@ -31,103 +31,103 @@ import org.compiere.util.Msg; * * @author Jorg Janke * @version $Id: M_Element.java,v 1.3 2006/07/30 00:58:37 jjanke Exp $ - * FR: [ 2214883 ] Remove SQL code and Replace for Query - red1, teo_sarca + * FR: [ 2214883 ] Remove SQL code and Replace for Query - red1, teo_sarca */ public class M_Element extends X_AD_Element -{ - - /** - * - */ - private static final long serialVersionUID = -6644398794862560030L; - - /** - * Get case sensitive Column Name - * @param columnName case insensitive column name - * @return case sensitive column name - */ - public static String getColumnName (String columnName) - { - return getColumnName(columnName, null); - } +{ + + /** + * + */ + private static final long serialVersionUID = -6644398794862560030L; + + /** + * Get case sensitive Column Name + * @param columnName case insensitive column name + * @return case sensitive column name + */ + public static String getColumnName (String columnName) + { + return getColumnName(columnName, null); + } /** * Get case sensitive Column Name - * @param columnName case insensitive column name + * @param columnName case insensitive column name * @param trxName optional transaction name * @return case sensitive column name */ public static String getColumnName (String columnName, String trxName) { if (columnName == null || columnName.length() == 0) - return columnName; - M_Element element = get(Env.getCtx(), columnName, trxName); - if (element == null) - return columnName; - return element.getColumnName(); + return columnName; + M_Element element = get(Env.getCtx(), columnName, trxName); + if (element == null) + return columnName; + return element.getColumnName(); } // getColumnName - - /** - * Get Element - * @param ctx context - * @param columnName case insensitive column name - * @return case sensitive column name - */ - public static M_Element get (Properties ctx, String columnName) - { - return get(ctx, columnName, null); - } + + /** + * Get Element + * @param ctx context + * @param columnName case insensitive column name + * @return case sensitive column name + */ + public static M_Element get (Properties ctx, String columnName) + { + return get(ctx, columnName, null); + } /** * Get Element * @param ctx context - * @param columnName case insensitive column name + * @param columnName case insensitive column name * @param trxName optional transaction name * @return case sensitive column name */ public static M_Element get (Properties ctx, String columnName, String trxName) { if (columnName == null || columnName.length() == 0) - return null; - // - // TODO: caching if trxName == null - final String whereClause = "UPPER(ColumnName)=?"; - M_Element retValue = new Query(ctx, I_AD_Element.Table_Name, whereClause, trxName) - .setParameters(columnName.toUpperCase()) - .firstOnly(); + return null; + // + // TODO: caching if trxName == null + final String whereClause = "UPPER(ColumnName)=?"; + M_Element retValue = new Query(ctx, I_AD_Element.Table_Name, whereClause, trxName) + .setParameters(columnName.toUpperCase()) + .firstOnly(); return retValue; } // get - /** - * Get Element - * @param ctx context - * @param columnName case insensitive column name + /** + * Get Element + * @param ctx context + * @param columnName case insensitive column name * @param trxName trx - * @return case sensitive column name - */ - public static M_Element getOfColumn (Properties ctx, int AD_Column_ID, String trxName) - { - if (AD_Column_ID ==0) - return null; - final String whereClause = "EXISTS (SELECT 1 FROM AD_Column c " - + "WHERE c.AD_Element_ID=AD_Element.AD_Element_ID AND c.AD_Column_ID=?)"; - M_Element retValue = new Query(ctx, Table_Name, whereClause, trxName) - .setParameters(AD_Column_ID) - .firstOnly(); - return retValue; - } // get + * @return case sensitive column name + */ + public static M_Element getOfColumn (Properties ctx, int AD_Column_ID, String trxName) + { + if (AD_Column_ID ==0) + return null; + final String whereClause = "EXISTS (SELECT 1 FROM AD_Column c " + + "WHERE c.AD_Element_ID=AD_Element.AD_Element_ID AND c.AD_Column_ID=?)"; + M_Element retValue = new Query(ctx, Table_Name, whereClause, trxName) + .setParameters(AD_Column_ID) + .firstOnly(); + return retValue; + } // get - /** - * Get Element - * @param ctx context - * @param columnName case insentitive column name - * @return case sensitive column name - */ - public static M_Element getOfColumn (Properties ctx, int AD_Column_ID) - { - return getOfColumn(ctx, AD_Column_ID, null); - } // get + /** + * Get Element + * @param ctx context + * @param columnName case insentitive column name + * @return case sensitive column name + */ + public static M_Element getOfColumn (Properties ctx, int AD_Column_ID) + { + return getOfColumn(ctx, AD_Column_ID, null); + } // get /************************************************************************** * Standard Constructor @@ -177,30 +177,30 @@ public class M_Element extends X_AD_Element } // M_Element - /* (non-Javadoc) - * @see org.compiere.model.PO#beforeSave(boolean) - */ - @Override - protected boolean beforeSave(boolean newRecord) { - // Column AD_Element.ColumnName should be unique - teo_sarca [ 1613107 ] - if (newRecord || is_ValueChanged(COLUMNNAME_ColumnName)) { - String columnName = getColumnName().trim(); - if (getColumnName().length() != columnName.length()) - setColumnName(columnName); - - StringBuilder sql = new StringBuilder("select count(*) from AD_Element where UPPER(ColumnName)=?"); - if (!newRecord) - sql.append(" AND AD_Element_ID<>").append(get_ID()); - int no = DB.getSQLValue(null, sql.toString(), columnName.toUpperCase()); - if (no > 0) { - log.saveError(DBException.SAVE_ERROR_NOT_UNIQUE_MSG, Msg.getElement(getCtx(), COLUMNNAME_ColumnName)); - return false; - } - } - - return true; - } - + /* (non-Javadoc) + * @see org.compiere.model.PO#beforeSave(boolean) + */ + @Override + protected boolean beforeSave(boolean newRecord) { + // Column AD_Element.ColumnName should be unique - teo_sarca [ 1613107 ] + if (newRecord || is_ValueChanged(COLUMNNAME_ColumnName)) { + String columnName = getColumnName().trim(); + if (getColumnName().length() != columnName.length()) + setColumnName(columnName); + + StringBuilder sql = new StringBuilder("select count(*) from AD_Element where UPPER(ColumnName)=?"); + if (!newRecord) + sql.append(" AND AD_Element_ID<>").append(get_ID()); + int no = DB.getSQLValue(null, sql.toString(), columnName.toUpperCase()); + if (no > 0) { + log.saveError(DBException.SAVE_ERROR_NOT_UNIQUE_MSG, Msg.getElement(getCtx(), COLUMNNAME_ColumnName)); + return false; + } + } + + return true; + } + /** * After Save * @param newRecord new @@ -208,118 +208,118 @@ public class M_Element extends X_AD_Element * @return success */ protected boolean afterSave (boolean newRecord, boolean success) - { - if (!success) - return success; + { + if (!success) + return success; // Update Columns, Fields, Parameters, Print Info if (!newRecord) - { - StringBuilder sql = new StringBuilder(); - int no = 0; + { + StringBuilder sql = new StringBuilder(); + int no = 0; - if ( is_ValueChanged(M_Element.COLUMNNAME_Name) - || is_ValueChanged(M_Element.COLUMNNAME_Description) - || is_ValueChanged(M_Element.COLUMNNAME_Help) - || is_ValueChanged(M_Element.COLUMNNAME_Placeholder) - || is_ValueChanged(M_Element.COLUMNNAME_ColumnName) - ) { - // Column - sql = new StringBuilder("UPDATE AD_Column SET ColumnName=") - .append(DB.TO_STRING(getColumnName())) - .append(", Name=").append(DB.TO_STRING(getName())) - .append(", Description=").append(DB.TO_STRING(getDescription())) - .append(", Help=").append(DB.TO_STRING(getHelp())) - .append(", Placeholder=").append(DB.TO_STRING(getPlaceholder())) - .append(" WHERE AD_Element_ID=").append(get_ID()); - no = DB.executeUpdate(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("afterSave - Columns updated #" + no); - - // Parameter - sql = new StringBuilder("UPDATE AD_Process_Para SET ColumnName=") - .append(DB.TO_STRING(getColumnName())) - .append(", Name=").append(DB.TO_STRING(getName())) - .append(", Description=").append(DB.TO_STRING(getDescription())) - .append(", Help=").append(DB.TO_STRING(getHelp())) - .append(", AD_Element_ID=").append(get_ID()) - .append(" WHERE UPPER(ColumnName)=") - .append(DB.TO_STRING(getColumnName().toUpperCase())) - .append(" AND IsCentrallyMaintained='Y' AND AD_Element_ID IS NULL"); - no = DB.executeUpdate(sql.toString(), get_TrxName()); - - sql = new StringBuilder("UPDATE AD_Process_Para SET ColumnName=") - .append(DB.TO_STRING(getColumnName())) - .append(", Name=").append(DB.TO_STRING(getName())) - .append(", Description=").append(DB.TO_STRING(getDescription())) - .append(", Help=").append(DB.TO_STRING(getHelp())) - .append(", Placeholder=").append(DB.TO_STRING(getPlaceholder())) - .append(" WHERE AD_Element_ID=").append(get_ID()) - .append(" AND IsCentrallyMaintained='Y'"); - no += DB.executeUpdate(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Parameters updated #" + no); - - // Info Column - sql = new StringBuilder("UPDATE AD_InfoColumn SET ColumnName=") - .append(DB.TO_STRING(getColumnName())) - .append(", Name=").append(DB.TO_STRING(getName())) - .append(", Description=").append(DB.TO_STRING(getDescription())) - .append(", Help=").append(DB.TO_STRING(getHelp())) - .append(", Placeholder=").append(DB.TO_STRING(getPlaceholder())) - .append(" WHERE AD_Element_ID=").append(get_ID()) - .append(" AND IsCentrallyMaintained='Y'"); - no += DB.executeUpdate(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Info Column updated #" + no); - } + if ( is_ValueChanged(M_Element.COLUMNNAME_Name) + || is_ValueChanged(M_Element.COLUMNNAME_Description) + || is_ValueChanged(M_Element.COLUMNNAME_Help) + || is_ValueChanged(M_Element.COLUMNNAME_Placeholder) + || is_ValueChanged(M_Element.COLUMNNAME_ColumnName) + ) { + // Column + sql = new StringBuilder("UPDATE AD_Column SET ColumnName=") + .append(DB.TO_STRING(getColumnName())) + .append(", Name=").append(DB.TO_STRING(getName())) + .append(", Description=").append(DB.TO_STRING(getDescription())) + .append(", Help=").append(DB.TO_STRING(getHelp())) + .append(", Placeholder=").append(DB.TO_STRING(getPlaceholder())) + .append(" WHERE AD_Element_ID=").append(get_ID()); + no = DB.executeUpdate(sql.toString(), get_TrxName()); + if (log.isLoggable(Level.FINE)) log.fine("afterSave - Columns updated #" + no); + + // Parameter + sql = new StringBuilder("UPDATE AD_Process_Para SET ColumnName=") + .append(DB.TO_STRING(getColumnName())) + .append(", Name=").append(DB.TO_STRING(getName())) + .append(", Description=").append(DB.TO_STRING(getDescription())) + .append(", Help=").append(DB.TO_STRING(getHelp())) + .append(", AD_Element_ID=").append(get_ID()) + .append(" WHERE UPPER(ColumnName)=") + .append(DB.TO_STRING(getColumnName().toUpperCase())) + .append(" AND IsCentrallyMaintained='Y' AND AD_Element_ID IS NULL"); + no = DB.executeUpdate(sql.toString(), get_TrxName()); + + sql = new StringBuilder("UPDATE AD_Process_Para SET ColumnName=") + .append(DB.TO_STRING(getColumnName())) + .append(", Name=").append(DB.TO_STRING(getName())) + .append(", Description=").append(DB.TO_STRING(getDescription())) + .append(", Help=").append(DB.TO_STRING(getHelp())) + .append(", Placeholder=").append(DB.TO_STRING(getPlaceholder())) + .append(" WHERE AD_Element_ID=").append(get_ID()) + .append(" AND IsCentrallyMaintained='Y'"); + no += DB.executeUpdate(sql.toString(), get_TrxName()); + if (log.isLoggable(Level.FINE)) log.fine("Parameters updated #" + no); + + // Info Column + sql = new StringBuilder("UPDATE AD_InfoColumn SET ColumnName=") + .append(DB.TO_STRING(getColumnName())) + .append(", Name=").append(DB.TO_STRING(getName())) + .append(", Description=").append(DB.TO_STRING(getDescription())) + .append(", Help=").append(DB.TO_STRING(getHelp())) + .append(", Placeholder=").append(DB.TO_STRING(getPlaceholder())) + .append(" WHERE AD_Element_ID=").append(get_ID()) + .append(" AND IsCentrallyMaintained='Y'"); + no += DB.executeUpdate(sql.toString(), get_TrxName()); + if (log.isLoggable(Level.FINE)) log.fine("Info Column updated #" + no); + } - if ( is_ValueChanged(M_Element.COLUMNNAME_Name) - || is_ValueChanged(M_Element.COLUMNNAME_Description) - || is_ValueChanged(M_Element.COLUMNNAME_Help) - || is_ValueChanged(M_Element.COLUMNNAME_Placeholder) - ) { - // Field - sql = new StringBuilder("UPDATE AD_Field SET Name=") - .append(DB.TO_STRING(getName())) - .append(", Description=").append(DB.TO_STRING(getDescription())) - .append(", Help=").append(DB.TO_STRING(getHelp())) - .append(", Placeholder=").append(DB.TO_STRING(getPlaceholder())) - .append(" WHERE AD_Column_ID IN (SELECT AD_Column_ID FROM AD_Column WHERE AD_Element_ID=") - .append(get_ID()) - .append(") AND IsCentrallyMaintained='Y'"); - no = DB.executeUpdate(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("Fields updated #" + no); - - // Info Column - update Name, Description, Help - doesn't have IsCentrallyMaintained currently - // no = DB.executeUpdate(sql.toString(), get_TrxName()); - // log.fine("InfoColumn updated #" + no); - } - - if ( is_ValueChanged(M_Element.COLUMNNAME_PrintName) - || is_ValueChanged(M_Element.COLUMNNAME_Name) - ) { - // Print Info - sql = new StringBuilder("UPDATE AD_PrintFormatItem SET PrintName=") - .append(DB.TO_STRING(getPrintName())) - .append(", Name=").append(DB.TO_STRING(getName())) - .append(" WHERE IsCentrallyMaintained='Y'") - .append(" AND EXISTS (SELECT * FROM AD_Column c ") - .append("WHERE c.AD_Column_ID=AD_PrintFormatItem.AD_Column_ID AND c.AD_Element_ID=") - .append(get_ID()).append(")"); - no = DB.executeUpdate(sql.toString(), get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine("PrintFormatItem updated #" + no); - } - - } - return success; - } // afterSave + if ( is_ValueChanged(M_Element.COLUMNNAME_Name) + || is_ValueChanged(M_Element.COLUMNNAME_Description) + || is_ValueChanged(M_Element.COLUMNNAME_Help) + || is_ValueChanged(M_Element.COLUMNNAME_Placeholder) + ) { + // Field + sql = new StringBuilder("UPDATE AD_Field SET Name=") + .append(DB.TO_STRING(getName())) + .append(", Description=").append(DB.TO_STRING(getDescription())) + .append(", Help=").append(DB.TO_STRING(getHelp())) + .append(", Placeholder=").append(DB.TO_STRING(getPlaceholder())) + .append(" WHERE AD_Column_ID IN (SELECT AD_Column_ID FROM AD_Column WHERE AD_Element_ID=") + .append(get_ID()) + .append(") AND IsCentrallyMaintained='Y'"); + no = DB.executeUpdate(sql.toString(), get_TrxName()); + if (log.isLoggable(Level.FINE)) log.fine("Fields updated #" + no); + + // Info Column - update Name, Description, Help - doesn't have IsCentrallyMaintained currently + // no = DB.executeUpdate(sql.toString(), get_TrxName()); + // log.fine("InfoColumn updated #" + no); + } + + if ( is_ValueChanged(M_Element.COLUMNNAME_PrintName) + || is_ValueChanged(M_Element.COLUMNNAME_Name) + ) { + // Print Info + sql = new StringBuilder("UPDATE AD_PrintFormatItem SET PrintName=") + .append(DB.TO_STRING(getPrintName())) + .append(", Name=").append(DB.TO_STRING(getName())) + .append(" WHERE IsCentrallyMaintained='Y'") + .append(" AND EXISTS (SELECT * FROM AD_Column c ") + .append("WHERE c.AD_Column_ID=AD_PrintFormatItem.AD_Column_ID AND c.AD_Element_ID=") + .append(get_ID()).append(")"); + no = DB.executeUpdate(sql.toString(), get_TrxName()); + if (log.isLoggable(Level.FINE)) log.fine("PrintFormatItem updated #" + no); + } + + } + return success; + } // afterSave + + /** + * String Representation + * @return info + */ + public String toString() + { + StringBuilder sb = new StringBuilder ("M_Element["); + sb.append (get_ID()).append ("-").append (getColumnName()).append ("]"); + return sb.toString (); + } // toString - /** - * String Representation - * @return info - */ - public String toString() - { - StringBuilder sb = new StringBuilder ("M_Element["); - sb.append (get_ID()).append ("-").append (getColumnName()).append ("]"); - return sb.toString (); - } // toString - } // M_Element diff --git a/org.adempiere.base/src/org/compiere/model/TranslationTable.java b/org.adempiere.base/src/org/compiere/model/TranslationTable.java index dc8611cbbc..ef38349d5b 100644 --- a/org.adempiere.base/src/org/compiere/model/TranslationTable.java +++ b/org.adempiere.base/src/org/compiere/model/TranslationTable.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,13 +16,13 @@ *****************************************************************************/ package org.compiere.model; -import java.util.ArrayList; -import java.util.logging.Level; - -import org.compiere.util.CCache; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; +import java.util.ArrayList; +import java.util.logging.Level; + +import org.compiere.util.CCache; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; /** * Translation Table Management @@ -120,7 +120,7 @@ public class TranslationTable m_baseTableName = baseTableName; m_trlTableName = baseTableName + "_Trl"; initColumns(); - if (log.isLoggable(Level.FINE)) log.fine(toString()); + if (log.isLoggable(Level.FINE)) log.fine(toString()); } // TranslationTable /** Static Logger */ @@ -195,13 +195,13 @@ public class TranslationTable sql2.append(",b.").append(columnName); } // - StringBuilder sql = new StringBuilder(); + StringBuilder sql = new StringBuilder(); sql.append(sql1).append(sql2) .append(" FROM AD_Language l, " + m_baseTableName + " b WHERE l.IsActive = 'Y' AND l.IsSystemLanguage = 'Y' AND b." + m_baseTableName + "_ID=").append(po.get_ID()); int no = DB.executeUpdate(sql.toString(), po.get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine(m_trlTableName + ": ID=" + po.get_ID() + " #" + no); + if (log.isLoggable(Level.FINE)) log.fine(m_trlTableName + ": ID=" + po.get_ID() + " #" + no); return no != 0; } // createTranslation @@ -217,12 +217,12 @@ public class TranslationTable if (po.get_ID() == 0) throw new IllegalArgumentException("PO ID is 0"); // - StringBuilder sb = new StringBuilder("UPDATE "); + StringBuilder sb = new StringBuilder("UPDATE "); sb.append(m_trlTableName) .append(" SET IsTranslated='N',Updated=SysDate WHERE ") .append(m_baseTableName).append("_ID=").append(po.get_ID()); int no = DB.executeUpdate(sb.toString(), po.get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine(m_trlTableName + ": ID=" + po.get_ID() + " #" + no); + if (log.isLoggable(Level.FINE)) log.fine(m_trlTableName + ": ID=" + po.get_ID() + " #" + no); return no != 0; } // resetTranslationFlag @@ -235,15 +235,15 @@ public class TranslationTable { if (!isActiveLanguages(false)) return true; - if (po.get_IDOld() == 0) - throw new IllegalArgumentException("PO Old ID is 0"); - // - StringBuilder sb = new StringBuilder("DELETE FROM "); - sb.append(m_trlTableName) - .append(" WHERE ") - .append(m_baseTableName).append("_ID=").append(po.get_IDOld()); + if (po.get_IDOld() == 0) + throw new IllegalArgumentException("PO Old ID is 0"); + // + StringBuilder sb = new StringBuilder("DELETE FROM "); + sb.append(m_trlTableName) + .append(" WHERE ") + .append(m_baseTableName).append("_ID=").append(po.get_IDOld()); int no = DB.executeUpdate(sb.toString(), po.get_TrxName()); - if (log.isLoggable(Level.FINE)) log.fine(m_trlTableName + ": ID=" + po.get_IDOld() + " #" + no); + if (log.isLoggable(Level.FINE)) log.fine(m_trlTableName + ": ID=" + po.get_IDOld() + " #" + no); return no != 0; } // resetTranslationFlag @@ -253,7 +253,7 @@ public class TranslationTable */ public String toString () { - StringBuilder sb = new StringBuilder ("TranslationTable["); + StringBuilder sb = new StringBuilder ("TranslationTable["); sb.append(m_trlTableName) .append("(").append(m_baseTableName).append(")"); for (int i = 0; i < m_columns.size(); i++) diff --git a/org.adempiere.base/src/org/compiere/print/DataEngine.java b/org.adempiere.base/src/org/compiere/print/DataEngine.java index 082ab78689..0e19747aa2 100644 --- a/org.adempiere.base/src/org/compiere/print/DataEngine.java +++ b/org.adempiere.base/src/org/compiere/print/DataEngine.java @@ -1,1236 +1,1236 @@ -/****************************************************************************** - * 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.compiere.print; - -import java.io.Serializable; -import java.sql.Clob; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Properties; -import java.util.logging.Level; -import java.util.regex.Pattern; - -import org.adempiere.exceptions.AdempiereException; -import org.compiere.model.MLookupFactory; -import org.compiere.model.MQuery; -import org.compiere.model.MRole; -import org.compiere.model.MTable; -import org.compiere.util.CLogMgt; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.DisplayType; -import org.compiere.util.Env; -import org.compiere.util.Ini; -import org.compiere.util.KeyNamePair; -import org.compiere.util.Language; -import org.compiere.util.Msg; -import org.compiere.util.Util; -import org.compiere.util.ValueNamePair; - -/** - * Data Engine. - * Creates SQL and laods data into PrintData (including totals/etc.) - * - * @author Jorg Janke - * @version $Id: DataEngine.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $ - * - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - *
  • BF [ 1761891 ] Included print format with report view attached issue - *
  • BF [ 1807368 ] DataEngine does not close DB connection - *
  • BF [ 2549128 ] Report View Column not working at all - *
  • BF [ 2865545 ] Error if not all parts of multikey are lookups - * https://sourceforge.net/tracker/?func=detail&aid=2865545&group_id=176962&atid=879332 - * @author Teo Sarca, teo.sarca@gmail.com - *
  • BF [ 2876268 ] DataEngine: error on text long fields - * https://sourceforge.net/tracker/?func=detail&aid=2876268&group_id=176962&atid=879332 - * @author victor.perez@e-evolution.com - *
  • FR [ 2011569 ] Implementing new Summary flag in Report View http://sourceforge.net/tracker/index.php?func=detail&aid=2011569&group_id=176962&atid=879335 - * @author Paul Bowden (phib) - *
  • BF 2908435 Virtual columns with lookup reference types can't be printed - * https://sourceforge.net/tracker/?func=detail&aid=2908435&group_id=176962&atid=879332 - * @contributor Fernandinho (FAIRE) - * - http://jira.idempiere.com/browse/IDEMPIERE-153 - */ -public class DataEngine -{ - /** - * Constructor - * @param language Language of the data (for translation) - */ - public DataEngine (Language language) - { - this(language, null); - } // DataEngine - - /** - * Constructor - * @param language Language of the data (for translation) - * @param trxName - */ - public DataEngine (Language language, String trxName){ - if (language != null) - m_language = language; - m_trxName = trxName; - } // DataEngine - - /** Logger */ - private static CLogger log = CLogger.getCLogger (DataEngine.class); - - /** Synonym */ - private String m_synonym = "A"; - - /** Default Language */ - private Language m_language = Language.getLoginLanguage(); - /** Break & Column Functions */ - private PrintDataGroup m_group = new PrintDataGroup(); - /** Start Time */ - private long m_startTime = System.currentTimeMillis(); - /** Running Total after .. lines */ - private int m_runningTotalLines = -1; - /** Print String */ - @SuppressWarnings("unused") - private String m_runningTotalString = null; - /** TrxName String */ +/****************************************************************************** + * 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.compiere.print; + +import java.io.Serializable; +import java.sql.Clob; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Properties; +import java.util.logging.Level; +import java.util.regex.Pattern; + +import org.adempiere.exceptions.AdempiereException; +import org.compiere.model.MLookupFactory; +import org.compiere.model.MQuery; +import org.compiere.model.MRole; +import org.compiere.model.MTable; +import org.compiere.util.CLogMgt; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.DisplayType; +import org.compiere.util.Env; +import org.compiere.util.Ini; +import org.compiere.util.KeyNamePair; +import org.compiere.util.Language; +import org.compiere.util.Msg; +import org.compiere.util.Util; +import org.compiere.util.ValueNamePair; + +/** + * Data Engine. + * Creates SQL and laods data into PrintData (including totals/etc.) + * + * @author Jorg Janke + * @version $Id: DataEngine.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $ + * + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1761891 ] Included print format with report view attached issue + *
  • BF [ 1807368 ] DataEngine does not close DB connection + *
  • BF [ 2549128 ] Report View Column not working at all + *
  • BF [ 2865545 ] Error if not all parts of multikey are lookups + * https://sourceforge.net/tracker/?func=detail&aid=2865545&group_id=176962&atid=879332 + * @author Teo Sarca, teo.sarca@gmail.com + *
  • BF [ 2876268 ] DataEngine: error on text long fields + * https://sourceforge.net/tracker/?func=detail&aid=2876268&group_id=176962&atid=879332 + * @author victor.perez@e-evolution.com + *
  • FR [ 2011569 ] Implementing new Summary flag in Report View http://sourceforge.net/tracker/index.php?func=detail&aid=2011569&group_id=176962&atid=879335 + * @author Paul Bowden (phib) + *
  • BF 2908435 Virtual columns with lookup reference types can't be printed + * https://sourceforge.net/tracker/?func=detail&aid=2908435&group_id=176962&atid=879332 + * @contributor Fernandinho (FAIRE) + * - http://jira.idempiere.com/browse/IDEMPIERE-153 + */ +public class DataEngine +{ + /** + * Constructor + * @param language Language of the data (for translation) + */ + public DataEngine (Language language) + { + this(language, null); + } // DataEngine + + /** + * Constructor + * @param language Language of the data (for translation) + * @param trxName + */ + public DataEngine (Language language, String trxName){ + if (language != null) + m_language = language; + m_trxName = trxName; + } // DataEngine + + /** Logger */ + private static CLogger log = CLogger.getCLogger (DataEngine.class); + + /** Synonym */ + private String m_synonym = "A"; + + /** Default Language */ + private Language m_language = Language.getLoginLanguage(); + /** Break & Column Functions */ + private PrintDataGroup m_group = new PrintDataGroup(); + /** Start Time */ + private long m_startTime = System.currentTimeMillis(); + /** Running Total after .. lines */ + private int m_runningTotalLines = -1; + /** Print String */ + @SuppressWarnings("unused") + private String m_runningTotalString = null; + /** TrxName String */ private String m_trxName = null; - /** Report Summary FR [ 2011569 ]**/ + /** Report Summary FR [ 2011569 ]**/ private boolean m_summary = false; - /** Key Indicator in Report */ - public static final String KEY = "*"; - - - /************************************************************************** - * Load Data - * - * @param format print format - * @param query query - * @param ctx context - * @return PrintData or null - */ - public PrintData getPrintData (Properties ctx, MPrintFormat format, MQuery query) - { - return getPrintData(ctx, format, query, false); - } - - /************************************************************************** - * Load Data - * - * @param format print format - * @param query query - * @param ctx context - * @param summary - * @return PrintData or null - */ - public PrintData getPrintData (Properties ctx, MPrintFormat format, MQuery query, boolean summary) - { - MQuery queryCopy = query.deepCopy(); + /** Key Indicator in Report */ + public static final String KEY = "*"; - /** Report Summary FR [ 2011569 ]**/ - m_summary = summary; - if (format == null) - throw new IllegalStateException ("No print format"); - - if (format.getJasperProcess_ID() > 0) - return null; - - String tableName = null; - String reportName = format.getName(); - // - if (format.getAD_ReportView_ID() != 0) - { - StringBuilder sql = new StringBuilder("SELECT t.AD_Table_ID, t.TableName, rv.Name, rv.WhereClause ") - .append("FROM AD_Table t") - .append(" INNER JOIN AD_ReportView rv ON (t.AD_Table_ID=rv.AD_Table_ID) ") - .append("WHERE rv.AD_ReportView_ID=?"); // 1 - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql.toString(), m_trxName); - pstmt.setInt(1, format.getAD_ReportView_ID()); - rs = pstmt.executeQuery(); - if (rs.next()) - { - tableName = rs.getString(2); // TableName - reportName = rs.getString(3); - // Add WhereClause restriction from AD_ReportView - teo_sarca BF [ 1761891 ] - String whereClause = rs.getString(4); - if (!Util.isEmpty(whereClause)) { - whereClause = "(" + whereClause + ")"; // IDEMPIERE-2597 - if (whereClause.indexOf("@") == -1) { - queryCopy.addRestriction(whereClause); - } else { // replace context variables - queryCopy.addRestriction(Env.parseContext(ctx, 0, whereClause.toString(), false, true)); - } - } - } - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql.toString(), e); - return null; - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - } - else - { - tableName = MTable.getTableName(ctx, format.getAD_Table_ID()); - } - if (tableName == null) - { - log.log(Level.SEVERE, "Not found Format=" + format); - return null; - } - if (format.isTranslationView() && tableName.toLowerCase().endsWith("_v")) // _vt not just _v - { - boolean hasVT = DB.isTableOrViewExists(tableName+"t"); - if (hasVT) - { - tableName += "t"; - format.setTranslationViewQuery (queryCopy); - } - } - // - PrintData pd = getPrintDataInfo (ctx, format, queryCopy, reportName, tableName); - if (pd == null) - return null; - loadPrintData(pd, format); - return pd; - } // getPrintData - - - /************************************************************************** - * Create Load SQL and update PrintData Info - * - * @param ctx context - * @param format print format - * @param query query - * @param reportName report name - * @param tableName table name - * @return PrintData or null - */ - private PrintData getPrintDataInfo (Properties ctx, MPrintFormat format, MQuery query, - String reportName, String tableName) - { - m_startTime = System.currentTimeMillis(); - if (log.isLoggable(Level.INFO)) log.info(reportName + " - " + m_language.getAD_Language()); - if (log.isLoggable(Level.FINE)) - { - log.fine("TableName=" + tableName + ", Query=" + query); - log.fine("Format=" + format); - } - ArrayList columns = new ArrayList(); - m_group = new PrintDataGroup(); - - // Order Columns (identified by non zero/null SortNo) - int[] orderAD_Column_IDs = format.getOrderAD_Column_IDs(); - ArrayList orderColumns = new ArrayList(orderAD_Column_IDs.length); - for (int i = 0; i < orderAD_Column_IDs.length; i++) - { - if (log.isLoggable(Level.FINEST)) log.finest("Order AD_Column_ID=" + orderAD_Column_IDs[i]); - orderColumns.add(""); // initial value overwritten with fully qualified name - } - - // Direct SQL w/o Reference Info - StringBuilder sqlSELECT = new StringBuilder("SELECT "); - StringBuilder sqlFROM = new StringBuilder(" FROM ").append(tableName); - ArrayList groupByColumns = new ArrayList(); - // - boolean IsGroupedBy = false; - // - StringBuilder sql = new StringBuilder("SELECT c.AD_Column_ID,c.ColumnName,") // 1..2 - .append("c.AD_Reference_ID,c.AD_Reference_Value_ID,") // 3..4 - .append("c.FieldLength,c.IsMandatory,c.IsKey,c.IsParent,") // 5..8 - .append("COALESCE(rvc.IsGroupFunction,'N'),rvc.FunctionColumn,") // 9..10 - .append("pfi.IsGroupBy,pfi.IsSummarized,pfi.IsAveraged,pfi.IsCounted, ") // 11..14 - .append("pfi.IsPrinted,pfi.SortNo,pfi.IsPageBreak, ") // 15..17 - .append("pfi.IsMinCalc,pfi.IsMaxCalc, ") // 18..19 - .append("pfi.isRunningTotal,pfi.RunningTotalLines, ") // 20..21 - .append("pfi.IsVarianceCalc, pfi.IsDeviationCalc, ") // 22..23 - .append("c.ColumnSQL, COALESCE(pfi.FormatPattern, c.FormatPattern) ") // 24, 25 - //BEGIN http://jira.idempiere.com/browse/IDEMPIERE-153 - .append(" , pfi.isDesc ") //26 - //END - .append("FROM AD_PrintFormat pf") - .append(" INNER JOIN AD_PrintFormatItem pfi ON (pf.AD_PrintFormat_ID=pfi.AD_PrintFormat_ID)") - .append(" INNER JOIN AD_Column c ON (pfi.AD_Column_ID=c.AD_Column_ID)") - .append(" LEFT OUTER JOIN AD_ReportView_Col rvc ON (pf.AD_ReportView_ID=rvc.AD_ReportView_ID AND c.AD_Column_ID=rvc.AD_Column_ID) ") - .append("WHERE pf.AD_PrintFormat_ID=?") // #1 - .append(" AND pfi.IsActive='Y' AND (pfi.IsPrinted='Y' OR c.IsKey='Y' OR pfi.SortNo > 0) ") - .append(" AND pfi.PrintFormatType IN ('" - + MPrintFormatItem.PRINTFORMATTYPE_Field - + "','" - + MPrintFormatItem.PRINTFORMATTYPE_Image - + "','" - + MPrintFormatItem.PRINTFORMATTYPE_PrintFormat - + "') ") - .append("ORDER BY pfi.IsPrinted DESC, pfi.SeqNo"); // Functions are put in first column - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql.toString(), m_trxName); - pstmt.setInt(1, format.get_ID()); - rs = pstmt.executeQuery(); - - m_synonym = "A"; // synonym - - // init regular object to replace table name in virtual column - String orgTable = null; - Pattern regTranslateTable = null; - if (tableName.toLowerCase().endsWith("_vt")){ - orgTable = MTable.getTableName(ctx, format.getAD_Table_ID()); - regTranslateTable = Pattern.compile("\\b" + orgTable + "\\b", Pattern.CASE_INSENSITIVE); - } - - while (rs.next()) - { - // get Values from record - int AD_Column_ID = rs.getInt(1); - String ColumnName = rs.getString(2); - String ColumnSQL = rs.getString(24); - if (ColumnSQL != null && ColumnSQL.length() > 0 && ColumnSQL.startsWith("@SQL=")) - ColumnSQL = "NULL"; - if (ColumnSQL != null && ColumnSQL.contains("@")) - ColumnSQL = Env.parseContext(Env.getCtx(), -1, ColumnSQL, false, true); - if (ColumnSQL == null) - ColumnSQL = ""; - else{ - // replace table with translate table IDEMPIERE-2234 - if (tableName.toLowerCase().endsWith("_vt")){ - ColumnSQL = regTranslateTable.matcher(ColumnSQL).replaceAll(tableName); - } - } - int AD_Reference_ID = rs.getInt(3); - int AD_Reference_Value_ID = rs.getInt(4); - // ColumnInfo - int FieldLength = rs.getInt(5); - boolean IsMandatory = "Y".equals(rs.getString(6)); - boolean IsKey = "Y".equals(rs.getString(7)); - //boolean IsParent = "Y".equals(rs.getString(8)); - // SQL GroupBy - boolean IsGroupFunction = "Y".equals(rs.getString(9)); - if (IsGroupFunction) - IsGroupedBy = true; - String FunctionColumn = rs.getString(10); - if (FunctionColumn == null) - FunctionColumn = ""; - // Breaks/Column Functions - if ("Y".equals(rs.getString(11))) - m_group.addGroupColumn(ColumnName); - if ("Y".equals(rs.getString(12))) - m_group.addFunction(ColumnName, PrintDataFunction.F_SUM); - if ("Y".equals(rs.getString(13))) - m_group.addFunction(ColumnName, PrintDataFunction.F_MEAN); - if ("Y".equals(rs.getString(14))) - m_group.addFunction(ColumnName, PrintDataFunction.F_COUNT); - if ("Y".equals(rs.getString(18))) // IsMinCalc - m_group.addFunction(ColumnName, PrintDataFunction.F_MIN); - if ("Y".equals(rs.getString(19))) // IsMaxCalc - m_group.addFunction(ColumnName, PrintDataFunction.F_MAX); - if ("Y".equals(rs.getString(22))) // IsVarianceCalc - m_group.addFunction(ColumnName, PrintDataFunction.F_VARIANCE); - if ("Y".equals(rs.getString(23))) // IsDeviationCalc - m_group.addFunction(ColumnName, PrintDataFunction.F_DEVIATION); - if ("Y".equals(rs.getString(20))) // isRunningTotal - // RunningTotalLines only once - use max - m_runningTotalLines = Math.max(m_runningTotalLines, rs.getInt(21)); - - // General Info - boolean IsPrinted = "Y".equals(rs.getString(15)); - //int SortNo = rs.getInt(16); - boolean isPageBreak = "Y".equals(rs.getString(17)); - - String formatPattern = rs.getString(25); - - //BEGIN http://jira.idempiere.com/browse/IDEMPIERE-153 - boolean isDesc = "Y".equals(rs.getString(26)); - //END - - // Fully qualified Table.Column for ordering - String orderName = tableName + "." + ColumnName; - String lookupSQL = orderName; - PrintDataColumn pdc = null; - - // -- Key -- - if (IsKey) - { - // => Table.Column, - sqlSELECT.append(tableName).append(".").append(ColumnName).append(","); - groupByColumns.add(tableName+"."+ColumnName); - pdc = new PrintDataColumn(AD_Column_ID, ColumnName, AD_Reference_ID, FieldLength, KEY, isPageBreak); // KeyColumn - } - // not printed Sort Columns - else if (!IsPrinted) - { - ; - } - // -- Parent, TableDir (and unqualified Search) -- - else if ( /* (IsParent && DisplayType.isLookup(AD_Reference_ID)) || <-- IDEMPIERE-71 Carlos Ruiz - globalqss */ - AD_Reference_ID == DisplayType.TableDir - || (AD_Reference_ID == DisplayType.Search && AD_Reference_Value_ID == 0) - ) - { - - // Creates Embedded SQL in the form - // SELECT ColumnTable.Name FROM ColumnTable WHERE TableName.ColumnName=ColumnTable.ColumnName - String eSql; - - if (ColumnSQL.length() > 0) - { - eSql = MLookupFactory.getLookup_TableDirEmbed(m_language, ColumnName, tableName, "(" + ColumnSQL + ")"); - lookupSQL = ColumnSQL; - } - else - { - eSql = MLookupFactory.getLookup_TableDirEmbed(m_language, ColumnName, tableName); - } - - if (Util.isEmpty(eSql)) { // No Identifier records found - eSql = lookupSQL; - } - // DisplayColumn - String display = ColumnName; - // => (..) AS AName, Table.ID, - sqlSELECT.append("(").append(eSql).append(") AS ").append(m_synonym).append(display).append(",") - .append(lookupSQL).append(" AS ").append(ColumnName).append(","); - groupByColumns.add(lookupSQL); - orderName = m_synonym + display; - // - pdc = new PrintDataColumn(AD_Column_ID, ColumnName, AD_Reference_ID, FieldLength, orderName, isPageBreak); - synonymNext(); - } - - // -- Table -- - else if (AD_Reference_ID == DisplayType.Table - || (AD_Reference_ID == DisplayType.Search && AD_Reference_Value_ID != 0) - ) - { - if (ColumnSQL.length() > 0) - { - lookupSQL = ColumnSQL; - } - - String eSql; - - eSql = MLookupFactory.getLookup_TableEmbed(m_language, ColumnName, tableName, AD_Reference_Value_ID); - - // DisplayColumn - String display = ColumnName; - // => (..) AS AName, Table.ID, - sqlSELECT.append("(").append(eSql).append(") AS ").append(m_synonym).append(display).append(",") - .append(lookupSQL).append(" AS ").append(ColumnName).append(","); - groupByColumns.add(m_synonym+display); - groupByColumns.add(lookupSQL); - orderName = m_synonym + display; - // - TableReference tr = getTableReference(AD_Reference_Value_ID); - String foreignColumnName = tr.KeyColumn; - pdc = new PrintDataColumn(AD_Column_ID, ColumnName, AD_Reference_ID, FieldLength, orderName, isPageBreak, foreignColumnName); - synonymNext(); - } - - // -- List or Button with ReferenceValue -- - else if (AD_Reference_ID == DisplayType.List - || (AD_Reference_ID == DisplayType.Button && AD_Reference_Value_ID != 0)) - { - if (ColumnSQL.length() > 0) - { - lookupSQL = ColumnSQL; - } - if (Env.isBaseLanguage(m_language, "AD_Ref_List")) - { - // => A.Name AS AName, - sqlSELECT.append(m_synonym).append(".Name AS ").append(m_synonym).append("Name,"); - groupByColumns.add(m_synonym+".Name"); - orderName = m_synonym + "Name"; - // => x JOIN AD_Ref_List A ON (x.KeyColumn=A.Value AND A.AD_Reference_ID=123) - sqlFROM.append(" LEFT OUTER JOIN "); - sqlFROM.append("AD_Ref_List ").append(m_synonym).append(" ON (") - .append(lookupSQL).append("=").append(m_synonym).append(".Value") - .append(" AND ").append(m_synonym).append(".AD_Reference_ID=").append(AD_Reference_Value_ID).append(")"); - } - else - { - // => A.Name AS AName, - sqlSELECT.append(m_synonym).append(".Name AS ").append(m_synonym).append("Name,"); - groupByColumns.add(m_synonym+".Name"); - orderName = m_synonym + "Name"; - - // LEFT OUTER JOIN AD_Ref_List XA ON (AD_Table.EntityType=XA.Value AND XA.AD_Reference_ID=245) - // LEFT OUTER JOIN AD_Ref_List_Trl A ON (XA.AD_Ref_List_ID=A.AD_Ref_List_ID AND A.AD_Language='de_DE') - sqlFROM.append(" LEFT OUTER JOIN "); - sqlFROM.append(" AD_Ref_List X").append(m_synonym).append(" ON (") - .append(lookupSQL).append("=X") - .append(m_synonym).append(".Value AND X").append(m_synonym).append(".AD_Reference_ID=").append(AD_Reference_Value_ID) - .append(")"); - sqlFROM.append(" LEFT OUTER JOIN "); - sqlFROM.append(" AD_Ref_List_Trl ").append(m_synonym).append(" ON (X") - .append(m_synonym).append(".AD_Ref_List_ID=").append(m_synonym).append(".AD_Ref_List_ID") - .append(" AND ").append(m_synonym).append(".AD_Language='").append(m_language.getAD_Language()).append("')"); - } - // TableName.ColumnName, - sqlSELECT.append(lookupSQL).append(" AS ").append(ColumnName).append(","); - pdc = new PrintDataColumn(AD_Column_ID, ColumnName, AD_Reference_ID, FieldLength, orderName, isPageBreak); - synonymNext(); - } - - // -- Special Lookups -- - else if (AD_Reference_ID == DisplayType.Location - || AD_Reference_ID == DisplayType.Account - || AD_Reference_ID == DisplayType.Locator - || AD_Reference_ID == DisplayType.PAttribute - ) - { - if (ColumnSQL.length() > 0) - { - lookupSQL = ColumnSQL; - } - // TableName, DisplayColumn - String table = ""; - String key = ""; - String display = ""; - String synonym = null; - // - if (AD_Reference_ID == DisplayType.Location) - { - table = "C_Location"; - key = "C_Location_ID"; - display = "City||'.'"; // in case City is empty - synonym = "Address"; - } - else if (AD_Reference_ID == DisplayType.Account) - { - table = "C_ValidCombination"; - key = "C_ValidCombination_ID"; - display = "Combination"; - } - else if (AD_Reference_ID == DisplayType.Locator) - { - table = "M_Locator"; - key = "M_Locator_ID"; - display = "Value"; - } - else if (AD_Reference_ID == DisplayType.PAttribute) - { - table = "M_AttributeSetInstance"; - key = "M_AttributeSetInstance_ID"; - display = "Description"; - if (CLogMgt.isLevelFine()) - display += "||'{'||" + m_synonym + ".M_AttributeSetInstance_ID||'}'"; - synonym = "Description"; - } - if (synonym == null) - synonym = display; - - // => A.Name AS AName, table.ID, - sqlSELECT.append(m_synonym).append(".").append(display).append(" AS ") - .append(m_synonym).append(synonym).append(",") - .append(lookupSQL).append(" AS ").append(ColumnName).append(","); - groupByColumns.add(m_synonym+"."+synonym); - groupByColumns.add(lookupSQL); - orderName = m_synonym + synonym; - // => x JOIN table A ON (table.ID=A.Key) - if (IsMandatory) - sqlFROM.append(" INNER JOIN "); - else - sqlFROM.append(" LEFT OUTER JOIN "); - sqlFROM.append(table).append(" ").append(m_synonym).append(" ON (") - .append(lookupSQL).append("=") - .append(m_synonym).append(".").append(key).append(")"); - // - pdc = new PrintDataColumn(AD_Column_ID, ColumnName, AD_Reference_ID, FieldLength, orderName, isPageBreak); - synonymNext(); - } - - // -- Standard Column -- - else - { - int index = FunctionColumn.indexOf('@'); - if (ColumnSQL != null && ColumnSQL.length() > 0) - { - // => ColumnSQL AS ColumnName - sqlSELECT.append(ColumnSQL).append(" AS ").append(ColumnName).append(","); - if (!IsGroupFunction) - groupByColumns.add(ColumnSQL); - orderName = ColumnName; // no prefix for synonym - } - else if (index == -1) - { - // => Table.Column, - StringBuilder sb = new StringBuilder(); - sb.append(tableName).append(".").append(ColumnName); - sqlSELECT.append(sb).append(","); - if (!IsGroupFunction) - groupByColumns.add(sb.toString()); - } - else - { - // => Function(Table.Column) AS Column -- function has @ where column name goes - StringBuilder sb = new StringBuilder(); - sb.append(FunctionColumn.substring(0, index)) - .append(tableName).append(".").append(ColumnName) - .append(FunctionColumn.substring(index+1)); - sqlSELECT.append(sb).append(" AS ").append(ColumnName).append(","); - if (!IsGroupFunction) - groupByColumns.add(sb.toString()); - orderName = ColumnName; // no prefix for synonym - } - pdc = new PrintDataColumn(AD_Column_ID, ColumnName, - AD_Reference_ID, FieldLength, ColumnName, isPageBreak); - } - - // Order Sequence - Overwrite order column name - for (int i = 0; i < orderAD_Column_IDs.length; i++) - { - if (AD_Column_ID == orderAD_Column_IDs[i]) - { - - //BEGIN fernandinho - http://jira.idempiere.com/browse/IDEMPIERE-153 - if (isDesc) - orderName += " DESC"; - //END - - orderColumns.set(i, orderName); - // We need to GROUP BY even is not printed, because is used in ORDER clause - if (!IsPrinted && !IsGroupFunction) - { - groupByColumns.add(tableName+"."+ColumnName); - } - break; - } - } - - // - if (pdc == null || (!IsPrinted && !IsKey)) - continue; - - pdc.setFormatPattern(formatPattern); - columns.add(pdc); - } // for all Fields in Tab - } - catch (SQLException e) - { - log.log(Level.SEVERE, "SQL=" + sql + " - ID=" + format.get_ID(), e); - } - finally - { - DB.close(rs, pstmt); - rs = null; - pstmt = null; - } - - if (columns.size() == 0) - { - log.log(Level.SEVERE, "No Colums - Delete Report Format " + reportName + " and start again"); - if (log.isLoggable(Level.FINEST)) log.finest("No Colums - SQL=" + sql + " - ID=" + format.get_ID()); - return null; - } - - boolean hasLevelNo = false; - if (tableName.startsWith("T_Report")) - { - hasLevelNo = true; - if (sqlSELECT.indexOf("LevelNo") == -1) - sqlSELECT.append("LevelNo,"); - } - - /** - * Assemble final SQL - delete last SELECT ',' - */ - StringBuilder finalSQL = new StringBuilder(); - finalSQL.append(sqlSELECT.substring(0, sqlSELECT.length()-1)) - .append(sqlFROM); - - // WHERE clause - if (tableName.startsWith("T_Report")) - { - finalSQL.append(" WHERE "); - for (int i = 0; i < query.getRestrictionCount(); i++) - { - String q = query.getWhereClause (i); - if (q.indexOf("AD_PInstance_ID") != -1) // ignore all other Parameters - finalSQL.append (q); - } // for all restrictions - } - else - { - // User supplied Where Clause - if (query != null && query.isActive ()) - { - finalSQL.append (" WHERE "); - if (!query.getTableName ().equals (tableName)) - query.setTableName (tableName); - finalSQL.append (query.getWhereClause (true)); - } - // Access Restriction - MRole role = MRole.getDefault(ctx, false); - if (role.getAD_Role_ID() == 0 && !Ini.isClient()) - ; // System Access - else - finalSQL = new StringBuilder (role.addAccessSQL (finalSQL.toString (), - tableName, MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO)); - } - - // Add GROUP BY clause - if (IsGroupedBy) - { - for (int i = 0; i < groupByColumns.size(); i++) - { - if (i == 0) - finalSQL.append(" GROUP BY "); - else - finalSQL.append(","); - finalSQL.append(groupByColumns.get(i)); - } - } - - // Add ORDER BY clause - if (orderColumns != null) - { - for (int i = 0; i < orderColumns.size(); i++) - { - if (i == 0) - finalSQL.append(" ORDER BY "); - else - finalSQL.append(","); - String by = (String)orderColumns.get(i); - if (by == null || by.length() == 0) - by = String.valueOf(i+1); - finalSQL.append(by); - } - } // order by - - - // Print Data - PrintData pd = new PrintData (ctx, reportName); - PrintDataColumn[] info = new PrintDataColumn [columns.size()]; - columns.toArray(info); // column order is is m_synonymc with SELECT column position - pd.setColumnInfo(info); - pd.setTableName(tableName); - pd.setSQL(finalSQL.toString()); - pd.setHasLevelNo(hasLevelNo); - - if (log.isLoggable(Level.FINEST)) - { - log.finest (finalSQL.toString ()); - log.finest ("Group=" + m_group); - } - return pd; - } // getPrintDataInfo - - /** - * Next Synonym. - * Creates next synonym A..Z AA..ZZ AAA..ZZZ - */ - private void synonymNext() - { - int length = m_synonym.length(); - char cc = m_synonym.charAt(0); - if (cc == 'Z') - { - cc = 'A'; - length++; - } - else - cc++; - // - m_synonym = String.valueOf(cc); - for (int i = 1; i < length; i++) { - m_synonym += String.valueOf(cc); - } - } // synonymNext - - /** - * Get TableName and ColumnName for Reference Tables. - * @param AD_Reference_Value_ID reference value - * @return 0=TableName, 1=KeyColumn, 2=DisplayColumn - */ - public static TableReference getTableReference (int AD_Reference_Value_ID) - { - if (AD_Reference_Value_ID <= 0) - throw new IllegalArgumentException("AD_Reference_Value_ID <= 0"); - // - TableReference tr = new TableReference(); - // - StringBuilder SQL = new StringBuilder("SELECT t.TableName, ck.ColumnName AS KeyColumn,") // 1..2 - .append(" cd.ColumnName AS DisplayColumn, rt.IsValueDisplayed, cd.IsTranslated ") - .append("FROM AD_Ref_Table rt") - .append(" INNER JOIN AD_Table t ON (rt.AD_Table_ID = t.AD_Table_ID)") - .append(" INNER JOIN AD_Column ck ON (rt.AD_Key = ck.AD_Column_ID)") - .append(" INNER JOIN AD_Column cd ON (rt.AD_Display = cd.AD_Column_ID) ") - .append("WHERE rt.AD_Reference_ID=?") // 1 - .append(" AND rt.IsActive = 'Y' AND t.IsActive = 'Y'"); - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(SQL.toString(), null); - pstmt.setInt (1, AD_Reference_Value_ID); - rs = pstmt.executeQuery(); - if (rs.next()) - { - tr.TableName = rs.getString(1); - tr.KeyColumn = rs.getString(2); - tr.DisplayColumn = rs.getString(3); - tr.IsValueDisplayed = "Y".equals(rs.getString(4)); - tr.IsTranslated = "Y".equals(rs.getString(5)); - } - } - catch (SQLException ex) - { - log.log(Level.SEVERE, SQL.toString(), ex); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - return tr; - } // getTableReference - - - /************************************************************************** - * Load Data into PrintData - * @param pd print data with SQL and ColumnInfo set - * @param format print format - */ - private void loadPrintData (PrintData pd, MPrintFormat format) - { - // Translate Spool Output - boolean translateSpool = pd.getTableName().equals("T_Spool"); - m_runningTotalString = Msg.getMsg(format.getLanguage(), "RunningTotal"); - int rowNo = 0; - PrintDataColumn pdc = null; - boolean hasLevelNo = pd.hasLevelNo(); - int levelNo = 0; - // - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareNormalReadReplicaStatement(pd.getSQL(), m_trxName); - rs = pstmt.executeQuery(); - // Row Loop - while (rs.next()) - { - if (hasLevelNo) - levelNo = rs.getInt("LevelNo"); - else - levelNo = 0; - // Check Group Change ---------------------------------------- - if (m_group.getGroupColumnCount() > 1) // one is GRANDTOTAL_ - { - ArrayList changedGroups = new ArrayList(); - ArrayList changedValues = new ArrayList(); - boolean force = false; - - // Check Columns for Function Columns - for (int i = 0; i < pd.getColumnInfo().length; i++) - { - PrintDataColumn group_pdc = pd.getColumnInfo()[i]; - if (!m_group.isGroupColumn(group_pdc.getColumnName())) - continue; - - // Group change - Object value = m_group.groupChange(group_pdc.getColumnName(), rs.getObject(group_pdc.getAlias()), force); - if (value != null) // Group change - { - changedGroups.add(group_pdc); - changedValues.add(value); - force = true; // all subsequent groups force change - } - } - - for (int j = changedGroups.size() - 1; j >= 0; j--) // backwards (least group first) - { - PrintDataColumn group_pdc = changedGroups.get(j); - Object value = changedValues.get(j); - - char[] functions = m_group.getFunctions(group_pdc.getColumnName()); - for (int f = 0; f < functions.length; f++) - { - printRunningTotal(pd, levelNo, rowNo++); - pd.addRow(true, levelNo); - // get columns - for (int c = 0; c < pd.getColumnInfo().length; c++) - { - pdc = pd.getColumnInfo()[c]; - // log.fine("loadPrintData - PageBreak = " + pdc.isPageBreak()); - - if (group_pdc.getColumnName().equals(pdc.getColumnName())) - { - String valueString = value.toString(); - if (value instanceof Timestamp) - valueString = DisplayType.getDateFormat(pdc.getDisplayType(), m_language).format(value); - if (format.getTableFormat().isPrintFunctionSymbols()) // Translate Sum, etc. - valueString += PrintDataFunction.getFunctionSymbol(functions[f]); - pd.addNode(new PrintDataElement(pdc.getColumnName(), - valueString, DisplayType.String, false, pdc.isPageBreak(), pdc.getFormatPattern())); - } - else if (m_group.isFunctionColumn(pdc.getColumnName(), functions[f])) - { - pd.addNode(new PrintDataElement(pdc.getColumnName(), - m_group.getValue(group_pdc.getColumnName(), - pdc.getColumnName(), functions[f]), - PrintDataFunction.getFunctionDisplayType(functions[f], pdc.getDisplayType()), - false, pdc.isPageBreak(), pdc.getFormatPattern())); - } - } // for all columns - } // for all functions - // Reset Group Values - for (int c = 0; c < pd.getColumnInfo().length; c++) - { - pdc = pd.getColumnInfo()[c]; - m_group.reset(group_pdc.getColumnName(), pdc.getColumnName()); - } - } // Group change - } // group change - - // new row --------------------------------------------------- - printRunningTotal(pd, levelNo, rowNo++); + /************************************************************************** + * Load Data + * + * @param format print format + * @param query query + * @param ctx context + * @return PrintData or null + */ + public PrintData getPrintData (Properties ctx, MPrintFormat format, MQuery query) + { + return getPrintData(ctx, format, query, false); + } + + /************************************************************************** + * Load Data + * + * @param format print format + * @param query query + * @param ctx context + * @param summary + * @return PrintData or null + */ + public PrintData getPrintData (Properties ctx, MPrintFormat format, MQuery query, boolean summary) + { + MQuery queryCopy = query.deepCopy(); - /** Report Summary FR [ 2011569 ]**/ - if(!m_summary) - pd.addRow(false, levelNo); - int counter = 1; - // get columns - for (int i = 0; i < pd.getColumnInfo().length; i++) - { - pdc = pd.getColumnInfo()[i]; - PrintDataElement pde = null; - - // Key Column - No DisplayColumn - if (pdc.getAlias().equals(KEY)) - { - if (pdc.getColumnName().endsWith("_ID")) - { - // int id = rs.getInt(pdc.getColumnIDName()); - int id = rs.getInt(counter++); - if (!rs.wasNull()) - { - KeyNamePair pp = new KeyNamePair(id, KEY); // Key - pde = new PrintDataElement(pdc.getColumnName(), pp, pdc.getDisplayType(), - true, pdc.isPageBreak(), pdc.getFormatPattern()); - } - } - else - { - // String id = rs.getString(pdc.getColumnIDName()); - String id = rs.getString(counter++); - if (!rs.wasNull()) - { - ValueNamePair pp = new ValueNamePair(id, KEY); // Key - pde = new PrintDataElement(pdc.getColumnName(), pp, pdc.getDisplayType(), - true, pdc.isPageBreak(), pdc.getFormatPattern()); - } - } - } - // Non-Key Column - else - { - // Display and Value Column - if (pdc.hasAlias()) - { - // DisplayColumn first - String display = rs.getString(counter++); - if (pdc.getColumnName().endsWith("_ID")) - { - int id = rs.getInt(counter++); - if (display != null && !rs.wasNull()) - { - KeyNamePair pp = new KeyNamePair(id, display); - pde = new PrintDataElement(pdc.getColumnName(), pp, pdc.getDisplayType(), pdc.getFormatPattern(), pdc.getForeignColumnName()); - } - } - else - { - String id = rs.getString(counter++); - if (display != null && !rs.wasNull()) - { - ValueNamePair pp = new ValueNamePair(id, display); - pde = new PrintDataElement(pdc.getColumnName(), pp, pdc.getDisplayType(), pdc.getFormatPattern()); - } - } - } - // Display Value only - else - { - // Transformation for Booleans - if (pdc.getDisplayType() == DisplayType.YesNo) - { - String s = rs.getString(counter++); - if (!rs.wasNull()) - { - boolean b = s.equals("Y"); - pde = new PrintDataElement(pdc.getColumnName(), Boolean.valueOf(b), pdc.getDisplayType(), pdc.getFormatPattern()); - } - } - else if (pdc.getDisplayType() == DisplayType.TextLong) - { - String value = ""; - if ("java.lang.String".equals(rs.getMetaData().getColumnClassName(counter))) - { - value = rs.getString(counter++); - } - else - { - Clob clob = rs.getClob(counter++); - if (clob != null) - { - long length = clob.length(); - value = clob.getSubString(1, (int)length); - } - } - pde = new PrintDataElement(pdc.getColumnName(), value, pdc.getDisplayType(), pdc.getFormatPattern()); - } - // fix bug [ 1755592 ] Printing time in format - else if (pdc.getDisplayType() == DisplayType.DateTime) -{ - Timestamp datetime = rs.getTimestamp(counter++); - pde = new PrintDataElement(pdc.getColumnName(), datetime, pdc.getDisplayType(), pdc.getFormatPattern()); - } - else - // The general case - { - Object obj = rs.getObject(counter++); - if (obj != null && obj instanceof String) - { - obj = ((String)obj).trim(); - if (((String)obj).length() == 0) - obj = null; - } - if (obj != null) - { - // Translate Spool Output - if (translateSpool && obj instanceof String) - { - String s = (String)obj; - s = Msg.parseTranslation(pd.getCtx(), s); - pde = new PrintDataElement(pdc.getColumnName(), s, pdc.getDisplayType(), pdc.getFormatPattern()); - } - else - pde = new PrintDataElement(pdc.getColumnName(), (Serializable)obj, pdc.getDisplayType(), pdc.getFormatPattern()); - } - } - } // Value only - } // Non-Key Column - if (pde != null) + /** Report Summary FR [ 2011569 ]**/ + m_summary = summary; + + if (format == null) + throw new IllegalStateException ("No print format"); + + if (format.getJasperProcess_ID() > 0) + return null; + + String tableName = null; + String reportName = format.getName(); + // + if (format.getAD_ReportView_ID() != 0) + { + StringBuilder sql = new StringBuilder("SELECT t.AD_Table_ID, t.TableName, rv.Name, rv.WhereClause ") + .append("FROM AD_Table t") + .append(" INNER JOIN AD_ReportView rv ON (t.AD_Table_ID=rv.AD_Table_ID) ") + .append("WHERE rv.AD_ReportView_ID=?"); // 1 + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql.toString(), m_trxName); + pstmt.setInt(1, format.getAD_ReportView_ID()); + rs = pstmt.executeQuery(); + if (rs.next()) + { + tableName = rs.getString(2); // TableName + reportName = rs.getString(3); + // Add WhereClause restriction from AD_ReportView - teo_sarca BF [ 1761891 ] + String whereClause = rs.getString(4); + if (!Util.isEmpty(whereClause)) { + whereClause = "(" + whereClause + ")"; // IDEMPIERE-2597 + if (whereClause.indexOf("@") == -1) { + queryCopy.addRestriction(whereClause); + } else { // replace context variables + queryCopy.addRestriction(Env.parseContext(ctx, 0, whereClause.toString(), false, true)); + } + } + } + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql.toString(), e); + return null; + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + } + else + { + tableName = MTable.getTableName(ctx, format.getAD_Table_ID()); + } + if (tableName == null) + { + log.log(Level.SEVERE, "Not found Format=" + format); + return null; + } + if (format.isTranslationView() && tableName.toLowerCase().endsWith("_v")) // _vt not just _v + { + boolean hasVT = DB.isTableOrViewExists(tableName+"t"); + if (hasVT) + { + tableName += "t"; + format.setTranslationViewQuery (queryCopy); + } + } + // + PrintData pd = getPrintDataInfo (ctx, format, queryCopy, reportName, tableName); + if (pd == null) + return null; + loadPrintData(pd, format); + return pd; + } // getPrintData + + + /************************************************************************** + * Create Load SQL and update PrintData Info + * + * @param ctx context + * @param format print format + * @param query query + * @param reportName report name + * @param tableName table name + * @return PrintData or null + */ + private PrintData getPrintDataInfo (Properties ctx, MPrintFormat format, MQuery query, + String reportName, String tableName) + { + m_startTime = System.currentTimeMillis(); + if (log.isLoggable(Level.INFO)) log.info(reportName + " - " + m_language.getAD_Language()); + if (log.isLoggable(Level.FINE)) + { + log.fine("TableName=" + tableName + ", Query=" + query); + log.fine("Format=" + format); + } + ArrayList columns = new ArrayList(); + m_group = new PrintDataGroup(); + + // Order Columns (identified by non zero/null SortNo) + int[] orderAD_Column_IDs = format.getOrderAD_Column_IDs(); + ArrayList orderColumns = new ArrayList(orderAD_Column_IDs.length); + for (int i = 0; i < orderAD_Column_IDs.length; i++) + { + if (log.isLoggable(Level.FINEST)) log.finest("Order AD_Column_ID=" + orderAD_Column_IDs[i]); + orderColumns.add(""); // initial value overwritten with fully qualified name + } + + // Direct SQL w/o Reference Info + StringBuilder sqlSELECT = new StringBuilder("SELECT "); + StringBuilder sqlFROM = new StringBuilder(" FROM ").append(tableName); + ArrayList groupByColumns = new ArrayList(); + // + boolean IsGroupedBy = false; + // + StringBuilder sql = new StringBuilder("SELECT c.AD_Column_ID,c.ColumnName,") // 1..2 + .append("c.AD_Reference_ID,c.AD_Reference_Value_ID,") // 3..4 + .append("c.FieldLength,c.IsMandatory,c.IsKey,c.IsParent,") // 5..8 + .append("COALESCE(rvc.IsGroupFunction,'N'),rvc.FunctionColumn,") // 9..10 + .append("pfi.IsGroupBy,pfi.IsSummarized,pfi.IsAveraged,pfi.IsCounted, ") // 11..14 + .append("pfi.IsPrinted,pfi.SortNo,pfi.IsPageBreak, ") // 15..17 + .append("pfi.IsMinCalc,pfi.IsMaxCalc, ") // 18..19 + .append("pfi.isRunningTotal,pfi.RunningTotalLines, ") // 20..21 + .append("pfi.IsVarianceCalc, pfi.IsDeviationCalc, ") // 22..23 + .append("c.ColumnSQL, COALESCE(pfi.FormatPattern, c.FormatPattern) ") // 24, 25 + //BEGIN http://jira.idempiere.com/browse/IDEMPIERE-153 + .append(" , pfi.isDesc ") //26 + //END + .append("FROM AD_PrintFormat pf") + .append(" INNER JOIN AD_PrintFormatItem pfi ON (pf.AD_PrintFormat_ID=pfi.AD_PrintFormat_ID)") + .append(" INNER JOIN AD_Column c ON (pfi.AD_Column_ID=c.AD_Column_ID)") + .append(" LEFT OUTER JOIN AD_ReportView_Col rvc ON (pf.AD_ReportView_ID=rvc.AD_ReportView_ID AND c.AD_Column_ID=rvc.AD_Column_ID) ") + .append("WHERE pf.AD_PrintFormat_ID=?") // #1 + .append(" AND pfi.IsActive='Y' AND (pfi.IsPrinted='Y' OR c.IsKey='Y' OR pfi.SortNo > 0) ") + .append(" AND pfi.PrintFormatType IN ('" + + MPrintFormatItem.PRINTFORMATTYPE_Field + + "','" + + MPrintFormatItem.PRINTFORMATTYPE_Image + + "','" + + MPrintFormatItem.PRINTFORMATTYPE_PrintFormat + + "') ") + .append("ORDER BY pfi.IsPrinted DESC, pfi.SeqNo"); // Functions are put in first column + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql.toString(), m_trxName); + pstmt.setInt(1, format.get_ID()); + rs = pstmt.executeQuery(); + + m_synonym = "A"; // synonym + + // init regular object to replace table name in virtual column + String orgTable = null; + Pattern regTranslateTable = null; + if (tableName.toLowerCase().endsWith("_vt")){ + orgTable = MTable.getTableName(ctx, format.getAD_Table_ID()); + regTranslateTable = Pattern.compile("\\b" + orgTable + "\\b", Pattern.CASE_INSENSITIVE); + } + + while (rs.next()) + { + // get Values from record + int AD_Column_ID = rs.getInt(1); + String ColumnName = rs.getString(2); + String ColumnSQL = rs.getString(24); + if (ColumnSQL != null && ColumnSQL.length() > 0 && ColumnSQL.startsWith("@SQL=")) + ColumnSQL = "NULL"; + if (ColumnSQL != null && ColumnSQL.contains("@")) + ColumnSQL = Env.parseContext(Env.getCtx(), -1, ColumnSQL, false, true); + if (ColumnSQL == null) + ColumnSQL = ""; + else{ + // replace table with translate table IDEMPIERE-2234 + if (tableName.toLowerCase().endsWith("_vt")){ + ColumnSQL = regTranslateTable.matcher(ColumnSQL).replaceAll(tableName); + } + } + int AD_Reference_ID = rs.getInt(3); + int AD_Reference_Value_ID = rs.getInt(4); + // ColumnInfo + int FieldLength = rs.getInt(5); + boolean IsMandatory = "Y".equals(rs.getString(6)); + boolean IsKey = "Y".equals(rs.getString(7)); + //boolean IsParent = "Y".equals(rs.getString(8)); + // SQL GroupBy + boolean IsGroupFunction = "Y".equals(rs.getString(9)); + if (IsGroupFunction) + IsGroupedBy = true; + String FunctionColumn = rs.getString(10); + if (FunctionColumn == null) + FunctionColumn = ""; + // Breaks/Column Functions + if ("Y".equals(rs.getString(11))) + m_group.addGroupColumn(ColumnName); + if ("Y".equals(rs.getString(12))) + m_group.addFunction(ColumnName, PrintDataFunction.F_SUM); + if ("Y".equals(rs.getString(13))) + m_group.addFunction(ColumnName, PrintDataFunction.F_MEAN); + if ("Y".equals(rs.getString(14))) + m_group.addFunction(ColumnName, PrintDataFunction.F_COUNT); + if ("Y".equals(rs.getString(18))) // IsMinCalc + m_group.addFunction(ColumnName, PrintDataFunction.F_MIN); + if ("Y".equals(rs.getString(19))) // IsMaxCalc + m_group.addFunction(ColumnName, PrintDataFunction.F_MAX); + if ("Y".equals(rs.getString(22))) // IsVarianceCalc + m_group.addFunction(ColumnName, PrintDataFunction.F_VARIANCE); + if ("Y".equals(rs.getString(23))) // IsDeviationCalc + m_group.addFunction(ColumnName, PrintDataFunction.F_DEVIATION); + if ("Y".equals(rs.getString(20))) // isRunningTotal + // RunningTotalLines only once - use max + m_runningTotalLines = Math.max(m_runningTotalLines, rs.getInt(21)); + + // General Info + boolean IsPrinted = "Y".equals(rs.getString(15)); + //int SortNo = rs.getInt(16); + boolean isPageBreak = "Y".equals(rs.getString(17)); + + String formatPattern = rs.getString(25); + + //BEGIN http://jira.idempiere.com/browse/IDEMPIERE-153 + boolean isDesc = "Y".equals(rs.getString(26)); + //END + + // Fully qualified Table.Column for ordering + String orderName = tableName + "." + ColumnName; + String lookupSQL = orderName; + PrintDataColumn pdc = null; + + // -- Key -- + if (IsKey) + { + // => Table.Column, + sqlSELECT.append(tableName).append(".").append(ColumnName).append(","); + groupByColumns.add(tableName+"."+ColumnName); + pdc = new PrintDataColumn(AD_Column_ID, ColumnName, AD_Reference_ID, FieldLength, KEY, isPageBreak); // KeyColumn + } + // not printed Sort Columns + else if (!IsPrinted) + { + ; + } + // -- Parent, TableDir (and unqualified Search) -- + else if ( /* (IsParent && DisplayType.isLookup(AD_Reference_ID)) || <-- IDEMPIERE-71 Carlos Ruiz - globalqss */ + AD_Reference_ID == DisplayType.TableDir + || (AD_Reference_ID == DisplayType.Search && AD_Reference_Value_ID == 0) + ) + { + + // Creates Embedded SQL in the form + // SELECT ColumnTable.Name FROM ColumnTable WHERE TableName.ColumnName=ColumnTable.ColumnName + String eSql; + + if (ColumnSQL.length() > 0) { - /** Report Summary FR [ 2011569 ]**/ + eSql = MLookupFactory.getLookup_TableDirEmbed(m_language, ColumnName, tableName, "(" + ColumnSQL + ")"); + lookupSQL = ColumnSQL; + } + else + { + eSql = MLookupFactory.getLookup_TableDirEmbed(m_language, ColumnName, tableName); + } + + if (Util.isEmpty(eSql)) { // No Identifier records found + eSql = lookupSQL; + } + // DisplayColumn + String display = ColumnName; + // => (..) AS AName, Table.ID, + sqlSELECT.append("(").append(eSql).append(") AS ").append(m_synonym).append(display).append(",") + .append(lookupSQL).append(" AS ").append(ColumnName).append(","); + groupByColumns.add(lookupSQL); + orderName = m_synonym + display; + // + pdc = new PrintDataColumn(AD_Column_ID, ColumnName, AD_Reference_ID, FieldLength, orderName, isPageBreak); + synonymNext(); + } + + // -- Table -- + else if (AD_Reference_ID == DisplayType.Table + || (AD_Reference_ID == DisplayType.Search && AD_Reference_Value_ID != 0) + ) + { + if (ColumnSQL.length() > 0) + { + lookupSQL = ColumnSQL; + } + + String eSql; + + eSql = MLookupFactory.getLookup_TableEmbed(m_language, ColumnName, tableName, AD_Reference_Value_ID); + + // DisplayColumn + String display = ColumnName; + // => (..) AS AName, Table.ID, + sqlSELECT.append("(").append(eSql).append(") AS ").append(m_synonym).append(display).append(",") + .append(lookupSQL).append(" AS ").append(ColumnName).append(","); + groupByColumns.add(m_synonym+display); + groupByColumns.add(lookupSQL); + orderName = m_synonym + display; + // + TableReference tr = getTableReference(AD_Reference_Value_ID); + String foreignColumnName = tr.KeyColumn; + pdc = new PrintDataColumn(AD_Column_ID, ColumnName, AD_Reference_ID, FieldLength, orderName, isPageBreak, foreignColumnName); + synonymNext(); + } + + // -- List or Button with ReferenceValue -- + else if (AD_Reference_ID == DisplayType.List + || (AD_Reference_ID == DisplayType.Button && AD_Reference_Value_ID != 0)) + { + if (ColumnSQL.length() > 0) + { + lookupSQL = ColumnSQL; + } + if (Env.isBaseLanguage(m_language, "AD_Ref_List")) + { + // => A.Name AS AName, + sqlSELECT.append(m_synonym).append(".Name AS ").append(m_synonym).append("Name,"); + groupByColumns.add(m_synonym+".Name"); + orderName = m_synonym + "Name"; + // => x JOIN AD_Ref_List A ON (x.KeyColumn=A.Value AND A.AD_Reference_ID=123) + sqlFROM.append(" LEFT OUTER JOIN "); + sqlFROM.append("AD_Ref_List ").append(m_synonym).append(" ON (") + .append(lookupSQL).append("=").append(m_synonym).append(".Value") + .append(" AND ").append(m_synonym).append(".AD_Reference_ID=").append(AD_Reference_Value_ID).append(")"); + } + else + { + // => A.Name AS AName, + sqlSELECT.append(m_synonym).append(".Name AS ").append(m_synonym).append("Name,"); + groupByColumns.add(m_synonym+".Name"); + orderName = m_synonym + "Name"; + + // LEFT OUTER JOIN AD_Ref_List XA ON (AD_Table.EntityType=XA.Value AND XA.AD_Reference_ID=245) + // LEFT OUTER JOIN AD_Ref_List_Trl A ON (XA.AD_Ref_List_ID=A.AD_Ref_List_ID AND A.AD_Language='de_DE') + sqlFROM.append(" LEFT OUTER JOIN "); + sqlFROM.append(" AD_Ref_List X").append(m_synonym).append(" ON (") + .append(lookupSQL).append("=X") + .append(m_synonym).append(".Value AND X").append(m_synonym).append(".AD_Reference_ID=").append(AD_Reference_Value_ID) + .append(")"); + sqlFROM.append(" LEFT OUTER JOIN "); + sqlFROM.append(" AD_Ref_List_Trl ").append(m_synonym).append(" ON (X") + .append(m_synonym).append(".AD_Ref_List_ID=").append(m_synonym).append(".AD_Ref_List_ID") + .append(" AND ").append(m_synonym).append(".AD_Language='").append(m_language.getAD_Language()).append("')"); + } + // TableName.ColumnName, + sqlSELECT.append(lookupSQL).append(" AS ").append(ColumnName).append(","); + pdc = new PrintDataColumn(AD_Column_ID, ColumnName, AD_Reference_ID, FieldLength, orderName, isPageBreak); + synonymNext(); + } + + // -- Special Lookups -- + else if (AD_Reference_ID == DisplayType.Location + || AD_Reference_ID == DisplayType.Account + || AD_Reference_ID == DisplayType.Locator + || AD_Reference_ID == DisplayType.PAttribute + ) + { + if (ColumnSQL.length() > 0) + { + lookupSQL = ColumnSQL; + } + // TableName, DisplayColumn + String table = ""; + String key = ""; + String display = ""; + String synonym = null; + // + if (AD_Reference_ID == DisplayType.Location) + { + table = "C_Location"; + key = "C_Location_ID"; + display = "City||'.'"; // in case City is empty + synonym = "Address"; + } + else if (AD_Reference_ID == DisplayType.Account) + { + table = "C_ValidCombination"; + key = "C_ValidCombination_ID"; + display = "Combination"; + } + else if (AD_Reference_ID == DisplayType.Locator) + { + table = "M_Locator"; + key = "M_Locator_ID"; + display = "Value"; + } + else if (AD_Reference_ID == DisplayType.PAttribute) + { + table = "M_AttributeSetInstance"; + key = "M_AttributeSetInstance_ID"; + display = "Description"; + if (CLogMgt.isLevelFine()) + display += "||'{'||" + m_synonym + ".M_AttributeSetInstance_ID||'}'"; + synonym = "Description"; + } + if (synonym == null) + synonym = display; + + // => A.Name AS AName, table.ID, + sqlSELECT.append(m_synonym).append(".").append(display).append(" AS ") + .append(m_synonym).append(synonym).append(",") + .append(lookupSQL).append(" AS ").append(ColumnName).append(","); + groupByColumns.add(m_synonym+"."+synonym); + groupByColumns.add(lookupSQL); + orderName = m_synonym + synonym; + // => x JOIN table A ON (table.ID=A.Key) + if (IsMandatory) + sqlFROM.append(" INNER JOIN "); + else + sqlFROM.append(" LEFT OUTER JOIN "); + sqlFROM.append(table).append(" ").append(m_synonym).append(" ON (") + .append(lookupSQL).append("=") + .append(m_synonym).append(".").append(key).append(")"); + // + pdc = new PrintDataColumn(AD_Column_ID, ColumnName, AD_Reference_ID, FieldLength, orderName, isPageBreak); + synonymNext(); + } + + // -- Standard Column -- + else + { + int index = FunctionColumn.indexOf('@'); + if (ColumnSQL != null && ColumnSQL.length() > 0) + { + // => ColumnSQL AS ColumnName + sqlSELECT.append(ColumnSQL).append(" AS ").append(ColumnName).append(","); + if (!IsGroupFunction) + groupByColumns.add(ColumnSQL); + orderName = ColumnName; // no prefix for synonym + } + else if (index == -1) + { + // => Table.Column, + StringBuilder sb = new StringBuilder(); + sb.append(tableName).append(".").append(ColumnName); + sqlSELECT.append(sb).append(","); + if (!IsGroupFunction) + groupByColumns.add(sb.toString()); + } + else + { + // => Function(Table.Column) AS Column -- function has @ where column name goes + StringBuilder sb = new StringBuilder(); + sb.append(FunctionColumn.substring(0, index)) + .append(tableName).append(".").append(ColumnName) + .append(FunctionColumn.substring(index+1)); + sqlSELECT.append(sb).append(" AS ").append(ColumnName).append(","); + if (!IsGroupFunction) + groupByColumns.add(sb.toString()); + orderName = ColumnName; // no prefix for synonym + } + pdc = new PrintDataColumn(AD_Column_ID, ColumnName, + AD_Reference_ID, FieldLength, ColumnName, isPageBreak); + } + + // Order Sequence - Overwrite order column name + for (int i = 0; i < orderAD_Column_IDs.length; i++) + { + if (AD_Column_ID == orderAD_Column_IDs[i]) + { + + //BEGIN fernandinho - http://jira.idempiere.com/browse/IDEMPIERE-153 + if (isDesc) + orderName += " DESC"; + //END + + orderColumns.set(i, orderName); + // We need to GROUP BY even is not printed, because is used in ORDER clause + if (!IsPrinted && !IsGroupFunction) + { + groupByColumns.add(tableName+"."+ColumnName); + } + break; + } + } + + // + if (pdc == null || (!IsPrinted && !IsKey)) + continue; + + pdc.setFormatPattern(formatPattern); + columns.add(pdc); + } // for all Fields in Tab + } + catch (SQLException e) + { + log.log(Level.SEVERE, "SQL=" + sql + " - ID=" + format.get_ID(), e); + } + finally + { + DB.close(rs, pstmt); + rs = null; + pstmt = null; + } + + if (columns.size() == 0) + { + log.log(Level.SEVERE, "No Colums - Delete Report Format " + reportName + " and start again"); + if (log.isLoggable(Level.FINEST)) log.finest("No Colums - SQL=" + sql + " - ID=" + format.get_ID()); + return null; + } + + boolean hasLevelNo = false; + if (tableName.startsWith("T_Report")) + { + hasLevelNo = true; + if (sqlSELECT.indexOf("LevelNo") == -1) + sqlSELECT.append("LevelNo,"); + } + + /** + * Assemble final SQL - delete last SELECT ',' + */ + StringBuilder finalSQL = new StringBuilder(); + finalSQL.append(sqlSELECT.substring(0, sqlSELECT.length()-1)) + .append(sqlFROM); + + // WHERE clause + if (tableName.startsWith("T_Report")) + { + finalSQL.append(" WHERE "); + for (int i = 0; i < query.getRestrictionCount(); i++) + { + String q = query.getWhereClause (i); + if (q.indexOf("AD_PInstance_ID") != -1) // ignore all other Parameters + finalSQL.append (q); + } // for all restrictions + } + else + { + // User supplied Where Clause + if (query != null && query.isActive ()) + { + finalSQL.append (" WHERE "); + if (!query.getTableName ().equals (tableName)) + query.setTableName (tableName); + finalSQL.append (query.getWhereClause (true)); + } + // Access Restriction + MRole role = MRole.getDefault(ctx, false); + if (role.getAD_Role_ID() == 0 && !Ini.isClient()) + ; // System Access + else + finalSQL = new StringBuilder (role.addAccessSQL (finalSQL.toString (), + tableName, MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO)); + } + + // Add GROUP BY clause + if (IsGroupedBy) + { + for (int i = 0; i < groupByColumns.size(); i++) + { + if (i == 0) + finalSQL.append(" GROUP BY "); + else + finalSQL.append(","); + finalSQL.append(groupByColumns.get(i)); + } + } + + // Add ORDER BY clause + if (orderColumns != null) + { + for (int i = 0; i < orderColumns.size(); i++) + { + if (i == 0) + finalSQL.append(" ORDER BY "); + else + finalSQL.append(","); + String by = (String)orderColumns.get(i); + if (by == null || by.length() == 0) + by = String.valueOf(i+1); + finalSQL.append(by); + } + } // order by + + + // Print Data + PrintData pd = new PrintData (ctx, reportName); + PrintDataColumn[] info = new PrintDataColumn [columns.size()]; + columns.toArray(info); // column order is is m_synonymc with SELECT column position + pd.setColumnInfo(info); + pd.setTableName(tableName); + pd.setSQL(finalSQL.toString()); + pd.setHasLevelNo(hasLevelNo); + + if (log.isLoggable(Level.FINEST)) + { + log.finest (finalSQL.toString ()); + log.finest ("Group=" + m_group); + } + return pd; + } // getPrintDataInfo + + /** + * Next Synonym. + * Creates next synonym A..Z AA..ZZ AAA..ZZZ + */ + private void synonymNext() + { + int length = m_synonym.length(); + char cc = m_synonym.charAt(0); + if (cc == 'Z') + { + cc = 'A'; + length++; + } + else + cc++; + // + m_synonym = String.valueOf(cc); + for (int i = 1; i < length; i++) { + m_synonym += String.valueOf(cc); + } + } // synonymNext + + /** + * Get TableName and ColumnName for Reference Tables. + * @param AD_Reference_Value_ID reference value + * @return 0=TableName, 1=KeyColumn, 2=DisplayColumn + */ + public static TableReference getTableReference (int AD_Reference_Value_ID) + { + if (AD_Reference_Value_ID <= 0) + throw new IllegalArgumentException("AD_Reference_Value_ID <= 0"); + // + TableReference tr = new TableReference(); + // + StringBuilder SQL = new StringBuilder("SELECT t.TableName, ck.ColumnName AS KeyColumn,") // 1..2 + .append(" cd.ColumnName AS DisplayColumn, rt.IsValueDisplayed, cd.IsTranslated ") + .append("FROM AD_Ref_Table rt") + .append(" INNER JOIN AD_Table t ON (rt.AD_Table_ID = t.AD_Table_ID)") + .append(" INNER JOIN AD_Column ck ON (rt.AD_Key = ck.AD_Column_ID)") + .append(" INNER JOIN AD_Column cd ON (rt.AD_Display = cd.AD_Column_ID) ") + .append("WHERE rt.AD_Reference_ID=?") // 1 + .append(" AND rt.IsActive = 'Y' AND t.IsActive = 'Y'"); + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(SQL.toString(), null); + pstmt.setInt (1, AD_Reference_Value_ID); + rs = pstmt.executeQuery(); + if (rs.next()) + { + tr.TableName = rs.getString(1); + tr.KeyColumn = rs.getString(2); + tr.DisplayColumn = rs.getString(3); + tr.IsValueDisplayed = "Y".equals(rs.getString(4)); + tr.IsTranslated = "Y".equals(rs.getString(5)); + } + } + catch (SQLException ex) + { + log.log(Level.SEVERE, SQL.toString(), ex); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + return tr; + } // getTableReference + + + /************************************************************************** + * Load Data into PrintData + * @param pd print data with SQL and ColumnInfo set + * @param format print format + */ + private void loadPrintData (PrintData pd, MPrintFormat format) + { + // Translate Spool Output + boolean translateSpool = pd.getTableName().equals("T_Spool"); + m_runningTotalString = Msg.getMsg(format.getLanguage(), "RunningTotal"); + int rowNo = 0; + PrintDataColumn pdc = null; + boolean hasLevelNo = pd.hasLevelNo(); + int levelNo = 0; + // + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareNormalReadReplicaStatement(pd.getSQL(), m_trxName); + rs = pstmt.executeQuery(); + // Row Loop + while (rs.next()) + { + if (hasLevelNo) + levelNo = rs.getInt("LevelNo"); + else + levelNo = 0; + // Check Group Change ---------------------------------------- + if (m_group.getGroupColumnCount() > 1) // one is GRANDTOTAL_ + { + ArrayList changedGroups = new ArrayList(); + ArrayList changedValues = new ArrayList(); + boolean force = false; + + // Check Columns for Function Columns + for (int i = 0; i < pd.getColumnInfo().length; i++) + { + PrintDataColumn group_pdc = pd.getColumnInfo()[i]; + if (!m_group.isGroupColumn(group_pdc.getColumnName())) + continue; + + // Group change + Object value = m_group.groupChange(group_pdc.getColumnName(), rs.getObject(group_pdc.getAlias()), force); + if (value != null) // Group change + { + changedGroups.add(group_pdc); + changedValues.add(value); + force = true; // all subsequent groups force change + } + } + + for (int j = changedGroups.size() - 1; j >= 0; j--) // backwards (least group first) + { + PrintDataColumn group_pdc = changedGroups.get(j); + Object value = changedValues.get(j); + + char[] functions = m_group.getFunctions(group_pdc.getColumnName()); + for (int f = 0; f < functions.length; f++) + { + printRunningTotal(pd, levelNo, rowNo++); + pd.addRow(true, levelNo); + // get columns + for (int c = 0; c < pd.getColumnInfo().length; c++) + { + pdc = pd.getColumnInfo()[c]; + // log.fine("loadPrintData - PageBreak = " + pdc.isPageBreak()); + + if (group_pdc.getColumnName().equals(pdc.getColumnName())) + { + String valueString = value.toString(); + if (value instanceof Timestamp) + valueString = DisplayType.getDateFormat(pdc.getDisplayType(), m_language).format(value); + if (format.getTableFormat().isPrintFunctionSymbols()) // Translate Sum, etc. + valueString += PrintDataFunction.getFunctionSymbol(functions[f]); + pd.addNode(new PrintDataElement(pdc.getColumnName(), + valueString, DisplayType.String, false, pdc.isPageBreak(), pdc.getFormatPattern())); + } + else if (m_group.isFunctionColumn(pdc.getColumnName(), functions[f])) + { + pd.addNode(new PrintDataElement(pdc.getColumnName(), + m_group.getValue(group_pdc.getColumnName(), + pdc.getColumnName(), functions[f]), + PrintDataFunction.getFunctionDisplayType(functions[f], pdc.getDisplayType()), + false, pdc.isPageBreak(), pdc.getFormatPattern())); + } + } // for all columns + } // for all functions + // Reset Group Values + for (int c = 0; c < pd.getColumnInfo().length; c++) + { + pdc = pd.getColumnInfo()[c]; + m_group.reset(group_pdc.getColumnName(), pdc.getColumnName()); + } + } // Group change + } // group change + + // new row --------------------------------------------------- + printRunningTotal(pd, levelNo, rowNo++); + + /** Report Summary FR [ 2011569 ]**/ + if(!m_summary) + pd.addRow(false, levelNo); + int counter = 1; + // get columns + for (int i = 0; i < pd.getColumnInfo().length; i++) + { + pdc = pd.getColumnInfo()[i]; + PrintDataElement pde = null; + + // Key Column - No DisplayColumn + if (pdc.getAlias().equals(KEY)) + { + if (pdc.getColumnName().endsWith("_ID")) + { + // int id = rs.getInt(pdc.getColumnIDName()); + int id = rs.getInt(counter++); + if (!rs.wasNull()) + { + KeyNamePair pp = new KeyNamePair(id, KEY); // Key + pde = new PrintDataElement(pdc.getColumnName(), pp, pdc.getDisplayType(), + true, pdc.isPageBreak(), pdc.getFormatPattern()); + } + } + else + { + // String id = rs.getString(pdc.getColumnIDName()); + String id = rs.getString(counter++); + if (!rs.wasNull()) + { + ValueNamePair pp = new ValueNamePair(id, KEY); // Key + pde = new PrintDataElement(pdc.getColumnName(), pp, pdc.getDisplayType(), + true, pdc.isPageBreak(), pdc.getFormatPattern()); + } + } + } + // Non-Key Column + else + { + // Display and Value Column + if (pdc.hasAlias()) + { + // DisplayColumn first + String display = rs.getString(counter++); + if (pdc.getColumnName().endsWith("_ID")) + { + int id = rs.getInt(counter++); + if (display != null && !rs.wasNull()) + { + KeyNamePair pp = new KeyNamePair(id, display); + pde = new PrintDataElement(pdc.getColumnName(), pp, pdc.getDisplayType(), pdc.getFormatPattern(), pdc.getForeignColumnName()); + } + } + else + { + String id = rs.getString(counter++); + if (display != null && !rs.wasNull()) + { + ValueNamePair pp = new ValueNamePair(id, display); + pde = new PrintDataElement(pdc.getColumnName(), pp, pdc.getDisplayType(), pdc.getFormatPattern()); + } + } + } + // Display Value only + else + { + // Transformation for Booleans + if (pdc.getDisplayType() == DisplayType.YesNo) + { + String s = rs.getString(counter++); + if (!rs.wasNull()) + { + boolean b = s.equals("Y"); + pde = new PrintDataElement(pdc.getColumnName(), Boolean.valueOf(b), pdc.getDisplayType(), pdc.getFormatPattern()); + } + } + else if (pdc.getDisplayType() == DisplayType.TextLong) + { + String value = ""; + if ("java.lang.String".equals(rs.getMetaData().getColumnClassName(counter))) + { + value = rs.getString(counter++); + } + else + { + Clob clob = rs.getClob(counter++); + if (clob != null) + { + long length = clob.length(); + value = clob.getSubString(1, (int)length); + } + } + pde = new PrintDataElement(pdc.getColumnName(), value, pdc.getDisplayType(), pdc.getFormatPattern()); + } + // fix bug [ 1755592 ] Printing time in format + else if (pdc.getDisplayType() == DisplayType.DateTime) +{ + Timestamp datetime = rs.getTimestamp(counter++); + pde = new PrintDataElement(pdc.getColumnName(), datetime, pdc.getDisplayType(), pdc.getFormatPattern()); + } + else + // The general case + { + Object obj = rs.getObject(counter++); + if (obj != null && obj instanceof String) + { + obj = ((String)obj).trim(); + if (((String)obj).length() == 0) + obj = null; + } + if (obj != null) + { + // Translate Spool Output + if (translateSpool && obj instanceof String) + { + String s = (String)obj; + s = Msg.parseTranslation(pd.getCtx(), s); + pde = new PrintDataElement(pdc.getColumnName(), s, pdc.getDisplayType(), pdc.getFormatPattern()); + } + else + pde = new PrintDataElement(pdc.getColumnName(), (Serializable)obj, pdc.getDisplayType(), pdc.getFormatPattern()); + } + } + } // Value only + } // Non-Key Column + if (pde != null) + { + /** Report Summary FR [ 2011569 ]**/ if(!m_summary) - pd.addNode(pde); - m_group.addValue(pde.getColumnName(), pde.getFunctionValue()); - } - } // for all columns - - } // for all rows - } - catch (SQLException e) - { - log.log(Level.SEVERE, pdc + " - " + e.getMessage() + "\nSQL=" + pd.getSQL()); - throw new AdempiereException(e); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - - // -- we have all rows - finish - // Check last Group Change - if (m_group.getGroupColumnCount() > 1) // one is TOTAL - { - for (int i = pd.getColumnInfo().length-1; i >= 0; i--) // backwards (leaset group first) - { - PrintDataColumn group_pdc = pd.getColumnInfo()[i]; - if (!m_group.isGroupColumn(group_pdc.getColumnName())) - continue; - Object value = m_group.groupChange(group_pdc.getColumnName(), new Object(), false); - if (value != null) // Group change - { - char[] functions = m_group.getFunctions(group_pdc.getColumnName()); - for (int f = 0; f < functions.length; f++) - { - printRunningTotal(pd, levelNo, rowNo++); - pd.addRow(true, levelNo); - // get columns - for (int c = 0; c < pd.getColumnInfo().length; c++) - { - pdc = pd.getColumnInfo()[c]; - if (group_pdc.getColumnName().equals(pdc.getColumnName())) - { - String valueString = value.toString(); - if (value instanceof Timestamp) - valueString = DisplayType.getDateFormat(pdc.getDisplayType(), m_language).format(value); - if (format.getTableFormat().isPrintFunctionSymbols()) // Translate Sum, etc. - valueString += PrintDataFunction.getFunctionSymbol(functions[f]); - pd.addNode(new PrintDataElement(pdc.getColumnName(), - valueString, DisplayType.String, pdc.getFormatPattern())); - } - else if (m_group.isFunctionColumn(pdc.getColumnName(), functions[f])) - { - pd.addNode(new PrintDataElement(pdc.getColumnName(), - m_group.getValue(group_pdc.getColumnName(), - pdc.getColumnName(), functions[f]), - PrintDataFunction.getFunctionDisplayType(functions[f], - pdc.getDisplayType()),pdc.getFormatPattern())); - } - } - } // for all functions - // No Need to Reset - } // Group change - } - } // last group change - - // Add Total Lines - if (m_group.isGroupColumn(PrintDataGroup.TOTAL)) - { - char[] functions = m_group.getFunctions(PrintDataGroup.TOTAL); - for (int f = 0; f < functions.length; f++) - { - printRunningTotal(pd, levelNo, rowNo++); - pd.addRow(true, levelNo); - // get columns - for (int c = 0; c < pd.getColumnInfo().length; c++) - { - pdc = pd.getColumnInfo()[c]; - if (c == 0) // put Function in first Column - { - String name; - if (!format.getTableFormat().isPrintFunctionSymbols()) // Translate Sum, etc. - name = Msg.getMsg(format.getLanguage(), PrintDataFunction.getFunctionName(functions[f])); - else - name = PrintDataFunction.getFunctionSymbol(functions[f]); // Symbol - pd.addNode(new PrintDataElement(pdc.getColumnName(), name.trim(), - DisplayType.String, pdc.getFormatPattern())); - } - else if (m_group.isFunctionColumn(pdc.getColumnName(), functions[f])) - { - pd.addNode(new PrintDataElement(pdc.getColumnName(), - m_group.getValue(PrintDataGroup.TOTAL, - pdc.getColumnName(), functions[f]), - PrintDataFunction.getFunctionDisplayType(functions[f], pdc.getDisplayType()), pdc.getFormatPattern())); - } - } // for all columns - } // for all functions - // No Need to Reset - } // TotalLine - - if (pd.getRowCount() == 0) - { - if (CLogMgt.isLevelFiner()) - log.warning("NO Rows - ms=" + (System.currentTimeMillis()-m_startTime) - + " - " + pd.getSQL()); - else - log.warning("NO Rows - ms=" + (System.currentTimeMillis()-m_startTime)); - } - else - if (log.isLoggable(Level.INFO)) log.info("Rows=" + pd.getRowCount() - + " - ms=" + (System.currentTimeMillis()-m_startTime)); - } // loadPrintData - - /** - * Print Running Total - * @param pd Print Data to add lines to - * @param levelNo level no - * @param rowNo row no - */ - private void printRunningTotal (PrintData pd, int levelNo, int rowNo) - { - if (m_runningTotalLines < 1) // -1 = none - return; - if (log.isLoggable(Level.FINE)) - log.fine("(" + m_runningTotalLines + ") - Row=" + rowNo - + ", mod=" + rowNo % m_runningTotalLines); - if (rowNo % m_runningTotalLines != 0) - return; - - if (log.isLoggable(Level.FINE)) - log.fine("Row=" + rowNo); - PrintDataColumn pdc = null; - int start = 0; - if (rowNo == 0) // no page break on page 1 - start = 1; - for (int rt = start; rt < 2; rt++) - { - pd.addRow (true, levelNo); - // get sum columns - for (int c = 0; c < pd.getColumnInfo().length; c++) - { - pdc = pd.getColumnInfo()[c]; - if (c == 0) - { - String title = "RunningTotal"; - pd.addNode(new PrintDataElement(pdc.getColumnName(), - title, DisplayType.String, false, rt==0, pdc.getFormatPattern())); // page break - } - else if (m_group.isFunctionColumn(pdc.getColumnName(), PrintDataFunction.F_SUM)) - { - pd.addNode(new PrintDataElement(pdc.getColumnName(), - m_group.getValue(PrintDataGroup.TOTAL, pdc.getColumnName(), PrintDataFunction.F_SUM), - PrintDataFunction.getFunctionDisplayType(PrintDataFunction.F_SUM, - pdc.getDisplayType()), false, false, pdc.getFormatPattern())); - } - } // for all sum columns - } // two lines - } // printRunningTotal - - - /************************************************************************* - * Test - * @param args args - */ - public static void main(String[] args) - { - org.compiere.Adempiere.startup(true); - - // DataEngine de = new DataEngine(null); - @SuppressWarnings("unused") - DataEngine de = new DataEngine(Language.getLanguage("de_DE")); - MQuery query = new MQuery(); - query.addRestriction("AD_Table_ID", MQuery.LESS, 105); - // PrintData pd = de.load_fromTable(100, query, null, null, false); - // pd.dump(); - // pd.createXML(new javax.xml.transform.stream.StreamResult(System.out)); - } - -} // DataEngine - -/** - * Table Reference Info - */ -class TableReference -{ - /** Table Name */ - public String TableName; - /** Key Column */ - public String KeyColumn; - /** Display Column */ - public String DisplayColumn; - /** Displayed */ - public boolean IsValueDisplayed = false; - /** Translated */ - public boolean IsTranslated = false; -} // TableReference + pd.addNode(pde); + m_group.addValue(pde.getColumnName(), pde.getFunctionValue()); + } + } // for all columns + + } // for all rows + } + catch (SQLException e) + { + log.log(Level.SEVERE, pdc + " - " + e.getMessage() + "\nSQL=" + pd.getSQL()); + throw new AdempiereException(e); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + + // -- we have all rows - finish + // Check last Group Change + if (m_group.getGroupColumnCount() > 1) // one is TOTAL + { + for (int i = pd.getColumnInfo().length-1; i >= 0; i--) // backwards (leaset group first) + { + PrintDataColumn group_pdc = pd.getColumnInfo()[i]; + if (!m_group.isGroupColumn(group_pdc.getColumnName())) + continue; + Object value = m_group.groupChange(group_pdc.getColumnName(), new Object(), false); + if (value != null) // Group change + { + char[] functions = m_group.getFunctions(group_pdc.getColumnName()); + for (int f = 0; f < functions.length; f++) + { + printRunningTotal(pd, levelNo, rowNo++); + pd.addRow(true, levelNo); + // get columns + for (int c = 0; c < pd.getColumnInfo().length; c++) + { + pdc = pd.getColumnInfo()[c]; + if (group_pdc.getColumnName().equals(pdc.getColumnName())) + { + String valueString = value.toString(); + if (value instanceof Timestamp) + valueString = DisplayType.getDateFormat(pdc.getDisplayType(), m_language).format(value); + if (format.getTableFormat().isPrintFunctionSymbols()) // Translate Sum, etc. + valueString += PrintDataFunction.getFunctionSymbol(functions[f]); + pd.addNode(new PrintDataElement(pdc.getColumnName(), + valueString, DisplayType.String, pdc.getFormatPattern())); + } + else if (m_group.isFunctionColumn(pdc.getColumnName(), functions[f])) + { + pd.addNode(new PrintDataElement(pdc.getColumnName(), + m_group.getValue(group_pdc.getColumnName(), + pdc.getColumnName(), functions[f]), + PrintDataFunction.getFunctionDisplayType(functions[f], + pdc.getDisplayType()),pdc.getFormatPattern())); + } + } + } // for all functions + // No Need to Reset + } // Group change + } + } // last group change + + // Add Total Lines + if (m_group.isGroupColumn(PrintDataGroup.TOTAL)) + { + char[] functions = m_group.getFunctions(PrintDataGroup.TOTAL); + for (int f = 0; f < functions.length; f++) + { + printRunningTotal(pd, levelNo, rowNo++); + pd.addRow(true, levelNo); + // get columns + for (int c = 0; c < pd.getColumnInfo().length; c++) + { + pdc = pd.getColumnInfo()[c]; + if (c == 0) // put Function in first Column + { + String name; + if (!format.getTableFormat().isPrintFunctionSymbols()) // Translate Sum, etc. + name = Msg.getMsg(format.getLanguage(), PrintDataFunction.getFunctionName(functions[f])); + else + name = PrintDataFunction.getFunctionSymbol(functions[f]); // Symbol + pd.addNode(new PrintDataElement(pdc.getColumnName(), name.trim(), + DisplayType.String, pdc.getFormatPattern())); + } + else if (m_group.isFunctionColumn(pdc.getColumnName(), functions[f])) + { + pd.addNode(new PrintDataElement(pdc.getColumnName(), + m_group.getValue(PrintDataGroup.TOTAL, + pdc.getColumnName(), functions[f]), + PrintDataFunction.getFunctionDisplayType(functions[f], pdc.getDisplayType()), pdc.getFormatPattern())); + } + } // for all columns + } // for all functions + // No Need to Reset + } // TotalLine + + if (pd.getRowCount() == 0) + { + if (CLogMgt.isLevelFiner()) + log.warning("NO Rows - ms=" + (System.currentTimeMillis()-m_startTime) + + " - " + pd.getSQL()); + else + log.warning("NO Rows - ms=" + (System.currentTimeMillis()-m_startTime)); + } + else + if (log.isLoggable(Level.INFO)) log.info("Rows=" + pd.getRowCount() + + " - ms=" + (System.currentTimeMillis()-m_startTime)); + } // loadPrintData + + /** + * Print Running Total + * @param pd Print Data to add lines to + * @param levelNo level no + * @param rowNo row no + */ + private void printRunningTotal (PrintData pd, int levelNo, int rowNo) + { + if (m_runningTotalLines < 1) // -1 = none + return; + if (log.isLoggable(Level.FINE)) + log.fine("(" + m_runningTotalLines + ") - Row=" + rowNo + + ", mod=" + rowNo % m_runningTotalLines); + if (rowNo % m_runningTotalLines != 0) + return; + + if (log.isLoggable(Level.FINE)) + log.fine("Row=" + rowNo); + PrintDataColumn pdc = null; + int start = 0; + if (rowNo == 0) // no page break on page 1 + start = 1; + for (int rt = start; rt < 2; rt++) + { + pd.addRow (true, levelNo); + // get sum columns + for (int c = 0; c < pd.getColumnInfo().length; c++) + { + pdc = pd.getColumnInfo()[c]; + if (c == 0) + { + String title = "RunningTotal"; + pd.addNode(new PrintDataElement(pdc.getColumnName(), + title, DisplayType.String, false, rt==0, pdc.getFormatPattern())); // page break + } + else if (m_group.isFunctionColumn(pdc.getColumnName(), PrintDataFunction.F_SUM)) + { + pd.addNode(new PrintDataElement(pdc.getColumnName(), + m_group.getValue(PrintDataGroup.TOTAL, pdc.getColumnName(), PrintDataFunction.F_SUM), + PrintDataFunction.getFunctionDisplayType(PrintDataFunction.F_SUM, + pdc.getDisplayType()), false, false, pdc.getFormatPattern())); + } + } // for all sum columns + } // two lines + } // printRunningTotal + + + /************************************************************************* + * Test + * @param args args + */ + public static void main(String[] args) + { + org.compiere.Adempiere.startup(true); + + // DataEngine de = new DataEngine(null); + @SuppressWarnings("unused") + DataEngine de = new DataEngine(Language.getLanguage("de_DE")); + MQuery query = new MQuery(); + query.addRestriction("AD_Table_ID", MQuery.LESS, 105); + // PrintData pd = de.load_fromTable(100, query, null, null, false); + // pd.dump(); + // pd.createXML(new javax.xml.transform.stream.StreamResult(System.out)); + } + +} // DataEngine + +/** + * Table Reference Info + */ +class TableReference +{ + /** Table Name */ + public String TableName; + /** Key Column */ + public String KeyColumn; + /** Display Column */ + public String DisplayColumn; + /** Displayed */ + public boolean IsValueDisplayed = false; + /** Translated */ + public boolean IsTranslated = false; +} // TableReference diff --git a/org.adempiere.base/src/org/compiere/report/MReportColumn.java b/org.adempiere.base/src/org/compiere/report/MReportColumn.java index 6eb1cc17bb..12d6cde23a 100644 --- a/org.adempiere.base/src/org/compiere/report/MReportColumn.java +++ b/org.adempiere.base/src/org/compiere/report/MReportColumn.java @@ -1,151 +1,151 @@ -/****************************************************************************** - * 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.compiere.report; - -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.util.Properties; -import java.util.logging.Level; - -import org.compiere.model.X_PA_ReportColumn; - -/** - * Report Column Model - * - * @author Jorg Janke - * @version $Id: MReportColumn.java,v 1.3 2006/08/03 22:16:52 jjanke Exp $ - */ -public class MReportColumn extends X_PA_ReportColumn -{ - /** - * - */ - private static final long serialVersionUID = 2395905882810790219L; - - /** - * Constructor - * @param ctx context - * @param PA_ReportColumn_ID id - * @param trxName transaction - */ - public MReportColumn (Properties ctx, int PA_ReportColumn_ID, String trxName) - { - super (ctx, PA_ReportColumn_ID, trxName); - if (PA_ReportColumn_ID == 0) - { - setIsPrinted (true); - setSeqNo (0); - } - } // MReportColumn - - /** - * Constructor - * @param ctx context - * @param rs ResultSet to load from - * @param trxName transaction - */ - public MReportColumn (Properties ctx, ResultSet rs, String trxName) - { - super(ctx, rs, trxName); - } // MReportColumn - - /************************************************************************** - * Get Column SQL Select Clause. - * @param withSum with SUM() function - * @return select clause - AmtAcctCR+AmtAcctDR/etc or "null" if not defined - */ - public String getSelectClause (boolean withSum) - { - String amountType = getPAAmountType(); // first character - StringBuilder sb = new StringBuilder(); - if (withSum) - sb.append("SUM("); - if (PAAMOUNTTYPE_BalanceExpectedSign.equals(amountType)) - // sb.append("AmtAcctDr-AmtAcctCr"); - sb.append("acctBalance(Account_ID,AmtAcctDr,AmtAcctCr)"); - else if ( PAAMOUNTTYPE_BalanceAccountedSign.equals(amountType) ) - sb.append("AmtAcctDr-AmtAcctCr"); - else if (PAAMOUNTTYPE_CreditOnly.equals(amountType)) - sb.append("AmtAcctCr"); - else if (PAAMOUNTTYPE_DebitOnly.equals(amountType)) - sb.append("AmtAcctDr"); - else if (PAAMOUNTTYPE_QuantityAccountedSign.equals(amountType)) - sb.append("Qty"); - else if (PAAMOUNTTYPE_QuantityExpectedSign.equals(amountType)) - sb.append("acctBalance(Account_ID,Qty,0)"); - else - { - log.log(Level.SEVERE, "AmountType=" + getPAAmountType () + ", at=" + amountType); - return "NULL"; - } - if (withSum) - sb.append(")"); - return sb.toString(); - } // getSelectClause - - /** - * Is it Period Info ? - * @return true if Period Amount Type - */ - public boolean isPeriod() - { - String pt = getPAPeriodType(); - if (pt == null) - return false; - return PAPERIODTYPE_Period.equals(pt); - } // isPeriod - - /** - * Is it Year Info ? - * @return true if Year Amount Type - */ - public boolean isYear() - { - String pt = getPAPeriodType(); - if (pt == null) - return false; - return PAPERIODTYPE_Year.equals(pt); - } // isYear - - /** - * Is it Total Info ? - * @return true if Year Amount Type - */ - public boolean isTotal() - { - String pt = getPAPeriodType(); - if (pt == null) - return false; - return PAPERIODTYPE_Total.equals(pt); - } // isTotalBalance - - /** - * Is it natural balance ? - * Natural balance means year balance for profit and loss a/c, total balance for balance sheet account - * @return true if Natural Balance Amount Type - */ - public boolean isNatural() { - String pt = getPAPeriodType(); - if (pt == null) - return false; - return PAPERIODTYPE_Natural.equals(pt); - } - - /** +/****************************************************************************** + * 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.compiere.report; + +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.util.Properties; +import java.util.logging.Level; + +import org.compiere.model.X_PA_ReportColumn; + +/** + * Report Column Model + * + * @author Jorg Janke + * @version $Id: MReportColumn.java,v 1.3 2006/08/03 22:16:52 jjanke Exp $ + */ +public class MReportColumn extends X_PA_ReportColumn +{ + /** + * + */ + private static final long serialVersionUID = 2395905882810790219L; + + /** + * Constructor + * @param ctx context + * @param PA_ReportColumn_ID id + * @param trxName transaction + */ + public MReportColumn (Properties ctx, int PA_ReportColumn_ID, String trxName) + { + super (ctx, PA_ReportColumn_ID, trxName); + if (PA_ReportColumn_ID == 0) + { + setIsPrinted (true); + setSeqNo (0); + } + } // MReportColumn + + /** + * Constructor + * @param ctx context + * @param rs ResultSet to load from + * @param trxName transaction + */ + public MReportColumn (Properties ctx, ResultSet rs, String trxName) + { + super(ctx, rs, trxName); + } // MReportColumn + + /************************************************************************** + * Get Column SQL Select Clause. + * @param withSum with SUM() function + * @return select clause - AmtAcctCR+AmtAcctDR/etc or "null" if not defined + */ + public String getSelectClause (boolean withSum) + { + String amountType = getPAAmountType(); // first character + StringBuilder sb = new StringBuilder(); + if (withSum) + sb.append("SUM("); + if (PAAMOUNTTYPE_BalanceExpectedSign.equals(amountType)) + // sb.append("AmtAcctDr-AmtAcctCr"); + sb.append("acctBalance(Account_ID,AmtAcctDr,AmtAcctCr)"); + else if ( PAAMOUNTTYPE_BalanceAccountedSign.equals(amountType) ) + sb.append("AmtAcctDr-AmtAcctCr"); + else if (PAAMOUNTTYPE_CreditOnly.equals(amountType)) + sb.append("AmtAcctCr"); + else if (PAAMOUNTTYPE_DebitOnly.equals(amountType)) + sb.append("AmtAcctDr"); + else if (PAAMOUNTTYPE_QuantityAccountedSign.equals(amountType)) + sb.append("Qty"); + else if (PAAMOUNTTYPE_QuantityExpectedSign.equals(amountType)) + sb.append("acctBalance(Account_ID,Qty,0)"); + else + { + log.log(Level.SEVERE, "AmountType=" + getPAAmountType () + ", at=" + amountType); + return "NULL"; + } + if (withSum) + sb.append(")"); + return sb.toString(); + } // getSelectClause + + /** + * Is it Period Info ? + * @return true if Period Amount Type + */ + public boolean isPeriod() + { + String pt = getPAPeriodType(); + if (pt == null) + return false; + return PAPERIODTYPE_Period.equals(pt); + } // isPeriod + + /** + * Is it Year Info ? + * @return true if Year Amount Type + */ + public boolean isYear() + { + String pt = getPAPeriodType(); + if (pt == null) + return false; + return PAPERIODTYPE_Year.equals(pt); + } // isYear + + /** + * Is it Total Info ? + * @return true if Year Amount Type + */ + public boolean isTotal() + { + String pt = getPAPeriodType(); + if (pt == null) + return false; + return PAPERIODTYPE_Total.equals(pt); + } // isTotalBalance + + /** + * Is it natural balance ? + * Natural balance means year balance for profit and loss a/c, total balance for balance sheet account + * @return true if Natural Balance Amount Type + */ + public boolean isNatural() { + String pt = getPAPeriodType(); + if (pt == null) + return false; + return PAPERIODTYPE_Natural.equals(pt); + } + + /** * Get Segment Value Where Clause * @param PA_Hierarchy_ID hierarchy * @return where clause @@ -155,281 +155,281 @@ public class MReportColumn extends X_PA_ReportColumn if (!isColumnTypeSegmentValue()) return ""; - String et = getElementType(); - // ID for Tree Leaf Value - int ID = 0; - // - if (MReportColumn.ELEMENTTYPE_Account.equals(et)) - ID = getC_ElementValue_ID(); - else if (MReportColumn.ELEMENTTYPE_Activity.equals(et)) - ID = getC_Activity_ID(); - else if (MReportColumn.ELEMENTTYPE_BPartner.equals(et)) - ID = getC_BPartner_ID(); - else if (MReportColumn.ELEMENTTYPE_Campaign.equals(et)) - ID = getC_Campaign_ID(); - else if (MReportColumn.ELEMENTTYPE_LocationFrom.equals(et)) - ID = getC_Location_ID(); - else if (MReportColumn.ELEMENTTYPE_LocationTo.equals(et)) - ID = getC_Location_ID(); - else if (MReportColumn.ELEMENTTYPE_Organization.equals(et)) - ID = getOrg_ID(); - else if (MReportColumn.ELEMENTTYPE_Product.equals(et)) - ID = getM_Product_ID(); - else if (MReportColumn.ELEMENTTYPE_Project.equals(et)) - ID = getC_Project_ID(); - else if (MReportColumn.ELEMENTTYPE_SalesRegion.equals(et)) - ID = getC_SalesRegion_ID(); - else if (MReportColumn.ELEMENTTYPE_OrgTrx.equals(et)) - ID = getOrg_ID(); // (re)uses Org_ID - else if (MReportColumn.ELEMENTTYPE_UserElementList1.equals(et)) - ID = getC_ElementValue_ID(); - else if (MReportColumn.ELEMENTTYPE_UserElementList2.equals(et)) - ID = getC_ElementValue_ID(); - else if (MReportColumn.ELEMENTTYPE_UserColumn1.equals(et)) - return " AND UserElement1_ID="+getUserElement1_ID(); // Not Tree - else if (MReportColumn.ELEMENTTYPE_UserColumn2.equals(et)) - return " AND UserElement2_ID="+getUserElement2_ID(); // Not Tree - // Financial Report Source with Type Combination - else if (MReportColumn.ELEMENTTYPE_Combination.equals(et)) + String et = getElementType(); + // ID for Tree Leaf Value + int ID = 0; + // + if (MReportColumn.ELEMENTTYPE_Account.equals(et)) + ID = getC_ElementValue_ID(); + else if (MReportColumn.ELEMENTTYPE_Activity.equals(et)) + ID = getC_Activity_ID(); + else if (MReportColumn.ELEMENTTYPE_BPartner.equals(et)) + ID = getC_BPartner_ID(); + else if (MReportColumn.ELEMENTTYPE_Campaign.equals(et)) + ID = getC_Campaign_ID(); + else if (MReportColumn.ELEMENTTYPE_LocationFrom.equals(et)) + ID = getC_Location_ID(); + else if (MReportColumn.ELEMENTTYPE_LocationTo.equals(et)) + ID = getC_Location_ID(); + else if (MReportColumn.ELEMENTTYPE_Organization.equals(et)) + ID = getOrg_ID(); + else if (MReportColumn.ELEMENTTYPE_Product.equals(et)) + ID = getM_Product_ID(); + else if (MReportColumn.ELEMENTTYPE_Project.equals(et)) + ID = getC_Project_ID(); + else if (MReportColumn.ELEMENTTYPE_SalesRegion.equals(et)) + ID = getC_SalesRegion_ID(); + else if (MReportColumn.ELEMENTTYPE_OrgTrx.equals(et)) + ID = getOrg_ID(); // (re)uses Org_ID + else if (MReportColumn.ELEMENTTYPE_UserElementList1.equals(et)) + ID = getC_ElementValue_ID(); + else if (MReportColumn.ELEMENTTYPE_UserElementList2.equals(et)) + ID = getC_ElementValue_ID(); + else if (MReportColumn.ELEMENTTYPE_UserColumn1.equals(et)) + return " AND UserElement1_ID="+getUserElement1_ID(); // Not Tree + else if (MReportColumn.ELEMENTTYPE_UserColumn2.equals(et)) + return " AND UserElement2_ID="+getUserElement2_ID(); // Not Tree + // Financial Report Source with Type Combination + else if (MReportColumn.ELEMENTTYPE_Combination.equals(et)) return getWhereCombination(PA_Hierarchy_ID); else log.warning("Unsupported Element Type=" + et); if (ID == 0) { - if (log.isLoggable(Level.FINE)) log.fine("No Restrictions - No ID for EntityType=" + et); + if (log.isLoggable(Level.FINE)) log.fine("No Restrictions - No ID for EntityType=" + et); return ""; - } - + } + return " AND " + MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, et, ID); } // getWhereClause - - /** - * Obtain where clause for the combination type - * @param PA_Hierarchy_ID - * @return - */ - private String getWhereCombination(int PA_Hierarchy_ID) { - StringBuilder whcomb = new StringBuilder(); - if (getC_ElementValue_ID() > 0) { - String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Account, getC_ElementValue_ID()); - if (isIncludeNullsElementValue()) - whcomb.append(" AND (Account_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsElementValue()) - whcomb.append(" AND Account_ID IS NULL"); - - if (getC_Activity_ID() > 0) { - String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Activity, getC_Activity_ID()); - if (isIncludeNullsActivity()) - whcomb.append(" AND (C_Activity_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsActivity()) - whcomb.append(" AND C_Activity_ID IS NULL"); - - if (getC_BPartner_ID() > 0) { - String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_BPartner, getC_BPartner_ID()); - if (isIncludeNullsBPartner()) - whcomb.append(" AND (C_BPartner_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsBPartner()) - whcomb.append(" AND C_BPartner_ID IS NULL"); - - if (getC_Campaign_ID() > 0) { - String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Campaign, getC_Campaign_ID()); - if (isIncludeNullsCampaign()) - whcomb.append(" AND (C_Campaign_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsCampaign()) - whcomb.append(" AND C_Campaign_ID IS NULL"); - - if (getC_Location_ID() > 0) { - String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_LocationFrom, getC_Location_ID()); - if (isIncludeNullsLocation()) - whcomb.append(" AND (C_LocFrom_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsLocation()) - whcomb.append(" AND C_LocFrom_ID IS NULL"); - - if (getOrg_ID() > 0) { - String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Organization, getOrg_ID()); - if (isIncludeNullsOrg()) - whcomb.append(" AND (AD_Org_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsOrg()) - whcomb.append(" AND AD_Org_ID IS NULL"); - - if (getAD_OrgTrx_ID() > 0) { - String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_OrgTrx, getAD_OrgTrx_ID()); - if (isIncludeNullsOrgTrx()) - whcomb.append(" AND (AD_OrgTrx_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsOrgTrx()) - whcomb.append(" AND AD_OrgTrx_ID IS NULL"); - - - if (getM_Product_ID() > 0) { - String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Product, getM_Product_ID()); - if (isIncludeNullsProduct()) - whcomb.append(" AND (M_Product_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsProduct()) - whcomb.append(" AND M_Product_ID IS NULL"); - - if (getC_Project_ID() > 0) { - String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Project, getC_Project_ID()); - if (isIncludeNullsProject()) - whcomb.append(" AND (C_Project_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsProject()) - whcomb.append(" AND C_Project_ID IS NULL"); - - if (getC_SalesRegion_ID() > 0) { - String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_SalesRegion, getC_SalesRegion_ID()); - if (isIncludeNullsSalesRegion()) - whcomb.append(" AND (C_SalesRegion_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsSalesRegion()) - whcomb.append(" AND C_SalesRegion_ID IS NULL"); - - if (getUserElement1_ID() > 0) { - String whtree = "UserElement1_ID=" + getUserElement1_ID(); // No Tree - if (isIncludeNullsUserElement1()) - whcomb.append(" AND (UserElement1_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsUserElement1()) - whcomb.append(" AND UserElement1_ID IS NULL"); - - if (getUserElement2_ID() > 0) { - String whtree = "UserElement2_ID=" + getUserElement2_ID(); // No Tree - if (isIncludeNullsUserElement2()) - whcomb.append(" AND (UserElement2_ID IS NULL OR ").append(whtree).append(")"); - else - whcomb.append(" AND ").append(whtree); - } else - if (isIncludeNullsUserElement2()) - whcomb.append(" AND UserElement2_ID IS NULL"); - - return whcomb.toString(); - } - - - /** - * Get String Representation - * @return String Representation - */ - public String toString () - { - StringBuffer sb = new StringBuffer ("MReportColumn[") - .append(get_ID()).append(" - ").append(getName()).append(" - ").append(getDescription()) - .append(", SeqNo=").append(getSeqNo()).append(", AmountType=").append(getPAAmountType()) - .append(", PeriodType=").append(getPAPeriodType()) - .append(", CurrencyType=").append(getCurrencyType()).append("/").append(getC_Currency_ID()) - .append(" - ColumnType=").append(getColumnType()); - if (isColumnTypeCalculation()) - sb.append(" - Calculation=").append(getCalculationType()) - .append(" - ").append(getOper_1_ID()).append(" - ").append(getOper_2_ID()); - else if (isColumnTypeRelativePeriod()) - sb.append(" - Period=").append(getRelativePeriod()); - else - sb.append(" - SegmentValue ElementType=").append(getElementType()); - sb.append ("]"); - return sb.toString (); - } // toString - - /** - * Calculation Type Range - * @return true if range - */ - public boolean isCalculationTypeRange() - { - return CALCULATIONTYPE_AddRangeOp1ToOp2.equals(getCalculationType()); - } - /** - * Calculation Type Add - * @return true id add - */ - public boolean isCalculationTypeAdd() - { - return CALCULATIONTYPE_AddOp1PlusOp2.equals(getCalculationType()); - } - /** - * Calculation Type Subtract - * @return true if subtract - */ - public boolean isCalculationTypeSubtract() - { - return CALCULATIONTYPE_SubtractOp1_Op2.equals(getCalculationType()); - } - /** - * Calculation Type Percent - * @return true if percent - */ - public boolean isCalculationTypePercent() - { - return CALCULATIONTYPE_PercentageOp1OfOp2.equals(getCalculationType()); - } - - - /** - * Column Type Calculation - * @return true if calculation - */ - public boolean isColumnTypeCalculation() - { - return COLUMNTYPE_Calculation.equals(getColumnType()); - } - /** - * Column Type Relative Period - * @return true if relative period - */ - public boolean isColumnTypeRelativePeriod() - { - return COLUMNTYPE_RelativePeriod.equals(getColumnType()); - } - /** - * Column Type Segment Value - * @return true if segment value - */ - public boolean isColumnTypeSegmentValue() - { - return COLUMNTYPE_SegmentValue.equals(getColumnType()); - } - /** - * Get Relative Period As Int - * @return relative period - */ - public int getRelativePeriodAsInt () - { - BigDecimal bd = getRelativePeriod(); - if (bd == null) - return 0; - return bd.intValue(); - } // getRelativePeriodAsInt - + + /** + * Obtain where clause for the combination type + * @param PA_Hierarchy_ID + * @return + */ + private String getWhereCombination(int PA_Hierarchy_ID) { + StringBuilder whcomb = new StringBuilder(); + if (getC_ElementValue_ID() > 0) { + String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Account, getC_ElementValue_ID()); + if (isIncludeNullsElementValue()) + whcomb.append(" AND (Account_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsElementValue()) + whcomb.append(" AND Account_ID IS NULL"); + + if (getC_Activity_ID() > 0) { + String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Activity, getC_Activity_ID()); + if (isIncludeNullsActivity()) + whcomb.append(" AND (C_Activity_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsActivity()) + whcomb.append(" AND C_Activity_ID IS NULL"); + + if (getC_BPartner_ID() > 0) { + String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_BPartner, getC_BPartner_ID()); + if (isIncludeNullsBPartner()) + whcomb.append(" AND (C_BPartner_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsBPartner()) + whcomb.append(" AND C_BPartner_ID IS NULL"); + + if (getC_Campaign_ID() > 0) { + String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Campaign, getC_Campaign_ID()); + if (isIncludeNullsCampaign()) + whcomb.append(" AND (C_Campaign_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsCampaign()) + whcomb.append(" AND C_Campaign_ID IS NULL"); + + if (getC_Location_ID() > 0) { + String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_LocationFrom, getC_Location_ID()); + if (isIncludeNullsLocation()) + whcomb.append(" AND (C_LocFrom_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsLocation()) + whcomb.append(" AND C_LocFrom_ID IS NULL"); + + if (getOrg_ID() > 0) { + String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Organization, getOrg_ID()); + if (isIncludeNullsOrg()) + whcomb.append(" AND (AD_Org_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsOrg()) + whcomb.append(" AND AD_Org_ID IS NULL"); + + if (getAD_OrgTrx_ID() > 0) { + String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_OrgTrx, getAD_OrgTrx_ID()); + if (isIncludeNullsOrgTrx()) + whcomb.append(" AND (AD_OrgTrx_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsOrgTrx()) + whcomb.append(" AND AD_OrgTrx_ID IS NULL"); + + + if (getM_Product_ID() > 0) { + String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Product, getM_Product_ID()); + if (isIncludeNullsProduct()) + whcomb.append(" AND (M_Product_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsProduct()) + whcomb.append(" AND M_Product_ID IS NULL"); + + if (getC_Project_ID() > 0) { + String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_Project, getC_Project_ID()); + if (isIncludeNullsProject()) + whcomb.append(" AND (C_Project_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsProject()) + whcomb.append(" AND C_Project_ID IS NULL"); + + if (getC_SalesRegion_ID() > 0) { + String whtree = MReportTree.getWhereClause (getCtx(), PA_Hierarchy_ID, MReportColumn.ELEMENTTYPE_SalesRegion, getC_SalesRegion_ID()); + if (isIncludeNullsSalesRegion()) + whcomb.append(" AND (C_SalesRegion_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsSalesRegion()) + whcomb.append(" AND C_SalesRegion_ID IS NULL"); + + if (getUserElement1_ID() > 0) { + String whtree = "UserElement1_ID=" + getUserElement1_ID(); // No Tree + if (isIncludeNullsUserElement1()) + whcomb.append(" AND (UserElement1_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsUserElement1()) + whcomb.append(" AND UserElement1_ID IS NULL"); + + if (getUserElement2_ID() > 0) { + String whtree = "UserElement2_ID=" + getUserElement2_ID(); // No Tree + if (isIncludeNullsUserElement2()) + whcomb.append(" AND (UserElement2_ID IS NULL OR ").append(whtree).append(")"); + else + whcomb.append(" AND ").append(whtree); + } else + if (isIncludeNullsUserElement2()) + whcomb.append(" AND UserElement2_ID IS NULL"); + + return whcomb.toString(); + } + + + /** + * Get String Representation + * @return String Representation + */ + public String toString () + { + StringBuffer sb = new StringBuffer ("MReportColumn[") + .append(get_ID()).append(" - ").append(getName()).append(" - ").append(getDescription()) + .append(", SeqNo=").append(getSeqNo()).append(", AmountType=").append(getPAAmountType()) + .append(", PeriodType=").append(getPAPeriodType()) + .append(", CurrencyType=").append(getCurrencyType()).append("/").append(getC_Currency_ID()) + .append(" - ColumnType=").append(getColumnType()); + if (isColumnTypeCalculation()) + sb.append(" - Calculation=").append(getCalculationType()) + .append(" - ").append(getOper_1_ID()).append(" - ").append(getOper_2_ID()); + else if (isColumnTypeRelativePeriod()) + sb.append(" - Period=").append(getRelativePeriod()); + else + sb.append(" - SegmentValue ElementType=").append(getElementType()); + sb.append ("]"); + return sb.toString (); + } // toString + + /** + * Calculation Type Range + * @return true if range + */ + public boolean isCalculationTypeRange() + { + return CALCULATIONTYPE_AddRangeOp1ToOp2.equals(getCalculationType()); + } + /** + * Calculation Type Add + * @return true id add + */ + public boolean isCalculationTypeAdd() + { + return CALCULATIONTYPE_AddOp1PlusOp2.equals(getCalculationType()); + } + /** + * Calculation Type Subtract + * @return true if subtract + */ + public boolean isCalculationTypeSubtract() + { + return CALCULATIONTYPE_SubtractOp1_Op2.equals(getCalculationType()); + } + /** + * Calculation Type Percent + * @return true if percent + */ + public boolean isCalculationTypePercent() + { + return CALCULATIONTYPE_PercentageOp1OfOp2.equals(getCalculationType()); + } + + + /** + * Column Type Calculation + * @return true if calculation + */ + public boolean isColumnTypeCalculation() + { + return COLUMNTYPE_Calculation.equals(getColumnType()); + } + /** + * Column Type Relative Period + * @return true if relative period + */ + public boolean isColumnTypeRelativePeriod() + { + return COLUMNTYPE_RelativePeriod.equals(getColumnType()); + } + /** + * Column Type Segment Value + * @return true if segment value + */ + public boolean isColumnTypeSegmentValue() + { + return COLUMNTYPE_SegmentValue.equals(getColumnType()); + } + /** + * Get Relative Period As Int + * @return relative period + */ + public int getRelativePeriodAsInt () + { + BigDecimal bd = getRelativePeriod(); + if (bd == null) + return 0; + return bd.intValue(); + } // getRelativePeriodAsInt + /** * Get Relative Period * @return relative period @@ -442,75 +442,75 @@ public class MReportColumn extends X_PA_ReportColumn return super.getRelativePeriod(); return null; } // getRelativePeriod - /** - * Get Element Type - */ - @Override - public String getElementType() - { - if (getColumnType().equals(COLUMNTYPE_SegmentValue)) - return super.getElementType(); - return null; - } // getElementType - - /** - * Get Calculation Type - */ - @Override - public String getCalculationType() - { - if (getColumnType().equals(COLUMNTYPE_Calculation)) - return super.getCalculationType(); - return null; - } // getCalculationType - - /** - * Before Save - * @param newRecord new - * @return true - */ - @Override - protected boolean beforeSave(boolean newRecord) - { - // Validate Type - String ct = getColumnType(); - if (ct.equals(COLUMNTYPE_RelativePeriod)) - { - setElementType(null); - setCalculationType(null); - } - else if (ct.equals(COLUMNTYPE_Calculation)) - { - setElementType(null); - setRelativePeriod(null); - } - else if (ct.equals(COLUMNTYPE_SegmentValue)) - { - setCalculationType(null); - } - return true; - } // beforeSave - /************************************************************************** - - /** - * Copy - * @param ctx context - * @param AD_Client_ID parent - * @param AD_Org_ID parent - * @param PA_ReportColumnSet_ID parent - * @param source copy source - * @param trxName transaction - * @return Report Column - */ - public static MReportColumn copy (Properties ctx, int AD_Client_ID, int AD_Org_ID, - int PA_ReportColumnSet_ID, MReportColumn source, String trxName) - { - MReportColumn retValue = new MReportColumn (ctx, 0, trxName); - MReportColumn.copyValues(source, retValue, AD_Client_ID, AD_Org_ID); - // - retValue.setPA_ReportColumnSet_ID(PA_ReportColumnSet_ID); // parent - retValue.setOper_1_ID(0); - retValue.setOper_2_ID(0); - return retValue; - } // copy -} // MReportColumn + /** + * Get Element Type + */ + @Override + public String getElementType() + { + if (getColumnType().equals(COLUMNTYPE_SegmentValue)) + return super.getElementType(); + return null; + } // getElementType + + /** + * Get Calculation Type + */ + @Override + public String getCalculationType() + { + if (getColumnType().equals(COLUMNTYPE_Calculation)) + return super.getCalculationType(); + return null; + } // getCalculationType + + /** + * Before Save + * @param newRecord new + * @return true + */ + @Override + protected boolean beforeSave(boolean newRecord) + { + // Validate Type + String ct = getColumnType(); + if (ct.equals(COLUMNTYPE_RelativePeriod)) + { + setElementType(null); + setCalculationType(null); + } + else if (ct.equals(COLUMNTYPE_Calculation)) + { + setElementType(null); + setRelativePeriod(null); + } + else if (ct.equals(COLUMNTYPE_SegmentValue)) + { + setCalculationType(null); + } + return true; + } // beforeSave + /************************************************************************** + + /** + * Copy + * @param ctx context + * @param AD_Client_ID parent + * @param AD_Org_ID parent + * @param PA_ReportColumnSet_ID parent + * @param source copy source + * @param trxName transaction + * @return Report Column + */ + public static MReportColumn copy (Properties ctx, int AD_Client_ID, int AD_Org_ID, + int PA_ReportColumnSet_ID, MReportColumn source, String trxName) + { + MReportColumn retValue = new MReportColumn (ctx, 0, trxName); + MReportColumn.copyValues(source, retValue, AD_Client_ID, AD_Org_ID); + // + retValue.setPA_ReportColumnSet_ID(PA_ReportColumnSet_ID); // parent + retValue.setOper_1_ID(0); + retValue.setOper_2_ID(0); + return retValue; + } // copy +} // MReportColumn diff --git a/org.adempiere.base/src/org/compiere/util/AmtInWords_IN.java b/org.adempiere.base/src/org/compiere/util/AmtInWords_IN.java index d758524bcf..b88da83f99 100644 --- a/org.adempiere.base/src/org/compiere/util/AmtInWords_IN.java +++ b/org.adempiere.base/src/org/compiere/util/AmtInWords_IN.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -11,23 +11,23 @@ * 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.compiere.util; - -/** - * Amount in Words for Bahasa Indonesia - * - * Bugs item #1569711: remove hard-coded "Rupiah" to support all currency - * Contributor: Armen Rizal (www.goodwill.co.id) - * - * @author Halim Englen - * @version $Id: AmtInWords_IN.java,v 1.3 2006/07/30 00:54:36 jjanke Exp $ - */ -public class AmtInWords_IN implements AmtInWords -{ + * 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.compiere.util; + +/** + * Amount in Words for Bahasa Indonesia + * + * Bugs item #1569711: remove hard-coded "Rupiah" to support all currency + * Contributor: Armen Rizal (www.goodwill.co.id) + * + * @author Halim Englen + * @version $Id: AmtInWords_IN.java,v 1.3 2006/07/30 00:54:36 jjanke Exp $ + */ +public class AmtInWords_IN implements AmtInWords +{ /** * AmtInWords_IN */ @@ -47,100 +47,100 @@ public class AmtInWords_IN implements AmtInWords "Tujuh", "Delapan", "Sembilan", - "Sepuluh", - "Sebelas", - }; - - private static final long POWER_THREE = 1000L; - private static final long POWER_SIX = 1000000L; - private static final long POWER_NINE = 1000000000L; - private static final long POWER_TWELVE = 1000000000000L; - private static final long POWER_FIFTEEN = 1000000000000000L; - - /** Static Logger */ - @SuppressWarnings("unused") - private static CLogger s_log = CLogger.getCLogger (AmtInWords_IN.class); - -//-------------------------- STATIC METHODS -------------------------- - + "Sepuluh", + "Sebelas", + }; + + private static final long POWER_THREE = 1000L; + private static final long POWER_SIX = 1000000L; + private static final long POWER_NINE = 1000000000L; + private static final long POWER_TWELVE = 1000000000000L; + private static final long POWER_FIFTEEN = 1000000000000000L; + + /** Static Logger */ + @SuppressWarnings("unused") + private static CLogger s_log = CLogger.getCLogger (AmtInWords_IN.class); + +//-------------------------- STATIC METHODS -------------------------- + /** * Convenient method for {@link #sayNumber(StringBuffer, long)}. * - * @param number number to say - * @return said number - */ - public static String sayNumber(double number) { - StringBuffer result = new StringBuffer(); - sayNumber(result, number); - //result.append(" Rupiah"); - return result.toString(); - } - + * @param number number to say + * @return said number + */ + public static String sayNumber(double number) { + StringBuffer result = new StringBuffer(); + sayNumber(result, number); + //result.append(" Rupiah"); + return result.toString(); + } + /** * Say a number. This method will append the result to the given string buffer. * * @param appendTo the string buffer * @param number number to say - * @return said number - * @throws IllegalArgumentException if the number equals to {@link Long#MIN_VALUE} - */ - public static String sayNumber(StringBuffer appendTo, double number) - throws IllegalArgumentException { - if (number == Double.MIN_VALUE) { - throw new IllegalArgumentException("Out of range"); - } - if (number < 0) { - appendTo.append("Minus "); - } - double abs = Math.abs(number); - // s_log.warning("Debug=" + abs); - if (abs < POWER_THREE) { - saySimpleNumber(appendTo, (int) abs); - } else if (abs < 2000) { - int thousand = (int) (abs % POWER_THREE); - appendTo.append("Seribu "); - saySimpleNumber(appendTo, thousand); - } else if (abs < POWER_SIX) { - int thousand = (int) (abs % POWER_SIX / POWER_THREE); - saySimpleNumber(appendTo, thousand); - appendTo.append(" Ribu"); - double remainder = abs - thousand * POWER_THREE; - if (remainder > 0) { - appendTo.append(' '); - sayNumber(appendTo, remainder); + * @return said number + * @throws IllegalArgumentException if the number equals to {@link Long#MIN_VALUE} + */ + public static String sayNumber(StringBuffer appendTo, double number) + throws IllegalArgumentException { + if (number == Double.MIN_VALUE) { + throw new IllegalArgumentException("Out of range"); + } + if (number < 0) { + appendTo.append("Minus "); + } + double abs = Math.abs(number); + // s_log.warning("Debug=" + abs); + if (abs < POWER_THREE) { + saySimpleNumber(appendTo, (int) abs); + } else if (abs < 2000) { + int thousand = (int) (abs % POWER_THREE); + appendTo.append("Seribu "); + saySimpleNumber(appendTo, thousand); + } else if (abs < POWER_SIX) { + int thousand = (int) (abs % POWER_SIX / POWER_THREE); + saySimpleNumber(appendTo, thousand); + appendTo.append(" Ribu"); + double remainder = abs - thousand * POWER_THREE; + if (remainder > 0) { + appendTo.append(' '); + sayNumber(appendTo, remainder); } } else if (abs < POWER_NINE) { - int million = (int) (abs % POWER_NINE / POWER_SIX); - saySimpleNumber(appendTo, million); - appendTo.append(" Juta"); - double remainder = abs - million * POWER_SIX; - if (remainder > 0) { - appendTo.append(' '); - sayNumber(appendTo, remainder); + int million = (int) (abs % POWER_NINE / POWER_SIX); + saySimpleNumber(appendTo, million); + appendTo.append(" Juta"); + double remainder = abs - million * POWER_SIX; + if (remainder > 0) { + appendTo.append(' '); + sayNumber(appendTo, remainder); } } else if (abs < POWER_TWELVE) { - int billion = (int) (abs % POWER_TWELVE / POWER_NINE); - saySimpleNumber(appendTo, billion); - appendTo.append(" Milyar"); - double remainder = abs - billion * POWER_NINE; - if (remainder > 0) { - appendTo.append(' '); - sayNumber(appendTo, remainder); + int billion = (int) (abs % POWER_TWELVE / POWER_NINE); + saySimpleNumber(appendTo, billion); + appendTo.append(" Milyar"); + double remainder = abs - billion * POWER_NINE; + if (remainder > 0) { + appendTo.append(' '); + sayNumber(appendTo, remainder); } } else if (abs < POWER_FIFTEEN) { - int trillion = (int) (abs % POWER_FIFTEEN / POWER_TWELVE); - saySimpleNumber(appendTo, trillion); - appendTo.append(" Trilyun"); - double remainder = abs - trillion * POWER_TWELVE; - if (remainder > 0) { - appendTo.append(' '); - sayNumber(appendTo, remainder); - } - } else { - appendTo.append("Lebih Dari Seribu Triliun"); - } - return appendTo.toString(); - } + int trillion = (int) (abs % POWER_FIFTEEN / POWER_TWELVE); + saySimpleNumber(appendTo, trillion); + appendTo.append(" Trilyun"); + double remainder = abs - trillion * POWER_TWELVE; + if (remainder > 0) { + appendTo.append(' '); + sayNumber(appendTo, remainder); + } + } else { + appendTo.append("Lebih Dari Seribu Triliun"); + } + return appendTo.toString(); + } @@ -185,42 +185,42 @@ public class AmtInWords_IN implements AmtInWords appendTo.append(" Ratus"); int remainder = number - ratusan * 100; if (remainder > 0) { - appendTo.append(' '); - saySimpleNumber(appendTo, remainder); - } - } - } - - + appendTo.append(' '); + saySimpleNumber(appendTo, remainder); + } + } + } + + /************************************************************************** - * Get Amount in Words - * @param amount numeric amount (352.80) - * @return amount in words (three*five*two 80/100) - */ - public String getAmtInWords (String amount) throws Exception - { - if (amount == null) - return amount; - // - StringBuffer result = new StringBuffer(); - - int pos = amount.lastIndexOf ('.'); - String oldamt = amount; - amount = amount.replaceAll (",", ""); - String cents = pos > 0 ? oldamt.substring (pos + 1):null; - double numDouble = Double.parseDouble(amount); - sayNumber(result, numDouble); - if (cents != null) - { - result.append(" Koma "); - numDouble = Double.parseDouble(cents); - sayNumber(result, numDouble); - } - //result.append(" Rupiah"); - return result.toString(); - } // getAmtInWords - - /** + * Get Amount in Words + * @param amount numeric amount (352.80) + * @return amount in words (three*five*two 80/100) + */ + public String getAmtInWords (String amount) throws Exception + { + if (amount == null) + return amount; + // + StringBuffer result = new StringBuffer(); + + int pos = amount.lastIndexOf ('.'); + String oldamt = amount; + amount = amount.replaceAll (",", ""); + String cents = pos > 0 ? oldamt.substring (pos + 1):null; + double numDouble = Double.parseDouble(amount); + sayNumber(result, numDouble); + if (cents != null) + { + result.append(" Koma "); + numDouble = Double.parseDouble(cents); + sayNumber(result, numDouble); + } + //result.append(" Rupiah"); + return result.toString(); + } // getAmtInWords + + /** * Test Print * @param amt amount */ @@ -240,29 +240,29 @@ public class AmtInWords_IN implements AmtInWords * Test * @param args ignored */ - public static void main (String[] args) - { - AmtInWords_IN aiw = new AmtInWords_IN(); - aiw.print ("0.00"); - aiw.print ("0.23"); - aiw.print ("1.23876787"); - aiw.print ("11.45"); - aiw.print ("121.45"); - aiw.print ("1231.56"); - aiw.print ("10341.78"); - aiw.print ("12341.78"); - aiw.print ("123451.89"); - aiw.print ("12234571.90"); - aiw.print ("123234571.90"); - aiw.print ("1987234571.90"); - aiw.print ("11123234571.90"); - aiw.print ("123123234571.90"); - aiw.print ("2123123234571.90"); - aiw.print ("23,123,123,234,571.90"); - aiw.print ("100,000,000,000,000.90"); - aiw.print ("111,111,111"); - aiw.print ("222,222,222,222,222"); - aiw.print ("222,222,222,222,222,222,222"); - } // main - -} // AmtInWords_IN + public static void main (String[] args) + { + AmtInWords_IN aiw = new AmtInWords_IN(); + aiw.print ("0.00"); + aiw.print ("0.23"); + aiw.print ("1.23876787"); + aiw.print ("11.45"); + aiw.print ("121.45"); + aiw.print ("1231.56"); + aiw.print ("10341.78"); + aiw.print ("12341.78"); + aiw.print ("123451.89"); + aiw.print ("12234571.90"); + aiw.print ("123234571.90"); + aiw.print ("1987234571.90"); + aiw.print ("11123234571.90"); + aiw.print ("123123234571.90"); + aiw.print ("2123123234571.90"); + aiw.print ("23,123,123,234,571.90"); + aiw.print ("100,000,000,000,000.90"); + aiw.print ("111,111,111"); + aiw.print ("222,222,222,222,222"); + aiw.print ("222,222,222,222,222,222,222"); + } // main + +} // AmtInWords_IN diff --git a/org.adempiere.base/src/org/compiere/util/AmtInWords_SR.java b/org.adempiere.base/src/org/compiere/util/AmtInWords_SR.java index 95d8ec4895..d7f2fa5690 100644 --- a/org.adempiere.base/src/org/compiere/util/AmtInWords_SR.java +++ b/org.adempiere.base/src/org/compiere/util/AmtInWords_SR.java @@ -1,263 +1,263 @@ -/****************************************************************************** - * 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. * - *****************************************************************************/ -package org.compiere.util; - -/** - *Amount in Words for Serbia. - * @author Nikola Petkov -The class is based on the AmtInWords_EN.java written - * by jjanke - */ -public class AmtInWords_SR - implements AmtInWords -{ - - /** - * AmtInWords_RS - */ - public AmtInWords_SR() - { - super (); - } - - private static final String zero = "Nula"; - - private static final String negative = "minus"; - - private static final String concat = "i"; - - private static final String din[] = - {"dinar", "dinara"}; - - /** Thousands plus */ - private static final String[][] majorNames = - { - {"", "", ""}, - {"Hiljadu", "Hiljade", "Hiljada"}, - {"Milion", "Miliona", "Miliona"}, - {"Milijarda", "Milijarde", "Milijardi"}, - {"Bilion", "Biliona", "Biliona"}, - {"Bilijarda", "Bilijarde", "Bilijardi"}, - {"Trilion", "Triliona", "Triliona"}}; - - /** Ten to Ninety */ - private static final String[] tensNames = - {"", "Deset", "Dvadeset", "Trideset", "ÄŒetrdeset", "Pedeset", "Å estdeset", - "Sedamdeset", "Osamdeset", "Devedeset"}; - - /* 100-1000 */ - private static final String[] hundredNames = - {"", "JednaStotina", "DveStotine", "TriStotine", "ÄŒetiriStotine", - "PetStotina", "Å estStotina", "SedamStotina", "OsamStotina", - "DevetStotina"}; - - /** numbers to 19 */ - private static final String[][] numNames = - { - {"", ""}, - {"Jedan", "Jedna"}, - {"Dva", "Dve"}, - {"Tri", "Tri"}, - {"ÄŒetiri", "ÄŒetiri"}, - {"Pet", "Pet"}, - {"Å est", "Å est"}, - {"Sedam", "Sedam"}, - {"Osam", "Osam"}, - {"Devet", "Devet"}, - {"Deset", "Deset"}, - {"Jedanaest", "Jedanast"}, - {"Dvanaeset", "Dvanaest"}, - {"Trinaeset", "Trinaest"}, - {"ÄŒetrnaest", "ÄŒetrnaest"}, - {"Petnaest", "Petnaest"}, - {"Å estnaest", "Å estnaest"}, - {"Sedamnaest", "Sedamnaest"}, - {"Osamnaest", "Osamnaest"}, - {"Devetnaest", "Devetnaest"}}; - - /** - *Convert Less Than One Thousand - * @param number - *@return amt - */ - private String convertLessThanOneThousand(int number, int w) - { - String soFar; - // Below 20 - if (number % 100 < 20) - { - soFar = numNames[number % 100][w]; - number /= 100; - } - else - { - soFar = numNames[number % 10][w]; - number /= 10; - if (soFar.compareTo ("") == 0) - { - soFar = tensNames[number % 10]; - } - else - { - soFar = tensNames[number % 10] + concat + soFar; - } - number /= 10; - } - if (number == 0) - return soFar; - return hundredNames[number] + soFar; - } // convertLessThanOneThousand - - /** - *Convert - * @param number - *@return amt - */ - private String convert(long number) - { - /* special case */ - if (number == 0) - { - return zero; - } - String prefix = ""; - if (number < 0) - { - number = -number; - prefix = negative + " "; - } - String soFar = ""; - int place = 0; - do - { - long n = number % 1000; - if (n != 0) - { - String s = convertLessThanOneThousand ((int)n, place == 1 ? 1 - : 0); - if ((place == 1) && (s.compareTo (numNames[1][1]) == 0)) - { - soFar = majorNames[place][0] + soFar; - } - else - { - long lastDigit = n % 10; - long lastTwoDigits = n % 100; - boolean teen = (lastTwoDigits > 10 && lastTwoDigits < 20); - String major = null; - if (lastDigit == 1 && !teen) - { - major = majorNames[place][0]; - } - // 2,3,4,22,23,24,32,33,34 ... - else if ((lastDigit > 1 && lastDigit < 5) && !teen) - { - major = majorNames[place][1]; - } - else - { - // 0,5,6,7,8,9,11,12,13,...,19 - major = majorNames[place][2]; - } - soFar = s + major + soFar; - } - } - place++; - number /= 1000; - } - while (number > 0); - return (prefix + soFar).trim (); - } // convert - - /************************************************************************** - *Get Amount in Words - * @param amount numeric amount (352.80) - *@return amount in words (three*five*two 80/100) - *@throws Exception - */ - public String getAmtInWords(String amount) - throws Exception - { - if (amount == null) - return amount; - StringBuilder sb = new StringBuilder (); - amount = amount.replaceAll (" ", "").replaceAll ("\u00A0", ""); - char sep = amount.contains (",") ? ',' : '.'; // Try to determine the - // separator either - // comma or a full stop - int pos = amount.lastIndexOf (sep); - long dins = Long.parseLong ((pos >= 0) ? amount.substring (0, pos) - : amount); - sb.append (convert (dins) + " " + din[dins == 1 ? 0 : 1]); - if (pos > 0) - { - String para = amount.substring (pos + 1); - if (para.length () > 2) - { - para = para.substring (0, 2); - } - sb.append (" " + concat + " ").append (para).append ("/100"); // para" - } - return sb.toString (); - } // getAmtInWords - - /** - *Test Print - * @param amt amount - */ - private void print(String amt) - { - try - { - System.out.println (amt + " = " + getAmtInWords (amt)); - } - catch (Exception e) - { - e.printStackTrace (); - } - } // print - - /** - *Test - * @param args ignored - */ - public static void main(String[] args) - { - AmtInWords_SR aiw = new AmtInWords_SR (); - aiw.print ("0.23"); - aiw.print ("23"); - aiw.print ("0,23"); - aiw.print ("1,23"); - aiw.print ("12,345"); - aiw.print ("123,45"); - aiw.print ("1 234,56"); - aiw.print ("12 345,78"); - aiw.print ("123 457,89"); - aiw.print ("1 234 578,90"); - aiw.print ("10,00"); - aiw.print ("50,00"); - aiw.print ("100,00"); - aiw.print ("300,00"); - aiw.print ("1 000,00"); - aiw.print ("3 000,00"); - aiw.print ("10 000,00"); - aiw.print ("1 000 000,00"); - aiw.print ("100 000 000,00"); - aiw.print ("100 000 000 000,00"); - aiw.print ("100 000 000 000 000,00"); - aiw.print ("1 000 000 000 000 000,00"); - aiw.print ("1 000 000 000 000 000 000,00"); - } // main -} // AmtInWords_RS +/****************************************************************************** + * 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. * + *****************************************************************************/ +package org.compiere.util; + +/** + *Amount in Words for Serbia. + * @author Nikola Petkov -The class is based on the AmtInWords_EN.java written + * by jjanke + */ +public class AmtInWords_SR + implements AmtInWords +{ + + /** + * AmtInWords_RS + */ + public AmtInWords_SR() + { + super (); + } + + private static final String zero = "Nula"; + + private static final String negative = "minus"; + + private static final String concat = "i"; + + private static final String din[] = + {"dinar", "dinara"}; + + /** Thousands plus */ + private static final String[][] majorNames = + { + {"", "", ""}, + {"Hiljadu", "Hiljade", "Hiljada"}, + {"Milion", "Miliona", "Miliona"}, + {"Milijarda", "Milijarde", "Milijardi"}, + {"Bilion", "Biliona", "Biliona"}, + {"Bilijarda", "Bilijarde", "Bilijardi"}, + {"Trilion", "Triliona", "Triliona"}}; + + /** Ten to Ninety */ + private static final String[] tensNames = + {"", "Deset", "Dvadeset", "Trideset", "ÄŒetrdeset", "Pedeset", "Å estdeset", + "Sedamdeset", "Osamdeset", "Devedeset"}; + + /* 100-1000 */ + private static final String[] hundredNames = + {"", "JednaStotina", "DveStotine", "TriStotine", "ÄŒetiriStotine", + "PetStotina", "Å estStotina", "SedamStotina", "OsamStotina", + "DevetStotina"}; + + /** numbers to 19 */ + private static final String[][] numNames = + { + {"", ""}, + {"Jedan", "Jedna"}, + {"Dva", "Dve"}, + {"Tri", "Tri"}, + {"ÄŒetiri", "ÄŒetiri"}, + {"Pet", "Pet"}, + {"Å est", "Å est"}, + {"Sedam", "Sedam"}, + {"Osam", "Osam"}, + {"Devet", "Devet"}, + {"Deset", "Deset"}, + {"Jedanaest", "Jedanast"}, + {"Dvanaeset", "Dvanaest"}, + {"Trinaeset", "Trinaest"}, + {"ÄŒetrnaest", "ÄŒetrnaest"}, + {"Petnaest", "Petnaest"}, + {"Å estnaest", "Å estnaest"}, + {"Sedamnaest", "Sedamnaest"}, + {"Osamnaest", "Osamnaest"}, + {"Devetnaest", "Devetnaest"}}; + + /** + *Convert Less Than One Thousand + * @param number + *@return amt + */ + private String convertLessThanOneThousand(int number, int w) + { + String soFar; + // Below 20 + if (number % 100 < 20) + { + soFar = numNames[number % 100][w]; + number /= 100; + } + else + { + soFar = numNames[number % 10][w]; + number /= 10; + if (soFar.compareTo ("") == 0) + { + soFar = tensNames[number % 10]; + } + else + { + soFar = tensNames[number % 10] + concat + soFar; + } + number /= 10; + } + if (number == 0) + return soFar; + return hundredNames[number] + soFar; + } // convertLessThanOneThousand + + /** + *Convert + * @param number + *@return amt + */ + private String convert(long number) + { + /* special case */ + if (number == 0) + { + return zero; + } + String prefix = ""; + if (number < 0) + { + number = -number; + prefix = negative + " "; + } + String soFar = ""; + int place = 0; + do + { + long n = number % 1000; + if (n != 0) + { + String s = convertLessThanOneThousand ((int)n, place == 1 ? 1 + : 0); + if ((place == 1) && (s.compareTo (numNames[1][1]) == 0)) + { + soFar = majorNames[place][0] + soFar; + } + else + { + long lastDigit = n % 10; + long lastTwoDigits = n % 100; + boolean teen = (lastTwoDigits > 10 && lastTwoDigits < 20); + String major = null; + if (lastDigit == 1 && !teen) + { + major = majorNames[place][0]; + } + // 2,3,4,22,23,24,32,33,34 ... + else if ((lastDigit > 1 && lastDigit < 5) && !teen) + { + major = majorNames[place][1]; + } + else + { + // 0,5,6,7,8,9,11,12,13,...,19 + major = majorNames[place][2]; + } + soFar = s + major + soFar; + } + } + place++; + number /= 1000; + } + while (number > 0); + return (prefix + soFar).trim (); + } // convert + + /************************************************************************** + *Get Amount in Words + * @param amount numeric amount (352.80) + *@return amount in words (three*five*two 80/100) + *@throws Exception + */ + public String getAmtInWords(String amount) + throws Exception + { + if (amount == null) + return amount; + StringBuilder sb = new StringBuilder (); + amount = amount.replaceAll (" ", "").replaceAll ("\u00A0", ""); + char sep = amount.contains (",") ? ',' : '.'; // Try to determine the + // separator either + // comma or a full stop + int pos = amount.lastIndexOf (sep); + long dins = Long.parseLong ((pos >= 0) ? amount.substring (0, pos) + : amount); + sb.append (convert (dins) + " " + din[dins == 1 ? 0 : 1]); + if (pos > 0) + { + String para = amount.substring (pos + 1); + if (para.length () > 2) + { + para = para.substring (0, 2); + } + sb.append (" " + concat + " ").append (para).append ("/100"); // para" + } + return sb.toString (); + } // getAmtInWords + + /** + *Test Print + * @param amt amount + */ + private void print(String amt) + { + try + { + System.out.println (amt + " = " + getAmtInWords (amt)); + } + catch (Exception e) + { + e.printStackTrace (); + } + } // print + + /** + *Test + * @param args ignored + */ + public static void main(String[] args) + { + AmtInWords_SR aiw = new AmtInWords_SR (); + aiw.print ("0.23"); + aiw.print ("23"); + aiw.print ("0,23"); + aiw.print ("1,23"); + aiw.print ("12,345"); + aiw.print ("123,45"); + aiw.print ("1 234,56"); + aiw.print ("12 345,78"); + aiw.print ("123 457,89"); + aiw.print ("1 234 578,90"); + aiw.print ("10,00"); + aiw.print ("50,00"); + aiw.print ("100,00"); + aiw.print ("300,00"); + aiw.print ("1 000,00"); + aiw.print ("3 000,00"); + aiw.print ("10 000,00"); + aiw.print ("1 000 000,00"); + aiw.print ("100 000 000,00"); + aiw.print ("100 000 000 000,00"); + aiw.print ("100 000 000 000 000,00"); + aiw.print ("1 000 000 000 000 000,00"); + aiw.print ("1 000 000 000 000 000 000,00"); + } // main +} // AmtInWords_RS diff --git a/org.adempiere.base/src/org/compiere/util/CLogger.java b/org.adempiere.base/src/org/compiere/util/CLogger.java index 653746224e..f1c984b134 100644 --- a/org.adempiere.base/src/org/compiere/util/CLogger.java +++ b/org.adempiere.base/src/org/compiere/util/CLogger.java @@ -1,343 +1,343 @@ -/****************************************************************************** - * 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.compiere.util; - -import java.io.Serializable; -import java.util.logging.LogManager; -import java.util.logging.Logger; - - -/** - * idempiere Logger - * - * @author Jorg Janke - * @version $Id: CLogger.java,v 1.3 2006/08/09 16:38:47 jjanke Exp $ - */ -public class CLogger extends Logger implements Serializable -{ - /** - * - */ - private static final long serialVersionUID = 6492376264463028357L; - private static final String LAST_INFO = "org.compiere.util.CLogger.lastInfo"; - private static final String LAST_WARNING = "org.compiere.util.CLogger.lastWarning"; - private static final String LAST_ERROR = "org.compiere.util.CLogger.lastError"; - private static final String LAST_EXCEPTION = "org.compiere.util.CLogger.lastException"; - - - /** - * Get Logger - * @param className class name - * @return Logger - */ - public static synchronized CLogger getCLogger (String className) - { - return getCLogger(className, true); - } - - /** - * Get Logger - * @param className class name - * @param usePackageLevel - * @return Logger - */ - public static synchronized CLogger getCLogger (String className, boolean usePackageLevel) - { - // CLogMgt.initialize(); - LogManager manager = LogManager.getLogManager(); - if (className == null || className.trim().length() == 0) - className = ""; - - Logger result = manager.getLogger(className); - if (result != null && result instanceof CLogger) - return (CLogger)result; - - Logger packageLogger = null; - if (className.indexOf(".") > 0 && usePackageLevel) - { - String s = className.substring(0, className.lastIndexOf(".")); - while(s.indexOf(".") > 0) - { - result = manager.getLogger(s); - if (result != null && result instanceof CLogger) - { - packageLogger = result; - break; - } - s = s.substring(0, s.lastIndexOf(".")); - } - } - // - CLogger newLogger = new CLogger(className, null); - if (packageLogger != null && packageLogger.getLevel() != null) - newLogger.setLevel(packageLogger.getLevel()); - else - newLogger.setLevel(CLogMgt.getLevel()); - manager.addLogger(newLogger); - return newLogger; - } // getLogger - - /** - * Get Logger - * @param clazz class name - * @return Logger - */ - public static CLogger getCLogger (Class clazz) - { - if (clazz == null) - return get(); - return getCLogger (clazz.getName()); - } // getLogger - - /** - * Get default idempiere Logger. - * Need to be used in serialized objects - * @return logger - */ - public static CLogger get() - { - if (s_logger == null) - s_logger = getCLogger("org.compiere.default"); - return s_logger; - } // get - - /** Default Logger */ - private volatile static CLogger s_logger = null; - - - /************************************************************************** - * Standard constructor - * @param name logger name - * @param resourceBundleName optional resource bundle (ignored) - */ - private CLogger (String name, String resourceBundleName) - { - super (name, resourceBundleName); - // setLevel(Level.ALL); - } // CLogger - - - /*************************************************************************/ - - /** - * Set and issue Error and save as ValueNamePair - * @param AD_Message message key - * @param message clear text message - * @return true (to avoid removal of method) - */ - public boolean saveError (String AD_Message, String message) - { - return saveError (AD_Message, message, true); - } // saveError - - /** - * Set and issue Error and save as ValueNamePair - * @param AD_Message message key - * @param ex exception - * @return true (to avoid removal of method) - */ - public boolean saveError (String AD_Message, Exception ex) - { - Env.getCtx().put(LAST_EXCEPTION, ex); - return saveError (AD_Message, ex.getLocalizedMessage(), true); - } // saveError - - /** - * Set and issue (if specified) Error and save as ValueNamePair - * @param AD_Message message key - * @param ex exception - * @param issueError if true will issue an error - * @return true (to avoid removal of method) - */ - public boolean saveError (String AD_Message, Exception ex, boolean issueError) - { - Env.getCtx().put(LAST_EXCEPTION, ex); - return saveError (AD_Message, ex.getLocalizedMessage(), issueError); - } // saveError - - /** - * Set Error and save as ValueNamePair - * @param AD_Message message key - * @param message clear text message - * @param issueError print error message (default true) - * @return true - */ - public boolean saveError (String AD_Message, String message, boolean issueError) - { - ValueNamePair lastError = new ValueNamePair (AD_Message, message); - Env.getCtx().put(LAST_ERROR, lastError); - // print it - if (issueError) - severe(AD_Message + " - " + message); - return true; - } // saveError - - /** - * Get Error from Stack - * @return AD_Message as Value and Message as String - */ - public static ValueNamePair retrieveError() - { - ValueNamePair vp = (ValueNamePair) Env.getCtx().remove(LAST_ERROR); - return vp; - } // retrieveError - - /** - * Get Error message from stack - * @param defaultMsg default message (used when there are no errors on stack) - * @return error message, or defaultMsg if there is not error message saved - * @see #retrieveError() - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - */ - public static String retrieveErrorString(String defaultMsg) { - ValueNamePair vp = retrieveError(); - if (vp == null) - return defaultMsg; - return vp.getName(); - } - - /** - * Get Error from Stack - * @return last exception - */ - public static Exception retrieveException() - { - Exception ex = (Exception) Env.getCtx().remove(LAST_EXCEPTION); - return ex; - } // retrieveError - - /** - * Save Warning as ValueNamePair. - * @param AD_Message message key - * @param message clear text message - * @return true - */ - public boolean saveWarning (String AD_Message, String message) - { - ValueNamePair lastWarning = new ValueNamePair(AD_Message, message); - Env.getCtx().put(LAST_WARNING, lastWarning); +/****************************************************************************** + * 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.compiere.util; + +import java.io.Serializable; +import java.util.logging.LogManager; +import java.util.logging.Logger; + + +/** + * idempiere Logger + * + * @author Jorg Janke + * @version $Id: CLogger.java,v 1.3 2006/08/09 16:38:47 jjanke Exp $ + */ +public class CLogger extends Logger implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 6492376264463028357L; + private static final String LAST_INFO = "org.compiere.util.CLogger.lastInfo"; + private static final String LAST_WARNING = "org.compiere.util.CLogger.lastWarning"; + private static final String LAST_ERROR = "org.compiere.util.CLogger.lastError"; + private static final String LAST_EXCEPTION = "org.compiere.util.CLogger.lastException"; + + + /** + * Get Logger + * @param className class name + * @return Logger + */ + public static synchronized CLogger getCLogger (String className) + { + return getCLogger(className, true); + } + + /** + * Get Logger + * @param className class name + * @param usePackageLevel + * @return Logger + */ + public static synchronized CLogger getCLogger (String className, boolean usePackageLevel) + { + // CLogMgt.initialize(); + LogManager manager = LogManager.getLogManager(); + if (className == null || className.trim().length() == 0) + className = ""; + + Logger result = manager.getLogger(className); + if (result != null && result instanceof CLogger) + return (CLogger)result; + + Logger packageLogger = null; + if (className.indexOf(".") > 0 && usePackageLevel) + { + String s = className.substring(0, className.lastIndexOf(".")); + while(s.indexOf(".") > 0) + { + result = manager.getLogger(s); + if (result != null && result instanceof CLogger) + { + packageLogger = result; + break; + } + s = s.substring(0, s.lastIndexOf(".")); + } + } + // + CLogger newLogger = new CLogger(className, null); + if (packageLogger != null && packageLogger.getLevel() != null) + newLogger.setLevel(packageLogger.getLevel()); + else + newLogger.setLevel(CLogMgt.getLevel()); + manager.addLogger(newLogger); + return newLogger; + } // getLogger + + /** + * Get Logger + * @param clazz class name + * @return Logger + */ + public static CLogger getCLogger (Class clazz) + { + if (clazz == null) + return get(); + return getCLogger (clazz.getName()); + } // getLogger + + /** + * Get default idempiere Logger. + * Need to be used in serialized objects + * @return logger + */ + public static CLogger get() + { + if (s_logger == null) + s_logger = getCLogger("org.compiere.default"); + return s_logger; + } // get + + /** Default Logger */ + private volatile static CLogger s_logger = null; + + + /************************************************************************** + * Standard constructor + * @param name logger name + * @param resourceBundleName optional resource bundle (ignored) + */ + private CLogger (String name, String resourceBundleName) + { + super (name, resourceBundleName); + // setLevel(Level.ALL); + } // CLogger + + + /*************************************************************************/ + + /** + * Set and issue Error and save as ValueNamePair + * @param AD_Message message key + * @param message clear text message + * @return true (to avoid removal of method) + */ + public boolean saveError (String AD_Message, String message) + { + return saveError (AD_Message, message, true); + } // saveError + + /** + * Set and issue Error and save as ValueNamePair + * @param AD_Message message key + * @param ex exception + * @return true (to avoid removal of method) + */ + public boolean saveError (String AD_Message, Exception ex) + { + Env.getCtx().put(LAST_EXCEPTION, ex); + return saveError (AD_Message, ex.getLocalizedMessage(), true); + } // saveError + + /** + * Set and issue (if specified) Error and save as ValueNamePair + * @param AD_Message message key + * @param ex exception + * @param issueError if true will issue an error + * @return true (to avoid removal of method) + */ + public boolean saveError (String AD_Message, Exception ex, boolean issueError) + { + Env.getCtx().put(LAST_EXCEPTION, ex); + return saveError (AD_Message, ex.getLocalizedMessage(), issueError); + } // saveError + + /** + * Set Error and save as ValueNamePair + * @param AD_Message message key + * @param message clear text message + * @param issueError print error message (default true) + * @return true + */ + public boolean saveError (String AD_Message, String message, boolean issueError) + { + ValueNamePair lastError = new ValueNamePair (AD_Message, message); + Env.getCtx().put(LAST_ERROR, lastError); + // print it + if (issueError) + severe(AD_Message + " - " + message); + return true; + } // saveError + + /** + * Get Error from Stack + * @return AD_Message as Value and Message as String + */ + public static ValueNamePair retrieveError() + { + ValueNamePair vp = (ValueNamePair) Env.getCtx().remove(LAST_ERROR); + return vp; + } // retrieveError + + /** + * Get Error message from stack + * @param defaultMsg default message (used when there are no errors on stack) + * @return error message, or defaultMsg if there is not error message saved + * @see #retrieveError() + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + */ + public static String retrieveErrorString(String defaultMsg) { + ValueNamePair vp = retrieveError(); + if (vp == null) + return defaultMsg; + return vp.getName(); + } + + /** + * Get Error from Stack + * @return last exception + */ + public static Exception retrieveException() + { + Exception ex = (Exception) Env.getCtx().remove(LAST_EXCEPTION); + return ex; + } // retrieveError + + /** + * Save Warning as ValueNamePair. + * @param AD_Message message key + * @param message clear text message + * @return true + */ + public boolean saveWarning (String AD_Message, String message) + { + ValueNamePair lastWarning = new ValueNamePair(AD_Message, message); + Env.getCtx().put(LAST_WARNING, lastWarning); // print it if (true) // issueError warning(AD_Message + " - " + message); - return true; - } // saveWarning - - /** - * Get Warning from Stack - * @return AD_Message as Value and Message as String - */ - public static ValueNamePair retrieveWarning() - { - ValueNamePair vp = (ValueNamePair) Env.getCtx().remove(LAST_WARNING); - return vp; - } // retrieveWarning - - /** - * Save Info as ValueNamePair - * @param AD_Message message key - * @param message clear text message - * @return true - */ - public boolean saveInfo (String AD_Message, String message) - { -// s_lastInfo = new ValueNamePair (AD_Message, message); - ValueNamePair lastInfo = new ValueNamePair (AD_Message, message); - Env.getCtx().put(LAST_INFO, lastInfo); - return true; - } // saveInfo - - /** - * Get Info from Stack - * @return AD_Message as Value and Message as String - */ - public static ValueNamePair retrieveInfo() - { - ValueNamePair vp = (ValueNamePair) Env.getCtx().remove(LAST_INFO); - return vp; - } // retrieveInfo - - /** - * Reset Saved Messages/Errors/Info - */ - public static void resetLast() - { - Env.getCtx().remove(LAST_ERROR); - Env.getCtx().remove(LAST_EXCEPTION); - Env.getCtx().remove(LAST_WARNING); - Env.getCtx().remove(LAST_INFO); - } // resetLast - - /** - * Get root cause - * @param t - * @return Throwable - */ - public static Throwable getRootCause(Throwable t) - { - Throwable cause = t; - while (cause.getCause() != null) - { - cause = cause.getCause(); - } - return cause; - } - - /** - * String Representation - * @return info - */ - public String toString () - { - StringBuilder sb = new StringBuilder ("CLogger["); - sb.append (getName()) - .append (",Level=").append (getLevel()).append ("]"); - return sb.toString (); - } // toString - - /** - * Write Object - Serialization - * @param out out - * @throws IOException - * - private void writeObject (ObjectOutputStream out) throws IOException - { - out.writeObject(getName()); - System.out.println("====writeObject:" + getName()); - } // writeObject - - private String m_className = null; - - private void readObject (ObjectInputStream in) throws IOException - { - try - { - m_className = (String)in.readObject(); - } - catch (Exception e) - { - e.printStackTrace(); - } - System.out.println("====readObject:" + m_className); - } - - protected Object readResolve() throws ObjectStreamException - { - System.out.println("====readResolve:" + m_className); - return getLogger(m_className); - } - /** **/ -} // CLogger + return true; + } // saveWarning + + /** + * Get Warning from Stack + * @return AD_Message as Value and Message as String + */ + public static ValueNamePair retrieveWarning() + { + ValueNamePair vp = (ValueNamePair) Env.getCtx().remove(LAST_WARNING); + return vp; + } // retrieveWarning + + /** + * Save Info as ValueNamePair + * @param AD_Message message key + * @param message clear text message + * @return true + */ + public boolean saveInfo (String AD_Message, String message) + { +// s_lastInfo = new ValueNamePair (AD_Message, message); + ValueNamePair lastInfo = new ValueNamePair (AD_Message, message); + Env.getCtx().put(LAST_INFO, lastInfo); + return true; + } // saveInfo + + /** + * Get Info from Stack + * @return AD_Message as Value and Message as String + */ + public static ValueNamePair retrieveInfo() + { + ValueNamePair vp = (ValueNamePair) Env.getCtx().remove(LAST_INFO); + return vp; + } // retrieveInfo + + /** + * Reset Saved Messages/Errors/Info + */ + public static void resetLast() + { + Env.getCtx().remove(LAST_ERROR); + Env.getCtx().remove(LAST_EXCEPTION); + Env.getCtx().remove(LAST_WARNING); + Env.getCtx().remove(LAST_INFO); + } // resetLast + + /** + * Get root cause + * @param t + * @return Throwable + */ + public static Throwable getRootCause(Throwable t) + { + Throwable cause = t; + while (cause.getCause() != null) + { + cause = cause.getCause(); + } + return cause; + } + + /** + * String Representation + * @return info + */ + public String toString () + { + StringBuilder sb = new StringBuilder ("CLogger["); + sb.append (getName()) + .append (",Level=").append (getLevel()).append ("]"); + return sb.toString (); + } // toString + + /** + * Write Object - Serialization + * @param out out + * @throws IOException + * + private void writeObject (ObjectOutputStream out) throws IOException + { + out.writeObject(getName()); + System.out.println("====writeObject:" + getName()); + } // writeObject + + private String m_className = null; + + private void readObject (ObjectInputStream in) throws IOException + { + try + { + m_className = (String)in.readObject(); + } + catch (Exception e) + { + e.printStackTrace(); + } + System.out.println("====readObject:" + m_className); + } + + protected Object readResolve() throws ObjectStreamException + { + System.out.println("====readResolve:" + m_className); + return getLogger(m_className); + } + /** **/ +} // CLogger diff --git a/org.adempiere.base/src/org/compiere/util/IniRes_hu.java b/org.adempiere.base/src/org/compiere/util/IniRes_hu.java index 53d0bd48ee..9bf9d5819e 100644 --- a/org.adempiere.base/src/org/compiere/util/IniRes_hu.java +++ b/org.adempiere.base/src/org/compiere/util/IniRes_hu.java @@ -1,48 +1,48 @@ -/****************************************************************************** - * 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.compiere.util; - -import java.util.ListResourceBundle; - -/** - * License Dialog Translation - * - * @author Jorg Janke - * @version $Id: IniRes.java,v 1.2 2006/07/30 00:52:23 jjanke Exp $ - */ -public class IniRes_hu extends ListResourceBundle -{ - /** Translation Content */ - static final Object[][] contents = new String[][] - { - { "Adempiere_License", "Licensz szerzÅ‘dés" }, - { "Do_you_accept", "Elfogadja a licensz feltételeit?" }, - { "No", "Nem" }, - { "Yes_I_Understand", "Igen, Megértettem és Elfogadom" }, - { "license_htm", "org/adempiere/license.htm" }, - { "License_rejected", "Licensz elutasítva, vagy lejárt" } - }; - - /** - * Get Content - * @return Content - */ - public Object[][] getContents() - { - return contents; - } // getContent +/****************************************************************************** + * 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.compiere.util; + +import java.util.ListResourceBundle; + +/** + * License Dialog Translation + * + * @author Jorg Janke + * @version $Id: IniRes.java,v 1.2 2006/07/30 00:52:23 jjanke Exp $ + */ +public class IniRes_hu extends ListResourceBundle +{ + /** Translation Content */ + static final Object[][] contents = new String[][] + { + { "Adempiere_License", "Licensz szerzÅ‘dés" }, + { "Do_you_accept", "Elfogadja a licensz feltételeit?" }, + { "No", "Nem" }, + { "Yes_I_Understand", "Igen, Megértettem és Elfogadom" }, + { "license_htm", "org/adempiere/license.htm" }, + { "License_rejected", "Licensz elutasítva, vagy lejárt" } + }; + + /** + * Get Content + * @return Content + */ + public Object[][] getContents() + { + return contents; + } // getContent } // IniRes diff --git a/org.adempiere.base/src/org/compiere/util/Login.java b/org.adempiere.base/src/org/compiere/util/Login.java index ecf9b1d878..fa31ef9f3f 100644 --- a/org.adempiere.base/src/org/compiere/util/Login.java +++ b/org.adempiere.base/src/org/compiere/util/Login.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -15,77 +15,77 @@ * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.util; - -import java.security.Principal; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Properties; -import java.util.logging.Level; - -import javax.swing.JOptionPane; - -import org.compiere.Adempiere; -import org.compiere.db.CConnection; -import org.compiere.model.I_M_Warehouse; -import org.compiere.model.MAcctSchema; -import org.compiere.model.MClientInfo; -import org.compiere.model.MCountry; -import org.compiere.model.MRole; -import org.compiere.model.MSysConfig; -import org.compiere.model.MSystem; -import org.compiere.model.MTable; -import org.compiere.model.MTree_Base; -import org.compiere.model.MUser; -import org.compiere.model.MUserPreference; -import org.compiere.model.ModelValidationEngine; -import org.compiere.model.Query; + +import java.security.Principal; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.logging.Level; + +import javax.swing.JOptionPane; + +import org.compiere.Adempiere; +import org.compiere.db.CConnection; +import org.compiere.model.I_M_Warehouse; +import org.compiere.model.MAcctSchema; +import org.compiere.model.MClientInfo; +import org.compiere.model.MCountry; +import org.compiere.model.MRole; +import org.compiere.model.MSysConfig; +import org.compiere.model.MSystem; +import org.compiere.model.MTable; +import org.compiere.model.MTree_Base; +import org.compiere.model.MUser; +import org.compiere.model.MUserPreference; +import org.compiere.model.ModelValidationEngine; +import org.compiere.model.Query; /** * Login Manager * - * @author Jorg Janke - * @author victor.perez@e-evolution.com, e-Evolution http://www.e-evolution.com - *
  • Incorrect global Variable when you use multi Account Schema - * http://sourceforge.net/tracker/?func=detail&atid=879335&aid=2531597&group_id=176962 - * @author teo.sarca@gmail.com - *
  • BF [ 2867246 ] Do not show InTrazit WHs on login + * @author Jorg Janke + * @author victor.perez@e-evolution.com, e-Evolution http://www.e-evolution.com + *
  • Incorrect global Variable when you use multi Account Schema + * http://sourceforge.net/tracker/?func=detail&atid=879335&aid=2531597&group_id=176962 + * @author teo.sarca@gmail.com + *
  • BF [ 2867246 ] Do not show InTrazit WHs on login * https://sourceforge.net/tracker/?func=detail&aid=2867246&group_id=176962&atid=879332 * @version $Id: Login.java,v 1.6 2006/10/02 05:19:06 jjanke Exp $ */ public class Login -{ - private String loginErrMsg; - private boolean isPasswordExpired; - - public String getLoginErrMsg() { - return loginErrMsg; - } - - public boolean isPasswordExpired() { - return isPasswordExpired; - } - +{ + private String loginErrMsg; + private boolean isPasswordExpired; + + public String getLoginErrMsg() { + return loginErrMsg; + } + + public boolean isPasswordExpired() { + return isPasswordExpired; + } + /** * Test Init - Set Environment for tests * @param isClient client session * @return Context */ - public static Properties initTest (boolean isClient) - { - // logger.entering("Env", "initTest"); - if (!Adempiere.startupEnvironment(true)) - System.exit (1); - // Test Context - Properties ctx = Env.getCtx(); - Login login = new Login(ctx); + public static Properties initTest (boolean isClient) + { + // logger.entering("Env", "initTest"); + if (!Adempiere.startupEnvironment(true)) + System.exit (1); + // Test Context + Properties ctx = Env.getCtx(); + Login login = new Login(ctx); KeyNamePair[] roles = login.getRoles(CConnection.get(), "System", "System", true); // load role @@ -99,7 +99,7 @@ public class Login // load org if (orgs != null && orgs.length > 0) { - @SuppressWarnings("unused") + @SuppressWarnings("unused") KeyNamePair[] whs = login.getWarehouses(orgs[0]); // login.loadPreferences(orgs[0], null, null, null); @@ -120,22 +120,22 @@ public class Login public static boolean isJavaOK (boolean isClient) { // Java System version check - String jVersion = System.getProperty("java.version"); - if (jVersion.startsWith("1.8.0") || jVersion.startsWith("9.") || jVersion.startsWith("10.") || jVersion.startsWith("11.")) - return true; + String jVersion = System.getProperty("java.version"); + if (jVersion.startsWith("1.8.0") || jVersion.startsWith("9.") || jVersion.startsWith("10.") || jVersion.startsWith("11.")) + return true; // Error Message - StringBuilder msg = new StringBuilder(); + StringBuilder msg = new StringBuilder(); msg.append(System.getProperty("java.vm.name")).append(" - ").append(jVersion); - msg.append(" <> 1.8.0 | 9 | 10 | 11"); - // - if (isClient) - JOptionPane.showMessageDialog(null, msg.toString(), - org.compiere.Adempiere.getName() + " - Java Version Check", - JOptionPane.ERROR_MESSAGE); - else - log.severe(msg.toString()); - return false; + msg.append(" <> 1.8.0 | 9 | 10 | 11"); + // + if (isClient) + JOptionPane.showMessageDialog(null, msg.toString(), + org.compiere.Adempiere.getName() + " - Java Version Check", + JOptionPane.ERROR_MESSAGE); + else + log.severe(msg.toString()); + return false; } // isJavaOK @@ -161,13 +161,13 @@ public class Login * - Get Connection * - Compare User info *

    - * Sets Context with login info + * Sets Context with login info * @param cc connection * @param app_user user * @param app_pwd pwd * @param force ignore pwd * @return Array of Role KeyNamePair or null if error - * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log + * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log * @deprecated */ protected KeyNamePair[] getRoles (CConnection cc, @@ -177,17 +177,17 @@ public class Login DB.setDBTarget(cc); Env.setContext(m_ctx, "#Host", cc.getAppsHost()); Env.setContext(m_ctx, "#Database", cc.getDbName()); - + Connection conn = DB.getConnectionRO(); if (conn == null) { log.saveError("NoDatabase", ""); return null; - } - try { - conn.close(); - } catch (SQLException e) { - } + } + try { + conn.close(); + } catch (SQLException e) { + } if (app_pwd == null) return null; @@ -200,10 +200,10 @@ public class Login *

    * Compare User Info *

    - * Sets Context with login info + * Sets Context with login info * @param app_user Principal * @return role array or null if in error. - * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log + * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log * @deprecated use public KeyNamePair[] getRoles(String app_user, KeyNamePair client) */ public KeyNamePair[] getRoles (Principal app_user) @@ -219,11 +219,11 @@ public class Login *

    * Compare User Info *

    - * Sets Context with login info + * Sets Context with login info * @param app_user user id * @param app_pwd password * @return role array or null if in error. - * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log + * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log * @deprecated use public KeyNamePair[] getRoles(String app_user, KeyNamePair client) */ public KeyNamePair[] getRoles (String app_user, String app_pwd) @@ -237,192 +237,192 @@ public class Login * @param app_pwd pwd * @param force ignore pwd * @return role array or null if in error. - * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log - * @deprecated use public KeyNamePair[] getRoles(String app_user, KeyNamePair client) + * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log + * @deprecated use public KeyNamePair[] getRoles(String app_user, KeyNamePair client) */ private KeyNamePair[] getRoles (String app_user, String app_pwd, boolean force) { - if (log.isLoggable(Level.INFO)) log.info("User=" + app_user); - - //long start = System.currentTimeMillis(); + if (log.isLoggable(Level.INFO)) log.info("User=" + app_user); + + //long start = System.currentTimeMillis(); if (app_user == null) { log.warning("No Apps User"); return null; } - // Authentication - boolean authenticated = false; + // Authentication + boolean authenticated = false; MSystem system = MSystem.get(m_ctx); - if (system == null) - throw new IllegalStateException("No System Info"); - - if (app_pwd == null || app_pwd.length() == 0) - { - log.warning("No Apps Password"); - return null; - } - - if (system.isLDAP()) - { - authenticated = system.isLDAP(app_user, app_pwd); - if (authenticated){ - app_pwd = null; - authenticated=true; - } - - // if not authenticated, use AD_User as backup - } - - boolean hash_password=MSysConfig.getBooleanValue(MSysConfig.USER_PASSWORD_HASH, false); - KeyNamePair[] retValue = null; - ArrayList list = new ArrayList(); - - - boolean email_login = MSysConfig.getBooleanValue(MSysConfig.USE_EMAIL_FOR_LOGIN, false); - String userNameCol; - if (email_login) - userNameCol = "AD_User.EMail"; - else - userNameCol = "COALESCE(AD_User.LDAPUser,AD_User.Name)"; - - if(hash_password){ - // adaxa-pb: try to authenticate using hashed password -- falls back to plain text/encrypted - String where = " " + userNameCol + " = ? AND" + - " EXISTS (SELECT * FROM AD_User_Roles ur" + - " INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID)" + - " WHERE ur.AD_User_ID=AD_User.AD_User_ID AND ur.IsActive='Y' AND r.IsActive='Y') AND " + - " EXISTS (SELECT * FROM AD_Client c" + - " WHERE c.AD_Client_ID=AD_User.AD_Client_ID" + - " AND c.IsActive='Y') AND " + - " AD_User.IsActive='Y'"; - - // deprecate this method - it cannot cope with same user found on multiple clients - // use public KeyNamePair[] getRoles(String app_user, KeyNamePair client) approach instead - MUser user = MTable.get(m_ctx, MUser.Table_ID).createQuery( where, null).setParameters(app_user).firstOnly(); // throws error if username collision occurs - - // always do calculation to confuse timing based attacks - if ( user == null ) - user = MUser.get(m_ctx, 0); - if ( user.authenticateHash(app_pwd) ) - { - authenticated = true; - } - } - else{ - StringBuffer sql = new StringBuffer("SELECT AD_User.AD_User_ID ").append(" FROM AD_User "); - sql.append(" WHERE ").append(userNameCol).append("=?"); - sql.append(" AND AD_User.IsActive='Y'").append(" AND EXISTS (SELECT * FROM AD_Client c WHERE AD_User.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')"); - - PreparedStatement pstmt1=null; - ResultSet rs1=null; - - try{ - pstmt1 = DB.prepareStatement(sql.toString(), null); - pstmt1.setString(1, app_user); - rs1 = pstmt1.executeQuery(); - - while(rs1.next()){ - MUser user = new MUser(m_ctx, rs1.getInt(1), null); - if (user.getPassword() != null && user.getPassword().equals(app_pwd)) { - authenticated=true; - } - - } - - }catch (Exception ex) { - // TODO: handle exception - log.log(Level.SEVERE, sql.toString(), ex); - log.saveError("DBLogin", ex); - retValue = null; - } - finally - { - DB.close(rs1, pstmt1); - rs1 = null; pstmt1 = null; - } - } - - if(authenticated){ + if (system == null) + throw new IllegalStateException("No System Info"); + + if (app_pwd == null || app_pwd.length() == 0) + { + log.warning("No Apps Password"); + return null; + } + + if (system.isLDAP()) + { + authenticated = system.isLDAP(app_user, app_pwd); + if (authenticated){ + app_pwd = null; + authenticated=true; + } + + // if not authenticated, use AD_User as backup + } + + boolean hash_password=MSysConfig.getBooleanValue(MSysConfig.USER_PASSWORD_HASH, false); + KeyNamePair[] retValue = null; + ArrayList list = new ArrayList(); + + + boolean email_login = MSysConfig.getBooleanValue(MSysConfig.USE_EMAIL_FOR_LOGIN, false); + String userNameCol; + if (email_login) + userNameCol = "AD_User.EMail"; + else + userNameCol = "COALESCE(AD_User.LDAPUser,AD_User.Name)"; + + if(hash_password){ + // adaxa-pb: try to authenticate using hashed password -- falls back to plain text/encrypted + String where = " " + userNameCol + " = ? AND" + + " EXISTS (SELECT * FROM AD_User_Roles ur" + + " INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID)" + + " WHERE ur.AD_User_ID=AD_User.AD_User_ID AND ur.IsActive='Y' AND r.IsActive='Y') AND " + + " EXISTS (SELECT * FROM AD_Client c" + + " WHERE c.AD_Client_ID=AD_User.AD_Client_ID" + + " AND c.IsActive='Y') AND " + + " AD_User.IsActive='Y'"; + + // deprecate this method - it cannot cope with same user found on multiple clients + // use public KeyNamePair[] getRoles(String app_user, KeyNamePair client) approach instead + MUser user = MTable.get(m_ctx, MUser.Table_ID).createQuery( where, null).setParameters(app_user).firstOnly(); // throws error if username collision occurs + + // always do calculation to confuse timing based attacks + if ( user == null ) + user = MUser.get(m_ctx, 0); + if ( user.authenticateHash(app_pwd) ) + { + authenticated = true; + } + } + else{ + StringBuffer sql = new StringBuffer("SELECT AD_User.AD_User_ID ").append(" FROM AD_User "); + sql.append(" WHERE ").append(userNameCol).append("=?"); + sql.append(" AND AD_User.IsActive='Y'").append(" AND EXISTS (SELECT * FROM AD_Client c WHERE AD_User.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')"); + + PreparedStatement pstmt1=null; + ResultSet rs1=null; + + try{ + pstmt1 = DB.prepareStatement(sql.toString(), null); + pstmt1.setString(1, app_user); + rs1 = pstmt1.executeQuery(); + + while(rs1.next()){ + MUser user = new MUser(m_ctx, rs1.getInt(1), null); + if (user.getPassword() != null && user.getPassword().equals(app_pwd)) { + authenticated=true; + } + + } + + }catch (Exception ex) { + // TODO: handle exception + log.log(Level.SEVERE, sql.toString(), ex); + log.saveError("DBLogin", ex); + retValue = null; + } + finally + { + DB.close(rs1, pstmt1); + rs1 = null; pstmt1 = null; + } + } + + if(authenticated){ StringBuffer sql = new StringBuffer("SELECT AD_User.AD_User_ID, r.AD_Role_ID,r.Name") - .append(" FROM AD_User ") - .append(" INNER JOIN AD_User_Roles ur ON (AD_User.AD_User_ID=ur.AD_User_ID AND ur.IsActive='Y')") - .append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID AND r.IsActive='Y') "); - - sql.append("WHERE ").append(userNameCol).append("=?"); // #1 - - sql.append(" AND AD_User.IsActive='Y'").append(" AND EXISTS (SELECT * FROM AD_Client c WHERE AD_User.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')"); - - sql.append(" ORDER BY r.Name"); - - PreparedStatement pstmt = null; + .append(" FROM AD_User ") + .append(" INNER JOIN AD_User_Roles ur ON (AD_User.AD_User_ID=ur.AD_User_ID AND ur.IsActive='Y')") + .append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID AND r.IsActive='Y') "); + + sql.append("WHERE ").append(userNameCol).append("=?"); // #1 + + sql.append(" AND AD_User.IsActive='Y'").append(" AND EXISTS (SELECT * FROM AD_Client c WHERE AD_User.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')"); + + sql.append(" ORDER BY r.Name"); + + PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql.toString(), null); - pstmt.setString(1, app_user); - + pstmt.setString(1, app_user); + // execute a query - rs = pstmt.executeQuery(); - - if (!rs.next()) // no record found - if (force) - { - Env.setContext(m_ctx, "#AD_User_Name", "System"); - Env.setContext(m_ctx, "#AD_User_ID", "0"); - Env.setContext(m_ctx, "#AD_User_Description", "System Forced Login"); - Env.setContext(m_ctx, "#User_Level", "S "); // Format 'SCO' - Env.setContext(m_ctx, "#User_Client", "0"); // Format c1, c2, ... - Env.setContext(m_ctx, "#User_Org", "0"); // Format o1, o2, ... - retValue = new KeyNamePair[] {new KeyNamePair(0, "System Administrator")}; - return retValue; - } - else - { - log.saveError("UserPwdError", app_user, false); - return null; - } - - Env.setContext(m_ctx, "#AD_User_Name", app_user); - Env.setContext(m_ctx, "#AD_User_ID", rs.getInt(1)); - Env.setContext(m_ctx, "#SalesRep_ID", rs.getInt(1)); - - if (Ini.isClient()) - { - if (MSystem.isSwingRememberUserAllowed()) - Ini.setProperty(Ini.P_UID, app_user); + rs = pstmt.executeQuery(); + + if (!rs.next()) // no record found + if (force) + { + Env.setContext(m_ctx, "#AD_User_Name", "System"); + Env.setContext(m_ctx, "#AD_User_ID", "0"); + Env.setContext(m_ctx, "#AD_User_Description", "System Forced Login"); + Env.setContext(m_ctx, "#User_Level", "S "); // Format 'SCO' + Env.setContext(m_ctx, "#User_Client", "0"); // Format c1, c2, ... + Env.setContext(m_ctx, "#User_Org", "0"); // Format o1, o2, ... + retValue = new KeyNamePair[] {new KeyNamePair(0, "System Administrator")}; + return retValue; + } else - Ini.setProperty(Ini.P_UID, ""); + { + log.saveError("UserPwdError", app_user, false); + return null; + } + + Env.setContext(m_ctx, "#AD_User_Name", app_user); + Env.setContext(m_ctx, "#AD_User_ID", rs.getInt(1)); + Env.setContext(m_ctx, "#SalesRep_ID", rs.getInt(1)); + + if (Ini.isClient()) + { + if (MSystem.isSwingRememberUserAllowed()) + Ini.setProperty(Ini.P_UID, app_user); + else + Ini.setProperty(Ini.P_UID, ""); if (Ini.isPropertyBool(Ini.P_STORE_PWD) && MSystem.isSwingRememberPasswordAllowed()) Ini.setProperty(Ini.P_PWD, app_pwd); } - + do // read all roles - { - MUser user = new MUser(m_ctx, rs.getInt(1), null); - boolean valid = false; - if (hash_password) { - valid = user.authenticateHash(app_pwd); - } else { - valid = user.getPassword() != null && user.getPassword().equals(app_pwd); - } + { + MUser user = new MUser(m_ctx, rs.getInt(1), null); + boolean valid = false; + if (hash_password) { + valid = user.authenticateHash(app_pwd); + } else { + valid = user.getPassword() != null && user.getPassword().equals(app_pwd); + } if (valid) { int AD_Role_ID = rs.getInt(2); if (AD_Role_ID == 0) Env.setContext(m_ctx, "#SysAdmin", "Y"); String Name = rs.getString(3); KeyNamePair p = new KeyNamePair(AD_Role_ID, Name); - list.add(p); + list.add(p); } } while (rs.next()); // retValue = new KeyNamePair[list.size()]; list.toArray(retValue); - if (log.isLoggable(Level.FINE)) log.fine("User=" + app_user + " - roles #" + retValue.length); - - } - + if (log.isLoggable(Level.FINE)) log.fine("User=" + app_user + " - roles #" + retValue.length); + + } + catch (Exception ex) { log.log(Level.SEVERE, sql.toString(), ex); @@ -430,17 +430,17 @@ public class Login retValue = null; } // - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - app_pwd = null; - } - } - //long ms = System.currentTimeMillis () - start; - return retValue; - } // getRoles - + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + app_pwd = null; + } + } + //long ms = System.currentTimeMillis () - start; + return retValue; + } // getRoles + /************************************************************************** * Load Clients. @@ -452,9 +452,9 @@ public class Login public KeyNamePair[] getClients (KeyNamePair role) { if (role == null) - throw new IllegalArgumentException("Role missing"); - - loginErrMsg = null; + throw new IllegalArgumentException("Role missing"); + + loginErrMsg = null; isPasswordExpired = false; // s_log.fine("loadClients - Role: " + role.toStringX()); @@ -468,7 +468,7 @@ public class Login + "WHERE r.AD_Role_ID=?" // #1 + " AND r.IsActive='Y' AND c.IsActive='Y'"; - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; // get Role details try @@ -502,17 +502,17 @@ public class Login // retValue = new KeyNamePair[list.size()]; list.toArray(retValue); - if (log.isLoggable(Level.FINE)) log.fine("Role: " + role.toStringX() + " - clients #" + retValue.length); + if (log.isLoggable(Level.FINE)) log.fine("Role: " + role.toStringX() + " - clients #" + retValue.length); } catch (SQLException ex) { log.log(Level.SEVERE, sql, ex); retValue = null; } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } return retValue; } // getClients @@ -524,100 +524,100 @@ public class Login * @param client client information * @return list of valid Org KeyNodePairs or null if in error */ - public KeyNamePair[] getOrgs (KeyNamePair rol) + public KeyNamePair[] getOrgs (KeyNamePair rol) { - if (rol == null) - throw new IllegalArgumentException("Rol missing"); - if (Env.getContext(m_ctx,"#AD_Client_ID").length() == 0) // could be number 0 - throw new UnsupportedOperationException("Missing Context #AD_Client_ID"); + if (rol == null) + throw new IllegalArgumentException("Rol missing"); + if (Env.getContext(m_ctx,"#AD_Client_ID").length() == 0) // could be number 0 + throw new UnsupportedOperationException("Missing Context #AD_Client_ID"); - int AD_Client_ID = Env.getContextAsInt(m_ctx,"#AD_Client_ID"); + int AD_Client_ID = Env.getContextAsInt(m_ctx,"#AD_Client_ID"); int AD_User_ID = Env.getContextAsInt(m_ctx, "#AD_User_ID"); // s_log.fine("Client: " + client.toStringX() + ", AD_Role_ID=" + AD_Role_ID); // get Client details for role ArrayList list = new ArrayList(); KeyNamePair[] retValue = null; - // - String sql = " SELECT DISTINCT r.UserLevel, r.ConnectionProfile,o.AD_Org_ID,o.Name,o.IsSummary " - +" FROM AD_Org o" - +" INNER JOIN AD_Role r on (r.AD_Role_ID=?)" - +" INNER JOIN AD_Client c on (c.AD_Client_ID=?)" - +" WHERE o.IsActive='Y' " - +" AND o.AD_Client_ID IN (0, c.AD_Client_ID)" - +" AND (r.IsAccessAllOrgs='Y'" - +" OR (r.IsUseUserOrgAccess='N' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_Role_OrgAccess ra" - +" WHERE ra.AD_Role_ID=r.AD_Role_ID AND ra.IsActive='Y')) " - +" OR (r.IsUseUserOrgAccess='Y' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_User_OrgAccess ua" - +" WHERE ua.AD_User_ID=?" - +" AND ua.IsActive='Y')))" - + "ORDER BY o.Name"; + // + String sql = " SELECT DISTINCT r.UserLevel, r.ConnectionProfile,o.AD_Org_ID,o.Name,o.IsSummary " + +" FROM AD_Org o" + +" INNER JOIN AD_Role r on (r.AD_Role_ID=?)" + +" INNER JOIN AD_Client c on (c.AD_Client_ID=?)" + +" WHERE o.IsActive='Y' " + +" AND o.AD_Client_ID IN (0, c.AD_Client_ID)" + +" AND (r.IsAccessAllOrgs='Y'" + +" OR (r.IsUseUserOrgAccess='N' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_Role_OrgAccess ra" + +" WHERE ra.AD_Role_ID=r.AD_Role_ID AND ra.IsActive='Y')) " + +" OR (r.IsUseUserOrgAccess='Y' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_User_OrgAccess ua" + +" WHERE ua.AD_User_ID=?" + +" AND ua.IsActive='Y')))" + + "ORDER BY o.Name"; // PreparedStatement pstmt = null; - MRole role = null; + MRole role = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, rol.getKey()); - pstmt.setInt(2, AD_Client_ID); + pstmt.setInt(1, rol.getKey()); + pstmt.setInt(2, AD_Client_ID); pstmt.setInt(3, AD_User_ID); rs = pstmt.executeQuery(); // load Orgs - if (!rs.next()) - { - log.log(Level.SEVERE, "No org for Role: " + rol.toStringX()); - return null; - } - // Role Info - Env.setContext(m_ctx, "#AD_Role_ID", rol.getKey()); - Env.setContext(m_ctx, "#AD_Role_Name", rol.getName()); - Ini.setProperty(Ini.P_ROLE, rol.getName()); - // User Level - Env.setContext(m_ctx, "#User_Level", rs.getString(1)); // Format 'SCO' - // load Orgs - - do{ - int AD_Org_ID = rs.getInt(3); - String Name = rs.getString(4); - boolean summary = "Y".equals(rs.getString(5)); - if (summary) - { - if (role == null) - role = MRole.get(m_ctx, rol.getKey()); - getOrgsAddSummary (list, AD_Org_ID, Name, role); - } - else - { - KeyNamePair p = new KeyNamePair(AD_Org_ID, Name); - if (!list.contains(p)) - list.add(p); - } - }while (rs.next()); - - retValue = new KeyNamePair[list.size()]; - list.toArray(retValue); - - if (log.isLoggable(Level.FINE)) log.fine("Client: " + AD_Client_ID +", AD_Role_ID=" + rol.getName()+", AD_User_ID=" + AD_User_ID+" - orgs #" + retValue.length); - } - catch (SQLException ex) - { - log.log(Level.SEVERE, sql, ex); - retValue = null; - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - - if (retValue == null || retValue.length == 0) - { - log.log(Level.WARNING, "No Org for Client: " + AD_Client_ID - + ", AD_Role_ID=" + rol.getKey() - + ", AD_User_ID=" + AD_User_ID); - return null; - } + if (!rs.next()) + { + log.log(Level.SEVERE, "No org for Role: " + rol.toStringX()); + return null; + } + // Role Info + Env.setContext(m_ctx, "#AD_Role_ID", rol.getKey()); + Env.setContext(m_ctx, "#AD_Role_Name", rol.getName()); + Ini.setProperty(Ini.P_ROLE, rol.getName()); + // User Level + Env.setContext(m_ctx, "#User_Level", rs.getString(1)); // Format 'SCO' + // load Orgs + + do{ + int AD_Org_ID = rs.getInt(3); + String Name = rs.getString(4); + boolean summary = "Y".equals(rs.getString(5)); + if (summary) + { + if (role == null) + role = MRole.get(m_ctx, rol.getKey()); + getOrgsAddSummary (list, AD_Org_ID, Name, role); + } + else + { + KeyNamePair p = new KeyNamePair(AD_Org_ID, Name); + if (!list.contains(p)) + list.add(p); + } + }while (rs.next()); + + retValue = new KeyNamePair[list.size()]; + list.toArray(retValue); + + if (log.isLoggable(Level.FINE)) log.fine("Client: " + AD_Client_ID +", AD_Role_ID=" + rol.getName()+", AD_User_ID=" + AD_User_ID+" - orgs #" + retValue.length); + } + catch (SQLException ex) + { + log.log(Level.SEVERE, sql, ex); + retValue = null; + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + + if (retValue == null || retValue.length == 0) + { + log.log(Level.WARNING, "No Org for Client: " + AD_Client_ID + + ", AD_Role_ID=" + rol.getKey() + + ", AD_User_ID=" + AD_User_ID); + return null; + } return retValue; } // getOrgs @@ -640,7 +640,7 @@ public class Login // Do we look for trees? if (role.getAD_Tree_Org_ID() == 0) { - if (log.isLoggable(Level.CONFIG)) log.config("Summary Org=" + Summary_Name + "(" + Summary_Org_ID + ") - No Org Tree: " + role); + if (log.isLoggable(Level.CONFIG)) log.config("Summary Org=" + Summary_Name + "(" + Summary_Org_ID + ") - No Org Tree: " + role); return; } // Summary Org - Get Dependents @@ -650,7 +650,7 @@ public class Login + tree.getNodeTableName() + " WHERE AD_Tree_ID=? AND Parent_ID=? AND IsActive='Y') " + "ORDER BY Name"; - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -660,7 +660,7 @@ public class Login rs = pstmt.executeQuery (); while (rs.next ()) { - //int AD_Client_ID = rs.getInt(1); + //int AD_Client_ID = rs.getInt(1); int AD_Org_ID = rs.getInt(2); String Name = rs.getString(3); boolean summary = "Y".equals(rs.getString(4)); @@ -679,10 +679,10 @@ public class Login { log.log (Level.SEVERE, sql, e); } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } } // getOrgAddSummary @@ -702,10 +702,10 @@ public class Login ArrayList list = new ArrayList(); KeyNamePair[] retValue = null; String sql = "SELECT M_Warehouse_ID, Name FROM M_Warehouse " - + "WHERE AD_Org_ID=? AND IsActive='Y' " + + "WHERE AD_Org_ID=? AND IsActive='Y' " + " AND "+I_M_Warehouse.COLUMNNAME_IsInTransit+"='N' " // do not show in tranzit warehouses - teo_sarca [ 2867246 ] + "ORDER BY Name"; - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -715,7 +715,7 @@ public class Login if (!rs.next()) { - if (log.isLoggable(Level.INFO)) log.info("No Warehouses for Org: " + org.toStringX()); + if (log.isLoggable(Level.INFO)) log.info("No Warehouses for Org: " + org.toStringX()); return null; } @@ -732,7 +732,7 @@ public class Login // retValue = new KeyNamePair[list.size()]; list.toArray(retValue); - if (log.isLoggable(Level.FINE)) log.fine("Org: " + org.toStringX() + if (log.isLoggable(Level.FINE)) log.fine("Org: " + org.toStringX() + " - warehouses #" + retValue.length); } catch (SQLException ex) @@ -740,10 +740,10 @@ public class Login log.log(Level.SEVERE, "getWarehouses", ex); retValue = null; } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } return retValue; } // getWarehouses @@ -764,15 +764,15 @@ public class Login { log.severe("Refused: " + error); return error; - } - - // IDEMPIERE-1717 Maintenance mode - if (! MRole.get(m_ctx, AD_Role_ID).isAccessAdvanced()) { - if (MSysConfig.getBooleanValue(MSysConfig.SYSTEM_IN_MAINTENANCE_MODE, false, 0)) - return Msg.getMsg(m_ctx, "SystemInMaintenance"); - if (AD_Client_ID != 0 && MSysConfig.getBooleanValue(MSysConfig.SYSTEM_IN_MAINTENANCE_MODE, false, AD_Client_ID)) - return Msg.getMsg(m_ctx, "SystemInMaintenance"); - } + } + + // IDEMPIERE-1717 Maintenance mode + if (! MRole.get(m_ctx, AD_Role_ID).isAccessAdvanced()) { + if (MSysConfig.getBooleanValue(MSysConfig.SYSTEM_IN_MAINTENANCE_MODE, false, 0)) + return Msg.getMsg(m_ctx, "SystemInMaintenance"); + if (AD_Client_ID != 0 && MSysConfig.getBooleanValue(MSysConfig.SYSTEM_IN_MAINTENANCE_MODE, false, AD_Client_ID)) + return Msg.getMsg(m_ctx, "SystemInMaintenance"); + } return null; } // validateLogin @@ -797,7 +797,7 @@ public class Login public String loadPreferences (KeyNamePair org, KeyNamePair warehouse, java.sql.Timestamp timestamp, String printerName) { - if (log.isLoggable(Level.INFO)) log.info("Org: " + org.toStringX()); + if (log.isLoggable(Level.INFO)) log.info("Org: " + org.toStringX()); if (m_ctx == null || org == null) throw new IllegalArgumentException("Required parameter missing"); @@ -835,7 +835,7 @@ public class Login // Load Role Info MRole.getDefault(m_ctx, true); - // Other + // Other loadUserPreferences(); if (MRole.getDefault(m_ctx, false).isShowAcct()) @@ -858,12 +858,12 @@ public class Login + "FROM C_AcctSchema a, AD_ClientInfo c " + "WHERE a.C_AcctSchema_ID=c.C_AcctSchema1_ID " + "AND c.AD_Client_ID=?"; - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try - { + { - int C_AcctSchema_ID = 0; + int C_AcctSchema_ID = 0; pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, AD_Client_ID); @@ -883,32 +883,32 @@ public class Login Env.setContext(m_ctx, "$C_Currency_ID", rs.getInt("C_Currency_ID")); Env.setContext(m_ctx, "$HasAlias", rs.getString("HasAlias")); } - DB.close(rs, pstmt); - rs = null; pstmt = null; - - /**Define AcctSchema , Currency, HasAlias for Multi AcctSchema**/ - MAcctSchema[] ass = MAcctSchema.getClientAcctSchema(Env.getCtx(), AD_Client_ID); - if(ass != null && ass.length > 1) - { - for(MAcctSchema as : ass) - { - C_AcctSchema_ID = MClientInfo.get(Env.getCtx(), AD_Client_ID).getC_AcctSchema1_ID(); - if (as.getAD_OrgOnly_ID() != 0) - { - if (as.isSkipOrg(AD_Org_ID)) - { - continue; - } - else - { - C_AcctSchema_ID = as.getC_AcctSchema_ID(); - Env.setContext(m_ctx, "$C_AcctSchema_ID", C_AcctSchema_ID); - Env.setContext(m_ctx, "$C_Currency_ID", as.getC_Currency_ID()); - Env.setContext(m_ctx, "$HasAlias", as.isHasAlias()); - break; - } - } - } + DB.close(rs, pstmt); + rs = null; pstmt = null; + + /**Define AcctSchema , Currency, HasAlias for Multi AcctSchema**/ + MAcctSchema[] ass = MAcctSchema.getClientAcctSchema(Env.getCtx(), AD_Client_ID); + if(ass != null && ass.length > 1) + { + for(MAcctSchema as : ass) + { + C_AcctSchema_ID = MClientInfo.get(Env.getCtx(), AD_Client_ID).getC_AcctSchema1_ID(); + if (as.getAD_OrgOnly_ID() != 0) + { + if (as.isSkipOrg(AD_Org_ID)) + { + continue; + } + else + { + C_AcctSchema_ID = as.getC_AcctSchema_ID(); + Env.setContext(m_ctx, "$C_AcctSchema_ID", C_AcctSchema_ID); + Env.setContext(m_ctx, "$C_Currency_ID", as.getC_Currency_ID()); + Env.setContext(m_ctx, "$HasAlias", as.isHasAlias()); + break; + } + } + } } // Accounting Elements @@ -921,12 +921,12 @@ public class Login rs = pstmt.executeQuery(); while (rs.next()) Env.setContext(m_ctx, "$Element_" + rs.getString("ElementType"), "Y"); - DB.close(rs, pstmt); - rs = null; pstmt = null; + DB.close(rs, pstmt); + rs = null; pstmt = null; // This reads all relevant window neutral defaults // overwriting superseeded ones. Window specific is read in Mainain - sql = "SELECT Attribute, Value, AD_Window_ID, AD_Process_ID, AD_InfoWindow_ID, PreferenceFor " + sql = "SELECT Attribute, Value, AD_Window_ID, AD_Process_ID, AD_InfoWindow_ID, PreferenceFor " + "FROM AD_Preference " + "WHERE AD_Client_ID IN (0, @#AD_Client_ID@)" + " AND AD_Org_ID IN (0, @#AD_Org_ID@)" @@ -944,34 +944,34 @@ public class Login while (rs.next()) { int AD_Window_ID = rs.getInt(3); - boolean isAllWindow = rs.wasNull(); - int AD_Process_ID = rs.getInt(4); - int AD_InfoWindow_ID = rs.getInt(5); - String PreferenceFor = rs.getString(6); + boolean isAllWindow = rs.wasNull(); + int AD_Process_ID = rs.getInt(4); + int AD_InfoWindow_ID = rs.getInt(5); + String PreferenceFor = rs.getString(6); String at = ""; - - // preference for window - if ("W".equals(PreferenceFor)){ - if (isAllWindow) + + // preference for window + if ("W".equals(PreferenceFor)){ + if (isAllWindow) at = "P|" + rs.getString(1); else at = "P" + AD_Window_ID + "|" + rs.getString(1); - }else if ("P".equals(PreferenceFor)){ // preference for processs - // when apply for all window or all process format is "P0|0|m_Attribute; - at = "P" + AD_Window_ID + "|" + AD_InfoWindow_ID + "|" + AD_Process_ID + "|" + rs.getString(1); - }else if ("I".equals(PreferenceFor)){ // preference for infoWindow - at = "P" + AD_Window_ID + "|" + AD_InfoWindow_ID + "|" + rs.getString(1); - } - + }else if ("P".equals(PreferenceFor)){ // preference for processs + // when apply for all window or all process format is "P0|0|m_Attribute; + at = "P" + AD_Window_ID + "|" + AD_InfoWindow_ID + "|" + AD_Process_ID + "|" + rs.getString(1); + }else if ("I".equals(PreferenceFor)){ // preference for infoWindow + at = "P" + AD_Window_ID + "|" + AD_InfoWindow_ID + "|" + rs.getString(1); + } + String va = rs.getString(2); Env.setContext(m_ctx, at, va); } - DB.close(rs, pstmt); - rs = null; pstmt = null; + DB.close(rs, pstmt); + rs = null; pstmt = null; } // Default Values - if (log.isLoggable(Level.INFO)) log.info("Default Values ..."); + if (log.isLoggable(Level.INFO)) log.info("Default Values ..."); sql = "SELECT t.TableName, c.ColumnName " + "FROM AD_Column c " + " INNER JOIN AD_Table t ON (c.AD_Table_ID=t.AD_Table_ID) " @@ -987,24 +987,24 @@ public class Login { log.log(Level.SEVERE, "loadPreferences", e); } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } // Country Env.setContext(m_ctx, "#C_Country_ID", MCountry.getDefault(m_ctx).getC_Country_ID()); - // Call ModelValidators afterLoadPreferences - teo_sarca FR [ 1670025 ] - ModelValidationEngine.get().afterLoadPreferences(m_ctx); + // Call ModelValidators afterLoadPreferences - teo_sarca FR [ 1670025 ] + ModelValidationEngine.get().afterLoadPreferences(m_ctx); return retValue; - } // loadPreferences - - /** - * Load preferences based on user - */ - public void loadUserPreferences(){ - MUserPreference userPreference = MUserPreference.getUserPreference(Env.getAD_User_ID(m_ctx), Env.getAD_Client_ID(m_ctx)); - userPreference.fillPreferences(); + } // loadPreferences + + /** + * Load preferences based on user + */ + public void loadUserPreferences(){ + MUserPreference userPreference = MUserPreference.getUserPreference(Env.getAD_User_ID(m_ctx), Env.getAD_Client_ID(m_ctx)); + userPreference.fillPreferences(); }// loadUserPreferences /** @@ -1016,7 +1016,7 @@ public class Login { if (TableName.startsWith("AD_Window") || TableName.startsWith("AD_PrintFormat") - || TableName.startsWith("AD_Workflow") + || TableName.startsWith("AD_Workflow") || TableName.startsWith("M_Locator") ) return; String value = null; @@ -1025,7 +1025,7 @@ public class Login + " WHERE IsDefault='Y' AND IsActive='Y' ORDER BY AD_Client_ID DESC, AD_Org_ID DESC"; sql = MRole.getDefault(m_ctx, false).addAccessSQL(sql, TableName, MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); - PreparedStatement pstmt = null; + PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -1039,10 +1039,10 @@ public class Login log.log(Level.SEVERE, TableName + " (" + sql + ")", e); return; } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } // Set Context Value if (value != null && value.length() != 0) @@ -1054,13 +1054,13 @@ public class Login } } // loadDefault - /** - * Batch Login using Ini values - * - Adempiere.startup(true); - Ini.setProperty(Ini.P_UID,"SuperUser"); - Ini.setProperty(Ini.P_PWD,"System"); - Ini.setProperty(Ini.P_ROLE,"GardenAdmin"); + /** + * Batch Login using Ini values + * + Adempiere.startup(true); + Ini.setProperty(Ini.P_UID,"SuperUser"); + Ini.setProperty(Ini.P_PWD,"System"); + Ini.setProperty(Ini.P_ROLE,"GardenAdmin"); Ini.setProperty(Ini.P_CLIENT, "Garden World"); Ini.setProperty(Ini.P_ORG,"HQ"); Ini.setProperty(Ini.P_WAREHOUSE,"HQ"); @@ -1076,46 +1076,46 @@ public class Login { // User Login String uid = Ini.getProperty(Ini.P_UID); - String pwd = Ini.getProperty(Ini.P_PWD); - - String client = Ini.getProperty(Ini.P_CLIENT); - KeyNamePair[] clients = getClients(uid, pwd); - if (clients == null || clients.length == 0) - { - log.severe("User/Password invalid: " + uid); - return false; - } - KeyNamePair clientPP = null; - for (KeyNamePair pair : clients) - { - if (pair.getName().equalsIgnoreCase(client)) - { - clientPP = pair; - break; - } - } - if (clientPP == null) - { - log.severe("Client invalid: " + client); - if (log.isLoggable(Level.INFO)) { - for (KeyNamePair pair : clients) - log.info("Option: " + pair); - } - return false; - } - - KeyNamePair[] roles = getRoles(uid, clientPP); - if (roles == null || roles.length == 0) + String pwd = Ini.getProperty(Ini.P_PWD); + + String client = Ini.getProperty(Ini.P_CLIENT); + KeyNamePair[] clients = getClients(uid, pwd); + if (clients == null || clients.length == 0) { - log.severe("No Roles for client: " + client); + log.severe("User/Password invalid: " + uid); return false; } - if (log.isLoggable(Level.INFO)) log.info("User: " + uid); + KeyNamePair clientPP = null; + for (KeyNamePair pair : clients) + { + if (pair.getName().equalsIgnoreCase(client)) + { + clientPP = pair; + break; + } + } + if (clientPP == null) + { + log.severe("Client invalid: " + client); + if (log.isLoggable(Level.INFO)) { + for (KeyNamePair pair : clients) + log.info("Option: " + pair); + } + return false; + } + + KeyNamePair[] roles = getRoles(uid, clientPP); + if (roles == null || roles.length == 0) + { + log.severe("No Roles for client: " + client); + return false; + } + if (log.isLoggable(Level.INFO)) log.info("User: " + uid); // Role String role = Ini.getProperty(Ini.P_ROLE); KeyNamePair rolePP = null; - for (KeyNamePair pair : roles) + for (KeyNamePair pair : roles) { if (pair.getName().equalsIgnoreCase(role)) { @@ -1125,25 +1125,25 @@ public class Login } if (rolePP == null) { - log.severe("Role invalid: " + role); - if (log.isLoggable(Level.INFO)) { - for (int i = 0; i < roles.length; i++) - log.info("Option: " + roles[i]); + log.severe("Role invalid: " + role); + if (log.isLoggable(Level.INFO)) { + for (int i = 0; i < roles.length; i++) + log.info("Option: " + roles[i]); } return false; } - if (log.isLoggable(Level.INFO)) log.info("Role: " + role); + if (log.isLoggable(Level.INFO)) log.info("Role: " + role); // Organization String org = Ini.getProperty(Ini.P_ORG); - KeyNamePair[] orgs = getOrgs(rolePP); + KeyNamePair[] orgs = getOrgs(rolePP); if (orgs == null || orgs.length == 0) { - log.severe("No Orgs for Role: " + role); + log.severe("No Orgs for Role: " + role); return false; } KeyNamePair orgPP = null; - for (KeyNamePair pair : orgs) + for (KeyNamePair pair : orgs) { if (pair.getName().equalsIgnoreCase(org)) { @@ -1153,43 +1153,43 @@ public class Login } if (orgPP == null) { - log.severe("Org invalid: " + org); - if (log.isLoggable(Level.INFO)) { - for (int i = 0; i < orgs.length; i++) - log.info("Option: " + orgs[i]); + log.severe("Org invalid: " + org); + if (log.isLoggable(Level.INFO)) { + for (int i = 0; i < orgs.length; i++) + log.info("Option: " + orgs[i]); } return false; - } + } // Warehouse - String wh = Ini.getProperty(Ini.P_WAREHOUSE); - KeyNamePair whPP = null; - - if (orgPP.getKey() != 0) { - KeyNamePair[] whs = getWarehouses(orgPP); - if (whs == null || whs.length == 0) + String wh = Ini.getProperty(Ini.P_WAREHOUSE); + KeyNamePair whPP = null; + + if (orgPP.getKey() != 0) { + KeyNamePair[] whs = getWarehouses(orgPP); + if (whs == null || whs.length == 0) { - log.severe("No Warehouses for Org: " + org); - return false; + log.severe("No Warehouses for Org: " + org); + return false; } - for (int i = 0; i < whs.length; i++) - { - KeyNamePair pair = whs[i]; - if (pair.getName().equalsIgnoreCase(wh)) - { - whPP = pair; - break; - } + for (int i = 0; i < whs.length; i++) + { + KeyNamePair pair = whs[i]; + if (pair.getName().equalsIgnoreCase(wh)) + { + whPP = pair; + break; + } + } + if (whPP == null) + { + log.severe("Warehouse invalid: " + wh); + if (log.isLoggable(Level.INFO)) { + for (int i = 0; i < whs.length; i++) + log.info("Option: " + whs[i]); + } + return false; } - if (whPP == null) - { - log.severe("Warehouse invalid: " + wh); - if (log.isLoggable(Level.INFO)) { - for (int i = 0; i < whs.length; i++) - log.info("Option: " + whs[i]); - } - return false; - } } // Language @@ -1206,13 +1206,13 @@ public class Login String printerName = Ini.getProperty(Ini.P_PRINTER); if (loginDate == null) loginDate = new java.sql.Timestamp(System.currentTimeMillis()); - loadPreferences(orgPP, whPP, loginDate, printerName); - - String error = validateLogin(orgPP); - if (error != null && error.length() > 0) - return false; + loadPreferences(orgPP, whPP, loginDate, printerName); + + String error = validateLogin(orgPP); + if (error != null && error.length() > 0) + return false; // - if (log.isLoggable(Level.INFO)) log.info("complete"); + if (log.isLoggable(Level.INFO)) log.info("complete"); return true; } // batchLogin @@ -1232,405 +1232,405 @@ public class Login public Principal getPrincipal() { return null; - } // getPrincipal - - /** - * Validate Client Login. - * Sets Context with login info - * @param app_user user id - * @param app_pwd password - * @return client array or null if in error. - */ - public KeyNamePair[] getClients(String app_user, String app_pwd) { - if (log.isLoggable(Level.INFO)) log.info("User=" + app_user); - - if (Util.isEmpty(app_user)) - { - log.warning("No Apps User"); - return null; - } - - // Authentication - boolean authenticated = false; - MSystem system = MSystem.get(m_ctx); - if (system == null) - throw new IllegalStateException("No System Info"); - - if (app_pwd == null || app_pwd.length() == 0) - { - log.warning("No Apps Password"); - return null; - } - - loginErrMsg = null; - isPasswordExpired = false; - - if (system.isLDAP()) - { - authenticated = system.isLDAP(app_user, app_pwd); - // if not authenticated, use AD_User as backup - } - - boolean hash_password = MSysConfig.getBooleanValue(MSysConfig.USER_PASSWORD_HASH, false); - boolean email_login = MSysConfig.getBooleanValue(MSysConfig.USE_EMAIL_FOR_LOGIN, false); - KeyNamePair[] retValue = null; - ArrayList clientList = new ArrayList(); - ArrayList clientsValidated = new ArrayList(); - - StringBuilder where = new StringBuilder("Password IS NOT NULL AND "); - if (email_login) - where.append("EMail=?"); - else - where.append("COALESCE(LDAPUser,Name)=?"); - where.append(" AND") - .append(" EXISTS (SELECT * FROM AD_User_Roles ur") - .append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID)") - .append(" WHERE ur.AD_User_ID=AD_User.AD_User_ID AND ur.IsActive='Y' AND r.IsActive='Y') AND ") - .append(" EXISTS (SELECT * FROM AD_Client c") - .append(" WHERE c.AD_Client_ID=AD_User.AD_Client_ID") - .append(" AND c.IsActive='Y') AND ") - .append(" AD_User.IsActive='Y'"); - - List users = new Query(m_ctx, MUser.Table_Name, where.toString(), null) - .setParameters(app_user) - .setOrderBy(MUser.COLUMNNAME_AD_User_ID) - .list(); - - if (users.size() == 0) { - log.saveError("UserPwdError", app_user, false); - return null; - } - - int MAX_ACCOUNT_LOCK_MINUTES = MSysConfig.getIntValue(MSysConfig.USER_LOCKING_MAX_ACCOUNT_LOCK_MINUTES, 0); - int MAX_INACTIVE_PERIOD_DAY = MSysConfig.getIntValue(MSysConfig.USER_LOCKING_MAX_INACTIVE_PERIOD_DAY, 0); - int MAX_PASSWORD_AGE = MSysConfig.getIntValue(MSysConfig.USER_LOCKING_MAX_PASSWORD_AGE_DAY, 0); - long now = new Date().getTime(); - for (MUser user : users) { - if (MAX_ACCOUNT_LOCK_MINUTES > 0 && user.isLocked() && user.getDateAccountLocked() != null) - { - long minutes = (now - user.getDateAccountLocked().getTime()) / (1000 * 60); - if (minutes > MAX_ACCOUNT_LOCK_MINUTES) - { - boolean inactive = false; - if (MAX_INACTIVE_PERIOD_DAY > 0 && user.getDateLastLogin() != null && !user.isNoExpire()) - { - long days = (now - user.getDateLastLogin().getTime()) / (1000 * 60 * 60 * 24); - if (days > MAX_INACTIVE_PERIOD_DAY) - inactive = true; - } - - if (!inactive) - { - user.setIsLocked(false); - user.setDateAccountLocked(null); - user.setFailedLoginCount(0); - Env.setContext(Env.getCtx(), "#AD_Client_ID", user.getAD_Client_ID()); - if (!user.save()) - log.severe("Failed to unlock user account"); - } - } - } - - if (MAX_INACTIVE_PERIOD_DAY > 0 && !user.isLocked() && user.getDateLastLogin() != null && !user.isNoExpire()) - { - long days = (now - user.getDateLastLogin().getTime()) / (1000 * 60 * 60 * 24); - if (days > MAX_INACTIVE_PERIOD_DAY) - { - user.setIsLocked(true); - user.setDateAccountLocked(new Timestamp(now)); - Env.setContext(Env.getCtx(), "#AD_Client_ID", user.getAD_Client_ID()); - if (!user.save()) - log.severe("Failed to lock user account"); - } - } - } - - boolean validButLocked = false; - for (MUser user : users) { - if (clientsValidated.contains(user.getAD_Client_ID())) { - log.severe("Two users with password with the same name/email combination on same tenant: " + app_user); - return null; - } - clientsValidated.add(user.getAD_Client_ID()); - boolean valid = false; - // authenticated by ldap - if (authenticated){ - valid = true; - } else if (hash_password) { - valid = user.authenticateHash(app_pwd); - } else { - // password not hashed - valid = user.getPassword() != null && user.getPassword().equals(app_pwd); - } - - if (valid ) { - if (user.isLocked()) - { - validButLocked = true; - continue; - } - - if (authenticated){ - // use Ldap because don't check password age - } - else if (user.isExpired()) - isPasswordExpired = true; - else if (MAX_PASSWORD_AGE > 0 && !user.isNoPasswordReset()) - { - if (user.getDatePasswordChanged() == null) - user.setDatePasswordChanged(new Timestamp(now)); - - long days = (now - user.getDatePasswordChanged().getTime()) / (1000 * 60 * 60 * 24); - if (days > MAX_PASSWORD_AGE) - { - user.setIsExpired(true); - isPasswordExpired = true; - } - } - - StringBuilder sql= new StringBuilder("SELECT DISTINCT cli.AD_Client_ID, cli.Name, u.AD_User_ID, u.Name"); - sql.append(" FROM AD_User_Roles ur") - .append(" INNER JOIN AD_User u on (ur.AD_User_ID=u.AD_User_ID)") - .append(" INNER JOIN AD_Client cli on (ur.AD_Client_ID=cli.AD_Client_ID)") - .append(" WHERE ur.IsActive='Y'") - .append(" AND u.IsActive='Y'") - .append(" AND cli.IsActive='Y'") - .append(" AND ur.AD_User_ID=? ORDER BY cli.Name"); - PreparedStatement pstmt=null; - ResultSet rs=null; - try{ - pstmt=DB.prepareStatement(sql.toString(),null); - pstmt.setInt(1, user.getAD_User_ID()); - rs=pstmt.executeQuery(); - - while (rs.next() && rs!=null){ - int AD_Client_ID=rs.getInt(1); - String Name=rs.getString(2); - KeyNamePair p = new KeyNamePair(AD_Client_ID,Name); - clientList.add(p); - } - }catch (SQLException ex) - { - log.log(Level.SEVERE, sql.toString(), ex); - retValue = null; - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - } - } - if (clientList.size() > 0) - authenticated=true; - - if (authenticated) { - if (Ini.isClient()) - { - if (MSystem.isSwingRememberUserAllowed()) - Ini.setProperty(Ini.P_UID, app_user); - else - Ini.setProperty(Ini.P_UID, ""); - if (Ini.isPropertyBool(Ini.P_STORE_PWD) && MSystem.isSwingRememberPasswordAllowed()) - Ini.setProperty(Ini.P_PWD, app_pwd); - - } - retValue = new KeyNamePair[clientList.size()]; - clientList.toArray(retValue); - if (log.isLoggable(Level.FINE)) log.fine("User=" + app_user + " - roles #" + retValue.length); - - for (MUser user : users) - { - user.setFailedLoginCount(0); - user.setDateLastLogin(new Timestamp(now)); - Env.setContext(Env.getCtx(), "#AD_Client_ID", user.getAD_Client_ID()); - if (!user.save()) - log.severe("Failed to update user record with date last login (" + user.getName() + " / clientID = " + user.getAD_Client_ID() + ")"); - } - } - else if (validButLocked) - { - // User account ({0}) is locked, please contact the system administrator - loginErrMsg = Msg.getMsg(m_ctx, "UserAccountLocked", new Object[] {app_user}); - } - else - { - boolean foundLockedAccount = false; - for (MUser user : users) - { - if (user.isLocked()) - { - foundLockedAccount = true; - continue; - } - - int count = user.getFailedLoginCount() + 1; - - boolean reachMaxAttempt = false; - int MAX_LOGIN_ATTEMPT = MSysConfig.getIntValue(MSysConfig.USER_LOCKING_MAX_LOGIN_ATTEMPT, 0); - if (MAX_LOGIN_ATTEMPT > 0 && count >= MAX_LOGIN_ATTEMPT) - { - // Reached the maximum number of login attempts, user account ({0}) is locked - loginErrMsg = Msg.getMsg(m_ctx, "ReachedMaxLoginAttempts", new Object[] {app_user}); - reachMaxAttempt = true; - } - else if (MAX_LOGIN_ATTEMPT > 0) - { - if (count == MAX_LOGIN_ATTEMPT -1){ - // Invalid User ID or Password (Login Attempts: {0} / {1}) - loginErrMsg = Msg.getMsg(m_ctx, "FailedLoginAttempt", new Object[] {count, MAX_LOGIN_ATTEMPT}); - reachMaxAttempt = false; - }else{ - loginErrMsg = Msg.getMsg(m_ctx,"FailedLogin", true); - } - - } - else - { - reachMaxAttempt = false; - } - - user.setFailedLoginCount(count); - user.setIsLocked(reachMaxAttempt); - user.setDateAccountLocked(user.isLocked() ? new Timestamp(now) : null); - Env.setContext(Env.getCtx(), "#AD_Client_ID", user.getAD_Client_ID()); - if (!user.save()) - log.severe("Failed to update user record with increase failed login count"); - } - - if (loginErrMsg == null && foundLockedAccount) - { - // User account ({0}) is locked, please contact the system administrator - loginErrMsg = Msg.getMsg(m_ctx, "UserAccountLocked", new Object[] {app_user}); - } - } - return retValue; - } - /************************************************************************** - * Load Roles. - *

    - * Sets Client info in context and loads its roles - * @param client client information - * @return list of valid roles KeyNodePairs or null if in error - */ - public KeyNamePair[] getRoles(String app_user, KeyNamePair client) { - if (client == null) - throw new IllegalArgumentException("Client missing"); - - ArrayList rolesList = new ArrayList(); - KeyNamePair[] retValue = null; - StringBuffer sql = new StringBuffer("SELECT u.AD_User_ID, r.AD_Role_ID,r.Name ") - .append("FROM AD_User u") - .append(" INNER JOIN AD_User_Roles ur ON (u.AD_User_ID=ur.AD_User_ID AND ur.IsActive='Y')") - .append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID AND r.IsActive='Y') "); - sql.append("WHERE u.Password IS NOT NULL AND ur.AD_Client_ID=? AND "); - boolean email_login = MSysConfig.getBooleanValue(MSysConfig.USE_EMAIL_FOR_LOGIN, false); - if (email_login) - sql.append("u.EMail=?"); - else - sql.append("COALESCE(u.LDAPUser,u.Name)=?"); - sql.append(" AND r.IsMasterRole='N'"); - sql.append(" AND u.IsActive='Y' AND EXISTS (SELECT * FROM AD_Client c WHERE u.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')"); - // don't show roles without org access - sql.append(" AND ("); - sql.append(" (r.isaccessallorgs='Y' OR EXISTS (SELECT 1 FROM AD_Role_OrgAccess ro WHERE ro.AD_Role_ID=r.AD_Role_ID AND ro.IsActive='Y'))"); - // show roll with isuseuserorgaccess = "Y" when Exist org in AD_User_Orgaccess - sql.append(" OR "); - sql.append(" (r.isuseuserorgaccess='Y' AND EXISTS (SELECT 1 FROM AD_User_Orgaccess uo WHERE uo.AD_User_ID=u.AD_User_ID AND uo.IsActive='Y')) "); - sql.append(")"); - sql.append(" ORDER BY r.Name"); - - PreparedStatement pstmt = null; - ResultSet rs = null; - // get Role details - try - { - pstmt = DB.prepareStatement(sql.toString(), null); - pstmt.setInt(1, client.getKey()); - pstmt.setString(2, app_user); - rs = pstmt.executeQuery(); - - if (!rs.next()) - { - log.log(Level.SEVERE, "No Roles for Client: " + client.toStringX()); - return null; - } - - // load Roles - do - { - int AD_Role_ID = rs.getInt(2); - String Name = rs.getString(3); - KeyNamePair p = new KeyNamePair(AD_Role_ID, Name); - rolesList.add(p); - } - while (rs.next()); - // - retValue = new KeyNamePair[rolesList.size()]; - rolesList.toArray(retValue); - if (log.isLoggable(Level.FINE)) log.fine("Role: " + client.toStringX() + " - clients #" + retValue.length); - } - catch (SQLException ex) - { - log.log(Level.SEVERE, sql.toString(), ex); - retValue = null; - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - //Client Info - Env.setContext(m_ctx, "#AD_Client_ID", client.getKey()); - Env.setContext(m_ctx, "#AD_Client_Name", client.getName()); - Ini.setProperty(Ini.P_CLIENT, client.getName()); - return retValue; - } // getRoles - - public KeyNamePair[] getClients() { - - if (Env.getContext(m_ctx,"#AD_User_ID").length() == 0){ - throw new UnsupportedOperationException("Missing Context #AD_User_ID"); - } - - loginErrMsg = null; - isPasswordExpired = false; - - int AD_User_ID = Env.getContextAsInt(m_ctx, "#AD_User_ID"); - KeyNamePair[] retValue = null; - ArrayList clientList = new ArrayList(); - StringBuilder sql= new StringBuilder("SELECT DISTINCT cli.AD_Client_ID, cli.Name, u.AD_User_ID, u.Name"); - sql.append(" FROM AD_User_Roles ur") - .append(" INNER JOIN AD_User u on (ur.AD_User_ID=u.AD_User_ID)") - .append(" INNER JOIN AD_Client cli on (ur.AD_Client_ID=cli.AD_Client_ID)") - .append(" WHERE ur.IsActive='Y'") - .append(" AND cli.IsActive='Y'") - .append(" AND u.IsActive='Y'") - .append(" AND u.AD_User_ID=? ORDER BY cli.Name"); - PreparedStatement pstmt = null; - ResultSet rs = null; - try { - pstmt = DB.prepareStatement(sql.toString(),null); - pstmt.setInt(1, AD_User_ID); - rs = pstmt.executeQuery(); - - while (rs.next() && rs != null) { - int AD_Client_ID = rs.getInt(1); - String Name = rs.getString(2); - KeyNamePair p = new KeyNamePair(AD_Client_ID, Name); - clientList.add(p); - } - retValue = new KeyNamePair[clientList.size()]; - clientList.toArray(retValue); - - } catch (SQLException ex) { - log.log(Level.SEVERE, sql.toString(), ex); - retValue = null; - } finally { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - return retValue; - } - + } // getPrincipal + + /** + * Validate Client Login. + * Sets Context with login info + * @param app_user user id + * @param app_pwd password + * @return client array or null if in error. + */ + public KeyNamePair[] getClients(String app_user, String app_pwd) { + if (log.isLoggable(Level.INFO)) log.info("User=" + app_user); + + if (Util.isEmpty(app_user)) + { + log.warning("No Apps User"); + return null; + } + + // Authentication + boolean authenticated = false; + MSystem system = MSystem.get(m_ctx); + if (system == null) + throw new IllegalStateException("No System Info"); + + if (app_pwd == null || app_pwd.length() == 0) + { + log.warning("No Apps Password"); + return null; + } + + loginErrMsg = null; + isPasswordExpired = false; + + if (system.isLDAP()) + { + authenticated = system.isLDAP(app_user, app_pwd); + // if not authenticated, use AD_User as backup + } + + boolean hash_password = MSysConfig.getBooleanValue(MSysConfig.USER_PASSWORD_HASH, false); + boolean email_login = MSysConfig.getBooleanValue(MSysConfig.USE_EMAIL_FOR_LOGIN, false); + KeyNamePair[] retValue = null; + ArrayList clientList = new ArrayList(); + ArrayList clientsValidated = new ArrayList(); + + StringBuilder where = new StringBuilder("Password IS NOT NULL AND "); + if (email_login) + where.append("EMail=?"); + else + where.append("COALESCE(LDAPUser,Name)=?"); + where.append(" AND") + .append(" EXISTS (SELECT * FROM AD_User_Roles ur") + .append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID)") + .append(" WHERE ur.AD_User_ID=AD_User.AD_User_ID AND ur.IsActive='Y' AND r.IsActive='Y') AND ") + .append(" EXISTS (SELECT * FROM AD_Client c") + .append(" WHERE c.AD_Client_ID=AD_User.AD_Client_ID") + .append(" AND c.IsActive='Y') AND ") + .append(" AD_User.IsActive='Y'"); + + List users = new Query(m_ctx, MUser.Table_Name, where.toString(), null) + .setParameters(app_user) + .setOrderBy(MUser.COLUMNNAME_AD_User_ID) + .list(); + + if (users.size() == 0) { + log.saveError("UserPwdError", app_user, false); + return null; + } + + int MAX_ACCOUNT_LOCK_MINUTES = MSysConfig.getIntValue(MSysConfig.USER_LOCKING_MAX_ACCOUNT_LOCK_MINUTES, 0); + int MAX_INACTIVE_PERIOD_DAY = MSysConfig.getIntValue(MSysConfig.USER_LOCKING_MAX_INACTIVE_PERIOD_DAY, 0); + int MAX_PASSWORD_AGE = MSysConfig.getIntValue(MSysConfig.USER_LOCKING_MAX_PASSWORD_AGE_DAY, 0); + long now = new Date().getTime(); + for (MUser user : users) { + if (MAX_ACCOUNT_LOCK_MINUTES > 0 && user.isLocked() && user.getDateAccountLocked() != null) + { + long minutes = (now - user.getDateAccountLocked().getTime()) / (1000 * 60); + if (minutes > MAX_ACCOUNT_LOCK_MINUTES) + { + boolean inactive = false; + if (MAX_INACTIVE_PERIOD_DAY > 0 && user.getDateLastLogin() != null && !user.isNoExpire()) + { + long days = (now - user.getDateLastLogin().getTime()) / (1000 * 60 * 60 * 24); + if (days > MAX_INACTIVE_PERIOD_DAY) + inactive = true; + } + + if (!inactive) + { + user.setIsLocked(false); + user.setDateAccountLocked(null); + user.setFailedLoginCount(0); + Env.setContext(Env.getCtx(), "#AD_Client_ID", user.getAD_Client_ID()); + if (!user.save()) + log.severe("Failed to unlock user account"); + } + } + } + + if (MAX_INACTIVE_PERIOD_DAY > 0 && !user.isLocked() && user.getDateLastLogin() != null && !user.isNoExpire()) + { + long days = (now - user.getDateLastLogin().getTime()) / (1000 * 60 * 60 * 24); + if (days > MAX_INACTIVE_PERIOD_DAY) + { + user.setIsLocked(true); + user.setDateAccountLocked(new Timestamp(now)); + Env.setContext(Env.getCtx(), "#AD_Client_ID", user.getAD_Client_ID()); + if (!user.save()) + log.severe("Failed to lock user account"); + } + } + } + + boolean validButLocked = false; + for (MUser user : users) { + if (clientsValidated.contains(user.getAD_Client_ID())) { + log.severe("Two users with password with the same name/email combination on same tenant: " + app_user); + return null; + } + clientsValidated.add(user.getAD_Client_ID()); + boolean valid = false; + // authenticated by ldap + if (authenticated){ + valid = true; + } else if (hash_password) { + valid = user.authenticateHash(app_pwd); + } else { + // password not hashed + valid = user.getPassword() != null && user.getPassword().equals(app_pwd); + } + + if (valid ) { + if (user.isLocked()) + { + validButLocked = true; + continue; + } + + if (authenticated){ + // use Ldap because don't check password age + } + else if (user.isExpired()) + isPasswordExpired = true; + else if (MAX_PASSWORD_AGE > 0 && !user.isNoPasswordReset()) + { + if (user.getDatePasswordChanged() == null) + user.setDatePasswordChanged(new Timestamp(now)); + + long days = (now - user.getDatePasswordChanged().getTime()) / (1000 * 60 * 60 * 24); + if (days > MAX_PASSWORD_AGE) + { + user.setIsExpired(true); + isPasswordExpired = true; + } + } + + StringBuilder sql= new StringBuilder("SELECT DISTINCT cli.AD_Client_ID, cli.Name, u.AD_User_ID, u.Name"); + sql.append(" FROM AD_User_Roles ur") + .append(" INNER JOIN AD_User u on (ur.AD_User_ID=u.AD_User_ID)") + .append(" INNER JOIN AD_Client cli on (ur.AD_Client_ID=cli.AD_Client_ID)") + .append(" WHERE ur.IsActive='Y'") + .append(" AND u.IsActive='Y'") + .append(" AND cli.IsActive='Y'") + .append(" AND ur.AD_User_ID=? ORDER BY cli.Name"); + PreparedStatement pstmt=null; + ResultSet rs=null; + try{ + pstmt=DB.prepareStatement(sql.toString(),null); + pstmt.setInt(1, user.getAD_User_ID()); + rs=pstmt.executeQuery(); + + while (rs.next() && rs!=null){ + int AD_Client_ID=rs.getInt(1); + String Name=rs.getString(2); + KeyNamePair p = new KeyNamePair(AD_Client_ID,Name); + clientList.add(p); + } + }catch (SQLException ex) + { + log.log(Level.SEVERE, sql.toString(), ex); + retValue = null; + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + } + } + if (clientList.size() > 0) + authenticated=true; + + if (authenticated) { + if (Ini.isClient()) + { + if (MSystem.isSwingRememberUserAllowed()) + Ini.setProperty(Ini.P_UID, app_user); + else + Ini.setProperty(Ini.P_UID, ""); + if (Ini.isPropertyBool(Ini.P_STORE_PWD) && MSystem.isSwingRememberPasswordAllowed()) + Ini.setProperty(Ini.P_PWD, app_pwd); + + } + retValue = new KeyNamePair[clientList.size()]; + clientList.toArray(retValue); + if (log.isLoggable(Level.FINE)) log.fine("User=" + app_user + " - roles #" + retValue.length); + + for (MUser user : users) + { + user.setFailedLoginCount(0); + user.setDateLastLogin(new Timestamp(now)); + Env.setContext(Env.getCtx(), "#AD_Client_ID", user.getAD_Client_ID()); + if (!user.save()) + log.severe("Failed to update user record with date last login (" + user.getName() + " / clientID = " + user.getAD_Client_ID() + ")"); + } + } + else if (validButLocked) + { + // User account ({0}) is locked, please contact the system administrator + loginErrMsg = Msg.getMsg(m_ctx, "UserAccountLocked", new Object[] {app_user}); + } + else + { + boolean foundLockedAccount = false; + for (MUser user : users) + { + if (user.isLocked()) + { + foundLockedAccount = true; + continue; + } + + int count = user.getFailedLoginCount() + 1; + + boolean reachMaxAttempt = false; + int MAX_LOGIN_ATTEMPT = MSysConfig.getIntValue(MSysConfig.USER_LOCKING_MAX_LOGIN_ATTEMPT, 0); + if (MAX_LOGIN_ATTEMPT > 0 && count >= MAX_LOGIN_ATTEMPT) + { + // Reached the maximum number of login attempts, user account ({0}) is locked + loginErrMsg = Msg.getMsg(m_ctx, "ReachedMaxLoginAttempts", new Object[] {app_user}); + reachMaxAttempt = true; + } + else if (MAX_LOGIN_ATTEMPT > 0) + { + if (count == MAX_LOGIN_ATTEMPT -1){ + // Invalid User ID or Password (Login Attempts: {0} / {1}) + loginErrMsg = Msg.getMsg(m_ctx, "FailedLoginAttempt", new Object[] {count, MAX_LOGIN_ATTEMPT}); + reachMaxAttempt = false; + }else{ + loginErrMsg = Msg.getMsg(m_ctx,"FailedLogin", true); + } + + } + else + { + reachMaxAttempt = false; + } + + user.setFailedLoginCount(count); + user.setIsLocked(reachMaxAttempt); + user.setDateAccountLocked(user.isLocked() ? new Timestamp(now) : null); + Env.setContext(Env.getCtx(), "#AD_Client_ID", user.getAD_Client_ID()); + if (!user.save()) + log.severe("Failed to update user record with increase failed login count"); + } + + if (loginErrMsg == null && foundLockedAccount) + { + // User account ({0}) is locked, please contact the system administrator + loginErrMsg = Msg.getMsg(m_ctx, "UserAccountLocked", new Object[] {app_user}); + } + } + return retValue; + } + /************************************************************************** + * Load Roles. + *

    + * Sets Client info in context and loads its roles + * @param client client information + * @return list of valid roles KeyNodePairs or null if in error + */ + public KeyNamePair[] getRoles(String app_user, KeyNamePair client) { + if (client == null) + throw new IllegalArgumentException("Client missing"); + + ArrayList rolesList = new ArrayList(); + KeyNamePair[] retValue = null; + StringBuffer sql = new StringBuffer("SELECT u.AD_User_ID, r.AD_Role_ID,r.Name ") + .append("FROM AD_User u") + .append(" INNER JOIN AD_User_Roles ur ON (u.AD_User_ID=ur.AD_User_ID AND ur.IsActive='Y')") + .append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID AND r.IsActive='Y') "); + sql.append("WHERE u.Password IS NOT NULL AND ur.AD_Client_ID=? AND "); + boolean email_login = MSysConfig.getBooleanValue(MSysConfig.USE_EMAIL_FOR_LOGIN, false); + if (email_login) + sql.append("u.EMail=?"); + else + sql.append("COALESCE(u.LDAPUser,u.Name)=?"); + sql.append(" AND r.IsMasterRole='N'"); + sql.append(" AND u.IsActive='Y' AND EXISTS (SELECT * FROM AD_Client c WHERE u.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')"); + // don't show roles without org access + sql.append(" AND ("); + sql.append(" (r.isaccessallorgs='Y' OR EXISTS (SELECT 1 FROM AD_Role_OrgAccess ro WHERE ro.AD_Role_ID=r.AD_Role_ID AND ro.IsActive='Y'))"); + // show roll with isuseuserorgaccess = "Y" when Exist org in AD_User_Orgaccess + sql.append(" OR "); + sql.append(" (r.isuseuserorgaccess='Y' AND EXISTS (SELECT 1 FROM AD_User_Orgaccess uo WHERE uo.AD_User_ID=u.AD_User_ID AND uo.IsActive='Y')) "); + sql.append(")"); + sql.append(" ORDER BY r.Name"); + + PreparedStatement pstmt = null; + ResultSet rs = null; + // get Role details + try + { + pstmt = DB.prepareStatement(sql.toString(), null); + pstmt.setInt(1, client.getKey()); + pstmt.setString(2, app_user); + rs = pstmt.executeQuery(); + + if (!rs.next()) + { + log.log(Level.SEVERE, "No Roles for Client: " + client.toStringX()); + return null; + } + + // load Roles + do + { + int AD_Role_ID = rs.getInt(2); + String Name = rs.getString(3); + KeyNamePair p = new KeyNamePair(AD_Role_ID, Name); + rolesList.add(p); + } + while (rs.next()); + // + retValue = new KeyNamePair[rolesList.size()]; + rolesList.toArray(retValue); + if (log.isLoggable(Level.FINE)) log.fine("Role: " + client.toStringX() + " - clients #" + retValue.length); + } + catch (SQLException ex) + { + log.log(Level.SEVERE, sql.toString(), ex); + retValue = null; + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + //Client Info + Env.setContext(m_ctx, "#AD_Client_ID", client.getKey()); + Env.setContext(m_ctx, "#AD_Client_Name", client.getName()); + Ini.setProperty(Ini.P_CLIENT, client.getName()); + return retValue; + } // getRoles + + public KeyNamePair[] getClients() { + + if (Env.getContext(m_ctx,"#AD_User_ID").length() == 0){ + throw new UnsupportedOperationException("Missing Context #AD_User_ID"); + } + + loginErrMsg = null; + isPasswordExpired = false; + + int AD_User_ID = Env.getContextAsInt(m_ctx, "#AD_User_ID"); + KeyNamePair[] retValue = null; + ArrayList clientList = new ArrayList(); + StringBuilder sql= new StringBuilder("SELECT DISTINCT cli.AD_Client_ID, cli.Name, u.AD_User_ID, u.Name"); + sql.append(" FROM AD_User_Roles ur") + .append(" INNER JOIN AD_User u on (ur.AD_User_ID=u.AD_User_ID)") + .append(" INNER JOIN AD_Client cli on (ur.AD_Client_ID=cli.AD_Client_ID)") + .append(" WHERE ur.IsActive='Y'") + .append(" AND cli.IsActive='Y'") + .append(" AND u.IsActive='Y'") + .append(" AND u.AD_User_ID=? ORDER BY cli.Name"); + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql.toString(),null); + pstmt.setInt(1, AD_User_ID); + rs = pstmt.executeQuery(); + + while (rs.next() && rs != null) { + int AD_Client_ID = rs.getInt(1); + String Name = rs.getString(2); + KeyNamePair p = new KeyNamePair(AD_Client_ID, Name); + clientList.add(p); + } + retValue = new KeyNamePair[clientList.size()]; + clientList.toArray(retValue); + + } catch (SQLException ex) { + log.log(Level.SEVERE, sql.toString(), ex); + retValue = null; + } finally { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + return retValue; + } + } // Login diff --git a/org.adempiere.base/src/org/compiere/util/Msg.java b/org.adempiere.base/src/org/compiere/util/Msg.java index 06458a4b28..e3d9400f7a 100644 --- a/org.adempiere.base/src/org/compiere/util/Msg.java +++ b/org.adempiere.base/src/org/compiere/util/Msg.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,17 +16,17 @@ *****************************************************************************/ package org.compiere.util; -import java.io.File; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.text.MessageFormat; -import java.util.Iterator; -import java.util.Properties; -import java.util.logging.Level; - -import org.compiere.Adempiere; -import org.compiere.model.I_AD_Message; +import java.io.File; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.MessageFormat; +import java.util.Iterator; +import java.util.Properties; +import java.util.logging.Level; + +import org.compiere.Adempiere; +import org.compiere.model.I_AD_Message; /** * Reads all Messages and stores them in a HashMap @@ -68,9 +68,9 @@ public final class Msg /** The Map */ private CCache> m_languages - = new CCache>(null, "msg_lang", 2, 0, false); - - private CCache> m_elementCache + = new CCache>(null, "msg_lang", 2, 0, false); + + private CCache> m_elementCache = new CCache>(null, "msg_element", 2, 0, false); /** @@ -96,21 +96,21 @@ public final class Msg return retValue; } return retValue; - } // getMsgMap - - private CCache getElementMap (String ad_language) - { - String AD_Language = ad_language; - if (AD_Language == null || AD_Language.length() == 0) - AD_Language = Language.getBaseAD_Language(); - // Do we have the language ? - CCache retValue = (CCache)m_elementCache.get(AD_Language); - if (retValue != null && retValue.size() > 0) - return retValue; - - retValue = new CCache("element", 100, 0, false, 0); - m_elementCache.put(AD_Language, retValue); - return retValue; + } // getMsgMap + + private CCache getElementMap (String ad_language) + { + String AD_Language = ad_language; + if (AD_Language == null || AD_Language.length() == 0) + AD_Language = Language.getBaseAD_Language(); + // Do we have the language ? + CCache retValue = (CCache)m_elementCache.get(AD_Language); + if (retValue != null && retValue.size() > 0) + return retValue; + + retValue = new CCache("element", 100, 0, false, 0); + m_elementCache.put(AD_Language, retValue); + return retValue; } @@ -124,15 +124,15 @@ public final class Msg private CCache initMsg (String AD_Language) { // Trace.printStack(); - CCache msg = new CCache(I_AD_Message.Table_Name, MAP_SIZE, 0, false, 0); + CCache msg = new CCache(I_AD_Message.Table_Name, MAP_SIZE, 0, false, 0); // if (!DB.isConnected()) { s_log.log(Level.SEVERE, "No DB Connection"); return null; } - PreparedStatement pstmt = null; - ResultSet rs = null; + PreparedStatement pstmt = null; + ResultSet rs = null; try { if (AD_Language == null || AD_Language.length() == 0 || Env.isBaseLanguage(AD_Language, "AD_Language")) @@ -151,7 +151,7 @@ public final class Msg while (rs.next()) { String AD_Message = rs.getString(1); - StringBuilder MsgText = new StringBuilder(); + StringBuilder MsgText = new StringBuilder(); MsgText.append(rs.getString(2)); String MsgTip = rs.getString(3); // @@ -164,11 +164,11 @@ public final class Msg { s_log.log(Level.SEVERE, "initMsg", e); return null; - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; } // if (msg.size() < 100) @@ -176,7 +176,7 @@ public final class Msg s_log.log(Level.SEVERE, "Too few (" + msg.size() + ") Records found for " + AD_Language); return null; } - if (s_log.isLoggable(Level.INFO)) s_log.info("Records=" + msg.size() + " - " + AD_Language); + if (s_log.isLoggable(Level.INFO)) s_log.info("Records=" + msg.size() + " - " + AD_Language); return msg; } // initMsg @@ -237,22 +237,22 @@ public final class Msg return text; // hardcoded trl if (text.equals("/") || text.equals("\\")) - return File.separator; - if (text.equals(";") || text.equals(":")) - return File.pathSeparator; - if (text.equals("IDEMPIERE_HOME")) - return Adempiere.getAdempiereHome(); - if (text.equals("bat") || text.equals("sh")) - { - if (System.getProperty("os.name").startsWith("Win")) + return File.separator; + if (text.equals(";") || text.equals(":")) + return File.pathSeparator; + if (text.equals("IDEMPIERE_HOME")) + return Adempiere.getAdempiereHome(); + if (text.equals("bat") || text.equals("sh")) + { + if (System.getProperty("os.name").startsWith("Win")) return "bat"; - return "sh"; - } - if (text.equals("CopyRight")) - return Adempiere.COPYRIGHT; - // - CCache langMap = getMsgMap(AD_Language); - if (langMap == null) + return "sh"; + } + if (text.equals("CopyRight")) + return Adempiere.COPYRIGHT; + // + CCache langMap = getMsgMap(AD_Language); + if (langMap == null) return null; return (String)langMap.get(text); } // lookup @@ -276,8 +276,8 @@ public final class Msg String retStr = get().lookup (AD_Language, AD_Message); // if (retStr == null || retStr.length() == 0) - { - s_log.warning("NOT found: " + AD_Message); + { + s_log.warning("NOT found: " + AD_Message); return AD_Message; } @@ -329,13 +329,13 @@ public final class Msg { if (getText) retStr = retStr.substring (0, pos); - else - { - int start = pos + SEPARATOR.length(); - // int end = retStr.length(); - retStr = retStr.substring (start); - } - } + else + { + int start = pos + SEPARATOR.length(); + // int end = retStr.length(); + retStr = retStr.substring (start); + } + } return retStr; } // getMsg @@ -434,7 +434,7 @@ public final class Msg } catch (ClassNotFoundException e) { - s_log.warning("Class not found: " + className); + s_log.warning("Class not found: " + className); } catch (Exception e) { @@ -442,7 +442,7 @@ public final class Msg } // Fallback - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); int pos = amount.lastIndexOf('.'); int pos2 = amount.lastIndexOf(','); if (pos2 > pos) @@ -482,18 +482,18 @@ public final class Msg return ""; String AD_Language = ad_language; if (AD_Language == null || AD_Language.length() == 0) - AD_Language = Language.getBaseAD_Language(); - - Msg msg = get(); - CCache cache = msg.getElementMap(AD_Language); - String key = ColumnName+"|"+isSOTrx; - String retStr = cache.get(key); - if (retStr != null) + AD_Language = Language.getBaseAD_Language(); + + Msg msg = get(); + CCache cache = msg.getElementMap(AD_Language); + String key = ColumnName+"|"+isSOTrx; + String retStr = cache.get(key); + if (retStr != null) return retStr; - // Check AD_Element - PreparedStatement pstmt = null; - ResultSet rs = null; + // Check AD_Element + PreparedStatement pstmt = null; + ResultSet rs = null; try { if (AD_Language == null || AD_Language.length() == 0 || Env.isBaseLanguage(AD_Language, "AD_Element")) @@ -505,7 +505,7 @@ public final class Msg + "AND t.AD_Language=?", null); pstmt.setString(2, AD_Language); } - + pstmt.setString(1, ColumnName.toUpperCase()); rs = pstmt.executeQuery(); if (rs.next()) @@ -523,16 +523,16 @@ public final class Msg { s_log.log(Level.SEVERE, "getElement", e); return ""; - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; } - - retStr = retStr == null ? "" : retStr.trim(); + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + + retStr = retStr == null ? "" : retStr.trim(); cache.put(key, retStr); - return retStr; + return retStr; } // getElement @@ -660,7 +660,7 @@ public final class Msg String inStr = text; String token; - StringBuilder outStr = new StringBuilder(); + StringBuilder outStr = new StringBuilder(); int i = inStr.indexOf('@'); while (i != -1) @@ -684,17 +684,17 @@ public final class Msg outStr.append(inStr); // add remainder return outStr.toString(); - } // parseTranslation - - - /** - * Get translated text message for AD_Message, ampersand cleaned (used to indicate shortcut) - * @param ctx Context to retrieve language - * @param AD_Message - Message Key - * @return translated text - */ - public static String getCleanMsg(Properties ctx, String string) { - return Util.cleanAmp(getMsg(Env.getAD_Language(ctx), string)); + } // parseTranslation + + + /** + * Get translated text message for AD_Message, ampersand cleaned (used to indicate shortcut) + * @param ctx Context to retrieve language + * @param AD_Message - Message Key + * @return translated text + */ + public static String getCleanMsg(Properties ctx, String string) { + return Util.cleanAmp(getMsg(Env.getAD_Language(ctx), string)); } } // Msg diff --git a/org.adempiere.extend/src/test/functional/MBPGroupTest.java b/org.adempiere.extend/src/test/functional/MBPGroupTest.java index 0d9a677399..4297ccb705 100644 --- a/org.adempiere.extend/src/test/functional/MBPGroupTest.java +++ b/org.adempiere.extend/src/test/functional/MBPGroupTest.java @@ -1,19 +1,19 @@ -//MBPGroupTest.java +//MBPGroupTest.java package test.functional; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import org.compiere.model.MBPGroup; -import org.compiere.util.DB; - -import test.AdempiereTestCase; - -public class MBPGroupTest extends AdempiereTestCase { - + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.compiere.model.MBPGroup; +import org.compiere.util.DB; + +import test.AdempiereTestCase; + +public class MBPGroupTest extends AdempiereTestCase { + // Variables needed for importing/migrating business partners - //private MLocation location = null; + //private MLocation location = null; private MBPGroup m_group = null; //business partner /* @@ -25,7 +25,7 @@ public class MBPGroupTest extends AdempiereTestCase { private MElementValue ev = null; //element value private MAcctSchema as = null; //account schema private MAccount acct = null; //account - + // Variables needed for importing/migrating bank statements private MBankStatement statement = null; private MBankAccount account = null; @@ -38,7 +38,7 @@ public class MBPGroupTest extends AdempiereTestCase { private MJournalBatch batch = null; private MJournal journal = null; private MJournalLine line = null; - + // Variables needed for importing/migrating Inventory private MInventory inventory = null; private MProduct product = null; @@ -514,13 +514,13 @@ public class MBPGroupTest extends AdempiereTestCase { m_group.setIsDefault (false); m_group.setPriorityBase(MBPGroup.PRIORITYBASE_Same); - m_group.saveEx(); - + m_group.saveEx(); + commit(); } catch(Exception e) { fail(e.getLocalizedMessage()); } } - + } diff --git a/org.adempiere.extend/src/test/functional/MBPartnerLocationTest.java b/org.adempiere.extend/src/test/functional/MBPartnerLocationTest.java index c663d2adec..566916f2a7 100644 --- a/org.adempiere.extend/src/test/functional/MBPartnerLocationTest.java +++ b/org.adempiere.extend/src/test/functional/MBPartnerLocationTest.java @@ -1,24 +1,24 @@ -//MBPartnerLocationTest.java -package test.functional; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import org.compiere.model.MBPGroup; -import org.compiere.model.MBPartner; -import org.compiere.model.MBPartnerLocation; -import org.compiere.model.MLocation; -import org.compiere.util.DB; -import org.compiere.util.Env; - -import test.AdempiereTestCase; - -public class MBPartnerLocationTest extends AdempiereTestCase { - +//MBPartnerLocationTest.java +package test.functional; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.compiere.model.MBPGroup; +import org.compiere.model.MBPartner; +import org.compiere.model.MBPartnerLocation; +import org.compiere.model.MLocation; +import org.compiere.util.DB; +import org.compiere.util.Env; + +import test.AdempiereTestCase; + +public class MBPartnerLocationTest extends AdempiereTestCase { + // Variables needed for importing/migrating business partners private MBPartner m_partner = null; //business partner - private MLocation location = null; + private MLocation location = null; private MBPartnerLocation bpl = null; //business partner location private MBPGroup m_group = null; @@ -30,7 +30,7 @@ public class MBPartnerLocationTest extends AdempiereTestCase { private MElementValue ev = null; //element value private MAcctSchema as = null; //account schema private MAccount acct = null; //account - + // Variables needed for importing/migrating bank statements private MBankStatement statement = null; private MBankAccount account = null; @@ -43,7 +43,7 @@ public class MBPartnerLocationTest extends AdempiereTestCase { private MJournalBatch batch = null; private MJournal journal = null; private MJournalLine line = null; - + // Variables needed for importing/migrating Inventory private MInventory inventory = null; private MProduct product = null; @@ -570,6 +570,6 @@ public class MBPartnerLocationTest extends AdempiereTestCase { } catch(Exception e) { fail(e.getLocalizedMessage()); } - + } } diff --git a/org.adempiere.extend/src/test/functional/MBPartnerTest.java b/org.adempiere.extend/src/test/functional/MBPartnerTest.java index 5d34b8487c..b07f5f48ca 100644 --- a/org.adempiere.extend/src/test/functional/MBPartnerTest.java +++ b/org.adempiere.extend/src/test/functional/MBPartnerTest.java @@ -1,16 +1,16 @@ -//MBPartnerTest.java +//MBPartnerTest.java package test.functional; - -import org.compiere.model.MBPartner; - -import test.AdempiereTestCase; - -public class MBPartnerTest extends AdempiereTestCase { - - // Variables needed for importing/migrating business partners - //private MLocation location = null; + +import org.compiere.model.MBPartner; + +import test.AdempiereTestCase; + +public class MBPartnerTest extends AdempiereTestCase { - //private MBPartner m_partner = null; //business partner + // Variables needed for importing/migrating business partners + //private MLocation location = null; + + //private MBPartner m_partner = null; //business partner /* private MBPartnerLocation bpl = null; //business partner location private MUser user = null; //business contact @@ -20,7 +20,7 @@ public class MBPartnerTest extends AdempiereTestCase { private MElementValue ev = null; //element value private MAcctSchema as = null; //account schema private MAccount acct = null; //account - + // Variables needed for importing/migrating bank statements private MBankStatement statement = null; private MBankAccount account = null; @@ -33,7 +33,7 @@ public class MBPartnerTest extends AdempiereTestCase { private MJournalBatch batch = null; private MJournal journal = null; private MJournalLine line = null; - + // Variables needed for importing/migrating Inventory private MInventory inventory = null; private MProduct product = null; @@ -507,7 +507,7 @@ public class MBPartnerTest extends AdempiereTestCase { try { m_partner = new MBPartner (getCtx(), 0, getTrxName()); m_partner.setValue (""); - m_partner.setName ("Test MBPartner"); + m_partner.setName ("Test MBPartner"); m_partner.setName2 (null); m_partner.setDUNS(""); m_partner.setFirstSale(null); @@ -541,10 +541,10 @@ public class MBPartnerTest extends AdempiereTestCase { fail(e.getLocalizedMessage()); } - } */ - public void testBPartner() { - MBPartner test = MBPartner.getBPartnerCashTrx(getCtx(), 11); - assertTrue("Confirming right BPartner record", test.getC_BPartner_ID() == 112); + } */ + public void testBPartner() { + MBPartner test = MBPartner.getBPartnerCashTrx(getCtx(), 11); + assertTrue("Confirming right BPartner record", test.getC_BPartner_ID() == 112); } - + } diff --git a/org.adempiere.extend/src/test/functional/MProductTest.java b/org.adempiere.extend/src/test/functional/MProductTest.java index 0d16e87601..cff3bfb19f 100644 --- a/org.adempiere.extend/src/test/functional/MProductTest.java +++ b/org.adempiere.extend/src/test/functional/MProductTest.java @@ -1,12 +1,12 @@ -//MProductTest.java -package test.functional; - -import org.compiere.model.MProductPrice; - -import test.AdempiereTestCase; - -public class MProductTest extends AdempiereTestCase { -/* +//MProductTest.java +package test.functional; + +import org.compiere.model.MProductPrice; + +import test.AdempiereTestCase; + +public class MProductTest extends AdempiereTestCase { +/* public int getProduct_Category_ID(String productCategory) { String sql = "select m_product_category_id from m_product_category where name = ?"; PreparedStatement pstmt = null; @@ -63,9 +63,9 @@ public class MProductTest extends AdempiereTestCase { } - public void testCreateMProduct() { - MProduct m_product = new MProduct(getCtx(), 0, getTrxName()); - m_product.setAD_Org_ID(0); + public void testCreateMProduct() { + MProduct m_product = new MProduct(getCtx(), 0, getTrxName()); + m_product.setAD_Org_ID(0); m_product.setProductType (X_I_Product.PRODUCTTYPE_Item); // I m_product.setIsBOM (false); // N m_product.setIsInvoicePrintDetails (false); @@ -81,20 +81,20 @@ public class MProductTest extends AdempiereTestCase { m_product.setProcessing (false); // N m_product.setName("Test Product"); // N m_product.setC_UOM_ID(getUOM_ID("Each")); - - boolean saveResult = m_product.saveEx(); - assertEquals("Create new product.", true, saveResult); - } - - public void testSetBaseInfo() { - MProductPricing prodprice = new MProductPricing(122,100, Env.ONEHUNDRED,true); - int uom = 0; - uom = prodprice.getC_UOM_ID(); - assertTrue("UOM must be correct", uom == 100); - } */ - - public void testPrice() { - MProductPrice test = MProductPrice.get(getCtx(), 105, 124, getTrxName()); - assertTrue("Confirming Prod ID to be true", test.getM_Product_ID() == 124); - } -} + + boolean saveResult = m_product.saveEx(); + assertEquals("Create new product.", true, saveResult); + } + + public void testSetBaseInfo() { + MProductPricing prodprice = new MProductPricing(122,100, Env.ONEHUNDRED,true); + int uom = 0; + uom = prodprice.getC_UOM_ID(); + assertTrue("UOM must be correct", uom == 100); + } */ + + public void testPrice() { + MProductPrice test = MProductPrice.get(getCtx(), 105, 124, getTrxName()); + assertTrue("Confirming Prod ID to be true", test.getM_Product_ID() == 124); + } +} diff --git a/org.adempiere.extend/src/test/functional/MUserTest.java b/org.adempiere.extend/src/test/functional/MUserTest.java index b94e5ccc67..6a32ef7902 100644 --- a/org.adempiere.extend/src/test/functional/MUserTest.java +++ b/org.adempiere.extend/src/test/functional/MUserTest.java @@ -1,22 +1,22 @@ -//MUserTest.java +//MUserTest.java package test.functional; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import org.compiere.model.MBPGroup; -import org.compiere.model.MBPartner; -import org.compiere.model.MUser; -import org.compiere.util.DB; -import org.compiere.util.Env; - -import test.AdempiereTestCase; - -public class MUserTest extends AdempiereTestCase { - + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.compiere.model.MBPGroup; +import org.compiere.model.MBPartner; +import org.compiere.model.MUser; +import org.compiere.util.DB; +import org.compiere.util.Env; + +import test.AdempiereTestCase; + +public class MUserTest extends AdempiereTestCase { + // Variables needed for importing/migrating business partners - //private MLocation location = null; + //private MLocation location = null; private MBPartner m_partner = null; //business partner private MUser m_contact = null; //business contact @@ -28,7 +28,7 @@ public class MUserTest extends AdempiereTestCase { private MElementValue ev = null; //element value private MAcctSchema as = null; //account schema private MAccount acct = null; //account - + // Variables needed for importing/migrating bank statements private MBankStatement statement = null; private MBankAccount account = null; @@ -41,7 +41,7 @@ public class MUserTest extends AdempiereTestCase { private MJournalBatch batch = null; private MJournal journal = null; private MJournalLine line = null; - + // Variables needed for importing/migrating Inventory private MInventory inventory = null; private MProduct product = null; @@ -549,13 +549,13 @@ public class MUserTest extends AdempiereTestCase { m_contact.setIsActive(true); m_contact.setC_BPartner_ID(m_partner.get_ID()); m_contact.saveEx(); - } - + } + commit(); } catch(Exception e) { fail(e.getLocalizedMessage()); } } - + } diff --git a/org.adempiere.install/build.xml b/org.adempiere.install/build.xml index 590cd9886f..8785dec2f8 100644 --- a/org.adempiere.install/build.xml +++ b/org.adempiere.install/build.xml @@ -1,58 +1,58 @@ - - - - - - - - This buildfile is used to setup the idempiere Environment. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + This buildfile is used to setup the idempiere Environment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.adempiere.install/src/org/compiere/install/SetupRes_hu.java b/org.adempiere.install/src/org/compiere/install/SetupRes_hu.java index 66d986c723..6ae672c8c7 100644 --- a/org.adempiere.install/src/org/compiere/install/SetupRes_hu.java +++ b/org.adempiere.install/src/org/compiere/install/SetupRes_hu.java @@ -1,119 +1,119 @@ -/****************************************************************************** - * 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.compiere.install; - -import java.util.ListResourceBundle; - -/** - * Setup Resources - * - * @author Jorg Janke - * @version $Id: SetupRes.java,v 1.3 2006/07/30 00:57:42 jjanke Exp $ - */ -public class SetupRes_hu extends ListResourceBundle -{ - /** Translation Info */ - static final Object[][] contents = new String[][]{ - { "AdempiereServerSetup", "iDempiere Szerver Beállítása" }, - { "Ok", "Ok" }, - { "File", "Fájl" }, - { "Exit", "Kilépés" }, - { "Help", "Súgó" }, - { "PleaseCheck", "Kérem ellenőrizze" }, - { "UnableToConnect", "Nem sikerült elérni a súgót az iDempiere web oldalán" }, - // - { "AdempiereHomeInfo", "iDempiere Home is the main Folder" }, - { "AdempiereHome", "iDempiere Home" }, - { "WebPortInfo", "Web (HTML) Port" }, - { "WebPort", "Web Port" }, - { "AppsServerInfo", "Application Server Name" }, - { "AppsServer", "Application Server" }, - { "DatabaseTypeInfo", "Database Type" }, - { "DatabaseType", "Database Type" }, - { "DatabaseNameInfo", "Database (Service) Name" }, - { "DatabaseName", "Database Name" }, - { "DatabasePortInfo", "Database Listener Port" }, - { "DatabasePort", "Database Port" }, - { "DatabaseUserInfo", "Database iDempiere User ID" }, - { "DatabaseUser", "Database User" }, - { "DatabasePasswordInfo", "Database iDempiere User Password" }, - { "DatabasePassword", "Database Password" }, - { "TNSNameInfo", "Discovered Databases" }, - { "TNSName", "Database Search" }, - { "SystemPasswordInfo", "Database System User Password" }, - { "SystemPassword", "System Password" }, - { "MailServerInfo", "Mail Server" }, - { "MailServer", "Mail Server" }, - { "AdminEMailInfo", "iDempiere Administrator EMail" }, - { "AdminEMail", "Admin EMail" }, - { "DatabaseServerInfo", "Database Server Name" }, - { "DatabaseServer", "Database Server" }, - { "JavaHomeInfo", "Java Home Folder" }, - { "JavaHome", "Java Home" }, - { "JNPPortInfo", "Application Server JNP Port" }, - { "JNPPort", "JNP Port" }, - { "MailUserInfo", "iDempiere Mail User" }, - { "MailUser", "Mail User" }, - { "MailPasswordInfo", "iDempiere Mail User Password" }, - { "MailPassword", "Mail Password" }, - { "KeyStorePassword", "KeyStore Password" }, - { "KeyStorePasswordInfo", "Password for SSL Key Store" }, - // - { "JavaType", "Java VM"}, - { "JavaTypeInfo", "Java VM Vendor"}, - { "AppsType", "Server Type"}, - { "AppsTypeInfo", "J2EE Application Server Type"}, - { "DeployDir", "Deployment"}, - { "DeployDirInfo", "J2EE Deployment Directory"}, - { "ErrorDeployDir", "Error Deployment Directory"}, - // - { "TestInfo", "Test the Setup" }, - { "Test", "Test" }, - { "SaveInfo", "Save the Setup" }, - { "Save", "Save" }, - { "HelpInfo", "Get Help" }, - // - { "ServerError", "Server Setup Error" }, - { "ErrorJavaHome", "Error Java Home" }, - { "ErrorAdempiereHome", "Error iDempiere Home" }, - { "ErrorAppsServer", "Error Apps Server" }, - { "ErrorWebPort", "Error Web Port" }, - { "ErrorJNPPort", "Error JNP Port" }, - { "ErrorDatabaseServer", "Error Database Server" }, - { "ErrorDatabasePort", "Error Database Port" }, - { "ErrorJDBC", "Error JDBC Connection" }, - { "ErrorTNS", "Error TNS Connection" }, - { "ErrorMailServer", "Error Mail Server" }, - { "ErrorMail", "Error Mail" }, - { "ErrorSave", "Error Saving File" }, - - { "EnvironmentSaved", "Environment file saved .... starting Deployment\n" - + "You can re-start the Application Server after program completes.\n" - + "Please check Trace for errors.\n" } - - }; - - /** - * Get Content - * @return content array - */ - public Object[][] getContents() - { - return contents; - } // getContents - +/****************************************************************************** + * 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.compiere.install; + +import java.util.ListResourceBundle; + +/** + * Setup Resources + * + * @author Jorg Janke + * @version $Id: SetupRes.java,v 1.3 2006/07/30 00:57:42 jjanke Exp $ + */ +public class SetupRes_hu extends ListResourceBundle +{ + /** Translation Info */ + static final Object[][] contents = new String[][]{ + { "AdempiereServerSetup", "iDempiere Szerver Beállítása" }, + { "Ok", "Ok" }, + { "File", "Fájl" }, + { "Exit", "Kilépés" }, + { "Help", "Súgó" }, + { "PleaseCheck", "Kérem ellenőrizze" }, + { "UnableToConnect", "Nem sikerült elérni a súgót az iDempiere web oldalán" }, + // + { "AdempiereHomeInfo", "iDempiere Home is the main Folder" }, + { "AdempiereHome", "iDempiere Home" }, + { "WebPortInfo", "Web (HTML) Port" }, + { "WebPort", "Web Port" }, + { "AppsServerInfo", "Application Server Name" }, + { "AppsServer", "Application Server" }, + { "DatabaseTypeInfo", "Database Type" }, + { "DatabaseType", "Database Type" }, + { "DatabaseNameInfo", "Database (Service) Name" }, + { "DatabaseName", "Database Name" }, + { "DatabasePortInfo", "Database Listener Port" }, + { "DatabasePort", "Database Port" }, + { "DatabaseUserInfo", "Database iDempiere User ID" }, + { "DatabaseUser", "Database User" }, + { "DatabasePasswordInfo", "Database iDempiere User Password" }, + { "DatabasePassword", "Database Password" }, + { "TNSNameInfo", "Discovered Databases" }, + { "TNSName", "Database Search" }, + { "SystemPasswordInfo", "Database System User Password" }, + { "SystemPassword", "System Password" }, + { "MailServerInfo", "Mail Server" }, + { "MailServer", "Mail Server" }, + { "AdminEMailInfo", "iDempiere Administrator EMail" }, + { "AdminEMail", "Admin EMail" }, + { "DatabaseServerInfo", "Database Server Name" }, + { "DatabaseServer", "Database Server" }, + { "JavaHomeInfo", "Java Home Folder" }, + { "JavaHome", "Java Home" }, + { "JNPPortInfo", "Application Server JNP Port" }, + { "JNPPort", "JNP Port" }, + { "MailUserInfo", "iDempiere Mail User" }, + { "MailUser", "Mail User" }, + { "MailPasswordInfo", "iDempiere Mail User Password" }, + { "MailPassword", "Mail Password" }, + { "KeyStorePassword", "KeyStore Password" }, + { "KeyStorePasswordInfo", "Password for SSL Key Store" }, + // + { "JavaType", "Java VM"}, + { "JavaTypeInfo", "Java VM Vendor"}, + { "AppsType", "Server Type"}, + { "AppsTypeInfo", "J2EE Application Server Type"}, + { "DeployDir", "Deployment"}, + { "DeployDirInfo", "J2EE Deployment Directory"}, + { "ErrorDeployDir", "Error Deployment Directory"}, + // + { "TestInfo", "Test the Setup" }, + { "Test", "Test" }, + { "SaveInfo", "Save the Setup" }, + { "Save", "Save" }, + { "HelpInfo", "Get Help" }, + // + { "ServerError", "Server Setup Error" }, + { "ErrorJavaHome", "Error Java Home" }, + { "ErrorAdempiereHome", "Error iDempiere Home" }, + { "ErrorAppsServer", "Error Apps Server" }, + { "ErrorWebPort", "Error Web Port" }, + { "ErrorJNPPort", "Error JNP Port" }, + { "ErrorDatabaseServer", "Error Database Server" }, + { "ErrorDatabasePort", "Error Database Port" }, + { "ErrorJDBC", "Error JDBC Connection" }, + { "ErrorTNS", "Error TNS Connection" }, + { "ErrorMailServer", "Error Mail Server" }, + { "ErrorMail", "Error Mail" }, + { "ErrorSave", "Error Saving File" }, + + { "EnvironmentSaved", "Environment file saved .... starting Deployment\n" + + "You can re-start the Application Server after program completes.\n" + + "Please check Trace for errors.\n" } + + }; + + /** + * Get Content + * @return content array + */ + public Object[][] getContents() + { + return contents; + } // getContents + } // SetupRes diff --git a/org.adempiere.install/src/org/compiere/install/util/AppsAction.java b/org.adempiere.install/src/org/compiere/install/util/AppsAction.java index de5a507b5e..d7c712dc55 100644 --- a/org.adempiere.install/src/org/compiere/install/util/AppsAction.java +++ b/org.adempiere.install/src/org/compiere/install/util/AppsAction.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,25 +16,25 @@ *****************************************************************************/ package org.compiere.install.util; -import java.awt.Dimension; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.AbstractAction; -import javax.swing.AbstractButton; -import javax.swing.Action; -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JComponent; -import javax.swing.JMenuItem; -import javax.swing.JToggleButton; -import javax.swing.KeyStroke; - -import org.compiere.util.Env; -import org.compiere.util.Msg; +import java.awt.Dimension; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.AbstractAction; +import javax.swing.AbstractButton; +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComponent; +import javax.swing.JMenuItem; +import javax.swing.JToggleButton; +import javax.swing.KeyStroke; + +import org.compiere.util.Env; +import org.compiere.util.Msg; /** * Application Action. @@ -47,11 +47,11 @@ import org.compiere.util.Msg; */ public final class AppsAction extends AbstractAction { - /** - * - */ - private static final long serialVersionUID = 8522301377339185496L; - + /** + * + */ + private static final long serialVersionUID = 8522301377339185496L; + /** * Application Action * @@ -146,13 +146,13 @@ public final class AppsAction extends AbstractAction m_button.setActionCommand(m_action); m_button.setMargin(BUTTON_INSETS); m_button.setSize(BUTTON_SIZE); - // - if (accelerator != null) - { - m_button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(accelerator, action); - m_button.getActionMap().put(action, this); - } - } // Action + // + if (accelerator != null) + { + m_button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(accelerator, action); + m_button.getActionMap().put(action, this); + } + } // Action /** Button Size */ public static final Dimension BUTTON_SIZE = new Dimension(28,28); @@ -175,14 +175,14 @@ public final class AppsAction extends AbstractAction * @param name name * @param small small * @return Icon - */ - private ImageIcon getIcon(String name, boolean small) - { - String fullName = name + (small ? "16" : "24"); - return Env.getImageIcon2(fullName); - } // getIcon - - /** + */ + private ImageIcon getIcon(String name, boolean small) + { + String fullName = name + (small ? "16" : "24"); + return Env.getImageIcon2(fullName); + } // getIcon + + /** * Get Name/ActionCommand * @return ActionName */ @@ -241,11 +241,11 @@ public final class AppsAction extends AbstractAction m_pressed = pressed; // Set Button - if (m_button != null) + if (m_button != null) m_button.setSelected(pressed); - + // Set Menu - if (m_menu != null) + if (m_menu != null) m_menu.setSelected(pressed); } // setPressed @@ -300,7 +300,7 @@ public final class AppsAction extends AbstractAction */ public String toString() { - StringBuilder sb = new StringBuilder("AppsAction["); + StringBuilder sb = new StringBuilder("AppsAction["); sb.append(m_action); Object oo = getValue(Action.ACCELERATOR_KEY); if (oo != null) diff --git a/org.adempiere.pipo.handlers/src/org/adempiere/pipo2/handler/SQLStatementElementHandler.java b/org.adempiere.pipo.handlers/src/org/adempiere/pipo2/handler/SQLStatementElementHandler.java index 89372ff93a..68e9ede7ed 100644 --- a/org.adempiere.pipo.handlers/src/org/adempiere/pipo2/handler/SQLStatementElementHandler.java +++ b/org.adempiere.pipo.handlers/src/org/adempiere/pipo2/handler/SQLStatementElementHandler.java @@ -1,169 +1,169 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 Adempiere, 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. * - * - * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com - * Contributor(s): Low Heng Sin hengsin@avantz.com - *****************************************************************************/ -package org.adempiere.pipo2.handler; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Savepoint; -import java.sql.Statement; -import java.util.logging.Level; - -import javax.xml.transform.sax.TransformerHandler; - -import org.adempiere.pipo2.AbstractElementHandler; -import org.adempiere.pipo2.Element; -import org.adempiere.pipo2.PIPOContext; -import org.adempiere.pipo2.PackOut; -import org.adempiere.pipo2.PackoutItem; -import org.adempiere.pipo2.SQLElementParameters; -import org.compiere.model.X_AD_Package_Imp_Detail; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.Trx; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.AttributesImpl; - -public class SQLStatementElementHandler extends AbstractElementHandler { - - public void startElement(PIPOContext ctx, Element element) throws SAXException { - String elementValue = element.getElementValue(); - - log.info(elementValue); - String DBType = getStringValue(element, "DBType"); - String sql = getStringValue(element, "statement"); - if (sql.endsWith(";") && !(sql.toLowerCase().endsWith("end;"))) - sql = sql.substring(0, sql.length() - 1); - sql=Env.parseContext(Env.getCtx(), 0, sql, false); // tbayen IDEMPIERE-2140 - Savepoint savepoint = null; +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, 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. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Savepoint; +import java.sql.Statement; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PIPOContext; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PackoutItem; +import org.adempiere.pipo2.SQLElementParameters; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Trx; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class SQLStatementElementHandler extends AbstractElementHandler { + + public void startElement(PIPOContext ctx, Element element) throws SAXException { + String elementValue = element.getElementValue(); + + log.info(elementValue); + String DBType = getStringValue(element, "DBType"); + String sql = getStringValue(element, "statement"); + if (sql.endsWith(";") && !(sql.toLowerCase().endsWith("end;"))) + sql = sql.substring(0, sql.length() - 1); + sql=Env.parseContext(Env.getCtx(), 0, sql, false); // tbayen IDEMPIERE-2140 + Savepoint savepoint = null; int count = 0; - PreparedStatement pstmt = null; - X_AD_Package_Imp_Detail impDetail = null; - impDetail = createImportDetail(ctx, element.qName, "", 0); - try { - // NOTE Postgres needs to commit DDL statements - // add a SQL command just with COMMIT if you want to simulate the Oracle behavior (commit on DDL) - // Use savepoint here so that SQL exception would not rollback the whole process - Trx trx = Trx.get(getTrxName(ctx), true); - savepoint = trx.setSavepoint(null); - - pstmt = DB.prepareStatement(sql, getTrxName(ctx)); - if (DBType.equals("ALL")) { - count = pstmt.executeUpdate(); - if (log.isLoggable(Level.INFO)) log.info("Executed SQL Statement: "+ getStringValue(element, "statement") + " ReturnValue="+count); - } else if (DB.isOracle() == true && DBType.equals("Oracle")) { - count = pstmt.executeUpdate(); - if (log.isLoggable(Level.INFO)) log.info("Executed SQL Statement for Oracle: "+ getStringValue(element, "statement") + " ReturnValue="+count); - } else if (DB.isPostgreSQL() - && ( DBType.equals("Postgres") - || DBType.equals("PostgreSQL") // backward compatibility with old packages developed by hand - ) - ) { - // Avoid convert layer - command specific for postgresql - // - // pstmt = DB.prepareStatement(sql, getTrxName(ctx)); - // pstmt.executeUpdate(); - // - - Statement stmt = null; - try { - stmt = pstmt.getConnection().createStatement(); - count = stmt.executeUpdate (sql); - if (log.isLoggable(Level.INFO)) log.info("Executed SQL Statement for PostgreSQL: "+ getStringValue(element,"statement") + " ReturnValue="+count); - } finally { - DB.close(stmt); - stmt = null; - } - } - logImportDetail (ctx, impDetail, 1, "SQLStatement",count,"Execute"); - ctx.packIn.getNotifier().addSuccessLine("-> " + sql); - } catch (Exception e) { - // rollback immediately on exception to avoid a wrong SQL stop the whole process - if (savepoint != null) - { - Trx trx = Trx.get(getTrxName(ctx), false); - try { - if (trx.getConnection() != null) - trx.getConnection().rollback(savepoint); - } catch (SQLException e1) { - //a rollback or commit have happens making the savepoint becomes invalid. - //rollback trx to continue - trx.rollback(); - } - savepoint = null; - } - ctx.packIn.getNotifier().addFailureLine("SQL statement failed but ignored, error (" + e.getLocalizedMessage() + "): "); - logImportDetail (ctx, impDetail, 0, "SQLStatement",-1,"Execute"); - ctx.packIn.getNotifier().addFailureLine("-> " + sql); - log.log(Level.SEVERE,"SQLStatement", e); - } finally { - DB.close(pstmt); - pstmt = null; - if (savepoint != null) { - Trx trx = Trx.get(getTrxName(ctx), false); - try { - trx.releaseSavepoint(savepoint); - } catch (SQLException e) { - if (DB.isPostgreSQL()) { - //a commit or rollback have happens that make the savepoint invalid. - //need to call rollback to continue - trx.commit(); - } - } - } - } - } - - public void endElement(PIPOContext ctx, Element element) throws SAXException { - } - - public void create(PIPOContext ctx, TransformerHandler document) - throws SAXException { - String SQLStatement = Env.getContext(ctx.ctx, SQLElementParameters.SQL_STATEMENT); - String DBType = Env.getContext(ctx.ctx, SQLElementParameters.DB_TYPE); - AttributesImpl atts = new AttributesImpl(); - addTypeName(atts, "custom"); - document.startElement("","","SQLStatement",atts); - createSQLStatmentBinding(document, SQLStatement, DBType); - document.endElement("","","SQLStatement"); - } - - private void createSQLStatmentBinding( TransformerHandler document, String sqlStatement, String DBType) throws SAXException - { - document.startElement("","","DBType", new AttributesImpl()); - char[] contents = DBType.toCharArray(); - document.characters(contents,0,contents.length); - document.endElement("","","DBType"); - - document.startElement("","","statement", new AttributesImpl()); - contents = sqlStatement.toCharArray(); - document.startCDATA(); - document.characters(contents,0,contents.length); - document.endCDATA(); - document.endElement("","","statement"); - - } - - public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int field) throws Exception - { - PackoutItem detail = packout.getCurrentPackoutItem(); - Env.setContext(packout.getCtx().ctx, SQLElementParameters.SQL_STATEMENT, (String)detail.getProperty(SQLElementParameters.SQL_STATEMENT)); - Env.setContext(packout.getCtx().ctx, SQLElementParameters.DB_TYPE, (String)detail.getProperty(SQLElementParameters.DB_TYPE)); - this.create(packout.getCtx(), packoutHandler); - packout.getCtx().ctx.remove(SQLElementParameters.SQL_STATEMENT); - packout.getCtx().ctx.remove(SQLElementParameters.DB_TYPE); - } -} + PreparedStatement pstmt = null; + X_AD_Package_Imp_Detail impDetail = null; + impDetail = createImportDetail(ctx, element.qName, "", 0); + try { + // NOTE Postgres needs to commit DDL statements + // add a SQL command just with COMMIT if you want to simulate the Oracle behavior (commit on DDL) + // Use savepoint here so that SQL exception would not rollback the whole process + Trx trx = Trx.get(getTrxName(ctx), true); + savepoint = trx.setSavepoint(null); + + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + if (DBType.equals("ALL")) { + count = pstmt.executeUpdate(); + if (log.isLoggable(Level.INFO)) log.info("Executed SQL Statement: "+ getStringValue(element, "statement") + " ReturnValue="+count); + } else if (DB.isOracle() == true && DBType.equals("Oracle")) { + count = pstmt.executeUpdate(); + if (log.isLoggable(Level.INFO)) log.info("Executed SQL Statement for Oracle: "+ getStringValue(element, "statement") + " ReturnValue="+count); + } else if (DB.isPostgreSQL() + && ( DBType.equals("Postgres") + || DBType.equals("PostgreSQL") // backward compatibility with old packages developed by hand + ) + ) { + // Avoid convert layer - command specific for postgresql + // + // pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + // pstmt.executeUpdate(); + // + + Statement stmt = null; + try { + stmt = pstmt.getConnection().createStatement(); + count = stmt.executeUpdate (sql); + if (log.isLoggable(Level.INFO)) log.info("Executed SQL Statement for PostgreSQL: "+ getStringValue(element,"statement") + " ReturnValue="+count); + } finally { + DB.close(stmt); + stmt = null; + } + } + logImportDetail (ctx, impDetail, 1, "SQLStatement",count,"Execute"); + ctx.packIn.getNotifier().addSuccessLine("-> " + sql); + } catch (Exception e) { + // rollback immediately on exception to avoid a wrong SQL stop the whole process + if (savepoint != null) + { + Trx trx = Trx.get(getTrxName(ctx), false); + try { + if (trx.getConnection() != null) + trx.getConnection().rollback(savepoint); + } catch (SQLException e1) { + //a rollback or commit have happens making the savepoint becomes invalid. + //rollback trx to continue + trx.rollback(); + } + savepoint = null; + } + ctx.packIn.getNotifier().addFailureLine("SQL statement failed but ignored, error (" + e.getLocalizedMessage() + "): "); + logImportDetail (ctx, impDetail, 0, "SQLStatement",-1,"Execute"); + ctx.packIn.getNotifier().addFailureLine("-> " + sql); + log.log(Level.SEVERE,"SQLStatement", e); + } finally { + DB.close(pstmt); + pstmt = null; + if (savepoint != null) { + Trx trx = Trx.get(getTrxName(ctx), false); + try { + trx.releaseSavepoint(savepoint); + } catch (SQLException e) { + if (DB.isPostgreSQL()) { + //a commit or rollback have happens that make the savepoint invalid. + //need to call rollback to continue + trx.commit(); + } + } + } + } + } + + public void endElement(PIPOContext ctx, Element element) throws SAXException { + } + + public void create(PIPOContext ctx, TransformerHandler document) + throws SAXException { + String SQLStatement = Env.getContext(ctx.ctx, SQLElementParameters.SQL_STATEMENT); + String DBType = Env.getContext(ctx.ctx, SQLElementParameters.DB_TYPE); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "custom"); + document.startElement("","","SQLStatement",atts); + createSQLStatmentBinding(document, SQLStatement, DBType); + document.endElement("","","SQLStatement"); + } + + private void createSQLStatmentBinding( TransformerHandler document, String sqlStatement, String DBType) throws SAXException + { + document.startElement("","","DBType", new AttributesImpl()); + char[] contents = DBType.toCharArray(); + document.characters(contents,0,contents.length); + document.endElement("","","DBType"); + + document.startElement("","","statement", new AttributesImpl()); + contents = sqlStatement.toCharArray(); + document.startCDATA(); + document.characters(contents,0,contents.length); + document.endCDATA(); + document.endElement("","","statement"); + + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int field) throws Exception + { + PackoutItem detail = packout.getCurrentPackoutItem(); + Env.setContext(packout.getCtx().ctx, SQLElementParameters.SQL_STATEMENT, (String)detail.getProperty(SQLElementParameters.SQL_STATEMENT)); + Env.setContext(packout.getCtx().ctx, SQLElementParameters.DB_TYPE, (String)detail.getProperty(SQLElementParameters.DB_TYPE)); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().ctx.remove(SQLElementParameters.SQL_STATEMENT); + packout.getCtx().ctx.remove(SQLElementParameters.DB_TYPE); + } +} diff --git a/org.adempiere.pipo.legacy/src/org/adempiere/pipo/AbstractElementHandler.java b/org.adempiere.pipo.legacy/src/org/adempiere/pipo/AbstractElementHandler.java index b1ff7a6b23..d778ee75bc 100644 --- a/org.adempiere.pipo.legacy/src/org/adempiere/pipo/AbstractElementHandler.java +++ b/org.adempiere.pipo.legacy/src/org/adempiere/pipo/AbstractElementHandler.java @@ -87,9 +87,9 @@ public abstract class AbstractElementHandler implements ElementHandler { int id = 0; TransformerHandler hd_document = getLogDocument(ctx); AttributesImpl attsOut = new AttributesImpl(); - String result = success == 1 ? "Success" : "Failure"; - - //hd_documemt.startElement("","","Successful",attsOut); + String result = success == 1 ? "Success" : "Failure"; + + //hd_documemt.startElement("","","Successful",attsOut); recordLayout.append("Type:") .append(objectType) .append(" - Name:") @@ -98,28 +98,28 @@ public abstract class AbstractElementHandler implements ElementHandler { .append(objectID) .append(" - Action:") .append(objectStatus) - .append(" - " + result); + .append(" - " + result); - hd_document.startElement("","",result,attsOut); + hd_document.startElement("","",result,attsOut); hd_document.characters(recordLayout.toString().toCharArray(),0,recordLayout.length()); - hd_document.endElement("","",result); + hd_document.endElement("","",result); - X_AD_Package_Imp_Detail detail = new X_AD_Package_Imp_Detail(ctx, 0, getTrxName(ctx)); - detail.setAD_Package_Imp_ID(getPackageImpId(ctx)); - detail.setAD_Org_ID(Env.getAD_Org_ID(ctx) ); - detail.setType(objectType); - detail.setName(objectName); - detail.setAction(objectStatus); - detail.setSuccess(result); - detail.setRecord_ID(objectID); - detail.setAD_Backup_ID(objectIDBackup); - detail.setTableName(tableName); - detail.setAD_Table_ID(AD_Table_ID); + X_AD_Package_Imp_Detail detail = new X_AD_Package_Imp_Detail(ctx, 0, getTrxName(ctx)); + detail.setAD_Package_Imp_ID(getPackageImpId(ctx)); + detail.setAD_Org_ID(Env.getAD_Org_ID(ctx) ); + detail.setType(objectType); + detail.setName(objectName); + detail.setAction(objectStatus); + detail.setSuccess(result); + detail.setRecord_ID(objectID); + detail.setAD_Backup_ID(objectIDBackup); + detail.setTableName(tableName); + detail.setAD_Table_ID(AD_Table_ID); - if ( !detail.save(getTrxName(ctx)) ) + if ( !detail.save(getTrxName(ctx)) ) log.info("Insert to import detail failed"); - id = detail.get_ID(); + id = detail.get_ID(); return id; } diff --git a/org.adempiere.pipo.legacy/src/org/adempiere/pipo/PackOut.java b/org.adempiere.pipo.legacy/src/org/adempiere/pipo/PackOut.java index c0277e716e..f9958e4573 100644 --- a/org.adempiere.pipo.legacy/src/org/adempiere/pipo/PackOut.java +++ b/org.adempiere.pipo.legacy/src/org/adempiere/pipo/PackOut.java @@ -1,894 +1,894 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 Adempiere, 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. * - * * - * Copyright (C) * - * 2004 Robert KLEIN. robeklein@hotmail.com * - * Contributor(s): Low Heng Sin hengsin@avantz.com * - * Teo Sarca teo.sarca@arhipac.ro, SC ARHIPAC SERVICE SRL * - *****************************************************************************/ -package org.adempiere.pipo; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.Properties; -import java.util.logging.Level; - -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; - -import org.adempiere.pipo.handler.AdElementHandler; -import org.adempiere.pipo.handler.CodeSnipitElementHandler; -import org.adempiere.pipo.handler.CommonTranslationHandler; -import org.adempiere.pipo.handler.DataElementHandler; -import org.adempiere.pipo.handler.DistFileElementHandler; -import org.adempiere.pipo.handler.DynValRuleElementHandler; -import org.adempiere.pipo.handler.EntityTypeElementHandler; -import org.adempiere.pipo.handler.FieldGroupElementHandler; -import org.adempiere.pipo.handler.FormElementHandler; -import org.adempiere.pipo.handler.ImpFormatElementHandler; -import org.adempiere.pipo.handler.MenuElementHandler; -import org.adempiere.pipo.handler.MessageElementHandler; -import org.adempiere.pipo.handler.ModelValidatorElementHandler; -import org.adempiere.pipo.handler.PrintFormatElementHandler; -import org.adempiere.pipo.handler.PrintPaperElementHandler; -import org.adempiere.pipo.handler.ProcessElementHandler; -import org.adempiere.pipo.handler.ReferenceElementHandler; -import org.adempiere.pipo.handler.ReportViewElementHandler; -import org.adempiere.pipo.handler.RoleElementHandler; -import org.adempiere.pipo.handler.SQLStatementElementHandler; -import org.adempiere.pipo.handler.TableElementHandler; -import org.adempiere.pipo.handler.TaskElementHandler; -import org.adempiere.pipo.handler.WindowElementHandler; -import org.adempiere.pipo.handler.WorkflowElementHandler; -import org.compiere.model.MSysConfig; -import org.compiere.model.X_AD_Element; -import org.compiere.model.X_AD_FieldGroup; -import org.compiere.model.X_AD_Package_Exp; -import org.compiere.model.X_AD_Package_Exp_Detail; -import org.compiere.model.X_AD_PrintPaper; -import org.compiere.model.X_AD_Reference; -import org.compiere.process.ProcessInfoParameter; -import org.compiere.process.SvrProcess; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.AttributesImpl; - - -/** - * Convert AD to XML - * - * @author Robert Klein - * @version $Id: PackOut.java,v 1.0 - * - * Contributor: William G. Heath - Export of workflows and dynamic validations - * - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - *

  • BF [ 1819315 ] PackOut: fix xml indentation not working - *
  • BF [ 1819319 ] PackOut: use just active AD_Package_Exp_Detail lines - *
  • -- - *
  • FR [ 2847727 ] 2pack export all messages for a entity type functionality - * https://sourceforge.net/tracker/?func=detail&atid=879335&aid=2847727&group_id=176962 - */ - -public class PackOut extends SvrProcess -{ - /** Record ID */ - private int p_PackOut_ID = 0; - private String PackOutVer = "005"; - private String packagedir = null; - private String packagename = null; - private String includesdir = null; - - public final static int MAX_OFFICIAL_ID = 999999; - - private Properties localContext = null; - - ProcessElementHandler processHandler = new ProcessElementHandler(); - TaskElementHandler taskHandler = new TaskElementHandler(); - FormElementHandler formHandler = new FormElementHandler(); - WindowElementHandler windowHandler = new WindowElementHandler(); - MenuElementHandler menuHandler = new MenuElementHandler(); - ReportViewElementHandler reportViewHandler = new ReportViewElementHandler(); - DataElementHandler dataHandler = new DataElementHandler(); - TableElementHandler tableHandler = new TableElementHandler(); - RoleElementHandler roleHandler = new RoleElementHandler(); - SQLStatementElementHandler sqlHandler = new SQLStatementElementHandler(); - ImpFormatElementHandler impFormtHandler = new ImpFormatElementHandler(); - CodeSnipitElementHandler codeHandler = new CodeSnipitElementHandler(); - WorkflowElementHandler workflowHandler = new WorkflowElementHandler(); - DynValRuleElementHandler dynValRuleHandler = new DynValRuleElementHandler(); - MessageElementHandler messageHandler = new MessageElementHandler(); - PrintFormatElementHandler printFormatHandler = new PrintFormatElementHandler(); - DistFileElementHandler distFileHandler = new DistFileElementHandler(); - ReferenceElementHandler referenceHandler = new ReferenceElementHandler(); - FieldGroupElementHandler fieldGroupHandler = new FieldGroupElementHandler(); - AdElementHandler adElementHandler = new AdElementHandler(); - CommonTranslationHandler translationHandler = new CommonTranslationHandler(); - ModelValidatorElementHandler modelValidatorHandler = new ModelValidatorElementHandler(); - EntityTypeElementHandler entitytypeHandler = new EntityTypeElementHandler(); - PrintPaperElementHandler printPaperHandler = new PrintPaperElementHandler(); - - /** - * Prepare - e.g., get Parameters. - */ - protected void prepare() - { - p_PackOut_ID = getRecord_ID(); - ProcessInfoParameter[] para = getParameter(); - for (int i = 0; i < para.length; i++) - { - } - } // prepare - - - /** - * Start the transformation to XML - * @return info - * @throws Exception - */ - protected String doIt() throws java.lang.Exception - { - initContext(); - - OutputStream packageDocStream = null; - OutputStream packOutDocStream = null; - if (log.isLoggable(Level.INFO)) log.info("doIt - AD_PACKAGE_EXP_ID=" + p_PackOut_ID); - if (p_PackOut_ID == 0) - throw new IllegalArgumentException("No Record"); - String sql1 = "SELECT * FROM AD_Package_Exp WHERE AD_Package_Exp_ID = "+p_PackOut_ID; - PreparedStatement pstmt1 = null; - pstmt1 = DB.prepareStatement (sql1, get_TrxName()); - - try { - ResultSet rs1 = pstmt1.executeQuery(); - while (rs1.next()){ - //Create the package documentation - packagedir = rs1.getString(X_AD_Package_Exp.COLUMNNAME_File_Directory).trim(); - if (!packagedir.endsWith("/") && !packagedir.endsWith("\\")) - packagedir += File.separator; - packagename = packagedir + rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name); - includesdir = rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name) + File.separator +"**"; - @SuppressWarnings("unused") - boolean success = (new File(packagename+File.separator+"doc"+File.separator)).mkdirs(); - String file_document = packagename+File.separator+"doc"+File.separator+rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name)+"Doc.xml"; - packageDocStream = new FileOutputStream (file_document, false); - StreamResult streamResult_document = new StreamResult(new OutputStreamWriter(packageDocStream,"ISO-8859-1")); - SAXTransformerFactory tf_document = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); - tf_document.setAttribute("indent-number", new Integer(4)); - TransformerHandler packageDocument = tf_document.newTransformerHandler(); - Transformer serializer_document = packageDocument.getTransformer(); - serializer_document.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); - serializer_document.setOutputProperty(OutputKeys.INDENT,"yes"); - packageDocument.setResult(streamResult_document); - packageDocument.startDocument(); - AttributesImpl atts = new AttributesImpl(); - atts.clear(); - packageDocument.processingInstruction("xml-stylesheet","type=\"text/css\" href=\"adempiereDocument.css\""); - packageDocument.startElement("","","adempiereDocument",atts); - packageDocument.startElement("","","header",atts); - packageDocument.characters((rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name)+" Package Description").toCharArray(),0,(rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name)+" Package Description").length()); - packageDocument.endElement("","","header"); - packageDocument.startElement("","","H1",atts); - packageDocument.characters(("Package Name:" ).toCharArray(),0,("Package Name:" ).length()); - packageDocument.endElement("","","H1"); - packageDocument.startElement("","","packagename",atts); - packageDocument.characters(rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name).toCharArray(),0,rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name).length()); - packageDocument.endElement("","","packagename"); - packageDocument.startElement("","","H1",atts); - packageDocument.characters(("Creator:" ).toCharArray(),0,("Creator:").length()); - packageDocument.endElement("","","H1"); - packageDocument.startElement("","","creator",atts); - packageDocument.characters(rs1.getString(X_AD_Package_Exp.COLUMNNAME_UserName).toCharArray(),0,rs1.getString(X_AD_Package_Exp.COLUMNNAME_UserName).length()); - packageDocument.endElement("","","creator"); - packageDocument.startElement("","","H1",atts); - packageDocument.characters(("Email Address:" ).toCharArray(),0,("Email Address:" ).length()); - packageDocument.endElement("","","H1"); - packageDocument.startElement("","","creatorcontact",atts); - packageDocument.characters(rs1.getString(X_AD_Package_Exp.COLUMNNAME_EMail).toCharArray(),0,rs1.getString(X_AD_Package_Exp.COLUMNNAME_EMail).length()); - packageDocument.endElement("","","creatorcontact"); - packageDocument.startElement("","","H1",atts); - packageDocument.characters(("Created:" ).toCharArray(),0,("Created:" ).length()); - packageDocument.endElement("","","H1"); - packageDocument.startElement("","","createddate",atts); - packageDocument.characters(rs1.getString("Created").toString().toCharArray(),0,rs1.getString("Created").toString().length()); - packageDocument.endElement("","","createddate"); - packageDocument.startElement("","","H1",atts); - packageDocument.characters(("Updated:" ).toCharArray(),0,("Updated:" ).length()); - packageDocument.endElement("","","H1"); - packageDocument.startElement("","","updateddate",atts); - packageDocument.characters(rs1.getString("Updated").toString().toCharArray(),0,rs1.getString("Updated".toString()).length()); - packageDocument.endElement("","","updateddate"); - packageDocument.startElement("","","H1",atts); - packageDocument.characters(("Description:" ).toCharArray(),0,("Description:" ).length()); - packageDocument.endElement("","","H1"); - packageDocument.startElement("","","description",atts); - packageDocument.characters(rs1.getString(X_AD_Package_Exp.COLUMNNAME_Description).toCharArray(),0,rs1.getString(X_AD_Package_Exp.COLUMNNAME_Description).length()); - packageDocument.endElement("","","description"); - packageDocument.startElement("","","H1",atts); - packageDocument.characters(("Instructions:" ).toCharArray(),0,("Instructions:" ).length()); - packageDocument.endElement("","","H1"); - packageDocument.startElement("","","instructions",atts); - packageDocument.characters(rs1.getString(X_AD_Package_Exp.COLUMNNAME_Instructions).toCharArray(),0,rs1.getString(X_AD_Package_Exp.COLUMNNAME_Instructions).length()); - packageDocument.endElement("","","instructions"); - packageDocument.startElement("","","H1",atts); - packageDocument.characters(("Files in Package:" ).toCharArray(),0,("Files in Package:" ).length()); - packageDocument.endElement("","","H1"); - packageDocument.startElement("","","file",atts); - packageDocument.characters(("File: PackOut.xml").toCharArray(),0,("File: PackOut.xml").length()); - packageDocument.endElement("","","file"); - packageDocument.startElement("","","filedirectory",atts); - packageDocument.characters("Directory: \\dict\\".toCharArray(),0,("Directory: \\dict\\").length()); - packageDocument.endElement("","","filedirectory"); - packageDocument.startElement("","","filenotes",atts); - packageDocument.characters("Notes: Contains all application/object settings for package".toCharArray(),0,"Notes: Contains all application/object settings for package".length()); - packageDocument.endElement("","","filenotes"); - success = (new File(packagename+File.separator+ "dict"+File.separator)).mkdirs(); - String file_menu = packagename+File.separator+ "dict"+File.separator+"PackOut.xml"; - packOutDocStream = new FileOutputStream (file_menu, false); - StreamResult streamResult_menu = new StreamResult(new OutputStreamWriter(packOutDocStream,"ISO-8859-1")); - SAXTransformerFactory tf_menu = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); - tf_menu.setAttribute("indent-number", new Integer(4)); - TransformerHandler packOutDocument = tf_menu.newTransformerHandler(); - Transformer serializer_menu = packOutDocument.getTransformer(); - serializer_menu.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); - serializer_menu.setOutputProperty(OutputKeys.INDENT,"yes"); - packOutDocument.setResult(streamResult_menu); - packOutDocument.startDocument(); - atts.clear(); - atts.addAttribute("","","Name","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name)); - atts.addAttribute("","","Version","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_PK_Version)); - atts.addAttribute("","","CompVer","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_ReleaseNo)); - atts.addAttribute("","","DataBase","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_Version)); - atts.addAttribute("","","Description","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_Description)); - atts.addAttribute("","","creator","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_UserName)); - atts.addAttribute("","","creatorcontact","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_EMail)); - atts.addAttribute("","","createddate","CDATA",rs1.getString("Created")); - atts.addAttribute("","","updateddate","CDATA",rs1.getString("Updated")); - atts.addAttribute("","","PackOutVer","CDATA",PackOutVer); - - packOutDocument.startElement("","","adempiereAD",atts); - atts.clear(); - - final String sql = "SELECT * FROM AD_Package_Exp_Detail WHERE AD_Package_Exp_ID = "+p_PackOut_ID+" AND IsActive='Y' ORDER BY Line ASC"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement (sql, get_TrxName()); - rs = pstmt.executeQuery(); - while (rs.next()) - { - final String Type = rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Type); - final int AD_EntityType_ID = rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_EntityType_ID); - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_EntityType_ID, AD_EntityType_ID); - // - if (log.isLoggable(Level.INFO)) log.info(rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Line)); - if (Type.compareTo("M") == 0){ - createMenu(rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Menu_ID), packOutDocument ); - } - else if (Type.compareTo("P") == 0) - createProcess ( rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Process_ID), packOutDocument ); - else if (Type.compareTo("R") == 0) - createReportview ( rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ReportView_ID), packOutDocument ); - else if (Type.compareTo("D") == 0) - createData ( rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID), rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement), packOutDocument ); - else if (Type.compareTo("T") == 0) - createTable (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID), packOutDocument); - else if (Type.compareTo("X") == 0) - createForm (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Form_ID), packOutDocument); - else if (Type.compareTo("W") == 0) - createWindow (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Window_ID), packOutDocument); - else if (Type.compareTo("S") == 0) - createRoles (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Role_ID), packOutDocument); - else if (Type.compareTo("SQL") == 0) - createSQL (rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement), rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_DBType), packOutDocument); - else if (Type.compareTo("IMP") == 0) - createImpFormat (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ImpFormat_ID), packOutDocument); - else if (Type.compareTo("REF") == 0) - createReference (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Reference_ID), packOutDocument); - else if (Type.compareTo("SNI") == 0) - createSnipit( - rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Destination_Directory), - rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Destination_FileName), - rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_Old), - rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_New), - rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo), - packOutDocument); - else if (Type.compareTo("F") == 0) - createWorkflow (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID), packOutDocument); - else if (Type.compareTo("V") == 0) - createDynamicRuleValidation(rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID), packOutDocument); - else if (Type.compareTo("MSG") == 0) - createMessage(rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Message_ID), packOutDocument); - else if (Type.compareTo("PFT") == 0) - createPrintFormat(rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_PrintFormat_ID), packOutDocument); - else if (Type.compareTo(X_AD_Package_Exp_Detail.TYPE_ModelValidator) == 0) - createModelValidator(rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ModelValidator_ID), packOutDocument); - else if (Type.compareTo(X_AD_Package_Exp_Detail.TYPE_EntityType) == 0) - createEntityType(AD_EntityType_ID, packOutDocument); - else if (Type.compareTo("C") == 0){ - log.log(Level.INFO,"In PackOut.java handling Code or Other 2pack module creation"); - - String fullDirectory = rs1.getString(X_AD_Package_Exp.COLUMNNAME_File_Directory) + rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name)+rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory); - log.log(Level.INFO,"fullDirectory" + fullDirectory); - String targetDirectoryModified=null; - char fileseperator1 = '/'; - char fileseperator2 = '\\'; - //Correct package for proper file separator - if (File.separator.equals("/")){ - targetDirectoryModified = fullDirectory.replace(fileseperator2,fileseperator1); - } - else - targetDirectoryModified = fullDirectory.replace(fileseperator1,fileseperator2); - - String target_File = (targetDirectoryModified); - success = (new File(target_File).mkdirs()); - fullDirectory = rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_File_Directory); - targetDirectoryModified=null; - //Correct package for proper file separator - if (File.separator.equals("/")){ - targetDirectoryModified = fullDirectory.replace(fileseperator2,fileseperator1); - } - else - targetDirectoryModified = fullDirectory.replace(fileseperator2,fileseperator1); - - copyCode( - targetDirectoryModified + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName), - target_File + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName)); - - atts.clear(); - - if(rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Destination_Directory) != null){ - - fullDirectory = rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Destination_Directory); - String destinationDirectoryModified=null; - - //Correct package for proper file separator - if (File.separator.equals("/")){ - destinationDirectoryModified = fullDirectory.replace(fileseperator2,fileseperator1); - } - else - destinationDirectoryModified = fullDirectory.replace(fileseperator2,fileseperator1); - - createDistributeFile( - rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName), - rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory), - rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo), - destinationDirectoryModified, - packOutDocument); - - } - - if(rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName) != null){ - packageDocument.startElement("","","file",atts); - packageDocument.characters(("File: "+rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName)).toCharArray(),0,("File: "+rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName)).length()); - packageDocument.endElement("","","file"); - } - packageDocument.startElement("","","filedirectory",atts); - packageDocument.characters( - ("Directory: " + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory)).toCharArray(), - 0, - ("Directory: " + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory)).length()); - packageDocument.endElement("","","filedirectory"); - - packageDocument.startElement("","","filenotes",atts); - packageDocument.characters( - ("Notes: " + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Description)).toCharArray(), - 0, - (("Notes: " + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Description)).length())); - packageDocument.endElement("","","filenotes"); - } - } - // - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_EntityType_ID); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - atts.clear(); - //no longer use - //packOutDocument.startElement("","","menuset",atts); - //packOutDocument.endElement("","","menuset"); - packOutDocument.endElement("","","adempiereAD"); - packOutDocument.endDocument();packageDocument.endElement("","","adempiereDocument"); - packageDocument.endDocument(); - //m_Exp.setProcessed(true); - //m_Exp.saveEx(); - } - rs1.close(); - pstmt1.close(); - pstmt1 = null; - } - catch (Exception e) - { - log.log(Level.SEVERE,e.getLocalizedMessage(), e); - throw e; - } - finally - { - try - { - if (pstmt1 != null) - pstmt1.close (); - } - catch (Exception e) - {} - pstmt1 = null; - - // Close streams - teo_sarca [ 1704762 ] - if (packageDocStream != null) - try { - packageDocStream.close(); - } catch (Exception e) {} - if (packOutDocStream != null) - try { - packOutDocStream.close(); - } catch (Exception e) {} - } - - //create compressed packages - //set the files - File srcFolder = new File(packagedir); - File destZipFile = new File(packagename+".zip"); - File destTarFile = new File(packagename+".tar"); - File destGZipFile = new File(packagename+".tar.gz"); - - //delete the old packages if necessary - @SuppressWarnings("unused") - boolean success = destZipFile.delete(); - success = destTarFile.delete(); - success = destGZipFile.delete(); - - //create the compressed packages - CreateZipFile.zipFolder(srcFolder, destZipFile, includesdir); - CreateZipFile.tarFolder(srcFolder, destTarFile, includesdir); - CreateZipFile.gzipFile(destTarFile, destGZipFile); - - //Clean .tar file up - success = destTarFile.delete(); - - return "Finish Process"; - } // doIt - - private void initContext() { - Properties tmp = new Properties(); - if (getCtx() != null) - tmp.putAll(getCtx()); - tmp.put("TrxName", get_TrxName()); - tmp.put("PackOutProcess", this); - localContext = tmp; - } - - private void copyCode (String sourceName, String copyName) - { - copyFile (sourceName, copyName ); - } - - /** - * - * @param AD_Menu_ID - * @param packOutDocument - * @throws Exception - */ - public void createMenu(int AD_Menu_ID, TransformerHandler packOutDocument) throws SAXException { - Env.setContext(getCtx(), "AD_Menu_ID", AD_Menu_ID); - menuHandler.create(getCtx(), packOutDocument); - getCtx().remove("AD_Menu_ID"); - } - - /** - * - * @param AD_PrintFormat_ID - * @param packOutDocument - * @throws Exception +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, 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. * + * * + * Copyright (C) * + * 2004 Robert KLEIN. robeklein@hotmail.com * + * Contributor(s): Low Heng Sin hengsin@avantz.com * + * Teo Sarca teo.sarca@arhipac.ro, SC ARHIPAC SERVICE SRL * + *****************************************************************************/ +package org.adempiere.pipo; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; + +import org.adempiere.pipo.handler.AdElementHandler; +import org.adempiere.pipo.handler.CodeSnipitElementHandler; +import org.adempiere.pipo.handler.CommonTranslationHandler; +import org.adempiere.pipo.handler.DataElementHandler; +import org.adempiere.pipo.handler.DistFileElementHandler; +import org.adempiere.pipo.handler.DynValRuleElementHandler; +import org.adempiere.pipo.handler.EntityTypeElementHandler; +import org.adempiere.pipo.handler.FieldGroupElementHandler; +import org.adempiere.pipo.handler.FormElementHandler; +import org.adempiere.pipo.handler.ImpFormatElementHandler; +import org.adempiere.pipo.handler.MenuElementHandler; +import org.adempiere.pipo.handler.MessageElementHandler; +import org.adempiere.pipo.handler.ModelValidatorElementHandler; +import org.adempiere.pipo.handler.PrintFormatElementHandler; +import org.adempiere.pipo.handler.PrintPaperElementHandler; +import org.adempiere.pipo.handler.ProcessElementHandler; +import org.adempiere.pipo.handler.ReferenceElementHandler; +import org.adempiere.pipo.handler.ReportViewElementHandler; +import org.adempiere.pipo.handler.RoleElementHandler; +import org.adempiere.pipo.handler.SQLStatementElementHandler; +import org.adempiere.pipo.handler.TableElementHandler; +import org.adempiere.pipo.handler.TaskElementHandler; +import org.adempiere.pipo.handler.WindowElementHandler; +import org.adempiere.pipo.handler.WorkflowElementHandler; +import org.compiere.model.MSysConfig; +import org.compiere.model.X_AD_Element; +import org.compiere.model.X_AD_FieldGroup; +import org.compiere.model.X_AD_Package_Exp; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_PrintPaper; +import org.compiere.model.X_AD_Reference; +import org.compiere.process.ProcessInfoParameter; +import org.compiere.process.SvrProcess; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + + +/** + * Convert AD to XML + * + * @author Robert Klein + * @version $Id: PackOut.java,v 1.0 + * + * Contributor: William G. Heath - Export of workflows and dynamic validations + * + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1819315 ] PackOut: fix xml indentation not working + *
  • BF [ 1819319 ] PackOut: use just active AD_Package_Exp_Detail lines + *
  • -- + *
  • FR [ 2847727 ] 2pack export all messages for a entity type functionality + * https://sourceforge.net/tracker/?func=detail&atid=879335&aid=2847727&group_id=176962 + */ + +public class PackOut extends SvrProcess +{ + /** Record ID */ + private int p_PackOut_ID = 0; + private String PackOutVer = "005"; + private String packagedir = null; + private String packagename = null; + private String includesdir = null; + + public final static int MAX_OFFICIAL_ID = 999999; + + private Properties localContext = null; + + ProcessElementHandler processHandler = new ProcessElementHandler(); + TaskElementHandler taskHandler = new TaskElementHandler(); + FormElementHandler formHandler = new FormElementHandler(); + WindowElementHandler windowHandler = new WindowElementHandler(); + MenuElementHandler menuHandler = new MenuElementHandler(); + ReportViewElementHandler reportViewHandler = new ReportViewElementHandler(); + DataElementHandler dataHandler = new DataElementHandler(); + TableElementHandler tableHandler = new TableElementHandler(); + RoleElementHandler roleHandler = new RoleElementHandler(); + SQLStatementElementHandler sqlHandler = new SQLStatementElementHandler(); + ImpFormatElementHandler impFormtHandler = new ImpFormatElementHandler(); + CodeSnipitElementHandler codeHandler = new CodeSnipitElementHandler(); + WorkflowElementHandler workflowHandler = new WorkflowElementHandler(); + DynValRuleElementHandler dynValRuleHandler = new DynValRuleElementHandler(); + MessageElementHandler messageHandler = new MessageElementHandler(); + PrintFormatElementHandler printFormatHandler = new PrintFormatElementHandler(); + DistFileElementHandler distFileHandler = new DistFileElementHandler(); + ReferenceElementHandler referenceHandler = new ReferenceElementHandler(); + FieldGroupElementHandler fieldGroupHandler = new FieldGroupElementHandler(); + AdElementHandler adElementHandler = new AdElementHandler(); + CommonTranslationHandler translationHandler = new CommonTranslationHandler(); + ModelValidatorElementHandler modelValidatorHandler = new ModelValidatorElementHandler(); + EntityTypeElementHandler entitytypeHandler = new EntityTypeElementHandler(); + PrintPaperElementHandler printPaperHandler = new PrintPaperElementHandler(); + + /** + * Prepare - e.g., get Parameters. */ - public void createPrintFormat (int AD_PrintFormat_ID, TransformerHandler packOutDocument) throws Exception - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_PrintFormat_ID, AD_PrintFormat_ID); - printFormatHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_PrintFormat_ID); - } - - /** - * - * @param AD_Message_ID - * @param packOutDocument - * @throws Exception - */ - public void createMessage (int AD_Message_ID, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Message_ID, AD_Message_ID); - messageHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Message_ID); - } - - /** - * - * @param AD_Val_Rule_ID - * @param packOutDocument - * @throws Exception - */ - public void createDynamicRuleValidation (int AD_Val_Rule_ID, - TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID, AD_Val_Rule_ID); - dynValRuleHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID); - } - - /** - * - * @param AD_Workflow_ID - * @param packOutDocument - * @throws SAXException - */ - public void createWorkflow (int AD_Workflow_ID, TransformerHandler packOutDocument) - throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID, AD_Workflow_ID); - workflowHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID); - } - - /** - * - * @param FileName - * @param Source_Directory - * @param ReleaseNo - * @param Target_Directory - * @param atts - * @param packOutDocument - * @throws SAXException - */ - public void createDistributeFile (String FileName, String Source_Directory, String ReleaseNo,String Target_Directory, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_FileName, FileName); - Env.setContext(getCtx(), "Source_Directory", Source_Directory); - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo, ReleaseNo); - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory, Target_Directory); - distFileHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_FileName); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory); - getCtx().remove("Source_Directory"); - } - - /** - * - * @param AD_Form_ID - * @param packOutDocument - * @throws SAXException - */ - public void createForm (int AD_Form_ID, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), "AD_Form_ID", AD_Form_ID); - formHandler.create(getCtx(), packOutDocument); - getCtx().remove("AD_Form_ID"); - } - - /** - * - * @param AD_Task_ID - * @param packOutDocument - * @throws SAXException - */ - public void createTask (int AD_Task_ID, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), "AD_Task_ID", AD_Task_ID); - taskHandler.create(getCtx(), packOutDocument); - getCtx().remove("AD_Task_ID"); - } - - /** - * - * @param AD_Process_ID - * @param packOutDocument - * @throws SAXException - */ - public void createProcess (int AD_Process_ID, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), "AD_Process_ID", AD_Process_ID); - processHandler.create(getCtx(), packOutDocument); - getCtx().remove("AD_Process_ID"); - } - - /** - * - * @param AD_Window_ID - * @param packOutDocument - * @throws SAXException - */ - public void createWindow (int AD_Window_ID, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), "AD_Window_ID", AD_Window_ID); - windowHandler.create(getCtx(), packOutDocument); - getCtx().remove("AD_Window_ID"); - } - - /** - * - * @param table_id - * @param sql - * @param packOutDocument - * @throws SAXException - */ - public void createData (int table_id, String sql, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID, table_id); - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement, sql); - dataHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement); - } - - /** - * - * @param Reportview_id - * @param packOutDocument - * @throws SAXException - */ - public void createReportview (int Reportview_id, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_ReportView_ID, Reportview_id); - reportViewHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ReportView_ID); - } - - /** - * - * @param SQLStatement - * @param DBType - * @param packOutDocument - * @throws SAXException - */ - public void createSQL (String SQLStatement, String DBType, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement, SQLStatement); - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_DBType, DBType); - sqlHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_DBType); - } - - /** - * - * @param FileDir - * @param FileName - * @param OldCode - * @param NewCode - * @param ReleaseNo - * @param atts - * @param packOutDocument - * @throws SAXException - */ - public void createSnipit (String FileDir, String FileName, String OldCode, String NewCode, String ReleaseNo, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_File_Directory, FileDir); - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_FileName, FileName); - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_Old, OldCode); - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_New, NewCode); - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo, ReleaseNo); - codeHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_File_Directory); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_FileName); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_Old); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_New); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo); - } - - /** - * - * @param Role_id - * @param packOutDocument - * @throws SAXException - */ - public void createRoles (int Role_id, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Role_ID, Role_id); - roleHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Role_ID); - } - - /** - * - * @param Reference_id - * @param packOutDocument - * @throws SAXException - */ - public void createReference (int Reference_id, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Reference.COLUMNNAME_AD_Reference_ID, Reference_id); - referenceHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Reference.COLUMNNAME_AD_Reference_ID); - } - - /** - * - * @param import_id - * @param packOutDocument - * @throws SAXException - */ - public void createImpFormat (int import_id, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_ImpFormat_ID, import_id); - impFormtHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ImpFormat_ID); - - } - - /** - * - * @param table_id - * @param packOutDocument - * @throws SAXException - */ - public void createTable (int table_id, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID, table_id); - tableHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID); - } - - /** - * - * @param FieldGroup_id - * @param packOutDocument - * @throws SAXException - */ - public void createFieldGroupElement (int FieldGroup_id, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_FieldGroup.COLUMNNAME_AD_FieldGroup_ID, FieldGroup_id); - fieldGroupHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_FieldGroup.COLUMNNAME_AD_FieldGroup_ID); - } - - /** - * - * @param Reference_id - * @param packOutDocument - * @throws SAXException - */ - public void createAdElement (int Ad_Element_id, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Element.COLUMNNAME_AD_Element_ID, Ad_Element_id); - adElementHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Element.COLUMNNAME_AD_Element_ID); - } - - /** - * - * @param parentTableName - * @param parentID - * @param packOutDocument - * @throws SAXException - */ - public void createTranslations (String parentTableName, int parentID, TransformerHandler packOutDocument) throws SAXException - { - if (MSysConfig.getBooleanValue(MSysConfig.TWOPACK_HANDLE_TRANSLATIONS, false)) { - - Env.setContext(getCtx(), CommonTranslationHandler.CONTEXT_KEY__PARENT_TABLE, - parentTableName); - Env.setContext(getCtx(), CommonTranslationHandler.CONTEXT_KEY__PARENT_RECORD_ID, - parentID); - - translationHandler.create(getCtx(), packOutDocument); - - getCtx().remove(CommonTranslationHandler.CONTEXT_KEY__PARENT_TABLE); - getCtx().remove(CommonTranslationHandler.CONTEXT_KEY__PARENT_RECORD_ID); - } - } - - /** - * - * @param AD_ModelValidator_ID - * @param packOutDocument - * @throws Exception - */ - public void createModelValidator (int AD_ModelValidator_ID, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_ModelValidator_ID, AD_ModelValidator_ID); - modelValidatorHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ModelValidator_ID); - } - - /** - * - * @param AD_EntityType_ID - * @param packOutDocument - * @throws Exception - */ - public void createEntityType (int AD_EntityType_ID, TransformerHandler packOutDocument) throws Exception - { - //Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_EntityType_ID, AD_EntityType_ID); - entitytypeHandler.create(getCtx(), packOutDocument); - //getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_EntityType_ID); - } - - public void createPrintPaper (int AD_PrintPaper_ID, TransformerHandler packOutDocument) throws SAXException - { - Env.setContext(getCtx(), X_AD_PrintPaper.COLUMNNAME_AD_PrintPaper_ID, AD_PrintPaper_ID); - printPaperHandler.create(getCtx(), packOutDocument); - getCtx().remove(X_AD_PrintPaper.COLUMNNAME_AD_PrintPaper_ID); - } - - - - public void copyFile (String sourceName, String copyName ) { - InputStream source; // Stream for reading from the source file. - OutputStream copy; // Stream for writing the copy. - boolean force; // This is set to true if the "-f" option - // is specified on the command line. - int byteCount; // Number of bytes copied from the source file. - - force = true; - try { - source = new FileInputStream(sourceName); - } - catch (FileNotFoundException e) { - System.out.println("Can't find file \"" + sourceName + "\"."); - return; - } - File file = new File(copyName); - if (file.exists() && force == false) { - System.out.println( - "Output file exists. Use the -f option to replace it."); - return; - } - try { - copy = new FileOutputStream(copyName, false); - } - catch (IOException e) { - System.out.println("Can't open output file \"" - + copyName + "\"."); - return; - } - byteCount = 0; - try { - while (true) { - int data = source.read(); - if (data < 0) - break; - copy.write(data); - byteCount++; - } - source.close(); - copy.close(); - System.out.println("Successfully copied " + byteCount + " bytes."); - } - catch (Exception e) { - System.out.println("Error occurred while copying. "+ byteCount + " bytes copied."); - System.out.println(e.toString()); - } - } - - - @Override - public Properties getCtx() { - return localContext != null ? localContext : super.getCtx(); - } - -} // PackOut + protected void prepare() + { + p_PackOut_ID = getRecord_ID(); + ProcessInfoParameter[] para = getParameter(); + for (int i = 0; i < para.length; i++) + { + } + } // prepare + + + /** + * Start the transformation to XML + * @return info + * @throws Exception + */ + protected String doIt() throws java.lang.Exception + { + initContext(); + + OutputStream packageDocStream = null; + OutputStream packOutDocStream = null; + if (log.isLoggable(Level.INFO)) log.info("doIt - AD_PACKAGE_EXP_ID=" + p_PackOut_ID); + if (p_PackOut_ID == 0) + throw new IllegalArgumentException("No Record"); + String sql1 = "SELECT * FROM AD_Package_Exp WHERE AD_Package_Exp_ID = "+p_PackOut_ID; + PreparedStatement pstmt1 = null; + pstmt1 = DB.prepareStatement (sql1, get_TrxName()); + + try { + ResultSet rs1 = pstmt1.executeQuery(); + while (rs1.next()){ + //Create the package documentation + packagedir = rs1.getString(X_AD_Package_Exp.COLUMNNAME_File_Directory).trim(); + if (!packagedir.endsWith("/") && !packagedir.endsWith("\\")) + packagedir += File.separator; + packagename = packagedir + rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name); + includesdir = rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name) + File.separator +"**"; + @SuppressWarnings("unused") + boolean success = (new File(packagename+File.separator+"doc"+File.separator)).mkdirs(); + String file_document = packagename+File.separator+"doc"+File.separator+rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name)+"Doc.xml"; + packageDocStream = new FileOutputStream (file_document, false); + StreamResult streamResult_document = new StreamResult(new OutputStreamWriter(packageDocStream,"ISO-8859-1")); + SAXTransformerFactory tf_document = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); + tf_document.setAttribute("indent-number", new Integer(4)); + TransformerHandler packageDocument = tf_document.newTransformerHandler(); + Transformer serializer_document = packageDocument.getTransformer(); + serializer_document.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); + serializer_document.setOutputProperty(OutputKeys.INDENT,"yes"); + packageDocument.setResult(streamResult_document); + packageDocument.startDocument(); + AttributesImpl atts = new AttributesImpl(); + atts.clear(); + packageDocument.processingInstruction("xml-stylesheet","type=\"text/css\" href=\"adempiereDocument.css\""); + packageDocument.startElement("","","adempiereDocument",atts); + packageDocument.startElement("","","header",atts); + packageDocument.characters((rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name)+" Package Description").toCharArray(),0,(rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name)+" Package Description").length()); + packageDocument.endElement("","","header"); + packageDocument.startElement("","","H1",atts); + packageDocument.characters(("Package Name:" ).toCharArray(),0,("Package Name:" ).length()); + packageDocument.endElement("","","H1"); + packageDocument.startElement("","","packagename",atts); + packageDocument.characters(rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name).toCharArray(),0,rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name).length()); + packageDocument.endElement("","","packagename"); + packageDocument.startElement("","","H1",atts); + packageDocument.characters(("Creator:" ).toCharArray(),0,("Creator:").length()); + packageDocument.endElement("","","H1"); + packageDocument.startElement("","","creator",atts); + packageDocument.characters(rs1.getString(X_AD_Package_Exp.COLUMNNAME_UserName).toCharArray(),0,rs1.getString(X_AD_Package_Exp.COLUMNNAME_UserName).length()); + packageDocument.endElement("","","creator"); + packageDocument.startElement("","","H1",atts); + packageDocument.characters(("Email Address:" ).toCharArray(),0,("Email Address:" ).length()); + packageDocument.endElement("","","H1"); + packageDocument.startElement("","","creatorcontact",atts); + packageDocument.characters(rs1.getString(X_AD_Package_Exp.COLUMNNAME_EMail).toCharArray(),0,rs1.getString(X_AD_Package_Exp.COLUMNNAME_EMail).length()); + packageDocument.endElement("","","creatorcontact"); + packageDocument.startElement("","","H1",atts); + packageDocument.characters(("Created:" ).toCharArray(),0,("Created:" ).length()); + packageDocument.endElement("","","H1"); + packageDocument.startElement("","","createddate",atts); + packageDocument.characters(rs1.getString("Created").toString().toCharArray(),0,rs1.getString("Created").toString().length()); + packageDocument.endElement("","","createddate"); + packageDocument.startElement("","","H1",atts); + packageDocument.characters(("Updated:" ).toCharArray(),0,("Updated:" ).length()); + packageDocument.endElement("","","H1"); + packageDocument.startElement("","","updateddate",atts); + packageDocument.characters(rs1.getString("Updated").toString().toCharArray(),0,rs1.getString("Updated".toString()).length()); + packageDocument.endElement("","","updateddate"); + packageDocument.startElement("","","H1",atts); + packageDocument.characters(("Description:" ).toCharArray(),0,("Description:" ).length()); + packageDocument.endElement("","","H1"); + packageDocument.startElement("","","description",atts); + packageDocument.characters(rs1.getString(X_AD_Package_Exp.COLUMNNAME_Description).toCharArray(),0,rs1.getString(X_AD_Package_Exp.COLUMNNAME_Description).length()); + packageDocument.endElement("","","description"); + packageDocument.startElement("","","H1",atts); + packageDocument.characters(("Instructions:" ).toCharArray(),0,("Instructions:" ).length()); + packageDocument.endElement("","","H1"); + packageDocument.startElement("","","instructions",atts); + packageDocument.characters(rs1.getString(X_AD_Package_Exp.COLUMNNAME_Instructions).toCharArray(),0,rs1.getString(X_AD_Package_Exp.COLUMNNAME_Instructions).length()); + packageDocument.endElement("","","instructions"); + packageDocument.startElement("","","H1",atts); + packageDocument.characters(("Files in Package:" ).toCharArray(),0,("Files in Package:" ).length()); + packageDocument.endElement("","","H1"); + packageDocument.startElement("","","file",atts); + packageDocument.characters(("File: PackOut.xml").toCharArray(),0,("File: PackOut.xml").length()); + packageDocument.endElement("","","file"); + packageDocument.startElement("","","filedirectory",atts); + packageDocument.characters("Directory: \\dict\\".toCharArray(),0,("Directory: \\dict\\").length()); + packageDocument.endElement("","","filedirectory"); + packageDocument.startElement("","","filenotes",atts); + packageDocument.characters("Notes: Contains all application/object settings for package".toCharArray(),0,"Notes: Contains all application/object settings for package".length()); + packageDocument.endElement("","","filenotes"); + success = (new File(packagename+File.separator+ "dict"+File.separator)).mkdirs(); + String file_menu = packagename+File.separator+ "dict"+File.separator+"PackOut.xml"; + packOutDocStream = new FileOutputStream (file_menu, false); + StreamResult streamResult_menu = new StreamResult(new OutputStreamWriter(packOutDocStream,"ISO-8859-1")); + SAXTransformerFactory tf_menu = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); + tf_menu.setAttribute("indent-number", new Integer(4)); + TransformerHandler packOutDocument = tf_menu.newTransformerHandler(); + Transformer serializer_menu = packOutDocument.getTransformer(); + serializer_menu.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); + serializer_menu.setOutputProperty(OutputKeys.INDENT,"yes"); + packOutDocument.setResult(streamResult_menu); + packOutDocument.startDocument(); + atts.clear(); + atts.addAttribute("","","Name","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name)); + atts.addAttribute("","","Version","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_PK_Version)); + atts.addAttribute("","","CompVer","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_ReleaseNo)); + atts.addAttribute("","","DataBase","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_Version)); + atts.addAttribute("","","Description","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_Description)); + atts.addAttribute("","","creator","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_UserName)); + atts.addAttribute("","","creatorcontact","CDATA",rs1.getString(X_AD_Package_Exp.COLUMNNAME_EMail)); + atts.addAttribute("","","createddate","CDATA",rs1.getString("Created")); + atts.addAttribute("","","updateddate","CDATA",rs1.getString("Updated")); + atts.addAttribute("","","PackOutVer","CDATA",PackOutVer); + + packOutDocument.startElement("","","adempiereAD",atts); + atts.clear(); + + final String sql = "SELECT * FROM AD_Package_Exp_Detail WHERE AD_Package_Exp_ID = "+p_PackOut_ID+" AND IsActive='Y' ORDER BY Line ASC"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement (sql, get_TrxName()); + rs = pstmt.executeQuery(); + while (rs.next()) + { + final String Type = rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Type); + final int AD_EntityType_ID = rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_EntityType_ID); + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_EntityType_ID, AD_EntityType_ID); + // + if (log.isLoggable(Level.INFO)) log.info(rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Line)); + if (Type.compareTo("M") == 0){ + createMenu(rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Menu_ID), packOutDocument ); + } + else if (Type.compareTo("P") == 0) + createProcess ( rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Process_ID), packOutDocument ); + else if (Type.compareTo("R") == 0) + createReportview ( rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ReportView_ID), packOutDocument ); + else if (Type.compareTo("D") == 0) + createData ( rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID), rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement), packOutDocument ); + else if (Type.compareTo("T") == 0) + createTable (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID), packOutDocument); + else if (Type.compareTo("X") == 0) + createForm (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Form_ID), packOutDocument); + else if (Type.compareTo("W") == 0) + createWindow (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Window_ID), packOutDocument); + else if (Type.compareTo("S") == 0) + createRoles (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Role_ID), packOutDocument); + else if (Type.compareTo("SQL") == 0) + createSQL (rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement), rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_DBType), packOutDocument); + else if (Type.compareTo("IMP") == 0) + createImpFormat (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ImpFormat_ID), packOutDocument); + else if (Type.compareTo("REF") == 0) + createReference (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Reference_ID), packOutDocument); + else if (Type.compareTo("SNI") == 0) + createSnipit( + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Destination_Directory), + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Destination_FileName), + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_Old), + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_New), + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo), + packOutDocument); + else if (Type.compareTo("F") == 0) + createWorkflow (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID), packOutDocument); + else if (Type.compareTo("V") == 0) + createDynamicRuleValidation(rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID), packOutDocument); + else if (Type.compareTo("MSG") == 0) + createMessage(rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Message_ID), packOutDocument); + else if (Type.compareTo("PFT") == 0) + createPrintFormat(rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_PrintFormat_ID), packOutDocument); + else if (Type.compareTo(X_AD_Package_Exp_Detail.TYPE_ModelValidator) == 0) + createModelValidator(rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ModelValidator_ID), packOutDocument); + else if (Type.compareTo(X_AD_Package_Exp_Detail.TYPE_EntityType) == 0) + createEntityType(AD_EntityType_ID, packOutDocument); + else if (Type.compareTo("C") == 0){ + log.log(Level.INFO,"In PackOut.java handling Code or Other 2pack module creation"); + + String fullDirectory = rs1.getString(X_AD_Package_Exp.COLUMNNAME_File_Directory) + rs1.getString(X_AD_Package_Exp.COLUMNNAME_Name)+rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory); + log.log(Level.INFO,"fullDirectory" + fullDirectory); + String targetDirectoryModified=null; + char fileseperator1 = '/'; + char fileseperator2 = '\\'; + //Correct package for proper file separator + if (File.separator.equals("/")){ + targetDirectoryModified = fullDirectory.replace(fileseperator2,fileseperator1); + } + else + targetDirectoryModified = fullDirectory.replace(fileseperator1,fileseperator2); + + String target_File = (targetDirectoryModified); + success = (new File(target_File).mkdirs()); + fullDirectory = rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_File_Directory); + targetDirectoryModified=null; + //Correct package for proper file separator + if (File.separator.equals("/")){ + targetDirectoryModified = fullDirectory.replace(fileseperator2,fileseperator1); + } + else + targetDirectoryModified = fullDirectory.replace(fileseperator2,fileseperator1); + + copyCode( + targetDirectoryModified + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName), + target_File + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName)); + + atts.clear(); + + if(rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Destination_Directory) != null){ + + fullDirectory = rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Destination_Directory); + String destinationDirectoryModified=null; + + //Correct package for proper file separator + if (File.separator.equals("/")){ + destinationDirectoryModified = fullDirectory.replace(fileseperator2,fileseperator1); + } + else + destinationDirectoryModified = fullDirectory.replace(fileseperator2,fileseperator1); + + createDistributeFile( + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName), + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory), + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo), + destinationDirectoryModified, + packOutDocument); + + } + + if(rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName) != null){ + packageDocument.startElement("","","file",atts); + packageDocument.characters(("File: "+rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName)).toCharArray(),0,("File: "+rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_FileName)).length()); + packageDocument.endElement("","","file"); + } + packageDocument.startElement("","","filedirectory",atts); + packageDocument.characters( + ("Directory: " + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory)).toCharArray(), + 0, + ("Directory: " + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory)).length()); + packageDocument.endElement("","","filedirectory"); + + packageDocument.startElement("","","filenotes",atts); + packageDocument.characters( + ("Notes: " + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Description)).toCharArray(), + 0, + (("Notes: " + rs.getString(X_AD_Package_Exp_Detail.COLUMNNAME_Description)).length())); + packageDocument.endElement("","","filenotes"); + } + } + // + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_EntityType_ID); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + atts.clear(); + //no longer use + //packOutDocument.startElement("","","menuset",atts); + //packOutDocument.endElement("","","menuset"); + packOutDocument.endElement("","","adempiereAD"); + packOutDocument.endDocument();packageDocument.endElement("","","adempiereDocument"); + packageDocument.endDocument(); + //m_Exp.setProcessed(true); + //m_Exp.saveEx(); + } + rs1.close(); + pstmt1.close(); + pstmt1 = null; + } + catch (Exception e) + { + log.log(Level.SEVERE,e.getLocalizedMessage(), e); + throw e; + } + finally + { + try + { + if (pstmt1 != null) + pstmt1.close (); + } + catch (Exception e) + {} + pstmt1 = null; + + // Close streams - teo_sarca [ 1704762 ] + if (packageDocStream != null) + try { + packageDocStream.close(); + } catch (Exception e) {} + if (packOutDocStream != null) + try { + packOutDocStream.close(); + } catch (Exception e) {} + } + + //create compressed packages + //set the files + File srcFolder = new File(packagedir); + File destZipFile = new File(packagename+".zip"); + File destTarFile = new File(packagename+".tar"); + File destGZipFile = new File(packagename+".tar.gz"); + + //delete the old packages if necessary + @SuppressWarnings("unused") + boolean success = destZipFile.delete(); + success = destTarFile.delete(); + success = destGZipFile.delete(); + + //create the compressed packages + CreateZipFile.zipFolder(srcFolder, destZipFile, includesdir); + CreateZipFile.tarFolder(srcFolder, destTarFile, includesdir); + CreateZipFile.gzipFile(destTarFile, destGZipFile); + + //Clean .tar file up + success = destTarFile.delete(); + + return "Finish Process"; + } // doIt + + private void initContext() { + Properties tmp = new Properties(); + if (getCtx() != null) + tmp.putAll(getCtx()); + tmp.put("TrxName", get_TrxName()); + tmp.put("PackOutProcess", this); + localContext = tmp; + } + + private void copyCode (String sourceName, String copyName) + { + copyFile (sourceName, copyName ); + } + + /** + * + * @param AD_Menu_ID + * @param packOutDocument + * @throws Exception + */ + public void createMenu(int AD_Menu_ID, TransformerHandler packOutDocument) throws SAXException { + Env.setContext(getCtx(), "AD_Menu_ID", AD_Menu_ID); + menuHandler.create(getCtx(), packOutDocument); + getCtx().remove("AD_Menu_ID"); + } + + /** + * + * @param AD_PrintFormat_ID + * @param packOutDocument + * @throws Exception + */ + public void createPrintFormat (int AD_PrintFormat_ID, TransformerHandler packOutDocument) throws Exception + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_PrintFormat_ID, AD_PrintFormat_ID); + printFormatHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_PrintFormat_ID); + } + + /** + * + * @param AD_Message_ID + * @param packOutDocument + * @throws Exception + */ + public void createMessage (int AD_Message_ID, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Message_ID, AD_Message_ID); + messageHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Message_ID); + } + + /** + * + * @param AD_Val_Rule_ID + * @param packOutDocument + * @throws Exception + */ + public void createDynamicRuleValidation (int AD_Val_Rule_ID, + TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID, AD_Val_Rule_ID); + dynValRuleHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID); + } + + /** + * + * @param AD_Workflow_ID + * @param packOutDocument + * @throws SAXException + */ + public void createWorkflow (int AD_Workflow_ID, TransformerHandler packOutDocument) + throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID, AD_Workflow_ID); + workflowHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID); + } + + /** + * + * @param FileName + * @param Source_Directory + * @param ReleaseNo + * @param Target_Directory + * @param atts + * @param packOutDocument + * @throws SAXException + */ + public void createDistributeFile (String FileName, String Source_Directory, String ReleaseNo,String Target_Directory, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_FileName, FileName); + Env.setContext(getCtx(), "Source_Directory", Source_Directory); + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo, ReleaseNo); + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory, Target_Directory); + distFileHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_FileName); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory); + getCtx().remove("Source_Directory"); + } + + /** + * + * @param AD_Form_ID + * @param packOutDocument + * @throws SAXException + */ + public void createForm (int AD_Form_ID, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), "AD_Form_ID", AD_Form_ID); + formHandler.create(getCtx(), packOutDocument); + getCtx().remove("AD_Form_ID"); + } + + /** + * + * @param AD_Task_ID + * @param packOutDocument + * @throws SAXException + */ + public void createTask (int AD_Task_ID, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), "AD_Task_ID", AD_Task_ID); + taskHandler.create(getCtx(), packOutDocument); + getCtx().remove("AD_Task_ID"); + } + + /** + * + * @param AD_Process_ID + * @param packOutDocument + * @throws SAXException + */ + public void createProcess (int AD_Process_ID, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), "AD_Process_ID", AD_Process_ID); + processHandler.create(getCtx(), packOutDocument); + getCtx().remove("AD_Process_ID"); + } + + /** + * + * @param AD_Window_ID + * @param packOutDocument + * @throws SAXException + */ + public void createWindow (int AD_Window_ID, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), "AD_Window_ID", AD_Window_ID); + windowHandler.create(getCtx(), packOutDocument); + getCtx().remove("AD_Window_ID"); + } + + /** + * + * @param table_id + * @param sql + * @param packOutDocument + * @throws SAXException + */ + public void createData (int table_id, String sql, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID, table_id); + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement, sql); + dataHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement); + } + + /** + * + * @param Reportview_id + * @param packOutDocument + * @throws SAXException + */ + public void createReportview (int Reportview_id, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_ReportView_ID, Reportview_id); + reportViewHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ReportView_ID); + } + + /** + * + * @param SQLStatement + * @param DBType + * @param packOutDocument + * @throws SAXException + */ + public void createSQL (String SQLStatement, String DBType, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement, SQLStatement); + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_DBType, DBType); + sqlHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_DBType); + } + + /** + * + * @param FileDir + * @param FileName + * @param OldCode + * @param NewCode + * @param ReleaseNo + * @param atts + * @param packOutDocument + * @throws SAXException + */ + public void createSnipit (String FileDir, String FileName, String OldCode, String NewCode, String ReleaseNo, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_File_Directory, FileDir); + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_FileName, FileName); + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_Old, OldCode); + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_New, NewCode); + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo, ReleaseNo); + codeHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_File_Directory); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_FileName); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_Old); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_New); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo); + } + + /** + * + * @param Role_id + * @param packOutDocument + * @throws SAXException + */ + public void createRoles (int Role_id, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Role_ID, Role_id); + roleHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Role_ID); + } + + /** + * + * @param Reference_id + * @param packOutDocument + * @throws SAXException + */ + public void createReference (int Reference_id, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Reference.COLUMNNAME_AD_Reference_ID, Reference_id); + referenceHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Reference.COLUMNNAME_AD_Reference_ID); + } + + /** + * + * @param import_id + * @param packOutDocument + * @throws SAXException + */ + public void createImpFormat (int import_id, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_ImpFormat_ID, import_id); + impFormtHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ImpFormat_ID); + + } + + /** + * + * @param table_id + * @param packOutDocument + * @throws SAXException + */ + public void createTable (int table_id, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID, table_id); + tableHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID); + } + + /** + * + * @param FieldGroup_id + * @param packOutDocument + * @throws SAXException + */ + public void createFieldGroupElement (int FieldGroup_id, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_FieldGroup.COLUMNNAME_AD_FieldGroup_ID, FieldGroup_id); + fieldGroupHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_FieldGroup.COLUMNNAME_AD_FieldGroup_ID); + } + + /** + * + * @param Reference_id + * @param packOutDocument + * @throws SAXException + */ + public void createAdElement (int Ad_Element_id, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Element.COLUMNNAME_AD_Element_ID, Ad_Element_id); + adElementHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Element.COLUMNNAME_AD_Element_ID); + } + + /** + * + * @param parentTableName + * @param parentID + * @param packOutDocument + * @throws SAXException + */ + public void createTranslations (String parentTableName, int parentID, TransformerHandler packOutDocument) throws SAXException + { + if (MSysConfig.getBooleanValue(MSysConfig.TWOPACK_HANDLE_TRANSLATIONS, false)) { + + Env.setContext(getCtx(), CommonTranslationHandler.CONTEXT_KEY__PARENT_TABLE, + parentTableName); + Env.setContext(getCtx(), CommonTranslationHandler.CONTEXT_KEY__PARENT_RECORD_ID, + parentID); + + translationHandler.create(getCtx(), packOutDocument); + + getCtx().remove(CommonTranslationHandler.CONTEXT_KEY__PARENT_TABLE); + getCtx().remove(CommonTranslationHandler.CONTEXT_KEY__PARENT_RECORD_ID); + } + } + + /** + * + * @param AD_ModelValidator_ID + * @param packOutDocument + * @throws Exception + */ + public void createModelValidator (int AD_ModelValidator_ID, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_ModelValidator_ID, AD_ModelValidator_ID); + modelValidatorHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ModelValidator_ID); + } + + /** + * + * @param AD_EntityType_ID + * @param packOutDocument + * @throws Exception + */ + public void createEntityType (int AD_EntityType_ID, TransformerHandler packOutDocument) throws Exception + { + //Env.setContext(getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_EntityType_ID, AD_EntityType_ID); + entitytypeHandler.create(getCtx(), packOutDocument); + //getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_EntityType_ID); + } + + public void createPrintPaper (int AD_PrintPaper_ID, TransformerHandler packOutDocument) throws SAXException + { + Env.setContext(getCtx(), X_AD_PrintPaper.COLUMNNAME_AD_PrintPaper_ID, AD_PrintPaper_ID); + printPaperHandler.create(getCtx(), packOutDocument); + getCtx().remove(X_AD_PrintPaper.COLUMNNAME_AD_PrintPaper_ID); + } + + + + public void copyFile (String sourceName, String copyName ) { + InputStream source; // Stream for reading from the source file. + OutputStream copy; // Stream for writing the copy. + boolean force; // This is set to true if the "-f" option + // is specified on the command line. + int byteCount; // Number of bytes copied from the source file. + + force = true; + try { + source = new FileInputStream(sourceName); + } + catch (FileNotFoundException e) { + System.out.println("Can't find file \"" + sourceName + "\"."); + return; + } + File file = new File(copyName); + if (file.exists() && force == false) { + System.out.println( + "Output file exists. Use the -f option to replace it."); + return; + } + try { + copy = new FileOutputStream(copyName, false); + } + catch (IOException e) { + System.out.println("Can't open output file \"" + + copyName + "\"."); + return; + } + byteCount = 0; + try { + while (true) { + int data = source.read(); + if (data < 0) + break; + copy.write(data); + byteCount++; + } + source.close(); + copy.close(); + System.out.println("Successfully copied " + byteCount + " bytes."); + } + catch (Exception e) { + System.out.println("Error occurred while copying. "+ byteCount + " bytes copied."); + System.out.println(e.toString()); + } + } + + + @Override + public Properties getCtx() { + return localContext != null ? localContext : super.getCtx(); + } + +} // PackOut diff --git a/org.adempiere.pipo.legacy/src/org/adempiere/pipo/handler/WorkflowElementHandler.java b/org.adempiere.pipo.legacy/src/org/adempiere/pipo/handler/WorkflowElementHandler.java index 0a7c069aae..6081bf582a 100644 --- a/org.adempiere.pipo.legacy/src/org/adempiere/pipo/handler/WorkflowElementHandler.java +++ b/org.adempiere.pipo.legacy/src/org/adempiere/pipo/handler/WorkflowElementHandler.java @@ -1,453 +1,453 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 Adempiere, 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. * - * - * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com - * Contributor(s): Low Heng Sin hengsin@avantz.com - * Teo Sarca, teo.sarca@gmail.com - *****************************************************************************/ -package org.adempiere.pipo.handler; - -import java.math.BigDecimal; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; - -import javax.xml.transform.sax.TransformerHandler; - -import org.adempiere.pipo.AbstractElementHandler; -import org.adempiere.pipo.Element; -import org.adempiere.pipo.PackOut; -import org.adempiere.pipo.exception.DatabaseAccessException; -import org.adempiere.pipo.exception.POSaveFailedException; -import org.compiere.model.X_AD_Package_Exp_Detail; -import org.compiere.model.X_AD_WF_NextCondition; -import org.compiere.model.X_AD_WF_Node; -import org.compiere.model.X_AD_WF_NodeNext; -import org.compiere.model.X_AD_Workflow; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.wf.MWorkflow; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.AttributesImpl; - -public class WorkflowElementHandler extends AbstractElementHandler { - - private WorkflowNodeElementHandler nodeHandler = new WorkflowNodeElementHandler(); - private WorkflowNodeNextElementHandler nodeNextHandler = new WorkflowNodeNextElementHandler(); - private WorkflowNodeNextConditionElementHandler nextConditionHandler = new WorkflowNodeNextConditionElementHandler(); - - private List workflows = new ArrayList(); - - public void startElement(Properties ctx, Element element) - throws SAXException { - Attributes atts = element.attributes; - String elementValue = element.getElementValue(); - if (log.isLoggable(Level.INFO)) log.info(elementValue + " " + atts.getValue("Name")); - String entitytype = atts.getValue("EntityType"); - if (log.isLoggable(Level.INFO)) log.info("entitytype " + atts.getValue("EntityType")); - - if (isProcessElement(ctx, entitytype)) { - - String workflowName = atts.getValue("Name"); - - int id = get_IDWithColumn(ctx, "AD_Workflow", "name", workflowName); - if (id > 0 && workflows.contains(id)) { - element.skip = true; - return; - } - - MWorkflow m_Workflow = new MWorkflow(ctx, id, getTrxName(ctx)); - int AD_Backup_ID = -1; - String Object_Status = null; - if (id <= 0 && atts.getValue("AD_Workflow_ID") != null && Integer.parseInt(atts.getValue("AD_Workflow_ID")) <= PackOut.MAX_OFFICIAL_ID) - m_Workflow.setAD_Workflow_ID(Integer.parseInt(atts.getValue("AD_Workflow_ID"))); - if (id > 0) { - AD_Backup_ID = copyRecord(ctx, "AD_Workflow", m_Workflow); - Object_Status = "Update"; - } else { - Object_Status = "New"; - AD_Backup_ID = 0; - } - - String name = atts.getValue("ADWorkflowResponsibleNameID"); - if (name != null && name.trim().length() > 0) { - id = get_IDWithColumn(ctx, "AD_WF_Responsible", "Name", name); - if (id <= 0) { - element.defer = true; - element.unresolved = "AD_WF_Responsible: " + name; - return; - } - m_Workflow.setAD_WF_Responsible_ID(id); - } - - name = atts.getValue("ADTableNameID"); - if (name != null && name.trim().length() > 0) { - id = get_IDWithColumn(ctx, "AD_Table", "TableName", name); - if (id <= 0) { - element.defer = true; - element.unresolved = "AD_Table: " + name; - return; - } - m_Workflow.setAD_Table_ID(id); - - } - - name = atts.getValue("ADWorkflowProcessorNameID"); - if (name != null && name.trim().length() > 0) { - id = get_IDWithColumn(ctx, "AD_WorkflowProcessor", "Name", name); - if (id <= 0) { - element.defer = true; - element.unresolved = "AD_WorkflowProcessor: " + name; - return; - } - m_Workflow.setAD_WorkflowProcessor_ID(id); - - } - +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, 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. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + * Teo Sarca, teo.sarca@gmail.com + *****************************************************************************/ +package org.adempiere.pipo.handler; + +import java.math.BigDecimal; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo.AbstractElementHandler; +import org.adempiere.pipo.Element; +import org.adempiere.pipo.PackOut; +import org.adempiere.pipo.exception.DatabaseAccessException; +import org.adempiere.pipo.exception.POSaveFailedException; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_WF_NextCondition; +import org.compiere.model.X_AD_WF_Node; +import org.compiere.model.X_AD_WF_NodeNext; +import org.compiere.model.X_AD_Workflow; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.wf.MWorkflow; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class WorkflowElementHandler extends AbstractElementHandler { + + private WorkflowNodeElementHandler nodeHandler = new WorkflowNodeElementHandler(); + private WorkflowNodeNextElementHandler nodeNextHandler = new WorkflowNodeNextElementHandler(); + private WorkflowNodeNextConditionElementHandler nextConditionHandler = new WorkflowNodeNextConditionElementHandler(); + + private List workflows = new ArrayList(); + + public void startElement(Properties ctx, Element element) + throws SAXException { + Attributes atts = element.attributes; + String elementValue = element.getElementValue(); + if (log.isLoggable(Level.INFO)) log.info(elementValue + " " + atts.getValue("Name")); + String entitytype = atts.getValue("EntityType"); + if (log.isLoggable(Level.INFO)) log.info("entitytype " + atts.getValue("EntityType")); + + if (isProcessElement(ctx, entitytype)) { + + String workflowName = atts.getValue("Name"); + + int id = get_IDWithColumn(ctx, "AD_Workflow", "name", workflowName); + if (id > 0 && workflows.contains(id)) { + element.skip = true; + return; + } + + MWorkflow m_Workflow = new MWorkflow(ctx, id, getTrxName(ctx)); + int AD_Backup_ID = -1; + String Object_Status = null; + if (id <= 0 && atts.getValue("AD_Workflow_ID") != null && Integer.parseInt(atts.getValue("AD_Workflow_ID")) <= PackOut.MAX_OFFICIAL_ID) + m_Workflow.setAD_Workflow_ID(Integer.parseInt(atts.getValue("AD_Workflow_ID"))); + if (id > 0) { + AD_Backup_ID = copyRecord(ctx, "AD_Workflow", m_Workflow); + Object_Status = "Update"; + } else { + Object_Status = "New"; + AD_Backup_ID = 0; + } + + String name = atts.getValue("ADWorkflowResponsibleNameID"); + if (name != null && name.trim().length() > 0) { + id = get_IDWithColumn(ctx, "AD_WF_Responsible", "Name", name); + if (id <= 0) { + element.defer = true; + element.unresolved = "AD_WF_Responsible: " + name; + return; + } + m_Workflow.setAD_WF_Responsible_ID(id); + } + + name = atts.getValue("ADTableNameID"); + if (name != null && name.trim().length() > 0) { + id = get_IDWithColumn(ctx, "AD_Table", "TableName", name); + if (id <= 0) { + element.defer = true; + element.unresolved = "AD_Table: " + name; + return; + } + m_Workflow.setAD_Table_ID(id); + + } + + name = atts.getValue("ADWorkflowProcessorNameID"); + if (name != null && name.trim().length() > 0) { + id = get_IDWithColumn(ctx, "AD_WorkflowProcessor", "Name", name); + if (id <= 0) { + element.defer = true; + element.unresolved = "AD_WorkflowProcessor: " + name; + return; + } + m_Workflow.setAD_WorkflowProcessor_ID(id); + + } + m_Workflow.setValue(atts.getValue("Value")); - m_Workflow.setName(workflowName); - m_Workflow.setIsBetaFunctionality (Boolean.valueOf(atts.getValue("isBetaFunctionality")).booleanValue()); - m_Workflow.setAccessLevel(atts.getValue("AccessLevel")); - m_Workflow.setDescription(getStringValue(atts,"Description")); - m_Workflow.setHelp(getStringValue(atts,"Help")); - m_Workflow.setDurationUnit(getStringValue(atts,"DurationUnit")); - m_Workflow.setAuthor(getStringValue(atts,"Author")); - if(getStringValue(atts, "Version") != null) - m_Workflow.setVersion(Integer.valueOf(atts.getValue("Version"))); - if(getStringValue(atts, "Priority") != null) - m_Workflow.setPriority(Integer.valueOf(atts.getValue("Priority"))); - if(getStringValue(atts, "Limit") != null) - m_Workflow.setLimit(Integer.valueOf(atts.getValue("Limit"))); - if(getStringValue(atts, "Duration") != null) - m_Workflow.setDuration(Integer.valueOf(atts.getValue("Duration"))); - if(getStringValue(atts, "Cost") != null) - m_Workflow.setCost(new BigDecimal(atts.getValue("Cost"))); - - m_Workflow.setWorkingTime(Integer.valueOf(atts - .getValue("WorkingTime"))); - m_Workflow.setWaitingTime(Integer.valueOf(atts - .getValue("WaitingTime"))); - m_Workflow.setPublishStatus(atts.getValue("PublishStatus")); - m_Workflow.setWorkflowType(atts.getValue("WorkflowType")); - m_Workflow.setDocValueLogic(getStringValue(atts,"DocValueLogic")); - m_Workflow.setIsValid(atts.getValue("isValid") != null ? Boolean - .valueOf(atts.getValue("isValid")).booleanValue() : true); - m_Workflow.setEntityType(atts.getValue("EntityType")); - m_Workflow.setAD_WF_Node_ID(-1); - log.info("about to execute m_Workflow.save"); - if (m_Workflow.save(getTrxName(ctx)) == true) { - log.info("m_Workflow save success"); - record_log(ctx, 1, m_Workflow.getName(), "Workflow", m_Workflow - .get_ID(), AD_Backup_ID, Object_Status, "AD_Workflow", - get_IDWithColumn(ctx, "AD_Table", "TableName", - "AD_Workflow")); - workflows.add(m_Workflow.getAD_Workflow_ID()); - element.recordId = m_Workflow.getAD_Workflow_ID(); - } else { - log.info("m_Workflow save failure"); - record_log(ctx, 0, m_Workflow.getName(), "Workflow", m_Workflow - .get_ID(), AD_Backup_ID, Object_Status, "AD_Workflow", - get_IDWithColumn(ctx, "AD_Table", "TableName", - "AD_Workflow")); - throw new POSaveFailedException("MWorkflow"); - } - } else { - element.skip = true; - } - } - - /** - * @param ctx - * @param element - */ - public void endElement(Properties ctx, Element element) throws SAXException { - if (!element.defer && !element.skip && element.recordId > 0) { - Attributes atts = element.attributes; - //set start node - String name = atts.getValue("ADWorkflowNodeNameID"); - if (name != null && name.trim().length() > 0) { - MWorkflow m_Workflow = new MWorkflow(ctx, element.recordId, getTrxName(ctx)); - int id = get_IDWithMasterAndColumn(ctx, "AD_WF_Node", "Name", name, "AD_Workflow", m_Workflow.getAD_Workflow_ID()); - if (id <= 0) { - log.warning("Failed to resolve start node reference for workflow element. Workflow=" - + m_Workflow.getName() + " StartNode=" + name); - return; - } - m_Workflow.setAD_WF_Node_ID(id); - if (m_Workflow.save(getTrxName(ctx)) == true) { - log.info("m_Workflow update success"); - record_log(ctx, 1, m_Workflow.getName(), "Workflow", m_Workflow - .get_ID(), 0, "Update", "AD_Workflow", - get_IDWithColumn(ctx, "AD_Table", "TableName", - "AD_Workflow")); - workflows.add(m_Workflow.getAD_Workflow_ID()); - element.recordId = m_Workflow.getAD_Workflow_ID(); - } else { - log.info("m_Workflow update fail"); - record_log(ctx, 0, m_Workflow.getName(), "Workflow", m_Workflow - .get_ID(), 0, "Update", "AD_Workflow", - get_IDWithColumn(ctx, "AD_Table", "TableName", - "AD_Workflow")); - throw new POSaveFailedException("MWorkflow"); - } - } - } - } - - public void create(Properties ctx, TransformerHandler document) - throws SAXException { - int AD_Workflow_ID = Env.getContextAsInt(ctx, - X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID); - if (workflows.contains(AD_Workflow_ID)) - return; - - workflows.add(AD_Workflow_ID); - String sql = "SELECT Name FROM AD_Workflow WHERE AD_Workflow_ID= " - + AD_Workflow_ID; - int ad_wf_nodenext_id = 0; - int ad_wf_nodenextcondition_id = 0; - AttributesImpl atts = new AttributesImpl(); - - PreparedStatement pstmt = null; - ResultSet rs = null; - pstmt = DB.prepareStatement(sql, getTrxName(ctx)); - - try { - - rs = pstmt.executeQuery(); - - while (rs.next()) { - X_AD_Workflow m_Workflow = new X_AD_Workflow(ctx, - AD_Workflow_ID, null); - - createWorkflowBinding(atts, m_Workflow); - document.startElement("", "", "workflow", atts); - String sql1 = "SELECT AD_WF_Node_ID FROM AD_WF_Node WHERE AD_Workflow_ID = " - + AD_Workflow_ID - + " ORDER BY "+X_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID - ; - - PreparedStatement pstmt1 = null; - ResultSet rs1 = null; - try { - pstmt1 = DB.prepareStatement(sql1, getTrxName(ctx)); - // Generated workflowNodeNext(s) and - // workflowNodeNextCondition(s) - rs1 = pstmt1.executeQuery(); - while (rs1.next()) { - - int nodeId = rs1.getInt("AD_WF_Node_ID"); - createNode(ctx, document, nodeId); - - ad_wf_nodenext_id = 0; - - String sqlnn = "SELECT AD_WF_NodeNext_ID FROM AD_WF_NodeNext WHERE AD_WF_Node_ID = ?" - + " ORDER BY "+X_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID; - PreparedStatement pstmtnn = null; - ResultSet rsnn = null; - try { - pstmtnn = DB.prepareStatement(sqlnn, getTrxName(ctx)); - pstmtnn.setInt(1, nodeId); - rsnn = pstmtnn.executeQuery(); - while (rsnn.next()) { - ad_wf_nodenext_id = rsnn.getInt("AD_WF_NodeNext_ID"); - if (ad_wf_nodenext_id > 0) { - createNodeNext(ctx, document, ad_wf_nodenext_id); - - ad_wf_nodenextcondition_id = 0; - - String sqlnnc = "SELECT AD_WF_NextCondition_ID FROM AD_WF_NextCondition WHERE AD_WF_NodeNext_ID = ?" - + " ORDER BY "+X_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID; - PreparedStatement pstmtnnc = null; - ResultSet rsnnc = null; - try { - pstmtnnc = DB.prepareStatement(sqlnnc, getTrxName(ctx)); - pstmtnnc.setInt(1, ad_wf_nodenext_id); - rsnnc = pstmtnnc.executeQuery(); - while (rsnnc.next()) { - ad_wf_nodenextcondition_id = rsnnc.getInt("AD_WF_NextCondition_ID"); - if (log.isLoggable(Level.INFO)) log.info("ad_wf_nodenextcondition_id: " + String.valueOf(ad_wf_nodenextcondition_id)); - if (ad_wf_nodenextcondition_id > 0) { - createNodeNextCondition(ctx, document, ad_wf_nodenextcondition_id); - } - } - } finally { - DB.close(rsnnc, pstmtnnc); - rsnnc = null; - pstmtnnc = null; - } - } - } - - } finally { - DB.close(rsnn, pstmtnn); - rsnn = null; - pstmtnn = null; - } - - } - } finally { - DB.close(rs1, pstmt1); - rs1 = null; - pstmt1 = null; - - document.endElement("", "", "workflow"); - } - } - } catch (Exception e) { - log.log(Level.SEVERE, "Workflow", e); - if (e instanceof SAXException) - throw (SAXException) e; - else if (e instanceof SQLException) - throw new DatabaseAccessException("Failed to export workflow.", e); - else - throw new RuntimeException("Failed to export workflow.", e); - } finally { - DB.close(rs, pstmt); - rs = null; - pstmt = null; - } - } - - private void createNodeNextCondition(Properties ctx, - TransformerHandler document, int ad_wf_nodenextcondition_id) - throws SAXException { - Env.setContext(ctx, - X_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID, - ad_wf_nodenextcondition_id); - nextConditionHandler.create(ctx, document); - ctx.remove(X_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID); - } - - private void createNodeNext(Properties ctx, TransformerHandler document, - int ad_wf_nodenext_id) throws SAXException { - Env.setContext(ctx, X_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID, - ad_wf_nodenext_id); - nodeNextHandler.create(ctx, document); - ctx.remove(X_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID); - } - - private void createNode(Properties ctx, TransformerHandler document, - int AD_WF_Node_ID) throws SAXException { - Env.setContext(ctx, X_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID, - AD_WF_Node_ID); - nodeHandler.create(ctx, document); - ctx.remove(X_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID); - } - - private AttributesImpl createWorkflowBinding(AttributesImpl atts, - X_AD_Workflow m_Workflow) { - String sql = null; - String name = null; - atts.clear(); - if (m_Workflow.getAD_Workflow_ID() <= PackOut.MAX_OFFICIAL_ID) - atts.addAttribute("","","AD_Workflow_ID","CDATA",Integer.toString(m_Workflow.getAD_Workflow_ID())); - atts.addAttribute("", "", "Value", "CDATA", (m_Workflow.getValue() != null ? m_Workflow.getValue() : "")); - atts.addAttribute("", "", "Name", "CDATA", - (m_Workflow.getName() != null ? m_Workflow.getName() : "")); - if (m_Workflow.getAD_Table_ID() > 0) { - sql = "SELECT TableName FROM AD_Table WHERE AD_Table_ID=?"; - name = DB.getSQLValueString(null, sql, m_Workflow.getAD_Table_ID()); - atts.addAttribute("", "", "ADTableNameID", "CDATA", - (name != null ? name : "")); - } else - atts.addAttribute("", "", "ADTableNameID", "CDATA", ""); - - if (m_Workflow.getAD_WF_Node_ID() > 0) { - sql = "SELECT Name FROM AD_WF_Node WHERE AD_WF_Node_ID=?"; - name = DB.getSQLValueString(null, sql, m_Workflow - .getAD_WF_Node_ID()); - atts.addAttribute("", "", "ADWorkflowNodeNameID", "CDATA", - (name != null ? name : "")); - } else - atts.addAttribute("", "", "ADWorkflowNodeNameID", "CDATA", ""); - - if (m_Workflow.getAD_WF_Responsible_ID() > 0) { - sql = "SELECT Name FROM AD_WF_Responsible WHERE AD_WF_Responsible_ID=?"; - name = DB.getSQLValueString(null, sql, m_Workflow - .getAD_WF_Responsible_ID()); - atts.addAttribute("", "", "ADWorkflowResponsibleNameID", "CDATA", - (name != null ? name : "")); - } else - atts.addAttribute("", "", "ADWorkflowResponsibleNameID", "CDATA", - ""); - - if (m_Workflow.getAD_WorkflowProcessor_ID() > 0) { - sql = "SELECT Name FROM AD_WorkflowProcessor_ID WHERE AD_WorkflowProcessor_ID=?"; - name = DB.getSQLValueString(null, sql, m_Workflow - .getAD_WorkflowProcessor_ID()); - atts.addAttribute("", "", "ADWorkflowProcessorNameID", "CDATA", - (name != null ? name : "")); - } else - atts.addAttribute("", "", "ADWorkflowProcessorNameID", "CDATA", ""); - - atts.addAttribute("","","isBetaFunctionality","CDATA",(m_Workflow.isBetaFunctionality()== true ? "true":"false")); - - atts.addAttribute("", "", "AccessLevel", "CDATA", (m_Workflow - .getAccessLevel() != null ? m_Workflow.getAccessLevel() : "")); - atts - .addAttribute("", "", "DurationUnit", "CDATA", (m_Workflow - .getDurationUnit() != null ? m_Workflow - .getDurationUnit() : "")); - atts.addAttribute("", "", "Help", "CDATA", - (m_Workflow.getHelp() != null ? m_Workflow.getHelp() : "")); - atts.addAttribute("", "", "Description", "CDATA", (m_Workflow - .getDescription() != null ? m_Workflow.getDescription() : "")); - atts.addAttribute("", "", "EntityType", "CDATA", (m_Workflow - .getEntityType() != null ? m_Workflow.getEntityType() : "")); - atts.addAttribute("", "", "Author", "CDATA", - (m_Workflow.getAuthor() != null ? m_Workflow.getAuthor() : "")); - atts.addAttribute("", "", "Version", "CDATA", ("" - + m_Workflow.getVersion() != null ? "" - + m_Workflow.getVersion() : "")); - // FIXME: Handle dates - // atts.addAttribute("","","ValidFrom","CDATA",(m_Workflow.getValidFrom - // ().toGMTString() != null ? - // m_Workflow.getValidFrom().toGMTString():"")); - // atts.addAttribute("","","ValidTo","CDATA",(m_Workflow.getValidTo - // ().toGMTString() != null ? - // m_Workflow.getValidTo().toGMTString():"")); - atts.addAttribute("", "", "Priority", "CDATA", ("" + m_Workflow - .getPriority())); - atts.addAttribute("", "", "Limit", "CDATA", - ("" + m_Workflow.getLimit())); - atts.addAttribute("", "", "Duration", "CDATA", ("" + m_Workflow - .getDuration())); - atts.addAttribute("", "", "Cost", "CDATA", ("" + m_Workflow.getCost())); - atts.addAttribute("", "", "WorkingTime", "CDATA", ("" + m_Workflow - .getWorkingTime())); - atts.addAttribute("", "", "WaitingTime", "CDATA", ("" + m_Workflow - .getWaitingTime())); - atts.addAttribute("", "", "PublishStatus", "CDATA", (m_Workflow - .getPublishStatus() != null ? m_Workflow.getPublishStatus() - : "")); - atts - .addAttribute("", "", "WorkflowType", "CDATA", (m_Workflow - .getWorkflowType() != null ? m_Workflow - .getWorkflowType() : "")); - atts.addAttribute("", "", "DocValueLogic", "CDATA", (m_Workflow - .getDocValueLogic() != null ? m_Workflow.getDocValueLogic() - : "")); - atts.addAttribute("", "", "isValid", "CDATA", - (m_Workflow.isValid() == true ? "true" : "false")); - // Doesn't appear to be necessary - // atts.addAttribute("","","SetupTime","CDATA",(""+m_Workflow.getSetupTime() - // != null ? ""+m_Workflow.getSetupTime():"")); - return atts; - } -} + m_Workflow.setName(workflowName); + m_Workflow.setIsBetaFunctionality (Boolean.valueOf(atts.getValue("isBetaFunctionality")).booleanValue()); + m_Workflow.setAccessLevel(atts.getValue("AccessLevel")); + m_Workflow.setDescription(getStringValue(atts,"Description")); + m_Workflow.setHelp(getStringValue(atts,"Help")); + m_Workflow.setDurationUnit(getStringValue(atts,"DurationUnit")); + m_Workflow.setAuthor(getStringValue(atts,"Author")); + if(getStringValue(atts, "Version") != null) + m_Workflow.setVersion(Integer.valueOf(atts.getValue("Version"))); + if(getStringValue(atts, "Priority") != null) + m_Workflow.setPriority(Integer.valueOf(atts.getValue("Priority"))); + if(getStringValue(atts, "Limit") != null) + m_Workflow.setLimit(Integer.valueOf(atts.getValue("Limit"))); + if(getStringValue(atts, "Duration") != null) + m_Workflow.setDuration(Integer.valueOf(atts.getValue("Duration"))); + if(getStringValue(atts, "Cost") != null) + m_Workflow.setCost(new BigDecimal(atts.getValue("Cost"))); + + m_Workflow.setWorkingTime(Integer.valueOf(atts + .getValue("WorkingTime"))); + m_Workflow.setWaitingTime(Integer.valueOf(atts + .getValue("WaitingTime"))); + m_Workflow.setPublishStatus(atts.getValue("PublishStatus")); + m_Workflow.setWorkflowType(atts.getValue("WorkflowType")); + m_Workflow.setDocValueLogic(getStringValue(atts,"DocValueLogic")); + m_Workflow.setIsValid(atts.getValue("isValid") != null ? Boolean + .valueOf(atts.getValue("isValid")).booleanValue() : true); + m_Workflow.setEntityType(atts.getValue("EntityType")); + m_Workflow.setAD_WF_Node_ID(-1); + log.info("about to execute m_Workflow.save"); + if (m_Workflow.save(getTrxName(ctx)) == true) { + log.info("m_Workflow save success"); + record_log(ctx, 1, m_Workflow.getName(), "Workflow", m_Workflow + .get_ID(), AD_Backup_ID, Object_Status, "AD_Workflow", + get_IDWithColumn(ctx, "AD_Table", "TableName", + "AD_Workflow")); + workflows.add(m_Workflow.getAD_Workflow_ID()); + element.recordId = m_Workflow.getAD_Workflow_ID(); + } else { + log.info("m_Workflow save failure"); + record_log(ctx, 0, m_Workflow.getName(), "Workflow", m_Workflow + .get_ID(), AD_Backup_ID, Object_Status, "AD_Workflow", + get_IDWithColumn(ctx, "AD_Table", "TableName", + "AD_Workflow")); + throw new POSaveFailedException("MWorkflow"); + } + } else { + element.skip = true; + } + } + + /** + * @param ctx + * @param element + */ + public void endElement(Properties ctx, Element element) throws SAXException { + if (!element.defer && !element.skip && element.recordId > 0) { + Attributes atts = element.attributes; + //set start node + String name = atts.getValue("ADWorkflowNodeNameID"); + if (name != null && name.trim().length() > 0) { + MWorkflow m_Workflow = new MWorkflow(ctx, element.recordId, getTrxName(ctx)); + int id = get_IDWithMasterAndColumn(ctx, "AD_WF_Node", "Name", name, "AD_Workflow", m_Workflow.getAD_Workflow_ID()); + if (id <= 0) { + log.warning("Failed to resolve start node reference for workflow element. Workflow=" + + m_Workflow.getName() + " StartNode=" + name); + return; + } + m_Workflow.setAD_WF_Node_ID(id); + if (m_Workflow.save(getTrxName(ctx)) == true) { + log.info("m_Workflow update success"); + record_log(ctx, 1, m_Workflow.getName(), "Workflow", m_Workflow + .get_ID(), 0, "Update", "AD_Workflow", + get_IDWithColumn(ctx, "AD_Table", "TableName", + "AD_Workflow")); + workflows.add(m_Workflow.getAD_Workflow_ID()); + element.recordId = m_Workflow.getAD_Workflow_ID(); + } else { + log.info("m_Workflow update fail"); + record_log(ctx, 0, m_Workflow.getName(), "Workflow", m_Workflow + .get_ID(), 0, "Update", "AD_Workflow", + get_IDWithColumn(ctx, "AD_Table", "TableName", + "AD_Workflow")); + throw new POSaveFailedException("MWorkflow"); + } + } + } + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Workflow_ID = Env.getContextAsInt(ctx, + X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID); + if (workflows.contains(AD_Workflow_ID)) + return; + + workflows.add(AD_Workflow_ID); + String sql = "SELECT Name FROM AD_Workflow WHERE AD_Workflow_ID= " + + AD_Workflow_ID; + int ad_wf_nodenext_id = 0; + int ad_wf_nodenextcondition_id = 0; + AttributesImpl atts = new AttributesImpl(); + + PreparedStatement pstmt = null; + ResultSet rs = null; + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + + try { + + rs = pstmt.executeQuery(); + + while (rs.next()) { + X_AD_Workflow m_Workflow = new X_AD_Workflow(ctx, + AD_Workflow_ID, null); + + createWorkflowBinding(atts, m_Workflow); + document.startElement("", "", "workflow", atts); + String sql1 = "SELECT AD_WF_Node_ID FROM AD_WF_Node WHERE AD_Workflow_ID = " + + AD_Workflow_ID + + " ORDER BY "+X_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID + ; + + PreparedStatement pstmt1 = null; + ResultSet rs1 = null; + try { + pstmt1 = DB.prepareStatement(sql1, getTrxName(ctx)); + // Generated workflowNodeNext(s) and + // workflowNodeNextCondition(s) + rs1 = pstmt1.executeQuery(); + while (rs1.next()) { + + int nodeId = rs1.getInt("AD_WF_Node_ID"); + createNode(ctx, document, nodeId); + + ad_wf_nodenext_id = 0; + + String sqlnn = "SELECT AD_WF_NodeNext_ID FROM AD_WF_NodeNext WHERE AD_WF_Node_ID = ?" + + " ORDER BY "+X_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID; + PreparedStatement pstmtnn = null; + ResultSet rsnn = null; + try { + pstmtnn = DB.prepareStatement(sqlnn, getTrxName(ctx)); + pstmtnn.setInt(1, nodeId); + rsnn = pstmtnn.executeQuery(); + while (rsnn.next()) { + ad_wf_nodenext_id = rsnn.getInt("AD_WF_NodeNext_ID"); + if (ad_wf_nodenext_id > 0) { + createNodeNext(ctx, document, ad_wf_nodenext_id); + + ad_wf_nodenextcondition_id = 0; + + String sqlnnc = "SELECT AD_WF_NextCondition_ID FROM AD_WF_NextCondition WHERE AD_WF_NodeNext_ID = ?" + + " ORDER BY "+X_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID; + PreparedStatement pstmtnnc = null; + ResultSet rsnnc = null; + try { + pstmtnnc = DB.prepareStatement(sqlnnc, getTrxName(ctx)); + pstmtnnc.setInt(1, ad_wf_nodenext_id); + rsnnc = pstmtnnc.executeQuery(); + while (rsnnc.next()) { + ad_wf_nodenextcondition_id = rsnnc.getInt("AD_WF_NextCondition_ID"); + if (log.isLoggable(Level.INFO)) log.info("ad_wf_nodenextcondition_id: " + String.valueOf(ad_wf_nodenextcondition_id)); + if (ad_wf_nodenextcondition_id > 0) { + createNodeNextCondition(ctx, document, ad_wf_nodenextcondition_id); + } + } + } finally { + DB.close(rsnnc, pstmtnnc); + rsnnc = null; + pstmtnnc = null; + } + } + } + + } finally { + DB.close(rsnn, pstmtnn); + rsnn = null; + pstmtnn = null; + } + + } + } finally { + DB.close(rs1, pstmt1); + rs1 = null; + pstmt1 = null; + + document.endElement("", "", "workflow"); + } + } + } catch (Exception e) { + log.log(Level.SEVERE, "Workflow", e); + if (e instanceof SAXException) + throw (SAXException) e; + else if (e instanceof SQLException) + throw new DatabaseAccessException("Failed to export workflow.", e); + else + throw new RuntimeException("Failed to export workflow.", e); + } finally { + DB.close(rs, pstmt); + rs = null; + pstmt = null; + } + } + + private void createNodeNextCondition(Properties ctx, + TransformerHandler document, int ad_wf_nodenextcondition_id) + throws SAXException { + Env.setContext(ctx, + X_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID, + ad_wf_nodenextcondition_id); + nextConditionHandler.create(ctx, document); + ctx.remove(X_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID); + } + + private void createNodeNext(Properties ctx, TransformerHandler document, + int ad_wf_nodenext_id) throws SAXException { + Env.setContext(ctx, X_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID, + ad_wf_nodenext_id); + nodeNextHandler.create(ctx, document); + ctx.remove(X_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID); + } + + private void createNode(Properties ctx, TransformerHandler document, + int AD_WF_Node_ID) throws SAXException { + Env.setContext(ctx, X_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID, + AD_WF_Node_ID); + nodeHandler.create(ctx, document); + ctx.remove(X_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID); + } + + private AttributesImpl createWorkflowBinding(AttributesImpl atts, + X_AD_Workflow m_Workflow) { + String sql = null; + String name = null; + atts.clear(); + if (m_Workflow.getAD_Workflow_ID() <= PackOut.MAX_OFFICIAL_ID) + atts.addAttribute("","","AD_Workflow_ID","CDATA",Integer.toString(m_Workflow.getAD_Workflow_ID())); + atts.addAttribute("", "", "Value", "CDATA", (m_Workflow.getValue() != null ? m_Workflow.getValue() : "")); + atts.addAttribute("", "", "Name", "CDATA", + (m_Workflow.getName() != null ? m_Workflow.getName() : "")); + if (m_Workflow.getAD_Table_ID() > 0) { + sql = "SELECT TableName FROM AD_Table WHERE AD_Table_ID=?"; + name = DB.getSQLValueString(null, sql, m_Workflow.getAD_Table_ID()); + atts.addAttribute("", "", "ADTableNameID", "CDATA", + (name != null ? name : "")); + } else + atts.addAttribute("", "", "ADTableNameID", "CDATA", ""); + + if (m_Workflow.getAD_WF_Node_ID() > 0) { + sql = "SELECT Name FROM AD_WF_Node WHERE AD_WF_Node_ID=?"; + name = DB.getSQLValueString(null, sql, m_Workflow + .getAD_WF_Node_ID()); + atts.addAttribute("", "", "ADWorkflowNodeNameID", "CDATA", + (name != null ? name : "")); + } else + atts.addAttribute("", "", "ADWorkflowNodeNameID", "CDATA", ""); + + if (m_Workflow.getAD_WF_Responsible_ID() > 0) { + sql = "SELECT Name FROM AD_WF_Responsible WHERE AD_WF_Responsible_ID=?"; + name = DB.getSQLValueString(null, sql, m_Workflow + .getAD_WF_Responsible_ID()); + atts.addAttribute("", "", "ADWorkflowResponsibleNameID", "CDATA", + (name != null ? name : "")); + } else + atts.addAttribute("", "", "ADWorkflowResponsibleNameID", "CDATA", + ""); + + if (m_Workflow.getAD_WorkflowProcessor_ID() > 0) { + sql = "SELECT Name FROM AD_WorkflowProcessor_ID WHERE AD_WorkflowProcessor_ID=?"; + name = DB.getSQLValueString(null, sql, m_Workflow + .getAD_WorkflowProcessor_ID()); + atts.addAttribute("", "", "ADWorkflowProcessorNameID", "CDATA", + (name != null ? name : "")); + } else + atts.addAttribute("", "", "ADWorkflowProcessorNameID", "CDATA", ""); + + atts.addAttribute("","","isBetaFunctionality","CDATA",(m_Workflow.isBetaFunctionality()== true ? "true":"false")); + + atts.addAttribute("", "", "AccessLevel", "CDATA", (m_Workflow + .getAccessLevel() != null ? m_Workflow.getAccessLevel() : "")); + atts + .addAttribute("", "", "DurationUnit", "CDATA", (m_Workflow + .getDurationUnit() != null ? m_Workflow + .getDurationUnit() : "")); + atts.addAttribute("", "", "Help", "CDATA", + (m_Workflow.getHelp() != null ? m_Workflow.getHelp() : "")); + atts.addAttribute("", "", "Description", "CDATA", (m_Workflow + .getDescription() != null ? m_Workflow.getDescription() : "")); + atts.addAttribute("", "", "EntityType", "CDATA", (m_Workflow + .getEntityType() != null ? m_Workflow.getEntityType() : "")); + atts.addAttribute("", "", "Author", "CDATA", + (m_Workflow.getAuthor() != null ? m_Workflow.getAuthor() : "")); + atts.addAttribute("", "", "Version", "CDATA", ("" + + m_Workflow.getVersion() != null ? "" + + m_Workflow.getVersion() : "")); + // FIXME: Handle dates + // atts.addAttribute("","","ValidFrom","CDATA",(m_Workflow.getValidFrom + // ().toGMTString() != null ? + // m_Workflow.getValidFrom().toGMTString():"")); + // atts.addAttribute("","","ValidTo","CDATA",(m_Workflow.getValidTo + // ().toGMTString() != null ? + // m_Workflow.getValidTo().toGMTString():"")); + atts.addAttribute("", "", "Priority", "CDATA", ("" + m_Workflow + .getPriority())); + atts.addAttribute("", "", "Limit", "CDATA", + ("" + m_Workflow.getLimit())); + atts.addAttribute("", "", "Duration", "CDATA", ("" + m_Workflow + .getDuration())); + atts.addAttribute("", "", "Cost", "CDATA", ("" + m_Workflow.getCost())); + atts.addAttribute("", "", "WorkingTime", "CDATA", ("" + m_Workflow + .getWorkingTime())); + atts.addAttribute("", "", "WaitingTime", "CDATA", ("" + m_Workflow + .getWaitingTime())); + atts.addAttribute("", "", "PublishStatus", "CDATA", (m_Workflow + .getPublishStatus() != null ? m_Workflow.getPublishStatus() + : "")); + atts + .addAttribute("", "", "WorkflowType", "CDATA", (m_Workflow + .getWorkflowType() != null ? m_Workflow + .getWorkflowType() : "")); + atts.addAttribute("", "", "DocValueLogic", "CDATA", (m_Workflow + .getDocValueLogic() != null ? m_Workflow.getDocValueLogic() + : "")); + atts.addAttribute("", "", "isValid", "CDATA", + (m_Workflow.isValid() == true ? "true" : "false")); + // Doesn't appear to be necessary + // atts.addAttribute("","","SetupTime","CDATA",(""+m_Workflow.getSetupTime() + // != null ? ""+m_Workflow.getSetupTime():"")); + return atts; + } +} diff --git a/org.adempiere.pipo.legacy/src/test/functional/PackOutTest.java b/org.adempiere.pipo.legacy/src/test/functional/PackOutTest.java index b50cd6e29c..9b12e98120 100644 --- a/org.adempiere.pipo.legacy/src/test/functional/PackOutTest.java +++ b/org.adempiere.pipo.legacy/src/test/functional/PackOutTest.java @@ -1,27 +1,27 @@ -//PackOutTest.java -package test.functional; - -import org.adempiere.pipo.IDFinder; -import org.adempiere.pipo.PackInHandler; -import org.adempiere.pipo.PackOut; -import org.compiere.model.MLocation; -import org.compiere.model.MPackageExp; -import org.compiere.model.X_AD_Package_Exp_Detail; -import org.compiere.process.ProcessInfo; -import org.compiere.util.Trx; - -import test.AdempiereTestCase; - -public class PackOutTest extends AdempiereTestCase { - - // Test: Specific variables - @SuppressWarnings("unused") - private MLocation location = null; - - - public void testPackOut() { +//PackOutTest.java +package test.functional; + +import org.adempiere.pipo.IDFinder; +import org.adempiere.pipo.PackInHandler; +import org.adempiere.pipo.PackOut; +import org.compiere.model.MLocation; +import org.compiere.model.MPackageExp; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.process.ProcessInfo; +import org.compiere.util.Trx; + +import test.AdempiereTestCase; + +public class PackOutTest extends AdempiereTestCase { + + // Test: Specific variables + @SuppressWarnings("unused") + private MLocation location = null; + + + public void testPackOut() { PackOut m_PackOut = new PackOut(); - @SuppressWarnings("unused") + @SuppressWarnings("unused") PackInHandler m_PackInHandler = new PackInHandler(); Trx m_trx = Trx.get(getTrxName(), true); int m_ad_process_id = IDFinder.get_IDWithColumn("ad_process", "Name", "PackOut", getAD_Client_ID(), getTrxName()); @@ -40,7 +40,7 @@ public class PackOutTest extends AdempiereTestCase { m_MPackageExp.setVersion("1.0"); m_MPackageExp.setPK_Version("1.0"); - boolean saveResult = m_MPackageExp.save(); + boolean saveResult = m_MPackageExp.save(); assertTrue("MPackageExp.save()", saveResult); X_AD_Package_Exp_Detail m_PackDetail =new X_AD_Package_Exp_Detail(getCtx(), 0, getTrxName()); @@ -69,20 +69,20 @@ public class PackOutTest extends AdempiereTestCase { m_PackDetail.setAD_ReportView_ID(rs.getInt("AD_REPORTVIEW_ID")); */ m_PackDetail.setLine(10); - saveResult = m_PackDetail.save(); - assertTrue("X_AD_Package_Exp_Detail.save()", saveResult); + saveResult = m_PackDetail.save(); + assertTrue("X_AD_Package_Exp_Detail.save()", saveResult); - @SuppressWarnings("unused") + @SuppressWarnings("unused") int m_ad_record_id = IDFinder.get_IDWithColumn("ad_package_exp", "Name", "test2packJunit", getAD_Client_ID(), getTrxName()); ProcessInfo m_ProcessInfo = new ProcessInfo("PackOut", m_ad_process_id, m_ad_table_id, m_MPackageExp.get_ID()); m_PackOut.startProcess(getCtx(), m_ProcessInfo, m_trx); - assertFalse("PackOut", m_ProcessInfo.isError()); - - try { - commit(); - } catch (Exception e) { - fail(e.getLocalizedMessage()); - } - } -} + assertFalse("PackOut", m_ProcessInfo.isError()); + + try { + commit(); + } catch (Exception e) { + fail(e.getLocalizedMessage()); + } + } +} diff --git a/org.adempiere.pipo/src/org/adempiere/pipo2/AbstractElementHandler.java b/org.adempiere.pipo/src/org/adempiere/pipo2/AbstractElementHandler.java index 32b7089560..371656b091 100644 --- a/org.adempiere.pipo/src/org/adempiere/pipo2/AbstractElementHandler.java +++ b/org.adempiere.pipo/src/org/adempiere/pipo2/AbstractElementHandler.java @@ -35,7 +35,7 @@ import org.compiere.model.PO; import org.compiere.model.POInfo; import org.compiere.model.X_AD_EntityType; import org.compiere.model.X_AD_Package_Imp_Backup; -import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; import org.compiere.util.CLogger; import org.compiere.util.DB; import org.compiere.util.Env; diff --git a/org.adempiere.report.jasper/src/org/adempiere/report/jasper/ReportStarter.java b/org.adempiere.report.jasper/src/org/adempiere/report/jasper/ReportStarter.java index e047c160b4..b170cf149a 100644 --- a/org.adempiere.report.jasper/src/org/adempiere/report/jasper/ReportStarter.java +++ b/org.adempiere.report.jasper/src/org/adempiere/report/jasper/ReportStarter.java @@ -1,1493 +1,1493 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * 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 * - *****************************************************************************/ -package org.adempiere.report.jasper; - -import java.awt.print.PrinterJob; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.math.BigDecimal; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.PropertyResourceBundle; -import java.util.logging.Level; - -import javax.print.attribute.HashPrintRequestAttributeSet; -import javax.print.attribute.PrintRequestAttributeSet; -import javax.print.attribute.standard.Copies; -import javax.print.attribute.standard.JobName; - -import org.adempiere.base.Service; -import org.adempiere.exceptions.AdempiereException; -import org.adempiere.exceptions.DBException; -import org.adempiere.util.IProcessUI; -import org.compiere.model.MAttachment; -import org.compiere.model.MAttachmentEntry; -import org.compiere.model.MProcess; -import org.compiere.model.MQuery; -import org.compiere.model.MSysConfig; -import org.compiere.model.MTable; -import org.compiere.model.PrintInfo; -import org.compiere.model.X_AD_PInstance_Para; -import org.compiere.print.MPrintFormat; -import org.compiere.print.PrintUtil; -import org.compiere.print.ServerReportCtl; -import org.compiere.process.ClientProcess; -import org.compiere.process.ProcessCall; -import org.compiere.process.ProcessInfo; -import org.compiere.process.ProcessInfoParameter; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.Ini; -import org.compiere.util.Language; -import org.compiere.util.Trx; -import org.compiere.util.Util; -import org.compiere.utils.DigestOfFile; - -import net.sf.jasperreports.engine.DefaultJasperReportsContext; -import net.sf.jasperreports.engine.JRException; -import net.sf.jasperreports.engine.JRParameter; -import net.sf.jasperreports.engine.JRPropertiesUtil; -import net.sf.jasperreports.engine.JRQuery; -import net.sf.jasperreports.engine.JRVariable; -import net.sf.jasperreports.engine.JasperCompileManager; -import net.sf.jasperreports.engine.JasperPrint; -import net.sf.jasperreports.engine.JasperReport; -import net.sf.jasperreports.engine.JasperReportsContext; -import net.sf.jasperreports.engine.SimpleJasperReportsContext; -import net.sf.jasperreports.engine.design.JRDesignQuery; -import net.sf.jasperreports.engine.design.JasperDesign; -import net.sf.jasperreports.engine.export.HtmlExporter; -import net.sf.jasperreports.engine.export.JRCsvExporter; -import net.sf.jasperreports.engine.export.JRPdfExporter; -import net.sf.jasperreports.engine.export.JRPrintServiceExporter; -import net.sf.jasperreports.engine.export.JRTextExporter; -import net.sf.jasperreports.engine.export.JRXlsExporter; -import net.sf.jasperreports.engine.export.JRXmlExporter; -import net.sf.jasperreports.engine.fill.JRBaseFiller; -import net.sf.jasperreports.engine.fill.JRFiller; -import net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer; -import net.sf.jasperreports.engine.util.JRLoader; -import net.sf.jasperreports.engine.util.JRSwapFile; -import net.sf.jasperreports.engine.xml.JRXmlLoader; -import net.sf.jasperreports.engine.xml.JRXmlWriter; -import net.sf.jasperreports.export.Exporter; -import net.sf.jasperreports.export.ExporterInput; -import net.sf.jasperreports.export.ExporterOutput; -import net.sf.jasperreports.export.SimpleCsvExporterConfiguration; -import net.sf.jasperreports.export.SimpleExporterConfiguration; -import net.sf.jasperreports.export.SimpleExporterInput; -import net.sf.jasperreports.export.SimpleHtmlExporterConfiguration; -import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput; -import net.sf.jasperreports.export.SimplePdfExporterConfiguration; -import net.sf.jasperreports.export.SimplePrintServiceExporterConfiguration; -import net.sf.jasperreports.export.SimpleTextExporterConfiguration; -import net.sf.jasperreports.export.SimpleWriterExporterOutput; -import net.sf.jasperreports.export.SimpleXlsExporterConfiguration; -import net.sf.jasperreports.export.SimpleXmlExporterOutput; - -/** - * @author rlemeill - * Originally coming from an application note from compiere.co.uk - * --- - * Modifications: Allow Jasper Reports to be able to be run on VPN profile (i.e: no direct connection to DB). - * Implemented ClientProcess for it to run on client. - * @author Ashley Ramdass - * @author victor.perez@e-evolution.com - * @see FR 1906632 http://sourceforge.net/tracker/?func=detail&atid=879335&aid=1906632&group_id=176962 - * @author Teo Sarca, www.arhipac.ro - *
  • FR [ 2581145 ] Jasper: Provide parameters info - * @author Cristina Ghita, www.arhipac.ro - *
  • BF [ 2778472 ] Subreport bug - */ -public class ReportStarter implements ProcessCall, ClientProcess -{ - private static final int DEFAULT_SWAP_MAX_PAGES = 100; - /** Logger */ - private static CLogger log = CLogger.getCLogger(ReportStarter.class); - private static File REPORT_HOME = null; - public static final JasperReportsContext jasperReportStartContext; - - static { - String reportPath = System.getProperty("org.compiere.report.path"); - if (reportPath == null) { - REPORT_HOME = new File(Ini.getAdempiereHome() + File.separator + "reports"); - } else { - REPORT_HOME = new File(reportPath); - } - - // SimpleJasperReportsContext just same like DefaultJasperReportsContext, but DefaultJasperReportsContext is singleton, - // every thing setting for ReportStarter will effect to other "customize" jasper engine - jasperReportStartContext = new SimpleJasperReportsContext(); - - // http://jasperreports.sourceforge.net/sample.reference/groovy/index.html#javaCompilers - // http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/JasperCompileManager.html - // default is 1.8 but jasper will don't understand and break autobox feature - // other value (org.eclipse.jdt.core.compiler.compliance, org.eclipse.jdt.core.compiler.codegen.targetPlatform) still keep 1.8 - jasperReportStartContext.setProperty("org.eclipse.jdt.core.compiler.source", "1.5"); - } - - private ProcessInfo processInfo; - private MAttachment attachment; +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * 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 * + *****************************************************************************/ +package org.adempiere.report.jasper; + +import java.awt.print.PrinterJob; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Serializable; +import java.math.BigDecimal; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.PropertyResourceBundle; +import java.util.logging.Level; + +import javax.print.attribute.HashPrintRequestAttributeSet; +import javax.print.attribute.PrintRequestAttributeSet; +import javax.print.attribute.standard.Copies; +import javax.print.attribute.standard.JobName; + +import org.adempiere.base.Service; +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.exceptions.DBException; +import org.adempiere.util.IProcessUI; +import org.compiere.model.MAttachment; +import org.compiere.model.MAttachmentEntry; +import org.compiere.model.MProcess; +import org.compiere.model.MQuery; +import org.compiere.model.MSysConfig; +import org.compiere.model.MTable; +import org.compiere.model.PrintInfo; +import org.compiere.model.X_AD_PInstance_Para; +import org.compiere.print.MPrintFormat; +import org.compiere.print.PrintUtil; +import org.compiere.print.ServerReportCtl; +import org.compiere.process.ClientProcess; +import org.compiere.process.ProcessCall; +import org.compiere.process.ProcessInfo; +import org.compiere.process.ProcessInfoParameter; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Ini; +import org.compiere.util.Language; +import org.compiere.util.Trx; +import org.compiere.util.Util; +import org.compiere.utils.DigestOfFile; + +import net.sf.jasperreports.engine.DefaultJasperReportsContext; +import net.sf.jasperreports.engine.JRException; +import net.sf.jasperreports.engine.JRParameter; +import net.sf.jasperreports.engine.JRPropertiesUtil; +import net.sf.jasperreports.engine.JRQuery; +import net.sf.jasperreports.engine.JRVariable; +import net.sf.jasperreports.engine.JasperCompileManager; +import net.sf.jasperreports.engine.JasperPrint; +import net.sf.jasperreports.engine.JasperReport; +import net.sf.jasperreports.engine.JasperReportsContext; +import net.sf.jasperreports.engine.SimpleJasperReportsContext; +import net.sf.jasperreports.engine.design.JRDesignQuery; +import net.sf.jasperreports.engine.design.JasperDesign; +import net.sf.jasperreports.engine.export.HtmlExporter; +import net.sf.jasperreports.engine.export.JRCsvExporter; +import net.sf.jasperreports.engine.export.JRPdfExporter; +import net.sf.jasperreports.engine.export.JRPrintServiceExporter; +import net.sf.jasperreports.engine.export.JRTextExporter; +import net.sf.jasperreports.engine.export.JRXlsExporter; +import net.sf.jasperreports.engine.export.JRXmlExporter; +import net.sf.jasperreports.engine.fill.JRBaseFiller; +import net.sf.jasperreports.engine.fill.JRFiller; +import net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer; +import net.sf.jasperreports.engine.util.JRLoader; +import net.sf.jasperreports.engine.util.JRSwapFile; +import net.sf.jasperreports.engine.xml.JRXmlLoader; +import net.sf.jasperreports.engine.xml.JRXmlWriter; +import net.sf.jasperreports.export.Exporter; +import net.sf.jasperreports.export.ExporterInput; +import net.sf.jasperreports.export.ExporterOutput; +import net.sf.jasperreports.export.SimpleCsvExporterConfiguration; +import net.sf.jasperreports.export.SimpleExporterConfiguration; +import net.sf.jasperreports.export.SimpleExporterInput; +import net.sf.jasperreports.export.SimpleHtmlExporterConfiguration; +import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput; +import net.sf.jasperreports.export.SimplePdfExporterConfiguration; +import net.sf.jasperreports.export.SimplePrintServiceExporterConfiguration; +import net.sf.jasperreports.export.SimpleTextExporterConfiguration; +import net.sf.jasperreports.export.SimpleWriterExporterOutput; +import net.sf.jasperreports.export.SimpleXlsExporterConfiguration; +import net.sf.jasperreports.export.SimpleXmlExporterOutput; + +/** + * @author rlemeill + * Originally coming from an application note from compiere.co.uk + * --- + * Modifications: Allow Jasper Reports to be able to be run on VPN profile (i.e: no direct connection to DB). + * Implemented ClientProcess for it to run on client. + * @author Ashley Ramdass + * @author victor.perez@e-evolution.com + * @see FR 1906632 http://sourceforge.net/tracker/?func=detail&atid=879335&aid=1906632&group_id=176962 + * @author Teo Sarca, www.arhipac.ro + *
  • FR [ 2581145 ] Jasper: Provide parameters info + * @author Cristina Ghita, www.arhipac.ro + *
  • BF [ 2778472 ] Subreport bug + */ +public class ReportStarter implements ProcessCall, ClientProcess +{ + private static final int DEFAULT_SWAP_MAX_PAGES = 100; + /** Logger */ + private static CLogger log = CLogger.getCLogger(ReportStarter.class); + private static File REPORT_HOME = null; + public static final JasperReportsContext jasperReportStartContext; + + static { + String reportPath = System.getProperty("org.compiere.report.path"); + if (reportPath == null) { + REPORT_HOME = new File(Ini.getAdempiereHome() + File.separator + "reports"); + } else { + REPORT_HOME = new File(reportPath); + } + + // SimpleJasperReportsContext just same like DefaultJasperReportsContext, but DefaultJasperReportsContext is singleton, + // every thing setting for ReportStarter will effect to other "customize" jasper engine + jasperReportStartContext = new SimpleJasperReportsContext(); + + // http://jasperreports.sourceforge.net/sample.reference/groovy/index.html#javaCompilers + // http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/JasperCompileManager.html + // default is 1.8 but jasper will don't understand and break autobox feature + // other value (org.eclipse.jdt.core.compiler.compliance, org.eclipse.jdt.core.compiler.codegen.targetPlatform) still keep 1.8 + jasperReportStartContext.setProperty("org.eclipse.jdt.core.compiler.source", "1.5"); + } + + private ProcessInfo processInfo; + private MAttachment attachment; @SuppressWarnings("unused") private IProcessUI m_processUI; - - /** - * @author rlemeill - * @param reportLocation http://applicationserver/webApp/standalone.jrxml for example - * @param localPath Where to put the http downloaded file - * @return abstract File which represent the downloaded file - */ - private File getRemoteFile(String reportLocation, String localPath) - { - try{ - URL reportURL = new URL(reportLocation); - InputStream in = reportURL.openStream(); - - File downloadedFile = new File(localPath); - - if (downloadedFile.exists()) - { - downloadedFile.delete(); - } - - FileOutputStream fout = new FileOutputStream(downloadedFile); - - byte buf[] = new byte[1024]; - int s = 0; - while((s = in.read(buf, 0, 1024)) > 0) - fout.write(buf, 0, s); - - in.close(); - fout.flush(); - fout.close(); - return downloadedFile; - } catch (FileNotFoundException e) { - if(reportLocation.indexOf("Subreport") == -1 && !reportLocation.endsWith(".properties")) // Only show the warning if it is not a subreport or properties - log.warning("404 not found: Report cannot be found on server "+ e.getMessage()); - return null; - } catch (IOException e) { - throw new AdempiereException("I/O error when trying to download (sub)report from server "+ e.getLocalizedMessage()); - } - } - - /** - * Search for additional subreports deployed to a webcontext if - * the parent report is located there - * @author deathmeat - * @param reportName The original report name - * @param reportPath The full path to the parent report - * @param fileExtension The file extension of the parent report - * @return An Array of File objects referencing to the downloaded subreports - */ - private File[] getHttpSubreports(String reportName, String reportPath, String fileExtension) - { - ArrayList subreports = new ArrayList(); - String remoteDir = reportPath.substring(0, reportPath.lastIndexOf("/")); - - // Currently check hardcoded for max. 10 subreports - for(int i=1; i<10; i++) - { - // Check if subreport number i exists - File subreport = httpDownloadedReport(remoteDir + "/" + reportName + i + fileExtension); - if(subreport == null) // Subreport doesn't exist, abort further approaches - break; - - subreports.add(subreport); - } - - File[] subreportsTemp = new File[0]; - subreportsTemp = subreports.toArray(subreportsTemp); - return subreportsTemp; - } - - /** - * @author rlemeill - * @param reportLocation http string url ex: http://adempiereserver.domain.com/webApp/standalone.jrxml - * @return downloaded File (or already existing one) - */ - private File httpDownloadedReport(String reportLocation) - { - File reportFile = null; - File downloadedFile = null; - if (log.isLoggable(Level.INFO)) log.info(" report deployed to " + reportLocation); - try { - - - String[] tmps = reportLocation.split("/"); - String cleanFile = tmps[tmps.length-1]; - String localFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + cleanFile; - String downloadedLocalFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator")+"TMP" + cleanFile; - - reportFile = new File(localFile); - - - if (reportFile.exists()) - { - String localMD5hash = DigestOfFile.GetLocalMD5Hash(reportFile); - String remoteMD5Hash = getRemoteMD5(reportLocation); - if (log.isLoggable(Level.INFO)) log.info("MD5 for local file is "+localMD5hash ); - if ( remoteMD5Hash != null) - { - if (localMD5hash.equals(remoteMD5Hash)) - { - if (log.isLoggable(Level.INFO)) log.info(" no need to download: local report is up-to-date"); - } - else - { - if (log.isLoggable(Level.INFO)) log.info(" report on server is different that local one, download and replace"); - downloadedFile = getRemoteFile(reportLocation, downloadedLocalFile); - reportFile.delete(); - downloadedFile.renameTo(reportFile); - } - } - else - { - log.warning("Remote hashing is not available did you deployed webApp.ear?"); - downloadedFile = getRemoteFile(reportLocation, downloadedLocalFile); - // compare hash of existing and downloaded - if ( DigestOfFile.md5localHashCompare(reportFile,downloadedFile) ) - { - //nothing file are identical - if (log.isLoggable(Level.INFO)) log.info(" no need to replace your existing report"); - } - else - { - if (log.isLoggable(Level.INFO)) log.info(" report on server is different that local one, replacing"); - reportFile.delete(); - downloadedFile.renameTo(reportFile); - } - } - } - else - { - reportFile = getRemoteFile(reportLocation,localFile); - } - - } - catch (Exception e) { - throw new AdempiereException("Unknown exception: "+ e.getLocalizedMessage()); - } - return reportFile; - } - - private String getRemoteMD5(String reportLocation) { - try{ - String md5url = reportLocation; - if (md5url.indexOf("?") > 0) - md5url = md5url + "&md5=true"; - else - md5url = md5url + "?md5=true"; - URL reportURL = new URL(md5url); - InputStream in = reportURL.openStream(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte buf[] = new byte[1024]; - int s = 0; - while((s = in.read(buf, 0, 1024)) > 0) - baos.write(buf, 0, s); - - in.close(); - String hash = new String(baos.toByteArray()); - return hash; - } catch (IOException e) { - throw new AdempiereException("I/O error when trying to download (sub)report from server "+ e.getLocalizedMessage()); - } - } - - /** - * Returns the Server Connection if direct connection is not available - * (VPN, WAN, Terminal) and thus query has to be run on server only else return - * a direct connection to DB. - * - * Notes: Need to refactor and integrate in DB if confirmed to be working as - * expected. - * - * @author Ashley Ramdass - * @return Connection DB Connection - */ - protected Connection getConnection() - { - return DB.getConnectionRW(); - } - - /** - * Start the process. - * Called then pressing the Process button in R_Request. - * It should only return false, if the function could not be performed - * as this causes the process to abort. - * @author rlemeill - * @param ctx context - * @param pi standard process info - * @param trx - * @return true if success - */ - public boolean startProcess(Properties ctx, ProcessInfo pi, Trx trx) - { - ClassLoader cl1 = Thread.currentThread().getContextClassLoader(); - ClassLoader cl2 = JasperReport.class.getClassLoader(); - try { - if (!cl1.equals(cl2)) { - Thread.currentThread().setContextClassLoader(cl2); - } - return startProcess0(ctx, pi, trx); - } finally { - if (!cl1.equals(Thread.currentThread().getContextClassLoader())) { - Thread.currentThread().setContextClassLoader(cl1); - } - } - } - - private boolean startProcess0(Properties ctx, ProcessInfo pi, Trx trx) - { - processInfo = pi; - int nrows = 0; - Object onrows = null; - String Name=pi.getTitle(); - int AD_PInstance_ID=pi.getAD_PInstance_ID(); - int Record_ID=pi.getRecord_ID(); - - if (log.isLoggable(Level.INFO)) log.info( "Name="+Name+" AD_PInstance_ID="+AD_PInstance_ID+" Record_ID="+Record_ID); - String trxName = null; - if (trx != null) { - trxName = trx.getTrxName(); - } - ReportData reportData = getReportData(pi, trxName); - if (reportData == null) { - reportResult(AD_PInstance_ID, "Can not find report data", trxName); - return false; - } - - List jasperPrintList = new ArrayList(); - String reportFilePath = reportData.getReportFilePath(); - String[] reportPathList = reportFilePath.split(";"); - for (int idx = 0; idx < reportPathList.length; idx++) { - - String reportPath = reportPathList[idx]; - if (Util.isEmpty(reportPath, true)) - { - reportResult(AD_PInstance_ID, "Can not find report", trxName); - return false; - } - if (reportPath.startsWith("@#LocalHttpAddr@")) { - String localaddr = Env.getContext(Env.getCtx(), "#LocalHttpAddr"); - if (!Util.isEmpty(localaddr)) { - reportPath = reportPath.replace("@#LocalHttpAddr@", localaddr); - } - } - - JasperData data = null; - File reportFile = null; - String fileExtension = ""; - HashMap params = new HashMap(); - - addProcessParameters(AD_PInstance_ID, params, trxName); - addProcessInfoParameters(params, pi.getParameter()); - - reportFile = getReportFile(reportPath, (String)params.get("ReportType")); - if (reportFile == null || reportFile.exists() == false) - { - log.severe("No report file found for given type, falling back to " + reportPath); - reportFile = getReportFile(reportPath); - } - - if (reportFile == null || reportFile.exists() == false) - { - String tmp = "Can not find report file at path - " + reportPath; - log.severe(tmp); - reportResult(AD_PInstance_ID, tmp, trxName); - } - - if (reportFile != null) - { - data = processReport(reportFile); - fileExtension = reportFile.getName().substring(reportFile.getName().lastIndexOf("."), - reportFile.getName().length()); - } - else - { - return false; - } - - JasperReport jasperReport = data.getJasperReport(); - String jasperName = data.getJasperName(); - String name = jasperReport.getName(); - File reportDir = data.getReportDir(); - - String resourcePath = reportDir.getAbsolutePath(); - if (!resourcePath.endsWith("/") && !resourcePath.endsWith("\\")); - { - resourcePath = resourcePath + File.separator; - } - params.put("SUBREPORT_DIR", resourcePath); - if (reportPath.startsWith("http://") || reportPath.startsWith("https://")) { - int i = reportPath.lastIndexOf("/"); - String httpPath = reportPath.substring(0, i+1); - params.put("RESOURCE_DIR", httpPath); - } else { - params.put("RESOURCE_DIR", resourcePath); - } - - if (jasperReport != null && pi.getTable_ID() > 0 && Record_ID <= 0 && pi.getRecord_IDs() != null && pi.getRecord_IDs().length > 0) - { - try - { - JRQuery originalQuery = jasperReport.getQuery(); - if (originalQuery != null) - { - String originalQueryText = originalQuery.getText(); - if (originalQueryText != null) - { - MTable table = new MTable(ctx, pi.getTable_ID(), trxName); - String tableName = table.getTableName(); - String originalQueryTemp = originalQueryText.toUpperCase(); - int index1 = originalQueryTemp.indexOf(" " + tableName.toUpperCase()); - if (index1 != -1) - { - int index2 = originalQueryTemp.substring(index1).indexOf(","); - if (index2 != -1) - { - String tableVariable = originalQueryTemp.substring(index1 + tableName.length() + 1, index1 + index2); - tableVariable = tableVariable.trim(); - - if (tableVariable.length() == 0) - tableVariable = tableName; - - MQuery query = new MQuery(tableName); - for (int recordId : pi.getRecord_IDs()) - query.addRestriction(tableVariable + "." + query.getTableName() + "_ID" + MQuery.EQUAL + recordId, false, 0); - - String newQueryText = null; - int index3 = originalQueryTemp.indexOf("WHERE"); - if (index3 != -1) - newQueryText = originalQueryText + " AND " + query.toString(); - else - newQueryText = originalQueryText + " WHERE " + query.toString(); - - File jrxmlFile = File.createTempFile(makePrefix(jasperReport.getName()), ".jrxml"); - JRXmlWriter.writeReport(jasperReport, new FileOutputStream(jrxmlFile), "UTF-8"); - - JasperDesign jasperDesign = JRXmlLoader.load(jrxmlFile); - - JRDesignQuery newQuery = new JRDesignQuery(); - newQuery.setText(newQueryText); - jasperDesign.setQuery(newQuery); - - JasperCompileManager manager = JasperCompileManager.getInstance(jasperReportStartContext); - JasperReport newJasperReport = manager.compile(jasperDesign); - if (newJasperReport != null) - { - data.jasperReport = newJasperReport; - jasperReport = newJasperReport; - } - } - } - } - } - } - catch(Exception e) - { - log.severe("Failed to modify the report query"); - } - } - - if (jasperReport != null) { - File[] subreports; - - // Subreports - if(reportPath.startsWith("http://") || reportPath.startsWith("https://")) - { - // Locate and download subreports from remote webcontext - subreports = getHttpSubreports(jasperName + "Subreport", reportPath, fileExtension); - } - else if (reportPath.startsWith("attachment:")) - { - subreports = getAttachmentSubreports(reportPath); - } - else if (reportPath.startsWith("resource:")) - { - String path = reportPath.substring(0, reportPath.length() +1 - (name+"."+fileExtension).length()); - subreports = getResourceSubreports(name+ "Subreport", path, fileExtension); - } - else - { - // Locate subreports from local/remote filesystem - subreports = reportDir.listFiles( new FileFilter( jasperName+"Subreport", reportDir, fileExtension)); - } - - for( int i=0; i 0) - params.put("RECORD_ID", Integer.valueOf( Record_ID)); - - // contribution from Ricardo (ralexsander) - // in iReports you can 'SELECT' AD_Client_ID, AD_Org_ID and AD_User_ID using only AD_PINSTANCE_ID - params.put("AD_PINSTANCE_ID", Integer.valueOf( AD_PInstance_ID)); - - // FR [3123850] - Add continuosly needed parameters to Jasper Starter - Carlos Ruiz - GlobalQSS - params.put("AD_CLIENT_ID", Integer.valueOf( Env.getAD_Client_ID(Env.getCtx()))); - params.put("AD_ROLE_ID", Integer.valueOf( Env.getAD_Role_ID(Env.getCtx()))); - params.put("AD_USER_ID", Integer.valueOf( Env.getAD_User_ID(Env.getCtx()))); - - params.put("AD_CLIENT_NAME", Env.getContext(Env.getCtx(), "#AD_Client_Name")); - params.put("AD_ROLE_NAME", Env.getContext(Env.getCtx(), "#AD_Role_Name")); - params.put("AD_USER_NAME", Env.getContext(Env.getCtx(), "#AD_User_Name")); - params.put("AD_ORG_NAME", Env.getContext(Env.getCtx(), "#AD_Org_Name")); - params.put("BASE_DIR", REPORT_HOME.getAbsolutePath()); - //params.put("HeaderLogo", reportPath); - //params.put("LoginLogo", reportPath); - - Language currLang = Env.getLanguage(Env.getCtx()); - String printerName = null; - MPrintFormat printFormat = null; - PrintInfo printInfo = null; - ProcessInfoParameter[] pip = pi.getParameter(); - // Get print format and print info parameters - if (pip!=null) { - for (int i=0; i exporter = null; - - //JRExporter exporter = null; - if (ext.equals("pdf")) { - JRPdfExporter export = new JRPdfExporter(jasperReportStartContext); - SimplePdfExporterConfiguration config = new SimplePdfExporterConfiguration(); - export.setConfiguration(config); - export.setExporterOutput(new SimpleOutputStreamExporterOutput(strm)); - exporter = export; - // give a chance for customize jasper report configuration per report - JREventManage.sentPdfExporterConfigurationEvent(export, config, pi); - } else if (ext.equals("ps")) { - JRPrintServiceExporter export = new JRPrintServiceExporter( - jasperContext); - SimplePrintServiceExporterConfiguration config = new SimplePrintServiceExporterConfiguration(); - export.setConfiguration(config); - export.setExporterOutput(new SimpleOutputStreamExporterOutput(strm)); - exporter = export; - } else if (ext.equals("xml")) { - JRXmlExporter export = new JRXmlExporter(jasperContext); - SimpleExporterConfiguration config = new SimpleExporterConfiguration(); - export.setConfiguration(config); - export.setExporterOutput(new SimpleXmlExporterOutput(strm)); - exporter = export; - } else if (ext.equals("csv") || ext.equals("ssv") ) { - JRCsvExporter export = new JRCsvExporter(jasperContext); - SimpleCsvExporterConfiguration config = new SimpleCsvExporterConfiguration(); - if(ext.equals("ssv")) - config.setFieldDelimiter(";"); - export.setConfiguration(config); - export.setExporterOutput(new SimpleWriterExporterOutput(strm)); - exporter = export; - } else if (ext.equals("txt")) { - JRTextExporter export = new JRTextExporter(jasperContext); - SimpleTextExporterConfiguration config = new SimpleTextExporterConfiguration(); - export.setConfiguration(config); - exporter = export; - } else if (ext.equals("html") || ext.equals("htm")) { - HtmlExporter export = new HtmlExporter(jasperContext); - SimpleHtmlExporterConfiguration config = new SimpleHtmlExporterConfiguration(); - export.setConfiguration(config); - exporter = export; - } else if (ext.equals("xls")) { - JRXlsExporter export = new JRXlsExporter(jasperContext); - SimpleXlsExporterConfiguration config = new SimpleXlsExporterConfiguration(); - export.setConfiguration(config); - exporter = export; - } else { - log.severe("FileInvalidExtension="+ext); - strm.close(); - } - - if (exporter == null) - exporter = new JRPdfExporter(jasperReportStartContext); - - exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); - - exporter.exportReport(); - processInfo.setExportFile(file); - } - catch (IOException e) - { - log.severe("ReportStarter.startProcess: Can not export PDF File - "+ e.getMessage()); - } - } - } catch (JRException e) { - throw new AdempiereException(e.getLocalizedMessage() + (e.getCause() != null ? " -> " + e.getCause().getLocalizedMessage() : "")); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException e) { - } - } - } - } - - } // for reportPathList - - if (onrows != null && onrows instanceof Integer) { - nrows = (Integer) onrows; - processInfo.setRowCount(nrows); - } - reportResult( AD_PInstance_ID, null, trxName); - return true; - } - - private String makePrefix(String name) { - StringBuilder prefix = new StringBuilder(); - char[] nameArray = name.toCharArray(); - for (char ch : nameArray) { - if (Character.isLetterOrDigit(ch)) { - prefix.append(ch); - } else { - prefix.append("_"); - } - } - return prefix.toString(); - } - - /** - * Get .property resource file from process attachment - * @param bundleName - * @param currLang - * @return File - */ - private File getAttachmentResourceFile(String bundleName, Language currLang) { - String resname = bundleName+"_"+currLang.getLocale().getLanguage()+"_"+currLang.getLocale().getCountry()+".properties"; - File resFile = getAttachmentEntryFile(resname); - if (resFile == null) { - resname = bundleName+"_"+currLang.getLocale().getLanguage()+".properties"; - resFile = getAttachmentEntryFile(resname); - if (resFile == null) { - resname = bundleName+".properties"; - resFile = getAttachmentEntryFile(resname); - } - } - return resFile; - } - - private File getAttachmentEntryFile(String resname) { - File fileattach = null; - MAttachmentEntry[] entries = attachment.getEntries(); - for( int i=0; i subreports = new ArrayList(); - MAttachmentEntry[] entries = attachment.getEntries(); - for(int i = 0; i < entries.length; i++) { - // @Trifon - if (!entries[i].getName().equals(name)) - { - File reportFile = getAttachmentEntryFile(entries[i]); - if (reportFile != null) { - if (entries[i].getName().toLowerCase().endsWith(".jrxml") - || entries[i].getName().toLowerCase().endsWith(".jasper")) { - subreports.add(reportFile); - } - } - } - } - File[] subreportsTemp = new File[0]; - subreportsTemp = subreports.toArray(subreportsTemp); - return subreportsTemp; - } - - /** - * Search for additional subreports deployed as resources - * @param reportName The original report name - * @param reportPath The full path to the parent report - * @param fileExtension The file extension of the parent report - * @return An Array of File objects referencing to the downloaded subreports - */ - private File[] getResourceSubreports(String reportName, String reportPath, String fileExtension) - { - ArrayList subreports = new ArrayList(); - // Currently check hardcoded for max. 10 subreports - for(int i=1; i<10; i++) - { - // Check if subreport number i exists - File subreport = null; - try { - subreport = getFileAsResource(reportPath + reportName + i + fileExtension); - } catch (Exception e) { - // just ignore it - } - if(subreport == null) // Subreport doesn't exist, abort further approaches - break; - - subreports.add(subreport); - } - - File[] subreportsTemp = new File[subreports.size()]; - subreportsTemp = subreports.toArray(subreportsTemp); - return subreportsTemp; - } - - /** - * @author alinv - * @param reportPath - * @param reportType - * @return the abstract file corresponding to typed report - */ - protected File getReportFile(String reportPath, String reportType) { - - if (reportType != null) - { - int cpos = reportPath.lastIndexOf('.'); - reportPath = reportPath.substring(0, cpos) + "_" + reportType + reportPath.substring(cpos, reportPath.length()); - } - - return getReportFile(reportPath); - } - - /** - * @author alinv - * @param reportPath - * @return the abstract file corresponding to report - */ - protected File getReportFile(String reportPath) - { - File reportFile = null; - - // Reports deployment on web server Thanks to Alin Vaida - if (reportPath.startsWith("http://") || reportPath.startsWith("https://")) { - reportFile = httpDownloadedReport(reportPath); - } else if (reportPath.startsWith("attachment:")) { - //report file from process attachment - reportFile = downloadAttachment(reportPath); - } else if (reportPath.startsWith("/")) { - reportFile = new File(reportPath); - } else if (reportPath.startsWith("file:/")) { - try { - reportFile = new File(new URI(reportPath)); - } catch (URISyntaxException e) { - log.warning(e.getLocalizedMessage()); - reportFile = null; - } - } else if (reportPath.startsWith("resource:")) { - try { - reportFile = getFileAsResource(reportPath); - } catch (Exception e) { - log.warning(e.getLocalizedMessage()); - reportFile = null; - } - } else { - reportFile = new File(REPORT_HOME, reportPath); - } - - return reportFile; - } - - /** - * @param reportPath - * @return - * @throws Exception - */ - private File getFileAsResource(String reportPath) throws Exception { - File reportFile; - String name = reportPath.substring("resource:".length()).trim(); - String localName = name.replace('/', '_'); - if (log.isLoggable(Level.INFO)) { - log.info("reportPath = " + reportPath); - log.info("getting resource from = " + getClass().getClassLoader().getResource(name)); - } - InputStream inputStream = getClass().getClassLoader().getResourceAsStream(name); - String localFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + localName; - if (log.isLoggable(Level.INFO)) log.info("localFile = " + localFile); - reportFile = new File(localFile); - - boolean empty = true; - OutputStream out = null; - try { - out = new FileOutputStream(reportFile); - if (out != null){ - byte buf[]=new byte[1024]; - int len; - while((len=inputStream.read(buf))>0) { - empty = false; - out.write(buf,0,len); - } - } - } catch (Exception e) { - throw e; - } finally { - if (out != null) - out.close(); - if (inputStream != null) - inputStream.close(); - } - - if (empty) - return null; - else - return reportFile; - } - - /** - * Download db attachment - * @param reportPath must of syntax attachment:filename - * @return File - */ - private File downloadAttachment(String reportPath) { - File reportFile = null; - String name = reportPath.substring("attachment:".length()).trim(); - MProcess process = new MProcess(Env.getCtx(), processInfo.getAD_Process_ID(), processInfo.getTransactionName()); - attachment = process.getAttachment(); - if (attachment != null) { - MAttachmentEntry[] entries = attachment.getEntries(); - MAttachmentEntry entry = null; - for (int i = 0; i < entries.length; i++) { - if (entries[i].getName().equals(name)) { - entry = entries[i]; - break; - } - } - if (entry != null) { - reportFile = getAttachmentEntryFile(entry); - } - } - return reportFile; - } - - /** - * Download db attachment to local file - * @param entry - * @return File - */ - private File getAttachmentEntryFile(MAttachmentEntry entry) { - String localFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + entry.getName(); - String downloadedLocalFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator")+"TMP" + entry.getName(); - File reportFile = new File(localFile); - if (reportFile.exists()) { - String localMD5hash = DigestOfFile.GetLocalMD5Hash(reportFile); - String entryMD5hash = DigestOfFile.getMD5Hash(entry.getData()); - if (localMD5hash.equals(entryMD5hash)) - { - log.info(" no need to download: local report is up-to-date"); - } - else - { - log.info(" report on server is different that local one, download and replace"); - File downloadedFile = new File(downloadedLocalFile); - entry.getFile(downloadedFile); - if (! reportFile.delete()) { - throw new AdempiereException("Cannot delete temporary file " + reportFile.toString()); - } - if (! downloadedFile.renameTo(reportFile)) { - throw new AdempiereException("Cannot rename temporary file " + downloadedFile.toString() + " to " + reportFile.toString()); - } - } - } else { - entry.getFile(reportFile); - } - return reportFile; - } - - /** - * Update AD_PInstance result and error message - * @author rlemeill - * @param AD_PInstance_ID - * @param errMsg error message or null if there is no error - */ - protected void reportResult(int AD_PInstance_ID, String errMsg, String trxName) - { - int result = (errMsg == null ? 1 : 0); - String sql = "UPDATE AD_PInstance SET Result=?, ErrorMsg=?" - +" WHERE AD_PInstance_ID="+AD_PInstance_ID; - DB.executeUpdateEx(sql, new Object[]{result, errMsg}, trxName); - } - - /** - * @author rlemeill - * @param reportFile - * @return - */ - protected JasperData processReport( File reportFile) { - if (log.isLoggable(Level.INFO)) log.info( "reportFile.getAbsolutePath() = "+reportFile.getAbsolutePath()); - JasperReport jasperReport = null; - - String jasperName = reportFile.getName(); - int pos = jasperName.indexOf('.'); - if (pos!=-1) jasperName = jasperName.substring(0, pos); - File reportDir = reportFile.getParentFile(); - - //test if the compiled report exists - File jasperFile = new File( reportDir.getAbsolutePath(), jasperName+".jasper"); - if (jasperFile.exists()) { // test time - if (reportFile.lastModified() == jasperFile.lastModified()) { - if (log.isLoggable(Level.INFO)) log.info(" no need to compile use "+jasperFile.getAbsolutePath()); - try { - jasperReport = (JasperReport)JRLoader.loadObjectFromFile(jasperFile.getAbsolutePath()); - } catch (JRException e) { - jasperReport = null; - log.severe("Can not load report - "+ e.getMessage()); - } - } else { - jasperReport = compileReport( reportFile, jasperFile); - } - } else { // create new jasper file - jasperReport = compileReport( reportFile, jasperFile); - } - - return new JasperData( jasperReport, reportDir, jasperName, jasperFile); - } - - /** - * Load Process Parameters into given params map - * @param AD_PInstance_ID - * @param params - * @param trxName - */ - private static void addProcessParameters(int AD_PInstance_ID, Map params, String trxName) - { - final String sql = "SELECT " - +" "+X_AD_PInstance_Para.COLUMNNAME_ParameterName - +","+X_AD_PInstance_Para.COLUMNNAME_P_String - +","+X_AD_PInstance_Para.COLUMNNAME_P_String_To - +","+X_AD_PInstance_Para.COLUMNNAME_P_Number - +","+X_AD_PInstance_Para.COLUMNNAME_P_Number_To - +","+X_AD_PInstance_Para.COLUMNNAME_P_Date - +","+X_AD_PInstance_Para.COLUMNNAME_P_Date_To - +","+X_AD_PInstance_Para.COLUMNNAME_Info - +","+X_AD_PInstance_Para.COLUMNNAME_Info_To - +" FROM "+X_AD_PInstance_Para.Table_Name - +" WHERE "+X_AD_PInstance_Para.COLUMNNAME_AD_PInstance_ID+"=?"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, trxName); - pstmt.setInt(1, AD_PInstance_ID); - rs = pstmt.executeQuery(); - while (rs.next()) - { - String name = rs.getString(1); - String pStr = rs.getString(2); - String pStrTo = rs.getString(3); - BigDecimal pNum = rs.getBigDecimal(4); - BigDecimal pNumTo = rs.getBigDecimal(5); - - Timestamp pDate = rs.getTimestamp(6); - Timestamp pDateTo = rs.getTimestamp(7); - if (pStr != null) { - if (pStrTo!=null) { - params.put( name+"1", pStr); - params.put( name+"2", pStrTo); - } else { - params.put( name, pStr); - } - } else if (pDate != null) { - if (pDateTo!=null) { - params.put( name+"1", pDate); - params.put( name+"2", pDateTo); - } else { - params.put( name, pDate); - } - } else if (pNum != null) { - if (name.endsWith("_ID")) { - if (pNumTo!=null) { - params.put( name+"1", pNum.intValue()); - params.put( name+"2", pNumTo.intValue()); - } else { - params.put( name, pNum.intValue()); - } - } else { - if (pNumTo!=null) { - params.put( name+"1", pNum); - params.put( name+"2", pNumTo); - } else { - params.put( name, pNum); - } - } - } - // - // Add parameter info - teo_sarca FR [ 2581145 ] - String info = rs.getString(8); - String infoTo = rs.getString(9); - params.put(name+"_Info1", (info != null ? info : "")); - params.put(name+"_Info2", (infoTo != null ? infoTo : "")); - } - } - catch (SQLException e) - { - throw new DBException(e, sql); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - } - - private void addProcessInfoParameters(Map params, ProcessInfoParameter[] para) - { - if (para != null) { - for (int i = 0; i < para.length; i++) { - if (para[i].getParameter_To() == null) { - if (para[i].getParameterName().endsWith("_ID") && para[i].getParameter() instanceof BigDecimal) { - params.put(para[i].getParameterName(), ((BigDecimal)para[i].getParameter()).intValue()); - } else { - params.put(para[i].getParameterName(), para[i].getParameter()); - } - } else { - // range - from - if (para[i].getParameterName().endsWith("_ID") && para[i].getParameter() != null && para[i].getParameter() instanceof BigDecimal) { - params.put( para[i].getParameterName()+"1", ((BigDecimal)para[i].getParameter()).intValue()); - } else { - params.put( para[i].getParameterName()+"1", para[i].getParameter()); - } - // range - to - if (para[i].getParameterName().endsWith("_ID") && para[i].getParameter_To() instanceof BigDecimal) { - params.put( para[i].getParameterName()+"2", ((BigDecimal)para[i].getParameter_To()).intValue()); - } else { - params.put( para[i].getParameterName()+"2", para[i].getParameter_To()); - } - } - } - } - } - - /** - * @author rlemeill - * @param reportFile - * @param jasperFile - * @return compiled JasperReport - */ - private JasperReport compileReport( File reportFile, File jasperFile) - { - JasperReport compiledJasperReport = null; - try { - JasperCompileManager manager = JasperCompileManager.getInstance(jasperReportStartContext); - manager.compileToFile(reportFile.getAbsolutePath(), jasperFile.getAbsolutePath() ); - jasperFile.setLastModified( reportFile.lastModified()); //Synchronize Dates - compiledJasperReport = (JasperReport)JRLoader.loadObject(jasperFile); - } catch (JRException e) { - throw new AdempiereException(e); - } - return compiledJasperReport; - } - - /** - * @author rlemeill - * @param ProcessInfo - * @return ReportData or null if no data found - */ - public ReportData getReportData (ProcessInfo pi, String trxName) - { - log.info(""); - String sql = "SELECT pr.JasperReport, pr.IsDirectPrint " - + "FROM AD_Process pr, AD_PInstance pi " - + "WHERE pr.AD_Process_ID = pi.AD_Process_ID " - + " AND pi.AD_PInstance_ID=?"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, trxName); - pstmt.setInt(1, pi.getAD_PInstance_ID()); - rs = pstmt.executeQuery(); - String path = null; - boolean directPrint = false; - boolean isPrintPreview = pi.isPrintPreview(); - if (rs.next()) { - path = rs.getString(1); - - if ("Y".equalsIgnoreCase(rs.getString(2)) && !Ini.isPropertyBool(Ini.P_PRINTPREVIEW) - && !isPrintPreview ) - directPrint = true; - } else { - log.severe("data not found; sql = "+sql); - return null; - } - - return new ReportData( path, directPrint); - } - catch (SQLException e) - { - throw new DBException(e, sql); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - } - - static class ReportData { - private String reportFilePath; - private boolean directPrint; - - public ReportData(String reportFilePath, boolean directPrint) { - this.reportFilePath = reportFilePath; - this.directPrint = directPrint; - } - - public String getReportFilePath() { - return reportFilePath; - } - - public boolean isDirectPrint() { - return directPrint; - } - } - - public static class JasperData - implements Serializable - { - /** - * - */ - private static final long serialVersionUID = 4375195020654531202L; - private JasperReport jasperReport; - private File reportDir; - private String jasperName; - private File jasperFile; - - public JasperData(JasperReport jasperReport, File reportDir, String jasperName, File jasperFile) { - this.jasperReport = jasperReport; - this.reportDir = reportDir; - this.jasperName = jasperName; - this.jasperFile = jasperFile; - } - - public JasperReport getJasperReport() { - return jasperReport; - } - - public File getReportDir() { - return reportDir; - } - - public String getJasperName() { - return jasperName; - } - - public File getJasperFile() { - return jasperFile; - } - } - - static class FileFilter implements FilenameFilter { - private String reportStart; - private File directory; - private String extension; - - public FileFilter(String reportStart, File directory, String extension) { - this.reportStart = reportStart; - this.directory = directory; - this.extension = extension; - } - - public boolean accept(File file, String name) { - if (file.equals( directory)) { - if (name.startsWith( reportStart)) { - int pos = name.lastIndexOf( extension); - if ( (pos!=-1) && (pos==(name.length()-extension.length()))) return true; - } - } - return false; - } - } - - @Override + + /** + * @author rlemeill + * @param reportLocation http://applicationserver/webApp/standalone.jrxml for example + * @param localPath Where to put the http downloaded file + * @return abstract File which represent the downloaded file + */ + private File getRemoteFile(String reportLocation, String localPath) + { + try{ + URL reportURL = new URL(reportLocation); + InputStream in = reportURL.openStream(); + + File downloadedFile = new File(localPath); + + if (downloadedFile.exists()) + { + downloadedFile.delete(); + } + + FileOutputStream fout = new FileOutputStream(downloadedFile); + + byte buf[] = new byte[1024]; + int s = 0; + while((s = in.read(buf, 0, 1024)) > 0) + fout.write(buf, 0, s); + + in.close(); + fout.flush(); + fout.close(); + return downloadedFile; + } catch (FileNotFoundException e) { + if(reportLocation.indexOf("Subreport") == -1 && !reportLocation.endsWith(".properties")) // Only show the warning if it is not a subreport or properties + log.warning("404 not found: Report cannot be found on server "+ e.getMessage()); + return null; + } catch (IOException e) { + throw new AdempiereException("I/O error when trying to download (sub)report from server "+ e.getLocalizedMessage()); + } + } + + /** + * Search for additional subreports deployed to a webcontext if + * the parent report is located there + * @author deathmeat + * @param reportName The original report name + * @param reportPath The full path to the parent report + * @param fileExtension The file extension of the parent report + * @return An Array of File objects referencing to the downloaded subreports + */ + private File[] getHttpSubreports(String reportName, String reportPath, String fileExtension) + { + ArrayList subreports = new ArrayList(); + String remoteDir = reportPath.substring(0, reportPath.lastIndexOf("/")); + + // Currently check hardcoded for max. 10 subreports + for(int i=1; i<10; i++) + { + // Check if subreport number i exists + File subreport = httpDownloadedReport(remoteDir + "/" + reportName + i + fileExtension); + if(subreport == null) // Subreport doesn't exist, abort further approaches + break; + + subreports.add(subreport); + } + + File[] subreportsTemp = new File[0]; + subreportsTemp = subreports.toArray(subreportsTemp); + return subreportsTemp; + } + + /** + * @author rlemeill + * @param reportLocation http string url ex: http://adempiereserver.domain.com/webApp/standalone.jrxml + * @return downloaded File (or already existing one) + */ + private File httpDownloadedReport(String reportLocation) + { + File reportFile = null; + File downloadedFile = null; + if (log.isLoggable(Level.INFO)) log.info(" report deployed to " + reportLocation); + try { + + + String[] tmps = reportLocation.split("/"); + String cleanFile = tmps[tmps.length-1]; + String localFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + cleanFile; + String downloadedLocalFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator")+"TMP" + cleanFile; + + reportFile = new File(localFile); + + + if (reportFile.exists()) + { + String localMD5hash = DigestOfFile.GetLocalMD5Hash(reportFile); + String remoteMD5Hash = getRemoteMD5(reportLocation); + if (log.isLoggable(Level.INFO)) log.info("MD5 for local file is "+localMD5hash ); + if ( remoteMD5Hash != null) + { + if (localMD5hash.equals(remoteMD5Hash)) + { + if (log.isLoggable(Level.INFO)) log.info(" no need to download: local report is up-to-date"); + } + else + { + if (log.isLoggable(Level.INFO)) log.info(" report on server is different that local one, download and replace"); + downloadedFile = getRemoteFile(reportLocation, downloadedLocalFile); + reportFile.delete(); + downloadedFile.renameTo(reportFile); + } + } + else + { + log.warning("Remote hashing is not available did you deployed webApp.ear?"); + downloadedFile = getRemoteFile(reportLocation, downloadedLocalFile); + // compare hash of existing and downloaded + if ( DigestOfFile.md5localHashCompare(reportFile,downloadedFile) ) + { + //nothing file are identical + if (log.isLoggable(Level.INFO)) log.info(" no need to replace your existing report"); + } + else + { + if (log.isLoggable(Level.INFO)) log.info(" report on server is different that local one, replacing"); + reportFile.delete(); + downloadedFile.renameTo(reportFile); + } + } + } + else + { + reportFile = getRemoteFile(reportLocation,localFile); + } + + } + catch (Exception e) { + throw new AdempiereException("Unknown exception: "+ e.getLocalizedMessage()); + } + return reportFile; + } + + private String getRemoteMD5(String reportLocation) { + try{ + String md5url = reportLocation; + if (md5url.indexOf("?") > 0) + md5url = md5url + "&md5=true"; + else + md5url = md5url + "?md5=true"; + URL reportURL = new URL(md5url); + InputStream in = reportURL.openStream(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte buf[] = new byte[1024]; + int s = 0; + while((s = in.read(buf, 0, 1024)) > 0) + baos.write(buf, 0, s); + + in.close(); + String hash = new String(baos.toByteArray()); + return hash; + } catch (IOException e) { + throw new AdempiereException("I/O error when trying to download (sub)report from server "+ e.getLocalizedMessage()); + } + } + + /** + * Returns the Server Connection if direct connection is not available + * (VPN, WAN, Terminal) and thus query has to be run on server only else return + * a direct connection to DB. + * + * Notes: Need to refactor and integrate in DB if confirmed to be working as + * expected. + * + * @author Ashley Ramdass + * @return Connection DB Connection + */ + protected Connection getConnection() + { + return DB.getConnectionRW(); + } + + /** + * Start the process. + * Called then pressing the Process button in R_Request. + * It should only return false, if the function could not be performed + * as this causes the process to abort. + * @author rlemeill + * @param ctx context + * @param pi standard process info + * @param trx + * @return true if success + */ + public boolean startProcess(Properties ctx, ProcessInfo pi, Trx trx) + { + ClassLoader cl1 = Thread.currentThread().getContextClassLoader(); + ClassLoader cl2 = JasperReport.class.getClassLoader(); + try { + if (!cl1.equals(cl2)) { + Thread.currentThread().setContextClassLoader(cl2); + } + return startProcess0(ctx, pi, trx); + } finally { + if (!cl1.equals(Thread.currentThread().getContextClassLoader())) { + Thread.currentThread().setContextClassLoader(cl1); + } + } + } + + private boolean startProcess0(Properties ctx, ProcessInfo pi, Trx trx) + { + processInfo = pi; + int nrows = 0; + Object onrows = null; + String Name=pi.getTitle(); + int AD_PInstance_ID=pi.getAD_PInstance_ID(); + int Record_ID=pi.getRecord_ID(); + + if (log.isLoggable(Level.INFO)) log.info( "Name="+Name+" AD_PInstance_ID="+AD_PInstance_ID+" Record_ID="+Record_ID); + String trxName = null; + if (trx != null) { + trxName = trx.getTrxName(); + } + ReportData reportData = getReportData(pi, trxName); + if (reportData == null) { + reportResult(AD_PInstance_ID, "Can not find report data", trxName); + return false; + } + + List jasperPrintList = new ArrayList(); + String reportFilePath = reportData.getReportFilePath(); + String[] reportPathList = reportFilePath.split(";"); + for (int idx = 0; idx < reportPathList.length; idx++) { + + String reportPath = reportPathList[idx]; + if (Util.isEmpty(reportPath, true)) + { + reportResult(AD_PInstance_ID, "Can not find report", trxName); + return false; + } + if (reportPath.startsWith("@#LocalHttpAddr@")) { + String localaddr = Env.getContext(Env.getCtx(), "#LocalHttpAddr"); + if (!Util.isEmpty(localaddr)) { + reportPath = reportPath.replace("@#LocalHttpAddr@", localaddr); + } + } + + JasperData data = null; + File reportFile = null; + String fileExtension = ""; + HashMap params = new HashMap(); + + addProcessParameters(AD_PInstance_ID, params, trxName); + addProcessInfoParameters(params, pi.getParameter()); + + reportFile = getReportFile(reportPath, (String)params.get("ReportType")); + if (reportFile == null || reportFile.exists() == false) + { + log.severe("No report file found for given type, falling back to " + reportPath); + reportFile = getReportFile(reportPath); + } + + if (reportFile == null || reportFile.exists() == false) + { + String tmp = "Can not find report file at path - " + reportPath; + log.severe(tmp); + reportResult(AD_PInstance_ID, tmp, trxName); + } + + if (reportFile != null) + { + data = processReport(reportFile); + fileExtension = reportFile.getName().substring(reportFile.getName().lastIndexOf("."), + reportFile.getName().length()); + } + else + { + return false; + } + + JasperReport jasperReport = data.getJasperReport(); + String jasperName = data.getJasperName(); + String name = jasperReport.getName(); + File reportDir = data.getReportDir(); + + String resourcePath = reportDir.getAbsolutePath(); + if (!resourcePath.endsWith("/") && !resourcePath.endsWith("\\")); + { + resourcePath = resourcePath + File.separator; + } + params.put("SUBREPORT_DIR", resourcePath); + if (reportPath.startsWith("http://") || reportPath.startsWith("https://")) { + int i = reportPath.lastIndexOf("/"); + String httpPath = reportPath.substring(0, i+1); + params.put("RESOURCE_DIR", httpPath); + } else { + params.put("RESOURCE_DIR", resourcePath); + } + + if (jasperReport != null && pi.getTable_ID() > 0 && Record_ID <= 0 && pi.getRecord_IDs() != null && pi.getRecord_IDs().length > 0) + { + try + { + JRQuery originalQuery = jasperReport.getQuery(); + if (originalQuery != null) + { + String originalQueryText = originalQuery.getText(); + if (originalQueryText != null) + { + MTable table = new MTable(ctx, pi.getTable_ID(), trxName); + String tableName = table.getTableName(); + String originalQueryTemp = originalQueryText.toUpperCase(); + int index1 = originalQueryTemp.indexOf(" " + tableName.toUpperCase()); + if (index1 != -1) + { + int index2 = originalQueryTemp.substring(index1).indexOf(","); + if (index2 != -1) + { + String tableVariable = originalQueryTemp.substring(index1 + tableName.length() + 1, index1 + index2); + tableVariable = tableVariable.trim(); + + if (tableVariable.length() == 0) + tableVariable = tableName; + + MQuery query = new MQuery(tableName); + for (int recordId : pi.getRecord_IDs()) + query.addRestriction(tableVariable + "." + query.getTableName() + "_ID" + MQuery.EQUAL + recordId, false, 0); + + String newQueryText = null; + int index3 = originalQueryTemp.indexOf("WHERE"); + if (index3 != -1) + newQueryText = originalQueryText + " AND " + query.toString(); + else + newQueryText = originalQueryText + " WHERE " + query.toString(); + + File jrxmlFile = File.createTempFile(makePrefix(jasperReport.getName()), ".jrxml"); + JRXmlWriter.writeReport(jasperReport, new FileOutputStream(jrxmlFile), "UTF-8"); + + JasperDesign jasperDesign = JRXmlLoader.load(jrxmlFile); + + JRDesignQuery newQuery = new JRDesignQuery(); + newQuery.setText(newQueryText); + jasperDesign.setQuery(newQuery); + + JasperCompileManager manager = JasperCompileManager.getInstance(jasperReportStartContext); + JasperReport newJasperReport = manager.compile(jasperDesign); + if (newJasperReport != null) + { + data.jasperReport = newJasperReport; + jasperReport = newJasperReport; + } + } + } + } + } + } + catch(Exception e) + { + log.severe("Failed to modify the report query"); + } + } + + if (jasperReport != null) { + File[] subreports; + + // Subreports + if(reportPath.startsWith("http://") || reportPath.startsWith("https://")) + { + // Locate and download subreports from remote webcontext + subreports = getHttpSubreports(jasperName + "Subreport", reportPath, fileExtension); + } + else if (reportPath.startsWith("attachment:")) + { + subreports = getAttachmentSubreports(reportPath); + } + else if (reportPath.startsWith("resource:")) + { + String path = reportPath.substring(0, reportPath.length() +1 - (name+"."+fileExtension).length()); + subreports = getResourceSubreports(name+ "Subreport", path, fileExtension); + } + else + { + // Locate subreports from local/remote filesystem + subreports = reportDir.listFiles( new FileFilter( jasperName+"Subreport", reportDir, fileExtension)); + } + + for( int i=0; i 0) + params.put("RECORD_ID", Integer.valueOf( Record_ID)); + + // contribution from Ricardo (ralexsander) + // in iReports you can 'SELECT' AD_Client_ID, AD_Org_ID and AD_User_ID using only AD_PINSTANCE_ID + params.put("AD_PINSTANCE_ID", Integer.valueOf( AD_PInstance_ID)); + + // FR [3123850] - Add continuosly needed parameters to Jasper Starter - Carlos Ruiz - GlobalQSS + params.put("AD_CLIENT_ID", Integer.valueOf( Env.getAD_Client_ID(Env.getCtx()))); + params.put("AD_ROLE_ID", Integer.valueOf( Env.getAD_Role_ID(Env.getCtx()))); + params.put("AD_USER_ID", Integer.valueOf( Env.getAD_User_ID(Env.getCtx()))); + + params.put("AD_CLIENT_NAME", Env.getContext(Env.getCtx(), "#AD_Client_Name")); + params.put("AD_ROLE_NAME", Env.getContext(Env.getCtx(), "#AD_Role_Name")); + params.put("AD_USER_NAME", Env.getContext(Env.getCtx(), "#AD_User_Name")); + params.put("AD_ORG_NAME", Env.getContext(Env.getCtx(), "#AD_Org_Name")); + params.put("BASE_DIR", REPORT_HOME.getAbsolutePath()); + //params.put("HeaderLogo", reportPath); + //params.put("LoginLogo", reportPath); + + Language currLang = Env.getLanguage(Env.getCtx()); + String printerName = null; + MPrintFormat printFormat = null; + PrintInfo printInfo = null; + ProcessInfoParameter[] pip = pi.getParameter(); + // Get print format and print info parameters + if (pip!=null) { + for (int i=0; i exporter = null; + + //JRExporter exporter = null; + if (ext.equals("pdf")) { + JRPdfExporter export = new JRPdfExporter(jasperReportStartContext); + SimplePdfExporterConfiguration config = new SimplePdfExporterConfiguration(); + export.setConfiguration(config); + export.setExporterOutput(new SimpleOutputStreamExporterOutput(strm)); + exporter = export; + // give a chance for customize jasper report configuration per report + JREventManage.sentPdfExporterConfigurationEvent(export, config, pi); + } else if (ext.equals("ps")) { + JRPrintServiceExporter export = new JRPrintServiceExporter( + jasperContext); + SimplePrintServiceExporterConfiguration config = new SimplePrintServiceExporterConfiguration(); + export.setConfiguration(config); + export.setExporterOutput(new SimpleOutputStreamExporterOutput(strm)); + exporter = export; + } else if (ext.equals("xml")) { + JRXmlExporter export = new JRXmlExporter(jasperContext); + SimpleExporterConfiguration config = new SimpleExporterConfiguration(); + export.setConfiguration(config); + export.setExporterOutput(new SimpleXmlExporterOutput(strm)); + exporter = export; + } else if (ext.equals("csv") || ext.equals("ssv") ) { + JRCsvExporter export = new JRCsvExporter(jasperContext); + SimpleCsvExporterConfiguration config = new SimpleCsvExporterConfiguration(); + if(ext.equals("ssv")) + config.setFieldDelimiter(";"); + export.setConfiguration(config); + export.setExporterOutput(new SimpleWriterExporterOutput(strm)); + exporter = export; + } else if (ext.equals("txt")) { + JRTextExporter export = new JRTextExporter(jasperContext); + SimpleTextExporterConfiguration config = new SimpleTextExporterConfiguration(); + export.setConfiguration(config); + exporter = export; + } else if (ext.equals("html") || ext.equals("htm")) { + HtmlExporter export = new HtmlExporter(jasperContext); + SimpleHtmlExporterConfiguration config = new SimpleHtmlExporterConfiguration(); + export.setConfiguration(config); + exporter = export; + } else if (ext.equals("xls")) { + JRXlsExporter export = new JRXlsExporter(jasperContext); + SimpleXlsExporterConfiguration config = new SimpleXlsExporterConfiguration(); + export.setConfiguration(config); + exporter = export; + } else { + log.severe("FileInvalidExtension="+ext); + strm.close(); + } + + if (exporter == null) + exporter = new JRPdfExporter(jasperReportStartContext); + + exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); + + exporter.exportReport(); + processInfo.setExportFile(file); + } + catch (IOException e) + { + log.severe("ReportStarter.startProcess: Can not export PDF File - "+ e.getMessage()); + } + } + } catch (JRException e) { + throw new AdempiereException(e.getLocalizedMessage() + (e.getCause() != null ? " -> " + e.getCause().getLocalizedMessage() : "")); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + } + } + } + } + + } // for reportPathList + + if (onrows != null && onrows instanceof Integer) { + nrows = (Integer) onrows; + processInfo.setRowCount(nrows); + } + reportResult( AD_PInstance_ID, null, trxName); + return true; + } + + private String makePrefix(String name) { + StringBuilder prefix = new StringBuilder(); + char[] nameArray = name.toCharArray(); + for (char ch : nameArray) { + if (Character.isLetterOrDigit(ch)) { + prefix.append(ch); + } else { + prefix.append("_"); + } + } + return prefix.toString(); + } + + /** + * Get .property resource file from process attachment + * @param bundleName + * @param currLang + * @return File + */ + private File getAttachmentResourceFile(String bundleName, Language currLang) { + String resname = bundleName+"_"+currLang.getLocale().getLanguage()+"_"+currLang.getLocale().getCountry()+".properties"; + File resFile = getAttachmentEntryFile(resname); + if (resFile == null) { + resname = bundleName+"_"+currLang.getLocale().getLanguage()+".properties"; + resFile = getAttachmentEntryFile(resname); + if (resFile == null) { + resname = bundleName+".properties"; + resFile = getAttachmentEntryFile(resname); + } + } + return resFile; + } + + private File getAttachmentEntryFile(String resname) { + File fileattach = null; + MAttachmentEntry[] entries = attachment.getEntries(); + for( int i=0; i subreports = new ArrayList(); + MAttachmentEntry[] entries = attachment.getEntries(); + for(int i = 0; i < entries.length; i++) { + // @Trifon + if (!entries[i].getName().equals(name)) + { + File reportFile = getAttachmentEntryFile(entries[i]); + if (reportFile != null) { + if (entries[i].getName().toLowerCase().endsWith(".jrxml") + || entries[i].getName().toLowerCase().endsWith(".jasper")) { + subreports.add(reportFile); + } + } + } + } + File[] subreportsTemp = new File[0]; + subreportsTemp = subreports.toArray(subreportsTemp); + return subreportsTemp; + } + + /** + * Search for additional subreports deployed as resources + * @param reportName The original report name + * @param reportPath The full path to the parent report + * @param fileExtension The file extension of the parent report + * @return An Array of File objects referencing to the downloaded subreports + */ + private File[] getResourceSubreports(String reportName, String reportPath, String fileExtension) + { + ArrayList subreports = new ArrayList(); + // Currently check hardcoded for max. 10 subreports + for(int i=1; i<10; i++) + { + // Check if subreport number i exists + File subreport = null; + try { + subreport = getFileAsResource(reportPath + reportName + i + fileExtension); + } catch (Exception e) { + // just ignore it + } + if(subreport == null) // Subreport doesn't exist, abort further approaches + break; + + subreports.add(subreport); + } + + File[] subreportsTemp = new File[subreports.size()]; + subreportsTemp = subreports.toArray(subreportsTemp); + return subreportsTemp; + } + + /** + * @author alinv + * @param reportPath + * @param reportType + * @return the abstract file corresponding to typed report + */ + protected File getReportFile(String reportPath, String reportType) { + + if (reportType != null) + { + int cpos = reportPath.lastIndexOf('.'); + reportPath = reportPath.substring(0, cpos) + "_" + reportType + reportPath.substring(cpos, reportPath.length()); + } + + return getReportFile(reportPath); + } + + /** + * @author alinv + * @param reportPath + * @return the abstract file corresponding to report + */ + protected File getReportFile(String reportPath) + { + File reportFile = null; + + // Reports deployment on web server Thanks to Alin Vaida + if (reportPath.startsWith("http://") || reportPath.startsWith("https://")) { + reportFile = httpDownloadedReport(reportPath); + } else if (reportPath.startsWith("attachment:")) { + //report file from process attachment + reportFile = downloadAttachment(reportPath); + } else if (reportPath.startsWith("/")) { + reportFile = new File(reportPath); + } else if (reportPath.startsWith("file:/")) { + try { + reportFile = new File(new URI(reportPath)); + } catch (URISyntaxException e) { + log.warning(e.getLocalizedMessage()); + reportFile = null; + } + } else if (reportPath.startsWith("resource:")) { + try { + reportFile = getFileAsResource(reportPath); + } catch (Exception e) { + log.warning(e.getLocalizedMessage()); + reportFile = null; + } + } else { + reportFile = new File(REPORT_HOME, reportPath); + } + + return reportFile; + } + + /** + * @param reportPath + * @return + * @throws Exception + */ + private File getFileAsResource(String reportPath) throws Exception { + File reportFile; + String name = reportPath.substring("resource:".length()).trim(); + String localName = name.replace('/', '_'); + if (log.isLoggable(Level.INFO)) { + log.info("reportPath = " + reportPath); + log.info("getting resource from = " + getClass().getClassLoader().getResource(name)); + } + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(name); + String localFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + localName; + if (log.isLoggable(Level.INFO)) log.info("localFile = " + localFile); + reportFile = new File(localFile); + + boolean empty = true; + OutputStream out = null; + try { + out = new FileOutputStream(reportFile); + if (out != null){ + byte buf[]=new byte[1024]; + int len; + while((len=inputStream.read(buf))>0) { + empty = false; + out.write(buf,0,len); + } + } + } catch (Exception e) { + throw e; + } finally { + if (out != null) + out.close(); + if (inputStream != null) + inputStream.close(); + } + + if (empty) + return null; + else + return reportFile; + } + + /** + * Download db attachment + * @param reportPath must of syntax attachment:filename + * @return File + */ + private File downloadAttachment(String reportPath) { + File reportFile = null; + String name = reportPath.substring("attachment:".length()).trim(); + MProcess process = new MProcess(Env.getCtx(), processInfo.getAD_Process_ID(), processInfo.getTransactionName()); + attachment = process.getAttachment(); + if (attachment != null) { + MAttachmentEntry[] entries = attachment.getEntries(); + MAttachmentEntry entry = null; + for (int i = 0; i < entries.length; i++) { + if (entries[i].getName().equals(name)) { + entry = entries[i]; + break; + } + } + if (entry != null) { + reportFile = getAttachmentEntryFile(entry); + } + } + return reportFile; + } + + /** + * Download db attachment to local file + * @param entry + * @return File + */ + private File getAttachmentEntryFile(MAttachmentEntry entry) { + String localFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + entry.getName(); + String downloadedLocalFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator")+"TMP" + entry.getName(); + File reportFile = new File(localFile); + if (reportFile.exists()) { + String localMD5hash = DigestOfFile.GetLocalMD5Hash(reportFile); + String entryMD5hash = DigestOfFile.getMD5Hash(entry.getData()); + if (localMD5hash.equals(entryMD5hash)) + { + log.info(" no need to download: local report is up-to-date"); + } + else + { + log.info(" report on server is different that local one, download and replace"); + File downloadedFile = new File(downloadedLocalFile); + entry.getFile(downloadedFile); + if (! reportFile.delete()) { + throw new AdempiereException("Cannot delete temporary file " + reportFile.toString()); + } + if (! downloadedFile.renameTo(reportFile)) { + throw new AdempiereException("Cannot rename temporary file " + downloadedFile.toString() + " to " + reportFile.toString()); + } + } + } else { + entry.getFile(reportFile); + } + return reportFile; + } + + /** + * Update AD_PInstance result and error message + * @author rlemeill + * @param AD_PInstance_ID + * @param errMsg error message or null if there is no error + */ + protected void reportResult(int AD_PInstance_ID, String errMsg, String trxName) + { + int result = (errMsg == null ? 1 : 0); + String sql = "UPDATE AD_PInstance SET Result=?, ErrorMsg=?" + +" WHERE AD_PInstance_ID="+AD_PInstance_ID; + DB.executeUpdateEx(sql, new Object[]{result, errMsg}, trxName); + } + + /** + * @author rlemeill + * @param reportFile + * @return + */ + protected JasperData processReport( File reportFile) { + if (log.isLoggable(Level.INFO)) log.info( "reportFile.getAbsolutePath() = "+reportFile.getAbsolutePath()); + JasperReport jasperReport = null; + + String jasperName = reportFile.getName(); + int pos = jasperName.indexOf('.'); + if (pos!=-1) jasperName = jasperName.substring(0, pos); + File reportDir = reportFile.getParentFile(); + + //test if the compiled report exists + File jasperFile = new File( reportDir.getAbsolutePath(), jasperName+".jasper"); + if (jasperFile.exists()) { // test time + if (reportFile.lastModified() == jasperFile.lastModified()) { + if (log.isLoggable(Level.INFO)) log.info(" no need to compile use "+jasperFile.getAbsolutePath()); + try { + jasperReport = (JasperReport)JRLoader.loadObjectFromFile(jasperFile.getAbsolutePath()); + } catch (JRException e) { + jasperReport = null; + log.severe("Can not load report - "+ e.getMessage()); + } + } else { + jasperReport = compileReport( reportFile, jasperFile); + } + } else { // create new jasper file + jasperReport = compileReport( reportFile, jasperFile); + } + + return new JasperData( jasperReport, reportDir, jasperName, jasperFile); + } + + /** + * Load Process Parameters into given params map + * @param AD_PInstance_ID + * @param params + * @param trxName + */ + private static void addProcessParameters(int AD_PInstance_ID, Map params, String trxName) + { + final String sql = "SELECT " + +" "+X_AD_PInstance_Para.COLUMNNAME_ParameterName + +","+X_AD_PInstance_Para.COLUMNNAME_P_String + +","+X_AD_PInstance_Para.COLUMNNAME_P_String_To + +","+X_AD_PInstance_Para.COLUMNNAME_P_Number + +","+X_AD_PInstance_Para.COLUMNNAME_P_Number_To + +","+X_AD_PInstance_Para.COLUMNNAME_P_Date + +","+X_AD_PInstance_Para.COLUMNNAME_P_Date_To + +","+X_AD_PInstance_Para.COLUMNNAME_Info + +","+X_AD_PInstance_Para.COLUMNNAME_Info_To + +" FROM "+X_AD_PInstance_Para.Table_Name + +" WHERE "+X_AD_PInstance_Para.COLUMNNAME_AD_PInstance_ID+"=?"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, trxName); + pstmt.setInt(1, AD_PInstance_ID); + rs = pstmt.executeQuery(); + while (rs.next()) + { + String name = rs.getString(1); + String pStr = rs.getString(2); + String pStrTo = rs.getString(3); + BigDecimal pNum = rs.getBigDecimal(4); + BigDecimal pNumTo = rs.getBigDecimal(5); + + Timestamp pDate = rs.getTimestamp(6); + Timestamp pDateTo = rs.getTimestamp(7); + if (pStr != null) { + if (pStrTo!=null) { + params.put( name+"1", pStr); + params.put( name+"2", pStrTo); + } else { + params.put( name, pStr); + } + } else if (pDate != null) { + if (pDateTo!=null) { + params.put( name+"1", pDate); + params.put( name+"2", pDateTo); + } else { + params.put( name, pDate); + } + } else if (pNum != null) { + if (name.endsWith("_ID")) { + if (pNumTo!=null) { + params.put( name+"1", pNum.intValue()); + params.put( name+"2", pNumTo.intValue()); + } else { + params.put( name, pNum.intValue()); + } + } else { + if (pNumTo!=null) { + params.put( name+"1", pNum); + params.put( name+"2", pNumTo); + } else { + params.put( name, pNum); + } + } + } + // + // Add parameter info - teo_sarca FR [ 2581145 ] + String info = rs.getString(8); + String infoTo = rs.getString(9); + params.put(name+"_Info1", (info != null ? info : "")); + params.put(name+"_Info2", (infoTo != null ? infoTo : "")); + } + } + catch (SQLException e) + { + throw new DBException(e, sql); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + } + + private void addProcessInfoParameters(Map params, ProcessInfoParameter[] para) + { + if (para != null) { + for (int i = 0; i < para.length; i++) { + if (para[i].getParameter_To() == null) { + if (para[i].getParameterName().endsWith("_ID") && para[i].getParameter() instanceof BigDecimal) { + params.put(para[i].getParameterName(), ((BigDecimal)para[i].getParameter()).intValue()); + } else { + params.put(para[i].getParameterName(), para[i].getParameter()); + } + } else { + // range - from + if (para[i].getParameterName().endsWith("_ID") && para[i].getParameter() != null && para[i].getParameter() instanceof BigDecimal) { + params.put( para[i].getParameterName()+"1", ((BigDecimal)para[i].getParameter()).intValue()); + } else { + params.put( para[i].getParameterName()+"1", para[i].getParameter()); + } + // range - to + if (para[i].getParameterName().endsWith("_ID") && para[i].getParameter_To() instanceof BigDecimal) { + params.put( para[i].getParameterName()+"2", ((BigDecimal)para[i].getParameter_To()).intValue()); + } else { + params.put( para[i].getParameterName()+"2", para[i].getParameter_To()); + } + } + } + } + } + + /** + * @author rlemeill + * @param reportFile + * @param jasperFile + * @return compiled JasperReport + */ + private JasperReport compileReport( File reportFile, File jasperFile) + { + JasperReport compiledJasperReport = null; + try { + JasperCompileManager manager = JasperCompileManager.getInstance(jasperReportStartContext); + manager.compileToFile(reportFile.getAbsolutePath(), jasperFile.getAbsolutePath() ); + jasperFile.setLastModified( reportFile.lastModified()); //Synchronize Dates + compiledJasperReport = (JasperReport)JRLoader.loadObject(jasperFile); + } catch (JRException e) { + throw new AdempiereException(e); + } + return compiledJasperReport; + } + + /** + * @author rlemeill + * @param ProcessInfo + * @return ReportData or null if no data found + */ + public ReportData getReportData (ProcessInfo pi, String trxName) + { + log.info(""); + String sql = "SELECT pr.JasperReport, pr.IsDirectPrint " + + "FROM AD_Process pr, AD_PInstance pi " + + "WHERE pr.AD_Process_ID = pi.AD_Process_ID " + + " AND pi.AD_PInstance_ID=?"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, trxName); + pstmt.setInt(1, pi.getAD_PInstance_ID()); + rs = pstmt.executeQuery(); + String path = null; + boolean directPrint = false; + boolean isPrintPreview = pi.isPrintPreview(); + if (rs.next()) { + path = rs.getString(1); + + if ("Y".equalsIgnoreCase(rs.getString(2)) && !Ini.isPropertyBool(Ini.P_PRINTPREVIEW) + && !isPrintPreview ) + directPrint = true; + } else { + log.severe("data not found; sql = "+sql); + return null; + } + + return new ReportData( path, directPrint); + } + catch (SQLException e) + { + throw new DBException(e, sql); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + } + + static class ReportData { + private String reportFilePath; + private boolean directPrint; + + public ReportData(String reportFilePath, boolean directPrint) { + this.reportFilePath = reportFilePath; + this.directPrint = directPrint; + } + + public String getReportFilePath() { + return reportFilePath; + } + + public boolean isDirectPrint() { + return directPrint; + } + } + + public static class JasperData + implements Serializable + { + /** + * + */ + private static final long serialVersionUID = 4375195020654531202L; + private JasperReport jasperReport; + private File reportDir; + private String jasperName; + private File jasperFile; + + public JasperData(JasperReport jasperReport, File reportDir, String jasperName, File jasperFile) { + this.jasperReport = jasperReport; + this.reportDir = reportDir; + this.jasperName = jasperName; + this.jasperFile = jasperFile; + } + + public JasperReport getJasperReport() { + return jasperReport; + } + + public File getReportDir() { + return reportDir; + } + + public String getJasperName() { + return jasperName; + } + + public File getJasperFile() { + return jasperFile; + } + } + + static class FileFilter implements FilenameFilter { + private String reportStart; + private File directory; + private String extension; + + public FileFilter(String reportStart, File directory, String extension) { + this.reportStart = reportStart; + this.directory = directory; + this.extension = extension; + } + + public boolean accept(File file, String name) { + if (file.equals( directory)) { + if (name.startsWith( reportStart)) { + int pos = name.lastIndexOf( extension); + if ( (pos!=-1) && (pos==(name.length()-extension.length()))) return true; + } + } + return false; + } + } + + @Override public void setProcessUI(IProcessUI processUI) { m_processUI = processUI; - } - + } + } \ No newline at end of file diff --git a/org.adempiere.server-feature/utils.windows/postgresql/ImportIdempiere.bat b/org.adempiere.server-feature/utils.windows/postgresql/ImportIdempiere.bat index ff0636d21d..6fe936c616 100644 --- a/org.adempiere.server-feature/utils.windows/postgresql/ImportIdempiere.bat +++ b/org.adempiere.server-feature/utils.windows/postgresql/ImportIdempiere.bat @@ -1,54 +1,54 @@ -@Echo idempiere Database Import $Revision: 1.3 $ - -@Rem $Id: ImportIdempiere.bat,v 1.3 2005/01/22 21:59:15 jjanke Exp $ - -@Echo Importing idempiere DB from %IDEMPIERE_HOME%\data\seed\Adempiere%5.dmp (%ADEMPIERE_DB_NAME%) - -@if (%IDEMPIERE_HOME%) == () goto environment -@if (%ADEMPIERE_DB_NAME%) == () goto environment -@if (%ADEMPIERE_DB_SERVER%) == () goto environment -@if (%ADEMPIERE_DB_PORT%) == () goto environment -@Rem Must have parameters systemAccount AdempiereID AdempierePwd -@if (%1) == () goto usage -@if (%2) == () goto usage -@if (%3) == () goto usage - -@set PGPASSWORD=%4 -@echo ------------------------------------- -@echo Re-Create user and database -@echo ------------------------------------- -@dropdb -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -U postgres %ADEMPIERE_DB_NAME% -@dropuser -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -U postgres %2 -@set ADEMPIERE_CREATE_ROLE_SQL=CREATE ROLE %2 SUPERUSER LOGIN PASSWORD '%3' -@psql -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -U postgres -c "%ADEMPIERE_CREATE_ROLE_SQL%" -@set ADEMPIERE_CREATE_ROLE_SQL= - -@set PGPASSWORD=%3 -@createdb --template=template0 -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -E UNICODE -O %2 -U %2 %ADEMPIERE_DB_NAME% - -@echo ------------------------------------- -@echo Import Adempiere%5.dmp -@echo ------------------------------------- +@Echo idempiere Database Import $Revision: 1.3 $ + +@Rem $Id: ImportIdempiere.bat,v 1.3 2005/01/22 21:59:15 jjanke Exp $ + +@Echo Importing idempiere DB from %IDEMPIERE_HOME%\data\seed\Adempiere%5.dmp (%ADEMPIERE_DB_NAME%) + +@if (%IDEMPIERE_HOME%) == () goto environment +@if (%ADEMPIERE_DB_NAME%) == () goto environment +@if (%ADEMPIERE_DB_SERVER%) == () goto environment +@if (%ADEMPIERE_DB_PORT%) == () goto environment +@Rem Must have parameters systemAccount AdempiereID AdempierePwd +@if (%1) == () goto usage +@if (%2) == () goto usage +@if (%3) == () goto usage + +@set PGPASSWORD=%4 +@echo ------------------------------------- +@echo Re-Create user and database +@echo ------------------------------------- +@dropdb -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -U postgres %ADEMPIERE_DB_NAME% +@dropuser -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -U postgres %2 +@set ADEMPIERE_CREATE_ROLE_SQL=CREATE ROLE %2 SUPERUSER LOGIN PASSWORD '%3' +@psql -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -U postgres -c "%ADEMPIERE_CREATE_ROLE_SQL%" +@set ADEMPIERE_CREATE_ROLE_SQL= + +@set PGPASSWORD=%3 +@createdb --template=template0 -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -E UNICODE -O %2 -U %2 %ADEMPIERE_DB_NAME% + +@echo ------------------------------------- +@echo Import Adempiere%5.dmp +@echo ------------------------------------- @set ADEMPIERE_ALTER_ROLE_SQL=ALTER ROLE %2 SET search_path TO adempiere, pg_catalog - + @psql -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -d %ADEMPIERE_DB_NAME% -U %2 -c "%ADEMPIERE_ALTER_ROLE_SQL%" - -@psql -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -d %ADEMPIERE_DB_NAME% -U %2 -f %IDEMPIERE_HOME%/data/seed/Adempiere%5.dmp + +@psql -h %ADEMPIERE_DB_SERVER% -p %ADEMPIERE_DB_PORT% -d %ADEMPIERE_DB_NAME% -U %2 -f %IDEMPIERE_HOME%/data/seed/Adempiere%5.dmp @set ADEMPIERE_ALTER_ROLE_SQL= - -@set PGPASSWORD= -@goto end - -:environment -@Echo Please make sure that the enviroment variables are set correctly: -@Echo IDEMPIERE_HOME e.g. D:\idempiere -@Echo ADEMPIERE_DB_NAME e.g. adempiere -@Echo ADEMPIERE_DB_SERVER e.g. dbserver.idempiere.org -@Echo ADEMPIERE_DB_PORT e.g. 5432 - -:usage -@echo Usage: %0 -@echo Example: %0 postgres idempiere idempiere postgresPwd - -:end + +@set PGPASSWORD= +@goto end + +:environment +@Echo Please make sure that the enviroment variables are set correctly: +@Echo IDEMPIERE_HOME e.g. D:\idempiere +@Echo ADEMPIERE_DB_NAME e.g. adempiere +@Echo ADEMPIERE_DB_SERVER e.g. dbserver.idempiere.org +@Echo ADEMPIERE_DB_PORT e.g. 5432 + +:usage +@echo Usage: %0 +@echo Example: %0 postgres idempiere idempiere postgresPwd + +:end diff --git a/org.adempiere.server/src/main/server/org/compiere/ldap/LdapConnectionHandler.java b/org.adempiere.server/src/main/server/org/compiere/ldap/LdapConnectionHandler.java index a5c6dbc940..98bd224074 100644 --- a/org.adempiere.server/src/main/server/org/compiere/ldap/LdapConnectionHandler.java +++ b/org.adempiere.server/src/main/server/org/compiere/ldap/LdapConnectionHandler.java @@ -1,34 +1,34 @@ -/****************************************************************************** - * 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. - * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html - * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org - *****************************************************************************/ -package org.compiere.ldap; - -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.Socket; -import java.util.Hashtable; -import java.util.logging.Level; - -import javax.naming.AuthenticationException; -import javax.naming.Context; -import javax.naming.ldap.InitialLdapContext; - -import org.compiere.model.MLdapProcessor; -import org.compiere.model.MLdapUser; -import org.compiere.util.CLogger; +/****************************************************************************** + * 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. + * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html + * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org + *****************************************************************************/ +package org.compiere.ldap; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.Socket; +import java.util.Hashtable; +import java.util.logging.Level; + +import javax.naming.AuthenticationException; +import javax.naming.Context; +import javax.naming.ldap.InitialLdapContext; + +import org.compiere.model.MLdapProcessor; +import org.compiere.model.MLdapUser; +import org.compiere.util.CLogger; /** * LDAP Connection Handler @@ -57,14 +57,14 @@ import org.compiere.util.CLogger; * - bind again with returned object name and password * The protocol for the java client, please refer to the sample code in main(). * - * @author Jorg Janke - * @version $Id: LdapConnectionHandler.java,v 1.1 2006/10/09 00:23:16 jjanke Exp $ - */ -public class LdapConnectionHandler extends Thread -{ - /** - * Ldap Connection Handler - * @param socket server socket + * @author Jorg Janke + * @version $Id: LdapConnectionHandler.java,v 1.1 2006/10/09 00:23:16 jjanke Exp $ + */ +public class LdapConnectionHandler extends Thread +{ + /** + * Ldap Connection Handler + * @param socket server socket * @param model model */ public LdapConnectionHandler(Socket socket, MLdapProcessor model) @@ -74,43 +74,43 @@ public class LdapConnectionHandler extends Thread m_socket = socket; m_socket.setTcpNoDelay(true); // should not be required m_model = model; - } - catch (Exception e) - { - log.log(Level.SEVERE, "", e); - } // no timeout - } // LdapConnectionHandler - - /** Socket */ - private Socket m_socket = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, "", e); + } // no timeout + } // LdapConnectionHandler + + /** Socket */ + private Socket m_socket = null; /** Ldap Model */ private MLdapProcessor m_model = null; - /** Logger */ - private static CLogger log = CLogger.getCLogger (LdapConnectionHandler.class); - - - /** - * Do Work - */ - public void run() - { - try - { - if (m_socket == null || m_socket.isClosed()) - return; - + /** Logger */ + private static CLogger log = CLogger.getCLogger (LdapConnectionHandler.class); + + + /** + * Do Work + */ + public void run() + { + try + { + if (m_socket == null || m_socket.isClosed()) + return; + LdapMessage msg = new LdapMessage(); MLdapUser ldapUser = new MLdapUser(); LdapResult result = new LdapResult(); - boolean activeSession = true; - while (activeSession) - { - InputStream in = m_socket.getInputStream(); - BufferedOutputStream out = new BufferedOutputStream(m_socket.getOutputStream()); - // Read - byte[] buffer = new byte[512]; - int length = in.read(buffer, 0, 512); - + boolean activeSession = true; + while (activeSession) + { + InputStream in = m_socket.getInputStream(); + BufferedOutputStream out = new BufferedOutputStream(m_socket.getOutputStream()); + // Read + byte[] buffer = new byte[512]; + int length = in.read(buffer, 0, 512); + // Decode the input message buffer result.reset(msg, ldapUser); msg.reset(result); @@ -136,34 +136,34 @@ public class LdapConnectionHandler extends Thread break; } } // while(activeSession) - } - catch (IOException e) - { - log.log(Level.SEVERE, "", e); - } - - try - { - m_socket.close(); - } - catch (Exception e) - { - log.log(Level.WARNING, "Socket", e); - } - m_socket = null; - } // run - - /** - * String Representation - * @return info - */ - public String toString() - { - StringBuilder sb = new StringBuilder ("LdapConnectionHandler["); - sb.append (hashCode()).append ("]"); - return sb.toString (); - } // toString - + } + catch (IOException e) + { + log.log(Level.SEVERE, "", e); + } + + try + { + m_socket.close(); + } + catch (Exception e) + { + log.log(Level.WARNING, "Socket", e); + } + m_socket = null; + } // run + + /** + * String Representation + * @return info + */ + public String toString() + { + StringBuilder sb = new StringBuilder ("LdapConnectionHandler["); + sb.append (hashCode()).append ("]"); + return sb.toString (); + } // toString + /** * Test using the java client. * Ldap v3 won't need to do any bind, search, bind anymore. diff --git a/org.adempiere.server/src/main/server/org/compiere/ldap/LdapMessage.java b/org.adempiere.server/src/main/server/org/compiere/ldap/LdapMessage.java index 5582fdd305..db3b3df1a5 100644 --- a/org.adempiere.server/src/main/server/org/compiere/ldap/LdapMessage.java +++ b/org.adempiere.server/src/main/server/org/compiere/ldap/LdapMessage.java @@ -1,34 +1,34 @@ -/****************************************************************************** - * 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. - * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html - * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org - *****************************************************************************/ -package org.compiere.ldap; - -import java.util.logging.Level; - -import org.compiere.util.CLogger; - -import com.sun.jndi.ldap.BerDecoder; - -/** - * Ldap Message - * - * @author Jorg Janke - * @version $Id: LdapMessage.java,v 1.1 2006/10/09 00:23:16 jjanke Exp $ - */ -public class LdapMessage -{ +/****************************************************************************** + * 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. + * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html + * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org + *****************************************************************************/ +package org.compiere.ldap; + +import java.util.logging.Level; + +import org.compiere.util.CLogger; + +import com.sun.jndi.ldap.BerDecoder; + +/** + * Ldap Message + * + * @author Jorg Janke + * @version $Id: LdapMessage.java,v 1.1 2006/10/09 00:23:16 jjanke Exp $ + */ +public class LdapMessage +{ static public final int BIND_REQUEST = 96; static public final int BIND_RESPONSE = 97; static public final int UNBIND_REQUEST = 98; @@ -124,12 +124,12 @@ public class LdapMessage // // Payload - if (m_protocolOp == BIND_REQUEST) { + if (m_protocolOp == BIND_REQUEST) { handleBind(); - } else if (m_protocolOp == UNBIND_REQUEST) { - if (log.isLoggable(Level.INFO)) log.info("#" + msgId + ": unbind"); - } else if (m_protocolOp == SEARCH_REQUEST) { - handleSearch(); + } else if (m_protocolOp == UNBIND_REQUEST) { + if (log.isLoggable(Level.INFO)) log.info("#" + msgId + ": unbind"); + } else if (m_protocolOp == SEARCH_REQUEST) { + handleSearch(); } else { // Only supoort BIND, UNBIND and SEARCH result.setErrorNo(LdapResult.LDAP_PROTOCOL_ERROR); result.setErrorString(": Unsupported Request"); @@ -202,7 +202,7 @@ public class LdapMessage { result.setErrorNo(LdapResult.LDAP_PROTOCOL_ERROR); result.setErrorString("Unsupported LDAP version"); - if (log.isLoggable(Level.INFO)) log.info("#" + msgId + ": unsupported LDAP version - " + version); + if (log.isLoggable(Level.INFO)) log.info("#" + msgId + ": unsupported LDAP version - " + version); return; } @@ -214,7 +214,7 @@ public class LdapMessage if (auth != SIMPLE_AUTHENTICATION) // 0x80 - simple authentication { result.setErrorNo(LdapResult.LDAP_AUTH_METHOD_NOT_SUPPORTED); - if (log.isLoggable(Level.INFO)) log.info("#" + msgId + ": unsupported authentication method - " + auth); + if (log.isLoggable(Level.INFO)) log.info("#" + msgId + ": unsupported authentication method - " + auth); return; } @@ -227,13 +227,13 @@ public class LdapMessage { result.setErrorNo(LdapResult.LDAP_NO_SUCH_OBJECT); result.setErrorString(": \"cn\" not defined"); - if (log.isLoggable(Level.INFO)) log.info("#" + msgId + ": \"cn\" not defined"); + if (log.isLoggable(Level.INFO)) log.info("#" + msgId + ": \"cn\" not defined"); return; } } // Log the information - if (log.isLoggable(Level.INFO)) log.info("#" + msgId + ": bind - version=" + version + ", userId=" + userId); + if (log.isLoggable(Level.INFO)) log.info("#" + msgId + ": bind - version=" + version + ", userId=" + userId); } catch (Exception ex) { @@ -257,16 +257,16 @@ public class LdapMessage orgUnit = dnArray[i].split("=")[1]; } } // parseDN() - - /** - * Get Operation Code - * @return protocolOp - */ - public int getOperation() - { - return m_protocolOp; - } // getOperation - + + /** + * Get Operation Code + * @return protocolOp + */ + public int getOperation() + { + return m_protocolOp; + } // getOperation + /** * Get message id * @return msgId diff --git a/org.adempiere.server/src/main/server/org/compiere/ldap/LdapResult.java b/org.adempiere.server/src/main/server/org/compiere/ldap/LdapResult.java index 01f2be5597..872ccf336a 100644 --- a/org.adempiere.server/src/main/server/org/compiere/ldap/LdapResult.java +++ b/org.adempiere.server/src/main/server/org/compiere/ldap/LdapResult.java @@ -1,36 +1,36 @@ -/****************************************************************************** - * 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. - * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html - * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org - *****************************************************************************/ -package org.compiere.ldap; - -import java.util.logging.Level; - -import org.compiere.model.MLdapProcessor; -import org.compiere.model.MLdapUser; -import org.compiere.util.CLogger; - -import com.sun.jndi.ldap.BerEncoder; - -/** - * Ldap Wire Response - * - * @author Jorg Janke - * @version $Id: LdapResult.java,v 1.1 2006/10/09 00:23:16 jjanke Exp $ - */ -public class LdapResult -{ +/****************************************************************************** + * 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. + * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html + * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org + *****************************************************************************/ +package org.compiere.ldap; + +import java.util.logging.Level; + +import org.compiere.model.MLdapProcessor; +import org.compiere.model.MLdapUser; +import org.compiere.util.CLogger; + +import com.sun.jndi.ldap.BerEncoder; + +/** + * Ldap Wire Response + * + * @author Jorg Janke + * @version $Id: LdapResult.java,v 1.1 2006/10/09 00:23:16 jjanke Exp $ + */ +public class LdapResult +{ /** LdapMesssage */ private LdapMessage ldapMsg = null; /** Encoder */ @@ -132,7 +132,7 @@ public class LdapResult generateResult("", LdapMessage.BIND_RESPONSE, LDAP_INAPPROPRIATE_AUTHENTICATION, ldapErrorMessage[LDAP_INAPPROPRIATE_AUTHENTICATION]); - if (log.isLoggable(Level.INFO)) log.info("Failed : " + ldapErrorMessage[LDAP_INAPPROPRIATE_AUTHENTICATION]); + if (log.isLoggable(Level.INFO)) log.info("Failed : " + ldapErrorMessage[LDAP_INAPPROPRIATE_AUTHENTICATION]); } } else if (ldapMsg.getOperation() == LdapMessage.SEARCH_REQUEST) diff --git a/org.adempiere.server/standard.css b/org.adempiere.server/standard.css index f60bed7ed2..abf0eea4da 100644 --- a/org.adempiere.server/standard.css +++ b/org.adempiere.server/standard.css @@ -1,151 +1,151 @@ -/* Adempiere Root (c) Jorg Janke */ -/* $Id: standard.css,v 1.1 2006/04/21 18:04:14 jjanke Exp $ */ -body{ - background-color: #FFFFFF; +/* Adempiere Root (c) Jorg Janke */ +/* $Id: standard.css,v 1.1 2006/04/21 18:04:14 jjanke Exp $ */ +body{ + background-color: #FFFFFF; color: #000000; font-size: 76%; font-family: Verdana, Arial, sans-serif; - line-height: 1.3em; -} - -a{ - color: #3465a4; - text-decoration: none; -} - -a:hover{ - text-decoration: none; -} - -h1{ - color: #FF0000; - font-size: x-large; - margin-bottom: 10px; - margin-top: 0; -} - -h2{ - color: #000066; - font-size: large; -} - -h3{ - color: #0000CC; - font-size: medium; - font-style: normal; - font-weight: bold; -} - -h4{ - color: #6600CC; - font-size: medium; - font-style: italic; -} - -h5{ - color: #660099; - font-size: medium; - font-weight: normal; -} - -h6{ - font-size: larger; - font-weight: bold; -} - -hr{ - color: #000099; - padding-bottom: 0; - padding-top: 0; -} - -p{ - text-align: justify; -} - -th{ - background-color: #E6E6FA; - text-align: left; -} - -caption{ - color: #660099; - text-align: left; - font-style: italic; - font-weight: bolder; -} - - -.menuDetail{ - color: #660099; - font-family: Arial,Helvetica,sans-serif; - font-size: 12px; - padding-bottom: 0; - padding-left: 20px; - padding-top: 0; - text-decoration: none; -} - -.menuDetail:hover{ - color: #660099; - font-family: Arial,Helvetica,sans-serif; - font-size: 12px; - padding-bottom: 0; - padding-left: 20px; - padding-top: 0; - text-decoration: none; - background-color: #99FFFF; -} - -.menuMain{ - color: #000066; - font-family: Arial,Helvetica,sans-serif; - font-size: 16px; - text-align: left; - text-decoration: none; -} - -.menuMain:hover{ - color: #000066; - font-family: Arial,Helvetica,sans-serif; - font-size: 16px; - text-align: left; - text-decoration: none; - background-color: #99FFFF; -} - -.menuSub{ - color: #000066; - font-family: Arial,Helvetica,sans-serif; - font-size: 14px; - padding-left: 10px; - text-align: left; - text-decoration: none; -} - -.menuSub:hover{ - color: #000066; - font-family: Arial,Helvetica,sans-serif; - font-size: 14px; - padding-left: 10px; - text-align: left; - text-decoration: none; - background-color: #99FFFF; -} - -.Cerror{ -background:#FF4A4A; -} -.Cmandatory{ -background:#9DFFFF; -} -.Cbasket{ - font-size: 9px; - display: inline; -} -#imgButton{ -border-style:outset; -} -#imgButtonPressed{ -border-style:inset; -} + line-height: 1.3em; +} + +a{ + color: #3465a4; + text-decoration: none; +} + +a:hover{ + text-decoration: none; +} + +h1{ + color: #FF0000; + font-size: x-large; + margin-bottom: 10px; + margin-top: 0; +} + +h2{ + color: #000066; + font-size: large; +} + +h3{ + color: #0000CC; + font-size: medium; + font-style: normal; + font-weight: bold; +} + +h4{ + color: #6600CC; + font-size: medium; + font-style: italic; +} + +h5{ + color: #660099; + font-size: medium; + font-weight: normal; +} + +h6{ + font-size: larger; + font-weight: bold; +} + +hr{ + color: #000099; + padding-bottom: 0; + padding-top: 0; +} + +p{ + text-align: justify; +} + +th{ + background-color: #E6E6FA; + text-align: left; +} + +caption{ + color: #660099; + text-align: left; + font-style: italic; + font-weight: bolder; +} + + +.menuDetail{ + color: #660099; + font-family: Arial,Helvetica,sans-serif; + font-size: 12px; + padding-bottom: 0; + padding-left: 20px; + padding-top: 0; + text-decoration: none; +} + +.menuDetail:hover{ + color: #660099; + font-family: Arial,Helvetica,sans-serif; + font-size: 12px; + padding-bottom: 0; + padding-left: 20px; + padding-top: 0; + text-decoration: none; + background-color: #99FFFF; +} + +.menuMain{ + color: #000066; + font-family: Arial,Helvetica,sans-serif; + font-size: 16px; + text-align: left; + text-decoration: none; +} + +.menuMain:hover{ + color: #000066; + font-family: Arial,Helvetica,sans-serif; + font-size: 16px; + text-align: left; + text-decoration: none; + background-color: #99FFFF; +} + +.menuSub{ + color: #000066; + font-family: Arial,Helvetica,sans-serif; + font-size: 14px; + padding-left: 10px; + text-align: left; + text-decoration: none; +} + +.menuSub:hover{ + color: #000066; + font-family: Arial,Helvetica,sans-serif; + font-size: 14px; + padding-left: 10px; + text-align: left; + text-decoration: none; + background-color: #99FFFF; +} + +.Cerror{ +background:#FF4A4A; +} +.Cmandatory{ +background:#9DFFFF; +} +.Cbasket{ + font-size: 9px; + display: inline; +} +#imgButton{ +border-style:outset; +} +#imgButtonPressed{ +border-style:inset; +} diff --git a/org.adempiere.ui.swing/src/org/compiere/apps/AppsAction.java b/org.adempiere.ui.swing/src/org/compiere/apps/AppsAction.java index 935aae5aaf..55f8a3ea98 100644 --- a/org.adempiere.ui.swing/src/org/compiere/apps/AppsAction.java +++ b/org.adempiere.ui.swing/src/org/compiere/apps/AppsAction.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,26 +16,26 @@ *****************************************************************************/ package org.compiere.apps; -import java.awt.Dimension; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.AbstractAction; -import javax.swing.AbstractButton; -import javax.swing.Action; -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JComponent; -import javax.swing.JMenuItem; -import javax.swing.KeyStroke; - -import org.compiere.swing.CButton; -import org.compiere.swing.CCheckBoxMenuItem; -import org.compiere.swing.CMenuItem; -import org.compiere.swing.CToggleButton; -import org.compiere.util.Env; -import org.compiere.util.Msg; +import java.awt.Dimension; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.AbstractAction; +import javax.swing.AbstractButton; +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JComponent; +import javax.swing.JMenuItem; +import javax.swing.KeyStroke; + +import org.compiere.swing.CButton; +import org.compiere.swing.CCheckBoxMenuItem; +import org.compiere.swing.CMenuItem; +import org.compiere.swing.CToggleButton; +import org.compiere.util.Env; +import org.compiere.util.Msg; /** * Application Action. @@ -48,11 +48,11 @@ import org.compiere.util.Msg; */ public final class AppsAction extends AbstractAction { - /** - * - */ - private static final long serialVersionUID = 8522301377339185496L; - + /** + * + */ + private static final long serialVersionUID = 8522301377339185496L; + /** * Application Action * @@ -147,13 +147,13 @@ public final class AppsAction extends AbstractAction m_button.setActionCommand(m_action); m_button.setMargin(BUTTON_INSETS); m_button.setSize(BUTTON_SIZE); - // - if (accelerator != null) - { - m_button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(accelerator, action); - m_button.getActionMap().put(action, this); - } - } // Action + // + if (accelerator != null) + { + m_button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(accelerator, action); + m_button.getActionMap().put(action, this); + } + } // Action /** Button Size */ public static final Dimension BUTTON_SIZE = new Dimension(28,28); @@ -176,14 +176,14 @@ public final class AppsAction extends AbstractAction * @param name name * @param small small * @return Icon - */ - private ImageIcon getIcon(String name, boolean small) - { - String fullName = name + (small ? "16" : "24"); - return Env.getImageIcon2(fullName); - } // getIcon - - /** + */ + private ImageIcon getIcon(String name, boolean small) + { + String fullName = name + (small ? "16" : "24"); + return Env.getImageIcon2(fullName); + } // getIcon + + /** * Get Name/ActionCommand * @return ActionName */ @@ -242,11 +242,11 @@ public final class AppsAction extends AbstractAction m_pressed = pressed; // Set Button - if (m_button != null) + if (m_button != null) m_button.setSelected(pressed); - + // Set Menu - if (m_menu != null) + if (m_menu != null) m_menu.setSelected(pressed); } // setPressed @@ -301,7 +301,7 @@ public final class AppsAction extends AbstractAction */ public String toString() { - StringBuilder sb = new StringBuilder("AppsAction["); + StringBuilder sb = new StringBuilder("AppsAction["); sb.append(m_action); Object oo = getValue(Action.ACCELERATOR_KEY); if (oo != null) diff --git a/org.adempiere.ui.swing/src/org/compiere/apps/ProcessDialog.java b/org.adempiere.ui.swing/src/org/compiere/apps/ProcessDialog.java index 97442342c8..5216988bac 100644 --- a/org.adempiere.ui.swing/src/org/compiere/apps/ProcessDialog.java +++ b/org.adempiere.ui.swing/src/org/compiere/apps/ProcessDialog.java @@ -1,688 +1,688 @@ -/****************************************************************************** - * 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.compiere.apps; - -import static org.compiere.model.SystemIDs.PROCESS_C_INVOICE_GENERATE; -import static org.compiere.model.SystemIDs.PROCESS_M_INOUT_GENERATE; - -import java.awt.AWTEvent; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GraphicsConfiguration; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import java.util.logging.Level; - -import javax.swing.DefaultComboBoxModel; -import javax.swing.ImageIcon; -import javax.swing.JEditorPane; -import javax.swing.JOptionPane; -import javax.swing.JScrollPane; -import javax.swing.JSeparator; - -import org.adempiere.exceptions.AdempiereException; -import org.adempiere.exceptions.DBException; -import org.adempiere.util.Callback; -import org.adempiere.util.IProcessUI; -import org.compiere.model.MPInstance; -import org.compiere.model.MPInstancePara; -import org.compiere.model.MProcess; -import org.compiere.print.ReportCtl; -import org.compiere.print.ReportEngine; -import org.compiere.process.ProcessInfo; -import org.compiere.process.ProcessInfoUtil; -import org.compiere.swing.CButton; -import org.compiere.swing.CComboBox; -import org.compiere.swing.CFrame; -import org.compiere.swing.CLabel; -import org.compiere.swing.CPanel; -import org.compiere.util.AdempiereSystemError; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.Msg; -import org.compiere.util.Util; - -/** - * Dialog to Start process. - * Displays information about the process - * and lets the user decide to start it - * and displays results (optionally print them). - * Calls ProcessCtl to execute. - * - * @author Jorg Janke - * @version $Id: ProcessDialog.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ - * @author Low Heng Sin - * - Merge process parameter dialog into process dialog. - * @author arboleda - globalqss - * - Implement ShowHelp option on processes and reports - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - *
  • BF [ 1893525 ] ProcessDialog: Cannot select the text from text field +/****************************************************************************** + * 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.compiere.apps; + +import static org.compiere.model.SystemIDs.PROCESS_C_INVOICE_GENERATE; +import static org.compiere.model.SystemIDs.PROCESS_M_INOUT_GENERATE; + +import java.awt.AWTEvent; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GraphicsConfiguration; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.logging.Level; + +import javax.swing.DefaultComboBoxModel; +import javax.swing.ImageIcon; +import javax.swing.JEditorPane; +import javax.swing.JOptionPane; +import javax.swing.JScrollPane; +import javax.swing.JSeparator; + +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.exceptions.DBException; +import org.adempiere.util.Callback; +import org.adempiere.util.IProcessUI; +import org.compiere.model.MPInstance; +import org.compiere.model.MPInstancePara; +import org.compiere.model.MProcess; +import org.compiere.print.ReportCtl; +import org.compiere.print.ReportEngine; +import org.compiere.process.ProcessInfo; +import org.compiere.process.ProcessInfoUtil; +import org.compiere.swing.CButton; +import org.compiere.swing.CComboBox; +import org.compiere.swing.CFrame; +import org.compiere.swing.CLabel; +import org.compiere.swing.CPanel; +import org.compiere.util.AdempiereSystemError; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Msg; +import org.compiere.util.Util; + +/** + * Dialog to Start process. + * Displays information about the process + * and lets the user decide to start it + * and displays results (optionally print them). + * Calls ProcessCtl to execute. + * + * @author Jorg Janke + * @version $Id: ProcessDialog.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + * @author Low Heng Sin + * - Merge process parameter dialog into process dialog. + * @author arboleda - globalqss + * - Implement ShowHelp option on processes and reports + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1893525 ] ProcessDialog: Cannot select the text from text field *
  • BF [ 1963128 ] Running a process w/o trl should display an error */ -public class ProcessDialog extends CFrame - implements ActionListener, IProcessUI -{ - /** - * - */ - private static final long serialVersionUID = 2435351857958558386L; - - /** - * @deprecated - * Dialog to start Process - * - * @param AD_Process_ID process - * @param isSOTrx is sales trx - */ - public ProcessDialog (int AD_Process_ID, boolean isSOTrx) - { - this(null, AD_Process_ID, isSOTrx); - - } // ProcessDialog - - /** - * Dialog to start Process - * - * @param gc - * @param AD_Process_ID process - * @param isSOTrx is sales trx - */ - public ProcessDialog (GraphicsConfiguration gc, int AD_Process_ID, boolean isSOTrx) - { - super(gc); - if (log.isLoggable(Level.INFO)) log.info("Process=" + AD_Process_ID + "; SOTrx=" + isSOTrx); - enableEvents(AWTEvent.WINDOW_EVENT_MASK); - m_AD_Process_ID = AD_Process_ID; - m_WindowNo = AEnv.createWindowNo (this); - Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", isSOTrx ? "Y" : "N"); - try - { - jbInit(); - } - catch(Exception ex) - { - log.log(Level.SEVERE, "", ex); - } - } // ProcessDialog - - private int m_AD_Process_ID; - private int m_WindowNo; - private String m_Name = null; - private boolean m_IsReport = false; - private int[] m_ids = null; - private boolean m_isLocked = false; - private StringBuffer m_messageText = new StringBuffer(); - private String m_ShowHelp = null; // Determine if a Help Process Window is shown - /** Logger */ - private static CLogger log = CLogger.getCLogger(ProcessDialog.class); - // - - private CPanel dialog = new CPanel() - { - /** - * - */ - private static final long serialVersionUID = 428410337428677817L; - - public Dimension getPreferredSize() { - Dimension d = super.getPreferredSize(); - Dimension m = getMinimumSize(); - if ( d.height < m.height || d.width < m.width ) { - Dimension d1 = new Dimension(); - d1.height = Math.max(d.height, m.height); - d1.width = Math.max(d.width, m.width); - return d1; - } else - return d; - } - }; - private BorderLayout mainLayout = new BorderLayout(); - private CPanel southPanel = new CPanel(); - private CButton bOK = ConfirmPanel.createOKButton(true); - private FlowLayout southLayout = new FlowLayout(); - private JEditorPane message = new JEditorPane() - { - /** - * - */ - private static final long serialVersionUID = -2271852928089812014L; - - public Dimension getPreferredSize() { - Dimension d = super.getPreferredSize(); - Dimension m = getMaximumSize(); - if ( d.height > m.height || d.width > m.width ) { - Dimension d1 = new Dimension(); - d1.height = Math.min(d.height, m.height); - d1.width = Math.min(d.width, m.width); - return d1; - } else - return d; - } - }; - private JScrollPane messagePane = new JScrollPane(message) - { - /** - * - */ - private static final long serialVersionUID = 3605316311642118445L; - - public Dimension getPreferredSize() { - Dimension d = super.getPreferredSize(); - Dimension m = getMaximumSize(); - if ( d.height > m.height || d.width > m.width ) { - Dimension d1 = new Dimension(); - d1.height = Math.min(d.height, m.height); - d1.width = Math.min(d.width, m.width); - return d1; - } else - return d; - } - }; - private CButton bPrint = ConfirmPanel.createPrintButton(true); - - private CPanel centerPanel = null; - private ProcessParameterPanel parameterPanel = null; - private JSeparator separator = new JSeparator(); - private ProcessInfo m_pi = null; - private CComboBoxfSavedName = new CComboBox(); - private CButton bSave = new CButton(); - private CButton bDelete = new CButton(); - private List savedParams; - private CLabel lSaved = new CLabel(Msg.getMsg(Env.getCtx(), "SavedParameter")); - - /** - * Static Layout - * @throws Exception - */ - private void jbInit() throws Exception - { - setIconImage(Env.getImage("mProcess.png")); - // - dialog.setLayout(mainLayout); - dialog.setMinimumSize(new Dimension(500, 200)); - bOK.addActionListener(this); - bPrint.addActionListener(this); - fSavedName.setToolTipText (Msg.getMsg(Env.getCtx(),"SavedParameter")); - fSavedName.setEditable(true); - fSavedName.addActionListener(this); - bSave.setIcon(new ImageIcon(org.compiere.Adempiere.class.getResource("images/Save24.gif"))); - bSave.setMargin(new Insets(2, 2, 2, 2)); - bSave.setToolTipText(Msg.getMsg(Env.getCtx(),"Save")); - bSave.addActionListener(this); - bSave.setEnabled(false); - bDelete.setIcon(new ImageIcon(org.compiere.Adempiere.class.getResource("images/Delete24.gif"))); - bDelete.setMargin(new Insets(2, 2, 2, 2)); - bDelete.setToolTipText(Msg.getMsg(Env.getCtx(),"Delete")); - bDelete.addActionListener(this); - bDelete.setEnabled(false); - // - southPanel.setLayout(southLayout); - southLayout.setAlignment(FlowLayout.RIGHT); - message.setContentType("text/html"); - message.setEditable(false); - message.setBackground(Color.white); - message.setFocusable(true); - getContentPane().add(dialog); - dialog.add(southPanel, BorderLayout.SOUTH); - - southPanel.add(lSaved,"wrap"); - southPanel.add(fSavedName, "w :200:"); - southPanel.add(bSave, null); - southPanel.add(bDelete, null); - southPanel.add(bPrint, "span, split 2, align right, pushx"); - southPanel.add(bOK, null); - dialog.add(messagePane, BorderLayout.NORTH); - messagePane.setBorder(null); - messagePane.setMaximumSize(new Dimension(600, 300)); - centerPanel = new CPanel(); - centerPanel.setBorder(null); - centerPanel.setLayout(new BorderLayout()); - dialog.add(centerPanel, BorderLayout.CENTER); - mainLayout.setVgap(2); - // - this.getRootPane().setDefaultButton(bOK); - } // jbInit - - /** - * Set Visible - * (set focus to OK if visible) - * @param visible true if visible - */ - public void setVisible (boolean visible) - { - super.setVisible(visible); - if (visible) { - bOK.requestFocus(); - } - } // setVisible - - /** - * Dispose - */ - public void dispose() - { - Env.clearWinContext(m_WindowNo); - super.dispose(); - } // dispose - - - /** - * Dynamic Init - * @return true, if there is something to process (start from menu) - */ - public boolean init() - { - log.config(""); - // - boolean trl = !Env.isBaseLanguage(Env.getCtx(), "AD_Process"); - String sql = "SELECT Name, Description, Help, IsReport, ShowHelp " - + "FROM AD_Process " - + "WHERE AD_Process_ID=?"; - if (trl) - sql = "SELECT t.Name, t.Description, t.Help, p.IsReport, p.ShowHelp " - + "FROM AD_Process p, AD_Process_Trl t " - + "WHERE p.AD_Process_ID=t.AD_Process_ID" - + " AND p.AD_Process_ID=? AND t.AD_Language=?"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, m_AD_Process_ID); - if (trl) - pstmt.setString(2, Env.getAD_Language(Env.getCtx())); - rs = pstmt.executeQuery(); - if (rs.next()) - { - m_Name = rs.getString(1); - m_IsReport = rs.getString(4).equals("Y"); - m_ShowHelp = rs.getString(5); - // - m_messageText.append(""); - String s = rs.getString(2); // Description - if (rs.wasNull()) - m_messageText.append(Msg.getMsg(Env.getCtx(), "StartProcess?")); - else - m_messageText.append(s); - m_messageText.append(""); - s = rs.getString(3); // Help - if (!rs.wasNull()) - m_messageText.append("

    ").append(s).append("

    "); - } - } - catch (SQLException e) - { - throw new DBException(e, sql); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - - if (m_Name == null) { - throw new AdempiereException("@NotFound@ @AD_Process_ID@="+m_AD_Process_ID+". @CheckMissingTrl@"); - } - // - this.setTitle(m_Name); - message.setText(m_messageText.toString()); - bOK.setText(Msg.getMsg(Env.getCtx(), "Start")); - - // Similar to APanel.actionButton - m_pi = new ProcessInfo(m_Name, m_AD_Process_ID); - m_pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx())); - m_pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx())); - parameterPanel = new ProcessParameterPanel(m_WindowNo, m_pi); - parameterPanel.setWindow(this); - centerPanel.removeAll(); - if (parameterPanel.init()) { - // hasfields - centerPanel.add(separator, BorderLayout.NORTH); - centerPanel.add(parameterPanel, BorderLayout.CENTER); - } else { - if (m_ShowHelp != null && MProcess.SHOWHELP_DonTShowHelp.equals(m_ShowHelp)) { - bOK.doClick(); // don't ask first click - // anyway show resulting window - } - } - - // Check if the process is a silent one - if(m_ShowHelp != null && MProcess.SHOWHELP_RunSilently_TakeDefaults.equals(m_ShowHelp)) - bOK.doClick(); - - querySaved(); - - dialog.revalidate(); - return true; - } // init - - private void querySaved() { - //user query - savedParams = MPInstance.get(Env.getCtx(), m_AD_Process_ID, Env.getContextAsInt(Env.getCtx(), "#AD_User_ID")); - String[] queries = new String[savedParams.size()+1]; - int i = 0; - queries[i++] = ""; - for (MPInstance instance : savedParams) - { - queries[i++] = instance.getName(); - } - fSavedName.setModel(new DefaultComboBoxModel(queries)); - fSavedName.setValue(""); - } - - /** - * ActionListener (Start) - * @param e ActionEvent - */ - public void actionPerformed (ActionEvent e) - { - - String saveName = null; - if (fSavedName.getSelectedItem() != null) - saveName = fSavedName.getSelectedItem().toString(); - - boolean lastRun = ("** " + Msg.getMsg(Env.getCtx(), "LastRun") + " **").equals(saveName); - - if (e.getSource() == bOK) - { - if (bOK.getText().length() == 0) - dispose(); - else - { - // Trx trx = Trx.get(Trx.createTrxName("ProcessDialog"), true); - ProcessCtl.process(this, m_WindowNo, parameterPanel, m_pi, null); - } - } - else if (e.getSource() == fSavedName) - { - if (savedParams != null && saveName != null) - { - for (int i = 0; i < savedParams.size(); i++) - { - if (savedParams.get(i).getName().equals(saveName)) - { - loadSavedParams(savedParams.get(i)); - } - } - } - boolean enabled = !Util.isEmpty(saveName); - bSave.setEnabled(enabled && !lastRun); - bDelete.setEnabled(enabled && fSavedName.getSelectedIndex() > -1 && !lastRun); - } - else if (e.getSource() == bSave && fSavedName != null && !lastRun) - { - // Update existing - if (fSavedName.getSelectedIndex() > -1 && savedParams != null) - { - for (int i = 0; i < savedParams.size(); i++) - { - if (savedParams.get(i).getName().equals(saveName)) - { - m_pi.setAD_PInstance_ID(savedParams.get(i).getAD_PInstance_ID()); - for (MPInstancePara para : savedParams.get(i).getParameters()) - { - para.deleteEx(true); - } - parameterPanel.saveParameters(); - } - } - } - // create new - else { - MPInstance instance = null; - try - { - instance = new MPInstance(Env.getCtx(), m_pi.getAD_Process_ID(), m_pi.getRecord_ID()); - instance.setName(saveName); - instance.saveEx(); - - m_pi.setAD_PInstance_ID(instance.getAD_PInstance_ID()); - // Get Parameters - if (parameterPanel != null) { - if (!parameterPanel.saveParameters()) - { - throw new AdempiereSystemError(Msg.getMsg(Env.getCtx(), "SaveParameterError")); - } - } - } - catch (Exception ex) - { - ADialog.warn(m_WindowNo, this, ex.getLocalizedMessage()); - } - } - querySaved(); - fSavedName.setSelectedItem(saveName); - } - else if (e.getSource() == bDelete && fSavedName != null && !lastRun ) - { - Object o = fSavedName.getSelectedItem(); - if (savedParams != null && o != null) - { - String selected = o.toString(); - for (int i = 0; i < savedParams.size(); i++) - { - if (savedParams.get(i).getName().equals(selected)) - { - savedParams.get(i).deleteEx(true); - } - } - } - querySaved(); - } - - else if (e.getSource() == bPrint) - printScreen(); - } // actionPerformed - - - private void loadSavedParams(MPInstance instance) { - parameterPanel.loadParameters(instance); - } - - /** - * Lock User Interface - * Called from the Worker before processing - * @param pi process info - */ - public void lockUI (ProcessInfo pi) - { - bOK.setText(""); - bOK.setEnabled(false); - this.setEnabled(false); - m_isLocked = true; - } // lockUI - - /** - * Unlock User Interface. - * Called from the Worker when processing is done - * @param pi process info - */ - public void unlockUI (ProcessInfo pi) - { - ProcessInfoUtil.setLogFromDB(pi); - m_messageText.append("

    ** ") - .append(pi.getSummary()) - .append("

    "); - m_messageText.append(pi.getLogInfo(true)); - message.setText(m_messageText.toString()); - message.setCaretPosition(message.getDocument().getLength()); // scroll down - m_ids = pi.getIDs(); - // - bOK.setEnabled(true); - this.setEnabled(true); - m_isLocked = false; - - //no longer needed, hide to give more space to display log - dialog.remove(centerPanel); - messagePane.setMaximumSize(null); - dialog.remove(messagePane); - dialog.add(messagePane, BorderLayout.CENTER); - - this.validate(); - AEnv.showCenterScreen(this); - // - afterProcessTask(); - // Close automatically - if (m_IsReport && !pi.isError()) - bOK.doClick(); - - // If the process is a silent one and no errors occurred, close the dialog - if(m_ShowHelp != null && MProcess.SHOWHELP_RunSilently_TakeDefaults.equals(m_ShowHelp)) - bOK.doClick(); - } // unlockUI - - /** - * Is the UI locked (Internal method) - * @return true, if UI is locked - */ - public boolean isUILocked() - { - return m_isLocked; - } // isUILocked - - /** - * Method to be executed async. - * Called from the ASyncProcess worker - * @param pi process info - */ - public void executeASync (ProcessInfo pi) - { - log.config("-"); - } // executeASync - - - /************************************************************************** - * Optional Processing Task - */ - private void afterProcessTask() - { - // something to do? - if (m_ids != null && m_ids.length > 0) - { - log.config(""); - // Print invoices - if (m_AD_Process_ID == PROCESS_C_INVOICE_GENERATE) - printInvoices(); - else if (m_AD_Process_ID == PROCESS_M_INOUT_GENERATE) - printShipments(); - } - - } // afterProcessTask - - - /************************************************************************** - * Print Shipments - */ - private void printShipments() - { - if (m_ids == null) - return; - if (!ADialog.ask(m_WindowNo, this, "PrintShipments")) - return; - m_messageText.append("

    ").append(Msg.getMsg(Env.getCtx(), "PrintShipments")).append("

    "); - message.setText(m_messageText.toString()); - int retValue = ADialogDialog.A_CANCEL; - do - { - // Loop through all items - for (int i = 0; i < m_ids.length; i++) - { - int M_InOut_ID = m_ids[i]; - ReportCtl.startDocumentPrint(ReportEngine.SHIPMENT, M_InOut_ID, this, AEnv.getWindowNo(this), true); - } - ADialogDialog d = new ADialogDialog (this, - Env.getHeader(Env.getCtx(), m_WindowNo), - Msg.getMsg(Env.getCtx(), "PrintoutOK?"), - JOptionPane.QUESTION_MESSAGE); - retValue = d.getReturnCode(); - } - while (retValue == ADialogDialog.A_CANCEL); - } // printInvoices - - /** - * Print Invoices - */ - private void printInvoices() - { - if (m_ids == null) - return; - if (!ADialog.ask(m_WindowNo, this, "PrintInvoices")) - return; - m_messageText.append("

    ").append(Msg.getMsg(Env.getCtx(), "PrintInvoices")).append("

    "); - message.setText(m_messageText.toString()); - int retValue = ADialogDialog.A_CANCEL; - do - { - // Loop through all items - for (int i = 0; i < m_ids.length; i++) - { - int AD_Invoice_ID = m_ids[i]; - ReportCtl.startDocumentPrint(ReportEngine.INVOICE, AD_Invoice_ID, this, AEnv.getWindowNo(this), true); - } - ADialogDialog d = new ADialogDialog (this, - Env.getHeader(Env.getCtx(), m_WindowNo), - Msg.getMsg(Env.getCtx(), "PrintoutOK?"), - JOptionPane.QUESTION_MESSAGE); - retValue = d.getReturnCode(); - } - while (retValue == ADialogDialog.A_CANCEL); - } // printInvoices - - /** - * Print Screen - */ - private void printScreen() - { - PrintScreenPainter.printScreen (this); - } // printScreen - - @Override - public void statusUpdate(String status) { - message.setText(status); - } - - @Override - public void ask(String message, Callback callback) { - boolean b = ADialog.ask(m_WindowNo, this, message); - if (callback != null) { - callback.onCallback(b); - } - } - - @Override - public void download(File file) { - // TODO Auto-generated method stub - - } - - @Override - public void askForInput(String message, Callback callback) { - String s = ADialog.askForInput(m_WindowNo, this, message); - if(callback != null) - callback.onCallback(s); - } - -} // ProcessDialog +public class ProcessDialog extends CFrame + implements ActionListener, IProcessUI +{ + /** + * + */ + private static final long serialVersionUID = 2435351857958558386L; + + /** + * @deprecated + * Dialog to start Process + * + * @param AD_Process_ID process + * @param isSOTrx is sales trx + */ + public ProcessDialog (int AD_Process_ID, boolean isSOTrx) + { + this(null, AD_Process_ID, isSOTrx); + + } // ProcessDialog + + /** + * Dialog to start Process + * + * @param gc + * @param AD_Process_ID process + * @param isSOTrx is sales trx + */ + public ProcessDialog (GraphicsConfiguration gc, int AD_Process_ID, boolean isSOTrx) + { + super(gc); + if (log.isLoggable(Level.INFO)) log.info("Process=" + AD_Process_ID + "; SOTrx=" + isSOTrx); + enableEvents(AWTEvent.WINDOW_EVENT_MASK); + m_AD_Process_ID = AD_Process_ID; + m_WindowNo = AEnv.createWindowNo (this); + Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", isSOTrx ? "Y" : "N"); + try + { + jbInit(); + } + catch(Exception ex) + { + log.log(Level.SEVERE, "", ex); + } + } // ProcessDialog + + private int m_AD_Process_ID; + private int m_WindowNo; + private String m_Name = null; + private boolean m_IsReport = false; + private int[] m_ids = null; + private boolean m_isLocked = false; + private StringBuffer m_messageText = new StringBuffer(); + private String m_ShowHelp = null; // Determine if a Help Process Window is shown + /** Logger */ + private static CLogger log = CLogger.getCLogger(ProcessDialog.class); + // + + private CPanel dialog = new CPanel() + { + /** + * + */ + private static final long serialVersionUID = 428410337428677817L; + + public Dimension getPreferredSize() { + Dimension d = super.getPreferredSize(); + Dimension m = getMinimumSize(); + if ( d.height < m.height || d.width < m.width ) { + Dimension d1 = new Dimension(); + d1.height = Math.max(d.height, m.height); + d1.width = Math.max(d.width, m.width); + return d1; + } else + return d; + } + }; + private BorderLayout mainLayout = new BorderLayout(); + private CPanel southPanel = new CPanel(); + private CButton bOK = ConfirmPanel.createOKButton(true); + private FlowLayout southLayout = new FlowLayout(); + private JEditorPane message = new JEditorPane() + { + /** + * + */ + private static final long serialVersionUID = -2271852928089812014L; + + public Dimension getPreferredSize() { + Dimension d = super.getPreferredSize(); + Dimension m = getMaximumSize(); + if ( d.height > m.height || d.width > m.width ) { + Dimension d1 = new Dimension(); + d1.height = Math.min(d.height, m.height); + d1.width = Math.min(d.width, m.width); + return d1; + } else + return d; + } + }; + private JScrollPane messagePane = new JScrollPane(message) + { + /** + * + */ + private static final long serialVersionUID = 3605316311642118445L; + + public Dimension getPreferredSize() { + Dimension d = super.getPreferredSize(); + Dimension m = getMaximumSize(); + if ( d.height > m.height || d.width > m.width ) { + Dimension d1 = new Dimension(); + d1.height = Math.min(d.height, m.height); + d1.width = Math.min(d.width, m.width); + return d1; + } else + return d; + } + }; + private CButton bPrint = ConfirmPanel.createPrintButton(true); + + private CPanel centerPanel = null; + private ProcessParameterPanel parameterPanel = null; + private JSeparator separator = new JSeparator(); + private ProcessInfo m_pi = null; + private CComboBoxfSavedName = new CComboBox(); + private CButton bSave = new CButton(); + private CButton bDelete = new CButton(); + private List savedParams; + private CLabel lSaved = new CLabel(Msg.getMsg(Env.getCtx(), "SavedParameter")); + + /** + * Static Layout + * @throws Exception + */ + private void jbInit() throws Exception + { + setIconImage(Env.getImage("mProcess.png")); + // + dialog.setLayout(mainLayout); + dialog.setMinimumSize(new Dimension(500, 200)); + bOK.addActionListener(this); + bPrint.addActionListener(this); + fSavedName.setToolTipText (Msg.getMsg(Env.getCtx(),"SavedParameter")); + fSavedName.setEditable(true); + fSavedName.addActionListener(this); + bSave.setIcon(new ImageIcon(org.compiere.Adempiere.class.getResource("images/Save24.gif"))); + bSave.setMargin(new Insets(2, 2, 2, 2)); + bSave.setToolTipText(Msg.getMsg(Env.getCtx(),"Save")); + bSave.addActionListener(this); + bSave.setEnabled(false); + bDelete.setIcon(new ImageIcon(org.compiere.Adempiere.class.getResource("images/Delete24.gif"))); + bDelete.setMargin(new Insets(2, 2, 2, 2)); + bDelete.setToolTipText(Msg.getMsg(Env.getCtx(),"Delete")); + bDelete.addActionListener(this); + bDelete.setEnabled(false); + // + southPanel.setLayout(southLayout); + southLayout.setAlignment(FlowLayout.RIGHT); + message.setContentType("text/html"); + message.setEditable(false); + message.setBackground(Color.white); + message.setFocusable(true); + getContentPane().add(dialog); + dialog.add(southPanel, BorderLayout.SOUTH); + + southPanel.add(lSaved,"wrap"); + southPanel.add(fSavedName, "w :200:"); + southPanel.add(bSave, null); + southPanel.add(bDelete, null); + southPanel.add(bPrint, "span, split 2, align right, pushx"); + southPanel.add(bOK, null); + dialog.add(messagePane, BorderLayout.NORTH); + messagePane.setBorder(null); + messagePane.setMaximumSize(new Dimension(600, 300)); + centerPanel = new CPanel(); + centerPanel.setBorder(null); + centerPanel.setLayout(new BorderLayout()); + dialog.add(centerPanel, BorderLayout.CENTER); + mainLayout.setVgap(2); + // + this.getRootPane().setDefaultButton(bOK); + } // jbInit + + /** + * Set Visible + * (set focus to OK if visible) + * @param visible true if visible + */ + public void setVisible (boolean visible) + { + super.setVisible(visible); + if (visible) { + bOK.requestFocus(); + } + } // setVisible + + /** + * Dispose + */ + public void dispose() + { + Env.clearWinContext(m_WindowNo); + super.dispose(); + } // dispose + + + /** + * Dynamic Init + * @return true, if there is something to process (start from menu) + */ + public boolean init() + { + log.config(""); + // + boolean trl = !Env.isBaseLanguage(Env.getCtx(), "AD_Process"); + String sql = "SELECT Name, Description, Help, IsReport, ShowHelp " + + "FROM AD_Process " + + "WHERE AD_Process_ID=?"; + if (trl) + sql = "SELECT t.Name, t.Description, t.Help, p.IsReport, p.ShowHelp " + + "FROM AD_Process p, AD_Process_Trl t " + + "WHERE p.AD_Process_ID=t.AD_Process_ID" + + " AND p.AD_Process_ID=? AND t.AD_Language=?"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, m_AD_Process_ID); + if (trl) + pstmt.setString(2, Env.getAD_Language(Env.getCtx())); + rs = pstmt.executeQuery(); + if (rs.next()) + { + m_Name = rs.getString(1); + m_IsReport = rs.getString(4).equals("Y"); + m_ShowHelp = rs.getString(5); + // + m_messageText.append(""); + String s = rs.getString(2); // Description + if (rs.wasNull()) + m_messageText.append(Msg.getMsg(Env.getCtx(), "StartProcess?")); + else + m_messageText.append(s); + m_messageText.append(""); + s = rs.getString(3); // Help + if (!rs.wasNull()) + m_messageText.append("

    ").append(s).append("

    "); + } + } + catch (SQLException e) + { + throw new DBException(e, sql); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + + if (m_Name == null) { + throw new AdempiereException("@NotFound@ @AD_Process_ID@="+m_AD_Process_ID+". @CheckMissingTrl@"); + } + // + this.setTitle(m_Name); + message.setText(m_messageText.toString()); + bOK.setText(Msg.getMsg(Env.getCtx(), "Start")); + + // Similar to APanel.actionButton + m_pi = new ProcessInfo(m_Name, m_AD_Process_ID); + m_pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx())); + m_pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx())); + parameterPanel = new ProcessParameterPanel(m_WindowNo, m_pi); + parameterPanel.setWindow(this); + centerPanel.removeAll(); + if (parameterPanel.init()) { + // hasfields + centerPanel.add(separator, BorderLayout.NORTH); + centerPanel.add(parameterPanel, BorderLayout.CENTER); + } else { + if (m_ShowHelp != null && MProcess.SHOWHELP_DonTShowHelp.equals(m_ShowHelp)) { + bOK.doClick(); // don't ask first click + // anyway show resulting window + } + } + + // Check if the process is a silent one + if(m_ShowHelp != null && MProcess.SHOWHELP_RunSilently_TakeDefaults.equals(m_ShowHelp)) + bOK.doClick(); + + querySaved(); + + dialog.revalidate(); + return true; + } // init + + private void querySaved() { + //user query + savedParams = MPInstance.get(Env.getCtx(), m_AD_Process_ID, Env.getContextAsInt(Env.getCtx(), "#AD_User_ID")); + String[] queries = new String[savedParams.size()+1]; + int i = 0; + queries[i++] = ""; + for (MPInstance instance : savedParams) + { + queries[i++] = instance.getName(); + } + fSavedName.setModel(new DefaultComboBoxModel(queries)); + fSavedName.setValue(""); + } + + /** + * ActionListener (Start) + * @param e ActionEvent + */ + public void actionPerformed (ActionEvent e) + { + + String saveName = null; + if (fSavedName.getSelectedItem() != null) + saveName = fSavedName.getSelectedItem().toString(); + + boolean lastRun = ("** " + Msg.getMsg(Env.getCtx(), "LastRun") + " **").equals(saveName); + + if (e.getSource() == bOK) + { + if (bOK.getText().length() == 0) + dispose(); + else + { + // Trx trx = Trx.get(Trx.createTrxName("ProcessDialog"), true); + ProcessCtl.process(this, m_WindowNo, parameterPanel, m_pi, null); + } + } + else if (e.getSource() == fSavedName) + { + if (savedParams != null && saveName != null) + { + for (int i = 0; i < savedParams.size(); i++) + { + if (savedParams.get(i).getName().equals(saveName)) + { + loadSavedParams(savedParams.get(i)); + } + } + } + boolean enabled = !Util.isEmpty(saveName); + bSave.setEnabled(enabled && !lastRun); + bDelete.setEnabled(enabled && fSavedName.getSelectedIndex() > -1 && !lastRun); + } + else if (e.getSource() == bSave && fSavedName != null && !lastRun) + { + // Update existing + if (fSavedName.getSelectedIndex() > -1 && savedParams != null) + { + for (int i = 0; i < savedParams.size(); i++) + { + if (savedParams.get(i).getName().equals(saveName)) + { + m_pi.setAD_PInstance_ID(savedParams.get(i).getAD_PInstance_ID()); + for (MPInstancePara para : savedParams.get(i).getParameters()) + { + para.deleteEx(true); + } + parameterPanel.saveParameters(); + } + } + } + // create new + else { + MPInstance instance = null; + try + { + instance = new MPInstance(Env.getCtx(), m_pi.getAD_Process_ID(), m_pi.getRecord_ID()); + instance.setName(saveName); + instance.saveEx(); + + m_pi.setAD_PInstance_ID(instance.getAD_PInstance_ID()); + // Get Parameters + if (parameterPanel != null) { + if (!parameterPanel.saveParameters()) + { + throw new AdempiereSystemError(Msg.getMsg(Env.getCtx(), "SaveParameterError")); + } + } + } + catch (Exception ex) + { + ADialog.warn(m_WindowNo, this, ex.getLocalizedMessage()); + } + } + querySaved(); + fSavedName.setSelectedItem(saveName); + } + else if (e.getSource() == bDelete && fSavedName != null && !lastRun ) + { + Object o = fSavedName.getSelectedItem(); + if (savedParams != null && o != null) + { + String selected = o.toString(); + for (int i = 0; i < savedParams.size(); i++) + { + if (savedParams.get(i).getName().equals(selected)) + { + savedParams.get(i).deleteEx(true); + } + } + } + querySaved(); + } + + else if (e.getSource() == bPrint) + printScreen(); + } // actionPerformed + + + private void loadSavedParams(MPInstance instance) { + parameterPanel.loadParameters(instance); + } + + /** + * Lock User Interface + * Called from the Worker before processing + * @param pi process info + */ + public void lockUI (ProcessInfo pi) + { + bOK.setText(""); + bOK.setEnabled(false); + this.setEnabled(false); + m_isLocked = true; + } // lockUI + + /** + * Unlock User Interface. + * Called from the Worker when processing is done + * @param pi process info + */ + public void unlockUI (ProcessInfo pi) + { + ProcessInfoUtil.setLogFromDB(pi); + m_messageText.append("

    ** ") + .append(pi.getSummary()) + .append("

    "); + m_messageText.append(pi.getLogInfo(true)); + message.setText(m_messageText.toString()); + message.setCaretPosition(message.getDocument().getLength()); // scroll down + m_ids = pi.getIDs(); + // + bOK.setEnabled(true); + this.setEnabled(true); + m_isLocked = false; + + //no longer needed, hide to give more space to display log + dialog.remove(centerPanel); + messagePane.setMaximumSize(null); + dialog.remove(messagePane); + dialog.add(messagePane, BorderLayout.CENTER); + + this.validate(); + AEnv.showCenterScreen(this); + // + afterProcessTask(); + // Close automatically + if (m_IsReport && !pi.isError()) + bOK.doClick(); + + // If the process is a silent one and no errors occurred, close the dialog + if(m_ShowHelp != null && MProcess.SHOWHELP_RunSilently_TakeDefaults.equals(m_ShowHelp)) + bOK.doClick(); + } // unlockUI + + /** + * Is the UI locked (Internal method) + * @return true, if UI is locked + */ + public boolean isUILocked() + { + return m_isLocked; + } // isUILocked + + /** + * Method to be executed async. + * Called from the ASyncProcess worker + * @param pi process info + */ + public void executeASync (ProcessInfo pi) + { + log.config("-"); + } // executeASync + + + /************************************************************************** + * Optional Processing Task + */ + private void afterProcessTask() + { + // something to do? + if (m_ids != null && m_ids.length > 0) + { + log.config(""); + // Print invoices + if (m_AD_Process_ID == PROCESS_C_INVOICE_GENERATE) + printInvoices(); + else if (m_AD_Process_ID == PROCESS_M_INOUT_GENERATE) + printShipments(); + } + + } // afterProcessTask + + + /************************************************************************** + * Print Shipments + */ + private void printShipments() + { + if (m_ids == null) + return; + if (!ADialog.ask(m_WindowNo, this, "PrintShipments")) + return; + m_messageText.append("

    ").append(Msg.getMsg(Env.getCtx(), "PrintShipments")).append("

    "); + message.setText(m_messageText.toString()); + int retValue = ADialogDialog.A_CANCEL; + do + { + // Loop through all items + for (int i = 0; i < m_ids.length; i++) + { + int M_InOut_ID = m_ids[i]; + ReportCtl.startDocumentPrint(ReportEngine.SHIPMENT, M_InOut_ID, this, AEnv.getWindowNo(this), true); + } + ADialogDialog d = new ADialogDialog (this, + Env.getHeader(Env.getCtx(), m_WindowNo), + Msg.getMsg(Env.getCtx(), "PrintoutOK?"), + JOptionPane.QUESTION_MESSAGE); + retValue = d.getReturnCode(); + } + while (retValue == ADialogDialog.A_CANCEL); + } // printInvoices + + /** + * Print Invoices + */ + private void printInvoices() + { + if (m_ids == null) + return; + if (!ADialog.ask(m_WindowNo, this, "PrintInvoices")) + return; + m_messageText.append("

    ").append(Msg.getMsg(Env.getCtx(), "PrintInvoices")).append("

    "); + message.setText(m_messageText.toString()); + int retValue = ADialogDialog.A_CANCEL; + do + { + // Loop through all items + for (int i = 0; i < m_ids.length; i++) + { + int AD_Invoice_ID = m_ids[i]; + ReportCtl.startDocumentPrint(ReportEngine.INVOICE, AD_Invoice_ID, this, AEnv.getWindowNo(this), true); + } + ADialogDialog d = new ADialogDialog (this, + Env.getHeader(Env.getCtx(), m_WindowNo), + Msg.getMsg(Env.getCtx(), "PrintoutOK?"), + JOptionPane.QUESTION_MESSAGE); + retValue = d.getReturnCode(); + } + while (retValue == ADialogDialog.A_CANCEL); + } // printInvoices + + /** + * Print Screen + */ + private void printScreen() + { + PrintScreenPainter.printScreen (this); + } // printScreen + + @Override + public void statusUpdate(String status) { + message.setText(status); + } + + @Override + public void ask(String message, Callback callback) { + boolean b = ADialog.ask(m_WindowNo, this, message); + if (callback != null) { + callback.onCallback(b); + } + } + + @Override + public void download(File file) { + // TODO Auto-generated method stub + + } + + @Override + public void askForInput(String message, Callback callback) { + String s = ADialog.askForInput(m_WindowNo, this, message); + if(callback != null) + callback.onCallback(s); + } + +} // ProcessDialog diff --git a/org.adempiere.ui.swing/src/org/compiere/apps/form/FormFrame.java b/org.adempiere.ui.swing/src/org/compiere/apps/form/FormFrame.java index c02715d626..dd880d8502 100644 --- a/org.adempiere.ui.swing/src/org/compiere/apps/form/FormFrame.java +++ b/org.adempiere.ui.swing/src/org/compiere/apps/form/FormFrame.java @@ -1,446 +1,446 @@ -/****************************************************************************** - * 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.compiere.apps.form; - -import java.awt.Cursor; -import java.awt.GraphicsConfiguration; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Properties; -import java.util.logging.Level; - -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.KeyStroke; - -import org.adempiere.client.Client; -import org.compiere.apps.AEnv; -import org.compiere.apps.AGlassPane; -import org.compiere.apps.AMenu; -import org.compiere.apps.Help; -import org.compiere.apps.WindowMenu; -import org.compiere.model.GridTab; -import org.compiere.model.MRole; -import org.compiere.model.MUser; -import org.compiere.process.ProcessInfo; -import org.compiere.swing.CFrame; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.Trace; +/****************************************************************************** + * 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.compiere.apps.form; + +import java.awt.Cursor; +import java.awt.GraphicsConfiguration; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Properties; +import java.util.logging.Level; + +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.KeyStroke; + +import org.adempiere.client.Client; +import org.compiere.apps.AEnv; +import org.compiere.apps.AGlassPane; +import org.compiere.apps.AMenu; +import org.compiere.apps.Help; +import org.compiere.apps.WindowMenu; +import org.compiere.model.GridTab; +import org.compiere.model.MRole; +import org.compiere.model.MUser; +import org.compiere.process.ProcessInfo; +import org.compiere.swing.CFrame; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Trace; -/** - * Form Framework - * - * @author Jorg Janke - * @version $Id: FormFrame.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - * - * Colin Rooney 2007/03/20 RFE#1670185 & BUG#1684142 - * Extend security to Info Queries - */ -public class FormFrame extends CFrame - implements ActionListener -{ - /** - * - */ - private static final long serialVersionUID = 2559005548469735515L; - - /** - * @deprecated - * Create Form. - * Need to call openForm - */ - public FormFrame () - { - this(null); - } // FormFrame - - /** - * Create Form. - * Need to call openForm - * @param gc - */ - public FormFrame (GraphicsConfiguration gc) - { - super(gc); - addWindowListener(new java.awt.event.WindowAdapter() - { - public void windowOpened(java.awt.event.WindowEvent evt) - { - formWindowOpened(evt); - } - }); - - m_WindowNo = AEnv.createWindowNo (this); - setGlassPane(m_glassPane); - try - { - jbInit(); - createMenu(); - } - catch(Exception e) - { - log.log(Level.SEVERE, "", e); - } - } // FormFrame - +/** + * Form Framework + * + * @author Jorg Janke + * @version $Id: FormFrame.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ + * + * Colin Rooney 2007/03/20 RFE#1670185 & BUG#1684142 + * Extend security to Info Queries + */ +public class FormFrame extends CFrame + implements ActionListener +{ + /** + * + */ + private static final long serialVersionUID = 2559005548469735515L; + + /** + * @deprecated + * Create Form. + * Need to call openForm + */ + public FormFrame () + { + this(null); + } // FormFrame + + /** + * Create Form. + * Need to call openForm + * @param gc + */ + public FormFrame (GraphicsConfiguration gc) + { + super(gc); + addWindowListener(new java.awt.event.WindowAdapter() + { + public void windowOpened(java.awt.event.WindowEvent evt) + { + formWindowOpened(evt); + } + }); + + m_WindowNo = AEnv.createWindowNo (this); + setGlassPane(m_glassPane); + try + { + jbInit(); + createMenu(); + } + catch(Exception e) + { + log.log(Level.SEVERE, "", e); + } + } // FormFrame + private ProcessInfo m_pi; - /** WindowNo */ - private int m_WindowNo; - /** The GlassPane */ - private AGlassPane m_glassPane = new AGlassPane(); - /** Description */ - private String m_Description = null; - /** Help */ - private String m_Help = null; - /** Menu Bar */ - private JMenuBar menuBar = new JMenuBar(); - /** The Panel to be displayed */ - private FormPanel m_panel = null; - /** Maximize Window */ - public boolean m_maximize = false; - /** Logger */ - private static CLogger log = CLogger.getCLogger(FormFrame.class); - - /** Form ID */ - private int p_AD_Form_ID = 0; - - /** - * Static Init - * @throws Exception - */ - private void jbInit() throws Exception - { - this.setIconImage(org.compiere.Adempiere.getImage16()); - this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - this.setJMenuBar(menuBar); - } // jbInit - - /** - * Create Menu - */ - private void createMenu() - { - // File - JMenu mFile = AEnv.getMenu("File"); - menuBar.add(mFile); - AEnv.addMenuItem("PrintScreen", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, 0), mFile, this); - AEnv.addMenuItem("ScreenShot", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, ActionEvent.SHIFT_MASK), mFile, this); - AEnv.addMenuItem("Report", null, KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.ALT_MASK), mFile, this); - mFile.addSeparator(); - AEnv.addMenuItem("End", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK), mFile, this); - AEnv.addMenuItem("Exit", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.SHIFT_MASK+ActionEvent.ALT_MASK), mFile, this); - - // View - JMenu mView = AEnv.getMenu("View"); - menuBar.add(mView); - - if (MRole.getDefault().isAllow_Info_Product()) - { - AEnv.addMenuItem("InfoProduct", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK), mView, this); - } - if (MRole.getDefault().isAllow_Info_BPartner()) - { - AEnv.addMenuItem("InfoBPartner", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK+ActionEvent.CTRL_MASK), mView, this); - } - if (MRole.getDefault().isShowAcct() && MRole.getDefault().isAllow_Info_Account()) - { - AEnv.addMenuItem("InfoAccount", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK+ActionEvent.CTRL_MASK), mView, this); - } - if (MRole.getDefault().isAllow_Info_Schedule()) - { - AEnv.addMenuItem("InfoSchedule", null, null, mView, this); - } - mView.addSeparator(); - if (MRole.getDefault().isAllow_Info_Order()) - { - AEnv.addMenuItem("InfoOrder", "Info", null, mView, this); - } - if (MRole.getDefault().isAllow_Info_Invoice()) - { - AEnv.addMenuItem("InfoInvoice", "Info", null, mView, this); - } - if (MRole.getDefault().isAllow_Info_InOut()) - { - AEnv.addMenuItem("InfoInOut", "Info", null, mView, this); - } - if (MRole.getDefault().isAllow_Info_Payment()) - { - AEnv.addMenuItem("InfoPayment", "Info", null, mView, this); - } -// if (MRole.getDefault().isAllow_Info_CashJournal()) -// { -// AEnv.addMenuItem("InfoCashLine", "Info", null, mView, this); -// } - if (MRole.getDefault().isAllow_Info_Resource()) - { - AEnv.addMenuItem("InfoAssignment", "Info", null, mView, this); - } - if (MRole.getDefault().isAllow_Info_Asset()) - { - AEnv.addMenuItem("InfoAsset", "Info", null, mView, this); - } - // Tools - JMenu mTools = AEnv.getMenu("Tools"); - menuBar.add(mTools); - AEnv.addMenuItem("Calculator", null, null, mTools, this); - AEnv.addMenuItem("Calendar", null, null, mTools, this); - AEnv.addMenuItem("Editor", null, null, mTools, this); - MUser user = MUser.get(Env.getCtx()); - if (user.isAdministrator()) - AEnv.addMenuItem("Script", null, null, mTools, this); - if (MRole.getDefault().isShowPreference()) - { - mTools.addSeparator(); - AEnv.addMenuItem("Preference", null, null, mTools, this); - } - - // Window - AMenu aMenu = (AMenu)AEnv.getWindow(0); - JMenu mWindow = new WindowMenu(aMenu.getWindowManager(), this); - menuBar.add(mWindow); - - // Help - JMenu mHelp = AEnv.getMenu("Help"); - menuBar.add(mHelp); - AEnv.addMenuItem("Help", "Help", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), mHelp, this); - AEnv.addMenuItem("Online", null, null, mHelp, this); - AEnv.addMenuItem("EMailSupport", null, null, mHelp, this); - AEnv.addMenuItem("About", null, null, mHelp, this); - } // createMenu - - /** - * Dispose - */ - public void dispose() - { - log.config(""); - // recursive calls - if (Trace.isCalledFrom("JFrame") && m_panel != null) // [x] close window pressed - m_panel.dispose(); - m_panel = null; - Env.clearWinContext(m_WindowNo); - super.dispose(); - } // dispose - - /** - * Open Form - * @param AD_Form_ID form - * @return true if form opened - */ - public boolean openForm (int AD_Form_ID) - { - return openForm(AD_Form_ID, null); - } - - public boolean openForm (int AD_Form_ID, GridTab gridTab) - { - Properties ctx = Env.getCtx(); - // - String name = null; - String className = null; - String sql = "SELECT Name, Description, ClassName, Help FROM AD_Form WHERE AD_Form_ID=?"; - boolean trl = !Env.isBaseLanguage(ctx, "AD_Form"); - if (trl) - sql = "SELECT t.Name, t.Description, f.ClassName, t.Help " - + "FROM AD_Form f INNER JOIN AD_Form_Trl t" - + " ON (f.AD_Form_ID=t.AD_Form_ID AND AD_Language=?)" - + "WHERE f.AD_Form_ID=?"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement (sql, null); - if (trl) - { - pstmt.setString(1, Env.getAD_Language(ctx)); - pstmt.setInt(2, AD_Form_ID); - } - else - pstmt.setInt(1, AD_Form_ID); - rs = pstmt.executeQuery(); - if (rs.next()) - { - name = rs.getString(1); - m_Description = rs.getString(2); - className = rs.getString(3); - m_Help = rs.getString(4); - } - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - if (className == null) - return false; - // - return openForm(AD_Form_ID, className, name, gridTab); - } // openForm - - /** - * Open Form - * @param AD_Form_ID Form - * @param className class name - * @param name title - * @return true if started - */ - protected boolean openForm (int AD_Form_ID, String className, String name) - { - return openForm(AD_Form_ID, className, name, null); - } - - protected boolean openForm (int AD_Form_ID, String className, String name, GridTab gridTab) - { - if (log.isLoggable(Level.INFO)) log.info("AD_Form_ID=" + AD_Form_ID + " - Class=" + className); - Properties ctx = Env.getCtx(); - Env.setContext(ctx, m_WindowNo, "_WinInfo_WindowName", name); - setTitle(Env.getHeader(ctx, m_WindowNo)); - this.gridTab = gridTab; - - try - { - // Create instance w/o parameters - // Try equinox extension then java classpath - m_panel = Client.getFormPanel(className); - } - catch (Exception e) - { - log.log(Level.SEVERE, "Class=" + className + ", AD_Form_ID=" + AD_Form_ID, e); - return false; - } - // - m_panel.init(m_WindowNo, this); - p_AD_Form_ID = AD_Form_ID; - return true; - } // openForm - - /** - * Get Form Panel - * @return form panel - */ - public FormPanel getFormPanel() - { - return m_panel; - } // getFormPanel - - /** - * Action Listener - * @param e event - */ - public void actionPerformed(ActionEvent e) - { - String cmd = e.getActionCommand(); - if (cmd.equals("End")) - dispose(); - else if (cmd.equals("Help")) - actionHelp(); - else if (!AEnv.actionPerformed(cmd, m_WindowNo, this)) - log.log(Level.SEVERE, "Not handeled=" + cmd); - } // actionPerformed - - /** - * Show Help - */ - private void actionHelp() - { - StringBuilder sb = new StringBuilder(); - if (m_Description != null && m_Description.length() > 0) - sb.append("

    ").append(m_Description).append("

    "); - if (m_Help != null && m_Help.length() > 0) - sb.append("

    ").append(m_Help); - Help hlp = new Help (AEnv.getFrame(this), this.getTitle(), sb.toString()); - hlp.setVisible(true); - } // actionHelp - - - /************************************************************************* - * Set Window Busy - * @param busy busy - */ - public void setBusy (boolean busy) - { - if (busy == m_glassPane.isVisible()) - return; - if (log.isLoggable(Level.INFO)) log.info("Busy=" + busy); - if (busy) - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - else - setCursor(Cursor.getDefaultCursor()); - m_glassPane.setMessage(null); - m_glassPane.setVisible(busy); - m_glassPane.requestFocus(); - } // setBusy - - /** - * Set Busy Message - * @param AD_Message message - */ - public void setBusyMessage (String AD_Message) - { - m_glassPane.setMessage(AD_Message); - } // setBusyMessage - - /** - * Set and start Busy Counter - * @param time in seconds - */ - public void setBusyTimer (int time) - { - m_glassPane.setBusyTimer (time); - } // setBusyTimer - - - /** - * Set Maximize Window - * @param max maximize - */ - public void setMaximize (boolean max) - { - m_maximize = max; - } // setMaximize - - - /** - * Form Window Opened. - * Maximize window if required - * @param evt event - */ - private void formWindowOpened(java.awt.event.WindowEvent evt) - { - if (m_maximize == true) - { - super.setVisible(true); - super.setExtendedState(JFrame.MAXIMIZED_BOTH); - } - } // formWindowOpened - + /** WindowNo */ + private int m_WindowNo; + /** The GlassPane */ + private AGlassPane m_glassPane = new AGlassPane(); + /** Description */ + private String m_Description = null; + /** Help */ + private String m_Help = null; + /** Menu Bar */ + private JMenuBar menuBar = new JMenuBar(); + /** The Panel to be displayed */ + private FormPanel m_panel = null; + /** Maximize Window */ + public boolean m_maximize = false; + /** Logger */ + private static CLogger log = CLogger.getCLogger(FormFrame.class); + + /** Form ID */ + private int p_AD_Form_ID = 0; + + /** + * Static Init + * @throws Exception + */ + private void jbInit() throws Exception + { + this.setIconImage(org.compiere.Adempiere.getImage16()); + this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + this.setJMenuBar(menuBar); + } // jbInit + + /** + * Create Menu + */ + private void createMenu() + { + // File + JMenu mFile = AEnv.getMenu("File"); + menuBar.add(mFile); + AEnv.addMenuItem("PrintScreen", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, 0), mFile, this); + AEnv.addMenuItem("ScreenShot", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, ActionEvent.SHIFT_MASK), mFile, this); + AEnv.addMenuItem("Report", null, KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.ALT_MASK), mFile, this); + mFile.addSeparator(); + AEnv.addMenuItem("End", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK), mFile, this); + AEnv.addMenuItem("Exit", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.SHIFT_MASK+ActionEvent.ALT_MASK), mFile, this); + + // View + JMenu mView = AEnv.getMenu("View"); + menuBar.add(mView); + + if (MRole.getDefault().isAllow_Info_Product()) + { + AEnv.addMenuItem("InfoProduct", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK), mView, this); + } + if (MRole.getDefault().isAllow_Info_BPartner()) + { + AEnv.addMenuItem("InfoBPartner", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK+ActionEvent.CTRL_MASK), mView, this); + } + if (MRole.getDefault().isShowAcct() && MRole.getDefault().isAllow_Info_Account()) + { + AEnv.addMenuItem("InfoAccount", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK+ActionEvent.CTRL_MASK), mView, this); + } + if (MRole.getDefault().isAllow_Info_Schedule()) + { + AEnv.addMenuItem("InfoSchedule", null, null, mView, this); + } + mView.addSeparator(); + if (MRole.getDefault().isAllow_Info_Order()) + { + AEnv.addMenuItem("InfoOrder", "Info", null, mView, this); + } + if (MRole.getDefault().isAllow_Info_Invoice()) + { + AEnv.addMenuItem("InfoInvoice", "Info", null, mView, this); + } + if (MRole.getDefault().isAllow_Info_InOut()) + { + AEnv.addMenuItem("InfoInOut", "Info", null, mView, this); + } + if (MRole.getDefault().isAllow_Info_Payment()) + { + AEnv.addMenuItem("InfoPayment", "Info", null, mView, this); + } +// if (MRole.getDefault().isAllow_Info_CashJournal()) +// { +// AEnv.addMenuItem("InfoCashLine", "Info", null, mView, this); +// } + if (MRole.getDefault().isAllow_Info_Resource()) + { + AEnv.addMenuItem("InfoAssignment", "Info", null, mView, this); + } + if (MRole.getDefault().isAllow_Info_Asset()) + { + AEnv.addMenuItem("InfoAsset", "Info", null, mView, this); + } + // Tools + JMenu mTools = AEnv.getMenu("Tools"); + menuBar.add(mTools); + AEnv.addMenuItem("Calculator", null, null, mTools, this); + AEnv.addMenuItem("Calendar", null, null, mTools, this); + AEnv.addMenuItem("Editor", null, null, mTools, this); + MUser user = MUser.get(Env.getCtx()); + if (user.isAdministrator()) + AEnv.addMenuItem("Script", null, null, mTools, this); + if (MRole.getDefault().isShowPreference()) + { + mTools.addSeparator(); + AEnv.addMenuItem("Preference", null, null, mTools, this); + } + + // Window + AMenu aMenu = (AMenu)AEnv.getWindow(0); + JMenu mWindow = new WindowMenu(aMenu.getWindowManager(), this); + menuBar.add(mWindow); + + // Help + JMenu mHelp = AEnv.getMenu("Help"); + menuBar.add(mHelp); + AEnv.addMenuItem("Help", "Help", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), mHelp, this); + AEnv.addMenuItem("Online", null, null, mHelp, this); + AEnv.addMenuItem("EMailSupport", null, null, mHelp, this); + AEnv.addMenuItem("About", null, null, mHelp, this); + } // createMenu + + /** + * Dispose + */ + public void dispose() + { + log.config(""); + // recursive calls + if (Trace.isCalledFrom("JFrame") && m_panel != null) // [x] close window pressed + m_panel.dispose(); + m_panel = null; + Env.clearWinContext(m_WindowNo); + super.dispose(); + } // dispose + + /** + * Open Form + * @param AD_Form_ID form + * @return true if form opened + */ + public boolean openForm (int AD_Form_ID) + { + return openForm(AD_Form_ID, null); + } + + public boolean openForm (int AD_Form_ID, GridTab gridTab) + { + Properties ctx = Env.getCtx(); + // + String name = null; + String className = null; + String sql = "SELECT Name, Description, ClassName, Help FROM AD_Form WHERE AD_Form_ID=?"; + boolean trl = !Env.isBaseLanguage(ctx, "AD_Form"); + if (trl) + sql = "SELECT t.Name, t.Description, f.ClassName, t.Help " + + "FROM AD_Form f INNER JOIN AD_Form_Trl t" + + " ON (f.AD_Form_ID=t.AD_Form_ID AND AD_Language=?)" + + "WHERE f.AD_Form_ID=?"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement (sql, null); + if (trl) + { + pstmt.setString(1, Env.getAD_Language(ctx)); + pstmt.setInt(2, AD_Form_ID); + } + else + pstmt.setInt(1, AD_Form_ID); + rs = pstmt.executeQuery(); + if (rs.next()) + { + name = rs.getString(1); + m_Description = rs.getString(2); + className = rs.getString(3); + m_Help = rs.getString(4); + } + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + if (className == null) + return false; + // + return openForm(AD_Form_ID, className, name, gridTab); + } // openForm + + /** + * Open Form + * @param AD_Form_ID Form + * @param className class name + * @param name title + * @return true if started + */ + protected boolean openForm (int AD_Form_ID, String className, String name) + { + return openForm(AD_Form_ID, className, name, null); + } + + protected boolean openForm (int AD_Form_ID, String className, String name, GridTab gridTab) + { + if (log.isLoggable(Level.INFO)) log.info("AD_Form_ID=" + AD_Form_ID + " - Class=" + className); + Properties ctx = Env.getCtx(); + Env.setContext(ctx, m_WindowNo, "_WinInfo_WindowName", name); + setTitle(Env.getHeader(ctx, m_WindowNo)); + this.gridTab = gridTab; + + try + { + // Create instance w/o parameters + // Try equinox extension then java classpath + m_panel = Client.getFormPanel(className); + } + catch (Exception e) + { + log.log(Level.SEVERE, "Class=" + className + ", AD_Form_ID=" + AD_Form_ID, e); + return false; + } + // + m_panel.init(m_WindowNo, this); + p_AD_Form_ID = AD_Form_ID; + return true; + } // openForm + + /** + * Get Form Panel + * @return form panel + */ + public FormPanel getFormPanel() + { + return m_panel; + } // getFormPanel + + /** + * Action Listener + * @param e event + */ + public void actionPerformed(ActionEvent e) + { + String cmd = e.getActionCommand(); + if (cmd.equals("End")) + dispose(); + else if (cmd.equals("Help")) + actionHelp(); + else if (!AEnv.actionPerformed(cmd, m_WindowNo, this)) + log.log(Level.SEVERE, "Not handeled=" + cmd); + } // actionPerformed + + /** + * Show Help + */ + private void actionHelp() + { + StringBuilder sb = new StringBuilder(); + if (m_Description != null && m_Description.length() > 0) + sb.append("

    ").append(m_Description).append("

    "); + if (m_Help != null && m_Help.length() > 0) + sb.append("

    ").append(m_Help); + Help hlp = new Help (AEnv.getFrame(this), this.getTitle(), sb.toString()); + hlp.setVisible(true); + } // actionHelp + + + /************************************************************************* + * Set Window Busy + * @param busy busy + */ + public void setBusy (boolean busy) + { + if (busy == m_glassPane.isVisible()) + return; + if (log.isLoggable(Level.INFO)) log.info("Busy=" + busy); + if (busy) + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + else + setCursor(Cursor.getDefaultCursor()); + m_glassPane.setMessage(null); + m_glassPane.setVisible(busy); + m_glassPane.requestFocus(); + } // setBusy + + /** + * Set Busy Message + * @param AD_Message message + */ + public void setBusyMessage (String AD_Message) + { + m_glassPane.setMessage(AD_Message); + } // setBusyMessage + + /** + * Set and start Busy Counter + * @param time in seconds + */ + public void setBusyTimer (int time) + { + m_glassPane.setBusyTimer (time); + } // setBusyTimer + + + /** + * Set Maximize Window + * @param max maximize + */ + public void setMaximize (boolean max) + { + m_maximize = max; + } // setMaximize + + + /** + * Form Window Opened. + * Maximize window if required + * @param evt event + */ + private void formWindowOpened(java.awt.event.WindowEvent evt) + { + if (m_maximize == true) + { + super.setVisible(true); + super.setExtendedState(JFrame.MAXIMIZED_BOTH); + } + } // formWindowOpened + // Add window and tab no called from public void setProcessInfo(ProcessInfo pi) @@ -456,45 +456,45 @@ public class FormFrame extends CFrame // End - /** - * Start Batch - * @param process - * @return running thread - */ - public Thread startBatch (final Runnable process) - { - Thread worker = new Thread() - { - public void run() - { - setBusy(true); - process.run(); - setBusy(false); - } - }; - worker.start(); - return worker; - } // startBatch - - /** - * @return Returns the AD_Form_ID. - */ - public int getAD_Form_ID () - { - return p_AD_Form_ID; - } // getAD_Window_ID - /** - * @return Returns the manuBar - */ - public JMenuBar getMenu() - { - return menuBar; - } - - private GridTab gridTab; - - public GridTab getGridTab() - { - return gridTab; - } -} // FormFrame + /** + * Start Batch + * @param process + * @return running thread + */ + public Thread startBatch (final Runnable process) + { + Thread worker = new Thread() + { + public void run() + { + setBusy(true); + process.run(); + setBusy(false); + } + }; + worker.start(); + return worker; + } // startBatch + + /** + * @return Returns the AD_Form_ID. + */ + public int getAD_Form_ID () + { + return p_AD_Form_ID; + } // getAD_Window_ID + /** + * @return Returns the manuBar + */ + public JMenuBar getMenu() + { + return menuBar; + } + + private GridTab gridTab; + + public GridTab getGridTab() + { + return gridTab; + } +} // FormFrame diff --git a/org.adempiere.ui.swing/src/org/compiere/minigrid/MiniTable.java b/org.adempiere.ui.swing/src/org/compiere/minigrid/MiniTable.java index 1025d02cc9..4334ea0524 100644 --- a/org.adempiere.ui.swing/src/org/compiere/minigrid/MiniTable.java +++ b/org.adempiere.ui.swing/src/org/compiere/minigrid/MiniTable.java @@ -1,8 +1,8 @@ -/****************************************************************************** - * 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 * +/****************************************************************************** + * 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. * @@ -16,36 +16,36 @@ *****************************************************************************/ package org.compiere.minigrid; -import java.awt.Component; -import java.awt.Insets; -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Collection; -import java.util.logging.Level; - -import javax.swing.DefaultCellEditor; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.DefaultTableModel; -import javax.swing.table.TableCellRenderer; -import javax.swing.table.TableColumn; -import javax.swing.table.TableModel; - -import org.compiere.apps.search.Info_Column; -import org.compiere.grid.ed.VCellRenderer; -import org.compiere.grid.ed.VHeaderRenderer; -import org.compiere.model.MRole; -import org.compiere.model.PO; -import org.compiere.swing.CCheckBox; -import org.compiere.swing.CTable; -import org.compiere.util.CLogger; -import org.compiere.util.DisplayType; -import org.compiere.util.Env; -import org.compiere.util.KeyNamePair; -import org.compiere.util.Util; +import java.awt.Component; +import java.awt.Insets; +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Collection; +import java.util.logging.Level; + +import javax.swing.DefaultCellEditor; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; +import javax.swing.table.TableModel; + +import org.compiere.apps.search.Info_Column; +import org.compiere.grid.ed.VCellRenderer; +import org.compiere.grid.ed.VHeaderRenderer; +import org.compiere.model.MRole; +import org.compiere.model.PO; +import org.compiere.swing.CCheckBox; +import org.compiere.swing.CTable; +import org.compiere.util.CLogger; +import org.compiere.util.DisplayType; +import org.compiere.util.Env; +import org.compiere.util.KeyNamePair; +import org.compiere.util.Util; /** * Mini Table. @@ -63,23 +63,23 @@ import org.compiere.util.Util; * * @author Jorg Janke * @version $Id: MiniTable.java,v 1.3 2006/07/30 00:51:28 jjanke Exp $ - * - * @author Teo Sarca, SC ARHIPAC SERVICE SRL - *

  • BF [ 1891082 ] NPE on MiniTable when you hide some columns - *
  • FR [ 1974299 ] Add MiniTable.getSelectedKeys method - *
  • FR [ 2847295 ] MiniTable multiselection checkboxes not working - * https://sourceforge.net/tracker/?func=detail&atid=879335&aid=2847295&group_id=176962 - * @author Teo Sarca, teo.sarca@gmail.com - *
  • BF [ 2876895 ] MiniTable.loadTable: NPE if column is null - * https://sourceforge.net/tracker/?func=detail&aid=2876895&group_id=176962&atid=879332 + * + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1891082 ] NPE on MiniTable when you hide some columns + *
  • FR [ 1974299 ] Add MiniTable.getSelectedKeys method + *
  • FR [ 2847295 ] MiniTable multiselection checkboxes not working + * https://sourceforge.net/tracker/?func=detail&atid=879335&aid=2847295&group_id=176962 + * @author Teo Sarca, teo.sarca@gmail.com + *
  • BF [ 2876895 ] MiniTable.loadTable: NPE if column is null + * https://sourceforge.net/tracker/?func=detail&aid=2876895&group_id=176962&atid=879332 */ public class MiniTable extends CTable implements IMiniTable { - /** - * - */ - private static final long serialVersionUID = 281959800766140642L; - + /** + * + */ + private static final long serialVersionUID = 281959800766140642L; + /** * Default Constructor */ @@ -109,46 +109,46 @@ public class MiniTable extends CTable implements IMiniTable /** Lauout set in prepareTable and used in loadTable */ private ColumnInfo[] m_layout = null; /** Logger */ - private static CLogger log = CLogger.getCLogger(MiniTable.class); - /** Is Total Show */ - private boolean showTotals = false; - private boolean autoResize = true; - - public boolean isAutoResize() { - return autoResize; - } - - public void setAutoResize(boolean autoResize) { - this.autoResize = autoResize; - } - - /** - * Gets the swing column of given index. No index checking - * is done. - * - * @param col - * @return - */ - public TableColumn getColumn(int col) { - return(getColumnModel().getColumn(col)); - } - - /** - * Return number of columns in the mini table - */ - public int getColumnCount() { - return(getColumnModel().getColumnCount()); - } + private static CLogger log = CLogger.getCLogger(MiniTable.class); + /** Is Total Show */ + private boolean showTotals = false; + private boolean autoResize = true; + + public boolean isAutoResize() { + return autoResize; + } + + public void setAutoResize(boolean autoResize) { + this.autoResize = autoResize; + } + + /** + * Gets the swing column of given index. No index checking + * is done. + * + * @param col + * @return + */ + public TableColumn getColumn(int col) { + return(getColumnModel().getColumn(col)); + } + + /** + * Return number of columns in the mini table + */ + public int getColumnCount() { + return(getColumnModel().getColumnCount()); + } /** * Size Columns. * Uses Mimimum Column Size */ public void autoSize() - { - if ( !autoResize ) - return; - + { + if ( !autoResize ) + return; + long start = System.currentTimeMillis(); // final int SLACK = 8; // making sure it fits in a column @@ -182,17 +182,17 @@ public class MiniTable extends CTable implements IMiniTable renderer = getCellRenderer(row, col); comp = renderer.getTableCellRendererComponent (this, getValueAt(row, col), false, false, row, col); - if (comp != null) { + if (comp != null) { int rowWidth = comp.getPreferredSize().width + SLACK; width = Math.max(width, rowWidth); - } + } } // Width not greater .. width = Math.min(MAXSIZE, width); tc.setPreferredWidth(width); // log.fine( "width=" + width); } // for all columns - if (log.isLoggable(Level.FINER)) log.finer("Cols=" + size + " - " + (System.currentTimeMillis()-start) + "ms"); + if (log.isLoggable(Level.FINER)) log.finer("Cols=" + size + " - " + (System.currentTimeMillis()-start) + "ms"); } // autoSize @@ -262,7 +262,7 @@ public class MiniTable extends CTable implements IMiniTable m_layout = layout; m_multiSelection = multiSelection; // - StringBuilder sql = new StringBuilder ("SELECT "); + StringBuilder sql = new StringBuilder ("SELECT "); // add columns & sql for (int i = 0; i < layout.length; i++) { @@ -307,12 +307,12 @@ public class MiniTable extends CTable implements IMiniTable * (DefaultTableModel fires TableStructureChanged, which calls * JTable.tableChanged .. createDefaultColumnsFromModel * @param header header - */ - public void addColumn (String header) - { - if (getModel() instanceof DefaultTableModel) - { - DefaultTableModel model = (DefaultTableModel)getModel(); + */ + public void addColumn (String header) + { + if (getModel() instanceof DefaultTableModel) + { + DefaultTableModel model = (DefaultTableModel)getModel(); model.addColumn(Util.cleanAmp(header)); } else @@ -326,7 +326,7 @@ public class MiniTable extends CTable implements IMiniTable * @param c class of column - determines renderere * @param readOnly read only flag */ - public void setColumnClass (int index, Class c, boolean readOnly) + public void setColumnClass (int index, Class c, boolean readOnly) { setColumnClass(index, c, readOnly, null); } // setColumnClass @@ -341,7 +341,7 @@ public class MiniTable extends CTable implements IMiniTable * @param readOnly read only flag * @param header optional header value */ - public void setColumnClass (int index, Class c, boolean readOnly, String header) + public void setColumnClass (int index, Class c, boolean readOnly, String header) { // log.config( "MiniTable.setColumnClass - " + index, c.getName() + ", r/o=" + readOnly); TableColumn tc = getColumnModel().getColumn(index); @@ -358,20 +358,20 @@ public class MiniTable extends CTable implements IMiniTable if (c == IDColumn.class) { tc.setCellRenderer(new IDColumnRenderer(m_multiSelection)); - if (m_multiSelection) + if (m_multiSelection) { - tc.setCellEditor(new IDColumnEditor()); - setColumnReadOnly(index, false); + tc.setCellEditor(new IDColumnEditor()); + setColumnReadOnly(index, false); } - else + else { - tc.setCellEditor(new ROCellEditor()); + tc.setCellEditor(new ROCellEditor()); } m_minWidth.add(Integer.valueOf(10)); tc.setMaxWidth(20); tc.setPreferredWidth(20); - tc.setResizable(false); - + tc.setResizable(false); + tc.setHeaderRenderer(new VHeaderRenderer(DisplayType.Number)); } // Boolean @@ -381,15 +381,15 @@ public class MiniTable extends CTable implements IMiniTable if (readOnly) tc.setCellEditor(new ROCellEditor()); else - { - CCheckBox check = new CCheckBox(); - check.setMargin(new Insets(0,0,0,0)); - check.setHorizontalAlignment(SwingConstants.CENTER); - tc.setCellEditor(new DefaultCellEditor(check)); - } - m_minWidth.add(Integer.valueOf(30)); - - tc.setHeaderRenderer(new VHeaderRenderer(DisplayType.YesNo)); + { + CCheckBox check = new CCheckBox(); + check.setMargin(new Insets(0,0,0,0)); + check.setHorizontalAlignment(SwingConstants.CENTER); + tc.setCellEditor(new DefaultCellEditor(check)); + } + m_minWidth.add(Integer.valueOf(30)); + + tc.setHeaderRenderer(new VHeaderRenderer(DisplayType.YesNo)); } // Date else if (c == Timestamp.class) @@ -399,8 +399,8 @@ public class MiniTable extends CTable implements IMiniTable tc.setCellEditor(new ROCellEditor()); else tc.setCellEditor(new MiniCellEditor(c)); - m_minWidth.add(Integer.valueOf(30)); - + m_minWidth.add(Integer.valueOf(30)); + tc.setHeaderRenderer(new VHeaderRenderer(DisplayType.DateTime)); } // Amount @@ -416,8 +416,8 @@ public class MiniTable extends CTable implements IMiniTable { tc.setCellEditor(new MiniCellEditor(c)); m_minWidth.add(Integer.valueOf(80)); - } - + } + tc.setHeaderRenderer(new VHeaderRenderer(DisplayType.Number)); } // Number @@ -433,8 +433,8 @@ public class MiniTable extends CTable implements IMiniTable { tc.setCellEditor(new MiniCellEditor(c)); m_minWidth.add(Integer.valueOf(80)); - } - + } + tc.setHeaderRenderer(new VHeaderRenderer(DisplayType.Number)); } // Integer @@ -445,8 +445,8 @@ public class MiniTable extends CTable implements IMiniTable tc.setCellEditor(new ROCellEditor()); else tc.setCellEditor(new MiniCellEditor(c)); - m_minWidth.add(Integer.valueOf(30)); - + m_minWidth.add(Integer.valueOf(30)); + tc.setHeaderRenderer(new VHeaderRenderer(DisplayType.Number)); } // String @@ -457,8 +457,8 @@ public class MiniTable extends CTable implements IMiniTable tc.setCellEditor(new ROCellEditor()); else tc.setCellEditor(new MiniCellEditor(String.class)); - m_minWidth.add(Integer.valueOf(30)); - + m_minWidth.add(Integer.valueOf(30)); + tc.setHeaderRenderer(new VHeaderRenderer(DisplayType.String)); } // log.fine( "Renderer=" + tc.getCellRenderer().toString() + ", Editor=" + tc.getCellEditor().toString()); @@ -505,7 +505,7 @@ public class MiniTable extends CTable implements IMiniTable { Object data = null; Class c = m_layout[col].getColClass(); - int colIndex = col + colOffset; + int colIndex = col + colOffset; if (c == IDColumn.class) data = new IDColumn(rs.getInt(colIndex)); else if (c == Boolean.class) @@ -535,20 +535,20 @@ public class MiniTable extends CTable implements IMiniTable setValueAt(data, row, col); // log.fine( "r=" + row + ", c=" + col + " " + m_layout[col].getColHeader(), // "data=" + data.toString() + " " + data.getClass().getName() + " * " + m_table.getCellRenderer(row, col)); - } - + } + } } catch (SQLException e) { log.log(Level.SEVERE, "", e); - } - if(getShowTotals()) + } + if(getShowTotals()) addTotals(m_layout); autoSize(); - if (log.isLoggable(Level.CONFIG)) log.config("Row(rs)=" + getRowCount()); - + if (log.isLoggable(Level.CONFIG)) log.config("Row(rs)=" + getRowCount()); + } // loadTable @@ -585,11 +585,11 @@ public class MiniTable extends CTable implements IMiniTable // store setValueAt(data, row, col); } - } - if(getShowTotals()) + } + if(getShowTotals()) addTotals(m_layout); autoSize(); - if (log.isLoggable(Level.CONFIG)) log.config("Row(array)=" + getRowCount()); + if (log.isLoggable(Level.CONFIG)) log.config("Row(array)=" + getRowCount()); } // loadTable @@ -614,35 +614,35 @@ public class MiniTable extends CTable implements IMiniTable return null; } // getSelectedRowKey - /** - * @return collection of selected IDs - */ - public Collection getSelectedKeys() - { - if (m_layout == null) - { - throw new UnsupportedOperationException("Layout not defined"); - } - if (p_keyColumnIndex < 0) - { - throw new UnsupportedOperationException("Key Column is not defined"); - } - // - ArrayList list = new ArrayList(); - for (int row = 0; row < getRowCount(); row++) - { - Object data = getModel().getValueAt(row, p_keyColumnIndex); - if (data instanceof IDColumn) - { - IDColumn record = (IDColumn)data; - if (record.isSelected()) - { - list.add(record.getRecord_ID()); - } - } - } - return list; - } + /** + * @return collection of selected IDs + */ + public Collection getSelectedKeys() + { + if (m_layout == null) + { + throw new UnsupportedOperationException("Layout not defined"); + } + if (p_keyColumnIndex < 0) + { + throw new UnsupportedOperationException("Key Column is not defined"); + } + // + ArrayList list = new ArrayList(); + for (int row = 0; row < getRowCount(); row++) + { + Object data = getModel().getValueAt(row, p_keyColumnIndex); + if (data instanceof IDColumn) + { + IDColumn record = (IDColumn)data; + if (record.isSelected()) + { + list.add(record.getRecord_ID()); + } + } + } + return list; + } /************************************************************************** * Get Layout @@ -738,173 +738,173 @@ public class MiniTable extends CTable implements IMiniTable if (cmp < 0) return 1; return 0; - } // getColorCode - - - /** - * Set if Totals is Show - * @param boolean Show - */ - public void setShowTotals(boolean show) - { - showTotals= show; - } - /** - * get if Totals is Show - * @param boolean Show - */ - public boolean getShowTotals() - { - return showTotals; - } - - /** - * Adding a new row with the totals - */ - public void addTotals(ColumnInfo[] layout) - { - if (getRowCount() == 0 || layout.length == 0) - return; - - Object[] total = new Object[layout.length]; - - for (int row = 0 ; row < getRowCount(); row ++) - { - - for (int col = 0; col < layout.length; col++) - { - Object data = getModel().getValueAt(row, col); - Class c = layout[col].getColClass(); - if (c == BigDecimal.class) - { - BigDecimal subtotal = Env.ZERO; - if(total[col]!= null) - subtotal = (BigDecimal)(total[col]); - - BigDecimal amt = (BigDecimal) data; - if(subtotal == null) - subtotal = Env.ZERO; - if(amt == null ) - amt = Env.ZERO; - total[col] = subtotal.add(amt); - } - else if (c == Double.class) - { - Double subtotal = Double.valueOf(0); - if(total[col] != null) - subtotal = (Double)(total[col]); - - Double amt = (Double) data; - if(subtotal == null) - subtotal = Double.valueOf(0); - if(amt == null ) - amt = Double.valueOf(0); - total[col] = subtotal + amt; - - } - } - } - - //adding total row - - int row = getRowCount() + 1; - setRowCount(row); - for (int col = 0; col < layout.length; col++) - { - Class c = layout[col].getColClass(); - if (c == BigDecimal.class) - { - setValueAt(total[col] , row - 1, col); - } - else if (c == Double.class) - { - setValueAt(total[col] , row -1 , col); - } - else - { - if(col == 0 ) - { - setValueAt(" Σ " , row -1 , col); - } - else - setValueAt(null , row - 1, col ); - } - - } + } // getColorCode + + + /** + * Set if Totals is Show + * @param boolean Show + */ + public void setShowTotals(boolean show) + { + showTotals= show; } - - /** - * Adding a new row with the totals - */ - public void addTotals(Info_Column[] layout) - { - if (getRowCount() == 0 || layout.length == 0) - return; - - Object[] total = new Object[layout.length]; - - for (int row = 0 ; row < getRowCount(); row ++) - { - - for (int col = 0; col < layout.length; col++) - { - Object data = getModel().getValueAt(row, col); - Class c = layout[col].getColClass(); - if (c == BigDecimal.class) - { - BigDecimal subtotal = Env.ZERO; - if(total[col]!= null) - subtotal = (BigDecimal)(total[col]); - - BigDecimal amt = (BigDecimal) data; - if(subtotal == null) - subtotal = Env.ZERO; - if(amt == null ) - amt = Env.ZERO; - total[col] = subtotal.add(amt); - } - else if (c == Double.class) - { - Double subtotal = Double.valueOf(0); - if(total[col] != null) - subtotal = (Double)(total[col]); - - Double amt = (Double) data; - if(subtotal == null) - subtotal = Double.valueOf(0); - if(amt == null ) - amt = Double.valueOf(0); - total[col] = subtotal + amt; - - } - } - } - - //adding total row - - int row = getRowCount() + 1; - setRowCount(row); - for (int col = 0; col < layout.length; col++) - { - Class c = layout[col].getColClass(); - if (c == BigDecimal.class) - { - setValueAt(total[col] , row - 1, col); - } - else if (c == Double.class) - { - setValueAt(total[col] , row -1 , col); - } - else - { - if(col == 1 ) - { - setValueAt(" Σ " , row -1 , col ); - } - else - setValueAt(null , row - 1, col ); - } - - } + /** + * get if Totals is Show + * @param boolean Show + */ + public boolean getShowTotals() + { + return showTotals; + } + + /** + * Adding a new row with the totals + */ + public void addTotals(ColumnInfo[] layout) + { + if (getRowCount() == 0 || layout.length == 0) + return; + + Object[] total = new Object[layout.length]; + + for (int row = 0 ; row < getRowCount(); row ++) + { + + for (int col = 0; col < layout.length; col++) + { + Object data = getModel().getValueAt(row, col); + Class c = layout[col].getColClass(); + if (c == BigDecimal.class) + { + BigDecimal subtotal = Env.ZERO; + if(total[col]!= null) + subtotal = (BigDecimal)(total[col]); + + BigDecimal amt = (BigDecimal) data; + if(subtotal == null) + subtotal = Env.ZERO; + if(amt == null ) + amt = Env.ZERO; + total[col] = subtotal.add(amt); + } + else if (c == Double.class) + { + Double subtotal = Double.valueOf(0); + if(total[col] != null) + subtotal = (Double)(total[col]); + + Double amt = (Double) data; + if(subtotal == null) + subtotal = Double.valueOf(0); + if(amt == null ) + amt = Double.valueOf(0); + total[col] = subtotal + amt; + + } + } + } + + //adding total row + + int row = getRowCount() + 1; + setRowCount(row); + for (int col = 0; col < layout.length; col++) + { + Class c = layout[col].getColClass(); + if (c == BigDecimal.class) + { + setValueAt(total[col] , row - 1, col); + } + else if (c == Double.class) + { + setValueAt(total[col] , row -1 , col); + } + else + { + if(col == 0 ) + { + setValueAt(" Σ " , row -1 , col); + } + else + setValueAt(null , row - 1, col ); + } + + } + } + + /** + * Adding a new row with the totals + */ + public void addTotals(Info_Column[] layout) + { + if (getRowCount() == 0 || layout.length == 0) + return; + + Object[] total = new Object[layout.length]; + + for (int row = 0 ; row < getRowCount(); row ++) + { + + for (int col = 0; col < layout.length; col++) + { + Object data = getModel().getValueAt(row, col); + Class c = layout[col].getColClass(); + if (c == BigDecimal.class) + { + BigDecimal subtotal = Env.ZERO; + if(total[col]!= null) + subtotal = (BigDecimal)(total[col]); + + BigDecimal amt = (BigDecimal) data; + if(subtotal == null) + subtotal = Env.ZERO; + if(amt == null ) + amt = Env.ZERO; + total[col] = subtotal.add(amt); + } + else if (c == Double.class) + { + Double subtotal = Double.valueOf(0); + if(total[col] != null) + subtotal = (Double)(total[col]); + + Double amt = (Double) data; + if(subtotal == null) + subtotal = Double.valueOf(0); + if(amt == null ) + amt = Double.valueOf(0); + total[col] = subtotal + amt; + + } + } + } + + //adding total row + + int row = getRowCount() + 1; + setRowCount(row); + for (int col = 0; col < layout.length; col++) + { + Class c = layout[col].getColClass(); + if (c == BigDecimal.class) + { + setValueAt(total[col] , row - 1, col); + } + else if (c == Double.class) + { + setValueAt(total[col] , row -1 , col); + } + else + { + if(col == 1 ) + { + setValueAt(" Σ " , row -1 , col ); + } + else + setValueAt(null , row - 1, col ); + } + + } } } // MiniTable diff --git a/org.adempiere.ui.swing/src/org/compiere/plaf/PlafRes_hu.java b/org.adempiere.ui.swing/src/org/compiere/plaf/PlafRes_hu.java index bcf2da9515..66524f6d95 100644 --- a/org.adempiere.ui.swing/src/org/compiere/plaf/PlafRes_hu.java +++ b/org.adempiere.ui.swing/src/org/compiere/plaf/PlafRes_hu.java @@ -1,133 +1,133 @@ -/****************************************************************************** - * 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.compiere.plaf; - -import java.util.ListResourceBundle; - -/** - * Translation Texts for Look & Feel - * - * @author Jorg Janke - * @version $Id: PlafRes.java,v 1.2 2006/07/30 00:52:24 jjanke Exp $ - */ -public class PlafRes_hu extends ListResourceBundle -{ - /** The data */ - static final Object[][] contents = new String[][] - { - { "BackColType", "Háttérszín típus" }, - { "BackColType_Flat", "Sima" }, - { "BackColType_Gradient", "Gradiens" }, - { "BackColType_Lines", "Vonalas" }, - { "BackColType_Texture", "Textúrázott" }, - // - { "LookAndFeelEditor", "Look & Feel Editor" }, - { "LookAndFeel", "Look & Feel" }, - { "Theme", "Theme" }, - { "EditAdempiereTheme", "Edit Adempiere Theme" }, - { "SetDefault", "Default Background" }, - { "SetDefaultColor", "Background Color" }, - { "ColorBlind", "Color Deficiency" }, - { "Example", "Example" }, - { "Reset", "Reset" }, - { "OK", "OK" }, - { "Cancel", "Cancel" }, - // - { "AdempiereThemeEditor", "Adempiere Theme Editor" }, - { "MetalColors", "Metal Colors" }, - { "AdempiereColors", "Adempiere Colors" }, - { "AdempiereFonts", "Adempiere Fonts" }, - { "Primary1Info", "Shadow, Separator" }, - { "Primary1", "Primary 1" }, - { "Primary2Info", "Focus Line, Selected Menu" }, - { "Primary2", "Primary 2" }, - { "Primary3Info", "Table Selected Row, Selected Text, ToolTip Background" }, - { "Primary3", "Primary 3" }, - { "Secondary1Info", "Border Lines" }, - { "Secondary1", "Secondary 1" }, - { "Secondary2Info", "Inactive Tabs, Pressed Fields, Inactive Border + Text" }, - { "Secondary2", "Secondary 2" }, - { "Secondary3Info", "Background" }, - { "Secondary3", "Secondary 3" }, - // - { "ControlFontInfo", "Control Font" }, - { "ControlFont", "Label Font" }, - { "SystemFontInfo", "Tool Tip, Tree nodes" }, - { "SystemFont", "System Font" }, - { "UserFontInfo", "User Entered Data" }, - { "UserFont", "Field Font" }, -// { "SmallFontInfo", "Reports" }, - { "SmallFont", "Small Font" }, - { "WindowTitleFont", "Title Font" }, - { "MenuFont", "Menu Font" }, - // - { "MandatoryInfo", "Mandatory Field Background" }, - { "Mandatory", "Mandatory" }, - { "ErrorInfo", "Error Field Background" }, - { "Error", "Error" }, - { "InfoInfo", "Info Field Background" }, - { "Info", "Info" }, - { "WhiteInfo", "Lines" }, - { "White", "White" }, - { "BlackInfo", "Lines, Text" }, - { "Black", "Black" }, - { "InactiveInfo", "Inactive Field Background" }, - { "Inactive", "Inactive" }, - { "TextOKInfo", "OK Text Foreground" }, - { "TextOK", "Text - OK" }, - { "TextIssueInfo", "Error Text Foreground" }, - { "TextIssue", "Text - Error" }, - // - { "FontChooser", "Font Chooser" }, - { "Fonts", "Fonts" }, - { "Plain", "Plain" }, - { "Italic", "Italic" }, - { "Bold", "Bold" }, - { "BoldItalic", "Bold & Italic" }, - { "Name", "Name" }, - { "Size", "Size" }, - { "Style", "Style" }, - { "TestString", "This is just a Test! The quick brown Fox is doing something. 12,3456.78 LetterLOne = l1 LetterOZero = O0" }, - { "FontString", "Font" }, - // - { "AdempiereColorEditor", "Adempiere Color Editor" }, - { "AdempiereType", "Color Type" }, - { "GradientUpperColor", "Gradient Upper Color" }, - { "GradientLowerColor", "Gradient Lower Color" }, - { "GradientStart", "Gradient Start" }, - { "GradientDistance", "Gradient Distance" }, - { "TextureURL", "Texture URL" }, - { "TextureAlpha", "Texture Alpha" }, - { "TextureTaintColor", "Texture Taint Color" }, - { "LineColor", "Line Color" }, - { "LineBackColor", "Background Color" }, - { "LineWidth", "Line Width" }, - { "LineDistance", "Line Distance" }, - { "FlatColor", "Flat Color" }, - { "UITheme", "User Interface Theme" }, - { "Preview", "Preview" } - }; - - /** - * Get Contents - * @return contents - */ - public Object[][] getContents() - { - return contents; - } +/****************************************************************************** + * 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.compiere.plaf; + +import java.util.ListResourceBundle; + +/** + * Translation Texts for Look & Feel + * + * @author Jorg Janke + * @version $Id: PlafRes.java,v 1.2 2006/07/30 00:52:24 jjanke Exp $ + */ +public class PlafRes_hu extends ListResourceBundle +{ + /** The data */ + static final Object[][] contents = new String[][] + { + { "BackColType", "Háttérszín típus" }, + { "BackColType_Flat", "Sima" }, + { "BackColType_Gradient", "Gradiens" }, + { "BackColType_Lines", "Vonalas" }, + { "BackColType_Texture", "Textúrázott" }, + // + { "LookAndFeelEditor", "Look & Feel Editor" }, + { "LookAndFeel", "Look & Feel" }, + { "Theme", "Theme" }, + { "EditAdempiereTheme", "Edit Adempiere Theme" }, + { "SetDefault", "Default Background" }, + { "SetDefaultColor", "Background Color" }, + { "ColorBlind", "Color Deficiency" }, + { "Example", "Example" }, + { "Reset", "Reset" }, + { "OK", "OK" }, + { "Cancel", "Cancel" }, + // + { "AdempiereThemeEditor", "Adempiere Theme Editor" }, + { "MetalColors", "Metal Colors" }, + { "AdempiereColors", "Adempiere Colors" }, + { "AdempiereFonts", "Adempiere Fonts" }, + { "Primary1Info", "Shadow, Separator" }, + { "Primary1", "Primary 1" }, + { "Primary2Info", "Focus Line, Selected Menu" }, + { "Primary2", "Primary 2" }, + { "Primary3Info", "Table Selected Row, Selected Text, ToolTip Background" }, + { "Primary3", "Primary 3" }, + { "Secondary1Info", "Border Lines" }, + { "Secondary1", "Secondary 1" }, + { "Secondary2Info", "Inactive Tabs, Pressed Fields, Inactive Border + Text" }, + { "Secondary2", "Secondary 2" }, + { "Secondary3Info", "Background" }, + { "Secondary3", "Secondary 3" }, + // + { "ControlFontInfo", "Control Font" }, + { "ControlFont", "Label Font" }, + { "SystemFontInfo", "Tool Tip, Tree nodes" }, + { "SystemFont", "System Font" }, + { "UserFontInfo", "User Entered Data" }, + { "UserFont", "Field Font" }, +// { "SmallFontInfo", "Reports" }, + { "SmallFont", "Small Font" }, + { "WindowTitleFont", "Title Font" }, + { "MenuFont", "Menu Font" }, + // + { "MandatoryInfo", "Mandatory Field Background" }, + { "Mandatory", "Mandatory" }, + { "ErrorInfo", "Error Field Background" }, + { "Error", "Error" }, + { "InfoInfo", "Info Field Background" }, + { "Info", "Info" }, + { "WhiteInfo", "Lines" }, + { "White", "White" }, + { "BlackInfo", "Lines, Text" }, + { "Black", "Black" }, + { "InactiveInfo", "Inactive Field Background" }, + { "Inactive", "Inactive" }, + { "TextOKInfo", "OK Text Foreground" }, + { "TextOK", "Text - OK" }, + { "TextIssueInfo", "Error Text Foreground" }, + { "TextIssue", "Text - Error" }, + // + { "FontChooser", "Font Chooser" }, + { "Fonts", "Fonts" }, + { "Plain", "Plain" }, + { "Italic", "Italic" }, + { "Bold", "Bold" }, + { "BoldItalic", "Bold & Italic" }, + { "Name", "Name" }, + { "Size", "Size" }, + { "Style", "Style" }, + { "TestString", "This is just a Test! The quick brown Fox is doing something. 12,3456.78 LetterLOne = l1 LetterOZero = O0" }, + { "FontString", "Font" }, + // + { "AdempiereColorEditor", "Adempiere Color Editor" }, + { "AdempiereType", "Color Type" }, + { "GradientUpperColor", "Gradient Upper Color" }, + { "GradientLowerColor", "Gradient Lower Color" }, + { "GradientStart", "Gradient Start" }, + { "GradientDistance", "Gradient Distance" }, + { "TextureURL", "Texture URL" }, + { "TextureAlpha", "Texture Alpha" }, + { "TextureTaintColor", "Texture Taint Color" }, + { "LineColor", "Line Color" }, + { "LineBackColor", "Background Color" }, + { "LineWidth", "Line Width" }, + { "LineDistance", "Line Distance" }, + { "FlatColor", "Flat Color" }, + { "UITheme", "User Interface Theme" }, + { "Preview", "Preview" } + }; + + /** + * Get Contents + * @return contents + */ + public Object[][] getContents() + { + return contents; + } } // Res diff --git a/org.adempiere.ui.swing/src/org/compiere/print/Viewer.java b/org.adempiere.ui.swing/src/org/compiere/print/Viewer.java index 40ee7f5b6d..75a13a41bb 100644 --- a/org.adempiere.ui.swing/src/org/compiere/print/Viewer.java +++ b/org.adempiere.ui.swing/src/org/compiere/print/Viewer.java @@ -1,1393 +1,1393 @@ -/****************************************************************************** - * 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 * - * Contributor: phib [ 1566335 ] Report View scrolling (Bug 1566328) * - * Teo Sarca [ 1619449 ] Minor typo problem * - *****************************************************************************/ -package org.compiere.print; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.GraphicsConfiguration; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowEvent; -import java.awt.event.WindowStateListener; -import java.io.File; -import java.io.IOException; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Properties; -import java.util.logging.Level; - -import javax.swing.AbstractAction; -import javax.swing.AbstractButton; -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JComponent; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JOptionPane; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JToolBar; -import javax.swing.KeyStroke; -import javax.swing.SpinnerNumberModel; -import javax.swing.SwingUtilities; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import org.adempiere.pdf.Document; -import org.compiere.apps.ADialog; -import org.compiere.apps.AEnv; -import org.compiere.apps.AMenu; -import org.compiere.apps.AWindow; -import org.compiere.apps.AWindowListener; -import org.compiere.apps.AppsAction; -import org.compiere.apps.EMailDialog; -import org.compiere.apps.StatusBar; -import org.compiere.apps.WindowMenu; -import org.compiere.apps.search.Find; -import org.compiere.model.GridField; -import org.compiere.model.MArchive; -import org.compiere.model.MClient; -import org.compiere.model.MQuery; -import org.compiere.model.MRole; -import org.compiere.model.MUser; -import org.compiere.model.PrintInfo; -import org.compiere.model.X_C_Invoice; -import org.compiere.swing.CButton; -import org.compiere.swing.CCheckBox; -import org.compiere.swing.CComboBox; -import org.compiere.swing.CFrame; -import org.compiere.swing.CLabel; -import org.compiere.swing.CMenuItem; -import org.compiere.swing.CPanel; -import org.compiere.tools.FileUtil; -import org.compiere.util.CLogMgt; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.ExtensionFileFilter; -import org.compiere.util.KeyNamePair; -import org.compiere.util.Language; -import org.compiere.util.Login; -import org.compiere.util.Msg; -import org.compiere.util.NamePair; -import org.compiere.util.ValueNamePair; - -/** - * Print View Frame - * - * @author Jorg Janke - * @version $Id: Viewer.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - * globalqss: integrate phib contribution from - * http://sourceforge.net/tracker/index.php?func=detail&aid=1566335&group_id=176962&atid=879334 - * globalqss: integrate Teo Sarca bug fixing - * Colin Rooney 2007/03/20 RFE#1670185 & BUG#1684142 - * Extend security to Info queries - * - * @author Teo Sarca, www.arhipac.ro - *
  • FR [ 1762466 ] Add "Window" menu to report viewer. - *
  • FR [ 1779403 ] Report Viewer: add PgUp and PgDown key handlers - *
  • BF [ 1836908 ] Report customize NPE when no window access - *
  • FR [ 1894640 ] Report Engine: Excel Export support - *
  • FR [ 2539927 ] Display Zoom combobox - * https://sourceforge.net/tracker/?func=detail&atid=879335&aid=2539927&group_id=176962 - * @author victor.perez@e-evolution.com - *
  • FR [ 1966328 ] New Window Info to MRP and CRP into View http://sourceforge.net/tracker/index.php?func=detail&aid=1966328&group_id=176962&atid=879335 - *
  • FR [ 2011569 ] Implementing new Summary flag in Report View http://sourceforge.net/tracker/index.php?func=detail&aid=2011569&group_id=176962&atid=879335 - * - */ -public class Viewer extends CFrame - implements ActionListener, ChangeListener, WindowStateListener, IReportEngineEventListener -{ - /** - * - */ - private static final long serialVersionUID = 3766771249690413641L; - - /** - * @deprecated - * Viewer Constructor - * @param re report engine - */ - public Viewer (ReportEngine re) - { - this(null, re); - } - - /** - * Viewer Constructor - * @param gc - * @param re report engine - */ - public Viewer (GraphicsConfiguration gc, ReportEngine re) - { - super(gc); - log.info(""); - m_WindowNo = AEnv.createWindowNo(this); - Env.setContext(re.getCtx(), m_WindowNo, "_WinInfo_IsReportViewer", "Y"); - m_reportEngine = re; - m_AD_Table_ID = re.getPrintFormat().getAD_Table_ID(); - if (!MRole.getDefault().isCanReport(m_AD_Table_ID)) - { - ADialog.error(m_WindowNo, this, "AccessCannotReport", m_reportEngine.getName()); - this.dispose(); - } - m_isCanExport = MRole.getDefault().isCanExport(m_AD_Table_ID); - try - { - m_viewPanel = new View(re.getLayout()); - re.addEventListener(this); - m_ctx = m_reportEngine.getCtx(); - jbInit(); - dynInit(); - if (!m_viewPanel.isArchivable()) - log.warning("Cannot archive Document"); - AEnv.showCenterScreen(this); - } - catch(Exception e) - { - log.log(Level.SEVERE, "", e); - ADialog.error(m_WindowNo, this, "LoadError", e.getLocalizedMessage()); - this.dispose(); - } - } // Viewer - - /** Window No */ - private int m_WindowNo; - /** Print Context */ - private Properties m_ctx; - /** Page No */ - private int m_pageNo = 1; - /** Max Page Number */ - private int m_pageMax = 1; - /** View Pane */ - private View m_viewPanel; - /** Setting Values */ - private boolean m_setting = false; - /** Report Engine */ - private ReportEngine m_reportEngine; - /** Drill Down/Across */ - private boolean m_drillDown = true; - /** Table ID */ - private int m_AD_Table_ID = 0; - private boolean m_isCanExport; - - private MQuery m_ddQ = null; - private MQuery m_daQ = null; - private CMenuItem m_ddM = null; - private CMenuItem m_daM = null; - - /** Logger */ - private static CLogger log = CLogger.getCLogger(Viewer.class); - - // - private CPanel northPanel = new CPanel(); - private JScrollPane centerScrollPane = new JScrollPane(); - private StatusBar statusBar = new StatusBar(false); - private JMenuBar menuBar = new JMenuBar(); - private JToolBar toolBar = new JToolBar(); - private CButton bPrint = new CButton(); - private CButton bSendMail = new CButton(); - private CButton bPageSetup = new CButton(); - private CButton bArchive = new CButton(); - private BorderLayout northLayout = new BorderLayout(); - private CButton bCustomize = new CButton(); - private CButton bEnd = new CButton(); - private CButton bFind = new CButton(); - private CButton bExport = new CButton(); - private CComboBoxcomboReport = new CComboBox(); - private CButton bPrevious = new CButton(); - private CButton bNext = new CButton(); - private SpinnerNumberModel spinnerModel = new SpinnerNumberModel(1,1,100,1); - private JSpinner spinner = new JSpinner(spinnerModel); - private CLabel labelDrill = new CLabel(); +/****************************************************************************** + * 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 * + * Contributor: phib [ 1566335 ] Report View scrolling (Bug 1566328) * + * Teo Sarca [ 1619449 ] Minor typo problem * + *****************************************************************************/ +package org.compiere.print; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.GraphicsConfiguration; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowEvent; +import java.awt.event.WindowStateListener; +import java.io.File; +import java.io.IOException; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Properties; +import java.util.logging.Level; + +import javax.swing.AbstractAction; +import javax.swing.AbstractButton; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JOptionPane; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JSpinner; +import javax.swing.JToolBar; +import javax.swing.KeyStroke; +import javax.swing.SpinnerNumberModel; +import javax.swing.SwingUtilities; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import org.adempiere.pdf.Document; +import org.compiere.apps.ADialog; +import org.compiere.apps.AEnv; +import org.compiere.apps.AMenu; +import org.compiere.apps.AWindow; +import org.compiere.apps.AWindowListener; +import org.compiere.apps.AppsAction; +import org.compiere.apps.EMailDialog; +import org.compiere.apps.StatusBar; +import org.compiere.apps.WindowMenu; +import org.compiere.apps.search.Find; +import org.compiere.model.GridField; +import org.compiere.model.MArchive; +import org.compiere.model.MClient; +import org.compiere.model.MQuery; +import org.compiere.model.MRole; +import org.compiere.model.MUser; +import org.compiere.model.PrintInfo; +import org.compiere.model.X_C_Invoice; +import org.compiere.swing.CButton; +import org.compiere.swing.CCheckBox; +import org.compiere.swing.CComboBox; +import org.compiere.swing.CFrame; +import org.compiere.swing.CLabel; +import org.compiere.swing.CMenuItem; +import org.compiere.swing.CPanel; +import org.compiere.tools.FileUtil; +import org.compiere.util.CLogMgt; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.ExtensionFileFilter; +import org.compiere.util.KeyNamePair; +import org.compiere.util.Language; +import org.compiere.util.Login; +import org.compiere.util.Msg; +import org.compiere.util.NamePair; +import org.compiere.util.ValueNamePair; + +/** + * Print View Frame + * + * @author Jorg Janke + * @version $Id: Viewer.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ + * globalqss: integrate phib contribution from + * http://sourceforge.net/tracker/index.php?func=detail&aid=1566335&group_id=176962&atid=879334 + * globalqss: integrate Teo Sarca bug fixing + * Colin Rooney 2007/03/20 RFE#1670185 & BUG#1684142 + * Extend security to Info queries + * + * @author Teo Sarca, www.arhipac.ro + *
  • FR [ 1762466 ] Add "Window" menu to report viewer. + *
  • FR [ 1779403 ] Report Viewer: add PgUp and PgDown key handlers + *
  • BF [ 1836908 ] Report customize NPE when no window access + *
  • FR [ 1894640 ] Report Engine: Excel Export support + *
  • FR [ 2539927 ] Display Zoom combobox + * https://sourceforge.net/tracker/?func=detail&atid=879335&aid=2539927&group_id=176962 + * @author victor.perez@e-evolution.com + *
  • FR [ 1966328 ] New Window Info to MRP and CRP into View http://sourceforge.net/tracker/index.php?func=detail&aid=1966328&group_id=176962&atid=879335 + *
  • FR [ 2011569 ] Implementing new Summary flag in Report View http://sourceforge.net/tracker/index.php?func=detail&aid=2011569&group_id=176962&atid=879335 + * + */ +public class Viewer extends CFrame + implements ActionListener, ChangeListener, WindowStateListener, IReportEngineEventListener +{ + /** + * + */ + private static final long serialVersionUID = 3766771249690413641L; + + /** + * @deprecated + * Viewer Constructor + * @param re report engine + */ + public Viewer (ReportEngine re) + { + this(null, re); + } + + /** + * Viewer Constructor + * @param gc + * @param re report engine + */ + public Viewer (GraphicsConfiguration gc, ReportEngine re) + { + super(gc); + log.info(""); + m_WindowNo = AEnv.createWindowNo(this); + Env.setContext(re.getCtx(), m_WindowNo, "_WinInfo_IsReportViewer", "Y"); + m_reportEngine = re; + m_AD_Table_ID = re.getPrintFormat().getAD_Table_ID(); + if (!MRole.getDefault().isCanReport(m_AD_Table_ID)) + { + ADialog.error(m_WindowNo, this, "AccessCannotReport", m_reportEngine.getName()); + this.dispose(); + } + m_isCanExport = MRole.getDefault().isCanExport(m_AD_Table_ID); + try + { + m_viewPanel = new View(re.getLayout()); + re.addEventListener(this); + m_ctx = m_reportEngine.getCtx(); + jbInit(); + dynInit(); + if (!m_viewPanel.isArchivable()) + log.warning("Cannot archive Document"); + AEnv.showCenterScreen(this); + } + catch(Exception e) + { + log.log(Level.SEVERE, "", e); + ADialog.error(m_WindowNo, this, "LoadError", e.getLocalizedMessage()); + this.dispose(); + } + } // Viewer + + /** Window No */ + private int m_WindowNo; + /** Print Context */ + private Properties m_ctx; + /** Page No */ + private int m_pageNo = 1; + /** Max Page Number */ + private int m_pageMax = 1; + /** View Pane */ + private View m_viewPanel; + /** Setting Values */ + private boolean m_setting = false; + /** Report Engine */ + private ReportEngine m_reportEngine; + /** Drill Down/Across */ + private boolean m_drillDown = true; + /** Table ID */ + private int m_AD_Table_ID = 0; + private boolean m_isCanExport; + + private MQuery m_ddQ = null; + private MQuery m_daQ = null; + private CMenuItem m_ddM = null; + private CMenuItem m_daM = null; + + /** Logger */ + private static CLogger log = CLogger.getCLogger(Viewer.class); + + // + private CPanel northPanel = new CPanel(); + private JScrollPane centerScrollPane = new JScrollPane(); + private StatusBar statusBar = new StatusBar(false); + private JMenuBar menuBar = new JMenuBar(); + private JToolBar toolBar = new JToolBar(); + private CButton bPrint = new CButton(); + private CButton bSendMail = new CButton(); + private CButton bPageSetup = new CButton(); + private CButton bArchive = new CButton(); + private BorderLayout northLayout = new BorderLayout(); + private CButton bCustomize = new CButton(); + private CButton bEnd = new CButton(); + private CButton bFind = new CButton(); + private CButton bExport = new CButton(); + private CComboBoxcomboReport = new CComboBox(); + private CButton bPrevious = new CButton(); + private CButton bNext = new CButton(); + private SpinnerNumberModel spinnerModel = new SpinnerNumberModel(1,1,100,1); + private JSpinner spinner = new JSpinner(spinnerModel); + private CLabel labelDrill = new CLabel(); private CComboBoxcomboDrill = new CComboBox(); - //FR 201156 + //FR 201156 private CCheckBox summary = new CCheckBox(); - private CComboBoxcomboZoom = new CComboBox(View.ZOOM_OPTIONS); - - - /** - * Static Layout - * @throws Exception - */ - private void jbInit() throws Exception - { - this.setIconImage(Env.getImage("mReport.png")); - this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - // - northPanel.setLayout(northLayout); - this.getContentPane().add(northPanel, BorderLayout.NORTH); - northPanel.add(toolBar, BorderLayout.EAST); - this.getContentPane().add(centerScrollPane, BorderLayout.CENTER); - centerScrollPane.getViewport().add(m_viewPanel, null); - // pb add: set scrolling with scrollbar buttons to move by 20 pixels - // each press - centerScrollPane.getVerticalScrollBar().setUnitIncrement(20); - centerScrollPane.getHorizontalScrollBar().setUnitIncrement(20); - // end pb - this.getContentPane().add(statusBar, BorderLayout.SOUTH); - - // ToolBar - this.setJMenuBar(menuBar); - // Page Control - toolBar.add(bPrevious); - toolBar.add(spinner); - spinner.setToolTipText(Msg.getMsg(m_ctx, "GoToPage")); - toolBar.add(bNext); - - // Add PgUp and PgDown key handlers - teo_sarca FR [ 1779403 ] - m_viewPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) - .put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), "PAGE_UP"); - m_viewPanel.getActionMap().put("PAGE_UP", new AbstractAction() { - private static final long serialVersionUID = -6439939910196779649L; - public void actionPerformed(ActionEvent e) { - setPage(m_pageNo-1); - } - }); - // - m_viewPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) - .put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), "PAGE_DOWN"); - m_viewPanel.getActionMap().put("PAGE_DOWN", new AbstractAction() { - private static final long serialVersionUID = -4468272400181368278L; - public void actionPerformed(ActionEvent e) { - setPage(m_pageNo+1); - } - }); - - // Zoom Level - toolBar.addSeparator(); - toolBar.add(comboZoom, null); - comboZoom.setToolTipText(Msg.getMsg(m_ctx, "Zoom")); - // Drill - toolBar.addSeparator(); - labelDrill.setText(Msg.getMsg(m_ctx, "Drill") + ": "); - toolBar.add(labelDrill); - toolBar.add(comboDrill); - comboDrill.setToolTipText(Msg.getMsg(m_ctx, "Drill")); - // Format, Customize, Find - toolBar.addSeparator(); - toolBar.add(comboReport); - comboReport.setToolTipText(Msg.translate(m_ctx, "AD_PrintFormat_ID")); - //FR 201156 - toolBar.add(summary); - summary.setText(Msg.getMsg(m_ctx, "Summary")); - toolBar.add(bCustomize); - bCustomize.setToolTipText(Msg.getMsg(m_ctx, "PrintCustomize")); - toolBar.add(bFind); - bFind.setToolTipText(Msg.getMsg(m_ctx, "Find")); - toolBar.addSeparator(); - // Print/Export - toolBar.add(bPrint); - toolBar.addSeparator(); - toolBar.add(bPageSetup); - bPageSetup.setToolTipText(Msg.getMsg(m_ctx, "PageSetup")); - toolBar.add(bSendMail); - toolBar.add(bArchive); - if (m_isCanExport) - { - bExport.setToolTipText(Msg.getMsg(m_ctx, "Export")); - toolBar.add(bExport); - } - // End - toolBar.addSeparator(); - toolBar.add(bEnd, null); - bEnd.setToolTipText(Msg.getMsg(m_ctx, "End")); - } // jbInit - - /** - * Dynamic Init - */ - private void dynInit() - { - createMenu(); - comboZoom.setSelectedIndex(m_viewPanel.getZoomLevel()); - comboZoom.addActionListener(this); - // Change Listener to set Page no - //pb comment this out so that scrolling works normally - //centerScrollPane.getViewport().addChangeListener(this); + private CComboBoxcomboZoom = new CComboBox(View.ZOOM_OPTIONS); + + + /** + * Static Layout + * @throws Exception + */ + private void jbInit() throws Exception + { + this.setIconImage(Env.getImage("mReport.png")); + this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + // + northPanel.setLayout(northLayout); + this.getContentPane().add(northPanel, BorderLayout.NORTH); + northPanel.add(toolBar, BorderLayout.EAST); + this.getContentPane().add(centerScrollPane, BorderLayout.CENTER); + centerScrollPane.getViewport().add(m_viewPanel, null); + // pb add: set scrolling with scrollbar buttons to move by 20 pixels + // each press + centerScrollPane.getVerticalScrollBar().setUnitIncrement(20); + centerScrollPane.getHorizontalScrollBar().setUnitIncrement(20); // end pb - //FR 201156 + this.getContentPane().add(statusBar, BorderLayout.SOUTH); + + // ToolBar + this.setJMenuBar(menuBar); + // Page Control + toolBar.add(bPrevious); + toolBar.add(spinner); + spinner.setToolTipText(Msg.getMsg(m_ctx, "GoToPage")); + toolBar.add(bNext); + + // Add PgUp and PgDown key handlers - teo_sarca FR [ 1779403 ] + m_viewPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), "PAGE_UP"); + m_viewPanel.getActionMap().put("PAGE_UP", new AbstractAction() { + private static final long serialVersionUID = -6439939910196779649L; + public void actionPerformed(ActionEvent e) { + setPage(m_pageNo-1); + } + }); + // + m_viewPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), "PAGE_DOWN"); + m_viewPanel.getActionMap().put("PAGE_DOWN", new AbstractAction() { + private static final long serialVersionUID = -4468272400181368278L; + public void actionPerformed(ActionEvent e) { + setPage(m_pageNo+1); + } + }); + + // Zoom Level + toolBar.addSeparator(); + toolBar.add(comboZoom, null); + comboZoom.setToolTipText(Msg.getMsg(m_ctx, "Zoom")); + // Drill + toolBar.addSeparator(); + labelDrill.setText(Msg.getMsg(m_ctx, "Drill") + ": "); + toolBar.add(labelDrill); + toolBar.add(comboDrill); + comboDrill.setToolTipText(Msg.getMsg(m_ctx, "Drill")); + // Format, Customize, Find + toolBar.addSeparator(); + toolBar.add(comboReport); + comboReport.setToolTipText(Msg.translate(m_ctx, "AD_PrintFormat_ID")); + //FR 201156 + toolBar.add(summary); + summary.setText(Msg.getMsg(m_ctx, "Summary")); + toolBar.add(bCustomize); + bCustomize.setToolTipText(Msg.getMsg(m_ctx, "PrintCustomize")); + toolBar.add(bFind); + bFind.setToolTipText(Msg.getMsg(m_ctx, "Find")); + toolBar.addSeparator(); + // Print/Export + toolBar.add(bPrint); + toolBar.addSeparator(); + toolBar.add(bPageSetup); + bPageSetup.setToolTipText(Msg.getMsg(m_ctx, "PageSetup")); + toolBar.add(bSendMail); + toolBar.add(bArchive); + if (m_isCanExport) + { + bExport.setToolTipText(Msg.getMsg(m_ctx, "Export")); + toolBar.add(bExport); + } + // End + toolBar.addSeparator(); + toolBar.add(bEnd, null); + bEnd.setToolTipText(Msg.getMsg(m_ctx, "End")); + } // jbInit + + /** + * Dynamic Init + */ + private void dynInit() + { + createMenu(); + comboZoom.setSelectedIndex(m_viewPanel.getZoomLevel()); + comboZoom.addActionListener(this); + // Change Listener to set Page no + //pb comment this out so that scrolling works normally + //centerScrollPane.getViewport().addChangeListener(this); + // end pb + //FR 201156 summary.addActionListener(this); - // Max Page - m_pageMax = m_viewPanel.getPageCount(); - spinnerModel.setMaximum(Integer.valueOf(m_pageMax)); - spinner.addChangeListener(this); - - fillComboReport(m_reportEngine.getPrintFormat().get_ID()); - - // View Panel Mouse Listener - m_viewPanel.addMouseListener(new MouseAdapter() - { - public void mouseClicked(MouseEvent e) - { - if (SwingUtilities.isRightMouseButton(e)) - mouse_clicked(e,true); - else if (e.getClickCount() > 1) - mouse_clicked(e,false); - } - }); - - // fill Drill Options (Name, TableName) - comboDrill.addItem(new ValueNamePair (null,"")); - String sql = "SELECT t.AD_Table_ID, t.TableName, e.PrintName, NULLIF(e.PO_PrintName,e.PrintName) " - + "FROM AD_Column c " - + " INNER JOIN AD_Column used ON (c.ColumnName=used.ColumnName)" - + " INNER JOIN AD_Table t ON (used.AD_Table_ID=t.AD_Table_ID AND t.IsView='N' AND t.AD_Table_ID <> c.AD_Table_ID)" - + " INNER JOIN AD_Column cKey ON (t.AD_Table_ID=cKey.AD_Table_ID AND cKey.IsKey='Y')" - + " INNER JOIN AD_Element e ON (cKey.ColumnName=e.ColumnName) " - + "WHERE c.AD_Table_ID=? AND c.IsKey='Y' " - + "ORDER BY 3"; - boolean trl = !Env.isBaseLanguage(Env.getCtx(), "AD_Element"); - if (trl) - sql = "SELECT t.AD_Table_ID, t.TableName, et.PrintName, NULLIF(et.PO_PrintName,et.PrintName) " - + "FROM AD_Column c" - + " INNER JOIN AD_Column used ON (c.ColumnName=used.ColumnName)" - + " INNER JOIN AD_Table t ON (used.AD_Table_ID=t.AD_Table_ID AND t.IsView='N' AND t.AD_Table_ID <> c.AD_Table_ID)" - + " INNER JOIN AD_Column cKey ON (t.AD_Table_ID=cKey.AD_Table_ID AND cKey.IsKey='Y')" - + " INNER JOIN AD_Element e ON (cKey.ColumnName=e.ColumnName)" - + " INNER JOIN AD_Element_Trl et ON (e.AD_Element_ID=et.AD_Element_ID) " - + "WHERE c.AD_Table_ID=? AND c.IsKey='Y'" - + " AND et.AD_Language=? " - + "ORDER BY 3"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, m_reportEngine.getPrintFormat().getAD_Table_ID()); - if (trl) - pstmt.setString(2, Env.getAD_Language(Env.getCtx())); - rs = pstmt.executeQuery(); - while (rs.next()) - { - String tableName = rs.getString(2); - String name = rs.getString(3); - String poName = rs.getString(4); - if (poName != null) - name += "/" + poName; - comboDrill.addItem(new ValueNamePair (tableName, name)); - } - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; - pstmt = null; - } - if (comboDrill.getItemCount() == 1) - { - labelDrill.setVisible(false); - comboDrill.setVisible(false); - } - else - comboDrill.addActionListener(this); - - revalidate(); - } // dynInit - - /** - * Fill ComboBox comboReport (report options) - * @param AD_PrintFormat_ID item to be selected - */ - private void fillComboReport(int AD_PrintFormat_ID) - { - comboReport.removeActionListener(this); - comboReport.removeAllItems(); - KeyNamePair selectValue = null; - - int AD_Window_ID = Env.getContextAsInt(Env.getCtx(), m_reportEngine.getWindowNo(), "_WinInfo_AD_Window_ID", true); - if (AD_Window_ID == 0) - AD_Window_ID = Env.getZoomWindowID(m_reportEngine.getQuery()); - // fill Report Options - String sql = MRole.getDefault().addAccessSQL( - "SELECT AD_PrintFormat_ID, Name, Description " - + "FROM AD_PrintFormat " - + "WHERE AD_Table_ID=? " - //Added Lines by Armen - + "AND IsActive='Y' " - //End of Added Lines - + (AD_Window_ID > 0 ? "AND (AD_Window_ID=? OR AD_Window_ID IS NULL) " : "") - + "ORDER BY Name", - "AD_PrintFormat", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); - int AD_Table_ID = m_reportEngine.getPrintFormat().getAD_Table_ID(); - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, AD_Table_ID); - if (AD_Window_ID > 0) - pstmt.setInt(2, AD_Window_ID); - rs = pstmt.executeQuery(); - while (rs.next()) - { - KeyNamePair pp = new KeyNamePair(rs.getInt(1), rs.getString(2)); - comboReport.addItem(pp); - if (rs.getInt(1) == AD_PrintFormat_ID) - selectValue = pp; - } - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; - pstmt = null; - } - // IDEMPIERE-297 - Check for Table Access and Window Access for New Report - int pfAD_Window_ID = MPrintFormat.getZoomWindowID(AD_PrintFormat_ID); - if ( MRole.getDefault().isTableAccess(MPrintFormat.Table_ID, false) - && (Boolean.TRUE.equals(MRole.getDefault().getWindowAccess(pfAD_Window_ID)))) - { - StringBuffer sb = new StringBuffer("** ").append(Msg.getMsg(m_ctx, "NewReport")).append(" **"); - KeyNamePair pp = new KeyNamePair(-1, sb.toString()); - comboReport.addItem(pp); - } - if (selectValue != null) - comboReport.setSelectedItem(selectValue); - comboReport.addActionListener(this); - } // fillComboReport - - /** - * Revalidate settings after change of environment - */ - public void revalidate() - { - m_pageMax = m_viewPanel.getPageCount(); - spinnerModel.setMaximum(Integer.valueOf(m_pageMax)); - - // scroll area (page size dependent) - centerScrollPane.setPreferredSize(new Dimension - (m_viewPanel.getPaperWidth()+30, m_viewPanel.getPaperHeight()+15)); - centerScrollPane.getViewport().setViewSize(new Dimension - (m_viewPanel.getPaperWidth()+2*m_viewPanel.getMarginSize(true), - m_viewPanel.getPaperHeight()+2*m_viewPanel.getMarginSize(true))); - - // Report Info - setTitle(Msg.getMsg(m_ctx, "Report") + ": " + m_reportEngine.getName() + " " + Env.getHeader(m_ctx, 0)); - StringBuilder sb = new StringBuilder (); - sb.append(m_viewPanel.getPaper().toString(m_ctx)) - .append(" - ").append(Msg.getMsg(m_ctx, "DataCols")).append("=") - .append(m_reportEngine.getColumnCount()) - .append(", ").append(Msg.getMsg(m_ctx, "DataRows")).append("=") - .append(m_reportEngine.getRowCount()); - statusBar.setStatusLine(sb.toString()); - // - setPage(m_pageNo); - } // revalidate - - - /** - * Create Menu - */ - private void createMenu() - { - // File - JMenu mFile = AEnv.getMenu("File"); - menuBar.add(mFile); - AEnv.addMenuItem("PrintScreen", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, 0), mFile, this); - AEnv.addMenuItem("ScreenShot", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, ActionEvent.SHIFT_MASK), mFile, this); - AEnv.addMenuItem("Report", null, KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.ALT_MASK), mFile, this); - mFile.addSeparator(); - AEnv.addMenuItem("PrintCustomize", "Preference", null, mFile, this); - AEnv.addMenuItem("Translate", null, null, mFile, this); - AEnv.addMenuItem("Find", null, KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK), mFile, this); - mFile.addSeparator(); - AEnv.addMenuItem("PageSetup", null, null, mFile, this); - AEnv.addMenuItem("Print", null, KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK), mFile, this); - if (m_isCanExport) - AEnv.addMenuItem("Export", null, null, mFile, this); - mFile.addSeparator(); - AEnv.addMenuItem("End", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK), mFile, this); - AEnv.addMenuItem("Logout", null, KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.SHIFT_MASK+ActionEvent.ALT_MASK), mFile, this); - AEnv.addMenuItem("Exit", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.SHIFT_MASK+ActionEvent.ALT_MASK), mFile, this); - - // View - JMenu mView = AEnv.getMenu("View"); - menuBar.add(mView); - - if (MRole.getDefault().isAllow_Info_Product()) - { - AEnv.addMenuItem("InfoProduct", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK), mView, this); - } - if (MRole.getDefault().isAllow_Info_BPartner()) - { - AEnv.addMenuItem("InfoBPartner", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK+ActionEvent.CTRL_MASK), mView, this); - } - if (MRole.getDefault().isShowAcct() && MRole.getDefault().isAllow_Info_Account()) - { - AEnv.addMenuItem("InfoAccount", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK+ActionEvent.CTRL_MASK), mView, this); - } - if (MRole.getDefault().isAllow_Info_Schedule()) - { - AEnv.addMenuItem("InfoSchedule", null, null, mView, this); - } - //FR [ 1966328 ] -// if (MRole.getDefault().isAllow_Info_MRP()) -// { -// AEnv.addMenuItem("InfoMRP", "Info", null, mView, this); -// } -// if (MRole.getDefault().isAllow_Info_CRP()) -// { -// AEnv.addMenuItem("InfoCRP", "Info", null, mView, this); -// } - mView.addSeparator(); - if (MRole.getDefault().isAllow_Info_Order()) - { - AEnv.addMenuItem("InfoOrder", "Info", null, mView, this); - } - if (MRole.getDefault().isAllow_Info_Invoice()) - { - AEnv.addMenuItem("InfoInvoice", "Info", null, mView, this); - } - if (MRole.getDefault().isAllow_Info_InOut()) - { - AEnv.addMenuItem("InfoInOut", "Info", null, mView, this); - } - if (MRole.getDefault().isAllow_Info_Payment()) - { - AEnv.addMenuItem("InfoPayment", "Info", null, mView, this); - } -// if (MRole.getDefault().isAllow_Info_CashJournal()) -// { -// AEnv.addMenuItem("InfoCashLine", "Info", null, mView, this); -// } - if (MRole.getDefault().isAllow_Info_Resource()) - { - AEnv.addMenuItem("InfoAssignment", "Info", null, mView, this); - } - if (MRole.getDefault().isAllow_Info_Asset()) - { - AEnv.addMenuItem("InfoAsset", "Info", null, mView, this); - } - - - // Go - JMenu mGo = AEnv.getMenu("Go"); - menuBar.add(mGo); - AEnv.addMenuItem("First", "First", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, ActionEvent.ALT_MASK), mGo, this); - AEnv.addMenuItem("PreviousPage", "Previous", KeyStroke.getKeyStroke(KeyEvent.VK_UP, ActionEvent.ALT_MASK), mGo, this); - AEnv.addMenuItem("NextPage", "Next", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, ActionEvent.ALT_MASK), mGo, this); - AEnv.addMenuItem("Last", "Last", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, ActionEvent.ALT_MASK), mGo, this); - - // Tools - JMenu mTools = AEnv.getMenu("Tools"); - menuBar.add(mTools); - AEnv.addMenuItem("Calculator", null, null, mTools, this); - AEnv.addMenuItem("Calendar", null, null, mTools, this); - MUser user = MUser.get(Env.getCtx()); - if (user.isAdministrator()) - AEnv.addMenuItem("Editor", null, null, mTools, this); - AEnv.addMenuItem("Script", null, null, mTools, this); - mTools.addSeparator(); - AEnv.addMenuItem("Preference", null, null, mTools, this); - - // Window - AMenu aMenu = (AMenu)AEnv.getWindow(0); - JMenu mWindow = new WindowMenu(aMenu.getWindowManager(), this); - menuBar.add(mWindow); - - // Help - JMenu mHelp = AEnv.getMenu("Help"); - menuBar.add(mHelp); - AEnv.addMenuItem("Online", null, null, mHelp, this); - AEnv.addMenuItem("SendMail", null, null, mHelp, this); - AEnv.addMenuItem("About", null, null, mHelp, this); - - // ---- ToolBar ---- - // - setButton(bPrint, "Print", "Print"); - setButton(bSendMail, "SendMail", "SendMail"); - setButton(bPageSetup, "PageSetup", "PageSetup"); - setButton(bArchive, "Archive", "Archive"); - if (m_isCanExport) - setButton(bExport, "Export", "Export"); - // - setButton(bNext, "NextPage", "Next"); - setButton(bPrevious, "PreviousPage", "Previous"); - // - setButton(bFind, "Find", "Find"); - setButton(bCustomize, "PrintCustomize", "Preference"); - // - setButton(bEnd, "End", "End"); - } // createMenu - - /** - * Set Button - * @param button button - * @param cmd command - * @param file fine mame - */ - private void setButton (AbstractButton button, String cmd, String file) - { - String text = Msg.getMsg(m_ctx, cmd); - button.setToolTipText(text); - button.setActionCommand(cmd); - // - ImageIcon ii24 = Env.getImageIcon(file+"24.gif"); - if (ii24 != null) - button.setIcon(ii24); - button.setMargin(AppsAction.BUTTON_INSETS); - button.setPreferredSize(AppsAction.BUTTON_SIZE); - button.addActionListener(this); - } // setButton - - /** - * Dispose - */ - public void dispose() - { - Env.clearWinContext(m_WindowNo); - m_reportEngine = null; - m_viewPanel = null; - m_ctx = null; - super.dispose(); - } // dispose - - - /************************************************************************** - * Action Listener - * @param e event - */ - public void actionPerformed (ActionEvent e) - { - if (m_setting) - return; - String cmd = e.getActionCommand(); - log.config(cmd); - this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - // - if (e.getSource() == comboZoom) - cmd_zoom(); - else if (e.getSource() == comboReport) - cmd_report(); - else if (e.getSource() == comboDrill) + // Max Page + m_pageMax = m_viewPanel.getPageCount(); + spinnerModel.setMaximum(Integer.valueOf(m_pageMax)); + spinner.addChangeListener(this); + + fillComboReport(m_reportEngine.getPrintFormat().get_ID()); + + // View Panel Mouse Listener + m_viewPanel.addMouseListener(new MouseAdapter() + { + public void mouseClicked(MouseEvent e) + { + if (SwingUtilities.isRightMouseButton(e)) + mouse_clicked(e,true); + else if (e.getClickCount() > 1) + mouse_clicked(e,false); + } + }); + + // fill Drill Options (Name, TableName) + comboDrill.addItem(new ValueNamePair (null,"")); + String sql = "SELECT t.AD_Table_ID, t.TableName, e.PrintName, NULLIF(e.PO_PrintName,e.PrintName) " + + "FROM AD_Column c " + + " INNER JOIN AD_Column used ON (c.ColumnName=used.ColumnName)" + + " INNER JOIN AD_Table t ON (used.AD_Table_ID=t.AD_Table_ID AND t.IsView='N' AND t.AD_Table_ID <> c.AD_Table_ID)" + + " INNER JOIN AD_Column cKey ON (t.AD_Table_ID=cKey.AD_Table_ID AND cKey.IsKey='Y')" + + " INNER JOIN AD_Element e ON (cKey.ColumnName=e.ColumnName) " + + "WHERE c.AD_Table_ID=? AND c.IsKey='Y' " + + "ORDER BY 3"; + boolean trl = !Env.isBaseLanguage(Env.getCtx(), "AD_Element"); + if (trl) + sql = "SELECT t.AD_Table_ID, t.TableName, et.PrintName, NULLIF(et.PO_PrintName,et.PrintName) " + + "FROM AD_Column c" + + " INNER JOIN AD_Column used ON (c.ColumnName=used.ColumnName)" + + " INNER JOIN AD_Table t ON (used.AD_Table_ID=t.AD_Table_ID AND t.IsView='N' AND t.AD_Table_ID <> c.AD_Table_ID)" + + " INNER JOIN AD_Column cKey ON (t.AD_Table_ID=cKey.AD_Table_ID AND cKey.IsKey='Y')" + + " INNER JOIN AD_Element e ON (cKey.ColumnName=e.ColumnName)" + + " INNER JOIN AD_Element_Trl et ON (e.AD_Element_ID=et.AD_Element_ID) " + + "WHERE c.AD_Table_ID=? AND c.IsKey='Y'" + + " AND et.AD_Language=? " + + "ORDER BY 3"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, m_reportEngine.getPrintFormat().getAD_Table_ID()); + if (trl) + pstmt.setString(2, Env.getAD_Language(Env.getCtx())); + rs = pstmt.executeQuery(); + while (rs.next()) + { + String tableName = rs.getString(2); + String name = rs.getString(3); + String poName = rs.getString(4); + if (poName != null) + name += "/" + poName; + comboDrill.addItem(new ValueNamePair (tableName, name)); + } + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; + pstmt = null; + } + if (comboDrill.getItemCount() == 1) + { + labelDrill.setVisible(false); + comboDrill.setVisible(false); + } + else + comboDrill.addActionListener(this); + + revalidate(); + } // dynInit + + /** + * Fill ComboBox comboReport (report options) + * @param AD_PrintFormat_ID item to be selected + */ + private void fillComboReport(int AD_PrintFormat_ID) + { + comboReport.removeActionListener(this); + comboReport.removeAllItems(); + KeyNamePair selectValue = null; + + int AD_Window_ID = Env.getContextAsInt(Env.getCtx(), m_reportEngine.getWindowNo(), "_WinInfo_AD_Window_ID", true); + if (AD_Window_ID == 0) + AD_Window_ID = Env.getZoomWindowID(m_reportEngine.getQuery()); + // fill Report Options + String sql = MRole.getDefault().addAccessSQL( + "SELECT AD_PrintFormat_ID, Name, Description " + + "FROM AD_PrintFormat " + + "WHERE AD_Table_ID=? " + //Added Lines by Armen + + "AND IsActive='Y' " + //End of Added Lines + + (AD_Window_ID > 0 ? "AND (AD_Window_ID=? OR AD_Window_ID IS NULL) " : "") + + "ORDER BY Name", + "AD_PrintFormat", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); + int AD_Table_ID = m_reportEngine.getPrintFormat().getAD_Table_ID(); + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Table_ID); + if (AD_Window_ID > 0) + pstmt.setInt(2, AD_Window_ID); + rs = pstmt.executeQuery(); + while (rs.next()) + { + KeyNamePair pp = new KeyNamePair(rs.getInt(1), rs.getString(2)); + comboReport.addItem(pp); + if (rs.getInt(1) == AD_PrintFormat_ID) + selectValue = pp; + } + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; + pstmt = null; + } + // IDEMPIERE-297 - Check for Table Access and Window Access for New Report + int pfAD_Window_ID = MPrintFormat.getZoomWindowID(AD_PrintFormat_ID); + if ( MRole.getDefault().isTableAccess(MPrintFormat.Table_ID, false) + && (Boolean.TRUE.equals(MRole.getDefault().getWindowAccess(pfAD_Window_ID)))) + { + StringBuffer sb = new StringBuffer("** ").append(Msg.getMsg(m_ctx, "NewReport")).append(" **"); + KeyNamePair pp = new KeyNamePair(-1, sb.toString()); + comboReport.addItem(pp); + } + if (selectValue != null) + comboReport.setSelectedItem(selectValue); + comboReport.addActionListener(this); + } // fillComboReport + + /** + * Revalidate settings after change of environment + */ + public void revalidate() + { + m_pageMax = m_viewPanel.getPageCount(); + spinnerModel.setMaximum(Integer.valueOf(m_pageMax)); + + // scroll area (page size dependent) + centerScrollPane.setPreferredSize(new Dimension + (m_viewPanel.getPaperWidth()+30, m_viewPanel.getPaperHeight()+15)); + centerScrollPane.getViewport().setViewSize(new Dimension + (m_viewPanel.getPaperWidth()+2*m_viewPanel.getMarginSize(true), + m_viewPanel.getPaperHeight()+2*m_viewPanel.getMarginSize(true))); + + // Report Info + setTitle(Msg.getMsg(m_ctx, "Report") + ": " + m_reportEngine.getName() + " " + Env.getHeader(m_ctx, 0)); + StringBuilder sb = new StringBuilder (); + sb.append(m_viewPanel.getPaper().toString(m_ctx)) + .append(" - ").append(Msg.getMsg(m_ctx, "DataCols")).append("=") + .append(m_reportEngine.getColumnCount()) + .append(", ").append(Msg.getMsg(m_ctx, "DataRows")).append("=") + .append(m_reportEngine.getRowCount()); + statusBar.setStatusLine(sb.toString()); + // + setPage(m_pageNo); + } // revalidate + + + /** + * Create Menu + */ + private void createMenu() + { + // File + JMenu mFile = AEnv.getMenu("File"); + menuBar.add(mFile); + AEnv.addMenuItem("PrintScreen", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, 0), mFile, this); + AEnv.addMenuItem("ScreenShot", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, ActionEvent.SHIFT_MASK), mFile, this); + AEnv.addMenuItem("Report", null, KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.ALT_MASK), mFile, this); + mFile.addSeparator(); + AEnv.addMenuItem("PrintCustomize", "Preference", null, mFile, this); + AEnv.addMenuItem("Translate", null, null, mFile, this); + AEnv.addMenuItem("Find", null, KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK), mFile, this); + mFile.addSeparator(); + AEnv.addMenuItem("PageSetup", null, null, mFile, this); + AEnv.addMenuItem("Print", null, KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK), mFile, this); + if (m_isCanExport) + AEnv.addMenuItem("Export", null, null, mFile, this); + mFile.addSeparator(); + AEnv.addMenuItem("End", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK), mFile, this); + AEnv.addMenuItem("Logout", null, KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.SHIFT_MASK+ActionEvent.ALT_MASK), mFile, this); + AEnv.addMenuItem("Exit", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.SHIFT_MASK+ActionEvent.ALT_MASK), mFile, this); + + // View + JMenu mView = AEnv.getMenu("View"); + menuBar.add(mView); + + if (MRole.getDefault().isAllow_Info_Product()) + { + AEnv.addMenuItem("InfoProduct", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK), mView, this); + } + if (MRole.getDefault().isAllow_Info_BPartner()) + { + AEnv.addMenuItem("InfoBPartner", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK+ActionEvent.CTRL_MASK), mView, this); + } + if (MRole.getDefault().isShowAcct() && MRole.getDefault().isAllow_Info_Account()) + { + AEnv.addMenuItem("InfoAccount", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK+ActionEvent.CTRL_MASK), mView, this); + } + if (MRole.getDefault().isAllow_Info_Schedule()) + { + AEnv.addMenuItem("InfoSchedule", null, null, mView, this); + } + //FR [ 1966328 ] +// if (MRole.getDefault().isAllow_Info_MRP()) +// { +// AEnv.addMenuItem("InfoMRP", "Info", null, mView, this); +// } +// if (MRole.getDefault().isAllow_Info_CRP()) +// { +// AEnv.addMenuItem("InfoCRP", "Info", null, mView, this); +// } + mView.addSeparator(); + if (MRole.getDefault().isAllow_Info_Order()) + { + AEnv.addMenuItem("InfoOrder", "Info", null, mView, this); + } + if (MRole.getDefault().isAllow_Info_Invoice()) + { + AEnv.addMenuItem("InfoInvoice", "Info", null, mView, this); + } + if (MRole.getDefault().isAllow_Info_InOut()) + { + AEnv.addMenuItem("InfoInOut", "Info", null, mView, this); + } + if (MRole.getDefault().isAllow_Info_Payment()) + { + AEnv.addMenuItem("InfoPayment", "Info", null, mView, this); + } +// if (MRole.getDefault().isAllow_Info_CashJournal()) +// { +// AEnv.addMenuItem("InfoCashLine", "Info", null, mView, this); +// } + if (MRole.getDefault().isAllow_Info_Resource()) + { + AEnv.addMenuItem("InfoAssignment", "Info", null, mView, this); + } + if (MRole.getDefault().isAllow_Info_Asset()) + { + AEnv.addMenuItem("InfoAsset", "Info", null, mView, this); + } + + + // Go + JMenu mGo = AEnv.getMenu("Go"); + menuBar.add(mGo); + AEnv.addMenuItem("First", "First", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, ActionEvent.ALT_MASK), mGo, this); + AEnv.addMenuItem("PreviousPage", "Previous", KeyStroke.getKeyStroke(KeyEvent.VK_UP, ActionEvent.ALT_MASK), mGo, this); + AEnv.addMenuItem("NextPage", "Next", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, ActionEvent.ALT_MASK), mGo, this); + AEnv.addMenuItem("Last", "Last", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, ActionEvent.ALT_MASK), mGo, this); + + // Tools + JMenu mTools = AEnv.getMenu("Tools"); + menuBar.add(mTools); + AEnv.addMenuItem("Calculator", null, null, mTools, this); + AEnv.addMenuItem("Calendar", null, null, mTools, this); + MUser user = MUser.get(Env.getCtx()); + if (user.isAdministrator()) + AEnv.addMenuItem("Editor", null, null, mTools, this); + AEnv.addMenuItem("Script", null, null, mTools, this); + mTools.addSeparator(); + AEnv.addMenuItem("Preference", null, null, mTools, this); + + // Window + AMenu aMenu = (AMenu)AEnv.getWindow(0); + JMenu mWindow = new WindowMenu(aMenu.getWindowManager(), this); + menuBar.add(mWindow); + + // Help + JMenu mHelp = AEnv.getMenu("Help"); + menuBar.add(mHelp); + AEnv.addMenuItem("Online", null, null, mHelp, this); + AEnv.addMenuItem("SendMail", null, null, mHelp, this); + AEnv.addMenuItem("About", null, null, mHelp, this); + + // ---- ToolBar ---- + // + setButton(bPrint, "Print", "Print"); + setButton(bSendMail, "SendMail", "SendMail"); + setButton(bPageSetup, "PageSetup", "PageSetup"); + setButton(bArchive, "Archive", "Archive"); + if (m_isCanExport) + setButton(bExport, "Export", "Export"); + // + setButton(bNext, "NextPage", "Next"); + setButton(bPrevious, "PreviousPage", "Previous"); + // + setButton(bFind, "Find", "Find"); + setButton(bCustomize, "PrintCustomize", "Preference"); + // + setButton(bEnd, "End", "End"); + } // createMenu + + /** + * Set Button + * @param button button + * @param cmd command + * @param file fine mame + */ + private void setButton (AbstractButton button, String cmd, String file) + { + String text = Msg.getMsg(m_ctx, cmd); + button.setToolTipText(text); + button.setActionCommand(cmd); + // + ImageIcon ii24 = Env.getImageIcon(file+"24.gif"); + if (ii24 != null) + button.setIcon(ii24); + button.setMargin(AppsAction.BUTTON_INSETS); + button.setPreferredSize(AppsAction.BUTTON_SIZE); + button.addActionListener(this); + } // setButton + + /** + * Dispose + */ + public void dispose() + { + Env.clearWinContext(m_WindowNo); + m_reportEngine = null; + m_viewPanel = null; + m_ctx = null; + super.dispose(); + } // dispose + + + /************************************************************************** + * Action Listener + * @param e event + */ + public void actionPerformed (ActionEvent e) + { + if (m_setting) + return; + String cmd = e.getActionCommand(); + log.config(cmd); + this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + // + if (e.getSource() == comboZoom) + cmd_zoom(); + else if (e.getSource() == comboReport) + cmd_report(); + else if (e.getSource() == comboDrill) cmd_drill(); - else if (e.getSource() == summary) //FR 201156 - { - m_reportEngine.setSummary(summary.isSelected()); - cmd_report(); + else if (e.getSource() == summary) //FR 201156 + { + m_reportEngine.setSummary(summary.isSelected()); + cmd_report(); } - else if (cmd.equals("First")) - setPage(1); - else if (cmd.equals("PreviousPage") || cmd.equals("Previous")) - setPage(m_pageNo-1); - else if (cmd.equals("NextPage") || cmd.equals("Next")) - setPage(m_pageNo+1); - else if (cmd.equals("Last")) - setPage(m_pageMax); - else if (cmd.equals("Find")) - cmd_find(); - else if (cmd.equals("Export")) - cmd_export(); - else if (cmd.equals("Print")) - cmd_print(); - else if (cmd.equals("SendMail")) - cmd_sendMail(); - else if (cmd.equals("Archive")) - cmd_archive(); - else if (cmd.equals("PrintCustomize")) - cmd_customize(); - else if (cmd.equals("PageSetup")) - cmd_pageSetup(); - else if (cmd.equals("Translate")) - cmd_translate(); - else if (cmd.equals("End")) - dispose(); - // - else if (e.getSource() == m_ddM) - cmd_window(m_ddQ); - else if (e.getSource() == m_daM) - cmd_window(m_daQ); - // - else if (!AEnv.actionPerformed(e.getActionCommand(), m_WindowNo, this)) - log.log(Level.SEVERE, "unknown action=" + e.getActionCommand()); - // - this.setCursor(Cursor.getDefaultCursor()); - } // actionPerformed - - /** - * Change Listener (spinner, viewpoint) - * @param e event - */ - public void stateChanged (ChangeEvent e) - { - if (m_setting) - return; - // log.config( "Viewer.stateChanged", e); - m_setting = true; - int newPage = 0; - if (e.getSource() == spinner) - { - newPage = ((Integer)spinnerModel.getValue()).intValue(); - } - // pb with the viewport change listener disabled the following is - // superfluous and should be removed - else // Viewpoint - { - Point p = centerScrollPane.getViewport().getViewPosition(); - newPage = Math.round(m_viewPanel.getPageNoAt(p)); - } - setPage(newPage); - m_setting = false; - } // stateChanged - - - /** - * Set Page No - * @param page page no - */ - private void setPage (int page) - { - m_setting = true; - m_pageNo = page; - if (m_pageNo < 1) - m_pageNo = 1; - if (page > m_pageMax) - m_pageNo = m_pageMax; - bPrevious.setEnabled (m_pageNo != 1); - bNext.setEnabled (m_pageNo != m_pageMax); - // - Rectangle pageRectangle = m_viewPanel.getRectangleOfPage(m_pageNo); - pageRectangle.x -= m_viewPanel.getMarginSize(true); - pageRectangle.y -= m_viewPanel.getMarginSize(true); - centerScrollPane.getViewport().setViewPosition(pageRectangle.getLocation()); - // System.out.println("scrollTo " + pageRectangle); - - // Set Page - spinnerModel.setValue(Integer.valueOf(m_pageNo)); - StringBuffer sb = new StringBuffer (Msg.getMsg(m_ctx, "Page")) - .append(" ").append(m_pageNo) - .append(m_viewPanel.getPageInfo(m_pageNo)) - .append(" ").append(Msg.getMsg(m_ctx, "of")).append(" ") - .append(m_pageMax) - .append(m_viewPanel.getPageInfoMax()); - statusBar.setStatusDB(sb.toString()); - m_setting = false; - } // setPage - - - /************************************************************************** - * (Re)Set Drill Accross Cursor - */ - private void cmd_drill() - { - m_drillDown = comboDrill.getSelectedIndex() < 1; // -1 or 0 - if (m_drillDown) - setCursor(Cursor.getDefaultCursor()); - else - setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - } // cmd_drill - - /** - * Mouse clicked - * @param e event - * @param rightClick true if right click - */ - private void mouse_clicked (MouseEvent e, boolean rightClick) - { - Point point = e.getPoint(); - if (log.isLoggable(Level.INFO)) log.info("Right=" + rightClick + " - " + point.toString()); - if (rightClick) - { - m_ddQ = m_viewPanel.getDrillDown(point); - m_daQ = m_viewPanel.getDrillAcross(point); - m_ddM = null; - m_daM = null; - if (m_ddQ == null && m_daQ == null) - return; - // Create Menu - JPopupMenu pop = new JPopupMenu(); - Icon wi = Env.getImageIcon("mWindow.png"); - if (m_ddQ != null) - { - m_ddM = new CMenuItem(m_ddQ.getDisplayName(Env.getCtx()), wi); - m_ddM.setToolTipText(m_ddQ.toString()); - m_ddM.addActionListener(this); - pop.add(m_ddM); - } - if (m_daQ != null) - { - m_daM = new CMenuItem(m_daQ.getDisplayName(Env.getCtx()), wi); - m_daM.setToolTipText(m_daQ.toString()); - m_daM.addActionListener(this); - pop.add(m_daM); - } - Point pp = e.getPoint(); - pop.show((Component)e.getSource(), pp.x, pp.y); - return; - } - - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - if (m_drillDown) - { - MQuery query = m_viewPanel.getDrillDown(point); - if (query != null) - { - if (log.isLoggable(Level.INFO)) log.info("Drill Down: " + query.getWhereClause(true)); - executeDrill(query); - } - } - else if (comboDrill.getSelectedItem() != null && comboDrill.getSelectedIndex() > 0) - { - MQuery query = m_viewPanel.getDrillAcross(point); - if (query != null) - { - NamePair pp = (NamePair)comboDrill.getSelectedItem(); - query.setTableName(pp.getID()); - if (log.isLoggable(Level.INFO)) log.info("Drill Accross: " + query.getWhereClause(true)); - executeDrill(query); - } - } - cmd_drill(); // setCursor - } // mouse_clicked - - /** - * Execute Drill to Query - * @param query query - */ - private void executeDrill (MQuery query) - { - int AD_Table_ID = AReport.getAD_Table_ID(query.getTableName()); - if (!MRole.getDefault().isCanReport(AD_Table_ID)) - { - ADialog.error(m_WindowNo, this, "AccessCannotReport", query.getTableName()); - return; - } - if (AD_Table_ID != 0) - new AReport (AD_Table_ID, null, query); - else - log.warning("No Table found for " + query.getWhereClause(true)); - } // executeDrill - - /** - * Open Window - * @param query query - */ - private void cmd_window (MQuery query) - { - if (query == null) - return; - AEnv.zoom(query); - } // cmd_window - - /************************************************************************** - * Print Report - */ - private void cmd_print() - { - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - m_reportEngine.getPrintInfo().setWithDialog(true); - m_reportEngine.print(); - cmd_drill(); // setCursor - } // cmd_print - - /** - * Send Mail - */ - private void cmd_sendMail() - { - String to = ""; - MUser from = MUser.get(Env.getCtx(), Env.getAD_User_ID(Env.getCtx())); - String subject = m_reportEngine.getName(); - String message = ""; - File attachment = null; - - try - { - attachment = new File(FileUtil.getTempMailName(subject, ".pdf")); - m_reportEngine.getPDF(attachment); - } - catch (Exception e) - { - log.log(Level.SEVERE, "", e); - } - - new EMailDialog (this, - Msg.getMsg(Env.getCtx(), "SendMail"), - from, to, subject, message, attachment); - } // cmd_sendMail - - /** - * Archive Report directly - */ - private void cmd_archive () - { - boolean success = false; - byte[] data = Document.getPDFAsArray(m_reportEngine.getLayout().getPageable(false)); // No Copy - if (data != null) - { - MArchive archive = new MArchive (Env.getCtx(), m_reportEngine.getPrintInfo(), null); - archive.setBinaryData(data); - success = archive.save(); - } - if (success) - ADialog.info(m_WindowNo, this, "Archived"); - else - ADialog.error(m_WindowNo, this, "ArchiveError"); - } // cmd_archive - - /** - * Print Setup Dialog - */ - private void cmd_pageSetup() - { - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - m_reportEngine.pageSetupDialog(); - revalidate(); - cmd_drill(); // setCursor - } // cmd_pageSetup - - /** - * Export - */ - private void cmd_export() - { - log.config(""); - if (!m_isCanExport) - { - ADialog.error(m_WindowNo, this, "AccessCannotExport", getTitle()); - return; - } - - // - JFileChooser chooser = new JFileChooser(); - chooser.setDialogType(JFileChooser.SAVE_DIALOG); - chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - chooser.setDialogTitle(Msg.getMsg(m_ctx, "Export") + ": " + getTitle()); - // - chooser.addChoosableFileFilter(new ExtensionFileFilter("ps", Msg.getMsg(m_ctx, "FilePS"))); - chooser.addChoosableFileFilter(new ExtensionFileFilter("xml", Msg.getMsg(m_ctx, "FileXML"))); - chooser.addChoosableFileFilter(new ExtensionFileFilter("pdf", Msg.getMsg(m_ctx, "FilePDF"))); - chooser.addChoosableFileFilter(new ExtensionFileFilter("html", Msg.getMsg(m_ctx, "FileHTML"))); - chooser.addChoosableFileFilter(new ExtensionFileFilter("txt", Msg.getMsg(m_ctx, "FileTXT"))); - chooser.addChoosableFileFilter(new ExtensionFileFilter("ssv", Msg.getMsg(m_ctx, "FileSSV"))); - chooser.addChoosableFileFilter(new ExtensionFileFilter("csv", Msg.getMsg(m_ctx, "FileCSV"))); - chooser.addChoosableFileFilter(new ExtensionFileFilter("xls", Msg.getMsg(m_ctx, "FileXLS"))); - // - if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) - return; - - // Create File - File outFile = ExtensionFileFilter.getFile(chooser.getSelectedFile(), chooser.getFileFilter()); - try - { - outFile.createNewFile(); - } - catch (IOException e) - { - log.log(Level.SEVERE, "", e); - ADialog.error(m_WindowNo, this, "FileCannotCreate", e.getLocalizedMessage()); - return; - } - - String ext = outFile.getPath(); - // no extension - if (ext.lastIndexOf('.') == -1) - { - ADialog.error(m_WindowNo, this, "FileInvalidExtension"); - return; - } - ext = ext.substring(ext.lastIndexOf('.')+1).toLowerCase(); - if (log.isLoggable(Level.CONFIG)) log.config( "File=" + outFile.getPath() + "; Type=" + ext); - - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - try { - if (ext.equals("pdf")) - m_reportEngine.createPDF(outFile); - else if (ext.equals("ps")) - m_reportEngine.createPS(outFile); - else if (ext.equals("xml")) - m_reportEngine.createXML(outFile); - else if (ext.equals("csv")) - m_reportEngine.createCSV(outFile, ',', m_reportEngine.getPrintFormat().getLanguage()); - else if (ext.equals("ssv")) - m_reportEngine.createCSV(outFile, ';', m_reportEngine.getPrintFormat().getLanguage()); - else if (ext.equals("txt")) - m_reportEngine.createCSV(outFile, '\t', m_reportEngine.getPrintFormat().getLanguage()); - else if (ext.equals("html") || ext.equals("htm")) - m_reportEngine.createHTML(outFile, false, m_reportEngine.getPrintFormat().getLanguage()); - else if (ext.equals("xls")) - m_reportEngine.createXLS(outFile, m_reportEngine.getPrintFormat().getLanguage()); - else - ADialog.error(m_WindowNo, this, "FileInvalidExtension"); - } - catch (Exception e) { - ADialog.error(m_WindowNo, this, "Error", e.getLocalizedMessage()); - if (CLogMgt.isLevelFinest()) - e.printStackTrace(); - } - cmd_drill(); // setCursor - } // cmd_export - - - /** - * Report Combo - Start other Report or create new one - */ - private void cmd_report() - { - KeyNamePair pp = (KeyNamePair)comboReport.getSelectedItem(); - if (pp == null) - return; - // - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - MPrintFormat pf = null; - int AD_PrintFormat_ID = pp.getKey(); - - // create new - if (AD_PrintFormat_ID == -1) - { - int AD_ReportView_ID = m_reportEngine.getPrintFormat().getAD_ReportView_ID(); - if (AD_ReportView_ID != 0) - { - String name = m_reportEngine.getName(); - int index = name.lastIndexOf('_'); - if (index != -1) - name = name.substring(0,index); - pf = MPrintFormat.createFromReportView(m_ctx, AD_ReportView_ID, name); - } - else - { - int AD_Table_ID = m_reportEngine.getPrintFormat().getAD_Table_ID(); - pf = MPrintFormat.createFromTable(m_ctx, AD_Table_ID); - } - if (pf != null) - fillComboReport(pf.get_ID()); - else - return; - } - else - pf = MPrintFormat.get (Env.getCtx(), AD_PrintFormat_ID, true); - - // Get Language from previous - thanks Gunther Hoppe - if (m_reportEngine.getPrintFormat() != null) - { - pf.setLanguage(m_reportEngine.getPrintFormat().getLanguage()); // needs to be re-set - otherwise viewer will be blank - pf.setTranslationLanguage(m_reportEngine.getPrintFormat().getLanguage()); - } - m_reportEngine.setPrintFormat(pf); - revalidate(); - - cmd_drill(); // setCursor - } // cmd_report - - /** - * Query Report - */ - private void cmd_find() - { - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - int AD_Table_ID = m_reportEngine.getPrintFormat().getAD_Table_ID(); - - String title = null; - String tableName = null; - - // Get Find Tab Info - String sql = "SELECT t.AD_Tab_ID " - // ,w.Name, t.Name, w.IsDefault, t.SeqNo, ABS (tt.AD_Window_ID-t.AD_Window_ID) - + "FROM AD_Tab t" - + " INNER JOIN AD_Window w ON (t.AD_Window_ID=w.AD_Window_ID)" - + " INNER JOIN AD_Table tt ON (t.AD_Table_ID=tt.AD_Table_ID) " - + "WHERE tt.AD_Table_ID=? " - + "ORDER BY w.IsDefault DESC, t.SeqNo, ABS (tt.AD_Window_ID-t.AD_Window_ID)"; - int AD_Tab_ID = DB.getSQLValue(null, sql, AD_Table_ID); - // ASP - MClient client = MClient.get(Env.getCtx()); - String ASPFilter = ""; - if (client.isUseASP()) - ASPFilter = - " AND ( AD_Tab_ID IN ( " - // Just ASP subscribed tabs for client " - + " SELECT t.AD_Tab_ID " - + " FROM ASP_Tab t, ASP_Window w, ASP_Level l, ASP_ClientLevel cl " - + " WHERE w.ASP_Level_ID = l.ASP_Level_ID " - + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() - + " AND cl.ASP_Level_ID = l.ASP_Level_ID " - + " AND t.ASP_Window_ID = w.ASP_Window_ID " - + " AND t.IsActive = 'Y' " - + " AND w.IsActive = 'Y' " - + " AND l.IsActive = 'Y' " - + " AND cl.IsActive = 'Y' " - + " AND t.ASP_Status = 'S') " // Show - + " OR AD_Tab_ID IN ( " - // + show ASP exceptions for client - + " SELECT AD_Tab_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Tab_ID IS NOT NULL " - + " AND ce.AD_Field_ID IS NULL " - + " AND ce.ASP_Status = 'S') " // Show - + " ) " - + " AND AD_Tab_ID NOT IN ( " - // minus hide ASP exceptions for client - + " SELECT AD_Tab_ID " - + " FROM ASP_ClientException ce " - + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() - + " AND ce.IsActive = 'Y' " - + " AND ce.AD_Tab_ID IS NOT NULL " - + " AND ce.AD_Field_ID IS NULL " - + " AND ce.ASP_Status = 'H')"; // Hide - // - sql = "SELECT Name, TableName FROM AD_Tab_v WHERE AD_Tab_ID=? " + ASPFilter; - if (!Env.isBaseLanguage(Env.getCtx(), "AD_Tab")) - sql = "SELECT Name, TableName FROM AD_Tab_vt WHERE AD_Tab_ID=?" - + " AND AD_Language='" + Env.getAD_Language(Env.getCtx()) + "' " + ASPFilter; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, AD_Tab_ID); - rs = pstmt.executeQuery(); - // - if (rs.next()) - { - title = rs.getString(1); - tableName = rs.getString(2); - } - // - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; - pstmt = null; - } - - GridField[] findFields = null; - if (tableName != null) - findFields = GridField.createFields(m_ctx, m_WindowNo, 0, AD_Tab_ID); - - if (findFields == null) // No Tab for Table exists - bFind.setEnabled(false); - else - { - Find find = new Find (this, m_reportEngine.getWindowNo(), title, - AD_Tab_ID, AD_Table_ID, tableName, m_reportEngine.getWhereExtended(), findFields, 1); - m_reportEngine.setQuery(find.getQuery()); - find.dispose(); - find = null; - revalidate(); - } - cmd_drill(); // setCursor - } // cmd_find - - /** - * Call Customize - */ - private void cmd_customize() - { - AWindow win = new AWindow (getGraphicsConfiguration()); - new AWindowListener (win, this); // forwards Window Events - int AD_PrintFormat_ID = m_reportEngine.getPrintFormat().get_ID(); - int AD_Window_ID = MPrintFormat.getZoomWindowID(AD_PrintFormat_ID); - boolean loadedOK = win.initWindow(AD_Window_ID, MQuery.getEqualQuery("AD_PrintFormat_ID", AD_PrintFormat_ID)); - if (loadedOK) - { - AEnv.addToWindowManager(win); - AEnv.showCenterScreen(win); - } - // see windowStateChanged for applying change - } // cmd_customize - - /** - * Window State Listener for Customize Window - * @param e event - */ - public void windowStateChanged (WindowEvent e) - { - // The Customize Window was closed - if (e.getID() == WindowEvent.WINDOW_CLOSED && m_reportEngine != null) - { - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - log.info("Re-read PrintFormat"); - int AD_PrintFormat_ID = m_reportEngine.getPrintFormat().get_ID(); - Language language = m_reportEngine.getPrintFormat().getLanguage(); - MPrintFormat pf = MPrintFormat.get (Env.getCtx(), AD_PrintFormat_ID, true); - pf.setLanguage (language); // needs to be re-set - otherwise viewer will be blank - pf.setTranslationLanguage (language); - m_reportEngine.setPrintFormat(pf); - revalidate(); - cmd_drill(); // setCursor - } - } // windowStateChanged - - /** - * Set Zoom Level - */ - private void cmd_zoom() - { - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - m_viewPanel.setZoomLevel(comboZoom.getSelectedIndex()); - revalidate(); - cmd_drill(); // setCursor - } // cmd_zoom - - - /** - * Show Translation Dialog. - * Translate base table entry, will be copied to trl tables if not multi-lingual - */ - private void cmd_translate() - { - ArrayList list = new ArrayList(); - ValueNamePair pp = null; - String sql = "SELECT Name, AD_Language FROM AD_Language WHERE IsSystemLanguage='Y' ORDER BY 1"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, null); - rs = pstmt.executeQuery(); - while (rs.next()) - list.add(new ValueNamePair (rs.getString(2), rs.getString(1))); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - DB.close(rs, pstmt); - rs = null; - pstmt = null; - } - if (list.size() == 0) - { - ADialog.warn(m_WindowNo, this, "NoTranslation"); - return; - } - - // Dialog - String title = Msg.getMsg(Env.getCtx(), "PrintFormatTrl", true); - String message = Msg.getMsg(Env.getCtx(), "PrintFormatTrl", false); - int choice = JOptionPane.showOptionDialog - (this, message, title, - JOptionPane.OK_OPTION, JOptionPane.QUESTION_MESSAGE, null, - list.toArray(), null); - if (choice == JOptionPane.CLOSED_OPTION) - return; - // - pp = (ValueNamePair)list.get(choice); - String AD_Language = pp.getValue(); - int AD_PrintFormat_ID = m_reportEngine.getPrintFormat().get_ID(); - if (log.isLoggable(Level.CONFIG)) log.config(AD_Language + " - AD_PrintFormat_ID=" + AD_PrintFormat_ID); - StringBuilder sb = new StringBuilder(); - // English - if (Language.isBaseLanguage (AD_Language)) - { - sb.append("UPDATE AD_PrintFormatItem pfi " - + "SET Name = (SELECT e.Name FROM AD_Element e, AD_Column c" - + " WHERE e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID)," - + "PrintName = (SELECT e.PrintName FROM AD_Element e, AD_Column c" - + " WHERE e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID) " - + "WHERE AD_PrintFormat_ID=").append(AD_PrintFormat_ID).append( - " AND EXISTS (SELECT * FROM AD_Element e, AD_Column c" - + " WHERE e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID)"); - } - else - { - AD_Language = "'" + AD_Language + "'"; - sb.append("UPDATE AD_PrintFormatItem pfi " - + "SET Name = (SELECT e.Name FROM AD_Element_Trl e, AD_Column c" - + " WHERE e.AD_Language=").append(AD_Language).append( - " AND e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID), " - + "PrintName = (SELECT e.PrintName FROM AD_Element_Trl e, AD_Column c" - + " WHERE e.AD_Language=").append(AD_Language).append( - " AND e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID) " - + "WHERE AD_PrintFormat_ID=").append(AD_PrintFormat_ID).append( - " AND EXISTS (SELECT * FROM AD_Element_Trl e, AD_Column c" - + " WHERE e.AD_Language=").append(AD_Language).append( - " AND e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID)"); - } - int count = DB.executeUpdate(sb.toString(), null); - if (log.isLoggable(Level.CONFIG)) log.config("Count=" + count); - // - m_reportEngine.setPrintFormat(MPrintFormat.get (Env.getCtx(), AD_PrintFormat_ID, true)); - revalidate(); - } // cmd_translate - - /*************************************************************************/ - - /** - * Test - * @param args args - */ - static public void main (String[] args) - { - Login.initTest(true); - - MQuery q = new MQuery("C_Invoice"); - q.addRestriction("C_Invoice_ID", MQuery.EQUAL, Integer.valueOf(103)); - - // 102 = Invoice - 100 = Order - PrintInfo i = new PrintInfo("test", X_C_Invoice.Table_ID, 102, 0); - MPrintFormat f = MPrintFormat.get (Env.getCtx(), 102, false); - ReportEngine re = new ReportEngine(Env.getCtx(), f, q, i); - - // MPrintFormat f = new MPrintFormat(Env.getCtx(), 101); - // ReportEngine re = new ReportEngine(f, null); - - new Viewer(null, re); - } // main - - @Override - public void onPrintFormatChanged(ReportEngineEvent event) { - if (m_viewPanel != null) - m_viewPanel.revalidate(); - } - - @Override - public void onQueryChanged(ReportEngineEvent event) { - if (m_viewPanel != null) - m_viewPanel.revalidate(); - } - - @Override - public void onPageSetupChanged(ReportEngineEvent event) { - if (m_viewPanel != null) - m_viewPanel.revalidate(); - } - -} // Viewer - + else if (cmd.equals("First")) + setPage(1); + else if (cmd.equals("PreviousPage") || cmd.equals("Previous")) + setPage(m_pageNo-1); + else if (cmd.equals("NextPage") || cmd.equals("Next")) + setPage(m_pageNo+1); + else if (cmd.equals("Last")) + setPage(m_pageMax); + else if (cmd.equals("Find")) + cmd_find(); + else if (cmd.equals("Export")) + cmd_export(); + else if (cmd.equals("Print")) + cmd_print(); + else if (cmd.equals("SendMail")) + cmd_sendMail(); + else if (cmd.equals("Archive")) + cmd_archive(); + else if (cmd.equals("PrintCustomize")) + cmd_customize(); + else if (cmd.equals("PageSetup")) + cmd_pageSetup(); + else if (cmd.equals("Translate")) + cmd_translate(); + else if (cmd.equals("End")) + dispose(); + // + else if (e.getSource() == m_ddM) + cmd_window(m_ddQ); + else if (e.getSource() == m_daM) + cmd_window(m_daQ); + // + else if (!AEnv.actionPerformed(e.getActionCommand(), m_WindowNo, this)) + log.log(Level.SEVERE, "unknown action=" + e.getActionCommand()); + // + this.setCursor(Cursor.getDefaultCursor()); + } // actionPerformed + + /** + * Change Listener (spinner, viewpoint) + * @param e event + */ + public void stateChanged (ChangeEvent e) + { + if (m_setting) + return; + // log.config( "Viewer.stateChanged", e); + m_setting = true; + int newPage = 0; + if (e.getSource() == spinner) + { + newPage = ((Integer)spinnerModel.getValue()).intValue(); + } + // pb with the viewport change listener disabled the following is + // superfluous and should be removed + else // Viewpoint + { + Point p = centerScrollPane.getViewport().getViewPosition(); + newPage = Math.round(m_viewPanel.getPageNoAt(p)); + } + setPage(newPage); + m_setting = false; + } // stateChanged + + + /** + * Set Page No + * @param page page no + */ + private void setPage (int page) + { + m_setting = true; + m_pageNo = page; + if (m_pageNo < 1) + m_pageNo = 1; + if (page > m_pageMax) + m_pageNo = m_pageMax; + bPrevious.setEnabled (m_pageNo != 1); + bNext.setEnabled (m_pageNo != m_pageMax); + // + Rectangle pageRectangle = m_viewPanel.getRectangleOfPage(m_pageNo); + pageRectangle.x -= m_viewPanel.getMarginSize(true); + pageRectangle.y -= m_viewPanel.getMarginSize(true); + centerScrollPane.getViewport().setViewPosition(pageRectangle.getLocation()); + // System.out.println("scrollTo " + pageRectangle); + + // Set Page + spinnerModel.setValue(Integer.valueOf(m_pageNo)); + StringBuffer sb = new StringBuffer (Msg.getMsg(m_ctx, "Page")) + .append(" ").append(m_pageNo) + .append(m_viewPanel.getPageInfo(m_pageNo)) + .append(" ").append(Msg.getMsg(m_ctx, "of")).append(" ") + .append(m_pageMax) + .append(m_viewPanel.getPageInfoMax()); + statusBar.setStatusDB(sb.toString()); + m_setting = false; + } // setPage + + + /************************************************************************** + * (Re)Set Drill Accross Cursor + */ + private void cmd_drill() + { + m_drillDown = comboDrill.getSelectedIndex() < 1; // -1 or 0 + if (m_drillDown) + setCursor(Cursor.getDefaultCursor()); + else + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + } // cmd_drill + + /** + * Mouse clicked + * @param e event + * @param rightClick true if right click + */ + private void mouse_clicked (MouseEvent e, boolean rightClick) + { + Point point = e.getPoint(); + if (log.isLoggable(Level.INFO)) log.info("Right=" + rightClick + " - " + point.toString()); + if (rightClick) + { + m_ddQ = m_viewPanel.getDrillDown(point); + m_daQ = m_viewPanel.getDrillAcross(point); + m_ddM = null; + m_daM = null; + if (m_ddQ == null && m_daQ == null) + return; + // Create Menu + JPopupMenu pop = new JPopupMenu(); + Icon wi = Env.getImageIcon("mWindow.png"); + if (m_ddQ != null) + { + m_ddM = new CMenuItem(m_ddQ.getDisplayName(Env.getCtx()), wi); + m_ddM.setToolTipText(m_ddQ.toString()); + m_ddM.addActionListener(this); + pop.add(m_ddM); + } + if (m_daQ != null) + { + m_daM = new CMenuItem(m_daQ.getDisplayName(Env.getCtx()), wi); + m_daM.setToolTipText(m_daQ.toString()); + m_daM.addActionListener(this); + pop.add(m_daM); + } + Point pp = e.getPoint(); + pop.show((Component)e.getSource(), pp.x, pp.y); + return; + } + + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + if (m_drillDown) + { + MQuery query = m_viewPanel.getDrillDown(point); + if (query != null) + { + if (log.isLoggable(Level.INFO)) log.info("Drill Down: " + query.getWhereClause(true)); + executeDrill(query); + } + } + else if (comboDrill.getSelectedItem() != null && comboDrill.getSelectedIndex() > 0) + { + MQuery query = m_viewPanel.getDrillAcross(point); + if (query != null) + { + NamePair pp = (NamePair)comboDrill.getSelectedItem(); + query.setTableName(pp.getID()); + if (log.isLoggable(Level.INFO)) log.info("Drill Accross: " + query.getWhereClause(true)); + executeDrill(query); + } + } + cmd_drill(); // setCursor + } // mouse_clicked + + /** + * Execute Drill to Query + * @param query query + */ + private void executeDrill (MQuery query) + { + int AD_Table_ID = AReport.getAD_Table_ID(query.getTableName()); + if (!MRole.getDefault().isCanReport(AD_Table_ID)) + { + ADialog.error(m_WindowNo, this, "AccessCannotReport", query.getTableName()); + return; + } + if (AD_Table_ID != 0) + new AReport (AD_Table_ID, null, query); + else + log.warning("No Table found for " + query.getWhereClause(true)); + } // executeDrill + + /** + * Open Window + * @param query query + */ + private void cmd_window (MQuery query) + { + if (query == null) + return; + AEnv.zoom(query); + } // cmd_window + + /************************************************************************** + * Print Report + */ + private void cmd_print() + { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + m_reportEngine.getPrintInfo().setWithDialog(true); + m_reportEngine.print(); + cmd_drill(); // setCursor + } // cmd_print + + /** + * Send Mail + */ + private void cmd_sendMail() + { + String to = ""; + MUser from = MUser.get(Env.getCtx(), Env.getAD_User_ID(Env.getCtx())); + String subject = m_reportEngine.getName(); + String message = ""; + File attachment = null; + + try + { + attachment = new File(FileUtil.getTempMailName(subject, ".pdf")); + m_reportEngine.getPDF(attachment); + } + catch (Exception e) + { + log.log(Level.SEVERE, "", e); + } + + new EMailDialog (this, + Msg.getMsg(Env.getCtx(), "SendMail"), + from, to, subject, message, attachment); + } // cmd_sendMail + + /** + * Archive Report directly + */ + private void cmd_archive () + { + boolean success = false; + byte[] data = Document.getPDFAsArray(m_reportEngine.getLayout().getPageable(false)); // No Copy + if (data != null) + { + MArchive archive = new MArchive (Env.getCtx(), m_reportEngine.getPrintInfo(), null); + archive.setBinaryData(data); + success = archive.save(); + } + if (success) + ADialog.info(m_WindowNo, this, "Archived"); + else + ADialog.error(m_WindowNo, this, "ArchiveError"); + } // cmd_archive + + /** + * Print Setup Dialog + */ + private void cmd_pageSetup() + { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + m_reportEngine.pageSetupDialog(); + revalidate(); + cmd_drill(); // setCursor + } // cmd_pageSetup + + /** + * Export + */ + private void cmd_export() + { + log.config(""); + if (!m_isCanExport) + { + ADialog.error(m_WindowNo, this, "AccessCannotExport", getTitle()); + return; + } + + // + JFileChooser chooser = new JFileChooser(); + chooser.setDialogType(JFileChooser.SAVE_DIALOG); + chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + chooser.setDialogTitle(Msg.getMsg(m_ctx, "Export") + ": " + getTitle()); + // + chooser.addChoosableFileFilter(new ExtensionFileFilter("ps", Msg.getMsg(m_ctx, "FilePS"))); + chooser.addChoosableFileFilter(new ExtensionFileFilter("xml", Msg.getMsg(m_ctx, "FileXML"))); + chooser.addChoosableFileFilter(new ExtensionFileFilter("pdf", Msg.getMsg(m_ctx, "FilePDF"))); + chooser.addChoosableFileFilter(new ExtensionFileFilter("html", Msg.getMsg(m_ctx, "FileHTML"))); + chooser.addChoosableFileFilter(new ExtensionFileFilter("txt", Msg.getMsg(m_ctx, "FileTXT"))); + chooser.addChoosableFileFilter(new ExtensionFileFilter("ssv", Msg.getMsg(m_ctx, "FileSSV"))); + chooser.addChoosableFileFilter(new ExtensionFileFilter("csv", Msg.getMsg(m_ctx, "FileCSV"))); + chooser.addChoosableFileFilter(new ExtensionFileFilter("xls", Msg.getMsg(m_ctx, "FileXLS"))); + // + if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) + return; + + // Create File + File outFile = ExtensionFileFilter.getFile(chooser.getSelectedFile(), chooser.getFileFilter()); + try + { + outFile.createNewFile(); + } + catch (IOException e) + { + log.log(Level.SEVERE, "", e); + ADialog.error(m_WindowNo, this, "FileCannotCreate", e.getLocalizedMessage()); + return; + } + + String ext = outFile.getPath(); + // no extension + if (ext.lastIndexOf('.') == -1) + { + ADialog.error(m_WindowNo, this, "FileInvalidExtension"); + return; + } + ext = ext.substring(ext.lastIndexOf('.')+1).toLowerCase(); + if (log.isLoggable(Level.CONFIG)) log.config( "File=" + outFile.getPath() + "; Type=" + ext); + + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + try { + if (ext.equals("pdf")) + m_reportEngine.createPDF(outFile); + else if (ext.equals("ps")) + m_reportEngine.createPS(outFile); + else if (ext.equals("xml")) + m_reportEngine.createXML(outFile); + else if (ext.equals("csv")) + m_reportEngine.createCSV(outFile, ',', m_reportEngine.getPrintFormat().getLanguage()); + else if (ext.equals("ssv")) + m_reportEngine.createCSV(outFile, ';', m_reportEngine.getPrintFormat().getLanguage()); + else if (ext.equals("txt")) + m_reportEngine.createCSV(outFile, '\t', m_reportEngine.getPrintFormat().getLanguage()); + else if (ext.equals("html") || ext.equals("htm")) + m_reportEngine.createHTML(outFile, false, m_reportEngine.getPrintFormat().getLanguage()); + else if (ext.equals("xls")) + m_reportEngine.createXLS(outFile, m_reportEngine.getPrintFormat().getLanguage()); + else + ADialog.error(m_WindowNo, this, "FileInvalidExtension"); + } + catch (Exception e) { + ADialog.error(m_WindowNo, this, "Error", e.getLocalizedMessage()); + if (CLogMgt.isLevelFinest()) + e.printStackTrace(); + } + cmd_drill(); // setCursor + } // cmd_export + + + /** + * Report Combo - Start other Report or create new one + */ + private void cmd_report() + { + KeyNamePair pp = (KeyNamePair)comboReport.getSelectedItem(); + if (pp == null) + return; + // + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + MPrintFormat pf = null; + int AD_PrintFormat_ID = pp.getKey(); + + // create new + if (AD_PrintFormat_ID == -1) + { + int AD_ReportView_ID = m_reportEngine.getPrintFormat().getAD_ReportView_ID(); + if (AD_ReportView_ID != 0) + { + String name = m_reportEngine.getName(); + int index = name.lastIndexOf('_'); + if (index != -1) + name = name.substring(0,index); + pf = MPrintFormat.createFromReportView(m_ctx, AD_ReportView_ID, name); + } + else + { + int AD_Table_ID = m_reportEngine.getPrintFormat().getAD_Table_ID(); + pf = MPrintFormat.createFromTable(m_ctx, AD_Table_ID); + } + if (pf != null) + fillComboReport(pf.get_ID()); + else + return; + } + else + pf = MPrintFormat.get (Env.getCtx(), AD_PrintFormat_ID, true); + + // Get Language from previous - thanks Gunther Hoppe + if (m_reportEngine.getPrintFormat() != null) + { + pf.setLanguage(m_reportEngine.getPrintFormat().getLanguage()); // needs to be re-set - otherwise viewer will be blank + pf.setTranslationLanguage(m_reportEngine.getPrintFormat().getLanguage()); + } + m_reportEngine.setPrintFormat(pf); + revalidate(); + + cmd_drill(); // setCursor + } // cmd_report + + /** + * Query Report + */ + private void cmd_find() + { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + int AD_Table_ID = m_reportEngine.getPrintFormat().getAD_Table_ID(); + + String title = null; + String tableName = null; + + // Get Find Tab Info + String sql = "SELECT t.AD_Tab_ID " + // ,w.Name, t.Name, w.IsDefault, t.SeqNo, ABS (tt.AD_Window_ID-t.AD_Window_ID) + + "FROM AD_Tab t" + + " INNER JOIN AD_Window w ON (t.AD_Window_ID=w.AD_Window_ID)" + + " INNER JOIN AD_Table tt ON (t.AD_Table_ID=tt.AD_Table_ID) " + + "WHERE tt.AD_Table_ID=? " + + "ORDER BY w.IsDefault DESC, t.SeqNo, ABS (tt.AD_Window_ID-t.AD_Window_ID)"; + int AD_Tab_ID = DB.getSQLValue(null, sql, AD_Table_ID); + // ASP + MClient client = MClient.get(Env.getCtx()); + String ASPFilter = ""; + if (client.isUseASP()) + ASPFilter = + " AND ( AD_Tab_ID IN ( " + // Just ASP subscribed tabs for client " + + " SELECT t.AD_Tab_ID " + + " FROM ASP_Tab t, ASP_Window w, ASP_Level l, ASP_ClientLevel cl " + + " WHERE w.ASP_Level_ID = l.ASP_Level_ID " + + " AND cl.AD_Client_ID = " + client.getAD_Client_ID() + + " AND cl.ASP_Level_ID = l.ASP_Level_ID " + + " AND t.ASP_Window_ID = w.ASP_Window_ID " + + " AND t.IsActive = 'Y' " + + " AND w.IsActive = 'Y' " + + " AND l.IsActive = 'Y' " + + " AND cl.IsActive = 'Y' " + + " AND t.ASP_Status = 'S') " // Show + + " OR AD_Tab_ID IN ( " + // + show ASP exceptions for client + + " SELECT AD_Tab_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Tab_ID IS NOT NULL " + + " AND ce.AD_Field_ID IS NULL " + + " AND ce.ASP_Status = 'S') " // Show + + " ) " + + " AND AD_Tab_ID NOT IN ( " + // minus hide ASP exceptions for client + + " SELECT AD_Tab_ID " + + " FROM ASP_ClientException ce " + + " WHERE ce.AD_Client_ID = " + client.getAD_Client_ID() + + " AND ce.IsActive = 'Y' " + + " AND ce.AD_Tab_ID IS NOT NULL " + + " AND ce.AD_Field_ID IS NULL " + + " AND ce.ASP_Status = 'H')"; // Hide + // + sql = "SELECT Name, TableName FROM AD_Tab_v WHERE AD_Tab_ID=? " + ASPFilter; + if (!Env.isBaseLanguage(Env.getCtx(), "AD_Tab")) + sql = "SELECT Name, TableName FROM AD_Tab_vt WHERE AD_Tab_ID=?" + + " AND AD_Language='" + Env.getAD_Language(Env.getCtx()) + "' " + ASPFilter; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Tab_ID); + rs = pstmt.executeQuery(); + // + if (rs.next()) + { + title = rs.getString(1); + tableName = rs.getString(2); + } + // + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; + pstmt = null; + } + + GridField[] findFields = null; + if (tableName != null) + findFields = GridField.createFields(m_ctx, m_WindowNo, 0, AD_Tab_ID); + + if (findFields == null) // No Tab for Table exists + bFind.setEnabled(false); + else + { + Find find = new Find (this, m_reportEngine.getWindowNo(), title, + AD_Tab_ID, AD_Table_ID, tableName, m_reportEngine.getWhereExtended(), findFields, 1); + m_reportEngine.setQuery(find.getQuery()); + find.dispose(); + find = null; + revalidate(); + } + cmd_drill(); // setCursor + } // cmd_find + + /** + * Call Customize + */ + private void cmd_customize() + { + AWindow win = new AWindow (getGraphicsConfiguration()); + new AWindowListener (win, this); // forwards Window Events + int AD_PrintFormat_ID = m_reportEngine.getPrintFormat().get_ID(); + int AD_Window_ID = MPrintFormat.getZoomWindowID(AD_PrintFormat_ID); + boolean loadedOK = win.initWindow(AD_Window_ID, MQuery.getEqualQuery("AD_PrintFormat_ID", AD_PrintFormat_ID)); + if (loadedOK) + { + AEnv.addToWindowManager(win); + AEnv.showCenterScreen(win); + } + // see windowStateChanged for applying change + } // cmd_customize + + /** + * Window State Listener for Customize Window + * @param e event + */ + public void windowStateChanged (WindowEvent e) + { + // The Customize Window was closed + if (e.getID() == WindowEvent.WINDOW_CLOSED && m_reportEngine != null) + { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + log.info("Re-read PrintFormat"); + int AD_PrintFormat_ID = m_reportEngine.getPrintFormat().get_ID(); + Language language = m_reportEngine.getPrintFormat().getLanguage(); + MPrintFormat pf = MPrintFormat.get (Env.getCtx(), AD_PrintFormat_ID, true); + pf.setLanguage (language); // needs to be re-set - otherwise viewer will be blank + pf.setTranslationLanguage (language); + m_reportEngine.setPrintFormat(pf); + revalidate(); + cmd_drill(); // setCursor + } + } // windowStateChanged + + /** + * Set Zoom Level + */ + private void cmd_zoom() + { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + m_viewPanel.setZoomLevel(comboZoom.getSelectedIndex()); + revalidate(); + cmd_drill(); // setCursor + } // cmd_zoom + + + /** + * Show Translation Dialog. + * Translate base table entry, will be copied to trl tables if not multi-lingual + */ + private void cmd_translate() + { + ArrayList list = new ArrayList(); + ValueNamePair pp = null; + String sql = "SELECT Name, AD_Language FROM AD_Language WHERE IsSystemLanguage='Y' ORDER BY 1"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, null); + rs = pstmt.executeQuery(); + while (rs.next()) + list.add(new ValueNamePair (rs.getString(2), rs.getString(1))); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + DB.close(rs, pstmt); + rs = null; + pstmt = null; + } + if (list.size() == 0) + { + ADialog.warn(m_WindowNo, this, "NoTranslation"); + return; + } + + // Dialog + String title = Msg.getMsg(Env.getCtx(), "PrintFormatTrl", true); + String message = Msg.getMsg(Env.getCtx(), "PrintFormatTrl", false); + int choice = JOptionPane.showOptionDialog + (this, message, title, + JOptionPane.OK_OPTION, JOptionPane.QUESTION_MESSAGE, null, + list.toArray(), null); + if (choice == JOptionPane.CLOSED_OPTION) + return; + // + pp = (ValueNamePair)list.get(choice); + String AD_Language = pp.getValue(); + int AD_PrintFormat_ID = m_reportEngine.getPrintFormat().get_ID(); + if (log.isLoggable(Level.CONFIG)) log.config(AD_Language + " - AD_PrintFormat_ID=" + AD_PrintFormat_ID); + StringBuilder sb = new StringBuilder(); + // English + if (Language.isBaseLanguage (AD_Language)) + { + sb.append("UPDATE AD_PrintFormatItem pfi " + + "SET Name = (SELECT e.Name FROM AD_Element e, AD_Column c" + + " WHERE e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID)," + + "PrintName = (SELECT e.PrintName FROM AD_Element e, AD_Column c" + + " WHERE e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID) " + + "WHERE AD_PrintFormat_ID=").append(AD_PrintFormat_ID).append( + " AND EXISTS (SELECT * FROM AD_Element e, AD_Column c" + + " WHERE e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID)"); + } + else + { + AD_Language = "'" + AD_Language + "'"; + sb.append("UPDATE AD_PrintFormatItem pfi " + + "SET Name = (SELECT e.Name FROM AD_Element_Trl e, AD_Column c" + + " WHERE e.AD_Language=").append(AD_Language).append( + " AND e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID), " + + "PrintName = (SELECT e.PrintName FROM AD_Element_Trl e, AD_Column c" + + " WHERE e.AD_Language=").append(AD_Language).append( + " AND e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID) " + + "WHERE AD_PrintFormat_ID=").append(AD_PrintFormat_ID).append( + " AND EXISTS (SELECT * FROM AD_Element_Trl e, AD_Column c" + + " WHERE e.AD_Language=").append(AD_Language).append( + " AND e.AD_Element_ID=c.AD_Element_ID AND c.AD_Column_ID=pfi.AD_Column_ID)"); + } + int count = DB.executeUpdate(sb.toString(), null); + if (log.isLoggable(Level.CONFIG)) log.config("Count=" + count); + // + m_reportEngine.setPrintFormat(MPrintFormat.get (Env.getCtx(), AD_PrintFormat_ID, true)); + revalidate(); + } // cmd_translate + + /*************************************************************************/ + + /** + * Test + * @param args args + */ + static public void main (String[] args) + { + Login.initTest(true); + + MQuery q = new MQuery("C_Invoice"); + q.addRestriction("C_Invoice_ID", MQuery.EQUAL, Integer.valueOf(103)); + + // 102 = Invoice - 100 = Order + PrintInfo i = new PrintInfo("test", X_C_Invoice.Table_ID, 102, 0); + MPrintFormat f = MPrintFormat.get (Env.getCtx(), 102, false); + ReportEngine re = new ReportEngine(Env.getCtx(), f, q, i); + + // MPrintFormat f = new MPrintFormat(Env.getCtx(), 101); + // ReportEngine re = new ReportEngine(f, null); + + new Viewer(null, re); + } // main + + @Override + public void onPrintFormatChanged(ReportEngineEvent event) { + if (m_viewPanel != null) + m_viewPanel.revalidate(); + } + + @Override + public void onQueryChanged(ReportEngineEvent event) { + if (m_viewPanel != null) + m_viewPanel.revalidate(); + } + + @Override + public void onPageSetupChanged(ReportEngineEvent event) { + if (m_viewPanel != null) + m_viewPanel.revalidate(); + } + +} // Viewer + diff --git a/org.adempiere.ui.zk/WEB-INF/src/org/adempiere/webui/panel/RolePanel.java b/org.adempiere.ui.zk/WEB-INF/src/org/adempiere/webui/panel/RolePanel.java index 739cf32c04..2306d33d39 100644 --- a/org.adempiere.ui.zk/WEB-INF/src/org/adempiere/webui/panel/RolePanel.java +++ b/org.adempiere.ui.zk/WEB-INF/src/org/adempiere/webui/panel/RolePanel.java @@ -91,8 +91,8 @@ public class RolePanel extends Window implements EventListener, Deferrabl protected Login login; protected Combobox lstRole, lstClient, lstOrganisation, lstWarehouse; - protected Label lblRole, lblClient, lblOrganisation, lblWarehouse, lblDate; - protected WDateEditor lstDate; + protected Label lblRole, lblClient, lblOrganisation, lblWarehouse, lblDate; + protected WDateEditor lstDate; protected Button btnOk, btnCancel; /** Context */ @@ -249,18 +249,18 @@ public class RolePanel extends Window implements EventListener, Deferrabl tr.appendChild(td); td.appendChild(lstWarehouse); - tr = new Tr(); - tr.setId("rowDate"); - table.appendChild(tr); - td = new Td(); - tr.appendChild(td); - td.setSclass(ITheme.LOGIN_LABEL_CLASS); - td.appendChild(lblDate.rightAlign()); - td = new Td(); - td.setSclass(ITheme.LOGIN_FIELD_CLASS); - tr.appendChild(td); - td.appendChild(lstDate.getComponent()); - + tr = new Tr(); + tr.setId("rowDate"); + table.appendChild(tr); + td = new Td(); + tr.appendChild(td); + td.setSclass(ITheme.LOGIN_LABEL_CLASS); + td.appendChild(lblDate.rightAlign()); + td = new Td(); + td.setSclass(ITheme.LOGIN_FIELD_CLASS); + tr.appendChild(td); + td.appendChild(lstDate.getComponent()); + div = new Div(); div.setSclass(ITheme.LOGIN_BOX_FOOTER_CLASS); ConfirmPanel pnlButtons = new ConfirmPanel(true, false, false, false, false, false, true); @@ -296,15 +296,15 @@ public class RolePanel extends Window implements EventListener, Deferrabl lblWarehouse.setId("lblWarehouse"); lblWarehouse.setValue(Msg.getMsg(language,"Warehouse")); - lblDate = new Label(); - lblDate.setId("lblDate"); + lblDate = new Label(); + lblDate.setId("lblDate"); lblDate.setValue(Msg.getMsg(language,"Date")); - + lstRole = new Combobox(); lstRole.setAutocomplete(true); lstRole.setAutodrop(true); lstRole.setId("lstRole"); - + lstRole.addEventListener(Events.ON_SELECT, this); ZKUpdateUtil.setWidth(lstRole, "220px"); @@ -312,7 +312,7 @@ public class RolePanel extends Window implements EventListener, Deferrabl lstClient.setAutocomplete(true); lstClient.setAutodrop(true); lstClient.setId("lstClient"); - + lstClient.addEventListener(Events.ON_SELECT, this); ZKUpdateUtil.setWidth(lstClient, "220px"); @@ -320,7 +320,7 @@ public class RolePanel extends Window implements EventListener, Deferrabl lstOrganisation.setAutocomplete(true); lstOrganisation.setAutodrop(true); lstOrganisation.setId("lstOrganisation"); - + lstOrganisation.addEventListener(Events.ON_SELECT, this); ZKUpdateUtil.setWidth(lstOrganisation, "220px"); @@ -328,14 +328,14 @@ public class RolePanel extends Window implements EventListener, Deferrabl lstWarehouse.setAutocomplete(true); lstWarehouse.setAutodrop(true); lstWarehouse.setId("lstWarehouse"); - + lstWarehouse.addEventListener(Events.ON_SELECT, this); ZKUpdateUtil.setWidth(lstWarehouse, "220px"); - lstDate = new WDateEditor(); + lstDate = new WDateEditor(); lstDate.setValue(new Timestamp(System.currentTimeMillis())); - lstDate.getComponent().setId("loginDate"); - + lstDate.getComponent().setId("loginDate"); + btnOk = new Button(); btnOk.setId("btnOk"); btnOk.setLabel("Ok"); diff --git a/org.adempiere.ui.zk/WEB-INF/xsd/zul.xsd b/org.adempiere.ui.zk/WEB-INF/xsd/zul.xsd index 065f2a0f65..4fc6a0c497 100644 --- a/org.adempiere.ui.zk/WEB-INF/xsd/zul.xsd +++ b/org.adempiere.ui.zk/WEB-INF/xsd/zul.xsd @@ -1,3212 +1,3212 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + diff --git a/org.adempiere.ui.zk/WEB-INF/zk.xml b/org.adempiere.ui.zk/WEB-INF/zk.xml index e6c4579b4f..10eb855cce 100644 --- a/org.adempiere.ui.zk/WEB-INF/zk.xml +++ b/org.adempiere.ui.zk/WEB-INF/zk.xml @@ -23,9 +23,9 @@ org.adempiere.webui.util.LogEventInterceptor - + - 500 + 500 diff --git a/org.adempiere.ui.zk/gif.jsp b/org.adempiere.ui.zk/gif.jsp index 0dcfd6f3a9..618913e2bb 100644 --- a/org.adempiere.ui.zk/gif.jsp +++ b/org.adempiere.ui.zk/gif.jsp @@ -1,21 +1,21 @@ <%@ page language="java" contentType="image/gif"%> -<% -String fileName = request.getParameter("f"); -if (fileName != null && fileName.endsWith(".gif")) { - java.io.File f = new java.io.File(fileName); - if (f.exists() && f.canRead()) { - response.setContentLength(new Long(f.length()).intValue()); - java.io.FileInputStream fis = new java.io.FileInputStream(f); - java.io.BufferedInputStream bis = new java.io.BufferedInputStream(fis); - java.io.OutputStream os = response.getOutputStream(); - java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(os); - while (bis.available() > 0) - { - bos.write(bis.read()); - } - bis.close(); - bos.flush(); - bos.close(); - } -} -%> +<% +String fileName = request.getParameter("f"); +if (fileName != null && fileName.endsWith(".gif")) { + java.io.File f = new java.io.File(fileName); + if (f.exists() && f.canRead()) { + response.setContentLength(new Long(f.length()).intValue()); + java.io.FileInputStream fis = new java.io.FileInputStream(f); + java.io.BufferedInputStream bis = new java.io.BufferedInputStream(fis); + java.io.OutputStream os = response.getOutputStream(); + java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(os); + while (bis.available() > 0) + { + bos.write(bis.read()); + } + bis.close(); + bos.flush(); + bos.close(); + } +} +%> diff --git a/org.adempiere.ui.zk/labeldata.jsp b/org.adempiere.ui.zk/labeldata.jsp index 5c807b6c21..625d261c01 100644 --- a/org.adempiere.ui.zk/labeldata.jsp +++ b/org.adempiere.ui.zk/labeldata.jsp @@ -1,44 +1,44 @@ -<%@ page language="java" contentType="application/octet-stream"%> -<%@ page trimDirectiveWhitespaces="true" %> -<%@page import="org.compiere.model.MArchive"%> -<%@page import="org.compiere.util.Env"%> -<%@page import="java.io.ByteArrayOutputStream"%> -<%@page import="java.io.FileInputStream"%> -<%@page import="java.io.File"%> -<%@page import="java.io.BufferedOutputStream"%> -<%@page import="java.io.OutputStream"%> -<% - try - { - String fileid = request.getParameter("fileid"); - if (fileid == null || fileid.trim().length() == 0) - { - response.setContentLength(0); - return; - } - - int AD_Archive_ID = Integer.parseInt(fileid); - if (AD_Archive_ID > 0) - { - MArchive archive = new MArchive(Env.getCtx(), AD_Archive_ID, null); - if (archive != null && archive.getAD_Archive_ID() > 0) - { - byte[] data = archive.getBinaryData(); - response.setContentLength(data.length); - - OutputStream os = response.getOutputStream(); - BufferedOutputStream bos = new BufferedOutputStream(os); - bos.write(data); - bos.flush(); - bos.close(); - - archive.delete(false); - } - } - } - catch (Exception e) - { - e.printStackTrace(); - response.setContentLength(0); - } +<%@ page language="java" contentType="application/octet-stream"%> +<%@ page trimDirectiveWhitespaces="true" %> +<%@page import="org.compiere.model.MArchive"%> +<%@page import="org.compiere.util.Env"%> +<%@page import="java.io.ByteArrayOutputStream"%> +<%@page import="java.io.FileInputStream"%> +<%@page import="java.io.File"%> +<%@page import="java.io.BufferedOutputStream"%> +<%@page import="java.io.OutputStream"%> +<% + try + { + String fileid = request.getParameter("fileid"); + if (fileid == null || fileid.trim().length() == 0) + { + response.setContentLength(0); + return; + } + + int AD_Archive_ID = Integer.parseInt(fileid); + if (AD_Archive_ID > 0) + { + MArchive archive = new MArchive(Env.getCtx(), AD_Archive_ID, null); + if (archive != null && archive.getAD_Archive_ID() > 0) + { + byte[] data = archive.getBinaryData(); + response.setContentLength(data.length); + + OutputStream os = response.getOutputStream(); + BufferedOutputStream bos = new BufferedOutputStream(os); + bos.write(data); + bos.flush(); + bos.close(); + + archive.delete(false); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + response.setContentLength(0); + } %> diff --git a/org.adempiere.ui/src/org/compiere/apps/form/TrxMaterial.java b/org.adempiere.ui/src/org/compiere/apps/form/TrxMaterial.java index 3545e3927a..9919e5f949 100644 --- a/org.adempiere.ui/src/org/compiere/apps/form/TrxMaterial.java +++ b/org.adempiere.ui/src/org/compiere/apps/form/TrxMaterial.java @@ -1,153 +1,153 @@ -/****************************************************************************** - * Copyright (C) 2009 Low Heng Sin * - * Copyright (C) 2009 Idalica Corporation * - * 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. * - *****************************************************************************/ -package org.compiere.apps.form; - -import static org.compiere.model.SystemIDs.WINDOW_MATERIALTRANSACTIONS_INDIRECTUSER; - -import java.sql.Timestamp; -import java.util.logging.Level; - -import org.compiere.apps.IStatusBar; -import org.compiere.model.GridTab; -import org.compiere.model.GridWindow; -import org.compiere.model.GridWindowVO; -import org.compiere.model.I_C_ProjectIssue; -import org.compiere.model.I_M_InOutLine; -import org.compiere.model.I_M_InventoryLine; -import org.compiere.model.I_M_MovementLine; -import org.compiere.model.I_M_ProductionLine; -import org.compiere.model.I_M_Transaction; -import org.compiere.model.MQuery; -import org.compiere.util.CLogger; -import org.compiere.util.Env; -import org.compiere.util.Msg; - -public class TrxMaterial { - - /** Window No */ - public int m_WindowNo = 0; - /** MWindow */ - public GridWindow m_mWindow = null; - /** MTab pointer */ - public GridTab m_mTab = null; - - public MQuery m_staticQuery = null; - /** Logger */ - public static CLogger log = CLogger.getCLogger(TrxMaterial.class); - - /** - * Dynamic Layout (Grid). - * Based on AD_Window: Material Transactions - */ - public void dynInit(IStatusBar statusBar) +/****************************************************************************** + * Copyright (C) 2009 Low Heng Sin * + * Copyright (C) 2009 Idalica Corporation * + * 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. * + *****************************************************************************/ +package org.compiere.apps.form; + +import static org.compiere.model.SystemIDs.WINDOW_MATERIALTRANSACTIONS_INDIRECTUSER; + +import java.sql.Timestamp; +import java.util.logging.Level; + +import org.compiere.apps.IStatusBar; +import org.compiere.model.GridTab; +import org.compiere.model.GridWindow; +import org.compiere.model.GridWindowVO; +import org.compiere.model.I_C_ProjectIssue; +import org.compiere.model.I_M_InOutLine; +import org.compiere.model.I_M_InventoryLine; +import org.compiere.model.I_M_MovementLine; +import org.compiere.model.I_M_ProductionLine; +import org.compiere.model.I_M_Transaction; +import org.compiere.model.MQuery; +import org.compiere.util.CLogger; +import org.compiere.util.Env; +import org.compiere.util.Msg; + +public class TrxMaterial { + + /** Window No */ + public int m_WindowNo = 0; + /** MWindow */ + public GridWindow m_mWindow = null; + /** MTab pointer */ + public GridTab m_mTab = null; + + public MQuery m_staticQuery = null; + /** Logger */ + public static CLogger log = CLogger.getCLogger(TrxMaterial.class); + + /** + * Dynamic Layout (Grid). + * Based on AD_Window: Material Transactions + */ + public void dynInit(IStatusBar statusBar) { - m_staticQuery = new MQuery(); - m_staticQuery.addRestriction("AD_Client_ID", MQuery.EQUAL, Env.getAD_Client_ID(Env.getCtx())); - int AD_Window_ID = WINDOW_MATERIALTRANSACTIONS_INDIRECTUSER; // Hardcoded - GridWindowVO wVO = Env.getMWindowVO (m_WindowNo, AD_Window_ID, 0); - if (wVO == null) - return; - m_mWindow = new GridWindow (wVO); - m_mTab = m_mWindow.getTab(0); - m_mWindow.initTab(0); - // - m_mTab.setQuery(MQuery.getEqualQuery("1", "2")); - m_mTab.query(false); - statusBar.setStatusLine(" ", false); - statusBar.setStatusDB(" "); - } // dynInit - - /************************************************************************** - * Refresh - Create Query and refresh grid - */ - public void refresh(Object organization, Object locator, Object product, Object movementType, - Timestamp movementDateFrom, Timestamp movementDateTo, IStatusBar statusBar) - { - /** - * Create Where Clause - */ - MQuery query = m_staticQuery.deepCopy(); - // Organization - if (organization != null && organization.toString().length() > 0) - query.addRestriction("AD_Org_ID", MQuery.EQUAL, organization); - // Locator - if (locator != null && locator.toString().length() > 0) - query.addRestriction("M_Locator_ID", MQuery.EQUAL, locator); - // Product - if (product != null && product.toString().length() > 0) - query.addRestriction("M_Product_ID", MQuery.EQUAL, product); - // MovementType - if (movementType != null && movementType.toString().length() > 0) - query.addRestriction("MovementType", MQuery.EQUAL, movementType); - // DateFrom - if (movementDateFrom != null) - query.addRestriction("TRUNC(MovementDate)", MQuery.GREATER_EQUAL, movementDateFrom); - // DateTO - if (movementDateTo != null) - query.addRestriction("TRUNC(MovementDate)", MQuery.LESS_EQUAL, movementDateTo); - if (log.isLoggable(Level.INFO)) log.info( "VTrxMaterial.refresh query=" + query.toString()); - - /** - * Refresh/Requery - */ - statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "StartSearch"), false); - // - m_mTab.setQuery(query); - m_mTab.query(false); - // - int no = m_mTab.getRowCount(); - statusBar.setStatusLine(" ", false); - statusBar.setStatusDB(Integer.toString(no)); - } // refresh - - public int AD_Table_ID; - public int Record_ID; - /** - * Zoom - */ - public void zoom() - { - log.info(""); - // - AD_Table_ID = 0; - Record_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, I_M_Transaction.COLUMNNAME_M_InOutLine_ID); - if (Record_ID != 0) { - AD_Table_ID = I_M_InOutLine.Table_ID; - } else { - Record_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, I_M_Transaction.COLUMNNAME_M_InventoryLine_ID); - if (Record_ID != 0) { - AD_Table_ID = I_M_InventoryLine.Table_ID; - } else { - Record_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, I_M_Transaction.COLUMNNAME_M_MovementLine_ID); - if (Record_ID != 0) { - AD_Table_ID = I_M_MovementLine.Table_ID; - } else { - Record_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, I_M_Transaction.COLUMNNAME_M_ProductionLine_ID); - if (Record_ID != 0) { - AD_Table_ID = I_M_ProductionLine.Table_ID; - } else { - Record_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, I_M_Transaction.COLUMNNAME_C_ProjectIssue_ID); - if (Record_ID != 0) { - AD_Table_ID = I_C_ProjectIssue.Table_ID; - } else { - log.warning("Not found zoom table WindowNo=" + m_WindowNo); - } - } - } - } - } - } // zoom - - -} + m_staticQuery = new MQuery(); + m_staticQuery.addRestriction("AD_Client_ID", MQuery.EQUAL, Env.getAD_Client_ID(Env.getCtx())); + int AD_Window_ID = WINDOW_MATERIALTRANSACTIONS_INDIRECTUSER; // Hardcoded + GridWindowVO wVO = Env.getMWindowVO (m_WindowNo, AD_Window_ID, 0); + if (wVO == null) + return; + m_mWindow = new GridWindow (wVO); + m_mTab = m_mWindow.getTab(0); + m_mWindow.initTab(0); + // + m_mTab.setQuery(MQuery.getEqualQuery("1", "2")); + m_mTab.query(false); + statusBar.setStatusLine(" ", false); + statusBar.setStatusDB(" "); + } // dynInit + + /************************************************************************** + * Refresh - Create Query and refresh grid + */ + public void refresh(Object organization, Object locator, Object product, Object movementType, + Timestamp movementDateFrom, Timestamp movementDateTo, IStatusBar statusBar) + { + /** + * Create Where Clause + */ + MQuery query = m_staticQuery.deepCopy(); + // Organization + if (organization != null && organization.toString().length() > 0) + query.addRestriction("AD_Org_ID", MQuery.EQUAL, organization); + // Locator + if (locator != null && locator.toString().length() > 0) + query.addRestriction("M_Locator_ID", MQuery.EQUAL, locator); + // Product + if (product != null && product.toString().length() > 0) + query.addRestriction("M_Product_ID", MQuery.EQUAL, product); + // MovementType + if (movementType != null && movementType.toString().length() > 0) + query.addRestriction("MovementType", MQuery.EQUAL, movementType); + // DateFrom + if (movementDateFrom != null) + query.addRestriction("TRUNC(MovementDate)", MQuery.GREATER_EQUAL, movementDateFrom); + // DateTO + if (movementDateTo != null) + query.addRestriction("TRUNC(MovementDate)", MQuery.LESS_EQUAL, movementDateTo); + if (log.isLoggable(Level.INFO)) log.info( "VTrxMaterial.refresh query=" + query.toString()); + + /** + * Refresh/Requery + */ + statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "StartSearch"), false); + // + m_mTab.setQuery(query); + m_mTab.query(false); + // + int no = m_mTab.getRowCount(); + statusBar.setStatusLine(" ", false); + statusBar.setStatusDB(Integer.toString(no)); + } // refresh + + public int AD_Table_ID; + public int Record_ID; + /** + * Zoom + */ + public void zoom() + { + log.info(""); + // + AD_Table_ID = 0; + Record_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, I_M_Transaction.COLUMNNAME_M_InOutLine_ID); + if (Record_ID != 0) { + AD_Table_ID = I_M_InOutLine.Table_ID; + } else { + Record_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, I_M_Transaction.COLUMNNAME_M_InventoryLine_ID); + if (Record_ID != 0) { + AD_Table_ID = I_M_InventoryLine.Table_ID; + } else { + Record_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, I_M_Transaction.COLUMNNAME_M_MovementLine_ID); + if (Record_ID != 0) { + AD_Table_ID = I_M_MovementLine.Table_ID; + } else { + Record_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, I_M_Transaction.COLUMNNAME_M_ProductionLine_ID); + if (Record_ID != 0) { + AD_Table_ID = I_M_ProductionLine.Table_ID; + } else { + Record_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, I_M_Transaction.COLUMNNAME_C_ProjectIssue_ID); + if (Record_ID != 0) { + AD_Table_ID = I_C_ProjectIssue.Table_ID; + } else { + log.warning("Not found zoom table WindowNo=" + m_WindowNo); + } + } + } + } + } + } // zoom + + +}