protected override string DoIt()
        {
            MCash cashheader = new MCash(GetCtx(), GetRecord_ID(), Get_Trx());

            sql = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cashheader.GetC_CashBook_ID();
            int C_Currencyheader_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));

            sql = "select * from C_Cashline WHERE C_Cash_ID=" + GetRecord_ID();
            DataSet dscashline = DB.ExecuteDataset(sql, null, Get_Trx());

            if (dscashline != null)
            {
                if (dscashline.Tables[0].Rows.Count > 0)
                {
                    for (i = 0; i < dscashline.Tables[0].Rows.Count; i++)
                    {
                        cashline = new MCashLine(GetCtx(), Util.GetValueOfInt(dscashline.Tables[0].Rows[i]["C_CashLine_ID"]), Get_Trx());
                        if (cashline.GetCashType().ToString() == "A" || cashline.GetCashType().ToString() == "F")
                        {
                            sql = "Select * from C_Cash where C_CashBook_Id=" + cashline.GetC_CashBook_ID() + " and docstatus='DR' and  DateAcct=" + GlobalVariable.TO_DATE(DateTime.Now, true);
                            DataSet dscashbook = DB.ExecuteDataset(sql, null, Get_Trx());
                            if (dscashbook != null)
                            {
                                if (dscashbook.Tables[0].Rows.Count > 0)
                                {
                                    int j;
                                    for (j = 0; j < dscashbook.Tables[0].Rows.Count; j++)
                                    {
                                        cash = new MCash(GetCtx(), Util.GetValueOfInt(dscashbook.Tables[0].Rows[j]["C_Cash_ID"]), Get_Trx());
                                        if (!_cashIds.Contains(cash.GetC_Cash_ID()))
                                        {
                                            _cashIds.Add(cash.GetC_Cash_ID());
                                        }
                                        //ViennaAdvantage.Model.MCashLine cashline1 = new ViennaAdvantage.Model.MCashLine(GetCtx(), 0, Get_Trx());
                                        MCashLine cashline1 = new MCashLine(GetCtx(), 0, Get_Trx());
                                        cashline1.SetC_Cash_ID(cash.GetC_Cash_ID());
                                        cashline1.SetAD_Client_ID(cash.GetAD_Client_ID());
                                        cashline1.SetAD_Org_ID(cash.GetAD_Org_ID());
                                        if (cashline.GetCashType().ToString() == "A")
                                        {
                                            cashline1.SetCashType("F");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline1.SetCashType("A");
                                        }
                                        // Added by Bharat as discussed with Ravikant on 22 March 2017
                                        if (cashline1.Get_ColumnIndex("C_ConversionType_ID") > 0)
                                        {
                                            cashline1.SetC_ConversionType_ID(cashline.GetC_ConversionType_ID());
                                        }
                                        cashline1.SetC_CashBook_ID(cashheader.GetC_CashBook_ID());
                                        cashline1.SetC_BPartner_ID(cashline.GetC_BPartner_ID());
                                        sql         = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cash.GetC_CashBook_ID();
                                        Currency_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                        if (Currency_ID == C_Currencyheader_ID)
                                        {
                                            cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                            cashline1.SetAmount(Decimal.Negate(cashline.GetAmount()));
                                            cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                        }
                                        else
                                        {
                                            //cashline1.SetC_Currency_ID(Currency_ID);
                                            // Change by Bharat as discussed with Ravikant on 22 March 2017
                                            cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                            if (cashline1.Get_ColumnIndex("C_ConversionType_ID") > 0)
                                            {
                                                //_Curencyrate = MConversionRate.GetRate(C_Currencyheader_ID, Currency_ID, cash.GetDateAcct(), cashline.GetC_ConversionType_ID(),
                                                //    cash.GetAD_Client_ID(), cash.GetAD_Org_ID());

                                                convertedamount = Decimal.Negate(Util.GetValueOfDecimal(cashline.GetConvertedAmt()));

                                                // if converted amount not found then get amount based on currency conversion avaliable
                                                if (cashline.GetAmount() != 0 && convertedamount == 0)
                                                {
                                                    convertedamount = MConversionRate.Convert(GetCtx(), Decimal.Negate(cashline.GetAmount()), Currency_ID, C_Currencyheader_ID,
                                                                                              cash.GetDateAcct(), cashline.GetC_ConversionType_ID(), cash.GetAD_Client_ID(), cash.GetAD_Org_ID());
                                                    cashline.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(convertedamount)));
                                                }

                                                if (cashline.GetAmount() != 0 && convertedamount == 0)
                                                {
                                                    return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                                }
                                                else if (cashline.GetAmount() == 0)
                                                {
                                                    return("Amount Should be greater than zero");
                                                }
                                                cashline1.SetAmount(convertedamount);
                                                cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                            }
                                            else
                                            {
                                                sql          = "select multiplyrate from c_conversion_rate where isactive='Y' and c_currency_id=" + C_Currencyheader_ID + " and c_currency_to_id=" + Currency_ID;
                                                _Curencyrate = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_Trx()));
                                                if (_Curencyrate == 0)
                                                {
                                                    return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                                }
                                                else
                                                {
                                                    convertedamount = Decimal.Round(Decimal.Multiply(_Curencyrate, Decimal.Negate(cashline.GetAmount())), 2);
                                                }
                                                cashline1.SetConvertedAmt(Util.GetValueOfString(convertedamount));
                                                cashline1.SetAmount(convertedamount);
                                            }
                                        }

                                        cashline1.SetC_Charge_ID(cashline.GetC_Charge_ID());
                                        if (cashline.GetCashType().ToString() == "A")
                                        {
                                            cashline1.SetVSS_PAYMENTTYPE("R");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline1.SetVSS_PAYMENTTYPE("P");
                                        }
                                        cashline1.SetC_CashLine_ID_1(cashline.GetC_CashLine_ID());
                                        if (!cashline1.Save())
                                        {
                                            Rollback();
                                            log.Severe("NotSaved");
                                            return(" NotSaved Cashline1 [ Header Found ]  ");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline.SetC_CashLine_ID_1(cashline1.GetC_CashLine_ID());
                                        }
                                        if (!cashline.Save())
                                        {
                                            Rollback();
                                            log.Severe("Not Saved");
                                            return(" NotSaved Cashline [ Header Found ]  ");
                                        }
                                        //change by Amit 1-june-2016 after discussion with ravikant

                                        //int BeginBal = Util.GetValueOfInt(DB.ExecuteScalar("select completedbalance from c_cashbook where c_cashbook_id=" + cash.GetC_CashBook_ID(), null, Get_Trx()));
                                        //cash.SetBeginningBalance(BeginBal);
                                        //if (!cash.Save(Get_Trx()))
                                        //{
                                        //    Rollback();
                                        //    log.Severe("Not Saved");
                                        //    return " NotSaved Cash [ Header Found ]  ";

                                        //}

                                        //end

                                        break;
                                    }
                                }
                                else
                                {
                                    dscashbook.Dispose();

                                    MCash cash1 = new MCash(GetCtx(), 0, Get_Trx());
                                    cash1.SetAD_Client_ID(cashheader.GetAD_Client_ID());
                                    cash1.SetAD_Org_ID(cashheader.GetAD_Org_ID());
                                    cash1.SetC_DocType_ID(cashheader.GetC_DocType_ID());
                                    cash1.SetName(Util.GetValueOfString(System.DateTime.Today.ToShortDateString()));
                                    cash1.SetC_CashBook_ID(cashline.GetC_CashBook_ID());
                                    cash1.SetDateAcct(DateTime.Now);
                                    cash1.SetStatementDate(DateTime.Now);
                                    //change by Amit 1-june-2016 after discussion with ravikant
                                    int BeginBal = Util.GetValueOfInt(DB.ExecuteScalar("select SUM(completedbalance + runningbalance) from c_cashbook where c_cashbook_id=" + cashline.GetC_CashBook_ID(), null, Get_Trx()));
                                    cash1.SetBeginningBalance(BeginBal);
                                    //end
                                    //Change by Bharat as discussed with Ravikant on 22 March 2017
                                    sql         = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cash1.GetC_CashBook_ID();
                                    Currency_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                    if (cash1.Get_ColumnIndex("C_Currency_ID") > 0)
                                    {
                                        cash1.SetC_Currency_ID(Currency_ID);
                                    }
                                    //End
                                    if (!cash1.Save())
                                    {
                                        Rollback();

                                        VAdvantage.Model.ValueNamePair ppE = VLogger.RetrieveError();
                                        if (ppE != null)
                                        {
                                            return(ppE.GetName() + "<--->" + ppE.GetValue());
                                        }

                                        return("cash1 not saved [header not found->]");
                                    }
                                    // return cash1.GetC_Cash_ID() + "suc";
                                    if (!_cashIds.Contains(cash1.GetC_Cash_ID()))
                                    {
                                        _cashIds.Add(cash1.GetC_Cash_ID());
                                    }
                                    MCashLine cashline1 = new MCashLine(GetCtx(), 0, Get_Trx());
                                    cashline1.SetC_Cash_ID(cash1.GetC_Cash_ID());
                                    cashline1.SetAD_Client_ID(cash1.GetAD_Client_ID());
                                    cashline1.SetAD_Org_ID(cash1.GetAD_Org_ID());
                                    if (cashline.GetCashType().ToString() == "A")
                                    {
                                        cashline1.SetCashType("F");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline1.SetCashType("A");
                                    }
                                    if (cashline1.Get_ColumnIndex("C_ConversionType_ID") > 0)
                                    {
                                        cashline1.SetC_ConversionType_ID(cashline.GetC_ConversionType_ID());
                                    }
                                    cashline1.SetC_CashBook_ID(cashheader.GetC_CashBook_ID());
                                    cashline1.SetC_BPartner_ID(cashline.GetC_BPartner_ID());

                                    //Change by Bharat as discussed with Ravikant on 22 March 2017
                                    //sql = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cash1.GetC_CashBook_ID();
                                    //Currency_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                    if (Currency_ID == C_Currencyheader_ID)
                                    {
                                        cashline1.SetAmount(Decimal.Negate(cashline.GetAmount()));
                                        cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                        cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                    }
                                    else
                                    {
                                        //Change by Bharat as discussed with Ravikant on 22 March 2017
                                        cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                        if (cashline1.Get_ColumnIndex("C_ConversionType_ID") > 0)
                                        {
                                            //_Curencyrate = MConversionRate.GetRate(C_Currencyheader_ID, Currency_ID, cashheader.GetDateAcct(), cashline.GetC_ConversionType_ID(),
                                            //    cashheader.GetAD_Client_ID(), cashheader.GetAD_Org_ID());
                                            convertedamount = Decimal.Negate(Util.GetValueOfDecimal(cashline.GetConvertedAmt()));

                                            // if converted amount not found then get amount based on currency conversion avaliable
                                            if (cashline.GetAmount() != 0 && convertedamount == 0)
                                            {
                                                convertedamount = MConversionRate.Convert(GetCtx(), Decimal.Negate(cashline.GetAmount()), Currency_ID, C_Currencyheader_ID,
                                                                                          cash1.GetDateAcct(), cashline.GetC_ConversionType_ID(), cash1.GetAD_Client_ID(), cash1.GetAD_Org_ID());
                                                cashline.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(convertedamount)));
                                            }

                                            if (cashline.GetAmount() != 0 && convertedamount == 0)
                                            {
                                                return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                            }
                                            else if (cashline.GetAmount() == 0)
                                            {
                                                return("Amount Should be greater than zero");
                                            }
                                            cashline1.SetAmount(convertedamount);
                                            cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                        }
                                        else
                                        {
                                            sql          = "select multiplyrate from c_conversion_rate where isactive='Y' and c_currency_id=" + C_Currencyheader_ID + " and c_currency_to_id=" + Currency_ID;
                                            _Curencyrate = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_Trx()));

                                            if (_Curencyrate == 0)
                                            {
                                                return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                            }
                                            else
                                            {
                                                convertedamount = Decimal.Round(Decimal.Multiply(_Curencyrate, Decimal.Negate(cashline.GetAmount())), 2);
                                            }
                                            cashline1.SetConvertedAmt(Util.GetValueOfString(convertedamount));
                                            cashline1.SetAmount(convertedamount);
                                        }
                                    }

                                    cashline1.SetC_Charge_ID(cashline.GetC_Charge_ID());
                                    if (cashline.GetCashType().ToString() == "A")
                                    {
                                        cashline1.SetVSS_PAYMENTTYPE("R");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline1.SetVSS_PAYMENTTYPE("P");
                                    }
                                    cashline1.SetC_CashLine_ID_1(cashline.GetC_CashLine_ID());
                                    if (!cashline1.Save(Get_Trx()))
                                    {
                                        Rollback();
                                        log.Severe("NotSaved");
                                        return(" NotSaved Cashline1 [ Header not Found ]  ");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline.SetC_CashLine_ID_1(cashline1.GetC_CashLine_ID());
                                    }
                                    if (!cashline.Save(Get_Trx()))
                                    {
                                        Rollback();
                                        log.Severe("NotSaved");
                                        return(" NotSaved Cashline [ Header not Found ]  ");
                                    }
                                    //change by Amit 1-june-2016 after discussion with ravikant

                                    //int BeginBal = Util.GetValueOfInt(DB.ExecuteScalar("select completedbalance from c_cashbook where c_cashbook_id=" + cash1.GetC_CashBook_ID(), null, Get_Trx()));
                                    //cash1.SetBeginningBalance(BeginBal);
                                    //if (!cash1.Save())
                                    //{
                                    //    Rollback();
                                    //    log.Severe("NotSaved");
                                    //    return " NotSaved Cash1 [ Header not Found(bb) ]  ";
                                    //}

                                    //end
                                }
                            }
                            else
                            {
                                //dscashbook.Dispose();
                            }
                        }
                        else
                        {
                            cashtype++;
                        }
                    }
                    // Discussed with Ravikant it is re updating the Header so commented on 23-March-2017 by Bharat
                    //decimal OpenBal = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT completedbalance FROM  C_CashBook WHERE c_cashbook_id=" + cashheader.GetC_CashBook_ID() + "", null, Get_Trx()));
                    //cashheader.SetBeginningBalance(OpenBal);
                    //if (!cashheader.Save())
                    //{
                    //    Rollback();
                    //    log.Severe("Not Saved");
                    //}
                }
                else
                {
                    dscashline.Dispose();
                    cashheader.SetGenerateCashBookTransfer("Y");
                    if (!cashheader.Save())
                    {
                        Rollback();
                        log.Severe("NotSaved");
                    }
                    return(Msg.GetMsg(GetCtx(), "NoCashLineExist"));
                }
                if (_cashIds.Count > 0)
                {
                    for (int k = 0; k < _cashIds.Count; k++)
                    {
                        cash = new MCash(GetCtx(), _cashIds[k], Get_Trx());
                        cash.SetDocStatus(cash.CompleteIt());
                        if (!cash.Save())
                        {
                            Rollback();
                            log.Severe("NotSaved");
                        }
                    }
                }
            }

            cashheader.SetGenerateCashBookTransfer("Y");
            if (!cashheader.Save())
            {
                log.Severe("NotSaved");
            }
            if (cashtype == i)
            {
                return(Msg.GetMsg(GetCtx(), "NoCashLineExist"));
            }
            return("Completed");
        }
        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("");
        }
