KickJava   Java API By Example, From Geeks To Geeks.

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


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 Smart 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-2003 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.util.*;
17 import java.sql.*;
18 import java.math.*;
19 import java.io.*;
20
21 import org.compiere.util.*;
22 import org.compiere.print.*;
23 import org.compiere.process.*;
24
25
26 /**
27  * Invoice Model
28  *
29  * @author Jorg Janke
30  * @version $Id: MInvoice.java,v 1.21 2003/11/07 06:36:36 jjanke Exp $
31  */

32 public class MInvoice extends X_C_Invoice
33 {
34     /**
35      * Invoice Constructor
36      * @param ctx context
37      * @param C_Invoice_ID invoice or 0 for new
38      */

39     public MInvoice (Properties ctx, int C_Invoice_ID)
40     {
41         super (ctx, C_Invoice_ID);
42         if (C_Invoice_ID == 0)
43         {
44             setDocStatus (DOCSTATUS_Drafted); // Draft
45
setDocAction (DOCACTION_Complete);
46             //
47
setPaymentRule(PAYMENTRULE_OnCredit); // Payment Terms
48

49             setDateInvoiced (new Timestamp (System.currentTimeMillis ()));
50             setDateAcct (new Timestamp (System.currentTimeMillis ()));
51             //
52
setChargeAmt (Env.ZERO);
53             setTotalLines (Env.ZERO);
54             setGrandTotal (Env.ZERO);
55             //
56
setIsSOTrx (true);
57             setIsTaxIncluded (false);
58             setIsApproved (false);
59             setIsDiscountPrinted (false);
60             setIsPaid (false);
61             setSendEMail (false);
62             setIsPrinted (false);
63             setIsTransferred (false);
64             setIsSelfService(false);
65             setPosted(false);
66             setProcessed (false);
67         }
68     } // MInvoice
69

70     /**
71      * Load Constructor
72      * @param ctx context
73      * @param rs result set record
74      */

75     public MInvoice (Properties ctx, ResultSet rs)
76     {
77         super (ctx, rs);
78     } // MOrder
79

80     public static final String JavaDoc DocBaseType_ARI = "ARI";
81     public static final String JavaDoc DocBaseType_API = "API";
82
83     /** Open Amount */
84     private BigDecimal m_openAmt = null;
85
86     /** Invoice Lines */
87     private MInvoiceLine[] m_lines;
88
89     /**
90      * Overwrite Client/Org if required
91      * @param AD_Client_ID client
92      * @param AD_Org_ID org
93      */

94     public void setClientOrg (int AD_Client_ID, int AD_Org_ID)
95     {
96         super.setClientOrg(AD_Client_ID, AD_Org_ID);
97     } // setClientOrg
98

99     /**
100      * Set Business Partner Defaults & Details
101      * @param bp business partner
102      */

103     public void setBPartner (MBPartner bp)
104     {
105         if (bp == null)
106             return;
107
108         setC_BPartner_ID(bp.getC_BPartner_ID());
109         // Set Defaults
110
int ii = 0;
111         if (isSOTrx())
112             ii = bp.getC_PaymentTerm_ID();
113         else
114             ii = bp.getPO_PaymentTerm_ID();
115         if (ii != 0)
116             setC_PaymentTerm_ID(ii);
117         //
118
if (isSOTrx())
119             ii = bp.getM_PriceList_ID();
120         else
121             ii = bp.getPO_PriceList_ID();
122         if (ii != 0)
123             setM_PriceList_ID(ii);
124         //
125
String JavaDoc ss = bp.getPaymentRule();
126         if (ss != null)
127             setPaymentRule(ss);
128
129
130         // Set Locations
131
MBPartner_Location[] locs = bp.getLocations();
132         if (locs != null)
133         {
134             for (int i = 0; i < locs.length; i++)
135             {
136                 if ((locs[i].isBillTo() && isSOTrx()) || (locs[i].isPayFrom() && !isSOTrx()))
137                     setC_BPartner_Location_ID(locs[i].getC_BPartner_Location_ID());
138             }
139             // set to first
140
if (getC_BPartner_Location_ID() == 0 && locs.length > 0)
141                 setC_BPartner_Location_ID(locs[0].getC_BPartner_Location_ID());
142         }
143         if (getC_BPartner_Location_ID() == 0)
144             log.error("setBPartner - Has no To Address: " + bp);
145
146         // Set Contact
147
MUser[] contacts = bp.getContacts();
148         if (contacts != null && contacts.length > 0) // get first User
149
setAD_User_ID(contacts[0].getAD_User_ID());
150     } // setBPartner
151

152     /**
153      * Set Target Document Type
154      * @param DocBaseType doc type
155      */

156     public void setC_DocTypeTarget_ID (String JavaDoc DocBaseType)
157     {
158         int C_DocType_ID = 0;
159         //
160
String JavaDoc sql = "SELECT C_DocType_ID FROM C_DocType WHERE AD_Client_ID=? AND DocBaseType=? ORDER BY IsDefault DESC";
161         PreparedStatement pstmt = null;
162         try
163         {
164             pstmt = DB.prepareStatement(sql);
165             pstmt.setInt(1, getAD_Client_ID());
166             pstmt.setString(2, DocBaseType);
167             ResultSet rs = pstmt.executeQuery();
168             if (rs.next())
169                 C_DocType_ID = rs.getInt(1);
170             rs.close();
171             pstmt.close();
172             pstmt = null;
173         }
174         catch (Exception JavaDoc e)
175         {
176             log.error("setC_DocTypeTarget_ID", e);
177         }
178         finally
179         {
180             try
181             {
182                 if (pstmt != null)
183                     pstmt.close ();
184             }
185             catch (Exception JavaDoc e)
186             {}
187             pstmt = null;
188         }
189         if (C_DocType_ID == 0)
190             log.error("setC_DocTypeTarget_ID - Not found for AC_Client_ID=" + getAD_Client_ID() + " - " + DocBaseType);
191         else
192         {
193             log.debug ("setC_DocTypeTarget_ID - " + DocBaseType);
194             setC_DocTypeTarget_ID (C_DocType_ID);
195             setIsSOTrx (DocBaseType_ARI.equals(DocBaseType));
196         }
197     } // setC_DocTypeTarget_ID
198

199     /**
200      * Set Defaults for mandatory values where not set yet
201      */

202     private void setDefaults ()
203     {
204         log.debug("setDefaults");
205         int AD_Client_ID = getAD_Client_ID();
206         // No Partner Info - set Template
207
if (getC_BPartner_ID() == 0)
208             setBPartner(MBPartner.getTemplate(getCtx(), AD_Client_ID));
209         if (getC_BPartner_Location_ID() == 0)
210             setBPartner(new MBPartner(getCtx(), getC_BPartner_ID()));
211
212         // Price List
213
if (getM_PriceList_ID() == 0)
214         {
215             int ii = Env.getContextAsInt(getCtx(), "#M_PriceList_ID");
216             if (ii != 0)
217                 setM_PriceList_ID(ii);
218             else
219             {
220                 String JavaDoc sql = "SLECT M_PriceList_ID FROM M_PriceList WHERE AD_Client_ID=? AND IsDefault='Y'";
221                 ii = DB.getSQLValue (sql, AD_Client_ID);
222                 if (ii != 0)
223                     setM_PriceList_ID (ii);
224             }
225         }
226         // Currency
227
if (getC_Currency_ID() == 0)
228         {
229             String JavaDoc sql = "SLECT C_Currency_ID FROM M_PriceList WHERE M_PriceList_ID=?";
230             int ii = DB.getSQLValue (sql, getM_PriceList_ID());
231             if (ii != 0)
232                 setC_Currency_ID (ii);
233             else
234                 setC_Currency_ID(Env.getContextAsInt(getCtx(), "#C_Currency_ID"));
235         }
236
237         // Sales Rep
238
if (getSalesRep_ID() == 0)
239         {
240             int ii = Env.getContextAsInt(getCtx(), "#SalesRep_ID");
241             if (ii != 0)
242                 setSalesRep_ID (ii);
243         }
244
245         // Document Type
246
if (getC_DocType_ID() == 0)
247             setC_DocType_ID (0); // make sure it's set to 0
248
if (getC_DocTypeTarget_ID() == 0)
249             setC_DocTypeTarget_ID(isSOTrx() ? DocBaseType_ARI : DocBaseType_API);
250
251         // Payment Term
252
if (getC_PaymentTerm_ID() == 0)
253         {
254             int ii = Env.getContextAsInt(getCtx(), "#C_PaymentTerm_ID");
255             if (ii != 0)
256                 setC_PaymentTerm_ID (ii);
257             else
258             {
259                 String JavaDoc sql = "SELECT C_PaymentTerm_ID FROM C_PaymentTerm WHERE AD_Client_ID=? AND IsDefault='Y'";
260                 ii = DB.getSQLValue(sql, AD_Client_ID);
261                 if (ii != 0)
262                     setC_PaymentTerm_ID (ii);
263             }
264         }
265     } // setDefaults
266

267     /**
268      * Get Invoice Lines
269      * @return lines
270      */

271     public MInvoiceLine[] getLines()
272     {
273         if (m_lines == null || m_lines.length == 0)
274             m_lines = getLines(getC_Invoice_ID());
275         return m_lines;
276     } // getLines
277

278     /**
279      * Get Invoice Lines of Invoice
280      * @param C_Invoice_ID id
281      * @return lines
282      */

283     private MInvoiceLine[] getLines (int C_Invoice_ID)
284     {
285         ArrayList list = new ArrayList();
286         String JavaDoc sql = "SELECT * FROM C_InvoiceLine WHERE C_Invoice_ID=? ORDER BY Line";
287         PreparedStatement pstmt = null;
288         try
289         {
290             pstmt = DB.prepareStatement(sql);
291             pstmt.setInt(1, C_Invoice_ID);
292             ResultSet rs = pstmt.executeQuery();
293             while (rs.next())
294                 list.add(new MInvoiceLine(getCtx(), rs));
295             rs.close();
296             pstmt.close();
297             pstmt = null;
298         }
299         catch (Exception JavaDoc e)
300         {
301             log.error("getLines", e);
302         }
303         finally
304         {
305             try
306             {
307                 if (pstmt != null)
308                     pstmt.close ();
309             }
310             catch (Exception JavaDoc e)
311             {}
312             pstmt = null;
313         }
314
315         //
316
MInvoiceLine[] lines = new MInvoiceLine[list.size()];
317         list.toArray(lines);
318         return lines;
319     } // getLines
320

321     /**
322      * Copy Lines From other Invoice.
323      * Tax??
324      * @param invoice invoice
325      * @return number of lines copied
326      */

327     public int copyLinesFrom (MInvoice invoice)
328     {
329         if (isProcessed() || isPosted() || invoice == null)
330             return 0;
331         MInvoiceLine[] fromLines = invoice.getLines();
332         int count = 0;
333         for (int i = 0; i < fromLines.length; i++)
334         {
335             MInvoiceLine line = new MInvoiceLine (invoice.getCtx(), 0);
336             PO.copyValues(fromLines[i], line, getAD_Client_ID(), getAD_Org_ID());
337             line.setC_Invoice_ID(getC_Invoice_ID());
338             line.setInvoice(invoice);
339             line.setC_InvoiceLine_ID(0);
340             line.setTax();
341             if (line.save())
342                 count++;
343         }
344         if (fromLines.length != count)
345             log.error("copyLinesFrom - Line difference - From=" + fromLines.length + " <> Saved=" + count);
346         return count;
347     } // copyLinesFrom
348

349
350     /*************************************************************************/
351
352     /**
353      * Save Invoice
354      * @return true if saved
355      */

356     public boolean save ()
357     {
358         log.debug ("save");
359         setDefaults();
360         if (getDocumentNo() == null)
361         {
362             String JavaDoc DocumentNo = DB.getDocumentNo (getAD_Client_ID (), getC_DocTypeTarget_ID ());
363             if (DocumentNo == null || DocumentNo.length() == 0)
364                 DocumentNo = DB.getDocumentNo(getAD_Client_ID(), "N", "C_Invoice");
365             setDocumentNo (DocumentNo);
366         }
367         return super.save ();
368     } // save
369

370     /**
371      * Process Order
372      * @param docAction doc action
373      * @return true if no error
374      */

375     public boolean process (String JavaDoc docAction)
376     {
377         setDocAction(docAction);
378         return process();
379     } // process
380

381     /**
382      * Process Order
383      * @return true if no error
384      */

385     public boolean process ()
386     {
387         save();
388         log.debug ("process - " + getDocAction());
389         int AD_Process_ID = 111; // C_Invoice_Post
390
MProcess pp = new MProcess (getCtx(), AD_Process_ID);
391         boolean ok = pp.process(getC_Invoice_ID()).isOK();
392         load(); // reload
393
log.debug("process - ok=" + ok + " - GrandTotal=" + getGrandTotal());
394         return ok;
395     } // process
396

397     public String JavaDoc toString ()
398     {
399         StringBuffer JavaDoc sb = new StringBuffer JavaDoc ("MInvoice[")
400             .append(getID())
401             .append ("]");
402         return sb.toString ();
403     }
404
405     /**
406      * Set Price List (and Currency) when valid
407      * @param M_PriceList_ID price list
408      */

409     public void setM_PriceList_ID (int M_PriceList_ID)
410     {
411         String JavaDoc sql = "SELECT M_PriceList_ID, C_Currency_ID "
412             + "FROM M_PriceList WHERE M_PriceList_ID=?";
413         PreparedStatement pstmt = null;
414         try
415         {
416             pstmt = DB.prepareStatement(sql);
417             pstmt.setInt(1, M_PriceList_ID);
418             ResultSet rs = pstmt.executeQuery();
419             if (rs.next())
420             {
421                 super.setM_PriceList_ID (rs.getInt(1));
422                 setC_Currency_ID (rs.getInt(2));
423             }
424             rs.close();
425             pstmt.close();
426             pstmt = null;
427         }
428         catch (Exception JavaDoc e)
429         {
430             log.error("setM_PriceList_ID", e);
431         }
432         finally
433         {
434             try
435             {
436                 if (pstmt != null)
437                     pstmt.close ();
438             }
439             catch (Exception JavaDoc e)
440             {}
441             pstmt = null;
442         }
443     } // setM_PriceList_ID
444

445
446     /**
447      * Get Open Amount
448      * @return Open Amt
449      */

450     public BigDecimal getOpenAmt ()
451     {
452         if (isPaid())
453             return Env.ZERO;
454         if (m_openAmt != null)
455             return m_openAmt;
456         //
457
String JavaDoc sql = "SELECT C_Invoice_Open(?) FROM DUAL";
458         PreparedStatement pstmt = null;
459         try
460         {
461             pstmt = DB.prepareStatement(sql);
462             pstmt.setInt(1, getC_Invoice_ID());
463             ResultSet rs = pstmt.executeQuery();
464             if (rs.next())
465                 m_openAmt = rs.getBigDecimal(1);
466             rs.close();
467             pstmt.close();
468             pstmt = null;
469         }
470         catch (Exception JavaDoc e)
471         {
472             log.error("getOpenAmt", e);
473         }
474         finally
475         {
476             try
477             {
478                 if (pstmt != null)
479                     pstmt.close ();
480             }
481             catch (Exception JavaDoc e)
482             {}
483             pstmt = null;
484         }
485         //
486
return m_openAmt;
487     } // getOpenAmt
488

489
490     /**
491      * Set Document No.
492      * make access public
493      * @param DocumentNo document no
494      */

495     public void setDocumentNo (String JavaDoc DocumentNo)
496     {
497         super.setDocumentNo(DocumentNo);;
498     } // setDocumentNo
499

500     /**
501      * Set SO Trx
502      * @param IsSOTrx is sales trx
503      */

504     public void setIsSOTrx (boolean IsSOTrx)
505     {
506         super.setIsSOTrx(IsSOTrx);
507     } // setIsSOTrx
508

509     /**
510      * Get Document Status
511      * @return Document Status Clear Text
512      */

513     public String JavaDoc getDocStatusName()
514     {
515         return MRef_List.getListName(getCtx(), 131, getDocStatus());
516     } // getDocStatusName
517

518
519     /*************************************************************************/
520
521     /**
522      * Create PDF
523      * @return true if success
524      */

525     public File getPDF ()
526     {
527         return getPDF(null);
528     } // getPDF
529

530     /**
531      * Create PDF file
532      * @param file output file
533      * @return true if success
534      */

535     public File getPDF (File file)
536     {
537         int AD_PrintFormat_ID = 0;
538         Language language = Language.getLanguage(); // Base Language;
539

540         String JavaDoc sql = "SELECT bp.AD_Language, c.IsMultiLingualDocument,"
541             + " pf.Invoice_PrintFormat_ID, c.DocumentDir "
542             + "FROM C_Invoice i"
543             + " INNER JOIN C_BPartner bp ON (i.C_BPartner_ID=bp.C_BPartner_ID)"
544             + " INNER JOIN AD_Client c ON (i.AD_Client_ID=c.AD_Client_ID)"
545             + " INNER JOIN AD_PrintForm pf ON (c.AD_Client_ID=pf.AD_Client_ID) "
546             + "WHERE i.C_Invoice_ID=?";
547         PreparedStatement pstmt = null;
548         try
549         {
550             pstmt = DB.prepareStatement(sql);
551             pstmt.setInt(1, getC_Invoice_ID());
552             ResultSet rs = pstmt.executeQuery();
553             if (rs.next())
554             {
555                 String JavaDoc AD_Language = rs.getString(1);
556                 if (AD_Language != null && "Y".equals(rs.getString(2)))
557                     language = Language.getLanguage(AD_Language);
558                 //
559
AD_PrintFormat_ID = rs.getInt(3);
560                 //
561
if (file == null)
562                     file = new File (getPDFFileName(rs.getString(4)));
563             }
564             rs.close();
565             pstmt.close();
566             pstmt = null;
567         }
568         catch (Exception JavaDoc e)
569         {
570             Log.error("getPDF", e);
571         }
572         finally
573         {
574             try
575             {
576                 if (pstmt != null)
577                     pstmt.close ();
578             }
579             catch (Exception JavaDoc e)
580             {}
581             pstmt = null;
582         }
583         if (AD_PrintFormat_ID == 0)
584         {
585             log.error("getPDF - No PrintFormat found");
586             return null;
587         }
588
589         // Format
590
MPrintFormat format = MPrintFormat.get (AD_PrintFormat_ID, false);
591         format.setLanguage(language);
592         format.setTranslationLanguage(language);
593
594         // Query
595
MQuery query = new MQuery("C_Invoice_Header_v");
596         query.addRestriction("C_Invoice_ID", MQuery.EQUAL, new Integer JavaDoc(getC_Invoice_ID()));
597
598         // Engine
599
ReportEngine re = new ReportEngine(getCtx(), format, query);
600         return re.getPDF(file);
601     } // getPDF
602

603     /**
604      * Get PDF File Name
605      * @param documentDir directory
606      * @return file name
607      */

608     public String JavaDoc getPDFFileName (String JavaDoc documentDir)
609     {
610         return getPDFFileName(documentDir, getC_Invoice_ID());
611     } // getPDFFileName
612

613     /**
614      * Get PDF File Name
615      * @param documentDir directory
616      * @param C_Invoice_ID invoice
617      * @return file name
618      */

619     public static String JavaDoc getPDFFileName (String JavaDoc documentDir, int C_Invoice_ID)
620     {
621         StringBuffer JavaDoc sb = new StringBuffer JavaDoc (documentDir);
622         if (sb.length() == 0)
623             sb.append(".");
624         if (!sb.toString().endsWith(File.separator))
625             sb.append(File.separator);
626         sb.append("C_Invoice_ID_")
627             .append(C_Invoice_ID)
628             .append(".pdf");
629         return sb.toString();
630     } // getPDFFileName
631

632     /**
633      * Get ISO Code of Currency
634      * @return Currency ISO
635      */

636     public String JavaDoc getCurrencyISO()
637     {
638         return MCurrency.getISO_Code (getCtx(), getC_Currency_ID());
639     } // getCurrencyISO
640

641     /**
642      * Create new Invoice by copying
643      * @param ctx context
644      * @param C_Invoice_ID invoice
645      * @param dateDoc date of the document date
646      * @return Invoice
647      */

648     public static MInvoice copyFrom (Properties ctx, int C_Invoice_ID, Timestamp dateDoc)
649     {
650         MInvoice from = new MInvoice (ctx, C_Invoice_ID);
651         if (from.getC_Invoice_ID() == 0)
652             throw new IllegalArgumentException JavaDoc ("From Invoice not found C_Invoice_ID=" + C_Invoice_ID);
653         //
654
MInvoice to = new MInvoice (ctx, 0);
655         PO.copyValues(from, to, from.getAD_Client_ID(), from.getAD_Org_ID());
656         to.setC_Invoice_ID(0);
657         to.setValueNoCheck ("DocumentNo", null);
658         //
659
to.setDocStatus (DOCSTATUS_Drafted); // Draft
660
to.setDocAction(DOCACTION_Process);
661         to.setC_DocTypeTarget_ID(to.getC_DocType_ID());
662         to.setDateInvoiced (dateDoc);
663         to.setDateAcct (dateDoc);
664         //
665
to.setIsApproved (false);
666         to.setC_Payment_ID(0);
667         to.setC_CashLine_ID(0);
668         to.setIsPaid (false);
669         //
670
// Amounts are updated by trigger when adding lines
671
to.setGrandTotal(Env.ZERO);
672         to.setTotalLines(Env.ZERO);
673         //
674
to.setDatePrinted(null);
675         to.setIsPrinted (false);
676         to.setIsTransferred (false);
677         to.setPosted (false);
678         to.setProcessed (false);
679         // delete references
680
to.setC_Order_ID(0);
681         to.setIsSelfService(false);
682         if (!to.save())
683             throw new IllegalStateException JavaDoc("Could not create Invoice");
684
685         if (to.copyLinesFrom(from) == 0)
686             throw new IllegalStateException JavaDoc("Could not create Invoice Lines");
687
688         return to;
689     } // copyFrom
690

691 } // MInvoice
692
Popular Tags