예제 #1
0
        /**
         *  Set Value, Name, Description
         *	@param invoice
         *	@param deliveryCount count
         *	@param product product
         *	@param partner partner
         */
        public void SetValueNameDescription(MInvoice invoice,
                                            int deliveryCount, MProduct product, MBPartner partner)
        {
            String documentNo = "_" + invoice.GetDocumentNo();

            if (deliveryCount > 1)
            {
                documentNo += "_" + deliveryCount;
            }
            //	Value
            String value = partner.GetValue() + "_" + product.GetValue();

            if (value.Length > 40 - documentNo.Length)
            {
                value = value.Substring(0, 40 - documentNo.Length) + documentNo;
            }
            // Change to set Value from Document Sequence
            // SetValue(value);

            // Change to set only name of product as value in Asset
            //	Name		MProduct.afterSave
            // String name = partner.GetName() + " - " + product.GetName();

            String name = product.GetName();

            if (name.Length > 60)
            {
                name = name.Substring(0, 60);
            }
            SetName(name);
            //	Description
            String description = product.GetDescription();

            SetDescription(description);
        }
예제 #2
0
        /// <summary>
        /// Get Product Details
        /// </summary>
        /// <returns>Product Name, etc.</returns>
        public String GetProductDetailHTML()
        {
            if (GetM_Product_ID() == 0)
            {
                return("");
            }
            StringBuilder sb      = new StringBuilder();
            MProduct      product = MProduct.Get(GetCtx(), GetM_Product_ID());

            sb.Append(product.GetName());
            if (product.GetDescription() != null && product.GetDescription().Length > 0)
            {
                sb.Append("<br><i>").Append(product.GetDescription()).Append("</i>");
            }
            return(sb.ToString());
        }
        protected override bool BeforeSave(bool newRecord)
        {
            // Movement Quantity can not be less than 0 when planned is greater than 0
            if (GetPlannedQty() > 0 && GetMovementQty() < 0)
            {
                log.SaveWarning("Warning", Msg.GetMsg(GetCtx(), "MovementQtyCantbelesszero"));
                return(false);
            }

            // Movement Quantity can not be greater than 0 when planned is less than 0
            if (GetPlannedQty() < 0 && GetMovementQty() > 0)
            {
                log.SaveWarning("Warning", Msg.GetMsg(GetCtx(), "MovementQtyCantbegrtzero"));
                return(false);
            }

            // when warehouse disallow negative inventory is false then on hand qty can't be in negative
            wh = MWarehouse.Get(GetCtx(), GetM_Warehouse_ID());
            if (wh.IsDisallowNegativeInv() && GetM_Product_ID() > 0)
            {
                product = MProduct.Get(GetCtx(), GetM_Product_ID());
                string qry = "SELECT NVL(SUM(NVL(QtyOnHand,0)),0) AS QtyOnHand FROM M_Storage where m_locator_id=" + GetM_Locator_ID() + " and m_product_id=" + GetM_Product_ID();
                //if (GetM_AttributeSetInstance_ID() != 0)
                //{
                qry += " AND NVL(M_AttributeSetInstance_ID , 0) =" + GetM_AttributeSetInstance_ID();
                //}
                Decimal?OnHandQty = Convert.ToDecimal(DB.ExecuteScalar(qry));

                qry = @"SELECT NVL(SUM(MovementQty) , 0) FROM M_ProductionLine WHERE IsActive = 'Y' AND  M_Locator_ID=" + GetM_Locator_ID() + @" AND m_product_id=" + GetM_Product_ID() +
                      @" AND NVL(M_AttributeSetInstance_ID , 0) =" + GetM_AttributeSetInstance_ID() + @" AND M_Production_ID = " + GetM_Production_ID();
                if (!newRecord)
                {
                    qry += @" AND M_ProductionLine_ID <> " + GetM_ProductionLine_ID();
                }
                Decimal?moveQty = Convert.ToDecimal(DB.ExecuteScalar(qry));
                if ((OnHandQty + GetMovementQty() + moveQty) < 0)
                {
                    log.SaveError("", product.GetName() + ", " + Msg.GetMsg(GetCtx(), "VIS_InsufficientQty") + OnHandQty);
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Before Save
        /// </summary>
        /// <param name="newRecord">new</param>
        /// <returns>true if can be saved</returns>
        protected override bool BeforeSave(bool newRecord)
        {
            Decimal    VA024_ProvisionPrice = 0;
            MInventory inventory            = new MInventory(GetCtx(), GetM_Inventory_ID(), Get_Trx());
            MProduct   product = MProduct.Get(GetCtx(), GetM_Product_ID());

            if (newRecord && _isManualEntry)
            {
                //	Product requires ASI
                if (GetM_AttributeSetInstance_ID() == 0)
                {
                    if (product.GetM_AttributeSet_ID() != 0)
                    {
                        MAttributeSet mas = MAttributeSet.Get(GetCtx(), product.GetM_AttributeSet_ID());
                        //uncomment by Amit on behalf of Mandeep 7-3-2016
                        //if (mas.IsInstanceAttribute()
                        //    && (mas.IsMandatory() || mas.IsMandatoryAlways()))
                        if (mas.IsMandatory() || mas.IsMandatoryAlways())
                        {
                            log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "M_AttributeSetInstance_ID"));
                            return(false);
                        }
                    }
                } //	No ASI
            }     //	new or manual

            // not to create Internal use Inventory with -ve qty -- but during reversal system will create record with -ve qty
            // duing reversal -- ReversalDoc_ID contain refernce o  orignal record id
            if (IsInternalUse() && Get_ColumnIndex("ReversalDoc_ID") > 0 && GetReversalDoc_ID() == 0 && GetQtyInternalUse() < 0)
            {
                log.SaveError("", Msg.GetMsg(GetCtx(), "VIS_CantbeNegative"));
                return(false);
            }

            //	Set Line No
            if (GetLine() == 0)
            {
                String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_InventoryLine WHERE M_Inventory_ID=" + GetM_Inventory_ID();
                int    ii  = DataBase.DB.GetSQLValue(Get_TrxName(), sql);
                SetLine(ii);
            }

            // SI_0644.1 : Enforce UOM Precision - Rounding Quantities
            if (newRecord || Is_ValueChanged("QtyInternalUse"))
            {
                SetQtyInternalUse(GetQtyInternalUse());
            }

            // change to set Converted Quantity in Internal Use Qty and AsonDateQty and difference qty if there is differnce in UOM of Base Product and UOM Selected on line
            if (newRecord || Is_ValueChanged("QtyEntered") || Is_ValueChanged("C_UOM_ID"))
            {
                Decimal?qty = Util.GetValueOfDecimal(Get_Value("QtyEntered"));
                if (product.GetC_UOM_ID() != Util.GetValueOfInt(Get_Value("C_UOM_ID")))
                {
                    qty = MUOMConversion.ConvertProductFrom(GetCtx(), GetM_Product_ID(), Util.GetValueOfInt(Get_Value("C_UOM_ID")), Util.GetValueOfDecimal(Get_Value("QtyEntered")));
                    if (IsInternalUse())
                    {
                        SetQtyInternalUse(qty);
                    }
                    else
                    {
                        SetAsOnDateCount(qty);
                        SetDifferenceQty(qty);
                    }
                }
            }

            // SI_0644 - As on date and difference should be according to the precision of UOM attached.
            if (newRecord || Is_ValueChanged("AsOnDateCount"))
            {
                if (product != null)
                {
                    int precision = product.GetUOMPrecision();
                    SetAsOnDateCount(Decimal.Round(GetAsOnDateCount(), precision, MidpointRounding.AwayFromZero));
                }
            }

            // SI_0644 - As on date and difference should be according to the precision of UOM attached.
            if (newRecord || Is_ValueChanged("DifferenceQty"))
            {
                if (product != null)
                {
                    int precision = product.GetUOMPrecision();
                    SetDifferenceQty(Decimal.Round(GetDifferenceQty(), precision, MidpointRounding.AwayFromZero));
                }
            }

            // SI_0682_1 Need to update the reserved qty on requisition line by internal use line save aslo and should work as work in inventory move.
            if (Env.IsModuleInstalled("DTD001_") && IsInternalUse())
            {
                qtyReserved = Util.GetValueOfDecimal(Get_ValueOld("QtyInternalUse"));
            }

            int    M_Warehouse_ID = 0; MWarehouse wh = null;
            string qry = "select m_warehouse_id from m_locator where m_locator_id=" + GetM_Locator_ID();

            M_Warehouse_ID = Util.GetValueOfInt(DB.ExecuteScalar(qry, null, Get_TrxName()));

            wh  = MWarehouse.Get(GetCtx(), M_Warehouse_ID);
            qry = "SELECT QtyOnHand FROM M_Storage where m_locator_id=" + GetM_Locator_ID() + " and m_product_id=" + GetM_Product_ID();
            if (GetM_AttributeSetInstance_ID() != 0)
            {
                qry += " AND M_AttributeSetInstance_ID=" + GetM_AttributeSetInstance_ID();
            }
            OnHandQty = Convert.ToDecimal(DB.ExecuteScalar(qry, null, Get_TrxName()));
            // when record is in completed & closed stage - then no need to check qty availablity in warehouse
            if (wh.IsDisallowNegativeInv() == true &&
                (!(inventory.GetDocStatus() == "CO" || inventory.GetDocStatus() == "CL" ||
                   inventory.GetDocStatus() == "RE" || inventory.GetDocStatus() == "VO")))
            {
                #region DisallowNegativeInv = True
                if (!IsInternalUse() && GetDifferenceQty() > 0)
                {
                    if ((OnHandQty - GetDifferenceQty()) < 0)
                    {
                        log.SaveError("Info", product.GetName() + ", " + Msg.GetMsg(GetCtx(), "VIS_InsufficientQty") + OnHandQty);
                        return(false);
                    }
                }
                else if (IsInternalUse())
                {
                    if ((OnHandQty - GetQtyInternalUse()) < 0)
                    {
                        log.SaveError("Info", product.GetName() + " , " + Msg.GetMsg(GetCtx(), "VIS_InsufficientQty") + OnHandQty);
                        return(false);
                    }
                }
                #endregion
            }
            //	Enforce Qty UOM
            if (newRecord || Is_ValueChanged("QtyCount"))
            {
                SetQtyCount(GetQtyCount());
            }

            //	InternalUse Inventory
            if (IsInternalUse() && Env.Signum(GetQtyInternalUse()) == 0)
            {
                log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "QtyInternalUse"));
                return(false);
            }
            if (Env.Signum(GetQtyInternalUse()) != 0)
            {
                if (!INVENTORYTYPE_ChargeAccount.Equals(GetInventoryType()))
                {
                    SetInventoryType(INVENTORYTYPE_ChargeAccount);
                }
                //
                if (GetC_Charge_ID() == 0)
                {
                    log.SaveError("Error", Msg.GetMsg(GetCtx(), "InternalUseNeedsCharge"));
                    return(false);
                }
            }
            else if (INVENTORYTYPE_ChargeAccount.Equals(GetInventoryType()))
            {
                if (GetC_Charge_ID() == 0)
                {
                    log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "C_Charge_ID"));
                    return(false);
                }
            }
            else if (GetC_Charge_ID() != 0)
            {
                SetC_Charge_ID(0);
            }

            //	Set AD_Org to parent if not charge
            if (GetC_Charge_ID() == 0)
            {
                SetAD_Org_ID(GetParent().GetAD_Org_ID());
            }

            // By Amit for Obsolete Inventory - 25-May-2016
            if (Env.IsModuleInstalled("VA024_"))
            {
                //MInventory inventory = new MInventory(GetCtx(), GetM_Inventory_ID(), Get_Trx());
                //shipment and Return to vendor
                if (inventory.IsInternalUse() || (!inventory.IsInternalUse() && (GetQtyBook() - GetQtyCount()) > 0))
                {
                    try
                    {
                        string qry1 = @"SELECT  SUM(o.VA024_UnitPrice)   FROM VA024_t_ObsoleteInventory o 
                                  WHERE o.IsActive = 'Y' AND  o.M_Product_ID = " + GetM_Product_ID() + @" and 
                                  ( o.M_AttributeSetInstance_ID = " + GetM_AttributeSetInstance_ID() + @" OR o.M_AttributeSetInstance_ID IS NULL )" +
                                      " AND o.AD_Org_ID = " + GetAD_Org_ID();
                        //+" AND M_Warehouse_ID = " + inventory.GetM_Warehouse_ID();
                        VA024_ProvisionPrice = Util.GetValueOfDecimal(DB.ExecuteScalar(qry1, null, Get_Trx()));
                        if (!inventory.IsInternalUse() && (GetQtyBook() - GetQtyCount()) > 0)
                        {
                            SetVA024_UnitPrice(Util.GetValueOfDecimal(VA024_ProvisionPrice * (GetQtyBook() - GetQtyCount())));
                        }
                        else
                        {
                            SetVA024_UnitPrice(Util.GetValueOfDecimal(VA024_ProvisionPrice * GetQtyInternalUse()));
                        }

                        if (!inventory.IsInternalUse() && (GetQtyBook() - GetQtyCount()) > 0)
                        {
                            qry1 = @"SELECT (ct.currentcostprice - " + VA024_ProvisionPrice + ") * " + (GetQtyBook() - GetQtyCount());
                        }
                        else
                        {
                            qry1 = @"SELECT (ct.currentcostprice - " + VA024_ProvisionPrice + ") * " + GetQtyInternalUse();
                        }
                        qry1 += @" FROM m_product p  INNER JOIN va024_t_obsoleteinventory oi ON p.m_product_id = oi.M_product_ID
                                 INNER JOIN m_product_category pc ON pc.m_product_category_ID = p.m_product_category_ID
                                 INNER JOIN AD_client c ON c.AD_Client_ID = p.Ad_Client_ID   INNER JOIN AD_ClientInfo ci  ON c.AD_Client_ID = ci.Ad_Client_ID
                                 INNER JOIN m_cost ct ON ( p.M_Product_ID     = ct.M_Product_ID  AND ci.C_AcctSchema1_ID = ct.C_AcctSchema_ID )
                                 INNER JOIN c_acctschema asch  ON (asch.C_AcctSchema_ID = ci.C_AcctSchema1_ID)
                                 INNER JOIN va024_obsoleteinvline oil ON oil.va024_obsoleteinvline_ID = oi.va024_obsoleteinvline_ID ";
                        qry1 += @"    WHERE ct.AD_Org_ID =  
                          CASE WHEN ( pc.costinglevel IS NOT NULL AND pc.costinglevel = 'O') THEN " + GetAD_Org_ID() + @" 
                               WHEN ( pc.costinglevel IS NOT NULL AND (pc.costinglevel  = 'C' OR pc.costinglevel = 'B')) THEN 0 
                               WHEN (pc.costinglevel IS NULL AND asch.costinglevel  = 'O') THEN " + GetAD_Org_ID() + @" 
                               WHEN ( pc.costinglevel IS NULL AND (asch.costinglevel  = 'C' OR asch.costinglevel   = 'B')) THEN 0  END
                          AND ct.m_costelement_id =  
                          CASE WHEN ( pc.costingmethod IS NOT NULL AND pc.costingmethod  != 'C') THEN  (SELECT MIN(m_costelement_id)  FROM m_costelement  
                                     WHERE m_costelement.costingmethod =pc.costingmethod  AND m_costelement.Ad_Client_ID  = oi.ad_client_id  ) 
                                WHEN ( pc.costingmethod IS NOT NULL AND pc.costingmethod = 'C' ) THEN  pc.m_costelement_id 
                                WHEN ( pc.costingmethod IS NULL AND asch.costingmethod  != 'C') THEN  (SELECT MIN(m_costelement_id)  FROM m_costelement 
                                     WHERE m_costelement.costingmethod = asch.costingmethod  AND m_costelement.Ad_Client_ID  = oi.ad_client_id  )
                                WHEN ( pc.costingmethod IS NULL AND asch.costingmethod  = 'C') THEN asch.m_costelement_id  END 
                         AND NVL(ct.M_Attributesetinstance_ID , 0) =  
                         CASE WHEN ( pc.costinglevel IS NOT NULL AND pc.costinglevel = 'B') THEN " + GetM_AttributeSetInstance_ID() + @" 
                              WHEN ( pc.costinglevel IS NOT NULL AND (pc.costinglevel  = 'C' OR pc.costinglevel = 'O')) THEN 0 
                              WHEN ( pc.costinglevel IS NULL AND asch.costinglevel  = 'B') THEN " + GetM_AttributeSetInstance_ID() + @"
                              WHEN ( pc.costinglevel IS NULL AND (asch.costinglevel  = 'C' OR asch.costinglevel   = 'O')) THEN 0  END 
                         AND p.M_Product_ID = " + GetM_Product_ID();
                        SetVA024_CostPrice(Util.GetValueOfDecimal(DB.ExecuteScalar(qry1, null, Get_Trx())));
                    }
                    catch { }
                }
            }

            return(true);
        }
        //	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());
        }
