/// <summary>
        /// Calculate Surcharge Tax
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public Dictionary <String, Object> CalculateSurcharge(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            int      C_Tax_ID;

            Dictionary <String, Object> retval = new Dictionary <String, Object>();

            //Assign parameter value
            C_Tax_ID = Util.GetValueOfInt(paramValue[0]);
            Decimal LineNetAmt    = Util.GetValueOfDecimal(paramValue[1]);
            int     StdPrecision  = Util.GetValueOfInt(paramValue[2]);
            Boolean IsTaxIncluded = true;

            if (paramValue.Length == 4)
            {
                IsTaxIncluded = Util.GetValueOfBool(paramValue[3]);
            }
            //End Assign parameter value
            MTax    tax          = new MTax(ctx, C_Tax_ID, null);
            Decimal surchargeAmt = Env.ZERO;
            Decimal TaxAmt       = Env.ZERO;

            if (tax.Get_ColumnIndex("Surcharge_Tax_ID") > 0 && tax.GetSurcharge_Tax_ID() > 0)
            {
                TaxAmt = tax.CalculateSurcharge(LineNetAmt, IsTaxIncluded, StdPrecision, out surchargeAmt);
            }
            else
            {
                TaxAmt = tax.CalculateTax(LineNetAmt, IsTaxIncluded, StdPrecision);
            }
            retval["TaxAmt"]       = TaxAmt;
            retval["SurchargeAmt"] = surchargeAmt;
            return(retval);
        }
        protected override bool AfterSave(bool newRecord, bool success)
        {
            //if (newRecord || (GetVA027_ChequeAmount() != Util.GetValueOfDecimal(Get_ValueOld("VA027_ChequeAmount"))))
            //{
            //    MVA027PostDatedCheck _PSD = new MVA027PostDatedCheck(GetCtx(), GetVA027_PostDatedCheck_ID(), null);
            //    _PSD.SetVA027_PayAmt(_PSD.GetVA027_PayAmt() + GetVA027_ChequeAmount());
            //    _PSD.Save();
            //}
            int     stdprecision = 0;
            int     C_Tax_ID     = 0;
            Decimal surchargeAmt = Env.ZERO;
            Decimal TaxAmt       = Env.ZERO;
            Decimal PayAmt       = Env.ZERO;

            string sql = "UPDATE VA027_PostDatedCheck i"
                         + " SET VA027_PayAmt="
                         + "(SELECT COALESCE(SUM(VA027_ChequeAmount),0) FROM VA027_ChequeDetails il WHERE i.VA027_PostDatedCheck_ID=il.VA027_PostDatedCheck_ID), "
                         + " VA027_ConvertedAmount = (SELECT COALESCE(SUM(VA027_ChequeAmount),0) FROM VA027_ChequeDetails il WHERE i.VA027_PostDatedCheck_ID=il.VA027_PostDatedCheck_ID) "
                         + "WHERE VA027_PostDatedCheck_ID=" + GetVA027_PostDatedCheck_ID();

            DB.ExecuteQuery(sql, null, Get_TrxName());

            sql = "SELECT StdPrecision, C_Tax_ID, VA027_PayAmt FROM VA027_PostDatedCheck i " +
                  "INNER JOIN C_Currency c ON i.C_Currency_ID = c.C_Currency_ID WHERE VA027_PostDatedCheck_ID =" + GetVA027_PostDatedCheck_ID() +
                  " AND i.C_Charge_ID > 0 AND i.C_Tax_ID > 0";

            DataSet ds = new DataSet();

            ds = DB.ExecuteDataset(sql, null, Get_Trx());
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                stdprecision = Util.GetValueOfInt(ds.Tables[0].Rows[0]["StdPrecision"]);
                C_Tax_ID     = Util.GetValueOfInt(ds.Tables[0].Rows[0]["C_Tax_ID"]);
                PayAmt       = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["VA027_PayAmt"]);

                MTax tax = new MTax(GetCtx(), C_Tax_ID, null);

                if (tax.Get_ColumnIndex("Surcharge_Tax_ID") > 0 && tax.GetSurcharge_Tax_ID() > 0)
                {
                    TaxAmt = tax.CalculateSurcharge(PayAmt, true, stdprecision, out surchargeAmt);
                }
                else
                {
                    TaxAmt = tax.CalculateTax(PayAmt, true, stdprecision);
                }

                sql = "UPDATE VA027_PostDatedCheck SET TaxAmount= " + TaxAmt + " , SurchargeAmt= " + surchargeAmt +
                      " WHERE VA027_PostDatedCheck_ID = " + GetVA027_PostDatedCheck_ID();

                DB.ExecuteQuery(sql, null, Get_TrxName());
            }
            return(true);
        }
        /// <summary>
        /// Calculate Tax
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public Decimal?CalculateTax(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            int      C_Tax_ID;
            //ecimal Qty;
            //bool isSOTrx;
            List <Decimal?> retval = new List <Decimal?>();

            //Assign parameter value
            C_Tax_ID = Util.GetValueOfInt(paramValue[0].ToString());
            Decimal LineNetAmt    = Util.GetValueOfDecimal(paramValue[1].ToString());
            Boolean IsTaxIncluded = Convert.ToBoolean(paramValue[2]);
            int     StdPrecision  = Util.GetValueOfInt(paramValue[3].ToString());
            //End Assign parameter value
            MTax    tax    = new MTax(ctx, C_Tax_ID, null);
            Decimal?TaxAmt = tax.CalculateTax(LineNetAmt, IsTaxIncluded, StdPrecision);

            return(TaxAmt);
        }
Пример #4
0
        /// <summary>
        /// Load Invoice Line
        /// </summary>
        /// <param name="invoice">invoice</param>
        /// <returns>DocLine Array</returns>
        private DocLine[] LoadLines(MInvoice invoice)
        {
            List <DocLine> list = new List <DocLine>();

            //
            MInvoiceLine[] lines = invoice.GetLines(false);
            for (int i = 0; i < lines.Length; i++)
            {
                MInvoiceLine line = lines[i];
                if (line.IsDescription())
                {
                    continue;
                }
                DocLine docLine = new DocLine(line, this);
                //	Qty
                Decimal Qty = line.GetQtyInvoiced();
                bool    cm  = GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_ARCREDITMEMO) ||
                              GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_APCREDITMEMO);
                docLine.SetQty(cm ? Decimal.Negate(Qty) : Qty, invoice.IsSOTrx());
                //
                Decimal LineNetAmt = line.GetLineNetAmt();
                Decimal PriceList  = line.GetPriceList();
                int     C_Tax_ID   = docLine.GetC_Tax_ID();
                //	Correct included Tax
                if (IsTaxIncluded() && C_Tax_ID != 0)
                {
                    MTax tax = MTax.Get(GetCtx(), C_Tax_ID);
                    if (!tax.IsZeroTax())
                    {
                        Decimal LineNetAmtTax = tax.CalculateTax(LineNetAmt, true, GetStdPercision());
                        log.Fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax);
                        LineNetAmt = Decimal.Subtract(LineNetAmt, LineNetAmtTax);
                        for (int t = 0; t < _taxes.Length; t++)
                        {
                            if (_taxes[t].GetC_Tax_ID() == C_Tax_ID)
                            {
                                _taxes[t].AddIncludedTax(LineNetAmtTax);
                                break;
                            }
                        }
                        Decimal PriceListTax = tax.CalculateTax(PriceList, true, GetStdPercision());
                        PriceList = Decimal.Subtract(PriceList, PriceListTax);
                    }
                }                                              //	correct included Tax

                docLine.SetAmount(LineNetAmt, PriceList, Qty); //	qty for discount calc
                if (docLine.IsItem())
                {
                    _allLinesService = false;
                }
                else
                {
                    _allLinesItem = false;
                }
                //
                log.Fine(docLine.ToString());
                list.Add(docLine);
            }

            //	Convert to Array
            DocLine[] dls = new DocLine[list.Count];
            dls = list.ToArray();

            //	Included Tax - make sure that no difference
            if (IsTaxIncluded())
            {
                for (int i = 0; i < _taxes.Length; i++)
                {
                    if (_taxes[i].IsIncludedTaxDifference())
                    {
                        Decimal diff = _taxes[i].GetIncludedTaxDifference();
                        for (int j = 0; j < dls.Length; j++)
                        {
                            if (dls[j].GetC_Tax_ID() == _taxes[i].GetC_Tax_ID())
                            {
                                dls[j].SetLineNetAmtDifference(diff);
                                break;
                            }
                        } //	for all lines
                    }     //	tax difference
                }         //	for all taxes
            }             //	Included Tax difference

            //	Return Array
            return(dls);
        }
