Пример #1
0
        }       //	MTaxDeclarationLine

        /// <summary>
        /// Parent Constructor
        /// </summary>
        /// <param name="parent">parent</param>
        /// <param name="invoice">invoice</param>
        /// <param name="iLine">invoice line</param>
        public MTaxDeclarationLine(MTaxDeclaration parent, MInvoice invoice, MInvoiceLine iLine) : this(parent.GetCtx(), 0, parent.Get_TrxName())
        {
            // this(parent.getCtx(), 0, parent.get_TrxName());
            SetClientOrg(invoice);
            SetC_TaxDeclaration_ID(parent.GetC_TaxDeclaration_ID());
            SetIsManual(false);
            //
            SetC_Invoice_ID(invoice.GetC_Invoice_ID());
            SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            SetC_Currency_ID(invoice.GetC_Currency_ID());
            SetDateAcct(invoice.GetDateAcct());
            //
            SetC_InvoiceLine_ID(iLine.GetC_InvoiceLine_ID());
            SetC_Tax_ID(iLine.GetC_Tax_ID());
            if (invoice.IsTaxIncluded())
            {
                SetTaxBaseAmt(iLine.GetLineNetAmt());
                SetTaxAmt(iLine.GetTaxAmt());
            }
            else
            {
                SetTaxBaseAmt(iLine.GetLineNetAmt());
                SetTaxAmt(iLine.GetTaxAmt());
            }
        }       //	MTaxDeclarationLine
Пример #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;
        }
Пример #3
0
        /**
         *  Set Value Name Description
         *	@param Invoice
         *	@param line line
         *	@param deliveryCount
         */
        public void SetValueNameDescription(MInvoice invoice, MInvoiceLine line, int deliveryCount)
        {
            MProduct  product = line.GetProduct();
            MBPartner partner = new MBPartner(GetCtx(), invoice.GetC_BPartner_ID(), null);

            SetValueNameDescription(invoice, deliveryCount, product, partner);
        }
Пример #4
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;
        }
Пример #5
0
 /**
  *  Get BPartner of Invoice
  *	@return bp
  */
 public int GetC_BPartner_ID()
 {
     if (_invoice == null)
     {
         GetInvoice();
     }
     if (_invoice == null)
     {
         return(0);
     }
     return(_invoice.GetC_BPartner_ID());
 }
Пример #6
0
        public VAdvantage.Model.MJournalLine GenerateJounalLine(VAdvantage.Model.MJournal journal, MInvoice invoice, VAdvantage.Model.MInvoiceLine invoiceLine,
                                                                MRevenueRecognitionPlan revenueRecognitionPlan, MRevenueRecognitionRun revenueRecognitionRun, string recognitionType, int k)
        {
            try
            {
                int combination_ID = 0;
                if (k == 0)
                {
                    if (recognitionType == "R")
                    {
                        combination_ID = revenueRecognitionPlan.GetUnEarnedRevenue_Acct();
                        //journalLine.SetC_ValidCombination_ID(combination_ID);
                    }
                    else
                    {
                        combination_ID = revenueRecognitionPlan.GetINT15_ProductExpense();
                        //journalLine.SetC_ValidCombination_ID(combination_ID);
                    }
                    journalLine.SetAmtAcctDr(revenueRecognitionRun.GetRecognizedAmt());
                    journalLine.SetAmtSourceDr(revenueRecognitionRun.GetRecognizedAmt());
                    journalLine.SetAmtSourceCr(0);
                    journalLine.SetAmtAcctCr(0);
                }
                else
                {
                    if (recognitionType == "R")
                    {
                        combination_ID = revenueRecognitionPlan.GetP_Revenue_Acct();
                        //journalLine.SetC_ValidCombination_ID(combination_ID);
                    }
                    else
                    {
                        combination_ID = revenueRecognitionPlan.GetINT15_PrepaidExpense();
                        //journalLine.SetC_ValidCombination_ID(combination_ID);
                    }
                    journalLine.SetAmtAcctDr(0);
                    journalLine.SetAmtSourceDr(0);
                    journalLine.SetAmtSourceCr(revenueRecognitionRun.GetRecognizedAmt());
                    journalLine.SetAmtAcctCr(revenueRecognitionRun.GetRecognizedAmt());
                }
                int account_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select Account_ID From C_ValidCombination Where C_ValidCombination_ID=" + combination_ID));
                //VAdvantage.Model.MElementValue elementValue = new VAdvantage.Model.MElementValue(GetCtx(), account_ID, Get_Trx());

                journalLine.Set_ValueNoCheck("Account_ID", account_ID);
                journalLine.Set_ValueNoCheck("C_BPartner_ID", invoice.GetC_BPartner_ID());
                journalLine.Set_ValueNoCheck("M_Product_ID", invoiceLine.GetM_Product_ID());
            }
            catch (Exception ex)
            {
                log.SaveError(null, ex);
            }
            return(journalLine);
        }
Пример #7
0
        }       //	MTaxDeclarationLine

        /// <summary>
        /// Parent Constructor
        /// </summary>
        /// <param name="parent">parent</param>
        /// <param name="invoice">invoice</param>
        /// <param name="tLine">tax line</param>
        public MTaxDeclarationLine(MTaxDeclaration parent, MInvoice invoice, MInvoiceTax tLine) : this(parent.GetCtx(), 0, parent.Get_TrxName())
        {
            //this(parent.getCtx(), 0, parent.get_TrxName());
            SetClientOrg(invoice);
            SetC_TaxDeclaration_ID(parent.GetC_TaxDeclaration_ID());
            SetIsManual(false);
            //
            SetC_Invoice_ID(invoice.GetC_Invoice_ID());
            SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            SetC_Currency_ID(invoice.GetC_Currency_ID());
            SetDateAcct(invoice.GetDateAcct());
            //
            SetC_Tax_ID(tLine.GetC_Tax_ID());
            SetTaxBaseAmt(tLine.GetTaxBaseAmt());
            SetTaxAmt(tLine.GetTaxAmt());
        } //	MTaxDeclarationLine
Пример #8
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;
        }
Пример #9
0
        /// <summary>
        /// Perrform Process.
        /// </summary>
        /// <returns>Message (clear text)</returns>
        protected override String DoIt()
        {
            log.Info("C_Order_ID=" + _C_Order_ID + ", C_Invoice_ID=" + _C_Invoice_ID);
            if (_C_Order_ID == 0 && _C_Invoice_ID == 0)
            {
                throw new Exception("Nothing to do");
            }

            String retValue = "";

            if (_C_Order_ID != 0)
            {
                MOrder       order    = new MOrder(GetCtx(), _C_Order_ID, Get_TrxName());
                Decimal      oldPrice = order.GetGrandTotal();
                MOrderLine[] lines    = order.GetLines();
                for (int i = 0; i < lines.Length; i++)
                {
                    lines[i].SetPrice(order.GetM_PriceList_ID());
                    lines[i].Save();
                }
                order = new MOrder(GetCtx(), _C_Order_ID, Get_TrxName());
                Decimal newPrice = order.GetGrandTotal();
                retValue = order.GetDocumentNo() + ":  " + oldPrice + " -> " + newPrice;
            }
            if (_C_Invoice_ID != 0)
            {
                MInvoice       invoice  = new MInvoice(GetCtx(), _C_Invoice_ID, null);
                Decimal        oldPrice = invoice.GetGrandTotal();
                MInvoiceLine[] lines    = invoice.GetLines(false);
                for (int i = 0; i < lines.Length; i++)
                {
                    lines[i].SetPrice(invoice.GetM_PriceList_ID(), invoice.GetC_BPartner_ID());
                    lines[i].Save();
                }
                invoice = new MInvoice(GetCtx(), _C_Invoice_ID, null);
                Decimal newPrice = invoice.GetGrandTotal();
                if (retValue.Length > 0)
                {
                    retValue += Env.NL;
                }
                retValue += invoice.GetDocumentNo() + ":  " + oldPrice + " -> " + newPrice;
            }
            //
            return(retValue);
        }
Пример #10
0
        /// <summary>
        /// Before Save
        /// </summary>
        /// <param name="newRecord"></param>
        /// <returns>true</returns>
        protected override bool BeforeSave(bool newRecord)
        {
            if (Env.Signum(GetChargeAmt()) != 0 && GetC_Charge_ID() == 0)
            {
                log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "C_Charge_ID"));
                // ErrorLog.FillErrorLog("FillMandatory", GetMessage.Translate(GetCtx(), "C_Charge_ID"), "", VAdvantage.Framework.Message.MessageType.ERROR);
                return(false);
            }

            //	Set Line No
            if (GetLine() == 0)
            {
                String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM C_BankStatementLine WHERE C_BankStatement_ID=@param1";
                int    ii  = Convert.ToInt32(DB.GetSQLValue(Get_TrxName(), sql, GetC_BankStatement_ID()));
                SetLine(ii);
            }

            //	Set References
            if (GetC_Payment_ID() != 0 && GetC_BPartner_ID() == 0)
            {
                MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_TrxName());
                SetC_BPartner_ID(payment.GetC_BPartner_ID());
                if (payment.GetC_Invoice_ID() != 0)
                {
                    SetC_Invoice_ID(payment.GetC_Invoice_ID());
                }
            }
            if (GetC_Invoice_ID() != 0 && GetC_BPartner_ID() == 0)
            {
                MInvoice invoice = new MInvoice(GetCtx(), GetC_Invoice_ID(), Get_TrxName());
                SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            }
            //	Calculate Charge = Statement - trx - Interest
            Decimal amt = GetStmtAmt();

            amt = Decimal.Subtract(amt, GetTrxAmt());
            amt = Decimal.Subtract(amt, GetInterestAmt());
            if (amt.CompareTo(GetChargeAmt()) != 0)
            {
                SetChargeAmt(amt);
            }
            return(true);
        }
