Exemplo n.º 1
0
 /// <summary>
 /// Before Save
 /// </summary>
 /// <param name="newRecord"></param>
 /// <returns></returns>
 protected override bool BeforeSave(bool newRecord)
 {
     //	Set Amt
     if (GetC_Invoice_ID() == 0 && GetC_Payment_ID() == 0 && Util.GetValueOfInt(Get_Value("C_CashLine_ID")) == 0 && Util.GetValueOfInt(Get_Value("GL_JournalLine_ID")) == 0 && (!Env.IsModuleInstalled("VA027_") || (Get_ColumnIndex("VA027_PostDatedCheck_ID") > 0 && Util.GetValueOfInt(Get_Value("VA027_PostDatedCheck_ID")) == 0)))
     {
         SetAmt(Env.ZERO);
         SetOpenAmt(Env.ZERO);
     }
     //	Converted Amt
     if (Env.ZERO.CompareTo(GetOpenAmt()) == 0)
     {
         SetConvertedAmt(Env.ZERO);
     }
     else if (Env.ZERO.CompareTo(GetConvertedAmt()) == 0)
     {
         SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                                 GetC_CurrencyFrom_ID(), GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
     }
     //	Total
     SetTotalAmt(Decimal.Add(Decimal.Add(GetConvertedAmt(), GetFeeAmt()), GetInterestAmt()));
     // Reset Collection Status only if null
     if (GetInvoice() != null && GetInvoice().GetInvoiceCollectionType() == null)
     {
         if (_invoice != null)
         {
             _invoice.SetInvoiceCollectionType(X_C_Invoice.INVOICECOLLECTIONTYPE_Dunning);
             _invoice.Save();
         }
     }
     //
     return(true);
 }
Exemplo n.º 2
0
        /**
         *  After Save
         *	@param newRecord
         *	@param success
         *	@return success
         */
        protected override bool AfterSave(bool newRecord, bool success)
        {
            if (!success)
            {
                return(success);
            }

            if (!UpdateCbAndLine())
            {
                return(false);
            }

            if (GetVSS_PAYMENTTYPE() == X_C_CashLine.VSS_PAYMENTTYPE_Payment && GetC_BPartner_ID() > 0)
            {
                MCash   csh = new MCash(GetCtx(), GetC_Cash_ID(), Get_TrxName());
                Decimal amt = MConversionRate.ConvertBase(GetCtx(), GetAmount(),        //	CM adjusted
                                                          GetC_Currency_ID(), csh.GetDateAcct(), 0, GetAD_Client_ID(), GetAD_Org_ID());

                MBPartner bp     = new MBPartner(GetCtx(), GetC_BPartner_ID(), Get_Trx());
                string    retMsg = "";
                bool      crdAll = bp.IsCreditAllowed(GetC_BPartner_Location_ID(), Decimal.Subtract(0, amt), out retMsg);
                if (!crdAll)
                {
                    log.SaveWarning("Warning", retMsg);
                }
                else if (bp.IsCreditWatch(GetC_BPartner_Location_ID()))
                {
                    log.SaveWarning("Warning", Msg.GetMsg(GetCtx(), "VIS_BPCreditWatch"));
                }
            }

            return(true);
        }
