KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openbravo > erpCommon > ad_forms > AcctServer


1 /*
2  ******************************************************************************
3  * The contents of this file are subject to the Compiere License Version 1.1
4  * ("License"); You may not use this file except in compliance with the License
5  * You may obtain a copy of the License at http://www.compiere.org/license.html
6  * Software distributed under the License is distributed on an "AS IS" basis,
7  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
8  * the specific language governing rights and limitations under the License.
9  * The Original Code is Compiere ERP & CRM Business Solution
10  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
11  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
12  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
13  * Contributor(s): Openbravo SL
14  * Contributions are Copyright (C) 2001-2006 Openbravo S.L.
15  ******************************************************************************
16 */

17 package org.openbravo.erpCommon.ad_forms;
18
19
20 import org.openbravo.erpCommon.utility.*;
21 import org.openbravo.base.secureApp.HttpSecureAppServlet;
22 import org.openbravo.base.secureApp.VariablesSecureApp;
23 import org.openbravo.exception.*;
24 import java.math.*;
25 import java.sql.*;
26 import java.io.*;
27 import java.util.*;
28 import javax.servlet.*;
29 import org.apache.log4j.Logger;
30 import org.openbravo.erpCommon.utility.DateTimeData;
31 // imports for transactions
32
import org.openbravo.database.ConnectionProvider;
33 import org.openbravo.data.FieldProvider;
34
35
36
37 public abstract class AcctServer extends HttpSecureAppServlet {
38   static Logger log4j = Logger.getLogger(AcctServer.class);
39     public String JavaDoc batchSize = "100";
40
41     public BigDecimal ZERO = new BigDecimal("0");
42
43     public String JavaDoc groupLines = "";
44     public String JavaDoc Qty = null;
45     public static String JavaDoc tableName = "";
46     public static String JavaDoc strDateColumn = "";
47     public static String JavaDoc AD_Table_ID = "";
48     public String JavaDoc AD_Client_ID = "";
49     public String JavaDoc AD_Org_ID = "";
50     public String JavaDoc Status = "";
51     public String JavaDoc C_BPartner_ID = "";
52     public String JavaDoc C_BPartner_Location_ID = "";
53     public String JavaDoc M_Product_ID = "";
54     public String JavaDoc AD_OrgTrx_ID = "";
55     public String JavaDoc C_SalesRegion_ID = "";
56     public String JavaDoc C_Project_ID = "";
57     public String JavaDoc C_Campaign_ID = "";
58     public String JavaDoc C_Activity_ID = "";
59     public String JavaDoc C_LocFrom_ID = "";
60     public String JavaDoc C_LocTo_ID = "";
61     public String JavaDoc User1_ID = "";
62     public String JavaDoc User2_ID = "";
63     public String JavaDoc Name = "";
64     public String JavaDoc DocumentNo = "";
65     public String JavaDoc DateAcct = "";
66     public String JavaDoc DateDoc = "";
67     public String JavaDoc C_Period_ID = "";
68     public String JavaDoc C_Currency_ID = "";
69     public String JavaDoc C_DocType_ID = "";
70     public String JavaDoc C_Charge_ID = "";
71     public String JavaDoc ChargeAmt = "";
72     public String JavaDoc C_BankAccount_ID = "";
73     public String JavaDoc C_CashBook_ID = "";
74     public String JavaDoc M_Warehouse_ID = "";
75     public String JavaDoc Posted = "";
76     public String JavaDoc DocumentType = "";
77     public String JavaDoc TaxIncluded = "";
78     public String JavaDoc GL_Category_ID = "";
79     public String JavaDoc GL_Budget_ID = "";
80     public String JavaDoc Record_ID = "";
81     /** No Currency in Document Indicator */
82     protected static final String JavaDoc NO_CURRENCY = "-1";
83     // This is just for the initialitation of the accounting
84
public String JavaDoc m_IsOpening = "N";
85
86     public Fact[] m_fact = null;
87     public AcctSchema[] m_as = null;
88
89     private FieldProvider objectFieldProvider [];
90
91     public String JavaDoc[] Amounts = new String JavaDoc[4];
92
93     public DocLine[] p_lines = new DocLine[0];
94     public DocLine_Payment[] m_debt_payments = new DocLine_Payment[0];
95
96     /** Is (Source) Multi-Currency Document - i.e. the document has different currencies
97      * (if true, the document will not be source balanced) */

98     public boolean MultiCurrency = false;
99
100     /** Amount Type - Invoice */
101     public static final int AMTTYPE_Gross = 0;
102     public static final int AMTTYPE_Net = 1;
103     public static final int AMTTYPE_Charge = 2;
104     /** Amount Type - Allocation */
105     public static final int AMTTYPE_Invoice = 0;
106     public static final int AMTTYPE_Allocation = 1;
107     public static final int AMTTYPE_Discount = 2;
108     public static final int AMTTYPE_WriteOff = 3;
109
110         /** Document Status */
111     public static final String JavaDoc STATUS_NotPosted = "N";
112     /** Document Status */
113     public static final String JavaDoc STATUS_NotBalanced = "b";
114     /** Document Status */
115     public static final String JavaDoc STATUS_NotConvertible = "c";
116     /** Document Status */
117     public static final String JavaDoc STATUS_PeriodClosed = "p";
118     /** Document Status */
119     public static final String JavaDoc STATUS_InvalidAccount = "i";
120     /** Document Status */
121     public static final String JavaDoc STATUS_PostPrepared = "y";
122     /** Document Status */
123     public static final String JavaDoc STATUS_Posted = "Y";
124     /** Document Status */
125     public static final String JavaDoc STATUS_Error = "E";
126
127     /** AR Invoices */
128     public static final String JavaDoc DOCTYPE_ARInvoice = "ARI";
129     /** AR Credit Memo */
130     public static final String JavaDoc DOCTYPE_ARCredit = "ARC";
131     /** AR Receipt */
132     public static final String JavaDoc DOCTYPE_ARReceipt = "STT";//antes ARR
133
/** AR ProForma */
134     public static final String JavaDoc DOCTYPE_ARProForma = "ARF";
135
136     /** AP Invoices */
137     public static final String JavaDoc DOCTYPE_APInvoice = "API";
138     /** AP Credit Memo */
139     public static final String JavaDoc DOCTYPE_APCredit = "APC";
140     /** AP Payment */
141     public static final String JavaDoc DOCTYPE_APPayment = "APP";
142
143     /** CashManagement Bank Statement */
144     public static final String JavaDoc DOCTYPE_BankStatement = "CMB";
145     /** CashManagement Cash Journals */
146     public static final String JavaDoc DOCTYPE_CashJournal = "CMC";
147     /** CashManagement Allocations */
148     public static final String JavaDoc DOCTYPE_Allocation = "CMA";
149
150     /** Amortization */
151     public static final String JavaDoc DOCTYPE_Amortization = "AMZ";
152
153     /** Material Shipment */
154     public static final String JavaDoc DOCTYPE_MatShipment = "MMS";
155     /** Material Receipt */
156     public static final String JavaDoc DOCTYPE_MatReceipt = "MMR";
157     /** Material Inventory */
158     public static final String JavaDoc DOCTYPE_MatInventory = "MMI";
159     /** Material Movement */
160     public static final String JavaDoc DOCTYPE_MatMovement = "MMM";
161     /** Material Production */
162     public static final String JavaDoc DOCTYPE_MatProduction = "MMP";
163
164     /** Match Invoice */
165     public static final String JavaDoc DOCTYPE_MatMatchInv = "MXI";
166     /** Match PO */
167     public static final String JavaDoc DOCTYPE_MatMatchPO = "MXP";
168
169     /** GL Journal */
170     public static final String JavaDoc DOCTYPE_GLJournal = "GLJ";
171
172     /** Purchase Order */
173     public static final String JavaDoc DOCTYPE_POrder = "POO";
174     /** Sales Order */
175     public static final String JavaDoc DOCTYPE_SOrder = "SOO";
176
177     //DPManagement
178
public static final String JavaDoc DOCTYPE_DPManagement = "DPM";
179
180     /*************************************************************************/
181
182     /** Account Type - Invoice */
183     public static final String JavaDoc ACCTTYPE_Charge = "0";
184     public static final String JavaDoc ACCTTYPE_C_Receivable = "1";
185     public static final String JavaDoc ACCTTYPE_V_Liability = "2";
186     public static final String JavaDoc ACCTTYPE_V_Liability_Services = "3";
187
188     /** Account Type - Payment */
189     public static final String JavaDoc ACCTTYPE_UnallocatedCash = "10";
190     public static final String JavaDoc ACCTTYPE_BankInTransit = "11";
191     public static final String JavaDoc ACCTTYPE_PaymentSelect = "12";
192     public static final String JavaDoc ACCTTYPE_WriteOffDefault = "13";
193     public static final String JavaDoc ACCTTYPE_BankInTransitDefault = "14";
194     public static final String JavaDoc ACCTTYPE_ConvertChargeDefaultAmt= "15";
195     public static final String JavaDoc ACCTTYPE_ConvertGainDefaultAmt = "16";
196
197
198     /** Account Type - Cash */
199     public static final String JavaDoc ACCTTYPE_CashAsset = "20";
200     public static final String JavaDoc ACCTTYPE_CashTransfer = "21";
201     public static final String JavaDoc ACCTTYPE_CashExpense = "22";
202     public static final String JavaDoc ACCTTYPE_CashReceipt = "23";
203     public static final String JavaDoc ACCTTYPE_CashDifference = "24";
204
205     /** Account Type - Allocation */
206     public static final String JavaDoc ACCTTYPE_DiscountExp = "30";
207     public static final String JavaDoc ACCTTYPE_DiscountRev = "31";
208     public static final String JavaDoc ACCTTYPE_WriteOff = "32";
209
210     /** Account Type - Bank Statement */
211     public static final String JavaDoc ACCTTYPE_BankAsset = "40";
212     public static final String JavaDoc ACCTTYPE_InterestRev = "41";
213     public static final String JavaDoc ACCTTYPE_InterestExp = "42";
214     public static final String JavaDoc ACCTTYPE_ConvertChargeLossAmt= "43";
215     public static final String JavaDoc ACCTTYPE_ConvertChargeGainAmt= "44";
216     
217
218     /** Inventory Accounts */
219     public static final String JavaDoc ACCTTYPE_InvDifferences = "50";
220     public static final String JavaDoc ACCTTYPE_NotInvoicedReceipts = "51";
221
222     /** Project Accounts */
223     public static final String JavaDoc ACCTTYPE_ProjectAsset = "61";
224     public static final String JavaDoc ACCTTYPE_ProjectWIP = "62";
225
226     /** GL Accounts */
227     public static final String JavaDoc ACCTTYPE_PPVOffset = "60";
228
229     // Reference (to find SalesRegion from BPartner)
230
public String JavaDoc BP_C_SalesRegion_ID = ""; // set in FactLine
231

232
233
234
235     int errors=0;
236     int success=0;
237
238     /**
239      * Cosntructor
240      * @param AD_Client_ID Client ID of these Documents
241      */

242     public AcctServer (String JavaDoc m_AD_Client_ID){
243         AD_Client_ID = m_AD_Client_ID;
244         if (log4j.isDebugEnabled()) log4j.debug("AcctServer - LOADING ARRAY: " + m_AD_Client_ID);
245         m_as = AcctSchema.getAcctSchemaArray (this, m_AD_Client_ID);
246     } //
247

248     public void setBatchSize(String JavaDoc newbatchSize) {
249       batchSize = newbatchSize;
250     }
251
252     public void run(VariablesSecureApp vars) throws IOException, ServletException{
253       AD_Client_ID = vars.getClient();
254       try {
255         Connection con = getTransactionConnection();
256         String JavaDoc strIDs = "";
257         if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Run - TableName = " + tableName);
258         AcctServerData [] data = AcctServerData.select(this,tableName, AD_Client_ID, strDateColumn, 0, Integer.valueOf(batchSize).intValue());
259         if(data==null)if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Run -Select inicial realizada N = " + data.length + " - Key: " + data[0].id);
260         for (int i=0;data != null && i<data.length;i++){
261             strIDs += data[i].getField("ID") + ", ";
262             if (!post(data[i].getField("ID"),false, vars,this,con)) {
263                 releaseRollbackConnection(con);
264                 return;
265             }
266         }
267         if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Run -" + data.length + " IDs [" + strIDs + "]");
268         // Create Automatic Matching
269
//match (vars, this,con);
270
releaseCommitConnection(con);
271       } catch (NoConnectionAvailableException ex) {
272         throw new ServletException("@CODE=NoConnectionAvailable");
273       } catch (SQLException ex2) {
274         throw new ServletException("@CODE=" + Integer.toString(ex2.getErrorCode()) + "@" + ex2.getMessage());
275       }
276     }
277
278     /**
279      * Factory - Create Posting document
280      *
281      * @param AD_Table_ID Table ID of Documents
282      * @param AD_Client_ID Client ID of Documents
283      * @return Document
284      */

285     public static AcctServer get (String JavaDoc AD_Table_ID, String JavaDoc AD_Client_ID) throws ServletException{
286         AcctServer acct = null;
287         if (log4j.isDebugEnabled()) log4j.debug("get - table: "+AD_Table_ID);
288         switch (Integer.parseInt(AD_Table_ID)){
289             case 318:
290                 acct = new DocInvoice (AD_Client_ID);
291                 acct.tableName = "C_Invoice";
292                 acct.AD_Table_ID = "318";
293                 acct.strDateColumn = "DateAcct";
294                 acct.reloadAcctSchemaArray();
295                 acct.groupLines = AcctServerData.selectGroupLines(acct, AD_Client_ID);
296                 break;
297 /* case 390:
298                 acct = new DocAllocation (AD_Client_ID);
299                 acct.strDateColumn = "";
300                 acct.AD_Table_ID = "390";
301                 acct.reloadAcctSchemaArray();
302                 acct.break;*/

303             case 800060:
304                 acct = new DocAmortization (AD_Client_ID);
305                 acct.tableName = "A_Amortization";
306                 acct.AD_Table_ID = "800060";
307                 acct.strDateColumn = "DateAcct";
308                 acct.reloadAcctSchemaArray();
309                 break;
310                 
311             case 800176:
312                 if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Get DPM");
313                 acct = new DocDPManagement (AD_Client_ID);
314                 acct.tableName = "C_DP_Management";
315                 acct.AD_Table_ID = "800176";
316                 acct.strDateColumn = "DateAcct";
317                 acct.reloadAcctSchemaArray();
318                 break;
319             case 407:
320                 acct = new DocCash (AD_Client_ID);
321                 acct.tableName = "C_Cash";
322                 acct.strDateColumn = "DateAcct";
323                 acct.AD_Table_ID = "407";
324                 acct.reloadAcctSchemaArray();
325                 break;
326             case 392:
327                 acct = new DocBank (AD_Client_ID);
328                 acct.tableName = "C_Bankstatement";
329                 acct.strDateColumn = "StatementDate";
330                 acct.AD_Table_ID = "392";
331                 acct.reloadAcctSchemaArray();
332                 break;
333             case 259:
334                 acct = new DocOrder (AD_Client_ID);
335                 acct.tableName = "C_Order";
336                 acct.strDateColumn = "DateAcct";
337                 acct.AD_Table_ID = "259";
338                 acct.reloadAcctSchemaArray();
339                 break;
340             case 800019:
341                 acct = new DocPayment (AD_Client_ID);
342                 acct.tableName = "C_Settlement";
343                 acct.strDateColumn = "Dateacct";
344                 acct.AD_Table_ID = "800019";
345                 acct.reloadAcctSchemaArray();
346                 break;
347             case 319:
348                 acct = new DocInOut (AD_Client_ID);
349                 acct.tableName = "M_InOut";
350                 acct.strDateColumn = "DateAcct";
351                 acct.AD_Table_ID = "319";
352                 acct.reloadAcctSchemaArray();
353                 break;
354             case 321:
355                 acct = new DocInventory (AD_Client_ID);
356                 acct.tableName = "M_Inventory";
357                 acct.strDateColumn = "MovementDate";
358                 acct.AD_Table_ID = "321";
359                 acct.reloadAcctSchemaArray();
360                 break;
361             case 323:
362                 acct = new DocMovement (AD_Client_ID);
363                 acct.tableName = "M_Movement";
364                 acct.strDateColumn = "MovementDate";
365                 acct.AD_Table_ID = "323";
366                 acct.reloadAcctSchemaArray();
367                 break;/*
368             case 325:
369                 acct = new DocProduction (AD_Client_ID);
370                 acct.strDateColumn = "MovementDate";
371                 acct.reloadAcctSchemaArray();
372                 break;*/

373             case 224:
374                 if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Before OBJECT CREATION");
375                 acct = new DocGLJournal (AD_Client_ID);
376                 acct.tableName = "GL_Journal";
377                 acct.strDateColumn = "DateAcct";
378                 acct.AD_Table_ID = "224";
379                 acct.reloadAcctSchemaArray();
380                 break;/*
381             case 472:
382                 acct = new DocMatchInv (AD_Client_ID);
383                 acct.strDateColumn = "MovementDate";
384                 acct.reloadAcctSchemaArray();
385                 break;
386             case 473:
387                 acct = new DocMatchPO (AD_Client_ID);
388                 acct.strDateColumn = "MovementDate";
389                 acct.reloadAcctSchemaArray();
390                 break;
391             case DocProjectIssue.AD_TABLE_ID:
392                 acct = new DocProjectIssue (AD_Client_ID);
393                 acct.strDateColumn = "MovementDate";
394                 acct.reloadAcctSchemaArray();
395                 break;*/

396         }
397         if (acct == null) log4j.warn("AcctServer - get - Unknown AD_Table_ID=" + AD_Table_ID);
398         else if (log4j.isDebugEnabled()) log4j.debug("AcctServer - get - AcctSchemaArray length=" + (acct.m_as).length);
399         if (log4j.isDebugEnabled()) log4j.debug("AcctServer - get - AD_Table_ID=" + AD_Table_ID);
400         return acct;
401     } // get
402

403   public void reloadAcctSchemaArray() throws ServletException{
404     if (log4j.isDebugEnabled()) log4j.debug("AcctServer - reloadAcctSchemaArray - " + this.AD_Table_ID);
405     AcctSchema acct = null;
406     ArrayList<Object JavaDoc> new_as = new ArrayList<Object JavaDoc>();
407     for (int i=0;i<(this.m_as).length;i++){
408       acct = m_as[i];
409       if(AcctSchemaData.selectAcctSchemaTable(this, acct.m_C_AcctSchema_ID, this.AD_Table_ID)){
410         new_as.add(new AcctSchema(this,acct.m_C_AcctSchema_ID));
411         /*System.out.println("###################### acct.m_C_AcctSchema_ID - " + acct.m_C_AcctSchema_ID);
412         System.out.println("###################### this.AD_Table_ID - " + this.AD_Table_ID);*/

413       }
414     }
415     AcctSchema[] retValue = new AcctSchema [new_as.size()];
416     new_as.toArray(retValue);
417     if (log4j.isDebugEnabled()) log4j.debug("AcctServer - RELOADING ARRAY: " + retValue.length);
418     this.m_as = retValue;
419     /*System.out.println("###################### reloadAcctSchemaArray - this.AD_Table_ID - " + this.AD_Table_ID);
420     System.out.println("###################### reloadAcctSchemaArray - this.m_as - " + (this.m_as).length);
421     System.out.println("###################### reloadAcctSchemaArray - retValue - " + retValue.length);*/

422   }
423
424
425   public boolean post(String JavaDoc strClave, boolean force,VariablesSecureApp vars,ConnectionProvider conn,Connection con)throws ServletException{
426     Record_ID = strClave;
427     if (log4j.isDebugEnabled()) log4j.debug("post " + strClave+" tablename: "+tableName);
428     //System.out.println("********************************** Record_ID post - **************************");
429
try{
430         if (AcctServerData.update(con,conn,tableName,strClave)!=1){
431               log4j.warn("AcctServer - Post -Cannot lock Document - ignored: " + tableName + "_ID=" + strClave);
432               return false;
433         }
434         if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Post -TableName -" + tableName + "- ad_client_id -" + AD_Client_ID + "- " + tableName + "_id -" + strClave);
435         try{
436             loadObjectFieldProvider(this,AD_Client_ID,strClave);
437         }catch(ServletException e){
438             log4j.warn(e);
439         }
440         FieldProvider data [] = getObjectFieldProvider();
441         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Post - Select registro realizada -" + data.length);
442
//for (int i=0;i<data.length;i++){
443
//System.out.println("********************************** Record_ID - " + Record_ID);
444
if (getDocumentConfirmation(conn, Record_ID) && post(data,force,vars,conn,con)){
445          success++;
446         }else errors++;
447         //}
448
}
449     catch (ServletException e){
450         log4j.warn(e);
451         return false;
452     }
453     return true;
454   }
455
456     private boolean post(FieldProvider [] data, boolean force,VariablesSecureApp vars,ConnectionProvider conn,Connection con)throws ServletException{
457        if (log4j.isDebugEnabled()) log4j.debug("post data" + C_Currency_ID);
458         if (!loadDocument(data,force,conn)){
459         log4j.warn("AcctServer - post - Error loading document");
460             return false;
461         }
462         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Post - Antes de getAcctSchemaArray - C_CURRENCY_ID = " + C_Currency_ID);
463
// Create Fact per AcctSchema
464
//if (log4j.isDebugEnabled()) log4j.debug("POSTLOADING ARRAY: " + AD_Client_ID);
465
//m_as = AcctSchema.getAcctSchemaArray (conn,AD_Client_ID);
466
//if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Post - Antes de new Fact - C_CURRENCY_ID = " + C_Currency_ID);
467
m_fact = new Fact [m_as.length];
468
469         // for all Accounting Schema
470
boolean OK = true;
471         if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Post -Beforde the loop - C_CURRENCY_ID = " + C_Currency_ID);
472         for (int i = 0; OK && i < m_as.length; i++){
473             if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Post - Before the postLogic - C_CURRENCY_ID = " + C_Currency_ID);
474             Status = postLogic (i, conn,con, vars);
475             if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Post - After postLogic");
476             if (!Status.equals(STATUS_Posted))
477                 OK = false;
478         }
479         if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Post - Before the postCommit - C_CURRENCY_ID = " + C_Currency_ID);
480         // commitFact
481
Status = postCommit (Status, conn, vars,con);
482
483         // Create Note
484
if (!Status.equals(STATUS_Posted)){
485             // Insert Note
486
String JavaDoc AD_Message = "PostingError-" + Status;
487             // Text - Only Status
488
String JavaDoc Text = Status;
489             // API - DocNo - 2000-01-31
490
String JavaDoc Reference = DocumentType
491                 + " - " + DocumentNo
492                 + " - " + DateDoc;
493             String JavaDoc AD_User_ID = "0";
494             insertNote(AD_Client_ID, AD_Org_ID, AD_User_ID,
495                 AD_Table_ID, Record_ID, AD_Message, Text, Reference,vars, conn,con);
496         }
497
498         // dispose facts
499
for (int i = 0; i < m_fact.length; i++)
500             if (m_fact[i] != null) m_fact[i].dispose();
501         p_lines = null;
502
503         return Status.equals(STATUS_Posted);
504     } // post
505

506     /**
507      * Post Commit.
508      * Save Facts & Document
509      * @param status status
510      * @return Posting Status
511      */

512     private final String JavaDoc postCommit (String JavaDoc status,ConnectionProvider conn,VariablesSecureApp vars,Connection con)throws ServletException{
513         log4j.debug("AcctServer - postCommit Sta=" + status + " DT=" + DocumentType + " ID=" + Record_ID);
514         Status = status;
515         try{
516         // *** Transaction Start ***
517
// Commit Facts
518
if (status.equals(AcctServer.STATUS_Posted)){
519                 if (m_fact!=null && m_fact.length!=0) {
520                     log4j.debug("AcctServer - postCommit - m_fact.length = " + m_fact.length);
521                     for (int i = 0; i < m_fact.length; i++){
522                         if (m_fact[i] != null && m_fact[i].save(con,conn, vars));
523                         else{
524                             //conn.releaseRollbackConnection(con);
525
unlock(conn,con);
526                             return AcctServer.STATUS_Error;
527                         }
528                     }
529                 }
530             }
531             // Commit Doc
532
if (!save(conn,con)){ // contains unlock
533
//conn.releaseRollbackConnection(con);
534
unlock(conn,con);
535                 return AcctServer.STATUS_Error;
536             }
537             //conn.releaseCommitConnection(con);
538
// *** Transaction End ***
539
}
540         catch (Exception JavaDoc e){
541             log4j.warn("AcctServer - postCommit" + e);
542             status = AcctServer.STATUS_Error;
543             //conn.releaseRollbackConnection(con);
544
unlock(conn,con);
545         }
546         return status;
547     } // postCommit
548

549     /**
550      * Save to Disk - set posted flag
551      * @param con connection
552      * @return true if saved
553      */

554     private final boolean save (ConnectionProvider conn, Connection con){
555         //if (log4j.isDebugEnabled()) log4j.debug ("AcctServer - save - ->" + Status);
556
int no = 0;
557         try{
558             no = AcctServerData.updateSave(con,conn,tableName,Status,Record_ID);
559         }catch(ServletException e){
560             log4j.warn(e);
561         }
562         return no==1;
563     } // save
564

565
566     /**
567      * Unlock Document
568      */

569     private void unlock(ConnectionProvider conn,Connection con){
570         int i =0;
571         try{
572         i = AcctServerData.updateUnlock(con,conn,tableName,Record_ID);
573         }catch(ServletException e){
574             log4j.warn("AcctServer - Document locked: -" + e);
575         }
576         /*if (i>0){
577             releaseCommitConnection(con);
578         }else{
579             releaseRollbackConnection(con);
580         }*/

581     } // unlock
582

583
584
585     public boolean loadDocument(FieldProvider[] data, boolean force,ConnectionProvider conn){
586         if (log4j.isDebugEnabled()) log4j.debug("loadDocument " + data.length);
587
588         Status = STATUS_Error;
589         String JavaDoc Name = "";
590         AD_Client_ID=data[0].getField("AD_Client_ID");
591         AD_Org_ID=data[0].getField("AD_Org_ID");
592         C_BPartner_ID=data[0].getField("C_BPartner_ID");
593         M_Product_ID=data[0].getField("M_Product_ID");
594         AD_OrgTrx_ID=data[0].getField("AD_OrgTrx_ID");
595         C_SalesRegion_ID=data[0].getField("C_SalesRegion_ID");
596         C_Project_ID=data[0].getField("C_Project_ID");
597         C_Campaign_ID=data[0].getField("C_Campaign_ID");
598         C_Activity_ID=data[0].getField("C_Activity_ID");
599         C_LocFrom_ID=data[0].getField("C_LocFrom_ID");
600         C_LocTo_ID=data[0].getField("C_LocTo_ID");
601         User1_ID=data[0].getField("User1_ID");
602         User2_ID=data[0].getField("User2_ID");
603
604         Name=data[0].getField("Name");
605         DocumentNo = data[0].getField("DocumentNo");
606         DateAcct = data[0].getField("DateAcct");
607         DateDoc = data[0].getField("DateDoc");
608         C_Period_ID = data[0].getField("C_Period_ID");
609         C_Currency_ID = data[0].getField("C_Currency_ID");
610         C_DocType_ID = data[0].getField("C_DocType_ID");
611         C_Charge_ID = data[0].getField("C_Charge_ID");
612         ChargeAmt = data[0].getField("ChargeAmt");
613         C_BankAccount_ID = data[0].getField("C_BankAccount_ID");
614         if (log4j.isDebugEnabled()) log4j.debug("AcctServer - loadDocument - C_BankAccount_ID : " + C_BankAccount_ID);
615         Posted = data[0].getField("Posted");
616         if (!loadDocumentDetails(data, conn)) loadDocumentType();
617         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - loadDocument - DocumentDetails Loaded");
618
if ((DateAcct == null || DateAcct == "") && (DateDoc != null && DateDoc != ""))
619             DateAcct = DateDoc;
620         else if ((DateDoc == null || DateDoc == "") && (DateAcct != null && DateAcct != ""))
621             DateDoc = DateAcct;
622         // DocumentNo (or Name)
623
if (DocumentNo == null || DocumentNo.length() == 0)
624             DocumentNo = Name;
625 // if (DocumentNo == null || DocumentNo.length() == 0)(DateDoc == "" && DateAcct != "")
626
// DocumentNo = "";
627

628         // Check Mandatory Info
629
//if (log4j.isDebugEnabled()) log4j.debug("AcctServer - loadDocument - C_Currency_ID : " + C_Currency_ID);
630
String JavaDoc error = "";
631         if (AD_Table_ID == null || AD_Table_ID == "")
632             error += " AD_Table_ID";
633         if (Record_ID == null || Record_ID == "")
634             error += " Record_ID";
635         if (AD_Client_ID == null || AD_Client_ID == "")
636             error += " AD_Client_ID";
637         if (AD_Org_ID == null || AD_Org_ID == "")
638             error += " AD_Org_ID";
639         if (C_Currency_ID == null || C_Currency_ID == "")
640             error += " C_Currency_ID";
641         if (DateAcct == null || DateAcct == "")
642             error += " DateAcct";
643         if (DateDoc == null || DateDoc == "")
644             error += " DateDoc";
645         if (error.length() > 0){
646             log4j.warn("AcctServer - loadDocument - " + DocumentNo + " - Mandatory info missing: " + error);
647             return false;
648         }
649
650         // Delete existing Accounting
651
if (force){
652             if (Posted.equals("Y") && !isPeriodOpen()){ // already posted - don't delete if period closed
653
log4j.warn("AcctServer - loadDocument - " + DocumentNo + " - Period Closed for already posted document");
654                 return false;
655             }
656             // delete it
657
int no =0;
658             try{
659             no = AcctServerData.delete(this,tableName,Record_ID);
660             }catch(ServletException e){
661                 log4j.warn(e);
662             }
663             //if (log4j.isDebugEnabled()) log4j.debug("post - deleted=" + no);
664
}
665         else if (Posted.equals("Y")){
666             log4j.warn("AcctServer - loadDocument - " + DocumentNo + " - Document already posted");
667             return false;
668         }
669         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - loadDocument -finished");
670
return true;
671     } // loadDocument
672

673
674     public void loadDocumentType(){
675       //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - loadDocumentType - DocumentType: " + DocumentType + " - C_DocType_ID : " + C_DocType_ID);
676
try{
677             if (/*DocumentType=="" && */C_DocType_ID != null && C_DocType_ID !=""){
678                 AcctServerData[] data = AcctServerData.selectDocType(this,C_DocType_ID);
679                 DocumentType = data[0].docbasetype;
680                 GL_Category_ID = data[0].glCategoryId;
681             }
682                     // We have a document Type, but no GL info - search for DocType
683
if (GL_Category_ID == ""){
684                 AcctServerData[] data = AcctServerData.selectGLCategory(this,AD_Client_ID,DocumentType);
685                 if (data!=null && data.length != 0)GL_Category_ID = data[0].glCategoryId;
686             }
687             if (DocumentType == "")log4j.warn("AcctServer - loadDocumentType - No DocType for GL Info");
688             if (GL_Category_ID == ""){
689                 AcctServerData[] data = AcctServerData.selectDefaultGLCategory(this,AD_Client_ID);
690                 GL_Category_ID = data[0].glCategoryId;
691             }
692         }catch(ServletException e){
693             log4j.warn(e);
694         }
695         if (GL_Category_ID == "")log4j.warn("AcctServer - loadDocumentType - No GL Info");
696         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - loadDocumentType -" + tableName + "_ID : " + Record_ID + " - C_DocType_ID: " + C_DocType_ID + " - DocumentType: " + DocumentType);
697
}
698
699     public boolean insertNote (String JavaDoc AD_Client_ID, String JavaDoc AD_Org_ID, String JavaDoc AD_User_ID,String JavaDoc AD_Table_ID, String JavaDoc Record_ID,String JavaDoc AD_MessageValue, String JavaDoc Text, String JavaDoc Reference,VariablesSecureApp vars,ConnectionProvider conn,Connection con){
700
701         if (AD_MessageValue == "" || AD_MessageValue.length() == 0)
702             throw new IllegalArgumentException JavaDoc("AcctServer - insertNote - required parameter missing - AD_Message");
703
704         // Database limits
705
if (Text == null)
706             Text = "";
707         if (Text.length() > 2000)
708             Text = Text.substring(0,1999);
709         if (Reference == null)
710             Reference = "";
711         if (Reference.length() > 60)
712             Reference = Reference.substring(0,59);
713         //
714
//if (log4j.isDebugEnabled()) log4j.debug("AcctServer - insertNote - " + AD_MessageValue + " - " + Reference);
715
//
716
String JavaDoc CompiereSys = "N";
717         int no=0;
718         try{
719             String JavaDoc AD_Note_ID = SequenceIdData.getSequence(this, "AD_Note", vars.getClient());
720             
721
722             // Create Entry
723
no = AcctServerData.insertNote(con,conn, AD_Note_ID, AD_Client_ID, AD_Org_ID, AD_User_ID, Text, Reference, AD_Table_ID, Record_ID, AD_MessageValue);
724
725             // AD_Message must exist, so if not created, it is probably
726
// due to non-existing AD_Message
727
if (no == 0){
728                 // Try again
729
no = AcctServerData.insertNote(con,conn, AD_Note_ID, AD_Client_ID, AD_Org_ID, AD_User_ID, Text, Reference, AD_Table_ID, Record_ID,"NoMessageFound");
730             }
731         }catch(ServletException e){
732             log4j.warn(e);
733         }
734
735         return no == 1;
736     } // insertNote
737

738     /**
739      * Posting logic for Accounting Schema index
740      * @param index Accounting Schema index
741      * @return posting status/error code
742      */

743     private final String JavaDoc postLogic (int index,ConnectionProvider conn,Connection con,VariablesSecureApp vars) throws ServletException{
744         // rejectUnbalanced
745
if (!m_as[index].isSuspenseBalancing() && !isBalanced())
746             return STATUS_NotBalanced;
747
748         // rejectUnconvertible
749
if (!isConvertible(m_as[index], conn))
750             return STATUS_NotConvertible;
751
752         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Before isPeriodOpen");
753
// rejectPeriodClosed
754
if (!isPeriodOpen())
755             return STATUS_PeriodClosed;
756         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - After isPeriodOpen");
757

758         // createFacts
759
try{
760           m_fact[index] = createFact (m_as[index], conn,con, vars);
761         }catch (Exception JavaDoc e){
762           log4j.warn(e);
763         }
764         if (m_fact[index] == null)
765             return STATUS_Error;
766         Status = STATUS_PostPrepared;
767
768         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Before balanceSource");
769
// balanceSource
770
if (!m_fact[index].isSourceBalanced())
771             m_fact[index].balanceSource(conn);
772         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - After balanceSource");
773

774         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Before isSegmentBalanced");
775
// balanceSegments
776
if (!m_fact[index].isSegmentBalanced(conn))
777             m_fact[index].balanceSegments(conn);
778         //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - After isSegmentBalanced");
779

780         // balanceAccounting
781
if (!m_fact[index].isAcctBalanced())
782             m_fact[index].balanceAccounting(conn);
783
784         return STATUS_Posted;
785     } // postLogic
786

787     /**
788      * Is the Source Document Balanced
789      * @return true if (source) baanced
790      */

791     public boolean isBalanced(){
792         // Multi-Currency documents are source balanced by definition
793
if (MultiCurrency)
794             return true;
795         //
796
boolean retValue = getBalance().equals("0");
797         if (retValue) if (log4j.isDebugEnabled()) log4j.debug("AcctServer - isBalanced - " + DocumentNo);
798         else log4j.warn("AcctServer - is not Balanced - " + DocumentNo);
799         return retValue;
800     } // isBalanced
801

802     /**
803      * Is Document convertible to currency and Conversion Type
804      * @param acctSchema accounting schema
805      * @return true, if vonvertable to accounting currency
806      */

807     public boolean isConvertible (AcctSchema acctSchema, ConnectionProvider conn) throws ServletException{
808         // No Currency in document
809
if (C_Currency_ID.equals("-1")){
810             //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - isConvertible (none) - " + DocumentNo);
811
return true;
812         }
813         // Get All Currencies
814
Vector<Object JavaDoc> set = new Vector<Object JavaDoc>();
815         set.addElement(C_Currency_ID);
816         for (int i = 0; p_lines != null && i < p_lines.length; i++){
817             String JavaDoc currency = p_lines[i].m_C_Currency_ID;
818             set.addElement(currency);
819         }
820
821         // just one and the same
822
if (set.size() == 1 && acctSchema.m_C_Currency_ID.equals(C_Currency_ID)){
823             //if (log4j.isDebugEnabled()) log4j.debug ("AcctServer - isConvertible (same) Cur=" + C_Currency_ID + " - " + DocumentNo);
824
return true;
825         }
826         boolean convertible = true;
827         for (int i=0;i<set.size();i++){
828             //if (log4j.isDebugEnabled()) log4j.debug ("AcctServer - get currency");
829
String JavaDoc currency = (String JavaDoc)set.elementAt(i);
830             if (currency==null) currency="";
831             //if (log4j.isDebugEnabled()) log4j.debug ("AcctServer - currency = " + currency);
832
if (!currency.equals(acctSchema.m_C_Currency_ID)){
833                 //if (log4j.isDebugEnabled()) log4j.debug ("AcctServer - get converted amount (init)");
834
String JavaDoc amt = getConvertedAmt("1", currency, acctSchema.m_C_Currency_ID,
835                     DateAcct, acctSchema.m_CurrencyRateType, AD_Client_ID, AD_Org_ID, conn);
836                 //if (log4j.isDebugEnabled()) log4j.debug ("get converted amount (end)");
837
if (amt == null){
838                     convertible = false;
839                     log4j.warn ("AcctServer - isConvertible NOT from " + currency + " - " + DocumentNo);
840                 }else if (log4j.isDebugEnabled()) log4j.debug ("AcctServer - isConvertible from " + currency);
841             }
842         }
843         //if (log4j.isDebugEnabled()) log4j.debug ("AcctServer - isConvertible=" + convertible + ", AcctSchemaCur=" + acctSchema.m_C_Currency_ID + " - " + DocumentNo);
844
return convertible;
845     } // isConvertible
846

847
848     /**
849      * Get the Amount
850      * (loaded in loadDocumentDetails)
851      *
852      * @param AmtType see AMTTYPE_*
853      * @return Amount
854      */

855     public String JavaDoc getAmount(int AmtType){
856         if (AmtType < 0 || Amounts == null || AmtType >= Amounts.length)
857             return null;
858         return (Amounts[AmtType].equals(""))?"0":Amounts[AmtType];
859     } // getAmount
860

861     /**
862      * Get Amount with index 0
863      * @return Amount (primary document amount)
864      */

865     public String JavaDoc getAmount(){
866         return Amounts[0];
867     } // getAmount
868

869         /**
870      * Convert an amount
871      * @param CurFrom_ID The C_Currency_ID FROM
872      * @param CurTo_ID The C_Currency_ID TO
873      * @param ConvDate The Conversion date - if null - use current date
874      * @param RateType The Conversion rate type - if null/empty - use Spot
875      * @param Amt The amount to be converted
876      * @return converted amount
877      */

878     public static String JavaDoc getConvertedAmt (String JavaDoc Amt, String JavaDoc CurFrom_ID, String JavaDoc CurTo_ID,
879         String JavaDoc ConvDate, String JavaDoc RateType, ConnectionProvider conn){
880       if (log4j.isDebugEnabled()) log4j.debug("AcctServer - getConvertedAmount no client nor org");
881       return getConvertedAmt (Amt, CurFrom_ID, CurTo_ID, ConvDate, RateType, "","", conn);
882     }
883    
884     public static String JavaDoc getConvertedAmt (String JavaDoc Amt, String JavaDoc CurFrom_ID, String JavaDoc CurTo_ID,
885         String JavaDoc ConvDate, String JavaDoc RateType, String JavaDoc client, String JavaDoc org, ConnectionProvider conn){
886         if (log4j.isDebugEnabled()) log4j.debug("AcctServer - getConvertedAmount - starting method - Amt : " + Amt + " - CurFrom_ID : " + CurFrom_ID + " - CurTo_ID : " + CurTo_ID + "- ConvDate: "+ConvDate+" - RateType:"+RateType+" - client:"+client+"- org:"+org);
887         
888         if (Amt.equals(""))
889             throw new IllegalArgumentException JavaDoc("AcctServer - getConvertedAmt - required parameter missing - Amt");
890         if (CurFrom_ID.equals(CurTo_ID) || Amt.equals("0"))
891             return Amt;
892         AcctServerData[] data = null;
893         try{
894             if (ConvDate == "")ConvDate = DateTimeData.today(conn);
895             // ConvDate IN DATE
896
if (RateType == null || RateType.equals("")) RateType = "S";
897             data = AcctServerData.currencyConvert(conn,Amt,CurFrom_ID,CurTo_ID,ConvDate,RateType, client, org);
898         }catch(ServletException e){
899             log4j.warn (e);
900         }
901         if (data==null || data.length == 0){
902             /*log4j.error("No conversion ratio");
903             throw new ServletException("No conversion ratio defined!");*/

904             return "";
905         }else {
906             if (log4j.isDebugEnabled()) log4j.debug("getConvertedAmount - converted:"+data[0].converted);
907               return data[0].converted;
908         }
909     } // getConvertedAmt
910

911   
912     /**
913      * Is Period Open
914      * @return true if period is open
915      */

916     public boolean isPeriodOpen(){
917         //if (log4j.isDebugEnabled()) log4j.debug(" ***************************** AD_Client_ID - " + AD_Client_ID + " -- DateAcct - " + DateAcct + " -- DocumentType - " + DocumentType);
918
setC_Period_ID();
919         boolean open = (!C_Period_ID.equals(""));
920         if (open)
921             if (log4j.isDebugEnabled()) log4j.debug("AcctServer - isPeriodOpen - " + DocumentNo);
922         else
923             log4j.warn("AcctServer - isPeriodOpen NO - " + DocumentNo);
924         return open;
925     } // isPeriodOpen
926

927     /**
928      * Calculate Period ID.
929      * Set to -1 if no period open, 0 if no period control
930      */

931     public void setC_Period_ID(){
932         if (C_Period_ID != null) return;
933         if (log4j.isDebugEnabled()) log4j.debug("AcctServer - setC_Period_ID - AD_Client_ID - " + AD_Client_ID + "--DateAcct - " + DateAcct + "--DocumentType -" + DocumentType);
934         AcctServerData [] data=null;
935         try{
936           if (log4j.isDebugEnabled()) log4j.debug("setC_Period_ID - inside try - AD_Client_ID - " + AD_Client_ID + " -- DateAcct - " + DateAcct + " -- DocumentType - " + DocumentType);
937           data = AcctServerData.periodOpen(this,AD_Client_ID,DocumentType,DateAcct);
938         }catch (ServletException e){
939             log4j.warn(e);
940         }
941         C_Period_ID = data[0].period;
942         if (log4j.isDebugEnabled()) log4j.debug ("AcctServer - setC_Period_ID - "+ AD_Client_ID + "/" + DateAcct + "/" + DocumentType + " => " + C_Period_ID);
943     } // setC_Period_ID
944

945
946     /**
947      * Get fully qualified Account Combination
948      *
949      * @param AD_Client_ID client
950      * @param AD_Org_ID org
951      * @param C_AcctSchema_ID acct schema
952      * @param Account_ID natural account
953      * @param base_ValidCombination_ID optional base combination to be specified
954      * @param Alias aloas
955      * @param AD_User_ID user
956      * @param M_Product_ID product
957      * @param C_BPartner_ID partner
958      * @param AD_OrgTrx_ID trx org
959      * @param C_LocFrom_ID loc from
960      * @param C_LocTo_ID loc to
961      * @param C_SRegion_ID sales region
962      * @param C_Project_ID project
963      * @param C_Campaign_ID campaign
964      * @param C_Activity_ID activity
965      * @param User1_ID user1
966      * @param User2_ID user2
967      * @return C_ValidCombination_ID of existing or new Combination
968      */

969     public static String JavaDoc getValidCombination (String JavaDoc AD_Client_ID, String JavaDoc AD_Org_ID,
970         String JavaDoc C_AcctSchema_ID, String JavaDoc Account_ID, String JavaDoc base_ValidCombination_ID, String JavaDoc Alias, String JavaDoc AD_User_ID,
971         String JavaDoc M_Product_ID, String JavaDoc C_BPartner_ID, String JavaDoc AD_OrgTrx_ID,
972         String JavaDoc C_LocFrom_ID, String JavaDoc C_LocTo_ID, String JavaDoc C_SRegion_ID, String JavaDoc C_Project_ID,
973         String JavaDoc C_Campaign_ID, String JavaDoc C_Activity_ID, String JavaDoc User1_ID, String JavaDoc User2_ID,ConnectionProvider conn){
974         String JavaDoc retValue = "";
975         StringBuffer JavaDoc sb = new StringBuffer JavaDoc ("C_ValidCombination_Get[");
976         sb.append("v,");
977         // -- Mandatory Accounting fields
978
// 2 - AD_Client_ID
979
sb.append("AD_Client_ID=").append(AD_Client_ID).append(",");
980         // 3 - AD_Org_ID
981
sb.append("AD_Org_ID=").append(AD_Org_ID).append(",");
982         // 4- C_AcctSchema_ID
983
sb.append("C_AcctSchema_ID=").append(C_AcctSchema_ID).append(",");
984         // 5 - Account_ID
985
sb.append("Account_ID=").append(Account_ID).append(", ");
986         // -- Optional
987
// 6 - Base C_ValidCombination_ID
988
sb.append("BaseValidCombination_ID=").append(base_ValidCombination_ID).append(",");
989         // 7 - MustBeFullyQualified
990
sb.append("MustBeFullyQualified='Y',");
991         // 8 - Alias
992
sb.append("Alias='").append(Alias).append("',");
993         // 9 - CreatedBy
994
sb.append("AD_User_ID=").append(AD_User_ID).append(", ");
995         // -- Optional Accounting fields
996
// 10 - M_Product_ID
997
sb.append("M_Product_ID=").append(M_Product_ID).append(",");
998         // 11 - C_BPartner_ID
999
sb.append("C_BPartner_ID=").append(C_BPartner_ID).append(",");
1000        // 12 - AD_OrgTrx_ID
1001
sb.append("AD_OrgTrx_ID=").append(AD_OrgTrx_ID).append(",");
1002        // 13 - C_LocFrom_ID
1003
sb.append("C_LocFrom_ID=").append(C_LocFrom_ID).append(",");
1004        // 14 - C_LocTo_ID
1005
sb.append("C_LocTo_ID=").append(C_LocTo_ID).append(", ");
1006        // 15 - C_SalesRegion_ID
1007
sb.append("C_SalesRegion_ID=").append(C_SRegion_ID).append(",");
1008        // 16 - C_Project_ID
1009
sb.append("C_Project_ID=").append(C_Project_ID).append(",");
1010        // 17 - C_Campaign_ID
1011
sb.append("C_Campaign_ID=").append(C_Campaign_ID).append(",");
1012        // 18 - C_Activity_ID
1013
sb.append("C_Activity_ID=").append(C_Activity_ID).append(",");
1014        // 19 - User1_ID
1015
sb.append("User1_ID=").append(User1_ID).append(",");
1016        // 20 - User2_ID
1017
sb.append("User2_ID=").append(User2_ID).append(")");
1018
1019        RespuestaCS_AcctServer data = null;
1020        try{
1021            data = AcctServerData.callGetValidCombination(conn, AD_Client_ID, AD_Org_ID, C_AcctSchema_ID, Account_ID, base_ValidCombination_ID, "Y", Alias, AD_User_ID, M_Product_ID, C_BPartner_ID, AD_OrgTrx_ID, C_LocFrom_ID, C_LocTo_ID, C_SRegion_ID, C_Project_ID, C_Campaign_ID, C_Activity_ID, User1_ID, User2_ID);
1022        }catch(ServletException e){
1023            log4j.warn(e);
1024        }
1025        //
1026
retValue = data.validCombination;
1027        //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - getValidCombination: " + sb.toString());
1028
return retValue;
1029    } // getValidCombination
1030

1031    /**
1032     * Matching
1033     * <pre>
1034     * Derive Invoice-Receipt Match from PO-Invoice and PO-Receipt
1035     * Purchase Order (20)
1036     * - Invoice1 (10)
1037     * - Invoice2 (10)
1038     * - Receipt1 (5)
1039     * - Receipt2 (15)
1040     *
1041     * (a) Creates Directs
1042     * - Invoice1 - Receipt1 (5)
1043     * - Invoice2 - Receipt2 (10)
1044     *
1045     * (b) Creates Indirects
1046     * - Invoice1 - Receipt2 (5)
1047     * (Not imlemented)
1048     *
1049     *
1050     * </pre>
1051     * @return number of records created
1052     */

1053    public int match(VariablesSecureApp vars,ConnectionProvider conn, Connection con){
1054        //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Match--Starting");
1055
int counter = 0;
1056        // (a) Direct Matches
1057
AcctServerData [] data=null;
1058        try{
1059            data= AcctServerData.selectMatch(conn,AD_Client_ID);
1060        }catch(ServletException e){
1061            log4j.warn(e);
1062        }
1063        for (int i = 0;i<data.length;i++){
1064            BigDecimal qty1 = new BigDecimal(data[i].qty1);
1065            BigDecimal qty2 = new BigDecimal(data[i].qty2);
1066            BigDecimal Qty = qty1.min(qty2);
1067            if (Qty.toString().equals("0"))
1068                continue;
1069            //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Match--dateTrx1 :->" + data[i].datetrx1 + "Match--dateTrx2: ->" + data[i].datetrx2);
1070
String JavaDoc dateTrx1 = data[i].datetrx1;
1071            String JavaDoc dateTrx2 = data[i].datetrx2;
1072            String JavaDoc compare = "";
1073            try{
1074                compare = DateTimeData.compare(conn, dateTrx1, dateTrx2);
1075            }catch(ServletException e){
1076                log4j.warn(e);
1077            }
1078            String JavaDoc DateTrx = dateTrx1;
1079            if (compare.equals("-1"))
1080                DateTrx = dateTrx2;
1081            //
1082
String JavaDoc strQty = Qty.toString();
1083            String JavaDoc strDateTrx = DateTrx;
1084            String JavaDoc AD_Client_ID = data[i].adClientId;
1085            String JavaDoc AD_Org_ID = data[i].adOrgId;
1086            String JavaDoc C_InvoiceLine_ID = data[i].cInvoicelineId;
1087            String JavaDoc M_InOutLine_ID = data[i].mInoutlineId;
1088            String JavaDoc M_Product_ID = data[i].mProductId;
1089            //
1090
if (createMatchInv(AD_Client_ID, AD_Org_ID,M_InOutLine_ID, C_InvoiceLine_ID,M_Product_ID, strDateTrx, strQty, vars, conn,con)==1)
1091                counter++;
1092        }
1093        //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - Matcher.match - Client_ID=" + AD_Client_ID + ", Records created=" + counter);
1094
return counter;
1095    } // match
1096

1097    /**
1098     * Create MatchInv record
1099     * @param AD_Client_ID Client
1100     * @param AD_Org_ID Org
1101     * @param M_InOutLine_ID Receipt
1102     * @param C_InvoiceLine_ID Invoice
1103     * @param M_Product_ID Product
1104     * @param DateTrx Date
1105     * @param Qty Qty
1106     * @return true if record created
1107     */

1108    private int createMatchInv (String JavaDoc AD_Client_ID, String JavaDoc AD_Org_ID,String JavaDoc M_InOutLine_ID, String JavaDoc C_InvoiceLine_ID,String JavaDoc
1109    M_Product_ID, String JavaDoc DateTrx, String JavaDoc Qty,VariablesSecureApp vars,ConnectionProvider conn, Connection con){
1110        //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - createMatchInv - InvLine=" + C_InvoiceLine_ID + ",Rec=" + M_InOutLine_ID + ", Qty=" + Qty + ", " + DateTrx);
1111
int no = 0;
1112        try{
1113            String JavaDoc M_MatchInv_ID = SequenceIdData.getSequence(conn, "M_MatchInv", vars.getClient());
1114            //
1115
no = AcctServerData.insertMatchInv(con,conn, M_MatchInv_ID, AD_Client_ID, AD_Org_ID, M_InOutLine_ID, C_InvoiceLine_ID, M_Product_ID, DateTrx, Qty);
1116        }catch(ServletException e){
1117            log4j.warn(e);
1118        }
1119        return no;
1120    } // createMatchInv
1121

1122    /**
1123     * Get the account for Accounting Schema
1124     * @param AcctType see ACCTTYPE_*
1125     * @param as accounting schema
1126     * @return Account
1127     */

1128    public final Account getAccount (String JavaDoc AcctType, AcctSchema as,ConnectionProvider conn){
1129        BigDecimal AMT = null;
1130        BigDecimal ZERO = new BigDecimal("0");
1131        AcctServerData [] data=null;
1132        //if (log4j.isDebugEnabled()) log4j.debug("*******************************getAccount 1: AcctType:-->" + AcctType);
1133
try{
1134            /** Account Type - Invoice */
1135            if (AcctType.equals(ACCTTYPE_Charge)){ // see getChargeAccount in DocLine
1136
//if (log4j.isDebugEnabled()) log4j.debug("AcctServer - *******************amount(AMT);-->" + getAmount(AMTTYPE_Charge));
1137
AMT = new BigDecimal(getAmount(AMTTYPE_Charge));
1138                //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - *******************AMT;-->" + AMT);
1139
int cmp = AMT.compareTo(ZERO);
1140                //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - ******************* CMP: " + cmp);
1141
if (cmp == 0)
1142                    return null;
1143                else if (cmp < 0)
1144                    data = AcctServerData.selectExpenseAcct(conn, C_Charge_ID, as.getC_AcctSchema_ID());
1145                else
1146                    data = AcctServerData.selectRevenueAcct(conn, C_Charge_ID, as.getC_AcctSchema_ID());
1147                //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - *******************************getAccount 2");
1148
}else if (AcctType.equals(ACCTTYPE_V_Liability)){
1149                data = AcctServerData.selectLiabilityAcct(conn, C_BPartner_ID, as.getC_AcctSchema_ID());
1150            }else if (AcctType.equals(ACCTTYPE_V_Liability_Services)){
1151                data = AcctServerData.selectLiabilityServicesAcct(conn, C_BPartner_ID, as.getC_AcctSchema_ID());
1152            }else if (AcctType.equals(ACCTTYPE_C_Receivable)){
1153                data = AcctServerData.selectReceivableAcct(conn, C_BPartner_ID, as.getC_AcctSchema_ID());
1154            }else if (AcctType.equals(ACCTTYPE_UnallocatedCash)){/** Account Type - Payment */
1155                data = AcctServerData.selectUnallocatedCashAcct(conn, C_BankAccount_ID, as.getC_AcctSchema_ID());
1156            }else if (AcctType.equals(ACCTTYPE_BankInTransit)){
1157                data = AcctServerData.selectInTransitAcct(conn, C_BankAccount_ID, as.getC_AcctSchema_ID());
1158            }else if (AcctType.equals(ACCTTYPE_BankInTransitDefault)){
1159                data = AcctServerData.selectInTransitDefaultAcct(conn, as.getC_AcctSchema_ID());
1160            }else if (AcctType.equals(ACCTTYPE_ConvertChargeDefaultAmt)){
1161                data = AcctServerData.selectConvertChargeDefaultAmtAcct(conn, as.getC_AcctSchema_ID());
1162            }else if (AcctType.equals(ACCTTYPE_ConvertGainDefaultAmt)){
1163                data = AcctServerData.selectConvertGainDefaultAmtAcct(conn, as.getC_AcctSchema_ID());
1164            }else if (AcctType.equals(ACCTTYPE_PaymentSelect)){
1165                data = AcctServerData.selectPaymentSelectAcct(conn, C_BankAccount_ID, as.getC_AcctSchema_ID());
1166            }else if (AcctType.equals(ACCTTYPE_WriteOffDefault)){
1167                data = AcctServerData.selectWriteOffDefault(conn, as.getC_AcctSchema_ID());
1168            }else if (AcctType.equals(ACCTTYPE_DiscountExp)){/** Account Type - Allocation */
1169                data = AcctServerData.selectDiscountExpAcct(conn, C_BPartner_ID, as.getC_AcctSchema_ID());
1170            }else if (AcctType.equals(ACCTTYPE_DiscountRev)){
1171                data = AcctServerData.selectDiscountRevAcct(conn, C_BPartner_ID, as.getC_AcctSchema_ID());
1172            }else if (AcctType.equals(ACCTTYPE_WriteOff)){
1173                data = AcctServerData.selectWriteOffAcct(conn, C_BPartner_ID, as.getC_AcctSchema_ID());
1174            }else if (AcctType.equals(ACCTTYPE_ConvertChargeLossAmt)){/** Account Type - Bank Statement */
1175                data = AcctServerData.selectConvertChargeLossAmt(conn, C_BankAccount_ID, as.getC_AcctSchema_ID());
1176            }else if (AcctType.equals(ACCTTYPE_ConvertChargeGainAmt)){
1177                data = AcctServerData.selectConvertChargeGainAmt(conn, C_BankAccount_ID, as.getC_AcctSchema_ID());
1178            }else if (AcctType.equals(ACCTTYPE_BankAsset)){
1179                data = AcctServerData.selectAssetAcct(conn, C_BankAccount_ID, as.getC_AcctSchema_ID());
1180            }else if (AcctType.equals(ACCTTYPE_InterestRev)){
1181                data = AcctServerData.selectInterestRevAcct(conn, C_BankAccount_ID, as.getC_AcctSchema_ID());
1182            }else if (AcctType.equals(ACCTTYPE_InterestExp)){
1183                data = AcctServerData.selectInterestExpAcct(conn, C_BankAccount_ID, as.getC_AcctSchema_ID());
1184            }else if (AcctType.equals(ACCTTYPE_CashAsset)){/** Account Type - Cash */
1185                data = AcctServerData.selectCBAssetAcct(conn, C_CashBook_ID, as.getC_AcctSchema_ID());
1186            }else if (AcctType.equals(ACCTTYPE_CashTransfer)){
1187                data = AcctServerData.selectCashTransferAcct(conn, C_CashBook_ID, as.getC_AcctSchema_ID());
1188            }else if (AcctType.equals(ACCTTYPE_CashExpense)){
1189                data = AcctServerData.selectCBExpenseAcct(conn, C_CashBook_ID, as.getC_AcctSchema_ID());
1190            }else if (AcctType.equals(ACCTTYPE_CashReceipt)){
1191                data = AcctServerData.selectCBReceiptAcct(conn, C_CashBook_ID, as.getC_AcctSchema_ID());
1192            }else if (AcctType.equals(ACCTTYPE_CashDifference)){
1193                data = AcctServerData.selectCBDifferencesAcct(conn, C_CashBook_ID, as.getC_AcctSchema_ID());
1194            }else if (AcctType.equals(ACCTTYPE_InvDifferences)){/** Inventory Accounts */
1195                data = AcctServerData.selectWDifferencesAcct(conn, M_Warehouse_ID, as.getC_AcctSchema_ID());
1196            }else if (AcctType.equals(ACCTTYPE_NotInvoicedReceipts)){
1197                if (log4j.isDebugEnabled()) log4j.debug("AcctServer - getAccount - ACCTYPE_NotInvoicedReceipts - C_BPartner_ID - " + C_BPartner_ID);
1198                data = AcctServerData.selectNotInvoicedReceiptsAcct(conn, C_BPartner_ID, as.getC_AcctSchema_ID());
1199            }else if (AcctType.equals(ACCTTYPE_ProjectAsset)){/** Project Accounts */
1200                data = AcctServerData.selectPJAssetAcct(conn, C_Project_ID, as.getC_AcctSchema_ID());
1201            }else if (AcctType.equals(ACCTTYPE_ProjectWIP)){
1202                data = AcctServerData.selectPJWIPAcct(conn, C_Project_ID, as.getC_AcctSchema_ID());
1203            }else if (AcctType.equals(ACCTTYPE_PPVOffset)){/** GL Accounts */
1204                data = AcctServerData.selectPPVOffsetAcct(conn, as.getC_AcctSchema_ID());
1205            }else{
1206                log4j.warn("AcctServer - getAccount - Not found AcctType=" + AcctType);
1207                return null;
1208            }
1209        //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - *******************************getAccount 3");
1210
}catch(ServletException e){
1211            log4j.warn(e);
1212        }
1213        // Get Acct
1214
String JavaDoc Account_ID = "";
1215        if (data != null && data.length!=0){
1216            Account_ID = data[0].accountId;
1217        }else return null;
1218        // No account
1219
if (Account_ID.equals("")){
1220            log4j.warn("AcctServer - getAccount - NO account Type="
1221                + AcctType + ", Record=" + Record_ID);
1222            return null;
1223        }
1224        //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - *******************************getAccount 4");
1225
// Return Account
1226
Account acct = null;
1227        try{
1228            acct = Account.getAccount(conn, Account_ID);
1229        }catch(ServletException e){
1230            log4j.warn(e);
1231        }
1232        return acct;
1233    } // getAccount
1234

1235    public FieldProvider [] getObjectFieldProvider(){
1236        return objectFieldProvider;
1237    }
1238
1239    public void setObjectFieldProvider(FieldProvider [] fieldProvider){
1240        objectFieldProvider = fieldProvider;
1241    }
1242
1243    public abstract void loadObjectFieldProvider(ConnectionProvider conn, String JavaDoc AD_Client_ID, String JavaDoc Id) throws ServletException;
1244
1245    public abstract boolean loadDocumentDetails(FieldProvider[] data,ConnectionProvider conn);
1246    /**
1247     * Get Source Currency Balance - subtracts line (and tax) amounts from total - no rounding
1248     * @return positive amount, if total header is bigger than lines
1249     */

1250    public abstract BigDecimal getBalance();
1251
1252    /**
1253     * Create Facts (the accounting logic)
1254     * @param as accounting schema
1255     * @return Fact
1256     */

1257    public abstract Fact createFact (AcctSchema as,ConnectionProvider conn,Connection con,VariablesSecureApp vars) throws ServletException;
1258
1259    public abstract boolean getDocumentConfirmation(ConnectionProvider conn, String JavaDoc strRecordId);
1260
1261    public String JavaDoc getInfo(VariablesSecureApp vars) {
1262      return(Utility.messageBD(this, "Created", vars.getLanguage()) + "=" + success /*+ ", " + Utility.messageBD(this, "Errors", vars.getLanguage()) + "=" + errors*/);
1263    } // end of getInfo() method
1264

1265    public boolean checkDocuments() throws ServletException{
1266      if(m_as.length==0) return false;
1267      AcctServerData [] docTypes = AcctServerData.selectDocTypes(this, AD_Table_ID, AD_Client_ID);
1268      //if (log4j.isDebugEnabled()) log4j.debug("AcctServer - AcctSchema length-" + (this.m_as).length);
1269
for (int i=0;i<docTypes.length;i++){
1270          AcctServerData [] data = AcctServerData.selectDocuments(this, tableName, docTypes[i].name, strDateColumn);
1271          if (log4j.isDebugEnabled()) log4j.debug("AcctServer - not posted "+docTypes[i].name+" documets length-" + data.length);
1272           if(data!=null && data.length>0) {
1273            if (!data[0].id.equals("")) return true;
1274          }
1275      }
1276      return false;
1277    } // end of checkDocuments() method
1278

1279    public String JavaDoc getServletInfo() {
1280    return "Servlet for the accounting";
1281  } // end of getServletInfo() method
1282
}
1283
Popular Tags