public Dictionary <string, string> GetProduct(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');

            //Assign parameter value
            int M_Product_ID   = Util.GetValueOfInt(paramValue[0].ToString());
            int M_Warehouse_ID = 0;

            if (paramValue.Length > 1)
            {
                M_Warehouse_ID = Util.GetValueOfInt(paramValue[1].ToString());
            }
            //End Assign parameter value

            MProduct product = MProduct.Get(ctx, M_Product_ID);
            Dictionary <string, string> result = new Dictionary <string, string>();

            result["C_UOM_ID"]  = product.GetC_UOM_ID().ToString();
            result["IsStocked"] = product.IsStocked() ? "Y" : "N";
            if (M_Product_ID > 0)
            {
                if (M_Warehouse_ID > 0)
                {
                    result["M_Locator_ID"] = MProductLocator.GetFirstM_Locator_ID(product, M_Warehouse_ID).ToString();
                }
            }
            return(result);
        }
        public JsonResult GetProduct(string fields)
        {
            string retError = "";
            string retJSON  = "";

            if (Session["ctx"] != null)
            {
                VAdvantage.Utility.Ctx ctx = Session["ctx"] as Ctx;
                string[] paramValue        = fields.Split(',');
                int      M_Product_ID;

                //Assign parameter value
                M_Product_ID = Util.GetValueOfInt(paramValue[0].ToString());
                MProduct product = MProduct.Get(ctx, M_Product_ID);


                Dictionary <String, String> retPDic = new Dictionary <string, string>();
                retPDic["IsStocked"] = product.IsStocked().ToString();
                //retlst.Add(retValue);

                //retVal.Add(notReserved);


                retJSON = JsonConvert.SerializeObject(retPDic);
            }
            else
            {
                retError = "Session Expired";
            }
            return(Json(new { result = retJSON, error = retError }, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// Create Facts (the accounting logic) for
        ///  PJI
        ///  <pre>
        ///  Issue
        ///      ProjectWIP      DR
        ///      Inventory               CR
        ///  </pre>
        ///  Project Account is either Asset or WIP depending on Project Type
        /// </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());

            MProject project         = new MProject(GetCtx(), _issue.GetC_Project_ID(), null);
            String   ProjectCategory = project.GetProjectCategory();
            MProduct product         = MProduct.Get(GetCtx(), _issue.GetM_Product_ID());

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

            //  Issue Cost
            Decimal?cost = null;

            if (_issue.GetM_InOutLine_ID() != 0)
            {
                cost = GetPOCost(as1);
            }
            else if (_issue.GetS_TimeExpenseLine_ID() != 0)
            {
                cost = GetLaborCost(as1);
            }
            if (cost == null)   //	standard Product Costs
            {
                cost = _line.GetProductCosts(as1, GetAD_Org_ID(), false);
            }

            //  Project         DR
            int acctType = ACCTTYPE_ProjectWIP;

            if (MProject.PROJECTCATEGORY_AssetProject.Equals(ProjectCategory))
            {
                acctType = ACCTTYPE_ProjectAsset;
            }
            dr = fact.CreateLine(_line,
                                 GetAccount(acctType, as1), as1.GetC_Currency_ID(), cost, null);
            dr.SetQty((Decimal?)Decimal.Negate(Utility.Util.GetValueOfDecimal(_line.GetQty())));

            //  Inventory               CR
            acctType = ProductCost.ACCTTYPE_P_Asset;
            if (product.IsService())
            {
                acctType = ProductCost.ACCTTYPE_P_Expense;
            }
            cr = fact.CreateLine(_line,
                                 _line.GetAccount(acctType, as1),
                                 as1.GetC_Currency_ID(), null, cost);
            cr.SetM_Locator_ID(_line.GetM_Locator_ID());
            cr.SetLocationFromLocator(_line.GetM_Locator_ID(), true);   // from Loc
            //
            List <Fact> facts = new List <Fact>();

            facts.Add(fact);
            return(facts);
        }
        /// <summary>
        /// Get UPM Precision
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public int GetUOMPrecision(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            int      M_Product_ID;

            M_Product_ID = Util.GetValueOfInt(paramValue[0].ToString());
            return(MProduct.Get(ctx, M_Product_ID).GetUOMPrecision());
        }
        //Added By amit
        public int GetTaxCategory(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            int      M_Product_ID;

            M_Product_ID = Util.GetValueOfInt(paramValue[0].ToString());
            return(MProduct.Get(ctx, M_Product_ID).GetC_TaxCategory_ID());
        }
Exemple #6
0
        /// <summary>
        /// Create/Add to Inventory Line Query
        /// </summary>
        /// <param name="M_Locator_ID">locator</param>
        /// <param name="M_Product_ID">product</param>
        /// <param name="M_AttributeSetInstance_ID">asi</param>
        /// <param name="qtyOnHand">quantity</param>
        /// <param name="M_AttributeSet_ID">attribute set</param>
        /// <returns>lines added</returns>
        private string InsertInventoryLine(int M_Locator_ID, int M_Product_ID, int lineNo,
                                           int M_AttributeSetInstance_ID, Decimal qtyOnHand, int M_AttributeSet_ID)
        {
            MInventoryLine line           = new MInventoryLine(GetCtx(), 0, Get_Trx());
            int            line_ID        = DB.GetNextID(GetCtx(), "M_InventoryLine", Get_Trx());
            string         qry            = "select m_warehouse_id from m_locator where m_locator_id=" + M_Locator_ID;
            int            M_Warehouse_ID = Util.GetValueOfInt(DB.ExecuteScalar(qry, null, Get_Trx()));
            MWarehouse     wh             = MWarehouse.Get(GetCtx(), M_Warehouse_ID);

            if (wh.IsDisallowNegativeInv() == true)
            {
                if (qtyOnHand < 0)
                {
                    return("");
                }
            }
            MProduct product = MProduct.Get(GetCtx(), M_Product_ID);

            if (product != null)
            {
                int precision = product.GetUOMPrecision();
                if (Env.Signum(qtyOnHand) != 0)
                {
                    qtyOnHand = Decimal.Round(qtyOnHand, precision, MidpointRounding.AwayFromZero);
                }
            }
            string sql = @"INSERT INTO M_InventoryLine (AD_Client_ID, AD_Org_ID,IsActive, Created, CreatedBy, Updated, UpdatedBy, Line, M_Inventory_ID, M_InventoryLine_ID,  
                M_Locator_ID, M_Product_ID, M_AttributeSetInstance_ID, QtyBook, QtyCount, OpeningStock, AsOnDateCount, DifferenceQty, AdjustmentType";

            if (line.Get_ColumnIndex("C_UOM_ID") > 0)
            {
                sql += ", QtyEntered, C_UOM_ID";
            }

            if (line.Get_ColumnIndex("IsFromProcess") > 0)
            {
                sql += ",IsFromProcess";
            }
            sql += " ) VALUES ( " + _inventory.GetAD_Client_ID() + "," + _inventory.GetAD_Org_ID() + ",'Y'," + GlobalVariable.TO_DATE(DateTime.Now, true) + "," + 0 + "," +
                   GlobalVariable.TO_DATE(DateTime.Now, true) + "," + 0 + "," + lineNo + "," + _m_Inventory_ID + "," + line_ID + "," + M_Locator_ID + "," + M_Product_ID + "," +
                   M_AttributeSetInstance_ID + "," + qtyOnHand + "," + qtyOnHand + "," + qtyOnHand + "," + qtyOnHand + "," + 0 + ",'A'";

            if (line.Get_ColumnIndex("C_UOM_ID") > 0)
            {
                sql += "," + qtyOnHand + "," + product.GetC_UOM_ID();
            }

            if (line.Get_ColumnIndex("IsFromProcess") > 0)
            {
                sql += ",'Y'";
            }
            string insertQry = " BEGIN execute immediate('" + sql.Replace("'", "''") + ")'); exception when others then null; END;";

            return(insertQry);
        }
        /// <summary>
        /// Is this an Item Product (vs. not a Service, a charge)
        /// </summary>
        /// <returns>true if product</returns>
        public bool IsItem()
        {
            if (_isItem != null)
            {
                return(Utility.Util.GetValueOfBool(_isItem));//.booleanValue();
            }

            _isItem = false;
            if (GetM_Product_ID() != 0)
            {
                MProduct product = MProduct.Get(_po.GetCtx(), GetM_Product_ID());
                if (product.Get_ID() == GetM_Product_ID() && product.IsItem())
                {
                    _isItem = true;
                }
            }
            return(Utility.Util.GetValueOfBool(_isItem));//.booleanValue();
        }
Exemple #8
0
        /// <summary>
        /// Check Qty Availablity in warehouse when Disallow Negative Inventory = true
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="M_Warehouse_ID">warehouse refernce - for checking disallow negative inventory or not</param>
        /// <param name="M_Locator_ID">locator ref - in which locator we have to check stock</param>
        /// <param name="M_Product_ID">product ref -- to which product, need to check stock</param>
        /// <param name="M_AttributeSetInstance_ID">AttributeSetInstance -- to which ASI, need to check stock</param>
        /// <param name="MovementQty">qty to be impacted</param>
        /// <param name="trxName">system transaction</param>
        /// <returns>TRUE/False</returns>
        private bool CheckQtyAvailablity(Ctx ctx, int M_Warehouse_ID, int M_Locator_ID, int M_Product_ID, int M_AttributeSetInstance_ID, Decimal?MovementQty, Trx trxName)
        {
            MWarehouse wh      = MWarehouse.Get(ctx, M_Warehouse_ID);
            MProduct   product = null;

            if (wh.IsDisallowNegativeInv() && M_Product_ID > 0)
            {
                product = MProduct.Get(ctx, M_Product_ID);
                string qry = "SELECT NVL(SUM(NVL(QtyOnHand,0)),0) AS QtyOnHand FROM M_Storage where m_locator_id=" + M_Locator_ID + @" and m_product_id=" + M_Product_ID;
                qry += " AND NVL(M_AttributeSetInstance_ID, 0) =" + M_AttributeSetInstance_ID;
                Decimal?OnHandQty = Convert.ToDecimal(DB.ExecuteScalar(qry, null, trxName));
                if (OnHandQty + MovementQty < 0)
                {
                    log.SaveError("Info", product.GetName() + ", " + Msg.GetMsg(GetCtx(), "VIS_InsufficientQty") + OnHandQty);
                    return(false);
                }
            }
            return(true);
        }
        public JsonResult GetProductStdPrecision(string fields)
        {
            string retError = "";
            string retJSON  = "";

            if (Session["ctx"] != null)
            {
                VAdvantage.Utility.Ctx ctx = Session["ctx"] as Ctx;
                string[] paramValue        = fields.Split(',');
                int      M_Product_ID;

                //Assign parameter value
                M_Product_ID = Util.GetValueOfInt(paramValue[0].ToString());
                //C_UOM_To_ID = Util.GetValueOfInt(paramValue[0].ToString());
                //Price = Util.GetValueOfInt(paramValue[2].ToString());


                //End Assign parameter value
                //var QtyOrdered = Utility.Util.getValueOfDecimal(mTab.getValue("QtyOrdered"));
                //var M_Warehouse_ID = ctx.getContextAsInt(WindowNo, "M_Warehouse_ID");
                //var M_AttributeSetInstance_ID = ctx.getContextAsInt(WindowNo, "M_AttributeSetInstance_ID");

                //Decimal? QtyOrdered = (Decimal?)MUOMConversion.ConvertProductTo(ctx, M_Product_ID,
                //      C_UOM_To_ID, QtyEntered);

                int retValue = MProduct.Get(ctx, M_Product_ID).GetUOMPrecision();

                List <int> retlst = new List <int>();

                retlst.Add(retValue);

                //retVal.Add(notReserved);


                retJSON = JsonConvert.SerializeObject(retlst);
            }
            else
            {
                retError = "Session Expired";
            }
            return(Json(new { result = retJSON, error = retError }, JsonRequestBehavior.AllowGet));
        }
Exemple #10
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@");
        }
Exemple #11
0
        /// <summary>
        /// Create/Add to Inventory Line Query
        /// </summary>
        /// <param name="M_Locator_ID">locator</param>
        /// <param name="M_Product_ID">product</param>
        /// <param name="M_AttributeSetInstance_ID">asi</param>
        /// <param name="currentQty">quantity</param>
        /// <param name="M_AttributeSet_ID">attribute set</param>
        /// <returns>lines added</returns>
        private string UpdateInventoryLine(int M_InventoryLine_ID, int M_Product_ID, int M_Locator_ID, Decimal currentQty, string AdjustType, Decimal AsOnDateCount, Decimal DiffQty)
        {
            string     qry            = "select m_warehouse_id from m_locator where m_locator_id=" + M_Locator_ID;
            int        M_Warehouse_ID = Util.GetValueOfInt(DB.ExecuteScalar(qry, null, Get_Trx()));
            MWarehouse wh             = MWarehouse.Get(GetCtx(), M_Warehouse_ID);

            if (wh.IsDisallowNegativeInv() == true)
            {
                if (currentQty < 0)
                {
                    return("");
                }
            }
            MProduct product = MProduct.Get(GetCtx(), M_Product_ID);

            if (product != null)
            {
                int precision = product.GetUOMPrecision();
                if (Env.Signum(currentQty) != 0)
                {
                    currentQty = Decimal.Round(currentQty, precision, MidpointRounding.AwayFromZero);
                }
            }
            if (AdjustType == "A")
            {
                DiffQty = Util.GetValueOfDecimal(Decimal.Subtract(currentQty, AsOnDateCount));
            }
            else if (AdjustType == "D")
            {
                AsOnDateCount = Util.GetValueOfDecimal(Decimal.Subtract(currentQty, DiffQty));
            }
            Decimal QtyCount = Util.GetValueOfDecimal(Decimal.Subtract(currentQty, DiffQty));

            // Changes by Bharat on 02 Aug 2017 as issue given by Ravikant
            string sql = @"UPDATE M_InventoryLine SET QtyBook = " + currentQty + ",QtyCount = " + QtyCount + ",OpeningStock = " + currentQty + ",AsOnDateCount = " + AsOnDateCount +
                         ",DifferenceQty = " + DiffQty + " WHERE M_InventoryLine_ID = " + M_InventoryLine_ID;

            string updateQry = " BEGIN execute immediate('" + sql.Replace("'", "''") + "'); exception when others then null; END;";

            return(updateQry);
        }
Exemple #12
0
        }       //	prepare

        /// <summary>
        /// Perrform Process.
        /// </summary>
        /// <returns>Info</returns>
        protected override String DoIt()
        {
            log.Info("M_Locator_ID=" + _M_Locator_ID + ",MovementDate=" + _MovementDate);
            //
            StringBuilder sql         = null;
            int           no          = 0;
            String        clientCheck = " AND AD_Client_ID=" + _AD_Client_ID;

            //	****	Prepare	****

            //	Delete Old Imported
            if (_DeleteOldImported)
            {
                sql = new StringBuilder("DELETE FROM I_Inventory "
                                        + "WHERE I_IsImported='Y'").Append(clientCheck);
                no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
                log.Fine("Delete Old Impored =" + no);
            }

            //	Set Client, Org, Location, IsActive, Created/Updated
            sql = new StringBuilder("UPDATE I_Inventory "
                                    + "SET AD_Client_ID = COALESCE (AD_Client_ID,").Append(_AD_Client_ID).Append("),"
                                                                                                                 + " AD_Org_ID = COALESCE (AD_Org_ID,").Append(_AD_Org_ID).Append("),");
            if (_MovementDate != null)
            {
                sql.Append(" MovementDate = COALESCE (MovementDate,").Append(DataBase.DB.TO_DATE(_MovementDate)).Append("),");
            }
            sql.Append(" IsActive = COALESCE (IsActive, 'Y'),"
                       + " Created = COALESCE (Created, SysDate),"
                       + " CreatedBy = COALESCE (CreatedBy, 0),"
                       + " Updated = COALESCE (Updated, SysDate),"
                       + " UpdatedBy = COALESCE (UpdatedBy, 0),"
                       + " I_ErrorMsg = NULL,"
                       + " M_Warehouse_ID = NULL," //	reset
                       + " I_IsImported = 'N' "
                       + "WHERE I_IsImported<>'Y' OR I_IsImported IS NULL");
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Info("Reset=" + no);

            String ts = DataBase.DB.IsPostgreSQL() ? "COALESCE(I_ErrorMsg,'')" : "I_ErrorMsg";  //java bug, it could not be used directly

            sql = new StringBuilder("UPDATE I_Inventory o "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Org, '"
                                    + "WHERE (AD_Org_ID IS NULL OR AD_Org_ID=0"
                                    + " OR EXISTS (SELECT * FROM AD_Org oo WHERE o.AD_Org_ID=oo.AD_Org_ID AND (oo.IsSummary='Y' OR oo.IsActive='N')))"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Org=" + no);
            }

            // gwu: bug 1703137
            // if Warehouse key provided, get Warehouse ID
            sql = new StringBuilder("UPDATE I_Inventory i "
                                    + "SET M_Warehouse_ID=(SELECT MAX(M_Warehouse_ID) FROM M_Warehouse w"
                                    + " WHERE i.WarehouseValue=w.Value AND i.AD_Client_ID=w.AD_Client_ID) "
                                    + "WHERE M_Warehouse_ID IS NULL AND WarehouseValue IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Warehouse from Value =" + no);

            //	Location
            sql = new StringBuilder("UPDATE I_Inventory i "
                                    + "SET M_Locator_ID=(SELECT MAX(M_Locator_ID) FROM M_Locator l"
                                    + " WHERE i.LocatorValue=l.Value AND COALESCE (i.M_Warehouse_ID, l.M_Warehouse_ID)=l.M_Warehouse_ID AND i.AD_Client_ID=l.AD_Client_ID) "
                                    + "WHERE M_Locator_ID IS NULL AND LocatorValue IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Locator from Value =" + no);
            sql = new StringBuilder("UPDATE I_Inventory i "
                                    + "SET M_Locator_ID=(SELECT MAX(M_Locator_ID) FROM M_Locator l"
                                    + " WHERE i.X=l.X AND i.Y=l.Y AND i.Z=l.Z AND COALESCE (i.M_Warehouse_ID, l.M_Warehouse_ID)=l.M_Warehouse_ID AND i.AD_Client_ID=l.AD_Client_ID) "
                                    + "WHERE M_Locator_ID IS NULL AND X IS NOT NULL AND Y IS NOT NULL AND Z IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Locator from X,Y,Z =" + no);
            if (_M_Locator_ID != 0)
            {
                sql = new StringBuilder("UPDATE I_Inventory "
                                        + "SET M_Locator_ID = ").Append(_M_Locator_ID).Append(
                    " WHERE M_Locator_ID IS NULL"
                    + " AND I_IsImported<>'Y'").Append(clientCheck);
                no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
                log.Fine("Set Locator from Parameter=" + no);
            }
            sql = new StringBuilder("UPDATE I_Inventory "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No Location, ' "
                                    + "WHERE M_Locator_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No Location=" + no);
            }


            //	Set M_Warehouse_ID
            sql = new StringBuilder("UPDATE I_Inventory i "
                                    + "SET M_Warehouse_ID=(SELECT M_Warehouse_ID FROM M_Locator l WHERE i.M_Locator_ID=l.M_Locator_ID) "
                                    + "WHERE M_Locator_ID IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Warehouse from Locator =" + no);
            sql = new StringBuilder("UPDATE I_Inventory "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No Warehouse, ' "
                                    + "WHERE M_Warehouse_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No Warehouse=" + no);
            }


            //	Product
            sql = new StringBuilder("UPDATE I_Inventory i "
                                    + "SET M_Product_ID=(SELECT MAX(M_Product_ID) FROM M_Product p"
                                    + " WHERE i.Value=p.Value AND i.AD_Client_ID=p.AD_Client_ID) "
                                    + "WHERE M_Product_ID IS NULL AND Value IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Product from Value=" + no);
            sql = new StringBuilder("UPDATE I_Inventory i "
                                    + "SET M_Product_ID=(SELECT MAX(M_Product_ID) FROM M_Product p"
                                    + " WHERE i.UPC=p.UPC AND i.AD_Client_ID=p.AD_Client_ID) "
                                    + "WHERE M_Product_ID IS NULL AND UPC IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Product from UPC=" + no);
            sql = new StringBuilder("UPDATE I_Inventory "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No Product, ' "
                                    + "WHERE M_Product_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No Product=" + no);
            }

            //	No QtyCount
            sql = new StringBuilder("UPDATE I_Inventory "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No Qty Count, ' "
                                    + "WHERE QtyCount IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No QtyCount=" + no);
            }

            Commit();

            /*********************************************************************/

            MInventory inventory = null;

            int noInsert     = 0;
            int noInsertLine = 0;

            //	Go through Inventory Records
            sql = new StringBuilder("SELECT * FROM I_Inventory "
                                    + "WHERE I_IsImported='N'").Append(clientCheck)
                  .Append(" ORDER BY M_Warehouse_ID, TRUNC(MovementDate,'DD'), I_Inventory_ID");
            IDataReader idr = null;

            try
            {
                //PreparedStatement pstmt = DataBase.prepareStatement (sql.ToString (), Get_TrxName());
                //ResultSet rs = pstmt.executeQuery ();
                idr = DataBase.DB.ExecuteReader(sql.ToString(), null, Get_TrxName());
                //
                int      x_M_Warehouse_ID = -1;
                DateTime?x_MovementDate   = null;
                while (idr.Read())
                {
                    X_I_Inventory imp          = new X_I_Inventory(GetCtx(), idr, Get_TrxName());
                    DateTime?     MovementDate = TimeUtil.GetDay(imp.GetMovementDate());

                    if (inventory == null ||
                        imp.GetM_Warehouse_ID() != x_M_Warehouse_ID ||
                        !MovementDate.Equals(x_MovementDate))
                    {
                        inventory = new MInventory(GetCtx(), 0, Get_TrxName());
                        inventory.SetClientOrg(imp.GetAD_Client_ID(), imp.GetAD_Org_ID());
                        inventory.SetDescription("I " + imp.GetM_Warehouse_ID() + " " + MovementDate);
                        inventory.SetM_Warehouse_ID(imp.GetM_Warehouse_ID());
                        inventory.SetMovementDate(MovementDate);
                        //
                        if (!inventory.Save())
                        {
                            log.Log(Level.SEVERE, "Inventory not saved");
                            break;
                        }
                        x_M_Warehouse_ID = imp.GetM_Warehouse_ID();
                        x_MovementDate   = MovementDate;
                        noInsert++;
                    }

                    //	Line
                    int M_AttributeSetInstance_ID = 0;
                    if (imp.GetLot() != null || imp.GetSerNo() != null)
                    {
                        MProduct product = MProduct.Get(GetCtx(), imp.GetM_Product_ID());
                        if (product.IsInstanceAttribute())
                        {
                            MAttributeSet         mas  = product.GetAttributeSet();
                            MAttributeSetInstance masi = new MAttributeSetInstance(GetCtx(), 0, mas.GetM_AttributeSet_ID(), Get_TrxName());
                            if (mas.IsLot() && imp.GetLot() != null)
                            {
                                masi.SetLot(imp.GetLot(), imp.GetM_Product_ID());
                            }
                            if (mas.IsSerNo() && imp.GetSerNo() != null)
                            {
                                masi.SetSerNo(imp.GetSerNo());
                            }
                            masi.SetDescription();
                            masi.Save();
                            M_AttributeSetInstance_ID = masi.GetM_AttributeSetInstance_ID();
                        }
                    }
                    MInventoryLine line = new MInventoryLine(inventory,
                                                             imp.GetM_Locator_ID(), imp.GetM_Product_ID(), M_AttributeSetInstance_ID,
                                                             imp.GetQtyBook(), imp.GetQtyCount());
                    if (line.Save())
                    {
                        imp.SetI_IsImported(X_I_Inventory.I_ISIMPORTED_Yes);
                        imp.SetM_Inventory_ID(line.GetM_Inventory_ID());
                        imp.SetM_InventoryLine_ID(line.GetM_InventoryLine_ID());
                        imp.SetProcessed(true);
                        if (imp.Save())
                        {
                            noInsertLine++;
                        }
                    }
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql.ToString(), e);
            }

            //	Set Error to indicator to not imported
            sql = new StringBuilder("UPDATE I_Inventory "
                                    + "SET I_IsImported='N', Updated=SysDate "
                                    + "WHERE I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            AddLog(0, null, Utility.Util.GetValueOfDecimal(no), "@Errors@");
            //
            AddLog(0, null, Utility.Util.GetValueOfDecimal(noInsert), "@M_Inventory_ID@: @Inserted@");
            AddLog(0, null, Utility.Util.GetValueOfDecimal(noInsertLine), "@M_InventoryLine_ID@: @Inserted@");
            return("");
        }       //	doIt
