/// <summary>
 /// Eliminate Reserved/Ordered
 /// </summary>
 /// <param name="target">target Storage</param>
 private void EliminateReservation(MStorage target)
 {
     //	Negative Ordered / Reserved Qty
     if (Env.Signum(target.GetQtyReserved()) != 0 || Env.Signum(target.GetQtyOrdered()) != 0)
     {
         int      M_Locator_ID = target.GetM_Locator_ID();
         MStorage storage0     = MStorage.Get(GetCtx(), M_Locator_ID,
                                              target.GetM_Product_ID(), 0, Get_Trx());
         if (storage0 == null)
         {
             MLocator defaultLoc = MLocator.GetDefault(GetCtx(), M_Locator_ID);
             if (M_Locator_ID != defaultLoc.GetM_Locator_ID())
             {
                 M_Locator_ID = defaultLoc.GetM_Locator_ID();
                 storage0     = MStorage.Get(GetCtx(), M_Locator_ID,
                                             target.GetM_Product_ID(), 0, Get_Trx());
             }
         }
         if (storage0 != null)
         {
             Decimal reserved = Env.ZERO;
             Decimal ordered  = Env.ZERO;
             if (Env.Signum(Decimal.Add(target.GetQtyReserved(), storage0.GetQtyReserved())) >= 0)
             {
                 reserved = target.GetQtyReserved();             //	negative
             }
             if (Env.Signum(Decimal.Add(target.GetQtyOrdered(), storage0.GetQtyOrdered())) >= 0)
             {
                 ordered = target.GetQtyOrdered();               //	negative
             }
             //	Eliminate Reservation
             if (Env.Signum(reserved) != 0 || Env.Signum(ordered) != 0)
             {
                 if (MStorage.Add(GetCtx(), target.GetM_Warehouse_ID(), target.GetM_Locator_ID(),
                                  target.GetM_Product_ID(),
                                  target.GetM_AttributeSetInstance_ID(), target.GetM_AttributeSetInstance_ID(),
                                  Env.ZERO, Decimal.Negate(reserved), Decimal.Negate(ordered), Get_Trx()))
                 {
                     if (MStorage.Add(GetCtx(), storage0.GetM_Warehouse_ID(), storage0.GetM_Locator_ID(),
                                      storage0.GetM_Product_ID(),
                                      storage0.GetM_AttributeSetInstance_ID(), storage0.GetM_AttributeSetInstance_ID(),
                                      Env.ZERO, reserved, ordered, Get_Trx()))
                     {
                         log.Info("Reserved=" + reserved + ",Ordered=" + ordered);
                     }
                     else
                     {
                         log.Warning("Failed Storage0 Update");
                     }
                 }
                 else
                 {
                     log.Warning("Failed Target Update");
                 }
             }
         }
     }
 }
Exemple #2
0
        /// <summary>
        /// is used to save Product container
        /// </summary>
        /// <param name="warehouseId">Warehouse where we create container</param>
        /// <param name="locatorId">Locator - in which locator we place container</param>
        /// <param name="value">Search key of the container</param>
        /// <param name="name">name of teh container</param>
        /// <param name="height">height of the container</param>
        /// <param name="width">width of the container</param>
        /// <param name="parentContainerId">Parent of the nw container</param>
        /// <returns>Save Or Not Saved message</returns>
        /// <writer>Amit Bansal</writer>
        public string SaveProductContainer(int warehouseId, int locatorId, string value, string name, Decimal height, Decimal width, int parentContainerId)
        {
            MLocator   m_locator   = null;
            MWarehouse m_warehouse = null;

            // when warehouse ID is ZERO, then extract it from Locator
            if (warehouseId == 0 && locatorId > 0)
            {
                m_locator   = MLocator.Get(_ctx, locatorId);
                warehouseId = m_locator.GetM_Warehouse_ID();
            }
            // when locator ID is ZERO, then extract it either from Parent Conatiner or from Warehouse
            else if (warehouseId > 0 && locatorId == 0)
            {
                if (parentContainerId == 0)
                {
                    m_warehouse = MWarehouse.Get(_ctx, warehouseId);
                    locatorId   = m_warehouse.GetDefaultM_Locator_ID();
                }
                else
                {
                    locatorId = Util.GetValueOfInt(DB.ExecuteScalar("SELECT M_Locator_ID FROM M_ProductContainer WHERE M_ProductContainer_ID = " + parentContainerId, null, null));
                }
            }

            // need to check warehouse and locator shoyld be active during ceation of Product Container
            m_warehouse = MWarehouse.Get(_ctx, warehouseId);
            m_locator   = MLocator.Get(_ctx, locatorId);
            if (!m_warehouse.IsActive())
            {
                return(Msg.GetMsg(_ctx, "VIS_WarehouseNotActive"));
            }
            else if (!m_locator.IsActive())
            {
                return(Msg.GetMsg(_ctx, "VIS_LocatorNotActive"));
            }

            // Create Product Container in Locator Organization
            //MProductContainer container = new MProductContainer(_ctx, 0, null);
            //container.SetAD_Org_ID(m_locator.GetAD_Org_ID());
            //container.SetValue(value);
            //container.SetName(name);
            //container.SetM_Warehouse_ID(warehouseId);
            //container.SetM_Locator_ID(locatorId);
            //container.SetHeight(height);
            //container.SetWidth(width);
            //container.SetRef_M_Container_ID(parentContainerId);
            //if (!container.Save())
            //{
            //    ValueNamePair pp = VLogger.RetrieveError();
            //    return Msg.GetMsg(_ctx, "VIS_ContainernotSaved") + " " + (pp != null ? pp.GetName() : "");
            //}
            //else
            //{
            //    return "";
            //}
            return("");
        }
        /**
         * Creates a Work Order Transaction header for a given Work Order assumes locator is same locator as on Work Order
         * @param ctx
         * @param VAMFG_M_WorkOrder_ID Work Order
         * @param TxnType valid values are CI (Component Issue), CR (Component Return), RU (Resource Usage)
         * @param trx
         * @return MVAMFGMWrkOdrTransaction on success, null otherwise
         */
        public ViennaAdvantage.Model.MVAMFGMWrkOdrTransaction CreateWOTxn(Ctx ctx, int VAMFG_M_WorkOrder_ID, String TxnType, Trx trx)
        {
            ViennaAdvantage.Model.MVAMFGMWorkOrder wo = new ViennaAdvantage.Model.MVAMFGMWorkOrder(ctx, VAMFG_M_WorkOrder_ID, trx);
            if (wo == null || !wo.GetDocStatus().Equals(ViennaAdvantage.Model.MVAMFGMWorkOrder.DOCSTATUS_InProgress))
            {
                log.Severe("Work Order number not valid for transactions.");
                return(null);
            }

            log.Info("Getting Default Locator of Work Order Warehouse.");
            MLocator loc = MWarehouse.Get(ctx, wo.GetM_Warehouse_ID()).GetDefaultLocator();

            return(createWOTxn(ctx, VAMFG_M_WorkOrder_ID, TxnType, 0, loc.GetM_Locator_ID(), Decimal.Zero, trx));
        }
