private void PopulateItems()
        {
            Item itm = new Item();

            itm.GetItemByPrimaryKey(this._itemID);
            if (itm.IsColumnNull("StorageTypeID"))
            {
                itm.StorageTypeID = 1;
                itm.Save();
            }
            if (itm.StorageTypeID.ToString() == StorageType.BulkStore && !itm.IsColumnNull("IsStackStored") && itm.IsStackStored)
            {
                layoutStackedView.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            }
            else
            {
                layoutStackedView.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            }


            lblItemName.Text = itm.FullItemName;
            BLL.ItemManufacturer imfr = new BLL.ItemManufacturer();
            imfr.LoadManufacturersFor(this._itemID);
            lstManufacturers.DataSource = imfr.DefaultView;
            itemUnit.LoadAllForItem(_itemID);
            gridUnits.DataSource = itemUnit.DefaultView;
        }
        private void btnAddManufacturer_Click(object sender, EventArgs e)
        {
            Dialogs.AddManufacturerForItem amfi = new HCMIS.Desktop.Dialogs.AddManufacturerForItem(_itemID);
            DialogResult dr = amfi.ShowDialog();
            if (DialogResult.Yes ==dr)
            {
                int manufID = amfi.SelectedManufacturer;
                Manufacturer manufacturer = new Manufacturer();
                manufacturer.LoadByPrimaryKey(manufID);

                BLL.ItemManufacturer imm = new BLL.ItemManufacturer();
                imm.LoadManufacturerItemRelationsFor(_itemID, manufID);
                if (imm.RowCount > 0)
                {

                }
                else
                {
                    imm.AddNew();
                    imm.ItemID = _itemID;
                    imm.ManufacturerID = manufID;
                    imm.BoxHeight = 1;
                    imm.BoxLength = 1;
                    imm.BoxWidth = 1;
                    imm.PackageLevel = 0;
                    imm.RecevingDefault = false;
                    imm.QuantityPerLevel = 1;
                    imm.Save();
                }
                im.LoadManufacturersFor(_itemID);
                this.lstManufacturers.DataSource = im.DefaultView;
            }
        }
        private void btnRemoveLevel_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete this Package Level?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
                DataRowView          drv = (DataRowView)lstLevel.SelectedItems[0];
                String SelectedID        = drv["ID"].ToString();

                imf.LoadByPrimaryKey(Convert.ToInt32(SelectedID));

                if (imf.HasDependants())
                {
                    XtraMessageBox.Show("This Item Manufacturer cannot be deleted because there are other box levels that depend on it.", "Deleting is not allowed.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (imf.HasReceives())
                {
                    XtraMessageBox.Show("This Item Manufacturer Cannot be Deleted because there are items that were received with this manufacturer item composition.", "Deleting is not allowed.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                imf.MarkAsDeleted();

                imf.Save();

                //refresh the window
                imf.LoadManufacturersFor(this._itemID);
                lstManufacturers.DataSource = imf.DefaultView;

                lstManufacturers_SelectedIndexChanged(null, null);
            }
        }
        /// <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);
        }
        /// <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;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Checks if a level has dependent levels
        /// </summary>
        /// <returns></returns>
        public bool HasDependants()
        {
            ItemManufacturer imf = new ItemManufacturer();

            imf.LoadIMbyLevel(this.ItemID, this.ManufacturerID, this.PackageLevel + 1);
            return(imf.RowCount > 0);
        }
        private void btnAddManufacturer_Click(object sender, EventArgs e)
        {
            Dialogs.AddManufacturerForItem amfi = new HCMIS.Desktop.Dialogs.AddManufacturerForItem(_itemID);
            DialogResult dr = amfi.ShowDialog();

            if (DialogResult.Yes == dr)
            {
                int          manufID      = amfi.SelectedManufacturer;
                Manufacturer manufacturer = new Manufacturer();
                manufacturer.LoadByPrimaryKey(manufID);

                BLL.ItemManufacturer imm = new BLL.ItemManufacturer();
                imm.LoadManufacturerItemRelationsFor(_itemID, manufID);
                if (imm.RowCount > 0)
                {
                }
                else
                {
                    imm.AddNew();
                    imm.ItemID           = _itemID;
                    imm.ManufacturerID   = manufID;
                    imm.BoxHeight        = 1;
                    imm.BoxLength        = 1;
                    imm.BoxWidth         = 1;
                    imm.PackageLevel     = 0;
                    imm.RecevingDefault  = false;
                    imm.QuantityPerLevel = 1;
                    imm.Save();
                }
                im.LoadManufacturersFor(_itemID);
                this.lstManufacturers.DataSource = im.DefaultView;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Checks if the loaded item manufacturer has had receives done
        /// </summary>
        /// <returns></returns>
        public bool HasReceives()
        {
            ItemManufacturer imf = new ItemManufacturer();
            var query            = HCMIS.Repository.Queries.ItemManufacturer.SelectHasReceives(this.ItemID, this.ManufacturerID);

            imf.LoadFromRawSql(query);
            return(imf.RowCount > 0);
        }
 private void LoadManufacturerForSelectedItem()
 {
     BLL.ItemManufacturer itemManufacturer = new BLL.ItemManufacturer();
     if (ShowOnlyReceivedManufacturer)
     {
         itemManufacturer.LoadManufactuererByItemWithReceive(ItemID);
     }
     lkManufacturer.Properties.DataSource = itemManufacturer.DefaultView;
 }
Exemplo n.º 10
0
        /// <summary>
        /// Enables changing the SKU of a product mid flight
        /// This should only be available to the administrator who could do it more carefully.
        /// </summary>
        /// <param name="itemID"></param>
        /// <param name="manufacturerID"></param>
        /// <param name="level"></param>
        /// <param name="newQuantity"></param>
        public static void ChangeSKU(int itemID, int manufacturerID, int level, int newQuantity)
        {
            // preserve the old SKU
            ItemManufacturer imf = new ItemManufacturer();

            imf.LoadIMbyLevel(itemID, manufacturerID, level);
            int previousQuantityPerLevel = imf.QuantityPerLevel;

            if (level == 0)
            {
                // change the SKU Unit
                imf.QuantityPerLevel = newQuantity;
                imf.Save();

                // change the received Qty Per pack

                var query = HCMIS.Repository.Queries.ItemManufacturer.UpdateChangeSKU(itemID, manufacturerID, newQuantity, previousQuantityPerLevel);


                imf.LoadFromRawSql(query);


                // Update Issue Doc
                query = HCMIS.Repository.Queries.ItemManufacturer.UpdateChangeSKUIssueDoc(itemID, manufacturerID, newQuantity, previousQuantityPerLevel);
                imf.LoadFromRawSql(query);

                // Update disposal table
                query =
                    HCMIS.Repository.Queries.ItemManufacturer.UpdateChangeSKULossAndAdjustment(itemID, manufacturerID, newQuantity, previousQuantityPerLevel);
                imf.LoadFromRawSql(query);
                // update the Receive Pallet
                query =
                    HCMIS.Repository.Queries.ItemManufacturer.UpdateChangeSKUReceivePallet(itemID, manufacturerID, newQuantity, previousQuantityPerLevel);

                imf.LoadFromRawSql(query);

                // Update Pick Face
                //TODO:

                // Update Order.
                // this is a bit tricky, it is better to not update it and ask the user to make sure
                // that they don't have an outstanding order with the item that is about to be changed.
                // Update Pick List.
                query =
                    HCMIS.Repository.Queries.ItemManufacturer.UpdateChangeSKUPickListDetail(itemID, manufacturerID, newQuantity, previousQuantityPerLevel);

                imf.LoadFromRawSql(query);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Get the basic units found in the most probable next supplied item
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <returns></returns>
        public static int GetDefaultBuInSKU(int itemId)
        {
            ItemManufacturer im = new ItemManufacturer();

            im.LoadDefaultSKUItemManufacturer(itemId);

            // check if there is atleast one manufacturer which has supplied the given item.
            if (im.RowCount > 0)
            {
                return(im.QuantityInBasicUnit);
            }
            else
            {
                return(1);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        ///  Saves a level as Default Receiving Package level
        ///  This is depreciated
        /// </summary>
        public void SaveReceivingDefault()
        {
            if (!this.RecevingDefault)
            {
                int id = this.ID;
                ItemManufacturer im = new ItemManufacturer();
                im.LoadFromRawSql(HCMIS.Repository.Queries.ItemManufacturer.UpdateSaveReceivingDefault(this.ItemID, this.ManufacturerID));

                this.RecevingDefault = true;
                this.Save();
                this.LoadManufacturerItemRelationsFor(this.ItemID, this.ManufacturerID);
            }
            else
            {
                this.RecevingDefault = true;
                this.Save();
            }
        }
        /// <summary>
        /// Gets replenishment list for item id in logical store storeid
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <param name="storeId">The store id.</param>
        /// <returns></returns>
        public DataTable GetReplenishmentListFor(int itemId, int storeId)
        {
            PalletLocation.CalculateAllVolumes(itemId);
            string query = HCMIS.Repository.Queries.PickFace.SelectGetReplenishmentListFor(itemId, storeId, StorageType.BulkStore);

            this.LoadFromRawSql(query);
            this.DataTable.Columns.Add("SKU", typeof(int));
            this.DataTable.Columns.Add("CanReplenish", typeof(bool));
            ItemManufacturer im  = new ItemManufacturer();
            DateTime         exp = new DateTime();
            int boxsize          = -1;
            int j = 0;

            while (!this.EOF)
            {
                if (j == 0)
                {
                    this.SetColumn("CanReplenish", true);
                    boxsize = Convert.ToInt32(this.GetColumn("BoxSize"));
                    if (!this.IsColumnNull("ExpiryDate"))
                    {
                        exp = Convert.ToDateTime(this.GetColumn("ExpiryDate"));
                    }
                }
                else
                {
                    int bs = Convert.ToInt32(this.GetColumn("BoxSize"));
                    if (bs < boxsize && exp.Subtract(Convert.ToDateTime(this.GetColumn("ExpiryDate"))).Days == 0)
                    {
                        this.SetColumn("CanReplenish", true);
                    }
                    else
                    {
                        this.SetColumn("CanReplenish", false);
                    }
                }
                j++;
                im.LoadIMbyLevel(Convert.ToInt32(this.GetColumn("ItemID")), Convert.ToInt32(this.GetColumn("ManufacturerID")), 0);
                int i = Convert.ToInt32(this.GetColumn("Balance"));
                this.SetColumn("SKU", i / im.QuantityInBasicUnit);
                this.MoveNext();
            }
            return(this.DataTable);
        }
Exemplo n.º 14
0
        private void returnToBulkStoreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataRow dr = gridPickFaceDetailView.GetFocusedDataRow();

            if (dr != null)
            {
                int           ReceivePalletID = Convert.ToInt32(dr["ID"]);
                ReceivePallet rp = new ReceivePallet();
                rp.LoadByPrimaryKey(ReceivePalletID);

                ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByPrimaryKey(rp.ReceiveID);

                BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
                imf.LoadIMbyLevel(rd.ItemID, rd.ManufacturerId, rp.BoxSize);

                int QuantityToReturn  = Convert.ToInt32(((rp.Balance - rp.ReservedStock) / imf.QuantityInBasicUnit) * imf.QuantityInBasicUnit);
                InternalTransfer itfr = new InternalTransfer();
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Gets picked order detail for item (Used by the IssueLog)
        /// </summary>
        /// <param name="ordID"></param>
        /// <param name="storeid"></param>
        /// <param name="pricedItems">True - For Priced Items Only, False - For Delivery Notes Only</param>
        /// <returns></returns>
        public DataView GetPickedOrderDetailForOrder(int stvLogID, bool includeDeleted)//,bool pricedItems)
        {
            string query;

            // remove this line ...
            // check if this has changed the dn to stv conversion
            // (pld.DeliveryNote is null or pld.DeliveryNote = 0 or (pld.DeliveryNote=1 and pld.UnitPrice<>0)) and
            query = HCMIS.Repository.Queries.PickList.SelectGetPickedOrderDetailForOrder(stvLogID);
            if (includeDeleted)
            {
                query = HCMIS.Repository.Queries.PickList.SelectGetPickedOrderDetailForOrderIncludeDeleted(stvLogID);
            }



            this.LoadFromRawSql(query);
            // Add important columns
            this.DataTable.Columns.Add("SKUTOPICK", typeof(int));
            this.DataTable.Columns.Add("SKUPICKED", typeof(int));
            this.DataTable.Columns.Add("BUPICKED", typeof(int));
            this.DataTable.Columns.Add("BoxSizeDisplay");
            this.DataTable.Columns.Add("SKUBU", typeof(int));
            this.DataTable.Columns.Add("IsManufacturerLocal", typeof(bool));
            this.DataTable.Columns.Add("PrintedSTVNumber", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreName", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreTypeID", typeof(int));
            this.DataTable.Columns.Add("PhysicalStoreTypeName", typeof(string));

            ItemManufacturer im = new ItemManufacturer();
            int i = 1;

            while (!this.EOF)
            {
                int          packs        = Convert.ToInt32(this.GetColumn("Packs"));
                int          manufacturer = Convert.ToInt32(this.GetColumn("ManufacturerID"));
                Manufacturer m            = new Manufacturer();
                m.LoadByPrimaryKey(manufacturer);
                if (!m.IsColumnNull("CountryOfOrigin") && m.CountryOfOrigin == "Ethiopia")
                {
                    this.SetColumn("IsManufacturerLocal", true);
                }
                else
                {
                    this.SetColumn("IsManufacturerLocal", false);
                }

                int           recPalletID = Convert.ToInt32(this.GetColumn("ReceivePalletID"));
                ReceivePallet rp          = new ReceivePallet();
                rp.LoadByPrimaryKey(recPalletID);
                try
                {
                    this.SetColumn("PhysicalStoreName", rp.GetPhysicalStoreName());
                    int physicalStoreTypeID = rp.GetPhysicalStoreTypeID();
                    this.SetColumn("PhysicalStoreTypeID", physicalStoreTypeID);
                    Warehouse phyStoreType = new Warehouse();
                    phyStoreType.LoadByPrimaryKey(physicalStoreTypeID);
                    this.SetColumn("PhysicalStoreTypeName", phyStoreType.Name);
                }
                catch
                {
                }

                int itemId     = Convert.ToInt32(this.GetColumn("ItemID"));
                int boxLevel   = Convert.ToInt32(this.GetColumn("BoxLevel"));
                int qtyPerPack = this.Getint("QtyPerPack");
                //im.LoadIMbyLevel(itemId, manufacturer, boxLevel);
                this.SetColumn("SKUTOPICK", (packs));
                this.SetColumn("SKUPICKED", this.GetColumn("SKUTOPICK"));
                // TODO:show the box size here for Program store
                this.SetColumn("BoxSizeDisplay", "");
                this.SetColumn("SKUBU", qtyPerPack);
                this.SetColumn("BUPICKED", qtyPerPack * Convert.ToInt32(this.GetColumn("SKUPICKED")));
                this.SetColumn("LineNum", i++);
                this.MoveNext();
            }
            return(this.DefaultView);
        }
        /// <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();
                    }
                }
            }
        }
        /// <summary>
        /// Generate the pick list
        /// </summary>
        /// <param name="orderId">The order id.</param>
        /// <param name="bgWorker">The bg worker.</param>
        /// <returns></returns>
        public DataView GetPalletLocationChoice(int userID, int orderId, BackgroundWorker bgWorker)
        {
            var order = new Order();
            // Load the order

            order.LoadByPrimaryKey(orderId);
            //TODO: check if the order is already approved or not.
            // if not please return from here
            // Load the order details
            var orderDetail = new OrderDetail();
            orderDetail.LoadAllByOrderID(orderId);
            orderDetail.AddColumn("ActivityConcat", typeof(string));
            // prepare the pick list data table with the proper fields
            _pickList = GetPickListTable();
            _replenishmentList = new DataTable();
            _replenishmentList.Columns.Add("ItemID", typeof(int));
            _replenishmentList.Columns.Add("StoreID", typeof(int));

            int count = 0;

            // iterate through the order detail and make the pick list
            while (!orderDetail.EOF)
            {
                DateTime startTime = DateTime.Now;
                System.Console.WriteLine("Processing - " + orderDetail.ItemID);
                // check if there are enough priced items of the same or more quantity in the store
                int? unitID = null;
                if (!orderDetail.IsColumnNull("UnitID"))
                {
                    unitID = orderDetail.UnitID;
                }

                if (!orderDetail.IsColumnNull("StockedOut") && (!orderDetail.StockedOut ||(orderDetail.ApprovedQuantity > 0 && orderDetail.Quantity > orderDetail.ApprovedQuantity)))
                {
                    DateTime? preferredExpiry = new DateTime();

                    if (orderDetail.IsColumnNull("PreferredManufacturerID"))
                        orderDetail.PreferredManufacturerID = -1;

                    if (orderDetail.IsColumnNull("PreferredPhysicalStoreID"))
                        orderDetail.PreferredPhysicalStoreID = -1;

                    if (orderDetail.IsColumnNull("PreferredExpiryDate"))
                        preferredExpiry = null;
                    else
                    {
                        preferredExpiry = orderDetail.PreferredExpiryDate;
                    }
                    if (!orderDetail.IsColumnNull("ApprovedQuantity") && (orderDetail.ApprovedQuantity > 0 && !orderDetail.IsColumnNull("StoreID")))
                    {
                        AddToPickListFor(userID, orderDetail.ID, orderDetail.ItemID, unitID, orderDetail.ApprovedQuantity, orderDetail.StoreID,
                                         orderDetail.PreferredManufacturerID, orderDetail.PreferredPhysicalStoreID,
                                         !orderDetail.IsColumnNull("DeliveryNote") && orderDetail.DeliveryNote,
                                         preferredExpiry);
                    }

                }
                System.Console.WriteLine(string.Format("Took - {0}:{1} for Item ID = {2}", DateTime.Now.Subtract(startTime).Minutes, DateTime.Now.Subtract(startTime).Seconds, orderDetail.ItemID));
                orderDetail.MoveNext();
                count++;
                bgWorker.ReportProgress(count, null);
            }

            // A quick hack just to show the pallet location on the order form

            var pl = new PalletLocation();
            var im = new ItemManufacturer();
            foreach (DataRowView drv in _pickList.DefaultView)
            {
                int plid = Convert.ToInt32(drv["PalletLocationID"]);
                pl.LoadByPrimaryKey(plid);
                drv["PalletLocation"] = pl.FullName;
                im.LoadIMbyLevel(Convert.ToInt32(drv["ItemID"]), Convert.ToInt32(drv["ManufacturerID"]),
                                 Convert.ToInt32(drv["BoxLevel"]));
                drv["QtyInSKU"] = im.RowCount > 0
                                     ? Convert.ToDecimal(drv["Pack"]) * im.QuantityInSku
                                     : Convert.ToDecimal(drv["Pack"]);
                drv["BoxSizeDisplay"] = im.RowCount > 0 ? im.LevelView2 : ""; //im.RightName;
                drv["WarehouseName"] = pl.WarehouseName;
                drv["PhysicalStoreName"] = pl.PhysicalStoreName;
                var activity = new Activity();
                activity.LoadByPrimaryKey(Convert.ToInt32(drv["StoreID"]));
                drv["ActivityConcat"] = activity.FullActivityName;
                drv["AccountName"] = activity.AccountName;
            }

            //foreach (DataRowView v in _pickList.DefaultView)
            //{

            //}

            return _pickList.DefaultView;
        }
        /// <summary>
        /// Needs to be the first function to be called when saving a new receive doc entry.
        /// </summary>
        /// <param name="rec"></param>
        /// <param name="receiptID"></param>
        /// <param name="dr"></param>
        private void FillInReceiveDocInformation(ReceiveDoc rec, int receiptID, DataRowView dr)
        {
            try
            {
                rec.GetColumn("GUID");
            }
            catch
            {
                rec.AddColumn("GUID", typeof(string));
                //rec.AddColumn("IsDamaged", typeof(bool));
                //This is only used if the Check box is used to receive damaged receives (For SRM only)
            }

            rec.StoreID = Convert.ToInt32(lkAccounts.EditValue);
            rec.RefNo = txtRefNo.Text;
            rec.Remark = txtRemark.Text;

            rec.ReceivedBy = CurrentContext.LoggedInUserName;

            DateTime xx = dtRecDate.Value;
            dtRecDate.CustomFormat = "MM/dd/yyyy";
            DateTime dtRec = new DateTime();
            rec.Date = ConvertDate.DateConverter(dtRecDate.Text);
            dtRec = ConvertDate.DateConverter(dtRecDate.Text);
            rec.EurDate = BLL.DateTimeHelper.ServerDateTime;
            rec.ItemID = Convert.ToInt32(dr["ID"]);
            rec.NoOfPack = Convert.ToDecimal(dr["Pack Qty"]);
            rec.SetColumn("GUID", dr["GUID"].ToString());
            rec.IsDamaged = Convert.ToBoolean(dr["IsDamaged"]);

            if (standardRecType == StandardReceiptType.iGRVOnline)
            {
                rec.SetColumn("PricePerPack", dr["Price/Pack"]);
                rec.SetColumn("Margin", dr["Margin"]);
                rec.SetColumn("UnitCost", dr["Price/Pack"]);
            }

            //TODO: This if is a garbage. Remove
            if (dr["InvoicedQty"] == DBNull.Value)
            {
                rec.InvoicedNoOfPack = rec.NoOfPack;
            }

            rec.InvoicedNoOfPack = srm ? Convert.ToDecimal(dr["IssuedQty"]) : Convert.ToDecimal(dr["OriginalInvoicedQty"]);

            rec.ManufacturerId = Convert.ToInt32(dr["Manufacturer"]);
            BLL.ItemManufacturer im = new BLL.ItemManufacturer();

            im.LoadIMbyLevel(rec.ItemID, rec.ManufacturerId, 0);
            if (dr["UnitID"] != DBNull.Value)
            {
                // if unit has been set, pick the qty per pack from the unit
                rec.UnitID = Convert.ToInt32(dr["UnitID"]);
                ItemUnit itemUnit = new ItemUnit();
                itemUnit.LoadByPrimaryKey(rec.UnitID);

                rec.QtyPerPack = itemUnit.QtyPerUnit;
            }
            else
            {
                rec.QtyPerPack = im.QuantityInBasicUnit;
            }
            rec.Quantity = rec.QuantityLeft = rec.NoOfPack * rec.QtyPerPack;

            try
            {
                if ((deliveryNoteType == DeliveryNoteType.NotSet))
                {
                    if (!BLL.Settings.HandleGRV && !srm)
                    {
                        rec.PricePerPack = Convert.ToDouble(dr["Price/Pack"]);
                        double pre = (Convert.ToDouble(dr["Price/Pack"]) / 1); //rec.QtyPerPack);
                        rec.Cost = pre;
                    }
                    rec.DeliveryNote = false;
                }
                else
                {
                    rec.DeliveryNote = true;
                    if (deliveryNoteType == DeliveryNoteType.Automatic)
                    {
                        rec.SetColumn("PricePerPack", dr["Price/Pack"]);
                        rec.SetColumn("Margin", dr["Margin"]);
                        rec.SetColumn("UnitCost", dr["Price/Pack"]);
                    }
                }
            }
            catch
            {
                // catch the error if the recieve doesn't have cost information
                // NOTE: this shall never happen.
            }

            if (dr["Batch No"] != DBNull.Value)
            {
                rec.BatchNo = dr["Batch No"].ToString(); // receivingGrid.Rows[i].Cells[8].Value.ToString();
            }

            if (dr["Expiry Date"] != DBNull.Value)
            {
                rec.ExpDate = Convert.ToDateTime(dr["Expiry Date"]); //receivingGrid.Rows[i].Cells[9].Value);
            }

            if (!srm)
            {
                rec.SupplierID = _supplierID;
            }
            else
            {
                rec.SupplierID = BLL.Supplier.CONSTANTS.RETURNED_FROM_FACILITY;
                //TODO: Returned From Supplier: To be removed.  This is an unacceptable hack.
                rec.RefNo = lkSTVInvoiceNo.Text;
                if (string.IsNullOrEmpty(txtRemark.Text))
                {
                    XtraMessageBox.Show(
                        "Please enter the reason for the SRM.", "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    throw new Exception("Reason not entered for SRM");
                }
                else
                {
                    rec.Remark = txtRemark.Text;
                }
            }

            rec.ReturnedStock = srm;

            if (srm && !chkSRMForOldSystemIssues.Checked)
            {
                rec.ReturnedFromIssueDocID = int.Parse(dr["IssueDocID"].ToString());
                int issueDocID = int.Parse(dr["IssueDocID"].ToString());
                BLL.IssueDoc iss = new IssueDoc();
                iss.LoadByPrimaryKey(issueDocID);
                BLL.ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByPrimaryKey(iss.RecievDocID);
                //If it was a delivery note, then the return will not have price information associated with it.

                // HW-2189
                decimal? UnitCost, SellingPrice, Margin;
                UnitCost = SellingPrice = Margin = null;

                if (!BLL.Settings.HandleGRV)
                {
                    if (!iss.IsColumnNull("UnitCost") && iss.IsColumnNull("SellingPrice"))
                    {
                        UnitCost = iss.UnitCost;
                        SellingPrice = iss.SellingPrice;
                        Margin = !iss.IsColumnNull("Margin") ? iss.Margin : 0;
                    }
                    else if (!iss.IsColumnNull("Cost"))
                    {
                        Margin = !rd.IsColumnNull("Margin") ? Convert.ToDecimal(rd.Margin) : 0;
                        SellingPrice = Convert.ToDecimal(iss.Cost / Convert.ToDouble(iss.NoOfPack));
                        UnitCost = BLL.Settings.IsCenter ? SellingPrice : SellingPrice / Convert.ToDecimal(Margin + 1);
                    }
                }
                else
                {
                    if (!iss.IsColumnNull("UnitCost") && iss.IsColumnNull("SellingPrice") && iss.UnitCost != 0 &&
                        iss.SellingPrice != 0)
                    {
                        UnitCost = iss.UnitCost;
                        SellingPrice = iss.SellingPrice;
                        Margin = !iss.IsColumnNull("Margin") ? iss.Margin : 0;
                    }
                    else if (!iss.IsColumnNull("Cost") && iss.Cost != 0)
                    {
                        Margin = !rd.IsColumnNull("Margin") ? Convert.ToDecimal(rd.Margin) : 0;
                        SellingPrice = Convert.ToDecimal(iss.Cost / Convert.ToDouble(iss.NoOfPack));
                        UnitCost = BLL.Settings.IsCenter ? SellingPrice : SellingPrice / Convert.ToDecimal(Margin + 1);
                    }
                }

                if (UnitCost.HasValue)
                {
                    rec.PricePerPack = Convert.ToDouble(UnitCost);
                    rec.Cost = Convert.ToDouble(UnitCost);
                    rec.UnitCost = UnitCost.Value;
                }

                if (SellingPrice.HasValue)
                {
                    rec.SellingPrice = Convert.ToDouble(SellingPrice);
                }

                if (Margin.HasValue)
                {
                    rec.Margin = Convert.ToDouble(Margin);
                }

                if (!rd.IsColumnNull("SupplierID"))
                    rec.SupplierID = rd.SupplierID;
            }

            rec.ReceiptID = receiptID;
            if (BLL.Settings.HandleGRV && !beginningBalance)
            {
                rec.RefNo = receiptID.ToString();
            }
            else if (beginningBalance)
            {
                rec.RefNo = "BeginningBalance";
            }

            //Needs to be fixed! Garbage
            string batch = DateTimeHelper.ServerDateTime.Day.ToString() + DateTimeHelper.ServerDateTime.Hour.ToString() +
                           DateTimeHelper.ServerDateTime.Minute.ToString() + rec.ItemID.ToString();
            rec.LocalBatchNo = batch;
            rec.Out = false;
            rec.IsApproved = false;
            if (dr["ShortageReasonID"] != DBNull.Value)
            {
                rec.ShortageReasonID = Convert.ToInt32(dr["ShortageReasonID"]);
            }
            var item = new Item();
            item.LoadByPrimaryKey(Convert.ToInt32(dr["id"]));

            if (dr["ShortageReasonID"] == DBNull.Value && (item.NeedExpiryBatch || rec.ExpDate <= DateTimeHelper.ServerDateTime))
            {
                rec.ShortageReasonID = ShortageReasons.Constants.DAMAGED;
            }

            dtRecDate.Value = xx;
            _receiptID = receiptID; //Assign it to the global variable so it can be used later on.
        }
        //, 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 PopulateListToGrid()
        {
            Item itm = new Item();

            if (_dtRecGrid.Columns.Count == 0)
            {
                string[] str =
                {
                    "ID", "Stock Code", "Item Name", "BoxLevel", "Unit", "Price/Pack", "Manufacturer",
                    "Batch No", "Expiry Date", "BasicUnitPerQ", "LevelView2"
                };
                foreach (string col in str)
                {
                    if (col.Contains("Date"))
                        _dtRecGrid.Columns.Add(col, typeof(DateTime));
                    else
                        _dtRecGrid.Columns.Add(col);
                }

                _dtRecGrid.Columns.Add("BU Qty", typeof (decimal));
                _dtRecGrid.Columns.Add("Pack Qty", typeof (decimal));
                _dtRecGrid.Columns.Add("NotReceived", typeof(decimal));
                _dtRecGrid.Columns.Add("IsDamaged", typeof (bool));
                _dtRecGrid.Columns.Add("Ordering", typeof (int));

                _dtRecGrid.Columns.Add("PalletComposition");
                _dtRecGrid.Columns.Add("PC", typeof(DataTable));
                _dtRecGrid.Columns.Add("UnitID", typeof(int));
                _dtRecGrid.Columns.Add("IssuedQty");
                _dtRecGrid.Columns.Add("IssueDocID"); //For srm only
                _dtRecGrid.Columns.Add("InvoicedQty", typeof(decimal));
                _dtRecGrid.Columns.Add("OriginalInvoicedQty", typeof(decimal));
                _dtRecGrid.Columns.Add("RemainingQty"); //For hasPreviousReceive is True
                _dtRecGrid.Columns.Add("StockCode");
                _dtRecGrid.Columns.Add("GUID");
                _dtRecGrid.Columns.Add("Margin");
                _dtRecGrid.Columns.Add("ShortageReasonID", typeof(int));

                _dtRecGrid.Columns.Add("Copy", typeof (string));
                _dtRecGrid.Columns.Add("CopyGUID");
                _dtRecGrid.Columns.Add("IsCopied",typeof(bool));
                    //this column will be used during splitting an Item on a Draft receive.
                _dtRecGrid.Columns.Add("Store", typeof (string));
            }

            int count = 1;
            // Bind the manufacturer editor
            BLL.Manufacturer mfs = new Manufacturer();
            BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
            mfs.LoadAll();
            editManufacturer.DataSource = mfs.DefaultView;

            editManuf2.DataSource = mfs.DefaultView;
            editManuf3.DataSource = mfs.DefaultView;
            EditRecivingBoxLevels.DataSource = BLL.ItemManufacturer.PackageLevelKeys;
            DataTable dtbl = (DataTable)gridSelected.DataSource;

            //bool srm = false;
            srm = Convert.ToInt32(cboReceiveType.EditValue) == ReceiptType.CONSTANTS.STOCK_RETURN;

            foreach (DataRow lst in dtbl.Rows)
            {

                if (lst["IsSelected"] == DBNull.Value || Convert.ToBoolean(lst["IsSelected"]))
                {
                    string itemName = lst["FullItemName"].ToString();

                    bool validateSRM = srm && !chkSRMForOldSystemIssues.Checked;

                    DataRow dr = _dtRecGrid.NewRow();
                    dr["ID"] = lst["ID"];
                    dr["StockCode"] = dr["Stock Code"] =lst["StockCode"];
                    dr["Item Name"] = itemName;

                    if (validateSRM || hasPreviousReceive || (standardRecType == StandardReceiptType.iGRVOnline) ||
                        (deliveryNoteType == DeliveryNoteType.Automatic))
                    {
                        dr["Unit"] = lst["Unit"];
                        dr["Manufacturer"] = lst["ManufacturerID"];
                        dr["Batch No"] = lst["BatchNo"];
                        dr["UnitID"] = lst["UnitID"];
                        dr["Expiry Date"] = lst["ExpDate"];
                        if (validateSRM)
                        {
                            dr["IssuedQty"] = lst["IssuedQty"];
                            dr["IssueDocID"] = lst["IssueDocID"];
                        }
                        if (hasPreviousReceive)
                        {
                            dr["OriginalInvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["InvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["RemainingQty"] = lst["RemainingQty"];
                        }
                        if (standardRecType == StandardReceiptType.iGRVOnline)
                        {
                            dr["OriginalInvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["InvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["Price/Pack"] = lst["UnitPrice"];
                            dr["Margin"] = lst["Margin"];
                        }
                        if (deliveryNoteType == DeliveryNoteType.Automatic)
                        {
                            dr["OriginalInvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["InvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["Price/Pack"] = lst["UnitPrice"];
                            dr["Margin"] = lst["Margin"];
                        }
                    }

                    count++;
                    lst["IsSelected"] = false;

                    dr["Ordering"] = _LastOrdering++;
                    dr["GUID"] = Guid.NewGuid();
                    dr["Copy"] = "Orginal";
                    dr["IsCopied"] = false;
                    dr["CopyGUID"] = Guid.NewGuid();
                    dr["IsDamaged"] = false;
                    _dtRecGrid.Rows.Add(dr);

                }
            }
            _dtRecGrid.DefaultView.Sort = "Ordering";
            receivingGrid.DataSource = _dtRecGrid.DefaultView;

            repoLkEditNotReceivedReason.DataSource = BLL.ShortageReasons.GetAllReasons();
            if (srm)
            {
                lcRemark.Text = "Reason for SRM";
            }
            dtRecDate.CustomFormat = "MMM dd,yyyy";
        }
        private void OnAnyCellValueChangedOnRecieveGrid(object sender,CellValueChangedEventArgs e)
        {
            var invoiceNo = lkReceiptInvoice.Text;
            var IsElectronic = ReceiptInvoice.IsInvoiceElectronic(invoiceNo);

            GridView view = sender as GridView;
            // make general calculations
            gridRecieveView.RefreshData();
            DataRow dr = gridRecieveView.GetFocusedDataRow();
            dr.ClearErrors();

            int manufid = Convert.ToInt32(dr["Manufacturer"]);
            int itemid = Convert.ToInt32(dr["ID"]);
            int unitid = Convert.ToInt32(dr["UnitID"]);
            string batchNofilter = (Convert.ToString(dr["Batch No"]).Equals("")) ? "" : string.Format(" And [Batch No] = '{0}'", Convert.ToString(dr["Batch No"]));
            string filterString = string.Format(
                "ID = '{0}' AND UnitID = '{1}' AND Manufacturer = '{2}' {3} ", itemid, unitid, manufid, batchNofilter);

            if (dr["Manufacturer"] != DBNull.Value && dr["Manufacturer"] != null && dr["Manufacturer"].ToString() != "")
            {
                BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                im.LoadIMbyLevel(itemid, manufid, 0);
                im.LoadDefaultReceiving(itemid, manufid);
                //dr["Manufacturer"] = manufid;
                dr["BoxLevel"] = im.PackageLevel;
                dr["BasicUnitPerQ"] = im.QuantityInBasicUnit;
                if (dr["Pack Qty"] != DBNull.Value && dr["Pack Qty"] != string.Empty)
                    dr["BU Qty"] = (im.QuantityInBasicUnit * Convert.ToDecimal(dr["Pack Qty"]));
                dr["LevelView2"] = im.LevelView2;
            }

            if ((view.FocusedColumn.FieldName == "Manufacturer") || (view.FocusedColumn.FieldName == "Pack Qty"))
            {
                SuggestComposition();
            }

            //if the item is expired then it's considered as damaged
            if (dr["Expiry Date"] != DBNull.Value &&
                Convert.ToDateTime(dr["Expiry Date"]) <= DateTimeHelper.ServerDateTime)
            {
                dr["IsDamaged"] = true;
            }

            decimal invoicedQty = 0;
            decimal receivedQty = 0;
            decimal difference = 0;
            decimal remainingQty = 0;

            if (dr["InvoicedQty"] != DBNull.Value && dr["Pack Qty"] != DBNull.Value && dr["Pack Qty"] != string.Empty)
            {
                var receiveGridDataSource = (gridRecieveView.DataSource as DataView).ToTable();
                var invRows = receiveGridDataSource.Select(filterString);

                invoicedQty = invRows.Sum(r => r.Field<decimal>("OriginalInvoicedQty"));

                var rows = receiveGridDataSource.Select(filterString);

                receivedQty = rows.CopyToDataTable().Select("[Pack Qty] IS NOT NULL").Sum(r => r.Field<decimal>("Pack Qty"));

                difference = invoicedQty - receivedQty;

                //update NotReceivedColumn
                _dtRecGrid.Select(filterString).ToList<DataRow>().ForEach(r => r["NotReceived"] = difference);

                if (!BLL.Settings.AllowBonusReceive && hasPreviousReceive && dr["RemainingQty"] != DBNull.Value)
                {
                    remainingQty = Convert.ToDecimal(dr["RemainingQty"]);
                    if (remainingQty - receivedQty < 0)
                    {
                        dr.SetColumnError("Pack Qty", "Unable to receive a quantity more than remaining Qty ");
                        dr["Pack Qty"] = DBNull.Value;
                        difference = 0;
                    }
                }

            }
            if (srm && Convert.ToBoolean(dr["IsDamaged"]))
            {
                dr["ShortageReasonID"] = ShortageReasons.Constants.DAMAGED;
            }

            if (difference > 0)
            {
                //int invoicedQty = Convert.ToInt32(dr["InvoicedQty"]);
                //int receivedQty = Convert.ToInt32(dr["Pack Qty"]);
                //int difference = invoicedQty - receivedQty;
                DataTable filteredTbl;
                DataRow newDataRow = null;

                lcShortageOrDamage.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                DataTable tbl = _dtRecGrid.Clone();

                bool notEntered = true;

                if (grdShortageOrDamaged.DataSource != null && (grdShortageOrDamaged.DataSource as DataTable).Rows.Count != 0)
                {
                    //tbl = ((DataView) grdViewShortageOrDamaged.DataSource).ToTable();
                    var dataView = (DataTable) grdShortageOrDamaged.DataSource;

                    DataRow[] filteredTable = dataView.Select(filterString);

                    if (filteredTable.Length > 0) //If the item/row is already in the descrepancy grid
                    {
                        notEntered = false;
                        //TODO: We're using the first one for now.  If there are more than one.  Needs to be handled.

                        foreach (DataRow drShortages in filteredTable)
                        {
                            if (filteredTable.Length == 1)
                            {
                                drShortages["Pack Qty"] = difference;
                            }
                            else
                            {
                                drShortages["Pack Qty"] = DBNull.Value;
                            }

                            newDataRow = drShortages;

                            //drShortages["Pack Qty"] = difference; //Commented out because we don't want to change user modified values.
                            drShortages["ManufacturerName"] = editManufacturer.GetDisplayText(dr["Manufacturer"]);
                            drShortages["UnitText"] = editUnits.GetDisplayText(dr["UnitID"]);
                            drShortages["UnitID"] = dr["UnitID"];
                            drShortages["Unit"] = dr["Unit"];
                            drShortages["Batch No"] = dr["Batch No"];
                            drShortages["Expiry Date"] = dr["Expiry Date"];
                            drShortages["Item Name"] = dr["Item Name"];
                            drShortages["Stock Code"] = dr["Stock Code"];
                            drShortages["Manufacturer"] = dr["Manufacturer"];
                            drShortages["ID"] = dr["ID"];
                            drShortages["GUID"] = dr["GUID"];

                        }
                    }
                }

                if (grdShortageOrDamaged.DataSource != null && (grdShortageOrDamaged.DataSource as DataTable).Rows.Count == 0 || notEntered)
                {
                    if (grdViewShortageOrDamaged.DataSource != null)
                        tbl = ((DataView)grdViewShortageOrDamaged.DataSource).ToTable();

                    if (!tbl.Columns.Contains(("ShortageReasonID")))
                    {
                        tbl.Columns.Add("ShortageReasonID", typeof(int));
                    }
                    if (!tbl.Columns.Contains("ManufacturerName"))
                    {
                        tbl.Columns.Add("ManufacturerName");
                    }
                    if (!tbl.Columns.Contains("UnitText"))
                    {
                        tbl.Columns.Add("UnitText");
                    }
                }

                bool isNewRow = false;

                if (newDataRow == null)
                {
                    dr.EndEdit();
                    if (tbl != null)
                    {
                        var rows = tbl.Select(filterString);
                        isNewRow = rows.Count() == 0;
                    }
                    if (tbl == null || isNewRow)
                    {
                        tbl.ImportRow(dr);
                        newDataRow = tbl.Rows[tbl.Rows.Count - 1];
                        newDataRow["Pack Qty"] = difference;
                        newDataRow["ManufacturerName"] = editManufacturer.GetDisplayText(dr["Manufacturer"]);
                        newDataRow["UnitText"] = editUnits.GetDisplayText(dr["UnitID"]);

                    }
                }

                if (hasPreviousReceive && difference > 0 && difference == (invoicedQty - remainingQty))
                {
                    newDataRow["ShortageReasonID"] = BLL.ShortageReasons.Constants.NOT_RECEIVED;
                }

                if (tbl.Rows.Count != 0)
                {
                    foreach (DataRow d in tbl.Rows)
                    {
                        d["IsDamaged"] = true;
                        d["OriginalInvoicedQty"] = 0;
                    }
                    grdShortageOrDamaged.DataSource = tbl;
                }

            }

            else if (difference == 0 && grdViewShortageOrDamaged.RowCount != 0)
            {
                       RemoveFromDiscrepancyByFilter(filterString);
            }
        }
        /// <summary>
        ///  Saves a level as Default Receiving Package level
        ///  This is depreciated
        /// </summary>
        public void SaveReceivingDefault()
        {
            if (!this.RecevingDefault)
            {
                int id = this.ID;
                ItemManufacturer im = new ItemManufacturer();
                im.LoadFromRawSql(HCMIS.Repository.Queries.ItemManufacturer.UpdateSaveReceivingDefault(this.ItemID, this.ManufacturerID));

                this.RecevingDefault = true;
                this.Save();
                this.LoadManufacturerItemRelationsFor(this.ItemID, this.ManufacturerID);
            }
            else
            {
                this.RecevingDefault = true;
                this.Save();
            }
        }
 /// <summary>
 /// Checks if the loaded item manufacturer has had receives done
 /// </summary>
 /// <returns></returns>
 public bool HasReceives()
 {
     ItemManufacturer imf = new ItemManufacturer();
     var query = HCMIS.Repository.Queries.ItemManufacturer.SelectHasReceives(this.ItemID, this.ManufacturerID);
     imf.LoadFromRawSql(query);
     return (imf.RowCount > 0);
 }
 /// <summary>
 /// Checks if a level has dependent levels
 /// </summary>
 /// <returns></returns>
 public bool HasDependants()
 {
     ItemManufacturer imf = new ItemManufacturer();
     imf.LoadIMbyLevel(this.ItemID, this.ManufacturerID, this.PackageLevel + 1);
     return (imf.RowCount > 0);
 }
        /// <summary>
        /// Get the basic units found in the most probable next supplied item
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <returns></returns>
        public static int GetDefaultBuInSKU(int itemId)
        {
            ItemManufacturer im = new ItemManufacturer();
            im.LoadDefaultSKUItemManufacturer(itemId);

            // check if there is atleast one manufacturer which has supplied the given item.
            if (im.RowCount > 0)
            {
                return im.QuantityInBasicUnit;
            }
            else
            {
                return 1;
            }
        }
        /// <summary>
        /// Enables changing the SKU of a product mid flight
        /// This should only be available to the administrator who could do it more carefully.
        /// </summary>
        /// <param name="itemID"></param>
        /// <param name="manufacturerID"></param>
        /// <param name="level"></param>
        /// <param name="newQuantity"></param>
        public static void ChangeSKU(int itemID, int manufacturerID,int level, int newQuantity)
        {
            // preserve the old SKU
               ItemManufacturer imf = new ItemManufacturer();
            imf.LoadIMbyLevel(itemID,manufacturerID,level);
            int previousQuantityPerLevel = imf.QuantityPerLevel;

            if(level == 0)
            {
                // change the SKU Unit
                imf.QuantityPerLevel = newQuantity;
                imf.Save();

                // change the received Qty Per pack

                var query = HCMIS.Repository.Queries.ItemManufacturer.UpdateChangeSKU(itemID, manufacturerID, newQuantity, previousQuantityPerLevel);

                imf.LoadFromRawSql(query);

                // Update Issue Doc
                query = HCMIS.Repository.Queries.ItemManufacturer.UpdateChangeSKUIssueDoc(itemID, manufacturerID, newQuantity, previousQuantityPerLevel);
                imf.LoadFromRawSql(query);

                // Update disposal table
                query =
                    HCMIS.Repository.Queries.ItemManufacturer.UpdateChangeSKULossAndAdjustment(itemID, manufacturerID, newQuantity, previousQuantityPerLevel);
                imf.LoadFromRawSql(query);
                // update the Receive Pallet
                query =
                    HCMIS.Repository.Queries.ItemManufacturer.UpdateChangeSKUReceivePallet(itemID, manufacturerID, newQuantity, previousQuantityPerLevel);

                imf.LoadFromRawSql(query);

                // Update Pick Face
                //TODO:

                // Update Order.
                // this is a bit tricky, it is better to not update it and ask the user to make sure
                // that they don't have an outstanding order with the item that is about to be changed.
                // Update Pick List.
                query =
                    HCMIS.Repository.Queries.ItemManufacturer.UpdateChangeSKUPickListDetail(itemID, manufacturerID, newQuantity, previousQuantityPerLevel);

                imf.LoadFromRawSql(query);

            }
        }
        private void OnSaveItemManufacturerClick(object sender, EventArgs e)
        {
            _isSaving = true;

            BLL.Item itm = new Item();

            if (im.RowCount > 0)
            {
                double divider = GetDivider();

                // Save the metric data
                im.BoxHeight = Convert.ToDouble(txtHeight.Text) / divider;
                im.BoxLength = Convert.ToDouble(txtLength.Text) / divider;
                im.BoxWidth  = Convert.ToDouble(txtWidth.Text) / divider;
                // validate if someone is attempting to change the SKU after it has been used.
                //
                if (im.PackageLevel == 0)
                {
                    BLL.ItemManufacturer imff = new BLL.ItemManufacturer();
                    imff.LoadIMbyLevel(im.ItemID, im.ManufacturerID, 0);
                    if (imff.HasReceives() && !Settings.IsRdfMode)
                    {
                        if (!Settings.IsRdfMode)
                        {
                            if (XtraMessageBox.Show("Are you sure you want change this level and all the received data along with it?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                // Do the logic that changes the SKU.
                                BLL.ItemManufacturer.ChangeSKU(im.ItemID, im.ManufacturerID, 0,
                                                               Convert.ToInt32(txtQuantity.Text));
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show("You cannot change an SKU for an Item that has already been Received using this quantity. Please contact the administrator for such changes.", "Changing a used SKU not allowed");
                            return;
                        }
                    }
                }

                im.QuantityPerLevel = Convert.ToInt32(txtQuantity.Text);

                if (im.QuantityPerLevel <= 0)
                {
                    im.QuantityPerLevel = 1;
                }

                im.Save();
                if (chkDefault.Checked)
                {
                    im.SaveReceivingDefault();
                }

                itm.LoadByPrimaryKey(_itemID);
                if (itm.StorageTypeID.ToString() == StorageType.BulkStore && !itm.IsColumnNull("IsStackStored") && itm.IsStackStored)
                {
                    BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
                    imf.SaveStackStored(_itemID, im.ManufacturerID, Convert.ToDouble(txtStackedHeight.EditValue));
                }
                SaveItemUnits();
                XtraMessageBox.Show("Your changes have been saved.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            _isSaving = false;
            OnPackageLevelSelected(new object(), new EventArgs());
        }
        private void PopulateItems()
        {
            Item itm = new Item();
            itm.GetItemByPrimaryKey(this._itemID);
            if (itm.IsColumnNull("StorageTypeID"))
            {
                itm.StorageTypeID = 1;
                itm.Save();
            }
            if (itm.StorageTypeID.ToString() == StorageType.BulkStore && !itm.IsColumnNull("IsStackStored") && itm.IsStackStored)
            {
                layoutStackedView.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            }
            else
                layoutStackedView.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;

            lblItemName.Text = itm.FullItemName;
            BLL.ItemManufacturer imfr = new BLL.ItemManufacturer();
            imfr.LoadManufacturersFor(this._itemID);
            lstManufacturers.DataSource = imfr.DefaultView;
            itemUnit.LoadAllForItem(_itemID);
            gridUnits.DataSource = itemUnit.DefaultView;
        }
        private void OnSaveItemManufacturerClick(object sender, EventArgs e)
        {
            _isSaving = true;

            BLL.Item itm = new Item();

            if (im.RowCount > 0)
            {
                double divider = GetDivider();

                // Save the metric data
                im.BoxHeight = Convert.ToDouble(txtHeight.Text) / divider;
                im.BoxLength = Convert.ToDouble(txtLength.Text) / divider;
                im.BoxWidth = Convert.ToDouble(txtWidth.Text) / divider;
                // validate if someone is attempting to change the SKU after it has been used.
                //
                if (im.PackageLevel == 0)
                {
                    BLL.ItemManufacturer imff = new BLL.ItemManufacturer();
                    imff.LoadIMbyLevel(im.ItemID, im.ManufacturerID, 0);
                    if (imff.HasReceives() && !Settings.IsRdfMode)
                    {
                        if(!Settings.IsRdfMode)
                        {
                           if(XtraMessageBox.Show("Are you sure you want change this level and all the received data along with it?","Confirmation",MessageBoxButtons.YesNo) == DialogResult.Yes)
                           {
                               // Do the logic that changes the SKU.
                               BLL.ItemManufacturer.ChangeSKU(im.ItemID, im.ManufacturerID,0,
                                                              Convert.ToInt32(txtQuantity.Text));
                           }
                        }
                        else
                        {
                            XtraMessageBox.Show("You cannot change an SKU for an Item that has already been Received using this quantity. Please contact the administrator for such changes.","Changing a used SKU not allowed");
                            return;
                        }
                    }
                }

                im.QuantityPerLevel = Convert.ToInt32(txtQuantity.Text);

                if (im.QuantityPerLevel <= 0)
                {
                    im.QuantityPerLevel = 1;
                }

                im.Save();
                if (chkDefault.Checked)
                {
                    im.SaveReceivingDefault();
                }

                itm.LoadByPrimaryKey( _itemID );
                if (itm.StorageTypeID.ToString() == StorageType.BulkStore && !itm.IsColumnNull("IsStackStored") && itm.IsStackStored)
                {
                    BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
                    imf.SaveStackStored( _itemID, im.ManufacturerID, Convert.ToDouble(txtStackedHeight.EditValue));
                }
                SaveItemUnits();
                XtraMessageBox.Show("Your changes have been saved.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            _isSaving = false;
               OnPackageLevelSelected(new object(), new EventArgs());
        }
 internal void UpdateComposition(DataTable dataTable)
 {
     DataRow dr = gridRecieveView.GetFocusedDataRow();
     BLL.ItemManufacturer im = new BLL.ItemManufacturer();
     dr["PC"] = dataTable;
     dr["PalletComposition"] = im.ConvertCompositionToString(dataTable);
 }
Exemplo n.º 31
0
        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 void OnAnyPopupOpenedOnRecieveGrid(object sender, EventArgs e)
        {
            GridView view = sender as GridView;

            if (view.FocusedColumn.FieldName == "UnitID")
            {
                LookUpEdit lke = (LookUpEdit)view.ActiveEditor;
                lke.EditValue = null;
                DataRow dr = gridRecieveView.GetDataRow(gridRecieveView.GetSelectedRows()[0]);
                int id = Convert.ToInt32(dr["ID"]);
                ItemUnit itemUnit = new ItemUnit();
                itemUnit.LoadAllForItem(id);
                lke.Properties.DataSource = itemUnit.DefaultView;
            }

            if (view.FocusedColumn.FieldName == "Manufacturer")
            {
                LookUpEdit lke = (LookUpEdit)view.ActiveEditor;
                lke.EditValue = null;
                DataRow dr = gridRecieveView.GetDataRow(gridRecieveView.GetSelectedRows()[0]);
                int id = Convert.ToInt32(dr["ID"]);
                Manufacturer mfs = new Manufacturer();
                mfs.LoadForItem(id);
                lke.Properties.DataSource = mfs.DefaultView;
            }
            if (view.FocusedColumn.FieldName == "BoxLevel")
            {
                LookUpEdit lke = (LookUpEdit)view.ActiveEditor;
                DataRow dr = gridRecieveView.GetDataRow(gridRecieveView.GetSelectedRows()[0]);
                int id = Convert.ToInt32(dr["ID"]);
                if (dr["Manufacturer"].ToString() != "")
                {
                    int manuf = Convert.ToInt32(dr["Manufacturer"]);
                    BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
                    lke.Properties.DataSource = imf.LoadLevelsFor2(id, manuf);
                }
                else
                {
                    lke.Properties.DataSource = null;
                }

            }
        }
        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 void CalculateVolumes()
        {
            BLL.ItemManufacturer im = new BLL.ItemManufacturer();

            foreach (DataRow dr in _dtPalletizedItemList.Rows)
            {
                //dr.EndEdit();

                int itemID = Convert.ToInt32(dr["ID"]);
                int manufID = Convert.ToInt32(dr["Manufacturer"]);
                int plevel = Convert.ToInt32(dr["BoxLevel"]);

                im.LoadManufacturerItemRelationsFor(itemID, manufID, plevel);
                double packQty = Convert.ToDouble(dr["Pack Qty"]);
                dr["Volume"] = (im.BoxHeight * im.BoxWidth * im.BoxLength * packQty);

            }

            foreach (DataRow dr in _dtNonPalletizedItemList.Rows)
            {

                int itemID = Convert.ToInt32(dr["ID"]);
                int manufID = Convert.ToInt32(dr["Manufacturer"]);
                int plevel = Convert.ToInt32(dr["BoxLevel"]);

                im.LoadManufacturerItemRelationsFor(itemID, manufID, plevel);
                dr["Volume"] = (im.BoxHeight * im.BoxWidth * im.BoxLength * Convert.ToDouble(dr["Pack Qty"]));

            }
        }
        private void EditReceived_Load(object sender, EventArgs e)
        {
            BLL.ItemManufacturer im = new BLL.ItemManufacturer();
            im.LoadManufacturersFor(rDoc.ItemID);
            lkManufacturer.Properties.DataSource = im.DefaultView;

            if (BLL.Settings.UseNewUserManagement && this.HasPermission("Edit-Quantity") && (rDoc.IsColumnNull("Confirmed") || (!rDoc.IsColumnNull("Confirmed") && !rDoc.Confirmed)))
            {
                txtQuanitity.Enabled = true;
            }
            else if ((!rDoc.IsColumnNull("Confirmed") && !rDoc.Confirmed))
            {
                txtQuanitity.Enabled = true;
            }
            else
            {
                txtQuanitity.Enabled = false;
            }
            Supplier supplier = new Supplier();

            supplier.LoadAll();
            lkSupplier.Properties.DataSource = supplier.DefaultView;

            lkAccount.SetupActivityEditor().SetDefaultActivity();
            BLL.ItemUnit iu = new ItemUnit();
            iu.LoadAllForItem(rDoc.ItemID);
            lkUnit.Properties.DataSource = iu.DefaultView;

            // Bind the variables)
            if (rDoc.RowCount > 0)
            {
                this.txtRefNo.Text     = rDoc.RefNo;
                this.txtQuanitity.Text =
                    Convert.ToInt32(Convert.ToDouble(rDoc.Quantity) / rDoc.QtyPerPack).ToString("#,##0");
                this.txtManufacturer.Text     = Manufacturer.GetName(rDoc.ManufacturerId);
                this.txtItemName.Text         = Item.GetName(rDoc.ItemID);
                this.txtGrvNo.Text            = rDoc.RefNo;
                this.lkManufacturer.EditValue = rDoc.ManufacturerId;
                this.lkAccount.EditValue      = rDoc.StoreID;
                this.lkUnit.EditValue         = rDoc.UnitID;

                if (!rDoc.IsColumnNull("SupplierID"))
                {
                    lkSupplier.EditValue = rDoc.SupplierID;
                }
                // Editable controls
                txtPrice.Text = rDoc.IsColumnNull("Cost") ? "0" : rDoc.Cost.ToString();
                if (!rDoc.IsColumnNull("ExpDate"))
                {
                    dtExpiry.EditValue = rDoc.ExpDate;
                }
                if (!rDoc.IsColumnNull("BatchNo"))
                {
                    txtBatchNo.Text = rDoc.BatchNo;
                }

                BLL.Item itm = new Item();
                itm.LoadByPrimaryKey(rDoc.ItemID);
                if (BLL.Settings.UseNewUserManagement && this.HasPermission("Edit-Batch-Expiry"))
                {
                }
                else if (!itm.NeedExpiryBatch &&
                         (CurrentContext.LoggedInUser.UserType == UserType.Constants.ADMIN ||
                          CurrentContext.LoggedInUser.UserType == UserType.Constants.SUPER_ADMINISTRATOR))
                {
                    btnRemoveExpiry.Enabled = true;
                    txtBatchNo.Enabled      = true;
                }
            }
        }
        private void SuggestComposition()
        {
            DataRow dr = gridRecieveView.GetDataRow(gridRecieveView.GetSelectedRows()[0]);
            if (dr["Pack Qty"].ToString() == "")
            {
                return;
            }
            decimal qty = Convert.ToDecimal(dr["Pack Qty"]);
            //if (qty > 0)
            //{

            if (dr["Manufacturer"] != null && dr["Manufacturer"].ToString() != "")
            {
                int manufID;
                int plevel;
                int itemId;

                try
                {
                    manufID = Convert.ToInt32(dr["Manufacturer"]);
                    plevel = Convert.ToInt32(dr["BoxLevel"]);
                    itemId = Convert.ToInt32(dr["ID"]);
                }
                catch
                {
                    return;
                }
                BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                im.LoadIMbyLevel(itemId, manufID, 0);
                dr["BU Qty"] = (im.QuantityInBasicUnit * qty);
                //dr["LevelView2"] = im.LevelView2;

                DataTable dtbl = im.SuggestComposition(itemId, manufID, qty);
                dr["PalletComposition"] = im.ConvertCompositionToString(dtbl);
                dr["PC"] = dtbl;
                //}
            }
        }
        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);
                }
            }
        }
        //,bool pricedItems)
        /// <summary>
        /// Gets picked order detail for item (Used by the IssueLog)
        /// </summary>
        /// <param name="ordID"></param>
        /// <param name="storeid"></param>
        /// <param name="pricedItems">True - For Priced Items Only, False - For Delivery Notes Only</param>
        /// <returns></returns>
        public DataView GetPickedOrderDetailForOrder(int stvLogID, bool includeDeleted)
        {
            string query;

            // remove this line ...
            // check if this has changed the dn to stv conversion
            // (pld.DeliveryNote is null or pld.DeliveryNote = 0 or (pld.DeliveryNote=1 and pld.UnitPrice<>0)) and
            query = HCMIS.Repository.Queries.PickList.SelectGetPickedOrderDetailForOrder(stvLogID);
            if (includeDeleted)
            {
                query = HCMIS.Repository.Queries.PickList.SelectGetPickedOrderDetailForOrderIncludeDeleted(stvLogID);
            }

            this.LoadFromRawSql(query);
            // Add important columns
            this.DataTable.Columns.Add("SKUTOPICK", typeof(int));
            this.DataTable.Columns.Add("SKUPICKED", typeof(int));
            this.DataTable.Columns.Add("BUPICKED", typeof(int));
            this.DataTable.Columns.Add("BoxSizeDisplay");
            this.DataTable.Columns.Add("SKUBU", typeof(int));
            this.DataTable.Columns.Add("IsManufacturerLocal", typeof(bool));
            this.DataTable.Columns.Add("PrintedSTVNumber", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreName", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreTypeID", typeof(int));
            this.DataTable.Columns.Add("PhysicalStoreTypeName", typeof(string));

            ItemManufacturer im = new ItemManufacturer();
            int i = 1;
            while (!this.EOF)
            {
                int packs = Convert.ToInt32(this.GetColumn("Packs"));
                int manufacturer = Convert.ToInt32(this.GetColumn("ManufacturerID"));
                Manufacturer m = new Manufacturer();
                m.LoadByPrimaryKey(manufacturer);
                if (!m.IsColumnNull("CountryOfOrigin") && m.CountryOfOrigin == "Ethiopia")
                    this.SetColumn("IsManufacturerLocal", true);
                else
                    this.SetColumn("IsManufacturerLocal", false);

                int recPalletID = Convert.ToInt32(this.GetColumn("ReceivePalletID"));
                ReceivePallet rp = new ReceivePallet();
                rp.LoadByPrimaryKey(recPalletID);
                try
                {
                    this.SetColumn("PhysicalStoreName", rp.GetPhysicalStoreName());
                    int physicalStoreTypeID = rp.GetPhysicalStoreTypeID();
                    this.SetColumn("PhysicalStoreTypeID", physicalStoreTypeID);
                    Warehouse phyStoreType = new Warehouse();
                    phyStoreType.LoadByPrimaryKey(physicalStoreTypeID);
                    this.SetColumn("PhysicalStoreTypeName", phyStoreType.Name);
                }
                catch
                {
                }

                int itemId = Convert.ToInt32(this.GetColumn("ItemID"));
                int boxLevel = Convert.ToInt32(this.GetColumn("BoxLevel"));
                int qtyPerPack = this.Getint("QtyPerPack");
                //im.LoadIMbyLevel(itemId, manufacturer, boxLevel);
                this.SetColumn("SKUTOPICK", (packs));
                this.SetColumn("SKUPICKED", this.GetColumn("SKUTOPICK"));
                // TODO:show the box size here for Program store
                this.SetColumn("BoxSizeDisplay", "");
                this.SetColumn("SKUBU", qtyPerPack);
                this.SetColumn("BUPICKED", qtyPerPack * Convert.ToInt32(this.GetColumn("SKUPICKED")));
                this.SetColumn("LineNum", i++);
                this.MoveNext();

            }
            return this.DefaultView;
        }
        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>
        /// 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();
            }
        }
        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);
                }
            }
        }
        /// <summary>
        /// Computes the stock calculations for an order detail.
        /// </summary>
        /// <param name="currentMonth">The current month.</param>
        /// <param name="currentYear">The current year.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="orderDetail">The order detail.</param>
        /// <returns></returns>
        public DataRow ComputeStockCalculationsForAnOrderDetail(int currentMonth, int currentYear, int userID, OrderDetail orderDetail)
        {
            if (!IsOrderDetailTableReady(orderDetail))
            {
                PrepareOrderDetailTable(orderDetail);
            }

            int? preferredManufacturer;
            int? preferredPhysicalStoreID;
            decimal usableStock;
            decimal approved;
            decimal availableQuantity;

            Balance bal = new Balance();
            ItemManufacturer imf = new ItemManufacturer();
            int? unitid = null;

            PriceSettings priceSettings = BLL.Settings.HandleDeliveryNotes ? PriceSettings.BOTH : PriceSettings.PRICED_ONLY;

            BLL.Order parentOrder = new Order();
            parentOrder.LoadByPrimaryKey(orderDetail.OrderID);

            unitid = orderDetail.UnitID;
            preferredManufacturer = orderDetail.IsColumnNull("PreferredManufacturerID") ? null : new int?(orderDetail.PreferredManufacturerID);
            preferredPhysicalStoreID = orderDetail.IsColumnNull("PreferredPhysicalStoreID") ? null : new int?(orderDetail.PreferredPhysicalStoreID);

            if (orderDetail.IsColumnNull("StoreID"))
            {
                orderDetail.StoreID = BLL.Activity.GetActivityUsingFEFO(this.FromStore, orderDetail.ItemID, orderDetail.UnitID);
                orderDetail.Save();
            }

            Activity storeObject = new Activity();
            availableQuantity = storeObject.LoadOptionsForOrderDetail(userID, orderDetail.ID, priceSettings, bal, false, out usableStock, out approved);
            orderDetail.SetColumn("AvailableStores", storeObject.DefaultView);
            if (storeObject.RowCount == 1)
            {

                orderDetail.StoreID = storeObject.ID;
                // Avoid error if the column IsDeliveryNote doesn't exsit at all.
                orderDetail.DeliveryNote = storeObject.DefaultView.Table.Columns.IndexOf("IsDeliveryNote") >= 0 &&
                                       !storeObject.IsColumnNull("IsDeliveryNote") &&
                                       Convert.ToBoolean(storeObject.GetColumn("IsDeliveryNote"));
                availableQuantity = Convert.ToDecimal(storeObject.GetColumn("AvailableSKU"));
            }
            else if (storeObject.RowCount > 1)
            {
                //TOCLEAN: Lord have mercy.
                //
                // check if the default activity is selected
                // if it has been selected, then do a good job and select it.
                storeObject.Rewind();

                while (
                            !storeObject.EOF
                            &&
                           (
                               (
                                    storeObject.ID == orderDetail.StoreID
                                        && !orderDetail.IsColumnNull("DeliveryNote")
                                        && orderDetail.DeliveryNote
                                        && !Convert.ToBoolean(storeObject.GetColumn("IsDeliveryNote"))
                               )
                               ||
                               storeObject.ID != orderDetail.StoreID
                          )
                   )
                {
                    storeObject.MoveNext();
                }

                // the selected store is found, don't worry.
                if (!storeObject.EOF)
                {
                    availableQuantity = Convert.ToDecimal(storeObject.GetColumn("AvailableSKU"));
                }
                else
                {
                    // the selected store is not found, please do select the first store.
                    storeObject.Rewind();
                    orderDetail.StoreID = storeObject.ID;
                    orderDetail.DeliveryNote = (storeObject.DefaultView.Table.Columns.IndexOf("IsDeliveryNote") >= 0 &&
                                                !storeObject.IsColumnNull("IsDeliveryNote") &&
                                                Convert.ToBoolean(storeObject.GetColumn("IsDeliveryNote")));
                    availableQuantity = Convert.ToDecimal(storeObject.GetColumn("AvailableSKU"));
                }
            }
            orderDetail.SetColumn("HasStores", (storeObject.RowCount > 1) ? "*" : "");
            // Precaution ... to hide -ve available quantity.
            if (availableQuantity < 0)
            {
                availableQuantity = 0;
            }

            orderDetail.StockedOut = availableQuantity <= 0;
            orderDetail.Save();

            int qinBu = 1;
            if (unitid.HasValue)
            {
                ItemUnit itemUnit = new ItemUnit();
                itemUnit.LoadByPrimaryKey(unitid.Value);
                qinBu = itemUnit.QtyPerUnit;

                //Checking if the columns from the vwGetAllItems have been filled in.
                var fullItemName = orderDetail.GetColumn("FullItemName").ToString();
                if (string.IsNullOrEmpty(fullItemName))
                {
                    BLL.Order temp = new Order();
                    temp.LoadFromRawSql(HCMIS.Repository.Queries.Order.SelectItemDetail(orderDetail.ItemID));
                    orderDetail.SetColumn("Unit", itemUnit.Text);
                    orderDetail.SetColumn("FullItemName", temp.GetColumn("FullItemName"));
                    orderDetail.SetColumn("StockCode", temp.GetColumn("StockCode"));
                    orderDetail.SetColumn("CategoryType", temp.GetColumn("CategoryType"));
                }
            }

            orderDetail.SetColumn("AvailableQuantity", availableQuantity);
            orderDetail.SetColumn("PricedQuantity", usableStock);

            if (orderDetail.IsColumnNull("ApprovedQuantity"))
            {
                if ((orderDetail.Quantity / ((long)qinBu)) < availableQuantity)
                {
                    orderDetail.ApprovedQuantity = orderDetail.Quantity;
                }
                else
                {
                    orderDetail.ApprovedQuantity = availableQuantity * qinBu;
                }
            }

            if (BLL.Settings.AllowPreferredManufacturers)
            {
                Manufacturer manuf = new Manufacturer();
                manuf.LoadForItem(orderDetail.ItemID, orderDetail.StoreID, orderDetail.UnitID, true);
                manuf.AddNew();
                manuf.ID = -1;
                manuf.Name = "Remove Preference";
                orderDetail.SetColumn("AvailableManufacturer", manuf.DefaultView);
                orderDetail.SetColumn("HasManufacturers", (manuf.RowCount > 2) ? "*" : "");

                if (manuf.RowCount == 2)
                {
                    manuf.Rewind();
                    orderDetail.PreferredManufacturerID = manuf.ID;
                }
            }

            if (BLL.Settings.AllowPreferredPhysicalStore)
            {
                PhysicalStore phyStore = new PhysicalStore();
                phyStore.LoadForItem(userID, orderDetail.ItemID, orderDetail.StoreID, orderDetail.UnitID);
                phyStore.AddNew();
                phyStore.Name = "Remove Preference";
                phyStore.ID = -1;
                orderDetail.SetColumn("AvailablePhysicalStore", phyStore.DefaultView);
                orderDetail.SetColumn("HasPhysicalStoreChoice", (phyStore.RowCount > 2) ? "*" : "");

                if (phyStore.RowCount == 2)
                {
                    phyStore.Rewind();
                    orderDetail.PreferredPhysicalStoreID = phyStore.ID;
                }
            }

            if (BLL.Settings.AllowPreferredExpiry)
            {
                ReceiveDoc rd = new ReceiveDoc();
                rd.LoadExpiryDatesForItem(orderDetail.ItemID, orderDetail.StoreID, orderDetail.UnitID, true, preferredManufacturer, preferredPhysicalStoreID);
                rd.AddNew();
                rd.SetColumn("ExpiryDateString", "Remove Preference");
                orderDetail.SetColumn("AvailableExpiry", rd.DefaultView);
                orderDetail.SetColumn("HasExpiryChoice", (rd.RowCount > 2) ? "*" : "");
                if (!orderDetail.IsColumnNull("PreferredExpiryDate"))
                {
                    DateTime expDate = orderDetail.PreferredExpiryDate;
                    string expDateStr = string.Format("{0}-{1:00}-{2:00}", expDate.Year, expDate.Month, expDate.Day, "");
                    orderDetail.SetColumn("ExpiryDateString", expDateStr);
                }
            }
            // do some reseting if the approved quanitty is greater than
            if (orderDetail.ApprovedQuantity / qinBu > availableQuantity)
            {
                orderDetail.ApprovedQuantity = availableQuantity * qinBu;
            }
            orderDetail.SetColumn("UsableStock", usableStock);
            orderDetail.SetColumn("PApprovedStock", approved);
            orderDetail.SetColumn("SKUBU", qinBu);
            orderDetail.SetColumn("AvailableSKU", availableQuantity);
            string TextID = ((orderDetail.IsColumnNull("DeliveryNote") || !orderDetail.DeliveryNote)
                                ? "N"
                                : "D") + orderDetail.StoreID.ToString();
            orderDetail.SetColumn("TextID", TextID);
            orderDetail.SetColumn("ApprovedSKU", orderDetail.ApprovedQuantity / Convert.ToDecimal(qinBu));
            orderDetail.SetColumn("RequestedSKU", orderDetail.Quantity / Convert.ToDecimal(qinBu));
            if (availableQuantity == 0)
            {
                orderDetail.SetColumnNull("TextID");
                orderDetail.SetColumnNull("StoreID");

            }
            Item itm = new Item();
            string warning = (itm.GetItemAllowStatus(orderDetail.ItemID, this.RequestedBy) == 0) ? "Warning" : "";
            orderDetail.SetColumn("Warning", warning);
            //if (!orderDetail.IsColumnNull("StoreID"))
            //{
                // var balance = new Balance();
                //balance.LoadQuantityNotReceive(orderDetail.ItemID, orderDetail.UnitID, parentOrder.FromStore);
                //var totalrequested =balance.GetTotalApprovedQuantityByItem(parentOrder.ID, orderDetail.ItemID, orderDetail.UnitID,parentOrder.FromStore);
                orderDetail.SetColumn("GIT", 0);
                orderDetail.SetColumn("CRequested",0);
                orderDetail.SetColumn("CApproved",0);
                //orderDetail.SetColumn("DOS", balance.DOS);
                //orderDetail.SetColumn("TotalIssued", balance.TotalIssued);
                //orderDetail.SetColumn("FiscalYearDays", balance.FiscalYearDays);

                //decimal amc = 0;
                //decimal mos = 0;

                //var totalissued = balance.TotalIssued;
                //var totaldatediff = balance.FiscalYearDays - balance.DOS;

                //if (totalissued != 0)
                //{
                //    amc = Convert.ToDecimal(totalissued / totaldatediff) * 30;
                //}

                //else if (amc == 0)
                //{
                //    mos = Convert.ToDecimal(balance.FiscalYearDays / 30.0);
                //}

                //else if (amc != 0 && availableQuantity != 0)
                //{
                //    mos = Convert.ToDecimal(availableQuantity / amc);
                //}

                //else if (availableQuantity == 0 && amc != 0)
                //{
                //    mos = 0;
                //}
                //else
                //{
                //    amc = 0;
                //    mos = 0;
                //}
                orderDetail.SetColumn("TotalRequested", 0);
                orderDetail.SetColumn("AMC", 0);
                orderDetail.SetColumn("MOS", 0);

            //}
            return orderDetail.DefaultView.ToTable().Rows[0];
        }
        private void LoadManufacturerForSelectedItem()
        {
            BLL.ItemManufacturer itemManufacturer = new BLL.ItemManufacturer();
            if (ShowOnlyReceivedManufacturer)
                itemManufacturer.LoadManufactuererByItemWithReceive(ItemID);
            chkManufacturer.DataSource = itemManufacturer.DefaultView;
            lkStockCardManufacturer.Properties.DataSource = itemManufacturer.DefaultView;

            chkManufacturer.CheckAll();
        }
        private void EditReceived_Load(object sender, EventArgs e)
        {
            BLL.ItemManufacturer im = new BLL.ItemManufacturer();
            im.LoadManufacturersFor(rDoc.ItemID);
            lkManufacturer.Properties.DataSource = im.DefaultView;

            if (BLL.Settings.UseNewUserManagement && this.HasPermission("Edit-Quantity") && (rDoc.IsColumnNull("Confirmed") || (!rDoc.IsColumnNull("Confirmed") && !rDoc.Confirmed)))
            {
                txtQuanitity.Enabled = true;
            }
            else if ( (!rDoc.IsColumnNull("Confirmed") && !rDoc.Confirmed))
            {
                txtQuanitity.Enabled = true;
            }
            else
            {
                txtQuanitity.Enabled = false;
            }
            Supplier supplier = new Supplier();
            supplier.LoadAll();
            lkSupplier.Properties.DataSource = supplier.DefaultView;

            lkAccount.SetupActivityEditor().SetDefaultActivity();
            BLL.ItemUnit iu = new ItemUnit();
            iu.LoadAllForItem(rDoc.ItemID);
            lkUnit.Properties.DataSource = iu.DefaultView;

            // Bind the variables)
            if (rDoc.RowCount > 0)
            {
                this.txtRefNo.Text = rDoc.RefNo;
                this.txtQuanitity.Text =
                    Convert.ToInt32(Convert.ToDouble(rDoc.Quantity)/rDoc.QtyPerPack).ToString("#,##0");
                this.txtManufacturer.Text = Manufacturer.GetName(rDoc.ManufacturerId);
                this.txtItemName.Text = Item.GetName(rDoc.ItemID);
                this.txtGrvNo.Text = rDoc.RefNo;
                this.lkManufacturer.EditValue = rDoc.ManufacturerId;
                this.lkAccount.EditValue = rDoc.StoreID;
                this.lkUnit.EditValue = rDoc.UnitID;

                if (!rDoc.IsColumnNull("SupplierID"))
                    lkSupplier.EditValue = rDoc.SupplierID;
                // Editable controls
                txtPrice.Text = rDoc.IsColumnNull("Cost") ? "0" : rDoc.Cost.ToString();
                if (!rDoc.IsColumnNull("ExpDate"))
                {
                    dtExpiry.EditValue = rDoc.ExpDate;
                }
                if (!rDoc.IsColumnNull("BatchNo"))
                {
                    txtBatchNo.Text = rDoc.BatchNo;
                }

                BLL.Item itm = new Item();
                itm.LoadByPrimaryKey(rDoc.ItemID);
                if (BLL.Settings.UseNewUserManagement && this.HasPermission("Edit-Batch-Expiry"))
                {

                }
                else if (!itm.NeedExpiryBatch &&
                         (CurrentContext.LoggedInUser.UserType == UserType.Constants.ADMIN ||
                          CurrentContext.LoggedInUser.UserType == UserType.Constants.SUPER_ADMINISTRATOR))
                {
                    btnRemoveExpiry.Enabled = true;
                    txtBatchNo.Enabled = true;
                }
            }
        }
        private void btnRemoveLevel_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete this Package Level?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {

                BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
                DataRowView drv = (DataRowView)lstLevel.SelectedItems[0];
                String SelectedID = drv["ID"].ToString();

                imf.LoadByPrimaryKey(Convert.ToInt32(SelectedID));

                if (imf.HasDependants())
                {
                    XtraMessageBox.Show("This Item Manufacturer cannot be deleted because there are other box levels that depend on it.", "Deleting is not allowed.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (imf.HasReceives())
                {
                    XtraMessageBox.Show("This Item Manufacturer Cannot be Deleted because there are items that were received with this manufacturer item composition.", "Deleting is not allowed.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                imf.MarkAsDeleted();

                imf.Save();

                //refresh the window
                imf.LoadManufacturersFor(this._itemID);
                lstManufacturers.DataSource = imf.DefaultView;

                lstManufacturers_SelectedIndexChanged(null, null);
            }
        }
 /// <summary>
 /// Gets replenishment list for item id in logical store storeid
 /// </summary>
 /// <param name="itemId">The item id.</param>
 /// <param name="storeId">The store id.</param>
 /// <returns></returns>
 public DataTable GetReplenishmentListFor(int itemId, int storeId)
 {
     PalletLocation.CalculateAllVolumes(itemId);
     string query = HCMIS.Repository.Queries.PickFace.SelectGetReplenishmentListFor(itemId, storeId, StorageType.BulkStore);
     this.LoadFromRawSql(query);
     this.DataTable.Columns.Add("SKU", typeof(int));
     this.DataTable.Columns.Add("CanReplenish", typeof(bool));
     ItemManufacturer im = new ItemManufacturer();
     DateTime exp = new DateTime();
     int boxsize = -1;
     int j = 0;
     while (!this.EOF)
     {
         if (j == 0)
         {
             this.SetColumn("CanReplenish", true);
             boxsize = Convert.ToInt32(this.GetColumn("BoxSize"));
             if (!this.IsColumnNull("ExpiryDate"))
             {
                 exp = Convert.ToDateTime(this.GetColumn("ExpiryDate"));
             }
         }
         else
         {
             int bs = Convert.ToInt32(this.GetColumn("BoxSize"));
             if ( bs < boxsize && exp.Subtract(Convert.ToDateTime(this.GetColumn("ExpiryDate"))).Days == 0)
             {
                 this.SetColumn( "CanReplenish" , true);
             }else{
                 this.SetColumn( "CanReplenish" , false);
             }
         }
         j++;
         im.LoadIMbyLevel(Convert.ToInt32( this.GetColumn( "ItemID" ) ), Convert.ToInt32(this.GetColumn("ManufacturerID")), 0);
         int i = Convert.ToInt32(this.GetColumn("Balance"));
         this.SetColumn("SKU", i / im.QuantityInBasicUnit );
         this.MoveNext();
     }
     return this.DataTable;
 }
 private void LoadManufacturerForChange()
 {
     BLL.ItemManufacturer itemManufacturer = new BLL.ItemManufacturer();
     itemManufacturer.LoadAllManufacturersByItem(ItemIDTo);
     lkManufacturerTo.Properties.DataSource = itemManufacturer.DefaultView;
 }
        private void returnToBulkStoreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataRow dr = gridPickFaceDetailView.GetFocusedDataRow();
            if (dr != null)
            {
                int ReceivePalletID = Convert.ToInt32(dr["ID"]);
                ReceivePallet rp = new ReceivePallet();
                rp.LoadByPrimaryKey(ReceivePalletID);

                ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByPrimaryKey(rp.ReceiveID);

                BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
                imf.LoadIMbyLevel(rd.ItemID, rd.ManufacturerId, rp.BoxSize);

                int QuantityToReturn = Convert.ToInt32(((rp.Balance - rp.ReservedStock) / imf.QuantityInBasicUnit) * imf.QuantityInBasicUnit);
                InternalTransfer itfr = new InternalTransfer();

            }
        }
        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);
                }
            }
        }