Exemplo n.º 3
0
 protected override bool AfterSave(bool newRecord, bool success)
 {
     //by Amit - 6-5-2016
     if (newRecord)
     {
         string sql = @"SELECT COUNT(*) FROM C_Conversion_Rate WHERE ISActive = 'Y' AND c_currency_id = " + GetC_Currency_To_ID() +
                      " AND C_Currency_To_ID = " + GetC_Currency_ID() + " AND c_conversiontype_id = " + GetC_ConversionType_ID() +
                      " AND ( ValidFrom BETWEEN " + GlobalVariable.TO_DATE(GetValidFrom(), true) + " AND " + GlobalVariable.TO_DATE(GetValidTo(), true) +
                      " OR ValidTo BETWEEN " + GlobalVariable.TO_DATE(GetValidFrom(), true) + " AND " + GlobalVariable.TO_DATE(GetValidTo(), true) + " ) " +
                      " AND AD_Client_ID = " + GetAD_Client_ID();
         if (Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx())) <= 0)
         {
             MConversionRate conRate = new MConversionRate(GetCtx(), 0, null);
             conRate.SetAD_Client_ID(GetAD_Client_ID());
             conRate.UpdateFromServer = false;
             conRate.SetAD_Org_ID(GetAD_Org_ID());
             conRate.SetC_Currency_ID(GetC_Currency_To_ID());
             conRate.SetC_Currency_To_ID(GetC_Currency_ID());
             conRate.SetC_ConversionType_ID(GetC_ConversionType_ID());
             conRate.SetDivideRate(GetMultiplyRate());
             conRate.SetMultiplyRate(GetDivideRate());
             conRate.SetValidFrom(GetValidFrom());
             conRate.SetValidTo(GetValidTo());
             if (!conRate.Save(Get_Trx()))
             {
                 ValueNamePair pp = VLogger.RetrieveError();
                 log.Info("Conversion Rate not saved : " + pp.GetValue() + " AND " + pp.GetName());
             }
         }
     }
     //end
     return(true);
 }
        }       //	setC_Currency_ID

        /// <summary>
        /// set rate
        /// </summary>
        /// <param name="windowNo"></param>
        private void SetRate(int windowNo)
        {
            //  Source info
            int?C_Currency_ID       = GetC_Currency_ID();
            int?C_ConversionType_ID = GetC_ConversionType_ID();

            if (C_Currency_ID == 0 || C_ConversionType_ID == 0)
            {
                return;
            }
            DateTime?DateAcct = GetDateAcct();

            if (DateAcct == null)
            {
                DateAcct = DateTime.Now;// new Timestamp(System.currentTimeMillis());
            }
            //
            int?        C_AcctSchema_ID = GetCtx().GetContextAsInt(windowNo, "C_AcctSchema_ID");
            MAcctSchema ass             = MAcctSchema.Get(GetCtx(), C_AcctSchema_ID.Value);
            int?        AD_Client_ID    = GetAD_Client_ID();
            int?        AD_Org_ID       = GetAD_Org_ID();

            Decimal?CurrencyRate = (Decimal?)MConversionRate.GetRate(C_Currency_ID.Value, ass.GetC_Currency_ID(),
                                                                     DateAcct, C_ConversionType_ID.Value, AD_Client_ID.Value, AD_Org_ID.Value);

            log.Fine("rate = " + CurrencyRate);
            if (CurrencyRate == null)
            {
                CurrencyRate = Env.ZERO;
            }
            SetCurrencyRate(CurrencyRate);
            SetAmt(windowNo);
        }       //	setRate
Exemplo n.º 5
0
 /// <summary>
 /// Before Save
 /// </summary>
 /// <param name="newRecord"></param>
 /// <returns></returns>
 protected override bool BeforeSave(bool newRecord)
 {
     //	Set Amt
     if (GetC_Invoice_ID() == 0 && GetC_Payment_ID() == 0)
     {
         SetAmt(Env.ZERO);
         SetOpenAmt(Env.ZERO);
     }
     //	Converted Amt
     if (Env.ZERO.CompareTo(GetOpenAmt()) == 0)
     {
         SetConvertedAmt(Env.ZERO);
     }
     else if (Env.ZERO.CompareTo(GetConvertedAmt()) == 0)
     {
         SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                                 GetC_CurrencyFrom_ID(), GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
     }
     //	Total
     SetTotalAmt(Decimal.Add(Decimal.Add(GetConvertedAmt(), GetFeeAmt()), GetInterestAmt()));
     // Reset Collection Status only if null
     if (GetInvoice() != null && GetInvoice().GetInvoiceCollectionType() == null)
     {
         if (_invoice != null)
         {
             _invoice.SetInvoiceCollectionType(X_C_Invoice.INVOICECOLLECTIONTYPE_Dunning);
             _invoice.Save();
         }
     }
     //
     return(true);
 }