Exemple #13
0
        /// <summary>
        /// is used to save data in case of Full move container / full qty move
        /// </summary>
        /// <param name="movementId">movement header refernce</param>
        /// <param name="fromLocatorId">From Locator - from where we have to move product</param>
        /// <param name="fromContainerId">From Container - from which container, we have to move product</param>
        /// <param name="toLocatorId">To Locator - where we are moving product</param>
        /// <param name="toContainerId">To container - in which container we are moving product</param>
        /// <param name="lineNo"></param>
        /// <param name="isMoveFullContainerQty">Is Container also move with Product</param>
        /// <param name="trx">Self created Trx</param>
        /// <returns>Message : lines inserted or not</returns>
        public String SaveMoveLinewithFullContainer(int movementId, int fromLocatorId, int fromContainerId, int toLocatorId, int toContainerId, int lineNo, bool isMoveFullContainerQty, Trx trx)
        {
            MMovement     movement         = new MMovement(_ctx, movementId, trx);
            string        childContainerId = null;
            StringBuilder error            = new StringBuilder();

            // Get Path upto selected container
            string sql           = @"SELECT sys_connect_by_path(m_productcontainer_id,'->') tree
                            FROM m_productcontainer 
                           WHERE m_productcontainer_id = " + fromContainerId + @"
                            START WITH ref_m_container_id IS NULL CONNECT BY prior m_productcontainer_id = ref_m_container_id
                           ORDER BY tree ";
            string pathContainer = Util.GetValueOfString(DB.ExecuteScalar(sql, null, trx));

            // child records with Parent Id
            if (!isMoveFullContainerQty)
            {
                sql = @"SELECT tree, m_productcontainer_id FROM
                            (SELECT sys_connect_by_path(m_productcontainer_id,'->') tree , m_productcontainer_id
                             FROM m_productcontainer
                             START WITH ref_m_container_id IS NULL
                             CONNECT BY prior m_productcontainer_id = ref_m_container_id
                             ORDER BY tree  
                             )
                           WHERE tree LIKE ('" + pathContainer + "%') ";
                DataSet ds = DB.ExecuteDataset(sql, null, trx);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (String.IsNullOrEmpty(childContainerId))
                        {
                            childContainerId = Util.GetValueOfString(ds.Tables[0].Rows[i]["m_productcontainer_id"]);
                        }
                        else
                        {
                            childContainerId += "," + Util.GetValueOfString(ds.Tables[0].Rows[i]["m_productcontainer_id"]);
                        }
                    }
                }
                ds.Dispose();
            }
            else
            {
                childContainerId = fromContainerId.ToString();
            }

            // check is same container already moved to another container
            // Ex :: p1 -> c1 and p1 -> c2
            // OR also check -- is any other container is moving into exist target container
            // Ex :: p1 -> c1 and p2 -> p1
            if (!isMoveFullContainerQty)
            {
                if (!IsContainerMoved(movementId, pathContainer, childContainerId, toContainerId, trx))
                {
                    return(Msg.GetMsg(_ctx, "VIS_AlreadyMoved"));
                }
            }

            // not to move Parent container to its child container
            if (toContainerId > 0 && childContainerId.Contains(toContainerId.ToString()))
            {
                //Parent cant be Move to its own child
                return(Msg.GetMsg(_ctx, "VIS_cantMoveParentTochild"));
            }

            // Get All records of Parent Container and child container
            sql = @"SELECT * FROM (
                            SELECT p.M_PRODUCT_ID, p.NAME, p.C_UOM_ID, u.Name AS UomName,  t.M_ATTRIBUTESETINSTANCE_ID, t.M_ProductContainer_ID,
                            SUM(t.ContainerCurrentQty) keep (dense_rank last ORDER BY t.MovementDate, t.M_Transaction_ID) AS ContainerCurrentQty
                            FROM M_Transaction t
                            INNER JOIN M_Product p ON p.M_Product_ID = t.M_Product_ID
                            INNER JOIN C_UOM u ON u.C_UOM_ID = p.C_UOM_ID
                            WHERE t.IsActive = 'Y' AND NVL(t.M_ProductContainer_ID, 0) IN ( " + childContainerId +
                  @" ) AND t.MovementDate <=" + GlobalVariable.TO_DATE(movement.GetMovementDate(), true) + @" 
                               AND t.M_Locator_ID  = " + fromLocatorId + @"
                               AND t.AD_Client_ID  = " + movement.GetAD_Client_ID() + @"
                            GROUP BY p.M_PRODUCT_ID, p.NAME, p.C_UOM_ID, u.Name, t.M_ATTRIBUTESETINSTANCE_ID, t.M_ProductContainer_ID 
                          ) t WHERE ContainerCurrentQty <> 0 ";
            DataSet dsRecords = DB.ExecuteDataset(sql, null, trx);

            if (dsRecords != null && dsRecords.Tables.Count > 0 && dsRecords.Tables[0].Rows.Count > 0)
            {
                int           movementlineId = 0;
                MMovementLine moveline       = null;
                MProduct      product        = null;
                for (int i = 0; i < dsRecords.Tables[0].Rows.Count; i++)
                {
                    movementlineId = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT NVL(M_MovementLine_ID, 0) AS M_Movement_ID FROM M_MovementLine WHERE 
                             M_Movement_ID = " + Util.GetValueOfInt(movementId) +
                                                                         @" AND M_Product_ID = " + Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_Product_ID"]) +
                                                                         @" AND NVL(M_AttributeSetInstance_ID, 0) = " + Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]) +
                                                                         @" AND M_Locator_ID = " + Util.GetValueOfInt(fromLocatorId) +
                                                                         @" AND NVL(M_ProductContainer_ID, 0) = " + Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_ProductContainer_ID"]) +
                                                                         @" AND M_LocatorTo_ID = " + Util.GetValueOfInt(toLocatorId) +
                                                                         @" AND NVL(Ref_M_ProductContainerTo_ID, 0) = " + toContainerId +
                                                                         @" AND AD_Org_ID = " + movement.GetAD_Org_ID()));

                    if (movementlineId > 0)
                    {
                        moveline = new MMovementLine(_ctx, movementlineId, trx);
                    }
                    else
                    {
                        moveline = new MMovementLine(_ctx, 0, trx);
                    }
                    if (movementlineId == 0)
                    {
                        #region Create new record of movement line
                        lineNo += 10;
                        moveline.SetAD_Client_ID(movement.GetAD_Client_ID());
                        moveline.SetAD_Org_ID(movement.GetAD_Org_ID());
                        moveline.SetM_Movement_ID(movement.GetM_Movement_ID());
                        moveline.SetLine(lineNo);
                        moveline.SetM_Product_ID(Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_Product_ID"]));
                        moveline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]));
                        moveline.SetC_UOM_ID(Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["C_UOM_ID"]));
                        moveline.SetM_Locator_ID(fromLocatorId);
                        moveline.SetM_LocatorTo_ID(toLocatorId);
                        moveline.SetM_ProductContainer_ID(Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_ProductContainer_ID"]));
                        moveline.SetRef_M_ProductContainerTo_ID(toContainerId);
                        moveline.SetQtyEntered(Util.GetValueOfDecimal(dsRecords.Tables[0].Rows[i]["ContainerCurrentQty"]));
                        moveline.SetMovementQty(Util.GetValueOfDecimal(dsRecords.Tables[0].Rows[i]["ContainerCurrentQty"]));
                        moveline.SetMoveFullContainer(isMoveFullContainerQty ? false : true);
                        // when move full container, then only need to update IsParentMove and Target container (which represent - to which container we are moving)
                        // and set true value on those line which container are moving, not on its child container
                        if (!isMoveFullContainerQty)
                        {
                            moveline.SetIsParentMove(Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_ProductContainer_ID"]) == fromContainerId ? true : false);
                            moveline.SetTargetContainer_ID(fromContainerId);
                        }
                        #endregion
                    }
                    else
                    {
                        #region Update record of movement line
                        moveline.SetQtyEntered(Decimal.Add(moveline.GetQtyEntered(), Util.GetValueOfDecimal(dsRecords.Tables[0].Rows[i]["ContainerCurrentQty"])));
                        moveline.SetMovementQty(Decimal.Add(moveline.GetMovementQty(), Util.GetValueOfDecimal(dsRecords.Tables[0].Rows[i]["ContainerCurrentQty"])));
                        moveline.SetMoveFullContainer(true);
                        #endregion
                    }
                    if (!moveline.Save(trx))
                    {
                        #region Save error catch and rollback
                        product = MProduct.Get(_ctx, Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_Product_ID"]));
                        ValueNamePair pp = VLogger.RetrieveError();
                        if (pp != null)
                        {
                            _log.SaveError("Movement line not inserted through Move Container Form : ", pp.GetName());
                            if (String.IsNullOrEmpty(error.ToString()))
                            {
                                error.Append(Msg.GetMsg(_ctx, "VIS_MoveLineNotSaveFor") + product.GetName() + Msg.GetMsg(_ctx, "VIS_DueTo") + pp.GetName());
                            }
                            else
                            {
                                error.Append(" , " + Msg.GetMsg(_ctx, "VIS_MoveLineNotSaveFor") + product.GetName() + Msg.GetMsg(_ctx, "VIS_DueTo") + pp.GetName());
                            }
                        }
                        trx.Rollback();
                        #endregion
                    }
                    else
                    {
                        trx.Commit();
                    }
                }
            }
            else
            {
                return(Msg.GetMsg(_ctx, "VIS_ContainerhaveNoRecord"));
            }

            return(String.IsNullOrEmpty(error.ToString()) ? "VIS_SuccessFullyInserted" : error.ToString());
        }