Пример #11
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="line"></param>
        /// <param name="doc"></param>
        public DocLine_Cash(MCashLine line, Doc_Cash doc)
            : base(line, doc)
        {
            _CashType         = line.GetCashType();
            _C_BankAccount_ID = line.GetC_BankAccount_ID();
            _C_CashBook_ID    = line.GetC_CashBook_ID();
            _C_Invoice_ID     = line.GetC_Invoice_ID();
            //
            if (_C_Invoice_ID != 0)
            {
                MInvoice invoice = MInvoice.Get(line.GetCtx(), _C_Invoice_ID);
                SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            }

            //
            _Amount            = line.GetAmount();
            _DiscountAmt       = line.GetDiscountAmt();
            _WriteOffAmt       = line.GetWriteOffAmt();
            _C_CashLine_Ref_ID = line.GetC_CashLine_ID_1();
            SetAmount(_Amount);
        }
Пример #12
0
        /**
         *  Set Invoice - no discount
         *	@param invoice invoice
         */
        public void SetInvoice(MInvoice invoice)
        {
            SetC_Invoice_ID(invoice.GetC_Invoice_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());
            Decimal  amt = invoice.GetGrandTotal();

            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()
        {
            try
            {
                MRevenueRecognition       mRevenueRecognition     = new MRevenueRecognition(GetCtx(), _RevenueRecognition_ID, Get_Trx());
                MRevenueRecognitionPlan[] revenueRecognitionPlans = MRevenueRecognitionPlan.GetRecognitionPlans(mRevenueRecognition, C_InvoiceLine_ID);
                for (int i = 0; i < revenueRecognitionPlans.Length; i++)
                {
                    MRevenueRecognitionPlan       revenueRecognitionPlan = revenueRecognitionPlans[i];
                    VAdvantage.Model.MInvoiceLine invoiceLine            = new VAdvantage.Model.MInvoiceLine(GetCtx(), revenueRecognitionPlan.GetC_InvoiceLine_ID(), Get_Trx());
                    MInvoice invoice = new MInvoice(GetCtx(), invoiceLine.GetC_Invoice_ID(), Get_Trx());
                    MRevenueRecognitionRun[] mRevenueRecognitionRuns = MRevenueRecognitionRun.GetRecognitionRuns(revenueRecognitionPlan, _RecognitionDate, false);
                    if (mRevenueRecognitionRuns.Length > 0)
                    {
                        if (_DocType == "GL")
                        {
                            if (revenueRecognitionPlan.GetC_AcctSchema_ID() != _AcctSchema_ID || revenueRecognitionPlan.GetC_Currency_ID() != _Currency_ID)
                            {
                                if (journal != null && journal.CompleteIt() == "CO")
                                {
                                    journal.SetProcessed(true);
                                    journal.SetDocStatus("CO");
                                    journal.SetDocAction("CL");
                                    journal.Save(Get_Trx());
                                    if (DocNo == null)
                                    {
                                        DocNo = journal.GetDocumentNo();
                                    }
                                    else
                                    {
                                        DocNo += "," + journal.GetDocumentNo();
                                    }
                                }
                                journal = new VAdvantage.Model.MJournal(GetCtx(), 0, Get_Trx());
                                journal = CreateJournalHDR(mRevenueRecognition, revenueRecognitionPlan);
                                journal.Save();
                                _AcctSchema_ID = journal.GetC_AcctSchema_ID();
                                _Currency_ID   = journal.GetC_Currency_ID();

                                decimal totalAmt = 0;
                                for (int j = 0; j < mRevenueRecognitionRuns.Length; j++)
                                {
                                    MRevenueRecognitionRun revenueRecognitionRun = mRevenueRecognitionRuns[j];
                                    totalAmt += revenueRecognitionRun.GetRecognizedAmt();
                                    revenueRecognitionRun.SetGL_Journal_ID(journal.GetGL_Journal_ID());
                                    revenueRecognitionRun.Save();
                                }

                                revenueRecognitionPlan.SetRecognizedAmt(totalAmt + revenueRecognitionPlan.GetRecognizedAmt());
                                revenueRecognitionPlan.Save();

                                for (int k = 0; k < 2; k++)
                                {
                                    journalLine = new VAdvantage.Model.MJournalLine(journal);
                                    int combination_ID = 0;
                                    if (k == 0)
                                    {
                                        if (mRevenueRecognition.GetINT15_RecognizeType() == "R")
                                        {
                                            combination_ID = revenueRecognitionPlan.GetUnEarnedRevenue_Acct();
                                            //journalLine.SetC_ValidCombination_ID(combination_ID);
                                        }
                                        else
                                        {
                                            combination_ID = revenueRecognitionPlan.GetINT15_ProductExpense();
                                            //journalLine.SetC_ValidCombination_ID(combination_ID);
                                        }
                                        journalLine.SetAmtAcctDr(totalAmt);
                                        journalLine.SetAmtSourceDr(totalAmt);
                                        journalLine.SetAmtSourceCr(0);
                                        journalLine.SetAmtAcctCr(0);
                                    }
                                    else
                                    {
                                        if (mRevenueRecognition.GetINT15_RecognizeType() == "R")
                                        {
                                            combination_ID = revenueRecognitionPlan.GetP_Revenue_Acct();
                                            //journalLine.SetC_ValidCombination_ID(combination_ID);
                                        }
                                        else
                                        {
                                            combination_ID = revenueRecognitionPlan.GetINT15_PrepaidExpense();
                                            //journalLine.SetC_ValidCombination_ID(combination_ID);
                                        }
                                        journalLine.SetAmtAcctDr(0);
                                        journalLine.SetAmtSourceDr(0);
                                        journalLine.SetAmtSourceCr(totalAmt);
                                        journalLine.SetAmtAcctCr(totalAmt);
                                    }
                                    int account_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select Account_ID From C_ValidCombination Where C_ValidCombination_ID=" + combination_ID));
                                    VAdvantage.Model.MElementValue elementValue = new VAdvantage.Model.MElementValue(GetCtx(), account_ID, Get_Trx());
                                    try
                                    {
                                        journalLine.Set_ValueNoCheck("Account_ID", account_ID);
                                        journalLine.Set_ValueNoCheck("C_BPartner_ID", invoice.GetC_BPartner_ID());
                                        journalLine.Set_ValueNoCheck("M_Product_ID", invoiceLine.GetM_Product_ID());
                                    }
                                    catch (Exception ex)
                                    {
                                    }
                                    journalLine.Save();
                                }
                            }
                        }
                    }
                }
                if (journal != null && journal.GetDocStatus() != "CO")
                {
                    if (journal.CompleteIt() == "CO")
                    {
                        journal.SetProcessed(true);
                        journal.SetDocStatus("CO");
                        journal.SetDocAction("CL");
                        journal.Save(Get_Trx());
                        if (DocNo == null)
                        {
                            DocNo = journal.GetDocumentNo();
                        }
                        else
                        {
                            DocNo += "," + journal.GetDocumentNo();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, "GL Journal not allocated due to " + ex);
                return(ex.ToString());
            }
            return(Msg.GetMsg(GetCtx(), "INT15_GLJournalCreated = " + DocNo));
        }
Пример #14
0
        /// <summary>
        /// Before Save
        /// </summary>
        /// <param name="newRecord"></param>
        /// <returns>true</returns>
        protected override bool BeforeSave(bool newRecord)
        {
            if (Env.Signum(GetChargeAmt()) != 0 && GetC_Charge_ID() == 0)
            {
                log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "C_Charge_ID"));
                // ErrorLog.FillErrorLog("FillMandatory", GetMessage.Translate(GetCtx(), "C_Charge_ID"), "", VAdvantage.Framework.Message.MessageType.ERROR);
                return(false);
            }

            //	Set Line No
            if (GetLine() == 0)
            {
                String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM C_BankStatementLine WHERE C_BankStatement_ID=@param1";
                int    ii  = Convert.ToInt32(DB.GetSQLValue(Get_TrxName(), sql, GetC_BankStatement_ID()));
                SetLine(ii);
            }

            //	Set References
            if (GetC_Payment_ID() != 0 && GetC_BPartner_ID() == 0)
            {
                MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_TrxName());
                SetC_BPartner_ID(payment.GetC_BPartner_ID());
                if (payment.GetC_Invoice_ID() != 0)
                {
                    SetC_Invoice_ID(payment.GetC_Invoice_ID());
                }
            }
            if (GetC_Invoice_ID() != 0 && GetC_BPartner_ID() == 0)
            {
                MInvoice invoice = new MInvoice(GetCtx(), GetC_Invoice_ID(), Get_TrxName());
                SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            }
            //Set BPartner_ID when having Order_ID
            if (Env.IsModuleInstalled("VA012_"))
            {
                if (GetC_Order_ID() != 0 && GetC_BPartner_ID() == 0)
                {
                    int _bpartner_ID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT C_BPartner_ID FROM C_Order WHERE IsActive='Y' AND C_Order_ID=" + GetC_Order_ID(), null, Get_Trx()));
                    SetC_BPartner_ID(_bpartner_ID);
                }
            }
            //	Calculate Charge = Statement - trx - Interest
            Decimal amt = GetStmtAmt();

            amt = Decimal.Subtract(amt, GetTrxAmt());
            //amt = Decimal.Subtract(amt, GetInterestAmt());     //Commented By Pratap to Exclude Interest 18-11-2015
            if (amt.CompareTo(GetChargeAmt()) != 0)
            {
                SetChargeAmt(amt);
            }

            // Reset Amount Dimension if Trx Amount is different
            if (Util.GetValueOfInt(Get_Value("AmtDimTrxAmount")) > 0)
            {
                string  qry       = "SELECT Amount FROM C_DimAmt WHERE C_DimAmt_ID=" + Util.GetValueOfInt(Get_Value("AmtDimTrxAmount"));
                decimal amtdimAmt = Util.GetValueOfDecimal(DB.ExecuteScalar(qry, null, Get_TrxName()));

                if (amtdimAmt != GetTrxAmt())
                {
                    resetAmtDim = true;
                    Set_Value("AmtDimTrxAmount", null);
                }
            }

            // Reset Amount Dimension if charge Amount is different
            if (Util.GetValueOfInt(Get_Value("AmtDimChargeAmount")) > 0)
            {
                string  qry       = "SELECT Amount FROM C_DimAmt WHERE C_DimAmt_ID=" + Util.GetValueOfInt(Get_Value("AmtDimChargeAmount"));
                decimal amtdimAmt = Util.GetValueOfDecimal(DB.ExecuteScalar(qry, null, Get_TrxName()));

                if (amtdimAmt != GetChargeAmt())
                {
                    resetAmtDim = true;
                    Set_Value("AmtDimChargeAmount", null);
                }
            }
            return(true);
        }