Exemplo n.º 6
0
        /// <summary>
        /// Get PO Price from PriceList - and convert it to AcctSchema Currency
        /// </summary>
        /// <param name="as1">accounting schema</param>
        /// <param name="onlyPOPriceList">use only PO price list</param>
        /// <returns>po price</returns>
        private Decimal?GetPriceList(MAcctSchema as1, bool onlyPOPriceList)
        {
            StringBuilder sql = new StringBuilder(
                "SELECT pl.C_Currency_ID, pp.PriceList, pp.PriceStd, pp.PriceLimit "
                + "FROM M_PriceList pl, M_PriceList_Version plv, M_ProductPrice pp "
                + "WHERE pl.M_PriceList_ID = plv.M_PriceList_ID"
                + " AND plv.M_PriceList_Version_ID = pp.M_PriceList_Version_ID"
                + " AND pp.M_Product_ID=" + _M_Product_ID);

            if (onlyPOPriceList)
            {
                sql.Append(" AND pl.IsSOPriceList='N'");
            }
            sql.Append(" ORDER BY pl.IsSOPriceList ASC, plv.ValidFrom DESC");
            int         C_Currency_ID = 0;
            Decimal?    PriceList     = null;
            Decimal?    PriceStd      = null;
            Decimal?    PriceLimit    = null;
            IDataReader idr           = null;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql.ToString(), null, null);
                if (idr.Read())
                {
                    C_Currency_ID = Utility.Util.GetValueOfInt(idr[0]);     //.getInt(1);
                    PriceList     = Utility.Util.GetValueOfDecimal(idr[1]); //.getBigDecimal(2);
                    PriceStd      = Utility.Util.GetValueOfDecimal(idr[2]); //.getBigDecimal(3);
                    PriceLimit    = Utility.Util.GetValueOfDecimal(idr[3]); //.getBigDecimal(4);
                }
                idr.Close();
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql.ToString(), e);
            }
            //  nothing found
            if (C_Currency_ID == 0)
            {
                return(null);
            }

            Decimal?price = PriceLimit;   //  best bet

            if (price == null || price.Equals(Env.ZERO))
            {
                price = PriceStd;
            }
            if (price == null || price.Equals(Env.ZERO))
            {
                price = PriceList;
            }
            //  Convert
            if (price != null && !price.Equals(Env.ZERO))
            {
                price = MConversionRate.Convert(as1.GetCtx(), Utility.Util.GetValueOfDecimal(price), C_Currency_ID, as1.GetC_Currency_ID(),
                                                as1.GetAD_Client_ID(), 0);
            }
            return(price);
        }
        }       //	setC_Currency_ID

        /// <summary>
        ///	Set Rate
        /// </summary>
        private void SetRate()
        {
            //  Source info
            int C_Currency_ID       = GetC_Currency_ID();
            int C_ConversionType_ID = GetC_ConversionType_ID();

            if (C_Currency_ID == 0 || C_ConversionType_ID == 0)
            {
                return;
            }
            DateTime?DateAcct = GetDateAcct();

            if (DateAcct == null)
            {
                DateAcct = DateTime.Now;// new Timestamp(System.currentTimeMillis());
            }
            //
            int         C_AcctSchema_ID = GetC_AcctSchema_ID();
            MAcctSchema a            = MAcctSchema.Get(GetCtx(), C_AcctSchema_ID);
            int         AD_Client_ID = GetAD_Client_ID();
            int         AD_Org_ID    = GetAD_Org_ID();

            Decimal?CurrencyRate = (Decimal?)MConversionRate.GetRate(C_Currency_ID, a.GetC_Currency_ID(),
                                                                     DateAcct, C_ConversionType_ID, AD_Client_ID, AD_Org_ID);

            log.Fine("rate = " + CurrencyRate);
            //if (CurrencyRate.Value == null)
            //{
            //    CurrencyRate = Env.ZERO;
            //}
            SetCurrencyRate(CurrencyRate.Value);
        }       //	setRate
Exemplo n.º 8
0
        /// <summary>
        /// Set Statement Line
        /// </summary>
        /// <param name="payment">Payment</param>
        /// <returns>Message</returns>
        public string SetPayments(MPayment payment)
        {
            SetC_Payment_ID(payment.GetC_Payment_ID());
            //SetC_Currency_ID(payment.GetC_Currency_ID());
            Decimal amt = payment.GetPayAmt(true);

            //Currency Conversion to BankStatementLine Currency
            if (GetC_Currency_ID() != payment.GetC_Currency_ID())
            {
                int conversionType = Get_ColumnIndex("C_ConversionType_ID") > 0 ? Get_ValueAsInt("C_ConversionType_ID") : payment.GetC_ConversionType_ID();
                amt = MConversionRate.Convert(GetCtx(), amt, payment.GetC_Currency_ID(), GetC_Currency_ID(), GetValutaDate(), conversionType, GetAD_Client_ID(), GetAD_Org_ID());
            }
            if (amt != 0)
            {
                SetTrxAmt(amt);
                if (GetStmtAmt() == 0)
                {
                    SetStmtAmt(amt);
                }
                else // Incase of Uncociled StatementLine have existing Amount
                {
                    decimal _diffAmt = GetStmtAmt() - GetTrxAmt();
                    SetChargeAmt(_diffAmt - GetInterestAmt());
                }
                SetDescription(payment.GetDescription());
            }
            else
            {
                return(Msg.GetMsg(GetCtx(), "NoCurrencyConversion"));
            }
            //Set VA012_VoucherType
            if (Env.IsModuleInstalled("VA012_"))
            {
                bool _IsPaymentAllocate = false;
                int  _InvCount;
                //When Payment have Multiple InvoicePaySchedules
                if (payment.Get_ColumnIndex("IsPaymentAllocate") > 0)
                {
                    _IsPaymentAllocate = Util.GetValueOfBool(payment.Get_Value("IsPaymentAllocate"));
                }
                if (_IsPaymentAllocate)
                {
                    _InvCount = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(C_PaymentAllocate_ID) FROM C_PaymentAllocate WHERE IsActive='Y' AND C_Payment_ID=" + payment.GetC_Payment_ID(), null, null));
                }
                else
                {
                    _InvCount = payment.GetC_Invoice_ID();
                }
                if (_InvCount > 0 || payment.GetC_Order_ID() > 0)
                {
                    SetVA012_VoucherType("M"); // 'M' indicates VA012_VoucherType as Payment
                }
                else if (payment.GetC_Charge_ID() > 0)
                {
                    SetVA012_VoucherType("V"); // 'V' indicates VA012_VoucherType as Voucher
                }
            }
            return("");
        }
