Example #1
0
        /// <summary>
        /// Delect recordes from allocation
        /// </summary>
        /// <param name="hdr"></param>
        /// <returns>Bool type</returns>
        private Boolean Delete(MAllocationHdr hdr)
        {
            //	_m_trx.start();
            Boolean success = false;

            String msg = null;

            //	Std Period open?
            msg = DocumentEngine.IsPeriodOpen(hdr);
            if (msg != null)
            {
                msg = "@DeleteError@" + hdr.GetDocumentNo() + ": " + msg;
                log.Warning(msg);
                return(false);
            }

            if (hdr.Delete(true, _m_trx))
            {
                log.Fine(hdr.ToString());
                success = true;
            }
            if (success)
            {
                _m_trx.Commit();
            }
            else
            {
                _m_trx.Rollback();
            }
            return(success);
        }
        }       //	allocateOldestFirst

        /// <summary>
        /// Create Allocation allocation
        /// </summary>
        /// <param name="_C_Currency_ID"></param>
        /// <param name="description"></param>
        /// <param name="_dateAcct"></param>
        /// <param name="Amount"></param>
        /// <param name="DiscountAmt"></param>
        /// <param name="WriteOffAmt"></param>
        /// <param name="OverUnderAmt"></param>
        /// <param name="_C_BPartner_ID"></param>
        /// <param name="C_Payment_ID"></param>
        /// <param name="C_Invoice_ID"></param>
        /// <param name="AD_Org_ID"></param>
        /// <returns>true if created</returns>
        private Boolean CreateAllocation(int _C_Currency_ID, String description,
                                         DateTime?_dateAcct, Decimal Amount,
                                         Decimal?DiscountAmt, Decimal?WriteOffAmt, Decimal?OverUnderAmt,
                                         int _C_BPartner_ID, int C_Payment_ID, int C_Invoice_ID, int AD_Org_ID)
        {
            //	Process old Allocation
            if (_allocation != null &&
                _allocation.GetC_Currency_ID() != _C_Currency_ID)
            {
                ProcessAllocation();
            }
            //	New Allocation
            if (_allocation == null)
            {
                _allocation = new MAllocationHdr(GetCtx(), false, _dateAcct,    //	automatic
                                                 _C_Currency_ID, "Auto " + description, Get_Trx());
                _allocation.SetAD_Org_ID(AD_Org_ID);
                if (!_allocation.Save())
                {
                    return(false);
                }
            }

            //	New Allocation Line
            MAllocationLine aLine = new MAllocationLine(_allocation, Amount,
                                                        DiscountAmt, WriteOffAmt, OverUnderAmt);

            aLine.SetC_BPartner_ID(_C_BPartner_ID);
            aLine.SetC_Payment_ID(C_Payment_ID);
            aLine.SetC_Invoice_ID(C_Invoice_ID);
            return(aLine.Save());
        }       //	createAllocation
        }       //	writeOff

        /// <summary>
        /// Process Allocation
        /// </summary>
        /// <returns>true if processed</returns>
        private Boolean ProcessAllocation()
        {
            if (_m_alloc == null)
            {
                return(true);
            }
            ProcessPayment();
            //	Process It
            if (_m_alloc.ProcessIt(DocActionVariables.ACTION_COMPLETE) && _m_alloc.Save())
            {
                _m_alloc = null;
                return(true);
            }
            //
            _m_alloc = null;
            return(false);
        }       //	processAllocation
        }       //	createAllocation

        /// <summary>
        /// Process Allocation
        /// </summary>
        /// <returns>true if processes/saved or none</returns>
        private Boolean ProcessAllocation()
        {
            if (_allocation == null)
            {
                return(true);
            }
            Boolean _success = _allocation.ProcessIt(MAllocationHdr.DOCACTION_Complete);

            if (_success)
            {
                _success = _allocation.Save();
            }
            else
            {
                _allocation.Save();
            }
            AddLog(0, _allocation.GetDateAcct(), null, _allocation.GetDescription());
            _allocation = null;
            return(_success);
        }       //	processAllocation
