Example #1
0
        public void CreateCashLine(MInvoice invoice, int C_InvoicePaySchedule_ID, decimal amt)
        {
            SetC_Invoice_ID(invoice.GetC_Invoice_ID());
            SetC_InvoicePaySchedule_ID(C_InvoicePaySchedule_ID);
            SetCashType(CASHTYPE_Invoice);
            SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            SetC_Currency_ID(invoice.GetC_Currency_ID());
            //	Amount
            MDocType dt = MDocType.Get(GetCtx(), invoice.GetC_DocType_ID());

            if (MDocBaseType.DOCBASETYPE_APINVOICE.Equals(dt.GetDocBaseType()) ||
                MDocBaseType.DOCBASETYPE_ARCREDITMEMO.Equals(dt.GetDocBaseType()))
            {
                amt = Decimal.Negate(amt);
                SetVSS_PAYMENTTYPE("P");
            }
            else
            {
                SetVSS_PAYMENTTYPE("R");
            }
            SetAmount(amt);
            //
            SetDiscountAmt(Env.ZERO);
            SetWriteOffAmt(Env.ZERO);
            SetIsGenerated(true);
            _invoice = invoice;
        }
Example #2
0
        /// <summary>
        /// Create Cash Journal Line
        /// </summary>
        /// <param name="invoice">Invoice</param>
        /// <param name="C_InvoicePaySchedule_ID">Invoice Payemt Schedule</param>
        /// <param name="amt">Amount</param>
        public void CreateCashLine(MInvoice invoice, int C_InvoicePaySchedule_ID, decimal amt)
        {
            SetC_Invoice_ID(invoice.GetC_Invoice_ID());
            SetC_InvoicePaySchedule_ID(C_InvoicePaySchedule_ID);
            SetCashType(CASHTYPE_Invoice);
            SetC_BPartner_ID(invoice.GetC_BPartner_ID());

            // JID_0687: System is not updating the Location on cash journal line in cases of POS order and payment method cash
            SetC_BPartner_Location_ID(invoice.GetC_BPartner_Location_ID());

            SetC_Currency_ID(invoice.GetC_Currency_ID());
            //	Amount
            MDocType dt = MDocType.Get(GetCtx(), invoice.GetC_DocType_ID());

            if (MDocBaseType.DOCBASETYPE_APINVOICE.Equals(dt.GetDocBaseType()) ||
                MDocBaseType.DOCBASETYPE_ARCREDITMEMO.Equals(dt.GetDocBaseType()))
            {
                amt = Decimal.Negate(amt);
                SetVSS_PAYMENTTYPE("P");
            }
            else
            {
                SetVSS_PAYMENTTYPE("R");
            }
            SetAmount(amt);
            //
            SetDiscountAmt(Env.ZERO);
            SetWriteOffAmt(Env.ZERO);
            SetIsGenerated(true);
            _invoice = invoice;
        }
Example #3
0
        }       //	toString

        /// <summary>
        /// Execute Run.
        /// </summary>
        /// <returns>clear text info</returns>
        public String ExecuteRun()
        {
            DateTime?dateDoc = GetDateNextRun();

            if (!CalculateRuns())
            {
                throw new Exception("No Runs Left");
            }
            //	log
            MRecurringRun run = new MRecurringRun(GetCtx(), this);
            String        msg = "@Created@ ";


            //	Copy
            if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Order))
            {
                MOrder from  = new MOrder(GetCtx(), GetC_Order_ID(), Get_TrxName());
                MOrder order = MOrder.CopyFrom(from, dateDoc,
                                               from.GetC_DocType_ID(), false, false, Get_TrxName());
                run.SetC_Order_ID(order.GetC_Order_ID());
                msg += order.GetDocumentNo();
            }
            else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Invoice))
            {
                MInvoice from    = new MInvoice(GetCtx(), GetC_Invoice_ID(), Get_TrxName());
                MInvoice invoice = MInvoice.CopyFrom(from, dateDoc,
                                                     from.GetC_DocType_ID(), false, Get_TrxName(), false);
                run.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                msg += invoice.GetDocumentNo();
            }
            else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Project))
            {
                MProject project = MProject.CopyFrom(GetCtx(), GetC_Project_ID(), dateDoc, Get_TrxName());
                run.SetC_Project_ID(project.GetC_Project_ID());
                msg += project.GetValue();
            }
            else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_GLJournal))
            {
                MJournalBatch journal = MJournalBatch.CopyFrom(GetCtx(), GetGL_JournalBatch_ID(), dateDoc, Get_TrxName());
                run.SetGL_JournalBatch_ID(journal.GetGL_JournalBatch_ID());
                msg += journal.GetDocumentNo();
            }
            else
            {
                return("Invalid @RecurringType@ = " + GetRecurringType());
            }
            run.Save(Get_TrxName());

            //
            SetDateLastRun(run.GetUpdated());
            SetRunsRemaining(GetRunsRemaining() - 1);
            SetDateNextRun();
            Save(Get_TrxName());
            return(msg);
        }       //	execureRun