Exemplo n.º 9
0
 /// <summary>
 /// Set GLJournalLine
 /// </summary>
 /// <param name="Gl_JournalLine_ID">cash Jurnal Line</param>
 /// <param name="C_Currency_ID">currency</param>
 /// <param name="Amtount">amount</param>
 /// <param name="openAmt">openAmount</param>
 public void SetJournalLine(int Gl_JournalLine_ID, int C_Currency_ID, Decimal Amount, Decimal OpenAmt)
 {
     Set_Value("GL_JournalLine_ID", Gl_JournalLine_ID);
     _C_CurrencyFrom_ID = C_Currency_ID;
     SetAmt(Amount);
     SetOpenAmt(Amount);
     SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                             C_Currency_ID, GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
 }
Exemplo n.º 10
0
 /// <summary>
 /// Set Fee
 /// </summary>
 /// <param name="C_Currency_ID"></param>
 /// <param name="feeAmount"></param>
 public void SetFee(int C_Currency_ID, Decimal feeAmount)
 {
     _C_CurrencyFrom_ID = C_Currency_ID;
     SetAmt(feeAmount);
     SetOpenAmt(feeAmount);
     SetFeeAmt(feeAmount);
     SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                             C_Currency_ID, GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
 }
Exemplo n.º 11
0
        /// <summary>
        /// Set Converted Amt
        /// </summary>
        /// <param name="date">date for conversion</param>
        public void SetConvertedAmt(DateTime?date)
        {
            Decimal amt = MConversionRate.ConvertBase(GetCtx(),
                                                      GetActualAmt(), GetC_Currency_ID(), date, 0, //	type
                                                      GetAD_Client_ID(), GetAD_Org_ID());

            //if (amt != null)
            SetConvertedAmt(amt);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Get PO Cost from Purchase Info - and convert it to AcctSchema Currency
        /// </summary>
        /// <param name="as1">accounting schema</param>
        /// <returns>po cost</returns>
        private Decimal?GetPOCost(MAcctSchema as1)
        {
            String sql = "SELECT C_Currency_ID, PriceList,PricePO,PriceLastPO "
                         + "FROM M_Product_PO WHERE M_Product_ID=" + _M_Product_ID
                         + "ORDER BY IsCurrentVendor DESC";

            int         C_Currency_ID = 0;
            Decimal?    PriceList     = null;
            Decimal?    PricePO       = null;
            Decimal?    PriceLastPO   = null;
            IDataReader idr           = null;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql, null, null);
                if (idr.Read())
                {
                    C_Currency_ID = Utility.Util.GetValueOfInt(idr[0]);     //.getInt(1);
                    PriceList     = Utility.Util.GetValueOfDecimal(idr[1]); //.getBigDecimal(2);
                    PricePO       = Utility.Util.GetValueOfDecimal(idr[2]); //.getBigDecimal(3);
                    PriceLastPO   = Utility.Util.GetValueOfDecimal(idr[3]); //.getBigDecimal(4);
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }
                log.Log(Level.SEVERE, sql, e);
            }
            //  nothing found
            if (C_Currency_ID == 0)
            {
                return(null);
            }

            Decimal?cost = PriceLastPO;   //  best bet

            if (cost == null || cost.Equals(Env.ZERO))
            {
                cost = PricePO;
            }
            if (cost == null || cost.Equals(Env.ZERO))
            {
                cost = PriceList;
            }
            //  Convert - standard precision!! - should be costing precision
            if (cost != null && !cost.Equals(Env.ZERO))
            {
                cost = MConversionRate.Convert(as1.GetCtx(), Utility.Util.GetValueOfDecimal(cost), C_Currency_ID, as1.GetC_Currency_ID(), as1.GetAD_Client_ID(), as1.GetAD_Org_ID());
            }
            return(cost);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Set Payment
 /// </summary>
 /// <param name="C_Payment_ID">payment</param>
 /// <param name="C_Currency_ID">currency</param>
 /// <param name="payAmt">amount</param>
 /// <param name="openAmt">open</param>
 public void SetPayment(int C_Payment_ID, int C_Currency_ID,
                        Decimal payAmt, Decimal openAmt)
 {
     SetC_Payment_ID(C_Payment_ID);
     _C_CurrencyFrom_ID = C_Currency_ID;
     SetAmt(payAmt);
     SetOpenAmt(openAmt);
     SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                             C_Currency_ID, GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
 }