Пример #5
0
        protected override String DoIt()
        {
            StringBuilder Sql    = new StringBuilder();
            string        newcon = "";

            String       date      = string.Format("{0:dd/MM/yy}", today);
            int          Record_id = GetRecord_ID();
            X_C_Contract con       = new X_C_Contract(GetCtx(), Record_id, Get_TrxName());

            if (Record_id != 0)
            {
                Sql.Append("SELECT RenewalType FROM C_Contract WHERE C_Contract_ID = " + Record_id + " AND RenewContract = 'N' AND IsActive = 'Y' AND AD_Client_ID = " + GetAD_Client_ID());
                string renewType = Util.GetValueOfString(DB.ExecuteScalar(Sql.ToString(), null, Get_TrxName()));
                if (renewType == "M")
                {
                    Sql.Clear();
                    Sql.Append("SELECT C_Contract_ID FROM C_Contract WHERE C_Contract_ID=" + Record_id + " AND RenewContract = 'N' AND AD_Client_ID = " + GetAD_Client_ID());
                }
                else
                {
                    Sql.Clear();
                    Sql.Append("SELECT C_Contract_ID FROM C_Contract WHERE (EndDate- NVL(CancelBeforeDays,0)) <= SYSDATE AND C_Contract_ID=" + Record_id
                               + " AND RenewContract = 'N' AND AD_Client_ID = " + GetAD_Client_ID());
                }
            }
            else
            {
                Sql.Clear();
                Sql.Append("SELECT C_Contract_ID FROM C_Contract WHERE (EndDate- NVL(CancelBeforeDays,0)) <= SYSDATE AND RenewalType='A' AND RenewContract = 'N' AND AD_Client_ID = " + GetAD_Client_ID());
            }

            IDataReader dr = DB.ExecuteReader(Sql.ToString(), null, Get_TrxName());
            int         count = 0;
            decimal     Listprice = 0, Stdprice = 0, TotalRate = 0;
            int         cycles = 0, duration = 0, frequency = 0, months = 0;
            DateTime?   CDate = null;
            DateTime    OldStart, Start, endDate;

            MPriceList    priceList = null;
            MTax          tax       = null;
            X_C_Contract  contact   = null;
            X_C_Contract  New       = null;
            ValueNamePair pp        = null;

            try
            {
                while (dr.Read())
                {
                    contact = new X_C_Contract(GetCtx(), Util.GetValueOfInt(dr[0]), Get_TrxName());
                    if (contact.GetRenewalType() == "M")
                    {
                        // SI_0772: By Clicking on Renew Contract, System is throwing an error as 'NoContractReNewed'.
                        CDate  = contact.GetCancellationDate();
                        cycles = Util.GetValueOfInt(contact.GetCycles());

                        if (CDate != null)
                        {
                            continue;
                        }

                        New = new X_C_Contract(GetCtx(), 0, Get_TrxName());
                        New.SetRefContract(contact.GetDocumentNo());
                        New.SetC_Order_ID(contact.GetC_Order_ID());
                        New.SetC_OrderLine_ID(contact.GetC_OrderLine_ID());
                        OldStart = (DateTime)(contact.GetStartDate());
                        Start    = (DateTime)(contact.GetEndDate());
                        New.SetStartDate(Start.AddDays(1));
                        New.SetC_BPartner_ID(contact.GetC_BPartner_ID());
                        New.SetBill_Location_ID(contact.GetBill_Location_ID());
                        New.SetBill_User_ID(contact.GetBill_User_ID());
                        New.SetSalesRep_ID(contact.GetSalesRep_ID());
                        New.SetC_ConversionType_ID(contact.GetC_ConversionType_ID());
                        New.SetC_PaymentTerm_ID(contact.GetC_PaymentTerm_ID());

                        frequency = contact.GetC_Frequency_ID();
                        New.SetC_Frequency_ID(frequency);

                        // Get No Of Months from Frequency
                        months   = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NoOfMonths FROM C_Frequency WHERE C_Frequency_ID=" + frequency, null, Get_TrxName()));
                        duration = months * cycles;
                        endDate  = New.GetStartDate().Value.AddMonths(duration);
                        endDate  = endDate.AddDays(-1);
                        New.SetEndDate(endDate);
                        New.SetTotalInvoice(cycles);
                        if (Record_id != 0)
                        {
                            // JID_1124:  System has to pick the Pricelist in Service Contract as defined in Renewal Pricelist. also need to pick Price from Latest Valid From Date Version
                            New.SetM_PriceList_ID(contact.GetRef_PriceList_ID());
                            priceList = new MPriceList(GetCtx(), contact.GetRef_PriceList_ID(), Get_TrxName());
                            Sql.Clear();
                            Sql.Append("SELECT pp.PriceList, pp.PriceStd FROM M_ProductPrice pp INNER JOIN M_PriceList_Version plv ON pp.M_PriceList_Version_ID = plv.M_PriceList_Version_ID"
                                       + " WHERE pp.M_Product_ID=" + contact.GetM_Product_ID() + " AND plv.IsActive='Y' AND plv.M_PriceList_ID=" + contact.GetRef_PriceList_ID()
                                       + " AND plv.VALIDFROM <= SYSDATE ORDER BY plv.VALIDFROM DESC");
                            DataSet ds = DB.ExecuteDataset(Sql.ToString(), null, Get_TrxName());
                            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                            {
                                Listprice = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["PriceList"]);
                                Stdprice  = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["PriceStd"]);
                            }
                            else
                            {
                                dr.Close();
                                Get_TrxName().Rollback();
                                return(Msg.GetMsg(GetCtx(), "ProductNotOnPriceList"));
                            }
                            //int Version = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            //Query = "SELECT PriceList FROM M_ProductPrice WHERE M_PriceList_Version_ID=" + Version + " AND M_Product_ID=" + contact.GetM_Product_ID();
                            //decimal Listprice = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            //Query = "SELECT PriceStd FROM M_ProductPrice WHERE M_PriceList_Version_ID=" + Version + " AND M_Product_ID=" + contact.GetM_Product_ID();
                            //decimal Stdprice = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            //if (Stdprice == 0 && Listprice == 0)
                            //{
                            //    dr.Close();
                            //    return Msg.GetMsg(GetCtx(), "ProductNotINPriceList");
                            //}

                            New.SetPriceEntered(Stdprice);
                            New.SetPriceActual(Stdprice);
                            New.SetPriceList(Listprice);
                        }
                        else
                        {
                            priceList = new MPriceList(GetCtx(), contact.GetM_PriceList_ID(), Get_TrxName());
                            New.SetM_PriceList_ID(contact.GetM_PriceList_ID());
                            New.SetPriceEntered(contact.GetPriceEntered());
                            New.SetPriceActual(contact.GetPriceActual());
                            New.SetPriceList(contact.GetPriceList());
                        }
                        New.SetC_Currency_ID(priceList.GetC_Currency_ID());
                        New.SetC_UOM_ID(contact.GetC_UOM_ID());
                        New.SetM_Product_ID(contact.GetM_Product_ID());
                        New.SetM_AttributeSetInstance_ID(contact.GetM_AttributeSetInstance_ID());
                        New.SetQtyEntered(contact.GetQtyEntered());
                        New.SetC_Tax_ID(contact.GetC_Tax_ID());
                        New.SetC_Campaign_ID(contact.GetC_Campaign_ID());
                        New.SetRef_Contract_ID(contact.GetC_Contract_ID());
                        New.SetC_Project_ID(contact.GetC_Project_ID());
                        New.SetDescription(contact.GetDescription());
                        //New.SetTaxAmt(contact.GetTaxAmt());
                        New.SetCancelBeforeDays(contact.GetCancelBeforeDays());
                        New.SetCycles(contact.GetCycles());
                        New.SetRenewContract("N");
                        New.SetScheduleContract("N");
                        New.SetDocStatus("DR");
                        New.SetRenewalType("M");
                        New.SetLineNetAmt(Decimal.Multiply(New.GetPriceEntered(), New.GetQtyEntered()));

                        //String sqltax = "SELECT Rate FROM C_Tax WHERE C_Tax_ID=" + contact.GetC_Tax_ID();
                        //Decimal? Rate = Util.GetValueOfDecimal(DB.ExecuteScalar(sqltax, null, Get_TrxName()));

                        //Decimal? TotalRate = Util.GetValueOfDecimal((Util.GetValueOfDecimal(New.GetLineNetAmt()) * Util.GetValueOfDecimal(Rate)) / 100);
                        //TotalRate = Decimal.Round(TotalRate.Value, 2);

                        // if Surcharge Tax is selected on Tax, then set value in Surcharge Amount
                        if (New.Get_ColumnIndex("SurchargeAmt") > 0 && tax.GetSurcharge_Tax_ID() > 0)
                        {
                            Decimal surchargeAmt = Env.ZERO;

                            // Calculate Surcharge Amount
                            TotalRate = tax.CalculateSurcharge(New.GetLineNetAmt(), priceList.IsTaxIncluded(), priceList.GetStandardPrecision(), out surchargeAmt);
                            New.SetTaxAmt(TotalRate);
                            New.SetSurchargeAmt(surchargeAmt);
                        }
                        else
                        {
                            // Calculate Tax Amount
                            tax       = MTax.Get(GetCtx(), contact.GetC_Tax_ID());
                            TotalRate = tax.CalculateTax(New.GetLineNetAmt(), priceList.IsTaxIncluded(), priceList.GetPricePrecision());
                            New.SetTaxAmt(TotalRate);
                        }
                        // Calculate Discount %
                        Decimal?dis = Decimal.Multiply(Decimal.Divide(Decimal.Subtract(New.GetPriceList(), New.GetPriceEntered()), New.GetPriceList()), 100);
                        New.SetDiscount(dis);

                        // Set Grand Total Amount
                        if (priceList.IsTaxIncluded())
                        {
                            New.SetGrandTotal(New.GetLineNetAmt());
                        }
                        else
                        {
                            if (New.Get_ColumnIndex("SurchargeAmt") > 0)
                            {
                                New.SetGrandTotal(Decimal.Add(Decimal.Add(New.GetLineNetAmt(), New.GetTaxAmt()), New.GetSurchargeAmt()));
                            }
                            else
                            {
                                New.SetGrandTotal(Decimal.Add(New.GetLineNetAmt(), New.GetTaxAmt()));
                            }
                        }

                        if (contact.GetBillStartDate() != null)
                        {
                            New.SetBillStartDate(contact.GetBillStartDate().Value.AddMonths(contact.GetTotalInvoice()));
                        }
                        else
                        {
                            New.SetBillStartDate(New.GetStartDate());
                        }
                        if (New.Save())
                        {
                            newcon = New.GetDocumentNo();
                            count++;
                            if (Record_id != 0)
                            {
                                contact.SetRef_Contract_ID(New.GetC_Contract_ID());
                                contact.SetRenewContract("Y");
                                if (!contact.Save())
                                {
                                    dr.Close();
                                    Get_TrxName().Rollback();
                                    return(Msg.GetMsg(GetCtx(), "ContractNotRenew"));
                                }
                            }
                        }
                        else
                        {
                            dr.Close();
                            Get_TrxName().Rollback();
                            pp = VLogger.RetrieveError();
                            if (pp != null)
                            {
                                return(!String.IsNullOrEmpty(pp.GetName()) ? pp.GetName() : Msg.GetMsg(GetCtx(), "ContractNotRenew"));
                            }
                            else
                            {
                                return(Msg.GetMsg(GetCtx(), "ContractNotRenew"));
                            }
                        }
                    }
                    else
                    {
                        // SI_0772: By Clicking on Renew Contract, System is throwing an error as 'NoContractReNewed'.
                        CDate  = contact.GetCancellationDate();
                        cycles = contact.GetCycles();
                        if (CDate != null)
                        {
                            continue;
                        }

                        New = new X_C_Contract(GetCtx(), 0, Get_TrxName());
                        New.SetRefContract(contact.GetDocumentNo());
                        New.SetC_Order_ID(contact.GetC_Order_ID());
                        New.SetC_OrderLine_ID(contact.GetC_OrderLine_ID());
                        OldStart = (DateTime)(contact.GetStartDate());
                        Start    = (DateTime)(contact.GetEndDate());
                        New.SetStartDate(Start.AddDays(1));

                        frequency = contact.GetC_Frequency_ID();

                        // Get No Of Months from Frequency
                        months   = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NoOfMonths FROM C_Frequency WHERE C_Frequency_ID=" + frequency, null, Get_TrxName()));
                        duration = months * cycles;

                        endDate = New.GetStartDate().Value.AddMonths(duration);
                        endDate = endDate.AddDays(-1);

                        New.SetEndDate(endDate);
                        New.SetC_BPartner_ID(contact.GetC_BPartner_ID());
                        New.SetBill_Location_ID(contact.GetBill_Location_ID());
                        New.SetBill_User_ID(contact.GetBill_User_ID());
                        New.SetSalesRep_ID(contact.GetSalesRep_ID());
                        New.SetC_ConversionType_ID(contact.GetC_ConversionType_ID());
                        New.SetC_PaymentTerm_ID(contact.GetC_PaymentTerm_ID());
                        New.SetC_Frequency_ID(frequency);

                        // invoice Count Start

                        if (Record_id != 0)
                        {
                            if (contact.GetRef_PriceList_ID() == 0)
                            {
                                dr.Close();
                                Get_TrxName().Rollback();
                                return(Msg.GetMsg(GetCtx(), "FirstSelectPriceList"));
                            }
                            New.SetM_PriceList_ID(contact.GetRef_PriceList_ID());

                            priceList = new MPriceList(GetCtx(), contact.GetRef_PriceList_ID(), Get_TrxName());
                            Sql.Clear();
                            Sql.Append("SELECT pp.PriceList, pp.PriceStd FROM M_ProductPrice pp INNER JOIN M_PriceList_Version plv ON pp.M_PriceList_Version_ID = plv.M_PriceList_Version_ID"
                                       + " WHERE pp.M_Product_ID=" + contact.GetM_Product_ID() + " AND plv.IsActive='Y' AND plv.M_PriceList_ID=" + contact.GetRef_PriceList_ID()
                                       + " AND plv.VALIDFROM <= SYSDATE ORDER BY plv.VALIDFROM DESC");
                            DataSet ds = DB.ExecuteDataset(Sql.ToString(), null, Get_TrxName());
                            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                            {
                                Listprice = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["PriceList"]);
                                Stdprice  = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["PriceStd"]);
                            }
                            else
                            {
                                dr.Close();
                                Get_TrxName().Rollback();
                                return(Msg.GetMsg(GetCtx(), "ProductNotOnPriceList"));
                            }

                            //String Query = "Select M_PriceList_Version_id from M_PriceList_Version where IsActive='Y' and M_PriceList_Id=" + contact.GetRef_PriceList_ID();
                            //int Version = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            //Query = "Select PriceList,PriceStd from M_ProductPrice where M_PriceList_Version_id=" + Version + " and M_Product_ID=" + contact.GetM_Product_ID();
                            //decimal Listprice = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            //Query = "Select PriceList,PriceStd from M_ProductPrice where M_PriceList_Version_id=" + Version + " and M_Product_ID=" + contact.GetM_Product_ID();
                            //decimal Stdprice = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            //if (Stdprice == 0 && Listprice == 0)
                            //{
                            //    return Msg.GetMsg(GetCtx(), "ProductNotINPriceList");
                            //}

                            New.SetPriceEntered(Stdprice);
                            New.SetPriceActual(Stdprice);
                            New.SetPriceList(Listprice);
                        }
                        else
                        {
                            priceList = new MPriceList(GetCtx(), contact.GetM_PriceList_ID(), Get_TrxName());
                            New.SetM_PriceList_ID(contact.GetM_PriceList_ID());
                            New.SetPriceActual(contact.GetPriceActual());
                            New.SetPriceList(contact.GetPriceList());
                            New.SetPriceEntered(contact.GetPriceEntered());
                        }
                        New.SetTotalInvoice(contact.GetCycles());
                        New.SetC_Currency_ID(priceList.GetC_Currency_ID());
                        New.SetC_UOM_ID(contact.GetC_UOM_ID());
                        New.SetM_Product_ID(contact.GetM_Product_ID());
                        New.SetM_AttributeSetInstance_ID(contact.GetM_AttributeSetInstance_ID());
                        New.SetQtyEntered(contact.GetQtyEntered());
                        New.SetC_Tax_ID(contact.GetC_Tax_ID());
                        New.SetC_Campaign_ID(contact.GetC_Campaign_ID());
                        New.SetRef_Contract_ID(contact.GetC_Contract_ID());
                        New.SetC_Project_ID(contact.GetC_Project_ID());
                        New.SetDescription(contact.GetDescription());
                        New.SetCancelBeforeDays(contact.GetCancelBeforeDays());
                        New.SetCycles(contact.GetCycles());
                        New.SetRenewContract("N");
                        New.SetScheduleContract("Y");
                        New.SetRenewalType("A");
                        New.SetDocStatus("DR");
                        New.SetLineNetAmt(Decimal.Multiply(New.GetPriceEntered(), New.GetQtyEntered()));

                        // Calculate Tax Amount
                        tax = MTax.Get(GetCtx(), contact.GetC_Tax_ID());

                        // if Surcharge Tax is selected on Tax, then set value in Surcharge Amount
                        if (New.Get_ColumnIndex("SurchargeAmt") > 0 && tax.GetSurcharge_Tax_ID() > 0)
                        {
                            Decimal surchargeAmt = Env.ZERO;

                            // Calculate Surcharge Amount
                            TotalRate = tax.CalculateSurcharge(New.GetLineNetAmt(), priceList.IsTaxIncluded(), priceList.GetStandardPrecision(), out surchargeAmt);
                            New.SetTaxAmt(TotalRate);
                            New.SetSurchargeAmt(surchargeAmt);
                        }
                        else
                        {
                            TotalRate = tax.CalculateTax(New.GetLineNetAmt(), priceList.IsTaxIncluded(), priceList.GetPricePrecision());
                            New.SetTaxAmt(TotalRate);
                        }
                        // Calculate Discount %
                        Decimal?dis = Decimal.Multiply(Decimal.Divide(Decimal.Subtract(New.GetPriceList(), New.GetPriceEntered()), New.GetPriceList()), 100);
                        New.SetDiscount(dis);

                        // Set Grand Total Amount
                        if (priceList.IsTaxIncluded())
                        {
                            New.SetGrandTotal(New.GetLineNetAmt());
                        }
                        else
                        {
                            if (New.Get_ColumnIndex("SurchargeAmt") > 0)
                            {
                                New.SetGrandTotal(Decimal.Add(Decimal.Add(New.GetLineNetAmt(), New.GetTaxAmt()), New.GetSurchargeAmt()));
                            }
                            else
                            {
                                New.SetGrandTotal(Decimal.Add(New.GetLineNetAmt(), New.GetTaxAmt()));
                            }
                        }

                        if (contact.GetBillStartDate() != null)
                        {
                            New.SetBillStartDate(contact.GetBillStartDate().Value.AddMonths(contact.GetTotalInvoice()));
                        }
                        else
                        {
                            New.SetBillStartDate(New.GetStartDate());
                        }

                        if (New.Save())
                        {
                            newcon = New.GetDocumentNo();
                            count++;
                            contact.SetRef_Contract_ID(New.GetC_Contract_ID());
                            contact.SetRenewContract("Y");
                            if (!contact.Save())
                            {
                                dr.Close();
                                Get_TrxName().Rollback();
                                return(Msg.GetMsg(GetCtx(), "ContractNotRenew"));
                            }
                            if (!EnterSchedules(New.GetC_Contract_ID(), cycles))
                            {
                                dr.Close();
                                Get_TrxName().Rollback();
                                return(Msg.GetMsg(GetCtx(), "ContractNotRenew"));
                            }
                            New.SetProcessed(true);
                            if (!New.Save())
                            {
                                dr.Close();
                                Get_TrxName().Rollback();
                                return(Msg.GetMsg(GetCtx(), "ContractNotRenew"));
                            }
                        }
                        else
                        {
                            dr.Close();
                            Get_TrxName().Rollback();
                            pp = VLogger.RetrieveError();
                            if (pp != null)
                            {
                                return(!String.IsNullOrEmpty(pp.GetName()) ? pp.GetName() : Msg.GetMsg(GetCtx(), "ContractNotRenew"));
                            }
                            else
                            {
                                return(Msg.GetMsg(GetCtx(), "ContractNotRenew"));
                            }
                        }
                    }
                }
                dr.Close();
                if (count != 0 && Record_id != 0)
                {
                    return(Msg.GetMsg(GetCtx(), "ContractReNewed") + ": " + newcon);
                }
                if (count != 0)
                {
                    return(Msg.GetMsg(GetCtx(), "ContractReNewed"));
                }
                return(Msg.GetMsg(GetCtx(), "ContractNotRenew"));
            }
            catch
            {
                if (dr != null)
                {
                    dr.Close();
                    dr = null;
                }
            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                    dr = null;
                }
            }
            return(Msg.GetMsg(GetCtx(), "ContractNotRenew"));
        }
        /// <summary>
        /// update Amount, converted Amount , writeoff and discount amount on Cheque details and postdatedcheck with the sum of
        /// checkallocate and chequedeatils amount respectively
        /// </summary>
        /// <param name="newRecord"></param>
        /// <param name="success"></param>
        /// <returns>true</returns>
        protected override bool AfterSave(bool newRecord, bool success)
        {
            int     stdprecision = 0;
            int     C_Tax_ID     = 0;
            Decimal surchargeAmt = Env.ZERO;
            Decimal TaxAmt       = Env.ZERO;
            Decimal PayAmt       = Env.ZERO;

            string sql = "UPDATE VA027_ChequeDetails i "
                         + "  SET VA027_ChequeAmount ="
                         + "   (SELECT COALESCE(SUM(Amount), 0) FROM VA027_checkallocate il WHERE i.VA027_ChequeDetails_ID = il.VA027_ChequeDetails_ID), VA027_IsCheckAllocated='Y'"
                         + " WHERE VA027_ChequeDetails_ID =" + GetVA027_ChequeDetails_ID() /*+ "And AD_Org_ID=" + GetAD_Org_ID() + "AND AD_Client_ID=" + GetAD_Client_ID()*/;

            int count = Util.GetValueOfInt(DB.ExecuteQuery(sql, null, Get_TrxName()));

            if (count > 0)
            {
                sql = "UPDATE va027_postdatedcheck SET VA027_PayAmt =" +
                      " (SELECT COALESCE(SUM(il.VA027_ChequeAmount),0) FROM va027_postdatedcheck i INNER JOIN VA027_ChequeDetails il" +
                      " ON i.va027_postdatedcheck_ID = il.va027_postdatedcheck_ID WHERE il.va027_postdatedcheck_ID =" +
                      "(SELECT va027_postdatedcheck_ID FROM VA027_ChequeDetails WHERE VA027_ChequeDetails_id = " + GetVA027_ChequeDetails_ID() + ")" +
                      " AND i.AD_Org_ID = " + GetAD_Org_ID() + " AND i.AD_Client_ID = " + GetAD_Client_ID() + ")," +
                      " VA027_ConvertedAmount = (SELECT COALESCE(SUM(il.VA027_ChequeAmount),0) FROM va027_postdatedcheck i INNER JOIN VA027_ChequeDetails il" +
                      " ON i.va027_postdatedcheck_ID = il.va027_postdatedcheck_ID WHERE il.va027_postdatedcheck_ID =" +
                      " (SELECT va027_postdatedcheck_ID FROM VA027_ChequeDetails WHERE VA027_ChequeDetails_id =" + GetVA027_ChequeDetails_ID() + ")" +
                      "  AND i.AD_Org_ID = " + GetAD_Org_ID() + "  AND i.AD_Client_ID = " + GetAD_Client_ID() + ")," +
                      " va027_writeoffAmt =(SELECT COALESCE(SUM(Writeoffamt),0) FROM Va027_checkAllocate i " +
                      "INNER JOIN va027_chequedetails ii ON i.va027_chequedetails_id = ii.va027_chequedetails_id " +
                      "INNER JOIN va027_postdatedCheck iii ON ii.va027_postdatedcheck_ID = iii.va027_postdatedcheck_ID " +
                      " WHERE iii.va027_postdatedcheck_ID = (SELECT va027_postdatedcheck_ID FROM VA027_ChequeDetails WHERE VA027_ChequeDetails_id =" + GetVA027_ChequeDetails_ID() + ")" +
                      " AND i.AD_Org_ID = " + GetAD_Org_ID() + "  AND i.AD_Client_ID = " + GetAD_Client_ID() + ")," +
                      " VA027_discountAmt = (SELECT COALESCE(SUM(discountAmt),0) FROM Va027_checkAllocate i " +
                      " INNER JOIN va027_chequedetails ii ON i.va027_chequedetails_id = ii.va027_chequedetails_id " +
                      " INNER JOIN va027_postdatedCheck iii ON ii.va027_postdatedcheck_ID = iii.va027_postdatedcheck_ID " +
                      " WHERE iii.va027_postdatedcheck_ID = (SELECT va027_postdatedcheck_ID FROM VA027_ChequeDetails WHERE VA027_ChequeDetails_id =" + GetVA027_ChequeDetails_ID() + ")" +
                      " AND i.AD_Org_ID = " + GetAD_Org_ID() + "  AND i.AD_Client_ID = " + GetAD_Client_ID() + ") " +
                      "  WHERE va027_postdatedcheck_ID =" +
                      "  (SELECT va027_postdatedcheck_ID FROM VA027_ChequeDetails WHERE VA027_ChequeDetails_id =" + GetVA027_ChequeDetails_ID() +
                      ") And AD_Org_ID = " + GetAD_Org_ID() + " AND AD_Client_ID = " + GetAD_Client_ID();

                DB.ExecuteQuery(sql, null, Get_TrxName());
            }

            sql = "SELECT StdPrecision, C_Tax_ID, VA027_PayAmt FROM VA027_PostDatedCheck i INNER JOIN C_Currency c ON i.C_Currency_ID = c.C_Currency_ID " +
                  "WHERE VA027_PostDatedCheck_ID = (SELECT VA027_PostDatedCheck_ID FROM VA027_ChequeDetails " +
                  "WHERE VA027_ChequeDetails_ID = " + GetVA027_ChequeDetails_ID() + ") AND i.C_Charge_ID > 0 AND i.C_Tax_ID > 0 ";

            DataSet ds = new DataSet();

            ds = DB.ExecuteDataset(sql, null, Get_Trx());
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                stdprecision = Util.GetValueOfInt(ds.Tables[0].Rows[0]["StdPrecision"]);
                C_Tax_ID     = Util.GetValueOfInt(ds.Tables[0].Rows[0]["C_Tax_ID"]);
                PayAmt       = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["VA027_PayAmt"]);

                MTax tax = new MTax(GetCtx(), C_Tax_ID, null);

                if (tax.Get_ColumnIndex("Surcharge_Tax_ID") > 0 && tax.GetSurcharge_Tax_ID() > 0)
                {
                    TaxAmt = tax.CalculateSurcharge(PayAmt, true, stdprecision, out surchargeAmt);
                }
                else
                {
                    TaxAmt = tax.CalculateTax(PayAmt, true, stdprecision);
                }

                sql = "UPDATE VA027_PostDatedCheck SET TaxAmount= " + TaxAmt + " , SurchargeAmt= " + surchargeAmt +
                      " WHERE VA027_PostDatedCheck_ID = (SELECT VA027_PostDatedCheck_ID FROM VA027_ChequeDetails WHERE VA027_ChequeDetails_ID =" + GetVA027_ChequeDetails_ID() + " )";

                DB.ExecuteQuery(sql, null, Get_TrxName());
            }
            return(true);
        }
