private void BinCardTransactionLoad(object sender, EventArgs e)
        {
            Item itm = new Item();
            itm.LoadByPrimaryKey(_ItemID);
            txtItemName.Text = txtitmName.Text = itm.FullItemName;
            this.Text = string.Format("{0} Detail Report", itm.FullItemName);

            BLL.Warehouse clusters = new BLL.Warehouse();
            clusters.LoadUsersClustersContainingItem(CurrentContext.UserId, _ItemID, _UnitID.Value, _StoreID);
            lkWarehouses.Properties.DataSource = clusters.DefaultView;
            lkWarehouses.ItemIndex = 0;

            lkBinCardWarehouse.Properties.DataSource = clusters.DefaultView;
            lkBinCardWarehouse.ItemIndex = 0;

            lblItemID.Text = this._ItemID.ToString();
            lblItemSerialNumber.Text = itm.SerialNumber;

            lkYear.Properties.DataSource = itm.AllYears();
            lkYear.EditValue = _Year;

            lkWarehouses_EditValueChanged(null, null);

            ItemUnit iu = new ItemUnit();
            iu.LoadByPrimaryKey(_UnitID.Value);
            lblBUnit.Text = iu.Text;

            dtDate.Value = DateTimeHelper.ServerDateTime;
            dtDate.CustomFormat = "MM/dd/yyyy";
            dtCurrent = ConvertDate.DateConverter(dtDate.Text);

            Activity stor = new Activity();
            stor.LoadByPrimaryKey(_StoreID);

            BindLocationView();

            if (CurrentContext.LoggedInUser.UserType == UserType.Constants.FINANCE ||
                CurrentContext.LoggedInUser.UserType == UserType.Constants.FUND_OFFICER)
            {
                tbClassicBinCard.Text = "Stock Card";
            }
            else
            {
                colTotalCost.Visible = false;
                colUnitCost.Visible = false;
                tbSOHPriceSummary.Visible = false;
            }

            if (this.HasPermission("Show-Classic-Bin-Card"))
            {
                tbClassicBinCard.Visible = false;
            }
            if (this.HasPermission("Show-Bin-Card"))
            {
                tbBinCard.Visible = false;
            }
        }
 public static string GetUnitText(int itemUnitID)
 {
     BLL.ItemUnit iUnit = new ItemUnit();
     iUnit.LoadByPrimaryKey(itemUnitID);
     if (iUnit.RowCount > 0)
     {
         return(iUnit.Text);
     }
     return("");
 }
        public static StockCardReport CreateStockCard(int activityID, int itemID, int unitID, int warehouse, int manufactuererID, DateTime? startDate = null, DateTime? endDate = null)
        {
            BLL.Balance balance = new Balance();

            BLL.Item item = new Item();
            item.LoadByPrimaryKey(itemID);

            ItemUnit iunit = new ItemUnit();
            iunit.LoadByPrimaryKey(unitID);

            BLL.Warehouse physicalStore = new Warehouse();
            physicalStore.LoadByPrimaryKey(warehouse);
            var dataView = new DataView();

            if(startDate == null || endDate == null)
            {
                dataView = Balance.GetStockCardByWarehouse(activityID, itemID, unitID, EthiopianDate.EthiopianDate.Now.FiscalYear,
                                          warehouse, manufactuererID);
            }
            else
            {
                dataView = Balance.GetStockCardByDate(activityID, itemID, unitID, warehouse, manufactuererID,
                                                      startDate.Value, endDate.Value);

            }
            StockCardReport report = new StockCardReport();
            report.DataSource = dataView;

            // Bind the headers here.
            report.StockCode.Text = item.StockCode;
            report.Description.Text = item.FullItemName;
            report.Unit.Text = iunit.Text;

            Activity store = new Activity();
            store.LoadByPrimaryKey(activityID);
            report.Account.Text = store.AccountName;
            report.SubAccount.Text = store.SubAccountName;
            report.Activity.Text = store.Name;

            Manufacturer manufacturers = new Manufacturer();
            manufacturers.LoadByPrimaryKey(manufactuererID);
            report.Manufacturer.Text = manufacturers.Name;
            // TODO: add the Item Source Here (the suggested interpretation is that item source is supplier)
            report.PrintedBy.Text = string.Format("Generated By: {0} On {1}", CurrentContext.LoggedInUserName,
                                                  BLL.DateTimeHelper.ServerDateTime.ToString("dd-MM-yyyy hh:mm tt"));
            report.Store.Text = physicalStore.Name;

            report.AppVersion.Text = "HCMIS";
            return report;
        }
        private void OrderDetailForm_Load(object sender, EventArgs e)
        {
            Item item = new Item();
            item.LoadByPrimaryKey(_itemID);

            txtItemName.Text = item.FullItemName;

            ItemUnit iu = new ItemUnit();
            iu.LoadByPrimaryKey(_unitID);
            txtUnit.Text = iu.Text;

            BLL.Balance balance = new Balance();
            gridApprovedPrinted.DataSource = balance.GetApprovedValueForFacility(CurrentContext.UserId, item.ID, iu.ID);

            gridPicklistPrinted.DataSource = balance.GetPicklistedValueForFacility(CurrentContext.UserId, item.ID, iu.ID);

            var activities = new Activity();
            activities.LoadByUserID(CurrentContext.UserId);

            DataTable dtbl = null;
            while (!activities.EOF)
            {
                DataTable dt = balance.GetSOHForAnItem(activities.ID, item.ID, iu.ID);
                if (dt != null && dt.Rows.Count > 0)
                {
                    dt.Columns.Add("Account");
                    dt.Rows[0]["Account"] = activities.FullActivityName;
                    if (dtbl == null && Convert.ToInt32(dt.Rows[0]["SOH"]) > 0)
                    {
                        dtbl = dt;
                    }
                    else if (Convert.ToInt32(dt.Rows[0]["SOH"]) > 0)
                    {
                        dtbl.ImportRow(dt.Rows[0]);
                    }
                }
                activities.MoveNext();
            }

            gridItemStockStatus.DataSource = dtbl;
            this.Text = string.Format("({0} - {1}) Details of : {2}", _itemID, _unitID, item.FullItemName);
        }
        public static Reports.BinCardReport CreateBinCard(int activityID, int itemID, int unitID, int warehouse,DateTime? startDate=null,DateTime? endDate =null)
        {
            BLL.Balance balance = new Balance();

            BLL.Item item = new Item();
            item.LoadByPrimaryKey(itemID);

            ItemUnit iunit = new ItemUnit();
            iunit.LoadByPrimaryKey(unitID);

            Activity activity = new Activity();
            activity.LoadByPrimaryKey(activityID);
            var dataView = new DataView();
            if (startDate == null || endDate == null)
            {
                dataView = Balance.GetBinCardByWarehouse(activityID, itemID, unitID, EthiopianDate.EthiopianDate.Now.FiscalYear,
                                          warehouse);
            }
            else
            {
                dataView = Balance.GetBinCardByDate(activityID, itemID, unitID, warehouse,startDate.Value,endDate.Value);
            }
            BinCardReport report = new BinCardReport();
            report.DataSource = dataView;

            report.StockCode.Text = item.StockCode;
            report.Description.Text = item.FullItemName;
            report.Unit.Text = iunit.Text;

            report.ItemSource.Text = activity.FullActivityName;

            // TODO: add the Item Source Here (the suggested interpretation is that item source is supplier)
            report.PrintedBy.Text = string.Format("Generated By: {0} On {1}", CurrentContext.LoggedInUserName,
                                                  BLL.DateTimeHelper.ServerDateTime.ToString("dd-MM-yyyy hh:mm tt"));
            report.AppVersion.Text = "HCMIS";
            return report;
        }
        private void PalletizeRecievedItems()
        {
            if (_dtPalletizedItemList == null)
            {
                _dtPalletizedItemList = _dtRecGrid.Clone();

                _dtPalletizedItemList.Columns.Add("PalletNumber");
                _dtPalletizedItemList.Columns.Add("Multiplier");
                _dtPalletizedItemList.Columns.Add("Volume");
                _dtPalletizedItemList.Columns.Add("BoxSizeDisplay");
                _dtPalletizedItemList.Columns.Add("Consolidate", typeof(bool));
                _dtPalletizedItemList.Columns.Add("CanConsolidate", typeof(bool));
                _dtPalletizedItemList.Columns.Add("PutAwayLocation", typeof(bool));
                _dtPalletizedItemList.Columns.Add("IsStoredInFreeStorageType", typeof(bool));
                _dtPalletizedItemList.Columns.Add("Index", typeof(int));
                //_dtPalletizedItemList.Columns.Add("GUID", typeof(string));

                _dtNonPalletizedItemList = _dtRecGrid.Clone();
                _dtNonPalletizedItemList.Columns.Add("Volume");
                _dtNonPalletizedItemList.Columns.Add("StorageTypeID");
                //_dtNonPalletizedItemList.Columns.Add("GUID", typeof(string));
                _dtNonPalletizedItemList.Columns.Add("Index", typeof(int));
                _dtNonPalletizedItemList.Columns.Add("Multiplier");
                _dtNonPalletizedItemList.Columns.Add("BoxSizeDisplay");

                // dtNonPalletizedItemList.Columns.Add("IsDamaged", typeof(bool));
            }
            else
            {
                _dtPalletizedItemList.Clear();
                _dtNonPalletizedItemList.Clear();
            }

            BLL.Item item = new Item();
            int lastPalletId = Pallet.GetLastPanelNumber();
            DateTime lastExpireDate = new DateTime();
            int previousProductId = 0;
            _dtRecGrid.DefaultView.Sort = "Ordering, ID, Expiry Date";
            int i = 0;
            DataRow r, rw;
            foreach (DataRowView drv in _dtRecGrid.DefaultView)
            {
                r = drv.Row;
                item.LoadByPrimaryKey(Convert.ToInt32(r["ID"]));
                int productID = 0;
                if (Convert.ToString(item.StorageTypeID) == StorageType.BulkStore &&
                    (r["IsDamaged"] != DBNull.Value && !Convert.ToBoolean(r["IsDamaged"])))
                {
                    DataTable dtbl = r["PC"] as DataTable;
                    foreach (DataRow rr in dtbl.Rows)
                    {
                        //if (Convert.ToInt32(rr["Qty"]) == 0)
                        //    continue;
                        _dtPalletizedItemList.ImportRow(r);
                        productID = Convert.ToInt32(r["ID"]);
                        rw = _dtPalletizedItemList.Rows[_dtPalletizedItemList.Rows.Count - 1];
                        rw["Pack Qty"] = rr["Qty"];
                        rw["BoxLevel"] = rr["BSize"];
                        rw["BoxSizeDisplay"] = rr["BoxSize"];
                        rw["Multiplier"] = rr["SKUM"];
                        int bs = Convert.ToInt32(rr["BSize"]);
                        // check if the item is consolidable
                        PalletLocation pll = new PalletLocation();
                        DateTime expiry = DateTime.MaxValue;

                        if (r["Expiry Date"] != DBNull.Value)
                        {
                            expiry = Convert.ToDateTime(r["Expiry Date"]);
                        }

                        pll.LoadConsolidationOption(productID, expiry, bs, Convert.ToInt32(lkAccounts.EditValue));
                        bool consolidate = false;
                        if (pll.RowCount > 0)
                        {
                            rw["CanConsolidate"] = true;
                            consolidate = true;
                        }
                        else
                        {
                            rw["CanConsolidate"] = false;
                        }
                        rw["Consolidate"] = false;

                        if (consolidate)
                        {

                        }
                        else if (r["Expiry Date"] != DBNull.Value && previousProductId == productID &&
                                 lastExpireDate.Subtract(Convert.ToDateTime(r["Expiry Date"])).Days == 0)
                        {
                            rw["PalletNumber"] = lastPalletId;
                        }
                        else
                        {
                            lastPalletId++;
                            rw["PalletNumber"] = lastPalletId;
                            lastExpireDate = DateTime.MaxValue;
                            if (r["Expiry Date"] != DBNull.Value)
                            {
                                lastExpireDate = Convert.ToDateTime(r["Expiry Date"]);
                            }
                            productID = Convert.ToInt32(r["ID"]);
                            previousProductId = productID;
                        }
                        rw["Index"] = i;
                    }
                }
                else
                {
                    // Put it in the putaway list

                    DataTable dtbl = r["PC"] as DataTable;
                    if (dtbl != null)
                    {
                        foreach (DataRow rr in dtbl.Rows)
                        {
                            if (Convert.ToInt32(rr["Qty"]) == 0)
                                continue;
                            _dtNonPalletizedItemList.ImportRow(r);
                            productID = Convert.ToInt32(r["ID"]);
                            rw = _dtNonPalletizedItemList.Rows[_dtNonPalletizedItemList.Rows.Count - 1];
                            rw["Pack Qty"] = rr["Qty"];
                            rw["BoxLevel"] = rr["BSize"];
                            rw["BoxSizeDisplay"] = rr["BoxSize"];
                            rw["Multiplier"] = rr["SKUM"];
                            rw["Index"] = i;
                        }
                    }

                }

                i++;
                previousProductId = Convert.ToInt32(r["ID"]);
                lastExpireDate = DateTime.MaxValue;
                if (r["Expiry Date"] != DBNull.Value)
                {
                    lastExpireDate = Convert.ToDateTime(r["Expiry Date"]);
                }
            }

            // now palletize the Damaged
            DataView dvShortage = grdViewShortageOrDamaged.DataSource as DataView;
            if (dvShortage != null && dvShortage.ToTable().Rows.Count > 0)
            {
                dvShortage.RowFilter = string.Format("[ShortageReasonID]={0}", ShortageReasons.Constants.DAMAGED);

                foreach (DataRow drDamages in dvShortage.ToTable().Rows)
                {
                    _dtNonPalletizedItemList.ImportRow(drDamages);
                    //productID = Convert.ToInt32(drDamages["ID"]);
                    rw = _dtNonPalletizedItemList.Rows[_dtNonPalletizedItemList.Rows.Count - 1];
                    rw["BoxLevel"] = 0;
                    rw["BoxSizeDisplay"] = 1;
                    BLL.ItemUnit iu = new ItemUnit();
                    iu.LoadByPrimaryKey(Convert.ToInt32(drDamages["UnitID"]));
                    rw["ID"] = iu.ItemID;
                    rw["Manufacturer"] = drDamages["Manufacturer"];
                    rw["Multiplier"] = iu.QtyPerUnit;
                    rw["IsDamaged"] = true;
                    rw["Index"] = i++;
                }
                dvShortage.RowFilter = null;
            }

            PalletizedGrid.DataSource = _dtPalletizedItemList;
            gridNonPalletized.DataSource = _dtNonPalletizedItemList;
            CalculateVolumes();
        }
        /// <summary>
        /// Change the UnitID of one item to another UnitID.
        /// </summary>
        /// <param name="storeID"></param>
        /// <param name="itemID"></param>
        /// <param name="fromUnitID"></param>
        /// <param name="toUnitID"></param>
        public static void ChangeItemUnit(int storeID, int itemID, int fromUnitID, int toUnitID)
        {
            MyGeneration.dOOdads.TransactionMgr transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
            try
            {
                transaction.BeginTransaction();
                ItemUnit iuFrom = new ItemUnit(), iuTo = new ItemUnit(), iuExecute = new ItemUnit();
                iuFrom.LoadByPrimaryKey(fromUnitID);
                iuTo.LoadByPrimaryKey(toUnitID);

                var receiveTableFilterQuery = HCMIS.Repository.Queries.ItemUnit.SelectChangeItemUnit(storeID, itemID, iuFrom.ID);

                string query;
                // Update Issue Doc
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitIssueDoc(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);
                iuExecute.LoadFromRawSql(query);

                // Update disposal table
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitLossAndAdjustment(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);
                iuExecute.LoadFromRawSql(query);

                // Update Order.
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitOrderDetail(itemID, iuFrom.ID, iuFrom.QtyPerUnit, iuTo.QtyPerUnit);

                iuExecute.LoadFromRawSql(query);

                // Update Pick List Detail
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitPickListDetail(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);

                iuExecute.LoadFromRawSql(query);

                // change the Weighted Average Log
                try
                {
                    query = HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitMovingAverageHistory(storeID, iuTo.ID, iuFrom.ID);

                    iuExecute.LoadFromRawSql(query);
                }

                catch
                {

                }

                BLL.ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByItemIDUnitIDStoreID(itemID, iuFrom.ID, storeID);
                rd.ChangeUnitID(iuTo.ID);

                //Change the YearEnd
                //If there is already an entry with the other UnitID, we need to merge the two.

                BLL.YearEnd yEndFrom = new YearEnd();
                yEndFrom.Where.UnitID.Value = iuFrom.ID;
                yEndFrom.Where.ItemID.Value = itemID;
                yEndFrom.Where.StoreID.Value = storeID;
                yEndFrom.Query.Load();

                if (yEndFrom.RowCount > 0)
                {
                    //There is a year end entry.
                    //If there is one by the new UnitID, we merge them.  If there is no entry by the new UnitID, we just change the values.
                    BLL.YearEnd yEndTo = new YearEnd();
                    yEndTo.Where.UnitID.Value = iuTo.ID;
                    yEndTo.Where.ItemID.Value = itemID;
                    yEndTo.Where.StoreID.Value = storeID;
                    yEndTo.Query.Load();
                    if (yEndTo.RowCount > 0)
                    {
                        //We need to merge.
                        if (!yEndTo.IsColumnNull("EndingPrice"))
                            yEndTo.EndingPrice += yEndFrom.EndingPrice;
                        else
                            yEndTo.EndingPrice = yEndFrom.EndingPrice;
                        if (!yEndTo.IsColumnNull("EBalance"))
                            yEndTo.EBalance += yEndFrom.EBalance;
                        else
                            yEndTo.EBalance = yEndFrom.EBalance;
                        if (!yEndTo.IsColumnNull("PhysicalInventory"))
                            yEndTo.PhysicalInventory += yEndFrom.PhysicalInventory;
                        else
                            yEndTo.PhysicalInventory = yEndFrom.PhysicalInventory;
                        if (!yEndTo.IsColumnNull("PhysicalInventoryPrice"))
                            yEndTo.PhysicalInventoryPrice += yEndFrom.PhysicalInventoryPrice;
                        else
                            yEndTo.PhysicalInventoryPrice = yEndFrom.PhysicalInventoryPrice;

                        yEndTo.Save();
                        yEndFrom.MarkAsDeleted();
                        yEndFrom.Save();
                    }
                    else
                    {
                        yEndFrom.UnitID = iuTo.ID;
                        yEndFrom.Save();
                    }
                }
                transaction.CommitTransaction();
            }
            catch(Exception ex)
            {
                transaction.RollbackTransaction();
                throw ex;
            }
        }
 public static string GetUnitText(int itemUnitID)
 {
     BLL.ItemUnit iUnit = new ItemUnit();
     iUnit.LoadByPrimaryKey(itemUnitID);
     if(iUnit.RowCount>0)
     {
         return iUnit.Text;
     }
     return "";
 }
        internal void Commit(DateTime ethiopianDate, BackgroundWorker backgroundWorker = null)
        {
            InventoryCommitMemberInstance.Transaction.BeginTransaction();
            //TODO: Create the order detail, pass the order id above this inventory object
            int count = 0;

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

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

            decimal endingTotalBalance = endingSoundBalance + endingDamagedBalance + endExpiredBalance;

            ItemUnit itemUnit = new ItemUnit();

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

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

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

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

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

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

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

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

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

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

                if (!IsColumnNull("DamagedReceiveDocID"))
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(DamagedReceiveDocID);
                    receiveDoc.ChangeQuantity(InventoryDamagedQuantity);
                }
            }
            IsDraft = false;
            Save();
            InventoryCommitMemberInstance.Transaction.CommitTransaction();
        }
        /// <summary>
        /// Computes the stock calculations for an order detail.
        /// </summary>
        /// <param name="currentMonth">The current month.</param>
        /// <param name="currentYear">The current year.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="orderDetail">The order detail.</param>
        /// <returns></returns>
        public DataRow ComputeStockCalculationsForAnOrderDetail(int currentMonth, int currentYear, int userID, OrderDetail orderDetail)
        {
            if (!IsOrderDetailTableReady(orderDetail))
            {
                PrepareOrderDetailTable(orderDetail);
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            //}
            return orderDetail.DefaultView.ToTable().Rows[0];
        }
        private void LoadMaster()
        {
            //Populate Item Name
            Item item = new Item();
            item.LoadByPrimaryKey(ItemID);
            txtitem.Text = item.FullItemName;

            //Populate Manufacturer
            Manufacturer mf = new Manufacturer();
            mf.LoadByPrimaryKey(ManufacturerID);
            txtManufacturer.Text = mf.Name;

            //Populate Unit
            ItemUnit unit = new ItemUnit();
            unit.LoadByPrimaryKey(UnitID);
            txtUnit.Text = unit.Text;

            //Populate Account
            Account Account = new Account();
            Account.LoadByPrimaryKey(StoreID);
            txtAccount.Text = Account.Name;
            if(BLL.Settings.IsCenter)
            layoutSellingPrice.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
        }
        /// <summary>
        /// Change the UnitID of one item to another UnitID.
        /// </summary>
        /// <param name="storeID"></param>
        /// <param name="itemID"></param>
        /// <param name="fromUnitID"></param>
        /// <param name="toUnitID"></param>
        public static void ChangeItemUnit(int storeID, int itemID, int fromUnitID, int toUnitID)
        {
            MyGeneration.dOOdads.TransactionMgr transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
            try
            {
                transaction.BeginTransaction();
                ItemUnit iuFrom = new ItemUnit(), iuTo = new ItemUnit(), iuExecute = new ItemUnit();
                iuFrom.LoadByPrimaryKey(fromUnitID);
                iuTo.LoadByPrimaryKey(toUnitID);

                var receiveTableFilterQuery = HCMIS.Repository.Queries.ItemUnit.SelectChangeItemUnit(storeID, itemID, iuFrom.ID);

                string query;
                // Update Issue Doc
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitIssueDoc(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);
                iuExecute.LoadFromRawSql(query);

                // Update disposal table
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitLossAndAdjustment(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);
                iuExecute.LoadFromRawSql(query);

                // Update Order.
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitOrderDetail(itemID, iuFrom.ID, iuFrom.QtyPerUnit, iuTo.QtyPerUnit);

                iuExecute.LoadFromRawSql(query);

                // Update Pick List Detail
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitPickListDetail(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);

                iuExecute.LoadFromRawSql(query);

                // change the Weighted Average Log
                try
                {
                    query = HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitMovingAverageHistory(storeID, iuTo.ID, iuFrom.ID);

                    iuExecute.LoadFromRawSql(query);
                }

                catch
                {
                }

                BLL.ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByItemIDUnitIDStoreID(itemID, iuFrom.ID, storeID);
                rd.ChangeUnitID(iuTo.ID);

                //Change the YearEnd
                //If there is already an entry with the other UnitID, we need to merge the two.

                BLL.YearEnd yEndFrom = new YearEnd();
                yEndFrom.Where.UnitID.Value  = iuFrom.ID;
                yEndFrom.Where.ItemID.Value  = itemID;
                yEndFrom.Where.StoreID.Value = storeID;
                yEndFrom.Query.Load();

                if (yEndFrom.RowCount > 0)
                {
                    //There is a year end entry.
                    //If there is one by the new UnitID, we merge them.  If there is no entry by the new UnitID, we just change the values.
                    BLL.YearEnd yEndTo = new YearEnd();
                    yEndTo.Where.UnitID.Value  = iuTo.ID;
                    yEndTo.Where.ItemID.Value  = itemID;
                    yEndTo.Where.StoreID.Value = storeID;
                    yEndTo.Query.Load();
                    if (yEndTo.RowCount > 0)
                    {
                        //We need to merge.
                        if (!yEndTo.IsColumnNull("EndingPrice"))
                        {
                            yEndTo.EndingPrice += yEndFrom.EndingPrice;
                        }
                        else
                        {
                            yEndTo.EndingPrice = yEndFrom.EndingPrice;
                        }
                        if (!yEndTo.IsColumnNull("EBalance"))
                        {
                            yEndTo.EBalance += yEndFrom.EBalance;
                        }
                        else
                        {
                            yEndTo.EBalance = yEndFrom.EBalance;
                        }
                        if (!yEndTo.IsColumnNull("PhysicalInventory"))
                        {
                            yEndTo.PhysicalInventory += yEndFrom.PhysicalInventory;
                        }
                        else
                        {
                            yEndTo.PhysicalInventory = yEndFrom.PhysicalInventory;
                        }
                        if (!yEndTo.IsColumnNull("PhysicalInventoryPrice"))
                        {
                            yEndTo.PhysicalInventoryPrice += yEndFrom.PhysicalInventoryPrice;
                        }
                        else
                        {
                            yEndTo.PhysicalInventoryPrice = yEndFrom.PhysicalInventoryPrice;
                        }

                        yEndTo.Save();
                        yEndFrom.MarkAsDeleted();
                        yEndFrom.Save();
                    }
                    else
                    {
                        yEndFrom.UnitID = iuTo.ID;
                        yEndFrom.Save();
                    }
                }
                transaction.CommitTransaction();
            }
            catch (Exception ex)
            {
                transaction.RollbackTransaction();
                throw ex;
            }
        }
        private int SaveOrder()
        {
            int warehouseID;
            var order = GenerateOrder();
            PickList pickList = PickList.GeneratePickList(order.ID);
            int picklistId = pickList.ID;
            if (TransferTypeID != Transfer.Constants.HUB_TO_HUB)
            {
                warehouseID = GenerateTransfer(order.ID);
            }

            // Log
            this.LogActivity("Transfer", order.ID);

            int LineNo = 0;

            // This is a kind of initializing the data table.

            DataView dv = orderGrid.DataSource as DataView;

            foreach (DataRowView r in dv)
            {
                if (r["ApprovedPacks"] != null && r["ApprovedPacks"] != DBNull.Value && r["ApprovedPacks"].ToString()!= "")
                    if (Convert.ToDecimal(r["ApprovedPacks"]) != 0)
                    {
                        LineNo = LineNo + 1;
                        int itemId = Convert.ToInt32(r["ItemID"]);
                        int unitId = Convert.ToInt32(r["UnitID"]);
                        decimal pack = Convert.ToDecimal(r["ApprovedPacks"]);
                        int qtyPerPack = Convert.ToInt32(r["QtyPerPack"]);
                        int activityId = Convert.ToInt32(lkFromActivity.EditValue);
                        int manufacturerId = Convert.ToInt32(Convert.ToInt32(r["ManufacturerID"]));
                        int receivePalletId = Convert.ToInt32(r["ReceivingLocationID"]);
                        int palletLocationId = Convert.ToInt32(r["LocationID"]);
                        double? unitPrice;
                        string batchNumber = r["BatchNo"].ToString();
                        string expireDate ="" ;
                        int receiveDocId = Convert.ToInt32(r["ReceiveDocID"]);
                        if((r["UnitPrice"] != DBNull.Value))
                        {
                            unitPrice = Convert.ToDouble(r["UnitPrice"]);
                        }
                        else
                        {
                            unitPrice = null;
                        }

                        if (r["ExpDate"] != DBNull.Value)
                             expireDate= r["ExpDate"].ToString();

                        OrderDetail ord = OrderDetail.GenerateOrderDetail(unitId, activityId, pack, order.ID, qtyPerPack, itemId);
                        PalletLocation palletLocation = new PalletLocation();
                        palletLocation.LoadByPrimaryKey(palletLocationId);
                        int palletID = palletLocation.PalletID;
                        PickListDetail pkDetail = PickListDetail.GeneratePickListDetail(pack, unitPrice, receiveDocId, manufacturerId, receivePalletId, qtyPerPack, activityId, unitId, itemId, picklistId, palletID, expireDate, batchNumber);
                        ReceivePallet.ReserveQty(pack, receivePalletId);
                        //To Print The Picklist
                        //Then reserve Items

                       Item item = new Item();
                        item.LoadByPrimaryKey(itemId);
                        DataRow drvpl = dvPickList.NewRow();
                        drvpl["FullItemName"] = item.FullItemName;
                        drvpl["StockCode"] = item.StockCode;
                        drvpl["BatchNo"] = batchNumber;
                        if (expireDate != "" )
                            drvpl["ExpDate"] = Convert.ToDateTime(expireDate).ToString("MMM/yyyy");
                        else
                            drvpl["ExpDate"] = DBNull.Value;
                        drvpl["LineNum"] = LineNo + 1;
                        var manufacturer = new Manufacturer();
                        manufacturer.LoadByPrimaryKey(manufacturerId);
                        drvpl["ManufacturerName"] = manufacturer.Name;

                        drvpl["Pack"] = pack;
                        drvpl["UnitPrice"] = unitPrice;
                        var unit = new ItemUnit();
                        unit.LoadByPrimaryKey(unitId);

                        drvpl["Unit"] = unit.Text;

                        drvpl["QtyInSKU"] = pack;
                        if (unitPrice != null)
                             drvpl["CalculatedCost"] = pack *Convert.ToDecimal(unitPrice);

                         palletLocation.LoadByPrimaryKey(pkDetail.PalletLocationID);
                         drvpl["PalletLocation"] = palletLocation.Label;
                         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");
            string receivingUnit;
                Transfer transfer = new Transfer();
                transfer.LoadByOrderID(order.ID);
                if (TransferTypeID == Transfer.Constants.ACCOUNT_TO_ACCOUNT)
                {
                    var fromActivity = new Activity();
                    fromActivity.LoadByPrimaryKey(transfer.FromStoreID);
                    var toActivity = new Activity();
                    toActivity.LoadByPrimaryKey(transfer.ToStoreID);

                    receivingUnit = String.Format("Account to Account from {0} to {1}", fromActivity.FullActivityName,
                                                toActivity.FullActivityName);
                }
                else if (TransferTypeID == Transfer.Constants.STORE_TO_STORE)
                {

                    var toStore = new PhysicalStore();

                    toStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);
                    receivingUnit = string.Format("Store to Store transfer to: {0}", toStore.WarehouseName);
                }
                else
                {
                    receivingUnit = lkForHub.Text;
                }
            var plr = HCMIS.Desktop.Reports.WorkflowReportFactory.CreatePicklistReport(order, receivingUnit,
                                                                                       dvPickList.DefaultView);
            plr.PrintDialog();

                XtraMessageBox.Show("Picklist Prepared!", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return order.ID;
        }
        /// <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();
            }
        }
        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();
        }
        //, string guid)
        private void SavePalletization(ReceiveDoc rec, DataRowView drow)
        {
            if ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") && rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED) || (rec.Quantity == 0 && rec.IsColumnNull("ShortageReasonID")))
            {
                HandleFullNotReceivedAndMultipleBatchPalletlization(rec,drow);
                return;
            }
            string guid;

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

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

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

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

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

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

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

                    int qtyPerPack = im.QuantityInBasicUnit;

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

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

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

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

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

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

                        }
                    }

                }
            }

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

                    int qtyPerPack = im.QuantityInBasicUnit;

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

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

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

            }

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

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

            rec.ReceivedBy = CurrentContext.LoggedInUserName;

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

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

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

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

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

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

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

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

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

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

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

            rec.ReturnedStock = srm;

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

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

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

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

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

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

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

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

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

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

            dtRecDate.Value = xx;
            _receiptID = receiptID; //Assign it to the global variable so it can be used later on.
        }
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            var view = sender as GridView;
            if (view == null) return;
            var iu = new ItemUnit();

            if ((view.FocusedColumn.FieldName == "Pack Qty") || (view.FocusedColumn.FieldName == "Qty Per Pack") || (view.FocusedColumn.FieldName == "DU Remaining SOH"))
            {
                DataRow dr = issueGridView.GetDataRow(issueGridView.GetSelectedRows()[0]);

                int qty = Convert.ToInt32(dr["Pack Qty"]);
                int qtyPerpack = Convert.ToInt32(dr["Qty Per Pack"]);
                switch (VisibilitySetting.HandleUnits)
                {
                    case 2:
                        {
                            iu.LoadByPrimaryKey(Convert.ToInt32(dr["UnitID"]));
                            var qtyperunit = iu.QtyPerUnit;
                            dr["Qty Per Pack"] = qtyperunit;
                            dr["Requested Qty"] = qty;
                        }
                        break;
                    case 3:
                        {
                            iu.LoadByPrimaryKey(Convert.ToInt32(dr["UnitID"]));
                            var qtyperunit = iu.QtyPerUnit;
                            dr["Qty Per Pack"] = qtyperunit;
                            dr["Requested Qty"] = qty;
                        }
                        break;
                    case 1:
                        dr["Qty Per Pack"] = qtyPerpack;
                        dr["Requested Qty"] = (qtyPerpack * qty);
                        break;
                }

                DateTime xx = dtIssueDate.Value;
                dtIssueDate.Value = DateTime.Now;
                dtIssueDate.CustomFormat = "MM/dd/yyyy";
                DateTime dtCurrent = ConvertDate.DateConverter(dtIssueDate.Text);
                dtIssueDate.Value = xx;

                var bal = new Balance();
                var receivingUnit = Convert.ToInt32(cboReceivingUnits.EditValue);

                Int64 duAmc = 0;
                int itmId = Convert.ToInt32(dr["ID"]);
                int lstSOH = ((dr["DU Remaining SOH"] != null && dr["DU Remaining SOH"] != DBNull.Value) ? Convert.ToInt32(dr["DU Remaining SOH"]) : 0);
                duAmc = bal.CalculateDUAMC(itmId, receivingUnit, dtCurrent.Month, dtCurrent.Year, lstSOH);
                dr["DU AMC"] = duAmc;

                //recommend qty to du
                var DUs = new ReceivingUnits();
                DUs.LoadByPrimaryKey(receivingUnit);
                double dumax = 0.5;
                try
                {
                    dumax = DUs.Max;
                }
                catch
                { }
                double recQty = (Convert.ToInt32(dr["DU AMC"]) * dumax) - lstSOH;
                dr["Recommended Qty"] = ((recQty > 0) ? Convert.ToInt64(recQty) : 0);
            }
        }
        /// <summary>
        /// Adds to pick list for an order detail.
        /// </summary>
        /// <param name="orderDetailID">The order detail ID.</param>
        /// <param name="itemId">The item id.</param>
        /// <param name="unitID">The unit ID.</param>
        /// <param name="initalApprovedQuantity">The inital approved quantity.</param>
        /// <param name="storeID">The store ID.</param>
        /// <param name="preferedManufacturer">The prefered manufacturer.</param>
        /// <param name="preferredPhysicalStore">The preferred physical store.</param>
        /// <param name="isDeliveryNote">if set to <c>true</c> [is delivery note].</param>
        /// <param name="preferredExpiry">The preferred expiry.</param>
        /// <exception cref="System.Exception"></exception>
        private void AddToPickListFor(int userID, int orderDetailID, int itemId, int? unitID, decimal initalApprovedQuantity, int storeID, int preferedManufacturer, int preferredPhysicalStore, bool isDeliveryNote, DateTime? preferredExpiry)
        {
            bool deliveryNoteWarning = false;

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

            decimal approvedQuantity = initalApprovedQuantity;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // this means the pick face has been setup.
                DataRowView drv = _replenishmentList.DefaultView.AddNew();
                drv["ItemID"] = itemId;
                drv["StoreID"] = storeID;
                drv.EndEdit();
            }
        }
        internal void Commit(DateTime ethiopianDate, BackgroundWorker backgroundWorker = null)
        {
            InventoryCommitMemberInstance.Transaction.BeginTransaction();
            //TODO: Create the order detail, pass the order id above this inventory object
            int count = 0;

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

            decimal endingTotalBalance = endingSoundBalance + endingDamagedBalance + endExpiredBalance;

            ItemUnit itemUnit = new ItemUnit();
            itemUnit.LoadByPrimaryKey(UnitID);
            if (IsColumnNull("ReceiveDocID") && IsColumnNull("DamagedReceiveDocID")) // This has been recently added to
            {

                if (endingTotalBalance > 0)
                {

                    OrderDetail.GenerateOrderDetail(UnitID, ActivityID, endingTotalBalance,
                                                    InventoryCommitMemberInstance.Order.ID, itemUnit.QtyPerUnit, ItemID);

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

                    while (!receivePallet.EOF)
                    {

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

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

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

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

                        receivePallet.MoveNext();
                        count++;
                        if (backgroundWorker != null)
                        {
                            backgroundWorker.ReportProgress(
                                Convert.ToInt32((Convert.ToDecimal(count) / Convert.ToDecimal(receivePallet.RowCount)) * 100),
                                "Detail");
                        }
                    }

                }
                //TODO: Create the receive (use the inventory object itself)
                ReceiveService receiveService = new ReceiveService();
                if (!IsColumnNull("InventorySoundQuantity") && InventorySoundQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                      ID, QuantityType.Sound,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    ReceiveDocID = receiveDoc.ID;
                }

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

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

                if (backgroundWorker != null)
                {
                    backgroundWorker.ReportProgress(100, "Detail");
                }

            }
            else
            {

                if (!IsColumnNull("ReceiveDocID"))
                {

                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(ReceiveDocID);
                    receiveDoc.ChangeQuantity(!IsColumnNull("InventorySoundQuantity") ? InventorySoundQuantity
                                                            : !IsColumnNull("InventoryExpiredQuantity") ? InventoryExpiredQuantity
                                                                                        : 0);

                }

                if (!IsColumnNull("DamagedReceiveDocID"))
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(DamagedReceiveDocID);
                    receiveDoc.ChangeQuantity(InventoryDamagedQuantity);
                }
            }
            IsDraft = false;
            Save();
            InventoryCommitMemberInstance.Transaction.CommitTransaction();
        }
        private void LoadSTVDetails()
        {
            int documentID = Convert.ToInt32(grdViewReceivedSTVs.GetFocusedDataRow()["DocumentID"]);
            BLL.Document document = new Document();
            document.LoadByPrimaryKey(documentID);
            DocumentExchange.Documents.XmlMappings.STV stv =
                DocumentExchange.Documents.XmlMappings.STV.Load(document.DocumentContent);

            //Clean up the receivedoc entry
            receiveDoc.FlushData();
            STVNo = Convert.ToInt32(stv.DocumentNumber);

            lblDaysAgo.Text = string.Format("Printed: {0}", Helpers.DateTimeFunctions.GetDateSpan(stv.PrintedDate));
            for (int i = 0; i < stv.DocumentDetails.Count; i++)
            {
                STVDetail detail = stv.DocumentDetails[i];
                receiveDoc.AddNew();

                //Add columns for display purposes and for storing temporary information
                if (!receiveDoc.DefaultView.ToTable().Columns.Contains("FullItemName"))
                {
                    receiveDoc.AddColumn("FullItemName", typeof(string));
                    receiveDoc.AddColumn("UnitName", typeof(string));
                    receiveDoc.AddColumn("ManufacturerName", typeof(string));
                    receiveDoc.AddColumn("ActivityName", typeof(string));
                    receiveDoc.AddColumn("StockCode", typeof(string));
                    receiveDoc.AddColumn("PalletLocationID", typeof(int));
                    receiveDoc.AddColumn("GUID", typeof(string));
                }

                //Fill in the data
                receiveDoc.ItemID = detail.ItemID;
                receiveDoc.UnitID = detail.UnitID;
                receiveDoc.StoreID = detail.ActivityID;
                receiveDoc.ManufacturerId = detail.ManufacturerID;
                receiveDoc.SetColumn("BatchNo", detail.BatchNumber);
                receiveDoc.SetColumn("ExpDate", detail.ExpiryDate);
                receiveDoc.SetColumn("GUID", Guid.NewGuid());

                BLL.Item item = new Item();
                item.LoadByPrimaryKey(detail.ItemID);
                receiveDoc.SetColumn("FullItemName", item.FullItemName);

                BLL.ItemUnit unit = new ItemUnit();
                unit.LoadByPrimaryKey(detail.UnitID);
                receiveDoc.SetColumn("UnitName", unit.Text);
                receiveDoc.QtyPerPack = unit.QtyPerUnit;

                BLL.Manufacturer manufacturer = new Manufacturer();
                manufacturer.LoadByPrimaryKey(detail.ManufacturerID);
                receiveDoc.SetColumn("ManufacturerName", manufacturer.Name);
                var activity = new Activity();
                activity.LoadByPrimaryKey(detail.ActivityID);
                receiveDoc.SetColumn("ActivityName", activity.FullActivityName);

                receiveDoc.SetColumn("StockCode", item.StockCode);

                //Financial Info
                receiveDoc.InvoicedNoOfPack = detail.Quantity;
                receiveDoc.Margin = detail.Margin;
                receiveDoc.PricePerPack = detail.UnitPrice;
            }

            grdSTVDetails.DataSource = receiveDoc.DefaultView;
        }
        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();
        }