Beispiel #1
0
        /// <summary>
        /// Perform Process.
        /// </summary>
        /// <returns>Message (text with variables)</returns>
        protected override String DoIt()
        {
            log.Info("M_Product_ID=" + _M_Product_ID);
            if (_M_Product_ID == 0)
            {
                throw new Exception("@NotFound@: @M_Product_ID@ = " + _M_Product_ID);
            }
            MProduct product = MProduct.Get(GetCtx(), _M_Product_ID);

            if (product.Get_ID() != _M_Product_ID)
            {
                throw new Exception("@NotFound@: @M_Product_ID@ = " + _M_Product_ID);
            }
            //
            if (MCostDetail.ProcessProduct(product, Get_Trx()))
            {
                return("@OK@");
            }
            return("@Error@");
        }
Beispiel #2
0
 public static bool CreateCostElementDetail(Ctx ctx, int AD_Client_ID, int AD_Org_ID, MProduct Product, int M_ASI_ID,
                                            MAcctSchema mas, int M_costElement_ID, string windowName, MCostDetail cd, decimal amt, decimal qty)
 {
     try
     {
         MCostElementDetail ced = new MCostElementDetail(ctx, 0, null);
         ced.SetAD_Client_ID(AD_Client_ID);
         ced.SetAD_Org_ID(AD_Org_ID);
         ced.SetC_AcctSchema_ID(mas.GetC_AcctSchema_ID());
         ced.SetM_CostElement_ID(M_costElement_ID);
         ced.SetM_Product_ID(Product.GetM_Product_ID());
         ced.SetM_AttributeSetInstance_ID(M_ASI_ID);
         ced.SetQty(qty);
         ced.SetAmt(amt);
         //Refrences
         ced.SetC_OrderLine_ID(cd.GetC_OrderLine_ID());
         ced.SetM_InOutLine_ID(cd.GetM_InOutLine_ID());
         if (windowName == "Material Receipt" || windowName == "Customer Return" || windowName == "Shipment" || windowName == "Return To Vendor")
         {
             // not to bind Invoiceline refernece on cost element detail
         }
         else
         {
             ced.SetC_InvoiceLine_ID(cd.GetC_InvoiceLine_ID());
         }
         ced.SetM_InventoryLine_ID(cd.GetM_InventoryLine_ID());
         ced.SetM_MovementLine_ID(cd.GetM_MovementLine_ID());
         ced.SetC_ProjectIssue_ID(cd.GetC_ProjectIssue_ID());
         ced.SetIsSOTrx(cd.IsSOTrx());
         ced.SetA_Asset_ID(cd.GetA_Asset_ID());
         ced.SetM_ProductionLine_ID(cd.GetM_ProductionLine_ID());
         ced.SetM_WorkOrderResourceTxnLine_ID(cd.GetM_WorkOrderResourceTxnLine_ID());
         ced.SetM_WorkOrderTransactionLine_ID(cd.GetM_WorkOrderTransactionLine_ID());
         if (!ced.Save())
         {
             ValueNamePair pp = VLogger.RetrieveError();
             _log.Info("Error Occured during costing " + pp.ToString());
             return(false);
         }
     }
     catch (Exception ex)
     {
         _log.Info("Error Occured during costing " + ex.ToString());
         return(false);
     }
     return(true);
 }
        /// <summary>
        /// Create Facts (the accounting logic) for
        ///  MMM.
        ///  <pre>
        ///  Movement
        ///      Inventory       DR      CR
        ///      InventoryTo     DR      CR
        ///  </pre>
        /// </summary>
        /// <param name="as1"></param>
        /// <returns>Fact</returns>
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            //  create Fact Header
            Fact fact = new Fact(this, as1, Fact.POST_Actual);

            SetC_Currency_ID(as1.GetC_Currency_ID());

            //  Line pointers
            FactLine dr = null;
            FactLine cr = null;

            for (int i = 0; i < _lines.Length; i++)
            {
                DocLine line  = _lines[i];
                Decimal costs = line.GetProductCosts(as1, line.GetAD_Org_ID(), false);

                //  ** Inventory       DR      CR
                dr = fact.CreateLine(line,
                                     line.GetAccount(ProductCost.ACCTTYPE_P_Asset, as1),
                                     as1.GetC_Currency_ID(), Decimal.Negate(costs)); //	from (-) CR
                if (dr == null)
                {
                    continue;
                }
                dr.SetM_Locator_ID(line.GetM_Locator_ID());
                dr.SetQty(Decimal.Negate(line.GetQty().Value)); //	outgoing

                //  ** InventoryTo     DR      CR
                cr = fact.CreateLine(line,
                                     line.GetAccount(ProductCost.ACCTTYPE_P_Asset, as1),
                                     as1.GetC_Currency_ID(), costs);    //	to (+) DR
                if (cr == null)
                {
                    continue;
                }
                cr.SetM_Locator_ID(line.GetM_LocatorTo_ID());
                cr.SetQty(line.GetQty());

                //	Only for between-org movements
                if (dr.GetAD_Org_ID() != cr.GetAD_Org_ID())
                {
                    String costingLevel      = as1.GetCostingLevel();
                    MProductCategoryAcct pca = MProductCategoryAcct.Get(GetCtx(),
                                                                        line.GetProduct().GetM_Product_Category_ID(),
                                                                        as1.GetC_AcctSchema_ID(), GetTrx());
                    if (pca.GetCostingLevel() != null)
                    {
                        costingLevel = pca.GetCostingLevel();
                    }
                    if (!MAcctSchema.COSTINGLEVEL_Organization.Equals(costingLevel))
                    {
                        continue;
                    }
                    //
                    String description = line.GetDescription();
                    if (description == null)
                    {
                        description = "";
                    }
                    if (!IsPosted())
                    {
                        //	Cost Detail From
                        MCostDetail.CreateMovement(as1, dr.GetAD_Org_ID(),      //	locator org
                                                   line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                   line.Get_ID(), 0,
                                                   Decimal.Negate(costs), Decimal.Negate(line.GetQty().Value), true,
                                                   description + "(|->)", GetTrx(), GetRectifyingProcess());


                        //	Cost Detail To
                        MCostDetail.CreateMovement(as1, cr.GetAD_Org_ID(),      //	locator org
                                                   line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                   line.Get_ID(), 0,
                                                   costs, line.GetQty().Value, false,
                                                   description + "(|<-)", GetTrx(), GetRectifyingProcess());
                    }
                }
            }

            //
            List <Fact> facts = new List <Fact>();

            facts.Add(fact);
            return(facts);
        }
        /// <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);
        }