예제 #6
0
        /**
         *  Create Trial Asset
         *	@param ctx context
         *	@param user user
         *	@param entityType entity type
         *	@return asset or null if no product found
         */
        public static MAsset GetTrial(Ctx ctx, MUser user, String entityType)
        {
            if (user == null)
            {
                _log.Warning("Cannot create Trial - No User");
                return(null);
            }
            if (Utility.Util.IsEmpty(entityType))
            {
                _log.Warning("Cannot create Trial - No Entity Type");
                return(null);
            }
            MProduct product = MProduct.GetTrial(ctx, entityType);

            if (product == null)
            {
                _log.Warning("No Trial for Entity Type=" + entityType);
                return(null);
            }
            //
            DateTime now = Convert.ToDateTime(CommonFunctions.CurrentTimeMillis());
            //
            MAsset asset = new MAsset(ctx, 0, null);

            asset.SetClientOrg(user);
            asset.SetAssetServiceDate(now);
            asset.SetIsOwned(false);
            asset.SetIsTrialPhase(true);
            //
            MBPartner partner    = new MBPartner(ctx, user.GetC_BPartner_ID(), null);
            String    documentNo = "Trial";
            //	Value
            String value = partner.GetValue() + "_" + product.GetValue();

            if (value.Length > 40 - documentNo.Length)
            {
                value = value.Substring(0, 40 - documentNo.Length) + documentNo;
            }
            asset.SetValue(value);
            //	Name		MProduct.afterSave
            String name = "Trial " + partner.GetName() + " - " + product.GetName();

            if (name.Length > 60)
            {
                name = name.Substring(0, 60);
            }
            asset.SetName(name);
            //	Description
            String description = product.GetDescription();

            asset.SetDescription(description);

            //	User
            asset.SetAD_User_ID(user.GetAD_User_ID());
            asset.SetC_BPartner_ID(user.GetC_BPartner_ID());
            //	Product
            asset.SetM_Product_ID(product.GetM_Product_ID());
            asset.SetA_Asset_Group_ID(product.GetA_Asset_Group_ID());
            asset.SetQty(new Decimal(product.GetSupportUnits()));
            //	Guarantee & Version
            asset.SetGuaranteeDate(TimeUtil.AddDays(now, product.GetTrialPhaseDays()));
            asset.SetVersionNo(product.GetVersionNo());
            //
            return(asset);
        }
        /// <summary>
        /// Before Save
        /// </summary>
        /// <param name="newRecord">new</param>
        /// <returns>true</returns>
        protected override Boolean BeforeSave(Boolean newRecord)
        {
            Decimal  VA024_ProvisionPrice = 0;
            MProduct product = MProduct.Get(GetCtx(), GetM_Product_ID());

            // chck pallet Functionality applicable or not
            bool isContainrApplicable = MTransaction.ProductContainerApplicable(GetCtx());

            // Get Old Value of AttributeSetInstance_ID
            _mvlOldAttId = Util.GetValueOfInt(Get_ValueOld("M_AttributeSetInstance_ID"));

            //	Set Line No
            if (GetLine() == 0)
            {
                String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_MovementLine WHERE M_Movement_ID=" + GetM_Movement_ID();
                int    ii  = DataBase.DB.GetSQLValue(Get_TrxName(), sql);
                SetLine(ii);
            }

            // JID_0775: System is not checking on move line that the attribute set instance is mandatory.
            if (GetM_AttributeSetInstance_ID() == 0)
            {
                if (product != null && product.GetM_AttributeSet_ID() != 0)
                {
                    MAttributeSet mas = MAttributeSet.Get(GetCtx(), product.GetM_AttributeSet_ID());
                    if (mas.IsMandatory() || mas.IsMandatoryAlways())
                    {
                        log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "M_AttributeSetInstance_ID"));
                        return(false);
                    }
                }
            }

            // Check Locator For Header Warehouse
            MMovement mov = new MMovement(GetCtx(), GetM_Movement_ID(), Get_TrxName());
            MLocator  loc = new MLocator(GetCtx(), GetM_Locator_ID(), Get_TrxName());
            Tuple <string, string, string> aInfo = null;

            if (Env.HasModulePrefix("DTD001_", out aInfo))
            {
                if (mov.GetDTD001_MWarehouseSource_ID() == loc.GetM_Warehouse_ID())
                {
                }
                else
                {
                    String sql = "SELECT M_Locator_ID FROM M_Locator WHERE M_Warehouse_ID=" + mov.GetDTD001_MWarehouseSource_ID() + " AND IsDefault = 'Y'";
                    int    ii  = DataBase.DB.GetSQLValue(Get_TrxName(), sql);
                    SetM_Locator_ID(ii);
                }
            }

            // when we try to move product from container to container which are in same locator then no need to check this case
            if (GetM_Locator_ID() == GetM_LocatorTo_ID() &&
                (Get_ColumnIndex("M_ProductContainer_ID") > 0 && Get_ColumnIndex("Ref_M_ProductContainerTo_ID") > 0 &&
                 !(GetM_ProductContainer_ID() > 0 || GetRef_M_ProductContainerTo_ID() > 0)))
            {
                log.SaveError("Error", Msg.ParseTranslation(GetCtx(), "'From @M_Locator_ID@' and '@M_LocatorTo_ID@' cannot be same."));//change message according to requirement
                return(false);
            }

            if (Env.Signum(GetMovementQty()) == 0 && Util.GetValueOfInt(GetTargetQty()) == 0)
            {
                log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "MovementQty"));
                return(false);
            }

            Tuple <String, String, String> mInfo = null;

            if (Env.HasModulePrefix("DTD001_", out mInfo))
            {
                if (!newRecord && Util.GetValueOfInt(Get_ValueOld("M_Product_ID")) != GetM_Product_ID())
                {
                    log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_ProdNotChanged"));
                    return(false);
                }
                if (!newRecord && Util.GetValueOfInt(Get_ValueOld("M_Locator_ID")) != GetM_Locator_ID())
                {
                    log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_LocatorNotChanged"));
                    return(false);
                }
                if (!newRecord && Util.GetValueOfInt(Get_ValueOld("M_RequisitionLine_ID")) != GetM_RequisitionLine_ID())
                {
                    log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_ReqNotChanged"));
                    return(false);
                }
            }
            //if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA203_'", null, null)) > 0)
            if (Env.IsModuleInstalled("VA203_"))
            {
                if (GetM_RequisitionLine_ID() > 0)
                {
                    MRequisitionLine reqline = new MRequisitionLine(GetCtx(), GetM_RequisitionLine_ID(), Get_Trx());        // Trx used to handle query stuck problem
                    if (GetM_AttributeSetInstance_ID() != reqline.GetM_AttributeSetInstance_ID())
                    {
                        log.SaveError("Message", Msg.GetMsg(GetCtx(), "VA203_AttributeInstanceMustBeSame"));
                        return(false);
                    }
                }
            }
            // IF Doc Status = InProgress then No record Save
            MMovement move = new MMovement(GetCtx(), GetM_Movement_ID(), Get_Trx());        // Trx used to handle query stuck problem

            if (newRecord && move.GetDocStatus() == "IP")
            {
                log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_CannotCreate"));
                return(false);
            }

            //	Qty Precision
            if (newRecord || Is_ValueChanged("QtyEntered"))
            {
                SetQtyEntered(GetQtyEntered());
            }

            // change to set Converted Quantity in Movement quantity if there is differnce in UOM of Base Product and UOM Selected on line
            if (newRecord || Is_ValueChanged("QtyEntered") || Is_ValueChanged("C_UOM_ID"))
            {
                Decimal?qty = Util.GetValueOfDecimal(Get_Value("QtyEntered"));
                if (product.GetC_UOM_ID() != Util.GetValueOfInt(Get_Value("C_UOM_ID")))
                {
                    SetMovementQty(MUOMConversion.ConvertProductFrom(GetCtx(), GetM_Product_ID(), Util.GetValueOfInt(Get_Value("C_UOM_ID")), Util.GetValueOfDecimal(Get_Value("QtyEntered"))));
                }
            }

            //	Qty Precision
            if (newRecord || Is_ValueChanged("QtyEntered"))
            {
                SetMovementQty(GetMovementQty());
            }

            string qry;

            if (!mov.IsProcessing() || newRecord)
            {
                MWarehouse wh = null; MWarehouse whTo = null;
                wh   = MWarehouse.Get(GetCtx(), mov.GetDTD001_MWarehouseSource_ID());
                whTo = MWarehouse.Get(GetCtx(), MLocator.Get(GetCtx(), GetM_LocatorTo_ID()).GetM_Warehouse_ID());

                qry = "SELECT NVL(SUM(NVL(QtyOnHand,0)),0) AS QtyOnHand FROM M_Storage where m_locator_id=" + GetM_Locator_ID() + " and m_product_id=" + GetM_Product_ID();
                if (GetDTD001_AttributeNumber() == null || GetM_AttributeSetInstance_ID() > 0)
                {
                    qry += " AND NVL(M_AttributeSetInstance_ID , 0) =" + GetM_AttributeSetInstance_ID();
                }
                OnHandQty = Convert.ToDecimal(DB.ExecuteScalar(qry));

                qry         = "SELECT NVL(SUM(NVL(QtyOnHand,0)),0) AS QtyOnHand FROM M_Storage where m_locator_id=" + GetM_LocatorTo_ID() + " and m_product_id=" + GetM_Product_ID();
                qry        += " AND NVL(M_AttributeSetInstance_ID, 0) =" + GetM_AttributeSetInstance_ID();
                OnHandQtyTo = Convert.ToDecimal(DB.ExecuteScalar(qry));

                // SI_0635 : System is giving error of insufficient qty if disallow is true in TO warehouse and false in From warehouse
                // when record is in completed & closed stage - then no need to check qty availablity in warehouse
                if ((wh.IsDisallowNegativeInv() || whTo.IsDisallowNegativeInv()) &&
                    (!(move.GetDocStatus() == "CO" || move.GetDocStatus() == "CL" || move.GetDocStatus() == "RE" || move.GetDocStatus() == "VO")))
                {
                    // pick container current qty from transaction based on locator / product / ASI / Container / Movement Date
                    if (isContainrApplicable && Get_ColumnIndex("M_ProductContainer_ID") >= 0)
                    {
                        //                    qry = @"SELECT SUM(t.ContainerCurrentQty) keep (dense_rank last ORDER BY t.MovementDate, t.M_Transaction_ID) AS CurrentQty FROM m_transaction t
                        //                            INNER JOIN M_Locator l ON t.M_Locator_ID = l.M_Locator_ID WHERE t.MovementDate <= " + GlobalVariable.TO_DATE(move.GetMovementDate(), true) +
                        //                                " AND t.AD_Client_ID = " + GetAD_Client_ID() +
                        //                                @" AND t.M_Locator_ID = " + (move.IsReversal() && GetMovementQty() < 0 ? GetM_LocatorTo_ID() : GetM_Locator_ID()) +
                        //                                " AND t.M_Product_ID = " + GetM_Product_ID() + " AND NVL(t.M_AttributeSetInstance_ID,0) = " + GetM_AttributeSetInstance_ID() +
                        //                                " AND NVL(t.M_ProductContainer_ID, 0) = " + (move.IsReversal() && !IsMoveFullContainer() && GetMovementQty() < 0 ? GetRef_M_ProductContainerTo_ID() : GetM_ProductContainer_ID());
                        //                    containerQty = Util.GetValueOfDecimal(DB.ExecuteScalar(qry.ToString(), null, null));  // dont use Transaction here - otherwise impact goes wrong on completion

                        //                    qry = @"SELECT SUM(t.ContainerCurrentQty) keep (dense_rank last ORDER BY t.MovementDate, t.M_Transaction_ID) AS CurrentQty FROM m_transaction t
                        //                            INNER JOIN M_Locator l ON t.M_Locator_ID = l.M_Locator_ID WHERE t.MovementDate <= " + GlobalVariable.TO_DATE(move.GetMovementDate(), true) +
                        //                               " AND t.AD_Client_ID = " + GetAD_Client_ID() +
                        //                               @" AND t.M_Locator_ID = " + (move.IsReversal() && GetMovementQty() < 0 ? GetM_Locator_ID() : GetM_LocatorTo_ID()) +
                        //                               " AND t.M_Product_ID = " + GetM_Product_ID() + " AND NVL(t.M_AttributeSetInstance_ID,0) = " + GetM_AttributeSetInstance_ID() +
                        //                               " AND NVL(t.M_ProductContainer_ID, 0) = " + (move.IsReversal() && !IsMoveFullContainer() && GetMovementQty() < 0 ? GetM_ProductContainer_ID() : GetRef_M_ProductContainerTo_ID());
                        //                    containerQtyTo = Util.GetValueOfDecimal(DB.ExecuteScalar(qry.ToString(), null, null));  // dont use Transaction here - otherwise impact goes wrong on completion

                        qry = @"SELECT DISTINCT First_VALUE(t.ContainerCurrentQty) OVER (PARTITION BY t.M_Product_ID, t.M_AttributeSetInstance_ID ORDER BY t.MovementDate DESC, t.M_Transaction_ID DESC) AS CurrentQty FROM m_transaction t 
                                                INNER JOIN M_Locator l ON t.M_Locator_ID = l.M_Locator_ID WHERE t.MovementDate <= " + GlobalVariable.TO_DATE(move.GetMovementDate(), true) +
                              " AND t.AD_Client_ID = " + GetAD_Client_ID() +
                              @" AND t.M_Locator_ID = " + GetM_Locator_ID() +
                              " AND t.M_Product_ID = " + GetM_Product_ID() + " AND NVL(t.M_ProductContainer_ID, 0) = " + GetM_ProductContainer_ID();

                        // In Case of Attribute Number do not check qty with attribute from storage
                        if (GetDTD001_AttributeNumber() == null || GetM_AttributeSetInstance_ID() > 0)
                        {
                            qry += " AND NVL(M_AttributeSetInstance_ID , 0) =" + GetM_AttributeSetInstance_ID();
                        }

                        containerQty = Util.GetValueOfDecimal(DB.ExecuteScalar(qry.ToString(), null, null));  // dont use Transaction here - otherwise impact goes wrong on completion

                        qry = @"SELECT DISTINCT First_VALUE(t.ContainerCurrentQty) OVER (PARTITION BY t.M_Product_ID, t.M_AttributeSetInstance_ID ORDER BY t.MovementDate DESC, t.M_Transaction_ID DESC)  AS CurrentQty FROM m_transaction t 
                                                INNER JOIN M_Locator l ON t.M_Locator_ID = l.M_Locator_ID WHERE t.MovementDate <= " + GlobalVariable.TO_DATE(move.GetMovementDate(), true) +
                              " AND t.AD_Client_ID = " + GetAD_Client_ID() +
                              @" AND t.M_Locator_ID = " + GetM_LocatorTo_ID() +
                              " AND t.M_Product_ID = " + GetM_Product_ID() + " AND NVL(t.M_AttributeSetInstance_ID,0) = " + GetM_AttributeSetInstance_ID() +
                              " AND NVL(t.M_ProductContainer_ID, 0) = " + GetRef_M_ProductContainerTo_ID();
                        containerQtyTo = Util.GetValueOfDecimal(DB.ExecuteScalar(qry.ToString(), null, null));  // dont use Transaction here - otherwise impact goes wrong on completion
                    }

                    if (wh.IsDisallowNegativeInv() && (OnHandQty - GetMovementQty()) < 0)
                    {
                        // check for From Locator
                        log.SaveError("Info", product.GetName() + " , " + Msg.GetMsg(GetCtx(), "VIS_InsufficientQty") + OnHandQty);
                        return(false);
                    }
                    else if (isContainrApplicable && wh.IsDisallowNegativeInv() && Get_ColumnIndex("M_ProductContainer_ID") >= 0 && (containerQty - GetMovementQty()) < 0)
                    {
                        // check container qty -  for From Locator
                        log.SaveError("Info", product.GetName() + " , " + Msg.GetMsg(GetCtx(), "VIS_InsufficientQtyContainer") + containerQty);
                        return(false);
                    }
                    else if (whTo.IsDisallowNegativeInv() && (OnHandQtyTo + GetMovementQty()) < 0)
                    {
                        // check for To Locator
                        log.SaveError("Info", product.GetName() + " , " + Msg.GetMsg(GetCtx(), "VIS_InsufficientQty") + OnHandQtyTo);
                        return(false);
                    }
                    else if (isContainrApplicable && whTo.IsDisallowNegativeInv() && Get_ColumnIndex("M_ProductContainer_ID") >= 0 && (containerQtyTo + GetMovementQty()) < 0)
                    {
                        // check for To Locator
                        log.SaveError("Info", product.GetName() + " , " + Msg.GetMsg(GetCtx(), "VIS_InsufficientQtyContainerTo") + containerQtyTo);
                        return(false);
                    }
                }
            }

            if (Env.IsModuleInstalled("DTD001_"))
            {
                // not used this variable, that why commented
                //qry = "SELECT   NVL(SUM(NVL(QtyOnHand,0)- qtyreserved),0) AS QtyAvailable  FROM M_Storage where m_locator_id=" + GetM_Locator_ID() + " and m_product_id=" + GetM_Product_ID();
                //if (GetM_AttributeSetInstance_ID() != 0)
                //{
                //    qry += " AND NVL(M_AttributeSetInstance_ID , 0) = " + GetM_AttributeSetInstance_ID();
                //}
                //qtyAvailable = Convert.ToDecimal(DB.ExecuteScalar(qry));
                qtyReserved = Util.GetValueOfDecimal(Get_ValueOld("MovementQty"));
                //if (wh.IsDisallowNegativeInv() == true)
                //{
                //    if ((qtyAvailable < (GetMovementQty() - qtyReserved)))
                //    {
                //        log.SaveError("Message", product.GetName() + " , " + Msg.GetMsg(GetCtx(), "DTD001_QtyNotAvailable"));
                //        return false;
                //    }
                //}
            }

            //By Amit - 17-April-2017
            if (Env.IsModuleInstalled("VA024_"))
            {
                // checking are we moving product from one warehouse to other warehouse
                if (Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT CASE WHEN ((SELECT CASE WHEN o.IsLegalEntity = 'Y' THEN w.AD_Org_ID
                 ELSE (SELECT AD_Org_ID FROM AD_Org WHERE Ad_Org_id = o.LegalEntityOrg ) END
                 FROM m_warehouse w INNER JOIN ad_org o ON o.AD_Org_ID = w.AD_Org_ID WHERE w.m_warehouse_id = m.DTD001_MWarehouseSource_ID)) =
                 (SELECT  CASE WHEN o2.IsLegalEntity = 'Y' THEN w2.AD_Org_ID 
                 ELSE (SELECT AD_Org_ID FROM AD_Org WHERE Ad_Org_id = o2.LegalEntityOrg) END
                 FROM m_warehouse w2 INNER JOIN ad_org o2 ON o2.AD_Org_ID = w2.AD_Org_ID WHERE M_Warehouse_ID = m.M_Warehouse_ID )
                 THEN 0 ELSE (SELECT ad_org_id FROM m_warehouse WHERE M_Warehouse_ID = m.M_Warehouse_ID ) END AS result FROM m_movement m WHERE m_movement_id = " + GetM_Movement_ID(), null, Get_Trx())) > 0)
                {
                    string qry1 = @"SELECT  SUM(o.VA024_UnitPrice)   FROM VA024_t_ObsoleteInventory o 
                                  WHERE o.IsActive = 'Y' AND  o.M_Product_ID = " + GetM_Product_ID() + @" and 
                                  ( o.M_AttributeSetInstance_ID = " + GetM_AttributeSetInstance_ID() + @" OR o.M_AttributeSetInstance_ID IS NULL )" +
                                  " AND o.AD_Org_ID = " + GetAD_Org_ID();
                    VA024_ProvisionPrice = Util.GetValueOfDecimal(DB.ExecuteScalar(qry1, null, Get_Trx()));
                    SetVA024_UnitPrice(Util.GetValueOfDecimal(VA024_ProvisionPrice * GetMovementQty()));

                    // is used to get cost of binded cost method / costing level of primary accounting schema
                    Decimal cost = MCost.GetproductCosts(move.GetAD_Client_ID(), move.GetAD_Org_ID(), GetM_Product_ID(),
                                                         GetM_AttributeSetInstance_ID(), Get_Trx(), move.GetDTD001_MWarehouseSource_ID());
                    SetVA024_CostPrice((cost - VA024_ProvisionPrice) * GetMovementQty());
                }
            }

            //	Mandatory Instance
            if (GetM_AttributeSetInstanceTo_ID() == 0)
            {
                if (GetM_AttributeSetInstance_ID() != 0)        //	Set to from
                {
                    SetM_AttributeSetInstanceTo_ID(GetM_AttributeSetInstance_ID());
                }
                else
                {
                    if (Env.HasModulePrefix("DTD001_", out mInfo))
                    {
                        //MProduct product = GetProduct();
                        if (product != null &&
                            product.GetM_AttributeSet_ID() != 0)
                        {
                            //MAttributeSet mas = MAttributeSet.Get(GetCtx(), product.GetM_AttributeSet_ID());
                            //if (mas.IsInstanceAttribute()
                            //    && (mas.IsMandatory() || mas.IsMandatoryAlways()))
                            //{
                            //    log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "M_AttributeSetInstanceTo_ID"));
                            //    return false;
                            //}

                            // Code Addeded by Bharat as Discussed with Mukesh Sir
                            if (String.IsNullOrEmpty(GetDTD001_AttributeNumber()))
                            {
                                return(true);
                            }
                            else
                            {
                                if (GetDTD001_AttributeNumber() == "" || GetDTD001_AttributeNumber() == null)
                                {
                                    log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "DTD001_AttributeNumber"));

                                    return(false);
                                }
                            }

                            //JID_1422: Check No Of Attributes Are Equal To Quantity Or Less Than

                            int Count = CountAttributes(GetDTD001_AttributeNumber());
                            if (Count != GetQtyEntered())
                            {
                                if (Count > GetQtyEntered())
                                {
                                    log.SaveError("DTD001_MovementAttrbtGreater", "");
                                    return(false);
                                }
                                else
                                {
                                    log.SaveError("DTD001_MovementAttrbtLess", "");
                                    return(false);
                                }
                            }
                        }
                        else
                        {
                            if (product != null)
                            {
                                if (product.GetM_AttributeSet_ID() == 0 && (GetDTD001_AttributeNumber() == "" || GetDTD001_AttributeNumber() == null))
                                {
                                    return(true);
                                }
                                else
                                {
                                    //log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "DTD001_AttributeNumber"));
                                    //ShowMessage.Info("a", true, "Product is not of Attribute Type", null);
                                    log.SaveError("Product is not of Attribute Type", Msg.GetElement(GetCtx(), "DTD001_AttributeNumber"));
                                    return(false);
                                }

                                //Check No Of Attributes Are Equal To Quantity Or Less Than

                                //int Count = CountAttributes(GetDTD001_AttributeNumber());
                                //if (Count != GetMovementQty())
                                //{
                                //    if (Count > GetMovementQty())
                                //    {
                                //        log.SaveError("Error", Msg.GetMsg(GetCtx(), "DTD001_MovementAttrbtGreater"));
                                //        return false;
                                //    }
                                //    else
                                //    {
                                //        log.SaveError("Error", Msg.GetMsg(GetCtx(), "DTD001_MovementAttrbtLess"));
                                //        return false;
                                //    }
                                //}
                            }
                        }
                    }
                    else
                    {
                        //MProduct product = GetProduct();
                        if (product != null &&
                            product.GetM_AttributeSet_ID() != 0)
                        {
                            MAttributeSet mas = MAttributeSet.Get(GetCtx(), product.GetM_AttributeSet_ID());
                            if (mas.IsInstanceAttribute() &&
                                (mas.IsMandatory() || mas.IsMandatoryAlways()))
                            {
                                log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "M_AttributeSetInstanceTo_ID"));
                                return(false);
                            }
                        }
                    }
                }
            }    //	ASI
            return(true);
        }
