/// <summary>
        /// Creates the procedure receive doc receive pallet.
        /// </summary>
        private static void CreateProcedureReceiveDocReceivePallet()
        {
            ReceivePallet rp         = new ReceivePallet();
            string        storedProc = HCMIS.Repository.Queries.ReceivePallet.SpCreateProcedureReceiveDocReceivePallet();

            rp.LoadFromRawSql(storedProc);
        }
        /// <summary>
        /// Drops the procedure receive doc receive pallet.
        /// </summary>
        private static void DropProcedureReceiveDocReceivePallet()
        {
            ReceivePallet rp    = new ReceivePallet();
            var           query = HCMIS.Repository.Queries.ReceivePallet.DropTriggerProcedureReceiveDocReceivePallet();

            rp.LoadFromRawSql(query);
        }
        /// <summary>
        /// Moves the balance.
        /// </summary>
        /// <param name="rpSource">The rp source.</param>
        /// <param name="rpDestination">The rp destination.</param>
        /// <param name="quantityToBeMoved">The quantity to be moved.</param>
        /// <exception cref="System.Exception"></exception>
        public static void MoveBalance(ReceivePallet rpSource, ReceivePallet rpDestination, long quantityToBeMoved)
        {
            TransactionMgr transaction = TransactionMgr.ThreadTransactionMgr();
            transaction.BeginTransaction();
            try
            {
                //DropProcedureReceiveDocReceivePallet();
                if (rpSource.Balance < quantityToBeMoved)
                {
                    throw new Exception("Quantity to be moved must be less than or equal to the balance!");
                }

                if (rpDestination.IsColumnNull("Balance"))
                {
                    rpDestination.Balance = 0;
                }

                rpDestination.Balance += quantityToBeMoved;
                rpDestination.BoxSize = 0;
                rpDestination.IsOriginalReceive = rpSource.IsOriginalReceive;
                rpDestination.Save();

                rpSource.BoxSize = 0;
                rpSource.Balance -= quantityToBeMoved;

                rpSource.Save();
                //CreateProcedureReceiveDocReceivePallet();
                transaction.CommitTransaction();
            }
            catch
            {
                transaction.RollbackTransaction();
                CreateProcedureReceiveDocReceivePallet();
            }
        }
        private void btnRelocatePallet_Click(object sender, EventArgs e)
        {
            //Get the chosen pallet Location
            BLL.PalletLocation palletLocation = new BLL.PalletLocation();
            palletLocation.LoadByPrimaryKey(Convert.ToInt16(lkAvailablePalletLocation.EditValue));

            //Get the chosen misplaced receivepallet entry
            DataRow dr = grdViewMisplacedItems.GetFocusedDataRow();
            int     receivePalletID = Convert.ToInt32(dr["ID"]);

            BLL.ReceivePallet rp = new BLL.ReceivePallet();
            rp.LoadByPrimaryKey(receivePalletID);
            if (palletLocation.IsColumnNull("PalletID"))
            {
                palletLocation.PalletID = rp.PalletID;
                palletLocation.Save();
            }
            else
            {
                rp.PalletID = palletLocation.PalletID;
                rp.Save();
            }

            int storeID = Convert.ToInt16(lkStoreLocation.EditValue);

            LoadMisplacedItems(storeID);

            XtraMessageBox.Show("Placed!!");
        }
Beispiel #5
0
        internal static PickListDetail GeneratePickListDetail(ReceivePallet receivePallet, int pickListId, decimal qtyInBU)
        {
            ReceiveDoc receiveDoc = new ReceiveDoc();

            receiveDoc.LoadByPrimaryKey(receivePallet.ReceiveID);
            decimal pack = qtyInBU / Convert.ToDecimal(receiveDoc.QtyPerPack);

            PickListDetail pkDetail = new PickListDetail();

            pkDetail.AddNew();
            pkDetail.PickListID = pickListId;
            pkDetail.ItemID     = receiveDoc.ItemID;
            PalletLocation palletLocation = new PalletLocation();

            palletLocation.loadByPalletID(receivePallet.PalletID);
            int palletLocationId;

            try
            {
                palletLocationId = palletLocation.ID;
            }
            catch (Exception exp)
            {
                palletLocationId = receivePallet.PalletLocationID;
                palletLocation.LoadByPrimaryKey(palletLocationId);
            }
            pkDetail.PalletLocationID = palletLocationId;
            if (!receiveDoc.IsColumnNull("BatchNo"))
            {
                pkDetail.BatchNumber = receiveDoc.BatchNo;
            }

            if (!receiveDoc.IsColumnNull("ExpDate"))
            {
                pkDetail.ExpireDate = receiveDoc.ExpDate;
            }

            pkDetail.StoreID      = receiveDoc.StoreID;
            pkDetail.UnitID       = receiveDoc.UnitID;
            pkDetail.ReceiveDocID = receiveDoc.ID;
            if (!receiveDoc.IsColumnNull("Cost"))
            {
                pkDetail.Cost      = Convert.ToDouble(pack) * Math.Round(receiveDoc.Cost, BLL.Settings.NoOfDigitsAfterTheDecimalPoint);
                pkDetail.UnitPrice = Math.Round(receiveDoc.Cost, BLL.Settings.NoOfDigitsAfterTheDecimalPoint);
            }
            pkDetail.Packs           = pack;
            pkDetail.QtyPerPack      = receiveDoc.QtyPerPack;
            pkDetail.QuantityInBU    = qtyInBU;
            pkDetail.StoreID         = receiveDoc.StoreID;
            pkDetail.ReceivePalletID = receivePallet.ID;
            pkDetail.ManufacturerID  = receiveDoc.ManufacturerId;
            pkDetail.BoxLevel        = 0;
            pkDetail.DeliveryNote    = true;

            pkDetail.PhysicalStoreID = palletLocation.PhysicalStoreID;
            pkDetail.Save();

            return(pkDetail);
        }
        /// <summary>
        /// Gets the facilities items reserved for.
        /// </summary>
        /// <returns></returns>
        public DataTable GetFacilitiesItemsReservedFor()
        {
            string        query = HCMIS.Repository.Queries.ReceivePallet.SelectGetFacilitiesItemsReservedFor(this.ID, OrderStatus.Constant.PICK_LIST_GENERATED, OrderStatus.Constant.PICK_LIST_CONFIRMED);
            ReceivePallet rp    = new ReceivePallet();

            rp.LoadFromRawSql(query);

            return(rp.DefaultView.ToTable());
        }
        public static void ReserveQty(decimal pack, int receivePalletId, bool isOriginalReceive = true)
        {
            var receivepallet = new ReceivePallet();

            receivepallet.LoadByPrimaryKey(receivePalletId);
            receivepallet.IsOriginalReceive = isOriginalReceive;
            receivepallet.ReservedStock     = receivepallet.ReservedStock + pack;
            if (receivepallet.Balance >= receivepallet.ReservedStock)
            {
                receivepallet.Save();
            }
        }
        /// <summary>
        /// Fixes the reserved stock problems.
        /// </summary>
        public static void FixReservedStockProblems()
        {
            ReceivePallet rp=new ReceivePallet();
            string query =
                HCMIS.Repository.Queries.ReceivePallet.UpdateFixReservedStockProblems();
            rp.LoadFromRawSql(query);

            query =
                HCMIS.Repository.Queries.ReceivePallet.UpdateFixReservedStockProblemsMakeReservationSameAsBalance();
            rp.LoadFromRawSql(query);

            query =
                HCMIS.Repository.Queries.ReceivePallet.UpdateFixReservedStockProblemsCancelReservations();
            rp.LoadFromRawSql(query);
        }
        /// <summary>
        /// Fixes the reserved stock problems.
        /// </summary>
        public static void FixReservedStockProblems()
        {
            ReceivePallet rp    = new ReceivePallet();
            string        query =
                HCMIS.Repository.Queries.ReceivePallet.UpdateFixReservedStockProblems();

            rp.LoadFromRawSql(query);

            query =
                HCMIS.Repository.Queries.ReceivePallet.UpdateFixReservedStockProblemsMakeReservationSameAsBalance();
            rp.LoadFromRawSql(query);


            query =
                HCMIS.Repository.Queries.ReceivePallet.UpdateFixReservedStockProblemsCancelReservations();
            rp.LoadFromRawSql(query);
        }
