/// <summary>
        ///  Before Save
        /// </summary>
        /// <param name="newRecord">new</param>
        /// <returns>true, on Save</returns>
        protected override Boolean BeforeSave(Boolean newRecord)
        {
            MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_TrxName());

            if ((newRecord || Is_ValueChanged("C_Invoice_ID")) &&
                (payment.GetC_Charge_ID() != 0 ||
                 payment.GetC_Invoice_ID() != 0 ||
                 payment.GetC_Order_ID() != 0))
            {
                log.SaveError("PaymentIsAllocated", "");
                return(false);
            }

            // during saving a new record, system will check same invoice schedule reference exist on same payment or not
            if (newRecord && Get_ColumnIndex("C_InvoicePaySchedule_ID") >= 0 && GetC_InvoicePaySchedule_ID() > 0)
            {
                if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(*) FROM C_PaymentAllocate   WHERE C_Payment_ID = " + GetC_Payment_ID() +
                                                        @" AND IsActive = 'Y' AND C_InvoicePaySchedule_ID = " + GetC_InvoicePaySchedule_ID(), null, Get_Trx())) > 0)
                {
                    //"Error" not required
                    //log.SaveError("Error", Msg.GetMsg(GetCtx(), "VIS_NotSaveDuplicateRecord"));
                    log.SaveError("", Msg.GetMsg(GetCtx(), "VIS_NotSaveDuplicateRecord"));
                    return(false);
                }
            }

            // check schedule is hold or not, if hold then no to save record
            if (Get_ColumnIndex("C_InvoicePaySchedule_ID") >= 0 && GetC_InvoicePaySchedule_ID() > 0)
            {
                if (payment.IsHoldpaymentSchedule(GetC_InvoicePaySchedule_ID()))
                {
                    log.SaveError("", Msg.GetMsg(GetCtx(), "VIS_PaymentisHold"));
                    return(false);
                }
            }

            if (!Env.IsModuleInstalled("VA009_"))
            {
                Decimal check = Decimal.Add(Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt()), GetOverUnderAmt());
                if (check.CompareTo(GetInvoiceAmt()) != 0)
                {
                    log.SaveError("Error", Msg.ParseTranslation(GetCtx(),
                                                                "@InvoiceAmt@(" + GetInvoiceAmt()
                                                                + ") <> @Totals@(" + check + ")"));
                    return(false);
                }
            }

            //	Org
            if (newRecord || Is_ValueChanged("C_Invoice_ID"))
            {
                GetInvoice();
                if (_invoice != null)
                {
                    SetAD_Org_ID(_invoice.GetAD_Org_ID());
                }
            }

            return(true);
        }