Example #5
0
        /// <summary>
        ///     Process
        /// </summary>
        /// <returns>message</returns>
        protected override String DoIt()
        {
            log.Info("C_BP_Group_ID=" + _C_BP_Group_ID + ", C_BPartner_ID=" + _C_BPartner_ID
                     + ", DateAcct= " + _DateAcct_From + " - " + _DateAcct_To
                     + ", C_AllocationHdr_ID=" + _C_AllocationHdr_ID);

            _m_trx = Trx.Get("AllocReset");
            int count = 0;

            if (_C_AllocationHdr_ID != 0)
            {
                MAllocationHdr hdr = new MAllocationHdr(GetCtx(), _C_AllocationHdr_ID, _m_trx);
                if (Delete(hdr))
                {
                    count++;
                }
                _m_trx.Close();
                return("@Deleted@ #" + count);
            }

            //	Selection
            StringBuilder sql = new StringBuilder("SELECT * FROM C_AllocationHdr ah "
                                                  + "WHERE EXISTS (SELECT * FROM C_AllocationLine al "
                                                  + "WHERE ah.C_AllocationHdr_ID=al.C_AllocationHdr_ID");

            if (_C_BPartner_ID != 0)
            {
                sql.Append(" AND al.C_BPartner_ID=" + _C_BPartner_ID);
            }
            else if (_C_BP_Group_ID != 0 && _C_BP_Group_ID != -1)
            {
                sql.Append(" AND EXISTS (SELECT * FROM C_BPartner bp "
                           + "WHERE bp.C_BPartner_ID=al.C_BPartner_ID AND bp.C_BP_Group_ID=" + _C_BP_Group_ID + ")");
            }
            else
            {
                sql.Append(" AND AD_Client_ID=" + GetCtx().GetAD_Client_ID());
            }
            if (_DateAcct_From != null)
            {
                sql.Append(" AND TRIM(ah.DateAcct) >=" + _DateAcct_From);
            }
            if (_DateAcct_To != null)
            {
                sql.Append(" AND TRIM(ah.DateAcct) <= " + _DateAcct_To);
            }
            //	Do not delete Cash Trx
            sql.Append(" AND al.C_CashLine_ID IS NULL)");
            //	Open Period
            sql.Append(" AND EXISTS (SELECT * FROM C_Period p"
                       + " INNER JOIN C_PeriodControl pc ON (p.C_Period_ID=pc.C_Period_ID AND pc.DocBaseType='CMA') "
                       + "WHERE ah.DateAcct BETWEEN p.StartDate AND p.EndDate)");

            DataTable   dt  = null;
            IDataReader idr = null;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql.ToString(), null, _m_trx);
                dt  = new DataTable();
                dt.Load(idr);
                idr.Close();
                foreach (DataRow dr in dt.Rows)
                {
                    Delete(new MAllocationHdr(GetCtx(), dr, _m_trx));
                }
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql.ToString(), e);
                if (idr != null)
                {
                    idr.Close();
                }
                _m_trx.Rollback();
            }
            finally
            {
                dt = null;
                if (idr != null)
                {
                    idr.Close();
                }
                _m_trx.Close();
            }


            return("@Deleted@ #" + count);
        }
        /// <summary>
        /// Save Data
        /// </summary>

        public void SavePaymentData(List <Dictionary <string, string> > rowsPayment, List <Dictionary <string, string> > rowsCash, List <Dictionary <string, string> > rowsInvoice, string currency,
                                    bool isCash, int _C_BPartner_ID, int _windowNo, string payment, DateTime DateTrx, string applied, string discount, string writeOff, string open)
        {
            //  fixed fields
            int AD_Client_ID  = ctx.GetContextAsInt(_windowNo, "AD_Client_ID");
            int AD_Org_ID     = ctx.GetContextAsInt(_windowNo, "AD_Org_ID");
            int C_BPartner_ID = _C_BPartner_ID;
            int C_Order_ID    = 0;
            int C_CashLine_ID = 0;
            //DateTime? DateTrx = Util.GetValueOfDateTime(vdtpDateField.GetValue());
            int C_Currency_ID = Convert.ToInt32(currency);

            //
            if (AD_Org_ID == 0)
            {
                //Classes.ShowMessage.Error("Org0NotAllowed", null);
                return;
            }
            //
            // log.Config("Client=" + AD_Client_ID + ", Org=" + AD_Org_ID
            //     + ", BPartner=" + C_BPartner_ID + ", Date=" + DateTrx);

            Trx trx = Trx.Get(Trx.CreateTrxName("AL"), true);

            /**
             * Generation of allocations:               amount/discount/writeOff
             *  - if there is one payment -- one line per invoice is generated
             *    with both the Invoice and Payment reference
             *      Pay=80  Inv=100 Disc=10 WOff=10 =>  80/10/10    Pay#1   Inv#1
             *    or
             *      Pay=160 Inv=100 Disc=10 WOff=10 =>  80/10/10    Pay#1   Inv#1
             *      Pay=160 Inv=100 Disc=10 WOff=10 =>  80/10/10    Pay#1   Inv#2
             *
             *  - if there are multiple payment lines -- the amounts are allocated
             *    starting with the first payment and payment
             *      Pay=60  Inv=100 Disc=10 WOff=10 =>  60/10/10    Pay#1   Inv#1
             *      Pay=100 Inv=100 Disc=10 WOff=10 =>  20/0/0      Pay#2   Inv#1
             *      Pay=100 Inv=100 Disc=10 WOff=10 =>  80/10/10    Pay#2   Inv#2
             *
             *  - if you apply a credit memo to an invoice
             *              Inv=10  Disc=0  WOff=0  =>  10/0/0              Inv#1
             *              Inv=-10 Disc=0  WOff=0  =>  -10/0/0             Inv#2
             *
             *  - if you want to write off a (partial) invoice without applying,
             *    enter zero in applied
             *              Inv=10  Disc=1  WOff=9  =>  0/1/9               Inv#1
             *  Issues
             *  - you cannot write-off a payment
             */


            //  Payment - Loop and Add them to paymentList/amountList

            try
            {
                #region Payment-Loop
                //int pRows = vdgvPayment.ItemsSource.OfType<object>().Count();
                //  IList rowsPayment = vdgvPayment.ItemsSource as IList;

                List <int>     paymentList       = new List <int>(rowsPayment.Count);
                List <Decimal> amountList        = new List <Decimal>(rowsPayment.Count);
                Decimal        paymentAppliedAmt = Env.ZERO;
                for (int i = 0; i < rowsPayment.Count; i++)
                {
                    //  Payment line is selected
                    // bool boolValue = false;
                    //if (boolValue)
                    {
                        //KeyNamePair pp = (KeyNamePair)vdgvPayment.Rows[i].Cells[2].Value;
                        // KeyNamePair pp = (KeyNamePair)(((BindableObject)rowsPayment[i]).GetValue(2));   //  Value
                        //  Payment variables
                        int C_Payment_ID = Util.GetValueOfInt(rowsPayment[i]["cpaymentid"]);
                        paymentList.Add(C_Payment_ID);
                        //
                        // Decimal PaymentAmt = Util.GetValueOfDecimal(vdgvPayment.Rows[i].Cells[_payment].Value);  //  Applied Payment
                        Decimal PaymentAmt = Util.GetValueOfDecimal(rowsPayment[i][payment]);  //  Applied Payment
                        amountList.Add(PaymentAmt);
                        //
                        paymentAppliedAmt = Decimal.Add(paymentAppliedAmt, PaymentAmt);
                        //
                        //   log.Fine("C_Payment_ID=" + C_Payment_ID
                        //       + " - PaymentAmt=" + PaymentAmt); // + " * " + Multiplier + " = " + PaymentAmtAbs);
                        MPayment pay1 = new MPayment(ctx, C_Payment_ID, trx);
                    }
                }
                //log.Config("Number of Payments=" + paymentList.Count + " - Total=" + paymentAppliedAmt);
                #endregion

                //  Invoices - Loop and generate alloctions
                #region Invoice-Loop with allocation
                // int iRows = vdgvInvoice.ItemsSource.OfType<object>().Count();
                //  IList rowsInvoice=vdgvInvoice.ItemsSource as IList;

                Decimal totalAppliedAmt = Env.ZERO;

                //	Create Allocation - but don't save yet
                MAllocationHdr alloc = new MAllocationHdr(ctx, true,    //	manual
                                                          DateTrx, C_Currency_ID, ctx.GetContext("#AD_User_Name"), trx);
                alloc.SetAD_Org_ID(AD_Org_ID);


                //	For all invoices
                int invoiceLines = 0;
                for (int i = 0; i < rowsInvoice.Count; i++)
                {
                    //  Invoice line is selected

                    //if (boolValue)
                    {
                        invoiceLines++;
                        //  KeyNamePair pp = (KeyNamePair)vdgvInvoice.Rows[i].Cells[2].Value;    //  Value
                        // KeyNamePair pp = (KeyNamePair)(((BindableObject)rowsPayment[i]).GetValue(2));      //  Value
                        //  Invoice variables
                        int C_Invoice_ID = Util.GetValueOfInt(rowsInvoice[i]["cinvoiceid"]);
                        //  Decimal AppliedAmt = Util.GetValueOfDecimal(vdgvInvoice.Rows[i].Cells[_applied].Value);

                        Decimal AppliedAmt = Util.GetValueOfDecimal(rowsInvoice[i][applied]);
                        //  semi-fixed fields (reset after first invoice)
                        //     Decimal DiscountAmt = Util.GetValueOfDecimal(vdgvInvoice.Rows[i].Cells[_discount].Value);
                        //    Decimal WriteOffAmt = Util.GetValueOfDecimal(vdgvInvoice.Rows[i].Cells[_writeOff].Value);

                        Decimal DiscountAmt = Util.GetValueOfDecimal(rowsInvoice[i][discount]);
                        Decimal WriteOffAmt = Util.GetValueOfDecimal(rowsInvoice[i][writeOff]);

                        //	OverUnderAmt needs to be in Allocation Currency
                        //     Decimal OverUnderAmt = Decimal.Subtract(Util.GetValueOfDecimal(vdgvInvoice.Rows[i].Cells[_open].Value),
                        //        Decimal.Subtract(AppliedAmt, Decimal.Subtract(DiscountAmt, WriteOffAmt)));

                        Decimal OverUnderAmt = Decimal.Subtract(Util.GetValueOfDecimal(rowsInvoice[i][open]),
                                                                Decimal.Subtract(AppliedAmt, Decimal.Subtract(DiscountAmt, WriteOffAmt)));

                        // log.Config("Invoice #" + i + " - AppliedAmt=" + AppliedAmt);// + " -> " + AppliedAbs);

                        //Payment Settelment**********
                        //  loop through all payments until invoice applied
                        int noPayments = 0;
                        for (int j = 0; j < paymentList.Count && Env.Signum(AppliedAmt) != 0; j++)
                        {
                            int     C_Payment_ID = Util.GetValueOfInt(paymentList[j]);
                            Decimal PaymentAmt   = Util.GetValueOfDecimal(amountList[j]);
                            if (Env.Signum(PaymentAmt) != 0)
                            {
                                // log.Config(".. with payment #" + j + ", Amt=" + PaymentAmt);
                                noPayments++;
                                //  use Invoice Applied Amt
                                Decimal amount = Env.ZERO;
                                if ((Math.Abs(AppliedAmt)).CompareTo(Math.Abs(PaymentAmt)) > 0)
                                {
                                    amount = PaymentAmt;
                                }
                                else
                                {
                                    amount = AppliedAmt;
                                }
                                //log.Fine("C_Payment_ID=" + C_Payment_ID + ", C_Invoice_ID=" + C_Invoice_ID
                                // + ", Amount=" + amount + ", Discount=" + DiscountAmt + ", WriteOff=" + WriteOffAmt);

                                //	Allocation Header
                                if (alloc.Get_ID() == 0 && !alloc.Save())
                                {
                                    // log.Log(Level.SEVERE, "Allocation not created");
                                    trx.Rollback();
                                    trx.Close();
                                    return;
                                }
                                //	Allocation Line
                                MAllocationLine aLine = new MAllocationLine(alloc, amount,
                                                                            DiscountAmt, WriteOffAmt, OverUnderAmt);
                                aLine.SetDocInfo(C_BPartner_ID, C_Order_ID, C_Invoice_ID);
                                //aLine.SetPaymentInfo(C_Payment_ID, C_CashLine_ID);
                                aLine.SetPaymentInfo(C_Payment_ID, 0);//cashline for payment allocation is zero
                                if (!aLine.Save())
                                {
                                    // log.Log(Level.SEVERE, "Allocation Line not written - Invoice=" + C_Invoice_ID);
                                }
                                //  Apply Discounts and WriteOff only first time
                                DiscountAmt = Env.ZERO;
                                WriteOffAmt = Env.ZERO;
                                //  subtract amount from Payment/Invoice
                                AppliedAmt = Decimal.Subtract(AppliedAmt, amount);
                                //AppliedAmt = Decimal.Subtract(PaymentAmt, AppliedAmt);
                                PaymentAmt = Decimal.Subtract(PaymentAmt, amount);
                                //log.Fine("Allocation Amount=" + amount + " - Remaining  Applied=" + AppliedAmt + ", Payment=" + PaymentAmt);

                                //amountList.set(j, PaymentAmt);  //  update
                                amountList[j] = PaymentAmt; //  update//set
                            }                               //	for all applied amounts

                            MPayment pay1 = new MPayment(ctx, C_Payment_ID, trx);
                        }       //	loop through payments for invoice

                        //  No Payments allocated and none existing (e.g. Inv/CM)

                        if (noPayments == 0 && paymentList.Count == 0)
                        {
                            int C_Payment_ID = 0;
                            //  log.Config(" ... no payment - TotalApplied=" + totalAppliedAmt);
                            //  Create Allocation
                            //  log.Fine("C_Payment_ID=" + C_Payment_ID + ", C_Invoice_ID=" + C_Invoice_ID
                            //  + ", Amount=" + AppliedAmt + ", Discount=" + DiscountAmt + ", WriteOff=" + WriteOffAmt);

                            //	Allocation Header
                            if (alloc.Get_ID() == 0 && !alloc.Save())
                            {
                                //log.Log(Level.SEVERE, "Allocation not created");
                                trx.Rollback();
                                trx.Close();
                                return;
                            }
                            //	Allocation Line
                            MAllocationLine aLine = new MAllocationLine(alloc, AppliedAmt,
                                                                        DiscountAmt, WriteOffAmt, OverUnderAmt);
                            aLine.SetDocInfo(C_BPartner_ID, C_Order_ID, C_Invoice_ID);
                            //aLine.SetPaymentInfo(C_Payment_ID, C_CashLine_ID);
                            aLine.SetPaymentInfo(C_Payment_ID, 0);
                            if (!aLine.Save(trx))
                            {
                                //Log(Level.SEVERE, "Allocation Line not written - Invoice=" + C_Invoice_ID);
                            }

                            // log.Fine("Allocation Amount=" + AppliedAmt);
                            MPayment pay1 = new MPayment(ctx, C_Payment_ID, trx);
                        }

                        totalAppliedAmt = Decimal.Add(totalAppliedAmt, AppliedAmt);
                        //   log.Config("TotalRemaining=" + totalAppliedAmt);
                    } //  invoice selected
                }     //  invoice loop

                #endregion

                //	Only Payments and total of 0 (e.g. Payment/Reversal)
                #region Reversal Payments
                if (invoiceLines == 0 && paymentList.Count > 0 &&
                    Env.Signum(paymentAppliedAmt) == 0)
                {
                    for (int i = 0; i < paymentList.Count; i++)
                    {
                        int     C_Payment_ID = Util.GetValueOfInt(paymentList[i]);
                        Decimal PaymentAmt   = Util.GetValueOfDecimal(amountList[i]);
                        // log.Fine("Payment=" + C_Payment_ID
                        //         + ", Amount=" + PaymentAmt);// + ", Abs=" + PaymentAbs);

                        //	Allocation Header
                        if (alloc.Get_ID() == 0 && !alloc.Save())
                        {
                            // log.Log(Level.SEVERE, "Allocation not created");
                            trx.Rollback();
                            trx.Close();
                            return;
                        }
                        //	Allocation Line
                        MAllocationLine aLine = new MAllocationLine(alloc, PaymentAmt,
                                                                    Env.ZERO, Env.ZERO, Env.ZERO);
                        aLine.SetDocInfo(C_BPartner_ID, 0, 0);
                        aLine.SetPaymentInfo(C_Payment_ID, 0);
                        if (!aLine.Save(trx))
                        {
                            //  log.Log(Level.SEVERE, "Allocation Line not saved - Payment=" + C_Payment_ID);
                        }
                        MPayment pay1 = new MPayment(ctx, C_Payment_ID, trx);
                    }
                }       //	onlyPayments
                #endregion

                if (Env.Signum(totalAppliedAmt) != 0)
                {
                    //log.Log(Level.SEVERE, "Remaining TotalAppliedAmt=" + totalAppliedAmt);
                }

                //	Should start WF
                if (alloc.Get_ID() != 0)
                {
                    alloc.ProcessIt(DocActionVariables.ACTION_COMPLETE);
                    alloc.Save();
                }

                //  Test/Set IsPaid for Invoice - requires that allocation is posted
                #region Set Invoice IsPaid
                for (int i = 0; i < rowsInvoice.Count; i++)
                {
                    //  Invoice line is selected

                    // if (boolValue)
                    {
                        //KeyNamePair pp = (KeyNamePair)vdgvInvoice.Rows[i].Cells[2].Value;    //  Value
                        // KeyNamePair pp = (KeyNamePair)((BindableObject)rowsInvoice[i]).GetValue(2);    //  Value

                        //  Invoice variables
                        int    C_Invoice_ID = Util.GetValueOfInt(rowsInvoice[i]["cinvoiceid"]);
                        String sql          = "SELECT invoiceOpen(C_Invoice_ID, 0) "
                                              + "FROM C_Invoice WHERE C_Invoice_ID=@param1";
                        Decimal opens = Util.GetValueOfDecimal(DB.GetSQLValueBD(trx, sql, C_Invoice_ID));
                        if (open != null && Env.Signum(opens) == 0)
                        {
                            sql = "UPDATE C_Invoice SET IsPaid='Y' "
                                  + "WHERE C_Invoice_ID=" + C_Invoice_ID;
                            int no = DB.ExecuteQuery(sql, null, trx);
                            // log.Config("Invoice #" + i + " is paid");
                        }
                        else
                        {
                            //  log.Config("Invoice #" + i + " is not paid - " + open);
                        }
                    }
                }
                #endregion

                //  Test/Set Payment is fully allocated
                #region Set Payment Allocated
                if (rowsPayment.Count > 0)
                {
                    for (int i = 0; i < paymentList.Count; i++)
                    {
                        int      C_Payment_ID = Util.GetValueOfInt(paymentList[i]);
                        MPayment pay          = new MPayment(ctx, C_Payment_ID, trx);
                        if (pay.TestAllocation())
                        {
                            pay.Save();
                        }

                        string  sqlGetOpenPayments = "SELECT  currencyConvert(ALLOCPAYMENTAVAILABLE(C_Payment_ID) ,p.C_Currency_ID ,260,p.DateTrx ,p.C_ConversionType_ID ,p.AD_Client_ID ,p.AD_Org_ID) FROM C_Payment p Where C_Payment_ID = " + C_Payment_ID;
                        object  result             = DB.ExecuteScalar(sqlGetOpenPayments, null, trx);
                        Decimal?amtPayment         = 0;
                        if (result == null || result == DBNull.Value)
                        {
                            amtPayment = -1;
                        }
                        else
                        {
                            amtPayment = Util.GetValueOfDecimal(result);
                        }

                        if (amtPayment == 0)
                        {
                            pay.SetIsAllocated(true);
                        }
                        else
                        {
                            pay.SetIsAllocated(false);
                        }
                        pay.Save();

                        //log.Config("Payment #" + i + (pay.IsAllocated() ? " not" : " is")
                        //    + " fully allocated");
                    }
                }
                #endregion

                paymentList.Clear();
                amountList.Clear();
                trx.Commit();
                trx.Close();
            }
            catch
            {
                if (trx != null)
                {
                    trx.Rollback();
                    trx.Close();
                    trx = null;
                }
            }
            finally
            {
                if (trx != null)
                {
                    trx.Rollback();
                    trx.Close();
                    trx = null;
                }
            }
        }
        public string SaveCashData(List <Dictionary <string, string> > paymentData, List <Dictionary <string, string> > rowsCash, List <Dictionary <string, string> > rowsInvoice, string currency,
                                   bool isCash, int _C_BPartner_ID, int _windowNo, string payment, DateTime DateTrx, string applied, string discount, string writeOff, string open)
        {
            //if (_noInvoices + _noCashLines == 0)
            //    return "";
            int C_Currency_ID = Convert.ToInt32(currency);
            //  fixed fields
            int AD_Client_ID  = ctx.GetContextAsInt(_windowNo, "AD_Client_ID");
            int AD_Org_ID     = ctx.GetContextAsInt(_windowNo, "AD_Org_ID");
            int C_BPartner_ID = _C_BPartner_ID;
            int C_Order_ID    = 0;
            int C_CashLine_ID = 0;

            //
            if (AD_Org_ID == 0)
            {
                //Classes.ShowMessage.Error("Org0NotAllowed", null);
                return("");
            }
            //
            //  log.Config("Client=" + AD_Client_ID + ", Org=" + AD_Org_ID
            //    + ", BPartner=" + C_BPartner_ID + ", Date=" + DateTrx);

            Trx trx = Trx.Get(Trx.CreateTrxName("AL"), true);

            /**
             * Generation of allocations:               amount/discount/writeOff
             *  - if there is one payment -- one line per invoice is generated
             *    with both the Invoice and Payment reference
             *      Pay=80  Inv=100 Disc=10 WOff=10 =>  80/10/10    Pay#1   Inv#1
             *    or
             *      Pay=160 Inv=100 Disc=10 WOff=10 =>  80/10/10    Pay#1   Inv#1
             *      Pay=160 Inv=100 Disc=10 WOff=10 =>  80/10/10    Pay#1   Inv#2
             *
             *  - if there are multiple payment lines -- the amounts are allocated
             *    starting with the first payment and payment
             *      Pay=60  Inv=100 Disc=10 WOff=10 =>  60/10/10    Pay#1   Inv#1
             *      Pay=100 Inv=100 Disc=10 WOff=10 =>  20/0/0      Pay#2   Inv#1
             *      Pay=100 Inv=100 Disc=10 WOff=10 =>  80/10/10    Pay#2   Inv#2
             *
             *  - if you apply a credit memo to an invoice
             *              Inv=10  Disc=0  WOff=0  =>  10/0/0              Inv#1
             *              Inv=-10 Disc=0  WOff=0  =>  -10/0/0             Inv#2
             *
             *  - if you want to write off a (partial) invoice without applying,
             *    enter zero in applied
             *              Inv=10  Disc=1  WOff=9  =>  0/1/9               Inv#1
             *  Issues
             *  - you cannot write-off a payment
             */

            //  CashLines - Loop and Add them to cashList/CashAmountList
            #region CashLines-Loop
            // int cRows = vdgvCashLines.RowCount;
            // IList rowsCash = vdgvCashLine.ItemsSource as IList;

            List <int>     cashList       = new List <int>(rowsCash.Count);
            List <Decimal> CashAmtList    = new List <Decimal>(rowsCash.Count);
            Decimal        cashAppliedAmt = Env.ZERO;
            for (int i = 0; i < rowsCash.Count; i++)
            {
                //  Payment line is selected
                bool boolValue = false;
                bool flag      = false;
                // if (boolValue)
                {
                    //  Payment variables
                    C_CashLine_ID = Util.GetValueOfInt(rowsCash[i]["ccashlineid"]);
                    cashList.Add(C_CashLine_ID);
                    //
                    //Decimal PaymentAmt = Util.GetValueOfDecimal(((BindableObject)rowsCash[i]).GetValue(_payment));  //  Applied Payment


                    Decimal PaymentAmt = Util.GetValueOfDecimal(rowsCash[i][payment]);  //  Applied Payment

                    CashAmtList.Add(PaymentAmt);
                    //
                    cashAppliedAmt = Decimal.Add(cashAppliedAmt, PaymentAmt);
                    //
                    // log.Fine("C_CashLine_ID=" + C_CashLine_ID
                    //  + " - PaymentAmt=" + PaymentAmt); // + " * " + Multiplier + " = " + PaymentAmtAbs);
                }
            }
            //log.Config("Number of Cashlines=" + cashList.Count + " - Total=" + cashAppliedAmt);
            #endregion

            //  Invoices - Loop and generate alloctions
            #region Invoice-Loop with allocation
            // int iRows = vdgvInvoice.RowCount;
            //  IList rowsInvoice = vdgvInvoice.ItemsSource as IList;
            Decimal totalAppliedAmt = Env.ZERO;

            //	Create Allocation - but don't save yet
            MAllocationHdr alloc = new MAllocationHdr(ctx, true,        //	manual
                                                      DateTrx, C_Currency_ID, ctx.GetContext("#AD_User_Name"), trx);
            alloc.SetAD_Org_ID(AD_Org_ID);

            //	For all invoices
            int invoiceLines = 0;
            //for (int i = 0; i < rowsCash.Count; i++)
            for (int i = 0; i < rowsInvoice.Count; i++)
            {
                //  Invoice line is selected
                bool boolValue = false;
                bool flag      = false;
                // if (boolValue)
                {
                    invoiceLines++;
                    //  Invoice variables
                    /// int C_Invoice_ID = Util.GetValueOfInt(((BindableObject)rowsInvoice[i]).GetValue("C_INVOICE_ID"));

                    int C_Invoice_ID = Util.GetValueOfInt(rowsInvoice[i]["cinvoiceid"]);

                    Decimal AppliedAmt = Util.GetValueOfDecimal(rowsInvoice[i][applied]);
                    //  semi-fixed fields (reset after first invoice)
                    Decimal DiscountAmt = Util.GetValueOfDecimal(rowsInvoice[i][discount]);
                    Decimal WriteOffAmt = Util.GetValueOfDecimal(rowsInvoice[i][writeOff]);
                    //	OverUnderAmt needs to be in Allocation Currency
                    Decimal OverUnderAmt = Decimal.Subtract(Util.GetValueOfDecimal(rowsInvoice[i][open]),
                                                            Decimal.Subtract(AppliedAmt, Decimal.Subtract(DiscountAmt, WriteOffAmt)));

                    //log.Config("Invoice #" + i + " - AppliedAmt=" + AppliedAmt);// + " -> " + AppliedAbs);

                    //CashLines settelment************
                    //  loop through all payments until invoice applied
                    int noCashlines = 0;
                    for (int j = 0; j < cashList.Count && Env.Signum(AppliedAmt) != 0; j++)
                    {
                        C_CashLine_ID = Util.GetValueOfInt(cashList[j]);
                        Decimal PaymentAmt = Util.GetValueOfDecimal(CashAmtList[j]);
                        if (Env.Signum(PaymentAmt) != 0)
                        {
                            //log.Config(".. with payment #" + j + ", Amt=" + PaymentAmt);
                            noCashlines++;
                            //  use Invoice Applied Amt
                            Decimal amount = AppliedAmt;
                            //log.Fine("C_CashLine_ID=" + C_CashLine_ID + ", C_Invoice_ID=" + C_Invoice_ID
                            //    + ", Amount=" + amount + ", Discount=" + DiscountAmt + ", WriteOff=" + WriteOffAmt);

                            //	Allocation Header
                            if (alloc.Get_ID() == 0 && !alloc.Save())
                            {
                                //  log.Log(Level.SEVERE, "Allocation not created");
                                trx.Rollback();
                                trx.Close();
                                return("");
                            }
                            //	Allocation Line
                            MAllocationLine aLine = new MAllocationLine(alloc, amount,
                                                                        DiscountAmt, WriteOffAmt, OverUnderAmt);
                            aLine.SetDocInfo(C_BPartner_ID, C_Order_ID, C_Invoice_ID);
                            aLine.SetPaymentInfo(0, C_CashLine_ID);//payment for payment allocation is zero
                            if (!aLine.Save())
                            {
                                //  log.Log(Level.SEVERE, "Allocation Line not written - Invoice=" + C_Invoice_ID);

                                //  Apply Discounts and WriteOff only first time
                                DiscountAmt = Env.ZERO;
                            }
                            WriteOffAmt = Env.ZERO;
                            //  subtract amount from Payment/Invoice
                            AppliedAmt = Decimal.Subtract(AppliedAmt, amount);
                            //AppliedAmt = Decimal.Subtract(PaymentAmt, AppliedAmt);
                            PaymentAmt = Decimal.Subtract(PaymentAmt, amount);
                            //log.Fine("Allocation Amount=" + amount + " - Remaining  Applied=" + AppliedAmt + ", Payment=" + PaymentAmt);

                            //amountList.set(j, PaymentAmt);  //  update
                            if (CashAmtList.Count > 0)
                            {
                                MCashLine cline = new MCashLine(ctx, C_CashLine_ID, null);
                                cline.SetAmount(Decimal.Subtract(cline.GetAmount(), CashAmtList[j]));
                                if (!cline.Save())
                                {
                                    // log.SaveError("AmountIsNotUpdated" + C_CashLine_ID.ToString(), "");
                                }
                                CashAmtList[j] = PaymentAmt; //  update//set
                            }
                        }                                    //	for all applied amounts
                    }                                        //	loop through Cash for invoice(Charge)

                    //  No Cashlines allocated and none existing
                    if (rowsCash.Count > 0)
                    {
                        if (noCashlines == 0 && cashList.Count == 0)
                        {
                            C_CashLine_ID = 0;
                            //log.Config(" ... no CashLines - TotalApplied=" + totalAppliedAmt);
                            //  Create Allocation
                            // log.Fine("C_CashLine_ID=" + C_CashLine_ID + ", C_Invoice_ID=" + C_Invoice_ID
                            //     + ", Amount=" + AppliedAmt + ", Discount=" + DiscountAmt + ", WriteOff=" + WriteOffAmt);

                            //	Allocation Header
                            if (alloc.Get_ID() == 0 && !alloc.Save())
                            {
                                //log.Log(Level.SEVERE, "Allocation not created");
                                trx.Rollback();
                                trx.Close();
                                return("");
                            }
                            //	Allocation Line
                            MAllocationLine aLine = new MAllocationLine(alloc, AppliedAmt,
                                                                        DiscountAmt, WriteOffAmt, OverUnderAmt);
                            aLine.SetDocInfo(C_BPartner_ID, C_Order_ID, C_Invoice_ID);
                            aLine.SetPaymentInfo(0, C_CashLine_ID);
                            if (!aLine.Save(trx))
                            {
                            }
                            // log.Log(Level.SEVERE, "Allocation Line not written - Invoice=" + C_Invoice_ID);

                            //log.Fine("Allocation Amount=" + AppliedAmt);
                        }
                    }
                    totalAppliedAmt = Decimal.Add(totalAppliedAmt, AppliedAmt);
                    //log.Config("TotalRemaining=" + totalAppliedAmt);
                } //  invoice selected
            }     //  invoice loop

            #endregion

            if (Env.Signum(totalAppliedAmt) != 0)
            {
                //log.Log(Level.SEVERE, "Remaining TotalAppliedAmt=" + totalAppliedAmt);

                //	Should start WF
                if (alloc.Get_ID() != 0)
                {
                    alloc.ProcessIt(DocActionVariables.ACTION_COMPLETE);
                    alloc.Save();
                }
            }

            //  Test/Set IsPaid for Invoice - requires that allocation is posted
            #region Set Invoice IsPaid
            for (int i = 0; i < rowsInvoice.Count; i++)
            {
                bool boolValue = false;
                //  Invoice line is selected
                bool flag = false;
                //Dispatcher.BeginInvoke(delegate
                //{
                //    boolValue = GetBoolValue(vdgvInvoice, i, 0);
                //    flag = true;
                //    SetBusy(false);
                //});
                //while (!flag)
                //{
                //    System.Threading.Thread.Sleep(1);
                //}
                // if (boolValue)
                {
                    //KeyNamePair pp = (KeyNamePair)vdgvInvoice.Rows[i].Cells[2].Value;    //  Value
                    //KeyNamePair pp = (KeyNamePair)((BindableObject)rowsInvoice[i]).GetValue(2);    //  Value
                    //  Invoice variables
                    int    C_Invoice_ID = Util.GetValueOfInt(rowsInvoice[i]["cinvoiceid"]);
                    String sql          = "SELECT invoiceOpen(C_Invoice_ID, 0) "
                                          + "FROM C_Invoice WHERE C_Invoice_ID=@param1";
                    Decimal opens = Util.GetValueOfDecimal(DB.GetSQLValueBD(trx, sql, C_Invoice_ID));
                    if (open != null && Env.Signum(opens) == 0)
                    {
                        sql = "UPDATE C_Invoice SET IsPaid='Y' "
                              + "WHERE C_Invoice_ID=" + C_Invoice_ID;
                        int no = DB.ExecuteQuery(sql, null, trx);
                        // log.Config("Invoice #" + i + " is paid");
                    }
                    else
                    {
                        // log.Config("Invoice #" + i + " is not paid - " + open);
                    }
                }
            }
            #endregion

            //  Test/Set CashLine is fully allocated
            #region Set CashLine Allocated
            if (rowsCash.Count > 0)
            {
                for (int i = 0; i < cashList.Count; i++)
                {
                    C_CashLine_ID = Util.GetValueOfInt(cashList[i]);
                    MCashLine cash = new MCashLine(ctx, C_CashLine_ID, trx);
                    if (cash.GetAmount() == 0)
                    {
                        cash.SetIsAllocated(true);
                        cash.Save();
                    }
                    // log.Config("Cash #" + i + (cash.IsAllocated() ? " not" : " is")
                    //   + " fully allocated");
                }
            }
            #endregion

            cashList.Clear();
            CashAmtList.Clear();
            trx.Commit();
            trx.Close();
            return("");
        }
        }       //	doIt

        /// <summary>
        /// Write Off
        /// </summary>
        /// <param name="C_Invoice_ID"></param>
        /// <param name="DocumentNo"></param>
        /// <param name="DateInvoiced"></param>
        /// <param name="C_Currency_ID"></param>
        /// <param name="OpenAmt"></param>
        /// <returns>true if written off</returns>
        private Boolean writeOff(int C_Invoice_ID, String DocumentNo, DateTime?DateInvoiced,
                                 int C_Currency_ID, Decimal OpenAmt)
        {
            //	Nothing to do
            if (Env.Signum(OpenAmt) == 0)
            {
                return(false);
            }
            if (Math.Abs(OpenAmt).CompareTo(_MaxInvWriteOffAmt) >= 0)
            {
                return(false);
            }
            //
            if (_IsSimulation)
            {
                AddLog(C_Invoice_ID, DateInvoiced, OpenAmt, DocumentNo);
                return(true);
            }

            //	Invoice
            MInvoice invoice = new MInvoice(GetCtx(), C_Invoice_ID, Get_TrxName());

            if (!invoice.IsSOTrx())
            {
                OpenAmt = Decimal.Negate(OpenAmt);
            }
            //	Allocation
            if (_m_alloc == null || C_Currency_ID != _m_alloc.GetC_Currency_ID())
            {
                ProcessAllocation();
                _m_alloc = new MAllocationHdr(GetCtx(), true,
                                              _DateAcct, C_Currency_ID,
                                              GetProcessInfo().GetTitle() + " #" + GetAD_PInstance_ID(), Get_TrxName());
                _m_alloc.SetAD_Org_ID(invoice.GetAD_Org_ID());
                if (!_m_alloc.Save())
                {
                    log.Log(Level.SEVERE, "Cannot create allocation header");
                    return(false);
                }
            }
            //	Payment
            if (_CreatePayment &&
                (_m_payment == null ||
                 invoice.GetC_BPartner_ID() != _m_payment.GetC_BPartner_ID() ||
                 C_Currency_ID != _m_payment.GetC_Currency_ID()))
            {
                ProcessPayment();
                _m_payment = new MPayment(GetCtx(), 0, Get_TrxName());
                _m_payment.SetAD_Org_ID(invoice.GetAD_Org_ID());
                _m_payment.SetC_BankAccount_ID(_C_BankAccount_ID);
                _m_payment.SetTenderType(MPayment.TENDERTYPE_Check);
                _m_payment.SetDateTrx(_DateAcct);
                _m_payment.SetDateAcct(_DateAcct);
                _m_payment.SetDescription(GetProcessInfo().GetTitle() + " #" + GetAD_PInstance_ID());
                _m_payment.SetC_BPartner_ID(invoice.GetC_BPartner_ID());
                _m_payment.SetIsReceipt(true);          //	payments are negative
                _m_payment.SetC_Currency_ID(C_Currency_ID);
                if (!_m_payment.Save())
                {
                    log.Log(Level.SEVERE, "Cannot create payment");
                    return(false);
                }
            }

            //	Line
            MAllocationLine aLine = null;

            if (_CreatePayment)
            {
                aLine = new MAllocationLine(_m_alloc, OpenAmt,
                                            Env.ZERO, Env.ZERO, Env.ZERO);
                _m_payment.SetPayAmt(Decimal.Add(_m_payment.GetPayAmt(), OpenAmt));
                aLine.SetC_Payment_ID(_m_payment.GetC_Payment_ID());
            }
            else
            {
                aLine = new MAllocationLine(_m_alloc, Env.ZERO,
                                            Env.ZERO, OpenAmt, Env.ZERO);
            }
            aLine.SetC_Invoice_ID(C_Invoice_ID);
            if (aLine.Save())
            {
                AddLog(C_Invoice_ID, DateInvoiced, OpenAmt, DocumentNo);
                return(true);
            }
            //	Error
            log.Log(Level.SEVERE, "Cannot create allocation line for C_Invoice_ID=" + C_Invoice_ID);
            return(false);
        }       //	writeOff