Beispiel #5
0
        /// <summary>
        /// Create Facts (the accounting logic) for
        ///  MXP.
        ///  <pre>
        ///      Product PPV     <difference>
        ///      PPV_Offset                  <difference>
        ///  </pre>
        /// </summary>
        /// <param name="as1"></param>
        /// <returns></returns>
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            List <Fact> facts = new List <Fact>();

            //
            if (GetM_Product_ID() == 0 ||       //  Nothing to do if no Product
                Env.Signum(Utility.Util.GetValueOfDecimal(GetQty())) == 0 ||
                _M_InOutLine_ID == 0)           //  No posting if not matched to Shipment
            {
                log.Fine("No Product/Qty - M_Product_ID=" + GetM_Product_ID()
                         + ",Qty=" + GetQty());
                return(facts);
            }

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

            SetC_Currency_ID(as1.GetC_Currency_ID());

            //	Purchase Order Line
            Decimal poCost = _oLine.GetPriceCost();

            if (Env.Signum(poCost) == 0)
            {
                poCost = _oLine.GetPriceActual();
            }
            poCost = Decimal.Multiply(poCost, Utility.Util.GetValueOfDecimal(GetQty()));                 //	Delivered so far
            //	Different currency
            if (_oLine.GetC_Currency_ID() != as1.GetC_Currency_ID())
            {
                MOrder  order = _oLine.GetParent();
                Decimal rate  = MConversionRate.GetRate(
                    order.GetC_Currency_ID(), as1.GetC_Currency_ID(),
                    order.GetDateAcct(), order.GetC_ConversionType_ID(),
                    _oLine.GetAD_Client_ID(), _oLine.GetAD_Org_ID());
                if (rate.ToString() == null)
                {
                    _error = "Purchase Order not convertible - " + as1.GetName();
                    return(null);
                }
                poCost = Decimal.Multiply(poCost, rate);
                if (Env.Scale(poCost) > as1.GetCostingPrecision())
                {
                    poCost = Decimal.Round(poCost, as1.GetCostingPrecision(), MidpointRounding.AwayFromZero);
                }
            }

            MOrder order1      = _oLine.GetParent();
            bool   isReturnTrx = order1.IsReturnTrx();

            log.Fine("Temp");

            if (!IsPosted())
            {
                //	Create PO Cost Detail Record firs
                MCostDetail.CreateOrder(as1, _oLine.GetAD_Org_ID(),
                                        GetM_Product_ID(), _M_AttributeSetInstance_ID,
                                        _C_OrderLine_ID, 0,                                                                                                                                               //	no cost element
                                        isReturnTrx ? Decimal.Negate(poCost) : poCost, isReturnTrx ? Decimal.Negate(Utility.Util.GetValueOfDecimal(GetQty())) : Utility.Util.GetValueOfDecimal(GetQty()), //	Delivered
                                        _oLine.GetDescription(), GetTrx(), GetRectifyingProcess());
            }


            //	Current Costs
            String               costingMethod = as1.GetCostingMethod();
            MProduct             product       = MProduct.Get(GetCtx(), GetM_Product_ID());
            MProductCategoryAcct pca           = MProductCategoryAcct.Get(GetCtx(),
                                                                          product.GetM_Product_Category_ID(), as1.GetC_AcctSchema_ID(), GetTrx());

            if (pca.GetCostingMethod() != null)
            {
                costingMethod = pca.GetCostingMethod();
            }
            Decimal?costs = _pc.GetProductCosts(as1, GetAD_Org_ID(), costingMethod, _C_OrderLine_ID, false);    //	non-zero costs

            //	No Costs yet - no PPV
            if (costs == null || Env.Signum(Utility.Util.GetValueOfDecimal(costs)) == 0)
            {
                _error = "Resubmit - No Costs for " + product.GetName();
                log.Log(Level.SEVERE, _error);
                return(null);
            }

            //	Difference
            Decimal difference = Decimal.Subtract(poCost, Utility.Util.GetValueOfDecimal(costs));


            /***********************************************************************************/
            //05,Sep,2011
            //Special Check to restic Price varience posting in case of
            //AvarageInvoice Selected on product Category.Then Neglact the AverageInvoice Cost

            try
            {
                if (as1.IsNotPostPOVariance())
                {
                    difference = 0;
                }
            }
            catch (Exception ex)
            {
                log.SaveError("AccountSchemaColumnError", ex);
            }
            /***********************************************************************************/
            //	Nothing to post
            if (Env.Signum(difference) == 0)
            {
                log.Log(Level.FINE, "No Cost Difference for M_Product_ID=" + GetM_Product_ID());
                facts.Add(fact);
                return(facts);
            }

            //  Product PPV
            FactLine cr = fact.CreateLine(null,
                                          _pc.GetAccount(ProductCost.ACCTTYPE_P_PPV, as1),
                                          as1.GetC_Currency_ID(), difference);

            if (cr != null)
            {
                cr.SetQty(GetQty());
                cr.SetC_BPartner_ID(_oLine.GetC_BPartner_ID());
                cr.SetC_Activity_ID(_oLine.GetC_Activity_ID());
                cr.SetC_Campaign_ID(_oLine.GetC_Campaign_ID());
                cr.SetC_Project_ID(_oLine.GetC_Project_ID());
                cr.SetC_UOM_ID(_oLine.GetC_UOM_ID());
                cr.SetUser1_ID(_oLine.GetUser1_ID());
                cr.SetUser2_ID(_oLine.GetUser2_ID());
            }

            //  PPV Offset
            FactLine dr = fact.CreateLine(null,
                                          GetAccount(Doc.ACCTTYPE_PPVOffset, as1),
                                          as1.GetC_Currency_ID(), Decimal.Negate(difference));

            if (dr != null)
            {
                dr.SetQty((Decimal?)Decimal.Negate(Utility.Util.GetValueOfDecimal(GetQty())));

                dr.SetC_BPartner_ID(_oLine.GetC_BPartner_ID());
                dr.SetC_Activity_ID(_oLine.GetC_Activity_ID());
                dr.SetC_Campaign_ID(_oLine.GetC_Campaign_ID());
                dr.SetC_Project_ID(_oLine.GetC_Project_ID());
                dr.SetC_UOM_ID(_oLine.GetC_UOM_ID());
                dr.SetUser1_ID(_oLine.GetUser1_ID());
                dr.SetUser2_ID(_oLine.GetUser2_ID());
            }
            //
            facts.Add(fact);
            return(facts);
        }