Example #4
0
        /// <summary>
        /// Set Invoice - no discount
        /// </summary>
        /// <param name="invoice">Invoice</param>
        public void SetInvoice(MInvoice invoice)
        {
            Decimal amt = 0;

            SetC_Invoice_ID(invoice.GetC_Invoice_ID());
            SetCashType(CASHTYPE_Invoice);
            SetC_BPartner_ID(invoice.GetC_BPartner_ID());

            // JID_0687: System is not updating the Location on cash journal line in cases of POS order and payment method cash
            SetC_BPartner_Location_ID(invoice.GetC_BPartner_Location_ID());

            SetC_Currency_ID(invoice.GetC_Currency_ID());
            //	Amount
            MDocType dt = MDocType.Get(GetCtx(), invoice.GetC_DocType_ID());

            if (invoice.GetRef_C_Invoice_ID() > 0)
            {
                //amt = Decimal.Negate(Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT SUM(Al.Amount) FROM c_allocationline al INNER JOIN c_allocationhdr alhdr ON alhdr.c_allocationhdr_ID=al.c_allocationhdr_ID "
                //                                            + " WHERE alhdr.isactive        ='Y' AND Alhdr.Docstatus        IN ('CO','CL') and al.c_invoice_id=" + invoice.GetRef_C_Invoice_ID())));
                // get amount against invoice wheether cash journal is completed or not
                // Done by Vivek on 01/03/2016
                amt = Decimal.Negate(Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT SUM(cl.Amount) FROM C_CashLine cl INNER JOIN C_Cash cs ON cs.C_Cash_ID=CL.C_CASH_ID WHERE cl.C_Invoice_ID=" + invoice.GetRef_C_Invoice_ID() + " AND cs.DocStatus NOT IN ('VO') ")));
            }
            else
            {
                amt = invoice.GetGrandTotal();
            }
            if (MDocBaseType.DOCBASETYPE_APINVOICE.Equals(dt.GetDocBaseType()) ||
                MDocBaseType.DOCBASETYPE_ARCREDITMEMO.Equals(dt.GetDocBaseType()))
            {
                amt = Decimal.Negate(amt);
                // set payment type according to invoice document type
                SetVSS_PAYMENTTYPE("P");
            }
            else
            {
                // set payment type according to invoice document type
                SetVSS_PAYMENTTYPE("R");
            }
            SetAmount(amt);
            //
            SetDiscountAmt(Env.ZERO);
            SetWriteOffAmt(Env.ZERO);
            SetIsGenerated(true);
            _invoice = invoice;
        }
Example #5
0
        /**
         *  Set Invoice - no discount
         *	@param invoice invoice
         */
        public void SetInvoiceMultiCurrency(MInvoice invoice, Decimal Amt, int C_Currency_ID)
        {
            SetC_Invoice_ID(invoice.GetC_Invoice_ID());
            SetCashType(CASHTYPE_Invoice);
            SetC_Currency_ID(C_Currency_ID);
            //	Amount
            MDocType dt  = MDocType.Get(GetCtx(), invoice.GetC_DocType_ID());
            Decimal  amt = Amt;

            if (MDocBaseType.DOCBASETYPE_APINVOICE.Equals(dt.GetDocBaseType()) ||
                MDocBaseType.DOCBASETYPE_ARCREDITMEMO.Equals(dt.GetDocBaseType()))
            {
                amt = Decimal.Negate(amt);
            }
            SetAmount(amt);
            //
            SetDiscountAmt(Env.ZERO);
            SetWriteOffAmt(Env.ZERO);
            SetIsGenerated(true);
            _invoice = invoice;
        }
        protected override string DoIt()
        {
            ds = new DataSet();

            ds = DB.ExecuteDataset("SELECT C_Recurring_ID From C_Recurring Where IsActive='Y' AND AD_Client_ID=" + GetAD_Client_ID()
                                   + " AND TRUNC(DateNextRun)=" + GlobalVariable.TO_DATE(DateTime.Now, true));
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                for (Int32 i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    Recurring = new MRecurring(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Recurring_ID"]), Get_Trx());
                    dateDoc   = Recurring.GetDateNextRun();
                    if (dateDoc != null && Recurring.CalculateRuns())
                    {
                        //  throw new Exception("No Runs Left");
                        MRecurringRun run = new MRecurringRun(GetCtx(), Recurring);
                        String        msg = "@Created@ ";
                        // if (Recurring.GetDateNextRun() == DateTime.Now.Date || Recurring.GetDateNextRun() == null)
                        //{
                        //	Copy
                        if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Order))
                        {
                            MOrder from  = new MOrder(GetCtx(), Recurring.GetC_Order_ID(), Get_TrxName());
                            MOrder order = MOrder.CopyFrom(from, dateDoc,
                                                           from.GetC_DocType_ID(), false, false, Get_TrxName());
                            run.SetC_Order_ID(order.GetC_Order_ID());
                            msg += order.GetDocumentNo();
                        }
                        else if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Invoice))
                        {
                            MInvoice from    = new MInvoice(GetCtx(), Recurring.GetC_Invoice_ID(), Get_TrxName());
                            MInvoice invoice = MInvoice.CopyFrom(from, dateDoc,
                                                                 from.GetC_DocType_ID(), false, Get_TrxName(), false);
                            run.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                            msg += invoice.GetDocumentNo();
                        }
                        else if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Project))
                        {
                            MProject project = MProject.CopyFrom(GetCtx(), Recurring.GetC_Project_ID(), dateDoc, Get_TrxName());
                            run.SetC_Project_ID(project.GetC_Project_ID());
                            msg += project.GetValue();
                        }
                        else if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_GLJournalBatch))
                        {
                            MJournalBatch journal = MJournalBatch.CopyFrom(GetCtx(), Recurring.GetGL_JournalBatch_ID(), dateDoc, Get_TrxName());
                            run.SetGL_JournalBatch_ID(journal.GetGL_JournalBatch_ID());
                            msg += journal.GetDocumentNo();
                        }
                        else if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_GLJournal))
                        {
                            MJournal Journal = MJournal.CopyFrom(GetCtx(), Recurring.GetGL_Journal_ID(), dateDoc, Get_TrxName());
                            run.SetGL_Journal_ID(Journal.GetGL_Journal_ID());
                            msg += Journal.GetDocumentNo();
                        }
                        else if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Payment))
                        {
                            MPayment from    = new MPayment(GetCtx(), Recurring.GetC_Payment_ID(), Get_TrxName());
                            MPayment payment = MPayment.CopyFrom(from, dateDoc,
                                                                 from.GetC_DocType_ID(), Get_TrxName());
                            run.SetC_Payment_ID(payment.GetC_Payment_ID());
                            msg += payment.GetDocumentNo();
                        }
                        //else
                        //  return "Invalid @RecurringType@ = " + Recurring.GetRecurringType();
                        if (run.Save(Get_TrxName()))
                        {
                            Recurring.SetDateLastRun(run.GetUpdated());
                            Recurring.SetRunsRemaining(Recurring.GetRunsRemaining() - 1);
                            SetDateNextRun();
                            Recurring.Save(Get_TrxName());
                        }
                        // }
                    }
                }
            }
            DisposeVariables();
            return("");
            //  throw new NotImplementedException();
        }