Example #3
0
        private TabDetails Save(PaymentInputValues inputs)
        {
            try
            {
                StringBuilder errorMsg       = new StringBuilder();
                string        SucessMsg      = "";
                String        newPaymentRule = inputs.cmbPayment;
                inputs._DateAcct = Convert.ToDateTime(inputs._DateAcct);
                DateTime?newDateAcct         = Convert.ToDateTime(inputs._DateAcct);
                int      newC_PaymentTerm_ID = inputs._C_PaymentTerm_ID;
                int      newC_CashLine_ID    = inputs._C_CashLine_ID;
                int      newC_CashBook_ID    = inputs._C_CashBook_ID;
                String   newCCType           = inputs.CCType;
                int      newC_BankAccount_ID = 0;

                //	B (Cash)		(Currency)
                if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_Cash))
                {
                    newC_CashBook_ID = inputs.cmbBCashBook;
                    //newDateAcct = (DateTime)bDateField.GetValue();
                    newDateAcct = Convert.ToDateTime(inputs.bDateField);
                }

                //	K (CreditCard)  Type, Number, Exp, Approval
                else if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_CreditCard))
                {
                    newCCType = inputs.cmbKType;
                }

                //	T (Transfer)	BPartner_Bank
                else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDeposit) ||
                         newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDebit))
                {
                    // KeyNamePair myObj = (KeyNamePair)cmbTAccount.SelectedItem;
                }

                //	P (PaymentTerm)	PaymentTerm
                else if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_OnCredit))
                {
                    newC_PaymentTerm_ID = inputs.cmbPTerm;
                }

                //	S (Check)		(Currency) CheckNo, Routing
                else if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_Check))
                {
                    //	cmbSCurrency.SelectedItem;
                    newC_BankAccount_ID = inputs.cmbSBankAccount;
                }
                else
                {
                    return(details);
                }


                SetPayments(inputs._C_Payment_ID, inputs._C_Currency_ID, inputs._PaymentRule);


                //  find Bank Account if not qualified yet
                if ("KTSD".IndexOf(newPaymentRule) != -1 && newC_BankAccount_ID == 0)
                {
                    String tender = MPayment.TENDERTYPE_CreditCard;
                    if (newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDeposit))
                    {
                        tender = MPayment.TENDERTYPE_DirectDeposit;
                    }
                    else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDebit))
                    {
                        tender = MPayment.TENDERTYPE_DirectDebit;
                    }
                    else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_Check))
                    {
                        tender = MPayment.TENDERTYPE_Check;
                    }
                }

                /***********************
                 *  Changed PaymentRule
                 */
                if (!newPaymentRule.Equals(inputs._PaymentRule))
                {
                    //log.fine("Changed PaymentRule: " + _PaymentRule + " -> " + newPaymentRule);
                    //  We had a CashBook Entry
                    if (inputs._PaymentRule.Equals(X_C_Order.PAYMENTRULE_Cash))
                    {
                        //log.fine("Old Cash - " + _cashLine);
                        if (_cashLine != null)
                        {
                            MCashLine cl = _cashLine.CreateReversal();
                            if (cl.Save())
                            {
                                // log.Config("CashCancelled");
                            }
                            else
                            {
                                errorMsg.Append(Msg.GetMsg(ctx, "CashNotCancelled", true) + Environment.NewLine);
                                //   ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "CashNotCancelled", true).ToString());
                            }
                        }
                        newC_CashLine_ID = 0;      //  reset
                    }
                    //  We had a change in Payment type (e.g. Check to CC)
                    else if ("KTSD".IndexOf(_PaymentRule) != -1 && "KTSD".IndexOf(newPaymentRule) != -1 && _mPaymentOriginal != null)
                    {
                        //log.fine("Old Payment(1) - " + _mPaymentOriginal);
                        _mPaymentOriginal.SetDocAction(DocActionVariables.ACTION_REVERSE_CORRECT);
                        bool ok = _mPaymentOriginal.ProcessIt(DocActionVariables.ACTION_REVERSE_CORRECT);
                        _mPaymentOriginal.Save();
                        if (ok)
                        {
                            // log.Info("Payment Canecelled - " + _mPaymentOriginal);
                        }
                        else
                        {
                            errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "PaymentNotCancelled", true) + Environment.NewLine);
                            // ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "PaymentNotCancelled", true).ToString() + _mPaymentOriginal.GetDocumentNo());
                        }
                        _mPayment.ReSetNew();
                    }
                    //	We had a Payment and something else (e.g. Check to Cash)
                    else if ("KTSD".IndexOf(_PaymentRule) != -1 && "KTSD".IndexOf(newPaymentRule) == -1)
                    {
                        //log.fine("Old Payment(2) - " + _mPaymentOriginal);
                        if (_mPaymentOriginal != null)
                        {
                            _mPaymentOriginal.SetDocAction(DocActionVariables.ACTION_REVERSE_CORRECT);
                            bool ok = _mPaymentOriginal.ProcessIt(DocActionVariables.ACTION_REVERSE_CORRECT);
                            _mPaymentOriginal.Save();
                            if (ok)        //  Cancel Payment
                            {
                                ///log.Fine("PaymentCancelled " + _mPayment.GetDocumentNo());
                                //_mTab.getTableModel().dataSave(true);
                                // DataRow datarow = null;
                                // _mTab.GetTableObj().DataSave(true, datarow);//**********************************2nd parameter
                                _mPayment.ReSetNew();
                                _mPayment.SetAmount(inputs._C_Currency_ID, inputs._Amount);
                            }
                            else
                            {
                                errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "PaymentNotCancelled", true) + _mPayment.GetDocumentNo() + Environment.NewLine);
                                //ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "PaymentNotCancelled", true).ToString() + _mPayment.GetDocumentNo());
                            }
                        }
                    }
                }


                //  Get Order and optionally Invoice
                //int C_Order_ID = ctx.GetContextAsInt(inputs.WindowNo, "C_Order_ID");
                //int C_Invoice_ID = ctx.GetContextAsInt(inputs.WindowNo, "C_Invoice_ID");
                if (inputs.C_Invoice_ID == 0 && inputs._DocStatus.Equals("CO"))
                {
                    inputs.C_Invoice_ID = GetInvoiceID(inputs.C_Order_ID);
                }
                //  Amount sign negative, if ARC (Credit Memo) or API (AP Invoice)
                bool     negateAmt = false;
                MInvoice invoice   = null;
                if (inputs.C_Invoice_ID != 0)
                {
                    invoice   = new MInvoice(ctx, inputs.C_Invoice_ID, null);
                    negateAmt = invoice.IsCreditMemo();
                }
                MOrder order = null;
                if (invoice == null && inputs.C_Order_ID != 0)
                {
                    order = new MOrder(ctx, inputs.C_Order_ID, null);
                }
                Decimal payAmount = inputs._Amount;
                if (negateAmt)
                {
                    payAmount = Decimal.Negate(inputs._Amount);//.negate();
                }
                // Info
                //    log.Config("C_Order_ID=" + C_Order_ID + ", C_Invoice_ID=" + C_Invoice_ID + ", NegateAmt=" + negateAmt);


                /***********************
                 *  CashBook
                 */
                if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_Cash))
                {
                    //log.fine("Cash");
                    String description = inputs.Description;

                    if (inputs.C_Invoice_ID == 0 && order == null)
                    {
                        //log.Config("No Invoice!");
                        //     ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCreated", true).ToString());
                        errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "CashNotCreated", true) + Environment.NewLine);
                    }
                    else
                    {
                        //  Changed Amount
                        if (inputs._C_CashLine_ID > 0)
                        {
                            _cashLine = new MCashLine(ctx, inputs._C_CashLine_ID, null);
                        }


                        if (_cashLine != null &&
                            payAmount.CompareTo(_cashLine.GetAmount()) != 0)
                        {
                            // log.Config("Changed CashBook Amount");
                            _cashLine.SetAmount(payAmount);
                            if (_cashLine.Save())
                            {
                                //     log.Config("CashAmt Changed");
                            }
                        }
                        //	Different Date/CashBook
                        if (_cashLine != null &&
                            (newC_CashBook_ID != inputs._C_CashBook_ID ||
                             !TimeUtil.IsSameDay(_cashLine.GetStatementDate(), newDateAcct)))
                        {
                            //log.Config("Changed CashBook/Date: " + _C_CashBook_ID + "->" + newC_CashBook_ID);
                            MCashLine reverse = _cashLine.CreateReversal();
                            if (!reverse.Save())
                            {
                                errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "CashNotCancelled", true) + Environment.NewLine);
                                //ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCancelled", true).ToString());
                            }
                            _cashLine = null;
                        }

                        //	Create new
                        if (_cashLine == null)
                        {
                            // log.Config("New CashBook");
                            int C_Currency_ID = 0;
                            if (invoice != null)
                            {
                                C_Currency_ID = invoice.GetC_Currency_ID();
                            }
                            if (C_Currency_ID == 0 && order != null)
                            {
                                C_Currency_ID = order.GetC_Currency_ID();
                            }
                            MCash cash = null;
                            if (newC_CashBook_ID != 0)
                            {
                                cash = MCash.Get(ctx, newC_CashBook_ID, newDateAcct, null);
                            }
                            else        //	Default
                            {
                                cash = MCash.Get(ctx, inputs._AD_Org_ID, newDateAcct, C_Currency_ID, null);
                            }
                            if (cash == null || cash.Get_ID() == 0)
                            {
                                errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "CashNotCreated", true) + Environment.NewLine);
                                //ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCreated", true).ToString());
                            }
                            else
                            {
                                MCashLine cl = new MCashLine(cash);
                                if (invoice != null)
                                {
                                    cl.SetInvoice(invoice);
                                }
                                if (order != null)
                                {
                                    cl.SetOrder(order, null);
                                    //_needSave = true;
                                }
                                if (cl.Save())
                                {
                                    //log.Config("CashCreated");
                                }
                                else
                                {
                                    errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "CashNotCreated", true) + Environment.NewLine);
                                    //ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCreated", true).ToString());
                                }
                            }
                        }
                    }   //	have invoice
                }

                /***********************
                 *  Payments
                 */
                if ("KS".IndexOf(newPaymentRule) != -1)
                {
                    //log.fine("Payment - " + newPaymentRule);
                    //  Set Amount
                    _mPayment.SetAmount(inputs._C_Currency_ID, payAmount);
                    if (newPaymentRule.Equals(MOrder.PAYMENTRULE_CreditCard))
                    {
                        _mPayment.SetCreditCard(MPayment.TRXTYPE_Sales, newCCType,
                                                inputs.txtKNumber, "", inputs.txtKExp);
                        _mPayment.SetPaymentProcessor();
                    }
                    else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_Check))
                    {
                        _mPayment.SetBankCheck(newC_BankAccount_ID, inputs._isSOTrx, inputs.txtSRouting,
                                               inputs.txtSNumber, inputs.txtSCheck);
                    }
                    _mPayment.SetC_BPartner_ID(inputs._C_BPartner_ID);
                    _mPayment.SetC_Invoice_ID(inputs.C_Invoice_ID);
                    if (order != null)
                    {
                        _mPayment.SetC_Order_ID(inputs.C_Order_ID);
                        //     _needSave = true;
                    }
                    _mPayment.SetDateTrx(DateTime.SpecifyKind(Convert.ToDateTime(inputs._DateAcct), DateTimeKind.Utc));
                    _mPayment.SetDateAcct(DateTime.SpecifyKind(Convert.ToDateTime(inputs._DateAcct), DateTimeKind.Utc));
                    _mPayment.Save();

                    //  Save/Post
                    if (MPayment.DOCSTATUS_Drafted.Equals(_mPayment.GetDocStatus()))
                    {
                        bool ok = _mPayment.ProcessIt(DocActionVariables.ACTION_COMPLETE);
                        _mPayment.Save();
                        if (ok)
                        {
                            SucessMsg = _mPayment.GetDocumentNo().ToString() + Msg.GetMsg(ctx, "PaymentCreated");
                            //ShowMessage.Info(_mPayment.GetDocumentNo().ToString(), true, "PaymentCreated", "");
                        }
                        else
                        {
                            errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "PaymentNotCreated", true) + Environment.NewLine);
                            //ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "PaymentNotCreated", true).ToString());
                        }
                    }
                    else
                    {
                        // log.Fine("NotDraft " + _mPayment);
                    }
                }
                if (details == null)
                {
                    details = new TabDetails();
                }
                details.newPaymentRule      = newPaymentRule;
                details.newDateAcct         = newDateAcct;
                details._C_CashLine_ID      = inputs._C_CashLine_ID;
                details._C_Payment_ID       = inputs._C_Payment_ID;
                details.newC_PaymentTerm_ID = inputs.cmbPTerm;
                details.ErrorMsg            = errorMsg.ToString();
                details.SucessMsg           = SucessMsg;
            }
            catch
            {
            }
            return(details);
        }
