Ejemplo n.º 1
0
        /**
         *  Create Line Reversal
         *	@return new reversed CashLine
         */
        public MCashLine CreateReversal()
        {
            MCash parent = GetParent();

            if (parent.IsProcessed())
            {   //	saved
                parent = MCash.Get(GetCtx(), parent.GetAD_Org_ID(),
                                   parent.GetStatementDate(), parent.GetC_Currency_ID(), Get_TrxName());
            }
            //
            MCashLine reversal = new MCashLine(parent);

            reversal.SetClientOrg(this);
            reversal.SetC_BankAccount_ID(GetC_BankAccount_ID());
            reversal.SetC_Charge_ID(GetC_Charge_ID());
            reversal.SetC_Currency_ID(GetC_Currency_ID());
            reversal.SetC_Invoice_ID(GetC_Invoice_ID());
            reversal.SetCashType(GetCashType());
            reversal.SetDescription(GetDescription());
            reversal.SetIsGenerated(true);
            //
            reversal.SetAmount(Decimal.Negate(GetAmount()));
            //if (GetDiscountAmt() == null)
            ////    SetDiscountAmt(Env.ZERO);
            //else
            reversal.SetDiscountAmt(Decimal.Negate(GetDiscountAmt()));
            //if (GetWriteOffAmt() == null)
            //    SetWriteOffAmt(Env.ZERO);
            //else
            reversal.SetWriteOffAmt(Decimal.Negate(GetWriteOffAmt()));
            reversal.AddDescription("(" + GetLine() + ")");
            return(reversal);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Complete Document
        /// </summary>
        /// <returns>new status (Complete, In Progress, Invalid, Waiting ..)</returns>
        public String CompleteIt()
        {
            //added by shubham (JID_1472) To check payment is complete or close
            int docStatus = Util.GetValueOfInt(DB.ExecuteScalar("SELECT count(c_payment_id) FROM c_payment WHERE c_payment_id in ((SELECT c_payment_id from c_bankstatementline WHERE c_bankstatement_id =" + GetC_BankStatement_ID() + " AND c_payment_id > 0)) AND docstatus NOT IN ('CO' , 'CL')", null, Get_Trx()));

            if (docStatus != 0)
            {
                m_processMsg = Msg.GetMsg(GetCtx(), "paymentnotcompleted");
                return(DocActionVariables.STATUS_INVALID);
            }
            //shubham
            //	Re-Check
            if (!m_justPrepared)
            {
                String status = PrepareIt();
                if (!DocActionVariables.STATUS_INPROGRESS.Equals(status))
                {
                    return(status);
                }
            }
            //	Implicit Approval
            if (!IsApproved())
            {
                ApproveIt();
            }
            log.Info("completeIt - " + ToString());

            int _CountVA034 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA034_'  AND IsActive = 'Y'"));

            //	Set Payment reconciled
            MBankStatementLine[] lines = GetLines(false);

            //Changes by SUkhwinder on 20 April, if all lines are not matched then dont allow complete.
            foreach (MBankStatementLine line in lines)
            {
                // if Transaction amount exist but no payment reference or Charge amount exist with no Charge then give message for Unmatched lines
                if ((line.GetTrxAmt() != Env.ZERO && line.GetC_Payment_ID() == 0) || (line.GetChargeAmt() != Env.ZERO && line.GetC_Charge_ID() == 0))
                {
                    m_processMsg = Msg.GetMsg(Env.GetCtx(), "LinesNotMatchedYet");
                    return(DocActionVariables.STATUS_INVALID);
                }
            }
            //Changes by SUkhwinder on 20 April, if all lines are not matched then dont allow complete.
            Decimal transactionAmt = 0; //Arpit to update only transaction amount in Bank Account UnMatched Balance asked by Ashish Gandhi

            for (int i = 0; i < lines.Length; i++)
            {
                MBankStatementLine line = lines[i];
                transactionAmt += line.GetTrxAmt();
                if (line.GetC_Payment_ID() != 0)
                {
                    MPayment payment = new MPayment(GetCtx(), line.GetC_Payment_ID(), Get_TrxName());
                    payment.SetIsReconciled(true);
                    if (_CountVA034 > 0)
                    {
                        payment.SetVA034_DepositSlipNo(line.GetVA012_VoucherNo());
                    }
                    payment.Save(Get_TrxName());
                }

                //Pratap 1-2-16
                /////	Set Cash Line reconciled
                int _CountVA012 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA012_'  AND IsActive = 'Y'"));
                if (_CountVA012 > 0)
                {
                    if (line.GetC_CashLine_ID() != 0)
                    {
                        MCashLine cashLine = new MCashLine(GetCtx(), line.GetC_CashLine_ID(), Get_TrxName());
                        cashLine.SetVA012_IsReconciled(true);
                        cashLine.Save(Get_TrxName());
                    }
                }
                ////
            }
            //	Update Bank Account
            MBankAccount ba = MBankAccount.Get(GetCtx(), GetC_BankAccount_ID());

            ba.SetCurrentBalance(GetEndingBalance());
            ba.SetUnMatchedBalance(Decimal.Subtract(ba.GetUnMatchedBalance(), transactionAmt));//Arpit
            ba.Save(Get_TrxName());



            //VA009----------------------------------Anuj----------------------
            //int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));
            if (Env.IsModuleInstalled("VA009_"))
            {
                MBankStatementLine[] STlines = GetLines(false);
                for (int i = 0; i < STlines.Length; i++)
                {
                    MBankStatementLine line = STlines[i];
                    if (line.GetC_Payment_ID() != 0)
                    {
                        MPayment payment = new MPayment(GetCtx(), line.GetC_Payment_ID(), Get_TrxName());
                        payment.SetVA009_ExecutionStatus("R");
                        if (_CountVA034 > 0)
                        {
                            payment.SetVA034_DepositSlipNo(line.GetVA012_VoucherNo());
                        }
                        payment.Save(Get_TrxName());

                        //MInvoicePaySchedule inp = new MInvoicePaySchedule(GetCtx(), payment.GetC_InvoicePaySchedule_ID(), Get_TrxName());
                        //inp.SetVA009_ExecutionStatus("R");
                        //inp.Save(Get_TrxName());

                        // update execution status as received on Invoice Schedule -  for those payment which are completed or closed
                        if (payment.GetDocStatus() == DOCSTATUS_Closed || payment.GetDocStatus() == DOCSTATUS_Completed)
                        {
                            int no = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE C_InvoicePaySchedule SET VA009_ExecutionStatus = 'R' WHERE C_Payment_ID = " + line.GetC_Payment_ID(), null, Get_Trx()));
                        }
                    }
                }
            }

            //END----------------------------------Anuj----------------------

            //	User Validation
            String valid = ModelValidationEngine.Get().FireDocValidate(this, ModalValidatorVariables.DOCTIMING_AFTER_COMPLETE);

            if (valid != null)
            {
                m_processMsg = valid;
                return(DocActionVariables.STATUS_INVALID);
            }
            SetProcessed(true);
            SetDocAction(DOCACTION_Close);
            return(DocActionVariables.STATUS_COMPLETED);
        }
Ejemplo n.º 3
0
        /**
         *  Complete Document
         *  @return new status (Complete, In Progress, Invalid, Waiting ..)
         */
        public String CompleteIt()
        {
            //	Re-Check
            if (!_justPrepared)
            {
                String status = PrepareIt();
                if (!DocActionVariables.STATUS_INPROGRESS.Equals(status))
                {
                    return(status);
                }
            }
            //	Implicit Approval
            if (!IsApproved())
            {
                ApproveIt();
            }
            //
            log.Info(ToString());

            //	Allocation Header
            MAllocationHdr alloc = new MAllocationHdr(GetCtx(), false,
                                                      GetDateAcct(), GetC_Currency_ID(),
                                                      Msg.Translate(GetCtx(), "C_Cash_ID") + ": " + GetName(), Get_TrxName());

            alloc.SetAD_Org_ID(GetAD_Org_ID());
            if (!alloc.Save())
            {
                _processMsg = "Could not create Allocation Hdr";
                return(DocActionVariables.STATUS_INVALID);
            }
            //
            MCashLine[] lines = GetLines(false);
            for (int i = 0; i < lines.Length; i++)
            {
                MCashLine line = lines[i];

                if (Util.GetValueOfInt(line.GetC_InvoicePaySchedule_ID()) != 0)
                {
                    MInvoicePaySchedule paySch = new MInvoicePaySchedule(GetCtx(), Util.GetValueOfInt(line.GetC_InvoicePaySchedule_ID()), Get_TrxName());
                    paySch.SetC_CashLine_ID(line.GetC_CashLine_ID());
                    paySch.Save();
                }
                else
                {
                    int[] InvoicePaySchedule_ID = MInvoicePaySchedule.GetAllIDs("C_InvoicePaySchedule", "C_Invoice_ID = " + line.GetC_Invoice_ID() + @" AND C_InvoicePaySchedule_ID NOT IN 
                    (SELECT NVL(C_InvoicePaySchedule_ID,0) FROM C_InvoicePaySchedule WHERE C_Payment_ID IN (SELECT NVL(C_Payment_ID,0) FROM C_InvoicePaySchedule) UNION 
                    SELECT NVL(C_InvoicePaySchedule_ID,0) FROM C_InvoicePaySchedule  WHERE C_Cashline_ID IN (SELECT NVL(C_Cashline_ID,0) FROM C_InvoicePaySchedule))", Get_TrxName());

                    foreach (int invocePay in InvoicePaySchedule_ID)
                    {
                        MInvoicePaySchedule paySch = new MInvoicePaySchedule(GetCtx(), invocePay, Get_TrxName());
                        paySch.SetC_CashLine_ID(line.GetC_CashLine_ID());
                        paySch.Save();
                    }
                }

                if (MCashLine.CASHTYPE_Invoice.Equals(line.GetCashType()))
                {
                    bool           differentCurrency = GetC_Currency_ID() != line.GetC_Currency_ID();
                    MAllocationHdr hdr = alloc;
                    if (differentCurrency)
                    {
                        hdr = new MAllocationHdr(GetCtx(), false,
                                                 GetDateAcct(), line.GetC_Currency_ID(),
                                                 Msg.Translate(GetCtx(), "C_Cash_ID") + ": " + GetName(), Get_TrxName());
                        hdr.SetAD_Org_ID(GetAD_Org_ID());
                        if (!hdr.Save())
                        {
                            _processMsg = "Could not create Allocation Hdr";
                            return(DocActionVariables.STATUS_INVALID);
                        }
                    }
                    //	Allocation Line
                    MAllocationLine aLine = new MAllocationLine(hdr, line.GetAmount(),
                                                                line.GetDiscountAmt(), line.GetWriteOffAmt(), line.GetOverUnderAmt());
                    aLine.SetC_Invoice_ID(line.GetC_Invoice_ID());
                    aLine.SetC_CashLine_ID(line.GetC_CashLine_ID());
                    if (!aLine.Save())
                    {
                        _processMsg = "Could not create Allocation Line";
                        return(DocActionVariables.STATUS_INVALID);
                    }
                    if (differentCurrency)
                    {
                        //	Should start WF
                        hdr.ProcessIt(DocActionVariables.ACTION_COMPLETE);
                        hdr.Save();
                    }
                }
                else if (MCashLine.CASHTYPE_BankAccountTransfer.Equals(line.GetCashType()))
                {
                    //	Payment just as intermediate info
                    MPayment pay = new MPayment(GetCtx(), 0, Get_TrxName());
                    pay.SetAD_Org_ID(GetAD_Org_ID());
                    String documentNo = GetName();
                    pay.SetDocumentNo(documentNo);
                    pay.SetR_PnRef(documentNo);
                    pay.Set_Value("TrxType", "X");              //	Transfer
                    pay.Set_Value("TenderType", "X");
                    //
                    pay.SetC_BankAccount_ID(line.GetC_BankAccount_ID());
                    pay.SetC_DocType_ID(true);  //	Receipt
                    pay.SetDateTrx(GetStatementDate());
                    pay.SetDateAcct(GetDateAcct());
                    pay.SetAmount(line.GetC_Currency_ID(), Decimal.Negate(line.GetAmount()));   //	Transfer
                    pay.SetDescription(line.GetDescription());
                    pay.SetDocStatus(MPayment.DOCSTATUS_Closed);
                    pay.SetDocAction(MPayment.DOCACTION_None);
                    pay.SetPosted(true);
                    pay.SetIsAllocated(true);   //	Has No Allocation!
                    pay.SetProcessed(true);
                    if (!pay.Save())
                    {
                        _processMsg = "Could not create Payment";
                        return(DocActionVariables.STATUS_INVALID);
                    }
                }
                // Added to Update Open Balance of Business Partner
                else if (MCashLine.CASHTYPE_BusinessPartner.Equals(line.GetCashType()))
                {
                    if (line.GetC_BPartner_ID() != 0)
                    {
                        Decimal?  UpdatedBal = 0;
                        MBPartner bp         = new MBPartner(GetCtx(), line.GetC_BPartner_ID(), Get_TrxName());

                        Decimal?cashAmt = VAdvantage.Model.MConversionRate.ConvertBase(GetCtx(), Decimal.Add(Decimal.Add(line.GetAmount(), line.GetDiscountAmt()), line.GetWriteOffAmt()),
                                                                                       GetC_Currency_ID(), GetDateAcct(), 0, GetAD_Client_ID(), GetAD_Org_ID());
                        if (cashAmt > 0)
                        {
                            UpdatedBal = Decimal.Subtract((Decimal)bp.GetTotalOpenBalance(), (Decimal)cashAmt);

                            Decimal?newCreditAmt = bp.GetSO_CreditUsed();
                            if (newCreditAmt == null)
                            {
                                newCreditAmt = Decimal.Negate((Decimal)cashAmt);
                            }
                            else
                            {
                                newCreditAmt = Decimal.Subtract((Decimal)newCreditAmt, (Decimal)cashAmt);
                            }
                            //
                            log.Fine("TotalOpenBalance=" + bp.GetTotalOpenBalance(false) + "(" + cashAmt
                                     + ", Credit=" + bp.GetSO_CreditUsed() + "->" + newCreditAmt
                                     + ", Balance=" + bp.GetTotalOpenBalance(false) + " -> " + UpdatedBal);
                            bp.SetSO_CreditUsed((Decimal)newCreditAmt);
                        }
                        else
                        {
                            UpdatedBal = Decimal.Subtract((Decimal)bp.GetTotalOpenBalance(), (Decimal)cashAmt);
                            log.Fine("Payment Amount =" + line.GetAmount() + "(" + cashAmt
                                     + ") Balance=" + bp.GetTotalOpenBalance(false) + " -> " + UpdatedBal);
                        }
                        bp.SetTotalOpenBalance(Convert.ToDecimal(UpdatedBal));
                        bp.SetSOCreditStatus();
                        if (!bp.Save(Get_TrxName()))
                        {
                            _processMsg = "Could not update Business Partner";
                            return(DocActionVariables.STATUS_INVALID);
                        }
                    }
                }
            }
            //	Should start WF
            alloc.ProcessIt(DocActionVariables.ACTION_COMPLETE);
            alloc.Save();

            //	User Validation
            String valid = ModelValidationEngine.Get().FireDocValidate(this, ModalValidatorVariables.DOCTIMING_AFTER_COMPLETE);

            if (valid != null)
            {
                _processMsg = valid;
                return(DocActionVariables.STATUS_INVALID);
            }
            //
            SetProcessed(true);
            SetDocAction(DOCACTION_Close);
            if (!UpdateCompletedBalance())
            {
                _processMsg = "Could not update Header";
                return(VAdvantage.Process.DocActionVariables.STATUS_INVALID);
            }

            return(VAdvantage.Process.DocActionVariables.STATUS_COMPLETED);
        }
Ejemplo n.º 4
0
        /**
         *	Prepare Document
         *  @return new status (In Progress or Invalid)
         */
        public String PrepareIt()
        {
            log.Info(ToString());
            _processMsg = ModelValidationEngine.Get().FireDocValidate(this, ModalValidatorVariables.DOCTIMING_BEFORE_PREPARE);
            if (_processMsg != null)
            {
                return(DocActionVariables.STATUS_INVALID);
            }

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

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


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

            for (int i = 0; i < lines.Length; i++)
            {
                MCashLine line = lines[i];
                if (!line.IsActive())
                {
                    continue;
                }
                if (C_Currency_ID == line.GetC_Currency_ID())
                {
                    difference = Decimal.Add(difference, line.GetAmount());
                }
                else
                {
                    Decimal amt = MConversionRate.Convert(GetCtx(), line.GetAmount(),
                                                          line.GetC_Currency_ID(), C_Currency_ID, GetDateAcct(), 0,
                                                          GetAD_Client_ID(), GetAD_Org_ID());
                    if (amt == null)
                    {
                        _processMsg = "No Conversion Rate found - @C_CashLine_ID@= " + line.GetLine();
                        return(DocActionVariables.STATUS_INVALID);
                    }
                    difference = Decimal.Add(difference, amt);
                }
            }
            SetStatementDifference(difference);
            //	setEndingBalance(getBeginningBalance().add(getStatementDifference()));
            //
            _justPrepared = true;
            if (!DOCACTION_Complete.Equals(GetDocAction()))
            {
                SetDocAction(DOCACTION_Complete);
            }
            return(DocActionVariables.STATUS_INPROGRESS);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Process Allocation (does not update line).
        /// - Update and Link Invoice/Payment/Cash
        /// </summary>
        /// <param name="reverse">reverse if true allocation is reversed</param>
        /// <returns>C_BPartner_ID</returns>
        public int ProcessIt(bool reverse)
        {
            log.Fine("Reverse=" + reverse + " - " + ToString());
            int C_Invoice_ID = GetC_Invoice_ID();
            MInvoicePaySchedule invoiceSchedule = null;
            MPayment            payment         = null;
            MCashLine           cashLine        = null;
            MInvoice            invoice         = GetInvoice();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return(GetC_BPartner_ID());
        }