Пример #15
0
 public bool SetProductQty(int recordID, string keyColName, List <string> product, List <string> attribute, List <string> qty, List <string> qtybook, List <string> oline_ID, int ordID, List <string> locID, int lineID, VAdvantage.Utility.Ctx ctx)
 {
     if (keyColName.ToUpper().Trim() == "C_ORDER_ID")
     {
         MOrder ord = new MOrder(ctx, recordID, null);
         for (int i = 0; i < product.Count; i++)
         {
             MOrderLine oline = new MOrderLine(ctx, lineID, null);
             oline.SetAD_Client_ID(ord.GetAD_Client_ID());
             oline.SetAD_Org_ID(ord.GetAD_Org_ID());
             oline.SetM_Product_ID(Util.GetValueOfInt(product[i]));
             oline.SetQty(Util.GetValueOfDecimal(qty[i]));
             oline.SetC_Order_ID(recordID);
             if (Util.GetValueOfInt(attribute[i]) != 0)
             {
                 oline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i]));
             }
             if (!ord.IsSOTrx())
             {
                 MProduct pro    = new MProduct(ctx, oline.GetM_Product_ID(), null);
                 String   qryUom = "SELECT vdr.C_UOM_ID FROM M_Product p LEFT JOIN M_Product_Po vdr ON p.M_Product_ID= vdr.M_Product_ID WHERE p.M_Product_ID=" + oline.GetM_Product_ID() + " AND vdr.C_BPartner_ID = " + ord.GetC_BPartner_ID();
                 int      uom    = Util.GetValueOfInt(DB.ExecuteScalar(qryUom));
                 if (pro.GetC_UOM_ID() != 0)
                 {
                     if (pro.GetC_UOM_ID() != uom && uom != 0)
                     {
                         decimal?Res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND M_Product_ID= " + oline.GetM_Product_ID() + " AND IsActive='Y'"));
                         if (Res > 0)
                         {
                             oline.SetQtyEntered(oline.GetQtyEntered() * Res);
                             //OrdQty = MUOMConversion.ConvertProductTo(GetCtx(), _M_Product_ID, UOM, OrdQty);
                         }
                         else
                         {
                             decimal?res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND IsActive='Y'"));
                             if (res > 0)
                             {
                                 oline.SetQtyEntered(oline.GetQtyEntered() * res);
                                 //OrdQty = MUOMConversion.Convert(GetCtx(), prdUOM, UOM, OrdQty);
                             }
                         }
                         oline.SetC_UOM_ID(uom);
                     }
                     else
                     {
                         oline.SetC_UOM_ID(pro.GetC_UOM_ID());
                     }
                 }
             }
             if (!oline.Save())
             {
             }
         }
     }
     else if (keyColName.ToUpper().Trim() == "C_INVOICE_ID")
     {
         MInvoice inv = new MInvoice(ctx, recordID, null);
         for (int i = 0; i < product.Count; i++)
         {
             MInvoiceLine invline = new MInvoiceLine(ctx, lineID, null);
             invline.SetAD_Client_ID(inv.GetAD_Client_ID());
             invline.SetAD_Org_ID(inv.GetAD_Org_ID());
             invline.SetM_Product_ID(Util.GetValueOfInt(product[i]));
             invline.SetQty(Util.GetValueOfDecimal(qty[i]));
             invline.SetC_Invoice_ID(recordID);
             if (Util.GetValueOfInt(attribute[i]) != 0)
             {
                 invline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i]));
             }
             if (!inv.IsSOTrx())
             {
                 MProduct pro    = new MProduct(ctx, invline.GetM_Product_ID(), null);
                 String   qryUom = "SELECT vdr.C_UOM_ID FROM M_Product p LEFT JOIN M_Product_Po vdr ON p.M_Product_ID= vdr.M_Product_ID WHERE p.M_Product_ID=" + invline.GetM_Product_ID() + " AND vdr.C_BPartner_ID = " + inv.GetC_BPartner_ID();
                 int      uom    = Util.GetValueOfInt(DB.ExecuteScalar(qryUom));
                 if (pro.GetC_UOM_ID() != 0)
                 {
                     if (pro.GetC_UOM_ID() != uom && uom != 0)
                     {
                         decimal?Res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND M_Product_ID= " + invline.GetM_Product_ID() + " AND IsActive='Y'"));
                         if (Res > 0)
                         {
                             invline.SetQtyEntered(invline.GetQtyEntered() * Res);
                             //OrdQty = MUOMConversion.ConvertProductTo(GetCtx(), _M_Product_ID, UOM, OrdQty);
                         }
                         else
                         {
                             decimal?res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND IsActive='Y'"));
                             if (res > 0)
                             {
                                 invline.SetQtyEntered(invline.GetQtyEntered() * res);
                                 //OrdQty = MUOMConversion.Convert(GetCtx(), prdUOM, UOM, OrdQty);
                             }
                         }
                         invline.SetC_UOM_ID(uom);
                     }
                     else
                     {
                         invline.SetC_UOM_ID(pro.GetC_UOM_ID());
                     }
                 }
             }
             if (!invline.Save())
             {
             }
         }
     }
     else if (keyColName.ToUpper().Trim() == "M_INOUT_ID")
     {
         MInOut inv = new MInOut(ctx, recordID, null);
         if (ordID > 0)
         {
             inv.SetC_Order_ID(ordID);
         }
         if (inv.Save())
         {
             for (int i = 0; i < product.Count; i++)
             {
                 MInOutLine ioline = new MInOutLine(ctx, lineID, null);
                 ioline.SetAD_Client_ID(inv.GetAD_Client_ID());
                 ioline.SetAD_Org_ID(inv.GetAD_Org_ID());
                 ioline.SetM_Product_ID(Util.GetValueOfInt(product[i]));
                 ioline.SetQty(Util.GetValueOfDecimal(qty[i]));
                 ioline.SetM_InOut_ID(recordID);
                 ioline.SetC_OrderLine_ID(Util.GetValueOfInt(oline_ID[i]));
                 ioline.SetM_Locator_ID(Util.GetValueOfInt(locID[i]));
                 if (Util.GetValueOfInt(attribute[i]) != 0)
                 {
                     ioline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i]));
                 }
                 if (!inv.IsSOTrx())
                 {
                     MProduct pro    = new MProduct(ctx, ioline.GetM_Product_ID(), null);
                     String   qryUom = "SELECT vdr.C_UOM_ID FROM M_Product p LEFT JOIN M_Product_Po vdr ON p.M_Product_ID= vdr.M_Product_ID WHERE p.M_Product_ID=" + ioline.GetM_Product_ID() + " AND vdr.C_BPartner_ID = " + inv.GetC_BPartner_ID();
                     int      uom    = Util.GetValueOfInt(DB.ExecuteScalar(qryUom));
                     if (pro.GetC_UOM_ID() != 0)
                     {
                         if (pro.GetC_UOM_ID() != uom && uom != 0)
                         {
                             decimal?Res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND M_Product_ID= " + ioline.GetM_Product_ID() + " AND IsActive='Y'"));
                             if (Res > 0)
                             {
                                 ioline.SetQtyEntered(ioline.GetQtyEntered() * Res);
                                 //OrdQty = MUOMConversion.ConvertProductTo(GetCtx(), _M_Product_ID, UOM, OrdQty);
                             }
                             else
                             {
                                 decimal?res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND IsActive='Y'"));
                                 if (res > 0)
                                 {
                                     ioline.SetQtyEntered(ioline.GetQtyEntered() * res);
                                     //OrdQty = MUOMConversion.Convert(GetCtx(), prdUOM, UOM, OrdQty);
                                 }
                             }
                             ioline.SetC_UOM_ID(uom);
                         }
                         else
                         {
                             ioline.SetC_UOM_ID(pro.GetC_UOM_ID());
                         }
                     }
                 }
                 if (!ioline.Save())
                 {
                 }
             }
         }
     }
     else if (keyColName.ToUpper().Trim() == "M_PACKAGE_ID")
     {
         MPackage pkg = new MPackage(ctx, recordID, null);
         for (int i = 0; i < product.Count; i++)
         {
             MPackageLine mline = new MPackageLine(ctx, lineID, null);
             mline.SetAD_Client_ID(pkg.GetAD_Client_ID());
             mline.SetAD_Org_ID(pkg.GetAD_Org_ID());
             mline.SetM_Product_ID(Util.GetValueOfInt(product[i]));
             mline.SetQty(Util.GetValueOfDecimal(qty[i]));
             if (Util.GetValueOfInt(oline_ID[i]) > 0)
             {
                 mline.SetM_MovementLine_ID(Util.GetValueOfInt(oline_ID[i]));
                 MMovementLine mov = new MMovementLine(ctx, Util.GetValueOfInt(oline_ID[i]), null);
                 mline.SetDTD001_TotalQty(mov.GetMovementQty());
             }
             if (Util.GetValueOfInt(attribute[i]) != 0)
             {
                 mline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i]));
             }
             mline.SetM_Package_ID(recordID);
             if (!mline.Save())
             {
             }
         }
     }
     else if (keyColName.ToUpper().Trim() == "M_INVENTORY_ID")
     {
         MInventory inv = new MInventory(ctx, recordID, null);
         for (int i = 0; i < product.Count; i++)
         {
             MInventoryLine invline = new MInventoryLine(ctx, lineID, null);
             invline.SetAD_Client_ID(inv.GetAD_Client_ID());
             invline.SetAD_Org_ID(inv.GetAD_Org_ID());
             invline.SetM_Locator_ID(Util.GetValueOfInt(locID[i]));
             invline.SetM_Product_ID(Util.GetValueOfInt(product[i]));
             invline.SetQtyCount(Util.GetValueOfDecimal(qty[i]));
             invline.SetQtyBook(Util.GetValueOfDecimal(qtybook[i]));
             invline.SetAsOnDateCount(Util.GetValueOfDecimal(qty[i]));
             invline.SetOpeningStock(Util.GetValueOfDecimal(qtybook[i]));
             invline.SetM_Inventory_ID(recordID);
             if (Util.GetValueOfInt(attribute[i]) != 0)
             {
                 invline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i]));
             }
             else
             {
                 invline.SetM_AttributeSetInstance_ID(0);
             }
             if (!invline.Save())
             {
             }
         }
     }
     return(true);
 }
        /// <summary>
        /// Create actual Payment
        /// </summary>
        /// <param name="C_Invoice_ID">invoice</param>
        /// <param name="C_BPartner_ID">partner ignored when invoice exists</param>
        /// <param name="C_Currency_ID">currency</param>
        /// <param name="StmtAmt">statement amount</param>
        /// <param name="TrxAmt">transaction amt</param>
        /// <param name="C_BankAccount_ID">bank account</param>
        /// <param name="DateTrx">transaction date</param>
        /// <param name="DateAcct">accounting date</param>
        /// <param name="Description">description</param>
        /// <param name="AD_Org_ID"></param>
        /// <returns>payment</returns>
        private MPayment CreatePayment(int C_Invoice_ID, int C_BPartner_ID,
                                       int C_Currency_ID, Decimal stmtAmt, Decimal trxAmt,
                                       int C_BankAccount_ID, DateTime?dateTrx, DateTime?dateAcct,
                                       String description, int AD_Org_ID)
        {
            //	Trx Amount = Payment overwrites Statement Amount if defined
            Decimal payAmt = trxAmt;

            if (Env.ZERO.CompareTo(payAmt) == 0)
            {
                payAmt = stmtAmt;
            }
            if (C_Invoice_ID == 0 && (Env.ZERO.CompareTo(payAmt) == 0))
            {
                throw new Exception("@PayAmt@ = 0");
            }
            //if (payAmt == null)
            //{
            //    payAmt = Env.ZERO;
            //}
            //
            MPayment payment = new MPayment(GetCtx(), 0, Get_Trx());

            payment.SetAD_Org_ID(AD_Org_ID);
            payment.SetC_BankAccount_ID(C_BankAccount_ID);
            payment.SetTenderType(MPayment.TENDERTYPE_Check);
            if (dateTrx != null)
            {
                payment.SetDateTrx(dateTrx);
            }
            else if (dateAcct != null)
            {
                payment.SetDateTrx(dateAcct);
            }
            if (dateAcct != null)
            {
                payment.SetDateAcct(dateAcct);
            }
            else
            {
                payment.SetDateAcct(payment.GetDateTrx());
            }
            payment.SetDescription(description);
            //
            if (C_Invoice_ID != 0)
            {
                MInvoice invoice = new MInvoice(GetCtx(), C_Invoice_ID, null);
                payment.SetC_DocType_ID(invoice.IsSOTrx());             //	Receipt
                payment.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                payment.SetC_BPartner_ID(invoice.GetC_BPartner_ID());
                if (Env.Signum(payAmt) != 0)    //	explicit Amount
                {
                    payment.SetC_Currency_ID(C_Currency_ID);
                    if (invoice.IsSOTrx())
                    {
                        payment.SetPayAmt(payAmt);
                    }
                    else        //	payment is likely to be negative
                    {
                        payment.SetPayAmt(Decimal.Negate(payAmt));
                    }
                    payment.SetOverUnderAmt(Decimal.Subtract(invoice.GetGrandTotal(true), payment.GetPayAmt()));
                }
                else    // set Pay Amout from Invoice
                {
                    payment.SetC_Currency_ID(invoice.GetC_Currency_ID());
                    payment.SetPayAmt(invoice.GetGrandTotal(true));
                }
            }
            else if (C_BPartner_ID != 0)
            {
                payment.SetC_BPartner_ID(C_BPartner_ID);
                payment.SetC_Currency_ID(C_Currency_ID);
                if (Env.Signum(payAmt) < 0)     //	Payment
                {
                    payment.SetPayAmt(Math.Abs(payAmt));
                    payment.SetC_DocType_ID(false);
                }
                else    //	Receipt
                {
                    payment.SetPayAmt(payAmt);
                    payment.SetC_DocType_ID(true);
                }
            }
            else
            {
                return(null);
            }
            payment.Save();
            //
            payment.ProcessIt(MPayment.DOCACTION_Complete);
            payment.Save();
            return(payment);
        }
