Exemple #1
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);
        }
        }       //	createRequisition

        /// <summary>
        /// Create Inventory Movements
        /// </summary>
        private void CreateMovements()
        {
            int    noMoves = 0;
            String info    = "";
            //
            MClient    client               = null;
            MMovement  move                 = null;
            int        M_Warehouse_ID       = 0;
            int        M_WarehouseSource_ID = 0;
            MWarehouse whSource             = null;
            MWarehouse whTarget             = null;

            string param = "";

            if (_M_WareSource != null)
            {
                param = _M_WareSource;
            }
            else
            {
                param = "M_WarehouseSource_ID IS NOT NULL";
            }
            X_T_Replenish[] replenishs = GetReplenish(param);;
            for (int i = 0; i < replenishs.Length; i++)
            {
                X_T_Replenish replenish = replenishs[i];
                if (whSource == null || whSource.GetM_WarehouseSource_ID() != replenish.GetM_WarehouseSource_ID())
                {
                    whSource = MWarehouse.Get(GetCtx(), replenish.GetM_WarehouseSource_ID());
                }
                if (whTarget == null || whTarget.GetM_Warehouse_ID() != replenish.GetM_Warehouse_ID())
                {
                    whTarget = MWarehouse.Get(GetCtx(), replenish.GetM_Warehouse_ID());
                }
                if (client == null || client.GetAD_Client_ID() != whSource.GetAD_Client_ID())
                {
                    client = MClient.Get(GetCtx(), whSource.GetAD_Client_ID());
                }
                //
                if (move == null ||
                    M_WarehouseSource_ID != replenish.GetM_WarehouseSource_ID() ||
                    M_Warehouse_ID != replenish.GetM_Warehouse_ID())
                {
                    M_WarehouseSource_ID = replenish.GetM_WarehouseSource_ID();
                    M_Warehouse_ID       = replenish.GetM_Warehouse_ID();

                    move = new MMovement(GetCtx(), 0, Get_TrxName());
                    move.SetC_DocType_ID(_C_DocType_ID);
                    move.SetDescription(Msg.GetMsg(GetCtx(), "Replenishment")
                                        + ": " + whSource.GetName() + "->" + whTarget.GetName());
                    //	Set Org
                    move.SetAD_Org_ID(whSource.GetAD_Org_ID());
                    if (!move.Save())
                    {
                        return;
                    }
                    log.Fine(move.ToString());
                    noMoves++;
                    info += " - " + move.GetDocumentNo();
                }
                MProduct product = MProduct.Get(GetCtx(), replenish.GetM_Product_ID());
                //	To
                int M_LocatorTo_ID = GetLocator_ID(product, whTarget);

                //	From: Look-up Storage
                MProductCategory pc       = MProductCategory.Get(GetCtx(), product.GetM_Product_Category_ID());
                String           MMPolicy = pc.GetMMPolicy();
                if (MMPolicy == null || MMPolicy.Length == 0)
                {
                    MMPolicy = client.GetMMPolicy();
                }
                //
                MStorage[] storages = MStorage.GetWarehouse(GetCtx(),
                                                            whSource.GetM_Warehouse_ID(), replenish.GetM_Product_ID(), 0, 0,
                                                            true, null,
                                                            MClient.MMPOLICY_FiFo.Equals(MMPolicy), Get_TrxName());
                if (storages == null || storages.Length == 0)
                {
                    AddLog("No Inventory in " + whSource.GetName()
                           + " for " + product.GetName());
                    continue;
                }
                //
                Decimal target = replenish.GetQtyToOrder();
                for (int j = 0; j < storages.Length; j++)
                {
                    MStorage storage = storages[j];
                    //if (storage.GetQtyOnHand().signum() <= 0)
                    if (Env.Signum(storage.GetQtyOnHand()) <= 0)
                    {
                        continue;
                    }
                    Decimal moveQty = target;
                    if (storage.GetQtyOnHand().CompareTo(moveQty) < 0)
                    {
                        moveQty = storage.GetQtyOnHand();
                    }
                    //
                    MMovementLine line = new MMovementLine(move);
                    line.SetM_Product_ID(replenish.GetM_Product_ID());
                    line.SetMovementQty(moveQty);
                    if (replenish.GetQtyToOrder().CompareTo(moveQty) != 0)
                    {
                        line.SetDescription("Total: " + replenish.GetQtyToOrder());
                    }
                    line.SetM_Locator_ID(storage.GetM_Locator_ID());            //	from
                    line.SetM_AttributeSetInstance_ID(storage.GetM_AttributeSetInstance_ID());
                    line.SetM_LocatorTo_ID(M_LocatorTo_ID);                     //	to
                    line.SetM_AttributeSetInstanceTo_ID(storage.GetM_AttributeSetInstance_ID());
                    line.Save();
                    //
                    //target = target.subtract(moveQty);
                    target = Decimal.Subtract(target, moveQty);
                    //if (target.signum() == 0)
                    if (Env.Signum(target) == 0)
                    {
                        break;
                    }
                }
                if (Env.Signum(target) != 0)
                {
                    AddLog("Insufficient Inventory in " + whSource.GetName()
                           + " for " + product.GetName() + " Qty=" + target);
                }
            }
            if (replenishs.Length == 0)
            {
                _info = "No Source Warehouse";
                log.Warning(_info);
            }
            else
            {
                _info = "#" + noMoves + info;
                log.Info(_info);
            }
        }       //	createRequisition
        /// <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);
        }
