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!!");
        }
        /// <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();
            }
        }
        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();
            }
        }
Ejemplo n.º 4
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();
        }
        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!");
        }
        /// <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();
            }
        }
        /// <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();
            }
        }
        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 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");
             }
        }
        //, string guid)
        private void SavePalletization(ReceiveDoc rec, DataRowView drow)
        {
            if ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") && rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED) || (rec.Quantity == 0 && rec.IsColumnNull("ShortageReasonID")))
            {
                HandleFullNotReceivedAndMultipleBatchPalletlization(rec,drow);
                return;
            }
            string guid;

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

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

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

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

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

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

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

                    int qtyPerPack = im.QuantityInBasicUnit;

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

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

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

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

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

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

                        }
                    }

                }
            }

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

                    int qtyPerPack = im.QuantityInBasicUnit;

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

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

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

            }

            rec.Save();
            rp.Rewind();
            while (!rp.EOF)
            {
                rp.ReceiveID = rec.ID;
                rp.MoveNext();
            }
            rp.Save();
            SavePutAwayItems();
        }
        private void OnReplenishClicked(object sender, EventArgs e)
        {
            PalletLocation pl = new PalletLocation();
            PickFace pf = new PickFace();
            DataRow dr = gridPickFaceStockLevelView.GetFocusedDataRow();
            DataRow dr2 = gridReplenishmentChoiceView.GetFocusedDataRow();
            if (dr2 != null)
            {
                // check if the replenishment is from allowed location.
                //
                if (!Convert.ToBoolean(dr2["CanReplenish"]))
                {
                    XtraMessageBox.Show("Please choose replenishment from the first to expire items", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

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

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

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

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

                InternalTransfer it = new InternalTransfer();

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

                BindPickFaceDetailAndReplenismehmnent();
                XtraMessageBox.Show("Your Pick Face is updated, please print the replenishment list and confirm the stock movement", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// Changes the unit ID.
        /// </summary>
        /// <param name="destinationUnitID">The destination unit ID.</param>
        internal void ChangeUnitID(int destinationUnitID)
        {
            BLL.ItemUnit iuTo = new ItemUnit();
            BLL.ItemUnit iuFrom = new ItemUnit();

            iuTo.LoadByPrimaryKey(destinationUnitID);
            iuFrom.LoadByPrimaryKey(this.UnitID);
            decimal multiplier = iuTo.QtyPerUnit / iuFrom.QtyPerUnit;

            while (!this.EOF)
            {

                this.QtyPerPack = iuTo.QtyPerUnit;
                this.Quantity =Convert.ToDecimal(this.Quantity * multiplier);
                this.QuantityLeft = Convert.ToDecimal(multiplier * this.QuantityLeft);
                this.UnitID = iuTo.ID;
                this.Save();

                BLL.ReceivePallet rp = new ReceivePallet();
                rp.LoadByReceiveDocID(this.ID);
                rp.ReceivedQuantity = Convert.ToDecimal(rp.ReceivedQuantity * multiplier);
                rp.Balance = Convert.ToDecimal(rp.Balance * multiplier);
                rp.ReservedStock = Convert.ToInt32(rp.ReservedStock * multiplier);
                rp.Save();

                this.MoveNext();
            }
        }
        /// <summary>
        /// Palletizes the transfer.
        /// </summary>
        /// <param name="rec">The rec.</param>
        public static void PalletizeTransfer(ReceiveDoc rec)
        {
            BLL.ReceivePallet rp = new ReceivePallet();
            Pallet pallet = new Pallet();
            PalletLocation pl = new PalletLocation();
            rec.Rewind();
            BLL.ItemManufacturer im = new BLL.ItemManufacturer();
            rp.AddNew();
            rp.ReceivedQuantity = rec.Quantity;
            rp.Balance = rec.Quantity;
            rp.ReservedStock = 0;
            rp.ReceiveID = rec.ID;
            //Just To Get the First Free pallet
            DataTable dtpl = PalletLocation.GetAllFreeForItem(rec.ItemID, StorageType.Free);
            DataRow drpl = dtpl.Rows[0];
            //After we assign the Location for it
            pl.LoadByPrimaryKey(Convert.ToInt32(drpl["ID"]));

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

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

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

            //Now Save the ReceiveDocConfirmation

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

            //Now Save the palletization.

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

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

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

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

                rp.PalletID = pLocation.PalletID;
                rp.PalletLocationID = pLocation.ID;
                rp.BoxSize = 0;
                rp.IsOriginalReceive = true;
                rp.Save();
            }
        }
        /// <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 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 SaveOrder()
        {
            var order = GenerateOrder();
            var picklist = PickList.GeneratePickList(order.ID);

            int lineNo = 0;

            // This is a kind of initializing the data table.
            OrderDetail ord = new OrderDetail();
            PickListDetail pkDetail = new PickListDetail();
            DataView dv = orderGrid.DataSource as DataView;

            foreach (DataRowView r in dv)
            {
                if (r["ApprovedPacks"] != null && r["ApprovedPacks"] != DBNull.Value && r["ApprovedPacks"].ToString()!= "")
                    if (Convert.ToInt32(r["ApprovedPacks"]) != 0)
                    {
                        lineNo = lineNo + 1;
                        int itemID = Convert.ToInt32(r["ItemID"]);
                        int unitID = Convert.ToInt32(r["UnitID"]);
                        ord.AddNew();
                        ord.OrderID = order.ID;
                        ord.ItemID = itemID;
                        if (r["ApprovedPacks"] != DBNull.Value)
                        {
                            ord.Pack = Convert.ToInt32(r["ApprovedPacks"]);
                        }
                        if (r["QtyPerPack"] != DBNull.Value)
                        {
                            ord.QtyPerPack = Convert.ToInt32(r["QtyPerPack"]);
                        }
                        ord.Quantity = Convert.ToInt32(r["ApprovedPacks"]) * Convert.ToInt32(r["QtyPerPack"]);
                        ord.ApprovedQuantity = Convert.ToInt32(r["ApprovedPacks"]) * Convert.ToInt32(r["QtyPerPack"]);
                        ord.UnitID = unitID;
                        ord.StoreID = Convert.ToInt32(lkAccountType.EditValue);

                        ord.Save();
                        pkDetail.AddNew();
                        pkDetail.PickListID = picklist.ID;
                        pkDetail.ItemID = itemID;
                        pkDetail.PalletLocationID = Convert.ToInt32(r["LocationID"]);
                        pkDetail.BatchNumber = r["BatchNo"].ToString();
                        if (r["ExpDate"] != DBNull.Value)
                            pkDetail.ExpireDate = DateTime.Parse(r["ExpDate"].ToString());

                        pkDetail.StoreID = Convert.ToInt32(r["StoreID"]);
                        pkDetail.UnitID = unitID;
                        pkDetail.ReceiveDocID = Convert.ToInt32(r["ReceiveDocID"]);
                        if (r["UnitPrice"] != DBNull.Value)
                        {
                            pkDetail.Cost = Convert.ToInt32(r["ApprovedPacks"]) * Convert.ToDouble(r["UnitPrice"]);
                            pkDetail.UnitPrice = Convert.ToDouble(r["UnitPrice"]);
                        }
                        pkDetail.Packs = Convert.ToInt32(r["ApprovedPacks"]);
                        pkDetail.QtyPerPack = Convert.ToInt32(r["QtyPerPack"]);
                        pkDetail.QuantityInBU = Convert.ToInt32(r["ApprovedPacks"]) * Convert.ToInt32(r["QtyPerPack"]);
                        pkDetail.StoreID = Convert.ToInt32(r["StoreID"]);
                        pkDetail.ReceivePalletID = Convert.ToInt32(r["ReceivingLocationID"]);
                        pkDetail.ManufacturerID = Convert.ToInt32(r["ManufacturerID"]);
                        pkDetail.BoxLevel = 0;
                        pkDetail.DeliveryNote = true;
                        pkDetail.Save();
                        //To Print The Picklist
                      //Then reserve Items
                        ReceivePallet receivepallet = new ReceivePallet();
                        receivepallet.LoadByPrimaryKey(Convert.ToInt32(r["ReceivingLocationID"]));
                        receivepallet.ReservedStock = receivepallet.ReservedStock + Convert.ToInt32(r["ApprovedPacks"]);
                        receivepallet.Save();

                        DataRow drvpl = dvPickList.NewRow();
                        drvpl["FullItemName"] = r["FullItemName"];
                        drvpl["StockCode"] = r["StockCode"];
                        drvpl["BatchNo"] = r["BatchNo"];
                        if (r["ExpDate"] != DBNull.Value)
                            drvpl["ExpDate"] = Convert.ToDateTime(r["ExpDate"]).ToString("MMM/yyyy");
                        else
                            drvpl["ExpDate"] = DBNull.Value;
                        drvpl["LineNum"] = lineNo + 1;
                        drvpl["ManufacturerName"] = r["Manufacturer"];
                        drvpl["Pack"] = r["ApprovedPacks"];
                        drvpl["UnitPrice"] = r["UnitPrice"];

                        drvpl["Unit"] = r["Unit"];
                        drvpl["PalletLocation"] = r["Location"];
                        drvpl["QtyInSKU"] = Convert.ToInt32(r["ApprovedPacks"]);
                        if (r["UnitPrice"] != DBNull.Value)
                        drvpl["CalculatedCost"] = Convert.ToInt32(r["ApprovedPacks"]) * Convert.ToDouble(r["UnitPrice"]);

                        PalletLocation palletLocation = new PalletLocation();
                        palletLocation.LoadByPrimaryKey(pkDetail.PalletLocationID);
                        drvpl["WarehouseName"] = palletLocation.WarehouseName;
                        drvpl["PhysicalStoreName"] = palletLocation.PhysicalStoreName;
                        var activity = new Activity();
                        activity.LoadByPrimaryKey(pkDetail.StoreID);
                        drvpl["ActivityConcat"] = activity.FullActivityName;
                        drvpl["AccountName"] = activity.AccountName;
                        dvPickList.Rows.Add(drvpl);

                    }

            }
            if (lineNo == 0)
                throw new System.ArgumentException("Please review your list,you haven't approved any Quantity");

            var plr = HCMIS.Desktop.Reports.WorkflowReportFactory.CreatePicklistReport(order, lkForHub.Text,
                                                                                       dvPickList.DefaultView);

            plr.PrintDialog();

            if (!BLL.Settings.IsCenter)
            {
                if (TransferTypeID == 3)
                {

                    XtraMessageBox.Show("Your Store To Store Transfer will be Printed now", "Store To Store Transfer");
                    Transfer.Move(picklist.ID);
                    HCMIS.Desktop.Reports.StoreTransferPrintOut STM =
                        new HCMIS.Desktop.Reports.StoreTransferPrintOut();
                    STM.LoadByPickListID(picklist.ID);
                    STM.PrintDialog();

                }
                else if (TransferTypeID == 2)
                {
                    XtraMessageBox.Show(ReceiveDoc.ReceiveFromAccountTransfer(picklist.ID,
                                                                              Convert.ToInt32(lkForHub.EditValue),
                                                                              CurrentContext.LoggedInUserName,
                                                                              CurrentContext.UserId));
                }
            }
            else
            {
                XtraMessageBox.Show("Picklist Prepared!", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <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);
        }
        public void DeleteAnIssue(int issueDociD)
        {
            ReceiveDoc rdoc = new ReceiveDoc();
            ReceivePallet rp = new ReceivePallet();
            IssueDoc idoc = new IssueDoc();
            idoc.LoadByPrimaryKey(issueDociD);

            if (idoc.IsThereSRM)
            {
                throw new Exception("There is an SRM for this issue.  You can't void it.");
            }

            PickListDetail pld = new PickListDetail();
            //pld.LoadByOrderAndItem(idoc.OrderID, idoc.ItemID, idoc.NoOfPack);
            pld.LoadByPrimaryKey(idoc.PLDetailID);

            string RefNo = idoc.RefNo;

            rdoc.LoadByPrimaryKey(idoc.RecievDocID);

            //if (pld.RowCount == 0)
            //{
            //    pld.LoadByOrderAndItem(idoc.OrderID, idoc.ItemID);
            //}

            rp.LoadByReceiveDocID(idoc.RecievDocID);
            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();
                }

            }

            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;

                //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)
                {
                    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();
                    pld.Save();
                }
                else
                {
                    XtraMessageBox.Show(
                        "This delete is not successful 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);

                }
            }
        }
        /// <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();
        }
        private void btnCommit_Click(object sender, EventArgs e)
        {
            if (ValidateQuarantine())
            {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                 it.AddNew();
                                 it.ItemID = rd.ItemID;
                                 it.BoxLevel = 0;// im.PackageLevel;
                                 //it.ExpireDate = rd.ExpDate;
                                 if (!rd.IsColumnNull("ExpDate"))
                                 {
                                     it.ExpireDate = rd.ExpDate;
                                 }
                                 it.BatchNumber = rd.BatchNo;
                                 it.ManufacturerID = Convert.ToInt32(dr["ManufacturerID"]);//im.ManufacturerID;
                                 it.FromPalletLocationID = qPalletLocationID;
                                 it.ToPalletLocationID = int.Parse(dr["NewPalletLocation"].ToString()); //pl2.ID;
                                 it.QtyPerPack = 1;
                                //it.Packs = pack qty;
                                 it.ReceiveDocID = rp.ReceiveID;
                                 it.QuantityInBU = amount;// it.QtyPerPack;
                                 it.Type = "ReLocation";
                                 it.IssuedDate = DateTime.Today;
                                 it.Status = 0;
                                 it.PrintNumber = printNubmer;
                                 it.Save();
                             }
                         }
                    }
                    transaction.CommitTransaction();
                    BindQuarantine();
                    XtraMessageBox.Show("Quarantine Write off/Adjustment was commitd.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        /// <summary>
        /// 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();
        }
        private void btnAdjustments_Click(object sender, EventArgs e)
        {
            if (ValidateMoveToAdjustments())
            {
                if (DialogResult.Yes == XtraMessageBox.Show("Are you sure you would like to commit this adjustment?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {

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

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

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

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

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

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

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

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

                         }
                    }
                    PopulateItemDetails();
                    XtraMessageBox.Show("Items adjusted successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Ejemplo n.º 24
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();
        }
        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();
            }
        }
 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 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();
        }
        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 ChangeQuantity(decimal quantity)
        {
            ItemUnit itemUnit = new ItemUnit();
            itemUnit.LoadByPrimaryKey(UnitID);
            ReceiveDocConfirmation receiveDocConfirmation = new ReceiveDocConfirmation();
            receiveDocConfirmation.LoadByReceiveDocID(ID);

            if(receiveDocConfirmation.ReceiptConfirmationStatusID == ReceiptConfirmationStatus.Constants.GRV_PRINTED)
            {
                throw new Exception("Price has already been set for this Item, You cannot commit the Change you have Made");
            }

            if(QuantityLeft != Quantity)
            {
                 throw new Exception("Some Quantity has already been issued, You cannot commit the Change you have Made");
            }

            QuantityLeft= Quantity = quantity * itemUnit.QtyPerUnit;
            InvoicedNoOfPack = NoOfPack = quantity;
            Save();
            ReceivePallet receivePallet = new ReceivePallet();
            receivePallet.LoadByReceiveDocID(ID);

            receivePallet.ReceivedQuantity = receivePallet.Balance = Quantity;
            receivePallet.Save();
        }