Last active
April 2, 2021 17:07
-
-
Save YoucefMegoura/7db16078542ca4035733bb8ec60f407f to your computer and use it in GitHub Desktop.
Worked but still AP problem !!!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/****************************************************************************** | |
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * | |
* This program is free software, you can redistribute it and/or modify it * | |
* under the terms version 2 of the GNU General Public License as published * | |
* by the Free Software Foundation. This program is distributed in the hope * | |
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * | |
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * | |
* See the GNU General Public License for more details. * | |
* You should have received a copy of the GNU General Public License along * | |
* with this program, if not, write to the Free Software Foundation, Inc., * | |
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * | |
* For the text or an alternative of this public license, you may reach us * | |
* ComPiere, Inc., 3600 Bridge Parkway #102, Redwood City, CA 94065, USA * | |
* or via [email protected] or http://www.compiere.org/license.html * | |
*****************************************************************************/ | |
package org.compiere.process; | |
import java.io.File; | |
import java.math.BigDecimal; | |
import java.sql.PreparedStatement; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.sql.Timestamp; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.TimeUnit; | |
import java.util.logging.Level; | |
import java.util.Map.Entry; | |
import org.compiere.common.QueryRestrictionVO; | |
import org.compiere.common.QueryVO; | |
import org.compiere.common.constants.DisplayTypeConstants; | |
import org.compiere.model.MBPartner; | |
import org.compiere.model.MClient; | |
import org.compiere.model.MConversionRate; | |
import org.compiere.model.MDocType; | |
import org.compiere.model.MInOut; | |
import org.compiere.model.MInOutLine; | |
import org.compiere.model.MInvoice; | |
import org.compiere.model.MInvoiceLine; | |
import org.compiere.model.MInvoiceSchedule; | |
import org.compiere.model.MOrder; | |
import org.compiere.model.MOrderLine; | |
import org.compiere.model.MPriceList; | |
import org.compiere.model.MProductPrice; | |
import org.compiere.model.X_C_Order; | |
import org.compiere.model.X_M_InOut; | |
import org.compiere.osg.print.ReportPdfCtl; | |
import org.compiere.print.ReportEngine; | |
import org.compiere.print.ReportServer; | |
import org.compiere.util.*; | |
import org.compiere.vos.DocActionConstants; | |
import com.audaxis.compiere.db.Util; | |
import com.audaxis.compiere.osg.model.MBPartnerProxy; | |
import com.audaxis.compiere.osg.model.MDocTypeProxy; | |
import com.audaxis.compiere.osg.model.MInOutLineProxy; | |
import com.audaxis.compiere.osg.model.MInvoiceProxy; | |
import com.audaxis.compiere.osg.model.MOrderProxy; | |
import com.audaxis.compiere.osg.util.DocumentTypeUtil; | |
import com.audaxis.compiere.osg.util.FreightInvoiceUtil; | |
import com.audaxis.compiere.osg.util.OrganizationUtil; | |
import com.audaxis.compiere.osg.util.PDFUtils; | |
import com.audaxis.compiere.osg.util.ProcessLockerWatch; | |
import com.audaxis.compiere.osg.util.ROMInvoiceCurrencyConvertor; | |
import com.audaxis.compiere.osg.util.TRInvoiceCurrencyConvertor; | |
import com.audaxis.compiere.process.ProcessStarter; | |
import com.audaxis.compiere.process.ReportBatchModeInterface; | |
import com.audaxis.compiere.process.ReportServerOutputImpl; | |
import com.audaxis.compiere.util.CompiereException; | |
/** | |
* Generate Invoices | |
* | |
* @author Jorg Janke | |
* @version $Id: InvoiceGenerate.java,v 1.2 2006/07/30 00:51:01 jjanke Exp $ | |
*/ | |
public class InvoiceGenerateV2 extends ReportServerOutputImpl implements ReportBatchModeInterface, ReportServer | |
, ZoomInterface{//Redmine 35598 | |
/** Manual Selection */ | |
private boolean p_Selection = false; | |
/** Date Invoiced */ | |
private Timestamp p_DateInvoiced = null; | |
/** Org */ | |
private int p_AD_Org_ID = 0; | |
/** BPartner */ | |
private int p_C_BPartner_ID = 0; | |
/** user */ | |
private int p_AD_User_ID = 0; | |
/** Order */ | |
private int p_C_Order_ID = 0; | |
/** Consolidate */ | |
private boolean p_ConsolidateDocument = true; | |
/** Invoice Document Action */ | |
private String p_docAction = DocActionConstants.ACTION_Complete; | |
//Redmine 35598 | |
private boolean p_print = false; | |
private ArrayList<File> m_files = new ArrayList<File>(); | |
private ReportPdfCtl m_pdfengine = null; | |
/** The current Invoice */ | |
private MInvoice m_invoice = null; | |
/** The current Shipment */ | |
private MInOut m_ship = null; | |
/** Numner of Invoices */ | |
private int m_created = 0; | |
/** Line Number */ | |
private int m_line = 0; | |
/** Business Partner */ | |
private MBPartner m_bp = null; | |
/** Date Ordered From **/ | |
private Timestamp p_DateOrdered_From = null; | |
/** Date Ordered To **/ | |
private Timestamp p_DateOrdered_To = null; | |
private Map<Integer, MInOut> invoicedShipments = null; | |
// Winfloware selection on InvoiceSchedule | |
int p_InvoiceSchedule_ID = 0; | |
// End of Winfloware | |
private StringBuffer msg = new StringBuffer(); | |
private int p_C_DocType_ID = 0;// ZCOM #26322 | |
private ArrayList<MInvoice> INVS = new ArrayList<MInvoice>();//Redmine 49943 | |
private int p_R_MailText_ID = 0;//67917 | |
/** Mail PDF */ | |
private boolean p_EMailPDF = false; //69916 | |
/** | |
* Prepare - e.g., get Parameters. | |
*/ | |
private HashMap<String, ArrayList<CollectData>> collectedData = new HashMap<String, ArrayList<CollectData>>(); | |
private class CollectData { | |
public Trx trx; | |
public Ctx ctx; | |
public int C_Order_ID; | |
} | |
private class InvoiceWorker implements Runnable{ | |
private ArrayList<CollectData> datas; | |
private Throwable error; | |
public InvoiceWorker(ArrayList<CollectData> datas) { | |
this.datas = datas; | |
} | |
@Override | |
public void run() { | |
try { | |
for(int index=0;index<datas.size();index++) { | |
CollectData data = datas.get(index); | |
MOrder order = new MOrder (data.ctx, data.C_Order_ID, data.trx); | |
// avoid re-consolidation | |
/* | |
MOrderProxy op = new MOrderProxy(order); | |
MInvoiceProxy ip = new MInvoiceProxy(m_invoice); | |
// Winfloware -- Begin | |
if (p_C_BPartner_ID == 0) | |
p_ConsolidateDocument = "Y".equals(QueryUtil.getSQLValueString(get_TrxName(), "SELECT CONSOLIDATEDOCUMENT FROM C_BPARTNER cbp WHERE cbp.C_BPARTNER_ID = ? ", order.getC_BPartner_ID())); | |
// Winfloware -- End | |
// | |
if (!romaniaInvoiceIt(op)){ | |
addLog(order.getDocumentNo() + ": No Rate found"); | |
continue; | |
} | |
// | |
//#74883 | |
Boolean ConOsgFrW0 = isConsolidateOsgFrWO(order); | |
//#74883 | |
// New Invoice Location | |
if (!p_ConsolidateDocument | |
|| (m_invoice != null | |
&& (m_invoice.getC_BPartner_Location_ID() != order.getBill_Location_ID() | |
|| m_invoice.getC_PaymentTerm_ID() != order.getC_PaymentTerm_ID() | |
|| m_invoice.getC_DocTypeTarget_ID() != MDocType.get(getCtx(), order.getC_DocType_ID()).getC_DocTypeInvoice_ID() | |
//|| ip.getCommercialDiscount().compareTo(op.getCommercialDiscount()) != 0 //ZCOM #40048 //108720 | |
|| !ConOsgFrW0) //#74883 | |
)) { | |
if (m_invoice != null) | |
log.info("***** NOT SAME Bill BPartner Location / Payment Term / Doc Type / Commercial Discount"); | |
completeInvoice(); | |
}*/ | |
boolean completeOrder = X_C_Order.INVOICERULE_AfterOrderDelivered.equals(order.getInvoiceRule()); | |
// Schedule After Delivery | |
boolean doInvoice= false; | |
if (X_C_Order.INVOICERULE_CustomerScheduleAfterDelivery.equals(order.getInvoiceRule())) | |
{ | |
m_bp = new MBPartner (getCtx(), order.getBill_BPartner_ID(), null); | |
if (m_bp.getC_InvoiceSchedule_ID() == 0) | |
{ | |
log.warning("BPartner has no Schedule - set to After Delivery"); | |
order.setInvoiceRule(X_C_Order.INVOICERULE_AfterDelivery); | |
order.save(); | |
} | |
else | |
{ | |
MInvoiceSchedule is = MInvoiceSchedule.get(getCtx(), m_bp.getC_InvoiceSchedule_ID()); | |
// Winfloware - Schedule type | |
if ( !p_Selection && is.get_ID() != p_InvoiceSchedule_ID | |
&& p_C_Order_ID <= 0 // ZCOM 37058 -- Tres rare qd on a des cas comme ca ou on connait le C_Order_ID donc on peut dire que le C_Order est prioritaire sur le invoice schedule | |
) | |
continue; // Wrong Type | |
// End Winfloware | |
if ( p_Selection || is.canInvoice(order.getDateOrdered(), order.getGrandTotal())) // Winfloware p_Selection || | |
doInvoice = true; | |
else | |
continue; | |
} | |
} // Schedule | |
// After Delivery | |
if (doInvoice || X_C_Order.INVOICERULE_AfterDelivery.equals(order.getInvoiceRule()) || X_C_Order.INVOICERULE_CustomerScheduleAfterDelivery.equals(order.getInvoiceRule())) | |
{ | |
MInOut shipment = null; | |
MInOutLine[] shipmentLines = order.Winf_getShipmentLines2Invoice(p_DateInvoiced); // Winfloware old : order.getShipmentLines(); -- do not invoice shipment newer the invoicedate | |
int inOutID = 0; | |
for (int i = 0; i < shipmentLines.length; i++) | |
{ | |
MInOutLine shipLine = shipmentLines[i]; | |
//#89073 #90767 : New Invoice | |
if (!p_ConsolidateDocument && (OrganizationUtil.isAustria(p_AD_Org_ID)||OrganizationUtil.isGmbH(p_AD_Org_ID)) | |
&& inOutID != shipLine.getM_InOut_ID()){ | |
completeInvoice(); | |
} | |
inOutID = shipLine.getM_InOut_ID(); | |
//#89073 #90767 | |
if (shipLine.isInvoiced()) | |
continue; | |
if (shipment == null | |
|| shipment.getM_InOut_ID() != shipLine.getM_InOut_ID()) | |
shipment = new MInOut(getCtx(), shipLine.getM_InOut_ID(), get_TrxName()); | |
if (!shipment.isComplete() // ignore incomplete or reversals | |
//ZCOM #11888 | |
//|| shipment.getDocStatus().equals(X_M_InOut.DOCSTATUS_Reversed) | |
) | |
continue; | |
// | |
//ZCOM999 On récupère l'erreur et on l'envoit à l'utilisateur | |
//#98931 | |
if(shipLine.getMovementQty().compareTo(BigDecimal.ZERO)==0)//#102397 | |
continue; | |
//#98931 | |
try { //ZCOM999 | |
createLine (order, shipment, shipLine); | |
//ZCOM999 | |
} catch (IllegalStateException e) { | |
log.log(Level.SEVERE, "E", e); | |
if (order != null && shipment != null && shipLine != null) { | |
msg.append("Order "+order.getDocumentNo()+ " Shipment "+shipment.getDocumentNo()+ " Shipment Line "+shipLine.getLine()); | |
msg.append("<br>"); | |
} | |
else if (order != null) { | |
msg.append("Order "+order.getDocumentNo()); | |
msg.append("<br>"); | |
} | |
ValueNamePair vnp = CLogger.retrieveError(); | |
if (vnp != null) { | |
msg.append(vnp.getName()); | |
msg.append("<br>"); | |
} | |
msg.append(e.toString()); | |
msg.append("<br>"); | |
throw e; | |
} catch (IllegalArgumentException e) { | |
log.log(Level.SEVERE, "E", e); | |
if (order != null && shipment != null && shipLine != null) { | |
msg.append("Order "+order.getDocumentNo()+ " Shipment "+shipment.getDocumentNo()+ " Shipment Line "+shipLine.getLine()); | |
msg.append("<br>"); | |
} | |
ValueNamePair vnp = CLogger.retrieveError(); | |
if (vnp != null) { | |
msg.append(vnp.getName()); | |
msg.append("<br>"); | |
} | |
msg.append(e.toString()); | |
msg.append("<br>"); | |
throw e; | |
} | |
//ZCOM999 | |
} // shipment lines | |
m_line = (int) ( m_line / 1000 ) * 1000 + 1000; // Winflo old = m_line += 1000; | |
} | |
// After Order Delivered, Immediate | |
else | |
{ | |
MOrderLine[] oLines = order.getLines(true, null); | |
for (int i = 0; i < oLines.length; i++) | |
{ | |
MOrderLine oLine = oLines[i]; | |
BigDecimal toInvoice = oLine.getQtyOrdered().subtract(oLine.getQtyInvoiced()); | |
// ZCOM 52338 | |
if ( OrganizationUtil.isTestOrderInOneShotEnabled()) | |
toInvoice = oLine.getQtyOrderedToInvoice().subtract(oLine.getQtyInvoiced()); | |
// ZCOM 52338 | |
if (toInvoice.compareTo(Env.ZERO) == 0 && oLine.getM_Product_ID() != 0) | |
continue; | |
// BigDecimal notInvoicedShipment = oLine.getQtyDelivered().subtract(oLine.getQtyInvoiced()); | |
// | |
boolean fullyDelivered = oLine.getQtyOrdered().compareTo(oLine.getQtyDelivered()) == 0; | |
// ZCOM 52338 | |
if (OrganizationUtil.isTestOrderInOneShotEnabled()) | |
fullyDelivered = oLine.getQtyOrderedToInvoice().compareTo(oLine.getQtyDelivered()) == 0; | |
// ZCOM 52338 | |
// Complete Order | |
if (completeOrder && !fullyDelivered) | |
{ | |
log.fine("Failed CompleteOrder - " + oLine); | |
completeOrder = false; | |
break; | |
} | |
// Immediate | |
else if (X_C_Order.INVOICERULE_Immediate.equals(order.getInvoiceRule())) | |
{ | |
log.fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine); | |
BigDecimal qtyEntered = toInvoice; | |
// Correct UOM for QtyEntered | |
// ZOMC 52338 | |
if ( OrganizationUtil.isTestOrderInOneShotEnabled() ){ | |
if (oLine.getQtyEnteredToInvoice().compareTo(oLine.getQtyOrderedToInvoice()) != 0 | |
&& oLine.getQtyOrderedToInvoice().compareTo(Env.ZERO) !=0) // ZCOM #24146 | |
qtyEntered = toInvoice | |
.multiply(oLine.getQtyEnteredToInvoice()) | |
.divide(oLine.getQtyOrderedToInvoice(), 12, BigDecimal.ROUND_HALF_UP); | |
createLine (order, oLine, toInvoice, qtyEntered); | |
log.info("ID "+oLine.get_ID() + "Qty Ordered " + oLine.getQtyOrderedToInvoice() + " Qty Invoiced "+oLine.getQtyInvoiced()); | |
}else{ | |
// ZCOM 52338 | |
if (oLine.getQtyEntered().compareTo(oLine.getQtyOrdered()) != 0 | |
&& oLine.getQtyOrdered().compareTo(Env.ZERO) !=0) // ZCOM #24146 | |
qtyEntered = toInvoice | |
.multiply(oLine.getQtyEntered()) | |
.divide(oLine.getQtyOrdered(), 12, BigDecimal.ROUND_HALF_UP); | |
createLine (order, oLine, toInvoice, qtyEntered); | |
log.info("ID "+oLine.get_ID() + "Qty Ordered " + oLine.getQtyOrdered() + " Qty Invoiced "+oLine.getQtyInvoiced()); | |
} // ZCOM 52338 | |
} | |
else | |
{ | |
log.fine("Failed: " + order.getInvoiceRule() | |
+ " - ToInvoice=" + toInvoice + " - " + oLine); | |
} | |
} // for all order lines | |
if (X_C_Order.INVOICERULE_Immediate.equals(order.getInvoiceRule())) | |
m_line = (int) ( m_line / 1000 ) * 1000 + 1000; // Winflo old = m_line += 1000; | |
} | |
// Complete Order successful | |
if (completeOrder && X_C_Order.INVOICERULE_AfterOrderDelivered.equals(order.getInvoiceRule())) | |
{ | |
MInOut[] shipments = order.getShipments(true); | |
for (int i = 0; i < shipments.length; i++) | |
{ | |
MInOut ship = shipments[i]; | |
if (!ship.isComplete() // ignore incomplete or reversals | |
|| ship.getDocStatus().equals(X_M_InOut.DOCSTATUS_Reversed)) | |
continue; | |
MInOutLine[] shipLines = ship.getLines(false); | |
for (int j = 0; j < shipLines.length; j++) | |
{ | |
MInOutLine shipLine = shipLines[j]; | |
if (!order.isOrderLine(shipLine.getC_OrderLine_ID())) | |
continue; | |
if (!shipLine.isInvoiced()) | |
createLine (order, ship, shipLine); | |
} // lines | |
m_line = (int) ( m_line / 1000 ) * 1000 + 1000; // Winflo old = m_line += 1000; | |
} // all shipments | |
} // complete Order | |
} // for all orders | |
if (m_invoice != null) { | |
log.info("***** FINAL Complete of Last Invoice " + m_invoice.getDocumentNo()); | |
} | |
// COMPLETE CURRENT INVOICE | |
completeInvoice(); | |
} catch (Throwable t) { | |
error = t; | |
} | |
} | |
} | |
@Override | |
protected void prepare() | |
{ | |
ProcessInfoParameter[] para = getParameter(); | |
for (int i = 0; i < para.length; i++) | |
{ | |
String name = para[i].getParameterName(); | |
if (para[i].getParameter() == null && para[i].getParameter_To() == null) | |
; | |
else if (name.equals("Selection")) | |
p_Selection = "Y".equals(para[i].getParameter()); | |
else if (name.equals("DateInvoiced")) | |
p_DateInvoiced = (Timestamp)para[i].getParameter(); | |
else if (name.equals("AD_Org_ID")) | |
p_AD_Org_ID = para[i].getParameterAsInt(); | |
else if (name.equals("C_BPartner_ID")) | |
p_C_BPartner_ID = para[i].getParameterAsInt(); | |
else if (name.equals("C_Order_ID")) | |
p_C_Order_ID = para[i].getParameterAsInt(); | |
else if (name.equals("ConsolidateDocument")) | |
p_ConsolidateDocument = "Y".equals(para[i].getParameter()); | |
else if (name.equals("DocAction")) | |
p_docAction = (String)para[i].getParameter(); | |
else if (name.equals("DateOrdered")) | |
{ | |
p_DateOrdered_From = (Timestamp)para[i].getParameter(); | |
p_DateOrdered_To = (Timestamp)para[i].getParameter_To(); | |
} | |
else if (name.equals("AD_User_ID")) | |
{ | |
p_AD_User_ID = para[i].getParameterAsInt(); | |
} | |
// ZCOM #26322 | |
else if (name.equals("C_DocType_ID")) | |
{ | |
p_C_DocType_ID = para[i].getParameterAsInt(); | |
} // ZCOM #26322 | |
// Winfloware Schedule | |
else if ( name.equals("C_InvoiceSchedule_ID")) | |
p_InvoiceSchedule_ID = para[i].getParameterAsInt(); | |
// End of Winfloware | |
else if (name.equals("Print")) | |
p_print = "Y".equals(para[i].getParameter()); // Redmine 35598 | |
//67917 | |
else if (name.equals("R_MailText_ID")) | |
p_R_MailText_ID = para[i].getParameterAsInt(); | |
//67917 | |
//69916 | |
else if (name.equals("EMailPDF")) | |
p_EMailPDF = "Y".equals(para[i].getParameter()); | |
//69916 | |
else | |
log.log(Level.SEVERE, "Unknown Parameter: " + name); | |
} | |
// Login Date | |
if (p_DateInvoiced == null) | |
p_DateInvoiced = new Timestamp(getCtx().getContextAsTime("#Date")); | |
// DocAction check | |
if (!DocActionConstants.ACTION_Complete.equals(p_docAction)) | |
p_docAction = DocActionConstants.ACTION_Prepare; | |
if (OrganizationUtil.isIberica(p_AD_Org_ID)) { | |
throw new CompiereException("OSG Iberica must use 'Generate Invoice Iberica'"); | |
} | |
} // prepare | |
/** | |
* Generate Invoices | |
* @return info | |
* @throws Exception | |
*/ | |
@Override | |
protected void buildOutputFile() //Redmine 35598 | |
{ | |
log.info("***** INVOICE GENERATE START - Selection=" + p_Selection + ", DateInvoiced=" + p_DateInvoiced | |
+ ", AD_Org_ID=" + p_AD_Org_ID + ", C_BPartner_ID=" + p_C_BPartner_ID | |
+ ", C_Order_ID=" + p_C_Order_ID + ", DocAction=" + p_docAction | |
+ ", Consolidate=" + p_ConsolidateDocument+", AD_User_ID=" + p_AD_User_ID | |
+ ", DateOrdered=" + p_DateOrdered_From + "->" + p_DateOrdered_To); | |
//Redmine 35598 | |
String result=null; | |
if ((p_R_MailText_ID > 0 && p_EMailPDF) || p_print) | |
m_pdfengine = new ReportPdfCtl(getCtx()); | |
// Pour ne pas se reposer sur getTrx() qu'un trou de balle peut avoir commité, on utilise une propre Trx ouverte du début à la fin | |
ProcessLockerWatch lockerWatch = null; | |
try { | |
// ZCOM #21321 - START - Avoid to generate twice at the same time | |
lockerWatch = new ProcessLockerWatch( | |
// ZCOM #43585 MessageUtil.AUDAXIS_BLOCK_CONCURRENT_INVOICE_GENERATION, | |
p_AD_Org_ID, ProcessLockerWatch.INVOICE_GENERATE, // ZCOM #43585 | |
"System is running, please check the result in Invoice (Customer). In case of missing pdf, please use Print Invoice Process.", | |
getCtx()); | |
lockerWatch.watch(); | |
// ZCOM #21321 - END | |
//67917 | |
// if(OrganizationUtil.isScandinavia(p_AD_Org_ID)) | |
// { | |
//Redmine #83620 : | |
//la selection des factures DK impact les factures SW (Scandinavia) dans le cas du lancement du processus au mm tps | |
//=> ajout d'un filtrage par organisation | |
DB.executeUpdate("UPDATE C_INVOICE SET IsSelected = 'N' WHERE IsSelected = 'Y' AND AD_Org_ID = ? ", p_AD_Org_ID, get_Trx());//Reset selection | |
// } | |
//67917 | |
// Winfloware - Be sure to have a Login Date | |
if (p_DateInvoiced == null) | |
p_DateInvoiced = new Timestamp(getCtx().getContextAsTime("#Date")); | |
//ZCOM OSG | |
String orderBy = "ORDER BY C_BPartner_ID, Bill_Location_ID, C_PaymentTerm_ID, C_DocTypeTarget_ID, C_Order_ID, CommercialDiscount "; // ZCOM C_DocTypeTarget_ID //#81284 | |
if (OrganizationUtil.isIbericaSpecificEnabled()) { | |
orderBy = "ORDER BY C_BPartner_ID, Bill_Location_ID, C_PaymentTerm_ID, (select dt.C_DocTypeInvoice_ID FROM C_DocType dt where dt.C_DocType_ID=C_DocTypeTarget_ID) , C_DocTypeTarget_ID, C_Order_ID, CommercialDiscount "; //#81284 | |
} | |
//ZCOM OSG | |
String sql = null; | |
if (p_Selection) // VInvoiceGen | |
{ | |
sql = "SELECT C_Order_ID FROM C_Order " | |
+ "WHERE IsSelected='Y' AND DocStatus IN('CO','CL') AND IsSOTrx='Y' AND Trunc(Coalesce(DontInvoiceBefore, SysDate), 'DD') <= TRUNC(SYSDATE,'DD') " // Winfloware | |
// Corr bug see below - no Warehouse and no priority needed + "ORDER BY M_Warehouse_ID, PriorityRule, C_BPartner_ID, Bill_Location_ID, C_PaymentTerm_ID, C_Order_ID"; // Winfloware TODO Corr Bug Bill | |
//NO Locker is not enough ! we set updatedby in GenerateInvoiceWindowImpl OSG Locker is enough | |
+ " AND UpdatedBy = " + getAD_User_ID() + " " // ZCOM216 | |
//ZCOM OSG IBERICA + "ORDER BY C_BPartner_ID, Bill_Location_ID, C_PaymentTerm_ID, C_Order_ID"; // ZCOM | |
+ orderBy; //ZCOM | |
} | |
else | |
{ | |
sql = "SELECT o.C_Order_ID FROM C_Order o " | |
+ " INNER JOIN c_doctype d on d.c_doctype_id = o.c_doctype_id " // ZCOM 52338 Test ORDER | |
+ "WHERE o.DocStatus IN('CO','CL') AND o.IsSOTrx='Y' AND Trunc(Coalesce(o.DontInvoiceBefore, SysDate), 'DD') <= TRUNC(SYSDATE,'DD') "; // Winfloware | |
// Old syntax sql += " AND o.documentno not like 'ST-%'"; // Winfloware - do not take stock transfer | |
sql += " AND o.c_doctypetarget_id in ( select c_doctype_id from c_doctype cdt where c_doctypeinvoice_id is not null "; // New syntax - Do not take orders without invoicing rule... | |
if( p_C_Order_ID <= 0 && ! OrganizationUtil.isTestOrderInOneShotEnabled() ) // ZCOM 52338 | |
sql+= " AND d.isTestOrder = 'N' "; | |
sql += ")"; // ZCOM #26322 | |
if (p_AD_Org_ID != 0) | |
sql += " AND o.AD_Org_ID=?"; | |
if (p_C_BPartner_ID != 0) | |
sql += " AND o.bill_bpartner_ID = ? "; // Winfloware BUG ! " AND C_BPartner_ID=?"; | |
if (p_C_Order_ID != 0) | |
sql += " AND o.C_Order_ID=?"; | |
if (p_DateOrdered_From != null) | |
sql+=" AND TRUNC(o.DateOrdered,'DD') >= ?"; | |
if (p_DateOrdered_To != null) | |
sql+=" AND TRUNC(o.DateOrdered,'DD') <= ?"; | |
if (p_AD_User_ID != 0) | |
sql += " AND o.AD_User_ID=?"; | |
// | |
sql += " AND EXISTS (SELECT * FROM C_OrderLine ol " | |
+ "WHERE o.C_Order_ID=ol.C_Order_ID AND ol.QtyOrdered<>ol.QtyInvoiced) " ; | |
// Correction see below - No Priority needed and no Marehouse needed + "ORDER BY M_Warehouse_ID, PriorityRule, C_BPartner_ID, Bill_Location_ID, C_PaymentTerm_ID, C_DocTypeTarget_ID,C_Order_ID"; // Winfloware C_DocTypeTarget_ID | |
//ZCOM OSG IB + "ORDER BY C_BPartner_ID, Bill_Location_ID, C_PaymentTerm_ID, C_DocTypeTarget_ID,C_Order_ID"; // ZCOM C_DocTypeTarget_ID | |
// ZCOM 52338 | |
sql += "AND ( (d.istestorder = 'N' AND d.isItTestOrder = 'N') OR EXISTS (SELECT * " | |
+ " FROM C_OrderLine ol " | |
+ " WHERE o.C_Order_ID=ol.C_Order_ID " | |
+ " AND ( ( ol.QtyOrdered<>ol.QtyInvoiced AND ol.z_isfinish = 'Y') OR (coalesce(ol.QtyToInvoice,0) > coalesce(ol.QtyInvoiced,0)))) " | |
+ " ) "; | |
// ZCOM 52338 | |
sql += orderBy; //ZCOM OSG | |
} | |
PreparedStatement pstmt = null; | |
try | |
{ | |
log.info(sql); | |
pstmt = DB.prepareStatement (sql, get_TrxName()); | |
int index = 1; | |
if (!p_Selection && p_AD_Org_ID != 0) | |
pstmt.setInt(index++, p_AD_Org_ID); | |
if (!p_Selection && p_C_BPartner_ID != 0) | |
pstmt.setInt(index++, p_C_BPartner_ID); | |
if (!p_Selection && p_C_Order_ID != 0) | |
pstmt.setInt(index++, p_C_Order_ID); | |
if (!p_Selection && p_DateOrdered_From != null) | |
pstmt.setTimestamp(index++, p_DateOrdered_From); | |
if (!p_Selection && p_DateOrdered_To != null) | |
pstmt.setTimestamp(index++, p_DateOrdered_To); | |
if (!p_Selection && p_AD_User_ID != 0) | |
pstmt.setInt(index++, p_AD_User_ID); | |
} | |
catch (Exception e) | |
{ | |
log.log(Level.SEVERE, sql, e); | |
} | |
result = generate(pstmt); | |
String filePath = null; | |
//67917 | |
if((p_R_MailText_ID > 0 && p_EMailPDF) || p_print) | |
{ | |
filePath = printInvoices(); | |
} | |
//67917 | |
//Redmine 35598 | |
addLog(result); | |
if (!GwtMode.isGwtMode(getCtx()) || !p_print) { | |
log.info("***** INVOICE GENERATE ENDS = "+ GwtMode.isGwtMode(getCtx()) + " " +p_print); | |
lockerWatch.closeSuccess(); // ZCOM 46733 | |
return; | |
} | |
if(filePath == null || filePath.equals("")){ | |
log.info("***** INVOICE GENERATE PDF MERGE START"); | |
String fileName = "U"+getCtx().getAD_User_ID() + "_" + getAD_PInstance_ID() + "_" + getOutputFileNameSimple(); | |
File file = new File(System.getProperty("java.io.tmpdir"), fileName); | |
PDFUtils.consolidatePDF(file, getCtx(), m_files); | |
log.info("***** INVOICE GENERATE PDF MERGE START"); | |
//69916 | |
}else{ | |
File f = new File(filePath); | |
String fileName = "U"+getCtx().getAD_User_ID() + "_" + getAD_PInstance_ID() + "_" + getOutputFileNameSimple(); | |
File file = new File(System.getProperty("java.io.tmpdir"), fileName); | |
f.renameTo(file); | |
} | |
//69916 | |
lockerWatch.closeSuccess(); // ZCOM 46733 | |
} catch (Exception e) { | |
lockerWatch.rollback(); | |
throw new CompiereException(e); | |
} finally { | |
lockerWatch.close(); | |
} | |
log.info("INVOICE GENERATE END"); | |
} // doIt | |
//67917 | |
/************************************************************************** | |
* Print Invoices | |
* @throws Exception | |
*/ | |
private String printInvoices() throws Exception | |
{ | |
ProcessStarter ps = new ProcessStarter(getCtx(), InvoicePrint.class, get_Trx()); | |
ps.addParameter("AD_Org_ID", p_AD_Org_ID, null); | |
ps.addParameter("IsSOTrx", "Y", null); | |
ps.addParameter("IncludeDraftInvoices", "N", null); | |
ps.addParameter("EMailPDF", p_EMailPDF ? "Y" : "N" , null); //69916 | |
ps.addParameter("R_MailText_ID", p_R_MailText_ID, null); | |
ps.addParameter("RePrint", "N", null); | |
ps.addParameter("INVOICES"," i.IsSelected = 'Y' ", null); | |
log.info ("AD_Org_ID=" + p_AD_Org_ID | |
+ ", IncludeDraftInvoices=" + "N" | |
+ ", IsSOTrx=" + "Y" | |
+ ", EmailPDF=" + p_EMailPDF + ",R_MailText_ID=" + p_R_MailText_ID | |
+ ", RePrint=" + "N" ); | |
try { | |
ps.start(); | |
} catch (Exception e) { | |
throw e; | |
} | |
String out = ps.getOutput(); | |
log.info("Print Invoices "+out); | |
return ps.getOutputFiles().get(0); //69916 | |
} // printInvoices | |
//67917 | |
/** | |
* Generate Shipments | |
* @param pstmt order query | |
* @return info | |
*/ | |
private String generate (PreparedStatement pstmt) throws Exception { | |
log.info("*****START*****"); | |
try | |
{ | |
int indexY = 0; | |
ResultSet rs = pstmt.executeQuery (); | |
while (rs.next ()) { | |
MOrder order = new MOrder (getCtx(), rs.getInt(1), get_TrxName()); | |
MOrderProxy op = new MOrderProxy(order); | |
Boolean ConOsgFrW0 = isConsolidateOsgFrWO(order); | |
CollectData data = new CollectData(); | |
data.ctx = getCtx(); | |
data.trx = get_Trx(); | |
data.C_Order_ID = rs.getInt(1); | |
if (! p_ConsolidateDocument) { | |
String key = String.valueOf(Boolean.toString(p_ConsolidateDocument) + "-" + | |
order.getBill_Location_ID() + "-" + | |
order.getC_PaymentTerm_ID() + "-" + | |
MDocType.get(getCtx(), order.getC_DocType_ID()).getC_DocTypeInvoice_ID() + "-" + | |
Boolean.toString(ConOsgFrW0)); | |
this.collectedData.put(key, new ArrayList<CollectData>()); | |
this.collectedData.get(key).add(data); | |
} else { | |
String key = String.valueOf(Boolean.toString(p_ConsolidateDocument) + "-" + | |
order.getBill_Location_ID() + "-" + | |
order.getC_PaymentTerm_ID() + "-" + | |
MDocType.get(getCtx(), order.getC_DocType_ID()).getC_DocTypeInvoice_ID() + "-" + | |
Boolean.toString(ConOsgFrW0)); | |
if (this.collectedData.get(key) == null) { | |
this.collectedData.put(key, new ArrayList<CollectData>()); | |
} | |
System.out.println("Key ::" + indexY++ + " :: " + key); | |
this.collectedData.get(key).add(data); | |
} | |
} | |
rs.close (); | |
pstmt.close (); | |
pstmt = null; | |
} | |
catch (SQLException e) | |
{ | |
throw new CompiereException(e); | |
} | |
finally { | |
Util.closeCursor(pstmt, null); | |
} | |
log.info("*****END*****"); | |
// ************ Thread Execution [ ************* // | |
if(collectedData.size() > 0) { | |
int nbThread = Integer.parseInt(Msg.getMsg(Language.AD_Language_en_US, "AUDAXIS_MAX_THREAD")); | |
ArrayList<InvoiceWorker> workers = new ArrayList<InvoiceWorker>(); | |
ExecutorService executor = Executors.newFixedThreadPool(nbThread); | |
for(Entry<String, ArrayList<CollectData>> entry : collectedData.entrySet()) { | |
InvoiceWorker worker = new InvoiceWorker(entry.getValue()); | |
workers.add(worker); | |
executor.submit(worker); | |
} | |
System.out.println("All tasks submitted"); | |
executor.shutdown(); | |
executor.awaitTermination(1, TimeUnit.DAYS); | |
System.out.println("All tasks completed"); | |
} | |
// ************ ] Thread Execution ************* // | |
//ZCOM999 return "@Created@ = " + m_created; | |
//ZCOM999 | |
msg.append("@Created@ = " + m_created); | |
return msg.toString(); | |
//ZCOM999 | |
} // generate | |
/************************************************************************** | |
* Create Invoice Line from Order Line | |
* | |
* USED IF INVOICE RULE IMMEDIATE | |
*/ | |
private void createLine (MOrder order, MOrderLine orderLine, | |
BigDecimal qtyInvoiced, BigDecimal qtyEntered) | |
{ | |
// #14025 : [OSG DK] 3 Permettre de bloquer la facturation de certaines lignes de commande client | |
if(orderLine.get_ValueAsString("ZZ_BlockInvoicing").equalsIgnoreCase("Y")) | |
return; | |
// #14025 : [OSG DK] 3 Permettre de bloquer la facturation de certaines lignes de commande client | |
if (m_invoice == null) | |
{ | |
m_invoice = new MInvoice (order, 0, p_DateInvoiced); | |
// ZCOM #26322 | |
if(p_C_DocType_ID > 0 ) { | |
m_invoice.setC_DocType_ID(p_C_DocType_ID); | |
m_invoice.setC_DocTypeTarget_ID(p_C_DocType_ID); | |
} | |
//Redmine 52751 | |
if (m_invoice.getAD_Org_ID()==OrganizationUtil.OSG_ROMANIA_ID) | |
m_invoice.setRomaniaInvoiceFinancial(); | |
// | |
// ZCOM #26322 | |
if (!m_invoice.save()) | |
throw new IllegalStateException("Could not create Invoice (o)"); | |
log.info("***** NEW INVOICE "+m_invoice.getDocumentNo()); | |
} | |
log.info("***** "+order.getDocumentNo()+ " "+orderLine.getLine() + " - "+qtyInvoiced); | |
// | |
MInvoiceLine line = new MInvoiceLine (m_invoice); | |
line.setOrderLine(orderLine); | |
line.setQtyInvoiced(qtyInvoiced); | |
line.setQtyEntered(qtyEntered); | |
//108720 | |
MOrderProxy orderProxy = new MOrderProxy(order); | |
line.set_Value("CommercialDiscount", orderProxy.getCommercialDiscount()); | |
//108720 | |
line.setLine( ++m_line ) ; // Winflo old line.setLine(m_line + orderLine.getLine()); | |
log.info("**** 100"); | |
if (!line.save()) | |
throw new IllegalStateException("Could not create Invoice Line (o)"); | |
log.info("**** 200"); | |
log.info("***** NEW LINE "+line.getLine() + line.getQtyInvoiced()); | |
} // createLine | |
/** | |
* Create Invoice Line from Shipment | |
* @param order order | |
* @param ship shipment header | |
* @param sLine shipment line | |
*/ | |
private void createLine (MOrder order, MInOut ship, MInOutLine sLine) | |
{ | |
// #14025 : [OSG DK] 3 Permettre de bloquer la facturation de certaines lignes de commande client | |
MOrderLine oLine = new MOrderLine(getCtx(),sLine.getC_OrderLine_ID(), get_Trx()); | |
if(oLine.get_ValueAsString("ZZ_BlockInvoicing").equalsIgnoreCase("Y")) | |
return; | |
// #14025 : [OSG DK] 3 Permettre de bloquer la facturation de certaines lignes de commande client | |
//Redmine 38935 | |
if(OrganizationUtil.isIbericaSpecificEnabled() | |
&& ship.get_ValueAsString("ZZ_BlockInvoicing").equalsIgnoreCase("Y")) | |
return; | |
// | |
if (m_invoice == null) | |
{ | |
m_invoice = new MInvoice (order, 0, p_DateInvoiced); | |
// ZCOM #26322 | |
if(p_C_DocType_ID > 0 ) { | |
m_invoice.setC_DocType_ID(p_C_DocType_ID); | |
m_invoice.setC_DocTypeTarget_ID(p_C_DocType_ID); | |
} | |
//Redmine 52751 | |
if (m_invoice.getAD_Org_ID()==OrganizationUtil.OSG_ROMANIA_ID) | |
m_invoice.setRomaniaInvoiceFinancial(); | |
// | |
// ZCOM #26322 | |
if (!m_invoice.save()) | |
throw new IllegalStateException("Could not create Invoice (s)"); | |
log.info("***** NEW INVOICE "+m_invoice.getDocumentNo()); | |
//Evolution #10232 (1): create a map of the shipments that have already created a FREIGHT line in this process | |
invoicedShipments = new HashMap<Integer, MInOut>(); | |
} | |
// Create Shipment Comment Line | |
if (m_ship == null | |
|| m_ship.getM_InOut_ID() != ship.getM_InOut_ID()) | |
{ | |
m_line = (int) ( m_line / 1000 ) * 1000 + 1000; // Winflo - separate by shipement | |
MDocType dt = MDocType.get(getCtx(), ship.getC_DocType_ID()); | |
if (m_bp == null || m_bp.getC_BPartner_ID() != ship.getC_BPartner_ID()) | |
m_bp = new MBPartner (getCtx(), ship.getC_BPartner_ID(), get_TrxName()); | |
// Reference: Delivery: 12345 - 12.12.12 | |
MClient client = MClient.get(getCtx(), order.getAD_Client_ID ()); | |
String AD_Language = client.getAD_Language(); | |
if (client.isMultiLingualDocument() && m_bp.getAD_Language() != null) | |
AD_Language = m_bp.getAD_Language(); | |
if (AD_Language == null) | |
AD_Language = Language.getBaseAD_Language(); | |
java.text.SimpleDateFormat format = DisplayType.getDateFormat | |
(DisplayTypeConstants.Date, Language.getLanguage(AD_Language)); | |
String reference = dt.getPrintName(m_bp.getAD_Language()) | |
+ ": " + ship.getDocumentNo() | |
+ " - " + format.format(ship.getMovementDate()); | |
m_ship = ship; | |
//ZCOM #13208 ne pas générer de ligne de description pour les exped VOIDED | |
if (! DocActionConstants.STATUS_Voided.equalsIgnoreCase(m_ship.getDocStatus()) | |
&& ! DocActionConstants.STATUS_Reversed.equalsIgnoreCase(m_ship.getDocStatus())) { | |
MInvoiceLine line = new MInvoiceLine (m_invoice); | |
line.setIsDescription(true); | |
line.setDescription(reference); | |
// Winfloware deactivate : line.setLine(m_line + sLine.getLine() - 2); | |
if ( m_line == 0 ) m_line = 1000; | |
line.setLine( ++m_line ); // Winfloware | |
// End of Winfloware | |
log.info("**** 1000"); | |
if (!line.save()) | |
throw new IllegalStateException("Could not create Invoice Comment Line (sh)"); | |
log.info("****2000"); | |
log.info("***** NEW LINE COMMENT "+line.getLine() + line.getQtyInvoiced()); | |
//=============================START: FREIGHT HANDLING ============================== | |
MInOut currentShip = invoicedShipments.get(ship.getM_InOut_ID()); | |
if(currentShip == null) { | |
FreightInvoiceUtil fu = new FreightInvoiceUtil(ship); | |
MInvoiceLine il = new MInvoiceLine(m_invoice); | |
boolean ok = fu.setFreightInfo(il, m_line); | |
if (ok) { | |
invoicedShipments.put(ship.getM_InOut_ID(), ship); | |
} | |
} | |
else { | |
log.info("***** NEW LINE FREIGHT Shipment " + currentShip.getDocumentNo() + " has already been charged for freight costs !"); | |
} | |
//=============================END: FREIGHT HANDLING ============================== | |
} | |
} | |
// ZCOM 52338 | |
boolean isTestOrder = false; | |
BigDecimal QtyInvoiced = Env.ZERO; | |
if ( sLine != null ) | |
QtyInvoiced = sLine.getMovementQty(); | |
// ZCOM 52338; | |
//ZCOM #13208 ne pas générer de ligne de facture si la qté est 0 et qu'on vient un shipment VO ou RE | |
if (ship == null | |
|| DocActionConstants.STATUS_Completed.equalsIgnoreCase(ship.getDocStatus()) | |
|| DocActionConstants.STATUS_Closed.equalsIgnoreCase(ship.getDocStatus()) | |
// || (DocActionConstants.STATUS_Reversed.equalsIgnoreCase(ship.getDocStatus()) && Env.ZERO.compareTo(sLine.getMovementQty()) != 0) | |
// || (DocActionConstants.STATUS_Voided.equalsIgnoreCase(ship.getDocStatus()) && Env.ZERO.compareTo(sLine.getMovementQty()) != 0) | |
) { | |
//ZCOM SCA GO LIVE | |
// Ici on crée le prix de l'article sur la liste de prix GO LIVE (uniquement) comme cela on peut facturer | |
log.info("***** 1"); | |
try { | |
MPriceList pl = new MPriceList(getCtx(), m_invoice.getM_PriceList_ID(), get_TrxName()); | |
if (pl != null && pl.getName() != null && pl.getName().startsWith("GO LIVE")) { | |
if (sLine.getM_Product_ID() > 0) { | |
int plvid = QueryUtil.getSQLValue(get_TrxName(), "SELECT MAX(M_PriceList_Version_ID) FROM M_PriceList_Version where M_PriceList_ID = ? ", m_invoice.getM_PriceList_ID()); | |
if (plvid > 0) { | |
// !! a faire hors Trx car MProductPricing travaille hors Trx !! | |
MProductPrice pp = new MProductPrice(getCtx(), plvid, sLine.getM_Product_ID(),null); | |
pp.setPrices(oLine.getPriceList(), oLine.getPriceActual(), Env.ZERO); | |
pp.save(); | |
} | |
} | |
} | |
} catch (Throwable t) { | |
log.log(Level.SEVERE, "TTT", t.getMessage()); | |
} | |
log.info("***** 2"); | |
//ZCOM SCA GO LIVE | |
log.info("***** ORDER "+order.getDocumentNo()+ " "+oLine.getLine() + " - "+oLine); | |
MInvoiceLine line = new MInvoiceLine (m_invoice); | |
log.info("***** 3"); | |
line.setShipLine(sLine); | |
BigDecimal QtyEntered = sLine.getQtyEntered(); | |
//ZCOM #40842 52338 | |
if ( OrganizationUtil.isTestOrderInOneShotEnabled() && order != null && oLine != null) { | |
MDocType docType = MDocType.get(getCtx(), order.getC_DocType_ID()); | |
if ( docType != null ) { | |
MDocTypeProxy docTypeProxy = new MDocTypeProxy(docType); | |
if ( docTypeProxy.isTestOrder() || docTypeProxy.isItTestOrder()){ //73174 | |
isTestOrder = true; | |
BigDecimal QtyToInvoice = oLine.getQtyOrderedToInvoice(); | |
QtyEntered = QtyToInvoice.subtract(oLine.getQtyInvoiced()).min(QtyInvoiced); | |
QtyInvoiced = QtyToInvoice.subtract(oLine.getQtyInvoiced()).min(QtyInvoiced); | |
//87629 | |
if(isTestOrder && QtyToInvoice.compareTo(Env.ZERO)<=0) | |
return; | |
// | |
} | |
} | |
}// ZCOM #40842 52338 | |
line.setQtyEntered(QtyEntered); | |
line.setQtyInvoiced(QtyInvoiced); | |
line.setLine( ++m_line ); // Winflo line.setLine(m_line + sLine.getLine()); | |
line.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); | |
//108720 | |
MOrderProxy orderProxy = new MOrderProxy(order); | |
line.set_Value("CommercialDiscount", orderProxy.getCommercialDiscount()); | |
//108720 | |
log.info("***** 4"); | |
if (!line.save()) { | |
String msg = "Could not create Invoice Line (s)"; | |
//ZCOM VNP is better | |
ValueNamePair vnp = CLogger.retrieveError(); | |
if (vnp != null) | |
msg = vnp.getName(); | |
throw new IllegalStateException(msg); | |
} | |
log.info("***** NEW LINE "+line.getLine() + line.getQtyInvoiced()); | |
} //ZCOM #13208 | |
// #13208 RE and VO shipments will no more appear on Invoice | |
// Link | |
// ZCOM 52338 | |
if ( OrganizationUtil.isTestOrderInOneShotEnabled() && isTestOrder ) { | |
MInOutLineProxy sLineProxy = new MInOutLineProxy(sLine); | |
BigDecimal qtyAllreadyInvoiced = sLineProxy.getQtyInvoiced(); | |
if ( (qtyAllreadyInvoiced.add(QtyInvoiced)).compareTo(sLine.getMovementQty()) >= 0 || oLine.isFinish()) | |
sLine.setIsInvoiced(true); | |
}else { | |
// ZCOM 52338 | |
sLine.setIsInvoiced(true); | |
}// ZCOM 52338 | |
if (!sLine.save()) | |
throw new IllegalStateException("Could not update Shipment Line"); | |
} // createLine | |
/** | |
* Complete Invoice | |
*/ | |
private void completeInvoice() | |
{ | |
if (m_invoice != null) | |
{ | |
log.info("***** COMPLETE INVOICE START "+m_invoice.getDocumentNo()); | |
//ZCOM #27879 On doit convertir la facture en TKL | |
if (m_invoice.getAD_Org_ID() == OrganizationUtil.OSG_TURKEY_ID) { | |
TRInvoiceCurrencyConvertor conv = new TRInvoiceCurrencyConvertor(m_invoice); | |
m_invoice = conv.convert(); | |
} | |
//ZCOM #27879 | |
//Redmine 52561 | |
MInvoiceProxy invp = new MInvoiceProxy(m_invoice); | |
// if (m_invoice.getAD_Org_ID() == OrganizationUtil.OSG_ROMANIA_ID) { //Redmine 57790 | |
if (invp.isInvCurrencyFromPartner()) { | |
ROMInvoiceCurrencyConvertor conv = new ROMInvoiceCurrencyConvertor(m_invoice); | |
m_invoice = conv.convert(); | |
} | |
//Redmine 52561 | |
//#41948 | |
if(m_invoice.isReturnTrx()){ | |
m_invoice.setIsDiscountPrinted(true); | |
}//#41948 | |
//#74883 | |
if((OrganizationUtil.isFrance(m_invoice.getAD_Org_ID()) || OrganizationUtil.isUK(m_invoice.getAD_Org_ID()))&& m_invoice.isSOTrx()) | |
CreateDiscount(); | |
//#74883 | |
this.commit();//111928 | |
boolean processOK = m_invoice.processIt(p_docAction); | |
m_invoice.save(); | |
this.commit();//108279 | |
log.info("***** COMPLETE INVOICE END "+m_invoice.getDocumentNo()); | |
if (processOK) | |
addLog(m_invoice.getC_Invoice_ID(), m_invoice.getDateInvoiced(), null, m_invoice.getDocumentNo()); | |
else | |
{ | |
log.warning("***** FAIL TO COMPLETE " + m_invoice.getDocumentNo()); | |
String msg = Msg.getMsg(getCtx(), "Error") + " " + m_invoice.getDocumentNo(); | |
addLog(m_invoice.getC_Invoice_ID(), m_invoice.getDateInvoiced(), null, msg); | |
} | |
m_created++; | |
//Redmine 35598 | |
if (processOK && p_print && (!OrganizationUtil.isScandinavia(p_AD_Org_ID) || p_R_MailText_ID == 0)){ | |
log.info("***** PDF INVOICE START "+m_invoice.getDocumentNo()); | |
File f = m_pdfengine.startDocumentPdf(getCtx(), ReportEngine.INVOICE, m_invoice.getC_Invoice_ID()); | |
m_invoice.setIsPrinted(false); | |
m_files.add(f); | |
log.info("***** PDF INVOICE END "+m_invoice.getDocumentNo()); | |
} | |
//67917 | |
if(processOK) | |
{ | |
m_invoice.set_Value("IsSelected", "Y"); | |
m_invoice.save(); | |
} | |
//67917 | |
//Redmine 49943 | |
INVS.add(m_invoice); | |
// | |
log.info("***** COMMIT"); | |
this.commit(); // Added by Winfloware | |
} | |
this.commit(); | |
m_invoice = null; | |
m_ship = null; | |
m_line = 0; | |
} // completeInvoice | |
@Override | |
protected String getOutputFileNameSimple() { | |
return "Invoice.pdf"; | |
} | |
@Override | |
public void addZoomInfo() { | |
QueryVO Query = new QueryVO(); | |
int AD_Window_ID = 167; | |
QueryRestrictionVO rest = null; | |
for (MInvoice po : INVS) { | |
rest = new QueryRestrictionVO(); | |
rest.ColumnName="DocumentNo"; | |
rest.Code = po.getDocumentNo(); | |
rest.DisplayType = DisplayTypeConstants.String; | |
Query.addRestriction(rest); | |
} | |
getProcessInfo().setQueryVO(Query); | |
getProcessInfo().setZoomWindow_ID(AD_Window_ID); | |
getProcessInfo().setIsDirectZoom(false); | |
} | |
private boolean romaniaInvoiceIt(MOrderProxy op){ | |
if (OrganizationUtil.OSG_ROMANIA_ID!=op.getPO().getAD_Org_ID()) | |
return true; | |
if (op.isInvCurrencyFromPartner() | |
&& op.getPO().getC_Currency_ID() != op.getC_InvoiceCurrency_ID()){ | |
Timestamp convdate = op.getPO().get_ValueAsTimestamp("InvConversionDate") == null | |
? new Timestamp(getCtx().getContextAsTime("#Date")) | |
: op.getPO().get_ValueAsTimestamp("InvConversionDate"); | |
BigDecimal rate = MConversionRate.getRate(op.getPO().getC_Currency_ID(), op.getC_InvoiceCurrency_ID(), | |
convdate, op.getPO().getC_ConversionType_ID(), | |
op.getPO().getAD_Client_ID(), op.getPO().getAD_Org_ID()); | |
if (rate == null) | |
return false; | |
} | |
return true; | |
} | |
//#74883 | |
public void CreateDiscount(){ | |
BigDecimal discPct = Env.ZERO; | |
int remiseID = 0; | |
MOrder order = new MOrder(getCtx(), m_invoice.getC_Order_ID(), get_Trx()); | |
if(order != null){ | |
remiseID = Integer.parseInt(Msg.getMsg(Language.AD_Language_en_US, "OSG_GLOBAL_DISCOUNT_PRODUCT_ID")); | |
if (remiseID > 0){ | |
if (order.get_ValueAsBD("BreakDiscount") != null && order.get_ValueAsBD("BreakDiscount").compareTo(BigDecimal.ZERO) == 1){ | |
discPct = order.get_ValueAsBD("BreakDiscount"); | |
} | |
} | |
} | |
m_invoice.set_ValueNoCheck("BreakDiscount", discPct); | |
//96071 | |
MBPartner bp = new MBPartner(getCtx(), order.getC_BPartner_ID(),get_Trx()); | |
if(OrganizationUtil.isUK(order.getAD_Org_ID()) && order.getC_DocType_ID() == DocumentTypeUtil.DOC_TYPE_SO_WEB_ORDER //uk and web store order | |
&& bp.get_ValueAsBoolean("IsSpecialWebDisc") | |
&& bp.get_ValueAsBD("WebDiscPct") !=null && bp.get_ValueAsBD("WebDiscPct").compareTo(BigDecimal.ZERO)>0 //web discount bigger than 0 | |
&& (order.getDateOrdered().before(bp.get_ValueAsTimestamp("DateWebTo")) && order.getDateOrdered().after(bp.get_ValueAsTimestamp("DateWebFrom")))){ | |
discPct=discPct.add(bp.get_ValueAsBD("WebDiscPct")); | |
} | |
if (discPct.compareTo(BigDecimal.ZERO) != 0 && remiseID > 0 ){ | |
String sql1 = "SELECT C_INVOICELINE_ID FROM C_INVOICELINE WHERE C_INVOICE_ID = ? AND M_PRODUCT_ID = ? "; | |
int invoiceLineID = DB.getSQLValue(get_Trx(), sql1, m_invoice.getID(), remiseID); | |
String sql = "SELECT SUM(LineNetAmt) FROM C_InvoiceLine WHERE C_Invoice_ID = ? AND M_Product_ID <> ? "; | |
BigDecimal amtTotFact = DB.getSQLValueBD(get_TrxName(), sql, m_invoice.getC_Invoice_ID(), remiseID); | |
if (amtTotFact != null && amtTotFact.compareTo(BigDecimal.ZERO) != 0){ | |
if(invoiceLineID==-1){ | |
MInvoiceLine line = new MInvoiceLine (m_invoice); | |
line.setM_Product_ID(remiseID); | |
line.setQtyInvoiced(new BigDecimal("-1")); | |
line.setQtyEntered(new BigDecimal("-1")); | |
if(OrganizationUtil.isUK(order.getAD_Org_ID())){ | |
line.setDescription("Web Store promotion and bp uk special web discount " + discPct + " % "); | |
} | |
else{ | |
line.setDescription("Web Store promotion " + discPct + " % "); | |
} | |
line.setPriceEntered(amtTotFact.multiply(discPct).movePointLeft(2)); | |
line.setPriceActual(amtTotFact.multiply(discPct).movePointLeft(2)); | |
line.setPrice(line.getPriceActual()); | |
line.save(); | |
}else{ | |
MInvoiceLine line = new MInvoiceLine (getCtx(),invoiceLineID,get_Trx()); | |
line.setPriceEntered(amtTotFact.multiply(discPct).movePointLeft(2)); | |
line.setPriceActual(amtTotFact.multiply(discPct).movePointLeft(2)); | |
line.setPrice(line.getPriceActual()); | |
if(OrganizationUtil.isUK(order.getAD_Org_ID())){ | |
line.setDescription("Web Store promotion and bp uk special web discount " + discPct + " % "); | |
} | |
else{ | |
line.setDescription("Web Store promotion " + discPct + " % "); | |
} | |
line.save(); | |
} | |
} | |
} | |
} | |
private Boolean isConsolidateOsgFrWO(MOrder order){ | |
MBPartner bp = new MBPartner(getCtx(), order.getC_BPartner_ID(), get_Trx()); | |
MBPartnerProxy bpp = new MBPartnerProxy(bp); | |
if((OrganizationUtil.isFrance(bp.getAD_Org_ID()) || OrganizationUtil.isUK(bp.getAD_Org_ID())) && order.getC_DocType_ID() == DocumentTypeUtil.DOC_TYPE_SO_WEB_ORDER | |
&& bpp.getIsAccelerateDiscount() && order.get_ValueAsBD("BreakDiscount") != null | |
&& order.get_ValueAsBD("BreakDiscount").compareTo(BigDecimal.ZERO) == 1){ | |
return false; | |
} | |
return true; | |
} | |
//#74883 | |
} // InvoiceGenerate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment