Пример #1
0
        }       //	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
Пример #2
0
        }       //	MTaxDeclarationLine

        /// <summary>
        /// Parent Constructor
        /// </summary>
        /// <param name="parent">parent</param>
        /// <param name="invoice">invoice</param>
        /// <param name="tLine">tax line</param>
        public MTaxDeclarationLine(MTaxDeclaration parent, MInvoice invoice, MInvoiceTax tLine) : 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_Tax_ID(tLine.GetC_Tax_ID());
            SetTaxBaseAmt(tLine.GetTaxBaseAmt());
            SetTaxAmt(tLine.GetTaxAmt());
        } //	MTaxDeclarationLine
Пример #3
0
        // 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>
        /// 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());
            }
        }
Пример #5
0
        /**
         *  Apply Payment Term with schedule to Invoice
         *	@param invoice invoice
         *	@return true if payment schedule is valid
         */
        private bool ApplySchedule(MInvoice invoice)
        {
            DeleteInvoicePaySchedule(invoice.GetC_Invoice_ID(), invoice.Get_TrxName());
            //	Create Schedule
            MInvoicePaySchedule ips       = null;
            Decimal             remainder = invoice.GetGrandTotal();

            for (int i = 0; i < _schedule.Length; i++)
            {
                ips = new MInvoicePaySchedule(invoice, _schedule[i]);
                //int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));
                //if (_CountVA009 > 0)
                //{
                //    ips.SetVA009_ExecutionStatus("A");
                //    ips.SetC_DocType_ID(invoice.GetC_DocType_ID());
                //}
                int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));
                if (_CountVA009 > 0)
                {
                    ips.SetVA009_ExecutionStatus("A");
                    ips.SetC_DocType_ID(invoice.GetC_DocType_ID());

                    MOrder _Order = new MOrder(GetCtx(), invoice.GetC_Order_ID(), Get_TrxName());
                    ips.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                    ips.SetC_PaymentTerm_ID(invoice.GetC_PaymentTerm_ID());
                    ips.SetVA009_GrandTotal(invoice.GetGrandTotal());

                    MPaymentTerm payterm   = new MPaymentTerm(GetCtx(), invoice.GetC_PaymentTerm_ID(), Get_TrxName());
                    int          _graceDay = payterm.GetGraceDays();
                    //DateTime? _followUpDay = GetDueDate(invoice);
                    ips.SetVA009_FollowupDate(ips.GetDueDate().Value.AddDays(_graceDay));
                    //ips.SetVA009_PlannedDueDate(GetDueDate(invoice));
                    ips.SetVA009_PlannedDueDate(ips.GetDueDate());
                    //ips.SetDueDate(GetDueDate(invoice));

                    //change by amit 25-11-2015
                    StringBuilder _sql = new StringBuilder();
                    _sql.Clear();
                    _sql.Append(@"SELECT UNIQUE asch.C_Currency_ID FROM c_acctschema asch INNER JOIN ad_clientinfo ci ON ci.c_acctschema1_id = asch.c_acctschema_id
                                 INNER JOIN ad_client c ON c.ad_client_id = ci.ad_client_id INNER JOIN c_invoice i ON c.ad_client_id    = i.ad_client_id
                                 WHERE i.ad_client_id = " + invoice.GetAD_Client_ID());
                    int BaseCurrency = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString(), null, null));

                    if (BaseCurrency != invoice.GetC_Currency_ID())
                    {
                        _sql.Clear();
                        _sql.Append(@"SELECT multiplyrate FROM c_conversion_rate WHERE AD_Client_ID = " + invoice.GetAD_Client_ID() + " AND  c_currency_id  = " + invoice.GetC_Currency_ID() +
                                    " AND c_currency_to_id = " + BaseCurrency + " AND " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                        decimal multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                        if (multiplyRate == 0)
                        {
                            _sql.Clear();
                            _sql.Append(@"SELECT dividerate FROM c_conversion_rate WHERE AD_Client_ID = " + invoice.GetAD_Client_ID() + " AND c_currency_id  = " + BaseCurrency +
                                        " AND c_currency_to_id = " + invoice.GetC_Currency_ID() + " AND " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                            multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                        }
                        ips.SetVA009_OpenAmnt(ips.GetDueAmt() * multiplyRate);
                    }
                    else
                    {
                        ips.SetVA009_OpenAmnt(ips.GetDueAmt());
                    }

                    ips.SetC_Currency_ID(invoice.GetC_Currency_ID());
                    ips.SetVA009_BseCurrncy(BaseCurrency);
                    ips.SetVA009_OpnAmntInvce(ips.GetDueAmt());
                    ips.SetC_BPartner_ID(invoice.GetC_BPartner_ID());
                    //end

                    string  sql = "Select va009_paymentmode, va009_paymenttype, va009_paymenttrigger  From va009_paymentmethod where va009_paymentmethod_ID=" + invoice.GetVA009_PaymentMethod_ID() + "   AND IsActive = 'Y' AND AD_Client_ID = " + invoice.GetAD_Client_ID();
                    DataSet ds  = new DataSet();
                    ds = DB.ExecuteDataset(sql);
                    if (ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                        {
                            ips.SetVA009_PaymentMode(Util.GetValueOfString(ds.Tables[0].Rows[j]["va009_paymentmode"]));
                            ips.SetVA009_PaymentType(Util.GetValueOfString(ds.Tables[0].Rows[j]["va009_paymenttype"]));
                            ips.SetVA009_PaymentTrigger(Util.GetValueOfString(ds.Tables[0].Rows[j]["va009_paymenttrigger"]));
                            ips.SetVA009_ExecutionStatus("A");
                        }
                    }
                }
                ips.Save(invoice.Get_TrxName());
                log.Fine(ips.ToString());
                remainder = Decimal.Subtract(remainder, ips.GetDueAmt());
            }   //	for all schedules
            //	Remainder - update last
            if (remainder.CompareTo(Env.ZERO) != 0 && ips != null)
            {
                ips.SetDueAmt(Decimal.Add(ips.GetDueAmt(), remainder));
                ips.Save(invoice.Get_TrxName());
                log.Fine("Remainder=" + remainder + " - " + ips);
            }

            //	updateInvoice
            if (invoice.GetC_PaymentTerm_ID() != GetC_PaymentTerm_ID())
            {
                invoice.SetC_PaymentTerm_ID(GetC_PaymentTerm_ID());
            }
            return(invoice.ValidatePaySchedule());
        }
Пример #6
0
        /**
         *  Apply Payment Term without schedule to Invoice
         *	@param invoice invoice
         *	@return false as no payment schedule
         */
        private bool ApplyNoSchedule(MInvoice invoice)
        {
            DeleteInvoicePaySchedule(invoice.GetC_Invoice_ID(), invoice.Get_TrxName());
            //	updateInvoice
            if (invoice.GetC_PaymentTerm_ID() != GetC_PaymentTerm_ID())
            {
                invoice.SetC_PaymentTerm_ID(GetC_PaymentTerm_ID());
            }
            if (invoice.IsPayScheduleValid())
            {
                invoice.SetIsPayScheduleValid(false);
            }
            //----------------Anuj------11/09/2015------------------------
            int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));

            if (_CountVA009 > 0)
            {
                StringBuilder       _sql     = new StringBuilder();
                MInvoicePaySchedule schedule = new MInvoicePaySchedule(GetCtx(), 0, Get_TrxName());
                MPaymentTerm        payterm  = new MPaymentTerm(GetCtx(), invoice.GetC_PaymentTerm_ID(), Get_TrxName());
                schedule.SetAD_Client_ID(invoice.GetAD_Client_ID());
                schedule.SetAD_Org_ID(invoice.GetAD_Org_ID());
                schedule.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                schedule.SetC_DocType_ID(invoice.GetC_DocType_ID());
                schedule.SetC_PaymentTerm_ID(invoice.GetC_PaymentTerm_ID());
                schedule.SetVA009_GrandTotal(invoice.GetGrandTotal());
                schedule.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                schedule.SetDueDate(GetDueDate(invoice));
                schedule.SetDueAmt(invoice.GetGrandTotal());
                schedule.SetDiscountDate(invoice.GetDateInvoiced().Value.AddDays(Util.GetValueOfInt(payterm.GetDiscountDays())));
                schedule.SetDiscountAmt((Util.GetValueOfDecimal((invoice.GetGrandTotal() * payterm.GetDiscount()) / 100)));

                schedule.SetDiscountDays2(invoice.GetDateInvoiced().Value.AddDays(Util.GetValueOfInt(payterm.GetDiscountDays2())));
                schedule.SetDiscount2((Util.GetValueOfDecimal((invoice.GetGrandTotal() * payterm.GetDiscount2()) / 100)));

                schedule.SetVA009_PlannedDueDate(GetDueDate(invoice));

                _sql.Clear();
                _sql.Append(@"SELECT UNIQUE asch.C_Currency_ID FROM c_acctschema asch INNER JOIN ad_clientinfo ci ON ci.c_acctschema1_id = asch.c_acctschema_id
                                 INNER JOIN ad_client c ON c.ad_client_id = ci.ad_client_id INNER JOIN c_invoice i ON c.ad_client_id    = i.ad_client_id
                                 WHERE i.ad_client_id = " + invoice.GetAD_Client_ID());
                int BaseCurrency = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString(), null, null));

                if (BaseCurrency != invoice.GetC_Currency_ID())
                {
                    // change by amit
                    _sql.Clear();
                    _sql.Append(@"SELECT multiplyrate FROM c_conversion_rate WHERE AD_Client_ID = " + GetCtx().GetAD_Client_ID() + " AND c_currency_id  = " + invoice.GetC_Currency_ID() +
                                " AND c_currency_to_id = " + BaseCurrency + " AND  " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                    decimal multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                    if (multiplyRate == 0)
                    {
                        _sql.Clear();
                        _sql.Append(@"SELECT dividerate FROM c_conversion_rate WHERE AD_Client_ID = " + GetCtx().GetAD_Client_ID() + " AND c_currency_id  = " + BaseCurrency +
                                    " AND c_currency_to_id = " + invoice.GetC_Currency_ID() + " AND  " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                        multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                    }
                    schedule.SetVA009_OpenAmnt(invoice.GetGrandTotal() * multiplyRate);
                }
                else
                {
                    schedule.SetVA009_OpenAmnt(invoice.GetGrandTotal());
                }

                schedule.SetC_Currency_ID(invoice.GetC_Currency_ID());
                schedule.SetVA009_BseCurrncy(BaseCurrency);
                schedule.SetVA009_OpnAmntInvce(invoice.GetGrandTotal());
                schedule.SetC_BPartner_ID(invoice.GetC_BPartner_ID());

                MOrder _Order = new MOrder(GetCtx(), invoice.GetC_Order_ID(), Get_TrxName());
                //schedule.SetVA009_PaymentMethod_ID(_Order.GetVA009_PaymentMethod_ID());
                //schedule.SetC_PaymentTerm_ID(_Order.GetC_PaymentTerm_ID());

                int      _graceDay    = payterm.GetGraceDays();
                DateTime?_followUpDay = GetDueDate(invoice);
                schedule.SetVA009_FollowupDate(_followUpDay.Value.AddDays(_graceDay));
                _sql.Clear();
                _sql.Append("Select va009_paymentmode, va009_paymenttype, va009_paymenttrigger  From va009_paymentmethod where va009_paymentmethod_ID=" + invoice.GetVA009_PaymentMethod_ID() + "   AND IsActive = 'Y' AND AD_Client_ID = " + invoice.GetAD_Client_ID());
                DataSet ds = new DataSet();
                ds = DB.ExecuteDataset(_sql.ToString());
                if (ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        schedule.SetVA009_PaymentMode(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymentmode"]));
                        schedule.SetVA009_PaymentType(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymenttype"]));
                        schedule.SetVA009_PaymentTrigger(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymenttrigger"]));
                        schedule.SetVA009_ExecutionStatus("A");
                    }
                }
                if (!schedule.Save())
                {
                    return(false);
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #7
0
        /// <summary>
        /// Create Facts (the accounting logic) for
        ///  MXI.
        ///     (single line)
        ///  <pre>
        ///      NotInvoicedReceipts     DR			(Receipt Org)
        ///      InventoryClearing               CR
        ///      InvoicePV               DR      CR  (difference)
        ///  Commitment
        ///         Expense							CR
        ///         Offset					DR
        ///  </pre>
        /// </summary>
        /// <param name="as1"></param>
        /// <returns></returns>
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            List <Fact> facts = new List <Fact>();

            //  Nothing to do
            if (GetM_Product_ID() == 0 ||                               //	no Product
                Env.Signum(GetQty().Value) == 0 ||
                Env.Signum(_receiptLine.GetMovementQty()) == 0)         //	Qty = 0
            {
                log.Fine("No Product/Qty - M_Product_ID=" + GetM_Product_ID()
                         + ",Qty=" + GetQty() + ",InOutQty=" + _receiptLine.GetMovementQty());
                return(facts);
            }
            MMatchInv matchInv = (MMatchInv)GetPO();

            //  create Fact Header
            Fact fact = new Fact(this, as1, Fact.POST_Actual);

            SetC_Currency_ID(as1.GetC_Currency_ID());

            /**	Needs to be handeled in PO Matching as1 no Receipt info
             * if (_pc.isService())
             * {
             *  log.Fine("Service - skipped");
             *  return fact;
             * }
             **/


            //  NotInvoicedReceipt      DR
            //  From Receipt
            Decimal  multiplier = Math.Abs(Decimal.Round(Decimal.Divide(GetQty().Value, _receiptLine.GetMovementQty()), 12, MidpointRounding.AwayFromZero));
            FactLine dr         = fact.CreateLine(null,
                                                  GetAccount(Doc.ACCTTYPE_NotInvoicedReceipts, as1),
                                                  as1.GetC_Currency_ID(), Env.ONE, null); // updated below

            if (dr == null)
            {
                _error = "No Product Costs";
                return(null);
            }
            dr.SetQty(GetQty());
            //	dr.setM_Locator_ID(_receiptLine.getM_Locator_ID());
            //	MInOut receipt = _receiptLine.getParent();
            //	dr.setLocationFromBPartner(receipt.getC_BPartner_Location_ID(), true);	//  from Loc
            //	dr.setLocationFromLocator(_receiptLine.getM_Locator_ID(), false);		//  to Loc
            Decimal temp = dr.GetAcctBalance();

            //	Set AmtAcctCr/Dr from Receipt (sets also Project)
            if (!dr.UpdateReverseLine(MInOut.Table_ID,          //	Amt updated
                                      _receiptLine.GetM_InOut_ID(), _receiptLine.GetM_InOutLine_ID(),
                                      multiplier))
            {
                _error = "Mat.Receipt not posted yet";
                return(null);
            }
            log.Fine("CR - Amt(" + temp + "->" + dr.GetAcctBalance()
                     + ") - " + dr.ToString());

            //  InventoryClearing               CR
            //  From Invoice
            MAccount expense = _pc.GetAccount(ProductCost.ACCTTYPE_P_InventoryClearing, as1);

            if (_pc.IsService())
            {
                expense = _pc.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1);
            }
            Decimal LineNetAmt = _invoiceLine.GetLineNetAmt();

            multiplier = Math.Abs(Decimal.Round(Decimal.Divide(GetQty().Value, _invoiceLine.GetQtyInvoiced()), 12, MidpointRounding.AwayFromZero));
            if (multiplier.CompareTo(Env.ONE) != 0)
            {
                LineNetAmt = Decimal.Multiply(LineNetAmt, multiplier);
            }
            if (_pc.IsService())
            {
                LineNetAmt = dr.GetAcctBalance();       //	book out exact receipt amt
            }
            FactLine cr = null;

            if (as1.IsAccrual())
            {
                cr = fact.CreateLine(null, expense,
                                     as1.GetC_Currency_ID(), null, LineNetAmt); //	updated below
                if (cr == null)
                {
                    log.Fine("Line Net Amt=0 - M_Product_ID=" + GetM_Product_ID()
                             + ",Qty=" + GetQty() + ",InOutQty=" + _receiptLine.GetMovementQty());
                    facts.Add(fact);
                    return(facts);
                }
                cr.SetQty(Decimal.Negate(GetQty().Value));
                temp = cr.GetAcctBalance();
                //	Set AmtAcctCr/Dr from Invoice (sets also Project)
                if (as1.IsAccrual() && !cr.UpdateReverseLine(MInvoice.Table_ID,                 //	Amt updated
                                                             _invoiceLine.GetC_Invoice_ID(), _invoiceLine.GetC_InvoiceLine_ID(), multiplier))
                {
                    _error = "Invoice not posted yet";
                    return(null);
                }
                log.Fine("DR - Amt(" + temp + "->" + cr.GetAcctBalance()
                         + ") - " + cr.ToString());
            }
            else        //	Cash Acct
            {
                MInvoice invoice = _invoiceLine.GetParent();
                if (as1.GetC_Currency_ID() == invoice.GetC_Currency_ID())
                {
                    LineNetAmt = MConversionRate.Convert(GetCtx(), LineNetAmt,
                                                         invoice.GetC_Currency_ID(), as1.GetC_Currency_ID(),
                                                         invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(),
                                                         invoice.GetAD_Client_ID(), invoice.GetAD_Org_ID());
                }
                cr = fact.CreateLine(null, expense,
                                     as1.GetC_Currency_ID(), null, LineNetAmt);

                cr.SetQty(Decimal.Negate(Decimal.Multiply(GetQty().Value, multiplier)));
            }
            cr.SetC_Activity_ID(_invoiceLine.GetC_Activity_ID());
            cr.SetC_Campaign_ID(_invoiceLine.GetC_Campaign_ID());
            cr.SetC_Project_ID(_invoiceLine.GetC_Project_ID());
            cr.SetC_UOM_ID(_invoiceLine.GetC_UOM_ID());
            cr.SetUser1_ID(_invoiceLine.GetUser1_ID());
            cr.SetUser2_ID(_invoiceLine.GetUser2_ID());


            //  Invoice Price Variance  difference
            Decimal ipv = Decimal.Negate(Decimal.Add(cr.GetAcctBalance(), dr.GetAcctBalance()));

            if (Env.Signum(ipv) != 0)
            {
                FactLine pv = fact.CreateLine(null,
                                              _pc.GetAccount(ProductCost.ACCTTYPE_P_IPV, as1),
                                              as1.GetC_Currency_ID(), ipv);
                pv.SetC_Activity_ID(_invoiceLine.GetC_Activity_ID());
                pv.SetC_Campaign_ID(_invoiceLine.GetC_Campaign_ID());
                pv.SetC_Project_ID(_invoiceLine.GetC_Project_ID());
                pv.SetC_UOM_ID(_invoiceLine.GetC_UOM_ID());
                pv.SetUser1_ID(_invoiceLine.GetUser1_ID());
                pv.SetUser2_ID(_invoiceLine.GetUser2_ID());
            }
            log.Fine("IPV=" + ipv + "; Balance=" + fact.GetSourceBalance());

            MInOut inOut       = _receiptLine.GetParent();
            bool   isReturnTrx = inOut.IsReturnTrx();

            if (!IsPosted())
            {
                //	Cost Detail Record - data from Expense/IncClearing (CR) record
                MCostDetail.CreateInvoice(as1, GetAD_Org_ID(),
                                          GetM_Product_ID(), matchInv.GetM_AttributeSetInstance_ID(),
                                          _invoiceLine.GetC_InvoiceLine_ID(), 0,                                                                                                                  //	No cost element
                                          Decimal.Negate(cr.GetAcctBalance()), isReturnTrx ? Decimal.Negate(Utility.Util.GetValueOfDecimal(GetQty())) : Utility.Util.GetValueOfDecimal(GetQty()), //	correcting
                                          GetDescription(), GetTrx(), GetRectifyingProcess());

                //  Update Costing
                UpdateProductInfo(as1.GetC_AcctSchema_ID(),
                                  MAcctSchema.COSTINGMETHOD_StandardCosting.Equals(as1.GetCostingMethod()));
            }
            //
            facts.Add(fact);

            /** Commitment release										****/
            if (as1.IsAccrual() && as1.IsCreateCommitment())
            {
                fact = Doc_Order.GetCommitmentRelease(as1, this,
                                                      Utility.Util.GetValueOfDecimal(GetQty()), _invoiceLine.GetC_InvoiceLine_ID(), Env.ONE);
                if (fact == null)
                {
                    return(null);
                }
                facts.Add(fact);
            }   //	Commitment

            return(facts);
        }
Пример #8
0
        /// <summary>
        /// Process Allocation (does not update line).
        /// - Update and Link Invoice/Payment/Cash
        /// </summary>
        /// <param name="reverse">reverse if true allocation is reversed</param>
        /// <returns>C_BPartner_ID</returns>
        public int ProcessIt(bool reverse)
        {
            log.Fine("Reverse=" + reverse + " - " + ToString());
            int C_Invoice_ID = GetC_Invoice_ID();
            MInvoicePaySchedule invoiceSchedule = null;
            MPayment            payment         = null;
            MCashLine           cashLine        = null;
            MInvoice            invoice         = GetInvoice();

            if (invoice != null &&
                GetC_BPartner_ID() != invoice.GetC_BPartner_ID())
            {
                SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            }
            //
            int C_Payment_ID  = GetC_Payment_ID();
            int C_CashLine_ID = GetC_CashLine_ID();

            //	Update Payment
            if (C_Payment_ID != 0)
            {
                payment = new MPayment(GetCtx(), C_Payment_ID, Get_TrxName());
                if (GetC_BPartner_ID() != payment.GetC_BPartner_ID())
                {
                    log.Warning("C_BPartner_ID different - Invoice=" + GetC_BPartner_ID() + " - Payment=" + payment.GetC_BPartner_ID());
                }
                if (reverse)
                {
                    if (!payment.IsCashTrx())
                    {
                        payment.SetIsAllocated(false);
                        payment.Save();
                    }
                }
                else
                {
                    if (payment.TestAllocation())
                    {
                        payment.Save();
                    }
                }
            }

            //	Payment - Invoice
            if (C_Payment_ID != 0 && invoice != null)
            {
                //	Link to Invoice
                if (reverse)
                {
                    invoice.SetC_Payment_ID(0);
                    log.Fine("C_Payment_ID=" + C_Payment_ID
                             + " Unlinked from C_Invoice_ID=" + C_Invoice_ID);
                }
                else if (invoice.IsPaid())
                {
                    invoice.SetC_Payment_ID(C_Payment_ID);
                    log.Fine("C_Payment_ID=" + C_Payment_ID
                             + " Linked to C_Invoice_ID=" + C_Invoice_ID);
                }

                //	Link to Order
                String update = "UPDATE C_Order o "
                                + "SET C_Payment_ID="
                                + (reverse ? "NULL " : "(SELECT C_Payment_ID FROM C_Invoice WHERE C_Invoice_ID=" + C_Invoice_ID + ") ")
                                + "WHERE EXISTS (SELECT * FROM C_Invoice i "
                                + "WHERE o.C_Order_ID=i.C_Order_ID AND i.C_Invoice_ID=" + C_Invoice_ID + ")";
                if (DataBase.DB.ExecuteQuery(update, null, Get_TrxName()) > 0)
                {
                    log.Fine("C_Payment_ID=" + C_Payment_ID
                             + (reverse ? " UnLinked from" : " Linked to")
                             + " order of C_Invoice_ID=" + C_Invoice_ID);
                }
            }

            //	Cash - Invoice
            if (C_CashLine_ID != 0 && invoice != null)
            {
                //	Link to Invoice
                if (reverse)
                {
                    invoice.SetC_CashLine_ID(0);
                    log.Fine("C_CashLine_ID=" + C_CashLine_ID
                             + " Unlinked from C_Invoice_ID=" + C_Invoice_ID);
                    // Set isallocated false on cashline while allocation gets deallocated assigned by Mukesh sir on 27/12/2017
                    MCashLine cashline = new MCashLine(GetCtx(), GetC_CashLine_ID(), Get_TrxName());
                    cashline.SetIsAllocated(false);
                    cashline.Save();
                }
                else
                {
                    invoice.SetC_CashLine_ID(C_CashLine_ID);
                    log.Fine("C_CashLine_ID=" + C_CashLine_ID
                             + " Linked to C_Invoice_ID=" + C_Invoice_ID);
                }

                //	Link to Order
                String update = "UPDATE C_Order o "
                                + "SET C_CashLine_ID="
                                + (reverse ? "NULL " : "(SELECT C_CashLine_ID FROM C_Invoice WHERE C_Invoice_ID=" + C_Invoice_ID + ") ")
                                + "WHERE EXISTS (SELECT * FROM C_Invoice i "
                                + "WHERE o.C_Order_ID=i.C_Order_ID AND i.C_Invoice_ID=" + C_Invoice_ID + ")";
                if (DataBase.DB.ExecuteQuery(update, null, Get_TrxName()) > 0)
                {
                    log.Fine("C_CashLine_ID=" + C_CashLine_ID
                             + (reverse ? " UnLinked from" : " Linked to")
                             + " order of C_Invoice_ID=" + C_Invoice_ID);
                }
            }

            // Added by Bharat- Update Discrepancy amount on Invoice.

            if (C_Payment_ID == 0 && C_CashLine_ID == 0 && invoice != null)
            {
                if (invoice.Get_ColumnIndex("DiscrepancyAmt") >= 0)
                {
                    decimal desAmt     = invoice.GetDiscrepancyAmt();
                    decimal desAjusted = invoice.GetDiscrepancyAdjusted();
                    decimal allocAmt   = Math.Abs(GetAmount()); //	absolute
                    if (reverse)
                    {
                        if (allocAmt > desAjusted)
                        {
                            desAmt     = Decimal.Add(desAjusted, desAmt);
                            desAjusted = 0;
                        }
                        else
                        {
                            desAmt     = Decimal.Add(desAmt, allocAmt);
                            desAjusted = Decimal.Subtract(desAjusted, allocAmt);
                        }

                        invoice.SetDiscrepancyAmt(desAmt);
                        invoice.SetDiscrepancyAdjusted(desAjusted);
                        if (desAmt > 0)
                        {
                            invoice.SetIsInDispute(true);
                        }
                    }
                    else
                    {
                        if (allocAmt > desAmt)
                        {
                            desAjusted = Decimal.Add(desAjusted, desAmt);
                            desAmt     = 0;
                        }
                        else
                        {
                            desAjusted = Decimal.Add(desAjusted, allocAmt);
                            desAmt     = Decimal.Subtract(desAmt, allocAmt);
                        }
                        invoice.SetDiscrepancyAmt(desAmt);
                        invoice.SetDiscrepancyAdjusted(desAjusted);
                        if (desAmt == 0)
                        {
                            invoice.SetIsInDispute(false);
                        }
                    }
                    if (!invoice.Save())
                    {
                        log.Log(Level.SEVERE, "Invoice not updated - " + invoice);
                    }
                }
            }

            //	Update Balance / Credit used - Counterpart of MInvoice.completeIt
            if (invoice != null)
            {
                if (invoice.TestAllocation() && !invoice.Save())
                {
                    log.Log(Level.SEVERE, "Invoice not updated - " + invoice);
                }
                else if (reverse)
                {
                    // added by Amit
                    // if payment Management module downloaded and Invoice Schedule id available on Allocation then mark ispaid on schedule as false
                    if (Env.IsModuleInstalled("VA009_"))
                    {
                        MAllocationHdr allocHdr = new MAllocationHdr(GetCtx(), GetC_AllocationHdr_ID(), Get_Trx());
                        decimal        payAmt   = 0;
                        MDocType       doctype  = null;
                        MCurrency      currency = new MCurrency(GetCtx(), invoice.GetC_Currency_ID(), null);
                        if (GetC_InvoicePaySchedule_ID() != 0 && !invoice.IsPaid())
                        {
                            invoiceSchedule = new MInvoicePaySchedule(GetCtx(), GetC_InvoicePaySchedule_ID(), Get_TrxName());
                            invoiceSchedule.SetVA009_IsPaid(false);
                            // when we update schedule paid as False, then update payment method and related fields on schedule as on Invoice Header
                            if (reverse)
                            {
                                invoiceSchedule.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                                DataSet dsPaymentMethod = DB.ExecuteDataset(@"SELECT VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod
                                          WHERE IsActive = 'Y' AND  VA009_PaymentMethod_ID = " + invoice.GetVA009_PaymentMethod_ID(), null, Get_Trx());
                                if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0)
                                {
                                    if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])))
                                    {
                                        invoiceSchedule.SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]));
                                    }
                                    if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])))
                                    {
                                        invoiceSchedule.SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]));
                                    }
                                    invoiceSchedule.SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"]));
                                }
                                dsPaymentMethod = null;
                            }
                            if (reverse && payment != null)
                            {
                                #region Handle for Payment & Invoice Allocation
                                doctype = new MDocType(GetCtx(), invoice.GetC_DocType_ID(), null);

                                // convert (payment amount / Amount from View Allocation) to invoice currency amount then subtract Paid invoice amount to calculated amount
                                if (doctype.GetDocBaseType() == "ARC" || doctype.GetDocBaseType() == "APC")
                                {
                                    if (payment.GetC_Invoice_ID() != 0)
                                    {
                                        // when payment created with invoice refernce direct
                                        // convert payment amount in invoice amt with payment date and payment conversion type
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Negate(Decimal.Add(Decimal.Add(payment.GetPayAmt(), payment.GetDiscountAmt()),
                                                                                                              payment.GetWriteOffAmt())), payment.GetC_Currency_ID(), invoice.GetC_Currency_ID(), payment.GetDateAcct(),
                                                                         payment.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    }
                                    else
                                    {
                                        // when payment created with Payment Allocate entry OR
                                        // when we match payment with invoice through Payment Allocation form
                                        // convert payment amount in invoice amt with view allocation date
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Negate(Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()),
                                                                                                              GetWriteOffAmt())), allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(),
                                                                         invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                        if (doctype.GetDocBaseType() == "APC")
                                        {
                                            payAmt = Decimal.Negate(payAmt);
                                        }
                                    }
                                }
                                else
                                {
                                    if (payment.GetC_Invoice_ID() != 0)
                                    {
                                        // when we create payment with invoice reference direct
                                        // convert payment amount in invoice amt with payment date and payment conversion type
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Add(Decimal.Add(payment.GetPayAmt(), payment.GetDiscountAmt()),
                                                                                               payment.GetWriteOffAmt()), payment.GetC_Currency_ID(), invoice.GetC_Currency_ID(), payment.GetDateAcct(),
                                                                         payment.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    }
                                    else
                                    {
                                        // when payment created with Payment Allocate entry Or
                                        // when we match payment with invoice through Payment Allocation form
                                        // convert payment amount in invoice amt with view allocation date
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt()),
                                                                         allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(), invoice.GetC_ConversionType_ID(),
                                                                         GetAD_Client_ID(), GetAD_Org_ID());
                                        if (doctype.GetDocBaseType() == "API")
                                        {
                                            payAmt = Decimal.Negate(payAmt);
                                        }
                                    }
                                }
                                invoiceSchedule.SetVA009_PaidAmntInvce(Decimal.Round(Decimal.Subtract(invoiceSchedule.GetVA009_PaidAmntInvce(), payAmt),
                                                                                     currency.GetStdPrecision()));

                                // during reversal, if Invoice paid amount <> 0 then reduce that amount from next schedule
                                try
                                {
                                    if (invoiceSchedule.GetVA009_PaidAmntInvce() != 0)
                                    {
                                        int no = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE C_InvoicePaySchedule 
                                                                 SET VA009_PaidAmntInvce =   NVL(VA009_PaidAmntInvce , 0) + " + Decimal.Round(invoiceSchedule.GetVA009_PaidAmntInvce(), currency.GetStdPrecision()) +
                                                                                    @" , VA009_PaidAmnt =  NVL(VA009_PaidAmnt , 0) + " + Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(), invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()), currency.GetStdPrecision()) +
                                                                                    @" WHERE C_InvoicePaySchedule_ID = ( SELECT MIN(C_InvoicePaySchedule_ID) FROM C_InvoicePaySchedule WHERE IsActive = 'Y'
                                                                 AND VA009_IsPaid = 'N' AND C_Invoice_ID = " + invoice.GetC_Invoice_ID() +
                                                                                    @" AND C_InvoicePaySchedule_ID <> " + GetC_InvoicePaySchedule_ID() + " ) ", null, Get_Trx()));

                                        // set paid invoice amount = 0, no > 0 bcz this is not last schedule
                                        if (no > 0)
                                        {
                                            invoiceSchedule.SetVA009_PaidAmntInvce(0);
                                        }
                                    }
                                }
                                catch { }

                                // convert invoice paid amount to base currency amount
                                invoiceSchedule.SetVA009_PaidAmnt(Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(),
                                                                                                            invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()),
                                                                                currency.GetStdPrecision()));

                                // set Currency Variance amount as 0, when we reverse paymnet/ cash journalor allocation against this schedule
                                invoiceSchedule.SetVA009_Variance(0);

                                // remove linking of Payment from schedule
                                invoiceSchedule.SetC_Payment_ID(0);

                                #endregion
                            }
                            else if (reverse && C_CashLine_ID > 0)
                            {
                                #region Handle fo Cash Journal & Invoice Allocation

                                doctype  = new MDocType(GetCtx(), invoice.GetC_DocType_ID(), null);
                                cashLine = new MCashLine(GetCtx(), C_CashLine_ID, Get_Trx());

                                // convert cash amount to invoice currency amount with allocation date then subtract Paid invoice amount to calculated amount
                                if (doctype.GetDocBaseType() == "ARC" || doctype.GetDocBaseType() == "API")
                                {
                                    payAmt = Decimal.Negate(Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt()));
                                    payAmt = MConversionRate.Convert(GetCtx(), payAmt, allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(),
                                                                     invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    invoiceSchedule.SetVA009_PaidAmntInvce(Decimal.Round(Decimal.Subtract(invoiceSchedule.GetVA009_PaidAmntInvce(), payAmt),
                                                                                         currency.GetStdPrecision()));
                                }
                                else
                                {
                                    payAmt = Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt());
                                    payAmt = MConversionRate.Convert(GetCtx(), payAmt, allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(),
                                                                     invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    invoiceSchedule.SetVA009_PaidAmntInvce(Decimal.Round(Decimal.Subtract(invoiceSchedule.GetVA009_PaidAmntInvce(), payAmt),
                                                                                         currency.GetStdPrecision()));
                                }

                                // during reversal, if Invoice paid amount <> 0 then reduce that amount from next schedule
                                try
                                {
                                    if (invoiceSchedule.GetVA009_PaidAmntInvce() != 0)
                                    {
                                        int no = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE C_InvoicePaySchedule 
                                                                 SET VA009_PaidAmntInvce =   NVL(VA009_PaidAmntInvce , 0) + " + Decimal.Round(invoiceSchedule.GetVA009_PaidAmntInvce(), currency.GetStdPrecision()) +
                                                                                    @" , VA009_PaidAmnt =  NVL(VA009_PaidAmnt , 0) + " + Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(), invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()), currency.GetStdPrecision()) +
                                                                                    @" WHERE C_InvoicePaySchedule_ID = ( SELECT MIN(C_InvoicePaySchedule_ID) FROM C_InvoicePaySchedule WHERE IsActive = 'Y'
                                                                 AND VA009_IsPaid = 'N' AND C_Invoice_ID = " + invoice.GetC_Invoice_ID() +
                                                                                    @" AND C_InvoicePaySchedule_ID <> " + GetC_InvoicePaySchedule_ID() + " ) ", null, Get_Trx()));

                                        // set paid invoice amount = 0, no > 0 bcz this is not last schedule
                                        if (no > 0)
                                        {
                                            invoiceSchedule.SetVA009_PaidAmntInvce(0);
                                        }
                                    }
                                }
                                catch { }

                                // convert invoice paid amount to base currency amount
                                invoiceSchedule.SetVA009_PaidAmnt(Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(),
                                                                                                            invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()),
                                                                                currency.GetStdPrecision()));

                                // set Currency Variance amount as 0, when we reverse paymnet/ cash journalor allocation against this schedule
                                invoiceSchedule.SetVA009_Variance(0);

                                // remove linking of cash line from schedule
                                invoiceSchedule.SetC_CashLine_ID(0);

                                #endregion
                            }
                            else
                            {
                                invoiceSchedule.SetVA009_PaidAmntInvce(0);
                                invoiceSchedule.SetVA009_PaidAmnt(0);
                                // set Currency Variance amount as 0, when we reverse paymnet/ cash journalor allocation against this schedule
                                invoiceSchedule.SetVA009_Variance(0);
                            }
                            if (!invoiceSchedule.Save(Get_TrxName()))
                            {
                                log.Log(Level.SEVERE, "Invoice Pay Schedule not updated - " + invoice);
                            }
                        }
                    }
                }
            }

            return(GetC_BPartner_ID());
        }
        /// <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);
            //  Message Display Wrong  Done  Vikas and Assigned by Gurinder
            int    count = Util.GetValueOfInt(DB.ExecuteScalar(" SELECT  Count(*)  FROM M_Inout WHERE  ISSOTRX='Y' AND  M_Inout_ID=" + GetRecord_ID()));
            MInOut ship  = null;

            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()))
                {
                    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()))
                {
                    throw new ArgumentException("Material Receipt not completed");
                }
            }
            //***********************END*****************************//
            MInvoice invoice = new MInvoice(ship, null);
            //-------------Column Added by Anuj----------------------
            //int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));
            int _CountVA009 = Env.IsModuleInstalled("VA009_") ? 1 : 0;

            // Code by Mohit Amortization process
            //int _CountVA038 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA038_'  AND IsActive = 'Y'"));
            int _CountVA038 = Env.IsModuleInstalled("VA038_") ? 1 : 0;

            // End Amortization Code

            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()));
                if (_PaymentMethod_ID > 0)
                {
                    invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID);
                }
            }
            //-------------Column Added by Anuj----------------------

            // added by Amit 26-may-2016
            //int _CountVA026 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA026_'  AND IsActive = 'Y'"));
            int _CountVA026 = Env.IsModuleInstalled("VA026_") ? 1 : 0;

            if (_CountVA026 > 0)
            {
                MOrder order = new MOrder(GetCtx(), ship.GetC_Order_ID(), Get_Trx());
                if (order != null && order.GetC_Order_ID() > 0)
                {
                    invoice.SetVA026_LCDetail_ID(order.GetVA026_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
                    if (invoice.GetC_DocTypeTarget_ID() == 0)
                    {
                        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 (ship.GetC_Order_ID() >= 0)
                    {
                        MOrder   order = new MOrder(GetCtx(), ship.GetC_Order_ID(), Get_Trx());
                        MDocType dt    = MDocType.Get(GetCtx(), order.GetC_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);
            }
            if (_InvoiceDocumentNo != null && _InvoiceDocumentNo.Length > 0)
            {
                invoice.SetDocumentNo(_InvoiceDocumentNo);
            }

            // 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());
            }

            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");
                //return GetReterivedError(invoice, "Cannot save Invoice");
            }
            MInOutLine[] shipLines      = ship.GetLines(false);
            DateTime?    AmortStartDate = null;
            DateTime?    AmortEndDate   = null;

            count = 0;
            DataSet ds = 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][0]);
                    decimal qtyInvoiced = Util.GetValueOfDecimal(ds.Tables[0].Rows[0][1]);
                    if (qtyEntered <= 0)
                    {
                        ds.Dispose();
                        log.Info("Invoice Line already exist for Receipt Line ID - " + sLine.GetM_InOutLine_ID());
                        continue;
                    }
                    else
                    {
                        MInvoiceLine line = new MInvoiceLine(invoice);
                        line.SetShipLine(sLine);
                        //line.SetQtyEntered(sLine.GetQtyEntered());
                        //line.SetQtyInvoiced(sLine.GetMovementQty());
                        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());
                                if (Util.GetValueOfInt(pro.Get_Value("VA038_AmortizationTemplate_ID")) > 0)
                                {
                                    line.Set_Value("VA038_AmortizationTemplate_ID", Util.GetValueOfInt(pro.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(pro.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.GetC_Charge_ID() > 0)
                            {
                                MCharge charge = new MCharge(GetCtx(), sLine.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();
                                    }
                                }
                            }
                        }
                        // End Change Amortization process--------------
                        if (!line.Save())
                        {
                            //return GetReterivedError(line, "Cannot save Invoice Line");
                            //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);
                    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());
                            if (Util.GetValueOfInt(pro.Get_Value("VA038_AmortizationTemplate_ID")) > 0)
                            {
                                line.Set_Value("VA038_AmortizationTemplate_ID", Util.GetValueOfInt(pro.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(pro.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.GetC_Charge_ID() > 0)
                        {
                            MCharge charge = new MCharge(GetCtx(), sLine.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();
                                }
                            }
                        }
                    }
                    // End Change Amortization process--------------
                    if (!line.Save())
                    {
                        //return GetReterivedError(line, "Cannot save Invoice Line");
                        //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,       "
                                + "   SUM(OL.QTYENTERED *OL.PRICEENTERED) AS LINEAMT, "
                                + "      SUM(ML.QTYENTERED*OL.PRICEENTERED) AS MRLINEVALUE "
                                + "  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;
                                decimal SumOfvalue = 0;
                                decimal sototval   = 0;

                                string sql = "SELECT SUM(OL.QTYENTERED *OL.PRICEENTERED) AS LINEAMT from C_ORDER CO,C_ORDERLINE OL WHERE CO.C_ORDER_ID=OL.C_ORDER_ID  AND (OL.C_CHARGE_ID IS NULL OR OL.C_CHARGE_ID    = 0) and CO.C_ORDER_ID  =" + ship.GetC_Order_ID();
                                sototval = VAdvantage.Utility.Util.GetValueOfDecimal(DB.ExecuteScalar(sql));



                                if (Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["ORDERQTY"]) == 0)
                                {
                                    SumOfQty = 1;
                                }
                                else
                                {
                                    SumOfQty   = Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["ORDERQTY"]);
                                    SumOfvalue = Util.GetValueOfDecimal(OrderDS.Tables[0].Rows[index]["LINEAMT"]);
                                }
                                //decimal amt = (Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["LINENETAMT"]) / SumOfQty) * Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["MRLINEQTY"]);
                                decimal amt = (Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["LINENETAMT"]) / sototval) * Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["MRLINEVALUE"]);

                                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())
                                {
                                    //return GetReterivedError(line, "Cannot save Invoice Line");
                                    //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();
                return(Msg.GetMsg(GetCtx(), "InvoiceExist"));
            }
        }