Exemple #14
0
        /// <summary>
        /// Get Costs
        /// </summary>
        /// <param name="cost">Cost</param>
        /// <param name="to">where to get costs from </param>
        /// <returns>costs (could be 0) or null if not found</returns>
        private Decimal?GetCosts(VAdvantage.Model.MCost cost, String to)
        {
            Decimal?retValue = null;

            //	Average Invoice
            if (to.Equals(TO_AverageInvoice))
            {
                MCostElement ce = GetCostElement(TO_AverageInvoice);
                if (ce == null)
                {
                    throw new Exception("CostElement not found: " + TO_AverageInvoice);
                }
                VAdvantage.Model.MCost xCost = VAdvantage.Model.MCost.Get(GetCtx(), cost.GetAD_Client_ID(), cost.GetAD_Org_ID(), cost.GetM_Product_ID(), cost.GetM_CostType_ID(), cost.GetC_AcctSchema_ID(), ce.GetM_CostElement_ID(), cost.GetM_AttributeSetInstance_ID());
                if (xCost != null)
                {
                    retValue = xCost.GetCurrentCostPrice();
                }
            }
            //	Average Invoice History
            else if (to.Equals(TO_AverageInvoiceHistory))
            {
                MCostElement ce = GetCostElement(TO_AverageInvoice);
                if (ce == null)
                {
                    throw new Exception("CostElement not found: " + TO_AverageInvoice);
                }
                VAdvantage.Model.MCost xCost = VAdvantage.Model.MCost.Get(GetCtx(), cost.GetAD_Client_ID(), cost.GetAD_Org_ID(), cost.GetM_Product_ID(), cost.GetM_CostType_ID(), cost.GetC_AcctSchema_ID(), ce.GetM_CostElement_ID(), cost.GetM_AttributeSetInstance_ID());
                if (xCost != null)
                {
                    retValue = xCost.GetHistoryAverage();
                }
            }

            //	Average PO
            else if (to.Equals(TO_AveragePO))
            {
                MCostElement ce = GetCostElement(TO_AveragePO);
                if (ce == null)
                {
                    throw new Exception("CostElement not found: " + TO_AveragePO);
                }
                VAdvantage.Model.MCost xCost = VAdvantage.Model.MCost.Get(GetCtx(), cost.GetAD_Client_ID(), cost.GetAD_Org_ID(), cost.GetM_Product_ID(), cost.GetM_CostType_ID(), cost.GetC_AcctSchema_ID(), ce.GetM_CostElement_ID(), cost.GetM_AttributeSetInstance_ID());
                if (xCost != null)
                {
                    retValue = xCost.GetCurrentCostPrice();
                }
            }
            //	Average PO History
            else if (to.Equals(TO_AveragePOHistory))
            {
                MCostElement ce = GetCostElement(TO_AveragePO);
                if (ce == null)
                {
                    throw new Exception("CostElement not found: " + TO_AveragePO);
                }
                VAdvantage.Model.MCost xCost = VAdvantage.Model.MCost.Get(GetCtx(), cost.GetAD_Client_ID(), cost.GetAD_Org_ID(), cost.GetM_Product_ID(), cost.GetM_CostType_ID(), cost.GetC_AcctSchema_ID(), ce.GetM_CostElement_ID(), cost.GetM_AttributeSetInstance_ID());
                if (xCost != null)
                {
                    retValue = xCost.GetHistoryAverage();
                }
            }

            //	FiFo
            else if (to.Equals(TO_FiFo))
            {
                MCostElement ce = GetCostElement(TO_FiFo);
                if (ce == null)
                {
                    throw new Exception("CostElement not found: " + TO_FiFo);
                }
                VAdvantage.Model.MCost xCost = VAdvantage.Model.MCost.Get(GetCtx(), cost.GetAD_Client_ID(), cost.GetAD_Org_ID(), cost.GetM_Product_ID(), cost.GetM_CostType_ID(), cost.GetC_AcctSchema_ID(), ce.GetM_CostElement_ID(), cost.GetM_AttributeSetInstance_ID());
                if (xCost != null)
                {
                    retValue = xCost.GetCurrentCostPrice();
                }
            }

            //	Future Std Costs
            else if (to.Equals(TO_FutureStandardCost))
            {
                retValue = cost.GetFutureCostPrice();
            }

            //	Last Inv Price
            else if (to.Equals(TO_LastInvoicePrice))
            {
                MCostElement ce = GetCostElement(TO_LastInvoicePrice);
                if (ce != null)
                {
                    VAdvantage.Model.MCost xCost = VAdvantage.Model.MCost.Get(GetCtx(), cost.GetAD_Client_ID(), cost.GetAD_Org_ID(), cost.GetM_Product_ID(), cost.GetM_CostType_ID(), cost.GetC_AcctSchema_ID(), ce.GetM_CostElement_ID(), cost.GetM_AttributeSetInstance_ID());
                    if (xCost != null)
                    {
                        retValue = xCost.GetCurrentCostPrice();
                    }
                }
                if (retValue == null)
                {
                    MProduct    product = MProduct.Get(GetCtx(), cost.GetM_Product_ID());
                    MAcctSchema as1     = MAcctSchema.Get(GetCtx(), cost.GetC_AcctSchema_ID());
                    retValue = VAdvantage.Model.MCost.GetLastInvoicePrice(product,
                                                                          cost.GetM_AttributeSetInstance_ID(), cost.GetAD_Org_ID(), as1.GetC_Currency_ID());
                }
            }

            //	Last PO Price
            else if (to.Equals(TO_LastPOPrice))
            {
                MCostElement ce = GetCostElement(TO_LastPOPrice);
                if (ce != null)
                {
                    if (BTR002_IsPickLastPO == "N")
                    {
                        VAdvantage.Model.MCost xCost = VAdvantage.Model.MCost.Get(GetCtx(), cost.GetAD_Client_ID(), cost.GetAD_Org_ID(), cost.GetM_Product_ID(), cost.GetM_CostType_ID(), cost.GetC_AcctSchema_ID(), ce.GetM_CostElement_ID(), cost.GetM_AttributeSetInstance_ID());
                        if (xCost != null)
                        {
                            retValue = xCost.GetCurrentCostPrice();
                        }
                    }
                }
                if (retValue == null)
                {
                    MProduct    product = MProduct.Get(GetCtx(), cost.GetM_Product_ID());
                    MAcctSchema as1     = MAcctSchema.Get(GetCtx(), cost.GetC_AcctSchema_ID());
                    retValue = VAdvantage.Model.MCost.GetLastPOPrice(product,
                                                                     cost.GetM_AttributeSetInstance_ID(), cost.GetAD_Org_ID(), as1.GetC_Currency_ID());
                }
            }

            //	FiFo
            else if (to.Equals(TO_LiFo))
            {
                MCostElement ce = GetCostElement(TO_LiFo);
                if (ce == null)
                {
                    throw new Exception("CostElement not found: " + TO_LiFo);
                }
                VAdvantage.Model.MCost xCost = VAdvantage.Model.MCost.Get(GetCtx(), cost.GetAD_Client_ID(), cost.GetAD_Org_ID(), cost.GetM_Product_ID(), cost.GetM_CostType_ID(), cost.GetC_AcctSchema_ID(), ce.GetM_CostElement_ID(), cost.GetM_AttributeSetInstance_ID());
                if (xCost != null)
                {
                    retValue = xCost.GetCurrentCostPrice();
                }
            }

            //	Old Std Costs
            else if (to.Equals(TO_OldStandardCost))
            {
                retValue = GetOldCurrentCostPrice(cost);
            }

            //	Price List
            else if (to.Equals(TO_PriceListLimit))
            {
                retValue = GetPrice(cost);
            }

            //	Standard Costs
            else if (to.Equals(TO_StandardCost))
            {
                retValue = cost.GetCurrentCostPrice();
            }

            return(retValue);
        }