Exemple #4
0
        /// <summary>
        /// Get Product Container in term of Tree Structure
        /// </summary>
        /// <param name="warehouse">Warehouse -- which warehouse container we have to show</param>
        /// <param name="locator">Locato - which locator container we have to show</param>
        /// <param name="container">not used this parameter functionality -- Tree structure mismatched</param>
        /// <returns></returns>
        public List <TreeContainer> GetContainerAsTree(int warehouse, int locator, int container, string validation)
        {
            if (warehouse == 0 && locator > 0)
            {
                MLocator m_locator = MLocator.Get(_ctx, locator);
                warehouse = m_locator.GetM_Warehouse_ID();
            }
            List <TreeContainer> keyVal = new List <TreeContainer>();
            string sql = @"SELECT value ,   '.'   || LPAD (' ', LEVEL * 1)   || Name AS Name,
                            LEVEL ,   name   || '_'   || value AS ContainerName , m_productcontainer_id
                         FROM m_productcontainer WHERE IsActive = 'Y'";

            if (warehouse > 0)
            {
                sql += " AND m_warehouse_id = " + warehouse;
            }
            if (locator > 0)
            {
                sql += "  AND M_Locator_ID = " + locator;
            }
            if (container > 0)
            {
                sql += " AND M_ProductContainer_ID != " + container;
            }
            if (!String.IsNullOrEmpty(validation))
            {
                sql += " AND " + validation;
            }
            sql += "  START WITH NVL(ref_m_container_id,0) =0  CONNECT BY NVL(ref_m_container_id,0) = PRIOR m_productcontainer_id";
            sql  = MRole.GetDefault(_ctx).AddAccessSQL(sql, "M_ProductContainer", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO); // fully qualidfied - RO
            DataSet ds = DB.ExecuteDataset(sql);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    keyVal.Add(new TreeContainer()
                    {
                        Value                 = Util.GetValueOfString(ds.Tables[0].Rows[i]["value"]),
                        Name                  = Util.GetValueOfString(ds.Tables[0].Rows[i]["Name"]),
                        Level                 = Util.GetValueOfInt(ds.Tables[0].Rows[i]["LEVEL"]),
                        ContainerName         = Util.GetValueOfString(ds.Tables[0].Rows[i]["ContainerName"]),
                        M_ProductContainer_ID = Util.GetValueOfInt(ds.Tables[0].Rows[i]["M_ProductContainer_ID"])
                    });
                }
                ds.Dispose();
            }
            return(keyVal);
        }
        /// <summary>
        /// GetLocator
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public Dictionary <string, string> GetLocator(Ctx ctx, string fields)
        {
            MLocator defaultLocator     = MLocator.GetDefaultLocatorOfOrg(ctx, ctx.GetAD_Org_ID());
            int      Default_Locator_ID = 0;

            if (defaultLocator != null)
            {
                Default_Locator_ID = defaultLocator.Get_ID();
            }

            Dictionary <string, string> retlst = new Dictionary <string, string>();

            retlst["Default_Locator_ID"] = Default_Locator_ID.ToString();
            return(retlst);
        }
