KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > compiere > model > CalloutSystem


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

14 package org.compiere.model;
15
16 import java.math.BigDecimal JavaDoc;
17 import java.sql.PreparedStatement JavaDoc;
18 import java.sql.ResultSet JavaDoc;
19 import java.sql.SQLException JavaDoc;
20 import java.sql.Timestamp JavaDoc;
21 import java.util.Properties JavaDoc;
22
23 import org.compiere.util.*;
24
25 /**
26  * Callout's are used for cross field validation and setting values in other fields
27  * when returning a non empty (error message) string, an exception is raised.
28  *
29  * When invoked, the grid controller has the new value!
30  *
31  * @author Jorg Janke
32  * @version $Id: CalloutSystem.java,v 1.54 2003/10/17 06:15:20 jjanke Exp $
33  */

34 public final class CalloutSystem extends CalloutEngine
35 {
36     /**
37      * Conversion Rate - set Multiply Rate from Divide Rate and vice versa
38      *
39      * @param ctx context
40      * @param WindowNo window
41      * @param mTab tab
42      * @param mField field
43      * @param value value
44      * @return error message
45      */

46     public String JavaDoc Conversion_Rate (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
47     {
48         if (isCalloutActive() || value == null) // assuming it is Conversion_Rate
49
return "";
50         setCalloutActive(true);
51
52         BigDecimal JavaDoc rate1 = (BigDecimal JavaDoc)value;
53         BigDecimal JavaDoc rate2 = Env.ZERO;
54         BigDecimal JavaDoc one = new BigDecimal JavaDoc(1.0);
55
56         if (rate1.doubleValue() != 0.0) // no divide by zero
57
rate2 = one.divide(rate1, 12, BigDecimal.ROUND_HALF_UP);
58         //
59
if (mField.getColumnName().equals("MultiplyRate"))
60             mTab.setValue("DivideRate", rate2);
61         else
62             mTab.setValue("MultiplyRate", rate2);
63         log.info(mField.getColumnName() + "=" + rate1 + " => " + rate2);
64         setCalloutActive(false);
65         return "";
66     } // Conversion_Rate
67

68     /*************************************************************************/
69
70     /**
71      * InOut - DocType.
72      * - sets MovementType
73      * - gets DocNo
74      */

75     public String JavaDoc InOut_DocType (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
76     {
77         Integer JavaDoc C_DocType_ID = (Integer JavaDoc)value;
78         if (C_DocType_ID == null || C_DocType_ID.intValue() == 0)
79             return "";
80
81         try
82         {
83             Env.setContext(ctx, WindowNo, "C_DocTypeTarget_ID", C_DocType_ID.intValue());
84
85             String JavaDoc SQL = "SELECT d.DocBaseType, d.IsDocNoControlled, s.CurrentNext "
86                 + "FROM C_DocType d, AD_Sequence s "
87                 + "WHERE C_DocType_ID=?" // 1
88
+ " AND d.DocNoSequence_ID=s.AD_Sequence_ID(+)";
89
90             PreparedStatement JavaDoc pstmt = DB.prepareStatement(SQL);
91             pstmt.setInt(1, C_DocType_ID.intValue());
92             ResultSet JavaDoc rs = pstmt.executeQuery();
93             if (rs.next())
94             {
95                 // Set Movement Type
96
String JavaDoc DocBaseType = rs.getString("DocBaseType");
97                 if (DocBaseType.equals("MMS")) // Material Shipments
98
mTab.setValue("MovementType", "C-"); // Customer Shipments
99
else if (DocBaseType.equals("MMR")) // Material Receipts
100
mTab.setValue("MovementType", "V+"); // Vendor Receipts
101

102                 // DocumentNo
103
if (rs.getString("IsDocNoControlled").equals("Y"))
104                     mTab.setValue("DocumentNo", "<" + rs.getString("CurrentNext") + ">");
105             }
106             rs.close();
107             pstmt.close();
108         }
109         catch (SQLException JavaDoc e)
110         {
111             log.error("InOut_DocType", e);
112             return e.getLocalizedMessage();
113         }
114         return "";
115     } // InOut_DocType
116

117
118     /**
119      * M_InOut - Defaults for BPartner.
120      * - Location
121      * - Contact
122      */

123     public String JavaDoc InOut_BPartner (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
124     {
125         Integer JavaDoc C_BPartner_ID = (Integer JavaDoc)value;
126         if (C_BPartner_ID == null || C_BPartner_ID.intValue() == 0)
127             return "";
128
129         String JavaDoc SQL = "SELECT p.AD_Language,p.C_PaymentTerm_ID,"
130             + "p.M_PriceList_ID,p.PaymentRule,p.POReference,"
131             + "p.SO_Description,p.IsDiscountPrinted,"
132             + "p.SO_CreditLimit-p.SO_CreditUsed AS CreditAvailable,"
133             + "l.C_BPartner_Location_ID,c.AD_User_ID "
134             + "FROM C_BPartner p, C_BPartner_Location l, AD_User c "
135             + "WHERE p.C_BPartner_ID=l.C_BPartner_ID(+)"
136             + " AND p.C_BPartner_ID=c.C_BPartner_ID(+)"
137             + " AND p.C_BPartner_ID=?"; // 1
138

139         try
140         {
141             PreparedStatement JavaDoc pstmt = DB.prepareStatement(SQL);
142             pstmt.setInt(1, C_BPartner_ID.intValue());
143             ResultSet JavaDoc rs = pstmt.executeQuery();
144             BigDecimal JavaDoc bd;
145             if (rs.next())
146             {
147                 // Location
148
Integer JavaDoc ii = new Integer JavaDoc(rs.getInt("C_BPartner_Location_ID"));
149                 if (rs.wasNull())
150                     mTab.setValue("C_BPartner_Location_ID", null);
151                 else
152                     mTab.setValue("C_BPartner_Location_ID", ii);
153                 // Contact
154
ii = new Integer JavaDoc(rs.getInt("AD_User_ID"));
155                 if (rs.wasNull())
156                     mTab.setValue("AD_User_ID", null);
157                 else
158                     mTab.setValue("AD_User_ID", ii);
159
160                 // CreditAvailable
161
double CreditAvailable = rs.getDouble("CreditAvailable");
162                 if (!rs.wasNull() && CreditAvailable < 0)
163                     mTab.fireDataStatusEEvent("CreditLimitOver",
164                         DisplayType.getNumberFormat(DisplayType.Amount).format(CreditAvailable));
165             }
166             rs.close();
167             pstmt.close();
168         }
169         catch (SQLException JavaDoc e)
170         {
171             log.error("InOut_BPartner", e);
172             return e.getLocalizedMessage();
173         }
174
175         return "";
176     } // InOut_BPartner
177

178     /**
179      * M_InOutLine - Default Locator for Product.
180      */

181     public String JavaDoc InOutLine_Product (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
182     {
183         Integer JavaDoc M_Product_ID = (Integer JavaDoc)value;
184         if (M_Product_ID == null || M_Product_ID.intValue() == 0)
185             return "";
186         // Set Attribute
187
if (Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_Product_ID") == M_Product_ID.intValue()
188             && Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID") != 0)
189             mTab.setValue("M_AttributeSetInstance_ID", new Integer JavaDoc(Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID")));
190         else
191             mTab.setValue("M_AttributeSetInstance_ID", null);
192
193         int M_Warehouse_ID = Env.getContextAsInt(ctx, WindowNo, "M_Warehouse_ID");
194         boolean IsSOTrx = "Y".equals(Env.getContext(ctx, WindowNo, "IsSOTrx"));
195         if (IsSOTrx)
196             return "";
197
198         String JavaDoc SQL = "SELECT p.M_Locator_ID "
199             + "FROM M_Product p INNER JOIN M_Locator l ON (p.M_Locator_ID=l.M_Locator_ID) "
200             + "WHERE p.IsActive='Y' AND l.IsActive='Y'"
201             + " AND p.M_Product_ID=? AND l.M_Warehouse_ID=?"; // #1/2
202
int M_Locator_ID = 0;
203         try
204         {
205             PreparedStatement JavaDoc pstmt = DB.prepareStatement(SQL);
206             pstmt.setInt(1, M_Product_ID.intValue());
207             pstmt.setInt(2, M_Warehouse_ID);
208             ResultSet JavaDoc rs = pstmt.executeQuery();
209             if (rs.next())
210             {
211                 M_Locator_ID = rs.getInt(1);
212                 if (M_Locator_ID != 0)
213                     mTab.setValue("M_Locator_ID", new Integer JavaDoc (M_Locator_ID));
214             }
215             rs.close();
216             pstmt.close();
217         }
218         catch (SQLException JavaDoc e)
219         {
220             log.error("InOutLine_Product", e);
221             return e.getLocalizedMessage();
222         }
223         if (M_Locator_ID == 0)
224             log.debug("InOutLine_Product - No Locator for M_Product_ID=" + M_Product_ID + " and M_Warehouse_ID=" + M_Warehouse_ID);
225         return "";
226     } // InOutLine_Product
227

228     /*************************************************************************/
229
230     /**
231      * BankStmt - Amount.
232      * Calculate ChargeAmt = StmtAmt - TrxAmt - InterestAmt
233      * or id Charge is entered - InterestAmt = StmtAmt - TrxAmt - ChargeAmt
234      */

235     public String JavaDoc BankStmt_Amount (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
236     {
237         if (isCalloutActive())
238             return "";
239         setCalloutActive(true);
240
241         // Get Stmt & Trx
242
BigDecimal JavaDoc stmt = (BigDecimal JavaDoc)mTab.getValue("StmtAmt");
243         if (stmt == null)
244             stmt = Env.ZERO;
245         BigDecimal JavaDoc trx = (BigDecimal JavaDoc)mTab.getValue("TrxAmt");
246         if (trx == null)
247             trx = Env.ZERO;
248         BigDecimal JavaDoc bd = stmt.subtract(trx);
249
250         // Charge - calculate Interest
251
if (mField.getColumnName().equals("ChargeAmt"))
252         {
253             BigDecimal JavaDoc charge = (BigDecimal JavaDoc)value;
254             if (charge == null)
255                 charge = Env.ZERO;
256             bd = bd.subtract(charge);
257         // log.trace(log.l5_DData, "Interest (" + bd + ") = Stmt(" + stmt + ") - Trx(" + trx + ") - Charge(" + charge + ")");
258
mTab.setValue("InterestAmt", bd);
259         }
260         // Calculate Charge
261
else
262         {
263             BigDecimal JavaDoc interest = (BigDecimal JavaDoc)mTab.getValue("InterestAmt");
264             if (interest == null)
265                 interest = Env.ZERO;
266             bd = bd.subtract(interest);
267         // log.trace(log.l5_DData, "Charge (" + bd + ") = Stmt(" + stmt + ") - Trx(" + trx + ") - Interest(" + interest + ")");
268
mTab.setValue("ChargeAmt", bd);
269         }
270         setCalloutActive(false);
271         return "";
272     } // BankStmt_Amount
273

274
275     /**
276      * BankStmt - Payment.
277      * Update Transaction Amount when payment is selected
278      */

279     public String JavaDoc BankStmt_Payment (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
280     {
281         Integer JavaDoc C_Payment_ID = (Integer JavaDoc)value;
282         if (C_Payment_ID == null || C_Payment_ID.intValue() == 0)
283             return "";
284
285         String JavaDoc sql = "SELECT PayAmt FROM C_Payment_v WHERE C_Payment_ID=?"; // 1
286
try
287         {
288             PreparedStatement JavaDoc pstmt = DB.prepareStatement(sql);
289             pstmt.setInt(1, C_Payment_ID.intValue());
290             ResultSet JavaDoc rs = pstmt.executeQuery();
291             if (rs.next())
292             {
293                 BigDecimal JavaDoc bd = rs.getBigDecimal(1);
294                 mTab.setValue("TrxAmt", bd);
295             }
296             rs.close();
297             pstmt.close();
298         }
299         catch (SQLException JavaDoc e)
300         {
301             log.error("BankStmt_Payment", e);
302             return e.getLocalizedMessage();
303         }
304         // Recalculate Amounts
305
BankStmt_Amount (ctx, WindowNo, mTab, mField, value);
306         return "";
307     } // BankStmt_Payment
308

309     /*************************************************************************/
310
311     /**
312      * Payment_Invoice.
313      * when Invoice selected
314      * - set C_Currency_ID
315      * - InvCurrency_ID/InvTotalAmt (Env),
316      * - C_BPartner_ID
317      * - DiscountAmt = C_Invoice_Discount (ID, DateTrx)
318      * - InvTotalAmt - C_Invoice_Open (ID)
319      * - PayAmt = InvTotalAmt - Discount
320      * - WriteOffAmt = 0
321      */

322     public String JavaDoc Payment_Invoice (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
323     {
324         if (isCalloutActive()) // assuming it is resetting value
325
return "";
326         setCalloutActive(true);
327
328         Integer JavaDoc C_Invoice_ID = (Integer JavaDoc)value;
329         if (C_Invoice_ID == null || C_Invoice_ID.intValue() == 0)
330         {
331             Env.setContext(ctx, WindowNo, "InvCurrency_ID", null);
332             Env.setContext(ctx, WindowNo, "InvTotalAmt", null);
333             setCalloutActive(false);
334             return "";
335         }
336
337         // Date
338
Timestamp JavaDoc ts = (Timestamp JavaDoc)mTab.getValue("DateTrx");
339         if (ts == null)
340             ts = new Timestamp JavaDoc(System.currentTimeMillis());
341         boolean isSOTrx = true;
342         //
343
String JavaDoc sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2
344
+ " C_Invoice_Open(C_Invoice_ID)," // 3
345
+ " C_Invoice_Discount(C_Invoice_ID,?), IsSOTrx " // 4..5
346
+ "FROM C_Invoice WHERE C_Invoice_ID=?";
347         try
348         {
349             PreparedStatement JavaDoc pstmt = DB.prepareStatement(sql);
350             pstmt.setTimestamp(1, ts);
351             pstmt.setInt(2, C_Invoice_ID.intValue());
352             ResultSet JavaDoc rs = pstmt.executeQuery();
353             if (rs.next())
354             {
355                 mTab.setValue("C_BPartner_ID", new Integer JavaDoc(rs.getInt(1)));
356                 int C_Currency_ID = rs.getInt(2);
357                 mTab.setValue("C_Currency_ID", new Integer JavaDoc(C_Currency_ID));
358                 Env.setContext(ctx, WindowNo, "InvCurrency_ID", C_Currency_ID);
359                 //
360
BigDecimal JavaDoc InvoiceOpen = rs.getBigDecimal(3);
361                 if (InvoiceOpen == null)
362                     InvoiceOpen = Env.ZERO;
363                 Env.setContext(ctx, WindowNo, "InvTotalAmt", InvoiceOpen.toString());
364                 BigDecimal JavaDoc DiscountAmt = rs.getBigDecimal(4);
365                 if (DiscountAmt == null)
366                     DiscountAmt = Env.ZERO;
367                 mTab.setValue("PayAmt", InvoiceOpen.subtract(DiscountAmt));
368                 mTab.setValue("DiscountAmt", DiscountAmt);
369                 mTab.setValue("WriteOffAmt", Env.ZERO);
370                 // reset as dependent fields get reset
371
Env.setContext(ctx, WindowNo, "C_Invoice_ID", C_Invoice_ID.toString());
372                 mTab.setValue("C_Invoice_ID", C_Invoice_ID);
373                 isSOTrx = "Y".equals(rs.getString(5));
374             }
375             rs.close();
376             pstmt.close();
377         }
378         catch (SQLException JavaDoc e)
379         {
380             log.error("Payment_Invoice", e);
381             setCalloutActive(false);
382             return e.getLocalizedMessage();
383         }
384
385         setCalloutActive(false);
386         return Payment_DocType(ctx, WindowNo, mTab, mField, value);
387     } // Payment_Invoice
388

389
390     /**
391      * Payment_Document Type.
392      * Verify that Document Type (AP/AR) and Invoice (SO/PO) are in sync
393      */

394     public String JavaDoc Payment_DocType (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
395     {
396         int C_Invoice_ID = Env.getContextAsInt(ctx, WindowNo, "C_Invoice_ID");
397         int C_DocType_ID = Env.getContextAsInt(ctx, WindowNo, "C_DocType_ID");
398     // if (mField.getColumnName().equals("C_DocType_ID"))
399
// {
400
// }
401
log.debug("Payment_DocType - C_Invoice_ID=" + C_Invoice_ID + ", C_DocType_ID=" + C_DocType_ID);
402         if (C_Invoice_ID == 0 || C_DocType_ID == 0)
403             return "";
404
405         String JavaDoc sql = "SELECT CASE WHEN (i.IsSOTrx='Y' AND dt.DocBaseType='ARR')"
406             + " OR (i.IsSOTrx='N' AND dt.DocBaseType='APP') THEN 'Y'"
407             + " ELSE 'N' END CASE "
408             + "FROM C_Invoice i, C_DocType dt "
409             + "WHERE i.C_Invoice_ID=? AND dt.C_DocType_ID=?";
410         String JavaDoc result = null;
411         PreparedStatement JavaDoc pstmt = null;
412         try
413         {
414             pstmt = DB.prepareStatement(sql);
415             pstmt.setInt(1, C_Invoice_ID);
416             pstmt.setInt(2, C_DocType_ID);
417             ResultSet JavaDoc rs = pstmt.executeQuery();
418             if (rs.next())
419                 result = rs.getString(1);
420             rs.close();
421             pstmt.close();
422             pstmt = null;
423         }
424         catch (Exception JavaDoc e)
425         {
426             log.error("Payment_DocType", e);
427         }
428         finally
429         {
430             try
431             {
432                 if (pstmt != null)
433                     pstmt.close ();
434             }
435             catch (Exception JavaDoc e)
436             {}
437             pstmt = null;
438         }
439
440         if ("N".equals(result))
441             return "PaymentDocTypeInvoiceInconsistent";
442
443         return "";
444     } // Payment_DocType
445

446
447     /**
448      * Payment_No_Verify.
449      * - Verify Credit Card No
450      */

451     public String JavaDoc Payment_No_Verify (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
452     {
453         String JavaDoc colName = mField.getColumnName();
454
455         // CC
456
if (colName.equals("CreditCardNumber"))
457         {
458             String JavaDoc cc = (String JavaDoc)value;
459             if (cc == null || cc.length() == 0)
460                 return "";
461             return MPayment.validateCreditCardNumber(cc);
462         }
463         if (colName.equals("RoutingNo"))
464         {
465             String JavaDoc rt = (String JavaDoc)value;
466             if (rt == null || rt.length() == 0)
467                 return "";
468             return MPayment.validateRoutingNo(rt);
469         }
470
471         log.warn("No Verification available");
472         return "";
473     } // Payment_CCNo_Verify
474

475
476     /**
477      * Payment_Amounts.
478      * when C_Currency_ID, DiscountAnt, PayAmt, WriteOffAmt, OverUnderAmt, IsOverUnderPayment change
479      * making sure that add up to InvTotalAmt in InvCurrency_ID (created by Payment_Invoice)
480      */

481     public String JavaDoc Payment_Amounts (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value, Object JavaDoc oldValue)
482     {
483         if (isCalloutActive()) // assuming it is resetting value
484
return "";
485         // New Payment
486
if (Env.getContextAsInt(ctx, WindowNo, "C_Payment_ID") == 0
487             && Env.getContextAsInt(ctx, WindowNo, "C_BPartner_ID") == 0
488             && Env.getContextAsInt(ctx, WindowNo, "C_Invoice_ID") == 0)
489             return "";
490         setCalloutActive(true);
491
492         // Check, if InvTotalAmt/InvCurrency_ID exists
493
String JavaDoc total = Env.getContext(ctx, WindowNo, "InvTotalAmt");
494         if (total == null || total.length() == 0)
495         {
496             setCalloutActive(false);
497             return "InvoiceReSelect";
498         }
499         BigDecimal JavaDoc InvTotalAmt = new BigDecimal JavaDoc(total);
500         int InvCurrency_ID = Env.getContextAsInt (ctx, WindowNo, "InvCurrency_ID");
501         //
502
String JavaDoc colName = mField.getColumnName();
503         if (colName.equals("IsOverUnderPayment")) // Set Over/Under Amt to Zero
504
{
505             mTab.setValue("OverUnderAmt", Env.ZERO);
506             setCalloutActive(false);
507             return "";
508         }
509         //
510
BigDecimal JavaDoc PayAmt = (BigDecimal JavaDoc)mTab.getValue("PayAmt");
511         BigDecimal JavaDoc DiscountAmt = (BigDecimal JavaDoc)mTab.getValue("DiscountAmt");
512         BigDecimal JavaDoc WriteOffAmt = (BigDecimal JavaDoc)mTab.getValue("WriteOffAmt");
513         BigDecimal JavaDoc OverUnderAmt = (BigDecimal JavaDoc)mTab.getValue("OverUnderAmt");
514         int C_Currency_ID = ((Integer JavaDoc)mTab.getValue("C_Currency_ID")).intValue();
515         Timestamp JavaDoc ConvDate = (Timestamp JavaDoc)mTab.getValue("DateTrx");
516         log.debug("Invoice=" + InvTotalAmt + " in Currency=" + InvCurrency_ID
517             + " - Pay=" + PayAmt + ", Discount=" + DiscountAmt
518             + ", WriteOff=" + WriteOffAmt + ", OverUnderAmt=" + OverUnderAmt
519             + " in Currency=" + C_Currency_ID + " on " + ConvDate);
520         int AD_Client_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Client_ID");
521         int AD_Org_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Org_ID");
522
523         // Currency Changed - convert all
524
if (colName.equals("C_Currency_ID"))
525         {
526             int oldCur = ((Integer JavaDoc)oldValue).intValue();
527             log.debug("FromCurrency=" + oldCur + ", ToCurrency=" + C_Currency_ID + ", Date=" + ConvDate);
528             BigDecimal JavaDoc CurrencyRate = DB.getConvesionRate(oldCur, C_Currency_ID, ConvDate, null, AD_Client_ID, AD_Org_ID);
529             log.debug("Rate=" + CurrencyRate);
530             if (CurrencyRate == null || CurrencyRate.compareTo(Env.ZERO) == 0)
531             {
532                 mTab.setValue("C_Currency_ID", new Integer JavaDoc(InvCurrency_ID));
533                 setCalloutActive(false);
534                 return "NoCurrencyConversion";
535             }
536             PayAmt = PayAmt.multiply(CurrencyRate).setScale(2, BigDecimal.ROUND_HALF_UP);
537             mTab.setValue("PayAmt", PayAmt);
538             DiscountAmt = DiscountAmt.multiply(CurrencyRate).setScale(2, BigDecimal.ROUND_HALF_UP);
539             mTab.setValue("DiscountAmt", DiscountAmt);
540             WriteOffAmt = WriteOffAmt.multiply(CurrencyRate).setScale(2, BigDecimal.ROUND_HALF_UP);
541             mTab.setValue("WriteOffAmt", WriteOffAmt);
542             OverUnderAmt = OverUnderAmt.multiply(CurrencyRate).setScale(2, BigDecimal.ROUND_HALF_UP);
543             mTab.setValue("OverUnderAmt", OverUnderAmt);
544         }
545         if (C_Currency_ID != InvCurrency_ID)
546         {
547             InvTotalAmt = DB.getConvertedAmt(InvTotalAmt, InvCurrency_ID, C_Currency_ID, ConvDate, null, AD_Client_ID, AD_Org_ID);
548             if (InvTotalAmt == null || InvTotalAmt.compareTo(Env.ZERO) == 0)
549             {
550                 mTab.setValue("C_Currency_ID", new Integer JavaDoc(InvCurrency_ID));
551                 setCalloutActive(false);
552                 return "NoCurrencyConversion";
553             }
554             log.debug("Converted InvTotalAmt=" + InvTotalAmt.toString());
555         }
556
557         // PayAmt - calculate write off
558
if (colName.equals("PayAmt"))
559         {
560             WriteOffAmt = InvTotalAmt.subtract(PayAmt).subtract(DiscountAmt).subtract(OverUnderAmt);
561             mTab.setValue("WriteOffAmt", WriteOffAmt);
562         }
563         else // calculate PayAmt
564
{
565             PayAmt = InvTotalAmt.subtract(DiscountAmt).subtract(WriteOffAmt).subtract(OverUnderAmt);
566             mTab.setValue("PayAmt", PayAmt);
567         }
568
569         setCalloutActive(false);
570         return "";
571     } // Payment_Amounts
572

573     /*************************************************************************/
574
575     /**
576      * Cash Journal Line Invoice.
577      * when Invoice selected
578      * - set C_Currency, DiscountAnt, Amount, WriteOffAmt
579      */

580     public String JavaDoc CashJournal_Invoice (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
581     {
582         if (isCalloutActive()) // assuming it is resetting value
583
return "";
584         setCalloutActive(true);
585
586         Integer JavaDoc C_Invoice_ID = (Integer JavaDoc)value;
587         if (C_Invoice_ID == null || C_Invoice_ID.intValue() == 0)
588         {
589             setCalloutActive(false);
590             return "";
591         }
592
593         // Date
594
Timestamp JavaDoc ts = Env.getContextAsDate(ctx, WindowNo, "DateAcct"); // from C_Cash
595
if (ts == null)
596             ts = new Timestamp JavaDoc(System.currentTimeMillis());
597         //
598
String JavaDoc sql = "SELECT C_BPartner_ID, C_Currency_ID, C_Invoice_Open(C_Invoice_ID),"
599             + "C_PaymentTerm_Discount(C_Invoice_Open(C_Invoice_ID),C_PaymentTerm_ID,DateInvoiced,?) "
600             + "FROM C_Invoice WHERE C_Invoice_ID=?";
601         try
602         {
603             PreparedStatement JavaDoc pstmt = DB.prepareStatement(sql);
604             pstmt.setTimestamp(1, ts);
605             pstmt.setInt(2, C_Invoice_ID.intValue());
606             ResultSet JavaDoc rs = pstmt.executeQuery();
607             if (rs.next())
608             {
609                 mTab.setValue("C_Currency_ID", new Integer JavaDoc(rs.getInt(2)));
610                 BigDecimal JavaDoc PayAmt = rs.getBigDecimal(3);
611                 BigDecimal JavaDoc DiscountAmt = rs.getBigDecimal(4);
612                 mTab.setValue("Amount", PayAmt.subtract(DiscountAmt));
613                 mTab.setValue("DiscountAmt", DiscountAmt);
614                 mTab.setValue("WriteOffAmt", Env.ZERO);
615                 Env.setContext(ctx, WindowNo, "InvTotalAmt", PayAmt.toString());
616             }
617             rs.close();
618             pstmt.close();
619         }
620         catch (SQLException JavaDoc e)
621         {
622             log.error("CashJournal_Invoice", e);
623             setCalloutActive(false);
624             return e.getLocalizedMessage();
625         }
626         setCalloutActive(false);
627         return "";
628     } // CashJournal_Invoice
629

630     /**
631      * Cash Journal Line Invoice Amounts.
632      * when DiscountAnt, Amount, WriteOffAmt change
633      * making sure that add up to InvTotalAmt (created by CashJournal_Invoice)
634      */

635     public String JavaDoc CashJournal_Amounts (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
636     {
637         // Needs to be Invoice
638
if (isCalloutActive() || !"I".equals(mTab.getValue("CashType")))
639             return "";
640         // Check, if InvTotalAmt exists
641
String JavaDoc total = Env.getContext(ctx, WindowNo, "InvTotalAmt");
642         if (total == null || total.length() == 0)
643             return "";
644         BigDecimal JavaDoc InvTotalAmt = new BigDecimal JavaDoc(total);
645         setCalloutActive(true);
646
647         BigDecimal JavaDoc PayAmt = (BigDecimal JavaDoc)mTab.getValue("Amount");
648         BigDecimal JavaDoc DiscountAmt = (BigDecimal JavaDoc)mTab.getValue("DiscountAmt");
649         BigDecimal JavaDoc WriteOffAmt = (BigDecimal JavaDoc)mTab.getValue("WriteOffAmt");
650         String JavaDoc colName = mField.getColumnName();
651         log.debug(colName + " - Invoice=" + InvTotalAmt
652             + " - Amount=" + PayAmt + ", Discount=" + DiscountAmt + ", WriteOff=" + WriteOffAmt);
653
654         // Amount - calculate write off
655
if (colName.equals("Amount"))
656         {
657             WriteOffAmt = InvTotalAmt.subtract(PayAmt).subtract(DiscountAmt);
658             mTab.setValue("WriteOffAmt", WriteOffAmt);
659         }
660         else // calculate PayAmt
661
{
662             PayAmt = InvTotalAmt.subtract(DiscountAmt).subtract(WriteOffAmt);
663             mTab.setValue("Amount", PayAmt);
664         }
665
666         setCalloutActive(false);
667         return "";
668     } // CashJournal_Amounts
669

670     /*************************************************************************/
671
672     /**
673      * Journal - Period.
674      * Check that selected period is in DateAcct Range or Adjusting Period
675      * Called when C_Period_ID or DateAcct, DateDoc changed
676      */

677     public String JavaDoc Journal_Period (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
678     {
679         String JavaDoc colName = mField.getColumnName();
680         if (value == null || isCalloutActive())
681             return "";
682         setCalloutActive(true);
683
684         int AD_Client_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Client_ID");
685         Timestamp JavaDoc DateAcct = null;
686         if (colName.equals("DateAcct"))
687             DateAcct = (Timestamp JavaDoc)value;
688         else
689             DateAcct = (Timestamp JavaDoc)mTab.getValue("DateAcct");
690         int C_Period_ID = 0;
691         if (colName.equals("C_Period_ID"))
692             C_Period_ID = ((Integer JavaDoc)value).intValue();
693
694         // When DateDoc is changed, update DateAcct
695
if (colName.equals("DateDoc"))
696         {
697             mTab.setValue("DateAcct", value);
698         }
699
700         // When DateAcct is changed, set C_Period_ID
701
else if (colName.equals("DateAcct"))
702         {
703             String JavaDoc sql = "SELECT C_Period_ID "
704                 + "FROM C_Period "
705                 + "WHERE C_Year_ID IN "
706                 + " (SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID ="
707                 + " (SELECT C_Calendar_ID FROM AD_ClientInfo WHERE AD_Client_ID=?))"
708                 + " AND ? BETWEEN StartDate AND EndDate"
709                 + " AND PeriodType='S'";
710             try
711             {
712                 PreparedStatement JavaDoc pstmt = DB.prepareStatement(sql);
713                 pstmt.setInt(1, AD_Client_ID);
714                 pstmt.setTimestamp(2, DateAcct);
715                 ResultSet JavaDoc rs = pstmt.executeQuery();
716                 if (rs.next())
717                     C_Period_ID = rs.getInt(1);
718                 rs.close();
719                 pstmt.close();
720             }
721             catch (SQLException JavaDoc e)
722             {
723                 log.error("Journal_Period - DateAcct", e);
724                 setCalloutActive(false);
725                 return e.getLocalizedMessage();
726             }
727             if (C_Period_ID != 0)
728                 mTab.setValue("C_Period_ID", new Integer JavaDoc(C_Period_ID));
729         }
730
731         // When C_Period_ID is changed, check if in DateAcct range and set to end date if not
732
else
733         {
734             String JavaDoc sql = "SELECT PeriodType, StartDate, EndDate "
735                 + "FROM C_Period WHERE C_Period_ID=?";
736             try
737             {
738                 PreparedStatement JavaDoc pstmt = DB.prepareStatement(sql);
739                 pstmt.setInt(1, C_Period_ID);
740                 ResultSet JavaDoc rs = pstmt.executeQuery();
741                 if (rs.next())
742                 {
743                     String JavaDoc PeriodType = rs.getString(1);
744                     Timestamp JavaDoc StartDate = rs.getTimestamp(2);
745                     Timestamp JavaDoc EndDate = rs.getTimestamp(3);
746                     if (PeriodType.equals("S")) // Standard Periods
747
{
748                         // out of range - set to last day
749
if (DateAcct.before(StartDate) || DateAcct.after(EndDate))
750                             mTab.setValue("DateAcct", EndDate);
751                     }
752                 }
753                 rs.close();
754                 pstmt.close();
755             }
756             catch (SQLException JavaDoc e)
757             {
758                 log.error("Journal_Period - Period", e);
759                 setCalloutActive(false);
760                 return e.getLocalizedMessage();
761             }
762         }
763         setCalloutActive(false);
764         return "";
765     } // Journal_Period
766

767
768     /**
769      * JournalLine - Amt.
770      * Convert the source amount to accounted amount (AmtAcctDr/Cr)
771      * Called when source amount (AmtSourceCr/Dr) or currency changes
772      * (C_Currency_ID, CurrencyRate, CurrencyRateType, DateAcct)
773      */

774     public String JavaDoc JournalLine_Amt (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
775     {
776         String JavaDoc colName = mField.getColumnName();
777         if (value == null || isCalloutActive())
778             return "";
779         // Ignore
780
if (mField.getColumnName().equals("CurrencyRate") && value == null)
781             return "";
782         if (mTab.getValue("C_Currency_ID") == null)
783             return "";
784
785         setCalloutActive(true);
786
787         // Source Currency
788
Integer JavaDoc Currency_ID = (Integer JavaDoc)mTab.getValue("C_Currency_ID");
789         int C_Currency_ID = Currency_ID.intValue();
790
791
792         // Get Target Currency & Precision from C_AcctSchema.C_Currency_ID
793
int C_AcctSchema_ID = Env.getContextAsInt(ctx, WindowNo, "C_AcctSchema_ID");
794         int Target_Currency_ID = 0;
795         int Precision = 2;
796         String JavaDoc sql = "SELECT c.C_Currency_ID, c.StdPrecision FROM C_AcctSchema a, C_Currency c "
797             + "WHERE a.C_Currency_ID=c.C_Currency_ID AND a.C_AcctSchema_ID=?";
798         try
799         {
800             PreparedStatement JavaDoc pstmt = DB.prepareStatement(sql);
801             pstmt.setInt(1, C_AcctSchema_ID);
802             ResultSet JavaDoc rs = pstmt.executeQuery();
803             if (rs.next())
804             {
805                 Target_Currency_ID = rs.getInt(1);
806                 Precision = rs.getInt(2);
807             }
808             rs.close();
809             pstmt.close();
810         }
811         catch (SQLException JavaDoc e)
812         {
813             log.error("JournalLine_Amt - Currency", e);
814             setCalloutActive(false);
815             return e.getLocalizedMessage();
816         }
817
818         // Get variables: DateAcct, CurrencyRate(Type)
819
Timestamp JavaDoc DateAcct = (Timestamp JavaDoc)mTab.getValue("DateAcct");
820         if (DateAcct == null)
821             DateAcct = new Timestamp JavaDoc(System.currentTimeMillis());
822         String JavaDoc CurrencyRateType = (String JavaDoc)mTab.getValue("CurrencyRateType");
823         if (CurrencyRateType == null)
824         {
825             CurrencyRateType = "S";
826             mTab.setValue("CurrencyRateType", CurrencyRateType);
827         }
828         BigDecimal JavaDoc CurrencyRate = (BigDecimal JavaDoc)mTab.getValue("CurrencyRate");
829         if (CurrencyRate == null)
830         {
831             CurrencyRate = new BigDecimal JavaDoc(1.0);
832             mTab.setValue("CurrencyRate", CurrencyRate);
833         }
834
835         // When C_Currency_ID, CurrencyRate(Type) or DateAcct is changed,
836
// look up CurrencyRate
837
// Issue: you are able to overwrite fixed rates
838
if (colName.equals("C_Currency_ID") || colName.equals("CurrencyRateType")
839             || colName.equals("DateAcct"))
840         {
841             log.debug("CurrencyConversion From=" + C_Currency_ID
842                 + "; To=" + Target_Currency_ID + "; Date=" + DateAcct.toString()
843                 + "; Type=" + CurrencyRateType);
844
845             int AD_Client_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Client_ID");
846             int AD_Org_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Org_ID");
847             CurrencyRate = DB.getConvesionRate(C_Currency_ID, Target_Currency_ID, DateAcct, CurrencyRateType, AD_Client_ID, AD_Org_ID);
848             log.debug("Rate From Rate Table=" + CurrencyRate);
849             if (CurrencyRate == null)
850             {
851                 sql = "SELECT CurrencyRate FROM GL_Journal "
852                     + "WHERE GL_Journal_ID=? AND C_Currency_ID=? AND CurrencyRateType=?";
853                 PreparedStatement JavaDoc pstmt = null;
854                 try
855                 {
856                     pstmt = DB.prepareStatement(sql);
857                     pstmt.setInt(1, ((Integer JavaDoc)mTab.getValue("GL_Journal_ID")).intValue());
858                     pstmt.setInt(2, C_Currency_ID);
859                     pstmt.setString(3, CurrencyRateType);
860                     ResultSet JavaDoc rs = pstmt.executeQuery();
861                     if (rs.next())
862                     {
863                         CurrencyRate = rs.getBigDecimal (1);
864                         log.debug("CurrencyConversion From Journal=" + CurrencyRate);
865                     }
866                     rs.close();
867                     pstmt.close();
868                     pstmt = null;
869                 }
870                 catch (SQLException JavaDoc ex)
871                 {
872                     log.error("JournalLine_Amt - Rate from Journal", ex);
873                 }
874                 try
875                 {
876                     if (pstmt != null)
877                         pstmt.close();
878                 }
879                 catch (SQLException JavaDoc ex1){}
880                 pstmt = null;
881             }
882             if (CurrencyRate == null)
883                 CurrencyRate = Env.ZERO;
884             mTab.setValue("CurrencyRate", CurrencyRate);
885         }
886
887         // AmtAcct = AmtSource * CurrencyRate ==> Precision
888
BigDecimal JavaDoc AmtSourceDr = (BigDecimal JavaDoc)mTab.getValue("AmtSourceDr");
889         if (AmtSourceDr == null)
890             AmtSourceDr = Env.ZERO;
891         BigDecimal JavaDoc AmtSourceCr = (BigDecimal JavaDoc)mTab.getValue("AmtSourceCr");
892         if (AmtSourceCr == null)
893             AmtSourceCr = Env.ZERO;
894
895         BigDecimal JavaDoc AmtAcctDr = AmtSourceDr.multiply(CurrencyRate);
896         AmtAcctDr = AmtAcctDr.setScale(Precision, BigDecimal.ROUND_HALF_UP);
897         mTab.setValue("AmtAcctDr", AmtAcctDr);
898         BigDecimal JavaDoc AmtAcctCr = AmtSourceCr.multiply(CurrencyRate);
899         AmtAcctCr = AmtAcctCr.setScale(Precision, BigDecimal.ROUND_HALF_UP);
900         mTab.setValue("AmtAcctCr", AmtAcctCr);
901
902         setCalloutActive(false);
903         return "";
904     } // JournalLine_Amt
905

906     /*************************************************************************/
907
908     /**
909      * Expense Report Line
910      * - get ExpenseAmt
911      */

912     public String JavaDoc Expense_Product (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
913     {
914         Integer JavaDoc M_Product_ID = (Integer JavaDoc)value;
915         if (M_Product_ID == null || M_Product_ID.intValue() == 0)
916             return "";
917         setCalloutActive(true);
918
919         // get expense date - or default to today's date
920
Timestamp JavaDoc DateExpense = Env.getContextAsDate(ctx, WindowNo, "DateExpense");
921         if (DateExpense == null)
922             DateExpense = new Timestamp JavaDoc(System.currentTimeMillis());
923
924         try
925         {
926             boolean noPrice = true;
927             BigDecimal JavaDoc priceActual = null;
928
929             // Search Pricelist for current version
930
String JavaDoc sql = "SELECT BOM_PriceStd(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceStd,"
931                 + "BOM_PriceList(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceList,"
932                 + "BOM_PriceLimit(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceLimit,"
933                 + "p.C_UOM_ID,pv.ValidFrom,pl.C_Currency_ID "
934                 + "FROM M_Product p, M_ProductPrice pp, M_Pricelist pl, M_PriceList_Version pv "
935                 + "WHERE p.M_Product_ID=pp.M_Product_ID"
936                 + " AND pp.M_PriceList_Version_ID=pv.M_PriceList_Version_ID"
937                 + " AND pv.M_PriceList_ID=pl.M_PriceList_ID"
938                 + " AND pv.IsActive='Y'"
939                 + " AND p.M_Product_ID=?" // 1
940
+ " AND pl.M_PriceList_ID=?" // 2
941
+ " ORDER BY pv.ValidFrom DESC";
942             PreparedStatement JavaDoc pstmt = DB.prepareStatement(sql);
943             pstmt.setInt(1, M_Product_ID.intValue());
944             pstmt.setInt(2, Env.getContextAsInt(ctx, WindowNo, "M_PriceList_ID"));
945             ResultSet JavaDoc rs = pstmt.executeQuery();
946             while (rs.next() && noPrice)
947             {
948                 java.sql.Date JavaDoc plDate = rs.getDate("ValidFrom");
949                 // we have the price list
950
// if order date is after or equal PriceList validFrom
951
if (plDate == null || !DateExpense.before(plDate))
952                 {
953                     noPrice = false;
954                     // Price
955
priceActual = rs.getBigDecimal("PriceStd");
956                     if (priceActual == null)
957                         priceActual = rs.getBigDecimal("PriceList");
958                     if (priceActual == null)
959                         priceActual = rs.getBigDecimal("PriceLimit");
960                     // Currency
961
Integer JavaDoc ii = new Integer JavaDoc(rs.getInt("C_Currency_ID"));
962                     if (!rs.wasNull())
963                         mTab.setValue("C_Currency_ID", ii);
964                 }
965             }
966             rs.close();
967             pstmt.close();
968
969             // no prices yet - look base pricelist
970
if (noPrice)
971             {
972                 // Find if via Base Pricelist
973
sql = "SELECT BOM_PriceStd(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceStd,"
974                     + "BOM_PriceList(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceList,"
975                     + "BOM_PriceLimit(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceLimit,"
976                     + "p.C_UOM_ID,pv.ValidFrom,pl.C_Currency_ID "
977                     + "FROM M_Product p, M_ProductPrice pp, M_Pricelist pl, M_Pricelist bpl, M_PriceList_Version pv "
978                     + "WHERE p.M_Product_ID=pp.M_Product_ID"
979                     + " AND pp.M_PriceList_Version_ID=pv.M_PriceList_Version_ID"
980                     + " AND pv.M_PriceList_ID=bpl.M_PriceList_ID"
981                     + " AND pv.IsActive='Y'"
982                     + " AND bpl.M_PriceList_ID=pl.BasePriceList_ID" // Base
983
+ " AND p.M_Product_ID=?" // 1
984
+ " AND pl.M_PriceList_ID=?" // 2
985
+ " ORDER BY pv.ValidFrom DESC";
986
987                 pstmt = DB.prepareStatement(sql);
988                 pstmt.setInt(1, M_Product_ID.intValue());
989                 pstmt.setInt(2, Env.getContextAsInt(ctx, WindowNo, "M_PriceList_ID"));
990                 rs = pstmt.executeQuery();
991                 while (rs.next() && noPrice)
992                 {
993                     java.sql.Date JavaDoc plDate = rs.getDate("ValidFrom");
994                     // we have the price list
995
// if order date is after or equal PriceList validFrom
996
if (plDate == null || !DateExpense.before(plDate))
997                     {
998                         noPrice = false;
999                         // Price
1000
priceActual = rs.getBigDecimal("PriceStd");
1001                        if (priceActual == null)
1002                            priceActual = rs.getBigDecimal("PriceList");
1003                        if (priceActual == null)
1004                            priceActual = rs.getBigDecimal("PriceLimit");
1005                        // Currency
1006
Integer JavaDoc ii = new Integer JavaDoc(rs.getInt("C_Currency_ID"));
1007                        if (!rs.wasNull())
1008                            mTab.setValue("C_Currency_ID", ii);
1009                    }
1010                }
1011                rs.close();
1012                pstmt.close();
1013            }
1014            //
1015
setCalloutActive(false); // calculate amount
1016
if (priceActual == null)
1017                priceActual = Env.ZERO;
1018            mTab.setValue("ExpenseAmt", priceActual);
1019        }
1020        catch (SQLException JavaDoc e)
1021        {
1022            log.error("Expense_Product", e);
1023            setCalloutActive(false);
1024            return e.getLocalizedMessage();
1025        }
1026
1027    // setCalloutActive(false);
1028
return "";
1029    } // Expense_Product
1030

1031    /**
1032     * Expense - Amount.
1033     * - called from Qty, ExpenseAmt, C_Currency_ID
1034     * - calculates ConvertedAmt
1035     */

1036    public String JavaDoc Expense_Amount (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
1037    {
1038        if (isCalloutActive())
1039            return "";
1040        setCalloutActive(true);
1041
1042        // get values
1043
BigDecimal JavaDoc Qty = (BigDecimal JavaDoc)mTab.getValue("Qty");
1044        BigDecimal JavaDoc ExpenseAmt = (BigDecimal JavaDoc)mTab.getValue("ExpenseAmt");
1045        Integer JavaDoc C_Currency_ID = (Integer JavaDoc)mTab.getValue("C_Currency_ID");
1046        int C_Currency_To_ID = Env.getContextAsInt(ctx, "$C_Currency_ID");
1047        Timestamp JavaDoc DateExpense = Env.getContextAsDate(ctx, WindowNo, "DateExpense");
1048        //
1049
log.debug("Qty=" + Qty + ", Amt=" + ExpenseAmt + ", C_Currency_ID=" + C_Currency_ID);
1050        // Converted Amount = Unit price
1051
BigDecimal JavaDoc ConvertedAmt = ExpenseAmt;
1052        // convert if required
1053
if (!ConvertedAmt.equals(Env.ZERO) && C_Currency_To_ID != C_Currency_ID.intValue())
1054        {
1055            int AD_Client_ID = Env.getContextAsInt (ctx, WindowNo, "AD_Client_ID");
1056            int AD_Org_ID = Env.getContextAsInt (ctx, WindowNo, "AD_Org_ID");
1057            ConvertedAmt = DB.getConvertedAmt (ConvertedAmt, C_Currency_ID.intValue (), C_Currency_To_ID, DateExpense, null, AD_Client_ID, AD_Org_ID);
1058        }
1059        mTab.setValue("ConvertedAmt", ConvertedAmt);
1060        log.debug("= ConvertedAmt=" + ConvertedAmt);
1061
1062        setCalloutActive(false);
1063        return "";
1064    } // Expense_Amount
1065

1066    /**
1067     * Assignment_Product.
1068     * - called from S_ResourceAssignment_ID
1069     * - sets M_Product_ID
1070     */

1071    public String JavaDoc Assignment_Product (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
1072    {
1073        if (isCalloutActive() || value == null)
1074            return "";
1075        // get value
1076
int S_ResourceAssignment_ID = ((Integer JavaDoc)value).intValue();
1077        if (S_ResourceAssignment_ID == 0)
1078            return "";
1079        setCalloutActive(true);
1080
1081        int M_Product_ID = 0;
1082        String JavaDoc Name = null;
1083        String JavaDoc Description = null;
1084        BigDecimal JavaDoc Qty = null;
1085        String JavaDoc sql = "SELECT p.M_Product_ID, ra.Name, ra.Description, ra.Qty "
1086            + "FROM S_ResourceAssignment ra"
1087            + " INNER JOIN M_Product p ON (p.S_Resource_ID=ra.S_Resource_ID) "
1088            + "WHERE ra.S_ResourceAssignment_ID=?";
1089        try
1090        {
1091            PreparedStatement JavaDoc pstmt = DB.prepareStatement(sql);
1092            pstmt.setInt(1, S_ResourceAssignment_ID);
1093            ResultSet JavaDoc rs = pstmt.executeQuery();
1094            if (rs.next())
1095            {
1096                M_Product_ID = rs.getInt (1);
1097                Name = rs.getString(2);
1098                Description = rs.getString(3);
1099                Qty = rs.getBigDecimal(4);
1100            }
1101            rs.close();
1102            pstmt.close();
1103        }
1104        catch (SQLException JavaDoc e)
1105        {
1106            log.error("Assignment_Product", e);
1107        }
1108
1109        log.debug("S_ResourceAssignment_ID=" + S_ResourceAssignment_ID + " - M_Product_ID=" + M_Product_ID);
1110        if (M_Product_ID != 0)
1111        {
1112            mTab.setValue ("M_Product_ID", new Integer JavaDoc (M_Product_ID));
1113            if (Description != null)
1114                Name += " (" + Description + ")";
1115            if (!".".equals(Name))
1116                mTab.setValue("Description", Name);
1117            //
1118
String JavaDoc variable = "Qty";
1119            if (mTab.getTableName().startsWith("C_Order"))
1120                variable = "QtyOrdered";
1121            else if (mTab.getTableName().startsWith("C_Invoice"))
1122                variable = "QtyInvoiced";
1123            if (Qty != null)
1124                mTab.setValue(variable, Qty);
1125        }
1126        setCalloutActive(false);
1127        return "";
1128    } // Assignment_Product
1129

1130    /*************************************************************************/
1131
1132    /**
1133     * Payment Selection - Payment Amount.
1134     * - called from C_PaySelectionLine.PayAmt
1135     * - update DifferenceAmt
1136     */

1137    public String JavaDoc PaySel_PayAmt (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
1138    {
1139        if (isCalloutActive() || value == null)
1140            return "";
1141        // get value
1142
BigDecimal JavaDoc PayAmt = (BigDecimal JavaDoc)value;
1143        Integer JavaDoc ii = (Integer JavaDoc)mTab.getValue("C_Invoice_ID");
1144        if (ii == null)
1145            return "";
1146        int C_Invoice_ID = ii.intValue();
1147        if (C_Invoice_ID == 0)
1148            return "";
1149        setCalloutActive(true);
1150
1151        BigDecimal JavaDoc OpenAmt = Env.ZERO;
1152        String JavaDoc sql = "SELECT C_Currency_Convert(C_Invoice_Open(C_Invoice_ID), C_Currency_ID, 100, DateInvoiced, 'S', AD_Client_ID, AD_Org_ID) "
1153            + "FROM C_Invoice WHERE C_Invoice_ID=?";
1154        try
1155        {
1156            PreparedStatement JavaDoc pstmt = DB.prepareStatement(sql);
1157            pstmt.setInt(1, C_Invoice_ID);
1158            ResultSet JavaDoc rs = pstmt.executeQuery();
1159            if (rs.next())
1160                OpenAmt = rs.getBigDecimal(1);
1161            rs.close();
1162            pstmt.close();
1163        }
1164        catch (SQLException JavaDoc e)
1165        {
1166            log.error("PaySel_PayAmt", e);
1167        }
1168
1169        BigDecimal JavaDoc DiffAmt = OpenAmt.subtract(PayAmt);
1170        log.debug("OpenAmt=" + OpenAmt + ", PayAmt=" + PayAmt + ", DiffAmt=" + DiffAmt);
1171        mTab.setValue("DifferenceAmt", DiffAmt);
1172
1173        setCalloutActive(false);
1174        return "";
1175    } // PaySel_PayAmt
1176

1177    /**
1178     * Payment Selection - Invoice.
1179     * - called from C_PaySelectionLine.C_Invoice_ID
1180     * - update PayAmt & DifferenceAmt
1181     */

1182    public String JavaDoc PaySel_Invoice (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
1183    {
1184        if (isCalloutActive() || value == null)
1185            return "";
1186        // get value
1187
int C_Invoice_ID = ((Integer JavaDoc)value).intValue();
1188        if (C_Invoice_ID == 0)
1189            return "";
1190        setCalloutActive(true);
1191
1192        BigDecimal JavaDoc OpenAmt = Env.ZERO;
1193        String JavaDoc sql = "SELECT C_Currency_Convert(C_Invoice_Open(C_Invoice_ID), C_Currency_ID, 100, DateInvoiced, 'S', AD_Client_ID, AD_Org_ID) "
1194            + "FROM C_Invoice WHERE C_Invoice_ID=?";
1195        try
1196        {
1197            PreparedStatement JavaDoc pstmt = DB.prepareStatement(sql);
1198            pstmt.setInt(1, C_Invoice_ID);
1199            ResultSet JavaDoc rs = pstmt.executeQuery();
1200            if (rs.next())
1201                OpenAmt = rs.getBigDecimal(1);
1202            rs.close();
1203            pstmt.close();
1204        }
1205        catch (SQLException JavaDoc e)
1206        {
1207            log.error("PaySel_Invoice", e);
1208        }
1209
1210        log.debug("OpenAmt=" + OpenAmt);
1211        mTab.setValue("PayAmt", OpenAmt);
1212        mTab.setValue("DifferenceAmt", Env.ZERO);
1213
1214        setCalloutActive(false);
1215        return "";
1216    } // PaySel_Invoice
1217

1218    /*************************************************************************/
1219
1220    /**
1221     * Project Planned - Price + Qty.
1222     * - called from PlannedPrice, PlannedQty
1223     * - calculates PlannedAmt (same as Trigger)
1224     */

1225    public String JavaDoc Project_Planned (Properties JavaDoc ctx, int WindowNo, MTab mTab, MField mField, Object JavaDoc value)
1226    {
1227        if (isCalloutActive() || value == null)
1228            return "";
1229        setCalloutActive(true);
1230
1231        BigDecimal JavaDoc PlannedQty, PlannedPrice;
1232        int StdPrecision = Env.getContextAsInt(ctx, WindowNo, "StdPrecision");
1233
1234
1235        // get values
1236
PlannedQty = (BigDecimal JavaDoc)mTab.getValue("PlannedQty");
1237        if (PlannedQty == null)
1238            PlannedQty = Env.ONE;
1239        PlannedPrice = ((BigDecimal JavaDoc)mTab.getValue("PlannedPrice"));
1240        if (PlannedPrice == null)
1241            PlannedPrice = Env.ZERO;
1242        //
1243
BigDecimal JavaDoc PlannedAmt = PlannedQty.multiply(PlannedPrice);
1244        if (PlannedAmt.scale() > StdPrecision)
1245            PlannedAmt = PlannedAmt.setScale(StdPrecision, BigDecimal.ROUND_HALF_UP);
1246        //
1247
log.debug("PlannedQty=" + PlannedQty + " * PlannedPrice=" + PlannedPrice + " -> PlannedAmt=" + PlannedAmt + " (Precision=" + StdPrecision+ ")");
1248        mTab.setValue("PlannedAmt", PlannedAmt);
1249        setCalloutActive(false);
1250        return "";
1251    } // Project_Planned
1252

1253
1254    public static final String JavaDoc DocSubTypeSO_Standard = "SO";
1255    public static final String JavaDoc DocSubTypeSO_Quotation = "OB";
1256    public static final String JavaDoc DocSubTypeSO_Proposal = "ON";
1257    public static final String JavaDoc DocSubTypeSO_Prepay = "PR";
1258    public static final String JavaDoc DocSubTypeSO_POS = "WR";
1259    public static final String JavaDoc DocSubTypeSO_Warehouse = "WP";
1260    public static final String JavaDoc DocSubTypeSO_OnCredit = "WI";
1261    public static final String JavaDoc DocSubTypeSO_RMA = "RM";
1262
1263} // CalloutSystem
1264
Popular Tags