Ejemplo n.º 2
0
        /**
         *  Before Save
         *	@param newRecord new
         *	@return true
         */
        protected override Boolean BeforeSave(Boolean newRecord)
        {
            MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_TrxName());

            if ((newRecord || Is_ValueChanged("C_Invoice_ID")) &&
                (payment.GetC_Charge_ID() != 0 ||
                 payment.GetC_Invoice_ID() != 0 ||
                 payment.GetC_Order_ID() != 0))
            {
                log.SaveError("PaymentIsAllocated", "");
                return(false);
            }

            Decimal check = Decimal.Add(Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt()), GetOverUnderAmt());

            if (check.CompareTo(GetInvoiceAmt()) != 0)
            {
                log.SaveError("Error", Msg.ParseTranslation(GetCtx(),
                                                            "@InvoiceAmt@(" + GetInvoiceAmt()
                                                            + ") <> @Totals@(" + check + ")"));
                return(false);
            }

            //	Org
            if (newRecord || Is_ValueChanged("C_Invoice_ID"))
            {
                GetInvoice();
                if (_invoice != null)
                {
                    SetAD_Org_ID(_invoice.GetAD_Org_ID());
                }
            }

            return(true);
        }
        }       //	afterSave

        /// <summary>
        /// This function is used to set Values on Recognition Plan
        /// </summary>
        /// <param name="invoiceLine">invoice line object </param>
        /// <param name="invoice">invoice object</param>
        /// <param name="C_RevenueRecognition_ID">Recognition ID</param>
        /// <param name="ToCurrency">Currency</param>
        public void SetRecognitionPlan(MInvoiceLine invoiceLine, MInvoice invoice, int C_RevenueRecognition_ID, int ToCurrency)
        {
            SetAD_Client_ID(invoice.GetAD_Client_ID());
            SetAD_Org_ID(invoice.GetAD_Org_ID());
            SetC_Currency_ID(ToCurrency);
            SetC_InvoiceLine_ID(invoiceLine.GetC_InvoiceLine_ID());
            SetC_RevenueRecognition_ID(C_RevenueRecognition_ID);
            // when tax include into price list, then reduce tax from Line Net Amount
            bool    isTaxIncide = (new MPriceList(invoice.GetCtx(), invoice.GetM_PriceList_ID(), invoice.Get_Trx())).IsTaxIncluded();
            Decimal Amount      = invoiceLine.GetLineNetAmt() - (isTaxIncide ? (invoiceLine.GetTaxAmt() + invoiceLine.GetSurchargeAmt()) : 0);

            if (invoice.GetC_Currency_ID() != ToCurrency)
            {
                Amount = MConversionRate.Convert(GetCtx(), Amount, invoice.GetC_Currency_ID(), ToCurrency, invoice.GetDateInvoiced(), invoice.GetC_ConversionType_ID(), invoice.GetAD_Client_ID(), invoice.GetAD_Org_ID());
            }
            SetTotalAmt(Amount);
            SetRecognizedAmt(Env.ZERO);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// After Save
 /// </summary>
 /// <param name="newRecord"></param>
 /// <param name="success"></param>
 /// <returns>Success</returns>
 ///
 public void SetRecognitionPlan(MInvoiceLine invoiceLine, MInvoice invoice, int C_RevenueRecognition_ID)
 {
     try
     {
         SetAD_Client_ID(invoice.GetAD_Client_ID());
         SetAD_Org_ID(invoice.GetAD_Org_ID());
         SetC_Currency_ID(invoice.GetC_Currency_ID());
         SetC_InvoiceLine_ID(invoiceLine.GetC_InvoiceLine_ID());
         SetC_RevenueRecognition_ID(C_RevenueRecognition_ID);
         SetP_Revenue_Acct(0);
         SetUnEarnedRevenue_Acct(0);
         SetTotalAmt(invoiceLine.GetLineNetAmt());
         SetRecognizedAmt(Env.ZERO);
     }
     catch (Exception ex)
     {
         // MessageBox.Show("MInvoiceLine--SetInvoice");
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Create Facts (the accounting logic) for
        ///  MXI.
        ///     (single line)
        ///  <pre>
        ///      NotInvoicedReceipts     DR			(Receipt Org)
        ///      InventoryClearing               CR
        ///      InvoicePV               DR      CR  (difference)
        ///  Commitment
        ///         Expense							CR
        ///         Offset					DR
        ///  </pre>
        /// </summary>
        /// <param name="as1"></param>
        /// <returns></returns>
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            List <Fact> facts = new List <Fact>();

            //  Nothing to do
            if (GetM_Product_ID() == 0 ||                               //	no Product
                Env.Signum(GetQty().Value) == 0 ||
                Env.Signum(_receiptLine.GetMovementQty()) == 0)         //	Qty = 0
            {
                log.Fine("No Product/Qty - M_Product_ID=" + GetM_Product_ID()
                         + ",Qty=" + GetQty() + ",InOutQty=" + _receiptLine.GetMovementQty());
                return(facts);
            }
            MMatchInv matchInv = (MMatchInv)GetPO();

            //  create Fact Header
            Fact fact = new Fact(this, as1, Fact.POST_Actual);

            SetC_Currency_ID(as1.GetC_Currency_ID());

            /**	Needs to be handeled in PO Matching as1 no Receipt info
             * if (_pc.isService())
             * {
             *  log.Fine("Service - skipped");
             *  return fact;
             * }
             **/


            //  NotInvoicedReceipt      DR
            //  From Receipt
            Decimal  multiplier = Math.Abs(Decimal.Round(Decimal.Divide(GetQty().Value, _receiptLine.GetMovementQty()), 12, MidpointRounding.AwayFromZero));
            FactLine dr         = fact.CreateLine(null,
                                                  GetAccount(Doc.ACCTTYPE_NotInvoicedReceipts, as1),
                                                  as1.GetC_Currency_ID(), Env.ONE, null); // updated below

            if (dr == null)
            {
                _error = "No Product Costs";
                return(null);
            }
            dr.SetQty(GetQty());
            //	dr.setM_Locator_ID(_receiptLine.getM_Locator_ID());
            //	MInOut receipt = _receiptLine.getParent();
            //	dr.setLocationFromBPartner(receipt.getC_BPartner_Location_ID(), true);	//  from Loc
            //	dr.setLocationFromLocator(_receiptLine.getM_Locator_ID(), false);		//  to Loc
            Decimal temp = dr.GetAcctBalance();

            //	Set AmtAcctCr/Dr from Receipt (sets also Project)
            if (!dr.UpdateReverseLine(MInOut.Table_ID,          //	Amt updated
                                      _receiptLine.GetM_InOut_ID(), _receiptLine.GetM_InOutLine_ID(),
                                      multiplier))
            {
                _error = "Mat.Receipt not posted yet";
                return(null);
            }
            log.Fine("CR - Amt(" + temp + "->" + dr.GetAcctBalance()
                     + ") - " + dr.ToString());

            //  InventoryClearing               CR
            //  From Invoice
            MAccount expense = _pc.GetAccount(ProductCost.ACCTTYPE_P_InventoryClearing, as1);

            if (_pc.IsService())
            {
                expense = _pc.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1);
            }
            Decimal LineNetAmt = _invoiceLine.GetLineNetAmt();

            multiplier = Math.Abs(Decimal.Round(Decimal.Divide(GetQty().Value, _invoiceLine.GetQtyInvoiced()), 12, MidpointRounding.AwayFromZero));
            if (multiplier.CompareTo(Env.ONE) != 0)
            {
                LineNetAmt = Decimal.Multiply(LineNetAmt, multiplier);
            }
            if (_pc.IsService())
            {
                LineNetAmt = dr.GetAcctBalance();       //	book out exact receipt amt
            }
            FactLine cr = null;

            if (as1.IsAccrual())
            {
                cr = fact.CreateLine(null, expense,
                                     as1.GetC_Currency_ID(), null, LineNetAmt); //	updated below
                if (cr == null)
                {
                    log.Fine("Line Net Amt=0 - M_Product_ID=" + GetM_Product_ID()
                             + ",Qty=" + GetQty() + ",InOutQty=" + _receiptLine.GetMovementQty());
                    facts.Add(fact);
                    return(facts);
                }
                cr.SetQty(Decimal.Negate(GetQty().Value));
                temp = cr.GetAcctBalance();
                //	Set AmtAcctCr/Dr from Invoice (sets also Project)
                if (as1.IsAccrual() && !cr.UpdateReverseLine(MInvoice.Table_ID,                 //	Amt updated
                                                             _invoiceLine.GetC_Invoice_ID(), _invoiceLine.GetC_InvoiceLine_ID(), multiplier))
                {
                    _error = "Invoice not posted yet";
                    return(null);
                }
                log.Fine("DR - Amt(" + temp + "->" + cr.GetAcctBalance()
                         + ") - " + cr.ToString());
            }
            else        //	Cash Acct
            {
                MInvoice invoice = _invoiceLine.GetParent();
                if (as1.GetC_Currency_ID() == invoice.GetC_Currency_ID())
                {
                    LineNetAmt = MConversionRate.Convert(GetCtx(), LineNetAmt,
                                                         invoice.GetC_Currency_ID(), as1.GetC_Currency_ID(),
                                                         invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(),
                                                         invoice.GetAD_Client_ID(), invoice.GetAD_Org_ID());
                }
                cr = fact.CreateLine(null, expense,
                                     as1.GetC_Currency_ID(), null, LineNetAmt);

                cr.SetQty(Decimal.Negate(Decimal.Multiply(GetQty().Value, multiplier)));
            }
            cr.SetC_Activity_ID(_invoiceLine.GetC_Activity_ID());
            cr.SetC_Campaign_ID(_invoiceLine.GetC_Campaign_ID());
            cr.SetC_Project_ID(_invoiceLine.GetC_Project_ID());
            cr.SetC_UOM_ID(_invoiceLine.GetC_UOM_ID());
            cr.SetUser1_ID(_invoiceLine.GetUser1_ID());
            cr.SetUser2_ID(_invoiceLine.GetUser2_ID());


            //  Invoice Price Variance  difference
            Decimal ipv = Decimal.Negate(Decimal.Add(cr.GetAcctBalance(), dr.GetAcctBalance()));

            if (Env.Signum(ipv) != 0)
            {
                FactLine pv = fact.CreateLine(null,
                                              _pc.GetAccount(ProductCost.ACCTTYPE_P_IPV, as1),
                                              as1.GetC_Currency_ID(), ipv);
                pv.SetC_Activity_ID(_invoiceLine.GetC_Activity_ID());
                pv.SetC_Campaign_ID(_invoiceLine.GetC_Campaign_ID());
                pv.SetC_Project_ID(_invoiceLine.GetC_Project_ID());
                pv.SetC_UOM_ID(_invoiceLine.GetC_UOM_ID());
                pv.SetUser1_ID(_invoiceLine.GetUser1_ID());
                pv.SetUser2_ID(_invoiceLine.GetUser2_ID());
            }
            log.Fine("IPV=" + ipv + "; Balance=" + fact.GetSourceBalance());

            MInOut inOut       = _receiptLine.GetParent();
            bool   isReturnTrx = inOut.IsReturnTrx();

            if (!IsPosted())
            {
                //	Cost Detail Record - data from Expense/IncClearing (CR) record
                MCostDetail.CreateInvoice(as1, GetAD_Org_ID(),
                                          GetM_Product_ID(), matchInv.GetM_AttributeSetInstance_ID(),
                                          _invoiceLine.GetC_InvoiceLine_ID(), 0,                                                                                                                  //	No cost element
                                          Decimal.Negate(cr.GetAcctBalance()), isReturnTrx ? Decimal.Negate(Utility.Util.GetValueOfDecimal(GetQty())) : Utility.Util.GetValueOfDecimal(GetQty()), //	correcting
                                          GetDescription(), GetTrx(), GetRectifyingProcess());

                //  Update Costing
                UpdateProductInfo(as1.GetC_AcctSchema_ID(),
                                  MAcctSchema.COSTINGMETHOD_StandardCosting.Equals(as1.GetCostingMethod()));
            }
            //
            facts.Add(fact);

            /** Commitment release										****/
            if (as1.IsAccrual() && as1.IsCreateCommitment())
            {
                fact = Doc_Order.GetCommitmentRelease(as1, this,
                                                      Utility.Util.GetValueOfDecimal(GetQty()), _invoiceLine.GetC_InvoiceLine_ID(), Env.ONE);
                if (fact == null)
                {
                    return(null);
                }
                facts.Add(fact);
            }   //	Commitment

            return(facts);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Generate Invoices
        /// </summary>
        /// <param name="idr">pstmt order query</param>
        /// <returns>info</returns>
        //private String Generate(IDataReader idr)
        private String Generate(DataTable dt)
        {
            //JID_1139 Avoided the duplicate charge line created Invoice(customer)
            bool isAllownonItem = Util.GetValueOfString(GetCtx().GetContext("$AllowNonItem")).Equals("Y");

            foreach (DataRow dr in dt.Rows)
            {
                MOrder order = new MOrder(GetCtx(), dr, Get_TrxName());

                // Credit Limit check
                MBPartner bp = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID());
                if (bp.GetCreditStatusSettingOn() == "CH")
                {
                    decimal creditLimit = bp.GetSO_CreditLimit();
                    string  creditVal   = bp.GetCreditValidation();
                    if (creditLimit != 0)
                    {
                        decimal creditAvlb = creditLimit - bp.GetSO_CreditUsed();
                        if (creditAvlb <= 0)
                        {
                            if (creditVal == "C" || creditVal == "D" || creditVal == "F")
                            {
                                AddLog(Msg.GetMsg(GetCtx(), "StopInvoice") + bp.GetName());
                                continue;
                            }
                            else if (creditVal == "I" || creditVal == "J" || creditVal == "L")
                            {
                                if (_msg != null)
                                {
                                    _msg.Clear();
                                }
                                _msg.Append(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName());
                                //AddLog(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName());
                            }
                        }
                    }
                }
                // JID_0161 // change here now will check credit settings on field only on Business Partner Header // Lokesh Chauhan 15 July 2019
                else if (bp.GetCreditStatusSettingOn() == X_C_BPartner.CREDITSTATUSSETTINGON_CustomerLocation)
                {
                    MBPartnerLocation bpl = new MBPartnerLocation(GetCtx(), order.GetC_BPartner_Location_ID(), null);
                    //MBPartner bpartner = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID());
                    //if (bpl.GetCreditStatusSettingOn() == "CL")
                    //{
                    decimal creditLimit = bpl.GetSO_CreditLimit();
                    string  creditVal   = bpl.GetCreditValidation();
                    if (creditLimit != 0)
                    {
                        decimal creditAvlb = creditLimit - bpl.GetSO_CreditUsed();
                        if (creditAvlb <= 0)
                        {
                            if (creditVal == "C" || creditVal == "D" || creditVal == "F")
                            {
                                AddLog(Msg.GetMsg(GetCtx(), "StopInvoice") + bp.GetName() + " " + bpl.GetName());
                                continue;
                            }
                            else if (creditVal == "I" || creditVal == "J" || creditVal == "L")
                            {
                                if (_msg != null)
                                {
                                    _msg.Clear();
                                }
                                _msg.Append(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName() + " " + bpl.GetName());
                                //AddLog(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName() + " " + bpl.GetName());
                            }
                        }
                    }
                    //}
                }
                // Credit Limit End

                //	New Invoice Location
                // JID_1237 : While creating invoice need to consolidate order on the basis of Org, Payment Term, BP Location (Bill to Location) and Pricelist.
                if (!_ConsolidateDocument ||
                    (_invoice != null &&
                     (_invoice.GetC_BPartner_Location_ID() != order.GetBill_Location_ID() ||
                      _invoice.GetC_PaymentTerm_ID() != order.GetC_PaymentTerm_ID() ||
                      _invoice.GetM_PriceList_ID() != order.GetM_PriceList_ID() ||
                      _invoice.GetAD_Org_ID() != order.GetAD_Org_ID() ||
                      ((_invoice.GetC_ConversionType_ID() != 0 ? _invoice.GetC_ConversionType_ID() : defaultConversionType)
                       != (order.GetC_ConversionType_ID() != 0 ? order.GetC_ConversionType_ID() : defaultConversionType))
                     )))
                {
                    CompleteInvoice();
                }
                bool completeOrder = MOrder.INVOICERULE_AfterOrderDelivered.Equals(order.GetInvoiceRule());

                //	Schedule After Delivery
                bool doInvoice = false;
                if (MOrder.INVOICERULE_CustomerScheduleAfterDelivery.Equals(order.GetInvoiceRule()))
                {
                    _bp = new MBPartner(GetCtx(), order.GetBill_BPartner_ID(), null);
                    if (_bp.GetC_InvoiceSchedule_ID() == 0)
                    {
                        log.Warning("BPartner has no Schedule - set to After Delivery");
                        order.SetInvoiceRule(MOrder.INVOICERULE_AfterDelivery);
                        order.Save();
                    }
                    else
                    {
                        MInvoiceSchedule ins = MInvoiceSchedule.Get(GetCtx(), _bp.GetC_InvoiceSchedule_ID(), Get_TrxName());
                        if (ins.CanInvoice(order.GetDateOrdered(), order.GetGrandTotal()))
                        {
                            doInvoice = true;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }       //	Schedule

                //	After Delivery
                if (doInvoice || MOrder.INVOICERULE_AfterDelivery.Equals(order.GetInvoiceRule()))
                {
                    MInOut       shipment      = null;
                    MInOutLine[] shipmentLines = order.GetShipmentLines();
                    MOrderLine[] oLines        = order.GetLines(true, null);
                    for (int i = 0; i < shipmentLines.Length; i++)
                    {
                        MInOutLine shipLine = shipmentLines[i];
                        if (shipLine.IsInvoiced())
                        {
                            continue;
                        }
                        if (shipment == null ||
                            shipment.GetM_InOut_ID() != shipLine.GetM_InOut_ID())
                        {
                            shipment = new MInOut(GetCtx(), shipLine.GetM_InOut_ID(), Get_TrxName());
                        }
                        if (!shipment.IsComplete() ||           //	ignore incomplete or reversals
                            shipment.GetDocStatus().Equals(MInOut.DOCSTATUS_Reversed))
                        {
                            continue;
                        }
                        //JID_1139 Avoided the duplicate charge records
                        if (shipLine.GetM_Product_ID() > 0 || isAllownonItem)
                        {
                            CreateLine(order, shipment, shipLine);
                        }
                    }//	shipment lines

                    //JID_1139 Avoided the duplicate charge records
                    if (!isAllownonItem)
                    {
                        for (int i = 0; i < oLines.Length; i++)
                        {
                            MOrderLine oLine = oLines[i];
                            if (oLine.GetC_Charge_ID() > 0)
                            {
                                Decimal toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced());
                                log.Fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine);
                                Decimal qtyEntered = toInvoice;
                                //	Correct UOM for QtyEntered
                                if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0)
                                {
                                    qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply(
                                                                                  toInvoice, oLine.GetQtyEntered()),
                                                                              oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero);
                                }
                                //JID_1139_1 avoided the charge line with 0 qty inserted
                                if (oLine.IsContract() == false && oLine.GetQtyOrdered() > oLine.GetQtyInvoiced())
                                {
                                    CreateLine(order, oLine, toInvoice, qtyEntered);
                                    log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced());
                                }
                            }
                        }
                    }
                }
                //	After Order Delivered, Immediate
                else
                {
                    MOrderLine[] oLines = order.GetLines(true, null);
                    for (int i = 0; i < oLines.Length; i++)
                    {
                        MOrderLine oLine     = oLines[i];
                        Decimal    toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced());
                        if (toInvoice.CompareTo(Env.ZERO) == 0 && oLine.GetM_Product_ID() != 0)
                        {
                            continue;
                        }
                        //
                        bool fullyDelivered = oLine.GetQtyOrdered().CompareTo(oLine.GetQtyDelivered()) == 0;
                        //JID_1136: While creating the Invoices against the charge system should not check the Ordered qty= Delivered qty. need to check this only in case of products
                        if (completeOrder && oLine.GetC_Charge_ID() > 0)
                        {
                            fullyDelivered = true;
                            if (oLine.GetC_Charge_ID() > 0)
                            {
                                log.Fine("After Order Delivery - ToInvoice=" + toInvoice + " - " + oLine);
                                Decimal qtyEntered = toInvoice;
                                //	Correct UOM for QtyEntered
                                if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0)
                                {
                                    qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply(
                                                                                  toInvoice, oLine.GetQtyEntered()),
                                                                              oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero);
                                }
                                //
                                if (oLine.IsContract() == false && !isAllownonItem)
                                {
                                    CreateLine(order, oLine, toInvoice, qtyEntered);
                                    log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced());
                                }
                            }
                        }

                        //	Complete Order
                        if (completeOrder && !fullyDelivered)
                        {
                            log.Fine("Failed CompleteOrder - " + oLine);
                            completeOrder = false;
                            break;
                        }
                        //	Immediate
                        else if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule()))
                        {
                            log.Fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine);
                            Decimal qtyEntered = toInvoice;
                            //	Correct UOM for QtyEntered
                            if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0)
                            {
                                qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply(
                                                                              toInvoice, oLine.GetQtyEntered()),
                                                                          oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero);
                            }
                            //
                            if (oLine.IsContract() == false)
                            {
                                CreateLine(order, oLine, toInvoice, qtyEntered);
                                log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced());
                            }
                        }
                        else
                        {
                            log.Fine("Failed: " + order.GetInvoiceRule()
                                     + " - ToInvoice=" + toInvoice + " - " + oLine);
                        }
                    }   //	for all order lines
                    if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule()))
                    {
                        _line += 1000;
                    }
                }

                //	Complete Order successful
                if (completeOrder && MOrder.INVOICERULE_AfterOrderDelivered.Equals(order.GetInvoiceRule()))
                {
                    MInOut[] shipments = order.GetShipments(true);
                    for (int i = 0; i < shipments.Length; i++)
                    {
                        MInOut ship = shipments[i];
                        if (!ship.IsComplete() ||       //	ignore incomplete or reversals
                            ship.GetDocStatus().Equals(MInOut.DOCSTATUS_Reversed))
                        {
                            continue;
                        }
                        MInOutLine[] shipLines = ship.GetLines(false);
                        for (int j = 0; j < shipLines.Length; j++)
                        {
                            MInOutLine shipLine = shipLines[j];
                            if (!order.IsOrderLine(shipLine.GetC_OrderLine_ID()))
                            {
                                continue;
                            }
                            if (!shipLine.IsInvoiced())
                            {
                                CreateLine(order, ship, shipLine);
                            }
                        } //	lines
                        _line += 1000;
                    }     //	all shipments
                }         //	complete Order
            }             //	for all orders

            CompleteInvoice();
            return("@Created@ = " + _created);
        }
        /// <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);
        }