Example #4
0
        protected override string DoIt()
        {
            MCash cashheader = new MCash(GetCtx(), GetRecord_ID(), Get_Trx());

            sql = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cashheader.GetC_CashBook_ID();
            int C_Currencyheader_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));

            sql = "select * from C_Cashline WHERE C_Cash_ID=" + GetRecord_ID();
            DataSet dscashline = DB.ExecuteDataset(sql, null, Get_Trx());

            if (dscashline != null)
            {
                if (dscashline.Tables[0].Rows.Count > 0)
                {
                    for (i = 0; i < dscashline.Tables[0].Rows.Count; i++)
                    {
                        cashline = new MCashLine(GetCtx(), Util.GetValueOfInt(dscashline.Tables[0].Rows[i]["C_CashLine_ID"]), Get_Trx());
                        if (cashline.GetCashType().ToString() == "A" || cashline.GetCashType().ToString() == "F")
                        {
                            sql = "Select * from C_Cash where C_CashBook_Id=" + cashline.GetC_CashBook_ID() + " and docstatus='DR' and  DateAcct=" + GlobalVariable.TO_DATE(DateTime.Now, true);
                            DataSet dscashbook = DB.ExecuteDataset(sql, null, Get_Trx());
                            if (dscashbook != null)
                            {
                                if (dscashbook.Tables[0].Rows.Count > 0)
                                {
                                    int j;
                                    for (j = 0; j < dscashbook.Tables[0].Rows.Count; j++)
                                    {
                                        cash = new MCash(GetCtx(), Util.GetValueOfInt(dscashbook.Tables[0].Rows[j]["C_Cash_ID"]), Get_Trx());
                                        if (!_cashIds.Contains(cash.GetC_Cash_ID()))
                                        {
                                            _cashIds.Add(cash.GetC_Cash_ID());
                                        }
                                        //ViennaAdvantage.Model.MCashLine cashline1 = new ViennaAdvantage.Model.MCashLine(GetCtx(), 0, Get_Trx());
                                        MCashLine cashline1 = new MCashLine(GetCtx(), 0, Get_Trx());
                                        cashline1.SetC_Cash_ID(cash.GetC_Cash_ID());
                                        cashline1.SetAD_Client_ID(cash.GetAD_Client_ID());
                                        cashline1.SetAD_Org_ID(cash.GetAD_Org_ID());
                                        if (cashline.GetCashType().ToString() == "A")
                                        {
                                            cashline1.SetCashType("F");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline1.SetCashType("A");
                                        }
                                        cashline1.SetC_CashBook_ID(cashheader.GetC_CashBook_ID());
                                        cashline1.SetC_BPartner_ID(cashline.GetC_BPartner_ID());
                                        sql         = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cash.GetC_CashBook_ID();
                                        Currency_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                        if (Currency_ID == C_Currencyheader_ID)
                                        {
                                            cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                            cashline1.SetAmount(Decimal.Negate(cashline.GetAmount()));
                                            cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                        }
                                        else
                                        {
                                            cashline1.SetC_Currency_ID(Currency_ID);
                                            sql          = "select multiplyrate from c_conversion_rate where isactive='Y' and c_currency_id=" + C_Currencyheader_ID + " and c_currency_to_id=" + Currency_ID;
                                            _Curencyrate = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_Trx()));
                                            if (_Curencyrate == 0)
                                            {
                                                return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                            }
                                            else
                                            {
                                                convertedamount = Decimal.Round(Decimal.Multiply(_Curencyrate, Decimal.Negate(cashline.GetAmount())), 2);
                                            }
                                            cashline1.SetConvertedAmt(Util.GetValueOfString(convertedamount));
                                            cashline1.SetAmount(convertedamount);
                                        }

                                        cashline1.SetC_Charge_ID(cashline.GetC_Charge_ID());
                                        if (cashline.GetCashType().ToString() == "A")
                                        {
                                            cashline1.SetVSS_PAYMENTTYPE("R");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline1.SetVSS_PAYMENTTYPE("P");
                                        }
                                        cashline1.SetC_CashLine_ID_1(cashline.GetC_CashLine_ID());
                                        if (!cashline1.Save())
                                        {
                                            Rollback();
                                            log.Severe("NotSaved");
                                            return(" NotSaved Cashline1 [ Header Found ]  ");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline.SetC_CashLine_ID_1(cashline1.GetC_CashLine_ID());
                                        }
                                        if (!cashline.Save())
                                        {
                                            Rollback();
                                            log.Severe("Not Saved");
                                            return(" NotSaved Cashline [ Header Found ]  ");
                                        }

                                        int BeginBal = Util.GetValueOfInt(DB.ExecuteScalar("select completedbalance from c_cashbook where c_cashbook_id=" + cash.GetC_CashBook_ID(), null, Get_Trx()));
                                        cash.SetBeginningBalance(BeginBal);
                                        if (!cash.Save(Get_Trx()))
                                        {
                                            Rollback();
                                            log.Severe("Not Saved");
                                            return(" NotSaved Cash [ Header Found ]  ");
                                        }

                                        break;
                                    }
                                }
                                else
                                {
                                    dscashbook.Dispose();

                                    MCash cash1 = new MCash(GetCtx(), 0, Get_Trx());
                                    cash1.SetAD_Client_ID(cashheader.GetAD_Client_ID());
                                    cash1.SetAD_Org_ID(cashheader.GetAD_Org_ID());
                                    cash1.SetC_DocType_ID(cashheader.GetC_DocType_ID());
                                    cash1.SetName(Util.GetValueOfString(System.DateTime.Today.ToShortDateString()));
                                    cash1.SetC_CashBook_ID(cashline.GetC_CashBook_ID());
                                    cash1.SetDateAcct(DateTime.Now);
                                    cash1.SetStatementDate(DateTime.Now);
                                    if (!cash1.Save())
                                    {
                                        Rollback();

                                        VAdvantage.Model.ValueNamePair ppE = VLogger.RetrieveError();
                                        if (ppE != null)
                                        {
                                            return(ppE.GetName() + "<--->" + ppE.GetValue());
                                        }

                                        return("cash1 not saved [header not found->]");
                                    }
                                    // return cash1.GetC_Cash_ID() + "suc";
                                    if (!_cashIds.Contains(cash1.GetC_Cash_ID()))
                                    {
                                        _cashIds.Add(cash1.GetC_Cash_ID());
                                    }
                                    MCashLine cashline1 = new MCashLine(GetCtx(), 0, Get_Trx());
                                    cashline1.SetC_Cash_ID(cash1.GetC_Cash_ID());
                                    cashline1.SetAD_Client_ID(cash1.GetAD_Client_ID());
                                    cashline1.SetAD_Org_ID(cash1.GetAD_Org_ID());
                                    if (cashline.GetCashType().ToString() == "A")
                                    {
                                        cashline1.SetCashType("F");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline1.SetCashType("A");
                                    }

                                    cashline1.SetC_CashBook_ID(cashheader.GetC_CashBook_ID());
                                    cashline1.SetC_BPartner_ID(cashline.GetC_BPartner_ID());
                                    sql         = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cash1.GetC_CashBook_ID();
                                    Currency_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                    if (Currency_ID == C_Currencyheader_ID)
                                    {
                                        cashline1.SetAmount(Decimal.Negate(cashline.GetAmount()));
                                        cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                        cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                    }
                                    else
                                    {
                                        cashline1.SetC_Currency_ID(Currency_ID);
                                        sql          = "select multiplyrate from c_conversion_rate where isactive='Y' and c_currency_id=" + C_Currencyheader_ID + " and c_currency_to_id=" + Currency_ID;
                                        _Curencyrate = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_Trx()));
                                        if (_Curencyrate == 0)
                                        {
                                            return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                        }
                                        else
                                        {
                                            convertedamount = Decimal.Round(Decimal.Multiply(_Curencyrate, Decimal.Negate(cashline.GetAmount())), 2);
                                        }
                                        cashline1.SetConvertedAmt(Util.GetValueOfString(convertedamount));
                                        cashline1.SetAmount(convertedamount);
                                    }

                                    cashline1.SetC_Charge_ID(cashline.GetC_Charge_ID());
                                    if (cashline.GetCashType().ToString() == "A")
                                    {
                                        cashline1.SetVSS_PAYMENTTYPE("R");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline1.SetVSS_PAYMENTTYPE("P");
                                    }
                                    cashline1.SetC_CashLine_ID_1(cashline.GetC_CashLine_ID());
                                    if (!cashline1.Save(Get_Trx()))
                                    {
                                        Rollback();
                                        log.Severe("NotSaved");
                                        return(" NotSaved Cashline1 [ Header not Found ]  ");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline.SetC_CashLine_ID_1(cashline1.GetC_CashLine_ID());
                                    }
                                    if (!cashline.Save(Get_Trx()))
                                    {
                                        Rollback();
                                        log.Severe("NotSaved");
                                        return(" NotSaved Cashline [ Header not Found ]  ");
                                    }
                                    int BeginBal = Util.GetValueOfInt(DB.ExecuteScalar("select completedbalance from c_cashbook where c_cashbook_id=" + cash1.GetC_CashBook_ID(), null, Get_Trx()));
                                    cash1.SetBeginningBalance(BeginBal);
                                    if (!cash1.Save())
                                    {
                                        Rollback();
                                        log.Severe("NotSaved");
                                        return(" NotSaved Cash1 [ Header not Found(bb) ]  ");
                                    }
                                }
                            }
                            else
                            {
                                //dscashbook.Dispose();
                            }
                        }
                        else
                        {
                            cashtype++;
                        }
                    }
                    decimal OpenBal = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT completedbalance FROM  C_CashBook WHERE c_cashbook_id=" + cashheader.GetC_CashBook_ID() + "", null, Get_Trx()));
                    cashheader.SetBeginningBalance(OpenBal);
                    if (!cashheader.Save())
                    {
                        Rollback();
                        log.Severe("Not Saved");
                    }
                }
                else
                {
                    dscashline.Dispose();
                    cashheader.SetGenerateCashBookTransfer("Y");
                    if (!cashheader.Save())
                    {
                        Rollback();
                        log.Severe("NotSaved");
                    }
                    return(Msg.GetMsg(GetCtx(), "NoCashLineExist"));
                }
                if (_cashIds.Count > 0)
                {
                    for (int k = 0; k < _cashIds.Count; k++)
                    {
                        cash = new MCash(GetCtx(), _cashIds[k], Get_Trx());
                        cash.SetDocStatus(cash.CompleteIt());
                        if (!cash.Save())
                        {
                            Rollback();
                            log.Severe("NotSaved");
                        }
                    }
                }
            }

            cashheader.SetGenerateCashBookTransfer("Y");
            if (!cashheader.Save())
            {
                log.Severe("NotSaved");
            }
            if (cashtype == i)
            {
                return(Msg.GetMsg(GetCtx(), "NoCashLineExist"));
            }
            return("Completed");
        }