Example #9
0
        public string DoIt(int recordID, Ctx ct, Trx trx, int CurrencyType_ID)
        {
            //Check Bank Response
//            sql.Append(@"SELECT count(bd.VA009_BankResponse) FROM va009_batchlinedetails bd INNER JOIN va009_batchlines bl ON bl.va009_batchlines_id=bd.va009_batchlines_id
//                          WHERE bl.va009_batch_id=" + recordID + " AND bd.VA009_BankResponse='IP' AND bd.AD_Client_ID = " + ct.GetAD_Client_ID() + " Group by bd.VA009_BankResponse ");
//            countresponse = Util.GetValueOfInt(DB.ExecuteScalar(sql.ToString(), null,trx));
            sql.Clear();
            sql.Append(@"SELECT b.c_bankaccount_id,  bl.c_bpartner_id,  bld.c_currency_id,  bld.c_invoice_id,  bld.dueamt, bld.VA009_ConvertedAmt,  bld.discountamt, bld.va009_batchlinedetails_ID , bl.va009_batchlines_id , 
                                     bld.discountdate, inv.issotrx,  inv.isreturntrx, bld.c_invoicepayschedule_id, bld.ad_org_id, bld.ad_client_id , doc.DocBaseType , bld.va009_paymentmethod_id , bl.VA009_DueAmount
                                 FROM va009_batchlinedetails bld INNER JOIN va009_batchlines bl ON bl.va009_batchlines_id=bld.va009_batchlines_id 
                                 INNER JOIN va009_batch b ON b.va009_batch_id =bl.va009_batch_id INNER JOIN c_invoice inv ON inv.c_invoice_id = bld.c_invoice_id
                                 INNER JOIN C_DocType doc ON doc.C_Doctype_ID = inv.C_Doctype_ID
                                 WHERE  NVL(bl.c_payment_id , 0) = 0 AND NVL(bld.c_payment_id , 0) = 0 AND NVL(bld.C_AllocationHdr_ID , 0) = 0 AND  b.va009_batch_id    =" + recordID);

            if (IsBankresponse == "Y" && countresponse == 0)
            {
                sql.Append(" AND bld.va009_bankresponse='RE' ORDER BY bl.c_bpartner_id ASC ");
            }
            else if (IsBankresponse == "N")
            {
                sql.Append(" ORDER BY bld.va009_batchlines_id ,  bl.c_bpartner_id ASC ");
            }
            //else if (IsBankresponse == "Y" && countresponse > 0)
            //    return Msg.GetMsg(ct, "VA009_AllResponseNotAvailable");

            DataSet ds = DB.ExecuteDataset(sql.ToString(), null, trx);

            MVA009Batch _batch = new MVA009Batch(ct, recordID, trx);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                #region Consolidate  = true
                if (_batch.IsVA009_Consolidate() == true)
                {
                    int c_currency_id = 0; int Bpartner_ID = 0; int C_Payment_ID = 0, batchline_id = 0, allocationHeader = 0;

                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        #region Create View Allocation Header and line when the Due Amount on Batch line = 0
                        if (c_currency_id == Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]) &&
                            Bpartner_ID == Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_bpartner_id"]) &&
                            batchline_id == Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlines_id"]) &&
                            Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["VA009_DueAmount"]) == 0)
                        {
                            MAllocationLine alloclne = new MAllocationLine(ct, 0, trx);
                            alloclne.SetAD_Client_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]));
                            alloclne.SetAD_Org_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]));
                            alloclne.SetC_AllocationHdr_ID(allocationHeader);
                            alloclne.SetC_BPartner_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_bpartner_id"]));
                            alloclne.SetC_Invoice_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoice_id"]));
                            alloclne.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoicepayschedule_id"]));
                            alloclne.SetDateTrx(System.DateTime.Now.ToLocalTime());
                            alloclne.SetAmount(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["VA009_ConvertedAmt"]));
                            alloclne.SetDiscountAmt(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["discountamt"]));
                            if (!alloclne.Save(trx))
                            {
                                msg = Msg.GetMsg(ct, "VA009_PymentNotSaved");
                                ValueNamePair ppE = VAdvantage.Logging.VLogger.RetrieveError();
                                SavePaymentBachLog(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]), Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]),
                                                   recordID, ppE.ToString(), ct, trx);
                                trx.Rollback();
                                payment.Clear();
                                viewAllocationId.Clear();
                                allocationDocumentNo = string.Empty;
                                paymentDocumentNo    = string.Empty;
                                break;
                            }
                            else
                            {
                                // set Allocation ID on Batch Line Details
                                batchLineDetails = new MVA009BatchLineDetails(ct, Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlinedetails_ID"]), trx);
                                batchLineDetails.SetC_AllocationHdr_ID(allocationHeader);
                                batchLineDetails.Save();
                            }
                        }
                        else if (Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["VA009_DueAmount"]) == 0)
                        {
                            MAllocationHdr allocHdr = new MAllocationHdr(ct, 0, trx);
                            allocHdr.SetAD_Client_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]));
                            allocHdr.SetAD_Org_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]));
                            allocHdr.SetDateAcct(System.DateTime.Now.ToLocalTime());
                            allocHdr.SetDateTrx(System.DateTime.Now.ToLocalTime());
                            allocHdr.SetC_Currency_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]));
                            allocHdr.SetDocStatus("DR");
                            allocHdr.SetDocAction("CO");
                            if (!allocHdr.Save(trx))
                            {
                                msg = Msg.GetMsg(ct, "VA009_PymentNotSaved");
                                ValueNamePair ppE = VAdvantage.Logging.VLogger.RetrieveError();
                                SavePaymentBachLog(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]), Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]),
                                                   recordID, ppE.ToString(), ct, trx);
                                trx.Rollback();
                                payment.Clear();
                                viewAllocationId.Clear();
                                allocationDocumentNo = string.Empty;
                                paymentDocumentNo    = string.Empty;
                                break;
                            }
                            else
                            {
                                if (!viewAllocationId.Contains(allocHdr.GetC_AllocationHdr_ID()))
                                {
                                    viewAllocationId.Add(allocHdr.GetC_AllocationHdr_ID());
                                }
                                MAllocationLine alloclne = new MAllocationLine(ct, 0, trx);
                                alloclne.SetAD_Client_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]));
                                alloclne.SetAD_Org_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]));
                                alloclne.SetC_AllocationHdr_ID(allocHdr.GetC_AllocationHdr_ID());
                                alloclne.SetC_BPartner_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_bpartner_id"]));
                                alloclne.SetC_Invoice_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoice_id"]));
                                alloclne.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoicepayschedule_id"]));
                                alloclne.SetDateTrx(System.DateTime.Now.ToLocalTime());
                                alloclne.SetAmount(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["VA009_ConvertedAmt"]));
                                alloclne.SetDiscountAmt(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["discountamt"]));
                                if (!alloclne.Save(trx))
                                {
                                    msg = Msg.GetMsg(ct, "VA009_PymentNotSaved");
                                    ValueNamePair ppE = VAdvantage.Logging.VLogger.RetrieveError();
                                    SavePaymentBachLog(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]), Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]),
                                                       recordID, ppE.ToString(), ct, trx);
                                    trx.Rollback();
                                    payment.Clear();
                                    viewAllocationId.Clear();
                                    allocationDocumentNo = string.Empty;
                                    paymentDocumentNo    = string.Empty;
                                    break;
                                }
                                else
                                {
                                    c_currency_id         = Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]);
                                    Bpartner_ID           = Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_bpartner_id"]);
                                    batchline_id          = Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlines_id"]);
                                    allocationHeader      = allocHdr.GetC_AllocationHdr_ID();
                                    allocationDocumentNo += allocHdr.GetDocumentNo() + " , ";

                                    // set Allocation ID on Batch Line
                                    //batchLines = new MVA009BatchLines(ct, Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlines_id"]), trx.trx);
                                    //batchLineDetails.SetC_AllocationHdr_ID(allocationHeader);
                                    //batchLines.Save();

                                    // set Allocation ID on Batch Line Details
                                    batchLineDetails = new MVA009BatchLineDetails(ct, Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlinedetails_ID"]), trx);
                                    batchLineDetails.SetC_AllocationHdr_ID(allocationHeader);
                                    batchLineDetails.Save();
                                }
                            }
                        }
                        #endregion

                        #region Create a new entry of payment Allocate against same payment and the condition
                        else if (c_currency_id == Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]) &&
                                 Bpartner_ID == Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_bpartner_id"]) &&
                                 batchline_id == Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlines_id"]))
                        {
                            MPaymentAllocate PayAlocate = new MPaymentAllocate(ct, 0, trx);
                            PayAlocate.SetC_Payment_ID(C_Payment_ID);
                            PayAlocate.SetC_Invoice_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoice_id"]));
                            PayAlocate.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoicepayschedule_id"]));
                            //if (Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) == "ARC" || Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) == "APC")
                            //{
                            //    PayAlocate.SetDiscountAmt(-1 * Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["discountamt"]));
                            //    PayAlocate.SetAmount(-1 * Util.GetValueOfInt(ds.Tables[0].Rows[i]["dueamt"]));
                            //    PayAlocate.SetInvoiceAmt(-1 * Util.GetValueOfInt(ds.Tables[0].Rows[i]["dueamt"]));
                            //}
                            //else
                            //{
                            PayAlocate.SetDiscountAmt(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["discountamt"]));
                            PayAlocate.SetAmount(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["VA009_ConvertedAmt"]));
                            PayAlocate.SetInvoiceAmt(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["dueamt"]));
                            //}
                            PayAlocate.SetAD_Client_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]));
                            PayAlocate.SetAD_Org_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]));
                            PayAlocate.SetWriteOffAmt(0);
                            PayAlocate.SetOverUnderAmt(0);
                            if (!PayAlocate.Save())
                            {
                                msg = Msg.GetMsg(ct, "VA009_PymentAllocateNotSaved");
                                ValueNamePair ppE = VAdvantage.Logging.VLogger.RetrieveError();
                                SavePaymentBachLog(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]), Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]),
                                                   recordID, ppE.ToString(), ct, trx);
                                trx.Rollback();
                                payment.Clear();
                                viewAllocationId.Clear();
                                allocationDocumentNo = string.Empty;
                                paymentDocumentNo    = string.Empty;
                                break;
                            }
                            else
                            {
                                batchLineDetails = new MVA009BatchLineDetails(ct, Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlinedetails_ID"]), trx);
                                batchLineDetails.SetC_Payment_ID(C_Payment_ID);
                                batchLineDetails.Save();
                            }
                        }
                        #endregion

                        #region Create a new payment
                        else
                        {
                            MPayment _pay         = new MPayment(ct, 0, trx);
                            int      C_Doctype_ID = GetDocumnetType(Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]), ct);
                            _pay.SetC_DocType_ID(C_Doctype_ID);
                            _pay.SetAD_Client_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]));
                            _pay.SetAD_Org_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]));
                            _pay.SetDateAcct(System.DateTime.Now);
                            _pay.SetDateTrx(System.DateTime.Now);
                            _pay.SetC_BankAccount_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_bankaccount_id"]));
                            _pay.SetC_BPartner_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_bpartner_id"]));
                            _pay.SetC_Currency_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]));
                            _pay.SetC_ConversionType_ID(CurrencyType_ID);
                            _pay.SetVA009_PaymentMethod_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_paymentmethod_id"]));
                            tenderType = Util.GetValueOfString(DB.ExecuteScalar(@"select VA009_PAYMENTBASETYPE from VA009_PAYMENTMETHOD where VA009_PAYMENTMETHOD_ID=" + Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_paymentmethod_id"])));
                            if (tenderType == "K")          // Credit Card
                            {
                                _pay.SetTenderType("C");
                            }
                            else if (tenderType == "D")   // Direct Debit
                            {
                                _pay.SetTenderType("D");
                            }
                            else if (tenderType == "S")    // Check
                            {
                                _pay.SetTenderType("K");
                            }
                            else if (tenderType == "T")    // Direct Deposit
                            {
                                _pay.SetTenderType("A");
                            }
                            else
                            {
                                _pay.SetTenderType("A");
                            }
                            if (!_pay.Save())
                            {
                                msg = Msg.GetMsg(ct, "VA009_PymentNotSaved");
                                ValueNamePair ppE = VAdvantage.Logging.VLogger.RetrieveError();
                                SavePaymentBachLog(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]), Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]),
                                                   recordID, ppE.ToString(), ct, trx);
                                trx.Rollback();
                                payment.Clear();
                                viewAllocationId.Clear();
                                allocationDocumentNo = string.Empty;
                                paymentDocumentNo    = string.Empty;
                                break;
                            }
                            else
                            {
                                if (!payment.Contains(_pay.GetC_Payment_ID()))
                                {
                                    payment.Add(_pay.GetC_Payment_ID());
                                }
                                c_currency_id      = Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]);
                                Bpartner_ID        = Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_bpartner_id"]);
                                C_Payment_ID       = _pay.GetC_Payment_ID();
                                batchline_id       = Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlines_id"]);
                                paymentDocumentNo += _pay.GetDocumentNo() + " , ";

                                MPaymentAllocate PayAlocate = new MPaymentAllocate(ct, 0, trx);
                                PayAlocate.SetC_Payment_ID(C_Payment_ID);
                                PayAlocate.SetC_Invoice_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoice_id"]));
                                PayAlocate.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoicepayschedule_id"]));
                                //if (Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) == "ARC" || Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) == "APC")
                                //{
                                //    PayAlocate.SetDiscountAmt(-1 * Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["discountamt"]));
                                //    PayAlocate.SetAmount(-1 * Util.GetValueOfInt(ds.Tables[0].Rows[i]["dueamt"]));
                                //    PayAlocate.SetInvoiceAmt(-1 * Util.GetValueOfInt(ds.Tables[0].Rows[i]["dueamt"]));
                                //}
                                //else
                                //{
                                PayAlocate.SetDiscountAmt(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["discountamt"]));
                                PayAlocate.SetAmount(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["VA009_ConvertedAmt"]));
                                PayAlocate.SetInvoiceAmt(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["dueamt"]));
                                //}
                                PayAlocate.SetAD_Client_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]));
                                PayAlocate.SetAD_Org_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]));
                                PayAlocate.SetWriteOffAmt(0);
                                PayAlocate.SetOverUnderAmt(0);
                                if (!PayAlocate.Save())
                                {
                                    msg = Msg.GetMsg(ct, "VA009_PymentAllocateNotSaved");
                                    ValueNamePair ppE = VAdvantage.Logging.VLogger.RetrieveError();
                                    SavePaymentBachLog(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]), Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]),
                                                       recordID, ppE.ToString(), ct, trx);
                                    trx.Rollback();
                                    payment.Clear();
                                    viewAllocationId.Clear();
                                    allocationDocumentNo = string.Empty;
                                    paymentDocumentNo    = string.Empty;
                                    break;
                                }
                                else
                                {
                                    batchLineDetails = new MVA009BatchLineDetails(ct, Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlinedetails_ID"]), trx);
                                    batchLineDetails.SetC_Payment_ID(_pay.GetC_Payment_ID());
                                    batchLineDetails.Save();

                                    batchLines = new MVA009BatchLines(ct, Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlines_id"]), trx);
                                    batchLines.SetC_Payment_ID(_pay.GetC_Payment_ID());
                                    batchLines.Save();
                                }
                            }
                        }
                        #endregion
                    }

                    // Complete the Consolidate Records of payment
                    for (int i = 0; i < payment.Count(); i++)
                    {
                        MPayment completePayment = new MPayment(ct, payment[i], trx);
                        if (completePayment.CompleteIt() == "CO")
                        {
                            completePayment.SetDocStatus("CO");
                            completePayment.SetDocAction("CL");
                            completePayment.Save();
                        }
                    }

                    // Complete the Consolidate Records of View allocation
                    for (int i = 0; i < viewAllocationId.Count(); i++)
                    {
                        MAllocationHdr completeAllocation = new MAllocationHdr(ct, viewAllocationId[i], trx);
                        if (completeAllocation.CompleteIt() == "CO")
                        {
                            completeAllocation.SetDocStatus("CO");
                            completeAllocation.SetDocAction("CL");
                            completeAllocation.Save();
                        }
                    }
                }
                #endregion

                #region Consolidate = false
                else if (_batch.IsVA009_Consolidate() == false)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        MPayment _pay         = new MPayment(ct, 0, trx);
                        int      C_Doctype_ID = GetDocumnetType(Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]), ct);
                        _pay.SetC_DocType_ID(C_Doctype_ID);
                        _pay.SetC_Invoice_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoice_id"]));
                        _pay.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoicepayschedule_id"]));
                        _pay.SetAD_Client_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]));
                        _pay.SetAD_Org_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]));
                        _pay.SetDateAcct(System.DateTime.Now);
                        _pay.SetDateTrx(System.DateTime.Now);
                        _pay.SetC_ConversionType_ID(CurrencyType_ID);
                        _pay.SetC_BankAccount_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_bankaccount_id"]));
                        _pay.SetC_BPartner_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_bpartner_id"]));
                        //if (Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) == "ARC" || Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) == "APC")
                        //{
                        //    _pay.SetDiscountAmt(-1 * Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["discountamt"]));
                        //    _pay.SetPayAmt(-1 * Util.GetValueOfInt(ds.Tables[0].Rows[i]["dueamt"]));
                        //}
                        //else
                        //{
                        _pay.SetDiscountAmt(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["discountamt"]));
                        //_pay.SetPayAmt(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["dueamt"]));
                        _pay.SetPayAmt(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["VA009_ConvertedAmt"]));
                        //}
                        _pay.SetC_Currency_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]));
                        _pay.SetVA009_PaymentMethod_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_paymentmethod_id"]));
                        tenderType = Util.GetValueOfString(DB.ExecuteScalar(@"select VA009_PAYMENTBASETYPE from VA009_PAYMENTMETHOD where VA009_PAYMENTMETHOD_ID=" + Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_paymentmethod_id"])));
                        if (tenderType == "K")          // Credit Card
                        {
                            _pay.SetTenderType("C");
                        }
                        else if (tenderType == "D")   // Direct Debit
                        {
                            _pay.SetTenderType("D");
                        }
                        else if (tenderType == "S")    // Check
                        {
                            _pay.SetTenderType("K");
                        }
                        else if (tenderType == "T")    // Direct Deposit
                        {
                            _pay.SetTenderType("A");
                        }
                        else
                        {
                            _pay.SetTenderType("A");
                        }
                        if (!_pay.Save(trx))
                        {
                            msg = Msg.GetMsg(ct, "VA009_PymentNotSaved");
                            ValueNamePair ppE = VAdvantage.Logging.VLogger.RetrieveError();
                            SavePaymentBachLog(Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_client_id"]), Util.GetValueOfInt(ds.Tables[0].Rows[i]["ad_org_id"]),
                                               recordID, ppE.ToString(), ct, trx);
                            trx.Rollback();
                            allocationDocumentNo = string.Empty;
                            paymentDocumentNo    = string.Empty;
                            break;
                        }
                        else
                        {
                            paymentDocumentNo += _pay.GetDocumentNo() + " , ";
                            batchLineDetails   = new MVA009BatchLineDetails(ct, Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_batchlinedetails_ID"]), trx);
                            batchLineDetails.SetC_Payment_ID(_pay.GetC_Payment_ID());
                            batchLineDetails.Save(trx);
                            if (_pay.CompleteIt() == "CO")
                            {
                                _pay.SetDocStatus("CO");
                                _pay.SetDocAction("CL");
                                _pay.Save(trx);
                            }
                        }
                    }
                }
                #endregion
            }
            else
            {
                return(msg = Msg.GetMsg(ct, "VA009_LinesNotAvailable"));
            }

            if (paymentDocumentNo != "" || allocationDocumentNo != "")
            {
                SaveRecordPaymentBachLog(_batch.GetAD_Client_ID(), _batch.GetAD_Org_ID(), recordID, paymentDocumentNo, allocationDocumentNo, ct, trx);
            }

            return(msg);
        }