Example #7
0
        /**
         *  Apply Payment Term with schedule to Invoice
         *	@param invoice invoice
         *	@return true if payment schedule is valid
         */
        private bool ApplySchedule(MInvoice invoice)
        {
            DeleteInvoicePaySchedule(invoice.GetC_Invoice_ID(), invoice.Get_TrxName());
            //	Create Schedule
            MInvoicePaySchedule ips       = null;
            Decimal             remainder = invoice.GetGrandTotal();

            for (int i = 0; i < _schedule.Length; i++)
            {
                ips = new MInvoicePaySchedule(invoice, _schedule[i]);
                //int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));
                //if (_CountVA009 > 0)
                //{
                //    ips.SetVA009_ExecutionStatus("A");
                //    ips.SetC_DocType_ID(invoice.GetC_DocType_ID());
                //}
                int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));
                if (_CountVA009 > 0)
                {
                    ips.SetVA009_ExecutionStatus("A");
                    ips.SetC_DocType_ID(invoice.GetC_DocType_ID());

                    MOrder _Order = new MOrder(GetCtx(), invoice.GetC_Order_ID(), Get_TrxName());
                    ips.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                    ips.SetC_PaymentTerm_ID(invoice.GetC_PaymentTerm_ID());
                    ips.SetVA009_GrandTotal(invoice.GetGrandTotal());

                    MPaymentTerm payterm   = new MPaymentTerm(GetCtx(), invoice.GetC_PaymentTerm_ID(), Get_TrxName());
                    int          _graceDay = payterm.GetGraceDays();
                    //DateTime? _followUpDay = GetDueDate(invoice);
                    ips.SetVA009_FollowupDate(ips.GetDueDate().Value.AddDays(_graceDay));
                    //ips.SetVA009_PlannedDueDate(GetDueDate(invoice));
                    ips.SetVA009_PlannedDueDate(ips.GetDueDate());
                    //ips.SetDueDate(GetDueDate(invoice));

                    //change by amit 25-11-2015
                    StringBuilder _sql = new StringBuilder();
                    _sql.Clear();
                    _sql.Append(@"SELECT UNIQUE asch.C_Currency_ID FROM c_acctschema asch INNER JOIN ad_clientinfo ci ON ci.c_acctschema1_id = asch.c_acctschema_id
                                 INNER JOIN ad_client c ON c.ad_client_id = ci.ad_client_id INNER JOIN c_invoice i ON c.ad_client_id    = i.ad_client_id
                                 WHERE i.ad_client_id = " + invoice.GetAD_Client_ID());
                    int BaseCurrency = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString(), null, null));

                    if (BaseCurrency != invoice.GetC_Currency_ID())
                    {
                        _sql.Clear();
                        _sql.Append(@"SELECT multiplyrate FROM c_conversion_rate WHERE AD_Client_ID = " + invoice.GetAD_Client_ID() + " AND  c_currency_id  = " + invoice.GetC_Currency_ID() +
                                    " AND c_currency_to_id = " + BaseCurrency + " AND " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                        decimal multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                        if (multiplyRate == 0)
                        {
                            _sql.Clear();
                            _sql.Append(@"SELECT dividerate FROM c_conversion_rate WHERE AD_Client_ID = " + invoice.GetAD_Client_ID() + " AND c_currency_id  = " + BaseCurrency +
                                        " AND c_currency_to_id = " + invoice.GetC_Currency_ID() + " AND " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                            multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                        }
                        ips.SetVA009_OpenAmnt(ips.GetDueAmt() * multiplyRate);
                    }
                    else
                    {
                        ips.SetVA009_OpenAmnt(ips.GetDueAmt());
                    }

                    ips.SetC_Currency_ID(invoice.GetC_Currency_ID());
                    ips.SetVA009_BseCurrncy(BaseCurrency);
                    ips.SetVA009_OpnAmntInvce(ips.GetDueAmt());
                    ips.SetC_BPartner_ID(invoice.GetC_BPartner_ID());
                    //end

                    string  sql = "Select va009_paymentmode, va009_paymenttype, va009_paymenttrigger  From va009_paymentmethod where va009_paymentmethod_ID=" + invoice.GetVA009_PaymentMethod_ID() + "   AND IsActive = 'Y' AND AD_Client_ID = " + invoice.GetAD_Client_ID();
                    DataSet ds  = new DataSet();
                    ds = DB.ExecuteDataset(sql);
                    if (ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                        {
                            ips.SetVA009_PaymentMode(Util.GetValueOfString(ds.Tables[0].Rows[j]["va009_paymentmode"]));
                            ips.SetVA009_PaymentType(Util.GetValueOfString(ds.Tables[0].Rows[j]["va009_paymenttype"]));
                            ips.SetVA009_PaymentTrigger(Util.GetValueOfString(ds.Tables[0].Rows[j]["va009_paymenttrigger"]));
                            ips.SetVA009_ExecutionStatus("A");
                        }
                    }
                }
                ips.Save(invoice.Get_TrxName());
                log.Fine(ips.ToString());
                remainder = Decimal.Subtract(remainder, ips.GetDueAmt());
            }   //	for all schedules
            //	Remainder - update last
            if (remainder.CompareTo(Env.ZERO) != 0 && ips != null)
            {
                ips.SetDueAmt(Decimal.Add(ips.GetDueAmt(), remainder));
                ips.Save(invoice.Get_TrxName());
                log.Fine("Remainder=" + remainder + " - " + ips);
            }

            //	updateInvoice
            if (invoice.GetC_PaymentTerm_ID() != GetC_PaymentTerm_ID())
            {
                invoice.SetC_PaymentTerm_ID(GetC_PaymentTerm_ID());
            }
            return(invoice.ValidatePaySchedule());
        }