Exemple #6
0
 /// <summary>
 /// This function is used to create or update record on Container Storage
 /// </summary>
 /// <param name="containerStorage">Container Storage Object</param>
 /// <param name="dr">data row</param>
 /// <returns>container Storage object</returns>
 private X_M_ContainerStorage InsertContainerStorage(X_M_ContainerStorage containerStorage, DataRow dr)
 {
     if (containerStorage.Get_ID() <= 0)
     {
         containerStorage.SetAD_Client_ID(Convert.ToInt32(dr["AD_Client_ID"]));
         containerStorage.SetAD_Org_ID(MLocator.Get(containerStorage.GetCtx(), Convert.ToInt32(dr["M_Locator_ID"])).GetAD_Org_ID());
         containerStorage.SetM_Locator_ID(Convert.ToInt32(dr["M_Locator_ID"]));
         containerStorage.SetM_Product_ID(Convert.ToInt32(dr["M_Product_ID"]));
         containerStorage.SetM_AttributeSetInstance_ID(Convert.ToInt32(dr["M_AttributeSetInstance_ID"]));
         containerStorage.SetMMPolicyDate(Convert.ToDateTime(dr["MovementDate"]));
         containerStorage.SetIsPhysicalInventory(Convert.ToString(dr["PhysicalInventory"]).Equals("Y") ? true : false);
         containerStorage.SetQty(Convert.ToDecimal(dr["MovementQty"]));
     }
     else
     {
         containerStorage.SetQty(Decimal.Add(containerStorage.GetQty(), Convert.ToDecimal(dr["MovementQty"])));
     }
     return(containerStorage);
 }
        //	API to generate component transaction lines in M_WorkOrderTransactionLine. It should be possible to generate component lines
        //	for all push / pull components in a specific operation and all push / pull components in all operations in a work order

        /**
         * api to generate component transaction lines in M_WorkOrderTransactionLine. Skips Optional operations unless they are either the starting operation sequence or ending operation sequence in the list of operations specified
         * @param ctx
         * @param M_WorkOrderTransaction_ID Work Order Transaction
         * @param Qty Number of Work Order Product Assemblies for which to generate components
         * @param OperationFrom Starting operation sequence number
         * @param OperationTo Ending operation sequence number
         * @param SupplyType Component Supply Type. Valid values are P (Push), O (Operation Pull), A (Assembly Pull)
         * @param M_Locator_ID Supply Locator for the components in case of Push supply type
         * @param trx
         * @return Array of MVAMFGMWrkOdrTrnsctionLine
         */
        public ViennaAdvantage.Model.MVAMFGMWrkOdrTrnsctionLine[] GenerateComponentTxnLine(Ctx ctx, int M_WorkOrderTransaction_ID,
                                                                                           Decimal?Qty, Decimal?OperationFrom, Decimal?OperationTo,
                                                                                           String SupplyType, int M_Locator_ID, Trx trx)
        {
            int _countGOM01 = 0;
            Tuple <String, String, String> mInfo = null;

            if (Env.HasModulePrefix("GOM01_", out mInfo))
            {
                _countGOM01 = 1;
            }
            if (OperationFrom != null && OperationFrom.Value.CompareTo(OperationTo) > 0)
            {
                log.Severe("Operation Numbers not correct.");
                return(null);
            }

            ViennaAdvantage.Model.MVAMFGMWrkOdrTransaction wot = new ViennaAdvantage.Model.MVAMFGMWrkOdrTransaction(ctx, M_WorkOrderTransaction_ID, trx);
            if (0 == M_WorkOrderTransaction_ID || !((wot.GetDocStatus().Equals(X_VAMFG_M_WrkOdrTransaction.DOCSTATUS_Drafted) || wot.GetDocStatus().Equals(X_VAMFG_M_WrkOdrTransaction.DOCSTATUS_InProgress)) &&
                                                    (wot.GetVAMFG_WorkOrderTxnType().Equals(X_VAMFG_M_WrkOdrTransaction.VAMFG_WORKORDERTXNTYPE_1_ComponentIssueToWorkOrder) ||
                                                     wot.GetVAMFG_WorkOrderTxnType().Equals(X_VAMFG_M_WrkOdrTransaction.VAMFG_WORKORDERTXNTYPE_ComponentReturnFromWorkOrder))))
            {
                log.Severe("Cannot create component lines against give WO Txn.");
                return(null);
            }

            if (Qty != null && Qty.Value.CompareTo(Decimal.Zero) <= 0)
            {
                log.Severe("Number of product assemblies must be positive");
                return(null);
            }

            //ArrayList<MVAMFGMWrkOdrTrnsctionLine> wotLines = new ArrayList<MVAMFGMWrkOdrTrnsctionLine>();
            // List<MVAMFGMWrkOdrTrnsctionLine> wotLines = new List<MVAMFGMWrkOdrTrnsctionLine>();
            ArrayList wotLines = new ArrayList();

            int lastMandatoryWOO = DB.GetSQLValue(trx, "SELECT MAX(VAMFG_SeqNo) FROM VAMFG_M_WorkOrderOperation " +
                                                  "WHERE VAMFG_M_WorkOrder_ID = " + wot.GetVAMFG_M_WorkOrder_ID() + " AND VAMFG_IsOptional<>'Y'");

            //			automatically consider AssemblyPull Supply Type when the OperationTo is greater than the last Work Order Operation.
            //			This in turn should take care of optional operations.
            bool assemblyPull = lastMandatoryWOO == OperationTo;

            StringBuilder response = new StringBuilder("");

            //	Getting the WorkOrder product assembly quantity
            Decimal woQty = DB.GetSQLValue(trx, "SELECT VAMFG_QtyEntered FROM VAMFG_M_WorkOrder " +
                                           "WHERE VAMFG_M_WorkOrder_ID = " + wot.GetVAMFG_M_WorkOrder_ID());

            // Get component requirements based on the operations moved through in this transaction and then make lines
            StringBuilder sqlBuf = new StringBuilder("SELECT woc.M_Product_ID, woc.C_UOM_ID, woc.VAMFG_QtyRequired, " +
                                                     " woc.VAMFG_SupplyType, woc.M_AttributeSetInstance_ID, woc.M_Locator_ID, woc.BasisType," +
                                                     " woo.VAMFG_M_WorkOrderOperation_ID, woc.VAMFG_QtyAvailable, woc.VAMFG_QtySpent," +
                                                     " woc.VAMFG_QtyAllocated, woc.VAMFG_QtyDedicated,woc.isqualitycorrection" +
                                                     " FROM VAMFG_M_WorkOrderOperation woo INNER JOIN VAMFG_M_WorkOrderComponent woc ON woo.VAMFG_M_WorkOrderOperation_ID = woc.VAMFG_M_WorkOrderOperation_ID" +
                                                     " WHERE woo.VAMFG_M_WorkOrder_ID = " + wot.GetVAMFG_M_WorkOrder_ID() + " AND woc.VAMFG_QtyRequired != 0 AND (woo.VAMFG_IsOptional <> 'Y' OR ");

            if (OperationFrom != null && OperationFrom.Value.CompareTo(Decimal.Zero) > 0)
            {
                sqlBuf.Append(" woo.VAMFG_SeqNo =" + VAdvantage.Utility.Util.GetValueOfInt(OperationFrom));
                sqlBuf.Append(" OR woo.VAMFG_SeqNo =" + VAdvantage.Utility.Util.GetValueOfInt(OperationTo));
                sqlBuf.Append(")");
            }
            else
            {
                sqlBuf.Append(" woo.VAMFG_SeqNo =0");
                sqlBuf.Append(" OR woo.VAMFG_SeqNo =0");
                sqlBuf.Append(")");
            }
            // Set OperationTo sequence no
            if (OperationTo != null && OperationTo.Value.CompareTo(Decimal.Zero) > 0)
            {
                sqlBuf.Append(" AND ((woo.VAMFG_SeqNo BETWEEN " + VAdvantage.Utility.Util.GetValueOfInt(OperationFrom) + " AND " + VAdvantage.Utility.Util.GetValueOfInt(OperationTo));
                sqlBuf.Append(")");
            }
            else
            {
                sqlBuf.Append(" AND ((woo.VAMFG_SeqNo BETWEEN " + lastMandatoryWOO + " AND 0");
                sqlBuf.Append(")");
            }

            if (assemblyPull) // if assembly pull, then get component lines from all operations except
            {
                sqlBuf.Append(" OR woc.VAMFG_SupplyType = 'A'");
            }
            sqlBuf.Append(" ) ORDER BY woo.VAMFG_SeqNo, woc.M_Product_ID, woc.VAMFG_QtyRequired "); // close the statement and add ORDER BY clause
            String sql = sqlBuf.ToString();
            // SqlParameter[] param = null;
            IDataReader idr = null;
            DataTable   dt  = new DataTable();

            try
            {
                //pstmt.setInt(1, wot.GetVAMFG_M_WorkOrder_ID()); // woo.VAMFG_M_WorkOrder_ID
                //param = new SqlParameter[5];
                //param[0] = new SqlParameter("@param1", wot.GetVAMFG_M_WorkOrder_ID());
                //// Set OperationFrom sequence no
                //if (OperationFrom != null && OperationFrom.Value.CompareTo(Decimal.Zero) > 0)
                //{
                //    param[1] = new SqlParameter("@param2", VAdvantage.Utility.Util.GetValueOfInt(OperationFrom));
                //    param[3] = new SqlParameter("@param4", VAdvantage.Utility.Util.GetValueOfInt(OperationFrom));
                //    //pstmt.setInt(2, OperationFrom.intValue());
                //    //pstmt.setInt(4, OperationFrom.intValue());
                //}
                //else
                //{
                //    param[1] = new SqlParameter("@param2", 0);
                //    param[3] = new SqlParameter("@param4", 0);
                //    //pstmt.setInt(2, 0);
                //    //pstmt.setInt(4, 0);
                //}
                //// Set OperationTo sequence no
                //if (OperationTo != null && OperationTo.Value.CompareTo(Decimal.Zero) > 0)
                //{
                //    param[2] = new SqlParameter("@param3", VAdvantage.Utility.Util.GetValueOfInt(OperationTo));
                //    param[4] = new SqlParameter("@param5", VAdvantage.Utility.Util.GetValueOfInt(OperationTo));
                //    //pstmt.setInt(3, OperationTo.intValue());
                //    //pstmt.setInt(5, OperationTo.intValue());
                //}
                //else
                //{
                //    param[2] = new SqlParameter("@param3", lastMandatoryWOO);
                //    param[4] = new SqlParameter("@param5", 0);
                //    //pstmt.setInt(3, lastMandatoryWOO);
                //    //pstmt.setInt(5, 0);
                //}

                //rs = pstmt.executeQuery();
                idr = DB.ExecuteReader(sql.ToString(), null, trx);
                //dt.Load(idr);
                //idr.Close();
                int     productID  = 0;
                int     uomID      = 0;
                Decimal qtyEntered = Decimal.Zero;  //	Quantity in the Product Transaction Line
                Decimal QtyInKg    = Decimal.Zero;  //	Quantity in KG at Product Transaction Line
                int     asiID      = 0;
                int     locatorID  = 0;

                //			set the component line no to 10 greater than existing
                int compLineNo = DB.GetSQLValue(trx, "SELECT COALESCE(MAX(VAMFG_Line),0)+10 FROM VAMFG_M_WrkOdrTrnsctionLine " +
                                                "WHERE VAMFG_M_WrkOdrTransaction_ID =" + M_WorkOrderTransaction_ID);

                bool checkInventory = wot.GetVAMFG_WorkOrderTxnType().Equals(X_VAMFG_M_WrkOdrTransaction.VAMFG_WORKORDERTXNTYPE_1_ComponentIssueToWorkOrder);

                while (idr.Read())
                {
                    productID = VAdvantage.Utility.Util.GetValueOfInt(idr[0]);
                    uomID     = VAdvantage.Utility.Util.GetValueOfInt(idr[1]);
                    Decimal qtyRequired   = VAdvantage.Utility.Util.GetValueOfDecimal(idr[2]);
                    String  wocSupplyType = VAdvantage.Utility.Util.GetValueOfString(idr[3]);
                    asiID     = VAdvantage.Utility.Util.GetValueOfInt(idr[4]);
                    locatorID = VAdvantage.Utility.Util.GetValueOfInt(idr[5]);
                    String basisType     = VAdvantage.Utility.Util.GetValueOfString(idr[6]);
                    int    wooID         = VAdvantage.Utility.Util.GetValueOfInt(idr[7]);
                    string IsQualityCorr = VAdvantage.Utility.Util.GetValueOfString(idr[12]);

                    //  If qty=0, then no value was passed for Qty
                    //	for Component Issue assume issue needs to be generated for remaining amount
                    //	for Component Return assume return needs to be generated for unused quantity
                    Decimal qtyIssued    = VAdvantage.Utility.Util.GetValueOfDecimal(idr[8]);
                    Decimal qtySpent     = VAdvantage.Utility.Util.GetValueOfDecimal(idr[9]);
                    Decimal qtyAllocated = VAdvantage.Utility.Util.GetValueOfDecimal(idr[10]);
                    Decimal qtyDedicated = VAdvantage.Utility.Util.GetValueOfDecimal(idr[11]);

                    // continue if component line is quality correction
                    if (IsQualityCorr == "Y")
                    {
                        continue;
                    }

                    if (Qty == null)
                    {
                        if (wot.GetVAMFG_WorkOrderTxnType().Equals(X_VAMFG_M_WrkOdrTransaction.VAMFG_WORKORDERTXNTYPE_1_ComponentIssueToWorkOrder))
                        {
                            // qtyEntered = (qtyRequired.multiply(woQty)).subtract(qtyIssued).subtract(qtyAllocated).subtract(qtyDedicated);
                            qtyEntered = Decimal.Subtract(Decimal.Subtract(Decimal.Subtract(Decimal.Multiply(qtyRequired, woQty), qtyIssued), qtyAllocated), qtyDedicated);
                        }
                        else    //	automatically assume ComponentReturn txn
                        {
                            qtyEntered = Decimal.Subtract(qtyIssued, qtySpent);
                        }
                    }
                    else
                    {
                        qtyEntered = Decimal.Multiply(qtyRequired, Qty.Value);
                        if (wot.GetVAMFG_WorkOrderTxnType().Equals(X_VAMFG_M_WrkOdrTransaction.VAMFG_WORKORDERTXNTYPE_ComponentReturnFromWorkOrder)
                            //&& qtyEntered.setScale(MUOM.getPrecision(ctx, uomID), Decimal.ROUND_HALF_UP).compareTo(qtyIssued.subtract(qtySpent)) > 0)
                            && Decimal.Round((qtyEntered), VAdvantage.Model.MUOM.GetPrecision(ctx, uomID), MidpointRounding.AwayFromZero).CompareTo(Decimal.Subtract(qtyIssued, qtySpent)) > 0)
                        {
                            log.Warning("Not enough quantities to return from Work Order");
                            continue;
                        }
                    }

                    //	For Pull type: If quantity requirement has been filled or there are not enough quantities to issue
                    //	then don't generate a line -> goto next line processing
                    //if (qtyEntered.setScale(MUOM.getPrecision(ctx, uomID), Decimal.ROUND_HALF_UP).compareTo(Decimal.Zero) <= 0)
                    //    continue;
                    if (Decimal.Round((qtyEntered), VAdvantage.Model.MUOM.GetPrecision(ctx, uomID), MidpointRounding.AwayFromZero).CompareTo(Decimal.Zero) <= 0)
                    {
                        continue;
                    }

                    if (SupplyType.Equals(wocSupplyType) ||
                        (wocSupplyType.Equals(X_VAMFG_M_WorkOrderComponent.VAMFG_SUPPLYTYPE_AssemblyPull) && assemblyPull &&
                         !SupplyType.Equals(X_VAMFG_M_WorkOrderComponent.VAMFG_SUPPLYTYPE_Push)))
                    {
                        ViennaAdvantage.Model.MVAMFGMWrkOdrTrnsctionLine compIssueLine = new ViennaAdvantage.Model.MVAMFGMWrkOdrTrnsctionLine(ctx, 0, trx);
                        //	set the client + org derived from the transaction header
                        compIssueLine.SetClientOrg(wot);
                        // Work done to add attributeset Instance ID for finished products
                        compIssueLine.SetRequiredColumns(M_WorkOrderTransaction_ID, productID, asiID, uomID, qtyEntered, wooID, basisType);

                        // Added by Bharat on 26 Dec 2017 to set Business Partner Information on Line
                        compIssueLine.SetC_BPartner_ID(wot.GetC_BPartner_ID());
                        compIssueLine.SetC_BPartner_Location_ID(wot.GetC_BPartner_Location_ID());

                        if (locatorID != 0)     // Implicit assumption : Only Pull components will have a locator populated in the WOC
                        {
                            // compIssueLine.SetM_Locator_ID(locatorID);
                            ((X_VAMFG_M_WrkOdrTrnsctionLine)compIssueLine).SetM_Locator_ID(locatorID);
                        }
                        else
                        {
                            // Check if the locator passed is under the Warehouse of the Work Order
                            // If no, then skip generating transaction line for this component
                            ViennaAdvantage.Model.MVAMFGMWorkOrder wo = new ViennaAdvantage.Model.MVAMFGMWorkOrder(ctx, wot.GetVAMFG_M_WorkOrder_ID(), trx);
                            MLocator loc = new MLocator(ctx, M_Locator_ID, trx);
                            if (loc.GetM_Warehouse_ID() != wo.GetM_Warehouse_ID())
                            {
                                log.Warning("Locator passed is not under the Warehouse of the WorkOrder");
                                continue;
                            }
                            ((X_VAMFG_M_WrkOdrTrnsctionLine)compIssueLine).SetM_Locator_ID(M_Locator_ID);
                        }

                        if (asiID > 0)
                        {
                            compIssueLine.SetM_AttributeSetInstance_ID(asiID);
                        }
                        compIssueLine.SetVAMFG_Line(compLineNo);
                        compLineNo += 10;

                        // Added by Bharat on 20/12/2016 to Set Density and Liter values for production execution Process of Gulf Oil.

                        if (_countGOM01 > 0)
                        {
                            Decimal density = wot.GetGOM01_Density();
                            QtyInKg = Decimal.Multiply(qtyEntered, density);
                            QtyInKg = Decimal.Round((QtyInKg), VAdvantage.Model.MUOM.GetPrecision(ctx, uomID));
                            Decimal ltrQty = density > 0 ? QtyInKg / density : 0;
                            compIssueLine.SetGOM01_Quantity(QtyInKg);
                            compIssueLine.SetGOM01_ActualQuantity(QtyInKg);
                            compIssueLine.SetGOM01_Density(density);
                            compIssueLine.SetGOM01_Litre(Decimal.Round((ltrQty), VAdvantage.Model.MUOM.GetPrecision(ctx, uomID)));
                            compIssueLine.SetGOM01_FromProcess(true);
                        }
                        // End Bharat


                        wotLines.Add(compIssueLine);

                        VAdvantage.Model.MProduct product = new VAdvantage.Model.MProduct(ctx, productID, trx);
                        if (checkInventory)
                        {
                            if (_countGOM01 > 0)
                            {
                                response.Append(product.GetName() + ": ").Append(VerifyQuantity(product, wot, QtyInKg, asiID)).Append(" ");
                            }
                            else
                            {
                                response.Append(product.GetName() + ": ").Append(VerifyQuantity(product, wot, qtyEntered, asiID)).Append(" ");
                            }
                        }

                        if (compIssueLine.Save())
                        {
                        }
                    }
                }
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sqlBuf.ToString(), e);
                log.Severe("SQL failure in checking component requirements");
                return(null);
            }
            finally
            {
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }
            }

            //Not using this here we have save line one by one
            //if (save)
            //{
            //    if (!VAdvantage.Model.PO.SaveAll(trx, wotLines))
            //    {
            //        log.Severe("Could not save component transaction lines.");
            //        return null;
            //    }
            //}
            log.SaveInfo("Info", response.ToString());
            //return wotLines.toArray(new MVAMFGMWrkOdrTrnsctionLine[] { });
            ViennaAdvantage.Model.MVAMFGMWrkOdrTrnsctionLine[] newObject = null;

            try
            {
                newObject = (ViennaAdvantage.Model.MVAMFGMWrkOdrTrnsctionLine[])wotLines.ToArray(typeof(ViennaAdvantage.Model.MVAMFGMWrkOdrTrnsctionLine));

                //newObject = new MVAMFGMWrkOdrTrnsctionLine[] { };
                //newObject = Convert.ChangeType(wotLines.ToArray(), typeof(MVAMFGMWrkOdrTrnsctionLine[]));
                //newObject = lst.ToArray();
                return(newObject);
            }
            catch { }
            return((ViennaAdvantage.Model.MVAMFGMWrkOdrTrnsctionLine[])wotLines.ToArray());
        }