Пример #10
0
        }       //	allocateBPartnerAll

        /// <summary>
        ///	Allocate Oldest First using Accounting currency
        /// </summary>
        /// <returns>allocations</returns>
        private int AllocateBPOldestFirst()
        {
            int      _C_Currency_ID = MClient.Get(GetCtx()).GetC_Currency_ID();
            DateTime?_dateAcct      = null;
            //	Payments
            Decimal _totalPayments = Env.ZERO;

            for (int p = 0; p < _payments.Length; p++)
            {
                MPayment _payment = _payments[p];
                if (_payment.IsAllocated())
                {
                    continue;
                }
                if (_payment.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                Decimal _allocatedAmt = Utility.Util.GetValueOfDecimal(_payment.GetAllocatedAmt());
                log.Info(_payment + ", Allocated=" + _allocatedAmt);
                Decimal _availableAmt = Decimal.Add(Decimal.Add(Decimal.Add(_payment.GetPayAmt(),
                                                                            _payment.GetDiscountAmt()),
                                                                _payment.GetWriteOffAmt()),
                                                    _payment.GetOverUnderAmt());
                if (!_payment.IsReceipt())
                {
                    _availableAmt = Decimal.Negate(_availableAmt);
                }
                log.Fine("Available=" + _availableAmt);
                if (_dateAcct == null || _payment.GetDateAcct() > (_dateAcct))
                {
                    _dateAcct = Utility.Util.GetValueOfDateTime(_payment.GetDateAcct());
                }
                _totalPayments = Decimal.Add(_totalPayments, (_availableAmt));
            }
            //	Invoices
            Decimal _totalInvoices = Env.ZERO;

            for (int i = 0; i < _invoices.Length; i++)
            {
                MInvoice _invoice = _invoices[i];
                if (_invoice.IsPaid())
                {
                    continue;
                }
                if (_invoice.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                Decimal _openAmt = Utility.Util.GetValueOfDecimal(_invoice.GetOpenAmt(true, null));
                log.Fine("" + _invoice);
                if (!_invoice.IsSOTrx())
                {
                    _openAmt = Decimal.Negate(_openAmt);
                }
                //	Foreign currency
                log.Fine("Open=" + _openAmt);
                if (_dateAcct == null || _invoice.GetDateAcct() > (_dateAcct))
                {
                    _dateAcct = _invoice.GetDateAcct();
                }
                _totalInvoices = Decimal.Add(_totalInvoices, _openAmt);
            }

            //	must be either AP or AR balance
            if (Env.Signum(_totalInvoices) != Env.Signum(_totalPayments))
            {
                log.Fine("Signum - Invoices=" + Env.Signum(_totalInvoices)
                         + " <> Payments=" + Env.Signum(_totalPayments));
                return(0);
            }

            Decimal _difference = Decimal.Subtract(_totalInvoices, _totalPayments);
            //Decimal _maxAmt = _totalInvoices.abs().min(_totalPayments.abs());
            Decimal _maxAmt = Math.Min(Math.Abs(_totalInvoices), Math.Abs(_totalPayments));

            if (Env.Signum(_totalInvoices) < 0)
            {
                _maxAmt = Decimal.Negate(_maxAmt);
            }
            log.Info("= Invoices=" + _totalInvoices
                     + " - Payments=" + _totalPayments
                     + " = Difference=" + _difference + " - Max=" + _maxAmt);


            //	Allocate Payments up to max
            Decimal _allocatedPayments = Env.ZERO;

            for (int p = 0; p < _payments.Length; p++)
            {
                MPayment _payment = _payments[p];
                if (_payment.IsAllocated())
                {
                    continue;
                }
                if (_payment.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                Decimal _allocatedAmt = Utility.Util.GetValueOfDecimal(_payment.GetAllocatedAmt());
                if (Env.Signum(_allocatedAmt) != 0)
                {
                    continue;
                }
                Decimal _availableAmt = Decimal.Add(Decimal.Add(Decimal.Add(_payment.GetPayAmt(),
                                                                            _payment.GetDiscountAmt()),
                                                                _payment.GetWriteOffAmt()),
                                                    _payment.GetOverUnderAmt());
                if (!_payment.IsReceipt())
                {
                    _availableAmt = Decimal.Negate(_availableAmt);
                }
                _allocatedPayments = Decimal.Add(_allocatedPayments, _availableAmt);
                if ((Env.Signum(_totalInvoices) > 0 && _allocatedPayments.CompareTo(_maxAmt) > 0) ||
                    (Env.Signum(_totalInvoices) < 0 && _allocatedPayments.CompareTo(_maxAmt) < 0))
                {
                    Decimal _diff = Decimal.Subtract(_allocatedPayments, _maxAmt);
                    _availableAmt      = Decimal.Subtract(_availableAmt, _diff);
                    _allocatedPayments = Decimal.Subtract(_allocatedPayments, _diff);
                }
                log.Fine("Payment Allocated=" + _availableAmt);
                if (!CreateAllocation(_C_Currency_ID, "BP Oldest (" + Math.Abs(_difference) + ")",
                                      _dateAcct, _availableAmt, null, null, null,
                                      _payment.GetC_BPartner_ID(), _payment.GetC_Payment_ID(), 0, _payment.GetAD_Org_ID()))
                {
                    throw new Exception("Cannot create Allocation");
                }
                if (_allocatedPayments.CompareTo(_maxAmt) == 0)
                {
                    break;
                }
            }   //	for all payments
            //	Allocated Invoices up to max
            Decimal _allocatedInvoices = Env.ZERO;

            for (int i = 0; i < _invoices.Length; i++)
            {
                MInvoice _invoice = _invoices[i];
                if (_invoice.IsPaid())
                {
                    continue;
                }
                if (_invoice.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                Decimal _openAmt = Utility.Util.GetValueOfDecimal(_invoice.GetOpenAmt(true, null));
                if (!_invoice.IsSOTrx())
                {
                    _openAmt = Decimal.Negate(_openAmt);
                }
                _allocatedInvoices = Decimal.Add(_allocatedInvoices, _openAmt);
                if ((Env.Signum(_totalInvoices) > 0 && _allocatedInvoices.CompareTo(_maxAmt) > 0) ||
                    (Env.Signum(_totalInvoices) < 0 && _allocatedInvoices.CompareTo(_maxAmt) < 0))
                {
                    Decimal _diff = Decimal.Subtract(_allocatedInvoices, _maxAmt);
                    _openAmt           = Decimal.Subtract(_openAmt, _diff);
                    _allocatedInvoices = Decimal.Subtract(_allocatedInvoices, _diff);
                }
                if (Env.Signum(_openAmt) == 0)
                {
                    break;
                }
                log.Fine("Invoice Allocated=" + _openAmt);
                if (!CreateAllocation(_C_Currency_ID, "BP Oldest (" + Math.Abs(_difference) + ")",
                                      _dateAcct, _openAmt, null, null, null,
                                      _invoice.GetC_BPartner_ID(), 0, _invoice.GetC_Invoice_ID(), _invoice.GetAD_Org_ID()))
                {
                    throw new Exception("Cannot create Allocation");
                }
                if (_allocatedInvoices.CompareTo(_maxAmt) == 0)
                {
                    break;
                }
            }   //	for all invoices

            if (_allocatedPayments.CompareTo(_allocatedInvoices) != 0)
            {
                throw new Exception("Allocated Payments=" + _allocatedPayments
                                    + " <> Invoices=" + _allocatedInvoices);
            }
            ProcessAllocation();
            return(1);
        }       //	allocateOldestFirst
Пример #11
0
        }         //	allocateOneToOne

        /// <summary>
        ///     Allocate all Payments/Invoices using Accounting currency
        /// </summary>
        /// <returns>allocations</returns>
        private int AllocateBPartnerAll()
        {
            int      _C_Currency_ID = MClient.Get(GetCtx()).GetC_Currency_ID();
            DateTime?_dateAcct      = null;
            //	Payments
            Decimal _totalPayments = Env.ZERO;

            for (int p = 0; p < _payments.Length; p++)
            {
                MPayment _payment = _payments[p];
                if (_payment.IsAllocated())
                {
                    continue;
                }
                Decimal _allocatedAmt = Utility.Util.GetValueOfDecimal(_payment.GetAllocatedAmt());
                //	log.info("allocateBPartnerAll - " + _payment + ", Allocated=" + _allocatedAmt);
                if (Env.Signum(_allocatedAmt) != 0)
                {
                    continue;
                }
                Decimal _availableAmt = Decimal.Add(Decimal.Add(Decimal.Add(_payment.GetPayAmt(),
                                                                            _payment.GetDiscountAmt()),
                                                                _payment.GetWriteOffAmt()),
                                                    _payment.GetOverUnderAmt());
                if (!_payment.IsReceipt())
                {
                    _availableAmt = Decimal.Negate(_availableAmt);
                }
                //	Foreign currency
                if (_payment.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                //	log.fine("allocateBPartnerAll - Available=" + _availableAmt);
                if (_dateAcct == null || _payment.GetDateAcct() > (_dateAcct))
                {
                    _dateAcct = _payment.GetDateAcct();
                }
                _totalPayments = Decimal.Add(_totalPayments, _availableAmt);
            }
            //	Invoices
            Decimal _totalInvoices = Env.ZERO;

            for (int i = 0; i < _invoices.Length; i++)
            {
                MInvoice _invoice = _invoices[i];
                if (_invoice.IsPaid())
                {
                    continue;
                }
                //	log.info("allocateBPartnerAll - " + _invoice);
                Decimal _openAmt = Utility.Util.GetValueOfDecimal(_invoice.GetOpenAmt(true, null));
                if (!_invoice.IsSOTrx())
                {
                    _openAmt = Decimal.Negate(_openAmt);
                }
                //	Foreign currency
                if (_invoice.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                //	log.fine("allocateBPartnerAll - Open=" + _openAmt);
                if (_dateAcct == null || _invoice.GetDateAcct() > (_dateAcct))
                {
                    _dateAcct = _invoice.GetDateAcct();
                }
                _totalInvoices = Decimal.Add(_totalInvoices, _openAmt);
            }

            Decimal _difference = Decimal.Subtract(_totalInvoices, _totalPayments);

            log.Info("= Invoices=" + _totalInvoices
                     + " - Payments=" + _totalPayments
                     + " = Difference=" + _difference);

            if (Env.Signum(_difference) == 0)
            {
                for (int p = 0; p < _payments.Length; p++)
                {
                    MPayment _payment = _payments[p];
                    if (_payment.IsAllocated())
                    {
                        continue;
                    }
                    Decimal _allocatedAmt = Utility.Util.GetValueOfDecimal(_payment.GetAllocatedAmt());
                    if (Env.Signum(_allocatedAmt) != 0)
                    {
                        continue;
                    }
                    Decimal _availableAmt = Decimal.Add(Decimal.Add(Decimal.Add(_payment.GetPayAmt(),
                                                                                _payment.GetDiscountAmt()),
                                                                    _payment.GetWriteOffAmt()),
                                                        _payment.GetOverUnderAmt());
                    if (!_payment.IsReceipt())
                    {
                        _availableAmt = Decimal.Negate(_availableAmt);
                    }
                    //	Foreign currency
                    if (_payment.GetC_Currency_ID() != _C_Currency_ID)
                    {
                        continue;
                    }
                    if (!CreateAllocation(_C_Currency_ID, "BP All",
                                          _dateAcct, _availableAmt, null, null, null,
                                          _payment.GetC_BPartner_ID(), _payment.GetC_Payment_ID(), 0, _payment.GetAD_Org_ID()))
                    {
                        throw new Exception("Cannot create Allocation");
                    }
                }       //	for all payments
                //
                for (int i = 0; i < _invoices.Length; i++)
                {
                    MInvoice _invoice = _invoices[i];
                    if (_invoice.IsPaid())
                    {
                        continue;
                    }
                    Decimal _openAmt = Utility.Util.GetValueOfDecimal(_invoice.GetOpenAmt(true, null));
                    if (!_invoice.IsSOTrx())
                    {
                        _openAmt = Decimal.Negate(_openAmt);
                    }
                    //	Foreign currency
                    if (_invoice.GetC_Currency_ID() != _C_Currency_ID)
                    {
                        continue;
                    }
                    if (!CreateAllocation(_C_Currency_ID, "BP All",
                                          _dateAcct, _openAmt, null, null, null,
                                          _invoice.GetC_BPartner_ID(), 0, _invoice.GetC_Invoice_ID(), _invoice.GetAD_Org_ID()))
                    {
                        throw new Exception("Cannot create Allocation");
                    }
                }       //	for all invoices
                ProcessAllocation();
                return(1);
            }   //	Difference OK

            return(0);
        }       //	allocateBPartnerAll
Пример #12
0
        }       //	allocateIndividualPayments

        /// <summary>
        ///Allocate Payment:Invoice 1:1
        /// </summary>
        /// <returns>allocations</returns>
        private int AllocateBPOneToOne()
        {
            int _count = 0;

            for (int p = 0; p < _payments.Length; p++)
            {
                MPayment _payment = _payments[p];
                if (_payment.IsAllocated())
                {
                    continue;
                }
                Decimal _allocatedAmt = Utility.Util.GetValueOfDecimal(_payment.GetAllocatedAmt());
                log.Info(_payment + ", Allocated=" + _allocatedAmt);
                if (Env.Signum(_allocatedAmt) != 0)
                {
                    continue;
                }
                Decimal _availableAmt = Decimal.Add(Decimal.Add(Decimal.Add(_payment.GetPayAmt()
                                                                            , _payment.GetDiscountAmt())
                                                                , _payment.GetWriteOffAmt())
                                                    , _payment.GetOverUnderAmt());
                if (!_payment.IsReceipt())
                {
                    _availableAmt = Decimal.Negate(_availableAmt);
                }
                log.Fine("Available=" + _availableAmt);
                for (int i = 0; i < _invoices.Length; i++)
                {
                    MInvoice _invoice = _invoices[i];
                    if (_invoice == null || _invoice.IsPaid())
                    {
                        continue;
                    }
                    if (_payment.GetC_Currency_ID() == _invoice.GetC_Currency_ID())
                    {
                        //	log.fine("allocateBPartnerAll - " + _invoice);
                        Decimal _openAmt = Utility.Util.GetValueOfDecimal(_invoice.GetOpenAmt(true, null));
                        if (!_invoice.IsSOTrx())
                        {
                            _openAmt = Decimal.Negate(_openAmt);
                        }
                        Decimal _difference = Decimal.Subtract(_availableAmt, Math.Abs((_openAmt)));
                        log.Fine(_invoice + ", Open=" + _openAmt + " - Difference=" + _difference);
                        if (Env.Signum(_difference) == 0)
                        {
                            DateTime?_dateAcct = _payment.GetDateAcct();
                            if (_invoice.GetDateAcct() > _dateAcct)
                            {
                                _dateAcct = _invoice.GetDateAcct();
                            }
                            if (!CreateAllocation(_payment.GetC_Currency_ID(), "1:1 (" + _availableAmt + ")",
                                                  _dateAcct, _availableAmt, null, null, null,
                                                  _invoice.GetC_BPartner_ID(), _payment.GetC_Payment_ID(),
                                                  _invoice.GetC_Invoice_ID(), _invoice.GetAD_Org_ID()))
                            {
                                throw new Exception("Cannot create Allocation");
                            }
                            ProcessAllocation();
                            _count++;
                            _invoices[i] = null;                //	remove _invoice
                            _payments[p] = null;
                            _payment     = null;
                            break;
                        }
                    }
                    else        //	Multi-Currency
                    {
                    }
                } //	for all invoices
            }     //	for all payments
            return(_count);
        }         //	allocateOneToOne
        /**
         *  Apply Payment Term without schedule to Invoice
         *	@param invoice invoice
         *	@return false as no payment schedule
         */

        #region Advance Payment by Vivek on 16/06/2016

        private bool ApplyNoSchedule(MInvoice invoice)
        {
            int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));

            if (_CountVA009 > 0)
            {
                DeleteInvoicePaySchedule(invoice.GetC_Invoice_ID(), invoice.Get_TrxName());
                StringBuilder       _sql     = new StringBuilder();
                MInvoicePaySchedule schedule = null;
                MPaymentTerm        payterm  = new MPaymentTerm(GetCtx(), invoice.GetC_PaymentTerm_ID(), invoice.Get_TrxName());

                Decimal remainder    = invoice.GetGrandTotal();
                int     BaseCurrency = 0;

                if (Util.GetValueOfInt(DB.ExecuteScalar("Select Count(*) From C_PaySchedule Where C_PaymentTerm_ID=" + invoice.GetC_PaymentTerm_ID())) > 1)
                {
                    for (int i = 0; i < _schedule.Length; i++)
                    {
                        MPaySchedule _sch = new MPaySchedule(GetCtx(), _schedule[i].GetC_PaySchedule_ID(), Get_TrxName());
                        #region IsAdvance true on Payment Schedule
                        if (_sch.IsVA009_Advance())
                        {
                            #region Copy Order Schedules
                            String  sql = "SELECT * FROM VA009_OrderPaySchedule WHERE C_Order_ID=" + invoice.GetC_Order_ID() + " AND VA009_IsPaid='Y' ORDER BY Created";
                            DataSet _ds = new DataSet();

                            _ds = DB.ExecuteDataset(sql, null);
                            if (_ds.Tables[0].Rows.Count > 0 && _ds.Tables[0].Rows != null)
                            {
                                for (int j = 0; j < _ds.Tables[0].Rows.Count; j++)
                                {
                                    schedule = new MInvoicePaySchedule(GetCtx(), 0, invoice.Get_TrxName());
                                    Boolean _isPaid = false;
                                    if (Util.GetValueOfString(_ds.Tables[0].Rows[j]["VA009_IsPaid"]) == "Y")
                                    {
                                        _isPaid = true;
                                    }
                                    schedule.SetAD_Client_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["AD_Client_ID"]));
                                    schedule.SetAD_Org_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["AD_Org_ID"]));
                                    schedule.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                                    schedule.SetC_DocType_ID(invoice.GetC_DocType_ID());
                                    schedule.SetC_PaymentTerm_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["C_PaymentTerm_ID"]));
                                    schedule.SetVA009_GrandTotal(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA009_GrandTotal"]));
                                    schedule.SetVA009_PaymentMethod_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA009_PaymentMethod_ID"]));
                                    schedule.SetDueDate(invoice.GetDateInvoiced());
                                    schedule.SetDueAmt(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["DueAmt"]));
                                    schedule.SetDiscountDate(Util.GetValueOfDateTime(_ds.Tables[0].Rows[j]["DiscountDate"]));
                                    schedule.SetDiscountAmt(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["DiscountAmt"]));
                                    schedule.SetVA009_IsPaid(_isPaid);
                                    schedule.SetC_Payment_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["C_Payment_ID"]));

                                    schedule.SetDiscountDays2(Util.GetValueOfDateTime(_ds.Tables[0].Rows[j]["DiscountDays2"]));
                                    schedule.SetDiscount2(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["Discount2"]));

                                    schedule.SetVA009_PlannedDueDate(Util.GetValueOfDateTime(_ds.Tables[0].Rows[j]["VA009_PlannedDueDate"]));

                                    schedule.SetVA009_OpenAmnt(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA009_OpenAmnt"]));


                                    schedule.SetC_Currency_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["C_Currency_ID"]));
                                    schedule.SetVA009_BseCurrncy(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA009_bseCurrncy"]));
                                    schedule.SetVA009_OpnAmntInvce(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA009_OpnAmntInvce"]));
                                    schedule.SetC_BPartner_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["C_Bpartner_ID"]));

                                    schedule.SetVA009_FollowupDate(Util.GetValueOfDateTime(_ds.Tables[0].Rows[j]["VA009_FollowUpDate"]));
                                    schedule.SetVA009_PaymentMode(Util.GetValueOfString(_ds.Tables[0].Rows[j]["va009_paymentmode"]));
                                    schedule.SetVA009_PaymentType(Util.GetValueOfString(_ds.Tables[0].Rows[j]["va009_paymenttype"]));
                                    schedule.SetVA009_PaymentTrigger(Util.GetValueOfString(_ds.Tables[0].Rows[j]["va009_paymenttrigger"]));
                                    schedule.SetVA009_ExecutionStatus(Util.GetValueOfString(_ds.Tables[0].Rows[j]["VA009_ExecutionStatus"]));
                                    schedule.SetProcessed(true);
                                    if (!schedule.Save(invoice.Get_TrxName()))
                                    {
                                        return(false);
                                    }
                                }
                            }
                            #endregion
                        }
                        #endregion

                        #region IsAdvance false on Payment Schedule
                        else
                        {
                            schedule = new MInvoicePaySchedule(invoice, _schedule[i]);

                            schedule.SetVA009_ExecutionStatus("A");
                            schedule.SetAD_Client_ID(invoice.GetAD_Client_ID());
                            schedule.SetAD_Org_ID(invoice.GetAD_Org_ID());
                            schedule.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                            schedule.SetC_DocType_ID(invoice.GetC_DocType_ID());

                            MOrder _Order = new MOrder(GetCtx(), invoice.GetC_Order_ID(), Get_TrxName());
                            schedule.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                            schedule.SetC_PaymentTerm_ID(invoice.GetC_PaymentTerm_ID());
                            schedule.SetVA009_GrandTotal(invoice.GetGrandTotal());

                            MPaymentTerm paytrm    = new MPaymentTerm(GetCtx(), invoice.GetC_PaymentTerm_ID(), Get_TrxName());
                            int          _graceDay = paytrm.GetGraceDays();
                            //DateTime? _followUpDay = GetDueDate(invoice);
                            schedule.SetVA009_FollowupDate(schedule.GetDueDate().Value.AddDays(_graceDay));
                            //schedule.SetVA009_PlannedDueDate(GetDueDate(invoice));
                            schedule.SetVA009_PlannedDueDate(schedule.GetDueDate());
                            //schedule.SetDueDate(GetDueDate(invoice));

                            //change by amit 25-11-2015
                            StringBuilder _sqlBsCrrncy = new StringBuilder();
                            _sql.Clear();
                            _sqlBsCrrncy.Append(@"SELECT UNIQUE asch.C_Currency_ID FROM c_acctschema asch INNER JOIN ad_clientinfo ci ON ci.c_acctschema1_id = asch.c_acctschema_id
                                 INNER JOIN ad_client c ON c.ad_client_id = ci.ad_client_id INNER JOIN c_invoice i ON c.ad_client_id    = i.ad_client_id
                                 WHERE i.ad_client_id = " + invoice.GetAD_Client_ID());
                            BaseCurrency = Util.GetValueOfInt(DB.ExecuteScalar(_sqlBsCrrncy.ToString(), null, null));

                            if (BaseCurrency != invoice.GetC_Currency_ID())
                            {
                                _sqlBsCrrncy.Clear();
                                _sqlBsCrrncy.Append(@"SELECT multiplyrate FROM c_conversion_rate WHERE AD_Client_ID = " + invoice.GetAD_Client_ID() + " AND  c_currency_id  = " + invoice.GetC_Currency_ID() +
                                                    " AND c_currency_to_id = " + BaseCurrency + " AND " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                                decimal multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sqlBsCrrncy.ToString(), null, null));
                                if (multiplyRate == 0)
                                {
                                    _sqlBsCrrncy.Clear();
                                    _sqlBsCrrncy.Append(@"SELECT dividerate FROM c_conversion_rate WHERE AD_Client_ID = " + invoice.GetAD_Client_ID() + " AND c_currency_id  = " + BaseCurrency +
                                                        " AND c_currency_to_id = " + invoice.GetC_Currency_ID() + " AND " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                                    multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sqlBsCrrncy.ToString(), null, null));
                                }
                                schedule.SetVA009_OpenAmnt(schedule.GetDueAmt() * multiplyRate);
                            }
                            else
                            {
                                schedule.SetVA009_OpenAmnt(schedule.GetDueAmt());
                            }

                            schedule.SetC_Currency_ID(invoice.GetC_Currency_ID());
                            schedule.SetVA009_BseCurrncy(BaseCurrency);
                            schedule.SetVA009_OpnAmntInvce(schedule.GetDueAmt());
                            schedule.SetC_BPartner_ID(invoice.GetC_BPartner_ID());
                            //end

                            string  _sqlPaymentMthd = "Select va009_paymentmode, va009_paymenttype, va009_paymenttrigger  From va009_paymentmethod where va009_paymentmethod_ID=" + invoice.GetVA009_PaymentMethod_ID() + "   AND IsActive = 'Y' AND AD_Client_ID = " + invoice.GetAD_Client_ID();
                            DataSet dsPayMthd       = new DataSet();
                            dsPayMthd = DB.ExecuteDataset(_sqlPaymentMthd);
                            if (dsPayMthd.Tables != null && dsPayMthd.Tables.Count > 0 && dsPayMthd.Tables[0].Rows.Count > 0)
                            {
                                for (int j = 0; j < dsPayMthd.Tables[0].Rows.Count; j++)
                                {
                                    schedule.SetVA009_PaymentMode(Util.GetValueOfString(dsPayMthd.Tables[0].Rows[j]["va009_paymentmode"]));
                                    schedule.SetVA009_PaymentType(Util.GetValueOfString(dsPayMthd.Tables[0].Rows[j]["va009_paymenttype"]));
                                    schedule.SetVA009_PaymentTrigger(Util.GetValueOfString(dsPayMthd.Tables[0].Rows[j]["va009_paymenttrigger"]));
                                    schedule.SetVA009_ExecutionStatus("A");
                                }
                            }
                            schedule.SetProcessed(true);
                            if (!schedule.Save(invoice.Get_TrxName()))
                            {
                                return(false);
                            }
                        }
                    }
                    #endregion

                    if (invoice.GetC_PaymentTerm_ID() != GetC_PaymentTerm_ID())
                    {
                        invoice.SetC_PaymentTerm_ID(GetC_PaymentTerm_ID());
                    }
                    return(invoice.ValidatePaySchedule());
                }
                else if (Util.GetValueOfInt(DB.ExecuteScalar("Select Count(*) From C_PaySchedule Where C_PaymentTerm_ID=" + invoice.GetC_PaymentTerm_ID())) <= 1)
                {
                    schedule = new MInvoicePaySchedule(GetCtx(), 0, Get_TrxName());

                    schedule.SetAD_Client_ID(invoice.GetAD_Client_ID());
                    schedule.SetAD_Org_ID(invoice.GetAD_Org_ID());
                    schedule.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                    schedule.SetC_DocType_ID(invoice.GetC_DocType_ID());
                    schedule.SetC_PaymentTerm_ID(invoice.GetC_PaymentTerm_ID());
                    schedule.SetVA009_GrandTotal(invoice.GetGrandTotal());
                    schedule.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                    schedule.SetDueDate(GetDueDate(invoice));
                    schedule.SetDueAmt(invoice.GetGrandTotal());
                    schedule.SetDiscountDate(invoice.GetDateInvoiced().Value.AddDays(Util.GetValueOfInt(payterm.GetDiscountDays())));
                    schedule.SetDiscountAmt((Util.GetValueOfDecimal((invoice.GetGrandTotal() * payterm.GetDiscount()) / 100)));

                    schedule.SetDiscountDays2(invoice.GetDateInvoiced().Value.AddDays(Util.GetValueOfInt(payterm.GetDiscountDays2())));
                    schedule.SetDiscount2((Util.GetValueOfDecimal((invoice.GetGrandTotal() * payterm.GetDiscount2()) / 100)));

                    schedule.SetVA009_PlannedDueDate(GetDueDate(invoice));

                    _sql.Clear();
                    _sql.Append(@"SELECT UNIQUE asch.C_Currency_ID FROM c_acctschema asch INNER JOIN ad_clientinfo ci ON ci.c_acctschema1_id = asch.c_acctschema_id
                                 INNER JOIN ad_client c ON c.ad_client_id = ci.ad_client_id INNER JOIN c_invoice i ON c.ad_client_id    = i.ad_client_id
                                 WHERE i.ad_client_id = " + invoice.GetAD_Client_ID());
                    BaseCurrency = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString(), null, null));

                    if (BaseCurrency != invoice.GetC_Currency_ID())
                    {
                        // change by amit
                        _sql.Clear();
                        _sql.Append(@"SELECT multiplyrate FROM c_conversion_rate WHERE AD_Client_ID = " + GetCtx().GetAD_Client_ID() + " AND c_currency_id  = " + invoice.GetC_Currency_ID() +
                                    " AND c_currency_to_id = " + BaseCurrency + " AND  " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                        decimal multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                        if (multiplyRate == 0)
                        {
                            _sql.Clear();
                            _sql.Append(@"SELECT dividerate FROM c_conversion_rate WHERE AD_Client_ID = " + GetCtx().GetAD_Client_ID() + " AND c_currency_id  = " + BaseCurrency +
                                        " AND c_currency_to_id = " + invoice.GetC_Currency_ID() + " AND  " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                            multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                        }
                        schedule.SetVA009_OpenAmnt(invoice.GetGrandTotal() * multiplyRate);
                    }
                    else
                    {
                        schedule.SetVA009_OpenAmnt(invoice.GetGrandTotal());
                    }

                    schedule.SetC_Currency_ID(invoice.GetC_Currency_ID());
                    schedule.SetVA009_BseCurrncy(BaseCurrency);
                    schedule.SetVA009_OpnAmntInvce(invoice.GetGrandTotal());
                    schedule.SetC_BPartner_ID(invoice.GetC_BPartner_ID());

                    MOrder _Order = new MOrder(GetCtx(), invoice.GetC_Order_ID(), Get_TrxName());
                    //schedule.SetVA009_PaymentMethod_ID(_Order.GetVA009_PaymentMethod_ID());
                    //schedule.SetC_PaymentTerm_ID(_Order.GetC_PaymentTerm_ID());

                    int      _graceDay    = payterm.GetGraceDays();
                    DateTime?_followUpDay = GetDueDate(invoice);
                    schedule.SetVA009_FollowupDate(_followUpDay.Value.AddDays(_graceDay));
                    _sql.Clear();
                    _sql.Append("Select va009_paymentmode, va009_paymenttype, va009_paymenttrigger  From va009_paymentmethod where va009_paymentmethod_ID=" + invoice.GetVA009_PaymentMethod_ID() + "   AND IsActive = 'Y' AND AD_Client_ID = " + invoice.GetAD_Client_ID());
                    DataSet ds = new DataSet();
                    ds = DB.ExecuteDataset(_sql.ToString());
                    if (ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            schedule.SetVA009_PaymentMode(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymentmode"]));
                            schedule.SetVA009_PaymentType(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymenttype"]));
                            schedule.SetVA009_PaymentTrigger(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymenttrigger"]));
                            schedule.SetVA009_ExecutionStatus("A");
                        }
                    }
                    if (!schedule.Save())
                    {
                        return(false);
                    }
                    if (invoice.GetC_PaymentTerm_ID() != GetC_PaymentTerm_ID())
                    {
                        invoice.SetC_PaymentTerm_ID(GetC_PaymentTerm_ID());
                    }
                    return(invoice.ValidatePaySchedule());
                }
            }
            return(true);
        }