Ejemplo n.º 8
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
Ejemplo n.º 9
0
        /**
         *  Before Save
         *	@param newRecord new
         *	@return true
         */
        protected override Boolean BeforeSave(Boolean newRecord)
        {
            string Sql   = "";
            int    count = 0;

            if (GetC_Invoice_ID() > 0)
            {
                if (newRecord)
                {
                    Sql = "SELECT COUNT(*) FROM c_paymentallocate WHERE IsActive='Y' AND C_Payment_ID=" + GetC_Payment_ID() + @"
                            AND C_Invoice_ID=" + GetC_Invoice_ID() + " AND C_InvoicePaySchedule_ID=" + GetC_InvoicePaySchedule_ID() + " ";
                }
                else
                {
                    Sql = "SELECT COUNT(*) FROM c_paymentallocate WHERE IsActive='Y' AND C_Payment_ID=" + GetC_Payment_ID() + @"
                            AND C_Invoice_ID=" + GetC_Invoice_ID() + " AND C_InvoicePaySchedule_ID=" + GetC_InvoicePaySchedule_ID() + " AND c_paymentallocate_ID!=" + GetC_PaymentAllocate_ID() + "";
                }
                count = Util.GetValueOfInt(DB.ExecuteScalar(Sql));
                if (count > 0)
                {
                    log.SaveError(Msg.GetMsg(GetCtx(), "INT13_SchedAlrdySel"), "");
                    return(false);
                }

                Sql   = @"SELECT COUNT(*) 
                            FROM c_paymentallocate payall 
                            INNER JOIN C_Charge chg 
                            ON (payall.c_charge_ID =chg.C_Charge_ID)
                            WHERE payall.INT13_AllocateType='C'
                            AND payall.isactive            ='Y'
                            AND payall.C_Payment_ID        =" + GetC_Payment_ID() + @"
                            AND chg.isadvancecharge        ='Y'";
                count = Util.GetValueOfInt(DB.ExecuteScalar(Sql));
                if (count > 0)
                {
                    log.SaveError(Msg.GetMsg(GetCtx(), "INT13_NoInvAdvCharge"), "");
                    return(false);
                }
            }
            else if (GetC_Charge_ID() > 0)
            {
                MCharge charge = new MCharge(GetCtx(), GetC_Charge_ID(), null);
                if (charge.IsAdvanceCharge())
                {
                    if (newRecord)
                    {
                        Sql = @"SELECT COUNT(*) 
                            FROM c_paymentallocate payall 
                            INNER JOIN C_Charge chg 
                            ON (payall.c_charge_ID =chg.C_Charge_ID)
                            WHERE payall.INT13_AllocateType='C'
                            AND payall.isactive            ='Y'
                            AND payall.C_Payment_ID        =" + GetC_Payment_ID() + @"
                            AND chg.isadvancecharge        ='N' ";
                    }
                    else
                    {
                        Sql = @"SELECT COUNT(*) 
                            FROM c_paymentallocate payall 
                            INNER JOIN C_Charge chg 
                            ON (payall.c_charge_ID =chg.C_Charge_ID)
                            WHERE payall.INT13_AllocateType='C'
                            AND payall.isactive            ='Y'
                            AND payall.C_Payment_ID        =" + GetC_Payment_ID() + @"
                            AND chg.isadvancecharge        ='N' AND payall.c_paymentallocate_ID!= " + GetC_PaymentAllocate_ID();
                    }


                    count = Util.GetValueOfInt(DB.ExecuteScalar(Sql));
                    if (count > 0)
                    {
                        log.SaveError(Msg.GetMsg(GetCtx(), "INT13_NoAdvChgOnCharge"), "");
                        return(false);
                    }

                    Sql   = "SELECT COUNT(*) FROM C_PaymentAllocate  WHERE IsActive='Y' AND INT13_AllocateType='I' AND C_Payment_ID=" + GetC_Payment_ID();
                    count = Util.GetValueOfInt(DB.ExecuteScalar(Sql));
                    if (count > 0)
                    {
                        log.SaveError(Msg.GetMsg(GetCtx(), "INT13_NoAdvChgOnInv"), "");
                        return(false);
                    }
                }
                else
                {
                    if (newRecord)
                    {
                        Sql = @"SELECT COUNT(*) 
                            FROM c_paymentallocate payall 
                            INNER JOIN C_Charge chg 
                            ON (payall.c_charge_ID =chg.C_Charge_ID)
                            WHERE payall.INT13_AllocateType='C'
                            AND payall.isactive            ='Y'
                            AND payall.C_Payment_ID        =" + GetC_Payment_ID() + @"
                            AND chg.isadvancecharge        ='Y' ";
                    }
                    else
                    {
                        Sql = @"SELECT COUNT(*) 
                            FROM c_paymentallocate payall 
                            INNER JOIN C_Charge chg 
                            ON (payall.c_charge_ID =chg.C_Charge_ID)
                            WHERE payall.INT13_AllocateType='C'
                            AND payall.isactive            ='Y'
                            AND payall.C_Payment_ID        =" + GetC_Payment_ID() + @"
                            AND chg.isadvancecharge        ='Y' AND payall.c_paymentallocate_ID != " + GetC_PaymentAllocate_ID();
                    }
                    count = Util.GetValueOfInt(DB.ExecuteScalar(Sql));
                    if (count > 0)
                    {
                        log.SaveError(Msg.GetMsg(GetCtx(), "INT13_NoChgLnAdvChg"), "");
                        return(false);
                    }
                }
            }


            MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_TrxName());

            if ((newRecord || Is_ValueChanged("C_Invoice_ID")) &&
                (payment.GetC_Charge_ID() != 0 ||
                 payment.GetC_Invoice_ID() != 0 ||
                 payment.GetC_Order_ID() != 0))
            {
                log.SaveError("PaymentIsAllocated", "");
                return(false);
            }

            if (GetC_Invoice_ID() > 0 && GetC_InvoicePaySchedule_ID() > 0)
            {
                string allocatesql = "Select Count(PA.C_Payment_ID) From C_PaymentAllocate PA Inner Join C_Payment Pay on Pay.C_Payment_ID=PA.C_Payment_ID Where PA.C_Invoice_ID=" + GetC_Invoice_ID() + " And "
                                     + "PA.C_InvoicePaySchedule_ID=" + GetC_InvoicePaySchedule_ID() + " And pay.Docstatus IN ('DR','IP')";
                int countPaymentAllocate = Util.GetValueOfInt(DB.ExecuteScalar(allocatesql));
                if (countPaymentAllocate > 0)
                {
                    log.SaveError("Error", Msg.GetMsg(GetCtx(), "INT15_PaymentAllocateExist"));
                    return(false);
                }
            }

            // during saving a new record, system will check same invoice schedule reference exist on same payment or not
            if (newRecord && Get_ColumnIndex("C_InvoicePaySchedule_ID") >= 0 && GetC_InvoicePaySchedule_ID() > 0)
            {
                if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(*) FROM C_PaymentAllocate   WHERE C_Payment_ID = " + GetC_Payment_ID() +
                                                        @" AND IsActive = 'Y' AND C_InvoicePaySchedule_ID = " + GetC_InvoicePaySchedule_ID(), null, Get_Trx())) > 0)
                {
                    log.SaveError("Error", Msg.GetMsg(GetCtx(), "VIS_NotSaveDuplicateRecord"));
                    return(false);
                }
            }

            if (!Env.IsModuleInstalled("VA009_"))
            {
                Decimal check = Decimal.Add(Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt()), GetOverUnderAmt());
                if (check.CompareTo(GetInvoiceAmt()) != 0)
                {
                    log.SaveError("Error", Msg.ParseTranslation(GetCtx(),
                                                                "@InvoiceAmt@(" + GetInvoiceAmt()
                                                                + ") <> @Totals@(" + check + ")"));
                    return(false);
                }
            }

            //	Org
            if (newRecord || Is_ValueChanged("C_Invoice_ID"))
            {
                GetInvoice();
                if (_invoice != null)
                {
                    SetAD_Org_ID(_invoice.GetAD_Org_ID());
                }
            }

            return(true);
        }