Пример #7
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();
            //
            String sql = "SELECT il.LineNetAmt, 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 = DB.ExecuteReader(sql, null, Get_TrxName());
                while (idr.Read())
                {
                    //Get References from invoiice header
                    c_Currency_ID       = Util.GetValueOfInt(idr[3]);
                    dateAcct            = Util.GetValueOfDateTime(idr[4]);
                    c_ConversionType_ID = Util.GetValueOfInt(idr[5]);
                    //	BaseAmt
                    Decimal baseAmt = Util.GetValueOfDecimal(idr[0]);
                    taxBaseAmt = Decimal.Add((Decimal)taxBaseAmt, baseAmt);
                    //	TaxAmt
                    Decimal amt = 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, IsTaxIncluded(), GetPrecision());
                    }
                    //
                    taxAmt = Decimal.Add(taxAmt, amt);
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, "setTaxBaseAmt", e);
                taxBaseAmt = null;
            }
            if (taxBaseAmt == null)
            {
                return(false);
            }

            //	Calculate Tax
            if (documentLevel || Env.Signum(taxAmt) == 0)
            {
                taxAmt = tax.CalculateTax((Decimal)taxBaseAmt, IsTaxIncluded(), 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);
        }
Пример #8
0
        /// <summary>
        /// Load Invoice Line
        /// </summary>
        /// <param name="order">order</param>
        /// <returns>DocLine Array</returns>
        private DocLine[] LoadLines(MOrder order)
        {
            List <DocLine> list = new List <DocLine>();

            MOrderLine[] lines = order.GetLines();
            for (int i = 0; i < lines.Length; i++)
            {
                MOrderLine line    = lines[i];
                DocLine    docLine = new DocLine(line, this);
                Decimal    Qty     = line.GetQtyOrdered();
                docLine.SetQty(Qty, order.IsSOTrx());
                //
                //	Decimal PriceActual = line.getPriceActual();
                Decimal?PriceCost = null;
                if (GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_PURCHASEORDER))   //	PO
                {
                    PriceCost = line.GetPriceCost();
                }
                Decimal?LineNetAmt = null;
                if (PriceCost != null && Env.Signum(PriceCost.Value) != 0)
                {
                    LineNetAmt = Decimal.Multiply(Qty, PriceCost.Value);
                }
                else
                {
                    LineNetAmt = line.GetLineNetAmt();
                }
                docLine.SetAmount(LineNetAmt);  //	DR
                Decimal PriceList = line.GetPriceList();
                int     C_Tax_ID  = docLine.GetC_Tax_ID();
                //	Correct included Tax
                if (IsTaxIncluded() && C_Tax_ID != 0)
                {
                    MTax tax = MTax.Get(GetCtx(), C_Tax_ID);
                    if (!tax.IsZeroTax())
                    {
                        Decimal LineNetAmtTax = tax.CalculateTax(LineNetAmt.Value, true, GetStdPrecision());
                        log.Fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax);
                        LineNetAmt = Decimal.Subtract(LineNetAmt.Value, LineNetAmtTax);
                        for (int t = 0; t < _taxes.Length; t++)
                        {
                            if (_taxes[t].GetC_Tax_ID() == C_Tax_ID)
                            {
                                _taxes[t].AddIncludedTax(LineNetAmtTax);
                                break;
                            }
                        }
                        Decimal PriceListTax = tax.CalculateTax(PriceList, true, GetStdPrecision());
                        PriceList = Decimal.Subtract(PriceList, PriceListTax);
                    }
                }       //	correct included Tax

                docLine.SetAmount(LineNetAmt, PriceList, Qty);
                list.Add(docLine);
            }

            //	Return Array
            DocLine[] dl = new DocLine[list.Count];
            dl = list.ToArray();
            return(dl);
        }