Beispiel #10
0
        /// <summary>
        /// Undo pick list that has been printed
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        public void CancelOrderWithPickList(int orderID)
        {
            // Create a pick list entry
            Order          ord            = new Order();
            PickList       pl             = new PickList();
            PickListDetail pld            = new PickListDetail();
            ReceivePallet  rp             = new ReceivePallet();
            ReceiveDoc     rd             = new ReceiveDoc();
            PickFace       pf             = new PickFace();
            PalletLocation palletLocation = new PalletLocation();


            ord.LoadByPrimaryKey(orderID);
            pl.LoadByOrderID(orderID);

            pld.LoadByPickListID(pl.ID);

            while (!pld.EOF)
            {
                rp.LoadByPrimaryKey(pld.ReceivePalletID);
                rp.ReservedStock -= Convert.ToInt32(pld.QuantityInBU);
                if (rp.ReservedStock < 0)
                {
                    rp.ReservedStock = 0; //If there has been no reservation, allow to cancel the picklist too.  No need for it to be blocked by the constraint.
                }
                rp.Save();
                palletLocation.LoadByPrimaryKey(pld.PalletLocationID);
                if (palletLocation.StorageTypeID.ToString() == StorageType.PickFace)
                {
                    pf.LoadByPalletLocation(pld.PalletLocationID);
                    pf.Balance += Convert.ToInt32(pld.QuantityInBU);
                    pf.Save();
                }

                //Delete from picklistDetail and add to pickListDetailDeleted
                PickListDetailDeleted.AddNewLog(pld, BLL.CurrentContext.UserId);
                pld.MarkAsDeleted();
                pld.MoveNext();
            }
            pld.Save();
            ord.ChangeStatus(OrderStatus.Constant.CANCELED, CurrentContext.UserId);

            pl.MarkAsDeleted();
            pl.Save();
        }
        public void LoadPalletLocation(int palletId,int shlefId=0)
        {
            _pl = new BLL.PalletLocation();
            _pl.loadByPalletID(palletId);

            txtPalletLocation.Text = _pl.FullName;
            lblStorageType.Text = _pl.FullName;

            _rpl = new BLL.ReceivePallet();
            gridMovement.DataSource = _rpl.GetPalletLocationReadyForMovement( palletId );

            _itm = new BLL.Item();
            _itm.LoadByPrimaryKey(Convert.ToInt32(_rpl.GetColumn("ItemID")));
            txtItemName.Text = _itm.FullItemName;
            lblItemName.Text = _itm.FullItemName;

            lkFreePalletLocations.Properties.DataSource = BLL.PalletLocation.GetAllFreeFor(_itm.ID, shlefId);
        }
        private void btnFixLocationStuff_Click(object sender, EventArgs e)
        {
            int storeID = Convert.ToInt32(lkStoreLocation.EditValue);

            BLL.ReceiveDoc rd = new BLL.ReceiveDoc();
            rd.LoadReceivesForStores(storeID);
            while (!rd.EOF)
            {
                BLL.ReceivePallet rp = new BLL.ReceivePallet();
                rp.LoadByReceiveDocID(rd.ID);
                decimal receivedQuantity = 0, balance = 0;
                if (rp.RowCount == 1)// rp.RowCount > 0)
                {
                    while (!rp.EOF)
                    {
                        receivedQuantity += rp.IsColumnNull("ReceivedQuantity") ? 0 : rp.ReceivedQuantity;
                        balance          += rp.IsColumnNull("Balance") ? 0 : rp.Balance;
                        rp.MoveNext();
                    }
                    rp.Rewind();

                    while (!rp.EOF && rp.IsColumnNull("ReceivedQuantity"))
                    {
                        rp.MoveNext();
                    }

                    if (rd.Quantity != receivedQuantity && rd.Quantity > receivedQuantity)
                    {
                        rp.ReceivedQuantity += (rd.Quantity - receivedQuantity);
                    }
                    if (rd.QuantityLeft != balance && rd.QuantityLeft > 0)//rd.QuantityLeft > balance)
                    {
                        rp.Balance += (rd.QuantityLeft - balance);
                    }
                    rp.Save();
                }
                rd.MoveNext();
            }
            XtraMessageBox.Show("Completed!");
        }
        private void btnDispose_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate()) return;

            TransferService transferService = new TransferService();
            IssueService issueService = new IssueService();

            if (XtraMessageBox.Show("Please Confirm that you want to dispose the selected items", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                int activityID = Convert.ToInt32(glkActivity.EditValue);
                var dt = (DataView)grdSelectedExpiredItemsView.DataSource;

                Order order = OrderForDisposal(activityID);
                PickList picklist = PickList.GeneratePickList(order.ID);

                BLL.Issue stvLog = issueService.CreateSTVLog(null, false, picklist, order, null, activityID, false, CurrentContext.UserId);

                foreach (DataRow row in dt.Table.Rows)
                {
                    ReceiveDoc rd = new ReceiveDoc();
                    ReceivePallet rp = new ReceivePallet();

                    rd.LoadByPrimaryKey((int)row["ReceiveDocID"]);
                    rp.LoadByReceiveDocID((int)row["ReceiveDocID"]);

                    var picklistDetail = transferService.GeneratePickListDetail(rd, rp, order, picklist);
                    issueService.CreateIssueFromPicklist(picklistDetail, order, DateTime.Now, stvLog, CurrentContext.LoggedInUser);
                }

                HCMIS.Reports.Workflow.Activities.Disposal disposalPrintout = new HCMIS.Reports.Workflow.Activities.Disposal(glkActivity.Text, txtLicenseNo.Text, DateTime.Now, ((DataView)grdSelectedExpiredItemsView.DataSource).Table);
                disposalPrintout.PrintDialog();

                RefreshSelection();
                txtLicenseNo.ResetText();
            }
        }
        /// <summary>
        /// Moves the balance.
        /// </summary>
        /// <param name="rpSource">The rp source.</param>
        /// <param name="rpDestination">The rp destination.</param>
        /// <param name="quantityToBeMoved">The quantity to be moved.</param>
        /// <exception cref="System.Exception"></exception>
        public static void MoveBalance(ReceivePallet rpSource, ReceivePallet rpDestination, long quantityToBeMoved)
        {
            TransactionMgr transaction = TransactionMgr.ThreadTransactionMgr();

            transaction.BeginTransaction();
            try
            {
                //DropProcedureReceiveDocReceivePallet();
                if (rpSource.Balance < quantityToBeMoved)
                {
                    throw new Exception("Quantity to be moved must be less than or equal to the balance!");
                }

                if (rpDestination.IsColumnNull("Balance"))
                {
                    rpDestination.Balance = 0;
                }

                rpDestination.Balance          += quantityToBeMoved;
                rpDestination.BoxSize           = 0;
                rpDestination.IsOriginalReceive = rpSource.IsOriginalReceive;
                rpDestination.Save();

                rpSource.BoxSize  = 0;
                rpSource.Balance -= quantityToBeMoved;

                rpSource.Save();
                //CreateProcedureReceiveDocReceivePallet();
                transaction.CommitTransaction();
            }
            catch
            {
                transaction.RollbackTransaction();
                CreateProcedureReceiveDocReceivePallet();
            }
        }
        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 btnConsolidate_Click(object sender, EventArgs e)
        {
            DataRow dr = gridView4.GetFocusedDataRow();
            if (dr != null)
            {
                if (DialogResult.Yes == XtraMessageBox.Show("Are you sure you want to consolidate the two pallets? you will not be able to undo this change.", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    DataRow dr2 = gridView3.GetFocusedDataRow();
                    PalletLocation pl = new PalletLocation();
                    pl.LoadByPrimaryKey( Convert.ToInt32(dr2["ID"]) );

                    int sourcePalletID = pl.PalletID;
                    pl.LoadByPrimaryKey(Convert.ToInt32(dr["ID"]));
                    int destinationPalletID = pl.PalletID;

                    ReceivePallet rp = new ReceivePallet();
                    rp.Consolidate(sourcePalletID, destinationPalletID);
                    pl.LoadByPrimaryKey(Convert.ToInt32(dr2["ID"]));
                    pl.SetColumnNull("PalletID");
                    pl.Save();
                    XtraMessageBox.Show("Items Consolidated.", "Items Consolidated");

                    gridView5_RowClick(null, null);
                }
            }
        }
 /// <summary>
 /// Drops the procedure receive doc receive pallet.
 /// </summary>
 private static void DropProcedureReceiveDocReceivePallet()
 {
     ReceivePallet rp = new ReceivePallet();
     var query = HCMIS.Repository.Queries.ReceivePallet.DropTriggerProcedureReceiveDocReceivePallet();
     rp.LoadFromRawSql(query);
 }
        /// <summary>
        /// Gets the pick list details for order.
        /// </summary>
        /// <param name="ordID">The ord ID.</param>
        /// <param name="Preparedby">The preparedby.</param>
        /// <returns></returns>
        public DataView GetPickListDetailsForOrder(int ordID, string Preparedby)
        {
            this.LoadByOrderID(ordID);
            var query = HCMIS.Repository.Queries.PickList.SelectGetPickListDetailsForOrder(this.ID);
            this.LoadFromRawSql(query);
            // Add important columns
            this.DataTable.Columns.Add("SKUTOPICK", typeof(decimal));
            this.DataTable.Columns.Add("SKUPICKED", typeof(decimal));
            this.DataTable.Columns.Add("BUPICKED", typeof(decimal));
            this.DataTable.Columns.Add("BoxSizeDisplay");
            this.DataTable.Columns.Add("SKUBU", typeof(decimal));
            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));
            this.DataTable.Columns.Add("PreparedBy", typeof(string));
            int i = 1;
            while (!this.EOF)
            {
                decimal packs = Convert.ToDecimal(this.GetColumn("Packs"));

                int manufacturer = Convert.ToInt32(this.GetColumn("ManufacturerID"));
                Manufacturer m = new Manufacturer();
                m.LoadByPrimaryKey(manufacturer);
                if (!m.IsColumnNull("CountryOfOrigin") && m.CountryOfOrigin.Contains("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
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    Receipt receipt = new Receipt();
                    receiveDoc.LoadByPrimaryKey(rp.ReceiveID);
                    receipt.LoadByPrimaryKey(receiveDoc.ReceiptID);
                    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);
                    if (BLL.Settings.PrintUserNameOnInvoice)
                    {
                        this.SetColumn("PreparedBy", Preparedby);
                    }

                }
                catch
                {

                }

                int itemId = Convert.ToInt32(this.GetColumn("ItemID"));
                int boxLevel = Convert.ToInt32(this.GetColumn("BoxLevel"));
                decimal 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.ToDecimal(this.GetColumn("SKUPICKED")));
                this.SetColumn("LineNum", i++);
                if (this.IsColumnNull("DeliveryNote"))
                {
                    this.SetColumn("DeliveryNote", false);
                }
                this.MoveNext();
            }
            return this.DefaultView;
        }
        /// <summary>
        /// Undo pick list that has been printed
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        public void CancelOrderWithPickList(int orderID)
        {
            // Create a pick list entry
            Order ord = new Order();
            PickList pl = new PickList();
            PickListDetail pld = new PickListDetail();
            ReceivePallet rp = new ReceivePallet();
            ReceiveDoc rd = new ReceiveDoc();
            PickFace pf = new PickFace();
            PalletLocation palletLocation = new PalletLocation();

            ord.LoadByPrimaryKey(orderID);
            pl.LoadByOrderID(orderID);

            pld.LoadByPickListID(pl.ID);

            while (!pld.EOF)
            {
                rp.LoadByPrimaryKey(pld.ReceivePalletID);
                rp.ReservedStock -= Convert.ToInt32(pld.QuantityInBU);
                if (rp.ReservedStock < 0)
                    rp.ReservedStock = 0; //If there has been no reservation, allow to cancel the picklist too.  No need for it to be blocked by the constraint.
                rp.Save();
                palletLocation.LoadByPrimaryKey(pld.PalletLocationID);
                if (palletLocation.StorageTypeID.ToString() == StorageType.PickFace)
                {
                    pf.LoadByPalletLocation(pld.PalletLocationID);
                    pf.Balance += Convert.ToInt32(pld.QuantityInBU);
                    pf.Save();
                }

                //Delete from picklistDetail and add to pickListDetailDeleted
                PickListDetailDeleted.AddNewLog(pld, BLL.CurrentContext.UserId);
                pld.MarkAsDeleted();
                pld.MoveNext();
            }
            pld.Save();
            ord.ChangeStatus(OrderStatus.Constant.CANCELED,CurrentContext.UserId);

            pl.MarkAsDeleted();
            pl.Save();
        }
        /// <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>
        /// Releases the reservation.
        /// </summary>
        public void ReleaseReservation()
        {
            PickList pickList = new PickList();
            pickList.LoadByOrderID(this.ID);
            if (pickList.RowCount == 0) //If there is no picklist, there is nothing to release.
                return;
            PickListDetail pld = new PickListDetail();
            pld.LoadByPickListID(pickList.ID);
            pld.Rewind();
            while (!pld.EOF)
            {
                ReceivePallet receivePallet = new ReceivePallet();
                receivePallet.LoadByPrimaryKey(pld.ReceivePalletID);
                ReceiveDoc rdoc = new ReceiveDoc();
                rdoc.LoadByPrimaryKey(pld.ReceiveDocID);

                receivePallet.ReservedStock = receivePallet.ReservedStock - Convert.ToInt32(pld.QuantityInBU);
                if (receivePallet.ReservedStock < 0)
                    receivePallet.ReservedStock = 0;
                receivePallet.Save();
                //Delete from picklistDetail and add to pickListDetailDeleted
                PickListDetailDeleted.AddNewLog(pld, BLL.CurrentContext.UserId);
                pld.MarkAsDeleted();
                pld.MoveNext();

                //Delete issues if the order has any
                    var iss = new Issue();
                    iss.GetIssueByOrderID(this.ID);
                iss.Rewind();
                if (iss.RowCount > 0)
                {
                    while (!iss.EOF)
                    {
                        iss.MarkAsDeleted();
                        iss.MoveNext();
                    }
                    iss.Save();
                }

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

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

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

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

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


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


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

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


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

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

                pl.Confirmed = false;
                pl.Save();
                if (rp.Balance == 0)
                {
                    PalletLocation.GarbageCollection();
                }
            }
        }
        /// <summary>
        /// Saves the whole transaction for
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        /// <param name="dvOutstandingPickList">The dv outstanding pick list.</param>
        /// <param name="remark">The remark.</param>
        /// <param name="issuedBy">The issued by.</param>
        /// <param name="etCurrentDate">The et current date.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static Order SaveIssueTransaction(int orderID, ref DataView dvOutstandingPickList, string remark, string issuedBy, DateTime etCurrentDate)
        {
            // Add the IssueDocID field
            dvOutstandingPickList.Table.Columns.Add("IssueDocID");
            PickList   plst   = new PickList();
            IssueDoc   issDoc = new IssueDoc();
            ReceiveDoc recDoc = new ReceiveDoc();

            BLL.Order ord = new BLL.Order();
            ord.LoadByPrimaryKey(orderID);
            plst.LoadByOrderID(ord.ID);

            foreach (DataRowView drv in dvOutstandingPickList)
            {
                // Pseudo:
                // for each row in the picklist
                // undate the issue document
                // subtract the issued quantity from the receive doc
                // subtract the issued quantity from recieve pallet
                // subtract the issued the reserved quantity irregardless of the quantity issued.


                //Saving the new Issue issue
                if (Convert.ToDecimal(drv["BUPICKED"]) == 0)
                {
                    continue;
                }

                if (Convert.ToDecimal(drv["SKUPicked"]) != Convert.ToDecimal(drv["SKUTOPICK"]))
                {
                    drv["Cost"] = Convert.ToDecimal(drv["SKUPicked"]) * Convert.ToDecimal(drv["UnitPrice"]);
                }

                // Select the receive doc that is associated with this issue.
                recDoc.LoadByPrimaryKey(Convert.ToInt32(drv["ReceiveDocID"]));


                issDoc.AddNew();
                issDoc.StoreId = Convert.ToInt32(drv["StoreID"]);
                issDoc.RefNo   = ord.RefNo;
                if (!ord.IsColumnNull("RequestedBy"))
                {
                    issDoc.ReceivingUnitID = ord.RequestedBy;
                }
                // TOFIX:
                // TODO:
                // Lord have mercy kind of hack to avoid the feb date problem
                // this needs to be fixed for pagume also
                issDoc.Date           = etCurrentDate;
                issDoc.EurDate        = DateTimeHelper.ServerDateTime;
                issDoc.RecievDocID    = Convert.ToInt32(drv["ReceiveDocID"]);
                issDoc.IsApproved     = true;
                issDoc.IsTransfer     = false;
                issDoc.Remark         = remark;
                issDoc.ItemID         = Convert.ToInt32(drv["ItemID"]);
                issDoc.Quantity       = Convert.ToDecimal(drv["BUPICKED"]);
                issDoc.NoOfPack       = Convert.ToDecimal(drv["SKUPICKED"]);
                issDoc.QtyPerPack     = Convert.ToInt32(drv["SKUBU"]);
                issDoc.BatchNo        = drv["BatchNumber"].ToString();
                issDoc.UnitID         = recDoc.UnitID;
                issDoc.ManufacturerID = recDoc.ManufacturerId;
                if (drv["Cost"] != DBNull.Value)
                {
                    issDoc.Cost = Convert.ToDouble(drv["Cost"]);

                    issDoc.SellingPrice = Convert.ToDecimal(drv["UnitPrice"]);
                    if (!recDoc.IsColumnNull("Cost"))
                    {
                        issDoc.UnitCost = Convert.ToDecimal(recDoc.Cost);
                    }
                }
                issDoc.OrderID  = orderID;
                issDoc.IssuedBy = issuedBy;
                // TODO: is this the right place where we need to pick the physical store ID from?
                // check it against the receipt pallet physical store.
                if (!recDoc.IsColumnNull("PhysicalStoreID"))
                {
                    issDoc.PhysicalStoreID = recDoc.PhysicalStoreID;
                }
                if (!recDoc.IsColumnNull("InventoryPeriodID"))
                {
                    //Todo: Remove for Inventory
                    issDoc.InventoryPeriodID = recDoc.InventoryPeriodID;
                }
                if (!recDoc.IsColumnNull("Margin"))
                {
                    issDoc.Margin = (decimal)recDoc.Margin;
                }
                //Replaced by
                issDoc.PLDetailID = Convert.ToInt32(drv["PLDetailID"]);
                BLL.Balance    bal = new Balance();
                BLL.ReceiveDoc rd  = new ReceiveDoc();
                rd.LoadByPrimaryKey(issDoc.RecievDocID);
                decimal currentBalance = bal.GetSoh(issDoc.ItemID, rd.UnitID, issDoc.StoreId, issDoc.Date.Month, issDoc.Date.Year);
                if (currentBalance < issDoc.NoOfPack)
                {
                    throw new Exception(string.Format("The item {0} is not available in {1} Qty.", drv["FullItemName"].ToString(), issDoc.NoOfPack));
                }

                // This is a field that is not applicable on the hub edition
                // It is about the dispensing unit quantity and there is no such thing as Dispensing unit
                // in the hub edition
                issDoc.DUSOH         = 0;
                issDoc.RecomendedQty = 0;// ((recQty > 0) ? Convert.ToInt64(recQty) : 0);
                // End DU
                issDoc.DispatchConfirmed = false;
                issDoc.Save();
                drv["IssueDocID"] = issDoc.ID;
                // updating the receiving doc

                //long prevQuantityLeft = recDoc.QuantityLeft;

                recDoc.QuantityLeft = recDoc.QuantityLeft - issDoc.Quantity;

                if (recDoc.QuantityLeft < 0)
                {
                    //Possibly the wrong ReceiveDoc Entry chosen
                    BLL.Item itm = new Item();
                    itm.LoadByPrimaryKey(recDoc.ItemID);
                    throw new Exception(string.Format("Quantity problem detected for the item {0}", itm.FullItemName));
                }
                //long
                recDoc.Out = (recDoc.QuantityLeft == 0) ? true : false;
                recDoc.Save();

                ReceivePallet rp = new ReceivePallet();
                int           id = Convert.ToInt32(drv["ReceivePalletID"]);
                rp.LoadByPrimaryKey(id);
                if (rp.IsColumnNull("Balance"))
                {
                    rp.Balance = rp.ReceivedQuantity;
                }
                rp.Balance -= issDoc.Quantity;

                if (rp.Balance < 0)
                {
                    BLL.Item itm = new Item();
                    itm.LoadByPrimaryKey(recDoc.ItemID);
                    throw new Exception(string.Format("Quantity problem detected for the item {0}", itm.FullItemName));
                }

                decimal totReservedQty = Convert.ToDecimal(drv["QuantityInBU"]);

                if (rp.IsColumnNull("ReservedStock"))
                {
                    rp.ReservedStock = 0;
                }

                rp.ReservedStock -= totReservedQty;
                if (rp.ReservedStock < 0) //If there has been a quantity problem somewhere
                {
                    rp.ReservedStock = 0;
                }
                rp.Save();
            }
            plst.IsConfirmed = true;
            ord.ChangeStatus(OrderStatus.Constant.ISSUED, CurrentContext.UserId);
            plst.Save();
            ord.Save();
            return(ord);
        }
 private void LoadMisplacedItems(int storeID)
 {
     BLL.ReceivePallet rp = new BLL.ReceivePallet();
     rp.LoadMisplacedItems(storeID);
     grdMisplacedItems.DataSource = rp.DefaultView;
 }