Beispiel #6
0
        /// <summary>
        /// Create Landed Cost accounting & Cost lines
        /// </summary>
        /// <param name="as1">accounting schema</param>
        /// <param name="fact">fact</param>
        /// <param name="line">document line</param>
        /// <param name="dr">DR entry (normal api)</param>
        /// <returns>true if landed costs were created</returns>
        private bool LandedCost(MAcctSchema as1, Fact fact, DocLine line, bool dr)
        {
            int C_InvoiceLine_ID = line.Get_ID();

            MLandedCostAllocation[] lcas = MLandedCostAllocation.GetOfInvoiceLine(
                GetCtx(), C_InvoiceLine_ID, GetTrx());
            if (lcas.Length == 0)
            {
                return(false);
            }

            //	Delete Old
            String sql = "DELETE FROM M_CostDetail WHERE C_InvoiceLine_ID=" + C_InvoiceLine_ID;
            int    no  = DataBase.DB.ExecuteQuery(sql, null, GetTrx());

            if (no != 0)
            {
                log.Config("CostDetail Deleted #" + no);
            }

            //	Calculate Total Base
            double totalBase = 0;

            for (int i = 0; i < lcas.Length; i++)
            {
                totalBase += Convert.ToDouble(lcas[i].GetBase());//.doubleValue();
            }
            //	Create New
            MInvoiceLine il = new MInvoiceLine(GetCtx(), C_InvoiceLine_ID, GetTrx());

            for (int i = 0; i < lcas.Length; i++)
            {
                MLandedCostAllocation lca = lcas[i];
                if (Env.Signum(lca.GetBase()) == 0)
                {
                    continue;
                }
                double percent = totalBase / Convert.ToDouble(lca.GetBase());
                String desc    = il.GetDescription();
                if (desc == null)
                {
                    desc = percent + "%";
                }
                else
                {
                    desc += " - " + percent + "%";
                }
                if (line.GetDescription() != null)
                {
                    desc += " - " + line.GetDescription();
                }

                //	Accounting
                ProductCost pc = new ProductCost(GetCtx(),
                                                 lca.GetM_Product_ID(), lca.GetM_AttributeSetInstance_ID(), GetTrx());
                Decimal?drAmt = null;
                Decimal?crAmt = null;
                if (dr)
                {
                    drAmt = lca.GetAmt();
                }
                else
                {
                    crAmt = lca.GetAmt();
                }
                FactLine fl = fact.CreateLine(line, pc.GetAccount(ProductCost.ACCTTYPE_P_CostAdjustment, as1),
                                              GetC_Currency_ID(), drAmt, crAmt);
                fl.SetDescription(desc);

                //	Cost Detail - Convert to AcctCurrency
                Decimal allocationAmt = lca.GetAmt();
                if (GetC_Currency_ID() != as1.GetC_Currency_ID())
                {
                    allocationAmt = MConversionRate.Convert(GetCtx(), allocationAmt,
                                                            GetC_Currency_ID(), as1.GetC_Currency_ID(),
                                                            GetDateAcct(), GetC_ConversionType_ID(),
                                                            GetAD_Client_ID(), GetAD_Org_ID());
                }
                if (Env.Scale(allocationAmt) > as1.GetCostingPrecision())
                {
                    allocationAmt = Decimal.Round(allocationAmt, as1.GetCostingPrecision(), MidpointRounding.AwayFromZero);
                }
                if (!dr)
                {
                    allocationAmt = Decimal.Negate(allocationAmt);
                }
                if (!IsPosted())
                {
                    MCostDetail cd = new MCostDetail(as1, lca.GetAD_Org_ID(),
                                                     lca.GetM_Product_ID(), lca.GetM_AttributeSetInstance_ID(),
                                                     lca.GetM_CostElement_ID(),
                                                     allocationAmt, lca.GetQty(), //	Qty
                                                     desc, GetTrx());

                    cd.SetC_InvoiceLine_ID(C_InvoiceLine_ID);
                    bool ok = cd.Save();
                    if (ok && !cd.IsProcessed())
                    {
                        MClient client = MClient.Get(as1.GetCtx(), as1.GetAD_Client_ID());
                        if (client.IsCostImmediate())
                        {
                            cd.Process();
                        }
                    }
                }
            }

            log.Config("Created #" + lcas.Length);
            return(true);
        }
