/// <summary> /// Create Cash Journal Line /// </summary> /// <param name="invoice">Invoice</param> /// <param name="C_InvoicePaySchedule_ID">Invoice Payemt Schedule</param> /// <param name="amt">Amount</param> public void CreateCashLine(MInvoice invoice, int C_InvoicePaySchedule_ID, decimal amt) { SetC_Invoice_ID(invoice.GetC_Invoice_ID()); SetC_InvoicePaySchedule_ID(C_InvoicePaySchedule_ID); SetCashType(CASHTYPE_Invoice); SetC_BPartner_ID(invoice.GetC_BPartner_ID()); // JID_0687: System is not updating the Location on cash journal line in cases of POS order and payment method cash SetC_BPartner_Location_ID(invoice.GetC_BPartner_Location_ID()); SetC_Currency_ID(invoice.GetC_Currency_ID()); // Amount MDocType dt = MDocType.Get(GetCtx(), invoice.GetC_DocType_ID()); if (MDocBaseType.DOCBASETYPE_APINVOICE.Equals(dt.GetDocBaseType()) || MDocBaseType.DOCBASETYPE_ARCREDITMEMO.Equals(dt.GetDocBaseType())) { amt = Decimal.Negate(amt); SetVSS_PAYMENTTYPE("P"); } else { SetVSS_PAYMENTTYPE("R"); } SetAmount(amt); // SetDiscountAmt(Env.ZERO); SetWriteOffAmt(Env.ZERO); SetIsGenerated(true); _invoice = invoice; }
/// <summary> /// Set Invoice - no discount /// </summary> /// <param name="invoice">Invoice</param> public void SetInvoice(MInvoice invoice) { Decimal amt = 0; SetC_Invoice_ID(invoice.GetC_Invoice_ID()); SetCashType(CASHTYPE_Invoice); SetC_BPartner_ID(invoice.GetC_BPartner_ID()); // JID_0687: System is not updating the Location on cash journal line in cases of POS order and payment method cash SetC_BPartner_Location_ID(invoice.GetC_BPartner_Location_ID()); SetC_Currency_ID(invoice.GetC_Currency_ID()); // Amount MDocType dt = MDocType.Get(GetCtx(), invoice.GetC_DocType_ID()); if (invoice.GetRef_C_Invoice_ID() > 0) { //amt = Decimal.Negate(Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT SUM(Al.Amount) FROM c_allocationline al INNER JOIN c_allocationhdr alhdr ON alhdr.c_allocationhdr_ID=al.c_allocationhdr_ID " // + " WHERE alhdr.isactive ='Y' AND Alhdr.Docstatus IN ('CO','CL') and al.c_invoice_id=" + invoice.GetRef_C_Invoice_ID()))); // get amount against invoice wheether cash journal is completed or not // Done by Vivek on 01/03/2016 amt = Decimal.Negate(Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT SUM(cl.Amount) FROM C_CashLine cl INNER JOIN C_Cash cs ON cs.C_Cash_ID=CL.C_CASH_ID WHERE cl.C_Invoice_ID=" + invoice.GetRef_C_Invoice_ID() + " AND cs.DocStatus NOT IN ('VO') "))); } else { amt = invoice.GetGrandTotal(); } if (MDocBaseType.DOCBASETYPE_APINVOICE.Equals(dt.GetDocBaseType()) || MDocBaseType.DOCBASETYPE_ARCREDITMEMO.Equals(dt.GetDocBaseType())) { amt = Decimal.Negate(amt); // set payment type according to invoice document type SetVSS_PAYMENTTYPE("P"); } else { // set payment type according to invoice document type SetVSS_PAYMENTTYPE("R"); } SetAmount(amt); // SetDiscountAmt(Env.ZERO); SetWriteOffAmt(Env.ZERO); SetIsGenerated(true); _invoice = invoice; }
} // prepare /// <summary> /// Perform Process. /// </summary> /// <returns>Message (clear text)</returns> protected override String DoIt() { int index = 1; StringBuilder sql = new StringBuilder("SELECT * " + "FROM S_TimeExpense e " + "WHERE e.Processed='Y'" + " AND e.AD_Client_ID=@param1"); // #1 if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1) { index++; sql.Append(" AND e.C_BPartner_ID=@param2"); // #2 } if (_DateFrom != null) { index++; sql.Append(" AND e.DateReport >=@param3"); // #3 } if (_DateTo != null) { index++; sql.Append(" AND e.DateReport <=@param4"); // #4 } // JID_0868 // chanegs done by Bharat on 12 September 2018 to handle the case if invoice is created with an expense for the selected Business Partner sql.Append(" AND EXISTS (SELECT * FROM S_TimeExpenseLine el " + "WHERE e.S_TimeExpense_ID=el.S_TimeExpense_ID" + " AND el.C_InvoiceLine_ID IS NULL" + " AND el.ConvertedAmt<>0) " + "ORDER BY e.C_BPartner_ID, e.S_TimeExpense_ID"); // int old_BPartner_ID = -1; MInvoice invoice = null; MTimeExpense te = null; // //PreparedStatement pstmt = null; SqlParameter[] param = new SqlParameter[index]; IDataReader idr = null; DataTable dt = null; try { //pstmt = DataBase.prepareStatement (sql.toString (), get_TrxName()); int par = 0; //pstmt.setInt(par++, getAD_Client_ID()); param[0] = new SqlParameter("@param1", GetAD_Client_ID()); if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1) { par++; //pstmt.setInt (par++, _C_BPartner_ID); param[par] = new SqlParameter("@param2", _C_BPartner_ID); } if (_DateFrom != null) { par++; //pstmt.setTimestamp (par++, _DateFrom); param[par] = new SqlParameter("@param3", _DateFrom); } if (_DateTo != null) { par++; //pstmt.setTimestamp (par++, _DateTo); param[par] = new SqlParameter("@param4", _DateTo); } //ResultSet rs = pstmt.executeQuery (); idr = DataBase.DB.ExecuteReader(sql.ToString(), param, Get_TrxName()); dt = new DataTable(); dt.Load(idr); idr.Close(); if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) // ********* Expense Line Loop { te = new MTimeExpense(GetCtx(), dr, Get_TrxName()); // New BPartner - New Order // if (te.GetC_BPartner_ID() != old_BPartner_ID) { CompleteInvoice(invoice, te); MBPartner bp = new MBPartner(GetCtx(), te.GetC_BPartner_ID(), Get_TrxName()); log.Info("New Invoice for " + bp); invoice = new MInvoice(GetCtx(), 0, Get_TrxName()); invoice.SetBPartner(bp); if (invoice.GetC_BPartner_Location_ID() == 0) { log.Log(Level.SEVERE, "No BP Location: " + bp); AddLog(0, te.GetDateReport(), null, "No Location: " + te.GetDocumentNo() + " " + bp.GetName()); invoice = null; break; } // Siddheshwar: added a code to check for payment method if null if (bp.GetVA009_PO_PaymentMethod_ID() <= 0) { paymethod = GetPaymentMethod(te); if (paymethod <= 0) { if (!noPayMethEmp.Contains(bp.GetC_BPartner_ID())) { noPayMethEmp.Add(bp.GetC_BPartner_ID()); if (string.IsNullOrEmpty(bpNameNoPM)) { bpNameNoPM = bp.GetName(); } else { bpNameNoPM += bp.GetName() + ", "; } return(Msg.GetMsg(GetCtx(), "NoPayMethEmp") + bpNameNoPM); } } else { invoice.SetVA009_PaymentMethod_ID(paymethod); } } else { //JID_1783_1 if active paymentMethod not found ,then dont create the invoice. if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM VA009_PaymentMethod WHERE VA009_PaymentMethod_ID=" + bp.GetVA009_PO_PaymentMethod_ID(), null, Get_Trx())).Equals("Y")) { invoice.SetVA009_PaymentMethod_ID(bp.GetVA009_PO_PaymentMethod_ID()); } else { return(Msg.GetMsg(GetCtx(), "IsActivePaymentMethodInv"));; } } // Checking payment term if (bp.GetPO_PaymentTerm_ID() <= 0) { payterm = GetPaymentTerm(te); if (payterm <= 0) { if (!PayTermEmp.Contains(bp.GetC_BPartner_ID())) { PayTermEmp.Add(bp.GetC_BPartner_ID()); if (string.IsNullOrEmpty(bpNamePT)) { bpNamePT = bp.GetName(); } else { bpNamePT += bp.GetName() + ", "; } return(Msg.GetMsg(GetCtx(), "NoPayTerm") + bpNamePT); } } else { invoice.SetC_PaymentTerm_ID(payterm); } } else { //JID_1783_1 if active paymentTerm not found ,then dont create the invoice. if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM C_PaymentTerm WHERE C_PaymentTerm_ID=" + bp.GetPO_PaymentTerm_ID(), null, Get_Trx())).Equals("Y")) { invoice.SetC_PaymentTerm_ID(bp.GetPO_PaymentTerm_ID()); } else { return(Msg.GetMsg(GetCtx(), "IsActivePaymentTermInv")); } } invoice.SetIsExpenseInvoice(true); //added by arpit asked by Surya Sir on DEC 28,2015 invoice.SetClientOrg(te.GetAD_Client_ID(), te.GetAD_Org_ID()); //invoice.SetVA009_PaymentMethod_ID(bp.GetVA009_PO_PaymentMethod_ID()); // JID_0868 // chanegs done by Bharat on 12 September 2018 to set the document type where Expense Invoice checkbox is true. // String qry = "SELECT C_DocType_ID FROM C_DocType " //+ "WHERE AD_Client_ID=@param1 AND DocBaseType=@param2" //+ " AND IsActive='Y' AND IsExpenseInvoice = 'Y' " //+ "ORDER BY C_DocType_ID DESC , IsDefault DESC"; String qry = "SELECT C_DocType_ID FROM C_DocType " + "WHERE AD_Client_ID=" + GetAD_Client_ID() + @" AND DocBaseType='" + MDocBaseType.DOCBASETYPE_APINVOICE + @"'" + " AND IsActive='Y' AND IsExpenseInvoice = 'Y' AND AD_Org_ID IN(0," + te.GetAD_Org_ID() + ") " + " ORDER BY AD_Org_ID Desc, C_DocType_ID DESC , IsDefault DESC"; //int C_DocType_ID = DB.GetSQLValue(null, qry, GetAD_Client_ID(), MDocBaseType.DOCBASETYPE_APINVOICE); int C_DocType_ID = Util.GetValueOfInt(DB.ExecuteScalar(qry)); if (C_DocType_ID <= 0) { log.Log(Level.SEVERE, "Not found for AC_Client_ID=" + GetAD_Client_ID() + " - " + MDocBaseType.DOCBASETYPE_APINVOICE); return(Msg.GetMsg(GetCtx(), "NoDocTypeExpInvoice")); } else { log.Fine(MDocBaseType.DOCBASETYPE_APINVOICE); } invoice.SetC_DocTypeTarget_ID(C_DocType_ID); //invoice.SetC_DocTypeTarget_ID(MDocBaseType.DOCBASETYPE_APINVOICE); // API //commented by Arpit on Jan 4,2015 Mentis issue no. 0000310 //invoice.SetDocumentNo(te.GetDocumentNo()); // invoice.SetM_PriceList_ID(te.GetM_PriceList_ID()); invoice.SetSalesRep_ID(te.GetDoc_User_ID()); String descr = Msg.Translate(GetCtx(), "S_TimeExpense_ID") + ": " + te.GetDocumentNo() + " " + DisplayType.GetDateFormat(DisplayType.Date).Format(te.GetDateReport()); invoice.SetDescription(descr); if (!invoice.Save()) { return(GetRetrievedError(invoice, "Cannot save Invoice")); // new Exception("Cannot save Invoice"); } //added by arpit asked by Surya Sir on 29/12/2015******* else { old_BPartner_ID = bp.GetC_BPartner_ID(); } //end*************** } // JID_0868 //Description include all document numbers which is come from Time And Expense Recording window to expense invoice in case of multiple records else if (old_BPartner_ID > 0) { String descr = invoice.GetDescription() + "\n" + Msg.Translate(GetCtx(), "S_TimeExpense_ID") + ": " + te.GetDocumentNo() + " " + DisplayType.GetDateFormat(DisplayType.Date).Format(te.GetDateReport()); invoice.SetDescription(descr); } MTimeExpenseLine[] tel = te.GetLines(false); for (int i = 0; i < tel.Length; i++) { MTimeExpenseLine line = tel[i]; // Already Invoiced or nothing to be reimbursed if (line.GetC_InvoiceLine_ID() != 0 || Env.ZERO.CompareTo(line.GetQtyReimbursed()) == 0 || Env.ZERO.CompareTo(line.GetPriceReimbursed()) == 0) { continue; } // Update Header info if (line.GetC_Activity_ID() != 0 && line.GetC_Activity_ID() != invoice.GetC_Activity_ID()) { invoice.SetC_Activity_ID(line.GetC_Activity_ID()); } if (line.GetC_Campaign_ID() != 0 && line.GetC_Campaign_ID() != invoice.GetC_Campaign_ID()) { invoice.SetC_Campaign_ID(line.GetC_Campaign_ID()); } if (line.GetC_Project_ID() != 0 && line.GetC_Project_ID() != invoice.GetC_Project_ID()) { invoice.SetC_Project_ID(line.GetC_Project_ID()); } if (!invoice.Save()) { return(GetRetrievedError(invoice, "Cannot save Invoice")); //new Exception("Cannot save Invoice"); } // Create OrderLine MInvoiceLine il = new MInvoiceLine(invoice); // if (line.GetM_Product_ID() != 0) { il.SetM_Product_ID(line.GetM_Product_ID(), true); } //added by arpit asked by Surya Sir on 28/12/2015_____*************************** if (line.GetC_Charge_ID() != 0) { il.SetC_Charge_ID(line.GetC_Charge_ID()); } //end here ***************************** il.SetQty(line.GetQtyReimbursed()); // Entered/Invoiced il.SetDescription(line.GetDescription()); // il.SetC_Project_ID(line.GetC_Project_ID()); il.SetC_ProjectPhase_ID(line.GetC_ProjectPhase_ID()); il.SetC_ProjectTask_ID(line.GetC_ProjectTask_ID()); il.SetC_Activity_ID(line.GetC_Activity_ID()); il.SetC_Campaign_ID(line.GetC_Campaign_ID()); // // il.setPrice(); // not really a list/limit price for reimbursements il.SetPrice(line.GetPriceReimbursed()); // il.SetC_UOM_ID(line.GetC_UOM_ID()); // JID_0868 // chanegs done by Bharat on 12 September 2018 to set the Amount in List price column. il.SetPriceList(line.GetPriceReimbursed()); il.SetTax(); if (!il.Save()) { return(GetRetrievedError(il, "Cannot save Invoice")); //new Exception("Cannot save Invoice Line"); } // Update TEL line.SetC_InvoiceLine_ID(il.GetC_InvoiceLine_ID()); line.SetIsInvoiced(true); line.Save(); } // for all expense lines } } else { message = Msg.GetMsg(GetCtx(), "NoRecForInv"); } // ********* Expense Line Loop dt = null; //dt.Clear(); } catch (Exception e) { if (dt != null) { dt = null; } if (idr != null) { idr.Close(); } log.Log(Level.SEVERE, sql.ToString(), e); } finally { if (dt != null) { dt = null; } if (idr != null) { idr.Close(); } } CompleteInvoice(invoice, te); //if (_noInvoices == 0) //{ // message = " @No Record Found for Invoice Creation@"; //} //Code for Showing Message when PaymentTerm is null if (!string.IsNullOrEmpty(bpNamePT)) { message += Msg.GetMsg(GetCtx(), "NoPayTerm") + bpNamePT + "\n"; } //code for showing Error Message when Invoice is not completed if (!string.IsNullOrEmpty(bpNameInvoice)) { message += Msg.GetMsg(GetCtx(), "NoInvoiceCreated") + bpNameInvoice + "\n"; } if (!string.IsNullOrEmpty(bpNameNoPM)) { message = Msg.GetMsg(GetCtx(), "NoPayMethEmp") + bpNameNoPM + "\n"; } if (_noInvoices > 0) { message += "" + _noInvoices + " " + Msg.GetMsg(GetCtx(), "VIS_InvGenerated"); } //return "" + _noInvoices + " @Invoices Generated Successfully@"; return(message); } // doIt
/** * Generate Shipments * @param pstmt order query * @return info */ private String Generate(IDataReader idr) { DataTable dt = new DataTable(); try { dt.Load(idr); idr.Close(); foreach (DataRow dr in dt.Rows)// while (dr.next ()) { MOrder order = new MOrder(GetCtx(), dr, Get_TrxName()); // New Invoice Location if (!_ConsolidateDocument || (_invoice != null && (_invoice.GetC_BPartner_Location_ID() != order.GetBill_Location_ID() || _invoice.GetC_PaymentTerm_ID() != order.GetC_PaymentTerm_ID()))) { CompleteInvoice(); } bool completeOrder = MOrder.INVOICERULE_AfterOrderDelivered.Equals(order.GetInvoiceRule()); // Schedule After Delivery bool doInvoice = false; if (MOrder.INVOICERULE_CustomerScheduleAfterDelivery.Equals(order.GetInvoiceRule())) { _bp = new MBPartner(GetCtx(), order.GetBill_BPartner_ID(), null); if (_bp.GetC_InvoiceSchedule_ID() == 0) { log.Warning("BPartner has no Schedule - set to After Delivery"); order.SetInvoiceRule(MOrder.INVOICERULE_AfterDelivery); order.Save(); } else { MInvoiceSchedule ins = MInvoiceSchedule.Get(GetCtx(), _bp.GetC_InvoiceSchedule_ID(), Get_TrxName()); if (ins.CanInvoice(order.GetDateOrdered(), order.GetGrandTotal())) { doInvoice = true; } else { continue; } } } // Schedule // After Delivery if (doInvoice || MOrder.INVOICERULE_AfterDelivery.Equals(order.GetInvoiceRule())) { MInOut shipment = null; MInOutLine[] shipmentLines = order.GetShipmentLines(); for (int i = 0; i < shipmentLines.Length; i++) { MInOutLine shipLine = shipmentLines[i]; 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 shipment.GetDocStatus().Equals(MInOut.DOCSTATUS_Reversed)) { continue; } // CreateLine(order, shipment, shipLine); } // shipment lines _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]; Decimal toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced()); if (toInvoice.CompareTo(Env.ZERO) == 0 && oLine.GetM_Product_ID() != 0) { continue; } // bool fullyDelivered = oLine.GetQtyOrdered().CompareTo(oLine.GetQtyDelivered()) == 0; // Complete Order if (completeOrder && !fullyDelivered) { log.Fine("Failed CompleteOrder - " + oLine); completeOrder = false; break; } // Immediate else if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule())) { log.Fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine); Decimal qtyEntered = toInvoice; // Correct UOM for QtyEntered if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0) { qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply( toInvoice, oLine.GetQtyEntered()), oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero); } // if (oLine.IsContract() == false) { CreateLine(order, oLine, toInvoice, qtyEntered); log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced()); } } else { log.Fine("Failed: " + order.GetInvoiceRule() + " - ToInvoice=" + toInvoice + " - " + oLine); } } // for all order lines if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule())) { _line += 1000; } } // Complete Order successful if (completeOrder && MOrder.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(MInOut.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 _line += 1000; } // all shipments } // complete Order } // for all orders } catch (Exception e) { if (idr != null) { idr.Close(); } log.Log(Level.SEVERE, "", e); } finally { if (idr != null) { idr.Close(); } dt = null; } CompleteInvoice(); return("@Created@ = " + _created); }
// Create Asset From Invoice Mohit /** * Shipment Constructor * @param Invoice * @param shipLine shipment line * @param deliveryCount 0 or number of delivery */ public MAsset(MInvoice invoice, MInvoiceLine invoiceline, int deliveryCount) : this(invoiceline.GetCtx(), 0, invoiceline.Get_TrxName()) { SetClientOrg(invoiceline); SetValueNameDescription(invoice, invoiceline, deliveryCount); // Header //SetIsOwned(true); SetC_BPartner_ID(invoice.GetC_BPartner_ID()); SetC_BPartner_Location_ID(invoice.GetC_BPartner_Location_ID()); SetAD_User_ID(invoice.GetAD_User_ID()); //SetM_Locator_ID(invoice.GetM_Locator_ID()); SetIsInPosession(true); SetAssetServiceDate(invoice.GetDateAcct()); // Line MProduct product = invoiceline.GetProduct(); SetM_Product_ID(product.GetM_Product_ID()); SetA_Asset_Group_ID(product.GetA_Asset_Group_ID()); //////////////////////////////* //Changes for vafam // SetAssetServiceDate(shipment.GetMovementDate()); //SetGuaranteeDate(TimeUtil.AddDays(shipment.GetMovementDate(), product.GetGuaranteeDays())); MAssetGroup _assetGroup = new MAssetGroup(GetCtx(), GetA_Asset_Group_ID(), invoice.Get_TrxName()); if (_assetGroup.IsOwned()) { SetIsOwned(true); //SetC_BPartner_ID(0); } if (_assetGroup.IsDepreciated()) { SetIsDepreciated(true); SetIsFullyDepreciated(false); } //////////////////////////////////// //Change by Sukhwinder for setting Asset type and amortization template on Asset window, MANTIS ID:1762 int countVA038 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA038_' ")); int countVAFAM = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VAFAM_' ")); if (countVA038 > 0) { Set_Value("VA038_AmortizationTemplate_ID", Utility.Util.GetValueOfInt(_assetGroup.Get_Value("VA038_AmortizationTemplate_ID"))); } if (countVAFAM > 0) { Set_Value("VAFAM_AssetType", _assetGroup.Get_Value("VAFAM_AssetType").ToString()); Set_Value("VAFAM_DepreciationType_ID", Utility.Util.GetValueOfInt(_assetGroup.Get_Value("VAFAM_DepreciationType_ID"))); } //////////////////////////////////// // Guarantee & Version SetGuaranteeDate(TimeUtil.AddDays(invoice.GetDateInvoiced(), product.GetGuaranteeDays())); SetVersionNo(product.GetVersionNo()); if (invoiceline.GetM_AttributeSetInstance_ID() != 0) // Instance { MAttributeSetInstance asi = new MAttributeSetInstance(GetCtx(), invoiceline.GetM_AttributeSetInstance_ID(), Get_TrxName()); SetM_AttributeSetInstance_ID(asi.GetM_AttributeSetInstance_ID()); SetLot(asi.GetLot()); SetSerNo(asi.GetSerNo()); } SetHelp(invoiceline.GetDescription()); // Qty int units = product.GetSupportUnits(); if (units == 0) { units = 1; } if (deliveryCount != 0) // one asset per UOM { SetQty(invoiceline.GetQtyEntered(), units); } else { SetQty((Decimal)units); } SetM_InOutLine_ID(invoiceline.GetM_InOutLine_ID()); Set_Value("C_InvoiceLine_ID", invoiceline.GetC_InvoiceLine_ID()); // Activate MAssetGroup ag = MAssetGroup.Get(GetCtx(), GetA_Asset_Group_ID()); if (!ag.IsCreateAsActive()) { SetIsActive(false); } }
/// <summary> /// Generate Invoices /// </summary> /// <param name="idr">pstmt order query</param> /// <returns>info</returns> //private String Generate(IDataReader idr) private String Generate(DataTable dt) { //JID_1139 Avoided the duplicate charge line created Invoice(customer) bool isAllownonItem = Util.GetValueOfString(GetCtx().GetContext("$AllowNonItem")).Equals("Y"); foreach (DataRow dr in dt.Rows) { MOrder order = new MOrder(GetCtx(), dr, Get_TrxName()); // Credit Limit check MBPartner bp = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID()); if (bp.GetCreditStatusSettingOn() == "CH") { decimal creditLimit = bp.GetSO_CreditLimit(); string creditVal = bp.GetCreditValidation(); if (creditLimit != 0) { decimal creditAvlb = creditLimit - bp.GetSO_CreditUsed(); if (creditAvlb <= 0) { if (creditVal == "C" || creditVal == "D" || creditVal == "F") { AddLog(Msg.GetMsg(GetCtx(), "StopInvoice") + bp.GetName()); continue; } else if (creditVal == "I" || creditVal == "J" || creditVal == "L") { if (_msg != null) { _msg.Clear(); } _msg.Append(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName()); //AddLog(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName()); } } } } // JID_0161 // change here now will check credit settings on field only on Business Partner Header // Lokesh Chauhan 15 July 2019 else if (bp.GetCreditStatusSettingOn() == X_C_BPartner.CREDITSTATUSSETTINGON_CustomerLocation) { MBPartnerLocation bpl = new MBPartnerLocation(GetCtx(), order.GetC_BPartner_Location_ID(), null); //MBPartner bpartner = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID()); //if (bpl.GetCreditStatusSettingOn() == "CL") //{ decimal creditLimit = bpl.GetSO_CreditLimit(); string creditVal = bpl.GetCreditValidation(); if (creditLimit != 0) { decimal creditAvlb = creditLimit - bpl.GetSO_CreditUsed(); if (creditAvlb <= 0) { if (creditVal == "C" || creditVal == "D" || creditVal == "F") { AddLog(Msg.GetMsg(GetCtx(), "StopInvoice") + bp.GetName() + " " + bpl.GetName()); continue; } else if (creditVal == "I" || creditVal == "J" || creditVal == "L") { if (_msg != null) { _msg.Clear(); } _msg.Append(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName() + " " + bpl.GetName()); //AddLog(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName() + " " + bpl.GetName()); } } } //} } // Credit Limit End // New Invoice Location // JID_1237 : While creating invoice need to consolidate order on the basis of Org, Payment Term, BP Location (Bill to Location) and Pricelist. if (!_ConsolidateDocument || (_invoice != null && (_invoice.GetC_BPartner_Location_ID() != order.GetBill_Location_ID() || _invoice.GetC_PaymentTerm_ID() != order.GetC_PaymentTerm_ID() || _invoice.GetM_PriceList_ID() != order.GetM_PriceList_ID() || _invoice.GetAD_Org_ID() != order.GetAD_Org_ID() || ((_invoice.GetC_ConversionType_ID() != 0 ? _invoice.GetC_ConversionType_ID() : defaultConversionType) != (order.GetC_ConversionType_ID() != 0 ? order.GetC_ConversionType_ID() : defaultConversionType)) ))) { CompleteInvoice(); } bool completeOrder = MOrder.INVOICERULE_AfterOrderDelivered.Equals(order.GetInvoiceRule()); // Schedule After Delivery bool doInvoice = false; if (MOrder.INVOICERULE_CustomerScheduleAfterDelivery.Equals(order.GetInvoiceRule())) { _bp = new MBPartner(GetCtx(), order.GetBill_BPartner_ID(), null); if (_bp.GetC_InvoiceSchedule_ID() == 0) { log.Warning("BPartner has no Schedule - set to After Delivery"); order.SetInvoiceRule(MOrder.INVOICERULE_AfterDelivery); order.Save(); } else { MInvoiceSchedule ins = MInvoiceSchedule.Get(GetCtx(), _bp.GetC_InvoiceSchedule_ID(), Get_TrxName()); if (ins.CanInvoice(order.GetDateOrdered(), order.GetGrandTotal())) { doInvoice = true; } else { continue; } } } // Schedule // After Delivery if (doInvoice || MOrder.INVOICERULE_AfterDelivery.Equals(order.GetInvoiceRule())) { MInOut shipment = null; MInOutLine[] shipmentLines = order.GetShipmentLines(); MOrderLine[] oLines = order.GetLines(true, null); for (int i = 0; i < shipmentLines.Length; i++) { MInOutLine shipLine = shipmentLines[i]; 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 shipment.GetDocStatus().Equals(MInOut.DOCSTATUS_Reversed)) { continue; } //JID_1139 Avoided the duplicate charge records if (shipLine.GetM_Product_ID() > 0 || isAllownonItem) { CreateLine(order, shipment, shipLine); } }// shipment lines //JID_1139 Avoided the duplicate charge records if (!isAllownonItem) { for (int i = 0; i < oLines.Length; i++) { MOrderLine oLine = oLines[i]; if (oLine.GetC_Charge_ID() > 0) { Decimal toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced()); log.Fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine); Decimal qtyEntered = toInvoice; // Correct UOM for QtyEntered if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0) { qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply( toInvoice, oLine.GetQtyEntered()), oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero); } //JID_1139_1 avoided the charge line with 0 qty inserted if (oLine.IsContract() == false && oLine.GetQtyOrdered() > oLine.GetQtyInvoiced()) { CreateLine(order, oLine, toInvoice, qtyEntered); log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced()); } } } } } // After Order Delivered, Immediate else { MOrderLine[] oLines = order.GetLines(true, null); for (int i = 0; i < oLines.Length; i++) { MOrderLine oLine = oLines[i]; Decimal toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced()); if (toInvoice.CompareTo(Env.ZERO) == 0 && oLine.GetM_Product_ID() != 0) { continue; } // bool fullyDelivered = oLine.GetQtyOrdered().CompareTo(oLine.GetQtyDelivered()) == 0; //JID_1136: While creating the Invoices against the charge system should not check the Ordered qty= Delivered qty. need to check this only in case of products if (completeOrder && oLine.GetC_Charge_ID() > 0) { fullyDelivered = true; if (oLine.GetC_Charge_ID() > 0) { log.Fine("After Order Delivery - ToInvoice=" + toInvoice + " - " + oLine); Decimal qtyEntered = toInvoice; // Correct UOM for QtyEntered if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0) { qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply( toInvoice, oLine.GetQtyEntered()), oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero); } // if (oLine.IsContract() == false && !isAllownonItem) { CreateLine(order, oLine, toInvoice, qtyEntered); log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced()); } } } // Complete Order if (completeOrder && !fullyDelivered) { log.Fine("Failed CompleteOrder - " + oLine); completeOrder = false; break; } // Immediate else if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule())) { log.Fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine); Decimal qtyEntered = toInvoice; // Correct UOM for QtyEntered if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0) { qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply( toInvoice, oLine.GetQtyEntered()), oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero); } // if (oLine.IsContract() == false) { CreateLine(order, oLine, toInvoice, qtyEntered); log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced()); } } else { log.Fine("Failed: " + order.GetInvoiceRule() + " - ToInvoice=" + toInvoice + " - " + oLine); } } // for all order lines if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule())) { _line += 1000; } } // Complete Order successful if (completeOrder && MOrder.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(MInOut.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 _line += 1000; } // all shipments } // complete Order } // for all orders CompleteInvoice(); return("@Created@ = " + _created); }
/// <summary> /// Create actual Payment /// </summary> /// <param name="C_Invoice_ID">invoice</param> /// <param name="C_BPartner_ID">partner ignored when invoice exists</param> /// <param name="C_Currency_ID">currency</param> /// <param name="stmtAmt">statement amount</param> /// <param name="trxAmt">transaction amt</param> /// <param name="C_BankAccount_ID">bank account</param> /// <param name="dateTrx">transaction date</param> /// <param name="dateAcct">accounting date</param> /// <param name="description">description</param> /// <param name="AD_Org_ID"></param> /// <param name="C_ConversionType_ID">C_ConversionType_ID</param> /// <param name="C_Order_ID">C_Order_ID</param> /// <returns>payment</returns> private MPayment CreatePayment(int C_Invoice_ID, int C_BPartner_ID, int C_Currency_ID, Decimal stmtAmt, Decimal trxAmt, int C_BankAccount_ID, DateTime?dateTrx, DateTime?dateAcct, String description, int AD_Org_ID, int C_ConversionType_ID, int C_Order_ID) { // Trx Amount = Payment overwrites Statement Amount if defined Decimal payAmt = trxAmt; if (Env.ZERO.CompareTo(payAmt) == 0) { payAmt = stmtAmt; } if (C_Invoice_ID == 0 && C_Order_ID == 0 && (Env.ZERO.CompareTo(payAmt) == 0)) { throw new Exception("@PayAmt@ = 0"); } //if (payAmt == null) //{ // payAmt = Env.ZERO; //} // MPayment payment = new MPayment(GetCtx(), 0, Get_Trx()); payment.SetAD_Org_ID(AD_Org_ID); payment.SetC_BankAccount_ID(C_BankAccount_ID); //payment.SetTenderType(MPayment.TENDERTYPE_Check);//not required it will update on MPayment class //Get the C_ConversionType_ID from BankStatementLine and Set C_ConversionType_ID for Payment payment.SetC_ConversionType_ID(C_ConversionType_ID); if (dateTrx != null) { payment.SetDateTrx(dateTrx); } else if (dateAcct != null) { payment.SetDateTrx(dateAcct); } if (dateAcct != null) { payment.SetDateAcct(dateAcct); } else { payment.SetDateAcct(payment.GetDateTrx()); } payment.SetDescription(description); // if (C_Invoice_ID != 0) { MInvoice invoice = new MInvoice(GetCtx(), C_Invoice_ID, Get_Trx()); //Used Trx payment.SetC_DocType_ID(invoice.IsSOTrx()); // Receipt payment.SetC_BPartner_ID(invoice.GetC_BPartner_ID()); //set the BPartner Location from the Invoice payment.SetC_BPartner_Location_ID(invoice.GetC_BPartner_Location_ID()); //set the PaymentMethod by the reference of Invoice payment.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID()); payment.SetC_Currency_ID(invoice.GetC_Currency_ID()); decimal _dueAmt = 0; string _sql = "SELECT * FROM C_InvoicePaySchedule WHERE VA009_PAIDAMNT IS NULL AND VA009_IsPaid = 'N' AND IsActive = 'Y' AND C_Invoice_ID =" + invoice.GetC_Invoice_ID(); DataSet _ds = DB.ExecuteDataset(_sql, null, Get_Trx()); if (_ds != null && _ds.Tables[0].Rows.Count == 1) { payment.SetC_Invoice_ID(invoice.GetC_Invoice_ID());//set Invoice Reference payment.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[0]["C_INVOICEPAYSCHEDULE_ID"])); _dueAmt = Util.GetValueOfDecimal(_ds.Tables[0].Rows[0]["DUEAMT"]); //Set PayAmt -ve sign Incase of DocBaseType APC or ARC - IsReturnTrx is true //Set PayAmt +ve sign Incase of DocBaseType API or ARI - IsReturnTrx is false if (!invoice.IsReturnTrx()) { payment.SetPayAmt(_dueAmt); } else // payment is likely to be negative { payment.SetPayAmt(Decimal.Negate(_dueAmt)); } if (!payment.Save(Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); //to get Exact Error Message first get Value from GetName() else GetValue() string error = pp != null?pp.GetName() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.GetValue() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.ToString() : ""; } } _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved"; return(null); } } else if (_ds != null && _ds.Tables[0].Rows.Count > 1) { if (!payment.Save(Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); //to get Exact Error Message first get Value from GetName() else GetValue() string error = pp != null?pp.GetName() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.GetValue() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.ToString() : ""; } } _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved"; return(null); } else { //Initialize the Object for MPaymentAllocate class MPaymentAllocate PayAlocate = null; for (int i = 0; _ds.Tables[0].Rows.Count > i; i++) { //Create the Object for MPaymentAllocate class for every Iteration PayAlocate = new MPaymentAllocate(GetCtx(), 0, Get_Trx()); PayAlocate.SetC_Payment_ID(payment.GetC_Payment_ID()); PayAlocate.SetAD_Client_ID(payment.GetAD_Client_ID()); //set Organization with the reference of Bank Account PayAlocate.SetAD_Org_ID(payment.GetAD_Org_ID());//set Org_ID from the Header PayAlocate.SetC_Invoice_ID(invoice.GetC_Invoice_ID()); PayAlocate.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[i]["C_INVOICEPAYSCHEDULE_ID"])); //Set PayAmt -ve sign Incase of DocBaseType APC or ARC - IsReturnTrx is true //Set PayAmt +ve sign Incase of DocBaseType API or ARI - IsReturnTrx is false if (!invoice.IsReturnTrx()) { PayAlocate.SetInvoiceAmt(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"])); PayAlocate.SetAmount(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"])); } else { PayAlocate.SetInvoiceAmt(-1 * Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"])); PayAlocate.SetAmount(-1 * Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"])); } if (!PayAlocate.Save(Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); //to get Exact Error Message first get Value from GetName() else GetValue() string error = pp != null?pp.GetName() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.GetValue() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.ToString() : ""; } } _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved"; return(null); } } } } } else if (C_Order_ID > 0 && C_BPartner_ID > 0) // Create Payment for prePayOrder reference { MOrder order = new MOrder(GetCtx(), C_Order_ID, Get_Trx()); payment.SetC_Order_ID(C_Order_ID); payment.SetC_DocType_ID(order.IsSOTrx()); // Receipt payment.SetC_BPartner_ID(order.GetC_BPartner_ID()); payment.SetC_BPartner_Location_ID(order.GetC_BPartner_Location_ID()); payment.SetC_Currency_ID(order.GetC_Currency_ID()); payment.SetVA009_PaymentMethod_ID(order.GetVA009_PaymentMethod_ID()); payment.SetPayAmt(order.GetGrandTotal()); if (!payment.Save(Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); //to get Exact Error Message first get Value from GetName() else GetValue() string error = pp != null?pp.GetName() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.GetValue() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.ToString() : ""; } } _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved"; return(null); } } else { _message = "VA012_ReferenceNotfoundtoCreatePayment"; return(null); } //Commit the Transaction Get_Trx().Commit(); //Call Complete Method to Complete the Record //149 is AD_Process_ID for C_Payment_Process _message = CompletePayment(GetCtx(), payment.GetC_Payment_ID(), 149, MPayment.DOCACTION_Complete); if (!string.IsNullOrEmpty(_message)) { return(null); } return(payment); }
} // prepare /// <summary> /// Perform Process. /// </summary> /// <returns>Message (clear text)</returns> protected override String DoIt() { int index = 1; StringBuilder sql = new StringBuilder("SELECT * " + "FROM S_TimeExpense e " + "WHERE e.Processed='Y'" + " AND e.AD_Client_ID=@param1"); // #1 if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1) { index++; sql.Append(" AND e.C_BPartner_ID=@param2"); // #2 } if (_DateFrom != null) { index++; sql.Append(" AND e.DateReport >=@param3"); // #3 } if (_DateTo != null) { index++; sql.Append(" AND e.DateReport <=@param4"); // #4 } // JID_0868 // chanegs done by Bharat on 12 September 2018 to handle the case if invoice is created with an expense for the selected Business Partner sql.Append(" AND EXISTS (SELECT * FROM S_TimeExpenseLine el " + "WHERE e.S_TimeExpense_ID=el.S_TimeExpense_ID" + " AND el.C_InvoiceLine_ID IS NULL" + " AND el.ConvertedAmt<>0) " + "ORDER BY e.C_BPartner_ID, e.S_TimeExpense_ID"); // int old_BPartner_ID = -1; MInvoice invoice = null; // //PreparedStatement pstmt = null; SqlParameter[] param = new SqlParameter[index]; IDataReader idr = null; DataTable dt = null; try { //pstmt = DataBase.prepareStatement (sql.toString (), get_TrxName()); int par = 0; //pstmt.setInt(par++, getAD_Client_ID()); param[0] = new SqlParameter("@param1", GetAD_Client_ID()); if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1) { par++; //pstmt.setInt (par++, _C_BPartner_ID); param[par] = new SqlParameter("@param2", _C_BPartner_ID); } if (_DateFrom != null) { par++; //pstmt.setTimestamp (par++, _DateFrom); param[par] = new SqlParameter("@param3", _DateFrom); } if (_DateTo != null) { par++; //pstmt.setTimestamp (par++, _DateTo); param[par] = new SqlParameter("@param4", _DateTo); } //ResultSet rs = pstmt.executeQuery (); idr = DataBase.DB.ExecuteReader(sql.ToString(), param, Get_TrxName()); dt = new DataTable(); dt.Load(idr); idr.Close(); foreach (DataRow dr in dt.Rows) // ********* Expense Line Loop { MTimeExpense te = new MTimeExpense(GetCtx(), dr, Get_TrxName()); // New BPartner - New Order if (te.GetC_BPartner_ID() != old_BPartner_ID) { CompleteInvoice(invoice); MBPartner bp = new MBPartner(GetCtx(), te.GetC_BPartner_ID(), Get_TrxName()); // log.Info("New Invoice for " + bp); invoice = new MInvoice(GetCtx(), 0, null); invoice.SetIsExpenseInvoice(true); //added by arpit asked by Surya Sir on DEC 28,2015 invoice.SetClientOrg(te.GetAD_Client_ID(), te.GetAD_Org_ID()); // JID_0868 // chanegs done by Bharat on 12 September 2018 to set the document type where Expense Invoice checkbox is true. String qry = "SELECT C_DocType_ID FROM C_DocType " + "WHERE AD_Client_ID=@param1 AND DocBaseType=@param2" + " AND IsActive='Y' AND IsExpenseInvoice = 'Y' " + "ORDER BY C_DocType_ID DESC , IsDefault DESC"; int C_DocType_ID = DB.GetSQLValue(null, qry, GetAD_Client_ID(), MDocBaseType.DOCBASETYPE_APINVOICE); if (C_DocType_ID <= 0) { log.Log(Level.SEVERE, "Not found for AC_Client_ID=" + GetAD_Client_ID() + " - " + MDocBaseType.DOCBASETYPE_APINVOICE); } else { log.Fine(MDocBaseType.DOCBASETYPE_APINVOICE); } invoice.SetC_DocTypeTarget_ID(C_DocType_ID); //invoice.SetC_DocTypeTarget_ID(MDocBaseType.DOCBASETYPE_APINVOICE); // API //commented by Arpit on Jan 4,2015 Mentis issue no. 0000310 //invoice.SetDocumentNo(te.GetDocumentNo()); // invoice.SetBPartner(bp); if (invoice.GetC_BPartner_Location_ID() == 0) { log.Log(Level.SEVERE, "No BP Location: " + bp); AddLog(0, te.GetDateReport(), null, "No Location: " + te.GetDocumentNo() + " " + bp.GetName()); invoice = null; break; } invoice.SetM_PriceList_ID(te.GetM_PriceList_ID()); invoice.SetSalesRep_ID(te.GetDoc_User_ID()); String descr = Msg.Translate(GetCtx(), "S_TimeExpense_ID") + ": " + te.GetDocumentNo() + " " + DisplayType.GetDateFormat(DisplayType.Date).Format(te.GetDateReport()); invoice.SetDescription(descr); if (!invoice.Save()) { //return GetReterivedError(invoice, "Cannot save Invoice"); new Exception("Cannot save Invoice"); } //added by arpit asked by Surya Sir on 29/12/2015******* else { old_BPartner_ID = bp.GetC_BPartner_ID(); } //end*************** } // JID_0868 //Description include all document numbers which is come from Time And Expense Recording window to expense invoice in case of multiple records else if (old_BPartner_ID > 0) { String descr = invoice.GetDescription() + "\n" + Msg.Translate(GetCtx(), "S_TimeExpense_ID") + ": " + te.GetDocumentNo() + " " + DisplayType.GetDateFormat(DisplayType.Date).Format(te.GetDateReport()); invoice.SetDescription(descr); } MTimeExpenseLine[] tel = te.GetLines(false); for (int i = 0; i < tel.Length; i++) { MTimeExpenseLine line = tel[i]; // Already Invoiced or nothing to be reimbursed if (line.GetC_InvoiceLine_ID() != 0 || Env.ZERO.CompareTo(line.GetQtyReimbursed()) == 0 || Env.ZERO.CompareTo(line.GetPriceReimbursed()) == 0) { continue; } // Update Header info if (line.GetC_Activity_ID() != 0 && line.GetC_Activity_ID() != invoice.GetC_Activity_ID()) { invoice.SetC_Activity_ID(line.GetC_Activity_ID()); } if (line.GetC_Campaign_ID() != 0 && line.GetC_Campaign_ID() != invoice.GetC_Campaign_ID()) { invoice.SetC_Campaign_ID(line.GetC_Campaign_ID()); } if (line.GetC_Project_ID() != 0 && line.GetC_Project_ID() != invoice.GetC_Project_ID()) { invoice.SetC_Project_ID(line.GetC_Project_ID()); } if (!invoice.Save()) { //return GetReterivedError(invoice, "Cannot save Invoice"); new Exception("Cannot save Invoice"); } // Create OrderLine MInvoiceLine il = new MInvoiceLine(invoice); // if (line.GetM_Product_ID() != 0) { il.SetM_Product_ID(line.GetM_Product_ID(), true); } //added by arpit asked by Surya Sir on 28/12/2015_____*************************** if (line.GetC_Charge_ID() != 0) { il.SetC_Charge_ID(line.GetC_Charge_ID()); } //end here ***************************** il.SetQty(line.GetQtyReimbursed()); // Entered/Invoiced il.SetDescription(line.GetDescription()); // il.SetC_Project_ID(line.GetC_Project_ID()); il.SetC_ProjectPhase_ID(line.GetC_ProjectPhase_ID()); il.SetC_ProjectTask_ID(line.GetC_ProjectTask_ID()); il.SetC_Activity_ID(line.GetC_Activity_ID()); il.SetC_Campaign_ID(line.GetC_Campaign_ID()); // // il.setPrice(); // not really a list/limit price for reimbursements il.SetPrice(line.GetPriceReimbursed()); // // JID_0868 // chanegs done by Bharat on 12 September 2018 to set the Amount in List price column. il.SetPriceList(line.GetPriceReimbursed()); il.SetTax(); if (!il.Save()) { //return GetReterivedError(il, "Cannot save Invoice"); new Exception("Cannot save Invoice Line"); } // Update TEL line.SetC_InvoiceLine_ID(il.GetC_InvoiceLine_ID()); line.SetIsInvoiced(true); line.Save(); } // for all expense lines } // ********* Expense Line Loop dt = null; //dt.Clear(); } catch (Exception e) { if (dt != null) { dt = null; } if (idr != null) { idr.Close(); } log.Log(Level.SEVERE, sql.ToString(), e); } finally { if (dt != null) { dt = null; } if (idr != null) { idr.Close(); } } CompleteInvoice(invoice); if (_noInvoices == 0) { return(" @No Record Found for Invoice Creation@"); } return("" + _noInvoices + " @Invoices Generated Successfully@"); } // doIt
} // prepare /// <summary> /// Perform Process. /// </summary> /// <returns>Message (clear text)</returns> protected override String DoIt() { int index = 1; StringBuilder sql = new StringBuilder("SELECT * " + "FROM S_TimeExpense e " + "WHERE e.Processed='Y'" + " AND e.AD_Client_ID=@param1"); // #1 if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1) { index++; sql.Append(" AND e.C_BPartner_ID=@param2"); // #2 } if (_DateFrom != null) { index++; sql.Append(" AND e.DateReport >=@param3"); // #3 } if (_DateTo != null) { index++; sql.Append(" AND e.DateReport <=@param4"); // #4 sql.Append(" AND EXISTS (SELECT * FROM S_TimeExpenseLine el " + "WHERE e.S_TimeExpense_ID=el.S_TimeExpense_ID" + " AND el.C_InvoiceLine_ID IS NULL" + " AND el.ConvertedAmt<>0) " + "ORDER BY e.C_BPartner_ID, e.S_TimeExpense_ID"); } // int old_BPartner_ID = -1; MInvoice invoice = null; // //PreparedStatement pstmt = null; SqlParameter[] param = new SqlParameter[index]; IDataReader idr = null; DataTable dt = null; try { //pstmt = DataBase.prepareStatement (sql.toString (), get_TrxName()); int par = 0; //pstmt.setInt(par++, getAD_Client_ID()); param[0] = new SqlParameter("@param1", GetAD_Client_ID()); if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1) { par++; //pstmt.setInt (par++, _C_BPartner_ID); param[par] = new SqlParameter("@param2", _C_BPartner_ID); } if (_DateFrom != null) { par++; //pstmt.setTimestamp (par++, _DateFrom); param[par] = new SqlParameter("@param3", _DateFrom); } if (_DateTo != null) { par++; //pstmt.setTimestamp (par++, _DateTo); param[par] = new SqlParameter("@param4", _DateTo); } //ResultSet rs = pstmt.executeQuery (); idr = DataBase.DB.ExecuteReader(sql.ToString(), param, Get_TrxName()); dt = new DataTable(); dt.Load(idr); idr.Close(); foreach (DataRow dr in dt.Rows) // ********* Expense Line Loop { MTimeExpense te = new MTimeExpense(GetCtx(), dr, Get_TrxName()); // New BPartner - New Order if (te.GetC_BPartner_ID() != old_BPartner_ID) { CompleteInvoice(invoice); MBPartner bp = new MBPartner(GetCtx(), te.GetC_BPartner_ID(), Get_TrxName()); // log.Info("New Invoice for " + bp); invoice = new MInvoice(GetCtx(), 0, null); invoice.SetClientOrg(te.GetAD_Client_ID(), te.GetAD_Org_ID()); invoice.SetC_DocTypeTarget_ID(MDocBaseType.DOCBASETYPE_APINVOICE); // API invoice.SetDocumentNo(te.GetDocumentNo()); // invoice.SetBPartner(bp); if (invoice.GetC_BPartner_Location_ID() == 0) { log.Log(Level.SEVERE, "No BP Location: " + bp); AddLog(0, te.GetDateReport(), null, "No Location: " + te.GetDocumentNo() + " " + bp.GetName()); invoice = null; break; } invoice.SetM_PriceList_ID(te.GetM_PriceList_ID()); invoice.SetSalesRep_ID(te.GetDoc_User_ID()); String descr = Msg.Translate(GetCtx(), "S_TimeExpense_ID") + ": " + te.GetDocumentNo() + " " + DisplayType.GetDateFormat(DisplayType.Date).Format(te.GetDateReport()); invoice.SetDescription(descr); if (!invoice.Save()) { new Exception("Cannot save Invoice"); } old_BPartner_ID = bp.GetC_BPartner_ID(); } MTimeExpenseLine[] tel = te.GetLines(false); for (int i = 0; i < tel.Length; i++) { MTimeExpenseLine line = tel[i]; // Already Invoiced or nothing to be reimbursed if (line.GetC_InvoiceLine_ID() != 0 || Env.ZERO.CompareTo(line.GetQtyReimbursed()) == 0 || Env.ZERO.CompareTo(line.GetPriceReimbursed()) == 0) { continue; } // Update Header info if (line.GetC_Activity_ID() != 0 && line.GetC_Activity_ID() != invoice.GetC_Activity_ID()) { invoice.SetC_Activity_ID(line.GetC_Activity_ID()); } if (line.GetC_Campaign_ID() != 0 && line.GetC_Campaign_ID() != invoice.GetC_Campaign_ID()) { invoice.SetC_Campaign_ID(line.GetC_Campaign_ID()); } if (line.GetC_Project_ID() != 0 && line.GetC_Project_ID() != invoice.GetC_Project_ID()) { invoice.SetC_Project_ID(line.GetC_Project_ID()); } if (!invoice.Save()) { new Exception("Cannot save Invoice"); } // Create OrderLine MInvoiceLine il = new MInvoiceLine(invoice); // if (line.GetM_Product_ID() != 0) { il.SetM_Product_ID(line.GetM_Product_ID(), true); } il.SetQty(line.GetQtyReimbursed()); // Entered/Invoiced il.SetDescription(line.GetDescription()); // il.SetC_Project_ID(line.GetC_Project_ID()); il.SetC_ProjectPhase_ID(line.GetC_ProjectPhase_ID()); il.SetC_ProjectTask_ID(line.GetC_ProjectTask_ID()); il.SetC_Activity_ID(line.GetC_Activity_ID()); il.SetC_Campaign_ID(line.GetC_Campaign_ID()); // // il.setPrice(); // not really a list/limit price for reimbursements il.SetPrice(line.GetPriceReimbursed()); // il.SetTax(); if (!il.Save()) { new Exception("Cannot save Invoice Line"); } // Update TEL line.SetC_InvoiceLine_ID(il.GetC_InvoiceLine_ID()); line.SetIsInvoiced(true); line.Save(); } // for all expense lines } // ********* Expense Line Loop dt = null; //dt.Clear(); } catch (Exception e) { if (dt != null) { dt = null; } if (idr != null) { idr.Close(); } log.Log(Level.SEVERE, sql.ToString(), e); } finally { if (dt != null) { dt = null; } if (idr != null) { idr.Close(); } } CompleteInvoice(invoice); if (_noInvoices == 0) { return(" @No Record Found for Invoice Creation@"); } return("" + _noInvoices + " @Invoices Generated Successfully@"); } // doIt