/// <summary>
        /// Loads the pick list from the pick face location
        /// this is only called if a pick face location is set for the item
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <param name="unitID">The unit ID.</param>
        /// <param name="innitallyApprovedQuantity">The innitally approved quantity.</param>
        /// <param name="fromstore">The fromstore.</param>
        /// <param name="isDeliveryNote">if set to <c>true</c> [is delivery note].</param>
        private void LoadFromPickFace(int itemId, int? unitID, decimal innitallyApprovedQuantity, int fromstore, bool isDeliveryNote)
        {
            decimal approvedQuantity = innitallyApprovedQuantity;
            var pf = new PickFace();
            pf.LoadPickFaceFor(itemId, fromstore);
            if (pf.RowCount > 0)
            {
                var rp = new ReceivePallet();
                rp.LoadPickFaceAllItemsReadyToDispatch(itemId, unitID, fromstore);
                var im = new ItemManufacturer();
                var imff = new ItemManufacturer();
                if (pf.IsColumnNull("Balance"))
                {
                    pf.Balance = 0;
                    pf.Save();
                }
                if (pf.Balance >= approvedQuantity)
                {
                    while (!rp.EOF)
                    {
                        int manufId = Convert.ToInt32(rp.GetColumn("ManufacturerID"));
                        im.LoadIMbyLevel(itemId, manufId, Convert.ToInt32(rp.GetColumn("BoxLevel")));
                        int boxLevel = im.PackageLevel;
                        int buinsku = Convert.ToInt32(rp.GetColumn("QtyPerPack"));//imff.LoadSKUUnit(itemId, manufId);
                        while (boxLevel >= 0 && approvedQuantity > 0)
                        {
                            long dispatchQuantity = Convert.ToInt32(rp.GetColumn("DispatchableStock"));
                            int bUsinBoxLevel = im.QuantityInBasicUnit;
                            decimal dispatch = (approvedQuantity / bUsinBoxLevel) * bUsinBoxLevel;
                            if (dispatch > dispatchQuantity)
                            {
                                dispatch = dispatchQuantity;
                            }
                            while (dispatch / bUsinBoxLevel < 1 && im.PackageLevel > 0)
                            {
                                im.LoadIMbyLevel(im.ItemID, im.ManufacturerID, im.PackageLevel - 1);
                                bUsinBoxLevel = im.QuantityInBasicUnit;
                            }
                            if (dispatch > 0)
                            {
                                _pickList.ImportRow(rp.CurrentDataRow);
                                // pick the currently inserted entry and adjust all the numbers in it.
                                DataRow dr = _pickList.Rows[_pickList.Rows.Count - 1];

                                // only Adjust the entries that matter to the pick list
                                SetPriceAndQuantity(dr, dispatch, buinsku, rp, itemId, isDeliveryNote);
                                approvedQuantity -= dispatch;
                            }
                            boxLevel--;
                            im.LoadIMbyLevel(itemId, manufId, boxLevel);
                        }
                        rp.MoveNext();
                    }
                }
            }
        }
        private void OnReplenishClicked(object sender, EventArgs e)
        {
            PalletLocation pl = new PalletLocation();
            PickFace pf = new PickFace();
            DataRow dr = gridPickFaceStockLevelView.GetFocusedDataRow();
            DataRow dr2 = gridReplenishmentChoiceView.GetFocusedDataRow();
            if (dr2 != null)
            {
                // check if the replenishment is from allowed location.
                //
                if (!Convert.ToBoolean(dr2["CanReplenish"]))
                {
                    XtraMessageBox.Show("Please choose replenishment from the first to expire items", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                pl.LoadByPrimaryKey(_palletLocationID);
                pf.LoadByPrimaryKey(_pickFaceID);
                if (pf.IsColumnNull("Balance"))
                {
                    pf.Balance = 0;
                }

                if (pl.IsColumnNull("PalletID"))
                {
                    Pallet pallet = new Pallet();
                    pallet.AddNew();
                    pallet.StorageTypeID = Convert.ToInt32(StorageType.PickFace);
                    pallet.Save();
                    pl.PalletID = pallet.ID;
                    pl.Save();
                }

                ReceivePallet rp = new ReceivePallet();
                ReceivePallet rp2 = new ReceivePallet();
                ReceiveDoc rd = new ReceiveDoc();
                rp.LoadByPrimaryKey(Convert.ToInt32(dr2["ReceivePalletID"]));
                rp2.AddNew();
                rp2.IsOriginalReceive = false;
                rp2.PalletID = pl.PalletID;
                rp2.ReceiveID = rp.ReceiveID;
                rp2.BoxSize = rp.BoxSize;

                // calculate the new balance
                BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                im.LoadIMbyLevel(_designatedItemID, Convert.ToInt32(dr2["ManufacturerID"]),Convert.ToInt32(dr2["BoxSize"]));
                if (rp.IsColumnNull("ReservedStock"))
                {
                    rp.ReservedStock = 0;
                }
                //if (rp.Balance - rp.ReservedStock < im.QuantityInBasicUnit )
                //{
                //    XtraMessageBox.Show("You cannot replenish the pick face from this location because the items are reserved for Issue. Please replenish from another receive.","Warning",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                //    return;
                //}
                BLL.ItemManufacturer imff = new BLL.ItemManufacturer();
                imff.LoadOuterBoxForItemManufacturer(im.ItemID,im.ManufacturerID);
                if (imff.PackageLevel > im.PackageLevel && rp.Balance < imff.QuantityInBasicUnit)
                {
                    rp2.Balance = rp.Balance;
                }
                else if (rp.Balance - rp.ReservedStock > im.QuantityInBasicUnit)
                {
                    rp2.ReceivedQuantity = rp2.Balance = im.QuantityInBasicUnit;
                }
                else
                {
                    rp2.Balance = rp.Balance;
                }
                rp2.ReservedStock = 0;
                rp.Balance -= rp2.Balance;
                if (rp.IsColumnNull("ReceivedQuantity"))
                {
                    rp.ReceivedQuantity = rp.Balance + rp2.Balance;
                }
                rp.ReceivedQuantity -= rp2.Balance;
                rp.Save();
                rp2.Save();
                pl.Confirmed = false;
                pl.Save();
                pf.Balance += Convert.ToInt32(rp2.Balance);
                pf.Save();
                PalletLocation pl2 = new PalletLocation();
                pl2.LoadLocationForPallet(rp.PalletID);
                rd.LoadByPrimaryKey(rp2.ReceiveID);
                // Now update the screen accordingly.
                dr["Balance"] = pf.Balance;// Convert.ToInt32(dr["Balance"]) + rp2.Balance;

                InternalTransfer it = new InternalTransfer();

                it.AddNew();
                it.ItemID = _designatedItemID;
                it.BoxLevel = im.PackageLevel;
                it.ExpireDate = rd.ExpDate;
                it.BatchNumber = rd.BatchNo;
                it.ManufacturerID = im.ManufacturerID;
                it.FromPalletLocationID = pl2.ID;
                it.ToPalletLocationID = _palletLocationID;
                it.IssuedDate = DateTimeHelper.ServerDateTime;
                it.QtyPerPack = im.QuantityInBasicUnit;
                it.Packs = 1;
                it.ReceiveDocID = rp.ReceiveID;
                it.QuantityInBU = it.Packs * it.QtyPerPack;
                it.Type = "PickFace";
                it.Status = 0;
                it.Save();

                BindPickFaceDetailAndReplenismehmnent();
                XtraMessageBox.Show("Your Pick Face is updated, please print the replenishment list and confirm the stock movement", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// Adds to pick list for an order detail.
        /// </summary>
        /// <param name="orderDetailID">The order detail ID.</param>
        /// <param name="itemId">The item id.</param>
        /// <param name="unitID">The unit ID.</param>
        /// <param name="initalApprovedQuantity">The inital approved quantity.</param>
        /// <param name="storeID">The store ID.</param>
        /// <param name="preferedManufacturer">The prefered manufacturer.</param>
        /// <param name="preferredPhysicalStore">The preferred physical store.</param>
        /// <param name="isDeliveryNote">if set to <c>true</c> [is delivery note].</param>
        /// <param name="preferredExpiry">The preferred expiry.</param>
        /// <exception cref="System.Exception"></exception>
        private void AddToPickListFor(int userID, int orderDetailID, int itemId, int? unitID, decimal initalApprovedQuantity, int storeID, int preferedManufacturer, int preferredPhysicalStore, bool isDeliveryNote, DateTime? preferredExpiry)
        {
            bool deliveryNoteWarning = false;

            if (isDeliveryNote && !BLL.Settings.HandleDeliveryNotes)
            {
                //If the request is for delivery notes but the delivery notes haven't been enabled, then let's change the delivery note bit but also set a warning bit so that we can report it to the user if there are no priced items available. (i.e. In case the picklist comes out empty, we report an error)
                deliveryNoteWarning = true;
                isDeliveryNote = false;
            }

            decimal approvedQuantity = initalApprovedQuantity;

            bool belowBoxPickedFromRack = false;
            //if (preferedManufacturer == -1)
            //{
            var rp = new ReceivePallet();
            var palletLoc = new PalletLocation();
            var im = new ItemManufacturer();

            var pf = new PickFace();
            int buinsku = 0;

            // no manufacturer is preferred so just do the pick list
            // select items that have balance, with sales price and that do have
            rp.LoadNonPickFaceAllItemsReadyToDispatch(userID, itemId, unitID, storeID, preferedManufacturer,
                                                      preferredPhysicalStore, isDeliveryNote, preferredExpiry);

            //If the delivery note warning bit has been set and there are no priced items in the databasee,
            //let's throw an error to the users so that they know the cause of the problem.
            //The solution is to either not choose delivery notes or on the approval stage or enable delivery notes in the settings.
            if (rp.RowCount == 0 && deliveryNoteWarning)
            {
                throw new Exception("Delivery Notes Preference has been set but delivery notes are not enabled for this database.");
            }

            // get how much of it is on the pick face
            //TOFIX: this doesn't have to rely on the quantity on the pick face
            pf.LoadPickFaceFor(itemId, storeID);

            // Just to be safe
            rp.Rewind();
            if (rp.RowCount == 0)
            {
                // this means there is no item to issue other than on the pick face
                // try issuing from the pick face
                LoadFromPickFace(itemId, unitID, approvedQuantity, storeID, isDeliveryNote);
                return;
            }
            while (!rp.EOF)
            {
                // get the current manufacturer
                int manufId = Convert.ToInt32(rp.GetColumn("ManufacturerID"));
                // what is the dispatch able quantity in the current record?
                decimal dispatchableQuantity = Convert.ToDecimal(rp.GetColumn("DispatchableStock"));
                palletLoc.loadByPalletID(rp.PalletID);

                // check if the item is from the rack or the low quantity storage place.
                // if it is from the rack, make sure the packs column counts in cartons
                // if it is not, count in number of packs/SKU or Level 0 only
                if (palletLoc.RowCount > 0 && palletLoc.StorageTypeID.ToString() == StorageType.StackedStorage)
                {
                    im.LoadIMbyLevel(itemId, manufId, 0);
                }
                else if ((palletLoc.RowCount > 0 && palletLoc.StorageTypeID.ToString() != StorageType.BulkStore) ||
                         (pf.RowCount == 0 && palletLoc.StorageTypeID.ToString() == StorageType.BulkStore))
                {
                    im.LoadIMbyLevel(itemId, manufId, 0);
                }
                else
                {
                    im.LoadIMbyLevel(itemId, manufId, Convert.ToInt32(rp.GetColumn("BoxLevel")));
                }
                // just incase there are open cartons on the rack, handle them here.
                if (im.RowCount > 0 && (im.QuantityInBasicUnit > dispatchableQuantity && im.PackageLevel > 0))
                {
                    im.LoadIMbyLevel(itemId, manufId, 0);
                }
                // hold what level we are about to issue,
                // which level of carton and the basic unit in that carton.

                int bUsinBoxLevel;
                buinsku = Convert.ToInt32(rp.GetColumn("QtyPerPack"));// imff.LoadSKUUnit(im.ItemID, im.ManufacturerID);
                if (unitID != null)
                {
                    ItemUnit iu = new ItemUnit();
                    iu.LoadByPrimaryKey(unitID.Value);
                    bUsinBoxLevel = iu.QtyPerUnit;

                    if (buinsku != bUsinBoxLevel)
                    {
                        // This defintely is an error,
                        //TODO: do something about it ;)
                        buinsku = bUsinBoxLevel;
                    }
                }
                else
                {
                    bUsinBoxLevel = im.QuantityInBasicUnit;
                }

                // get the maximum amount of item that can be fulfilled under the current box level
                decimal dispatch = (approvedQuantity / bUsinBoxLevel) * bUsinBoxLevel;
                if (dispatch > dispatchableQuantity)
                {
                    // if the dispatch able quantity is less than what is requested,
                    // only give what we have.
                    dispatch = dispatchableQuantity;
                }
                else if (dispatch == 0)
                {
                    break;
                }

                if (dispatchableQuantity > approvedQuantity)
                {
                    // check if the dispatch is possible with existing pick face items

                    decimal remaining = approvedQuantity - dispatch;
                    // TODO: Explain WTF all this condition is
                    // I assume at this point that it is checking if the remaining amount should be fulfilled from the pick face or not
                    //
                    if (((pf.RowCount == 0 || pf.IsColumnNull("Balance")) && remaining == 0) ||
                        ((pf.RowCount > 0 && !pf.IsColumnNull("Balance") && pf.Balance >= remaining)))
                    {
                        // do this if we should go to the pick face for any reason.
                        if (dispatch > 0)
                        {
                            // do the pick list entries here
                            _pickList.ImportRow(rp.CurrentDataRow);
                            // pick the currently inserted entry and adjust all the numbers in it.
                            DataRow dr = _pickList.Rows[_pickList.Rows.Count - 1];
                            dr["OrderDetailID"] = orderDetailID;
                            // only Adjust the entries that matter to the pick list
                            SetPriceAndQuantity(dr, dispatch, buinsku, rp, itemId, isDeliveryNote);
                            approvedQuantity -= dispatch;
                            // add the items from the pick face
                        }
                        //TODO: implement the pick face logic here.
                        LoadFromPickFace(itemId, unitID, approvedQuantity, storeID, isDeliveryNote);
                        return;
                    }
                    else
                    {
                        // do the bulk pick list and  entries here
                        if (dispatch > 0)
                        {
                            _pickList.ImportRow(rp.CurrentDataRow);
                            // pick the currently inserted entry and adjust all the numbers in it.
                            DataRow dr = _pickList.Rows[_pickList.Rows.Count - 1];
                            dr["OrderDetailID"] = orderDetailID;

                            // only Adjust the entries that matter to the pick list
                            SetPriceAndQuantity(dr, dispatch, buinsku, rp, itemId, isDeliveryNote);
                            approvedQuantity -= dispatch;
                            // the order couldn't be done at this time because the pickface has to be reprenished,
                            // Mark the ReplenishmentList and continue with the other pick list items.
                            // return this message to the user and continue to the next level
                            // do the pick list entries here
                        }
                    }
                }
                else
                // if we are here, it means that the dispatch able quantity is equal to  what we have or greater than the request
                {
                    // dispatch the existing quantity and continue with the other entries in the receive pallet
                    _pickList.ImportRow(rp.CurrentDataRow);
                    // pick the currently inserted entry and adjust all the numbers in it.
                    DataRow dr = _pickList.Rows[_pickList.Rows.Count - 1];
                    dr["OrderDetailID"] = orderDetailID;
                    // only Adjust the entries that matter to the pick list
                    SetPriceAndQuantity(dr, dispatch, buinsku, rp, itemId, isDeliveryNote);
                    approvedQuantity -= dispatch;
                    belowBoxPickedFromRack = true;
                }
                rp.MoveNext();
            }

            if (!belowBoxPickedFromRack && approvedQuantity > 0)
            {
                LoadFromPickFace(itemId, unitID, approvedQuantity, storeID, isDeliveryNote);
            }

            if (approvedQuantity > buinsku && approvedQuantity > 0 &&
                ((pf.RowCount == 0 || pf.IsColumnNull("Balance")) || (approvedQuantity > pf.Balance)))
            {
                //TODO: if this was the last entry in the rp pallet, then it means that the pick face needs to be replenished,\
                // Implement that logic here.

                // this means the pick face has been setup.
                DataRowView drv = _replenishmentList.DefaultView.AddNew();
                drv["ItemID"] = itemId;
                drv["StoreID"] = storeID;
                drv.EndEdit();
            }
        }
        //, string guid)
        private void SavePalletization(ReceiveDoc rec, DataRowView drow)
        {
            if ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") && rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED) || (rec.Quantity == 0 && rec.IsColumnNull("ShortageReasonID")))
            {
                HandleFullNotReceivedAndMultipleBatchPalletlization(rec,drow);
                return;
            }
            string guid;

            BLL.ReceivePallet rp = new ReceivePallet();
            Pallet pallet = new Pallet();
            PalletLocation pl = new PalletLocation();
            ItemUnit itemUnit = new ItemUnit();

            BLL.ItemManufacturer im = new BLL.ItemManufacturer();

            guid = rec.GetColumn("GUID").ToString();
            var isDamaged = Convert.ToBoolean(rec.GetColumn("IsDamaged"));
            //DataRow[] r = _dtPalletizedItemList.Select(string.Format("Index = '{0}'", i));
            DataRow[] r =
                _dtPalletizedItemList.Select(string.Format("GUID = '{0}' AND IsDamaged = {1}", guid, isDamaged));
            if (r.Length > 0)
            {
                foreach (DataRow rw in r)
                {
                    rp.AddNew();
                    rp.IsOriginalReceive = true;
                    if (Convert.ToBoolean(rw["Consolidate"]))
                    {
                        try
                        {
                            DataRow dr =
                                _dtPutAwayPalletized.Select(string.Format("PalletNumber={0}",
                                    Convert.ToInt32(rw["PalletNumber"])))[0]; //Assuming we only need one.
                            if (rw["IsStoredInFreeStorageType"] != null)
                            {
                                if (Convert.ToBoolean(rw["IsStoredInFreeStorageType"]) == true)
                                {
                                    pl.LoadByPrimaryKey(Convert.ToInt32(dr["PutAwayLocation"]));
                                }
                            }
                        }
                        catch
                        {
                            pl.LoadByPalletNumber(Convert.ToInt32(rw["PalletNumber"]));
                        }
                        try
                        {
                            rp.PalletID = pl.PalletID;
                            rp.PalletLocationID = pl.ID;
                        }
                        catch
                        {
                            rp.PalletID = GetPalletID(rw["PalletNumber"].ToString());
                            try
                            {
                                rp.PalletLocationID = PalletLocation.GetPalletLocationID(rp.PalletID);
                            }
                            catch
                            {
                                DataRow dr =
                                    _dtPutAwayPalletized.Select(string.Format("PalletNumber={0}",
                                        Convert.ToInt32(rw["PalletNumber"])))[0];
                                pl.LoadByPrimaryKey(Convert.ToInt32(dr["PutAwayLocation"]));
                                pl.PalletID = rp.PalletID;
                                pl.Save();
                                rp.PalletLocationID = pl.ID;
                            }
                        }

                        //// if the putaway is on a pick face, increase the amount stored on the pick face
                        //if (pl.StorageTypeID.ToString() == StorageType.PickFace)
                        //{
                        //    PickFace pf = new PickFace();

                        //    pf.LoadPickFaceFor(rec.ItemID, Convert.ToInt32(cboStores.EditValue));
                        //    if (pf.RowCount > 0)
                        //    {
                        //        if (pf.IsColumnNull("Balance"))
                        //        {
                        //            pf.Balance = 0;
                        //        }

                        //        pf.Balance += Convert.ToInt32(rp.Balance);
                        //        pf.Save();
                        //    }
                        //}
                    }
                    else
                    {
                        var palletNumber = Convert.ToInt32(rw["PalletNumber"]);
                        DataRow dr = _dtPutAwayPalletized.Select(string.Format("PalletNumber={0}", palletNumber))[0];
                        //Assuming we only need one.
                        pl.LoadByPrimaryKey(Convert.ToInt32(dr["PutAwayLocation"]));
                        rp.PalletID = GetPalletID(rw["PalletNumber"].ToString());
                        pl.PalletID = rp.PalletID;
                        rp.PalletLocationID = pl.ID; //PalletLocation.GetPalletLocationID(rp.PalletID);
                        pl.Save();
                    }

                    rp.ReservedStock = 0;
                    im.LoadIMbyLevel(Convert.ToInt32(rw["ID"]), Convert.ToInt32(rw["Manufacturer"]),
                        Convert.ToInt32(rw["BoxLevel"]));

                    int qtyPerPack = im.QuantityInBasicUnit;

                    if (rw["UnitID"] != DBNull.Value)
                    {
                        itemUnit.LoadByPrimaryKey(Convert.ToInt32(rw["UnitID"]));
                        qtyPerPack = itemUnit.QtyPerUnit;
                    }

                    rp.ReceivedQuantity = rp.Balance = (Convert.ToDecimal(rw["Pack Qty"]) * Convert.ToDecimal(qtyPerPack));
                    rp.BoxSize = Convert.ToInt32(rw["BoxLevel"]);
                    if (rec.IsColumnNull("PhysicalStoreID") && !rp.IsColumnNull("PalletLocationID"))
                    {
                        PalletLocation l = new PalletLocation();
                        l.LoadByPrimaryKey(rp.PalletLocationID);
                        rec.PhysicalStoreID = (l.PhysicalStoreID);

                        PhysicalStore physicalStore = new PhysicalStore();
                        physicalStore.LoadByPrimaryKey(l.PhysicalStoreID);
                        rec.InventoryPeriodID = physicalStore.CurrentInventoryPeriodID;
                    }

                    if (Convert.ToBoolean(rw["Consolidate"]))
                    {
                        try
                        {
                            // if the putaway is on a pick face, increase the amount stored on the pick face
                            if (pl.StorageTypeID.ToString() == StorageType.PickFace)
                            {
                                PickFace pf = new PickFace();

                                pf.LoadPickFaceFor(rec.ItemID, Convert.ToInt32(lkAccounts.EditValue));
                                if (pf.RowCount > 0)
                                {
                                    if (pf.IsColumnNull("Balance"))
                                    {
                                        pf.Balance = 0;
                                    }

                                    pf.Balance += Convert.ToInt32(rp.Balance);
                                    pf.Save();
                                }
                            }
                        }
                        catch
                        {

                        }
                    }

                }
            }

            //r = _dtPutAwayNonPalletized.Select(string.Format("Index = '{0}'", i));
            string filterQuery = _revDocRelatePalletGuid.ContainsKey(guid)
                ? string.Format("{0} AND IsDamaged = {1}", GetFilterByGuid(_revDocRelatePalletGuid[guid]), isDamaged)
                : string.Format("GUID = '{0}' AND IsDamaged = {1} ", guid, isDamaged);
            r = _dtPutAwayNonPalletized.Select(filterQuery);
            if (r.Length > 0)
            {
                // Save the palletization and the putaway here,// this was supposed to be out of here but it is easlier to implement here.
                foreach (DataRow rw in r)
                {
                    pl.LoadByPrimaryKey(Convert.ToInt32(rw["PutAwayLocation"]));
                    if (pl.IsColumnNull("PalletID"))
                    {
                        pallet.AddNew();
                        pallet.Save();
                    }
                    else
                    {
                        pallet.LoadByPrimaryKey(pl.PalletID);
                    }
                    rp.AddNew();
                    rp.IsOriginalReceive = true;
                    rp.PalletID = pallet.ID;
                    rp.PalletLocationID = pl.ID;
                    // rp.ReceiveID = rec.ID;
                    rp.ReservedStock = 0;
                    im.LoadIMbyLevel(Convert.ToInt32(rw["ID"]), Convert.ToInt32(rw["Manufacturer"]),
                        Convert.ToInt32(rw["BoxLevel"]));

                    int qtyPerPack = im.QuantityInBasicUnit;

                    if (rw["UnitID"] != DBNull.Value)
                    {
                        itemUnit.LoadByPrimaryKey(Convert.ToInt32(rw["UnitID"]));
                        qtyPerPack = itemUnit.QtyPerUnit;
                    }

                    rp.ReceivedQuantity =
                        rp.Balance = (Convert.ToDecimal(rw["Palletized Quantity"]) * Convert.ToDecimal(qtyPerPack));
                    rp.BoxSize = Convert.ToInt32(rw["BoxLevel"]);
                    //Get the putaway location

                    pl.Save();
                    if (pl.IsColumnNull("PalletID"))
                    {
                        pl.PalletID = pallet.ID;
                        pl.Confirmed = false;
                        pl.Save();
                    }
                }
            }
            if (rec.IsColumnNull("PhysicalStoreID") && !rp.IsColumnNull("PalletLocationID"))
            {
                PalletLocation l = new PalletLocation();
                l.LoadByPrimaryKey(rp.PalletLocationID);
                PhysicalStore physicalStore = new PhysicalStore();
                physicalStore.LoadByPrimaryKey(l.PhysicalStoreID);
                rec.PhysicalStoreID = (l.PhysicalStoreID);
                // we can take any of the pallet location physical store. as we have one entry on receiveDoc per Store.
                if (physicalStore.IsColumnNull("CurrentInventoryPeriodID"))
                {
                    XtraMessageBox.Show(string.Format("Please Set InventoryPeriod for '{0}' PhysicalStore!",
                        physicalStore.Name), "Empty InventoryPeriod", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new Exception(string.Format("Please Set InventoryPeriod for '{0}' PhysicalStore!",
                        physicalStore.Name));
                }
                rec.InventoryPeriodID = physicalStore.CurrentInventoryPeriodID;

            }

            rec.Save();
            rp.Rewind();
            while (!rp.EOF)
            {
                rp.ReceiveID = rec.ID;
                rp.MoveNext();
            }
            rp.Save();
            SavePutAwayItems();
        }
        private void SaveHubDetails()
        {
            if (isStorageTypeChanged)
            {

                isStorageTypeChanged = false;
                BLL.ItemPrefferedLocation ipl = new ItemPrefferedLocation();
                ipl.LoadByItemID(itemId);
                while (!ipl.EOF)
                {
                    ipl.MarkAsDeleted();
                    ipl.MoveNext();
                }
                ipl.Save();

            }

            Item itm = new Item();

            if (cmbStorageType.SelectedValue != null)
            {
                if (cmbStorageType.SelectedValue.ToString() == StorageType.BulkStore)
                {
                    // store the stacked storage settings
                    itm.LoadByPrimaryKey(itemId);
                    itm.IsStackStored = chkIsStackStored.Checked;
                    itm.Save();

                    if (lstPreferredPalletLocation.ItemCount > 0)
                    {
                        //Items itm = new Items();

                        // save near expiry trigger point

                        ItemPrefferedLocation ipr = new ItemPrefferedLocation();
                        DataView dv = (DataView)lstPreferredPalletLocation.DataSource;
                        foreach (DataRowView drv in dv)
                        {
                            ipr.SaveNewItemPreferredRack(itemId, Convert.ToInt32(drv["ID"]),false);
                        }

                    }
                    // store pickface settings
                    pf.Rewind();
                    PickFace pfc = new PickFace();
                    while (!pf.EOF)
                    {
                        pf.AcceptChanges();
                        if (!pf.IsColumnNull("PalletLocationID"))
                        {
                            pfc.SavePickFaceLocation(itemId, pf.PalletLocationID, pf.LogicalStore);
                        }
                        else
                        {

                            pfc.LoadPickFaceFor(itemId, pf.LogicalStore);
                            if (pfc.RowCount> 0 && (pfc.IsColumnNull("Balance") || pfc.Balance == 0))
                            {
                                pfc.ClearPickFaceFor(itemId, pfc.LogicalStore);
                            }
                            else
                            {
                                //TODO: show the error message for the user
                            }

                        }
                        pf.MoveNext();
                    }

                }
                else
                {
                    // Save the fixed locations
                    var ipr = new ItemPrefferedLocation();
                    DataView dv = (DataView)lstPreferredPalletLocation.DataSource;
                    if (dv != null)
                    {
                        foreach (DataRowView drv in dv)
                        {
                            ipr.SaveNewItemPreferredRack(itemId, Convert.ToInt32(drv["ID"]), true);
                        }
                    }
                }

                itm.LoadByPrimaryKey(itemId);
                itm.StorageTypeID = int.Parse(cmbStorageType.SelectedValue.ToString());
                itm.NearExpiryTrigger = Convert.ToDouble(numNearExpiryTrigger.Value);
                itm.Save();

            }
        }
        private void BindPalletLocationForEdit(object sender, EventArgs e)
        {
            // Keep the reference of the current popup control so that the cancel logic works just fine.
            CurrentPopup = (PopupContainerEdit)sender;
            //Get the selected row
            DataRow dr = detailView.GetFocusedDataRow();
            int palletLocationID = Convert.ToInt32(dr["PalletLocationID"]);
            // Enable and disable optional fields
            String SType = dr["STI"].ToString();
            if (SType == "")
            {
                SType = dr["ShelfStorageType"].ToString();
            }
            cmbFixedPrefered.Enabled = true;

            if (SType == StorageType.BulkStore)
            {
                //lstPreferedItems.Visible = true;
                //lblPreferredItem.Visible = true;
                //cmbFixedPrefered.Enabled = false;
                lblFixedPickItem.Visible = false;
                cmbFixedPrefered.Visible = false;
            }

            else if (SType == StorageType.PickFace)
            {
                lblFixedPickItem.Text = "Pick Item";

                lstPreferedItems.Visible = false;
                lblPreferredItem.Visible = false;

                cmbFixedPrefered.Properties.DataSource = Item.GetItems(StorageType.BulkStore);
                PickFace pf = new PickFace();
                pf.LoadByPalletLocation(palletLocationID);
                if (pf.RowCount >0 && !pf.IsColumnNull("DesignatedItem"))
                {
                    cmbFixedPrefered.EditValue = pf.DesignatedItem;
                }
                else
                {
                    cmbFixedPrefered.EditValue = null;
                }
                lblFixedPickItem.Visible = true;
                cmbFixedPrefered.Visible = true;
            }
            else
            {

                cmbFixedPrefered.Properties.DataSource = Item.GetItems(dr["STI"].ToString());

                BLL.ItemPrefferedLocation ipl = new ItemPrefferedLocation();
                ipl.LoadByRackID( palletLocationID );
                if (ipl.RowCount > 0)
                {
                    cmbFixedPrefered.EditValue = ipl.ItemID;
                }
                else
                {
                    cmbFixedPrefered.EditValue = null;
                }
                lblFixedPickItem.Text = "Fixed Item";
                lblFixedPickItem.Visible = true;
                cmbFixedPrefered.Visible = true;
                lstPreferedItems.Visible = false;
                lblPreferredItem.Visible = false;
            }

            // Bind the available variables
            txtPalletLocationLabel.Text = dr["Label"].ToString();
            chkEnabled.Checked = Convert.ToBoolean(dr["IsEnabled"]);
        }
        /// <summary>
        /// Loads the consolidation option.
        /// </summary>
        /// <param name="itemID">The item ID.</param>
        /// <param name="expiry">The expiry.</param>
        /// <param name="boxSize">Size of the box.</param>
        /// <param name="store">The store.</param>
        public void LoadConsolidationOption(int itemID, DateTime? expiry, int boxSize, int store)
        {
            string pfaceQuery = "";
            if (boxSize == 0)
            {
                PickFace pf = new PickFace();
                pf.LoadPickFaceFor(itemID, store);
                if (pf.RowCount > 0)
                {

                    if (!pf.IsColumnNull("PalletLocationID"))
                    {
                        PalletLocation pl = new PalletLocation();
                        pl.LoadByPrimaryKey(pf.PalletLocationID);
                        if (pl.IsColumnNull("PalletID"))
                        {
                            Pallet pallet = new Pallet();
                            pallet.AddNew();
                            pallet.StorageTypeID = Convert.ToInt32(StorageType.PickFace);
                            pallet.Save();

                            pl.PalletID = pallet.ID;
                            pl.Save();
                        }

                        pfaceQuery = string.Format(" pl.ID = {0}", pl.ID);
                    }

                }
            }

            string date = expiry != null ? string.Format("ExpDate = '{0}'", expiry.Value.ToShortDateString()) : "ExpDate is null";
            string query = HCMIS.Repository.Queries.PalletLocation.SelectLoadConsolidationOption(itemID, date);

            this.LoadFromRawSql(query);

            DataTable dtbl = this.DataTable;
            if (pfaceQuery != "")
            {
                query = HCMIS.Repository.Queries.PalletLocation.SelectLoadConsolidationOptionOther(pfaceQuery);
                this.LoadFromRawSql(query);
            }
            this.DataTable.Merge(dtbl);
        }