Пример #17
0
        // Create Asset From Invoice Mohit

        /**
         *  Shipment Constructor
         *  @param Invoice
         *	@param shipLine shipment line
         *	@param deliveryCount 0 or number of delivery
         */
        public MAsset(MInvoice invoice, MInvoiceLine invoiceline, int deliveryCount)
            : this(invoiceline.GetCtx(), 0, invoiceline.Get_TrxName())
        {
            SetClientOrg(invoiceline);

            SetValueNameDescription(invoice, invoiceline, deliveryCount);
            //	Header

            //SetIsOwned(true);
            SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            SetC_BPartner_Location_ID(invoice.GetC_BPartner_Location_ID());
            SetAD_User_ID(invoice.GetAD_User_ID());
            //SetM_Locator_ID(invoice.GetM_Locator_ID());
            SetIsInPosession(true);


            SetAssetServiceDate(invoice.GetDateAcct());


            //	Line
            MProduct product = invoiceline.GetProduct();

            SetM_Product_ID(product.GetM_Product_ID());
            SetA_Asset_Group_ID(product.GetA_Asset_Group_ID());

            //////////////////////////////*
            //Changes for vafam
            // SetAssetServiceDate(shipment.GetMovementDate());
            //SetGuaranteeDate(TimeUtil.AddDays(shipment.GetMovementDate(), product.GetGuaranteeDays()));
            MAssetGroup _assetGroup = new MAssetGroup(GetCtx(), GetA_Asset_Group_ID(), invoice.Get_TrxName());

            if (_assetGroup.IsOwned())
            {
                SetIsOwned(true);
                //SetC_BPartner_ID(0);
            }
            if (_assetGroup.IsDepreciated())
            {
                SetIsDepreciated(true);
                SetIsFullyDepreciated(false);
            }
            ////////////////////////////////////
            //Change by Sukhwinder for setting Asset type and amortization template on Asset window, MANTIS ID:1762
            int countVA038 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA038_' "));
            int countVAFAM = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VAFAM_' "));

            if (countVA038 > 0)
            {
                Set_Value("VA038_AmortizationTemplate_ID", Utility.Util.GetValueOfInt(_assetGroup.Get_Value("VA038_AmortizationTemplate_ID")));
            }
            if (countVAFAM > 0)
            {
                Set_Value("VAFAM_AssetType", _assetGroup.Get_Value("VAFAM_AssetType").ToString());
                Set_Value("VAFAM_DepreciationType_ID", Utility.Util.GetValueOfInt(_assetGroup.Get_Value("VAFAM_DepreciationType_ID")));
            }

            ////////////////////////////////////

            //	Guarantee & Version
            SetGuaranteeDate(TimeUtil.AddDays(invoice.GetDateInvoiced(), product.GetGuaranteeDays()));
            SetVersionNo(product.GetVersionNo());
            if (invoiceline.GetM_AttributeSetInstance_ID() != 0)                //	Instance
            {
                MAttributeSetInstance asi = new MAttributeSetInstance(GetCtx(), invoiceline.GetM_AttributeSetInstance_ID(), Get_TrxName());
                SetM_AttributeSetInstance_ID(asi.GetM_AttributeSetInstance_ID());
                SetLot(asi.GetLot());
                SetSerNo(asi.GetSerNo());
            }
            SetHelp(invoiceline.GetDescription());
            //	Qty
            int units = product.GetSupportUnits();

            if (units == 0)
            {
                units = 1;
            }
            if (deliveryCount != 0)             //	one asset per UOM
            {
                SetQty(invoiceline.GetQtyEntered(), units);
            }
            else
            {
                SetQty((Decimal)units);
            }
            SetM_InOutLine_ID(invoiceline.GetM_InOutLine_ID());
            Set_Value("C_InvoiceLine_ID", invoiceline.GetC_InvoiceLine_ID());

            //	Activate
            MAssetGroup ag = MAssetGroup.Get(GetCtx(), GetA_Asset_Group_ID());

            if (!ag.IsCreateAsActive())
            {
                SetIsActive(false);
            }
        }