Exemple #15
0
        public JsonResult GetProductPricing(string fields)
        {
            string retError = "";
            string retJSON  = "";

            if (Session["ctx"] != null)
            {
                VAdvantage.Utility.Ctx ctx = Session["ctx"] as Ctx;
                string[] paramValue = fields.Split(',');
                int      M_Product_ID, C_BPartner_ID, M_PriceList_ID, M_PriceList_Version_ID;
                decimal  Qty;
                bool     isSOTrx;

                //Assign parameter value
                M_Product_ID           = Util.GetValueOfInt(paramValue[0].ToString());
                C_BPartner_ID          = Util.GetValueOfInt(paramValue[1].ToString());
                Qty                    = Util.GetValueOfDecimal(paramValue[2].ToString());
                isSOTrx                = Util.GetValueOfBool(paramValue[3].ToString());
                M_PriceList_ID         = Util.GetValueOfInt(paramValue[4].ToString());
                M_PriceList_Version_ID = Util.GetValueOfInt(paramValue[5].ToString());
                DateTime orderDate = System.Convert.ToDateTime(paramValue[6].ToString());

                //End Assign parameter value

                MProductPricing pp = new MProductPricing(ctx.GetAD_Client_ID(), ctx.GetAD_Org_ID(),
                                                         M_Product_ID, C_BPartner_ID, Qty, isSOTrx);

                //var M_PriceList_ID = ctx.GetContextAsInt(WindowNo, "M_PriceList_ID");
                pp.SetM_PriceList_ID(M_PriceList_ID);
                /** PLV is only accurate if PL selected in header */
                //var M_PriceList_Version_ID = ctx.GetContextAsInt(WindowNo, "M_PriceList_Version_ID");
                pp.SetM_PriceList_Version_ID(M_PriceList_Version_ID);

                //var orderDate = System.Convert.ToDateTime(mTab.getValue("DateOrdered"));
                pp.SetPriceDate(orderDate);

                //Get product stock
                MProduct product = MProduct.Get(ctx, M_Product_ID);


                VIS.DataContracts.ProductDataOut objInfo = new VIS.DataContracts.ProductDataOut
                {
                    PriceList     = pp.GetPriceList(),
                    PriceLimit    = pp.GetPriceLimit(),
                    PriceActual   = pp.GetPriceStd(),
                    PriceEntered  = pp.GetPriceStd(),
                    PriceStd      = pp.GetPriceStd(),
                    C_Currency_ID = System.Convert.ToInt32(pp.GetC_Currency_ID()),
                    Discount      = pp.GetDiscount(),

                    C_UOM_ID = System.Convert.ToInt32(pp.GetC_UOM_ID()),
                    //QtyOrdered= mTab.GetValue("QtyEntered"));
                    EnforcePriceLimit = pp.IsEnforcePriceLimit(),
                    DiscountSchema    = pp.IsDiscountSchema(),
                    IsStocked         = product.IsStocked()
                };
                product = null;
                pp      = null;
                retJSON = JsonConvert.SerializeObject(objInfo);
            }
            else
            {
                retError = "Session Expired";
            }
            return(Json(new { result = retJSON, error = retError }, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// GetProductPricing
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public ProductDataOut GetProductPricing(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            int      M_Product_ID, C_BPartner_ID, M_PriceList_ID, M_PriceList_Version_ID, M_AttributeSetInstance_ID = 0, countED011 = 0, C_UOM_ID = 0;
            decimal  Qty;
            bool     isSOTrx;

            //Assign parameter value
            M_Product_ID           = Util.GetValueOfInt(paramValue[0].ToString());
            C_BPartner_ID          = Util.GetValueOfInt(paramValue[1].ToString());
            Qty                    = Util.GetValueOfDecimal(paramValue[2].ToString());
            isSOTrx                = Convert.ToBoolean(paramValue[3]);
            M_PriceList_ID         = Util.GetValueOfInt(paramValue[4].ToString());
            M_PriceList_Version_ID = Util.GetValueOfInt(paramValue[5].ToString());
            DateTime?orderDate  = Util.GetValueOfDateTime(paramValue[6]);
            DateTime?orderDate1 = Util.GetValueOfDateTime(paramValue[7]);

            //if (paramValue.Length > 8)
            if (paramValue.Length == 9 || paramValue.Length == 11)
            {
                M_AttributeSetInstance_ID = Util.GetValueOfInt(paramValue[8].ToString());
            }

            if (paramValue.Length > 9)
            {
                if (paramValue.Length == 11)
                {
                    C_UOM_ID   = Util.GetValueOfInt(paramValue[9].ToString());
                    countED011 = Util.GetValueOfInt(paramValue[10].ToString());
                }
                else if (paramValue.Length == 10)
                {
                    C_UOM_ID   = Util.GetValueOfInt(paramValue[8].ToString());
                    countED011 = Util.GetValueOfInt(paramValue[9].ToString());
                }
            }

            /** Price List - ValidFrom date validation ** Dt:01/02/2021 ** Modified By: Kumar **/
            if (!string.IsNullOrEmpty(Util.GetValueOfString(orderDate)))
            {
                StringBuilder sbparams = new StringBuilder();
                sbparams.Append(Util.GetValueOfInt(M_PriceList_ID));
                sbparams.Append(",").Append(Convert.ToDateTime(orderDate).ToString("MM-dd-yyyy"));
                sbparams.Append(",").Append(Util.GetValueOfInt(M_Product_ID));
                sbparams.Append(",").Append(Util.GetValueOfInt(C_UOM_ID));
                sbparams.Append(",").Append(Util.GetValueOfInt(M_AttributeSetInstance_ID));
                MPriceListVersionModel objPriceList = new MPriceListVersionModel();
                M_PriceList_Version_ID = objPriceList.GetM_PriceList_Version_ID_On_Transaction_Date(ctx, sbparams.ToString());
            }

            //End Assign parameter value

            MProductPricing pp = new MProductPricing(ctx.GetAD_Client_ID(), ctx.GetAD_Org_ID(),
                                                     M_Product_ID, C_BPartner_ID, Qty, isSOTrx);

            //var M_PriceList_ID = ctx.GetContextAsInt(WindowNo, "M_PriceList_ID");
            pp.SetM_PriceList_ID(M_PriceList_ID);
            /** PLV is only accurate if PL selected in header */
            //var M_PriceList_Version_ID = ctx.GetContextAsInt(WindowNo, "M_PriceList_Version_ID");
            pp.SetM_PriceList_Version_ID(M_PriceList_Version_ID);

            //if (paramValue.Length > 8)
            if (paramValue.Length == 9 || paramValue.Length == 11)
            {
                pp.SetM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
            }
            //var orderDate = System.Convert.ToDateTime(mTab.getValue("DateOrdered"));
            pp.SetPriceDate(orderDate);
            pp.SetPriceDate1(orderDate1);

            if (countED011 > 0)
            {
                pp.SetC_UOM_ID(C_UOM_ID);
            }

            //Get product stock
            MProduct product = MProduct.Get(ctx, M_Product_ID);


            ProductDataOut objInfo = new ProductDataOut
            {
                //** Price List - ValidFrom date : return 0 when plv is not available ** Dt:03/26/2021 ** Modified By: Kumar **//

                PriceList     = (M_PriceList_Version_ID == 0 ? 0: pp.GetPriceList()),
                PriceLimit    = (M_PriceList_Version_ID == 0 ? 0 : pp.GetPriceLimit()),
                PriceActual   = (M_PriceList_Version_ID == 0 ? 0 : pp.GetPriceStd()),
                PriceEntered  = (M_PriceList_Version_ID == 0 ? 0 : pp.GetPriceStd()),
                PriceStd      = (M_PriceList_Version_ID == 0 ? 0 : pp.GetPriceStd()),
                LineAmt       = pp.GetLineAmt(2),
                C_Currency_ID = System.Convert.ToInt32(pp.GetC_Currency_ID()),
                Discount      = pp.GetDiscount(),
                C_UOM_ID      = System.Convert.ToInt32(pp.GetC_UOM_ID()),
                //QtyOrdered= mTab.GetValue("QtyEntered"));
                EnforcePriceLimit = pp.IsEnforcePriceLimit(),
                DiscountSchema    = pp.IsDiscountSchema(),
                IsStocked         = product.IsStocked()
            };

            product = null;
            pp      = null;
            return(objInfo);
        }
        /// <summary>
        /// New Order Line (different Product)
        /// </summary>
        /// <param name="rLine">request line</param>
        private void NewLine(MRequisitionLine rLine)
        {
            if (_orderLine != null)
            {
                if (!_orderLine.Save())
                {
                    throw new Exception("Cannot update Order Line");
                }
            }
            _orderLine = null;
            MProduct product = null;

            //	Get Business Partner
            int C_BPartner_ID = rLine.GetC_BPartner_ID();

            if (C_BPartner_ID != 0)
            {
                ;
            }
            else if (rLine.GetC_Charge_ID() != 0)
            {
                MCharge charge = MCharge.Get(GetCtx(), rLine.GetC_Charge_ID());
                C_BPartner_ID = charge.GetC_BPartner_ID();
                if (C_BPartner_ID == 0)
                {
                    throw new Exception("No Vendor for Charge " + charge.GetName());
                }
            }
            else
            {
                //	Find Vendor from Produt
                product = MProduct.Get(GetCtx(), rLine.GetM_Product_ID());
                MProductPO[] ppos = MProductPO.GetOfProduct(GetCtx(), product.GetM_Product_ID(), null);
                for (int i = 0; i < ppos.Length; i++)
                {
                    if (ppos[i].IsCurrentVendor() && ppos[i].GetC_BPartner_ID() != 0)
                    {
                        C_BPartner_ID = ppos[i].GetC_BPartner_ID();
                        break;
                    }
                }
                if (C_BPartner_ID == 0 && ppos.Length > 0)
                {
                    C_BPartner_ID = ppos[0].GetC_BPartner_ID();
                }
                if (C_BPartner_ID == 0)
                {
                    throw new Exception("No Vendor for " + product.GetName());
                }
            }

            //	New Order - Different Vendor
            if (_order == null ||
                _order.GetC_BPartner_ID() != C_BPartner_ID)
            {
                NewOrder(rLine, C_BPartner_ID);
            }

            //	No Order Line
            _orderLine = new MOrderLine(_order);
            if (product != null)
            {
                _orderLine.SetProduct(product);
                _orderLine.SetM_AttributeSetInstance_ID(rLine.GetM_AttributeSetInstance_ID());
            }
            else
            {
                _orderLine.SetC_Charge_ID(rLine.GetC_Charge_ID());
                _orderLine.SetPriceActual(rLine.GetPriceActual());
            }
            _orderLine.SetAD_Org_ID(rLine.GetAD_Org_ID());


            //	Prepare Save
            _m_M_Product_ID = rLine.GetM_Product_ID();
            _m_M_AttributeSetInstance_ID = rLine.GetM_AttributeSetInstance_ID();
            if (!_orderLine.Save())
            {
                throw new Exception("Cannot save Order Line");
            }
        }
        /// <summary>
        /// GetProductPricing
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public ProductDataOut GetProductPricing(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            int      M_Product_ID, C_BPartner_ID, M_PriceList_ID, M_PriceList_Version_ID, M_AttributeSetInstance_ID = 0;
            decimal  Qty;
            bool     isSOTrx;

            //Assign parameter value
            M_Product_ID           = Util.GetValueOfInt(paramValue[0].ToString());
            C_BPartner_ID          = Util.GetValueOfInt(paramValue[1].ToString());
            Qty                    = Util.GetValueOfDecimal(paramValue[2].ToString());
            isSOTrx                = Convert.ToBoolean(paramValue[3]);
            M_PriceList_ID         = Util.GetValueOfInt(paramValue[4].ToString());
            M_PriceList_Version_ID = Util.GetValueOfInt(paramValue[5].ToString());
            DateTime?orderDate  = Util.GetValueOfDateTime(paramValue[6]);
            DateTime?orderDate1 = Util.GetValueOfDateTime(paramValue[7]);

            if (paramValue.Length > 8)
            {
                M_AttributeSetInstance_ID = Util.GetValueOfInt(paramValue[8].ToString());
            }
            //End Assign parameter value

            MProductPricing pp = new MProductPricing(ctx.GetAD_Client_ID(), ctx.GetAD_Org_ID(),
                                                     M_Product_ID, C_BPartner_ID, Qty, isSOTrx);

            //var M_PriceList_ID = ctx.GetContextAsInt(WindowNo, "M_PriceList_ID");
            pp.SetM_PriceList_ID(M_PriceList_ID);
            /** PLV is only accurate if PL selected in header */
            //var M_PriceList_Version_ID = ctx.GetContextAsInt(WindowNo, "M_PriceList_Version_ID");
            pp.SetM_PriceList_Version_ID(M_PriceList_Version_ID);
            if (paramValue.Length > 8)
            {
                pp.SetM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
            }
            //var orderDate = System.Convert.ToDateTime(mTab.getValue("DateOrdered"));
            pp.SetPriceDate(orderDate);
            pp.SetPriceDate1(orderDate1);

            //Get product stock
            MProduct product = MProduct.Get(ctx, M_Product_ID);


            ProductDataOut objInfo = new ProductDataOut
            {
                PriceList     = pp.GetPriceList(),
                PriceLimit    = pp.GetPriceLimit(),
                PriceActual   = pp.GetPriceStd(),
                PriceEntered  = pp.GetPriceStd(),
                PriceStd      = pp.GetPriceStd(),
                LineAmt       = pp.GetLineAmt(2),
                C_Currency_ID = System.Convert.ToInt32(pp.GetC_Currency_ID()),
                Discount      = pp.GetDiscount(),
                C_UOM_ID      = System.Convert.ToInt32(pp.GetC_UOM_ID()),
                //QtyOrdered= mTab.GetValue("QtyEntered"));
                EnforcePriceLimit = pp.IsEnforcePriceLimit(),
                DiscountSchema    = pp.IsDiscountSchema(),
                IsStocked         = product.IsStocked()
            };

            product = null;
            pp      = null;
            return(objInfo);
        }
        }       //	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>
        /// Process
        /// </summary>
        /// <returns>info</returns>
        protected override String DoIt()
        {
            log.Info("M_Movement_ID=" + _m_Movement_ID
                     + ", M_Locator_ID=" + _m_Locator_ID + ", M_LocatorTo_ID=" + _m_LocatorTo_ID
                     + ", M_Product_ID=" + _m_product_ID
                     + ", M_Product_Category_ID=" + _m_Product_Category_ID
                     + ", QtyRange=" + _qtyRange + ", DeleteOld=" + _deleteOld);
            _movement = new MMovement(GetCtx(), _m_Movement_ID, Get_Trx());
            if (_movement.Get_ID() == 0)
            {
                throw new SystemException("Not found: M_Movement_ID=" + _m_Movement_ID);
            }
            if (_movement.IsProcessed())
            {
                throw new SystemException("@M_Movement_ID@ @Processed@");
            }

            // is used to check Container applicable into system
            isContainerApplicable = MTransaction.ProductContainerApplicable(GetCtx());

            //
            String sqlQry = "";

            if (_deleteOld)
            {
                sqlQry = "DELETE FROM M_MovementLine WHERE Processed='N' "
                         + "AND M_Movement_ID=" + _m_Movement_ID;
                int no = DB.ExecuteQuery(sqlQry, null, Get_Trx());
                log.Fine("doIt - Deleted #" + no);
            }

            //	Create Null Storage records
            if (_qtyRange != null && _qtyRange.Equals("="))
            {
                sqlQry = "INSERT INTO M_Storage "
                         + "(AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, Updated, UpdatedBy,"
                         + " M_Locator_ID, M_Product_ID, M_AttributeSetInstance_ID,"
                         + " qtyOnHand, QtyReserved, QtyOrdered, DateLastInventory) "
                         + "SELECT l.AD_CLIENT_ID, l.AD_ORG_ID, 'Y', SysDate, 0,SysDate, 0,"
                         + " l.M_Locator_ID, p.M_Product_ID, 0,"
                         + " 0,0,0,null "
                         + "FROM M_Locator l"
                         + " INNER JOIN M_Product p ON (l.AD_Client_ID=p.AD_Client_ID) "
                         + "WHERE l.M_Warehouse_ID=" + _movement.GetM_Warehouse_ID();
                if (_m_Locator_ID != 0)
                {
                    sqlQry += " AND l.M_Locator_ID=" + _m_Locator_ID;
                }
                sqlQry += " AND l.IsDefault='Y'"
                          + " AND p.IsActive='Y' AND p.IsStocked='Y' and p.ProductType='I'"
                          + " AND NOT EXISTS (SELECT * FROM M_Storage s"
                          + " INNER JOIN M_Locator sl ON (s.M_Locator_ID=sl.M_Locator_ID) "
                          + "WHERE sl.M_Warehouse_ID=l.M_Warehouse_ID"
                          + " AND s.M_Product_ID=p.M_Product_ID)";
                int no = DB.ExecuteQuery(sqlQry, null, Get_Trx());
                log.Fine("'0' Inserted #" + no);
            }

            StringBuilder sql = null;

            if (!isContainerApplicable)
            {
                sql = new StringBuilder(
                    "SELECT s.M_Product_ID, s.M_Locator_ID, s.M_AttributeSetInstance_ID,"
                    + " s.qtyOnHand, p.M_AttributeSet_ID, 0 AS M_ProductContainer_ID "
                    + "FROM M_Product p"
                    + " INNER JOIN M_Storage s ON (s.M_Product_ID=p.M_Product_ID)"
                    + " INNER JOIN M_Locator l ON (s.M_Locator_ID=l.M_Locator_ID) "
                    + "WHERE l.M_Warehouse_ID=" + _movement.GetDTD001_MWarehouseSource_ID()
                    + " AND p.IsActive='Y' AND p.IsStocked='Y' and p.ProductType='I'");
            }
            else
            {
                sql = new StringBuilder(
                    "SELECT s.M_Product_ID, s.M_Locator_ID, s.M_AttributeSetInstance_ID,"
                    + " NVL(SUM(s.Qty) , 0) AS qtyOnHand , p.M_AttributeSet_ID, s.M_ProductContainer_ID "
                    + "FROM M_Product p"
                    + " INNER JOIN M_ContainerStorage s ON (s.M_Product_ID=p.M_Product_ID)"
                    + " INNER JOIN M_Locator l ON (s.M_Locator_ID=l.M_Locator_ID) "
                    + "WHERE l.M_Warehouse_ID=" + _movement.GetDTD001_MWarehouseSource_ID()
                    + " AND p.IsActive='Y' AND p.IsStocked='Y' and p.ProductType='I'");
            }
            //
            if (_m_Locator_ID != 0)
            {
                sql.Append(" AND s.M_Locator_ID=" + _m_Locator_ID);
            }

            //
            if (_m_product_ID != null && !string.IsNullOrEmpty(_m_product_ID))
            {
                sql.Append(" AND  p.M_Product_ID IN ( " + _m_product_ID + ") ");
            }
            //
            if (_m_Product_Category_ID != 0)
            {
                sql.Append(" AND p.M_Product_Category_ID=" + _m_Product_Category_ID);
            }

            //	Do not overwrite existing records
            if (!_deleteOld)
            {
                sql.Append(" AND NOT EXISTS (SELECT * FROM M_MovementLine il "
                           + "WHERE il.M_Movement_ID=" + _m_Movement_ID
                           + " AND il.M_Product_ID=s.M_Product_ID"
                           + " AND il.M_Locator_ID=s.M_Locator_ID"
                           + " AND COALESCE(il.M_AttributeSetInstance_ID,0)=COALESCE(s.M_AttributeSetInstance_ID,0)");
                if (!isContainerApplicable)
                {
                    sql.Append(@" )  ");
                }
                else
                {
                    sql.Append(@" AND COALESCE(il.M_ProductContainer_ID,0)=COALESCE(s.M_ProductContainer_ID,0) )  ");
                }
            }
            //
            if (!isContainerApplicable)
            {
                sql.Append(" ORDER BY l.Value, p.Value, s.qtyOnHand DESC");     //	Locator/Product
            }
            else
            {
                sql.Append(@" GROUP BY s.M_Product_ID, s.M_Locator_ID, s.M_AttributeSetInstance_ID, p.M_AttributeSet_ID, s.M_ProductContainer_ID, s.Qty
ORDER BY s.M_Locator_ID, s.M_Product_ID, s.Qty DESC, s.M_AttributeSetInstance_ID, p.M_AttributeSet_ID,s.M_ProductContainer_ID");        //	Locator/Product
            }
            //
            int         count   = 0;
            IDataReader idr     = null;
            DataTable   dt      = null;
            MProduct    product = null;

            try
            {
                idr = DB.ExecuteReader(sql.ToString(), null, Get_Trx());
                dt  = new DataTable();
                dt.Load(idr);
                idr.Close();
                foreach (DataRow dr in dt.Rows)
                // while (idr.Read())
                {
                    int M_Product_ID = Util.GetValueOfInt(dr[0]);
                    product = MProduct.Get(GetCtx(), M_Product_ID);
                    int     M_Locator_ID = Util.GetValueOfInt(dr[1]);
                    int     M_AttributeSetInstance_ID = Util.GetValueOfInt(dr[2]);
                    Decimal qtyOnHand = Util.GetValueOfDecimal(dr[3]);
                    //if (qtyOnHand == null) commented by manjot Because Decimal is Never equals to Null
                    //  qtyOnHand = Env.ZERO;
                    int M_AttributeSet_ID = Util.GetValueOfInt(dr[4]);
                    //container
                    int container_Id = Util.GetValueOfInt(dr[5]);
                    //
                    int compare = qtyOnHand.CompareTo(Env.ZERO);
                    if (_qtyRange == null ||
                        (_qtyRange.Equals(">") && compare > 0) ||
                        (_qtyRange.Equals("<") && compare < 0) ||
                        (_qtyRange.Equals("=") && compare == 0) ||
                        (_qtyRange.Equals("N") && compare != 0))
                    {
                        //Save data on Movement Line
                        _line = new MMovementLine(GetCtx(), 0, Get_Trx());
                        _line.SetAD_Client_ID(_movement.GetAD_Client_ID());
                        _line.SetAD_Org_ID(_movement.GetAD_Org_ID());
                        _line.SetM_Movement_ID(_m_Movement_ID);
                        _line.SetM_Locator_ID(_m_Locator_ID);
                        _line.SetM_LocatorTo_ID(_m_LocatorTo_ID);
                        _line.SetMovementQty(qtyOnHand);
                        _line.SetProcessed(false);
                        _line.SetM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
                        _line.SetM_Product_ID(M_Product_ID);
                        if (isContainerApplicable && _line.Get_ColumnIndex("M_ProductContainer_ID") > 0)
                        {
                            _line.SetM_ProductContainer_ID(container_Id);
                        }
                        if (_line.Get_ColumnIndex("C_UOM_ID") > 0 && product != null)
                        {
                            _line.SetC_UOM_ID(product.GetC_UOM_ID());
                        }
                        if (_line.Get_ColumnIndex("QtyEntered") > 0)
                        {
                            _line.SetQtyEntered(qtyOnHand);
                        }
                        if (!_line.Save())
                        {
                            return(GetRetrievedError(_line, "Movement Line Not Created for M_Product_ID = " + M_Product_ID + " M_AttributeSetInstance =  " + M_AttributeSetInstance_ID));
                            //log.Info("Movement Line Not Created for M_Product_ID = " + M_Product_ID + " M_AttributeSetInstance =  " + M_AttributeSetInstance_ID);
                        }
                        else
                        {
                            count = count + 1;
                        }
                    }
                }
                //idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql.ToString(), e);
            }

            //
            return("@M_MovementLine_ID@ - #" + count);
        }
Exemple #21
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);
        }
Exemple #22
0
        /// <summary>
        /// Is used to save data on movememt line
        /// </summary>
        /// <param name="mData"></param>
        /// <returns></returns>
        public String SaveMovementLine(List <Dictionary <string, string> > mData)
        {
            StringBuilder error = new StringBuilder();
            bool          isMoveFullContainer    = false;
            bool          isMoveFullContainerQty = false;

            Trx trx = Trx.GetTrx("Movement");

            if (mData.Count > 0)
            {
                isMoveFullContainer = Util.GetValueOfBool(mData[0]["IsFullMoveContainer"]);

                //to delete all the movement lines where MoveFullContainer is False
                if (isMoveFullContainer)
                {
                    DB.ExecuteQuery("DELETE FROM M_MovementLine WHERE M_Movement_ID = " + Util.GetValueOfInt(mData[0]["M_Movement_ID"]) + " AND MoveFullContainer= 'N' ", null, null);
                }

                // Lines not inserted, as movement line already has a full move container line.
                if (!isMoveFullContainer)
                {
                    if (Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT COUNT(MoveFullContainer) FROM M_MovementLine WHERE MoveFullContainer= 'Y' AND M_Movement_ID = "
                                                            + Util.GetValueOfInt(mData[0]["M_Movement_ID"]), null, trx)) > 0)
                    {
                        trx.Close();
                        return(Msg.GetMsg(_ctx, "VIS_LinehaveFullContainer"));
                    }
                }

                // Get Line No
                int lineNo = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT NVL(MAX(Line),0) AS DefaultValue FROM M_MovementLine WHERE M_Movement_ID="
                                                                 + Util.GetValueOfInt(mData[0]["M_Movement_ID"]), null, trx));


                isMoveFullContainerQty = Util.GetValueOfBool(mData[0]["IsfullContainerQtyWise"]);

                if (!isMoveFullContainer && !isMoveFullContainerQty)
                {
                    goto moveFullContainer;
                }
                else if (isMoveFullContainer || isMoveFullContainerQty)
                {
                    error.Clear();
                    error.Append(SaveMoveLinewithFullContainer(Util.GetValueOfInt(mData[0]["M_Movement_ID"]),
                                                               Util.GetValueOfInt(mData[0]["FromLocator"]),
                                                               Util.GetValueOfInt(mData[0]["FromContainer"]),
                                                               Util.GetValueOfInt(mData[0]["ToLocator"]),
                                                               Util.GetValueOfInt(mData[0]["ToContainer"]),
                                                               lineNo, isMoveFullContainerQty,
                                                               trx));
                    trx.Close();
                    return(error.ToString());
                }