Exemplo n.º 14
0
 /// <summary>
 /// Set CashJournalLine
 /// </summary>
 /// <param name="C_CashLine_ID">cash Jurnal Line</param>
 /// <param name="C_Currency_ID">currency</param>
 /// <param name="payAmt">amount</param>
 /// <param name="openAmt">openAmount</param>
 public void SetcashLine(int C_CashLine_ID,
                         Decimal payAmt, Decimal openAmt, int C_Currency_ID)
 {
     Set_Value("C_CashLine_ID", C_CashLine_ID);
     _C_CurrencyFrom_ID = C_Currency_ID;
     SetAmt(payAmt);
     SetOpenAmt(openAmt);
     SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                             C_Currency_ID, GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
 }
Exemplo n.º 15
0
 /// <summary>
 /// set PostDatedCheque
 /// </summary>
 /// <param name="VA027_PostDatedCheck_ID">PostDatedCheque</param>
 /// <param name="C_Currency_ID">Currency</param>
 /// <param name="Amount">Amount</param>
 /// <param name="openAmt">openAmount</param>
 public void SetPostDatedCheque(int VA027_PostDatedCheck_ID, int C_Currency_ID, Decimal Amount)
 {
     Set_Value("VA027_PostDatedCheck_ID", VA027_PostDatedCheck_ID);
     _C_CurrencyFrom_ID = C_Currency_ID;
     SetAmt(Amount);
     //openAmount same as Amount in PDC  whose payment is not generated
     SetOpenAmt(Amount);
     SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                             C_Currency_ID, GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
 }
Exemplo n.º 16
0
 /// <summary>
 /// set payment from dunningRunCreate process
 /// </summary>
 /// <param name="C_Payment_ID">payment</param>
 /// <param name="C_Currency_ID">currency</param>
 /// <param name="payAmt">amount</param>
 /// <param name="openAmt">openamont</param>
 /// <param name="VA027_PostDatedCheck_ID">PostDatedCheque</param>
 public void SetPayment(int C_Payment_ID, int C_Currency_ID,
                        Decimal payAmt, Decimal openAmt, int VA027_PostDatedCheck_ID)
 {
     SetC_Payment_ID(C_Payment_ID);
     _C_CurrencyFrom_ID = C_Currency_ID;
     SetAmt(payAmt);
     SetOpenAmt(openAmt);
     SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                             C_Currency_ID, GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
     if (Env.IsModuleInstalled("VA027_") && VA027_PostDatedCheck_ID > 0)
     {
         Set_Value("VA027_PostDatedCheck_ID", VA027_PostDatedCheck_ID);
     }
 }