Пример #9
0
        /// <summary>
        /// Get Commitments
        /// </summary>
        /// <param name="doc">document</param>
        /// <param name="maxQty">Qty invoiced/matched</param>
        /// <param name="C_InvoiceLine_ID">invoice line</param>
        /// <returns>commitments (order lines)</returns>
        protected static DocLine[] GetCommitments(Doc doc, Decimal maxQty, int C_InvoiceLine_ID)
        {
            int precision = -1;
            //
            List <DocLine> list = new List <DocLine>();
            String         sql  = "SELECT * FROM C_OrderLine ol "
                                  + "WHERE EXISTS "
                                  + "(SELECT * FROM C_InvoiceLine il "
                                  + "WHERE il.C_OrderLine_ID=ol.C_OrderLine_ID"
                                  + " AND il.C_InvoiceLine_ID=" + C_InvoiceLine_ID + ")"
                                  + " OR EXISTS "
                                  + "(SELECT * FROM M_MatchPO po "
                                  + "WHERE po.C_OrderLine_ID=ol.C_OrderLine_ID"
                                  + " AND po.C_InvoiceLine_ID=" + C_InvoiceLine_ID + ")";
            IDataReader idr = null;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql, null, null);
                while (idr.Read())
                {
                    if (Env.Signum(maxQty) == 0)
                    {
                        continue;
                    }
                    MOrderLine line    = new MOrderLine(doc.GetCtx(), idr, null);
                    DocLine    docLine = new DocLine(line, doc);
                    //	Currency
                    if (precision == -1)
                    {
                        doc.SetC_Currency_ID(docLine.GetC_Currency_ID());
                        precision = MCurrency.GetStdPrecision(doc.GetCtx(), docLine.GetC_Currency_ID());
                    }
                    //	Qty
                    Decimal Qty = Math.Max(line.GetQtyOrdered(), maxQty);
                    docLine.SetQty(Qty, false);
                    //
                    Decimal PriceActual = line.GetPriceActual();
                    Decimal PriceCost   = line.GetPriceCost();
                    Decimal?LineNetAmt  = null;
                    if (Env.Signum(PriceCost) != 0)
                    {
                        LineNetAmt = Decimal.Multiply(Qty, PriceCost);
                    }
                    else if (Qty.Equals(maxQty))
                    {
                        LineNetAmt = line.GetLineNetAmt();
                    }
                    else
                    {
                        LineNetAmt = Decimal.Multiply(Qty, PriceActual);
                    }
                    maxQty = Decimal.Subtract(maxQty, Qty);

                    docLine.SetAmount(LineNetAmt);      //	DR
                    Decimal PriceList = line.GetPriceList();
                    int     C_Tax_ID  = docLine.GetC_Tax_ID();
                    //	Correct included Tax
                    if (C_Tax_ID != 0 && line.GetParent().IsTaxIncluded())
                    {
                        MTax tax = MTax.Get(doc.GetCtx(), C_Tax_ID);
                        if (!tax.IsZeroTax())
                        {
                            Decimal LineNetAmtTax = tax.CalculateTax(LineNetAmt.Value, true, precision);
                            _log.Fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax);
                            LineNetAmt = Decimal.Subtract(LineNetAmt.Value, LineNetAmtTax);
                            Decimal PriceListTax = tax.CalculateTax(PriceList, true, precision);
                            PriceList = Decimal.Subtract(PriceList, PriceListTax);
                        }
                    }   //	correct included Tax

                    docLine.SetAmount(LineNetAmt, PriceList, Qty);
                    list.Add(docLine);
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }
                _log.Log(Level.SEVERE, sql, e);
            }


            //	Return Array
            DocLine[] dl = new DocLine[list.Count];
            dl = list.ToArray();
            return(dl);
        }