moveFullContainer:
                MMovementLine moveline = null;
                MProduct product = null;
                int      moveId  = 0;
                for (int i = 0; i < mData.Count; i++)
                {
                    #region Quantity Only
                    MMovement move = new MMovement(_ctx, Util.GetValueOfInt(mData[i]["M_Movement_ID"]), null);

                    moveId = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT NVL(M_MovementLine_ID, 0) AS M_Movement_ID FROM M_MovementLine WHERE 
                             M_Movement_ID = " + Util.GetValueOfInt(mData[i]["M_Movement_ID"]) +
                                                                 @" AND M_Product_ID = " + Util.GetValueOfInt(mData[i]["M_Product_ID"]) +
                                                                 @" AND NVL(M_AttributeSetInstance_ID, 0) = " + Util.GetValueOfInt(mData[i]["M_AttributeSetInstance_ID"]) +
                                                                 @" AND M_Locator_ID = " + Util.GetValueOfInt(mData[i]["FromLocator"]) +
                                                                 @" AND NVL(M_ProductContainer_ID, 0) = " + Util.GetValueOfInt(mData[i]["FromContainer"]) +
                                                                 @" AND M_LocatorTo_ID = " + Util.GetValueOfInt(mData[i]["ToLocator"]) +
                                                                 @" AND NVL(Ref_M_ProductContainerTo_ID, 0) = " + Util.GetValueOfInt(mData[i]["ToContainer"]) +
                                                                 @" AND AD_Org_ID = " + move.GetAD_Org_ID()));

                    if (moveId > 0)
                    {
                        moveline = new MMovementLine(_ctx, moveId, trx);
                    }
                    else
                    {
                        moveline = new MMovementLine(_ctx, 0, trx);
                    }
                    if (moveId == 0)
                    {
                        #region Create new record of movement line
                        lineNo += 10;
                        moveline.SetAD_Client_ID(move.GetAD_Client_ID());
                        moveline.SetAD_Org_ID(move.GetAD_Org_ID());
                        moveline.SetM_Movement_ID(move.GetM_Movement_ID());
                        moveline.SetLine(lineNo);
                        moveline.SetM_Product_ID(Util.GetValueOfInt(mData[i]["M_Product_ID"]));
                        moveline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(mData[i]["M_AttributeSetInstance_ID"]));
                        moveline.SetC_UOM_ID(Util.GetValueOfInt(mData[i]["C_UOM_ID"]));
                        moveline.SetM_Locator_ID(Util.GetValueOfInt(mData[i]["FromLocator"]));
                        moveline.SetM_LocatorTo_ID(Util.GetValueOfInt(mData[i]["ToLocator"]));
                        moveline.SetM_ProductContainer_ID(Util.GetValueOfInt(mData[i]["FromContainer"]));
                        moveline.SetRef_M_ProductContainerTo_ID(Util.GetValueOfInt(mData[i]["ToContainer"]));
                        moveline.SetQtyEntered(Util.GetValueOfDecimal(mData[i]["MoveQty"]));
                        moveline.SetMovementQty(Util.GetValueOfDecimal(mData[i]["MoveQty"]));
                        moveline.SetMoveFullContainer(Util.GetValueOfBool(mData[i]["IsFullMoveContainer"]));
                        #endregion
                    }
                    else
                    {
                        #region Update record of movement line
                        moveline.SetQtyEntered(Decimal.Add(moveline.GetQtyEntered(), Util.GetValueOfDecimal(mData[i]["MoveQty"])));
                        moveline.SetMovementQty(Decimal.Add(moveline.GetMovementQty(), Util.GetValueOfDecimal(mData[i]["MoveQty"])));
                        moveline.SetMoveFullContainer(Util.GetValueOfBool(mData[i]["IsFullMoveContainer"]));
                        #endregion
                    }
                    if (!moveline.Save(trx))
                    {
                        #region Save error catch and rollback
                        product = MProduct.Get(_ctx, Util.GetValueOfInt(mData[i]["M_Product_ID"]));
                        ValueNamePair pp = VLogger.RetrieveError();
                        if (pp != null)
                        {
                            _log.SaveError("Movement line not inserted through Move Container Form : ", pp.GetName());
                            if (String.IsNullOrEmpty(error.ToString()))
                            {
                                error.Append(Msg.GetMsg(_ctx, "VIS_MoveLineNotSaveFor") + product.GetName() + Msg.GetMsg(_ctx, "VIS_DueTo") + pp.GetName());
                            }
                            else
                            {
                                error.Append(" , " + Msg.GetMsg(_ctx, "VIS_MoveLineNotSaveFor") + product.GetName() + Msg.GetMsg(_ctx, "VIS_DueTo") + pp.GetName());
                            }
                        }
                        trx.Rollback();
                        #endregion
                    }
                    else
                    {
                        trx.Commit();
                    }

                    #endregion
                }
            }
            trx.Close();
            return(String.IsNullOrEmpty(error.ToString()) ? "VIS_SuccessFullyInserted" : error.ToString());
        }
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            List <Fact>          facts   = new List <Fact>();
            MProductCategoryAcct pca     = null;
            String costingMethodOfSchema = as1.GetCostingMethod();
            String costingLevelOfSchema  = as1.GetCostingLevel();

            // Get the costing method and the costing level of the product Category for the current accounting schema.
            if (mpc != null)
            {
                pca = MProductCategoryAcct.Get(GetCtx(), mpc.GetM_Product_Category_ID(), as1.GetC_AcctSchema_ID(), null);
                if (pca.GetCostingMethod() != null)
                {
                    costingMethod = pca.GetCostingMethod();
                }
                else
                {
                    costingMethod = costingMethodOfSchema;
                }

                if (pca.GetCostingLevel() != null)
                {
                    costingLevel = pca.GetCostingLevel();
                }
                else
                {
                    costingLevel = costingLevelOfSchema;
                }

                // proceed only if the costing method is standard
                if (!costingMethod.Equals(X_C_AcctSchema.COSTINGMETHOD_StandardCosting))
                {
                    return(facts);
                }
            }

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

            FactLine dr = null;
            FactLine cr = null;

            for (int i = 0; i < _lines.Length; i++)
            {
                DocLine line = _lines[i];

                if (mpc == null)
                {
                    pca = MProductCategoryAcct.Get(GetCtx(), MProduct.Get(GetCtx(), line.GetM_Product_ID()).
                                                   GetM_Product_Category_ID(),
                                                   as1.GetC_AcctSchema_ID(), null);
                    if (pca.GetCostingMethod() != null)
                    {
                        costingMethod = pca.GetCostingMethod();
                    }
                    else
                    {
                        costingMethod = costingMethodOfSchema;
                    }

                    if (pca.GetCostingLevel() != null)
                    {
                        costingLevel = pca.GetCostingLevel();
                    }
                    else
                    {
                        costingLevel = costingLevelOfSchema;
                    }

                    // proceed only if the costing method is standard
                    if (!costingMethod.Equals(X_C_AcctSchema.COSTINGMETHOD_StandardCosting))
                    {
                        return(facts);
                    }
                }
                Decimal currentCost = Env.ZERO;
                Decimal oldCost     = Env.ZERO;
                Decimal Qty         = Env.ZERO;
                String  sql         = " SELECT Sum(CurrentCostPrice), Sum(LastCostPrice), Sum(CurrentQty)"
                                      + " FROM M_Cost WHERE M_Product_ID = " + line.GetM_Product_ID()
                                      + " AND C_AcctSchema_ID = " + as1.GetC_AcctSchema_ID()
                                      + " AND M_CostElement_ID = " + m_ce.GetM_CostElement_ID()
                                      + " AND M_CostType_ID = " + as1.GetM_CostType_ID()
                                      + " AND AD_Client_ID = " + GetAD_Client_ID();
                if (costingLevel.Equals(X_C_AcctSchema.COSTINGLEVEL_Client))
                {
                    sql += " AND AD_Org_ID = 0"
                           + " AND M_AttributeSetInstance_ID  = 0";
                }
                else if (costingLevel.Equals(X_C_AcctSchema.COSTINGLEVEL_Organization))
                {
                    sql += " AND M_AttributeSetInstance_ID  = 0";
                }
                else if (costingLevel.Equals(X_C_AcctSchema.COSTINGLEVEL_BatchLot))
                {
                    sql += " AND AD_Org_ID = 0";
                }

                IDataReader idr = null;
                try
                {
                    idr = DB.ExecuteReader(sql, null, GetTrx());
                    while (idr.Read())
                    {
                        currentCost = Util.GetValueOfDecimal(idr[0]);
                        oldCost     = Util.GetValueOfDecimal(idr[1]);
                        Qty         = Util.GetValueOfDecimal(idr[2]);
                        line.SetQty(Qty, costupdate.IsSOTrx());

                        Decimal PriceCost = Decimal.Subtract(currentCost, oldCost);
                        Decimal amt       = Env.ZERO;
                        if (Env.Signum(PriceCost) != 0)
                        {
                            amt = Decimal.Multiply(Qty, PriceCost);
                        }

                        line.SetAmount(amt);

                        if (Env.Signum(amt) == 0)
                        {
                            continue;
                        }
                        MAccount db_acct, cr_acct;

                        /* Decide the Credit and Debit Accounts */
                        if (Env.Signum(amt) == 1)
                        {
                            db_acct = line.GetAccount(ProductCost.ACCTTYPE_P_Asset, as1);
                            cr_acct = line.GetAccount(ProductCost.ACCTTYPE_P_CostAdjustment, as1);
                        }
                        else
                        {
                            cr_acct = line.GetAccount(ProductCost.ACCTTYPE_P_Asset, as1);
                            db_acct = line.GetAccount(ProductCost.ACCTTYPE_P_CostAdjustment, as1);
                        }

                        /* Create Credit and Debit lines*/
                        dr = fact.CreateLine(line, db_acct, as1.GetC_Currency_ID(), Math.Abs(amt), null);
                        if (dr == null)
                        {
                            log.SaveError("NoProductCosts", "No Product Costs");
                            return(null);
                        }

                        cr = fact.CreateLine(line, cr_acct, as1.GetC_Currency_ID(), null, Math.Abs(amt));
                        if (cr == null)
                        {
                            log.SaveError("NoProductCosts", "No Product Costs");
                            return(null);
                        }
                    }
                    idr.Close();
                }
                catch (Exception e)
                {
                    log.Log(Level.SEVERE, sql, e);
                }
                finally
                {
                    if (idr != null)
                    {
                        idr.Close();
                        idr = null;
                    }
                }
            }
            facts.Add(fact);
            return(facts);
        }