예제 #8
0
        /// <summary>
        /// Before Save
        /// </summary>
        /// <param name="newRecord">new</param>
        /// <returns>true</returns>
        protected override Boolean BeforeSave(Boolean newRecord)
        {
            Decimal  VA024_ProvisionPrice = 0;
            MProduct product = MProduct.Get(GetCtx(), GetM_Product_ID());

            // By vikas
            // Get Old Value of AttributeSetInstance_ID
            _mvlOldAttId = Util.GetValueOfInt(Get_ValueOld("M_AttributeSetInstance_ID"));

            //	Set Line No
            if (GetLine() == 0)
            {
                String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_MovementLine WHERE M_Movement_ID=" + GetM_Movement_ID();
                int    ii  = DataBase.DB.GetSQLValue(Get_TrxName(), sql);
                SetLine(ii);
            }

            // Check Locator For Header Warehouse
            MMovement mov = new MMovement(GetCtx(), GetM_Movement_ID(), Get_TrxName());
            MLocator  loc = new MLocator(GetCtx(), GetM_Locator_ID(), Get_TrxName());
            Tuple <string, string, string> aInfo = null;

            if (Env.HasModulePrefix("DTD001_", out aInfo))
            {
                if (mov.GetDTD001_MWarehouseSource_ID() == loc.GetM_Warehouse_ID())
                {
                }
                else
                {
                    String sql = "SELECT M_Locator_ID FROM M_Locator WHERE M_Warehouse_ID=" + mov.GetDTD001_MWarehouseSource_ID() + " AND IsDefault = 'Y'";
                    int    ii  = DataBase.DB.GetSQLValue(Get_TrxName(), sql);
                    SetM_Locator_ID(ii);
                }
            }

            if (GetM_Locator_ID() == GetM_LocatorTo_ID())
            {
                log.SaveError("Error", Msg.ParseTranslation(GetCtx(), "'From @M_Locator_ID@' and '@M_LocatorTo_ID@' cannot be same."));//change message according to requirement
                return(false);
            }

            if (Env.Signum(GetMovementQty()) == 0 && Util.GetValueOfInt(GetTargetQty()) == 0)
            {
                log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "MovementQty"));
                return(false);
            }
            //Amit
            Tuple <String, String, String> mInfo = null;

            if (Env.HasModulePrefix("DTD001_", out mInfo))
            {
                if (!newRecord && Util.GetValueOfInt(Get_ValueOld("M_Product_ID")) != GetM_Product_ID())
                {
                    log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_ProdNotChanged"));
                    return(false);
                }
                if (!newRecord && Util.GetValueOfInt(Get_ValueOld("M_Locator_ID")) != GetM_Locator_ID())
                {
                    log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_LocatorNotChanged"));
                    return(false);
                }
                if (!newRecord && Util.GetValueOfInt(Get_ValueOld("M_RequisitionLine_ID")) != GetM_RequisitionLine_ID())
                {
                    log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_ReqNotChanged"));
                    return(false);
                }
            }
            //if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA203_'", null, null)) > 0)
            if (Env.IsModuleInstalled("VA203_"))
            {
                if (GetM_RequisitionLine_ID() > 0)
                {
                    MRequisitionLine reqline = new MRequisitionLine(GetCtx(), GetM_RequisitionLine_ID(), Get_Trx());        // Trx used to handle query stuck problem
                    if (GetM_AttributeSetInstance_ID() != reqline.GetM_AttributeSetInstance_ID())
                    {
                        log.SaveError("Message", Msg.GetMsg(GetCtx(), "VA203_AttributeInstanceMustBeSame"));
                        return(false);
                    }
                }
            }
            // IF Doc Status = InProgress then No record Save
            MMovement move = new MMovement(GetCtx(), GetM_Movement_ID(), Get_Trx());        // Trx used to handle query stuck problem

            if (newRecord && move.GetDocStatus() == "IP")
            {
                log.SaveError("Message", Msg.GetMsg(GetCtx(), "DTD001_CannotCreate"));
                return(false);
            }

            // change to set Converted Quantity in Movement quantity if there is differnce in UOM of Base Product and UOM Selected on line
            if (newRecord || Is_ValueChanged("QtyEntered") || Is_ValueChanged("C_UOM_ID"))
            {
                Decimal?qty = Util.GetValueOfDecimal(Get_Value("QtyEntered"));
                if (product.GetC_UOM_ID() != Util.GetValueOfInt(Get_Value("C_UOM_ID")))
                {
                    SetMovementQty(MUOMConversion.ConvertProductFrom(GetCtx(), GetM_Product_ID(), Util.GetValueOfInt(Get_Value("C_UOM_ID")), Util.GetValueOfDecimal(Get_Value("QtyEntered"))));
                }
            }

            //	Qty Precision
            if (newRecord || Is_ValueChanged("QtyEntered"))
            {
                SetMovementQty(GetMovementQty());
            }
            MWarehouse wh = null; MWarehouse whTo = null;

            //string qry = "select m_warehouse_id from m_locator where m_locator_id=" + GetM_Locator_ID();
            //M_Warehouse_ID = Util.GetValueOfInt(DB.ExecuteScalar(qry));

            wh   = MWarehouse.Get(GetCtx(), mov.GetDTD001_MWarehouseSource_ID());
            whTo = MWarehouse.Get(GetCtx(), mov.GetM_Warehouse_ID());

            string qry = "SELECT NVL(SUM(NVL(QtyOnHand,0)),0) AS QtyOnHand FROM M_Storage where m_locator_id=" + GetM_Locator_ID() + " and m_product_id=" + GetM_Product_ID();

            if (GetM_AttributeSetInstance_ID() != 0)
            {
                qry += " AND M_AttributeSetInstance_ID=" + GetM_AttributeSetInstance_ID();
            }
            OnHandQty = Convert.ToDecimal(DB.ExecuteScalar(qry));

            qry = "SELECT NVL(SUM(NVL(QtyOnHand,0)),0) AS QtyOnHand FROM M_Storage where m_locator_id=" + GetM_LocatorTo_ID() + " and m_product_id=" + GetM_Product_ID();
            if (GetM_AttributeSetInstance_ID() != 0)
            {
                qry += " AND M_AttributeSetInstance_ID=" + GetM_AttributeSetInstance_ID();
            }
            OnHandQtyTo = Convert.ToDecimal(DB.ExecuteScalar(qry));

            // SI_0635 : System is giving error of insufficient qty if disallow is true in TO warehouse and false in From warehouse
            // when record is in completed & closed stage - then no need to check qty availablity in warehouse
            if ((wh.IsDisallowNegativeInv() || whTo.IsDisallowNegativeInv()) &&
                (!(move.GetDocStatus() == "CO" || move.GetDocStatus() == "CL" || move.GetDocStatus() == "RE" || move.GetDocStatus() == "VO")))
            {
                if (wh.IsDisallowNegativeInv() && (OnHandQty - GetMovementQty()) < 0)
                {
                    // check for From Locator
                    log.SaveError("Info", product.GetName() + " , " + Msg.GetMsg(GetCtx(), "VIS_InsufficientQty") + OnHandQty);
                    return(false);
                }
                else if (whTo.IsDisallowNegativeInv() && (OnHandQtyTo + GetMovementQty()) < 0)
                {
                    // check for To Locator
                    log.SaveError("Info", product.GetName() + " , " + Msg.GetMsg(GetCtx(), "VIS_InsufficientQty") + OnHandQtyTo);
                    return(false);
                }
            }
            if (Env.HasModulePrefix("DTD001_", out mInfo))
            {
                qry = "SELECT   NVL(SUM(NVL(QtyOnHand,0)- qtyreserved),0) AS QtyAvailable  FROM M_Storage where m_locator_id=" + GetM_Locator_ID() + " and m_product_id=" + GetM_Product_ID();
                if (GetM_AttributeSetInstance_ID() != 0)
                {
                    qry += " AND M_AttributeSetInstance_ID=" + GetM_AttributeSetInstance_ID();
                }
                qtyAvailable = Convert.ToDecimal(DB.ExecuteScalar(qry));
                qtyReserved  = Util.GetValueOfDecimal(Get_ValueOld("MovementQty"));
                //if (wh.IsDisallowNegativeInv() == true)
                //{
                //    if ((qtyAvailable < (GetMovementQty() - qtyReserved)))
                //    {
                //        log.SaveError("Message", product.GetName() + " , " + Msg.GetMsg(GetCtx(), "DTD001_QtyNotAvailable"));
                //        return false;
                //    }
                //}
            }

            //By Amit - 17-April-2017
            if (Env.IsModuleInstalled("VA024_"))
            {
                // checking are we moving product from one warehouse to other warehouse
                if (Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT CASE WHEN ((SELECT CASE WHEN o.IsLegalEntity = 'Y' THEN w.AD_Org_ID
                 ELSE (SELECT AD_Org_ID FROM AD_Org WHERE Ad_Org_id = o.LegalEntityOrg ) END
                 FROM m_warehouse w INNER JOIN ad_org o ON o.AD_Org_ID = w.AD_Org_ID WHERE w.m_warehouse_id = m.DTD001_MWarehouseSource_ID)) =
                 (SELECT  CASE WHEN o2.IsLegalEntity = 'Y' THEN w2.AD_Org_ID 
                 ELSE (SELECT AD_Org_ID FROM AD_Org WHERE Ad_Org_id = o2.LegalEntityOrg) END
                 FROM m_warehouse w2 INNER JOIN ad_org o2 ON o2.AD_Org_ID = w2.AD_Org_ID WHERE M_Warehouse_ID = m.M_Warehouse_ID )
                 THEN 0 ELSE (SELECT ad_org_id FROM m_warehouse WHERE M_Warehouse_ID = m.M_Warehouse_ID ) END AS result FROM m_movement m WHERE m_movement_id = " + GetM_Movement_ID(), null, Get_Trx())) > 0)
                {
                    MMovement inventory = new MMovement(GetCtx(), GetM_Movement_ID(), Get_Trx());
                    try
                    {
                        string qry1 = @"SELECT  SUM(o.VA024_UnitPrice)   FROM VA024_t_ObsoleteInventory o 
                                  WHERE o.IsActive = 'Y' AND  o.M_Product_ID = " + GetM_Product_ID() + @" and 
                                  ( o.M_AttributeSetInstance_ID = " + GetM_AttributeSetInstance_ID() + @" OR o.M_AttributeSetInstance_ID IS NULL )" +
                                      " AND o.AD_Org_ID = " + GetAD_Org_ID();
                        VA024_ProvisionPrice = Util.GetValueOfDecimal(DB.ExecuteScalar(qry1, null, Get_Trx()));
                        SetVA024_UnitPrice(Util.GetValueOfDecimal(VA024_ProvisionPrice * GetMovementQty()));

                        qry1  = @"SELECT (ct.currentcostprice - " + VA024_ProvisionPrice + ") * " + GetMovementQty();
                        qry1 += @" FROM m_product p  INNER JOIN va024_t_obsoleteinventory oi ON p.m_product_id = oi.M_product_ID
                                 INNER JOIN m_product_category pc ON pc.m_product_category_ID = p.m_product_category_ID
                                 INNER JOIN AD_client c ON c.AD_Client_ID = p.Ad_Client_ID   INNER JOIN AD_ClientInfo ci  ON c.AD_Client_ID = ci.Ad_Client_ID
                                 INNER JOIN m_cost ct ON ( p.M_Product_ID     = ct.M_Product_ID  AND ci.C_AcctSchema1_ID = ct.C_AcctSchema_ID )
                                 INNER JOIN c_acctschema asch  ON (asch.C_AcctSchema_ID = ci.C_AcctSchema1_ID)
                                 INNER JOIN va024_obsoleteinvline oil ON oil.va024_obsoleteinvline_ID = oi.va024_obsoleteinvline_ID ";
                        qry1 += @"    WHERE ct.AD_Org_ID =  
                          CASE WHEN ( pc.costinglevel IS NOT NULL AND pc.costinglevel = 'O') THEN " + GetAD_Org_ID() + @" 
                               WHEN ( pc.costinglevel IS NOT NULL AND (pc.costinglevel  = 'C' OR pc.costinglevel = 'B')) THEN 0 
                               WHEN (pc.costinglevel IS NULL AND asch.costinglevel  = 'O') THEN " + GetAD_Org_ID() + @" 
                               WHEN ( pc.costinglevel IS NULL AND (asch.costinglevel  = 'C' OR asch.costinglevel   = 'B')) THEN 0  END
                          AND ct.m_costelement_id =  
                          CASE WHEN ( pc.costingmethod IS NOT NULL AND pc.costingmethod  != 'C') THEN  (SELECT MIN(m_costelement_id)  FROM m_costelement  
                                     WHERE m_costelement.costingmethod =pc.costingmethod  AND m_costelement.Ad_Client_ID  = oi.ad_client_id  ) 
                                WHEN ( pc.costingmethod IS NOT NULL AND pc.costingmethod = 'C' ) THEN  pc.m_costelement_id 
                                WHEN ( pc.costingmethod IS NULL AND asch.costingmethod  != 'C') THEN  (SELECT MIN(m_costelement_id)  FROM m_costelement 
                                     WHERE m_costelement.costingmethod = asch.costingmethod  AND m_costelement.Ad_Client_ID  = oi.ad_client_id  )
                                WHEN ( pc.costingmethod IS NULL AND asch.costingmethod  = 'C') THEN asch.m_costelement_id  END 
                         AND NVL(ct.M_Attributesetinstance_ID , 0) =  
                         CASE WHEN ( pc.costinglevel IS NOT NULL AND pc.costinglevel = 'B') THEN " + GetM_AttributeSetInstance_ID() + @" 
                              WHEN ( pc.costinglevel IS NOT NULL AND (pc.costinglevel  = 'C' OR pc.costinglevel = 'O')) THEN 0 
                              WHEN ( pc.costinglevel IS NULL AND asch.costinglevel  = 'B') THEN " + GetM_AttributeSetInstance_ID() + @"
                              WHEN ( pc.costinglevel IS NULL AND (asch.costinglevel  = 'C' OR asch.costinglevel   = 'O')) THEN 0  END 
                         AND p.M_Product_ID = " + GetM_Product_ID();
                        SetVA024_CostPrice(Util.GetValueOfDecimal(DB.ExecuteScalar(qry1, null, Get_Trx())));
                    }
                    catch { }
                }
            }

            //	Mandatory Instance
            if (GetM_AttributeSetInstanceTo_ID() == 0)
            {
                if (GetM_AttributeSetInstance_ID() != 0)        //	Set to from
                {
                    SetM_AttributeSetInstanceTo_ID(GetM_AttributeSetInstance_ID());
                }
                else
                {
                    if (Env.HasModulePrefix("DTD001_", out mInfo))
                    {
                        //MProduct product = GetProduct();
                        if (product != null &&
                            product.GetM_AttributeSet_ID() != 0)
                        {
                            //MAttributeSet mas = MAttributeSet.Get(GetCtx(), product.GetM_AttributeSet_ID());
                            //if (mas.IsInstanceAttribute()
                            //    && (mas.IsMandatory() || mas.IsMandatoryAlways()))
                            //{
                            //    log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "M_AttributeSetInstanceTo_ID"));
                            //    return false;
                            //}

                            // Code Addeded by Bharat as Discussed with Mukesh Sir
                            if (String.IsNullOrEmpty(GetDTD001_AttributeNumber()))
                            {
                                return(true);
                            }
                            else
                            {
                                if (GetDTD001_AttributeNumber() == "" || GetDTD001_AttributeNumber() == null)
                                {
                                    log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "DTD001_AttributeNumber"));

                                    return(false);
                                }
                            }
                        }
                        else
                        {
                            if (product != null)
                            {
                                if (product.GetM_AttributeSet_ID() == 0 && (GetDTD001_AttributeNumber() == "" || GetDTD001_AttributeNumber() == null))
                                {
                                    return(true);
                                }
                                else
                                {
                                    //log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "DTD001_AttributeNumber"));
                                    //ShowMessage.Info("a", true, "Product is not of Attribute Type", null);
                                    log.SaveError("Product is not of Attribute Type", Msg.GetElement(GetCtx(), "DTD001_AttributeNumber"));
                                    return(false);
                                }

                                //Check No Of Attributes Are Equal To Quantity Or Less Than

                                int Count = CountAttributes(GetDTD001_AttributeNumber());
                                if (Count != GetMovementQty())
                                {
                                    if (Count > GetMovementQty())
                                    {
                                        log.SaveError("Error", Msg.GetMsg(GetCtx(), "DTD001_MovementAttrbtGreater"));
                                        return(false);
                                    }
                                    else
                                    {
                                        log.SaveError("Error", Msg.GetMsg(GetCtx(), "DTD001_MovementAttrbtLess"));
                                        return(false);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        //MProduct product = GetProduct();
                        if (product != null &&
                            product.GetM_AttributeSet_ID() != 0)
                        {
                            MAttributeSet mas = MAttributeSet.Get(GetCtx(), product.GetM_AttributeSet_ID());
                            if (mas.IsInstanceAttribute() &&
                                (mas.IsMandatory() || mas.IsMandatoryAlways()))
                            {
                                log.SaveError("FillMandatory", Msg.GetElement(GetCtx(), "M_AttributeSetInstanceTo_ID"));
                                return(false);
                            }
                        }
                    }
                }
            }   //	ASI
            return(true);
        }