Exemplo n.º 17
0
 /// <summary>
 /// Set Invoice
 /// </summary>
 /// <param name="C_Invoice_ID">invoice</param>
 /// <param name="C_Currency_ID">currency</param>
 /// <param name="grandTotal"> total</param>
 /// <param name="open"> open amount</param>
 /// <param name="feeAmount">days due</param>
 /// <param name="daysDue">in dispute</param>
 /// <param name="isInDispute">bp</param>
 /// <param name="timesDunned">number of dunnings</param>
 /// <param name="daysAfterLast">not used</param>
 public void SetInvoice(int C_Invoice_ID, int C_Currency_ID,
                        Decimal grandTotal, Decimal open,
                        Decimal feeAmount,
                        int daysDue, bool isInDispute,
                        int timesDunned, int daysAfterLast)
 {
     SetC_Invoice_ID(C_Invoice_ID);
     _C_CurrencyFrom_ID = C_Currency_ID;
     SetAmt(grandTotal);
     SetOpenAmt(open);
     SetFeeAmt(feeAmount);
     SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                             C_Currency_ID, GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
     SetIsInDispute(isInDispute);
     SetDaysDue(daysDue);
     SetTimesDunned(timesDunned);
 }
        }       //	afterSave

        /// <summary>
        /// This function is used to set Values on Recognition Plan
        /// </summary>
        /// <param name="invoiceLine">invoice line object </param>
        /// <param name="invoice">invoice object</param>
        /// <param name="C_RevenueRecognition_ID">Recognition ID</param>
        /// <param name="ToCurrency">Currency</param>
        public void SetRecognitionPlan(MInvoiceLine invoiceLine, MInvoice invoice, int C_RevenueRecognition_ID, int ToCurrency)
        {
            SetAD_Client_ID(invoice.GetAD_Client_ID());
            SetAD_Org_ID(invoice.GetAD_Org_ID());
            SetC_Currency_ID(ToCurrency);
            SetC_InvoiceLine_ID(invoiceLine.GetC_InvoiceLine_ID());
            SetC_RevenueRecognition_ID(C_RevenueRecognition_ID);
            // when tax include into price list, then reduce tax from Line Net Amount
            bool    isTaxIncide = (new MPriceList(invoice.GetCtx(), invoice.GetM_PriceList_ID(), invoice.Get_Trx())).IsTaxIncluded();
            Decimal Amount      = invoiceLine.GetLineNetAmt() - (isTaxIncide ? (invoiceLine.GetTaxAmt() + invoiceLine.GetSurchargeAmt()) : 0);

            if (invoice.GetC_Currency_ID() != ToCurrency)
            {
                Amount = MConversionRate.Convert(GetCtx(), Amount, invoice.GetC_Currency_ID(), ToCurrency, invoice.GetDateInvoiced(), invoice.GetC_ConversionType_ID(), invoice.GetAD_Client_ID(), invoice.GetAD_Org_ID());
            }
            SetTotalAmt(Amount);
            SetRecognizedAmt(Env.ZERO);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Set Payment
 /// </summary>
 /// <param name="payment"></param>
 public void SetPayment(MPayment payment)
 {
     _payment = payment;
     if (payment != null)
     {
         _C_CurrencyFrom_ID = payment.GetC_Currency_ID();
         SetAmt(payment.GetPayAmt()); //	need to reverse
         SetOpenAmt(GetAmt());        //	not correct
         SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                                 GetC_CurrencyFrom_ID(), GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
     }
     else
     {
         _C_CurrencyFrom_ID = 0;
         SetAmt(Env.ZERO);
         SetConvertedAmt(Env.ZERO);
     }
 }
Exemplo n.º 20
0
 /// <summary>
 /// Set Invoice
 /// </summary>
 /// <param name="invoice">The invoice to set.</param>
 public void SetInvoice(MInvoice invoice)
 {
     _invoice = invoice;
     if (invoice != null)
     {
         _C_CurrencyFrom_ID = invoice.GetC_Currency_ID();
         SetAmt(invoice.GetGrandTotal());
         SetOpenAmt(GetAmt());   //	not correct
         SetConvertedAmt(MConversionRate.Convert(GetCtx(), GetOpenAmt(),
                                                 GetC_CurrencyFrom_ID(), GetC_CurrencyTo_ID(), GetAD_Client_ID(), GetAD_Org_ID()));
     }
     else
     {
         _C_CurrencyFrom_ID = 0;
         SetAmt(Env.ZERO);
         SetOpenAmt(Env.ZERO);
         SetConvertedAmt(Env.ZERO);
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Calculate/Set Surcharge Tax Amt from Invoice Lines
        /// </summary>
        /// <returns>true if calculated</returns>
        public bool CalculateSurchargeFromLines()
        {
            Decimal taxBaseAmt = Env.ZERO;
            Decimal surTaxAmt  = Env.ZERO;
            //
            MTax surTax        = new MTax(GetCtx(), GetC_Tax_ID(), Get_TrxName());
            bool documentLevel = surTax.IsDocumentLevel();
            //
            String sql = "SELECT il.TaxBaseAmt, COALESCE(il.TaxAmt,0), i.IsSOTrx  , i.C_Currency_ID , i.DateAcct , i.C_ConversionType_ID, tax.SurchargeType "
                         + "FROM C_InvoiceLine il"
                         + " INNER JOIN C_Invoice i ON (il.C_Invoice_ID=i.C_Invoice_ID) "
                         + " INNER JOIN C_Tax tax ON il.C_Tax_ID=tax.C_Tax_ID "
                         + "WHERE il.C_Invoice_ID=" + GetC_Invoice_ID() + " AND tax.Surcharge_Tax_ID=" + GetC_Tax_ID();
            IDataReader idr                 = null;
            int         c_Currency_ID       = 0;
            DateTime?   dateAcct            = null;
            int         c_ConversionType_ID = 0;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName());
                while (idr.Read())
                {
                    //Get References from invoiice header
                    c_Currency_ID       = Utility.Util.GetValueOfInt(idr[3]);
                    dateAcct            = Utility.Util.GetValueOfDateTime(idr[4]);
                    c_ConversionType_ID = Utility.Util.GetValueOfInt(idr[5]);
                    //	BaseAmt
                    Decimal baseAmt = Utility.Util.GetValueOfDecimal(idr[0]);
                    //	TaxAmt
                    Decimal taxAmt        = Utility.Util.GetValueOfDecimal(idr[1]);
                    string  surchargeType = Util.GetValueOfString(idr[6]);

                    // for Surcharge Calculation type - Line Amount + Tax Amount
                    if (surchargeType.Equals(MTax.SURCHARGETYPE_LineAmountPlusTax))
                    {
                        baseAmt    = Decimal.Add(baseAmt, taxAmt);
                        taxBaseAmt = Decimal.Add(taxBaseAmt, baseAmt);
                    }
                    // for Surcharge Calculation type - Line Amount
                    else if (surchargeType.Equals(MTax.SURCHARGETYPE_LineAmount))
                    {
                        taxBaseAmt = Decimal.Add(taxBaseAmt, baseAmt);
                    }
                    // for Surcharge Calculation type - Tax Amount
                    else
                    {
                        baseAmt    = taxAmt;
                        taxBaseAmt = Decimal.Add(taxBaseAmt, baseAmt);
                    }

                    taxAmt = Env.ZERO;

                    bool isSOTrx = "Y".Equals(idr[2].ToString());
                    //
                    if (documentLevel || Env.Signum(baseAmt) == 0)
                    {
                    }
                    else if (Env.Signum(taxAmt) != 0 && !isSOTrx)       //	manually entered
                    {
                        ;
                    }
                    else        // calculate line tax
                    {
                        taxAmt = surTax.CalculateTax(baseAmt, false, GetPrecision());
                    }
                    //
                    surTaxAmt = Decimal.Add(surTaxAmt, taxAmt);
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, "setTaxBaseAmt", e);
                taxBaseAmt = Util.GetValueOfDecimal(null);
            }

            //	Calculate Tax
            if (documentLevel || Env.Signum(surTaxAmt) == 0)
            {
                surTaxAmt = surTax.CalculateTax(taxBaseAmt, false, GetPrecision());
            }
            SetTaxAmt(surTaxAmt);

            // set Tax Amount in base currency
            if (Get_ColumnIndex("TaxBaseCurrencyAmt") >= 0)
            {
                decimal taxAmtBaseCurrency        = GetTaxAmt();
                int     primaryAcctSchemaCurrency = GetCtx().GetContextAsInt("$C_Currency_ID");
                if (c_Currency_ID != primaryAcctSchemaCurrency)
                {
                    taxAmtBaseCurrency = MConversionRate.Convert(GetCtx(), GetTaxAmt(), primaryAcctSchemaCurrency, c_Currency_ID,
                                                                 dateAcct, c_ConversionType_ID, GetAD_Client_ID(), GetAD_Org_ID());
                }
                SetTaxBaseCurrencyAmt(taxAmtBaseCurrency);
            }

            //	Set Base
            SetTaxBaseAmt(taxBaseAmt);
            return(true);
        }
Exemplo n.º 22
0
        /**************************************************************************
         *  Calculate/Set Tax Base Amt from Invoice Lines
         *  @return true if tax calculated
         */
        public bool CalculateTaxFromLines()
        {
            Decimal?taxBaseAmt = Env.ZERO;
            Decimal taxAmt     = Env.ZERO;
            //
            bool documentLevel = GetTax().IsDocumentLevel();
            MTax tax           = GetTax();
            // Calculate Tax on TaxAble Amount
            String sql = "SELECT il.TaxBaseAmt, COALESCE(il.TaxAmt,0), i.IsSOTrx  , i.C_Currency_ID , i.DateAcct , i.C_ConversionType_ID "
                         + "FROM C_InvoiceLine il"
                         + " INNER JOIN C_Invoice i ON (il.C_Invoice_ID=i.C_Invoice_ID) "
                         + "WHERE il.C_Invoice_ID=" + GetC_Invoice_ID() + " AND il.C_Tax_ID=" + GetC_Tax_ID();
            IDataReader idr                 = null;
            int         c_Currency_ID       = 0;
            DateTime?   dateAcct            = null;
            int         c_ConversionType_ID = 0;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName());
                while (idr.Read())
                {
                    //Get References from invoiice header
                    c_Currency_ID       = Utility.Util.GetValueOfInt(idr[3]);
                    dateAcct            = Utility.Util.GetValueOfDateTime(idr[4]);
                    c_ConversionType_ID = Utility.Util.GetValueOfInt(idr[5]);
                    //	BaseAmt
                    Decimal baseAmt = Utility.Util.GetValueOfDecimal(idr[0]);
                    taxBaseAmt = Decimal.Add((Decimal)taxBaseAmt, baseAmt);
                    //	TaxAmt
                    Decimal amt = Utility.Util.GetValueOfDecimal(idr[1]);
                    //if (amt == null)
                    //    amt = Env.ZERO;
                    bool isSOTrx = "Y".Equals(idr[2].ToString());
                    //
                    if (documentLevel || Env.Signum(baseAmt) == 0)
                    {
                        amt = Env.ZERO;
                    }
                    else if (Env.Signum(amt) != 0 && !isSOTrx)  //	manually entered
                    {
                        ;
                    }
                    else        // calculate line tax
                    {
                        amt = tax.CalculateTax(baseAmt, false, GetPrecision());
                    }
                    //
                    taxAmt = Decimal.Add(taxAmt, amt);
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, "setTaxBaseAmt", e);
                log.Log(Level.SEVERE, sql, e);
                taxBaseAmt = null;
            }
            if (taxBaseAmt == null)
            {
                return(false);
            }

            //	Calculate Tax
            if (documentLevel || Env.Signum(taxAmt) == 0)
            {
                taxAmt = tax.CalculateTax((Decimal)taxBaseAmt, false, GetPrecision());
            }
            SetTaxAmt(taxAmt);

            // set Tax Amount in base currency
            if (Get_ColumnIndex("TaxBaseCurrencyAmt") >= 0)
            {
                decimal taxAmtBaseCurrency        = GetTaxAmt();
                int     primaryAcctSchemaCurrency = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT C_Currency_ID FROM C_AcctSchema WHERE C_AcctSchema_ID = 
                                            (SELECT c_acctschema1_id FROM ad_clientinfo WHERE ad_client_id = " + GetAD_Client_ID() + ")", null, Get_Trx()));
                if (c_Currency_ID != primaryAcctSchemaCurrency)
                {
                    taxAmtBaseCurrency = MConversionRate.Convert(GetCtx(), GetTaxAmt(), primaryAcctSchemaCurrency, c_Currency_ID,
                                                                 dateAcct, c_ConversionType_ID, GetAD_Client_ID(), GetAD_Org_ID());
                }
                SetTaxBaseCurrencyAmt(taxAmtBaseCurrency);
            }

            //	Set Base
            //if (IsTaxIncluded())
            //    SetTaxBaseAmt(Decimal.Subtract((Decimal)taxBaseAmt, taxAmt));
            //else
            SetTaxBaseAmt((Decimal)taxBaseAmt);
            return(true);
        }