Exemple #24
0
        /// <summary>
        /// Create Orders
        /// </summary>
        /// <returns>true if created</returns>
        private bool CreateOrders()
        {
            //	Get Counter Org/BP
            int runAD_Org_ID = _run.GetAD_Org_ID();

            if (runAD_Org_ID == 0)
            {
                runAD_Org_ID = GetCtx().GetAD_Org_ID();
            }
            MOrg runOrg           = MOrg.Get(GetCtx(), runAD_Org_ID);
            int  runC_BPartner_ID = runOrg.GetLinkedC_BPartner_ID();
            bool counter          = !_run.IsCreateSingleOrder() && //	no single Order
                                    runC_BPartner_ID > 0 &&             //	Org linked to BP
                                    !_docType.IsSOTrx();                //	PO
            MBPartner runBPartner = counter ? new MBPartner(GetCtx(), runC_BPartner_ID, Get_TrxName()) : null;

            if (!counter || runBPartner == null || runBPartner.Get_ID() != runC_BPartner_ID)
            {
                counter = false;
            }
            if (counter)
            {
                log.Info("RunBP=" + runBPartner
                         + " - " + _docType);
            }
            log.Info("Single=" + _run.IsCreateSingleOrder()
                     + " - " + _docType + ",SO=" + _docType.IsSOTrx());
            log.Fine("Counter=" + counter
                     + ",C_BPartner_ID=" + runC_BPartner_ID + "," + runBPartner);
            //
            MBPartner bp          = null;
            MOrder    singleOrder = null;
            MProduct  product     = null;

            //	Consolidated Order
            if (_run.IsCreateSingleOrder())
            {
                bp = new MBPartner(GetCtx(), _run.GetC_BPartner_ID(), Get_TrxName());
                if (bp.Get_ID() == 0)
                {
                    throw new ArgumentException("Business Partner not found - C_BPartner_ID=" + _run.GetC_BPartner_ID());
                }
                //
                if (!_IsTest)
                {
                    singleOrder = new MOrder(GetCtx(), 0, Get_TrxName());
                    singleOrder.SetC_DocTypeTarget_ID(_docType.GetC_DocType_ID());
                    singleOrder.SetC_DocType_ID(_docType.GetC_DocType_ID());
                    singleOrder.SetIsReturnTrx(_docType.IsReturnTrx());
                    singleOrder.SetIsSOTrx(_docType.IsSOTrx());
                    singleOrder.SetBPartner(bp);
                    if (_run.GetC_BPartner_Location_ID() != 0)
                    {
                        singleOrder.SetC_BPartner_Location_ID(_run.GetC_BPartner_Location_ID());
                    }
                    singleOrder.SetDateOrdered(_DateOrdered);
                    singleOrder.SetDatePromised(_DatePromised);
                    if (!singleOrder.Save())
                    {
                        log.Log(Level.SEVERE, "Order not saved");
                        return(false);
                    }
                    _counter++;
                }
            }

            int    lastC_BPartner_ID          = 0;
            int    lastC_BPartner_Location_ID = 0;
            MOrder order = null;

            //	For all lines
            for (int i = 0; i < _details.Length; i++)
            {
                MDistributionRunDetail detail = _details[i];

                //	Create Order Header
                if (_run.IsCreateSingleOrder())
                {
                    order = singleOrder;
                }
                //	New Business Partner
                else if (lastC_BPartner_ID != detail.GetC_BPartner_ID() ||
                         lastC_BPartner_Location_ID != detail.GetC_BPartner_Location_ID())
                {
                    //	finish order
                    order = null;
                }
                lastC_BPartner_ID          = detail.GetC_BPartner_ID();
                lastC_BPartner_Location_ID = detail.GetC_BPartner_Location_ID();

                //	New Order
                if (order == null)
                {
                    bp = new MBPartner(GetCtx(), detail.GetC_BPartner_ID(), Get_TrxName());
                    if (!_IsTest)
                    {
                        order = new MOrder(GetCtx(), 0, Get_TrxName());
                        order.SetC_DocTypeTarget_ID(_docType.GetC_DocType_ID());
                        order.SetIsReturnTrx(_docType.IsReturnTrx());
                        order.SetC_DocType_ID(_docType.GetC_DocType_ID());
                        order.SetIsSOTrx(_docType.IsSOTrx());
                        //	Counter Doc
                        if (counter && bp.GetAD_OrgBP_ID_Int() > 0)
                        {
                            log.Fine("Counter - From_BPOrg=" + bp.GetAD_OrgBP_ID_Int()
                                     + "-" + bp + ", To_BP=" + runBPartner);
                            order.SetAD_Org_ID(bp.GetAD_OrgBP_ID_Int());
                            MOrgInfo oi = MOrgInfo.Get(GetCtx(), bp.GetAD_OrgBP_ID_Int(), null);
                            if (oi.GetM_Warehouse_ID() > 0)
                            {
                                order.SetM_Warehouse_ID(oi.GetM_Warehouse_ID());
                            }
                            order.SetBPartner(runBPartner);
                        }
                        else    //	normal
                        {
                            log.Fine("From_Org=" + runAD_Org_ID
                                     + ", To_BP=" + bp);
                            order.SetAD_Org_ID(runAD_Org_ID);
                            order.SetBPartner(bp);
                            if (detail.GetC_BPartner_Location_ID() != 0)
                            {
                                order.SetC_BPartner_Location_ID(detail.GetC_BPartner_Location_ID());
                            }
                        }
                        order.SetDateOrdered(_DateOrdered);
                        order.SetDatePromised(_DatePromised);
                        if (!order.Save())
                        {
                            log.Log(Level.SEVERE, "Order not saved");
                            return(false);
                        }
                    }
                }

                //	Line
                if (product == null || product.GetM_Product_ID() != detail.GetM_Product_ID())
                {
                    product = MProduct.Get(GetCtx(), detail.GetM_Product_ID());
                }
                if (_IsTest)
                {
                    AddLog(0, null, detail.GetActualAllocation(),
                           bp.GetName() + " - " + product.GetName());
                    continue;
                }

                //	Create Order Line
                MOrderLine line = new MOrderLine(order);
                if (counter && bp.GetAD_OrgBP_ID_Int() > 0)
                {
                    ;   //	don't overwrite counter doc
                }
                else    //	normal - optionally overwrite
                {
                    line.SetC_BPartner_ID(detail.GetC_BPartner_ID());
                    if (detail.GetC_BPartner_Location_ID() != 0)
                    {
                        line.SetC_BPartner_Location_ID(detail.GetC_BPartner_Location_ID());
                    }
                }
                //
                line.SetProduct(product);
                line.SetQty(detail.GetActualAllocation());
                line.SetPrice();
                if (!line.Save())
                {
                    log.Log(Level.SEVERE, "OrderLine not saved");
                    return(false);
                }
                AddLog(0, null, detail.GetActualAllocation(), order.GetDocumentNo()
                       + ": " + bp.GetName() + " - " + product.GetName());
            }
            //	finish order
            order = null;


            return(true);
        }