Пример #10
0
        /** Generate Payment for Multi Cheque Details  */
        public string GenratePaymentLine(Ctx ctx, int Record_Id, int paymentDocumentTypeId, Trx trxName)
        {
            int     stdprecision = 0;
            Decimal surchargeAmt = Env.ZERO;
            Decimal TaxAmt       = Env.ZERO;

            StringBuilder        _sql = new StringBuilder();
            MVA027PostDatedCheck _pdc = new MVA027PostDatedCheck(ctx, Record_Id, trxName);
            String   sql      = "SELECT * FROM VA027_ChequeDetails WHERE VA027_PostDatedCheck_ID= " + Record_Id + " AND NVL(C_Payment_ID,0)=0 ORDER BY Va027_CheckDate";
            DataSet  _ds      = new DataSet();
            MPayment _payment = null;

            _ds = DB.ExecuteDataset(sql.ToString(), null, trxName);
            int _count = _ds.Tables[0].Rows.Count;

            if (_ds != null && _ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < _ds.Tables[0].Rows.Count; i++)
                {
                    MVA027ChequeDetails cd = new MVA027ChequeDetails(GetCtx(), Util.GetValueOfInt(_ds.Tables[0].Rows[i]["VA027_ChequeDetails_ID"]), Get_Trx());
                    if (cd.IsVA027_DiscountingPDC())
                    {
                        if (Util.GetValueOfInt(_ds.Tables[0].Rows[i]["C_Payment_ID"]) == 0)
                        {
                            _sql.Clear();
                            _payment = new MPayment(ctx, 0, trxName);
                            _payment.SetAD_Client_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[i]["AD_Client_ID"]));
                            _payment.SetAD_Org_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[i]["AD_Org_ID"]));
                            if (c_BankAccount_ID == 0)
                            {
                                _payment.SetC_BankAccount_ID(_pdc.GetC_BankAccount_ID());
                            }
                            else
                            {
                                _payment.SetC_BankAccount_ID(c_BankAccount_ID);
                            }
                            _payment.SetDateTrx(_sysDate);
                            _payment.SetDateAcct(_sysDate);                       //cd.GetVA027_CheckDate());
                            _payment.SetDescription(_pdc.GetVA027_Description());
                            _payment.SetIsPrepayment(_pdc.IsVA027_IsPrepayment());
                            if (_pdc.GetC_Charge_ID() > 0)
                            {
                                _payment.SetC_Charge_ID(_pdc.GetC_Charge_ID());
                            }
                            _payment.SetVA027_DiscountingPDC(true);
                            if (_pdc.GetVA027_Payee() != null)
                            {
                                _payment.SetDescription(_pdc.GetVA027_Payee());
                            }
                            //added by arpit
                            if (_pdc.GetC_BPartner_ID() > 0)
                            {
                                _payment.SetC_BPartner_ID(_pdc.GetC_BPartner_ID());
                                if (_pdc.GetC_BPartner_Location_ID() > 0)
                                {
                                    _payment.SetC_BPartner_Location_ID(_pdc.GetC_BPartner_Location_ID());
                                }
                            }
                            //end here
                            _payment.SetC_Tax_ID(_pdc.GetC_Tax_ID());
                            _payment.SetPayAmt(Math.Round(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["VA027_ChequeAmount"]), 2));
                            _payment.SetC_Currency_ID(_pdc.GetC_Currency_ID());
                            _payment.SetDiscountAmt(Math.Round(_pdc.GetVA027_DiscountAmt(), 2));
                            _payment.SetWriteOffAmt(Math.Round(_pdc.GetVA027_WriteoffAmt(), 2));
                            _payment.SetVA009_PaymentMethod_ID(_pdc.GetVA009_PaymentMethod_ID());
                            _payment.SetCheckNo(Util.GetValueOfString(_ds.Tables[0].Rows[i]["VA027_CheckNo"]));
                            _payment.SetCheckDate(Util.GetValueOfDateTime(_ds.Tables[0].Rows[i]["VA027_CheckDate"]));
                            _payment.SetValidMonths(Util.GetValueOfInt(_ds.Tables[0].Rows[i]["VA027_ValidMonth"]));
                            _payment.SetMicr(Util.GetValueOfString(_ds.Tables[0].Rows[i]["VA027_MICR"]));
                            _payment.SetAccountNo(Util.GetValueOfString(_ds.Tables[0].Rows[i]["VA027_AccountNo"]));
                            _payment.SetA_Name(Util.GetValueOfString(_ds.Tables[0].Rows[i]["VA027_AccountName"]));
                            _payment.SetPDCType(_pdc.GetPDCType());
                            //calculate Tax Amount
                            if (_pdc.GetC_Tax_ID() > 0)
                            {
                                sql = "SELECT StdPrecision FROM VA027_PostDatedCheck i INNER JOIN C_Currency c ON i.C_Currency_ID = c.C_Currency_ID " +
                                      "WHERE VA027_PostDatedCheck_ID = " + _pdc.GetVA027_PostDatedCheck_ID();
                                stdprecision = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                MTax tax = new MTax(GetCtx(), _pdc.GetC_Tax_ID(), null);
                                if (tax.Get_ColumnIndex("Surcharge_Tax_ID") > 0 && tax.GetSurcharge_Tax_ID() > 0)
                                {
                                    TaxAmt = tax.CalculateSurcharge(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["VA027_ChequeAmount"]), true, stdprecision, out surchargeAmt);
                                }
                                else
                                {
                                    TaxAmt = tax.CalculateTax(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["VA027_ChequeAmount"]), true, stdprecision);
                                }
                                _payment.SetTaxAmount(TaxAmt);
                                _payment.Set_Value("SurchargeAmt", surchargeAmt);
                            }

                            //_sql.Append("select docbasetype,c_doctype_id from C_doctype where c_doctype_id=" + _pdc.GetC_DocType_ID());
                            //_docBaseType = Util.GetValueOfString(DB.ExecuteScalar(_sql.ToString()));
                            _sql.Clear();
                            //if (_docBaseType == "PDR")
                            //{
                            //    _sql.Append("SELECT C_DocType_ID FROM C_DocType WHERE DocBaseType='ARR' AND AD_Client_ID=" + ctx.GetAD_Client_ID());

                            //    int _docuType = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));
                            //    _payment.SetC_DocType_ID(_docuType);
                            //    _sql.Clear();
                            //}
                            //else
                            //{
                            //    _sql.Append("SELECT C_DocType_ID FROM C_DocType WHERE DocBaseType='APP' AND AD_Client_ID=" + ctx.GetAD_Client_ID());
                            //    int _documentType = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString(), null, trxName));
                            //    _payment.SetC_DocType_ID(_documentType);
                            //    _sql.Clear();
                            //}
                            _payment.SetC_DocType_ID(paymentDocumentTypeId);
                            _exeStatus = _payment.GetVA009_ExecutionStatus();
                            _payment.SetVA009_ExecutionStatus(_exeStatus = "I");
                            if (_payment.Save(trxName))
                            {
                                //payment will get completed only if PaymentAllocate is generated.
                                if (GenratePaymentAllocate(GetCtx(), Util.GetValueOfInt(_ds.Tables[0].Rows[i]["VA027_ChequeDetails_ID"]), _payment.GetC_Payment_ID(), Get_TrxName()))
                                {
                                    _status = null;
                                    _status = _payment.CompleteIt();
                                }
                                else
                                {
                                    return("N");
                                }
                            }
                            else
                            {
                                return("F");
                            }
                            if (_status == "CO")
                            {
                                _payment.SetDocStatus("CO");
                                _payment.Set_Value("VA027_PostDatedCheck_ID", _pdc.GetVA027_PostDatedCheck_ID());
                                if (_payment.Save(trxName))
                                {
                                    cqd = new MVA027ChequeDetails(ctx, Util.GetValueOfInt(_ds.Tables[0].Rows[i]["VA027_ChequeDetails_ID"]), trxName);
                                    cqd.SetC_Payment_ID(_payment.GetC_Payment_ID());
                                    cqd.SetVA027_PaymentStatus("1");
                                    if (!cqd.Save(trxName))
                                    {
                                        trxName.Rollback();
                                        ValueNamePair pp = VLogger.RetrieveError();
                                        log.Info("Error Saving Chequedetails : " + pp.GetValue() + "  , Error Name : " + pp.GetName());
                                        _msg = Msg.GetMsg(ctx, "ChequedetailsNotSaved") + ", " + (pp != null ? pp.GetName() : "");

                                        return("N");
                                    }
                                }
                                documentno += _payment.GetDocumentNo() + ",";
                            }
                        }
                    }
                    else
                    {
                        if (Convert.ToDateTime(_ds.Tables[0].Rows[i]["VA027_CheckDate"]) <= _sysDate)
                        {
                            if (Util.GetValueOfInt(_ds.Tables[0].Rows[i]["C_Payment_ID"]) == 0)
                            {
                                _sql.Clear();
                                _payment = new MPayment(ctx, 0, trxName);
                                _payment.SetAD_Client_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[i]["AD_Client_ID"]));
                                _payment.SetAD_Org_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[i]["AD_Org_ID"]));
                                if (c_BankAccount_ID == 0)
                                {
                                    _payment.SetC_BankAccount_ID(_pdc.GetC_BankAccount_ID());
                                }
                                else
                                {
                                    _payment.SetC_BankAccount_ID(c_BankAccount_ID);
                                }
                                _payment.SetDateTrx(_sysDate);
                                _payment.SetDateAcct(cd.GetVA027_CheckDate());
                                _payment.SetDescription(_pdc.GetVA027_Description());
                                _payment.SetIsPrepayment(_pdc.IsVA027_IsPrepayment());
                                if (_pdc.GetC_Charge_ID() > 0)
                                {
                                    _payment.SetC_Charge_ID(_pdc.GetC_Charge_ID());
                                }
                                if (_pdc.GetVA027_Payee() != null)
                                {
                                    _payment.SetDescription(_pdc.GetVA027_Payee());
                                }
                                //added by arpit
                                if (_pdc.GetC_BPartner_ID() > 0)
                                {
                                    _payment.SetC_BPartner_ID(_pdc.GetC_BPartner_ID());
                                    if (_pdc.GetC_BPartner_Location_ID() > 0)
                                    {
                                        _payment.SetC_BPartner_Location_ID(_pdc.GetC_BPartner_Location_ID());
                                    }
                                }
                                //end here
                                _payment.SetC_Tax_ID(_pdc.GetC_Tax_ID());
                                _payment.SetPayAmt(Math.Round(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["VA027_ChequeAmount"]), 2));
                                _payment.SetC_Currency_ID(_pdc.GetC_Currency_ID());
                                _payment.SetDiscountAmt(Math.Round(_pdc.GetVA027_DiscountAmt(), 2));
                                _payment.SetWriteOffAmt(Math.Round(_pdc.GetVA027_WriteoffAmt(), 2));
                                _payment.SetVA009_PaymentMethod_ID(_pdc.GetVA009_PaymentMethod_ID());
                                _payment.SetCheckNo(Util.GetValueOfString(_ds.Tables[0].Rows[i]["VA027_CheckNo"]));
                                _payment.SetCheckDate(Util.GetValueOfDateTime(_ds.Tables[0].Rows[i]["VA027_CheckDate"]));
                                _payment.SetValidMonths(Util.GetValueOfInt(_ds.Tables[0].Rows[i]["VA027_ValidMonth"]));
                                _payment.SetMicr(Util.GetValueOfString(_ds.Tables[0].Rows[i]["VA027_MICR"]));
                                _payment.SetAccountNo(Util.GetValueOfString(_ds.Tables[0].Rows[i]["VA027_AccountNo"]));
                                _payment.SetA_Name(Util.GetValueOfString(_ds.Tables[0].Rows[i]["VA027_AccountName"]));
                                _payment.SetPDCType(_pdc.GetPDCType());

                                //calculate Tax Amount
                                if (_pdc.GetC_Tax_ID() > 0)
                                {
                                    sql = "SELECT StdPrecision FROM VA027_PostDatedCheck i INNER JOIN C_Currency c ON i.C_Currency_ID = c.C_Currency_ID " +
                                          "WHERE VA027_PostDatedCheck_ID = " + _pdc.GetVA027_PostDatedCheck_ID();
                                    stdprecision = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                    MTax tax = new MTax(GetCtx(), _pdc.GetC_Tax_ID(), null);
                                    if (tax.Get_ColumnIndex("Surcharge_Tax_ID") > 0 && tax.GetSurcharge_Tax_ID() > 0)
                                    {
                                        TaxAmt = tax.CalculateSurcharge(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["VA027_ChequeAmount"]), true, stdprecision, out surchargeAmt);
                                    }
                                    else
                                    {
                                        TaxAmt = tax.CalculateTax(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["VA027_ChequeAmount"]), true, stdprecision);
                                    }
                                    _payment.SetTaxAmount(TaxAmt);
                                    _payment.Set_Value("SurchargeAmt", surchargeAmt);
                                }
                                //_sql.Append("select docbasetype,c_doctype_id from C_doctype where c_doctype_id=" + _pdc.GetC_DocType_ID());
                                //_docBaseType = Util.GetValueOfString(DB.ExecuteScalar(_sql.ToString()));
                                _sql.Clear();
                                //if (_docBaseType == "PDR")
                                //{
                                //    _sql.Append("SELECT C_DocType_ID FROM C_DocType WHERE DocBaseType='ARR' AND AD_Client_ID=" + ctx.GetAD_Client_ID());

                                //    int _docuType = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));
                                //    _payment.SetC_DocType_ID(_docuType);
                                //    _sql.Clear();
                                //}
                                //else
                                //{
                                //    _sql.Append("SELECT C_DocType_ID FROM C_DocType WHERE DocBaseType='APP' AND AD_Client_ID=" + ctx.GetAD_Client_ID());
                                //    int _documentType = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString(), null, trxName));
                                //    _payment.SetC_DocType_ID(_documentType);
                                //    _sql.Clear();
                                //}
                                _payment.SetC_DocType_ID(paymentDocumentTypeId);
                                _exeStatus = _payment.GetVA009_ExecutionStatus();
                                _payment.SetVA009_ExecutionStatus(_exeStatus = "I");
                                if (_payment.Save(trxName))
                                {
                                    //payment will get completed only if PaymentAllocate is generated.
                                    if (GenratePaymentAllocate(GetCtx(), Util.GetValueOfInt(_ds.Tables[0].Rows[i]["VA027_ChequeDetails_ID"]), _payment.GetC_Payment_ID(), Get_TrxName()))
                                    {
                                        _status = null;
                                        _status = _payment.CompleteIt();
                                    }
                                    else
                                    {
                                        return("N");
                                    }
                                }
                                else
                                {
                                    return("F");
                                }
                                if (_status == "CO")
                                {
                                    _payment.SetDocStatus("CO");
                                    _payment.Set_Value("VA027_PostDatedCheck_ID", _pdc.GetVA027_PostDatedCheck_ID());
                                    if (_payment.Save(trxName))
                                    {
                                        cqd = new MVA027ChequeDetails(ctx, Util.GetValueOfInt(_ds.Tables[0].Rows[i]["VA027_ChequeDetails_ID"]), trxName);
                                        cqd.SetC_Payment_ID(_payment.GetC_Payment_ID());
                                        cqd.SetVA027_PaymentStatus("1");
                                        if (!cqd.Save(trxName))
                                        {
                                            trxName.Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            log.Info("Error Saving Chequedetails : " + pp.GetValue() + "  , Error Name : " + pp.GetName());
                                            _msg = Msg.GetMsg(ctx, "ChequedetailsNotSaved") + ", " + (pp != null ? pp.GetName() : "");
                                            return("N");
                                        }
                                    }
                                    documentno += _payment.GetDocumentNo() + ",";
                                }
                            }
                            else
                            {
                                return("E");
                            }
                        }
                        else
                        {
                            return("F");
                        }
                    }
                }
            }
            if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT Count(VA027_ChequeDetails_ID) From VA027_ChequeDetails Where VA027_PostDatedCheck_ID=" + Record_Id
                                                    + " AND VA027_PaymentStatus!='1'", null, trxName)) == 0)
            {
                _pdc.SetVA027_PaymentStatus("1");
                _pdc.SetVA027_PaymentGenerated(true);
                _pdc.SetVA027_GeneratePayment("Y");
                if (!_pdc.Save(trxName))
                {
                    return("E");
                }
            }

            return("Success");
        }