Ejemplo n.º 10
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
Ejemplo n.º 11
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
Ejemplo n.º 12
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
        /// <summary>
        /// This function is used to create Recognition plan and run
        /// </summary>
        /// <param name="C_InvoiceLine_ID">invoice line</param>
        /// <param name="C_RevenueRecognition_ID">Revenue Recognition</param>
        /// <param name="Invoice">Invoice</param>
        /// <returns>true, when success</returns>
        public static bool CreateRevenueRecognitionPlan(int C_InvoiceLine_ID, int C_RevenueRecognition_ID, MInvoice Invoice)
        {
            try
            {
                MRevenueRecognitionRun revenueRecognitionRun = null;
                DateTime?           RecognizationDate        = null;
                int                 NoofMonths             = 0;
                MRevenueRecognition revenueRecognition     = new MRevenueRecognition(Invoice.GetCtx(), C_RevenueRecognition_ID, Invoice.Get_Trx());
                int                 defaultAccSchemaOrg_ID = GetDefaultActSchema(Invoice.GetCtx(), Invoice.GetAD_Client_ID(), Invoice.GetAD_Org_ID());
                int                 ToCurrency             = Util.GetValueOfInt(DB.ExecuteScalar("SELECT C_Currency_ID FROM C_AcctSchema WHERE C_AcctSchema_ID=" + defaultAccSchemaOrg_ID));

                MInvoiceLine invoiceLine = new MInvoiceLine(Invoice.GetCtx(), C_InvoiceLine_ID, Invoice.Get_Trx());

                //if recoganization date is null recognition plan and run cant be generated
                if (invoiceLine.Get_Value("RevenueStartDate") == null)
                {
                    _log.Log(Level.SEVERE, "DateIsInvlidOrNull");
                    return(false);
                }
                RecognizationDate = Util.GetValueOfDateTime(invoiceLine.Get_Value("RevenueStartDate"));

                // precision to be handle based on std precision defined on acct schema
                string sql          = "SELECT C.StdPrecision FROM C_AcctSchema a INNER JOIN C_Currency c ON c.C_Currency_ID= a.C_Currency_ID WHERE a.C_AcctSchema_ID=" + defaultAccSchemaOrg_ID;
                int    stdPrecision = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));


                if (revenueRecognition.GetRecognitionFrequency().Equals(RECOGNITIONFREQUENCY_Month) && RecognizationDate.Value.Day != 1 && revenueRecognition.GetNoMonths() > 0)
                {
                    //if startdate is in between day of month
                    NoofMonths = revenueRecognition.GetNoMonths() + 1;
                }
                else
                {
                    //if start date is the first day of the month
                    NoofMonths = revenueRecognition.GetNoMonths();
                }
                MRevenueRecognitionPlan revenueRecognitionPlan = new MRevenueRecognitionPlan(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                revenueRecognitionPlan.SetRecognitionPlan(invoiceLine, Invoice, C_RevenueRecognition_ID, ToCurrency);
                revenueRecognitionPlan.SetC_AcctSchema_ID(defaultAccSchemaOrg_ID);
                revenueRecognitionPlan.SetRecognizedAmt(0);
                if (!revenueRecognitionPlan.Save())
                {
                    ValueNamePair pp    = VLogger.RetrieveError();
                    string        error = pp != null?pp.GetValue() : "";

                    if (pp != null && string.IsNullOrEmpty(error))
                    {
                        error = pp.GetName();
                    }
                    if (!string.IsNullOrEmpty(error))
                    {
                        _log.Log(Level.SEVERE, error);
                        return(false);
                    }
                }
                else
                {
                    if (!revenueRecognition.IsTimeBased())
                    {
                    }
                    else
                    {
                        if (revenueRecognition.GetRecognitionFrequency().Equals(RECOGNITIONFREQUENCY_Month))
                        {
                            decimal totaldays = Util.GetValueOfDecimal((RecognizationDate.Value.AddMonths(revenueRecognition.GetNoMonths()) - RecognizationDate.Value.Date).TotalDays);

                            decimal  perdayAmt     = Math.Round(revenueRecognitionPlan.GetTotalAmt() / (totaldays > 0?totaldays:1), 12);
                            decimal  recognizedAmt = 0;
                            DateTime?lastdate      = null;
                            int      days          = 0;
                            for (int i = 0; i < NoofMonths; i++)
                            {
                                if (i == 0)
                                {
                                    if (RecognizationDate.Value.Month == 12)
                                    {
                                        //last date of the month
                                        lastdate = new DateTime(RecognizationDate.Value.Year, RecognizationDate.Value.Month, 1).AddMonths(1).AddDays(-1);
                                    }
                                    else
                                    {
                                        //last date of the month
                                        lastdate = new DateTime(RecognizationDate.Value.Year, RecognizationDate.Value.Month + 1, 1).AddDays(-1);
                                    }
                                    days  = Util.GetValueOfInt((lastdate.Value.Date - RecognizationDate.Value.Date).TotalDays);
                                    days += 1;
                                }
                                else if (i == (revenueRecognition.GetNoMonths()))
                                {
                                    //last date of the month would the day before  the recoganizationdate
                                    lastdate = RecognizationDate.Value.AddMonths(i).AddDays(-1);
                                    DateTime startDate = new DateTime(lastdate.Value.Year, lastdate.Value.Month, 1);
                                    days  = Util.GetValueOfInt((lastdate.Value.Date - startDate.Date).TotalDays);
                                    days += 1;
                                }
                                else
                                {
                                    DateTime startDate = lastdate.Value.AddDays(1);
                                    days     = DateTime.DaysInMonth(startDate.Year, startDate.Month);
                                    lastdate = startDate.AddDays(days - 1);
                                }
                                recognizedAmt         = Math.Round(days * perdayAmt, stdPrecision);
                                revenueRecognitionRun = new MRevenueRecognitionRun(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                                revenueRecognitionRun.SetRecognitionRun(revenueRecognitionPlan);
                                revenueRecognitionRun.SetRecognizedAmt(recognizedAmt);
                                revenueRecognitionRun.SetRecognitionDate(lastdate);
                                if (!revenueRecognitionRun.Save())
                                {
                                    ValueNamePair pp    = VLogger.RetrieveError();
                                    string        error = pp != null?pp.GetValue() : "";

                                    if (pp != null && string.IsNullOrEmpty(error))
                                    {
                                        error = pp.GetName();
                                    }
                                    if (!string.IsNullOrEmpty(error))
                                    {
                                        _log.Log(Level.SEVERE, error);
                                        return(false);
                                    }
                                }
                                recognizedAmt = 0;
                            }
                        }
                        else if (revenueRecognition.GetRecognitionFrequency().Equals(RECOGNITIONFREQUENCY_Day))
                        {
                            Decimal recognizedAmt = Math.Round(revenueRecognitionPlan.GetTotalAmt() / revenueRecognition.GetNoMonths(), stdPrecision);
                            int     days          = 0;
                            for (int i = 0; i < revenueRecognition.GetNoMonths(); i++)
                            {
                                revenueRecognitionRun = new MRevenueRecognitionRun(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                                revenueRecognitionRun.SetRecognitionRun(revenueRecognitionPlan);
                                revenueRecognitionRun.SetRecognizedAmt(recognizedAmt);
                                revenueRecognitionRun.SetRecognitionDate(RecognizationDate.Value.AddDays(days));
                                days += 1;
                                if (!revenueRecognitionRun.Save())
                                {
                                    ValueNamePair pp    = VLogger.RetrieveError();
                                    string        error = pp != null?pp.GetValue() : "";

                                    if (pp != null && string.IsNullOrEmpty(error))
                                    {
                                        error = pp.GetName();
                                    }
                                    if (!string.IsNullOrEmpty(error))
                                    {
                                        _log.Log(Level.SEVERE, error);
                                        return(false);
                                    }
                                }
                            }
                        }
                        else if (revenueRecognition.GetRecognitionFrequency().Equals(RECOGNITIONFREQUENCY_Year))
                        {
                            DateTime?fstartDate  = null;
                            DateTime?fendDate    = null;
                            int      calendar_ID = 0;
                            DataSet  ds          = new DataSet();

                            calendar_ID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT C_Calendar_ID FROM AD_OrgInfo WHERE ad_org_id = " + Invoice.GetAD_Org_ID()));
                            if (calendar_ID == 0)
                            {
                                calendar_ID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT C_Calendar_ID FROM AD_ClientInfo WHERE ad_client_id = " + Invoice.GetAD_Client_ID()));
                            }
                            sql = "SELECT startdate , enddate FROM c_period WHERE " +
                                  "c_year_id = (SELECT c_year.c_year_id FROM c_year INNER JOIN C_period ON c_year.c_year_id = C_period.c_year_id " +
                                  "WHERE  c_year.c_calendar_id =" + calendar_ID + " AND " + GlobalVariable.TO_DATE(RecognizationDate, true) + " BETWEEN C_period.startdate AND C_period.enddate) AND periodno IN (1, 12)";
                            ds = DB.ExecuteDataset(sql);
                            if (ds != null && ds.Tables[0].Rows.Count > 0)
                            {
                                fstartDate = Convert.ToDateTime(ds.Tables[0].Rows[0]["startdate"]);
                                fendDate   = Convert.ToDateTime(ds.Tables[0].Rows[1]["enddate"]);
                            }
                            if (fstartDate != RecognizationDate)
                            {
                                //RecognizationDate  is not same as financial year's start date
                                NoofMonths += 1;
                            }
                            decimal totaldays = Util.GetValueOfDecimal((RecognizationDate.Value.AddYears(revenueRecognition.GetNoMonths()) - RecognizationDate.Value.Date).TotalDays);

                            decimal  perdayAmt     = Math.Round(revenueRecognitionPlan.GetTotalAmt() / (totaldays > 0?totaldays:1), 12);
                            decimal  recognizedAmt = 0;
                            DateTime?lastdate      = null;
                            int      days          = 0;
                            for (int i = 0; i < NoofMonths; i++)
                            {
                                if (i == 0)
                                {
                                    //last date will always be financial year's end date
                                    lastdate = fendDate;
                                    days     = Util.GetValueOfInt((lastdate.Value.Date - RecognizationDate.Value.Date).TotalDays);
                                    days    += 1;
                                }
                                else if (i == revenueRecognition.GetNoMonths())
                                {
                                    //last date of the year would the day before the recoganizationdate
                                    lastdate = RecognizationDate.Value.AddYears(i).AddDays(-1);
                                    DateTime startDate = fstartDate.Value.AddYears(i);
                                    days  = Util.GetValueOfInt((lastdate.Value.Date - startDate.Date).TotalDays);
                                    days += 1;
                                }
                                else
                                {
                                    lastdate = fendDate.Value.AddYears(i);
                                    DateTime _startDate = fstartDate.Value.AddYears(i);
                                    days  = Util.GetValueOfInt((lastdate.Value.Date - _startDate.Date).TotalDays);
                                    days += 1;
                                }
                                recognizedAmt         = Math.Round(days * perdayAmt, stdPrecision);
                                revenueRecognitionRun = new MRevenueRecognitionRun(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                                revenueRecognitionRun.SetRecognitionRun(revenueRecognitionPlan);
                                revenueRecognitionRun.SetRecognizedAmt(recognizedAmt);
                                revenueRecognitionRun.SetRecognitionDate(lastdate);
                                if (!revenueRecognitionRun.Save())
                                {
                                    ValueNamePair pp    = VLogger.RetrieveError();
                                    string        error = pp != null?pp.GetValue() : "";

                                    if (pp != null && string.IsNullOrEmpty(error))
                                    {
                                        error = pp.GetName();
                                    }
                                    if (!string.IsNullOrEmpty(error))
                                    {
                                        _log.Log(Level.SEVERE, error);
                                        return(false);
                                    }
                                }
                                recognizedAmt = 0;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Severe("Exception during creation of Recognition Plan and Run. " + ex.Message);
                return(false);
            }
            return(true);
        }
        /**
         *  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);
        }
Ejemplo n.º 15
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);
            }
        }
Ejemplo n.º 16
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);
 }
Ejemplo n.º 17
0
        /**
         *  Create Invoice Line from Shipment
         *	@param order order
         *	@param ship shipment header
         *	@param sLine shipment line
         */
        private void CreateLine(MOrder order, MInOut ship, MInOutLine sLine)
        {
            if (_invoice == null)
            {
                _invoice = new MInvoice(order, 0, _DateInvoiced);
                //---------------------------Column Added by Anuj------------------
                int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));
                if (_CountVA009 > 0)
                {
                    int _PaymentMethod_ID = order.GetVA009_PaymentMethod_ID();
                    if (_PaymentMethod_ID > 0)
                    {
                        _invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID);
                    }
                }
                //-----------------Column Added by Anuj------------------

                int _CountVA026 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA026_'  AND IsActive = 'Y'"));
                if (_CountVA026 > 0)
                {
                    _invoice.SetVA026_LCDetail_ID(order.GetVA026_LCDetail_ID());
                }

                // Added by Bharat on 29 Jan 2018 to set Inco Term from Order

                if (_invoice.Get_ColumnIndex("C_IncoTerm_ID") > 0)
                {
                    _invoice.SetC_IncoTerm_ID(order.GetC_IncoTerm_ID());
                }

                if (!_invoice.Save())
                {
                    throw new Exception("Could not create Invoice (s)");
                }
            }
            #region Comment Create Shipment Comment Line
            //	Create Shipment Comment Line
            //if (_ship == null
            //    || _ship.GetM_InOut_ID() != ship.GetM_InOut_ID())
            //{
            //    MDocType dt = MDocType.Get(GetCtx(), ship.GetC_DocType_ID());
            //    if (_bp == null || _bp.GetC_BPartner_ID() != ship.GetC_BPartner_ID())
            //    {
            //        _bp = new MBPartner(GetCtx(), ship.GetC_BPartner_ID(), Get_TrxName());
            //    }

            //    //	Reference: Delivery: 12345 - 12.12.12
            //    MClient client = MClient.Get(GetCtx(), order.GetAD_Client_ID());
            //    String AD_Language = client.GetAD_Language();
            //    if (client.IsMultiLingualDocument() && _bp.GetAD_Language() != null)
            //    {
            //        AD_Language = _bp.GetAD_Language();
            //    }
            //    if (AD_Language == null)
            //    {
            //        // MessageBox.Show("Set base Language");
            //        //AD_Language = Language.getBaseAD_Language();
            //    }
            //    //java.text.SimpleDateFormat format = DisplayType.getDateFormat
            //    //    (DisplayType.Date, Language.getLanguage(AD_Language));

            //    //String reference = dt.GetPrintName(_bp.GetAD_Language())
            //    //    + ": " + ship.GetDocumentNo()
            //    //    + " - " + format.format(ship.GetMovementDate());
            //    String reference = dt.GetPrintName(_bp.GetAD_Language())
            //        + ": " + ship.GetDocumentNo()
            //        + " - " + ship.GetMovementDate();
            //    _ship = ship;
            //    //
            //    MInvoiceLine line = new MInvoiceLine(_invoice);
            //    line.SetIsDescription(true);
            //    line.SetDescription(reference);
            //    line.SetLine(_line + sLine.GetLine() - 2);
            //    if (!line.Save())
            //    {
            //        throw new Exception("Could not create Invoice Comment Line (sh)");
            //    }
            //    //	Optional Ship Address if not Bill Address
            //    if (order.GetBill_Location_ID() != ship.GetC_BPartner_Location_ID())
            //    {
            //        MLocation addr = MLocation.GetBPLocation(GetCtx(), ship.GetC_BPartner_Location_ID(), null);
            //        line = new MInvoiceLine(_invoice);
            //        line.SetIsDescription(true);
            //        line.SetDescription(addr.ToString());
            //        line.SetLine(_line + sLine.GetLine() - 1);
            //        if (!line.Save())
            //        {
            //            throw new Exception("Could not create Invoice Comment Line 2 (sh)");
            //        }
            //    }
            //}
            #endregion
            //
            MInvoiceLine line1 = new MInvoiceLine(_invoice);
            line1.SetShipLine(sLine);
            line1.SetQtyEntered(sLine.GetQtyEntered());
            line1.SetQtyInvoiced(sLine.GetMovementQty());
            line1.SetLine(_line + sLine.GetLine());
            line1.SetM_AttributeSetInstance_ID(sLine.GetM_AttributeSetInstance_ID());
            if (sLine.GetA_Asset_ID() > 0)
            {
                line1.SetA_Asset_ID(sLine.GetA_Asset_ID());
                if (line1.Get_ColumnIndex("VAFAM_AssetCost") > 0)
                {
                    int         PAcctSchema_ID = 0;
                    int         pCurrency_ID   = 0;
                    MAcctSchema as1            = MClient.Get(GetCtx(), GetAD_Client_ID()).GetAcctSchema();
                    if (as1 != null)
                    {
                        PAcctSchema_ID = as1.GetC_AcctSchema_ID();
                        pCurrency_ID   = as1.GetC_Currency_ID();
                    }
                    decimal LineNetAmt = Decimal.Multiply(line1.GetPriceActual(), line1.GetQtyEntered());
                    decimal AssetCost  = GetAssetCost(sLine.GetA_Asset_ID(), sLine.GetM_Product_ID(), PAcctSchema_ID);
                    AssetCost = Decimal.Multiply(AssetCost, line1.GetQtyEntered());
                    if (LineNetAmt > 0)
                    {
                        LineNetAmt = MConversionRate.Convert(GetCtx(), LineNetAmt, _invoice.GetC_Currency_ID(), pCurrency_ID, _invoice.GetAD_Client_ID(), _invoice.GetAD_Org_ID());
                    }
                    decimal Diff = LineNetAmt - AssetCost;
                    line1.Set_Value("VAFAM_AssetCost", AssetCost);
                    line1.Set_Value("VAFAM_Difference", Diff);
                }
            }

            if (!line1.Save())
            {
                throw new Exception("Could not create Invoice Line (s)");
            }
            //	Link
            sLine.SetIsInvoiced(true);
            if (!sLine.Save())
            {
                throw new Exception("Could not update Shipment Line");
            }

            log.Fine(line1.ToString());
        }
        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);
        }
        public static string CreateRevenueRecognitionPlan(int C_InvoiceLine_ID, int C_RevenueRecognition_ID, MInvoice Invoice)
        {
            try
            {
                MRevenueRecognitionRun revenueRecognitionRun = null;
                DateTime?           RecognizationDate        = null;
                MRevenueRecognition revenueRecognition       = new MRevenueRecognition(Invoice.GetCtx(), C_RevenueRecognition_ID, Invoice.Get_Trx());
                int defaultAccSchemaOrg_ID = GetDefaultActSchema(Invoice.GetAD_Org_ID());
                if (defaultAccSchemaOrg_ID <= 0)
                {
                    _log.Log(Level.SEVERE, "Default Schema not found for the oraganization");
                    return("Default Schema not found for the oraganization");
                }
                MINT15AccountingSchemaOrg accountingSchemaOrg = new MINT15AccountingSchemaOrg(Invoice.GetCtx(), defaultAccSchemaOrg_ID, Invoice.Get_Trx());

                MRevenueRecognitionPlan revenueRecognitionPlan = new MRevenueRecognitionPlan(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                MInvoiceLine            invoiceLine            = new MInvoiceLine(Invoice.GetCtx(), C_InvoiceLine_ID, Invoice.Get_Trx());
                MInvoice invoice = new MInvoice(Invoice.GetCtx(), invoiceLine.GetC_Invoice_ID(), Invoice.Get_Trx());

                string sql = "Select INT15_StartDate From C_InvoiceLine Where C_InvoiceLine_ID=" + invoiceLine.GetC_InvoiceLine_ID();
                RecognizationDate = Util.GetValueOfDateTime(DB.ExecuteScalar(sql));
                if (RecognizationDate == null)
                {
                    RecognizationDate = invoice.GetDateInvoiced();
                }

                revenueRecognitionPlan.SetRecognitionPlan(invoiceLine, invoice, C_RevenueRecognition_ID);
                revenueRecognitionPlan.SetC_AcctSchema_ID(accountingSchemaOrg.GetC_AcctSchema_ID());
                revenueRecognitionPlan.SetRecognizedAmt(0);
                if (revenueRecognition.GetINT15_RecognizeType() == "R")
                {
                    revenueRecognitionPlan.SetUnEarnedRevenue_Acct(RecognitionCombination(accountingSchemaOrg, "UR", invoiceLine));
                    revenueRecognitionPlan.SetP_Revenue_Acct(RecognitionCombination(accountingSchemaOrg, "TR", invoiceLine));
                }
                else
                {
                    revenueRecognitionPlan.SetINT15_PrepaidExpense(RecognitionCombination(accountingSchemaOrg, "DE", invoiceLine));
                    revenueRecognitionPlan.SetINT15_ProductExpense(RecognitionCombination(accountingSchemaOrg, "PE", invoiceLine));
                }
                revenueRecognitionPlan.Save();
                if (!revenueRecognition.IsTimeBased())
                {
                    MINT15RevenueService[] revenueService = GetServices(revenueRecognition);
                    for (int i = 0; i < revenueService.Length; i++)
                    {
                        MINT15RevenueService revenueserviceline = revenueService[i];
                        revenueRecognitionRun = new MRevenueRecognitionRun(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                        revenueRecognitionRun.SetRecognitionRun(revenueRecognition, revenueserviceline, revenueRecognitionPlan);
                        Decimal recognizedAmt = (revenueRecognitionPlan.GetTotalAmt() * revenueserviceline.GetINT15_Percentage()) / 100;
                        revenueRecognitionRun.SetRecognizedAmt(recognizedAmt);
                        revenueRecognitionRun.SetINT15_RevenueService_ID(revenueserviceline.GetINT15_RevenueService_ID());

                        revenueRecognitionRun.Save();
                    }
                }
                else
                {
                    if (revenueRecognition.GetRecognitionFrequency() == "M")
                    {
                        //Decimal recognizedAmt = revenueRecognitionPlan.GetTotalAmt() / revenueRecognition.GetNoMonths();
                        double   totaldays     = (RecognizationDate.Value.AddMonths(revenueRecognition.GetNoMonths()) - RecognizationDate.Value.Date).TotalDays;
                        decimal  perdayAmt     = revenueRecognitionPlan.GetTotalAmt() / Convert.ToDecimal(totaldays);
                        decimal  recognizedAmt = 0;
                        DateTime?lastdate      = null;
                        int      days          = 0;
                        for (int i = 0; i < revenueRecognition.GetNoMonths() + 1; i++)
                        {
                            if (i == 0)
                            {
                                if (RecognizationDate.Value.Month == 12)
                                {
                                    lastdate = new DateTime(RecognizationDate.Value.Year, RecognizationDate.Value.Month, 1).AddMonths(1).AddDays(-1);
                                }
                                else
                                {
                                    lastdate = new DateTime(RecognizationDate.Value.Year, RecognizationDate.Value.Month + 1, 1).AddDays(-1);
                                }
                                days  = Util.GetValueOfInt((lastdate.Value.Date - RecognizationDate.Value.Date).TotalDays);
                                days += 1;
                            }
                            else if (i == (revenueRecognition.GetNoMonths()))
                            {
                                DateTime EndDate   = RecognizationDate.Value.AddMonths(i);
                                var      startDate = new DateTime(EndDate.Year, EndDate.Month, 1);
                                days = Util.GetValueOfInt((EndDate.Date - startDate.Date).TotalDays);
                            }
                            else
                            {
                                DateTime startdate = RecognizationDate.Value.AddMonths(i);
                                days = DateTime.DaysInMonth(startdate.Year, startdate.Month);
                            }
                            recognizedAmt         = Convert.ToDecimal(days) * perdayAmt;
                            revenueRecognitionRun = new MRevenueRecognitionRun(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                            revenueRecognitionRun.SetRecognitionRun(revenueRecognition, null, revenueRecognitionPlan);
                            revenueRecognitionRun.SetRecognizedAmt(recognizedAmt);
                            revenueRecognitionRun.SetINT15_RecognitionDate(RecognizationDate.Value.AddMonths(i));
                            revenueRecognitionRun.Save();
                            recognizedAmt = 0;
                        }
                    }
                    else if (revenueRecognition.GetRecognitionFrequency() == "D")
                    {
                        Decimal recognizedAmt = revenueRecognitionPlan.GetTotalAmt() / revenueRecognition.GetNoMonths();
                        int     days          = 0;
                        for (int i = 0; i < revenueRecognition.GetNoMonths(); i++)
                        {
                            revenueRecognitionRun = new MRevenueRecognitionRun(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                            revenueRecognitionRun.SetRecognitionRun(revenueRecognition, null, revenueRecognitionPlan);
                            revenueRecognitionRun.SetRecognizedAmt(recognizedAmt);
                            revenueRecognitionRun.SetINT15_RecognitionDate(RecognizationDate.Value.AddDays(days));
                            days += 1;
                            revenueRecognitionRun.Save();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
            return("Revenue Recognition Created");
        }