Exemple #8
0
        protected override string DoIt()
        {
            Qry = "TRUNCATE TABLE M_TransactionSummary";
            int no = DB.ExecuteQuery(Qry);

            sql.Append(@" SELECT TR.M_PRODUCT_ID ,
                      TR.M_LOCATOR_ID ,
                      TR.M_ATTRIBUTESETINSTANCE_ID ,
                      TR.M_TRANSACTION_ID ,
                      TR.CURRENTQTY ,
                      TR.MOVEMENTQTY ,
                      TR.MOVEMENTTYPE ,
                      TR.MOVEMENTDATE ,
                      TR.AD_ORG_ID
                    FROM M_TRANSACTION TR
                    INNER JOIN M_PRODUCT PR
                    ON PR.M_PRODUCT_ID  =TR.M_PRODUCT_ID
                    WHERE TR.ISACTIVE   = 'Y'
                    AND PR.ISACTIVE     ='Y'");
            if (productId > 0)
            {
                sql.Append(@" AND PR.M_PRODUCT_ID  IN ( " + productId + " )");
            }
            sql.Append(@" ORDER BY TR.M_PRODUCT_ID ,
                      TR.M_LOCATOR_ID ,
                      TR.M_ATTRIBUTESETINSTANCE_ID ,
                      TR.MOVEMENTDATE ,
                      TR.M_TRANSACTION_ID ASC ");
            dsTransaction = new DataSet();
            try
            {
                dsTransaction = DB.ExecuteDataset(sql.ToString(), null, Get_Trx());
                if (dsTransaction != null)
                {
                    if (dsTransaction.Tables.Count > 0)
                    {
                        if (dsTransaction.Tables[0].Rows.Count > 0)
                        {
                            int i = 0;
                            log.Info(" =====> Transaction Summary Entering Started at " + DateTime.Now.ToString() + " , Total Transactions To Correct = " + dsTransaction.Tables[0].Rows.Count + " <===== ");
                            for (i = 0; i < dsTransaction.Tables[0].Rows.Count; i++)
                            {
                                if (i % 10000 == 0)
                                {
                                    log.Info(" =====> " + i + " Transactions Updated till " + DateTime.Now.ToString() + "<===== ");
                                }
                                _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
                                _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
                                _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
                                _moveType   = Util.GetValueOfString(dsTransaction.Tables[0].Rows[i]["MovementType"]);
                                _moveDate   = Util.GetValueOfDateTime(dsTransaction.Tables[0].Rows[i]["MovementDate"]);
                                _moveQty    = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["MovementQty"]);
                                _currentQty = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
                                sql.Clear();

                                sql.Append(@"Select M_TransactionSummary_ID From M_TransactionSummary Where M_Product_ID=" + _M_Product_ID + @" AND M_AttributeSetInstance_ID=" + _M_AttributeSetInstance_ID + @"
                                        AND M_Locator_ID=" + _M_Locator_ID + @" AND MovementDate=" + GlobalVariable.TO_DATE(_moveDate, true));
                                int M_TransactionSummary_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql.ToString()));
                                if (M_TransactionSummary_ID > 0)
                                {
                                    Trs = new MTransactionSummary(GetCtx(), M_TransactionSummary_ID, Get_TrxName());
                                    Trs.SetClosingStock(_currentQty);
                                }
                                else
                                {
                                    Qry = "SELECT Count(*) FROM M_TransactionSummary WHERE IsActive = 'Y' AND  M_Product_ID = " + _M_Product_ID +
                                          " AND M_Locator_ID = " + _M_Locator_ID + " AND M_AttributeSetInstance_ID = " + _M_AttributeSetInstance_ID +
                                          " AND movementdate < " + GlobalVariable.TO_DATE(_moveDate, true);
                                    int existOld = Util.GetValueOfInt(DB.ExecuteScalar(Qry));
                                    if (existOld > 0)
                                    {
                                        Qry = "SELECT ClosingStock FROM M_TransactionSummary WHERE IsActive = 'Y' AND  M_Product_ID = " + _M_Product_ID +
                                              " AND M_Locator_ID = " + _M_Locator_ID + " AND M_AttributeSetInstance_ID = " + _M_AttributeSetInstance_ID +
                                              " AND movementdate < " + GlobalVariable.TO_DATE(_moveDate, true) + " ORDER BY MovementDate DESC";
                                    }
                                    else
                                    {
                                        Qry = "SELECT NVL(GetStockofWarehouse(" + _M_Product_ID + "," + _M_Locator_ID + ",0," + _M_AttributeSetInstance_ID + ","
                                              + GlobalVariable.TO_DATE(Convert.ToDateTime(_moveDate).AddDays(-1), true) + "," + GetAD_Client_ID() + "," + GetAD_Org_ID() + "),0) AS Stock FROM DUAL";
                                    }
                                    OpeningStock = Util.GetValueOfDecimal(DB.ExecuteScalar(Qry));
                                    MLocator loc = new MLocator(GetCtx(), _M_Locator_ID, Get_TrxName());
                                    Trs = new MTransactionSummary(GetCtx(), loc.GetAD_Org_ID(), _M_Locator_ID, _M_Product_ID, _M_AttributeSetInstance_ID,
                                                                  OpeningStock, _currentQty, _moveDate, Get_TrxName());
                                }
                                if (_moveType == MTransaction.MOVEMENTTYPE_CustomerReturns)
                                {
                                    Trs.SetQtyCustReturn(Trs.GetQtyCustReturn() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_CustomerShipment)
                                {
                                    Trs.SetQtyCustShipment(Trs.GetQtyCustShipment() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_InventoryIn)
                                {
                                    Trs.SetQtyInventoryIn(Trs.GetQtyInventoryIn() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_InventoryOut)
                                {
                                    Trs.SetQtyInventoryOut(Trs.GetQtyInventoryOut() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_MovementFrom)
                                {
                                    Trs.SetQtyMoveOut(Trs.GetQtyMoveOut() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_MovementTo)
                                {
                                    Trs.SetQtyMoveTo(Trs.GetQtyMoveTo() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_Production_)
                                {
                                    Trs.SetQtyProductionOut(Trs.GetQtyProductionOut() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_ProductionPlus)
                                {
                                    Trs.SetQtyProductionIn(Trs.GetQtyProductionIn() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_VendorReceipts)
                                {
                                    Trs.SetQtyMaterialIn(Trs.GetQtyMaterialIn() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_VendorReturns)
                                {
                                    Trs.SetQtyMaterialOut(Trs.GetQtyMaterialOut() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_WorkOrderPlus)
                                {
                                    Trs.SetQtyWorkOrderIn(Trs.GetQtyWorkOrderIn() + _moveQty);
                                }
                                else if (_moveType == MTransaction.MOVEMENTTYPE_WorkOrder_)
                                {
                                    Trs.SetQtyWorkOrderOut(Trs.GetQtyWorkOrderOut() + _moveQty);
                                }
                                if (!Trs.Save())
                                {
                                    log.Info(Msg.GetMsg(GetCtx(), "TrxSummaryNotSaved"));
                                    Rollback();
                                }
                                else
                                {
                                    log.Info(Msg.GetMsg(GetCtx(), "TrxSummarySaved"));
                                    Commit();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (dsTransaction != null)
                {
                    dsTransaction.Dispose();
                }
                return(Msg.GetMsg(GetCtx(), "NotCompleted"));
            }
            finally
            {
                if (dsTransaction != null)
                {
                    dsTransaction.Dispose();
                }
            }
            log.Info(" =====> Transaction Correction End at " + DateTime.Now.ToString() + " <===== ");
            return(Msg.GetMsg(GetCtx(), "SucessfullyCompleted"));
        }
        /// <summary>
        /// savelocator value into database
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="warehouseId"></param>
        /// <param name="tValue"></param>
        /// <param name="tX"></param>
        /// <param name="tY"></param>
        /// <param name="tZ"></param>
        /// <returns></returns>
        public int LocatorSave(Ctx ctx, string warehouseId, string tValue, string tX, string tY, string tZ)
        {
            var loc = MLocator.Get(ctx, Convert.ToInt32(warehouseId), tValue, tX, tY, tZ);

            return(loc.GetM_Locator_ID());
        }
        }       //	prepare

        /// <summary>
        /// Perform Process.
        /// </summary>
        /// <returns>Message (text with variables)</returns>
        protected override String DoIt()
        {
            log.Info("C_BPartner_ID=" + _C_BPartner_ID
                     + ", AD_Org_ID=" + _AD_Org_ID
                     + ", AD_OrgType_ID=" + _AD_OrgType_ID
                     + ", AD_Role_ID=" + _AD_Role_ID);
            if (_C_BPartner_ID == 0)
            {
                throw new Exception("No Business Partner ID");
            }
            MBPartner bp = new MBPartner(GetCtx(), _C_BPartner_ID, Get_Trx());

            if (bp.Get_ID() == 0)
            {
                throw new Exception("Business Partner not found - C_BPartner_ID=" + _C_BPartner_ID);
            }
            //	BP Location
            MBPartnerLocation[] locs = bp.GetLocations(false);
            if (locs == null || locs.Length == 0)
            {
                throw new ArgumentException("Business Partner has no Location");
            }
            //	Location
            int C_Location_ID = locs[0].GetC_Location_ID();

            if (C_Location_ID == 0)
            {
                throw new ArgumentException("Business Partner Location has no Address");
            }

            //	Create Org
            Boolean newOrg = _AD_Org_ID == 0;
            MOrg    org    = new MOrg(GetCtx(), _AD_Org_ID, Get_Trx());

            if (newOrg)
            {
                org.SetValue(bp.GetValue());
                org.SetName(bp.GetName());
                org.SetDescription(bp.GetDescription());
                if (!org.Save())
                {
                    return(GetRetrievedError(org, "Organization not saved"));
                    //throw new Exception("Organization not saved");
                }
            }
            else        //	check if linked to already
            {
                int C_BPartner_ID = org.GetLinkedC_BPartner_ID();
                if (C_BPartner_ID > 0)
                {
                    throw new ArgumentException("Organization '" + org.GetName()
                                                + "' already linked (to C_BPartner_ID=" + C_BPartner_ID + ")");
                }
            }
            _AD_Org_ID = org.GetAD_Org_ID();

            //	Update Org Info
            MOrgInfo oInfo = org.GetInfo();

            oInfo.SetAD_OrgType_ID(_AD_OrgType_ID);
            if (newOrg)
            {
                oInfo.SetC_Location_ID(C_Location_ID);
            }

            //	Create Warehouse
            MWarehouse wh = null;

            if (!newOrg)
            {
                MWarehouse[] whs = MWarehouse.GetForOrg(GetCtx(), _AD_Org_ID);
                if (whs != null && whs.Length > 0)
                {
                    wh = whs[0]; //	pick first
                }
            }
            //	New Warehouse
            if (wh == null)
            {
                wh = new MWarehouse(org);
                if (!wh.Save())
                {
                    return(GetRetrievedError(wh, "Warehouse not saved"));
                    //throw new Exception("Warehouse not saved");
                }
            }
            //	Create Locator
            MLocator mLoc = wh.GetDefaultLocator();

            if (mLoc == null)
            {
                mLoc = new MLocator(wh, "Standard");
                mLoc.SetIsDefault(true);
                mLoc.Save();
            }

            //	Update/Save Org Info
            oInfo.SetM_Warehouse_ID(wh.GetM_Warehouse_ID());
            if (!oInfo.Save(Get_Trx()))
            {
                return(GetRetrievedError(oInfo, "Organization Info not saved"));
                //throw new Exception("Organization Info not saved");
            }

            //	Update BPartner
            bp.SetAD_OrgBP_ID(_AD_Org_ID);
            if (bp.GetAD_Org_ID() != 0)
            {
                bp.SetClientOrg(bp.GetAD_Client_ID(), 0); //	Shared BPartner
            }

            //	Save BP
            if (!bp.Save())
            {
                return(GetRetrievedError(bp, "Business Partner not updated"));
                //throw new Exception("Business Partner not updated");
            }

            //	Limit to specific Role
            if (_AD_Role_ID != 0)
            {
                Boolean          found       = false;
                MRoleOrgAccess[] orgAccesses = MRoleOrgAccess.GetOfOrg(GetCtx(), _AD_Org_ID);
                //	delete all accesses except the specific
                for (int i = 0; i < orgAccesses.Length; i++)
                {
                    if (orgAccesses[i].GetAD_Role_ID() == _AD_Role_ID)
                    {
                        found = true;
                    }
                    else
                    {
                        orgAccesses[i].Delete(true);
                    }
                }
                //	create access
                if (!found)
                {
                    MRoleOrgAccess orgAccess = new MRoleOrgAccess(org, _AD_Role_ID);
                    orgAccess.Save();
                }
            }

            //	Reset Client Role
            MRole.GetDefault(GetCtx(), true);

            return("Business Partner - Organization Link created");
        } //	doIt