} // invoiceNew /// <summary> /// Invoice Line /// </summary> /// <param name="request">request</param> private void InvoiceLine(MRequest request) { MRequestUpdate[] updates = request.GetUpdates(null); for (int i = 0; i < updates.Length; i++) { Decimal qty = updates[i].GetQtyInvoiced(); if (Env.Signum(qty) == 0) { continue; } MInvoiceLine il = new MInvoiceLine(_m_invoice); _m_linecount++; il.SetLine(_m_linecount * 10); // il.SetQty(qty); // Product int M_Product_ID = updates[i].GetM_ProductSpent_ID(); if (M_Product_ID == 0) { M_Product_ID = _M_Product_ID; } il.SetM_Product_ID(M_Product_ID); // il.SetPrice(); il.Save(); } } // invoiceLine
/************************************************************************** * Create Invoice Line from Order Line * @param order order * @param orderLine line * @param qtyInvoiced qty * @param qtyEntered qty */ private void CreateLine(MOrder order, MOrderLine orderLine, Decimal qtyInvoiced, Decimal qtyEntered) { if (_invoice == null) { _invoice = new MInvoice(order, 0, _DateInvoiced); if (!_invoice.Save()) { throw new Exception("Could not create Invoice (o)"); } } // MInvoiceLine line = new MInvoiceLine(_invoice); line.SetOrderLine(orderLine); line.SetQtyInvoiced(qtyInvoiced); log.Info("Qty Invoiced" + line.GetQtyInvoiced()); line.SetQtyEntered(qtyEntered); line.SetLine(_line + orderLine.GetLine()); if (!line.Save()) { throw new Exception("Could not create Invoice Line (o)"); } log.Fine(line.ToString()); }
/** * After Delete * @param success success * @return success */ protected override bool AfterDelete(bool success) { if (success) { // Get Order and decrease invoices MInvoiceLine iLine = new MInvoiceLine(GetCtx(), GetC_InvoiceLine_ID(), Get_TrxName()); int C_OrderLine_ID = iLine.GetC_OrderLine_ID(); if (C_OrderLine_ID == 0) { MInOutLine ioLine = new MInOutLine(GetCtx(), GetM_InOutLine_ID(), Get_TrxName()); C_OrderLine_ID = ioLine.GetC_OrderLine_ID(); } // No Order Found if (C_OrderLine_ID == 0) { return(success); } // Find MatchPO MMatchPO[] mPO = MMatchPO.Get(GetCtx(), C_OrderLine_ID, GetC_InvoiceLine_ID(), Get_TrxName()); for (int i = 0; i < mPO.Length; i++) { if (mPO[i].GetM_InOutLine_ID() == 0) { mPO[i].Delete(true); } else { mPO[i].SetC_InvoiceLine_ID(null); mPO[i].Save(); } } } return(success); }
/// <summary> /// Get Costs of Invoice Line /// </summary> /// <param name="il">invoice line</param> /// <returns>array of landed cost lines</returns> public static MLandedCost[] GetLandedCosts(MInvoiceLine il) { List <MLandedCost> list = new List <MLandedCost>(); String sql = "SELECT * FROM C_LandedCost WHERE C_InvoiceLine_ID=" + il.GetC_InvoiceLine_ID(); try { DataSet ds = DataBase.DB.ExecuteDataset(sql, null, il.Get_TrxName()); if (ds.Tables.Count > 0) { foreach (DataRow dr in ds.Tables[0].Rows) { list.Add(new MLandedCost(il.GetCtx(), dr, il.Get_TrxName())); } } } catch (Exception e) { _log.Log(Level.SEVERE, sql, e); } // MLandedCost[] retValue = new MLandedCost[list.Count]; retValue = list.ToArray(); return(retValue); }
} // MTaxDeclarationLine /// <summary> /// Parent Constructor /// </summary> /// <param name="parent">parent</param> /// <param name="invoice">invoice</param> /// <param name="iLine">invoice line</param> public MTaxDeclarationLine(MTaxDeclaration parent, MInvoice invoice, MInvoiceLine iLine) : this(parent.GetCtx(), 0, parent.Get_TrxName()) { // this(parent.getCtx(), 0, parent.get_TrxName()); SetClientOrg(invoice); SetC_TaxDeclaration_ID(parent.GetC_TaxDeclaration_ID()); SetIsManual(false); // SetC_Invoice_ID(invoice.GetC_Invoice_ID()); SetC_BPartner_ID(invoice.GetC_BPartner_ID()); SetC_Currency_ID(invoice.GetC_Currency_ID()); SetDateAcct(invoice.GetDateAcct()); // SetC_InvoiceLine_ID(iLine.GetC_InvoiceLine_ID()); SetC_Tax_ID(iLine.GetC_Tax_ID()); if (invoice.IsTaxIncluded()) { SetTaxBaseAmt(iLine.GetLineNetAmt()); SetTaxAmt(iLine.GetTaxAmt()); } else { SetTaxBaseAmt(iLine.GetLineNetAmt()); SetTaxAmt(iLine.GetTaxAmt()); } } // MTaxDeclarationLine
} // MLandedCostAllocation /** * Parent Constructor * @param parent parent * @param M_CostElement_ID cost element */ public MLandedCostAllocation(MInvoiceLine parent, int M_CostElement_ID) : this(parent.GetCtx(), 0, parent.Get_TrxName()) { SetClientOrg(parent); SetC_InvoiceLine_ID(parent.GetC_InvoiceLine_ID()); SetM_CostElement_ID(M_CostElement_ID); } // MLandedCostAllocation
/** * Set Value Name Description * @param Invoice * @param line line * @param deliveryCount */ public void SetValueNameDescription(MInvoice invoice, MInvoiceLine line, int deliveryCount) { MProduct product = line.GetProduct(); MBPartner partner = new MBPartner(GetCtx(), invoice.GetC_BPartner_ID(), null); SetValueNameDescription(invoice, deliveryCount, product, partner); }
/// <summary> /// Load Document Details /// </summary> /// <returns>error message or null</returns> public override String LoadDocumentDetails() { SetC_Currency_ID(Doc.NO_CURRENCY); MMatchInv matchInv = (MMatchInv)GetPO(); SetDateDoc(matchInv.GetDateTrx()); SetQty(matchInv.GetQty()); // Invoice Info int C_InvoiceLine_ID = matchInv.GetC_InvoiceLine_ID(); _invoiceLine = new MInvoiceLine(GetCtx(), C_InvoiceLine_ID, null); // BP for NotInvoicedReceipts int C_BPartner_ID = _invoiceLine.GetParent().GetC_BPartner_ID(); SetC_BPartner_ID(C_BPartner_ID); // int M_InOutLine_ID = matchInv.GetM_InOutLine_ID(); _receiptLine = new MInOutLine(GetCtx(), M_InOutLine_ID, null); // _pc = new ProductCost(GetCtx(), GetM_Product_ID(), matchInv.GetM_AttributeSetInstance_ID(), null); _pc.SetQty(GetQty()); return(null); }
/// <summary> /// Get Invoice Line /// </summary> /// <returns>invoice line or null</returns> public MInvoiceLine GetInvoiceLine() { if (_iLine == null && GetC_InvoiceLine_ID() != 0) { _iLine = new MInvoiceLine(GetCtx(), GetC_InvoiceLine_ID(), Get_Trx()); } return(_iLine); }
/// <summary> /// Create Invoice. /// </summary> /// <returns>document no</returns> protected override String DoIt() { //log.info("M_InOut_ID=" + _M_InOut_ID // + ", M_PriceList_ID=" + _M_PriceList_ID // + ", InvoiceDocumentNo=" + _InvoiceDocumentNo); if (_M_InOut_ID == 0) { throw new ArgumentException("No Shipment"); } // MInOut ship = new MInOut(GetCtx(), _M_InOut_ID, null); if (ship.Get_ID() == 0) { throw new ArgumentException("Shipment not found"); } if (!MInOut.DOCSTATUS_Completed.Equals(ship.GetDocStatus())) { throw new ArgumentException("Shipment not completed"); } MInvoice invoice = new MInvoice(ship, null); if (ship.IsReturnTrx()) { invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO); } if (_M_PriceList_ID != 0) { invoice.SetM_PriceList_ID(_M_PriceList_ID); } if (_InvoiceDocumentNo != null && _InvoiceDocumentNo.Length > 0) { invoice.SetDocumentNo(_InvoiceDocumentNo); } if (!invoice.Save()) { throw new ArgumentException("Cannot save Invoice"); } MInOutLine[] shipLines = ship.GetLines(false); for (int i = 0; i < shipLines.Length; i++) { MInOutLine sLine = shipLines[i]; MInvoiceLine line = new MInvoiceLine(invoice); line.SetShipLine(sLine); line.SetQtyEntered(sLine.GetQtyEntered()); line.SetQtyInvoiced(sLine.GetMovementQty()); if (!line.Save()) { throw new ArgumentException("Cannot save Invoice Line"); } } return(invoice.GetDocumentNo()); }
/// <summary> /// Set C_InvoiceLine_ID /// </summary> /// <param name="line">line</param> public void SetC_InvoiceLine_ID(MInvoiceLine line) { _iLine = line; if (line == null) { SetC_InvoiceLine_ID(0); } else { SetC_InvoiceLine_ID(line.GetC_InvoiceLine_ID()); } }
/************************************************************************** * Create Invoice Line from Order Line * @param order order * @param orderLine line * @param qtyInvoiced qty * @param qtyEntered qty */ private void CreateLine(MOrder order, MOrderLine orderLine, Decimal qtyInvoiced, Decimal qtyEntered) { if (_invoice == null) { _invoice = new MInvoice(order, 0, _DateInvoiced); //-----------------Column Added by Anuj------------------ int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_' AND IsActive = 'Y'")); if (_CountVA009 > 0) { int _PaymentMethod_ID = order.GetVA009_PaymentMethod_ID(); if (_PaymentMethod_ID > 0) { _invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID); } } //-----------------Column Added by Anuj------------------ int _CountVA026 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA026_' AND IsActive = 'Y'")); if (_CountVA026 > 0) { _invoice.SetVA026_LCDetail_ID(order.GetVA026_LCDetail_ID()); } // Added by Bharat on 29 Jan 2018 to set Inco Term from Order if (_invoice.Get_ColumnIndex("C_IncoTerm_ID") > 0) { _invoice.SetC_IncoTerm_ID(order.GetC_IncoTerm_ID()); } if (!_invoice.Save()) { throw new Exception("Could not create Invoice (o)"); } } // MInvoiceLine line = new MInvoiceLine(_invoice); line.SetOrderLine(orderLine); line.SetQtyInvoiced(qtyInvoiced); // if drop ship line true line.SetIsDropShip(orderLine.IsDropShip()); log.Info("Qty Invoiced" + line.GetQtyInvoiced()); line.SetQtyEntered(qtyEntered); line.SetLine(_line + orderLine.GetLine()); if (!line.Save()) { throw new Exception("Could not create Invoice Line (o)"); } log.Fine(line.ToString()); }
/** * Invoice Line Constructor * @param iLine invoice line * @param dateTrx optional date * @param qty matched quantity */ public MMatchInv(MInvoiceLine iLine, DateTime?dateTrx, Decimal qty) : this(iLine.GetCtx(), 0, iLine.Get_TrxName()) { SetClientOrg(iLine); SetC_InvoiceLine_ID(iLine.GetC_InvoiceLine_ID()); SetM_InOutLine_ID(iLine.GetM_InOutLine_ID()); if (dateTrx != null) { SetDateTrx(dateTrx); } SetM_Product_ID(iLine.GetM_Product_ID()); SetM_AttributeSetInstance_ID(iLine.GetM_AttributeSetInstance_ID()); SetQty(qty); SetProcessed(true); // auto }
/// <summary> /// Save to Invoice /// </summary> /// <param name="C_Invoice_ID">id</param> /// <returns>true if saved</returns> private bool Cmd_SaveInvoice(Ctx ctx, int C_Invoice_ID) { Decimal qty = 0; log.Config("C_Invoice_ID=" + C_Invoice_ID); MInvoice invoice = new MInvoice(ctx, C_Invoice_ID, null); if (invoice.Get_ID() == 0) { log.Log(Level.SEVERE, "Not found - C_Invoice_ID=" + C_Invoice_ID); } int lineCount = 0; bool chk = false; // for all bom lines if (_selectionList != null) { bool isQtySet = false; for (int i = 0; i < _selectionList.Count; i++) { if (_selectionList[i].IsSelected) { int M_Product_ID = Util.GetValueOfInt(_selectionList[i].ProductID);//.intValue(); // Create Line MInvoiceLine il = new MInvoiceLine(invoice); il.SetM_Product_ID(Util.GetValueOfInt(_selectionList[i].ProductID)); il.SetQty(Util.GetValueOfInt(_selectionList[i].BOMQty)); il.SetPrice(); il.SetTax(); if (il.Save()) { lineCount++; } else { log.Log(Level.SEVERE, "Line not saved"); } } // line selected } // for all bom lines log.Config("#" + lineCount); } return(true); }
} // afterSave /// <summary> /// This function is used to set Values on Recognition Plan /// </summary> /// <param name="invoiceLine">invoice line object </param> /// <param name="invoice">invoice object</param> /// <param name="C_RevenueRecognition_ID">Recognition ID</param> /// <param name="ToCurrency">Currency</param> public void SetRecognitionPlan(MInvoiceLine invoiceLine, MInvoice invoice, int C_RevenueRecognition_ID, int ToCurrency) { SetAD_Client_ID(invoice.GetAD_Client_ID()); SetAD_Org_ID(invoice.GetAD_Org_ID()); SetC_Currency_ID(ToCurrency); SetC_InvoiceLine_ID(invoiceLine.GetC_InvoiceLine_ID()); SetC_RevenueRecognition_ID(C_RevenueRecognition_ID); // when tax include into price list, then reduce tax from Line Net Amount bool isTaxIncide = (new MPriceList(invoice.GetCtx(), invoice.GetM_PriceList_ID(), invoice.Get_Trx())).IsTaxIncluded(); Decimal Amount = invoiceLine.GetLineNetAmt() - (isTaxIncide ? (invoiceLine.GetTaxAmt() + invoiceLine.GetSurchargeAmt()) : 0); if (invoice.GetC_Currency_ID() != ToCurrency) { Amount = MConversionRate.Convert(GetCtx(), Amount, invoice.GetC_Currency_ID(), ToCurrency, invoice.GetDateInvoiced(), invoice.GetC_ConversionType_ID(), invoice.GetAD_Client_ID(), invoice.GetAD_Org_ID()); } SetTotalAmt(Amount); SetRecognizedAmt(Env.ZERO); }
/// <summary> /// After Save /// </summary> /// <param name="newRecord"></param> /// <param name="success"></param> /// <returns>Success</returns> /// public void SetRecognitionPlan(MInvoiceLine invoiceLine, MInvoice invoice, int C_RevenueRecognition_ID) { try { SetAD_Client_ID(invoice.GetAD_Client_ID()); SetAD_Org_ID(invoice.GetAD_Org_ID()); SetC_Currency_ID(invoice.GetC_Currency_ID()); SetC_InvoiceLine_ID(invoiceLine.GetC_InvoiceLine_ID()); SetC_RevenueRecognition_ID(C_RevenueRecognition_ID); SetP_Revenue_Acct(0); SetUnEarnedRevenue_Acct(0); SetTotalAmt(invoiceLine.GetLineNetAmt()); SetRecognizedAmt(Env.ZERO); } catch (Exception ex) { // MessageBox.Show("MInvoiceLine--SetInvoice"); } }
/** * Set Invoice Line. * Does not set Quantity! * @param iLine invoice line * @param M_Locator_ID locator * @param Qty qty only fo find suitable locator */ public void SetInvoiceLine(MInvoiceLine iLine, int M_Locator_ID, Decimal Qty) { SetC_OrderLine_ID(iLine.GetC_OrderLine_ID()); SetLine(iLine.GetLine()); SetC_UOM_ID(iLine.GetC_UOM_ID()); int M_Product_ID = iLine.GetM_Product_ID(); if (M_Product_ID == 0) { Set_ValueNoCheck("M_Product_ID", null); Set_ValueNoCheck("M_Locator_ID", null); Set_ValueNoCheck("M_AttributeSetInstance_ID", null); } else { SetM_Product_ID(M_Product_ID); SetM_AttributeSetInstance_ID(iLine.GetM_AttributeSetInstance_ID()); if (M_Locator_ID == 0) { SetM_Locator_ID(Qty); // requires warehouse, product, asi } else { SetM_Locator_ID(M_Locator_ID); } } SetC_Charge_ID(iLine.GetC_Charge_ID()); SetDescription(iLine.GetDescription()); SetIsDescription(iLine.IsDescription()); // SetC_Project_ID(iLine.GetC_Project_ID()); SetC_ProjectPhase_ID(iLine.GetC_ProjectPhase_ID()); SetC_ProjectTask_ID(iLine.GetC_ProjectTask_ID()); SetC_Activity_ID(iLine.GetC_Activity_ID()); SetC_Campaign_ID(iLine.GetC_Campaign_ID()); SetAD_OrgTrx_ID(iLine.GetAD_OrgTrx_ID()); SetUser1_ID(iLine.GetUser1_ID()); SetUser2_ID(iLine.GetUser2_ID()); }
} // 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
public static bool InsertForeignCostMatchInvoice(Ctx ctx, MInvoiceLine invoiceLine, decimal matchQty, int ASI, Trx trx) { int acctSchema_ID = 0; int M_CostElement_ID = 0; int AD_Org_ID = 0; int M_ASI_ID = 0; MProduct product = null; MAcctSchema acctSchema = null; MCostForeignCurrency foreignCost = null; dynamic pc = null; String cl = null; MInvoice invoice = null; try { // if cost is calculated then not to calculate again if (invoiceLine.IsFutureCostCalculated()) { return(true); } invoice = new MInvoice(ctx, invoiceLine.GetC_Invoice_ID(), trx); if (!invoice.IsSOTrx() && !invoice.IsReturnTrx()) { acctSchema_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT asch.c_acctschema_id FROM c_acctschema asch INNER JOIN ad_clientinfo ci ON ci.c_acctschema1_id = asch.c_acctschema_id WHERE ci.ad_client_id = " + invoice.GetAD_Client_ID())); acctSchema = new MAcctSchema(ctx, acctSchema_ID, trx); if (acctSchema.GetC_Currency_ID() != invoice.GetC_Currency_ID()) { // Get Costing Element of Av. Invoice M_CostElement_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT M_CostElement_ID FROM M_CostElement WHERE AD_Client_ID = " + invoice.GetAD_Client_ID() + " AND IsActive = 'Y' AND CostingMethod = 'I'")); product = new MProduct(ctx, invoiceLine.GetM_Product_ID(), trx); if (product != null && product.GetProductType() == "I" && product.GetM_Product_ID() > 0) // for Item Type product { pc = MProductCategory.Get(product.GetCtx(), product.GetM_Product_Category_ID()); // Get Costing Level if (pc != null) { cl = pc.GetCostingLevel(); } if (cl == null) { cl = acctSchema.GetCostingLevel(); } if (cl == "C" || cl == "B") { AD_Org_ID = 0; } else { AD_Org_ID = invoice.GetAD_Org_ID(); } if (cl != "B") { M_ASI_ID = 0; } else { M_ASI_ID = ASI; } foreignCost = MCostForeignCurrency.Get(product, M_ASI_ID, AD_Org_ID, M_CostElement_ID, invoice.GetC_BPartner_ID(), invoice.GetC_Currency_ID()); foreignCost.SetC_Invoice_ID(invoice.GetC_Invoice_ID()); foreignCost.SetCumulatedQty(Decimal.Add(foreignCost.GetCumulatedQty(), matchQty)); foreignCost.SetCumulatedAmt(Decimal.Add(foreignCost.GetCumulatedAmt(), Decimal.Multiply(invoiceLine.GetPriceActual(), matchQty))); if (foreignCost.GetCumulatedQty() != 0) { foreignCost.SetCostPerUnit(Decimal.Round(Decimal.Divide(foreignCost.GetCumulatedAmt(), foreignCost.GetCumulatedQty()), acctSchema.GetCostingPrecision())); } else { foreignCost.SetCostPerUnit(0); } if (!foreignCost.Save(trx)) { ValueNamePair pp = VLogger.RetrieveError(); _log.Severe("Error occured during updating M_Cost_ForeignCurrency. Error name : " + pp.GetName() + " AND Error Value : " + pp.GetValue() + " , For Invoice line : " + invoiceLine.GetC_InvoiceLine_ID() + " , AND Ad_Client_ID : " + invoiceLine.GetAD_Client_ID()); return(false); } } } } } catch (Exception ex) { _log.Log(Level.SEVERE, "", ex); return(false); } return(true); }
/// <summary> /// Create Landed Cost accounting & Cost lines /// </summary> /// <param name="as1">accounting schema</param> /// <param name="fact">fact</param> /// <param name="line">document line</param> /// <param name="dr">DR entry (normal api)</param> /// <returns>true if landed costs were created</returns> private bool LandedCost(MAcctSchema as1, Fact fact, DocLine line, bool dr) { int C_InvoiceLine_ID = line.Get_ID(); MLandedCostAllocation[] lcas = MLandedCostAllocation.GetOfInvoiceLine( GetCtx(), C_InvoiceLine_ID, GetTrx()); if (lcas.Length == 0) { return(false); } // Delete Old String sql = "DELETE FROM M_CostDetail WHERE C_InvoiceLine_ID=" + C_InvoiceLine_ID; int no = DataBase.DB.ExecuteQuery(sql, null, GetTrx()); if (no != 0) { log.Config("CostDetail Deleted #" + no); } // Calculate Total Base double totalBase = 0; for (int i = 0; i < lcas.Length; i++) { totalBase += Convert.ToDouble(lcas[i].GetBase());//.doubleValue(); } // Create New MInvoiceLine il = new MInvoiceLine(GetCtx(), C_InvoiceLine_ID, GetTrx()); for (int i = 0; i < lcas.Length; i++) { MLandedCostAllocation lca = lcas[i]; if (Env.Signum(lca.GetBase()) == 0) { continue; } double percent = totalBase / Convert.ToDouble(lca.GetBase()); String desc = il.GetDescription(); if (desc == null) { desc = percent + "%"; } else { desc += " - " + percent + "%"; } if (line.GetDescription() != null) { desc += " - " + line.GetDescription(); } // Accounting ProductCost pc = new ProductCost(GetCtx(), lca.GetM_Product_ID(), lca.GetM_AttributeSetInstance_ID(), GetTrx()); Decimal?drAmt = null; Decimal?crAmt = null; if (dr) { drAmt = lca.GetAmt(); } else { crAmt = lca.GetAmt(); } FactLine fl = fact.CreateLine(line, pc.GetAccount(ProductCost.ACCTTYPE_P_CostAdjustment, as1), GetC_Currency_ID(), drAmt, crAmt); fl.SetDescription(desc); // Cost Detail - Convert to AcctCurrency Decimal allocationAmt = lca.GetAmt(); if (GetC_Currency_ID() != as1.GetC_Currency_ID()) { allocationAmt = MConversionRate.Convert(GetCtx(), allocationAmt, GetC_Currency_ID(), as1.GetC_Currency_ID(), GetDateAcct(), GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()); } if (Env.Scale(allocationAmt) > as1.GetCostingPrecision()) { allocationAmt = Decimal.Round(allocationAmt, as1.GetCostingPrecision(), MidpointRounding.AwayFromZero); } if (!dr) { allocationAmt = Decimal.Negate(allocationAmt); } if (!IsPosted()) { MCostDetail cd = new MCostDetail(as1, lca.GetAD_Org_ID(), lca.GetM_Product_ID(), lca.GetM_AttributeSetInstance_ID(), lca.GetM_CostElement_ID(), allocationAmt, lca.GetQty(), // Qty desc, GetTrx()); cd.SetC_InvoiceLine_ID(C_InvoiceLine_ID); bool ok = cd.Save(); if (ok && !cd.IsProcessed()) { MClient client = MClient.Get(as1.GetCtx(), as1.GetAD_Client_ID()); if (client.IsCostImmediate()) { cd.Process(); } } } } log.Config("Created #" + lcas.Length); return(true); }
/// <summary> /// Load Invoice Line /// </summary> /// <param name="invoice">invoice</param> /// <returns>DocLine Array</returns> private DocLine[] LoadLines(MInvoice invoice) { List <DocLine> list = new List <DocLine>(); // MInvoiceLine[] lines = invoice.GetLines(false); for (int i = 0; i < lines.Length; i++) { MInvoiceLine line = lines[i]; if (line.IsDescription()) { continue; } DocLine docLine = new DocLine(line, this); // Qty Decimal Qty = line.GetQtyInvoiced(); bool cm = GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_ARCREDITMEMO) || GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_APCREDITMEMO); docLine.SetQty(cm ? Decimal.Negate(Qty) : Qty, invoice.IsSOTrx()); // Decimal LineNetAmt = line.GetLineNetAmt(); Decimal PriceList = line.GetPriceList(); int C_Tax_ID = docLine.GetC_Tax_ID(); // Correct included Tax if (IsTaxIncluded() && C_Tax_ID != 0) { MTax tax = MTax.Get(GetCtx(), C_Tax_ID); if (!tax.IsZeroTax()) { Decimal LineNetAmtTax = tax.CalculateTax(LineNetAmt, true, GetStdPercision()); log.Fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax); LineNetAmt = Decimal.Subtract(LineNetAmt, LineNetAmtTax); for (int t = 0; t < _taxes.Length; t++) { if (_taxes[t].GetC_Tax_ID() == C_Tax_ID) { _taxes[t].AddIncludedTax(LineNetAmtTax); break; } } Decimal PriceListTax = tax.CalculateTax(PriceList, true, GetStdPercision()); PriceList = Decimal.Subtract(PriceList, PriceListTax); } } // correct included Tax docLine.SetAmount(LineNetAmt, PriceList, Qty); // qty for discount calc if (docLine.IsItem()) { _allLinesService = false; } else { _allLinesItem = false; } // log.Fine(docLine.ToString()); list.Add(docLine); } // Convert to Array DocLine[] dls = new DocLine[list.Count]; dls = list.ToArray(); // Included Tax - make sure that no difference if (IsTaxIncluded()) { for (int i = 0; i < _taxes.Length; i++) { if (_taxes[i].IsIncludedTaxDifference()) { Decimal diff = _taxes[i].GetIncludedTaxDifference(); for (int j = 0; j < dls.Length; j++) { if (dls[j].GetC_Tax_ID() == _taxes[i].GetC_Tax_ID()) { dls[j].SetLineNetAmtDifference(diff); break; } } // for all lines } // tax difference } // for all taxes } // Included Tax difference // Return Array return(dls); }
/// <summary> /// Process Invoice Batch /// </summary> /// <returns></returns> protected override String DoIt() { log.Info("C_InvoiceBatch_ID=" + _C_InvoiceBatch_ID + ", DocAction=" + _DocAction); if (_C_InvoiceBatch_ID == 0) { throw new Exception("C_InvoiceBatch_ID = 0"); } MInvoiceBatch batch = new MInvoiceBatch(GetCtx(), _C_InvoiceBatch_ID, Get_TrxName()); if (batch.Get_ID() == 0) { throw new Exception("@NotFound@: @C_InvoiceBatch_ID@ - " + _C_InvoiceBatch_ID); } if (batch.IsProcessed()) { throw new Exception("@Processed@"); } // if (Signum(batch.GetControlAmt()) != 0 && batch.GetControlAmt().CompareTo(batch.GetDocumentAmt()) != 0) { throw new Exception("@ControlAmt@ <> @DocumentAmt@"); } // MInvoiceBatchLine[] lines = batch.GetLines(false); for (int i = 0; i < lines.Length; i++) { MInvoiceBatchLine line = lines[i]; if (line.GetC_Invoice_ID() != 0 || line.GetC_InvoiceLine_ID() != 0) { continue; } if ((_oldDocumentNo != null && !_oldDocumentNo.Equals(line.GetDocumentNo())) || _oldC_BPartner_ID != line.GetC_BPartner_ID() || _oldC_BPartner_Location_ID != line.GetC_BPartner_Location_ID()) { CompleteInvoice(); } // New Invoice if (_invoice == null) { _invoice = new MInvoice(batch, line); if (!_invoice.Save()) { return(GetRetrievedError(_invoice, "Cannot save Invoice")); } //throw new Exception("Cannot save Invoice"); // _oldDocumentNo = line.GetDocumentNo(); _oldC_BPartner_ID = line.GetC_BPartner_ID(); _oldC_BPartner_Location_ID = line.GetC_BPartner_Location_ID(); } if (line.IsTaxIncluded() != _invoice.IsTaxIncluded()) { return(GetRetrievedError(line, "Line " + line.GetLine() + " TaxIncluded inconsistent")); // rollback // throw new Exception("Line " + line.GetLine() + " TaxIncluded inconsistent"); } // Add Line MInvoiceLine invoiceLine = new MInvoiceLine(_invoice); invoiceLine.SetDescription(line.GetDescription()); invoiceLine.SetC_Charge_ID(line.GetC_Charge_ID()); invoiceLine.SetQty(line.GetQtyEntered()); // Entered/Invoiced invoiceLine.SetPrice(line.GetPriceEntered()); invoiceLine.SetC_Tax_ID(line.GetC_Tax_ID()); invoiceLine.SetTaxAmt(line.GetTaxAmt()); invoiceLine.SetLineNetAmt(line.GetLineNetAmt()); invoiceLine.SetLineTotalAmt(line.GetLineTotalAmt()); if (!invoiceLine.Save()) { return(GetRetrievedError(invoiceLine, "Cannot save Invoice Line")); // rollback // throw new Exception("Cannot save Invoice Line"); } // Update Batch Line line.SetC_Invoice_ID(_invoice.GetC_Invoice_ID()); line.SetC_InvoiceLine_ID(invoiceLine.GetC_InvoiceLine_ID()); line.Save(); } // for all lines CompleteInvoice(); // batch.SetProcessed(true); batch.Save(); return("#" + _count); } // doIt
/** * Get Tax Line for Invoice Line * @param line invoice line * @param precision currency precision * @param oldTax if true old tax is returned * @param trxName transaction name * @return existing or new tax */ public static MInvoiceTax Get(MInvoiceLine line, int precision, Boolean oldTax, Trx trxName) { MInvoiceTax retValue = null; try { if (line == null || line.GetC_Invoice_ID() == 0 || line.IsDescription()) { return(null); } int C_Tax_ID = line.GetC_Tax_ID(); if (oldTax && line.Is_ValueChanged("C_Tax_ID")) { Object old = line.Get_ValueOld("C_Tax_ID"); if (old == null) { return(null); } C_Tax_ID = int.Parse(old.ToString()); } if (C_Tax_ID == 0) { _log.Warning("C_Tax_ID=0"); return(null); } String sql = "SELECT * FROM C_InvoiceTax WHERE C_Invoice_ID=" + line.GetC_Invoice_ID() + " AND C_Tax_ID=" + C_Tax_ID; try { DataSet ds = DataBase.DB.ExecuteDataset(sql, null, trxName); if (ds.Tables.Count > 0) { foreach (DataRow dr in ds.Tables[0].Rows) { retValue = new MInvoiceTax(line.GetCtx(), dr, trxName); } } } catch (Exception e) { _log.Log(Level.SEVERE, sql, e); } if (retValue != null) { retValue.Set_TrxName(trxName); retValue.SetPrecision(precision); _log.Fine("(old=" + oldTax + ") " + retValue); return(retValue); } // Create New retValue = new MInvoiceTax(line.GetCtx(), 0, trxName); retValue.Set_TrxName(trxName); retValue.SetClientOrg(line); retValue.SetC_Invoice_ID(line.GetC_Invoice_ID()); retValue.SetC_Tax_ID(line.GetC_Tax_ID()); retValue.SetPrecision(precision); retValue.SetIsTaxIncluded(line.IsTaxIncluded()); _log.Fine("(new) " + retValue); } catch { // MessageBox.Show("MInvoiceTax--Get"); } return(retValue); }
/// <summary> /// Perform Process. /// </summary> /// <returns>Message (variables are parsed)</returns> protected override String DoIt() { log.Info("doIt - C_CommissionRun_ID=" + GetRecord_ID()); // Load Data MCommissionRun comRun = new MCommissionRun(GetCtx(), GetRecord_ID(), Get_Trx()); if (comRun.Get_ID() == 0) { throw new ArgumentException("CommissionAPInvoice - No Commission Run"); } if (Env.ZERO.CompareTo(comRun.GetGrandTotal()) == 0) { throw new ArgumentException("@GrandTotal@ = 0"); } MCommission com = new MCommission(GetCtx(), comRun.GetC_Commission_ID(), Get_Trx()); if (com.Get_ID() == 0) { throw new ArgumentException("CommissionAPInvoice - No Commission"); } if (com.GetC_Charge_ID() == 0) { throw new ArgumentException("CommissionAPInvoice - No Charge on Commission"); } MBPartner bp = new MBPartner(GetCtx(), com.GetC_BPartner_ID(), Get_Trx()); if (bp.Get_ID() == 0) { throw new ArgumentException("CommissionAPInvoice - No BPartner"); } // Create Invoice MInvoice invoice = new MInvoice(GetCtx(), 0, null); invoice.SetClientOrg(com.GetAD_Client_ID(), com.GetAD_Org_ID()); invoice.SetC_DocTypeTarget_ID(MDocBaseType.DOCBASETYPE_APINVOICE); // API invoice.SetBPartner(bp); // invoice.setDocumentNo (comRun.getDocumentNo()); // may cause unique constraint invoice.SetSalesRep_ID(GetAD_User_ID()); // caller // if (com.GetC_Currency_ID() != invoice.GetC_Currency_ID()) { throw new ArgumentException("CommissionAPInvoice - Currency of PO Price List not Commission Currency"); } // if (!invoice.Save()) { throw new Exception("CommissionAPInvoice - cannot save Invoice"); } // Create Invoice Line MInvoiceLine iLine = new MInvoiceLine(invoice); iLine.SetC_Charge_ID(com.GetC_Charge_ID()); iLine.SetQty(1); iLine.SetPrice(comRun.GetGrandTotal()); iLine.SetTax(); if (!iLine.Save()) { throw new Exception("CommissionAPInvoice - cannot save Invoice Line"); } // return("@C_Invoice_ID@ = " + invoice.GetDocumentNo()); }
/** * 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) { if (_invoice == null) { _invoice = new MInvoice(order, 0, _DateInvoiced); if (!_invoice.Save()) { throw new Exception("Could not create Invoice (s)"); } } #region Comment Create Shipment Comment Line // Create Shipment Comment Line //if (_ship == null // || _ship.GetM_InOut_ID() != ship.GetM_InOut_ID()) //{ // MDocType dt = MDocType.Get(GetCtx(), ship.GetC_DocType_ID()); // if (_bp == null || _bp.GetC_BPartner_ID() != ship.GetC_BPartner_ID()) // { // _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() && _bp.GetAD_Language() != null) // { // AD_Language = _bp.GetAD_Language(); // } // if (AD_Language == null) // { // // MessageBox.Show("Set base Language"); // //AD_Language = Language.getBaseAD_Language(); // } // //java.text.SimpleDateFormat format = DisplayType.getDateFormat // // (DisplayType.Date, Language.getLanguage(AD_Language)); // //String reference = dt.GetPrintName(_bp.GetAD_Language()) // // + ": " + ship.GetDocumentNo() // // + " - " + format.format(ship.GetMovementDate()); // String reference = dt.GetPrintName(_bp.GetAD_Language()) // + ": " + ship.GetDocumentNo() // + " - " + ship.GetMovementDate(); // _ship = ship; // // // MInvoiceLine line = new MInvoiceLine(_invoice); // line.SetIsDescription(true); // line.SetDescription(reference); // line.SetLine(_line + sLine.GetLine() - 2); // if (!line.Save()) // { // throw new Exception("Could not create Invoice Comment Line (sh)"); // } // // Optional Ship Address if not Bill Address // if (order.GetBill_Location_ID() != ship.GetC_BPartner_Location_ID()) // { // MLocation addr = MLocation.GetBPLocation(GetCtx(), ship.GetC_BPartner_Location_ID(), null); // line = new MInvoiceLine(_invoice); // line.SetIsDescription(true); // line.SetDescription(addr.ToString()); // line.SetLine(_line + sLine.GetLine() - 1); // if (!line.Save()) // { // throw new Exception("Could not create Invoice Comment Line 2 (sh)"); // } // } //} #endregion // MInvoiceLine line1 = new MInvoiceLine(_invoice); line1.SetShipLine(sLine); line1.SetQtyEntered(sLine.GetQtyEntered()); line1.SetQtyInvoiced(sLine.GetMovementQty()); line1.SetLine(_line + sLine.GetLine()); line1.SetM_AttributeSetInstance_ID(sLine.GetM_AttributeSetInstance_ID()); if (!line1.Save()) { throw new Exception("Could not create Invoice Line (s)"); } // Link sLine.SetIsInvoiced(true); if (!sLine.Save()) { throw new Exception("Could not update Shipment Line"); } log.Fine(line1.ToString()); }
public bool SetProductQty(int recordID, string keyColName, List <string> product, List <string> attribute, List <string> qty, List <string> qtybook, List <string> oline_ID, int ordID, List <string> locID, int lineID, VAdvantage.Utility.Ctx ctx) { if (keyColName.ToUpper().Trim() == "C_ORDER_ID") { MOrder ord = new MOrder(ctx, recordID, null); for (int i = 0; i < product.Count; i++) { MOrderLine oline = new MOrderLine(ctx, lineID, null); oline.SetAD_Client_ID(ord.GetAD_Client_ID()); oline.SetAD_Org_ID(ord.GetAD_Org_ID()); oline.SetM_Product_ID(Util.GetValueOfInt(product[i])); oline.SetQty(Util.GetValueOfDecimal(qty[i])); oline.SetC_Order_ID(recordID); if (Util.GetValueOfInt(attribute[i]) != 0) { oline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i])); } if (!ord.IsSOTrx()) { MProduct pro = new MProduct(ctx, oline.GetM_Product_ID(), null); String qryUom = "SELECT vdr.C_UOM_ID FROM M_Product p LEFT JOIN M_Product_Po vdr ON p.M_Product_ID= vdr.M_Product_ID WHERE p.M_Product_ID=" + oline.GetM_Product_ID() + " AND vdr.C_BPartner_ID = " + ord.GetC_BPartner_ID(); int uom = Util.GetValueOfInt(DB.ExecuteScalar(qryUom)); if (pro.GetC_UOM_ID() != 0) { if (pro.GetC_UOM_ID() != uom && uom != 0) { decimal?Res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND M_Product_ID= " + oline.GetM_Product_ID() + " AND IsActive='Y'")); if (Res > 0) { oline.SetQtyEntered(oline.GetQtyEntered() * Res); //OrdQty = MUOMConversion.ConvertProductTo(GetCtx(), _M_Product_ID, UOM, OrdQty); } else { decimal?res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND IsActive='Y'")); if (res > 0) { oline.SetQtyEntered(oline.GetQtyEntered() * res); //OrdQty = MUOMConversion.Convert(GetCtx(), prdUOM, UOM, OrdQty); } } oline.SetC_UOM_ID(uom); } else { oline.SetC_UOM_ID(pro.GetC_UOM_ID()); } } } if (!oline.Save()) { } } } else if (keyColName.ToUpper().Trim() == "C_INVOICE_ID") { MInvoice inv = new MInvoice(ctx, recordID, null); for (int i = 0; i < product.Count; i++) { MInvoiceLine invline = new MInvoiceLine(ctx, lineID, null); invline.SetAD_Client_ID(inv.GetAD_Client_ID()); invline.SetAD_Org_ID(inv.GetAD_Org_ID()); invline.SetM_Product_ID(Util.GetValueOfInt(product[i])); invline.SetQty(Util.GetValueOfDecimal(qty[i])); invline.SetC_Invoice_ID(recordID); if (Util.GetValueOfInt(attribute[i]) != 0) { invline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i])); } if (!inv.IsSOTrx()) { MProduct pro = new MProduct(ctx, invline.GetM_Product_ID(), null); String qryUom = "SELECT vdr.C_UOM_ID FROM M_Product p LEFT JOIN M_Product_Po vdr ON p.M_Product_ID= vdr.M_Product_ID WHERE p.M_Product_ID=" + invline.GetM_Product_ID() + " AND vdr.C_BPartner_ID = " + inv.GetC_BPartner_ID(); int uom = Util.GetValueOfInt(DB.ExecuteScalar(qryUom)); if (pro.GetC_UOM_ID() != 0) { if (pro.GetC_UOM_ID() != uom && uom != 0) { decimal?Res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND M_Product_ID= " + invline.GetM_Product_ID() + " AND IsActive='Y'")); if (Res > 0) { invline.SetQtyEntered(invline.GetQtyEntered() * Res); //OrdQty = MUOMConversion.ConvertProductTo(GetCtx(), _M_Product_ID, UOM, OrdQty); } else { decimal?res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND IsActive='Y'")); if (res > 0) { invline.SetQtyEntered(invline.GetQtyEntered() * res); //OrdQty = MUOMConversion.Convert(GetCtx(), prdUOM, UOM, OrdQty); } } invline.SetC_UOM_ID(uom); } else { invline.SetC_UOM_ID(pro.GetC_UOM_ID()); } } } if (!invline.Save()) { } } } else if (keyColName.ToUpper().Trim() == "M_INOUT_ID") { MInOut inv = new MInOut(ctx, recordID, null); if (ordID > 0) { inv.SetC_Order_ID(ordID); } if (inv.Save()) { for (int i = 0; i < product.Count; i++) { MInOutLine ioline = new MInOutLine(ctx, lineID, null); ioline.SetAD_Client_ID(inv.GetAD_Client_ID()); ioline.SetAD_Org_ID(inv.GetAD_Org_ID()); ioline.SetM_Product_ID(Util.GetValueOfInt(product[i])); ioline.SetQty(Util.GetValueOfDecimal(qty[i])); ioline.SetM_InOut_ID(recordID); ioline.SetC_OrderLine_ID(Util.GetValueOfInt(oline_ID[i])); ioline.SetM_Locator_ID(Util.GetValueOfInt(locID[i])); if (Util.GetValueOfInt(attribute[i]) != 0) { ioline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i])); } if (!inv.IsSOTrx()) { MProduct pro = new MProduct(ctx, ioline.GetM_Product_ID(), null); String qryUom = "SELECT vdr.C_UOM_ID FROM M_Product p LEFT JOIN M_Product_Po vdr ON p.M_Product_ID= vdr.M_Product_ID WHERE p.M_Product_ID=" + ioline.GetM_Product_ID() + " AND vdr.C_BPartner_ID = " + inv.GetC_BPartner_ID(); int uom = Util.GetValueOfInt(DB.ExecuteScalar(qryUom)); if (pro.GetC_UOM_ID() != 0) { if (pro.GetC_UOM_ID() != uom && uom != 0) { decimal?Res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND M_Product_ID= " + ioline.GetM_Product_ID() + " AND IsActive='Y'")); if (Res > 0) { ioline.SetQtyEntered(ioline.GetQtyEntered() * Res); //OrdQty = MUOMConversion.ConvertProductTo(GetCtx(), _M_Product_ID, UOM, OrdQty); } else { decimal?res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND IsActive='Y'")); if (res > 0) { ioline.SetQtyEntered(ioline.GetQtyEntered() * res); //OrdQty = MUOMConversion.Convert(GetCtx(), prdUOM, UOM, OrdQty); } } ioline.SetC_UOM_ID(uom); } else { ioline.SetC_UOM_ID(pro.GetC_UOM_ID()); } } } if (!ioline.Save()) { } } } } else if (keyColName.ToUpper().Trim() == "M_PACKAGE_ID") { MPackage pkg = new MPackage(ctx, recordID, null); for (int i = 0; i < product.Count; i++) { MPackageLine mline = new MPackageLine(ctx, lineID, null); mline.SetAD_Client_ID(pkg.GetAD_Client_ID()); mline.SetAD_Org_ID(pkg.GetAD_Org_ID()); mline.SetM_Product_ID(Util.GetValueOfInt(product[i])); mline.SetQty(Util.GetValueOfDecimal(qty[i])); if (Util.GetValueOfInt(oline_ID[i]) > 0) { mline.SetM_MovementLine_ID(Util.GetValueOfInt(oline_ID[i])); MMovementLine mov = new MMovementLine(ctx, Util.GetValueOfInt(oline_ID[i]), null); mline.SetDTD001_TotalQty(mov.GetMovementQty()); } if (Util.GetValueOfInt(attribute[i]) != 0) { mline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i])); } mline.SetM_Package_ID(recordID); if (!mline.Save()) { } } } else if (keyColName.ToUpper().Trim() == "M_INVENTORY_ID") { MInventory inv = new MInventory(ctx, recordID, null); for (int i = 0; i < product.Count; i++) { MInventoryLine invline = new MInventoryLine(ctx, lineID, null); invline.SetAD_Client_ID(inv.GetAD_Client_ID()); invline.SetAD_Org_ID(inv.GetAD_Org_ID()); invline.SetM_Locator_ID(Util.GetValueOfInt(locID[i])); invline.SetM_Product_ID(Util.GetValueOfInt(product[i])); invline.SetQtyCount(Util.GetValueOfDecimal(qty[i])); invline.SetQtyBook(Util.GetValueOfDecimal(qtybook[i])); invline.SetAsOnDateCount(Util.GetValueOfDecimal(qty[i])); invline.SetOpeningStock(Util.GetValueOfDecimal(qtybook[i])); invline.SetM_Inventory_ID(recordID); if (Util.GetValueOfInt(attribute[i]) != 0) { invline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i])); } else { invline.SetM_AttributeSetInstance_ID(0); } if (!invline.Save()) { } } } return(true); }
/// <summary> /// Create Shipment /// </summary> /// <returns>info</returns> protected override String DoIt() { //log.info("C_Invoice_ID=" + _C_Invoice_ID // + ", M_Warehouse_ID=" + _M_Warehouse_ID // + ", C_DocType_ID=" + _C_DocType_ID); if (_C_Invoice_ID == 0) { throw new ArgumentException("@NotFound@ @C_Invoice_ID@"); } if (_M_Warehouse_ID == 0) { throw new ArgumentException("@NotFound@ @M_Warehouse_ID@"); } // MInvoice invoice = new MInvoice(GetCtx(), _C_Invoice_ID, Get_Trx()); if (invoice.Get_ID() == 0) { throw new ArgumentException("@NotFound@ @C_Invoice_ID@"); } if (!MInvoice.DOCSTATUS_Completed.Equals(invoice.GetDocStatus())) { throw new ArgumentException("@InvoiceCreateDocNotCompleted@"); } MDocType dt = MDocType.Get(GetCtx(), _C_DocType_ID); if (invoice.IsSOTrx() != dt.IsSOTrx() || invoice.IsReturnTrx() != dt.IsReturnTrx()) { throw new ArgumentException("@C_DocType_ID@ <> @C_Invoice_ID@"); } //*****************************Vikas 1 Dec 2015 ********************************* //Case Msg Not Showing Proper MInOut ship = null; MOrder ord = new MOrder(GetCtx(), invoice.GetC_Order_ID(), null); if (ord.GetC_BPartner_ID() > 0) { ship = new MInOut(invoice, _C_DocType_ID, null, _M_Warehouse_ID); // Change by Mohit Asked by Amardeep sir 02/03/2016 ship.SetPOReference(invoice.GetPOReference()); // End if (!ship.Save()) { return(GetRetrievedError(ship, "@SaveError@ Receipt")); // throw new ArgumentException("@SaveError@ Receipt"); } } else { return(GetRetrievedError(ship, "InvoiceNotLinkedWithPO")); //throw new ArgumentException("@InvoiceNotLinkedWithPO@"); } /* * MInOut ship = new MInOut(invoice, _C_DocType_ID, null, _M_Warehouse_ID); * if (!ship.Save()) * { * throw new ArgumentException("@SaveError@ Receipt"); * } */ //************************END***************************************** MInvoiceLine[] invoiceLines = invoice.GetLines(false); for (int i = 0; i < invoiceLines.Length; i++) { MInvoiceLine invoiceLine = invoiceLines[i]; MProduct product = invoiceLine.GetProduct(); // Nothing to Deliver // Get the lines of Invoice based on the setting taken on Tenant to allow non item Product if (Util.GetValueOfString(GetCtx().GetContext("$AllowNonItem")).Equals("N") && ((product != null && product.GetProductType() != MProduct.PRODUCTTYPE_Item) || invoiceLine.GetC_Charge_ID() != 0)) { continue; } MInOutLine sLine = new MInOutLine(ship); //JID_1679 Generate Receipt from Invoice(Vendor) for remaining quantity //decimal movementqty = 0; //if (invoiceLine.GetC_OrderLine_ID() != 0) //{ // decimal? res = 0; // movementqty = Util.GetValueOfDecimal(DB.ExecuteScalar(@" select (QtyOrdered-sum(MovementQty)) from C_OrderLine ol Inner join M_InOutLine il on il.C_orderline_ID= ol.C_Orderline_Id " // + " WHERE il.C_OrderLine_ID =" + invoiceLine.GetC_OrderLine_ID() + "group by QtyOrdered", null, Get_Trx())); // // in case of partial receipt // if (invoiceLine.GetQtyInvoiced() > movementqty && movementqty != 0) // { // if (product.GetC_UOM_ID() != invoiceLine.GetC_UOM_ID()) // { // res = MUOMConversion.ConvertProductTo(GetCtx(), product.GetM_Product_ID(), invoiceLine.GetC_UOM_ID(), movementqty); // } // sLine.SetInvoiceLine(invoiceLine, 0, // Locator // invoice.IsSOTrx() ? (movementqty) : Env.ZERO); // sLine.SetQtyEntered(res == 0 ? (movementqty) : res); // sLine.SetMovementQty(movementqty); // } // // if QtyInvoiced is less or No Material receipt is found against the order // else // { // sLine.SetInvoiceLine(invoiceLine, 0, // Locator // invoice.IsSOTrx() ? invoiceLine.GetQtyInvoiced() : Env.ZERO); // sLine.SetQtyEntered(invoiceLine.GetQtyEntered()); // sLine.SetMovementQty(invoiceLine.GetQtyInvoiced()); // } //} //else //{ sLine.SetInvoiceLine(invoiceLine, 0, // Locator invoice.IsSOTrx() ? invoiceLine.GetQtyInvoiced() : Env.ZERO); sLine.SetQtyEntered(invoiceLine.GetQtyEntered()); sLine.SetMovementQty(invoiceLine.GetQtyInvoiced()); //} if (invoice.IsCreditMemo()) { sLine.SetQtyEntered(Decimal.Negate(sLine.GetQtyEntered())); //.negate()); sLine.SetMovementQty(Decimal.Negate(sLine.GetMovementQty())); //.negate()); } if (!sLine.Save()) { ship.Get_Trx().Rollback(); //if (movementqty == 0) //{ // _processMsg += ", LineNo: " + invoiceLine.GetLine() + Msg.GetMsg(GetCtx(), "MRIsAlreadyCreated"); // return _processMsg; //} //else //{ return(GetRetrievedError(sLine, "@SaveError@ @M_InOutLine_ID@")); //} // throw new ArgumentException("@SaveError@ @M_InOutLine_ID@"); } invoiceLine.SetM_InOutLine_ID(sLine.GetM_InOutLine_ID()); // _processMsg+= ", LineNo: "+invoiceLine.GetLine()+Msg.GetMsg(GetCtx(), "MRCreatedWithDocNo" + ship.GetDocumentNo()); if (!invoiceLine.Save()) { return(GetRetrievedError(invoiceLine, "@SaveError@ @C_InvoiceLine_ID@")); //throw new ArgumentException("@SaveError@ @C_InvoiceLine_ID@"); } } return(ship.GetDocumentNo()); }
// 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); } }
protected override String DoIt() { MInvoice obj = new MInvoice(GetCtx(), GetRecord_ID(), Get_Trx()); // get Precision for rounding MCurrency currency = new MCurrency(GetCtx(), obj.GetC_Currency_ID(), Get_Trx()); precision = currency.GetStdPrecision(); MInvoiceLine[] lines = obj.GetLines(); if (_IsCLearDiscount == "N") { if (_DiscountAmt == 0 && _DiscountPercent == 0) { return(Msg.GetMsg(GetCtx(), "PlsSelAtlstOneField")); } if (_DiscountAmt != 0 && _DiscountPercent != 0) { return(Msg.GetMsg(GetCtx(), "PlsSelOneField")); } // get amount on which we have to apply discount subTotal = obj.GetTotalLines(); // when we are giving discount in terms of amount, then we have to calculate discount in term of percentage discountPercentageOnTotalAmount = GetDiscountPercentageOnTotal(subTotal, _DiscountAmt, precision); for (int i = 0; i < lines.Length; i++) { MInvoiceLine ln = lines[i]; // this value represent discount on line net amount discountAmountOnTotal = GetDiscountAmountOnTotal(ln.GetLineNetAmt(), discountPercentageOnTotalAmount != 0 ? discountPercentageOnTotalAmount : _DiscountPercent); // this value represent discount on unit price of 1 qty discountAmountOnTotal = Decimal.Round(Decimal.Divide(discountAmountOnTotal, ln.GetQtyEntered()), precision); ln.SetAmountAfterApplyDiscount(Decimal.Add(ln.GetAmountAfterApplyDiscount(), discountAmountOnTotal)); ln.SetPriceActual(Decimal.Round(Decimal.Subtract(ln.GetPriceActual(), discountAmountOnTotal), precision)); ln.SetPriceEntered(Decimal.Round(Decimal.Subtract(ln.GetPriceEntered(), discountAmountOnTotal), precision)); // set tax amount as 0, so that on before save we calculate tax again on discounted price ln.SetTaxAmt(0); if (!ln.Save(Get_TrxName())) { Rollback(); ValueNamePair pp = VLogger.RetrieveError(); log.Info("ApplyDiscountInvoiceVendor : Not Saved. Error Value : " + pp.GetValue() + " , Error Name : " + pp.GetName()); throw new Exception(Msg.GetMsg(GetCtx(), "DiscNotApplied")); } } return(Msg.GetMsg(GetCtx(), "DiscAppliedSuccess")); } else { for (int i = 0; i < lines.Length; i++) { MInvoiceLine ln = lines[i]; ln.SetPriceEntered(Decimal.Add(ln.GetPriceEntered(), ln.GetAmountAfterApplyDiscount())); ln.SetPriceActual(Decimal.Add(ln.GetPriceActual(), ln.GetAmountAfterApplyDiscount())); ln.SetAmountAfterApplyDiscount(0); ln.SetTaxAmt(0); if (!ln.Save(Get_TrxName())) { Rollback(); ValueNamePair pp = VLogger.RetrieveError(); log.Info("ApplyDiscountInvoiceVendor : Not Saved. Error Value : " + pp.GetValue() + " , Error Name : " + pp.GetName()); throw new Exception(Msg.GetMsg(GetCtx(), "DiscNotCleared")); } } return(Msg.GetMsg(GetCtx(), "DiscClearedSuccessfully")); } }
/// <summary> /// Create Invoice. /// </summary> /// <returns>document no</returns> protected override String DoIt() { StringBuilder invDocumentNo = new StringBuilder(); int count = Util.GetValueOfInt(DB.ExecuteScalar(" SELECT Count(*) FROM M_Inout WHERE ISSOTRX='Y' AND M_Inout_ID=" + GetRecord_ID())); MInOut ship = null; bool isAllownonItem = Util.GetValueOfString(GetCtx().GetContext("$AllowNonItem")).Equals("Y"); if (count > 0) { if (_M_InOut_ID == 0) { throw new ArgumentException("No Shipment"); } // ship = new MInOut(GetCtx(), _M_InOut_ID, Get_Trx()); if (ship.Get_ID() == 0) { throw new ArgumentException("Shipment not found"); } if (!MInOut.DOCSTATUS_Completed.Equals(ship.GetDocStatus())) { // JID_0750: done by Bharat on 05 Feb 2019 if Customer Return document and status is not complete it should give message "Customer Return Not Completed". if (ship.IsReturnTrx()) { throw new ArgumentException("Customer Return Not Completed"); } else { throw new ArgumentException("Shipment Not Completed"); } } } else { if (_M_InOut_ID == 0) { throw new ArgumentException("No Material Receipt"); } // ship = new MInOut(GetCtx(), _M_InOut_ID, Get_Trx()); if (ship.Get_ID() == 0) { throw new ArgumentException("Material Receipt not found"); } if (!MInOut.DOCSTATUS_Completed.Equals(ship.GetDocStatus())) { // JID_0750: done by Bharat on 05 Feb 2019 if Return to vendor document and status is not complete it should give message "Return To Vendor Not Completed". if (ship.IsReturnTrx()) { throw new ArgumentException("Return To Vendor Not Completed"); } else { throw new ArgumentException("Material Receipt Not Completed"); } } } // When record contain more than single order and order having different Payment term or Price List then not to generate invoices // JID_0976 - For conversion Type if (ship.GetC_Order_ID() > 0 && Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT COUNT(DISTINCT c_order.m_pricelist_id) + count(distinct c_order.c_paymentterm_id) + count(distinct COALESCE( c_order.C_ConversionType_ID , " + MConversionType.GetDefault(GetAD_Client_ID()) + @")) as recordcount FROM m_inoutline INNER JOIN c_orderline ON m_inoutline.c_orderline_id = c_orderline.c_orderline_id INNER JOIN c_order ON c_order.c_order_id = c_orderline.c_order_id WHERE m_inoutline.m_inout_id = " + _M_InOut_ID + @" GROUP BY m_inoutline.m_inout_id ", null, Get_Trx())) > 3) { if (ship.IsSOTrx()) { //Different Payment Terms, Price list found against the selected orders, use "Generate Invoice" process to create multiple invoices. throw new ArgumentException(Msg.GetMsg(GetCtx(), "VIS_SoDifferentPayAndPrice")); } else { //Different Payment Terms, Price list found against the selected orders throw new ArgumentException(Msg.GetMsg(GetCtx(), "VIS_DifferentPayAndPrice")); } } // Create Invoice Header MInvoice invoice = new MInvoice(ship, null); //Payment Management int _CountVA009 = Env.IsModuleInstalled("VA009_") ? 1 : 0; // Amortization int _CountVA038 = Env.IsModuleInstalled("VA038_") ? 1 : 0; if (_CountVA009 > 0) { int _PaymentMethod_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select VA009_PaymentMethod_ID From C_Order Where C_Order_ID=" + ship.GetC_Order_ID(), null, Get_Trx())); // during consolidation, payment method need to set that is defined on selected business partner. // If not defined on BP then it will set from order int bpPamentMethod_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT " + (ship.IsSOTrx() ? " VA009_PaymentMethod_ID " : " VA009_PO_PaymentMethod_ID ") + @" FROM C_BPartner WHERE C_BPartner_ID = " + ship.GetC_BPartner_ID(), null, Get_Trx())); if (bpPamentMethod_ID != 0) { _PaymentMethod_ID = bpPamentMethod_ID; } if (_PaymentMethod_ID > 0) { invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID); } } // Letter Of Credit int _CountVA026 = Env.IsModuleInstalled("VA026_") ? 1 : 0; if (_CountVA026 > 0) { int VA026_LCDetail_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select VA026_LCDetail_ID From C_Order Where C_Order_ID=" + ship.GetC_Order_ID(), null, Get_Trx())); if (VA026_LCDetail_ID > 0) { invoice.SetVA026_LCDetail_ID(VA026_LCDetail_ID); } } //end if (ship.IsReturnTrx()) { if (!ship.IsSOTrx()) { // Purchase Return // set target document from documnet type window -- based on documnet type available on material receipt / return to vendor // JID_0779: Create AP Credit memo if we run the Generate TO process from Returm to Vendor window. //if (invoice.GetC_DocTypeTarget_ID() == 0) //{ if (_C_DocType_ID > 0) { invoice.SetC_DocTypeTarget_ID(_C_DocType_ID); } else { int C_DocTypeTarget_ID = DB.GetSQLValue(null, "SELECT C_DocTypeInvoice_ID FROM C_DocType WHERE C_DocType_ID=@param1", ship.GetC_DocType_ID()); if (C_DocTypeTarget_ID > 0) { invoice.SetC_DocTypeTarget_ID(C_DocTypeTarget_ID); } else { invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO); } } invoice.SetIsReturnTrx(ship.IsReturnTrx()); invoice.SetIsSOTrx(ship.IsSOTrx()); } else { // Sales Return if (_C_DocType_ID > 0) { invoice.SetC_DocTypeTarget_ID(_C_DocType_ID); } else { if (ship.GetC_Order_ID() >= 0) { int C_DocType_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select C_DocType_ID From C_Order Where C_Order_ID=" + ship.GetC_Order_ID(), null, Get_Trx())); MDocType dt = MDocType.Get(GetCtx(), C_DocType_ID); if (dt.GetC_DocTypeInvoice_ID() != 0) { invoice.SetC_DocTypeTarget_ID(dt.GetC_DocTypeInvoice_ID(), true); } else { invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO); } } else { invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO); } } } } if (_M_PriceList_ID != 0) { invoice.SetM_PriceList_ID(_M_PriceList_ID); } //Set InvoiceDocumentNo to InvoiceReference if (_InvoiceDocumentNo != null && _InvoiceDocumentNo.Length > 0) { invoice.Set_Value("InvoiceReference", _InvoiceDocumentNo); } //Set TargetDoctype if (_C_DocType_ID > 0 && !ship.IsReturnTrx()) { invoice.Set_Value("C_DocTypeTarget_ID", _C_DocType_ID); } // Added by Bharat on 30 Jan 2018 to set Inco Term from Order if (invoice.Get_ColumnIndex("C_IncoTerm_ID") > 0) { invoice.SetC_IncoTerm_ID(ship.GetC_IncoTerm_ID()); } //To get Payment Rule and set the Payment method if (invoice.GetPaymentRule() != "") { invoice.SetPaymentMethod(invoice.GetPaymentRule()); } if (!invoice.Save()) { //SI_0708 - message was not upto the mark ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError(); if (pp != null) { throw new ArgumentException("Cannot save Invoice. " + pp.GetName()); } throw new ArgumentException("Cannot save Invoice"); } MInOutLine[] shipLines = ship.GetLines(false); DateTime? AmortStartDate = null; DateTime? AmortEndDate = null; count = 0; DataSet ds = null; DataSet dsDoc = null; for (int i = 0; i < shipLines.Length; i++) { MInOutLine sLine = shipLines[i]; // Changes done by Bharat on 06 July 2017 restrict to create invoice if Invoice already created against that for same quantity string sql = @"SELECT ml.QtyEntered - SUM(COALESCE(li.QtyEntered,0)) as QtyEntered, ml.MovementQty- SUM(COALESCE(li.QtyInvoiced, 0)) as QtyInvoiced" + " FROM M_InOutLine ml INNER JOIN C_InvoiceLine li ON li.M_InOutLine_ID = ml.M_InOutLine_ID INNER JOIN C_Invoice ci ON ci.C_Invoice_ID = li.C_Invoice_ID " + " WHERE ci.DocStatus NOT IN ('VO', 'RE') AND ml.M_InOutLine_ID =" + sLine.GetM_InOutLine_ID() + " GROUP BY ml.MovementQty, ml.QtyEntered"; ds = DB.ExecuteDataset(sql, null, Get_Trx()); if (ds != null && ds.Tables[0].Rows.Count > 0) { decimal qtyEntered = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["QtyEntered"]); decimal qtyInvoiced = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["QtyInvoiced"]); if (qtyEntered <= 0) { // Getting document number Count if Invoice already generated for Material Receipt string StrSql = "SELECT ci.DocumentNo,li.M_InOutLine_ID FROM C_InvoiceLine li INNER JOIN C_Invoice ci ON ci.C_Invoice_ID = li.C_Invoice_ID " + " WHERE ci.DocStatus NOT IN ('VO', 'RE') AND li.M_InOutLine_ID = " + sLine.GetM_InOutLine_ID(); dsDoc = DB.ExecuteDataset(StrSql, null, Get_Trx()); if (dsDoc != null && dsDoc.Tables[0].Rows.Count > 0) { for (int j = 0; j < dsDoc.Tables[0].Rows.Count; j++) { // JID_1358: Need to show document number in message if Invoice already generated for Material Receipt string no = invDocumentNo.ToString(); if (invDocumentNo.Length > 0 && no != Util.GetValueOfString(dsDoc.Tables[0].Rows[j]["DocumentNo"])) { invDocumentNo.Append(", " + Util.GetValueOfString(dsDoc.Tables[0].Rows[j]["DocumentNo"])); } else { invDocumentNo.Clear(); invDocumentNo.Append(Util.GetValueOfString(dsDoc.Tables[0].Rows[j]["DocumentNo"])); } ds.Dispose(); log.Info("Invoice Line already exist for Receipt Line ID - " + sLine.GetM_InOutLine_ID()); continue; } dsDoc.Dispose(); } } else { MInvoiceLine line = new MInvoiceLine(invoice); line.SetShipLine(sLine); line.SetQtyEntered(qtyEntered); line.SetQtyInvoiced(qtyInvoiced); // Change By Mohit Amortization process ------------- if (_CountVA038 > 0) { if (line.GetM_Product_ID() > 0) { //MProduct pro = new MProduct(GetCtx(), sLine.GetM_Product_ID(), Get_TrxName()); int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID FROM M_Product WHERE M_Product_ID = " + sLine.GetM_Product_ID(), null, Get_Trx())); if (VA038_AmortizationTemplate_ID > 0) { line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID); DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID); AmortStartDate = null; AmortEndDate = null; if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A") { AmortStartDate = invoice.GetDateAcct(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T") { AmortStartDate = invoice.GetDateInvoiced(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M") { AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y") { AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } line.Set_Value("FROMDATE", AmortStartDate); line.Set_Value("EndDate", AmortEndDate); if (amrtDS != null) { amrtDS.Dispose(); } } } if (line.GetC_Charge_ID() > 0) { //MCharge charge = new MCharge(GetCtx(), sLine.GetC_Charge_ID(), Get_TrxName()); int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID FROM C_Charge WHERE C_Charge_ID = " + sLine.GetC_Charge_ID(), null, Get_Trx())); if (VA038_AmortizationTemplate_ID > 0) { line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID); DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID); AmortStartDate = null; AmortEndDate = null; if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A") { AmortStartDate = invoice.GetDateAcct(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T") { AmortStartDate = invoice.GetDateInvoiced(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M") { AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y") { AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } line.Set_Value("FROMDATE", AmortStartDate); line.Set_Value("EndDate", AmortEndDate); if (amrtDS != null) { amrtDS.Dispose(); } } } } // End Change Amortization process-------------- if (!line.Save()) { //SI_0708 - message was not upto the mark ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError(); if (pp != null) { throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName()); } throw new ArgumentException("Cannot save Invoice Line"); } count++; } ds.Dispose(); } else { MInvoiceLine line = new MInvoiceLine(invoice); // JID_1850 Avoid the duplicate charge line if (sLine.GetC_Charge_ID() > 0 && (!isAllownonItem || _GenerateCharges)) { continue; } line.SetShipLine(sLine); line.SetQtyEntered(sLine.GetQtyEntered()); line.SetQtyInvoiced(sLine.GetMovementQty()); line.Set_ValueNoCheck("IsDropShip", sLine.Get_Value("IsDropShip")); //Arpit Rai 20-Sept-2017 // Change By Mohit Amortization process ------------- if (_CountVA038 > 0) { if (line.GetM_Product_ID() > 0) { //MProduct pro = new MProduct(GetCtx(), sLine.GetM_Product_ID(), Get_TrxName()); int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID FROM M_Product WHERE M_Product_ID = " + sLine.GetM_Product_ID(), null, Get_Trx())); if (VA038_AmortizationTemplate_ID > 0) { line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID); DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID); AmortStartDate = null; AmortEndDate = null; if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A") { AmortStartDate = invoice.GetDateAcct(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T") { AmortStartDate = invoice.GetDateInvoiced(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M") { AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y") { AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } line.Set_Value("FROMDATE", AmortStartDate); line.Set_Value("EndDate", AmortEndDate); if (amrtDS != null) { amrtDS.Dispose(); } } } if (line.GetC_Charge_ID() > 0) { //MCharge charge = new MCharge(GetCtx(), sLine.GetC_Charge_ID(), Get_TrxName()); int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID FROM C_Charge WHERE C_Charge_ID = " + sLine.GetC_Charge_ID(), null, Get_Trx())); if (VA038_AmortizationTemplate_ID > 0) { line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID); DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID); AmortStartDate = null; AmortEndDate = null; if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A") { AmortStartDate = invoice.GetDateAcct(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T") { AmortStartDate = invoice.GetDateInvoiced(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M") { AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y") { AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } line.Set_Value("FROMDATE", AmortStartDate); line.Set_Value("EndDate", AmortEndDate); if (amrtDS != null) { amrtDS.Dispose(); } } } } // End Change Amortization process-------------- if (!line.Save()) { //SI_0708 - message was not upto the mark ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError(); if (pp != null) { throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName()); } throw new ArgumentException("Cannot save Invoice Line"); } count++; } } #region [Enhancement for Charges Distribution/Generation by Sukhwinder on 13 December 2017] if (_GenerateCharges && count > 0) { StringBuilder OrderSql = new StringBuilder(); OrderSql.Append(" SELECT CO.C_ORDER_ID, " + " SUM(ML.QTYENTERED) AS MRLINEQTY, " + " SUM(OL.QTYENTERED) AS ORDERQTY " + " FROM M_INOUTLINE ML " + " INNER JOIN C_ORDERLINE OL " + " ON OL.C_ORDERLINE_ID = ML.C_ORDERLINE_ID " + " INNER JOIN C_ORDER CO " + " ON CO.C_ORDER_ID = OL.C_ORDER_ID " + " WHERE ML.M_INOUT_ID = " + _M_InOut_ID + " AND (OL.C_CHARGE_ID IS NULL " + " OR OL.C_CHARGE_ID = 0) " + " GROUP BY CO.C_ORDER_ID "); DataSet OrderDS = DB.ExecuteDataset(OrderSql.ToString(), null, Get_Trx()); if (OrderDS != null && OrderDS.Tables[0].Rows.Count > 0) { StringBuilder ChargesSql = new StringBuilder(); for (int index = 0; index < OrderDS.Tables[0].Rows.Count; index++) { ds = null; ChargesSql.Clear(); ChargesSql.Append(" SELECT C_CHARGE_ID, " + " C_ORDERLINE_ID, " + " C_ORDER_ID, " + " C_CURRENCY_ID, " + " PRICEENTERED, " + " PRICEACTUAL, " + " LINENETAMT, " + " QTYENTERED, " + " C_UOM_ID, " + " C_Tax_ID, " + " IsDropShip " + " FROM C_ORDERLINE " + " WHERE C_ORDER_ID IN " + " ( " + Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["C_ORDER_ID"]) + " ) " + " AND C_CHARGE_ID IS NOT NULL " + " AND C_CHARGE_ID > 0 "); ds = DB.ExecuteDataset(ChargesSql.ToString(), null, Get_Trx()); if (ds != null && ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { MInvoiceLine line = new MInvoiceLine(invoice); line.SetQty(1); line.SetQtyEntered(1); line.SetQtyInvoiced(1); line.SetOrderLine(new MOrderLine(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_ORDERLINE_ID"]), Get_Trx())); line.SetC_Charge_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_CHARGE_ID"])); line.SetC_UOM_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_UOM_ID"])); line.SetC_Tax_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_TAX_ID"])); decimal SumOfQty = 0; if (Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["ORDERQTY"]) == 0) { SumOfQty = 1; } else { SumOfQty = Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["ORDERQTY"]); } decimal amt = (Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["LINENETAMT"]) / SumOfQty) * Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["MRLINEQTY"]); line.SetPrice(Decimal.Round(amt, 3)); line.SetPriceActual(Decimal.Round(amt, 3)); line.SetPriceEntered(Decimal.Round(amt, 3)); line.SetLineNetAmt(Decimal.Round(amt, 3)); line.Set_ValueNoCheck("IsDropShip", Util.GetValueOfString(ds.Tables[0].Rows[i]["ISDROPSHIP"])); if (_CountVA038 > 0) { if (line.GetC_Charge_ID() > 0) { MCharge charge = new MCharge(GetCtx(), line.GetC_Charge_ID(), Get_TrxName()); if (Util.GetValueOfInt(charge.Get_Value("VA038_AmortizationTemplate_ID")) > 0) { line.Set_Value("VA038_AmortizationTemplate_ID", Util.GetValueOfInt(charge.Get_Value("VA038_AmortizationTemplate_ID"))); DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + Util.GetValueOfInt(charge.Get_Value("VA038_AmortizationTemplate_ID"))); AmortStartDate = null; AmortEndDate = null; if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A") { AmortStartDate = invoice.GetDateAcct(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T") { AmortStartDate = invoice.GetDateInvoiced(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M") { AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y") { AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } line.Set_Value("FROMDATE", AmortStartDate); line.Set_Value("EndDate", AmortEndDate); if (amrtDS != null) { amrtDS.Dispose(); } } } } if (!line.Save()) { //SI_0708 - message was not upto the mark ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError(); if (pp != null) { throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName()); } throw new ArgumentException("Cannot save Invoice Line"); } } } } } } #endregion if (count > 0) { return(invoice.GetDocumentNo()); } else { //Get_Trx().Rollback(); throw new ArgumentException(Msg.GetMsg(GetCtx(), "InvoiceExist") + ": " + invDocumentNo.ToString()); } }