Beispiel #25
0
        /// <summary>
        /// Gets the pick list details for order.
        /// </summary>
        /// <param name="ordID">The ord ID.</param>
        /// <param name="Preparedby">The preparedby.</param>
        /// <returns></returns>
        public DataView GetPickListDetailsForOrder(int ordID, string Preparedby)
        {
            this.LoadByOrderID(ordID);
            var query = HCMIS.Repository.Queries.PickList.SelectGetPickListDetailsForOrder(this.ID);

            this.LoadFromRawSql(query);
            // Add important columns
            this.DataTable.Columns.Add("SKUTOPICK", typeof(decimal));
            this.DataTable.Columns.Add("SKUPICKED", typeof(decimal));
            this.DataTable.Columns.Add("BUPICKED", typeof(decimal));
            this.DataTable.Columns.Add("BoxSizeDisplay");
            this.DataTable.Columns.Add("SKUBU", typeof(decimal));
            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));
            this.DataTable.Columns.Add("PreparedBy", typeof(string));
            int i = 1;

            while (!this.EOF)
            {
                decimal packs = Convert.ToDecimal(this.GetColumn("Packs"));


                int          manufacturer = Convert.ToInt32(this.GetColumn("ManufacturerID"));
                Manufacturer m            = new Manufacturer();
                m.LoadByPrimaryKey(manufacturer);
                if (!m.IsColumnNull("CountryOfOrigin") && m.CountryOfOrigin.Contains("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
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    Receipt    receipt    = new Receipt();
                    receiveDoc.LoadByPrimaryKey(rp.ReceiveID);
                    receipt.LoadByPrimaryKey(receiveDoc.ReceiptID);
                    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);
                    if (BLL.Settings.PrintUserNameOnInvoice)
                    {
                        this.SetColumn("PreparedBy", Preparedby);
                    }
                }
                catch
                {
                }

                int     itemId     = Convert.ToInt32(this.GetColumn("ItemID"));
                int     boxLevel   = Convert.ToInt32(this.GetColumn("BoxLevel"));
                decimal 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.ToDecimal(this.GetColumn("SKUPICKED")));
                this.SetColumn("LineNum", i++);
                if (this.IsColumnNull("DeliveryNote"))
                {
                    this.SetColumn("DeliveryNote", false);
                }
                this.MoveNext();
            }
            return(this.DefaultView);
        }
        //,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;
        }
        /// <summary>
        /// Gets the facilities items reserved for.
        /// </summary>
        /// <returns></returns>
        public DataTable GetFacilitiesItemsReservedFor()
        {
            string query = HCMIS.Repository.Queries.ReceivePallet.SelectGetFacilitiesItemsReservedFor(this.ID, OrderStatus.Constant.PICK_LIST_GENERATED, OrderStatus.Constant.PICK_LIST_CONFIRMED);
            ReceivePallet rp = new ReceivePallet();
            rp.LoadFromRawSql(query);

            return rp.DefaultView.ToTable();
        }
        /// <summary>
        /// Saves issue order details
        /// </summary>
        /// <param name="orderID"></param>
        /// <param name="dvPickListMakeup"></param>
        public void SavePickList(int orderID, DataView dvPickListMakeup, int userID)
        {
            //~ Check if This Order has a previous Printed Picklist with detail: Note a header only doesnt affect us! //
            var pickList = new PickList();
            pickList.LoadByOrderID(orderID);
            if(pickList.RowCount>0)
            {
                var pldetail = new PickListDetail();
                pldetail.LoadByPickListID(pickList.ID);
                if (pldetail.RowCount > 0)
                {
                    RemoveFakePartialCommitPickListDetails(orderID);
                      var pickL = new PickList();
                    pickL.LoadByOrderID(orderID);
                    if (pickL.RowCount > 0)
                    {
                        throw new Exception("Picklist has already been printed for this Order ");
                        // This error has been apprearing for the last one year so funny! I hope it won't come again! day: 10/21/2014 @yido  //
                    }
                }
            }
            // Create a pick list entry
            Order ord = new Order();
            ord.LoadByPrimaryKey(orderID);
            PickList pl = new PickList();
            PalletLocation plocation = new PalletLocation();
            plocation.LoadByPrimaryKey(Convert.ToInt32(dvPickListMakeup[0]["PalletLocationID"]));
            pl.AddNew();
            pl.OrderID = orderID;
            pl.PickType = "Pick";
            pl.PickedBy = userID;

            pl.IsConfirmed = false;
            pl.IssuedDate = DateTimeHelper.ServerDateTime;
            pl.SavedDate = DateTimeHelper.ServerDateTime;
            pl.PickedDate = DateTimeHelper.ServerDateTime;
            pl.IsWarehouseConfirmed = 0;
            pl.WarehouseID = plocation.WarehouseID;
            pl.Save();
            PickListDetail pld = new PickListDetail();
            ReceivePallet rp = new ReceivePallet();
            ReceiveDoc rd = new ReceiveDoc();

            PickFace pf = new PickFace();

            foreach (DataRowView drv in dvPickListMakeup)
            {
                pld.AddNew();
                pld.PickListID = pl.ID;
                pld.OrderDetailID = Convert.ToInt32(drv["OrderDetailID"]);

                pld.ItemID = Convert.ToInt32(drv["ItemID"]);
                pld.BatchNumber = (drv["BatchNo"].ToString());
                if (drv["ExpDate"] != DBNull.Value)
                {
                    pld.ExpireDate = Convert.ToDateTime(drv["ExpDate"]);
                }
                pld.ManufacturerID = Convert.ToInt32(drv["ManufacturerID"]);
                pld.BoxLevel = Convert.ToInt32(drv["BoxLevel"]);
                pld.QtyPerPack = Convert.ToInt32(drv["QtyPerPack"]);
                pld.Packs = Convert.ToDecimal(drv["Pack"]);
                pld.PalletLocationID = Convert.ToInt32(drv["PalletLocationID"]);
                pld.QuantityInBU = Convert.ToDecimal(drv["QtyInBU"]);
                pld.ReceiveDocID = Convert.ToInt32(drv["ReceiveDocID"]);
                pld.ReceivePalletID = Convert.ToInt32(drv["ReceivePalletID"]);
                if (drv["CalculatedCost"] != DBNull.Value)
                    pld.Cost = Convert.ToDouble(drv["CalculatedCost"]);
                if (drv["UnitPrice"] != DBNull.Value)
                    pld.UnitPrice = Convert.ToDouble(drv["UnitPrice"]);
                int ReceivePalletID = Convert.ToInt32(drv["ReceivePalletID"]);
                rp.LoadByPrimaryKey(ReceivePalletID);
                pld.StoreID = Convert.ToInt32(drv["StoreID"]);

                if (drv["DeliveryNote"] != null)
                    pld.DeliveryNote = Convert.ToBoolean(drv["DeliveryNote"]);
                else
                    pld.DeliveryNote = false;

                if (rp.IsColumnNull("ReservedStock"))
                {
                    rp.ReservedStock = Convert.ToDecimal(pld.QuantityInBU);
                }
                else
                {
                    rp.ReservedStock += Convert.ToDecimal(pld.QuantityInBU);
                }
                if (drv["UnitID"] != DBNull.Value)
                {
                    pld.UnitID = Convert.ToInt32(drv["UnitID"]);
                }
                plocation.LoadByPrimaryKey(Convert.ToInt32(drv["PalletLocationID"]));
                pld.PhysicalStoreID = plocation.PhysicalStoreID;

                rp.Save();

                if (drv["StorageTypeID"].ToString() == StorageType.PickFace)
                {
                    pf.LoadByPalletLocation(Convert.ToInt32(drv["PalletLocationID"]));
                    //pf.Balance -= Convert.ToDecimal(pld.QuantityInBU);
                    pf.Save();
                }
            }

            pld.Save();
            ord.ChangeStatus(OrderStatus.Constant.PICK_LIST_GENERATED,CurrentContext.UserId);
            ord.Save();
        }
 private void LoadMisplacedItems(int storeID)
 {
     BLL.ReceivePallet rp = new BLL.ReceivePallet();
     rp.LoadMisplacedItems(storeID);
     grdMisplacedItems.DataSource = rp.DefaultView;
 }
        /// <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();
            }
        }
        public static void DeleteIssueDoc(int issueID)
        {
            MyGeneration.dOOdads.TransactionMgr tranMgr =
                MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                tranMgr.BeginTransaction();

                var pld = new PickListDetail();
                var rdoc = new ReceiveDoc();
                var rp = new ReceivePallet();
                var idoc = new IssueDoc();

                idoc.LoadByPrimaryKey(issueID);
                pld.LoadByPrimaryKey(idoc.PLDetailID);
                rdoc.LoadByPrimaryKey(idoc.RecievDocID);

                rp.LoadByPrimaryKey(pld.ReceivePalletID);
                var pl = new PalletLocation();
                pl.loadByPalletID(rp.PalletID);

                if (pl.RowCount == 0)
                {
                    pl.LoadByPrimaryKey(pld.PalletLocationID);
                    if (pl.IsColumnNull("PalletID"))
                    {
                        pl.PalletID = rp.PalletID;
                        pl.Save();
                    }
                }

                if (rp.RowCount == 0)
                {
                    XtraMessageBox.Show("You cannot delete this item, please contact the administrator", "Error");
                    return;
                }
                if (rp.RowCount > 0)
                {
                    // in error cases this could lead to a number greater than the received quantity
                    // instead of being an error, it should just delete the respective issue and
                    // adjust the remaining quantity to the received quantity.
                    if (rdoc.QuantityLeft + idoc.Quantity > rdoc.Quantity)
                    {
                        rdoc.QuantityLeft = rp.Balance = rdoc.Quantity;
                    }
                    else
                    {
                        rdoc.QuantityLeft += idoc.Quantity;
                        rp.Balance += idoc.Quantity;
                    }

                    //Delete from picklistDetail and add to pickListDetailDeleted
                    PickListDetailDeleted.AddNewLog(pld, BLL.CurrentContext.UserId);
                    pld.MarkAsDeleted();

                    // are we adding it the pick face?
                    // if so add it to the balance of the pick face also
                    pl.loadByPalletID(rp.PalletID);

                    if (pl.RowCount == 0)
                    {
                        var plocation = new PutawayLocation(rdoc.ItemID);

                        // we don't have a location for this yet,
                        // select a new location
                        //PutawayLocataion pl = new PutawayLocataion();
                        if (plocation.ShowDialog() == DialogResult.OK)
                        {
                            pl.LoadByPrimaryKey(plocation.PalletLocationID);
                            if (pl.RowCount > 0)
                            {
                                pl.PalletID = rp.PalletID;
                                pl.Save();
                            }
                        }
                    }

                    if (pl.RowCount > 0)
                    {
                        var pf = new PickFace();
                        pf.LoadByPalletLocation(pl.ID);
                        if (pf.RowCount > 0)
                        {
                            pf.Balance += Convert.ToInt32(idoc.Quantity);
                            pf.Save();
                        }

                        IssueDocDeleted.AddNewLog(idoc, CurrentContext.UserId);
                        idoc.MarkAsDeleted();
                        rdoc.Save();
                        rp.Save();
                        idoc.Save();
                        pld.Save();

                        // now refresh the window
                        XtraMessageBox.Show("Issue Deleted!", "Confirmation", MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        tranMgr.CommitTransaction();

                    }
                }
                else
                {
                    XtraMessageBox.Show(
                        "This delete is not successfull because a free pick face location was not selected. please select a free location and try again.",
                        "Error Deleteing issue transaction", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    tranMgr.RollbackTransaction();
                }
            }
            catch
            {
                XtraMessageBox.Show("This delete is not successfull", "Warning ...", MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                tranMgr.RollbackTransaction();
            }
        }
        private void SetPriceAndQuantity(DataRow dr, decimal dispatch, int buinsku, ReceivePallet rp, int itemId, bool isDeliveryNote)
        {
            dr["DeliveryNote"] = isDeliveryNote;
            dr["BoxLevel"] = 0;
            dr["QtyPerPack"] = buinsku;
            dr["Pack"] = dispatch / buinsku;
            decimal packs = dispatch / buinsku;
            dr["QtyInBU"] = dispatch;
            dr["approvedQuantity"] = dispatch;

            if (isDeliveryNote)// (!Settings.UsesMovingAverage)  //We are taking care of this at the receive page.  Therefore, the selling price would have been set when entering here so for now, I'm disabling this condition
            {
                dr["CalculatedCost"] = 0;
                dr["UnitPrice"] = 0;
            }
            else
            {
                // Apply the cost and selling price from the cost tier.
                if (BLL.Settings.UseCostTier)
                {
                    HCMIS.Specification.Finance.CostTier.ILedger ledgerService = new LedgerService();
                    var ledgerObject = ledgerService.GetLedger(Convert.ToInt32(dr["ItemID"]),
                                                               Convert.ToInt32(dr["UnitID"]),
                                                               Convert.ToInt32(dr["ManufacturerID"]),
                                                               MovingAverageGroup.Convert(Convert.ToInt32(dr["StoreID"]))
                                                               );
                    if (BLL.Settings.IsCenter)
                    {
                        dr["CalculatedCost"] =
                            Math.Round(Convert.ToDouble(ledgerObject.UnitCost)*Convert.ToDouble(packs),
                                       BLL.Settings.NoOfDigitsAfterTheDecimalPoint, MidpointRounding.AwayFromZero);
                        dr["UnitPrice"] = Math.Round(ledgerObject.UnitCost,
                                                     BLL.Settings.NoOfDigitsAfterTheDecimalPoint,
                                                     MidpointRounding.AwayFromZero);
                    }
                    else
                    {
                        dr["CalculatedCost"] =
                           Math.Round(Convert.ToDouble(ledgerObject.SellingPrice) * Convert.ToDouble(packs),
                                      BLL.Settings.NoOfDigitsAfterTheDecimalPoint, MidpointRounding.AwayFromZero);
                        dr["UnitPrice"] = Math.Round(ledgerObject.SellingPrice,
                                                     BLL.Settings.NoOfDigitsAfterTheDecimalPoint,
                                                     MidpointRounding.AwayFromZero);

                    }
                }
                else
                {
                    try
                    {
                        //
                        if (BLL.Settings.IsCenter)
                        {
                            //TOFIXXX when selling price is null, it shouldn't be coming here
                            dr["CalculatedCost"] = Convert.ToDouble(packs) * Math.Round(Convert.ToDouble(rp.GetColumn("Cost")), BLL.Settings.NoOfDigitsAfterTheDecimalPoint, MidpointRounding.AwayFromZero);
                            double sPrice = Math.Round(Convert.ToDouble(rp.GetColumn("Cost")), BLL.Settings.NoOfDigitsAfterTheDecimalPoint, MidpointRounding.AwayFromZero);
                            dr["UnitPrice"] = sPrice;
                        }
                        else
                        {
                            //TOFIXXX when selling price is null, it shouldn't be coming here
                            dr["CalculatedCost"] = Convert.ToDouble(packs) * Math.Round(Convert.ToDouble(rp.GetColumn("SellingPrice")), BLL.Settings.NoOfDigitsAfterTheDecimalPoint, MidpointRounding.AwayFromZero);
                            double sPrice = Math.Round(Convert.ToDouble(rp.GetColumn("SellingPrice")), BLL.Settings.NoOfDigitsAfterTheDecimalPoint, MidpointRounding.AwayFromZero);
                            dr["UnitPrice"] = sPrice;
                        }

                    }
                    catch
                    {
                        BLL.Item itm = new Item();
                        itm.LoadByPrimaryKey(itemId);
                        //throw new Exception(string.Format("Selling price not set for {0}", itm.FullItemName));
                    }
                }

            }

            dr["UnitsInSKU"] = buinsku;
        }
        internal static PickListDetail GeneratePickListDetail(ReceivePallet receivePallet, int pickListId,decimal qtyInBU)
        {
            ReceiveDoc receiveDoc = new ReceiveDoc();
            receiveDoc.LoadByPrimaryKey(receivePallet.ReceiveID);
            decimal pack = qtyInBU / Convert.ToDecimal(receiveDoc.QtyPerPack);

            PickListDetail pkDetail = new PickListDetail();

            pkDetail.AddNew();
            pkDetail.PickListID = pickListId;
            pkDetail.ItemID = receiveDoc.ItemID;
            PalletLocation palletLocation = new PalletLocation();
            palletLocation.loadByPalletID(receivePallet.PalletID);
            int palletLocationId;
            try
            {
                palletLocationId = palletLocation.ID;
            }
            catch (Exception exp)
            {

                palletLocationId = receivePallet.PalletLocationID;
                palletLocation.LoadByPrimaryKey(palletLocationId);

            }
            pkDetail.PalletLocationID = palletLocationId;
            if (!receiveDoc.IsColumnNull("BatchNo"))
                pkDetail.BatchNumber = receiveDoc.BatchNo;

            if (!receiveDoc.IsColumnNull("ExpDate"))
                pkDetail.ExpireDate = receiveDoc.ExpDate;

            pkDetail.StoreID = receiveDoc.StoreID;
            pkDetail.UnitID = receiveDoc.UnitID;
            pkDetail.ReceiveDocID = receiveDoc.ID;
            if (!receiveDoc.IsColumnNull("Cost"))
            {
                pkDetail.Cost = Convert.ToDouble(pack) * Math.Round(receiveDoc.Cost, BLL.Settings.NoOfDigitsAfterTheDecimalPoint);
                pkDetail.UnitPrice = Math.Round(receiveDoc.Cost, BLL.Settings.NoOfDigitsAfterTheDecimalPoint);
            }
            pkDetail.Packs = pack;
            pkDetail.QtyPerPack = receiveDoc.QtyPerPack;
            pkDetail.QuantityInBU = qtyInBU;
            pkDetail.StoreID = receiveDoc.StoreID;
            pkDetail.ReceivePalletID = receivePallet.ID;
            pkDetail.ManufacturerID = receiveDoc.ManufacturerId;
            pkDetail.BoxLevel = 0;
            pkDetail.DeliveryNote = true;

            pkDetail.PhysicalStoreID = palletLocation.PhysicalStoreID;
            pkDetail.Save();

            return pkDetail;
        }
Beispiel #34
0
        /// <summary>
        /// Saves issue order details
        /// </summary>
        /// <param name="orderID"></param>
        /// <param name="dvPickListMakeup"></param>
        public void SavePickList(int orderID, DataView dvPickListMakeup, int userID)
        {
            //~ Check if This Order has a previous Printed Picklist with detail: Note a header only doesnt affect us! //
            var pickList = new PickList();

            pickList.LoadByOrderID(orderID);
            if (pickList.RowCount > 0)
            {
                var pldetail = new PickListDetail();
                pldetail.LoadByPickListID(pickList.ID);
                if (pldetail.RowCount > 0)
                {
                    RemoveFakePartialCommitPickListDetails(orderID);
                    var pickL = new PickList();
                    pickL.LoadByOrderID(orderID);
                    if (pickL.RowCount > 0)
                    {
                        throw new Exception("Picklist has already been printed for this Order ");
                        // This error has been apprearing for the last one year so funny! I hope it won't come again! day: 10/21/2014 @yido  //
                    }
                }
            }
            // Create a pick list entry
            Order ord = new Order();

            ord.LoadByPrimaryKey(orderID);
            PickList       pl        = new PickList();
            PalletLocation plocation = new PalletLocation();

            plocation.LoadByPrimaryKey(Convert.ToInt32(dvPickListMakeup[0]["PalletLocationID"]));
            pl.AddNew();
            pl.OrderID  = orderID;
            pl.PickType = "Pick";
            pl.PickedBy = userID;

            pl.IsConfirmed          = false;
            pl.IssuedDate           = DateTimeHelper.ServerDateTime;
            pl.SavedDate            = DateTimeHelper.ServerDateTime;
            pl.PickedDate           = DateTimeHelper.ServerDateTime;
            pl.IsWarehouseConfirmed = 0;
            pl.WarehouseID          = plocation.WarehouseID;
            pl.Save();
            PickListDetail pld = new PickListDetail();
            ReceivePallet  rp  = new ReceivePallet();
            ReceiveDoc     rd  = new ReceiveDoc();

            PickFace pf = new PickFace();

            foreach (DataRowView drv in dvPickListMakeup)
            {
                pld.AddNew();
                pld.PickListID    = pl.ID;
                pld.OrderDetailID = Convert.ToInt32(drv["OrderDetailID"]);

                pld.ItemID      = Convert.ToInt32(drv["ItemID"]);
                pld.BatchNumber = (drv["BatchNo"].ToString());
                if (drv["ExpDate"] != DBNull.Value)
                {
                    pld.ExpireDate = Convert.ToDateTime(drv["ExpDate"]);
                }
                pld.ManufacturerID   = Convert.ToInt32(drv["ManufacturerID"]);
                pld.BoxLevel         = Convert.ToInt32(drv["BoxLevel"]);
                pld.QtyPerPack       = Convert.ToInt32(drv["QtyPerPack"]);
                pld.Packs            = Convert.ToDecimal(drv["Pack"]);
                pld.PalletLocationID = Convert.ToInt32(drv["PalletLocationID"]);
                pld.QuantityInBU     = Convert.ToDecimal(drv["QtyInBU"]);
                pld.ReceiveDocID     = Convert.ToInt32(drv["ReceiveDocID"]);
                pld.ReceivePalletID  = Convert.ToInt32(drv["ReceivePalletID"]);
                if (drv["CalculatedCost"] != DBNull.Value)
                {
                    pld.Cost = Convert.ToDouble(drv["CalculatedCost"]);
                }
                if (drv["UnitPrice"] != DBNull.Value)
                {
                    pld.UnitPrice = Convert.ToDouble(drv["UnitPrice"]);
                }
                int ReceivePalletID = Convert.ToInt32(drv["ReceivePalletID"]);
                rp.LoadByPrimaryKey(ReceivePalletID);
                pld.StoreID = Convert.ToInt32(drv["StoreID"]);

                if (drv["DeliveryNote"] != null)
                {
                    pld.DeliveryNote = Convert.ToBoolean(drv["DeliveryNote"]);
                }
                else
                {
                    pld.DeliveryNote = false;
                }


                if (rp.IsColumnNull("ReservedStock"))
                {
                    rp.ReservedStock = Convert.ToDecimal(pld.QuantityInBU);
                }
                else
                {
                    rp.ReservedStock += Convert.ToDecimal(pld.QuantityInBU);
                }
                if (drv["UnitID"] != DBNull.Value)
                {
                    pld.UnitID = Convert.ToInt32(drv["UnitID"]);
                }
                plocation.LoadByPrimaryKey(Convert.ToInt32(drv["PalletLocationID"]));
                pld.PhysicalStoreID = plocation.PhysicalStoreID;

                rp.Save();

                if (drv["StorageTypeID"].ToString() == StorageType.PickFace)
                {
                    pf.LoadByPalletLocation(Convert.ToInt32(drv["PalletLocationID"]));
                    //pf.Balance -= Convert.ToDecimal(pld.QuantityInBU);
                    pf.Save();
                }
            }

            pld.Save();
            ord.ChangeStatus(OrderStatus.Constant.PICK_LIST_GENERATED, CurrentContext.UserId);
            ord.Save();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            LogReceiptChange change = new LogReceiptChange(rDoc);

            if (txtBatchNo.EditValue != null)
            {
                rDoc.BatchNo = txtBatchNo.Text;
            }
            if (dtExpiry.EditValue != null)
            {
                rDoc.ExpDate = dtExpiry.DateTime;
            }
            else
            {
                rDoc.SetColumnNull("ExpDate");
            }
            if (txtPrice.EditValue != null)
            {
                rDoc.Cost = Convert.ToDouble(txtPrice.EditValue);
            }

            if(lkAccount.EditValue!=null)
            {
                rDoc.StoreID = Convert.ToInt32(lkAccount.EditValue);
                //TODO:Edit other tables as well.
            }

            if(lkUnit.EditValue!=null)
            {
                int unitID = Convert.ToInt32(lkUnit.EditValue);
                if (rDoc.UnitID != unitID)
                {

                    rDoc.UnitID = Convert.ToInt32(lkUnit.EditValue);
                    BLL.ItemUnit itemUnit = new ItemUnit();
                    itemUnit.LoadByPrimaryKey(rDoc.UnitID);
                    rDoc.QtyPerPack = itemUnit.QtyPerUnit;
                    rDoc.Quantity = rDoc.NoOfPack * rDoc.QtyPerPack;
                    rDoc.QuantityLeft = rDoc.Quantity;

                    BLL.ReceivePallet rp = new ReceivePallet();
                    rp.LoadByReceiveDocID(rDoc.ID);
                    rp.Balance = rDoc.QuantityLeft;
                    rp.ReceivedQuantity = rDoc.Quantity;

                    rDoc.Save();
                    rp.Save();
                }
            }

            // decide to save the quantity or not
            //Lord have mercy, this is not a proper way to do it,
            decimal quantity = Convert.ToDecimal(txtQuanitity.EditValue.ToString().Replace(",", ""));

            if (txtQuanitity.Enabled && !rDoc.HasTransactions() && rDoc.Quantity != rDoc.QtyPerPack * quantity)
            {
                // now find the receive pallets
                ReceivePallet receivePallet = new ReceivePallet();
                receivePallet.LoadNonZeroRPByReceiveID(rDoc.ID);
                if (receivePallet.RowCount > 1)
                {
                    //
                    XtraMessageBox.Show(
                        "This Item is stored in more than one location and chaning the quanitity is not implemented. try to consolidate it and try again");
                }
                else
                {

                    rDoc.NoOfPack = quantity;
                    receivePallet.Balance = receivePallet.ReceivedQuantity = rDoc.QuantityLeft = rDoc.Quantity = quantity * rDoc.QtyPerPack;
                    rDoc.Save();
                    receivePallet.Save();
                }
            }
            else if (rDoc.Quantity != quantity * rDoc.QtyPerPack)
            {
                XtraMessageBox.Show("The Quantity was not edited because there was an issue transaction on it.");
            }

            rDoc.RefNo = txtGrvNo.EditValue.ToString();
            //rDoc.SupplierID = Convert.ToInt32(lkSupplier.EditValue);
            if (lkManufacturer.EditValue != null)
                rDoc.ManufacturerId = Convert.ToInt32(lkManufacturer.EditValue);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            rDoc.Save();
            change.SaveChangeLog(rDoc, CurrentContext.UserId);
            this.LogActivity("Save-Receipt-Change", rDoc.ID);
            this.Close();
        }
Beispiel #36
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);
        }
        private void tpDelete_Click(object sender, EventArgs e)
        {
            DataRow dr = gridViewBinCard.GetFocusedDataRow();
             if (Convert.ToInt32(dr["Precedance"]) != 3)
             {
             XtraMessageBox.Show("You cannot delete this");
             return;
             }
             if (CurrentContext.LoggedInUser.UserType == UserType.Constants.DISTRIBUTION_MANAGER_WITH_DELETE)
             {

             if (
                 XtraMessageBox.Show(
                     "Are you sure you want to delete this transaction? You will not be able to undo this.",
                     "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
             {
                 MyGeneration.dOOdads.TransactionMgr tranMgr =
                     MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

                 try
                 {
                     tranMgr.BeginTransaction();

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

                     PickListDetail pld = new PickListDetail();
                     int issueID = Convert.ToInt32(dr["ID"]);
                     //pld.LoadByOrderAndItem(Convert.ToInt32(dr["OrderID"]), Convert.ToInt32(dr["ItemID"]),
                     //                       Convert.ToInt32(dr["Quantity"]));
                     idoc.LoadByPrimaryKey(issueID);
                     pld.LoadByPrimaryKey(idoc.PLDetailID);

                     string RefNo = idoc.RefNo;

                     rdoc.LoadByPrimaryKey(idoc.RecievDocID);

                     //if (pld.RowCount == 0)
                     //{
                     //    pld.LoadByOrderAndItem(Convert.ToInt32(dr["OrderID"]), Convert.ToInt32(dr["ItemID"]));
                     //}

                     rp.LoadByPrimaryKey(pld.ReceivePalletID);
                     PalletLocation pl = new PalletLocation();
                     pl.loadByPalletID(rp.PalletID);

                     if (pl.RowCount == 0)
                     {
                         pl.LoadByPrimaryKey(pld.PalletLocationID);
                         if (pl.IsColumnNull("PalletID"))
                         {
                             pl.PalletID = rp.PalletID;
                             pl.Save();
                         }
                         //rp.LoadNonZeroRPByReceiveID(rdoc.ID);
                     }

                     if (rp.RowCount == 0)
                     {
                         XtraMessageBox.Show("You cannot delete this item, please contact the administrator", "Error");
                         return;
                     }
                     if (rp.RowCount > 0)
                     {
                         rdoc.QuantityLeft += idoc.Quantity;
                         rp.Balance += idoc.Quantity;
                         pld.QuantityInBU = 0;

                         // are we adding it the pick face?
                         // if so add it to the balance of the pick face also
                         pl.loadByPalletID(rp.PalletID);

                         if (pl.RowCount == 0)
                         {
                             PutawayLocation plocation = new PutawayLocation(rdoc.ItemID);

                             // we don't have a location for this yet,
                             // select a new location
                             //PutawayLocataion pl = new PutawayLocataion();
                             if (plocation.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                             {
                                 pl.LoadByPrimaryKey(plocation.PalletLocationID);
                                 if (pl.RowCount > 0)
                                 {
                                     pl.PalletID = rp.PalletID;
                                     pl.Save();
                                 }
                             }
                         }

                         if (pl.RowCount > 0)
                         {

                             PickFace pf = new PickFace();
                             pf.LoadByPalletLocation(pl.ID);
                             if (pf.RowCount > 0)
                             {
                                 pf.Balance += Convert.ToInt32(idoc.Quantity);
                                 pf.Save();
                             }

                             IssueDocDeleted.AddNewLog(idoc, CurrentContext.UserId);
                             idoc.MarkAsDeleted();
                             rdoc.Save();
                             rp.Save();
                             idoc.Save();

                             // now refresh the window
                             XtraMessageBox.Show("Issue Deleted!", "Confirmation", MessageBoxButtons.OK,
                                                 MessageBoxIcon.Information);
                             tranMgr.CommitTransaction();
                             //TODO: refresh the list
                             // gridViewReferences_FocusedRowChanged(null, null);
                         }

                     }
                     else
                     {
                         XtraMessageBox.Show(
                             "This delete is not successfull because a free pick face location was not selected. please select a free location and try again.",
                             "Error Deleteing issue transaction", MessageBoxButtons.OK, MessageBoxIcon.Error);
                         tranMgr.RollbackTransaction();
                     }
                 }
                 catch
                 {
                     XtraMessageBox.Show("This delete is not successfull", "Warning ...", MessageBoxButtons.OK,
                                         MessageBoxIcon.Warning);
                     tranMgr.RollbackTransaction();
                 }
             }
             }
             else
             {
             XtraMessageBox.Show(
                 "You cannot delete this transaction because you don't have previlage. Please contact the administrator if you thing this is an error.",
                 "Delete is not allowed");
             }
        }
 /// <summary>
 /// Creates the procedure receive doc receive pallet.
 /// </summary>
 private static void CreateProcedureReceiveDocReceivePallet()
 {
     ReceivePallet rp = new ReceivePallet();
     string storedProc = HCMIS.Repository.Queries.ReceivePallet.SpCreateProcedureReceiveDocReceivePallet();
     rp.LoadFromRawSql(storedProc);
 }
        //, string guid)
        private void SavePalletization(ReceiveDoc rec, DataRowView drow)
        {
            if ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") && rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED) || (rec.Quantity == 0 && rec.IsColumnNull("ShortageReasonID")))
            {
                HandleFullNotReceivedAndMultipleBatchPalletlization(rec,drow);
                return;
            }
            string guid;

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

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

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

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

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

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

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

                    int qtyPerPack = im.QuantityInBasicUnit;

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

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

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

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

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

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

                        }
                    }

                }
            }

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

                    int qtyPerPack = im.QuantityInBasicUnit;

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

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

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

            }

            rec.Save();
            rp.Rewind();
            while (!rp.EOF)
            {
                rp.ReceiveID = rec.ID;
                rp.MoveNext();
            }
            rp.Save();
            SavePutAwayItems();
        }
        /// <summary>
        /// This method handles Receive of an Item with full NotReceived Reason
        /// </summary>
        /// <param name="rec"></param>
        /// <param name="dr"></param>
        private void HandleFullNotReceivedAndMultipleBatchPalletlization(ReceiveDoc rec,DataRowView dr)
        {
            DataRow firstEntry = null;
            bool noSoundItems = false;
            // Here: We Can Use One of the Items on a receipt //
            if ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") &&
                 rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED))
            {
                firstEntry =
                    rec.DefaultView.Table.Select(String.Format("[ID] > 0 AND [IsDamaged] = 0")).FirstOrDefault();
            }

            //~ This is a multiple batch case ~//
            if ((rec.Quantity == 0 && rec.IsColumnNull("ShortageReasonID")))
            {
                  var oneAmongMultipleBatchsAndDbSavedGuid =
                        _dtRecGrid.Select(string.Format("CopyGUID = '{0}' And IsCopied = 1 ", dr["CopyGUID"]));

                DataRow[] dbSavedcounts = oneAmongMultipleBatchsAndDbSavedGuid.Any()
                    ? rec.DefaultView.Table.Select(String.Format("GUID = '{0}'",
                        oneAmongMultipleBatchsAndDbSavedGuid[0]["GUID"]))
                    : oneAmongMultipleBatchsAndDbSavedGuid;

                firstEntry = dbSavedcounts.Any()
                    ? dbSavedcounts.FirstOrDefault()
                    : rec.DefaultView.Table.Select(String.Format("[ID] > 0 AND [IsDamaged] = 0")).FirstOrDefault();
            }
            // If we cant find any normal receive in this receipt let's just use one of receiveDocID's randomly: This is just to save a not received Entry with zero quantity! (an awful recent request!)~//
            if (firstEntry == null && ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") &&
                rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED)))
            {
                firstEntry =
                    rec.DefaultView.Table.Select(String.Format("[ID] > 0")).FirstOrDefault();
                if (firstEntry != null)
                {
                    noSoundItems = true;

                }
            }
            // This is  a Zero Quantity ReceiveDoc //
            if (firstEntry != null)
            {
                rec.PhysicalStoreID = Convert.ToInt16(firstEntry["PhysicalStoreID"]);
                rec.InventoryPeriodID = Convert.ToInt16(firstEntry["InventoryPeriodID"]);
                rec.Save();

                // Lets Create a Zero ReceivePallet in the same palletlocation as one of the Items in the receipt //
                var oneOfrecievePallet = new BLL.ReceivePallet();
                oneOfrecievePallet.LoadByReceiveDocID(Convert.ToInt16(firstEntry["ID"]));

                var newReceivePallet = new BLL.ReceivePallet();
                newReceivePallet.AddNew();
                newReceivePallet.IsOriginalReceive = true;
                newReceivePallet.ReceiveID = rec.ID;
                newReceivePallet.Balance = newReceivePallet.ReceivedQuantity = newReceivePallet.ReservedStock = 0;
                newReceivePallet.PalletID = oneOfrecievePallet.PalletID;
                newReceivePallet.PalletLocationID = oneOfrecievePallet.PalletLocationID;
                newReceivePallet.BoxSize = oneOfrecievePallet.BoxSize;
                newReceivePallet.Save();
            }

            if (!rec.IsColumnNull("ShortageReasonID") && rec.ShortageReasonID == BLL.ShortageReasons.Constants.NOT_RECEIVED)
            {
                var recShortage = new ReceiveDocShortage();
                recShortage.AddNew();
                recShortage.ShortageReasonID = rec.ShortageReasonID;
                recShortage.ReceiveDocID = rec.ID;
                recShortage.NoOfPacks = Convert.ToDecimal(dr["InvoicedQty"]);
                recShortage.Save();
            }
        }
        /// <summary>
        /// Moves the specified pick list ID.
        /// </summary>
        /// <param name="PickListID">The pick list ID.</param>
        public static void Move(int PickListID)
        {
            DataView dv = GetTransferReportForStore();
            PalletLocation pl = new PalletLocation();
            foreach (DataRowView dr in dv)
            {

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

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

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

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

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

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

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

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

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

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

            }
        }
 public static void ReserveQty(decimal pack, int receivePalletId, bool isOriginalReceive = true)
 {
     var receivepallet = new ReceivePallet();
     receivepallet.LoadByPrimaryKey(receivePalletId);
     receivepallet.IsOriginalReceive = isOriginalReceive;
     receivepallet.ReservedStock = receivepallet.ReservedStock + pack;
     if (receivepallet.Balance >= receivepallet.ReservedStock)
         receivepallet.Save();
 }
        private void btnFixLocationStuff_Click(object sender, EventArgs e)
        {
            int storeID = Convert.ToInt32(lkStoreLocation.EditValue);
            BLL.ReceiveDoc rd = new BLL.ReceiveDoc();
            rd.LoadReceivesForStores(storeID);
            while(!rd.EOF)
            {
                BLL.ReceivePallet rp = new BLL.ReceivePallet();
                rp.LoadByReceiveDocID(rd.ID);
                decimal receivedQuantity = 0, balance = 0;
                if (rp.RowCount==1)// rp.RowCount > 0)
                {
                    while (!rp.EOF)
                    {
                        receivedQuantity += rp.IsColumnNull("ReceivedQuantity") ? 0 : rp.ReceivedQuantity;
                        balance += rp.IsColumnNull("Balance") ? 0 : rp.Balance;
                        rp.MoveNext();
                    }
                    rp.Rewind();

                    while (!rp.EOF && rp.IsColumnNull("ReceivedQuantity"))
                    {
                        rp.MoveNext();
                    }

                    if (rd.Quantity != receivedQuantity && rd.Quantity > receivedQuantity)
                    {
                        rp.ReceivedQuantity += (rd.Quantity - receivedQuantity);
                    }
                    if (rd.QuantityLeft != balance && rd.QuantityLeft > 0)//rd.QuantityLeft > balance)
                    {
                        rp.Balance += (rd.QuantityLeft - balance);
                    }
                    rp.Save();
                }
                rd.MoveNext();
            }
            XtraMessageBox.Show("Completed!");
        }
        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 btnRelocatePallet_Click(object sender, EventArgs e)
        {
            //Get the chosen pallet Location
            BLL.PalletLocation palletLocation = new BLL.PalletLocation();
            palletLocation.LoadByPrimaryKey(Convert.ToInt16(lkAvailablePalletLocation.EditValue));

            //Get the chosen misplaced receivepallet entry
            DataRow dr = grdViewMisplacedItems.GetFocusedDataRow();
            int receivePalletID = Convert.ToInt32(dr["ID"]);

            BLL.ReceivePallet rp = new BLL.ReceivePallet();
            rp.LoadByPrimaryKey(receivePalletID);
            if (palletLocation.IsColumnNull("PalletID"))
            {
                palletLocation.PalletID = rp.PalletID;
                palletLocation.Save();
            }
            else
            {
                rp.PalletID = palletLocation.PalletID;
                rp.Save();
            }

            int storeID = Convert.ToInt16(lkStoreLocation.EditValue);
            LoadMisplacedItems(storeID);

            XtraMessageBox.Show("Placed!!");
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            int warehouseID = Convert.ToInt32(lkWarehouse.EditValue);

            receiveDoc.Rewind();
            var po = new BLL.PO();
            var receiptInvoice = new BLL.ReceiptInvoice();

            while (!receiveDoc.EOF)
            {
                //Handle the PO.
                //int receiptID;
                if (po.RowCount == 0 || po.StoreID != receiveDoc.StoreID)
                {
                    Supplier supplier = new Supplier();
                    po = BLL.PO.CreatePOforStandard(OrderType.CONSTANTS.STANDARD_ORDER, receiveDoc.StoreID,
                                                    supplier.GetHubHomeOfficeSupplierID(), "",CurrentContext.LoggedInUser.ID);
                    //Should we receive it as hub to hub transfer? We're now using Standard order.
                    receipt = BLL.ReceiptInvoice.CreateAutomaticReceiptInvoiceForSTVTransfer(po.ID, warehouseID, STVNo,
                                                                                             CurrentContext.UserId);
                }

                receiveDoc.Quantity = receiveDoc.QtyPerPack * receiveDoc.NoOfPack;
                receiveDoc.ReceiptID = receipt.ID;
                receiveDoc.MoveNext();
            }
            receiveDoc.Save();

            //Save the location
            receiveDoc.Rewind();

            BLL.ReceivePallet receivePallet = new ReceivePallet();
            while (!receiveDoc.EOF)
            {
                //Save Location Information
                BLL.PalletLocation palletLocation = new PalletLocation();

                receivePallet.AddNew();

                int palletLocationID = Convert.ToInt32(receiveDoc.GetColumn("PalletLocationID"));
                receivePallet.PalletLocationID = palletLocationID;

                palletLocation.LoadByPrimaryKey(palletLocationID);

                receivePallet.PalletID = palletLocation.PalletID;
                receivePallet.ReceivedQuantity = receiveDoc.Quantity;
                receivePallet.Balance = receiveDoc.Quantity;
                receivePallet.ReceiveID = receiveDoc.ID;
                receivePallet.ReservedStock = 0;

                //Save Discrepancy information if there is any
                receiveDocShortage.Rewind();
                while (receiveDocShortage.FindNextByGUID(receiveDoc.GetColumn("GUID").ToString()))
                {
                    receiveDocShortage.ReceiveDocID = receiveDoc.ID;

                    if (receiveDocShortage.ShortageReasonID == ShortageReasons.Constants.DAMAGED)
                    {
                        receiveDoc.NoOfPack += receiveDocShortage.NoOfPacks;
                        receiveDoc.Quantity += receiveDocShortage.NoOfPacks*receiveDoc.QtyPerPack;

                        palletLocationID = Convert.ToInt32(receiveDocShortage.GetColumn("PalletLocationID"));
                        receivePallet.AddNew();
                        receivePallet.PalletLocationID = palletLocationID;
                        palletLocation.LoadByPrimaryKey(palletLocationID);

                        receivePallet.PalletID = palletLocation.PalletID;
                        receivePallet.ReceivedQuantity = receiveDocShortage.NoOfPacks*receiveDoc.QtyPerPack;
                        receivePallet.Balance = receiveDocShortage.NoOfPacks*receiveDoc.QtyPerPack;
                        receivePallet.ReceiveID = receiveDoc.ID;
                        receivePallet.ReservedStock = 0;
                    }
                }

                receiveDoc.MoveNext();
            }
            receivePallet.IsOriginalReceive = true;
            receivePallet.Save();
        }
        internal void Commit(DateTime ethiopianDate, BackgroundWorker backgroundWorker = null)
        {
            InventoryCommitMemberInstance.Transaction.BeginTransaction();
            //TODO: Create the order detail, pass the order id above this inventory object
            int count = 0;

            if (backgroundWorker != null)
            {
                backgroundWorker.ReportProgress(0, "Detail");
            }
            //Add the System Damaged quantity, System Sound Quantity and System Expired Quantity to generate this.
            decimal endingSoundBalance, endingDamagedBalance, endExpiredBalance;

            endingSoundBalance   = !IsColumnNull("SystemSoundQuantity") ? SystemSoundQuantity : 0;
            endingDamagedBalance = !IsColumnNull("SystemDamagedQuantity") ? SystemDamagedQuantity : 0;
            endExpiredBalance    = !IsColumnNull("SystemExpiredQuantity") ? SystemExpiredQuantity : 0;

            decimal endingTotalBalance = endingSoundBalance + endingDamagedBalance + endExpiredBalance;

            ItemUnit itemUnit = new ItemUnit();

            itemUnit.LoadByPrimaryKey(UnitID);
            if (IsColumnNull("ReceiveDocID") && IsColumnNull("DamagedReceiveDocID")) // This has been recently added to
            {
                if (endingTotalBalance > 0)
                {
                    OrderDetail.GenerateOrderDetail(UnitID, ActivityID, endingTotalBalance,
                                                    InventoryCommitMemberInstance.Order.ID, itemUnit.QtyPerUnit, ItemID);

                    //TODO: Get the receive doc details for this inventory object
                    ReceivePallet receivePallet = new ReceivePallet();
                    receivePallet.LoadForInventory(this);
                    receivePallet.Rewind();

                    while (!receivePallet.EOF)
                    {
                        //Review: New Code
                        PickListDetail pickListDetail = PickListDetail.GeneratePickListDetail(receivePallet,
                                                                                              InventoryCommitMemberInstance
                                                                                              .PickList.ID,
                                                                                              Convert.ToDecimal(
                                                                                                  receivePallet.Balance));

                        //TODO: Create the issueDoc, pass the picklistdetail, orderid and picklist above
                        IssueService issueService = new IssueService();

                        IssueDoc issueDoc = issueService.CreateIssueFromPicklist(pickListDetail,
                                                                                 InventoryCommitMemberInstance.Order,
                                                                                 ethiopianDate,
                                                                                 InventoryCommitMemberInstance.Issue,
                                                                                 InventoryCommitMemberInstance.User);

                        //Link IssueDoc to InventoryTable
                        // Could have put it on the issueService method but it would have decrease the useablity
                        IssueDocInventory issueDocInventory = new IssueDocInventory();
                        issueDocInventory.AddNew();
                        issueDocInventory.InventoryID = ID;
                        issueDocInventory.IssueDocID  = issueDoc.ID;
                        issueDocInventory.Save();

                        receivePallet.MoveNext();
                        count++;
                        if (backgroundWorker != null)
                        {
                            backgroundWorker.ReportProgress(
                                Convert.ToInt32((Convert.ToDecimal(count) / Convert.ToDecimal(receivePallet.RowCount)) * 100),
                                "Detail");
                        }
                    }
                }
                //TODO: Create the receive (use the inventory object itself)
                ReceiveService receiveService = new ReceiveService();
                if (!IsColumnNull("InventorySoundQuantity") && InventorySoundQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                  ID, QuantityType.Sound,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    ReceiveDocID = receiveDoc.ID;
                }

                if (!IsColumnNull("InventoryExpiredQuantity") && InventoryExpiredQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                  ID, QuantityType.Expired,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    ReceiveDocID = receiveDoc.ID;
                }

                if (!IsColumnNull("InventoryDamagedQuantity") && InventoryDamagedQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                  ID, QuantityType.Damaged,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    DamagedReceiveDocID = receiveDoc.ID;
                }

                if (backgroundWorker != null)
                {
                    backgroundWorker.ReportProgress(100, "Detail");
                }
            }
            else
            {
                if (!IsColumnNull("ReceiveDocID"))
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(ReceiveDocID);
                    receiveDoc.ChangeQuantity(!IsColumnNull("InventorySoundQuantity") ? InventorySoundQuantity
                                                            : !IsColumnNull("InventoryExpiredQuantity") ? InventoryExpiredQuantity
                                                                                        : 0);
                }

                if (!IsColumnNull("DamagedReceiveDocID"))
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(DamagedReceiveDocID);
                    receiveDoc.ChangeQuantity(InventoryDamagedQuantity);
                }
            }
            IsDraft = false;
            Save();
            InventoryCommitMemberInstance.Transaction.CommitTransaction();
        }