Exemple #4
0
        /// <summary>
        /// Generate Shipments
        /// </summary>
        /// <param name="idr">Order Query</param>
        /// <returns>info</returns>
        private String Generate(IDataReader idr)
        {
            DataTable dt     = new DataTable();
            MClient   client = MClient.Get(GetCtx());

            try
            {
                dt.Load(idr);
                idr.Close();
                //ResultSet dr = pstmt.executeQuery();
                foreach (DataRow dr in dt.Rows)//  while (dr.next ())		//	Order
                {
                    MOrder order = new MOrder(GetCtx(), dr, Get_TrxName());
                    //	New Header different Shipper, Shipment Location
                    if (!_consolidateDocument ||
                        (_shipment != null &&
                         (_shipment.GetC_BPartner_Location_ID() != order.GetC_BPartner_Location_ID() ||
                          _shipment.GetM_Shipper_ID() != order.GetM_Shipper_ID())))
                    {
                        CompleteShipment();
                    }
                    log.Fine("check: " + order + " - DeliveryRule=" + order.GetDeliveryRule());
                    //
                    DateTime?minGuaranteeDate = _movementDate;
                    bool     completeOrder    = MOrder.DELIVERYRULE_CompleteOrder.Equals(order.GetDeliveryRule());
                    //	OrderLine WHERE
                    String where = " AND M_Warehouse_ID=" + _M_Warehouse_ID;
                    if (_datePromised != null)
                    {
                        where += " AND (TRUNC(DatePromised,'DD')<=" + DB.TO_DATE((DateTime?)_datePromised, true)
                                 + " OR DatePromised IS NULL)";
                        //where += " AND (TRUNC(DatePromised,'DD')<='" + String.Format("{0:dd-MMM-yy}", _datePromised)
                        //    + "' OR DatePromised IS NULL)";
                    }
                    //	Exclude Auto Delivery if not Force
                    if (!MOrder.DELIVERYRULE_Force.Equals(order.GetDeliveryRule()))
                    {
                        where += " AND (C_OrderLine.M_Product_ID IS NULL"
                                 + " OR EXISTS (SELECT * FROM M_Product p "
                                 + "WHERE C_OrderLine.M_Product_ID=p.M_Product_ID"
                                 + " AND IsExcludeAutoDelivery='N'))";
                    }
                    //	Exclude Unconfirmed
                    if (!_isUnconfirmedInOut)
                    {
                        where += " AND NOT EXISTS (SELECT * FROM M_InOutLine iol"
                                 + " INNER JOIN M_InOut io ON (iol.M_InOut_ID=io.M_InOut_ID) "
                                 + "WHERE iol.C_OrderLine_ID=C_OrderLine.C_OrderLine_ID AND io.DocStatus IN ('IP','WC'))";
                    }
                    //	Deadlock Prevention - Order by M_Product_ID
                    MOrderLine[] lines = order.GetLines(where, "ORDER BY C_BPartner_Location_ID, M_Product_ID");
                    for (int i = 0; i < lines.Length; i++)
                    {
                        MOrderLine line = lines[i];
                        if (line.GetM_Warehouse_ID() != _M_Warehouse_ID)
                        {
                            continue;
                        }
                        log.Fine("check: " + line);
                        Decimal onHand    = Env.ZERO;
                        Decimal toDeliver = Decimal.Subtract(line.GetQtyOrdered(),
                                                             line.GetQtyDelivered());
                        MProduct product = line.GetProduct();
                        //	Nothing to Deliver
                        if (product != null && Env.Signum(toDeliver) == 0)
                        {
                            continue;
                        }

                        //	Check / adjust for confirmations
                        Decimal unconfirmedShippedQty = Env.ZERO;
                        if (_isUnconfirmedInOut && product != null && Env.Signum(toDeliver) != 0)
                        {
                            String       where2 = "EXISTS (SELECT * FROM M_InOut io WHERE io.M_InOut_ID=M_InOutLine.M_InOut_ID AND io.DocStatus IN ('IP','WC'))";
                            MInOutLine[] iols   = MInOutLine.GetOfOrderLine(GetCtx(),
                                                                            line.GetC_OrderLine_ID(), where2, null);
                            for (int j = 0; j < iols.Length; j++)
                            {
                                unconfirmedShippedQty = Decimal.Add(unconfirmedShippedQty, iols[j].GetMovementQty());
                            }
                            String logInfo = "Unconfirmed Qty=" + unconfirmedShippedQty
                                             + " - ToDeliver=" + toDeliver + "->";
                            toDeliver = Decimal.Subtract(toDeliver, unconfirmedShippedQty);
                            logInfo  += toDeliver;
                            if (Env.Signum(toDeliver) < 0)
                            {
                                toDeliver = Env.ZERO;
                                logInfo  += " (set to 0)";
                            }
                            //	Adjust On Hand
                            onHand = Decimal.Subtract(onHand, unconfirmedShippedQty);
                            log.Fine(logInfo);
                        }

                        //	Comments & lines w/o product & services
                        if ((product == null || !product.IsStocked()) &&
                            (Env.Signum(line.GetQtyOrdered()) == 0 ||                               //	comments
                             Env.Signum(toDeliver) != 0))                                           //	lines w/o product
                        {
                            if (!MOrder.DELIVERYRULE_CompleteOrder.Equals(order.GetDeliveryRule())) //	printed later
                            {
                                CreateLine(order, line, toDeliver, null, false);
                            }
                            continue;
                        }

                        //	Stored Product
                        MProductCategory pc       = MProductCategory.Get(order.GetCtx(), product.GetM_Product_Category_ID());
                        String           MMPolicy = pc.GetMMPolicy();
                        if (MMPolicy == null || MMPolicy.Length == 0)
                        {
                            MMPolicy = client.GetMMPolicy();
                        }
                        //
                        MStorage[] storages = GetStorages(line.GetM_Warehouse_ID(),
                                                          line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                          product.GetM_AttributeSet_ID(),
                                                          line.GetM_AttributeSetInstance_ID() == 0,
                                                          (DateTime?)minGuaranteeDate,
                                                          MClient.MMPOLICY_FiFo.Equals(MMPolicy));

                        for (int j = 0; j < storages.Length; j++)
                        {
                            MStorage storage = storages[j];
                            onHand = Decimal.Add(onHand, storage.GetQtyOnHand());
                        }
                        bool fullLine = onHand.CompareTo(toDeliver) >= 0 ||
                                        Env.Signum(toDeliver) < 0;

                        //	Complete Order
                        if (completeOrder && !fullLine)
                        {
                            log.Fine("Failed CompleteOrder - OnHand=" + onHand
                                     + " (Unconfirmed=" + unconfirmedShippedQty
                                     + "), ToDeliver=" + toDeliver + " - " + line);
                            completeOrder = false;
                            break;
                        }
                        //	Complete Line
                        else if (fullLine && MOrder.DELIVERYRULE_CompleteLine.Equals(order.GetDeliveryRule()))
                        {
                            log.Fine("CompleteLine - OnHand=" + onHand
                                     + " (Unconfirmed=" + unconfirmedShippedQty
                                     + ", ToDeliver=" + toDeliver + " - " + line);
                            //
                            CreateLine(order, line, toDeliver, storages, false);
                        }
                        //	Availability
                        else if (MOrder.DELIVERYRULE_Availability.Equals(order.GetDeliveryRule()) &&
                                 (Env.Signum(onHand) > 0 ||
                                  Env.Signum(toDeliver) < 0))
                        {
                            Decimal deliver = toDeliver;
                            if (deliver.CompareTo(onHand) > 0)
                            {
                                deliver = onHand;
                            }
                            log.Fine("Available - OnHand=" + onHand
                                     + " (Unconfirmed=" + unconfirmedShippedQty
                                     + "), ToDeliver=" + toDeliver
                                     + ", Delivering=" + deliver + " - " + line);
                            //
                            CreateLine(order, line, deliver, storages, false);
                        }
                        //	Force
                        else if (MOrder.DELIVERYRULE_Force.Equals(order.GetDeliveryRule()))
                        {
                            Decimal deliver = toDeliver;
                            log.Fine("Force - OnHand=" + onHand
                                     + " (Unconfirmed=" + unconfirmedShippedQty
                                     + "), ToDeliver=" + toDeliver
                                     + ", Delivering=" + deliver + " - " + line);
                            //
                            CreateLine(order, line, deliver, storages, true);
                        }
                        //	Manual
                        else if (MOrder.DELIVERYRULE_Manual.Equals(order.GetDeliveryRule()))
                        {
                            log.Fine("Manual - OnHand=" + onHand
                                     + " (Unconfirmed=" + unconfirmedShippedQty
                                     + ") - " + line);
                        }
                        else
                        {
                            log.Fine("Failed: " + order.GetDeliveryRule() + " - OnHand=" + onHand
                                     + " (Unconfirmed=" + unconfirmedShippedQty
                                     + "), ToDeliver=" + toDeliver + " - " + line);
                        }
                    }   //	for all order lines

                    //	Complete Order successful
                    if (completeOrder && MOrder.DELIVERYRULE_CompleteOrder.Equals(order.GetDeliveryRule()))
                    {
                        for (int i = 0; i < lines.Length; i++)
                        {
                            MOrderLine line = lines[i];
                            if (line.GetM_Warehouse_ID() != _M_Warehouse_ID)
                            {
                                continue;
                            }
                            MProduct product   = line.GetProduct();
                            Decimal  toDeliver = Decimal.Subtract(line.GetQtyOrdered(), line.GetQtyDelivered());
                            //
                            MStorage[] storages = null;
                            if (product != null && product.IsStocked())
                            {
                                MProductCategory pc       = MProductCategory.Get(order.GetCtx(), product.GetM_Product_Category_ID());
                                String           MMPolicy = pc.GetMMPolicy();
                                if (MMPolicy == null || MMPolicy.Length == 0)
                                {
                                    MMPolicy = client.GetMMPolicy();
                                }
                                //
                                storages = GetStorages(line.GetM_Warehouse_ID(),
                                                       line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                       product.GetM_AttributeSet_ID(),
                                                       line.GetM_AttributeSetInstance_ID() == 0, (DateTime?)minGuaranteeDate,
                                                       MClient.MMPOLICY_FiFo.Equals(MMPolicy));
                            }
                            //
                            CreateLine(order, line, toDeliver, storages, false);
                        }
                    }
                    _line += 1000;
                }       //	while order
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, _sql, e);
            }
            finally
            {
                if (idr != null)
                {
                    idr.Close();
                }
                dt = null;
            }
            CompleteShipment();
            return("@Created@ = " + _created);
        }