Example #8
0
        /**
         *  Apply Payment Term without schedule to Invoice
         *	@param invoice invoice
         *	@return false as no payment schedule
         */
        private bool ApplyNoSchedule(MInvoice invoice)
        {
            DeleteInvoicePaySchedule(invoice.GetC_Invoice_ID(), invoice.Get_TrxName());
            //	updateInvoice
            if (invoice.GetC_PaymentTerm_ID() != GetC_PaymentTerm_ID())
            {
                invoice.SetC_PaymentTerm_ID(GetC_PaymentTerm_ID());
            }
            if (invoice.IsPayScheduleValid())
            {
                invoice.SetIsPayScheduleValid(false);
            }
            //----------------Anuj------11/09/2015------------------------
            int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));

            if (_CountVA009 > 0)
            {
                StringBuilder       _sql     = new StringBuilder();
                MInvoicePaySchedule schedule = new MInvoicePaySchedule(GetCtx(), 0, Get_TrxName());
                MPaymentTerm        payterm  = new MPaymentTerm(GetCtx(), invoice.GetC_PaymentTerm_ID(), Get_TrxName());
                schedule.SetAD_Client_ID(invoice.GetAD_Client_ID());
                schedule.SetAD_Org_ID(invoice.GetAD_Org_ID());
                schedule.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                schedule.SetC_DocType_ID(invoice.GetC_DocType_ID());
                schedule.SetC_PaymentTerm_ID(invoice.GetC_PaymentTerm_ID());
                schedule.SetVA009_GrandTotal(invoice.GetGrandTotal());
                schedule.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                schedule.SetDueDate(GetDueDate(invoice));
                schedule.SetDueAmt(invoice.GetGrandTotal());
                schedule.SetDiscountDate(invoice.GetDateInvoiced().Value.AddDays(Util.GetValueOfInt(payterm.GetDiscountDays())));
                schedule.SetDiscountAmt((Util.GetValueOfDecimal((invoice.GetGrandTotal() * payterm.GetDiscount()) / 100)));

                schedule.SetDiscountDays2(invoice.GetDateInvoiced().Value.AddDays(Util.GetValueOfInt(payterm.GetDiscountDays2())));
                schedule.SetDiscount2((Util.GetValueOfDecimal((invoice.GetGrandTotal() * payterm.GetDiscount2()) / 100)));

                schedule.SetVA009_PlannedDueDate(GetDueDate(invoice));

                _sql.Clear();
                _sql.Append(@"SELECT UNIQUE asch.C_Currency_ID FROM c_acctschema asch INNER JOIN ad_clientinfo ci ON ci.c_acctschema1_id = asch.c_acctschema_id
                                 INNER JOIN ad_client c ON c.ad_client_id = ci.ad_client_id INNER JOIN c_invoice i ON c.ad_client_id    = i.ad_client_id
                                 WHERE i.ad_client_id = " + invoice.GetAD_Client_ID());
                int BaseCurrency = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString(), null, null));

                if (BaseCurrency != invoice.GetC_Currency_ID())
                {
                    // change by amit
                    _sql.Clear();
                    _sql.Append(@"SELECT multiplyrate FROM c_conversion_rate WHERE AD_Client_ID = " + GetCtx().GetAD_Client_ID() + " AND c_currency_id  = " + invoice.GetC_Currency_ID() +
                                " AND c_currency_to_id = " + BaseCurrency + " AND  " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                    decimal multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                    if (multiplyRate == 0)
                    {
                        _sql.Clear();
                        _sql.Append(@"SELECT dividerate FROM c_conversion_rate WHERE AD_Client_ID = " + GetCtx().GetAD_Client_ID() + " AND c_currency_id  = " + BaseCurrency +
                                    " AND c_currency_to_id = " + invoice.GetC_Currency_ID() + " AND  " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                        multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                    }
                    schedule.SetVA009_OpenAmnt(invoice.GetGrandTotal() * multiplyRate);
                }
                else
                {
                    schedule.SetVA009_OpenAmnt(invoice.GetGrandTotal());
                }

                schedule.SetC_Currency_ID(invoice.GetC_Currency_ID());
                schedule.SetVA009_BseCurrncy(BaseCurrency);
                schedule.SetVA009_OpnAmntInvce(invoice.GetGrandTotal());
                schedule.SetC_BPartner_ID(invoice.GetC_BPartner_ID());

                MOrder _Order = new MOrder(GetCtx(), invoice.GetC_Order_ID(), Get_TrxName());
                //schedule.SetVA009_PaymentMethod_ID(_Order.GetVA009_PaymentMethod_ID());
                //schedule.SetC_PaymentTerm_ID(_Order.GetC_PaymentTerm_ID());

                int      _graceDay    = payterm.GetGraceDays();
                DateTime?_followUpDay = GetDueDate(invoice);
                schedule.SetVA009_FollowupDate(_followUpDay.Value.AddDays(_graceDay));
                _sql.Clear();
                _sql.Append("Select va009_paymentmode, va009_paymenttype, va009_paymenttrigger  From va009_paymentmethod where va009_paymentmethod_ID=" + invoice.GetVA009_PaymentMethod_ID() + "   AND IsActive = 'Y' AND AD_Client_ID = " + invoice.GetAD_Client_ID());
                DataSet ds = new DataSet();
                ds = DB.ExecuteDataset(_sql.ToString());
                if (ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        schedule.SetVA009_PaymentMode(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymentmode"]));
                        schedule.SetVA009_PaymentType(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymenttype"]));
                        schedule.SetVA009_PaymentTrigger(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymenttrigger"]));
                        schedule.SetVA009_ExecutionStatus("A");
                    }
                }
                if (!schedule.Save())
                {
                    return(false);
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #9
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());
        }
Example #10
0
        }       //	toString

        /// <summary>
        /// Execute Run.
        /// </summary>
        /// <returns>clear text info</returns>
        public String ExecuteRun()
        {
            DateTime?dateDoc = GetDateNextRun();

            if (!CalculateRuns())
            {
                throw new Exception("No Runs Left");
            }
            //	log
            MRecurringRun run = new MRecurringRun(GetCtx(), this);
            String        msg = "@Created@ ";

            //Checked if the Next Date Run is less then the date pressent Arpit on 15th Dec,2016
            if (GetDateNextRun() == DateTime.Now.Date || GetDateNextRun() == null)
            {
                //	Copy
                if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Order))
                {
                    MOrder from  = new MOrder(GetCtx(), GetC_Order_ID(), Get_TrxName());
                    MOrder order = MOrder.CopyFrom(from, dateDoc,
                                                   from.GetC_DocType_ID(), false, false, Get_TrxName());
                    run.SetC_Order_ID(order.GetC_Order_ID());
                    msg += order.GetDocumentNo();
                }
                else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Invoice))
                {
                    MInvoice from    = new MInvoice(GetCtx(), GetC_Invoice_ID(), Get_TrxName());
                    MInvoice invoice = MInvoice.CopyFrom(from, dateDoc,
                                                         from.GetC_DocType_ID(), false, Get_TrxName(), false);
                    run.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                    //Set Invoice Refrence and Description from Orignal to Recurring
                    invoice.Set_Value("InvoiceReference", from.GetDocumentNo() + "_" + (GetRunsMax() - GetRunsRemaining() + 1));
                    invoice.AddDescription(Msg.GetMsg(from.GetCtx(), "RecurringDocument") + from.GetDocumentNo());
                    if (!invoice.Save(Get_TrxName()))
                    {
                        ValueNamePair pp = VLogger.RetrieveError();
                        if (pp != null)
                        {
                            from.SetProcessMsg(Msg.GetMsg(from.GetCtx(), "CouldNotCreateInvoice") + pp.GetName());
                        }
                        else
                        {
                            from.SetProcessMsg(Msg.GetMsg(from.GetCtx(), "CouldNotCreateInvoice"));
                        }
                        throw new Exception(Msg.GetMsg(from.GetCtx(), "CouldNotCreateInvoice") + (pp != null ? pp.GetName() : ""));
                    }
                    msg += invoice.GetDocumentNo();
                }
                else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Project))
                {
                    MProject project = MProject.CopyFrom(GetCtx(), GetC_Project_ID(), dateDoc, Get_TrxName());
                    run.SetC_Project_ID(project.GetC_Project_ID());
                    msg += project.GetValue();
                }
                else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_GLJournalBatch)) //Changes to GL Journal Batch by Arpit
                {
                    MJournalBatch journal = MJournalBatch.CopyFrom(GetCtx(), GetGL_JournalBatch_ID(), dateDoc, Get_TrxName());
                    run.SetGL_JournalBatch_ID(journal.GetGL_JournalBatch_ID());
                    msg += journal.GetDocumentNo();
                }
                //Added by Arpit on 14th, Dec,2016
                else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_GLJournal))
                {
                    MJournal Journal = MJournal.CopyFrom(GetCtx(), GetGL_Journal_ID(), dateDoc, Get_TrxName());
                    run.SetGL_Journal_ID(Journal.GetGL_Journal_ID());
                    msg += Journal.GetDocumentNo();
                }

                //End here
                else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Payment))
                {
                    MPayment from    = new MPayment(GetCtx(), GetC_Payment_ID(), Get_TrxName());
                    MPayment payment = MPayment.CopyFrom(from, dateDoc,
                                                         from.GetC_DocType_ID(), Get_TrxName());
                    run.SetC_Payment_ID(payment.GetC_Payment_ID());
                    msg += payment.GetDocumentNo();
                }
                else
                {
                    return("Invalid @RecurringType@ = " + GetRecurringType());
                }
                run.Save(Get_TrxName());

                //
                SetDateLastRun(run.GetUpdated());
                SetRunsRemaining(GetRunsRemaining() - 1);
                SetDateNextRun();
                Save(Get_TrxName());
                return(msg);
            }
            else
            {
                return(Msg.GetMsg(GetCtx(), "RecurringNotCompleted") + String.Format("{0:dd/M/yyyy}", Convert.ToDateTime(GetDateNextRun())));
            }
        }       //	execureRun
        /**
         *  Apply Payment Term without schedule to Invoice
         *	@param invoice invoice
         *	@return false as no payment schedule
         */

        #region Advance Payment by Vivek on 16/06/2016

        private bool ApplyNoSchedule(MInvoice invoice)
        {
            int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));

            if (_CountVA009 > 0)
            {
                DeleteInvoicePaySchedule(invoice.GetC_Invoice_ID(), invoice.Get_TrxName());
                StringBuilder       _sql     = new StringBuilder();
                MInvoicePaySchedule schedule = null;
                MPaymentTerm        payterm  = new MPaymentTerm(GetCtx(), invoice.GetC_PaymentTerm_ID(), invoice.Get_TrxName());

                Decimal remainder    = invoice.GetGrandTotal();
                int     BaseCurrency = 0;

                if (Util.GetValueOfInt(DB.ExecuteScalar("Select Count(*) From C_PaySchedule Where C_PaymentTerm_ID=" + invoice.GetC_PaymentTerm_ID())) > 1)
                {
                    for (int i = 0; i < _schedule.Length; i++)
                    {
                        MPaySchedule _sch = new MPaySchedule(GetCtx(), _schedule[i].GetC_PaySchedule_ID(), Get_TrxName());
                        #region IsAdvance true on Payment Schedule
                        if (_sch.IsVA009_Advance())
                        {
                            #region Copy Order Schedules
                            String  sql = "SELECT * FROM VA009_OrderPaySchedule WHERE C_Order_ID=" + invoice.GetC_Order_ID() + " AND VA009_IsPaid='Y' ORDER BY Created";
                            DataSet _ds = new DataSet();

                            _ds = DB.ExecuteDataset(sql, null);
                            if (_ds.Tables[0].Rows.Count > 0 && _ds.Tables[0].Rows != null)
                            {
                                for (int j = 0; j < _ds.Tables[0].Rows.Count; j++)
                                {
                                    schedule = new MInvoicePaySchedule(GetCtx(), 0, invoice.Get_TrxName());
                                    Boolean _isPaid = false;
                                    if (Util.GetValueOfString(_ds.Tables[0].Rows[j]["VA009_IsPaid"]) == "Y")
                                    {
                                        _isPaid = true;
                                    }
                                    schedule.SetAD_Client_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["AD_Client_ID"]));
                                    schedule.SetAD_Org_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["AD_Org_ID"]));
                                    schedule.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                                    schedule.SetC_DocType_ID(invoice.GetC_DocType_ID());
                                    schedule.SetC_PaymentTerm_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["C_PaymentTerm_ID"]));
                                    schedule.SetVA009_GrandTotal(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA009_GrandTotal"]));
                                    schedule.SetVA009_PaymentMethod_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA009_PaymentMethod_ID"]));
                                    schedule.SetDueDate(invoice.GetDateInvoiced());
                                    schedule.SetDueAmt(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["DueAmt"]));
                                    schedule.SetDiscountDate(Util.GetValueOfDateTime(_ds.Tables[0].Rows[j]["DiscountDate"]));
                                    schedule.SetDiscountAmt(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["DiscountAmt"]));
                                    schedule.SetVA009_IsPaid(_isPaid);
                                    schedule.SetC_Payment_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["C_Payment_ID"]));

                                    schedule.SetDiscountDays2(Util.GetValueOfDateTime(_ds.Tables[0].Rows[j]["DiscountDays2"]));
                                    schedule.SetDiscount2(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["Discount2"]));

                                    schedule.SetVA009_PlannedDueDate(Util.GetValueOfDateTime(_ds.Tables[0].Rows[j]["VA009_PlannedDueDate"]));

                                    schedule.SetVA009_OpenAmnt(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA009_OpenAmnt"]));


                                    schedule.SetC_Currency_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["C_Currency_ID"]));
                                    schedule.SetVA009_BseCurrncy(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA009_bseCurrncy"]));
                                    schedule.SetVA009_OpnAmntInvce(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA009_OpnAmntInvce"]));
                                    schedule.SetC_BPartner_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[j]["C_Bpartner_ID"]));

                                    schedule.SetVA009_FollowupDate(Util.GetValueOfDateTime(_ds.Tables[0].Rows[j]["VA009_FollowUpDate"]));
                                    schedule.SetVA009_PaymentMode(Util.GetValueOfString(_ds.Tables[0].Rows[j]["va009_paymentmode"]));
                                    schedule.SetVA009_PaymentType(Util.GetValueOfString(_ds.Tables[0].Rows[j]["va009_paymenttype"]));
                                    schedule.SetVA009_PaymentTrigger(Util.GetValueOfString(_ds.Tables[0].Rows[j]["va009_paymenttrigger"]));
                                    schedule.SetVA009_ExecutionStatus(Util.GetValueOfString(_ds.Tables[0].Rows[j]["VA009_ExecutionStatus"]));
                                    schedule.SetProcessed(true);
                                    if (!schedule.Save(invoice.Get_TrxName()))
                                    {
                                        return(false);
                                    }
                                }
                            }
                            #endregion
                        }
                        #endregion

                        #region IsAdvance false on Payment Schedule
                        else
                        {
                            schedule = new MInvoicePaySchedule(invoice, _schedule[i]);

                            schedule.SetVA009_ExecutionStatus("A");
                            schedule.SetAD_Client_ID(invoice.GetAD_Client_ID());
                            schedule.SetAD_Org_ID(invoice.GetAD_Org_ID());
                            schedule.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                            schedule.SetC_DocType_ID(invoice.GetC_DocType_ID());

                            MOrder _Order = new MOrder(GetCtx(), invoice.GetC_Order_ID(), Get_TrxName());
                            schedule.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                            schedule.SetC_PaymentTerm_ID(invoice.GetC_PaymentTerm_ID());
                            schedule.SetVA009_GrandTotal(invoice.GetGrandTotal());

                            MPaymentTerm paytrm    = new MPaymentTerm(GetCtx(), invoice.GetC_PaymentTerm_ID(), Get_TrxName());
                            int          _graceDay = paytrm.GetGraceDays();
                            //DateTime? _followUpDay = GetDueDate(invoice);
                            schedule.SetVA009_FollowupDate(schedule.GetDueDate().Value.AddDays(_graceDay));
                            //schedule.SetVA009_PlannedDueDate(GetDueDate(invoice));
                            schedule.SetVA009_PlannedDueDate(schedule.GetDueDate());
                            //schedule.SetDueDate(GetDueDate(invoice));

                            //change by amit 25-11-2015
                            StringBuilder _sqlBsCrrncy = new StringBuilder();
                            _sql.Clear();
                            _sqlBsCrrncy.Append(@"SELECT UNIQUE asch.C_Currency_ID FROM c_acctschema asch INNER JOIN ad_clientinfo ci ON ci.c_acctschema1_id = asch.c_acctschema_id
                                 INNER JOIN ad_client c ON c.ad_client_id = ci.ad_client_id INNER JOIN c_invoice i ON c.ad_client_id    = i.ad_client_id
                                 WHERE i.ad_client_id = " + invoice.GetAD_Client_ID());
                            BaseCurrency = Util.GetValueOfInt(DB.ExecuteScalar(_sqlBsCrrncy.ToString(), null, null));

                            if (BaseCurrency != invoice.GetC_Currency_ID())
                            {
                                _sqlBsCrrncy.Clear();
                                _sqlBsCrrncy.Append(@"SELECT multiplyrate FROM c_conversion_rate WHERE AD_Client_ID = " + invoice.GetAD_Client_ID() + " AND  c_currency_id  = " + invoice.GetC_Currency_ID() +
                                                    " AND c_currency_to_id = " + BaseCurrency + " AND " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                                decimal multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sqlBsCrrncy.ToString(), null, null));
                                if (multiplyRate == 0)
                                {
                                    _sqlBsCrrncy.Clear();
                                    _sqlBsCrrncy.Append(@"SELECT dividerate FROM c_conversion_rate WHERE AD_Client_ID = " + invoice.GetAD_Client_ID() + " AND c_currency_id  = " + BaseCurrency +
                                                        " AND c_currency_to_id = " + invoice.GetC_Currency_ID() + " AND " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                                    multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sqlBsCrrncy.ToString(), null, null));
                                }
                                schedule.SetVA009_OpenAmnt(schedule.GetDueAmt() * multiplyRate);
                            }
                            else
                            {
                                schedule.SetVA009_OpenAmnt(schedule.GetDueAmt());
                            }

                            schedule.SetC_Currency_ID(invoice.GetC_Currency_ID());
                            schedule.SetVA009_BseCurrncy(BaseCurrency);
                            schedule.SetVA009_OpnAmntInvce(schedule.GetDueAmt());
                            schedule.SetC_BPartner_ID(invoice.GetC_BPartner_ID());
                            //end

                            string  _sqlPaymentMthd = "Select va009_paymentmode, va009_paymenttype, va009_paymenttrigger  From va009_paymentmethod where va009_paymentmethod_ID=" + invoice.GetVA009_PaymentMethod_ID() + "   AND IsActive = 'Y' AND AD_Client_ID = " + invoice.GetAD_Client_ID();
                            DataSet dsPayMthd       = new DataSet();
                            dsPayMthd = DB.ExecuteDataset(_sqlPaymentMthd);
                            if (dsPayMthd.Tables != null && dsPayMthd.Tables.Count > 0 && dsPayMthd.Tables[0].Rows.Count > 0)
                            {
                                for (int j = 0; j < dsPayMthd.Tables[0].Rows.Count; j++)
                                {
                                    schedule.SetVA009_PaymentMode(Util.GetValueOfString(dsPayMthd.Tables[0].Rows[j]["va009_paymentmode"]));
                                    schedule.SetVA009_PaymentType(Util.GetValueOfString(dsPayMthd.Tables[0].Rows[j]["va009_paymenttype"]));
                                    schedule.SetVA009_PaymentTrigger(Util.GetValueOfString(dsPayMthd.Tables[0].Rows[j]["va009_paymenttrigger"]));
                                    schedule.SetVA009_ExecutionStatus("A");
                                }
                            }
                            schedule.SetProcessed(true);
                            if (!schedule.Save(invoice.Get_TrxName()))
                            {
                                return(false);
                            }
                        }
                    }
                    #endregion

                    if (invoice.GetC_PaymentTerm_ID() != GetC_PaymentTerm_ID())
                    {
                        invoice.SetC_PaymentTerm_ID(GetC_PaymentTerm_ID());
                    }
                    return(invoice.ValidatePaySchedule());
                }
                else if (Util.GetValueOfInt(DB.ExecuteScalar("Select Count(*) From C_PaySchedule Where C_PaymentTerm_ID=" + invoice.GetC_PaymentTerm_ID())) <= 1)
                {
                    schedule = new MInvoicePaySchedule(GetCtx(), 0, Get_TrxName());

                    schedule.SetAD_Client_ID(invoice.GetAD_Client_ID());
                    schedule.SetAD_Org_ID(invoice.GetAD_Org_ID());
                    schedule.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                    schedule.SetC_DocType_ID(invoice.GetC_DocType_ID());
                    schedule.SetC_PaymentTerm_ID(invoice.GetC_PaymentTerm_ID());
                    schedule.SetVA009_GrandTotal(invoice.GetGrandTotal());
                    schedule.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                    schedule.SetDueDate(GetDueDate(invoice));
                    schedule.SetDueAmt(invoice.GetGrandTotal());
                    schedule.SetDiscountDate(invoice.GetDateInvoiced().Value.AddDays(Util.GetValueOfInt(payterm.GetDiscountDays())));
                    schedule.SetDiscountAmt((Util.GetValueOfDecimal((invoice.GetGrandTotal() * payterm.GetDiscount()) / 100)));

                    schedule.SetDiscountDays2(invoice.GetDateInvoiced().Value.AddDays(Util.GetValueOfInt(payterm.GetDiscountDays2())));
                    schedule.SetDiscount2((Util.GetValueOfDecimal((invoice.GetGrandTotal() * payterm.GetDiscount2()) / 100)));

                    schedule.SetVA009_PlannedDueDate(GetDueDate(invoice));

                    _sql.Clear();
                    _sql.Append(@"SELECT UNIQUE asch.C_Currency_ID FROM c_acctschema asch INNER JOIN ad_clientinfo ci ON ci.c_acctschema1_id = asch.c_acctschema_id
                                 INNER JOIN ad_client c ON c.ad_client_id = ci.ad_client_id INNER JOIN c_invoice i ON c.ad_client_id    = i.ad_client_id
                                 WHERE i.ad_client_id = " + invoice.GetAD_Client_ID());
                    BaseCurrency = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString(), null, null));

                    if (BaseCurrency != invoice.GetC_Currency_ID())
                    {
                        // change by amit
                        _sql.Clear();
                        _sql.Append(@"SELECT multiplyrate FROM c_conversion_rate WHERE AD_Client_ID = " + GetCtx().GetAD_Client_ID() + " AND c_currency_id  = " + invoice.GetC_Currency_ID() +
                                    " AND c_currency_to_id = " + BaseCurrency + " AND  " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                        decimal multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                        if (multiplyRate == 0)
                        {
                            _sql.Clear();
                            _sql.Append(@"SELECT dividerate FROM c_conversion_rate WHERE AD_Client_ID = " + GetCtx().GetAD_Client_ID() + " AND c_currency_id  = " + BaseCurrency +
                                        " AND c_currency_to_id = " + invoice.GetC_Currency_ID() + " AND  " + GlobalVariable.TO_DATE(invoice.GetDateAcct(), true) + " BETWEEN ValidFrom AND ValidTo");
                            multiplyRate = Util.GetValueOfDecimal(DB.ExecuteScalar(_sql.ToString(), null, null));
                        }
                        schedule.SetVA009_OpenAmnt(invoice.GetGrandTotal() * multiplyRate);
                    }
                    else
                    {
                        schedule.SetVA009_OpenAmnt(invoice.GetGrandTotal());
                    }

                    schedule.SetC_Currency_ID(invoice.GetC_Currency_ID());
                    schedule.SetVA009_BseCurrncy(BaseCurrency);
                    schedule.SetVA009_OpnAmntInvce(invoice.GetGrandTotal());
                    schedule.SetC_BPartner_ID(invoice.GetC_BPartner_ID());

                    MOrder _Order = new MOrder(GetCtx(), invoice.GetC_Order_ID(), Get_TrxName());
                    //schedule.SetVA009_PaymentMethod_ID(_Order.GetVA009_PaymentMethod_ID());
                    //schedule.SetC_PaymentTerm_ID(_Order.GetC_PaymentTerm_ID());

                    int      _graceDay    = payterm.GetGraceDays();
                    DateTime?_followUpDay = GetDueDate(invoice);
                    schedule.SetVA009_FollowupDate(_followUpDay.Value.AddDays(_graceDay));
                    _sql.Clear();
                    _sql.Append("Select va009_paymentmode, va009_paymenttype, va009_paymenttrigger  From va009_paymentmethod where va009_paymentmethod_ID=" + invoice.GetVA009_PaymentMethod_ID() + "   AND IsActive = 'Y' AND AD_Client_ID = " + invoice.GetAD_Client_ID());
                    DataSet ds = new DataSet();
                    ds = DB.ExecuteDataset(_sql.ToString());
                    if (ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            schedule.SetVA009_PaymentMode(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymentmode"]));
                            schedule.SetVA009_PaymentType(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymenttype"]));
                            schedule.SetVA009_PaymentTrigger(Util.GetValueOfString(ds.Tables[0].Rows[i]["va009_paymenttrigger"]));
                            schedule.SetVA009_ExecutionStatus("A");
                        }
                    }
                    if (!schedule.Save())
                    {
                        return(false);
                    }
                    if (invoice.GetC_PaymentTerm_ID() != GetC_PaymentTerm_ID())
                    {
                        invoice.SetC_PaymentTerm_ID(GetC_PaymentTerm_ID());
                    }
                    return(invoice.ValidatePaySchedule());
                }
            }
            return(true);
        }