/// <summary>
        /// Calculates the current volume of a pallet, 
        /// this assumes that the box levels have all the dimentions set.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public double CalculateCurrentVolume( int id)
        {
            Pallet p = new Pallet();
            p.GetAllItemsInPallet(id);
            ReceiveDoc rd = new ReceiveDoc();
            ItemManufacturer im = new ItemManufacturer();
            double volume = 0;

            foreach (DataRowView drv in p.DefaultView)
            {
                //Get the recieving box size and manufacturer
                rd.LoadByPrimaryKey(Convert.ToInt32(drv["ReceiveID"]));
                //Handle if the box size was not specified for some reason.
                // this shouldn't happen on a non error condition
                if (drv["BoxSize"].ToString() == "")
                {
                    drv["BoxSize"] = 0;
                }
                im.LoadIMbyLevel(rd.ItemID, rd.ManufacturerId, Convert.ToInt32(drv["BoxSize"]));
                if (im.RowCount == 0)
                {
                    im.LoadIMbyLevel(rd.ItemID, rd.ManufacturerId, 0);
                }
                double quantity = Convert.ToInt32(drv["Balance"])/im.QuantityInBasicUnit;
                volume += quantity * im.Volume;
                // find the volume of the items in the current pallet.

            }
            return volume;
        }
 public static int GetLastPanelNumber()
 {
     Pallet pl = new Pallet();
     string query = "select max(PalletNo) Last from Pallet";
     pl.LoadFromRawSql(query);
     return Convert.ToInt32(pl.DataRow["Last"]);
 }
 /// <summary>
 /// Gets the last pallet number 
 /// </summary>
 /// <returns></returns>
 public static int GetLastPanelNumber()
 {
     Pallet pl = new Pallet();
     string query = HCMIS.Repository.Queries.Pallet.SelectGetLastPanelNumber();
     pl.LoadFromRawSql(query);
     if (pl.RowCount == 0 || pl.DataRow["Last"] == DBNull.Value)
     {
         return 0;
     }
     return Convert.ToInt32(pl.DataRow["Last"]);
 }
        private void btnAdjustments_Click(object sender, EventArgs e)
        {
            if (ValidateMoveToAdjustments())
            {
                if (DialogResult.Yes == XtraMessageBox.Show("Are you sure you would like to commit this adjustment?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {

                    PalletLocation pl = new PalletLocation();
                    Pallet p = new Pallet();
                    ReceiveDoc rdoc = new ReceiveDoc();
                    ReceivePallet rp = new ReceivePallet();
                    int printNubmer = InternalTransfer.GetNewPrintNumber() + 1 ;
                    for (int i = 0; i < gridView3.RowCount; i++)
                    {
                         DataRow dr = gridView3.GetDataRow(i);
                         if (dr["Adjust"] != DBNull.Value)
                         {

                             int amount = Convert.ToInt32(dr["Adjust"]);
                             rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                             rdoc.LoadByPrimaryKey(rp.ReceiveID);

                             rdoc.NoOfPack += amount;
                             amount *= rdoc.QtyPerPack;
                             rp.Balance += amount;
                             if (rp.IsColumnNull("ReceivedQuantity"))
                             {
                                 rp.ReceivedQuantity = 0;
                             }
                             rp.ReceivedQuantity += amount;

                             rdoc.QuantityLeft += amount;
                             rdoc.Quantity += amount;

                             BLL.LossAndAdjustment d = new BLL.LossAndAdjustment();
                             d.AddNew();
                             d.GenerateRefNo();
                             d.ItemID = Convert.ToInt32(dr["ItemID"]);
                             d.ReasonId = Convert.ToInt32(dr["Reason"]);
                             d.RecID = rdoc.ID;
                             d.Quantity = amount;
                             d.BatchNo = rdoc.BatchNo;

                             CalendarLib.DateTimePickerEx edate = new CalendarLib.DateTimePickerEx();
                             edate.Value = DateTime.Today;

                             edate.CustomFormat = "MM/dd/yyyy";
                             d.Date = ConvertDate.DateConverter(edate.Text);

                             d.EurDate = DateTime.Today;
                             if (!rdoc.IsColumnNull("Cost"))
                             {
                                 d.Cost = Math.Abs(rdoc.Cost*amount);
                             }
                             d.StoreId = rdoc.StoreID;
                             d.Losses = false;
                             d.ApprovedBy = CurrentContext.UserId.ToString();
                             d.Save();
                             rdoc.Save();
                             rp.Save();

                         }
                    }
                    PopulateItemDetails();
                    XtraMessageBox.Show("Items adjusted successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        private void btnMoveToQuaranteen_Click(object sender, EventArgs e)
        {
            if (ValidateMoveToQuaranteen())
            {
                if (DialogResult.Yes == XtraMessageBox.Show("Are you sure you want to move the items to Quarantine", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    InternalItemMovements ims = new InternalItemMovements();
                    PalletLocation pl = new PalletLocation();
                    int printNubmer = InternalTransfer.GetNewPrintNumber() + 1 ;
                    for (int i = 0; i < gridView3.RowCount; i++)
                    {
                        DataRow dr = gridView3.GetDataRow(i);
                        if (dr["Loss"] != DBNull.Value)
                        {
                            int amount = Convert.ToInt32(dr["Loss"]);
                            int palletLocationID = Convert.ToInt32(dr["PalletLocationID"]);

                            ReceivePallet rp = new ReceivePallet();
                            ReceiveDoc rdoc = new ReceiveDoc();

                            rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                            rdoc.LoadByPrimaryKey(rp.ReceiveID);
                            amount *= rdoc.QtyPerPack;

                            if (rp.Balance - amount < rp.ReservedStock)
                            {
                                //Item has been reserved for a facility.  This needs to be handled.
                                DataTable dtble = rp.GetFacilitiesItemsReservedFor();
                                string facilities = "";
                                foreach(DataRow dRow in dtble.Rows)
                                {
                                    if (dr != null)
                                        facilities += dRow["Name"].ToString() + System.Environment.NewLine;
                                }
                                XtraMessageBox.Show("You cannot fill in a loss because the item in this location has been reserved to the following facilities:" + System.Environment.NewLine + facilities, "Exisiting reservations must be cancelled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return;
                            }

                            var receiveDocID = Convert.ToInt32(dr["ID"]);
                            var rec = new ReceiveDoc();
                            rec.LoadByPrimaryKey(receiveDocID);

                            int qPalletLocationID = PalletLocation.GetQuaranteenPalletLocation(rec.PhysicalStoreID);
                            pl.LoadByPrimaryKey(qPalletLocationID);
                            if (pl.IsColumnNull("PalletID"))
                            {
                                Pallet p = new Pallet();
                                p.AddNew();
                                p.StorageTypeID = Convert.ToInt32( StorageType.Quaranteen);
                                p.Save();
                                pl.PalletID = p.ID;
                                pl.Save();
                            }

                            ReceivePallet rp2 = new ReceivePallet();
                            ReceiveDoc rd = new ReceiveDoc();

                            rd.LoadByPrimaryKey(rp.ReceiveID);
                            rp2.AddNew();

                            rp2.PalletID = pl.PalletID;
                            rp2.ReceiveID = rp.ReceiveID;
                            rp2.PalletLocationID = pl.ID;

                            // calculate the new balance
                            BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                            //im.LoadDefaultReceiving(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]));
                            if (dr["BoxLevel"] == DBNull.Value)
                            {
                                dr["BoxLevel"] = 0;
                            }
                            im.LoadIMbyLevel(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]), Convert.ToInt32(dr["BoxLevel"]));
                            int packqty = (amount / im.QuantityInBasicUnit);
                            rp2.ReservedStock = 0;

                            BLL.ReceivePallet.MoveBalance(rp, rp2, amount);
                            //rp2.Balance = amount;
                            //rp.Balance -= rp2.Balance;

                            //rp.Save();
                            //rp2.Save();

                            pl.Confirmed = false;
                            pl.Save();
                            if (rp.Balance == 0 )
                            {
                                PalletLocation.GarbageCollection();
                            }

                            InternalTransfer it = new InternalTransfer();
                            it.AddNew();
                            it.ItemID = rd.ItemID;
                            it.BoxLevel = im.PackageLevel;
                            if (!rd.IsColumnNull("ExpDate"))
                            {
                                it.ExpireDate = rd.ExpDate;
                            }
                            it.BatchNumber = rd.BatchNo;
                            it.ManufacturerID = im.ManufacturerID;
                            it.FromPalletLocationID = palletLocationID;
                            it.ToPalletLocationID = qPalletLocationID;
                            it.QtyPerPack = im.QuantityInBasicUnit;
                            it.Packs = packqty;
                            it.ReceiveDocID = rp.ReceiveID;
                            it.QuantityInBU = rp2.Balance; //it.Packs * it.QtyPerPack;
                            it.Type = "ToQuaranteen";
                            it.IssuedDate = DateTime.Today;
                            it.Status = 0;
                            it.PrintNumber = printNubmer;
                            it.Save();
                        }
                    }

                    gridConfirmationControl.DataSource = InternalTransfer.GetAllTransfers("ToQuaranteen");

                    PopulateItemDetails();
                    XtraMessageBox.Show("Your items are marked for movement to Quarantine, please go to Internal Movements page to confirm!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        /// <summary>
        /// Recommends the pallet movments.
        /// </summary>
        /// <returns></returns>
        public DataView RecommendPalletMovments()
        {
            // check for each pallet in bulk store
            this.LoadFromRawSql(HCMIS.Repository.Queries.PalletLocation.SelectRecommendPalletMovments(StorageType.BulkStore));
            DataTable dtbl = new DataTable();
            dtbl.Columns.Add("ItemID");
            dtbl.Columns.Add("FullItemName");
            dtbl.Columns.Add("PalletNo");
            dtbl.Columns.Add("FromID");
            dtbl.Columns.Add("ToID");
            dtbl.Columns.Add("From");
            dtbl.Columns.Add("To");
            int itemID = 0;
            int freePreferedLocationCount = 0;
            Item itms = new Item();
            bool checkable = false;
            PalletLocation pl = new PalletLocation();

            while (!this.EOF)
            {
                if (Convert.ToInt32(this.DataRow["ItemID"]) != itemID)
                {
                    itemID = Convert.ToInt32(this.DataRow["ItemID"]);
                    // do this if this item is a bulk storage
                    itms.GetItemByPrimaryKey(itemID);
                    if (itms.StorageTypeID.ToString() == StorageType.BulkStore)
                    {
                        checkable = true;

                        pl.LoadFreePrefferedLocationFor(itemID);
                        freePreferedLocationCount = pl.RowCount;
                    }
                    else
                    {
                        checkable = false;
                    }
                }

                if (checkable && freePreferedLocationCount > 0)
                {
                    //add it to the table
                    DataRowView drv = dtbl.DefaultView.AddNew();
                    drv["ItemID"] = itemID;
                    drv["FullItemName"] = itms.FullItemName;
                    drv["FromID"] = this.ID;
                    drv["ToID"] = pl.ID;
                    Pallet pallet = new Pallet();
                    pallet.LoadByPrimaryKey(this.PalletID);
                    drv["PalletNo"] = pallet.PalletNo;
                    pl.MoveNext();
                    freePreferedLocationCount--;
                    drv["From"] = this.FullName;
                    drv["To"] = pl.FullName;
                }

                this.MoveNext();
            }

            return dtbl.DefaultView;
        }
        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);
            }
        }
 private int GetPalletID(string palletNumber)
 {
     Pallet plt = new Pallet();
     plt.LoadByPalletNumber(palletNumber);
     if (plt.RowCount == 0)
     {
         plt.AddNew();
         plt.PalletNo = Convert.ToInt32(palletNumber);
         plt.Save();
     }
     return plt.ID;
 }
        //, 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();
        }
        /// <summary>
        /// Palletizes the transfer.
        /// </summary>
        /// <param name="rec">The rec.</param>
        public static void PalletizeTransfer(ReceiveDoc rec)
        {
            BLL.ReceivePallet rp = new ReceivePallet();
            Pallet pallet = new Pallet();
            PalletLocation pl = new PalletLocation();
            rec.Rewind();
            BLL.ItemManufacturer im = new BLL.ItemManufacturer();
            rp.AddNew();
            rp.ReceivedQuantity = rec.Quantity;
            rp.Balance = rec.Quantity;
            rp.ReservedStock = 0;
            rp.ReceiveID = rec.ID;
            //Just To Get the First Free pallet
            DataTable dtpl = PalletLocation.GetAllFreeForItem(rec.ItemID, StorageType.Free);
            DataRow drpl = dtpl.Rows[0];
            //After we assign the Location for it
            pl.LoadByPrimaryKey(Convert.ToInt32(drpl["ID"]));

            rp.PalletID = pl.PalletID;
            rp.PalletLocationID = pl.ID;
            rp.IsOriginalReceive = true;
            rp.Save();
        }
        /// <summary>
        /// Saves the new receive doc entry from picklist detail.
        /// </summary>
        /// <param name="pld">The PLD.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="activityID">The new store ID.</param>
        /// <param name="newPhysicalStoreID">The new physical store ID.</param>
        /// <param name="convertedEthDate">The converted eth date.</param>
        /// <param name="supplierID">Activity or Store where it has Transfered from </param>
        /// <exception cref="System.Exception"></exception>
        internal void SaveNewReceiveDocEntryFromPicklistDetail(PickListDetail pld, int userID, int activityID, int newPhysicalStoreID, DateTime convertedEthDate,int receiptID,int? supplierID)
        {
            BLL.User user = new User();
            user.LoadByPrimaryKey(userID);

            BLL.ReceiveDoc rdOriginal = new ReceiveDoc();
            rdOriginal.LoadByPrimaryKey(pld.ReceiveDocID);

            //Now Save the receive doc entry
            this.AddNew();
            this.SetColumn("BatchNo", pld.GetColumn("BatchNumber"));
            this.ItemID = pld.ItemID;
            if (supplierID != null) this.SupplierID = supplierID.Value;
            this.Quantity = pld.QuantityInBU;
            //this.Date=
            this.Date = convertedEthDate;
            this.SetColumn("ExpDate", rdOriginal.GetColumn("ExpDate"));
            this.Out = false;
            this.ReceivedBy = user.UserName;
            this.StoreID = activityID;
            SetColumn("LocalBatchNo", rdOriginal.GetColumn("LocalBatchNo"));
            this.RefNo = receiptID.ToString();
            this.SetColumn("Cost", rdOriginal.GetColumn("Cost"));
            this.SetColumn("IsApproved", rdOriginal.GetColumn("IsApproved"));
            this.ManufacturerId = rdOriginal.ManufacturerId;
            this.QuantityLeft = this.Quantity;
            this.NoOfPack = pld.Packs;
            this.QtyPerPack = rdOriginal.QtyPerPack;
            this.EurDate = DateTimeHelper.ServerDateTime;
            this.SetColumn("SellingPrice", rdOriginal.GetColumn("SellingPrice"));
            this.SetColumn("UnitCost", rdOriginal.GetColumn("Cost"));
            this.SetColumn("Cost", rdOriginal.GetColumn("Cost"));
            this.SetColumn("PricePerPack", rdOriginal.GetColumn("Cost"));
            this.SetColumn("UnitID", rdOriginal.GetColumn("UnitID"));
            this.SetColumn("DeliveryNote", rdOriginal.GetColumn("DeliveryNote"));
            this.Confirmed = false;
            this.ConfirmedDateTime = DateTimeHelper.ServerDateTime;
            this.ReturnedStock = false;
            this.ReceiptID = receiptID;
            this.PhysicalStoreID = newPhysicalStoreID;
            PhysicalStore physicalStore = new PhysicalStore();
            physicalStore.LoadByPrimaryKey(newPhysicalStoreID);
            this.InventoryPeriodID = physicalStore.CurrentInventoryPeriodID;
            this.SetColumn("Margin", rdOriginal.GetColumn("Margin"));
            this.InvoicedNoOfPack = pld.Packs;
            this.IsDamaged = (bool) rdOriginal.GetColumn("IsDamaged");
            this.Save();

            //Now Save the ReceiveDocConfirmation

            ReceiveDocConfirmation rdConf = new ReceiveDocConfirmation();
            rdConf.AddNew();
            rdConf.ReceiveDocID = this.ID;
            rdConf.ReceivedByUserID = userID;
            rdConf.ReceiptConfirmationStatusID = BLL.ReceiptConfirmationStatus.Constants.RECEIVE_ENTERED;
            rdConf.Save();

            //Now Save the palletization.

            ReceivePallet rp = new ReceivePallet();
            rp.AddNew();

            rp.ReceivedQuantity = this.Quantity;
            rp.Balance = this.Quantity;
            rp.ReservedStock = 0;
            rp.ReceiveID = this.ID;

            PalletLocation pLocation = new PalletLocation();
            pLocation.LoadFirstOrDefault(newPhysicalStoreID, int.Parse(BLL.StorageType.BulkStore));

            if (pLocation.RowCount == 0)
            {
                throw new Exception("No locations created in the destination store. Please check if there are Bulk store pallet locations in the physical store.");
            }
            else
            {
                if (pLocation.IsColumnNull("PalletID"))
                {
                    Pallet pallet = new Pallet();
                    pallet.AddNew();
                    pallet.PalletNo = BLL.Pallet.GetLastPanelNumber() + 1;
                    pallet.StorageTypeID = int.Parse(BLL.StorageType.Free);
                    pallet.Save();
                    pLocation.PalletID = pallet.ID;
                }

                rp.PalletID = pLocation.PalletID;
                rp.PalletLocationID = pLocation.ID;
                rp.BoxSize = 0;
                rp.IsOriginalReceive = true;
                rp.Save();
            }
        }
        public int GetpalletidbyPalletLocationOrgetnew( int palletlocationid)
        {
            string query = HCMIS.Repository.Queries.PalletLocation.selectpalletidbyPalletLocation(palletlocationid);
            PalletLocation pl = new PalletLocation();
            pl.LoadFromRawSql(query);
            if (pl.RowCount > 0)
                return pl.PalletID;
            else
            {// create new pallet
                Pallet pallet = new Pallet();
                pallet.AddNew();

                string query2 = HCMIS.Repository.Queries.PalletLocation.selectstoreIDbyPalletLocationID(palletlocationid);
                PalletLocation pl2 = new PalletLocation();
                pl2.LoadFromRawSql(query2);
                pallet.StorageTypeID = pl2.StorageTypeID;

                pallet.Save();

                return pallet.ID;
            }
        }
        /// <summary>
        /// Gets the percentage grid for.
        /// </summary>
        /// <param name="shelfID">The shelf ID.</param>
        /// <returns></returns>
        public static DataTable GetPercentageGridFor(int shelfID)
        {
            // create the table
            DataTable dtbl = new DataTable();
            ShelfRowColumn src = new ShelfRowColumn();
            src.LoadColumnsForShelf(shelfID);
            while (!src.EOF)
            {
                dtbl.Columns.Add(src.Label, typeof(float));
                src.MoveNext();
            }

            ShelfRowColumn srcrows = new ShelfRowColumn();
            srcrows.LoadRowsForShelf(shelfID);
            PalletLocation pl = new PalletLocation();

            while (!srcrows.EOF)
            {
                src.Rewind();
                DataRowView drv = dtbl.DefaultView.AddNew();
                while (!src.EOF)
                {
                    pl.LoadPalletLocationFor(shelfID, src.Index, srcrows.Index);
                    if (pl.RowCount > 0)
                    {

                        {
                            if (pl.IsColumnNull("PalletID"))
                            {
                                pl.UsedVolume = 0;
                            }
                            else
                            {
                                Pallet p = new Pallet();
                                p.LoadByPrimaryKey(pl.PalletID);
                                pl.UsedVolume = p.CalculateCurrentVolume(pl.PalletID);
                                pl.Save();
                            }

                        }
                        pl.PercentUsed = pl.AvailableVolume == 0 ? 0 : Convert.ToDouble((pl.UsedVolume / pl.AvailableVolume) * 100);
                        pl.Save();
                        drv[src.Label] = pl.PercentUsed;

                    }
                    src.MoveNext();
                }
                srcrows.MoveNext();
            }
            return dtbl;
        }
 /// <summary>
 /// Calculates all volumes.
 /// </summary>
 /// <param name="itemID">The item ID.</param>
 internal static void CalculateAllVolumes(int itemID)
 {
     PalletLocation pl = new PalletLocation();
     pl.LoadFromRawSql(HCMIS.Repository.Queries.PalletLocation.SelectCalculateAllVolumes(itemID));
     Pallet pallet = new Pallet();
     while (!pl.EOF)
     {
         pl.UsedVolume = pallet.CalculateCurrentVolume(pl.PalletID);
         pl.Save();
         pl.MoveNext();
     }
 }
        private bool PalletizationIsValid()
        {
            if (_dtPalletizedItemList == null)
            {
                return false;
            }
            bool valid = true;
            // check if the items are of equal quantity
            DataTable palletized = _dtPalletizedItemList.DefaultView.ToTable(); //(true, "Ordering", "Expiry Date");

            foreach (DataRow dr in palletized.Rows)
            {
                string guid = dr["GUID"].ToString();
                DataRow[] arrReceive = null;
                arrReceive = _dtRecGrid.Select(string.Format("[GUID] = '{0}'", guid));
                DataRow[] arrPalletized = null;
                arrPalletized = _dtPalletizedItemList.Select(string.Format("[GUID] = '{0}'", guid));
                DataRow[] arrNonPalletized = null;
                arrNonPalletized = _dtNonPalletizedItemList.Select(string.Format("[GUID] = '{0}'", guid));
                DataView dataView = null;
                if (grdShortageOrDamaged.DataSource != null)
                {
                    dataView = ((DataTable)grdShortageOrDamaged.DataSource).AsDataView();
                    dataView.RowFilter = string.Format("[GUID]='{0}' and [ShortageReasonID] = {1}", guid,
                        BLL.ShortageReasons.Constants.DAMAGED);
                    //Since we want to do quantity verification only, we need the damaged ones only.  This is because unlike the other type of discrepancies, the damaged adds quantity to the stock.
                }
                DataRowCollection arrDamaged = null;
                if (dataView != null)
                    arrDamaged = dataView.ToTable().Rows;

                // find sum of BU Qty in arr,
                decimal receiveQty = 0;
                decimal palletizedQty = 0;
                decimal nonPalletizedQty = 0;
                decimal damagedQty = 0;

                if (arrReceive != null)
                {
                    foreach (DataRow d in arrReceive)
                    {
                        d.ClearErrors();
                        receiveQty += Convert.ToDecimal(d["Pack Qty"]);
                    }
                }
                if (arrPalletized != null)
                {
                    foreach (DataRow d in arrPalletized)
                    {
                        d.ClearErrors();
                        palletizedQty += Convert.ToDecimal(d["Pack Qty"]);
                    }
                }

                if (arrNonPalletized != null)
                {
                    foreach (DataRow d in arrNonPalletized)
                    {
                        d.ClearErrors();
                        nonPalletizedQty += Convert.ToDecimal(d["Pack Qty"]);
                    }
                }

                if (arrDamaged != null)
                {
                    foreach (DataRow d in arrDamaged)
                    {
                        d.ClearErrors();
                        damagedQty += Convert.ToDecimal(d["Pack Qty"]);
                    }
                }

                if (receiveQty != (palletizedQty + nonPalletizedQty - damagedQty))
                {
                    foreach (DataRow d in arrPalletized)
                    {
                        d.SetColumnError("Pack Qty",
                            String.Format("Sum should be equal to what's specified in Step two({0})", receiveQty));
                    }
                    // this was an error
                    valid = false;

                }
            }

            Pallet plt = new Pallet();
            // check if the pallet # don't allow null or 0
            foreach (DataRow dr in _dtPalletizedItemList.Rows)
            {

                if (dr["PalletNumber"] == DBNull.Value || dr["PalletNumber"].ToString().Equals("") ||
                    Convert.ToInt32(dr["PalletNumber"]) == 0)
                {
                    dr.SetColumnError("PalletNumber", "The Pallet Number you specified is Already Used.");
                    valid = false;
                    continue;
                }
            }

            // check if same expiry on a single pallet location rule is held
            DataTable PalletNumbers = _dtPalletizedItemList.DefaultView.ToTable(true, "PalletNumber");
            foreach (DataRow dr in PalletNumbers.Rows)
            {
                // validate if the pallet number specified is not already used

                plt.LoadByPalletNumber(dr["PalletNumber"].ToString());

                if (plt.RowCount > 0)
                {
                    // there is an existing pallet number in the pallet list

                    DataRow[] darr =
                        _dtPalletizedItemList.Select(string.Format("PalletNumber = '{0}'", dr["PalletNumber"]));
                    foreach (DataRow d in darr)
                    {

                        if (!Convert.ToBoolean(d["Consolidate"]))
                        {
                            d.SetColumnError("PalletNumber", "The Pallet Number you specified is Already Used.");
                            valid = false;
                        }
                    }

                    continue;
                }

                DataRow[] arr1 = _dtPalletizedItemList.Select(string.Format("PalletNumber = '{0}'", dr["PalletNumber"]));
                int ItemID = 0;
                DateTime ExpiryDate = DateTime.Today;
                foreach (DataRow drw in arr1)
                {
                    if (ItemID == 0)
                    {
                        ItemID = Convert.ToInt32(drw["ID"]);
                        if (drw["Expiry Date"] != DBNull.Value)
                        {
                            ExpiryDate = Convert.ToDateTime(drw["Expiry Date"]);
                        }
                    }
                    else
                    {
                        //Validate if the same Item,with same Epiry date is in the same pallet
                        if (ItemID != Convert.ToInt32(drw["ID"]))
                        {
                            drw.SetColumnError("Item Name", "Different Items couldn't be put on the same pallet.");
                            valid = false;
                        }
                        if (drw["Expiry Date"] != DBNull.Value)
                        {
                            if (ExpiryDate.Subtract(Convert.ToDateTime(drw["Expiry Date"])).Days != 0)
                            {
                                drw.SetColumnError("Expiry Date",
                                    "Items With Different Expiry Date couldn't be put on the same pallet.");
                                valid = false;
                            }
                        }
                    }
                }
            }

            return valid;
        }
        private void PutAwayRecievedItems(bool reset)
        {
            if (_dtPutAwayNonPalletized == null || reset == true)
            {
                // Prep the data tables
                _dtPutAwayNonPalletized = new DataTable();
                _dtPutAwayPalletized = new DataTable();

                _dtPutAwayPalletized.Columns.Add("ID");
                _dtPutAwayPalletized.Columns.Add("Item Name");
                _dtPutAwayPalletized.Columns.Add("PalletNumber");
                _dtPutAwayPalletized.Columns.Add("Expiry Date", typeof(DateTime));
                _dtPutAwayPalletized.Columns.Add("PutAwayLocation");
                _dtPutAwayPalletized.Columns.Add("Consolidate", typeof(bool));
                _dtPutAwayPalletized.Columns.Add("Notes");
                _dtPutAwayPalletized.Columns.Add("Volume");
                _dtPutAwayPalletized.Columns.Add("Stock Code");

                _dtPutAwayNonPalletized.Columns.Add("ID");
                _dtPutAwayNonPalletized.Columns.Add("Item Name");
                _dtPutAwayNonPalletized.Columns.Add("Pack Qty", typeof(decimal));
                _dtPutAwayNonPalletized.Columns.Add("Expiry Date", typeof(DateTime));
                _dtPutAwayNonPalletized.Columns.Add("PutAwayLocation");
                _dtPutAwayNonPalletized.Columns.Add("Batch No");
                _dtPutAwayNonPalletized.Columns.Add("StorageType");
                _dtPutAwayNonPalletized.Columns.Add("BoxLevel", typeof(int));
                _dtPutAwayNonPalletized.Columns.Add("Index");
                _dtPutAwayNonPalletized.Columns.Add("BasicUnitPerQ");
                _dtPutAwayNonPalletized.Columns.Add("IsDamaged", typeof(bool));
                _dtPutAwayNonPalletized.Columns.Add("Volume");
                _dtPutAwayNonPalletized.Columns.Add("Manufacturer", typeof(int));
                _dtPutAwayNonPalletized.Columns.Add("UnitID", typeof(int));
                _dtPutAwayNonPalletized.Columns.Add("Stock Code");
                _dtPutAwayNonPalletized.Columns.Add("GUID");
                _dtPutAwayNonPalletized.Columns.Add("Palletized Quantity", typeof(decimal));
                // import the neccessary data tables
                _dtPalletizedItemList.DefaultView.Sort = "Ordering, PalletNumber";

                int prevPalletID = 0;
                int palletID = 0;
                DataRow LastDr = null;
                foreach (DataRowView drv in _dtPalletizedItemList.DefaultView)
                {
                    DataRow dr = drv.Row;
                    palletID = Convert.ToInt32(drv["PalletNumber"]);
                    if (palletID != prevPalletID)
                    {
                        _dtPutAwayPalletized.ImportRow(dr);
                        LastDr = _dtPutAwayPalletized.Rows[_dtPutAwayPalletized.Rows.Count - 1];
                        LastDr.EndEdit();
                        if (Convert.ToBoolean(LastDr["Consolidate"]))
                        {
                            int plid;
                            LastDr["PutAwayLocation"] = plid = Convert.ToInt32(drv["PalletNumber"]);
                            PalletLocation plc = new PalletLocation();
                            plc.LoadByPrimaryKey(plid);
                            Pallet plt = new Pallet();
                            plt.LoadByPrimaryKey(plc.PalletID);
                            LastDr["PalletNumber"] = (!plt.IsColumnNull("PalletNo")) ? plt.PalletNo : 0;
                        }
                    }
                    else
                    {
                        // add the volume
                        LastDr["Volume"] = Convert.ToDouble(LastDr["Volume"]) + Convert.ToDouble(dr["Volume"]);
                    }
                    prevPalletID = palletID;
                }
                //int quarantine = PalletLocation.GetQuaranteenPalletLocation();
                foreach (DataRowView drv in _dtNonPalletizedItemList.DefaultView)
                {
                    _dtPutAwayNonPalletized.ImportRow(drv.Row);

                    DataRow dr = _dtPutAwayNonPalletized.Rows[_dtPutAwayNonPalletized.Rows.Count - 1];
                    dr.ClearErrors();
                }
                foreach (DataRowView dr in _dtPutAwayNonPalletized.DefaultView)
                {
                    dr["Palletized Quantity"] = dr["Pack Qty"];
                }

                // Bind the data tables with the grids
                //gridPutAwayPalletized.DataSource = _dtPutAwayPalletized;
                //gridPutAwayPalletizedView.SelectRow(0);
                gridPutAwayNonPalletized.DataSource = _dtPutAwayNonPalletized;
                //gridPutAwayPalletizedView.SelectRow(0);
            }
        }
        private void btnMove_Click(object sender, EventArgs e)
        {
            // Validation
            foreach (DataRowView drv in _rpl.DefaultView)
            {
                int Balance = Convert.ToInt32(drv["Balance"]);
                int splited = Convert.ToInt32(drv["BalanceToMove"]);
                if (Balance < splited)
                {
                    XtraMessageBox.Show("Couldn't split to the numbers you specified. Please specify number less than the balance.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            // validate the selected pallet location
            if (lkFreePalletLocations.EditValue == null)
            {
                XtraMessageBox.Show("Please select a valid destination pallet location.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //

            PalletLocation destinationPalletLocatin = new PalletLocation();
            destinationPalletLocatin.LoadByPrimaryKey(Convert.ToInt32(lkFreePalletLocations.EditValue));
            if (destinationPalletLocatin.IsColumnNull("PalletID"))//The Pallet Location is empty
            {
                Pallet pallet = new Pallet();
                pallet.AddNew();
                pallet.Save();
                destinationPalletLocatin.PalletID = pallet.ID;
                destinationPalletLocatin.Save();
            }
            // THIS HAS BEEN REMOVED AS PER RUTH'S SUGGESTION THAT: THE SYSTEM SHOULD NOT BLOCK IF THE WAREHOUSE MANAGER WANTES TO USE
            //else if (destinationPalletLocatin.StorageTypeID.ToString() != BLL.StorageType.Free) //If the pallet location is not empty and it is not free storage, you can't put more on it.
            //{
            //    // the thingy has not been moved
            //    XtraMessageBox.Show("The selected Pallet location is not Empty. Please select another location.", "Error splitting");
            //    return;
            //}

            foreach (DataRowView drv in _rpl.DefaultView)
            {
                int balanceToMove = Convert.ToInt32(drv["BalanceToMove"]);
                int qtyPerPack = Convert.ToInt32(drv["QtyPerPack"]);
                balanceToMove *= qtyPerPack;
                if (balanceToMove > 0)
                {
                    ReceivePallet rpSource = new ReceivePallet();
                    ReceivePallet rpDestination = new ReceivePallet();

                    rpSource.LoadByPrimaryKey(Convert.ToInt32(drv["ID"]));

                    rpDestination.AddNew();

                    //rpDestination.Balance = balanceToMove;//
                    if (!rpSource.IsColumnNull("BoxSize"))
                    {
                        rpDestination.BoxSize = rpSource.BoxSize;
                    }
                    else
                    {
                        rpDestination.BoxSize = 1;
                    }
                    rpDestination.ReceivedQuantity = balanceToMove;
                    rpDestination.PalletID = destinationPalletLocatin.PalletID;//pallet.ID;
                    rpDestination.PalletLocationID = destinationPalletLocatin.ID;
                    rpDestination.ReceiveID = rpSource.ReceiveID;
                    if (!rpSource.IsColumnNull("ReceivedQuantity"))
                        rpSource.ReceivedQuantity -= balanceToMove;
                    //rpSource.Balance -= balanceToMove;//

                    rpDestination.ReservedStock = 0;
                    rpDestination.IsOriginalReceive = false;
                    BLL.ReceivePallet.MoveBalance(rpSource, rpDestination, balanceToMove);
                    //rpSource.Save();
                    //rpDestination.Save();
                }
            }
            XtraMessageBox.Show("The pallet was split.", "Success");
            this.Close();
        }
        private void SavePutAwayItems()
        {
            PalletLocation pl = new PalletLocation();
            Pallet pallet = new Pallet();
            foreach (DataRow rw in _dtPutAwayPalletized.Rows)
            {
                pl.LoadByPrimaryKey(Convert.ToInt32(rw["PutAwayLocation"]));
                if (pl.IsColumnNull("PalletID"))
                {
                    pl.PalletID = GetPalletID(rw["PalletNumber"].ToString());
                    pl.Confirmed = false;
                    pallet.LoadByPrimaryKey(pl.PalletID);
                    pl.UsedVolume = pallet.CalculateCurrentVolume(pl.PalletID);
                    pl.Save();
                }
                else
                {

                }
            }
        }
        /// <summary>
        /// Moves the specified pick list ID.
        /// </summary>
        /// <param name="PickListID">The pick list ID.</param>
        public static void Move(int PickListID)
        {
            DataView       dv = GetTransferReportForStore();
            PalletLocation pl = new PalletLocation();

            foreach (DataRowView dr in dv)
            {
                int amount           = Convert.ToInt32(dr["packs"]);
                int palletLocationID = Convert.ToInt32(dr["PalletLocationID"]);

                ReceivePallet rp   = new ReceivePallet();
                ReceiveDoc    rdoc = new ReceiveDoc();

                rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                rdoc.LoadByPrimaryKey(rp.ReceiveID);
                amount *= rdoc.QtyPerPack;

                int qPalletLocationID = PalletLocation.GetTransferPalletLocation(Convert.ToInt32(dr["PhysicalStoreID"]));
                pl.LoadByPrimaryKey(qPalletLocationID);
                if (pl.IsColumnNull("PalletID"))
                {
                    Pallet p = new Pallet();
                    p.AddNew();
                    p.StorageTypeID = Convert.ToInt32(StorageType.Quaranteen);
                    p.Save();
                    pl.PalletID = p.ID;
                    pl.Save();
                }


                ReceivePallet rp2 = new ReceivePallet();
                ReceiveDoc    rd  = new ReceiveDoc();


                rd.LoadByPrimaryKey(rp.ReceiveID);
                rp2.AddNew();

                rp2.PalletID  = pl.PalletID;
                rp2.ReceiveID = rp.ReceiveID;


                // calculate the new balance
                BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                //im.LoadDefaultReceiving(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]));
                if (dr["BoxLevel"] == DBNull.Value)
                {
                    dr["BoxLevel"] = 0;
                }
                im.LoadIMbyLevel(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]), Convert.ToInt32(dr["BoxLevel"]));
                int packqty = (amount / im.QuantityInBasicUnit);
                rp2.ReservedStock = 0;
                rp.ReservedStock -= amount;
                BLL.ReceivePallet.MoveBalance(rp, rp2, amount);
                //rp2.Balance = amount;
                //rp.Balance -= rp2.Balance;

                //rp.Save();
                //rp2.Save();

                pl.Confirmed = false;
                pl.Save();
                if (rp.Balance == 0)
                {
                    PalletLocation.GarbageCollection();
                }
            }
        }
        /// <summary>
        /// Moves the specified pick list ID.
        /// </summary>
        /// <param name="PickListID">The pick list ID.</param>
        public static void Move(int PickListID)
        {
            DataView dv = GetTransferReportForStore();
            PalletLocation pl = new PalletLocation();
            foreach (DataRowView dr in dv)
            {

                int amount = Convert.ToInt32(dr["packs"]);
                int palletLocationID = Convert.ToInt32(dr["PalletLocationID"]);

                ReceivePallet rp = new ReceivePallet();
                ReceiveDoc rdoc = new ReceiveDoc();

                rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                rdoc.LoadByPrimaryKey(rp.ReceiveID);
                amount *= rdoc.QtyPerPack;

                int qPalletLocationID = PalletLocation.GetTransferPalletLocation(Convert.ToInt32(dr["PhysicalStoreID"]));
                pl.LoadByPrimaryKey(qPalletLocationID);
                if (pl.IsColumnNull("PalletID"))
                {
                    Pallet p = new Pallet();
                    p.AddNew();
                    p.StorageTypeID = Convert.ToInt32(StorageType.Quaranteen);
                    p.Save();
                    pl.PalletID = p.ID;
                    pl.Save();
                }

                ReceivePallet rp2 = new ReceivePallet();
                ReceiveDoc rd = new ReceiveDoc();

                rd.LoadByPrimaryKey(rp.ReceiveID);
                rp2.AddNew();

                rp2.PalletID = pl.PalletID;
                rp2.ReceiveID = rp.ReceiveID;

                // calculate the new balance
                BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                //im.LoadDefaultReceiving(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]));
                if (dr["BoxLevel"] == DBNull.Value)
                {
                    dr["BoxLevel"] = 0;
                }
                im.LoadIMbyLevel(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]), Convert.ToInt32(dr["BoxLevel"]));
                int packqty = (amount / im.QuantityInBasicUnit);
                rp2.ReservedStock = 0;
                rp.ReservedStock -= amount;
                BLL.ReceivePallet.MoveBalance(rp, rp2, amount);
                //rp2.Balance = amount;
                //rp.Balance -= rp2.Balance;

                //rp.Save();
                //rp2.Save();

                pl.Confirmed = false;
                pl.Save();
                if (rp.Balance == 0)
                {
                    PalletLocation.GarbageCollection();
                }

            }
        }
        private void btnCommit_Click(object sender, EventArgs e)
        {
            if (ValidateQuarantine())
            {

                MyGeneration.dOOdads.TransactionMgr transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
                transaction.BeginTransaction();
                if (DialogResult.Yes == XtraMessageBox.Show("Are you sure you want to commit the Loss and Adjustment on this screen?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    // do the actual commit here.
                    int printNubmer = InternalTransfer.GetNewPrintNumber() + 1;
                    PalletLocation pl = new PalletLocation();
                    Pallet p = new Pallet();
                    ReceiveDoc rdoc = new ReceiveDoc();
                    ReceivePallet rp = new ReceivePallet();
                    for (int i = 0; i < gridView1.RowCount; i++)
                    {
                        DataRow dr = gridView1.GetDataRow(i);
                        Double writeoff = 0;
                        Double reLocate = 0;
                        try
                        {
                            if (dr["WriteOff"] != DBNull.Value)
                            {
                                writeoff = Double.Parse(dr["WriteOff"].ToString());
                            }
                            if (dr["ReLocate"] != DBNull.Value)
                            {
                                reLocate = Double.Parse(dr["ReLocate"].ToString());
                            }
                        }
                        catch (Exception exc)
                        {
                        }

                        if(dr["WriteOff"] != DBNull.Value & writeoff>0)
                        {
                            if (Double.Parse(dr["WriteOff"].ToString()) > Double.Parse(dr["Balance"].ToString()))
                            {
                                XtraMessageBox.Show("Couldn't commit to the numbers you specified. Please specify number less than the balance.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            int writeoffAmout = Convert.ToInt32(dr["WriteOff"]);
                            int qtyPerPack = Convert.ToInt32(dr["QtyPerPack"]);
                            writeoffAmout *= qtyPerPack;
                            rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                            rdoc.LoadByPrimaryKey(rp.ReceiveID);
                            string x = dr["NewPalletLocation"].ToString();
                            rp.Balance -= writeoffAmout;
                            try
                            {
                              //  rp.ReceivedQuantity -= writeoffAmout;
                            }
                            catch { }
                            rdoc.QuantityLeft -= writeoffAmout;

                             ReceivePallet nrp =new ReceivePallet();
                             nrp.AddNew();
                             nrp.ReceiveID = rp.ReceiveID;
                             nrp.PalletID = pl.GetpalletidbyPalletLocationOrgetnew(int.Parse(dr["NewPalletLocation"].ToString()));
                            //nrp.ReceivedQuantity = rp.ReceivedQuantity;
                            nrp.Balance = writeoffAmout;
                            nrp.ReservedStock = 0;
                            //nrp.ReserveOrderID = rp.ReserveOrderID;
                            nrp.BoxSize = rp.BoxSize;
                            nrp.PalletLocationID = int.Parse(dr["NewPalletLocation"].ToString());
                            nrp.IsOriginalReceive = rp.IsOriginalReceive;

                            BLL.LossAndAdjustment d = new BLL.LossAndAdjustment();
                            d.AddNew();
                            d.GenerateRefNo();
                            d.ItemID = Convert.ToInt32(dr["ItemID"]);
                            d.ReasonId = Convert.ToInt32(dr["Reason"]);
                            d.RecID = rdoc.ID;
                            d.Quantity = writeoffAmout;
                            d.BatchNo = rdoc.BatchNo;

                            CalendarLib.DateTimePickerEx edate = new CalendarLib.DateTimePickerEx();
                            edate.Value = DateTime.Today;
                            //TODO: fix to an ethiopian date here
                            edate.CustomFormat = "MM/dd/yyyy";

                            d.Date = ConvertDate.DateConverter(edate.Text);

                            d.EurDate = DateTime.Today;
                             d.Cost = rdoc.IsColumnNull("Cost")? 0: Math.Abs(rdoc.Cost * writeoffAmout);
                            d.StoreId = rdoc.StoreID;
                            d.Losses = true;
                            //todo:
                            d.ApprovedBy = CurrentContext.UserId.ToString();
                            //d.Remarks

                             InternalTransfer it =new  InternalTransfer();
                             it.AddNew();
                            it.ItemID = d.ItemID;
                            it.FromPalletLocationID = pl.GetPalletLocationIDByPalletID(int.Parse(dr["PalletID"].ToString()));
                            it.ToPalletLocationID = nrp.PalletLocationID;
                            it.BatchNumber = d.BatchNo;
                            if (!rdoc.IsColumnNull("ExpDate"))
                            {
                                it.ExpireDate = rdoc.ExpDate;
                            }
                            it.ReceiveDocID = rdoc.ID;
                            it.ManufacturerID = rdoc.ManufacturerId;
                            it.QtyPerPack = Convert.ToInt32(dr["QtyPerPack"]);
                            it.Packs = rdoc.NoOfPack;
                            it.QuantityInBU = nrp.Balance;

                            LossAndAdjustmentReason r = new LossAndAdjustmentReason();
                            it.Type = r.GetReasonByID(d.ReasonId);

                           // d.Save();
                            rdoc.Save();
                            rp.Save();

                            rdoc.QuantityLeft += writeoffAmout;
                             rdoc.Save();
                             nrp.Save();
                             it.Save();
                            int xs = it.ID;
                        }
                        else if (dr["ReLocate"] != DBNull.Value & reLocate > 0)
                         {

                             if (dr["ReLocate"] != DBNull.Value)
                             {
                                 int amount = Convert.ToInt32(dr["ReLocate"]);
                                 int qtyPerPack = Convert.ToInt32(dr["QtyPerPack"]);
                                 amount *= qtyPerPack;
                                 rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                                 rdoc.LoadByPrimaryKey(rp.ReceiveID);
                                 int palletLocationID = Convert.ToInt32(dr["PalletLocationID"]);

                                 int qPalletLocationID =
                                     PalletLocation.GetQuaranteenPalletLocationByPalletLocationID(palletLocationID);//PalletLocation.GetQuaranteenPalletLocation(Convert.ToInt32(dr["ID"]));
                                 pl.LoadByPrimaryKey(qPalletLocationID);

                                 ReceivePallet rp2 = new ReceivePallet();
                                 ReceiveDoc rd = new ReceiveDoc();
                                 Pallet pallet = new Pallet();
                                 rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                                 rd.LoadByPrimaryKey(rp.ReceiveID);
                                 pallet.AddNew();
                                 Item item = new Item();
                                 item.LoadByPrimaryKey(rdoc.ItemID);
                                 if (item.StorageTypeID.ToString() == StorageType.BulkStore)
                                 {
                                     pallet.PalletNo = Pallet.GetLastPanelNumber();

                                 }
                                 pallet.Save();
                                 rp2.AddNew();
                                 rp2.PalletID = pl.GetpalletidbyPalletLocationOrgetnew(int.Parse(dr["NewPalletLocation"].ToString()));//pallet.ID;
                                 rp2.ReceiveID = rp.ReceiveID;
                                 rp2.IsOriginalReceive = rp.IsOriginalReceive;
                                 // calculate the new balance
                                 BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                                 //im.LoadDefaultReceiving(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]));
                                 //im.LoadIMbyLevel(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]), Convert.ToInt32(dr["BoxLevel"]));
                                 //int packqty = (amount / im.QuantityInBasicUnit);
                                 rd.QuantityLeft -= amount;
                                 rp.Balance -= amount;
                                rd.Save();
                                rp.Save();

                                 rd.QuantityLeft += amount;
                                 rp2.Balance = amount;//packqty * im.QuantityInBasicUnit;
                                 rd.Save();

                                 rp2.BoxSize = rp.BoxSize;
                                 rp2.ReservedStock = 0;
                                 rp2.PalletLocationID= int.Parse(dr["NewPalletLocation"].ToString());
                                 rp2.Save();

                                 pl.Confirmed = false;
                                 pl.Save();

                                 // select the new pallet location here.
                              /*   XtraForm xdb = new XtraForm();
                                 xdb.Controls.Add(panelControl2);
                                 Item itms= new Item();
                                 itms.GetItemByPrimaryKey(Convert.ToInt32(dr["ItemID"]));
                                 lblItemName.Text = itms.FullItemName;
                                 panelControl2.Visible = true;
                                 panelControl2.Dock = DockStyle.Fill;
                                 xdb.Text = "Select Location for relocated Item";
                                 lkLocation.Properties.DataSource = PalletLocation.GetAllFreeFor(Convert.ToInt32(dr["ItemID"]));
                                 xdb.ShowDialog();

                                 PalletLocation pl2 = new PalletLocation();
                                 pl2.LoadByPrimaryKey(Convert.ToInt32(lkLocation.EditValue));
                                 pl2.PalletID = pallet.ID;
                                 pl2.Confirmed = false;
                                 pl2.Save();
                                 */
                                 InternalTransfer it = new InternalTransfer();

                                 it.AddNew();
                                 it.ItemID = rd.ItemID;
                                 it.BoxLevel = 0;// im.PackageLevel;
                                 //it.ExpireDate = rd.ExpDate;
                                 if (!rd.IsColumnNull("ExpDate"))
                                 {
                                     it.ExpireDate = rd.ExpDate;
                                 }
                                 it.BatchNumber = rd.BatchNo;
                                 it.ManufacturerID = Convert.ToInt32(dr["ManufacturerID"]);//im.ManufacturerID;
                                 it.FromPalletLocationID = qPalletLocationID;
                                 it.ToPalletLocationID = int.Parse(dr["NewPalletLocation"].ToString()); //pl2.ID;
                                 it.QtyPerPack = 1;
                                //it.Packs = pack qty;
                                 it.ReceiveDocID = rp.ReceiveID;
                                 it.QuantityInBU = amount;// it.QtyPerPack;
                                 it.Type = "ReLocation";
                                 it.IssuedDate = DateTime.Today;
                                 it.Status = 0;
                                 it.PrintNumber = printNubmer;
                                 it.Save();
                             }
                         }
                    }
                    transaction.CommitTransaction();
                    BindQuarantine();
                    XtraMessageBox.Show("Quarantine Write off/Adjustment was commitd.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        private void repositoryItemButtonEdit1_DoubleClick(object sender, EventArgs e)
        {
            Pallet pallet = new Pallet();
            PalletLocation pl = new PalletLocation();
            if (gridItemMovementView.FocusedValue != null )
            {
                prev = gridItemMovementView.FocusedValue;
                pl.LoadByPrimaryKey(Convert.ToInt32(gridItemMovementView.FocusedValue));
                if (!pl.IsColumnNull("PalletID"))
                {
                    pallet.GetAllItemsInPallet(pl.PalletID);
                    gridControl2.DataSource = pallet.DefaultView;
                    pallet.GetAllItemsInPalletSKUTotal(pl.PalletID);
                    Label l = new Label();
                    l.Dock = DockStyle.Bottom;

                    XtraForm f = new XtraForm();
                    //gridControl2.Parent = null;
                    f.ShowInTaskbar = false;
                    f.Width = gridControl2.Width;
                    if (pallet.RowCount > 0 && !pallet.IsColumnNull("Total"))
                    {

                        l.Text = string.Format("Total SKU: {0}", pallet.GetColumn("Total").ToString());
                    }
                    else
                    {
                        l.Text = "Total SKU: 0";
                    }
                    f.Controls.Add(l);

                    pallet.LoadByPrimaryKey(pl.PalletID);
                    if (!pallet.IsColumnNull("PalletNo"))
                    {
                        f.Text = String.Format("Pallet Number: {0}", pallet.PalletNo);

                    }
                    f.Controls.Add(gridControl2);

                    f.StartPosition = FormStartPosition.CenterScreen;
                    f.ShowDialog();
                }
            }
        }
        /// <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);
        }