Exemplo n.º 23
0
        /**
         *	Prepare Document
         *  @return new status (In Progress or Invalid)
         */
        public String PrepareIt()
        {
            log.Info(ToString());
            _processMsg = ModelValidationEngine.Get().FireDocValidate(this, ModalValidatorVariables.DOCTIMING_BEFORE_PREPARE);
            if (_processMsg != null)
            {
                return(DocActionVariables.STATUS_INVALID);
            }

            //	Std Period open?
            if (!MPeriod.IsOpen(GetCtx(), GetDateAcct(), MDocBaseType.DOCBASETYPE_CASHJOURNAL))
            {
                _processMsg = "@PeriodClosed@";
                return(DocActionVariables.STATUS_INVALID);
            }

            // is Non Business Day?
            if (MNonBusinessDay.IsNonBusinessDay(GetCtx(), GetDateAcct()))
            {
                _processMsg = Common.Common.NONBUSINESSDAY;
                return(DocActionVariables.STATUS_INVALID);
            }


            MCashLine[] lines = GetLines(false);
            if (lines.Length == 0)
            {
                _processMsg = "@NoLines@";
                return(DocActionVariables.STATUS_INVALID);
            }
            //	Add up Amounts
            Decimal difference    = Env.ZERO;
            int     C_Currency_ID = GetC_Currency_ID();

            for (int i = 0; i < lines.Length; i++)
            {
                MCashLine line = lines[i];
                if (!line.IsActive())
                {
                    continue;
                }
                if (C_Currency_ID == line.GetC_Currency_ID())
                {
                    difference = Decimal.Add(difference, line.GetAmount());
                }
                else
                {
                    Decimal amt = MConversionRate.Convert(GetCtx(), line.GetAmount(),
                                                          line.GetC_Currency_ID(), C_Currency_ID, GetDateAcct(), 0,
                                                          GetAD_Client_ID(), GetAD_Org_ID());
                    if (amt == null)
                    {
                        _processMsg = "No Conversion Rate found - @C_CashLine_ID@= " + line.GetLine();
                        return(DocActionVariables.STATUS_INVALID);
                    }
                    difference = Decimal.Add(difference, amt);
                }
            }
            SetStatementDifference(difference);
            //	setEndingBalance(getBeginningBalance().add(getStatementDifference()));
            //
            _justPrepared = true;
            if (!DOCACTION_Complete.Equals(GetDocAction()))
            {
                SetDocAction(DOCACTION_Complete);
            }
            return(DocActionVariables.STATUS_INPROGRESS);
        }
Exemplo n.º 24
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());
        }