Beispiel #7
0
        /// <summary>
        /// Create Facts (the accounting logic) for
        /// ARI, ARC, ARF, API, APC.
        /// <pre>
        ///   ARI, ARF
        ///         Receivables     DR
        ///         Charge                  CR
        ///         TaxDue                  CR
        ///Revenue                 CR
        ///    ARC
        ///  Receivables             CR
        ///    Charge          DR
        ///    TaxDue          DR
        ///      Revenue         RR
        ///
        ///  API
        ///    Payables                CR
        ///    Charge          DR
        ///    TaxCredit       DR
        ///    Expense         DR
        ///
        ///  APC
        ///    Payables        DR
        ///     Charge                  CR
        ///    TaxCredit               CR
        ///     Expense                 CR
        /// </pre>
        /// </summary>
        /// <param name="as1">accounting schema</param>
        /// <returns> Fact</returns>
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            //
            List <Fact> facts = new List <Fact>();
            //  create Fact Header
            Fact fact = new Fact(this, as1, Fact.POST_Actual);

            //  Cash based accounting
            if (!as1.IsAccrual())
            {
                return(facts);
            }

            //  ** ARI, ARF
            if (GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_ARINVOICE) ||
                GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_ARPROFORMAINVOICE))
            {
                Decimal grossAmt   = GetAmount(Doc.AMTTYPE_Gross).Value;
                Decimal serviceAmt = Env.ZERO;

                //  Header Charge           CR
                Decimal amt = GetAmount(Doc.AMTTYPE_Charge).Value;
                if (Env.Signum(amt) != 0)
                {
                    fact.CreateLine(null, GetAccount(Doc.ACCTTYPE_Charge, as1),
                                    GetC_Currency_ID(), null, amt);
                }
                //  TaxDue                  CR
                for (int i = 0; i < _taxes.Length; i++)
                {
                    amt = _taxes[i].GetAmount();
                    if (Env.Signum(amt) != 0)
                    {
                        FactLine tl = fact.CreateLine(null, _taxes[i].GetAccount(DocTax.ACCTTYPE_TaxDue, as1),
                                                      GetC_Currency_ID(), null, amt);
                        if (tl != null)
                        {
                            tl.SetC_Tax_ID(_taxes[i].GetC_Tax_ID());
                        }
                    }
                }
                //  Revenue                 CR
                for (int i = 0; i < _lines.Length; i++)
                {
                    amt = _lines[i].GetAmtSource();
                    Decimal?dAmt = null;
                    if (as1.IsTradeDiscountPosted())
                    {
                        Decimal discount = _lines[i].GetDiscount();
                        if (Env.Signum(discount) != 0)
                        {
                            amt  = Decimal.Add(amt, discount);
                            dAmt = discount;
                        }
                    }
                    fact.CreateLine(_lines[i],
                                    _lines[i].GetAccount(ProductCost.ACCTTYPE_P_Revenue, as1),
                                    GetC_Currency_ID(), dAmt, amt);
                    if (!_lines[i].IsItem())
                    {
                        grossAmt   = Decimal.Subtract(grossAmt, amt);
                        serviceAmt = Decimal.Add(serviceAmt, amt);
                    }
                }
                //  Set Locations
                FactLine[] fLines = fact.GetLines();
                for (int i = 0; i < fLines.Length; i++)
                {
                    if (fLines[i] != null)
                    {
                        fLines[i].SetLocationFromOrg(fLines[i].GetAD_Org_ID(), true);          //  from Loc
                        fLines[i].SetLocationFromBPartner(GetC_BPartner_Location_ID(), false); //  to Loc
                    }
                }

                //  Receivables     DR
                int receivables_ID         = GetValidCombination_ID(Doc.ACCTTYPE_C_Receivable, as1);
                int receivablesServices_ID = GetValidCombination_ID(Doc.ACCTTYPE_C_Receivable_Services, as1);
                if (_allLinesItem || !as1.IsPostServices() ||
                    receivables_ID == receivablesServices_ID)
                {
                    grossAmt   = GetAmount(Doc.AMTTYPE_Gross).Value;
                    serviceAmt = Env.ZERO;
                }
                else if (_allLinesService)
                {
                    serviceAmt = GetAmount(Doc.AMTTYPE_Gross).Value;
                    grossAmt   = Env.ZERO;
                }
                if (Env.Signum(grossAmt) != 0)
                {
                    fact.CreateLine(null, MAccount.Get(GetCtx(), receivables_ID),
                                    GetC_Currency_ID(), grossAmt, null);
                }
                if (Env.Signum(serviceAmt) != 0)
                {
                    fact.CreateLine(null, MAccount.Get(GetCtx(), receivablesServices_ID),
                                    GetC_Currency_ID(), serviceAmt, null);
                }
            }
            //  ARC
            else if (GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_ARCREDITMEMO))
            {
                Decimal grossAmt   = GetAmount(Doc.AMTTYPE_Gross).Value;
                Decimal serviceAmt = Env.ZERO;

                //  Header Charge   DR
                Decimal amt = GetAmount(Doc.AMTTYPE_Charge).Value;
                if (Env.Signum(amt) != 0)
                {
                    fact.CreateLine(null, GetAccount(Doc.ACCTTYPE_Charge, as1),
                                    GetC_Currency_ID(), amt, null);
                }
                //  TaxDue          DR
                for (int i = 0; i < _taxes.Length; i++)
                {
                    amt = _taxes[i].GetAmount();
                    if (Env.Signum(amt) != 0)
                    {
                        FactLine tl = fact.CreateLine(null, _taxes[i].GetAccount(DocTax.ACCTTYPE_TaxDue, as1),
                                                      GetC_Currency_ID(), amt, null);
                        if (tl != null)
                        {
                            tl.SetC_Tax_ID(_taxes[i].GetC_Tax_ID());
                        }
                    }
                }
                //  Revenue         CR
                for (int i = 0; i < _lines.Length; i++)
                {
                    amt = _lines[i].GetAmtSource();
                    Decimal?dAmt = null;
                    if (as1.IsTradeDiscountPosted())
                    {
                        Decimal discount = _lines[i].GetDiscount();
                        if (Env.Signum(discount) != 0)
                        {
                            amt  = Decimal.Add(amt, discount);
                            dAmt = discount;
                        }
                    }
                    fact.CreateLine(_lines[i],
                                    _lines[i].GetAccount(ProductCost.ACCTTYPE_P_Revenue, as1),
                                    GetC_Currency_ID(), amt, dAmt);
                    if (!_lines[i].IsItem())
                    {
                        grossAmt   = Decimal.Subtract(grossAmt, amt);
                        serviceAmt = Decimal.Add(serviceAmt, amt);
                    }
                }
                //  Set Locations
                FactLine[] fLines = fact.GetLines();
                for (int i = 0; i < fLines.Length; i++)
                {
                    if (fLines[i] != null)
                    {
                        fLines[i].SetLocationFromOrg(fLines[i].GetAD_Org_ID(), true);          //  from Loc
                        fLines[i].SetLocationFromBPartner(GetC_BPartner_Location_ID(), false); //  to Loc
                    }
                }
                //  Receivables             CR
                int receivables_ID         = GetValidCombination_ID(Doc.ACCTTYPE_C_Receivable, as1);
                int receivablesServices_ID = GetValidCombination_ID(Doc.ACCTTYPE_C_Receivable_Services, as1);
                if (_allLinesItem || !as1.IsPostServices() ||
                    receivables_ID == receivablesServices_ID)
                {
                    grossAmt   = GetAmount(Doc.AMTTYPE_Gross).Value;
                    serviceAmt = Env.ZERO;
                }
                else if (_allLinesService)
                {
                    serviceAmt = GetAmount(Doc.AMTTYPE_Gross).Value;
                    grossAmt   = Env.ZERO;
                }
                if (Env.Signum(grossAmt) != 0)
                {
                    fact.CreateLine(null, MAccount.Get(GetCtx(), receivables_ID),
                                    GetC_Currency_ID(), null, grossAmt);
                }
                if (Env.Signum(serviceAmt) != 0)
                {
                    fact.CreateLine(null, MAccount.Get(GetCtx(), receivablesServices_ID),
                                    GetC_Currency_ID(), null, serviceAmt);
                }
            }

            //  ** API
            else if (GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_APINVOICE))
            {
                Decimal grossAmt   = GetAmount(Doc.AMTTYPE_Gross).Value;
                Decimal serviceAmt = Env.ZERO;

                //  Charge          DR
                fact.CreateLine(null, GetAccount(Doc.ACCTTYPE_Charge, as1),
                                GetC_Currency_ID(), GetAmount(Doc.AMTTYPE_Charge), null);
                //  TaxCredit       DR
                for (int i = 0; i < _taxes.Length; i++)
                {
                    FactLine tl = fact.CreateLine(null, _taxes[i].GetAccount(_taxes[i].GetAPTaxType(), as1),
                                                  GetC_Currency_ID(), _taxes[i].GetAmount(), null);
                    if (tl != null)
                    {
                        tl.SetC_Tax_ID(_taxes[i].GetC_Tax_ID());
                    }
                }
                //  Expense         DR
                for (int i = 0; i < _lines.Length; i++)
                {
                    DocLine line       = _lines[i];
                    bool    landedCost = LandedCost(as1, fact, line, true);
                    if (landedCost && as1.IsExplicitCostAdjustment())
                    {
                        fact.CreateLine(line, line.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1),
                                        GetC_Currency_ID(), line.GetAmtSource(), null);
                        //
                        FactLine fl = fact.CreateLine(line, line.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1),
                                                      GetC_Currency_ID(), null, line.GetAmtSource());
                        String desc = line.GetDescription();
                        if (desc == null)
                        {
                            desc = "100%";
                        }
                        else
                        {
                            desc += " 100%";
                        }
                        fl.SetDescription(desc);
                    }
                    if (!landedCost)
                    {
                        MAccount expense = line.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1);
                        if (line.IsItem())
                        {
                            expense = line.GetAccount(ProductCost.ACCTTYPE_P_InventoryClearing, as1);
                        }
                        Decimal amt  = line.GetAmtSource();
                        Decimal?dAmt = null;
                        if (as1.IsTradeDiscountPosted() && !line.IsItem())
                        {
                            Decimal discount = line.GetDiscount();
                            if (Env.Signum(discount) != 0)
                            {
                                amt  = Decimal.Add(amt, discount);
                                dAmt = discount;
                            }
                        }
                        fact.CreateLine(line, expense, GetC_Currency_ID(), amt, dAmt);
                        if (!line.IsItem())
                        {
                            grossAmt   = Decimal.Subtract(grossAmt, amt);
                            serviceAmt = Decimal.Add(serviceAmt, amt);
                        }
                        //
                        if (line.GetM_Product_ID() != 0 &&
                            line.GetProduct().IsService())      //	otherwise Inv Matching
                        {
                            if (!IsPosted())
                            {
                                MCostDetail.CreateInvoice(as1, line.GetAD_Org_ID(),
                                                          line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                          line.Get_ID(), 0, //	No Cost Element
                                                          line.GetAmtSource(), line.GetQty().Value,
                                                          line.GetDescription(), GetTrx(), GetRectifyingProcess());
                            }
                        }
                    }
                }
                //  Set Locations
                FactLine[] fLines = fact.GetLines();
                for (int i = 0; i < fLines.Length; i++)
                {
                    if (fLines[i] != null)
                    {
                        fLines[i].SetLocationFromBPartner(GetC_BPartner_Location_ID(), true); //  from Loc
                        fLines[i].SetLocationFromOrg(fLines[i].GetAD_Org_ID(), false);        //  to Loc
                    }
                }

                //  Liability               CR
                int payables_ID         = GetValidCombination_ID(Doc.ACCTTYPE_V_Liability, as1);
                int payablesServices_ID = GetValidCombination_ID(Doc.ACCTTYPE_V_Liability_Services, as1);
                if (_allLinesItem || !as1.IsPostServices() ||
                    payables_ID == payablesServices_ID)
                {
                    grossAmt   = GetAmount(Doc.AMTTYPE_Gross).Value;
                    serviceAmt = Env.ZERO;
                }
                else if (_allLinesService)
                {
                    serviceAmt = GetAmount(Doc.AMTTYPE_Gross).Value;
                    grossAmt   = Env.ZERO;
                }
                if (Env.Signum(grossAmt) != 0)
                {
                    fact.CreateLine(null, MAccount.Get(GetCtx(), payables_ID),
                                    GetC_Currency_ID(), null, grossAmt);
                }
                if (Env.Signum(serviceAmt) != 0)
                {
                    fact.CreateLine(null, MAccount.Get(GetCtx(), payablesServices_ID),
                                    GetC_Currency_ID(), null, serviceAmt);
                }
                //
                UpdateProductPO(as1);   //	Only API
            }
            //  APC
            else if (GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_APCREDITMEMO))
            {
                Decimal grossAmt   = GetAmount(Doc.AMTTYPE_Gross).Value;
                Decimal serviceAmt = Env.ZERO;
                //  Charge                  CR
                fact.CreateLine(null, GetAccount(Doc.ACCTTYPE_Charge, as1),
                                GetC_Currency_ID(), null, GetAmount(Doc.AMTTYPE_Charge));
                //  TaxCredit               CR
                for (int i = 0; i < _taxes.Length; i++)
                {
                    FactLine tl = fact.CreateLine(null, _taxes[i].GetAccount(_taxes[i].GetAPTaxType(), as1),
                                                  GetC_Currency_ID(), null, _taxes[i].GetAmount());
                    if (tl != null)
                    {
                        tl.SetC_Tax_ID(_taxes[i].GetC_Tax_ID());
                    }
                }
                //  Expense                 CR
                for (int i = 0; i < _lines.Length; i++)
                {
                    DocLine line       = _lines[i];
                    bool    landedCost = LandedCost(as1, fact, line, false);
                    if (landedCost && as1.IsExplicitCostAdjustment())
                    {
                        fact.CreateLine(line, line.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1),
                                        GetC_Currency_ID(), null, line.GetAmtSource());
                        //
                        FactLine fl = fact.CreateLine(line, line.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1),
                                                      GetC_Currency_ID(), line.GetAmtSource(), null);
                        String desc = line.GetDescription();
                        if (desc == null)
                        {
                            desc = "100%";
                        }
                        else
                        {
                            desc += " 100%";
                        }
                        fl.SetDescription(desc);
                    }
                    if (!landedCost)
                    {
                        MAccount expense = line.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1);
                        if (line.IsItem())
                        {
                            expense = line.GetAccount(ProductCost.ACCTTYPE_P_InventoryClearing, as1);
                        }
                        Decimal amt  = line.GetAmtSource();
                        Decimal?dAmt = null;
                        if (as1.IsTradeDiscountPosted() && !line.IsItem())
                        {
                            Decimal discount = line.GetDiscount();
                            if (Env.Signum(discount) != 0)
                            {
                                amt  = Decimal.Add(amt, discount);
                                dAmt = discount;
                            }
                        }
                        fact.CreateLine(line, expense,
                                        GetC_Currency_ID(), dAmt, amt);
                        if (!line.IsItem())
                        {
                            grossAmt   = Decimal.Subtract(grossAmt, amt);
                            serviceAmt = Decimal.Add(serviceAmt, amt);
                        }
                        //
                        if (line.GetM_Product_ID() != 0 &&
                            line.GetProduct().IsService())      //	otherwise Inv Matching
                        {
                            if (!IsPosted())
                            {
                                MCostDetail.CreateInvoice(as1, line.GetAD_Org_ID(),
                                                          line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                          line.Get_ID(), 0, //	No Cost Element
                                                          Decimal.Negate(line.GetAmtSource()), line.GetQty().Value,
                                                          line.GetDescription(), GetTrx(), GetRectifyingProcess());
                            }
                        }
                    }
                }
                //  Set Locations
                FactLine[] fLines = fact.GetLines();
                for (int i = 0; i < fLines.Length; i++)
                {
                    if (fLines[i] != null)
                    {
                        fLines[i].SetLocationFromBPartner(GetC_BPartner_Location_ID(), true); //  from Loc
                        fLines[i].SetLocationFromOrg(fLines[i].GetAD_Org_ID(), false);        //  to Loc
                    }
                }
                //  Liability       DR
                int payables_ID         = GetValidCombination_ID(Doc.ACCTTYPE_V_Liability, as1);
                int payablesServices_ID = GetValidCombination_ID(Doc.ACCTTYPE_V_Liability_Services, as1);
                if (_allLinesItem || !as1.IsPostServices() ||
                    payables_ID == payablesServices_ID)
                {
                    grossAmt   = GetAmount(Doc.AMTTYPE_Gross).Value;
                    serviceAmt = Env.ZERO;
                }
                else if (_allLinesService)
                {
                    serviceAmt = GetAmount(Doc.AMTTYPE_Gross).Value;
                    grossAmt   = Env.ZERO;
                }
                if (Env.Signum(grossAmt) != 0)
                {
                    fact.CreateLine(null, MAccount.Get(GetCtx(), payables_ID),
                                    GetC_Currency_ID(), grossAmt, null);
                }
                if (Env.Signum(serviceAmt) != 0)
                {
                    fact.CreateLine(null, MAccount.Get(GetCtx(), payablesServices_ID),
                                    GetC_Currency_ID(), serviceAmt, null);
                }
            }
            else
            {
                _error = "DocumentType unknown: " + GetDocumentType();
                log.Log(Level.SEVERE, _error);
                fact = null;
            }
            //
            facts.Add(fact);
            return(facts);
        }
        /// <summary>
        /// Create Facts (the accounting logic) for
        /// MMS, MMR.
        /// <pre>
        /// Shipment
        /// CoGS (RevOrg)   DR
        /// Inventory               CR
        /// Shipment of Project Issue
        /// CoGS            DR
        /// Project                 CR
        /// Receipt
        /// Inventory       DR
        /// NotInvoicedReceipt      CR
        /// </pre>
        /// </summary>
        /// <param name="as1">accounting schema</param>
        /// <returns>Fact</returns>
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            //  create Fact Header
            Fact fact = new Fact(this, as1, Fact.POST_Actual);

            SetC_Currency_ID(as1.GetC_Currency_ID());

            //  Line pointers
            FactLine dr = null;
            FactLine cr = null;

            //  *** Sales - Shipment
            if (GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_MATERIALDELIVERY))
            {
                for (int i = 0; i < _lines.Length; i++)
                {
                    DocLine    line  = _lines[i];
                    MInOutLine sLine = new MInOutLine(GetCtx(), line.Get_ID(), null);
                    Decimal    costs = 0;
                    if (sLine.GetA_Asset_ID() > 0)
                    {
                        costs = Util.GetValueOfDecimal(DB.ExecuteScalar(@"SELECT cost.CUrrentcostPrice
                                                                            FROM m_cost cost
                                                                            INNER JOIN A_Asset ass
                                                                            ON(ass.a_asset_ID=cost.a_asset_ID)
                                                                            INNER JOIN M_InOutLine IOL
                                                                            ON(IOL.A_Asset_ID       =ass.A_Asset_ID)
                                                                            WHERE IOL.M_InOutLine_ID=" + sLine.GetM_InOutLine_ID() + @"
                                                                              ORDER By cost.created desc"));
                        // Change if Cost not found against Asset then get Product Cost
                        if (Env.Signum(costs) == 0)     //	zero costs OK
                        {
                            costs = line.GetProductCosts(as1, line.GetAD_Org_ID(), true);
                        }
                    }
                    else
                    {
                        costs = line.GetProductCosts(as1, line.GetAD_Org_ID(), true);
                    }

                    if (Env.Signum(costs) == 0) //	zero costs OK
                    {
                        MProduct product = line.GetProduct();
                        if (product.IsStocked())
                        {
                            _error = "No Costs for " + line.GetProduct().GetName();
                            log.Log(Level.WARNING, _error);
                            return(null);
                        }
                        else    //	ignore service
                        {
                            continue;
                        }
                    }

                    if (!IsReturnTrx())
                    {
                        //  CoGS            DR
                        dr = fact.CreateLine(line,
                                             line.GetAccount(ProductCost.ACCTTYPE_P_Cogs, as1),
                                             as1.GetC_Currency_ID(), costs, null);
                        if (dr == null)
                        {
                            _error = "FactLine DR not created: " + line;
                            log.Log(Level.WARNING, _error);
                            return(null);
                        }
                        dr.SetM_Locator_ID(line.GetM_Locator_ID());
                        dr.SetLocationFromLocator(line.GetM_Locator_ID(), true);        //  from Loc
                        dr.SetLocationFromBPartner(GetC_BPartner_Location_ID(), false); //  to Loc
                        dr.SetAD_Org_ID(line.GetOrder_Org_ID());                        //	Revenue X-Org
                        dr.SetQty(Decimal.Negate(line.GetQty().Value));

                        //  Inventory               CR
                        cr = fact.CreateLine(line, line.GetAccount(ProductCost.ACCTTYPE_P_Asset, as1),
                                             as1.GetC_Currency_ID(), null, costs);
                        if (cr == null)
                        {
                            _error = "FactLine CR not created: " + line;
                            log.Log(Level.WARNING, _error);
                            return(null);
                        }
                        cr.SetM_Locator_ID(line.GetM_Locator_ID());
                        cr.SetLocationFromLocator(line.GetM_Locator_ID(), true);        // from Loc
                        cr.SetLocationFromBPartner(GetC_BPartner_Location_ID(), false); // to Loc
                    }
                    else // Reverse accounting entries for returns
                    {
                        //				  CoGS            CR
                        cr = fact.CreateLine(line,
                                             line.GetAccount(ProductCost.ACCTTYPE_P_Cogs, as1),
                                             as1.GetC_Currency_ID(), null, costs);
                        if (cr == null)
                        {
                            _error = "FactLine CR not created: " + line;
                            log.Log(Level.WARNING, _error);
                            return(null);
                        }
                        cr.SetM_Locator_ID(line.GetM_Locator_ID());
                        cr.SetLocationFromLocator(line.GetM_Locator_ID(), true);        //  from Loc
                        cr.SetLocationFromBPartner(GetC_BPartner_Location_ID(), false); //  to Loc
                        cr.SetAD_Org_ID(line.GetOrder_Org_ID());                        //	Revenue X-Org
                        cr.SetQty(Decimal.Negate(line.GetQty().Value));

                        //  Inventory               DR
                        dr = fact.CreateLine(line,
                                             line.GetAccount(ProductCost.ACCTTYPE_P_Asset, as1),
                                             as1.GetC_Currency_ID(), costs, null);
                        if (dr == null)
                        {
                            _error = "FactLine DR not created: " + line;
                            log.Log(Level.WARNING, _error);
                            return(null);
                        }
                        dr.SetM_Locator_ID(line.GetM_Locator_ID());
                        dr.SetLocationFromLocator(line.GetM_Locator_ID(), true);        // from Loc
                        dr.SetLocationFromBPartner(GetC_BPartner_Location_ID(), false); // to Loc
                    }
                    //
                    if (line.GetM_Product_ID() != 0)
                    {
                        if (!IsPosted())
                        {
                            MCostDetail.CreateShipment(as1, line.GetAD_Org_ID(),
                                                       line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                       line.Get_ID(), 0,
                                                       costs, IsReturnTrx() ? Decimal.Negate(line.GetQty().Value) : line.GetQty().Value,
                                                       line.GetDescription(), true, GetTrx(), GetRectifyingProcess());
                        }
                    }
                }       //	for all lines

                if (!IsPosted())
                {
                    UpdateProductInfo(as1.GetC_AcctSchema_ID()); //  only for SO!
                }
            }                                                    //	Shipment

            //  *** Purchasing - Receipt
            else if (GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_MATERIALRECEIPT))
            {
                for (int i = 0; i < _lines.Length; i++)
                {
                    Decimal  costs   = 0;
                    DocLine  line    = _lines[i];
                    MProduct product = line.GetProduct();
                    /***********************************************************/
                    //05,Sep,2011
                    //Special Check to restic Price varience posting in case of
                    //AvarageInvoice Selected on product Category.Then Neglact the AverageInvoice Cost
                    MProductCategoryAcct pca = MProductCategoryAcct.Get(product.GetCtx(),
                                                                        product.GetM_Product_Category_ID(), as1.GetC_AcctSchema_ID(), null);
                    try
                    {
                        if (as1.IsNotPostPOVariance() && line.GetC_OrderLine_ID() > 0)
                        {
                            MOrderLine oLine         = new MOrderLine(product.GetCtx(), line.GetC_OrderLine_ID(), null);
                            MOrder     order         = new MOrder(product.GetCtx(), oLine.GetC_Order_ID(), null);
                            Decimal    convertedCost = MConversionRate.Convert(product.GetCtx(),
                                                                               oLine.GetPriceEntered(), order.GetC_Currency_ID(), as1.GetC_Currency_ID(),
                                                                               line.GetDateAcct(), order.GetC_ConversionType_ID(),
                                                                               oLine.GetAD_Client_ID(), line.GetAD_Org_ID());

                            costs = Decimal.Multiply(convertedCost, oLine.GetQtyEntered());
                        }
                        else
                        {
                            costs = line.GetProductCosts(as1, line.GetAD_Org_ID(), false);      //	non-zero costs
                        }
                    }
                    catch (Exception ex)
                    {
                        log.SaveError("AccountSchemaColumnError", ex);
                        costs = line.GetProductCosts(as1, line.GetAD_Org_ID(), false);  //	non-zero costs
                    }
                    /***********************************************************/

                    //Decimal costs = costs = line.GetProductCosts(as1, line.GetAD_Org_ID(), false);	//	non-zero costs

                    if (Env.Signum(costs) == 0)
                    {
                        _error = "Resubmit - No Costs for " + product.GetName();
                        log.Log(Level.WARNING, _error);
                        return(null);
                    }
                    //  Inventory/Asset			DR
                    MAccount assets = line.GetAccount(ProductCost.ACCTTYPE_P_Asset, as1);
                    if (product.IsService())
                    {
                        assets = line.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1);
                    }

                    if (!IsReturnTrx())
                    {
                        //  Inventory/Asset			DR
                        dr = fact.CreateLine(line, assets,
                                             as1.GetC_Currency_ID(), costs, null);
                        if (dr == null)
                        {
                            _error = "DR not created: " + line;
                            log.Log(Level.WARNING, _error);
                            return(null);
                        }
                        dr.SetM_Locator_ID(line.GetM_Locator_ID());
                        dr.SetLocationFromBPartner(GetC_BPartner_Location_ID(), true); // from Loc
                        dr.SetLocationFromLocator(line.GetM_Locator_ID(), false);      // to Loc
                        //  NotInvoicedReceipt				CR
                        cr = fact.CreateLine(line,
                                             GetAccount(Doc.ACCTTYPE_NotInvoicedReceipts, as1),
                                             as1.GetC_Currency_ID(), null, costs);
                        if (cr == null)
                        {
                            _error = "CR not created: " + line;
                            log.Log(Level.WARNING, _error);
                            return(null);
                        }
                        cr.SetM_Locator_ID(line.GetM_Locator_ID());
                        cr.SetLocationFromBPartner(GetC_BPartner_Location_ID(), true); //  from Loc
                        cr.SetLocationFromLocator(line.GetM_Locator_ID(), false);      //  to Loc
                        cr.SetQty(Decimal.Negate(line.GetQty().Value));
                    }
                    else // reverse accounting entries for returns
                    {
                        //  Inventory/Asset			CR
                        cr = fact.CreateLine(line, assets,
                                             as1.GetC_Currency_ID(), null, costs);
                        if (cr == null)
                        {
                            _error = "CR not created: " + line;
                            log.Log(Level.WARNING, _error);
                            return(null);
                        }
                        cr.SetM_Locator_ID(line.GetM_Locator_ID());
                        cr.SetLocationFromBPartner(GetC_BPartner_Location_ID(), true); // from Loc
                        cr.SetLocationFromLocator(line.GetM_Locator_ID(), false);      // to Loc
                        //  NotInvoicedReceipt				DR
                        dr = fact.CreateLine(line,
                                             GetAccount(Doc.ACCTTYPE_NotInvoicedReceipts, as1),
                                             as1.GetC_Currency_ID(), costs, null);
                        if (dr == null)
                        {
                            _error = "DR not created: " + line;
                            log.Log(Level.WARNING, _error);
                            return(null);
                        }
                        dr.SetM_Locator_ID(line.GetM_Locator_ID());
                        dr.SetLocationFromBPartner(GetC_BPartner_Location_ID(), true); //  from Loc
                        dr.SetLocationFromLocator(line.GetM_Locator_ID(), false);      //  to Loc
                        dr.SetQty(Decimal.Negate(line.GetQty().Value));
                    }
                }
            }   //	Receipt
            else
            {
                _error = "DocumentType unknown: " + GetDocumentType();
                log.Log(Level.SEVERE, _error);
                return(null);
            }
            //
            List <Fact> facts = new List <Fact>();

            facts.Add(fact);
            return(facts);
        }
        /// <summary>
        /// This function will create child record of Cost Queue, which will contain transaction affects
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="AD_Client_ID">Client ID</param>
        /// <param name="AD_Org_ID">Organization ID</param>
        /// <param name="M_CostQueue_ID">Cost Queue ID</param>
        /// <param name="cd">Cost Detail Reference</param>
        /// <param name="qty">qty</param>
        /// <returns>true, when success</returns>
        public static bool CreateCostQueueTransaction(Ctx ctx, int AD_Client_ID, int AD_Org_ID, int M_CostQueue_ID, MCostDetail cd, decimal qty)
        {
            try
            {
                MCostQueueTransaction ced = new MCostQueueTransaction(ctx, 0, cd.Get_Trx());
                ced.SetAD_Client_ID(AD_Client_ID);
                ced.SetAD_Org_ID(AD_Org_ID);
                ced.SetM_CostQueue_ID(M_CostQueue_ID);
                ced.SetM_Product_ID(cd.GetM_Product_ID());
                ced.SetM_AttributeSetInstance_ID(cd.GetM_AttributeSetInstance_ID());
                ced.SetM_Warehouse_ID(cd.GetM_Warehouse_ID());

                // date and qty
                ced.SetMovementQty(qty);
                ced.SetMovementDate(DateTime.Now);

                //Refrences
                ced.SetM_InOutLine_ID(cd.GetM_InOutLine_ID());
                if (ced.GetM_InOutLine_ID() > 0)
                {
                    DataSet ds = DB.ExecuteDataset(@"SELECT M_InOut.IsSOTrx, M_InOut.IsReturnTrx FROM M_InOutLine
                                    INNER JOIN M_InOut ON M_InOutLine.M_InOut_ID = M_InOut.M_InOut_ID 
                                    WHERE M_InOutLine.M_InOutLine_ID = " + ced.GetM_InOutLine_ID(), null, cd.Get_Trx());
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        ced.SetIsSOTrx(Util.GetValueOfString(ds.Tables[0].Rows[0]["IsSOTrx"]).Equals("N") ? false : true);
                        ced.SetIsReturnTrx(Util.GetValueOfString(ds.Tables[0].Rows[0]["IsReturnTrx"]).Equals("N") ? false : true);
                    }
                }
                ced.SetM_InventoryLine_ID(cd.GetM_InventoryLine_ID());
                if (ced.GetM_InventoryLine_ID() > 0)
                {
                    bool isInternalUse = Util.GetValueOfString(DB.ExecuteScalar(@"SELECT M_Inventory.IsInternalUse  FROM M_InventoryLine
                                    INNER JOIN M_Inventory ON M_InventoryLine.M_Inventory_ID = M_Inventory.M_Inventory_ID 
                                    WHERE M_InventoryLine.M_InventoryLine_ID = " + ced.GetM_InventoryLine_ID(), null, cd.Get_Trx())).Equals("N") ? false : true;
                    ced.SetIsInternalUse(isInternalUse);
                }
                ced.SetM_MovementLine_ID(cd.GetM_MovementLine_ID());
                ced.SetC_ProjectIssue_ID(cd.GetC_ProjectIssue_ID());
                //ced.SetA_Asset_ID(cd.GetA_Asset_ID());
                ced.SetM_ProductionLine_ID(cd.GetM_ProductionLine_ID());
                if (Env.IsModuleInstalled("VAFAM_") && ced.Get_ColumnIndex("VAFAM_AssetDisposal_ID") > -1)
                {
                    ced.Set_Value("VAFAM_AssetDisposal_ID", cd.Get_Value("VAFAM_AssetDisposal_ID"));
                }
                if (Env.IsModuleInstalled("VAMFG_"))
                {
                    if (ced.Get_ColumnIndex("VAMFG_M_WrkOdrRscTxnLine_ID") > -1)
                    {
                        ced.Set_Value("VAMFG_M_WrkOdrRscTxnLine_ID", cd.GetVAMFG_M_WrkOdrRscTxnLine_ID());
                    }
                    if (ced.Get_ColumnIndex("VAMFG_M_WrkOdrTrnsctionLine_ID") > -1)
                    {
                        ced.Set_Value("VAMFG_M_WrkOdrTrnsctionLine_ID", cd.GetVAMFG_M_WrkOdrTrnsctionLine_ID());
                    }
                }
                if (!ced.Save())
                {
                    ValueNamePair pp    = VLogger.RetrieveError();
                    string        error = "";
                    if (pp != null)
                    {
                        error = pp.GetValue();
                        if (String.IsNullOrEmpty(error))
                        {
                            error = pp.GetValue();
                        }
                    }
                    _log.Info("Costing Engine : Error Occured during saving a record on Cost Queue Transaction -> " + error);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                _log.Info("Costing Engine : Exception Occured during saving a record on Cost Queue Transaction " + ex.Message);
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Create Facts (the accounting logic) for
        ///  MMP.
        ///  <pre>
        ///  Production
        ///      Inventory       DR      CR
        ///  </pre>
        /// </summary>
        /// <param name="as1"></param>
        /// <returns>fact</returns>
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            //  create Fact Header
            Fact fact = new Fact(this, as1, Fact.POST_Actual);

            SetC_Currency_ID(as1.GetC_Currency_ID());

            //  Line pointer
            FactLine fl = null;

            for (int i = 0; i < _lines.Length; i++)
            {
                DocLine line = _lines[i];
                //	Calculate Costs
                Decimal?costs = null;
                if (line.IsProductionBOM())
                {
                    //	Get BOM Cost - Sum of individual lines
                    Decimal bomCost = Env.ZERO;
                    for (int ii = 0; ii < _lines.Length; ii++)
                    {
                        DocLine line0 = _lines[ii];
                        if (line0.GetM_ProductionPlan_ID() != line.GetM_ProductionPlan_ID())
                        {
                            continue;
                        }
                        if (!line0.IsProductionBOM())
                        {
                            bomCost = Decimal.Add(bomCost, line0.GetProductCosts(as1, line.GetAD_Org_ID(), false));
                        }
                    }
                    costs = Decimal.Negate(bomCost);
                }
                else
                {
                    costs = line.GetProductCosts(as1, line.GetAD_Org_ID(), false);
                }

                //  Inventory       DR      CR
                fl = fact.CreateLine(line,
                                     line.GetAccount(ProductCost.ACCTTYPE_P_Asset, as1),
                                     as1.GetC_Currency_ID(), costs);
                if (fl == null)
                {
                    _error = "No Costs for Line " + line.GetLine() + " - " + line;
                    return(null);
                }
                fl.SetM_Locator_ID(line.GetM_Locator_ID());
                fl.SetQty(line.GetQty());

                //	Cost Detail
                String description = line.GetDescription();
                if (description == null)
                {
                    description = "";
                }
                if (line.IsProductionBOM())
                {
                    description += "(*)";
                }

                if (!IsPosted())
                {
                    MCostDetail.CreateProduction(as1, line.GetAD_Org_ID(),
                                                 line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                 line.Get_ID(), 0,
                                                 Utility.Util.GetValueOfInt(costs), line.GetQty().Value,
                                                 description, GetTrx(), GetRectifyingProcess());
                }
            }
            //
            List <Fact> facts = new List <Fact>();

            facts.Add(fact);
            return(facts);
        }
Beispiel #11
0
        /// <summary>
        /// Create Facts (the accounting logic) for
        ///  MMI.
        ///  <pre>
        ///  Inventory
        ///      Inventory       DR      CR
        ///      InventoryDiff   DR      CR   (or Charge)
        ///  </pre>
        /// </summary>
        /// <param name="?"></param>
        /// <returns> Fact</returns>
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            //  create Fact Header
            Fact fact = new Fact(this, as1, Fact.POST_Actual);

            SetC_Currency_ID(as1.GetC_Currency_ID());

            //  Line pointers
            FactLine dr = null;
            FactLine cr = null;

            for (int i = 0; i < _lines.Length; i++)
            {
                DocLine line  = _lines[i];
                Decimal costs = line.GetProductCosts(as1, line.GetAD_Org_ID(), false);
                if (Env.Signum(costs) == 0)
                {
                    _error = "No Costs for " + line.GetProduct().GetName();
                    return(null);
                }
                //  Inventory       DR      CR
                dr = fact.CreateLine(line,
                                     line.GetAccount(ProductCost.ACCTTYPE_P_Asset, as1),
                                     as1.GetC_Currency_ID(), costs);
                //  may be zero difference - no line created.
                if (dr == null)
                {
                    continue;
                }
                dr.SetM_Locator_ID(line.GetM_Locator_ID());

                //  InventoryDiff   DR      CR
                //	or Charge
                MAccount invDiff = line.GetChargeAccount(as1, Decimal.Negate(costs));
                if (invDiff == null)
                {
                    invDiff = GetAccount(Doc.ACCTTYPE_InvDifferences, as1);
                }
                cr = fact.CreateLine(line, invDiff,
                                     as1.GetC_Currency_ID(), Decimal.Negate(costs));
                if (cr == null)
                {
                    continue;
                }
                cr.SetM_Locator_ID(line.GetM_Locator_ID());
                cr.SetQty(Decimal.Negate(line.GetQty().Value));
                if (line.GetC_Charge_ID() != 0) //	explicit overwrite for charge
                {
                    cr.SetAD_Org_ID(line.GetAD_Org_ID());
                }
                if (!IsPosted())
                {
                    //	Cost Detail
                    MCostDetail.CreateInventory(as1, line.GetAD_Org_ID(),
                                                line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                line.Get_ID(), 0,
                                                costs, line.GetQty().Value,
                                                line.GetDescription(), GetTrx(), GetRectifyingProcess());
                }
            }
            //
            List <Fact> facts = new List <Fact>();

            facts.Add(fact);
            return(facts);
        }