Пример #18
0
        }       //	allocateBPartnerAll

        /// <summary>
        ///	Allocate Oldest First using Accounting currency
        /// </summary>
        /// <returns>allocations</returns>
        private int AllocateBPOldestFirst()
        {
            int      _C_Currency_ID = MClient.Get(GetCtx()).GetC_Currency_ID();
            DateTime?_dateAcct      = null;
            //	Payments
            Decimal _totalPayments = Env.ZERO;

            for (int p = 0; p < _payments.Length; p++)
            {
                MPayment _payment = _payments[p];
                if (_payment.IsAllocated())
                {
                    continue;
                }
                if (_payment.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                Decimal _allocatedAmt = Utility.Util.GetValueOfDecimal(_payment.GetAllocatedAmt());
                log.Info(_payment + ", Allocated=" + _allocatedAmt);
                Decimal _availableAmt = Decimal.Add(Decimal.Add(Decimal.Add(_payment.GetPayAmt(),
                                                                            _payment.GetDiscountAmt()),
                                                                _payment.GetWriteOffAmt()),
                                                    _payment.GetOverUnderAmt());
                if (!_payment.IsReceipt())
                {
                    _availableAmt = Decimal.Negate(_availableAmt);
                }
                log.Fine("Available=" + _availableAmt);
                if (_dateAcct == null || _payment.GetDateAcct() > (_dateAcct))
                {
                    _dateAcct = Utility.Util.GetValueOfDateTime(_payment.GetDateAcct());
                }
                _totalPayments = Decimal.Add(_totalPayments, (_availableAmt));
            }
            //	Invoices
            Decimal _totalInvoices = Env.ZERO;

            for (int i = 0; i < _invoices.Length; i++)
            {
                MInvoice _invoice = _invoices[i];
                if (_invoice.IsPaid())
                {
                    continue;
                }
                if (_invoice.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                Decimal _openAmt = Utility.Util.GetValueOfDecimal(_invoice.GetOpenAmt(true, null));
                log.Fine("" + _invoice);
                if (!_invoice.IsSOTrx())
                {
                    _openAmt = Decimal.Negate(_openAmt);
                }
                //	Foreign currency
                log.Fine("Open=" + _openAmt);
                if (_dateAcct == null || _invoice.GetDateAcct() > (_dateAcct))
                {
                    _dateAcct = _invoice.GetDateAcct();
                }
                _totalInvoices = Decimal.Add(_totalInvoices, _openAmt);
            }

            //	must be either AP or AR balance
            if (Env.Signum(_totalInvoices) != Env.Signum(_totalPayments))
            {
                log.Fine("Signum - Invoices=" + Env.Signum(_totalInvoices)
                         + " <> Payments=" + Env.Signum(_totalPayments));
                return(0);
            }

            Decimal _difference = Decimal.Subtract(_totalInvoices, _totalPayments);
            //Decimal _maxAmt = _totalInvoices.abs().min(_totalPayments.abs());
            Decimal _maxAmt = Math.Min(Math.Abs(_totalInvoices), Math.Abs(_totalPayments));

            if (Env.Signum(_totalInvoices) < 0)
            {
                _maxAmt = Decimal.Negate(_maxAmt);
            }
            log.Info("= Invoices=" + _totalInvoices
                     + " - Payments=" + _totalPayments
                     + " = Difference=" + _difference + " - Max=" + _maxAmt);


            //	Allocate Payments up to max
            Decimal _allocatedPayments = Env.ZERO;

            for (int p = 0; p < _payments.Length; p++)
            {
                MPayment _payment = _payments[p];
                if (_payment.IsAllocated())
                {
                    continue;
                }
                if (_payment.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                Decimal _allocatedAmt = Utility.Util.GetValueOfDecimal(_payment.GetAllocatedAmt());
                if (Env.Signum(_allocatedAmt) != 0)
                {
                    continue;
                }
                Decimal _availableAmt = Decimal.Add(Decimal.Add(Decimal.Add(_payment.GetPayAmt(),
                                                                            _payment.GetDiscountAmt()),
                                                                _payment.GetWriteOffAmt()),
                                                    _payment.GetOverUnderAmt());
                if (!_payment.IsReceipt())
                {
                    _availableAmt = Decimal.Negate(_availableAmt);
                }
                _allocatedPayments = Decimal.Add(_allocatedPayments, _availableAmt);
                if ((Env.Signum(_totalInvoices) > 0 && _allocatedPayments.CompareTo(_maxAmt) > 0) ||
                    (Env.Signum(_totalInvoices) < 0 && _allocatedPayments.CompareTo(_maxAmt) < 0))
                {
                    Decimal _diff = Decimal.Subtract(_allocatedPayments, _maxAmt);
                    _availableAmt      = Decimal.Subtract(_availableAmt, _diff);
                    _allocatedPayments = Decimal.Subtract(_allocatedPayments, _diff);
                }
                log.Fine("Payment Allocated=" + _availableAmt);
                if (!CreateAllocation(_C_Currency_ID, "BP Oldest (" + Math.Abs(_difference) + ")",
                                      _dateAcct, _availableAmt, null, null, null,
                                      _payment.GetC_BPartner_ID(), _payment.GetC_Payment_ID(), 0, _payment.GetAD_Org_ID()))
                {
                    throw new Exception("Cannot create Allocation");
                }
                if (_allocatedPayments.CompareTo(_maxAmt) == 0)
                {
                    break;
                }
            }   //	for all payments
            //	Allocated Invoices up to max
            Decimal _allocatedInvoices = Env.ZERO;

            for (int i = 0; i < _invoices.Length; i++)
            {
                MInvoice _invoice = _invoices[i];
                if (_invoice.IsPaid())
                {
                    continue;
                }
                if (_invoice.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                Decimal _openAmt = Utility.Util.GetValueOfDecimal(_invoice.GetOpenAmt(true, null));
                if (!_invoice.IsSOTrx())
                {
                    _openAmt = Decimal.Negate(_openAmt);
                }
                _allocatedInvoices = Decimal.Add(_allocatedInvoices, _openAmt);
                if ((Env.Signum(_totalInvoices) > 0 && _allocatedInvoices.CompareTo(_maxAmt) > 0) ||
                    (Env.Signum(_totalInvoices) < 0 && _allocatedInvoices.CompareTo(_maxAmt) < 0))
                {
                    Decimal _diff = Decimal.Subtract(_allocatedInvoices, _maxAmt);
                    _openAmt           = Decimal.Subtract(_openAmt, _diff);
                    _allocatedInvoices = Decimal.Subtract(_allocatedInvoices, _diff);
                }
                if (Env.Signum(_openAmt) == 0)
                {
                    break;
                }
                log.Fine("Invoice Allocated=" + _openAmt);
                if (!CreateAllocation(_C_Currency_ID, "BP Oldest (" + Math.Abs(_difference) + ")",
                                      _dateAcct, _openAmt, null, null, null,
                                      _invoice.GetC_BPartner_ID(), 0, _invoice.GetC_Invoice_ID(), _invoice.GetAD_Org_ID()))
                {
                    throw new Exception("Cannot create Allocation");
                }
                if (_allocatedInvoices.CompareTo(_maxAmt) == 0)
                {
                    break;
                }
            }   //	for all invoices

            if (_allocatedPayments.CompareTo(_allocatedInvoices) != 0)
            {
                throw new Exception("Allocated Payments=" + _allocatedPayments
                                    + " <> Invoices=" + _allocatedInvoices);
            }
            ProcessAllocation();
            return(1);
        }       //	allocateOldestFirst
Пример #19
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());
        }
        /// <summary>
        /// Create actual Payment
        /// </summary>
        /// <param name="C_Invoice_ID">invoice</param>
        /// <param name="C_BPartner_ID">partner ignored when invoice exists</param>
        /// <param name="C_Currency_ID">currency</param>
        /// <param name="stmtAmt">statement amount</param>
        /// <param name="trxAmt">transaction amt</param>
        /// <param name="C_BankAccount_ID">bank account</param>
        /// <param name="dateTrx">transaction date</param>
        /// <param name="dateAcct">accounting date</param>
        /// <param name="description">description</param>
        /// <param name="AD_Org_ID"></param>
        /// <param name="C_ConversionType_ID">C_ConversionType_ID</param>
        /// <param name="C_Order_ID">C_Order_ID</param>
        /// <returns>payment</returns>
        private MPayment CreatePayment(int C_Invoice_ID, int C_BPartner_ID,
                                       int C_Currency_ID, Decimal stmtAmt, Decimal trxAmt,
                                       int C_BankAccount_ID, DateTime?dateTrx, DateTime?dateAcct,
                                       String description, int AD_Org_ID, int C_ConversionType_ID, int C_Order_ID)
        {
            //	Trx Amount = Payment overwrites Statement Amount if defined
            Decimal payAmt = trxAmt;

            if (Env.ZERO.CompareTo(payAmt) == 0)
            {
                payAmt = stmtAmt;
            }
            if (C_Invoice_ID == 0 && C_Order_ID == 0 && (Env.ZERO.CompareTo(payAmt) == 0))
            {
                throw new Exception("@PayAmt@ = 0");
            }
            //if (payAmt == null)
            //{
            //    payAmt = Env.ZERO;
            //}
            //
            MPayment payment = new MPayment(GetCtx(), 0, Get_Trx());

            payment.SetAD_Org_ID(AD_Org_ID);
            payment.SetC_BankAccount_ID(C_BankAccount_ID);
            //payment.SetTenderType(MPayment.TENDERTYPE_Check);//not required it will update on MPayment class
            //Get the C_ConversionType_ID from BankStatementLine and Set C_ConversionType_ID for Payment
            payment.SetC_ConversionType_ID(C_ConversionType_ID);
            if (dateTrx != null)
            {
                payment.SetDateTrx(dateTrx);
            }
            else if (dateAcct != null)
            {
                payment.SetDateTrx(dateAcct);
            }
            if (dateAcct != null)
            {
                payment.SetDateAcct(dateAcct);
            }
            else
            {
                payment.SetDateAcct(payment.GetDateTrx());
            }
            payment.SetDescription(description);
            //
            if (C_Invoice_ID != 0)
            {
                MInvoice invoice = new MInvoice(GetCtx(), C_Invoice_ID, Get_Trx()); //Used Trx
                payment.SetC_DocType_ID(invoice.IsSOTrx());                         //	Receipt
                payment.SetC_BPartner_ID(invoice.GetC_BPartner_ID());
                //set the BPartner Location from the Invoice
                payment.SetC_BPartner_Location_ID(invoice.GetC_BPartner_Location_ID());
                //set the PaymentMethod by the reference of Invoice
                payment.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                payment.SetC_Currency_ID(invoice.GetC_Currency_ID());
                decimal _dueAmt = 0;

                string  _sql = "SELECT * FROM C_InvoicePaySchedule WHERE VA009_PAIDAMNT IS NULL AND VA009_IsPaid = 'N' AND IsActive = 'Y' AND C_Invoice_ID =" + invoice.GetC_Invoice_ID();
                DataSet _ds  = DB.ExecuteDataset(_sql, null, Get_Trx());

                if (_ds != null && _ds.Tables[0].Rows.Count == 1)
                {
                    payment.SetC_Invoice_ID(invoice.GetC_Invoice_ID());//set Invoice Reference
                    payment.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[0]["C_INVOICEPAYSCHEDULE_ID"]));
                    _dueAmt = Util.GetValueOfDecimal(_ds.Tables[0].Rows[0]["DUEAMT"]);
                    //Set PayAmt -ve sign Incase of DocBaseType APC or ARC - IsReturnTrx is true
                    //Set PayAmt +ve sign Incase of DocBaseType API or ARI - IsReturnTrx is false
                    if (!invoice.IsReturnTrx())
                    {
                        payment.SetPayAmt(_dueAmt);
                    }
                    else    //	payment is likely to be negative
                    {
                        payment.SetPayAmt(Decimal.Negate(_dueAmt));
                    }
                    if (!payment.Save(Get_Trx()))
                    {
                        Get_Trx().Rollback();
                        ValueNamePair pp = VLogger.RetrieveError();
                        //to get Exact Error Message first get Value from GetName() else GetValue()
                        string error = pp != null?pp.GetName() : "";

                        if (string.IsNullOrEmpty(error))
                        {
                            error = pp != null?pp.GetValue() : "";

                            if (string.IsNullOrEmpty(error))
                            {
                                error = pp != null?pp.ToString() : "";
                            }
                        }
                        _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved";
                        return(null);
                    }
                }
                else if (_ds != null && _ds.Tables[0].Rows.Count > 1)
                {
                    if (!payment.Save(Get_Trx()))
                    {
                        Get_Trx().Rollback();
                        ValueNamePair pp = VLogger.RetrieveError();
                        //to get Exact Error Message first get Value from GetName() else GetValue()
                        string error = pp != null?pp.GetName() : "";

                        if (string.IsNullOrEmpty(error))
                        {
                            error = pp != null?pp.GetValue() : "";

                            if (string.IsNullOrEmpty(error))
                            {
                                error = pp != null?pp.ToString() : "";
                            }
                        }
                        _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved";
                        return(null);
                    }
                    else
                    {
                        //Initialize the Object for MPaymentAllocate class
                        MPaymentAllocate PayAlocate = null;
                        for (int i = 0; _ds.Tables[0].Rows.Count > i; i++)
                        {
                            //Create the Object for MPaymentAllocate class for every Iteration
                            PayAlocate = new MPaymentAllocate(GetCtx(), 0, Get_Trx());
                            PayAlocate.SetC_Payment_ID(payment.GetC_Payment_ID());
                            PayAlocate.SetAD_Client_ID(payment.GetAD_Client_ID());
                            //set Organization with the reference of Bank Account
                            PayAlocate.SetAD_Org_ID(payment.GetAD_Org_ID());//set Org_ID from the Header
                            PayAlocate.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                            PayAlocate.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[i]["C_INVOICEPAYSCHEDULE_ID"]));

                            //Set PayAmt -ve sign Incase of DocBaseType APC or ARC - IsReturnTrx is true
                            //Set PayAmt +ve sign Incase of DocBaseType API or ARI - IsReturnTrx is false
                            if (!invoice.IsReturnTrx())
                            {
                                PayAlocate.SetInvoiceAmt(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"]));
                                PayAlocate.SetAmount(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"]));
                            }
                            else
                            {
                                PayAlocate.SetInvoiceAmt(-1 * Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"]));
                                PayAlocate.SetAmount(-1 * Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"]));
                            }
                            if (!PayAlocate.Save(Get_Trx()))
                            {
                                Get_Trx().Rollback();
                                ValueNamePair pp = VLogger.RetrieveError();
                                //to get Exact Error Message first get Value from GetName() else GetValue()
                                string error = pp != null?pp.GetName() : "";

                                if (string.IsNullOrEmpty(error))
                                {
                                    error = pp != null?pp.GetValue() : "";

                                    if (string.IsNullOrEmpty(error))
                                    {
                                        error = pp != null?pp.ToString() : "";
                                    }
                                }
                                _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved";
                                return(null);
                            }
                        }
                    }
                }
            }
            else if (C_Order_ID > 0 && C_BPartner_ID > 0) // Create Payment for prePayOrder reference
            {
                MOrder order = new MOrder(GetCtx(), C_Order_ID, Get_Trx());
                payment.SetC_Order_ID(C_Order_ID);
                payment.SetC_DocType_ID(order.IsSOTrx()); //	Receipt
                payment.SetC_BPartner_ID(order.GetC_BPartner_ID());

                payment.SetC_BPartner_Location_ID(order.GetC_BPartner_Location_ID());
                payment.SetC_Currency_ID(order.GetC_Currency_ID());
                payment.SetVA009_PaymentMethod_ID(order.GetVA009_PaymentMethod_ID());
                payment.SetPayAmt(order.GetGrandTotal());
                if (!payment.Save(Get_Trx()))
                {
                    Get_Trx().Rollback();
                    ValueNamePair pp = VLogger.RetrieveError();
                    //to get Exact Error Message first get Value from GetName() else GetValue()
                    string error = pp != null?pp.GetName() : "";

                    if (string.IsNullOrEmpty(error))
                    {
                        error = pp != null?pp.GetValue() : "";

                        if (string.IsNullOrEmpty(error))
                        {
                            error = pp != null?pp.ToString() : "";
                        }
                    }
                    _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved";
                    return(null);
                }
            }
            else
            {
                _message = "VA012_ReferenceNotfoundtoCreatePayment";
                return(null);
            }
            //Commit the Transaction
            Get_Trx().Commit();
            //Call Complete Method to Complete the Record
            //149 is AD_Process_ID for C_Payment_Process
            _message = CompletePayment(GetCtx(), payment.GetC_Payment_ID(), 149, MPayment.DOCACTION_Complete);
            if (!string.IsNullOrEmpty(_message))
            {
                return(null);
            }
            return(payment);
        }
Пример #21
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();
            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)
            {
                MPayment 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);
                }
                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);
                }
            }

            //	Update Balance / Credit used - Counterpart of MInvoice.completeIt
            if (invoice != null)
            {
                if (invoice.TestAllocation() && !invoice.Save())
                {
                    log.Log(Level.SEVERE, "Invoice not updated - " + invoice);
                }
            }

            return(GetC_BPartner_ID());
        }
        /**
         *  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);
        }
Пример #23
0
        }       //	doIt

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

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

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

            //	Line
            MAllocationLine aLine = null;

            if (_CreatePayment)
            {
                aLine = new MAllocationLine(_m_alloc, OpenAmt,
                                            Env.ZERO, Env.ZERO, Env.ZERO);
                _m_payment.SetPayAmt(Decimal.Add(_m_payment.GetPayAmt(), OpenAmt));
                aLine.SetC_Payment_ID(_m_payment.GetC_Payment_ID());
            }
            else
            {
                aLine = new MAllocationLine(_m_alloc, Env.ZERO,
                                            Env.ZERO, OpenAmt, Env.ZERO);
            }
            aLine.SetC_Invoice_ID(C_Invoice_ID);
            if (aLine.Save())
            {
                AddLog(C_Invoice_ID, DateInvoiced, OpenAmt, DocumentNo);
                return(true);
            }
            //	Error
            log.Log(Level.SEVERE, "Cannot create allocation line for C_Invoice_ID=" + C_Invoice_ID);
            return(false);
        }       //	writeOff
Пример #24
0
        }       //	allocateIndividualPayments

        /// <summary>
        ///Allocate Payment:Invoice 1:1
        /// </summary>
        /// <returns>allocations</returns>
        private int AllocateBPOneToOne()
        {
            int _count = 0;

            for (int p = 0; p < _payments.Length; p++)
            {
                MPayment _payment = _payments[p];
                if (_payment.IsAllocated())
                {
                    continue;
                }
                Decimal _allocatedAmt = Utility.Util.GetValueOfDecimal(_payment.GetAllocatedAmt());
                log.Info(_payment + ", Allocated=" + _allocatedAmt);
                if (Env.Signum(_allocatedAmt) != 0)
                {
                    continue;
                }
                Decimal _availableAmt = Decimal.Add(Decimal.Add(Decimal.Add(_payment.GetPayAmt()
                                                                            , _payment.GetDiscountAmt())
                                                                , _payment.GetWriteOffAmt())
                                                    , _payment.GetOverUnderAmt());
                if (!_payment.IsReceipt())
                {
                    _availableAmt = Decimal.Negate(_availableAmt);
                }
                log.Fine("Available=" + _availableAmt);
                for (int i = 0; i < _invoices.Length; i++)
                {
                    MInvoice _invoice = _invoices[i];
                    if (_invoice == null || _invoice.IsPaid())
                    {
                        continue;
                    }
                    if (_payment.GetC_Currency_ID() == _invoice.GetC_Currency_ID())
                    {
                        //	log.fine("allocateBPartnerAll - " + _invoice);
                        Decimal _openAmt = Utility.Util.GetValueOfDecimal(_invoice.GetOpenAmt(true, null));
                        if (!_invoice.IsSOTrx())
                        {
                            _openAmt = Decimal.Negate(_openAmt);
                        }
                        Decimal _difference = Decimal.Subtract(_availableAmt, Math.Abs((_openAmt)));
                        log.Fine(_invoice + ", Open=" + _openAmt + " - Difference=" + _difference);
                        if (Env.Signum(_difference) == 0)
                        {
                            DateTime?_dateAcct = _payment.GetDateAcct();
                            if (_invoice.GetDateAcct() > _dateAcct)
                            {
                                _dateAcct = _invoice.GetDateAcct();
                            }
                            if (!CreateAllocation(_payment.GetC_Currency_ID(), "1:1 (" + _availableAmt + ")",
                                                  _dateAcct, _availableAmt, null, null, null,
                                                  _invoice.GetC_BPartner_ID(), _payment.GetC_Payment_ID(),
                                                  _invoice.GetC_Invoice_ID(), _invoice.GetAD_Org_ID()))
                            {
                                throw new Exception("Cannot create Allocation");
                            }
                            ProcessAllocation();
                            _count++;
                            _invoices[i] = null;                //	remove _invoice
                            _payments[p] = null;
                            _payment     = null;
                            break;
                        }
                    }
                    else        //	Multi-Currency
                    {
                    }
                } //	for all invoices
            }     //	for all payments
            return(_count);
        }         //	allocateOneToOne
Пример #25
0
        }         //	allocateOneToOne

        /// <summary>
        ///     Allocate all Payments/Invoices using Accounting currency
        /// </summary>
        /// <returns>allocations</returns>
        private int AllocateBPartnerAll()
        {
            int      _C_Currency_ID = MClient.Get(GetCtx()).GetC_Currency_ID();
            DateTime?_dateAcct      = null;
            //	Payments
            Decimal _totalPayments = Env.ZERO;

            for (int p = 0; p < _payments.Length; p++)
            {
                MPayment _payment = _payments[p];
                if (_payment.IsAllocated())
                {
                    continue;
                }
                Decimal _allocatedAmt = Utility.Util.GetValueOfDecimal(_payment.GetAllocatedAmt());
                //	log.info("allocateBPartnerAll - " + _payment + ", Allocated=" + _allocatedAmt);
                if (Env.Signum(_allocatedAmt) != 0)
                {
                    continue;
                }
                Decimal _availableAmt = Decimal.Add(Decimal.Add(Decimal.Add(_payment.GetPayAmt(),
                                                                            _payment.GetDiscountAmt()),
                                                                _payment.GetWriteOffAmt()),
                                                    _payment.GetOverUnderAmt());
                if (!_payment.IsReceipt())
                {
                    _availableAmt = Decimal.Negate(_availableAmt);
                }
                //	Foreign currency
                if (_payment.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                //	log.fine("allocateBPartnerAll - Available=" + _availableAmt);
                if (_dateAcct == null || _payment.GetDateAcct() > (_dateAcct))
                {
                    _dateAcct = _payment.GetDateAcct();
                }
                _totalPayments = Decimal.Add(_totalPayments, _availableAmt);
            }
            //	Invoices
            Decimal _totalInvoices = Env.ZERO;

            for (int i = 0; i < _invoices.Length; i++)
            {
                MInvoice _invoice = _invoices[i];
                if (_invoice.IsPaid())
                {
                    continue;
                }
                //	log.info("allocateBPartnerAll - " + _invoice);
                Decimal _openAmt = Utility.Util.GetValueOfDecimal(_invoice.GetOpenAmt(true, null));
                if (!_invoice.IsSOTrx())
                {
                    _openAmt = Decimal.Negate(_openAmt);
                }
                //	Foreign currency
                if (_invoice.GetC_Currency_ID() != _C_Currency_ID)
                {
                    continue;
                }
                //	log.fine("allocateBPartnerAll - Open=" + _openAmt);
                if (_dateAcct == null || _invoice.GetDateAcct() > (_dateAcct))
                {
                    _dateAcct = _invoice.GetDateAcct();
                }
                _totalInvoices = Decimal.Add(_totalInvoices, _openAmt);
            }

            Decimal _difference = Decimal.Subtract(_totalInvoices, _totalPayments);

            log.Info("= Invoices=" + _totalInvoices
                     + " - Payments=" + _totalPayments
                     + " = Difference=" + _difference);

            if (Env.Signum(_difference) == 0)
            {
                for (int p = 0; p < _payments.Length; p++)
                {
                    MPayment _payment = _payments[p];
                    if (_payment.IsAllocated())
                    {
                        continue;
                    }
                    Decimal _allocatedAmt = Utility.Util.GetValueOfDecimal(_payment.GetAllocatedAmt());
                    if (Env.Signum(_allocatedAmt) != 0)
                    {
                        continue;
                    }
                    Decimal _availableAmt = Decimal.Add(Decimal.Add(Decimal.Add(_payment.GetPayAmt(),
                                                                                _payment.GetDiscountAmt()),
                                                                    _payment.GetWriteOffAmt()),
                                                        _payment.GetOverUnderAmt());
                    if (!_payment.IsReceipt())
                    {
                        _availableAmt = Decimal.Negate(_availableAmt);
                    }
                    //	Foreign currency
                    if (_payment.GetC_Currency_ID() != _C_Currency_ID)
                    {
                        continue;
                    }
                    if (!CreateAllocation(_C_Currency_ID, "BP All",
                                          _dateAcct, _availableAmt, null, null, null,
                                          _payment.GetC_BPartner_ID(), _payment.GetC_Payment_ID(), 0, _payment.GetAD_Org_ID()))
                    {
                        throw new Exception("Cannot create Allocation");
                    }
                }       //	for all payments
                //
                for (int i = 0; i < _invoices.Length; i++)
                {
                    MInvoice _invoice = _invoices[i];
                    if (_invoice.IsPaid())
                    {
                        continue;
                    }
                    Decimal _openAmt = Utility.Util.GetValueOfDecimal(_invoice.GetOpenAmt(true, null));
                    if (!_invoice.IsSOTrx())
                    {
                        _openAmt = Decimal.Negate(_openAmt);
                    }
                    //	Foreign currency
                    if (_invoice.GetC_Currency_ID() != _C_Currency_ID)
                    {
                        continue;
                    }
                    if (!CreateAllocation(_C_Currency_ID, "BP All",
                                          _dateAcct, _openAmt, null, null, null,
                                          _invoice.GetC_BPartner_ID(), 0, _invoice.GetC_Invoice_ID(), _invoice.GetAD_Org_ID()))
                    {
                        throw new Exception("Cannot create Allocation");
                    }
                }       //	for all invoices
                ProcessAllocation();
                return(1);
            }   //	Difference OK

            return(0);
        }       //	allocateBPartnerAll
        public static bool InsertForeignCostMatchInvoice(Ctx ctx, MInvoiceLine invoiceLine, decimal matchQty, int ASI, Trx trx)
        {
            int                  acctSchema_ID    = 0;
            int                  M_CostElement_ID = 0;
            int                  AD_Org_ID        = 0;
            int                  M_ASI_ID         = 0;
            MProduct             product          = null;
            MAcctSchema          acctSchema       = null;
            MCostForeignCurrency foreignCost      = null;
            dynamic              pc      = null;
            String               cl      = null;
            MInvoice             invoice = null;

            try
            {
                // if cost is calculated then not to calculate again
                if (invoiceLine.IsFutureCostCalculated())
                {
                    return(true);
                }

                invoice = new MInvoice(ctx, invoiceLine.GetC_Invoice_ID(), trx);

                if (!invoice.IsSOTrx() && !invoice.IsReturnTrx())
                {
                    acctSchema_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT asch.c_acctschema_id FROM c_acctschema asch INNER JOIN ad_clientinfo ci
                                    ON ci.c_acctschema1_id = asch.c_acctschema_id WHERE ci.ad_client_id  = " + invoice.GetAD_Client_ID()));
                    acctSchema    = new MAcctSchema(ctx, acctSchema_ID, trx);

                    if (acctSchema.GetC_Currency_ID() != invoice.GetC_Currency_ID())
                    {
                        // Get Costing Element of Av. Invoice
                        M_CostElement_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT M_CostElement_ID FROM M_CostElement WHERE AD_Client_ID = "
                                                                               + invoice.GetAD_Client_ID() + " AND IsActive = 'Y' AND CostingMethod = 'I'"));

                        product = new MProduct(ctx, invoiceLine.GetM_Product_ID(), trx);

                        if (product != null && product.GetProductType() == "I" && product.GetM_Product_ID() > 0) // for Item Type product
                        {
                            pc = MProductCategory.Get(product.GetCtx(), product.GetM_Product_Category_ID());

                            // Get Costing Level
                            if (pc != null)
                            {
                                cl = pc.GetCostingLevel();
                            }
                            if (cl == null)
                            {
                                cl = acctSchema.GetCostingLevel();
                            }

                            if (cl == "C" || cl == "B")
                            {
                                AD_Org_ID = 0;
                            }
                            else
                            {
                                AD_Org_ID = invoice.GetAD_Org_ID();
                            }
                            if (cl != "B")
                            {
                                M_ASI_ID = 0;
                            }
                            else
                            {
                                M_ASI_ID = ASI;
                            }

                            foreignCost = MCostForeignCurrency.Get(product, M_ASI_ID, AD_Org_ID, M_CostElement_ID, invoice.GetC_BPartner_ID(), invoice.GetC_Currency_ID());
                            foreignCost.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                            foreignCost.SetCumulatedQty(Decimal.Add(foreignCost.GetCumulatedQty(), matchQty));
                            foreignCost.SetCumulatedAmt(Decimal.Add(foreignCost.GetCumulatedAmt(), Decimal.Multiply(invoiceLine.GetPriceActual(), matchQty)));
                            if (foreignCost.GetCumulatedQty() != 0)
                            {
                                foreignCost.SetCostPerUnit(Decimal.Round(Decimal.Divide(foreignCost.GetCumulatedAmt(), foreignCost.GetCumulatedQty()), acctSchema.GetCostingPrecision()));
                            }
                            else
                            {
                                foreignCost.SetCostPerUnit(0);
                            }
                            if (!foreignCost.Save(trx))
                            {
                                ValueNamePair pp = VLogger.RetrieveError();
                                _log.Severe("Error occured during updating M_Cost_ForeignCurrency. Error name : " + pp.GetName() +
                                            " AND Error Value : " + pp.GetValue() + " , For Invoice line : " + invoiceLine.GetC_InvoiceLine_ID() +
                                            " , AND Ad_Client_ID : " + invoiceLine.GetAD_Client_ID());
                                return(false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Log(Level.SEVERE, "", ex);
                return(false);
            }
            return(true);
        }
Пример #27
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);
            }
        }
        /// <summary>
        /// Create Gl Journal Line
        /// </summary>
        /// <param name="Journal">GL Journal</param>
        /// <param name="Invoice">Invoice</param>
        /// <param name="InvoiceLine">Invoice Line</param>
        /// <param name="RevenueRecognitionPlan">Revenue Recognition Plan</param>
        /// <param name="TotalAmt">Sum of RecognizeAmt</param>
        /// <param name="RecognitionType">Recognition Type</param>
        /// <param name="k">loop variable</param>
        /// <returns>>Journal line object</returns>
        public MJournalLine GenerateJounalLine(MJournal Journal, MInvoice Invoice, MInvoiceLine InvoiceLine,
                                               MRevenueRecognitionPlan RevenueRecognitionPlan, Decimal TotalAmt, string RecognitionType, int k)
        {
            int combination_ID = 0;

            if (k == 0)
            {
                combination_ID = RevenueRun.GetCombinationID(InvoiceLine.GetM_Product_ID(), InvoiceLine.GetC_Charge_ID(), journal.GetC_AcctSchema_ID(), Invoice.IsSOTrx(), Invoice.IsReturnTrx(), totalAmt, RevenueRecognitionPlan.GetC_RevenueRecognition_ID());
                journalLine.SetLine(lineno);
                if (RecognitionType.Equals("E") && TotalAmt > 0)
                {
                    journalLine.SetAmtAcctDr(TotalAmt);
                    journalLine.SetAmtSourceDr(TotalAmt);
                    journalLine.SetAmtSourceCr(0);
                    journalLine.SetAmtAcctCr(0);
                }
                else if (RecognitionType.Equals("E") && TotalAmt < 0)
                {
                    journalLine.SetAmtAcctCr(Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceCr(Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceDr(0);
                    journalLine.SetAmtAcctDr(0);
                }
                else if (RecognitionType.Equals("R") && TotalAmt > 0)
                {
                    journalLine.SetAmtAcctCr(TotalAmt);
                    journalLine.SetAmtSourceCr(TotalAmt);
                    journalLine.SetAmtSourceDr(0);
                    journalLine.SetAmtAcctDr(0);
                }
                else if (RecognitionType.Equals("R") && TotalAmt < 0)
                {
                    journalLine.SetAmtAcctDr(Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceDr(Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceCr(0);
                    journalLine.SetAmtAcctCr(0);
                }
                int account_ID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT Account_ID From C_ValidCombination Where C_ValidCombination_ID=" + combination_ID));
                journalLine.Set_ValueNoCheck("Account_ID", account_ID);
                journalLine.Set_ValueNoCheck("C_BPartner_ID", Invoice.GetC_BPartner_ID());
                journalLine.SetAD_OrgTrx_ID(InvoiceLine.Get_ColumnIndex("AD_OrgTrx_ID") > 0 ? InvoiceLine.GetAD_OrgTrx_ID() : Invoice.GetAD_OrgTrx_ID());
                journalLine.Set_ValueNoCheck("C_Project_ID", InvoiceLine.GetC_Project_ID() > 0 ? InvoiceLine.GetC_Project_ID() : Invoice.Get_Value("C_ProjectRef_ID"));
                journalLine.Set_ValueNoCheck("C_Campaign_ID", InvoiceLine.Get_ColumnIndex("C_Campaign_ID") > 0 ? InvoiceLine.GetC_Campaign_ID() : Invoice.GetC_Campaign_ID());
                journalLine.Set_ValueNoCheck("C_Activity_ID", InvoiceLine.Get_ColumnIndex("C_Activity_ID") > 0 ? InvoiceLine.GetC_Activity_ID() : Invoice.GetC_Activity_ID());
                journalLine.Set_ValueNoCheck("M_Product_ID", InvoiceLine.GetM_Product_ID());
            }
            else
            {
                combination_ID = RevenueRun.GetCombinationID(0, 0, RevenueRecognitionPlan.GetC_AcctSchema_ID(), Invoice.IsSOTrx(), Invoice.IsReturnTrx(), totalAmt, RevenueRecognitionPlan.GetC_RevenueRecognition_ID());
                int account_ID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT Account_ID From C_ValidCombination Where C_ValidCombination_ID=" + combination_ID));

                journalLine = RevenueRun.GetOrCreate(journal, journalLine, InvoiceLine.GetM_Product_ID(), InvoiceLine.GetC_Charge_ID(),
                                                     InvoiceLine.Get_ColumnIndex("C_Campaign_ID") > 0 ? InvoiceLine.GetC_Campaign_ID() : Invoice.GetC_Campaign_ID(),
                                                     account_ID, InvoiceLine.GetC_Project_ID() > 0 ? InvoiceLine.GetC_Project_ID() : Util.GetValueOfInt(Invoice.Get_Value("C_ProjectRef_ID")),
                                                     InvoiceLine.Get_ColumnIndex("C_Activity_ID") > 0 ? InvoiceLine.GetC_Activity_ID() : Invoice.GetC_Activity_ID(), Invoice.GetC_BPartner_ID(),
                                                     Invoice.GetAD_Org_ID(), InvoiceLine.Get_ColumnIndex("AD_OrgTrx_ID") > 0 ? InvoiceLine.GetAD_OrgTrx_ID() : Invoice.GetAD_OrgTrx_ID());

                journalLine.SetLine(lineno);

                if (RecognitionType.Equals("E") && TotalAmt > 0)
                {
                    journalLine.SetAmtAcctCr(journalLine.GetAmtAcctCr() + TotalAmt);
                    journalLine.SetAmtSourceCr(journalLine.GetAmtSourceCr() + TotalAmt);
                    journalLine.SetAmtSourceDr(0);
                    journalLine.SetAmtAcctDr(0);
                }
                else if (RecognitionType.Equals("E") && TotalAmt < 0)
                {
                    journalLine.SetAmtAcctDr(journalLine.GetAmtAcctDr() + Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceDr(journalLine.GetAmtSourceDr() + Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceCr(0);
                    journalLine.SetAmtAcctCr(0);
                }
                else if (RecognitionType.Equals("R") && TotalAmt > 0)
                {
                    journalLine.SetAmtAcctDr(journalLine.GetAmtAcctDr() + TotalAmt);
                    journalLine.SetAmtSourceDr(journalLine.GetAmtSourceDr() + TotalAmt);
                    journalLine.SetAmtSourceCr(0);
                    journalLine.SetAmtAcctCr(0);
                }
                else if (RecognitionType.Equals("R") && TotalAmt < 0)
                {
                    journalLine.SetAmtAcctCr(journalLine.GetAmtAcctCr() + Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceCr(journalLine.GetAmtSourceCr() + Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceDr(0);
                    journalLine.SetAmtAcctDr(0);
                }
            }
            return(journalLine);
        }
Пример #29
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());
        }