Exemple #1
0
        public DataTable GetAllUnits()
        {
            var units = new ItemUnit();

            units.LoadFromRawSql("select * from ItemUnit");
            return(units.DataTable);
        }
        /// <summary>
        /// Corrects QtyPerPack Inconsistencies across different tables.
        /// </summary>
        public static void CorrectUnitQtyPerUnitInconsistencies()
        {
            string   query;
            ItemUnit iuExecute = new ItemUnit();

            //Make sure quantity values are corrected.

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesRd();
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesId();
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesOdd();
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesIdPld();
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesIdPld2();
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesIdDisp();
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesIdIssueDoc();
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesIdReceiveDoc();
            iuExecute.LoadFromRawSql(query);
        }
Exemple #3
0
        public DataTable LoadFromSQl(int itemid)
        {
            var units = new ItemUnit();

            units.LoadFromRawSql(string.Format("select * from ItemUnit where ItemID={0}", itemid));
            return(units.DataTable);
        }
        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;
        }
Exemple #7
0
        protected override ICollection <Unit> GetData()
        {
            ICollection <Domain.Unit> units = new Collection <Domain.Unit>();
            var dbUnit = new BLL.ItemUnit();

            dbUnit.LoadAll();
            while (!dbUnit.EOF)
            {
                units.Add(new Unit {
                    UnitID = dbUnit.ID, Text = dbUnit.Text
                });
                dbUnit.MoveNext();
            }
            return(units);
        }
        private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                int itemID;
                if (!string.IsNullOrEmpty(txtItemID.Text))
                {
                    _itemID = int.Parse(txtItemID.Text);
                }
                itemID = _itemID;
                BLL.Item itm = new BLL.Item();
                itm.LoadByPrimaryKey(itemID);
                lblFullItemName.Text = itm.FullItemName;

                rd.LoadByItemID(itemID);
                grdReceiveDoc.DataSource = rd.DefaultView;

                recPallet.LoadByItemID(itemID);
                grdReceivePallet.DataSource = recPallet.DefaultView;

                id.LoadByItemID(itemID);
                grdIssueDoc.DataSource = id.DefaultView;

                ordDetail.LoadByItemID(itemID);
                grdOrderDetail.DataSource = ordDetail.DefaultView;

                pld.LoadByItemID(itemID);
                grdPickListDetail.DataSource = pld.DefaultView;

                _lossAndAdjustment.LoadByItemID(itemID);
                grdDisposal.DataSource = _lossAndAdjustment.DefaultView;

                yearEnd.LoadByItemID(itemID);
                grdYearEnd.DataSource = yearEnd.DefaultView;

                BLL.ItemUnit iu = new BLL.ItemUnit();
                iu.LoadAllForItem(int.Parse(txtItemID.Text));

                grdItemManufacturerItemUnit.DataSource = iu.DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        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;
        }
        /// <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 void ManageItems_Load(object sender, EventArgs e)
        {
            PopulateCatTree(SelectedType);

            lkCommodityTypes.Properties.DataSource = BLL.Type.GetAllTypes();
            lkCommodityTypes.ItemIndex = 0;

            var itemunit = new ItemUnit();
            var allunits = itemunit.GetAllUnits();
            unitBindingSource.DataSource = allunits.DefaultView;

            var stor = new Stores();
            stor.GetActiveStores();
            cboStores.Properties.DataSource = stor.DefaultView;

            DataTable dtMonths = new DataTable();
            dtMonths.Columns.Add("Value");
            dtMonths.Columns.Add("Month");
            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            dtCur = ConvertDate.DateConverter(dtDate.Text);
            int currentMont = dtCur.Month;
            int year = ((currentMont < 11) ? dtCur.Year : dtCur.Year + 1);
            // this is just a try
            if (currentMont >= 11)
            {
                currentMont -= 11;
            }

            var dtyears = Items.AllYears();

            cboStores.ItemIndex = 0;
            cboYear.Properties.DataSource = dtyears;
            cboYear.EditValue = year;
            if (cboYear.Properties.Columns.Count > 0)
                cboYear.Properties.Columns[0].Alignment = DevExpress.Utils.HorzAlignment.Near;

            IsReady = true;
            PopulateGrid();
        }
        /// <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>
        /// The save button should be active only when the date is Sene 30 or in the month of Hamle.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void YearEndProcess_Load(object sender, EventArgs e)
        {
            var ethDate = new EthiopianDate.EthiopianDate();

            lkCommodityTypes.Properties.DataSource = BLL.Type.GetAllTypes();
            lkCommodityTypes.ItemIndex = 0;
            btnSave.Enabled = false;
            var unit = new ItemUnit();
            var allunits = unit.GetAllUnits();
            unitBindingSource.DataSource = allunits.DefaultView;
            var unitcolumn = ((GridView)grdYearEnd.MainView).Columns[9];
            switch (VisibilitySetting.HandleUnits)
            {
                case 1:
                    unitcolumn.Visible = false;
                    break;
                case 2:
                    unitcolumn.Visible = true;
                    break;
                default:
                    unitcolumn.Visible = true;
                   break;
            }
            var str = new Stores();
            str.GetActiveStores();

            cboStores.Properties.DataSource = str.DefaultView;
            cboStores.ItemIndex = 0;
            dtDate.CustomFormat = "MMMM dd, yyyy";
        }
        //, string guid)
        private void SavePalletization(ReceiveDoc rec, DataRowView drow)
        {
            if ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") && rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED) || (rec.Quantity == 0 && rec.IsColumnNull("ShortageReasonID")))
            {
                HandleFullNotReceivedAndMultipleBatchPalletlization(rec,drow);
                return;
            }
            string guid;

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

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

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

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

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

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

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

                    int qtyPerPack = im.QuantityInBasicUnit;

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

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

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

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

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

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

                        }
                    }

                }
            }

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

                    int qtyPerPack = im.QuantityInBasicUnit;

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

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

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

            }

            rec.Save();
            rp.Rewind();
            while (!rp.EOF)
            {
                rp.ReceiveID = rec.ID;
                rp.MoveNext();
            }
            rp.Save();
            SavePutAwayItems();
        }
        private void 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>
        /// Load the loookups
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ManageItems_Load(object sender, EventArgs e)
        {
            var unitcolumn = ((GridView) gridInventory.MainView).Columns[7];
            unitcolumn.Visible = VisibilitySetting.HandleUnits != 1;
            var stor = new Stores();

            var unit = new ItemUnit();
            var allunit = unit.GetAllUnits();
            unitbindingSource.DataSource = allunit.DefaultView;

            stor.GetActiveStores();
            cboStores.DataSource = stor.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();
        }
        private void EditReceived_Load(object sender, EventArgs e)
        {
            BLL.ItemManufacturer im = new BLL.ItemManufacturer();
            im.LoadManufacturersFor(rDoc.ItemID);
            lkManufacturer.Properties.DataSource = im.DefaultView;

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

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

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

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

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

                }
                else if (!itm.NeedExpiryBatch &&
                         (CurrentContext.LoggedInUser.UserType == UserType.Constants.ADMIN ||
                          CurrentContext.LoggedInUser.UserType == UserType.Constants.SUPER_ADMINISTRATOR))
                {
                    btnRemoveExpiry.Enabled = true;
                    txtBatchNo.Enabled = true;
                }
            }
        }
        private static BLL.OrderDetail GetOrderDetail(int? orderID, IEnumerable<ApprovedOrderDetail> plitsApprovedOrderDetails)
        {
            var hcmisOrderDetail = new BLL.OrderDetail();
            //var plitsApprovedOrderDetails = plitsApprovedOrderDetail as List<ApprovedOrderDetail> ?? plitsApprovedOrderDetail.ToList();
            foreach (var plitsOrderDetail in plitsApprovedOrderDetails)
            {
                hcmisOrderDetail.AddNew();
                hcmisOrderDetail.ItemID = plitsOrderDetail.PharmaceuticalId;
                hcmisOrderDetail.HACTOrderDetailID = plitsOrderDetail.Id;
                hcmisOrderDetail.Pack = Convert.ToDecimal(plitsOrderDetail.ApprovedQty);

                BLL.ItemUnit iu = new ItemUnit();
                iu.LoadAllForItem(plitsOrderDetail.PharmaceuticalId); //Just load it by item id.  This loads a collection but we just pick and use the first one. :)

                if (iu.RowCount == 0)
                {
                    hcmisOrderDetail.QtyPerPack = iu.QtyPerUnit;
                    hcmisOrderDetail.Quantity = hcmisOrderDetail.Pack * iu.QtyPerUnit;
                    hcmisOrderDetail.UnitID = iu.ID;
                    throw new Exception(string.Format("IU Not Configured correctly for item: {0}",
                                                      plitsOrderDetail.PharmaceuticalId));
                }

                hcmisOrderDetail.QtyPerPack = iu.QtyPerUnit;
                hcmisOrderDetail.Quantity = hcmisOrderDetail.Pack * iu.QtyPerUnit;
                hcmisOrderDetail.UnitID = iu.ID;
            }

            return hcmisOrderDetail;
        }
        // Load Filter
        // Construct the General Filter String
        private void LoadUnitsForSelectedItem()
        {
            ItemUnit itemUnit = new ItemUnit();
            if (ShowOnlyReceivedItemUnit)
                itemUnit.LoadReceivedByItemID(ItemID);
            chkUnits.DataSource = itemUnit.DefaultView;
            lkStockCardUnit.Properties.DataSource = itemUnit.DefaultView;
            lkBinCardUnit.Properties.DataSource = itemUnit.DefaultView;

            chkUnits.CheckAll();
        }
        /// <summary>
        /// Populates the fields based on the supplied itemID or categoryID
        /// </summary>
        private void PopulateFields()
        {
            if (_itemId == 0)
                return;

            Items itm = new Items();

            DataTable dtItem = itm.GetItemById(_itemId);
            txtItemName.Text = dtItem.Rows[0]["ItemName"].ToString() + " - " + dtItem.Rows[0]["DosageForm"].ToString() + " - " + dtItem.Rows[0]["Strength"].ToString();
            ckExculed.Checked =itm.IsInHospitalList;
            chkNeedExpiryBatch.Checked = itm.NeedExpiryBatch;
            txtText.Text = itm.StockCodeDACA ?? string.Empty;
            txtQuantityPerPack.Text = itm.Cost ?? string.Empty;

            try
            {
                if (dtItem.Rows[0]["ABC"].ToString() == "A")
                    rdA.Checked = true;
                else if (dtItem.Rows[0]["ABC"].ToString() == "B")
                    rdB.Checked = true;
                else if (dtItem.Rows[0]["ABC"].ToString() == "C")
                    rdC.Checked = true;
            }
            catch { }

            try
            {
                if (dtItem.Rows[0]["VEN"].ToString() == "V")
                    rdV.Checked = true;
                else if (dtItem.Rows[0]["VEN"].ToString() == "E")
                    rdE.Checked = true;
                else if (dtItem.Rows[0]["VEN"].ToString() == "N")
                    rdN.Checked = true;
            }
            catch { }

            //ItemShelf itmShelf = new ItemShelf();
            //DataTable dtSlf = itmShelf.GetLocationByItem(itm.ID);
            //lstBinLocation.DataSource = dtSlf;

            var unit = new ItemUnit();
            var itemunits= unit.LoadFromSQl(_itemId);
            itemunitbindingSource.DataSource = itemunits;

            if (VisibilitySetting.HandleUnits == 2)
            {
                listBox1.Visible = true;
            }
            else if(VisibilitySetting.HandleUnits == 3)
            {
                 listBox1.Visible = true;
            }
            else if(VisibilitySetting.HandleUnits == 1)
            {
                listBox1.Hide();
            }
            Supplier sup = new Supplier();
            sup.GetActiveSuppliers();

            ItemSupplier itmSup = new ItemSupplier();
            itm.GetItemsBySupplier(_itemId);
            foreach (DataRowView dv in sup.DefaultView)
            {
                bool check = false;
                check = itmSup.CheckIfExist(_itemId, Convert.ToInt32(dv["ID"]));
                object obj = dv["CompanyName"];
                lstSuppliers.Items.Add(obj, check);
            }

            Programs prog = new Programs();
            prog.GetSubPrograms();
            ProgramProduct progItem = new ProgramProduct();
            lstPrograms.Items.Clear();
            foreach (DataRowView dv in prog.DefaultView)
            {
                bool check = false;
                check = progItem.CheckIfExists(_itemId, Convert.ToInt32(dv["ID"]));
                lstPrograms.Items.Add(dv["Name"], check);
            }

            ReceivingUnits dus = new ReceivingUnits();
            dus.GetActiveDispensaries();
            lstDUs.Items.Clear();

            DUsItemList duItem = new DUsItemList();

            foreach (DataRowView drDus in dus.DefaultView)
            {
                bool check = false;
                check = duItem.CheckIfExsits(_itemId, Convert.ToInt32(drDus["ID"]));
                lstDUs.Items.Add(drDus["Name"], check);
            }
        }
        /// <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 void OnAnyPopupOpenedOnRecieveGrid(object sender, EventArgs e)
        {
            GridView view = sender as GridView;

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

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

            }
        }
        private void RRFForm_Load(object sender, EventArgs e)
        {
            btnAutoPushToPFSA.Enabled = false;
            btnSendEmergencyOrder.Enabled = false;
            var unitcolumn = ((GridView) gridItemsChoice.MainView).Columns[2];
            var unitcolumn1 = ((GridView) gridItemsChoice.MainView).Columns[13];
            layoutControlItem18.Visibility =LayoutVisibility.Never;
            switch (VisibilitySetting.HandleUnits)
            {
                case 3:
                    unitcolumn.Visible = false;
                    unitcolumn1.Visible = true;
                    break;
                case 2:
                    unitcolumn.Visible = false;
                    unitcolumn1.Visible = true;
                    break;
                default:
                    unitcolumn.Visible = true;
                    unitcolumn1.Visible = false;
                    break;
            }

            var unit = new ItemUnit();
            var units = unit.GetAllUnits();
            unitsBindingSource.DataSource = units.DefaultView;

            var type = new BLL.Type();
            var alltypes = type.GetAllCategory();
            categorybindingSource.DataSource = alltypes.DefaultView;

            var program = new Programs();
            var programs = program.GetSubPrograms();
            cboProgram.Properties.DataSource = programs;
            cboProgram.Properties.DisplayMember = "Name";
            cboProgram.Properties.ValueMember = "ID";

            var orderstatus = new PharmInventory.HelperClasses.OrderStatus();
            orderbindingSource.DataSource = orderstatus.GetRRFOrders();
            lkorderstatus.Properties.DataSource = orderbindingSource;
            lkorderstatus.Properties.ValueMember = "RecordId";
            lkorderstatus.Properties.DisplayMember = "Name";

            PopulateTheMonthCombos(cboFromMonth);
            PopulateTheMonthCombos(cboToMonth);
            PopulateTheYearCombo(cboFromYear);
            PopulateTheYearCombo(cboToYear);
            var stor = new Stores();
            stor.GetActiveStores();
            cboStores.Properties.DataSource = stor.DefaultView;
            PopulateRRFs();

            WindowVisibility(false);
            EnableDisableStatusCheck();

            var prog = new Programs();
            prog.GetSubPrograms();
            cboProgram.Properties.DataSource = prog.DefaultView;
            cboProgram.EditValue = 1000;
        }
        private void ReceiveingForm_Load(object sender, EventArgs e)
        {
            SetPermissions();
            LoadDecimalFormatings();
            //Bind ReceiptType
            cboReceiveType.Properties.DataSource = ReceiptType.GetAllReceiptTypesForReceive();
            cboReceiveType.EditValue = ReceiptType.CONSTANTS.STANDARD_RECEIPT;

            //Bind the Receiving units Types Lookup
            InstitutionType institutionsTypes = new InstitutionType();
            institutionsTypes.LoadAll();
            institutionsTypes.Sort = "Name ASC";
            lkType.Properties.DataSource = institutionsTypes.DefaultView;
            lkType.EditValue = InstitutionType.Constants.HEALTH_CENTER;
            //---

            //Bind the Ownership Type Lookup
            LoadOwnershipType();
            lkOwnership.EditValue = OwnershipType.Constants.Public;
            LoadReceivingUnits();
            //----------------------------
            // reset the receiving date
            dtRecDate.Value = DateTimeHelper.ServerDateTime;
            // Load the logical stores and populate the combo boxes
            //lkStoreType.Properties.DataSource = BLL.StoreType.GetStoreTypesForAUser(NewMainWindow.UserId).DefaultView;
            lkAccounts.SetupActivityEditor().SetDefaultActivity();

            // Load the possible suppliers and populate

            // Load all occupied Pallet location list for the consolidate lookup editManuf2
            repoLKConsolidate.DataSource = PalletLocation.GetAllOccupied();

            // load the receiving unit's to the combo box
            Institution rus = new Institution();
            rus.LoadAll();
            lkFacilitySelection.Properties.DataSource = rus.DefaultView;

            lkStorageType.DataSource = StorageType.AllStorageTypes;

            // bulkPalletLocationLookup.DataSource = PalletLocation.GetAllFree(StorageType.BulkStore);
            nonBulkPalletLocationLookup.DataSource = PalletLocation.GetAllFreeNonBulk();
            //OnSelectedFilterChanged(new object(), new DevExpress.XtraEditors.Controls.ChangingEventArgs(null,"Drug"));

            // load all item Units
            ItemUnit itemUnit = new ItemUnit();
            itemUnit.LoadAll();
            editUnits.DataSource = itemUnit.DefaultView;

            lkCategories.Properties.DataSource = BLL.CommodityType.GetAllTypes();
            lkCategories.ItemIndex = 0;

            // Get the default who's receiving this
            txtReceivedBy.Text = CurrentContext.LoggedInUserName;

            // for RDF, Hide the packs column on receipt
            if (BLL.Settings.IsRdfMode)
            {
                colPacks.Visible = false;
            }

            //lcDeliveryNoteCheck.Visibility = BLL.Settings.HandleDeliveryNotes ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            colPricePerPack.Visible = !BLL.Settings.HandleGRV && srm != true;
            lcRefNoInput.Visibility =
                lcRefNo.Visibility =
                    BLL.Settings.HandleGRV
                        ? DevExpress.XtraLayout.Utils.LayoutVisibility.Never
                        : DevExpress.XtraLayout.Utils.LayoutVisibility.Always;

            if (BLL.Settings.IsCenter)
            {
                colShipper.Visible = false;
                colPercentReceived.Visible = true;
                colPrintedDate.Visible = false;
                PalletizeTab.PageVisible = false;
                txtPassCode.Enabled = false;
                lcPassCode .Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                tabReceiveTabs.TabPages[3].Text = "Step Three - Store Selection";
            }

            //Load the allowed Warehouses
            DataView PossibleWarehouses = BLL.Warehouse.getActiveWarehouseWithCluster(CurrentContext.UserId);
            lkWarehouse.Properties.DataSource = PossibleWarehouses;
            if (PossibleWarehouses.Count > 0)
            {
                lkWarehouse.EditValue = ((DataView)lkWarehouse.Properties.DataSource)[0]["ID"];
            }

            //Load IsElectronicReceiveOnly Setting
            LoadIsPOElectronicSetting();
        }
        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>
        /// 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 unitsrepositoryItemLookUpEdit_Enter(object sender, EventArgs e)
 {
     var edit = sender as LookUpEdit;
     if (edit == null) return;
     var clone = new ItemUnit();
     var row = gridRecieveView.GetFocusedDataRow();
     var id = Convert.ToInt32(row["ID"]);
     var filterunit = clone.LoadFromSQl(id);
     edit.Properties.DataSource = filterunit;
     edit.Properties.DisplayMember = "Text";
     edit.Properties.ValueMember = "ID";
 }
        private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                int itemID;
                if (!string.IsNullOrEmpty(txtItemID.Text))
                    _itemID = int.Parse(txtItemID.Text);
                itemID = _itemID;
                BLL.Item itm = new BLL.Item();
                itm.LoadByPrimaryKey(itemID);
                lblFullItemName.Text = itm.FullItemName;

                rd.LoadByItemID(itemID);
                grdReceiveDoc.DataSource = rd.DefaultView;

                recPallet.LoadByItemID(itemID);
                grdReceivePallet.DataSource = recPallet.DefaultView;

                id.LoadByItemID(itemID);
                grdIssueDoc.DataSource = id.DefaultView;

                ordDetail.LoadByItemID(itemID);
                grdOrderDetail.DataSource = ordDetail.DefaultView;

                pld.LoadByItemID(itemID);
                grdPickListDetail.DataSource = pld.DefaultView;

                _lossAndAdjustment.LoadByItemID(itemID);
                grdDisposal.DataSource = _lossAndAdjustment.DefaultView;

                yearEnd.LoadByItemID(itemID);
                grdYearEnd.DataSource = yearEnd.DefaultView;

                BLL.ItemUnit iu = new BLL.ItemUnit();
                iu.LoadAllForItem(int.Parse(txtItemID.Text));

                grdItemManufacturerItemUnit.DataSource = iu.DefaultView;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Corrects the unit qty per unit inconsistencies.
        /// </summary>
        /// <param name="itemID">The item ID.</param>
        public static void CorrectUnitQtyPerUnitInconsistencies(int itemID)
        {
            string query;
            ItemUnit iuExecute = new ItemUnit();
            //Make sure quantity values are corrected.

            query =
                HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesRd(itemID);
            iuExecute.LoadFromRawSql(query);

            query =
                HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesRp(itemID);
            iuExecute.LoadFromRawSql(query);

            query =
                HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesRd2(itemID);
            iuExecute.LoadFromRawSql(query);
            query =
                HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesId(itemID);
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesOdd(itemID);
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesPid(itemID);
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesPid2(itemID);
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesDisp(itemID);
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesIssueDoc(itemID);
            iuExecute.LoadFromRawSql(query);

            query = HCMIS.Repository.Queries.ItemUnit.UpdateCorrectUnitQtyPerUnitInconsistenciesReceiveDoc(itemID);
            iuExecute.LoadFromRawSql(query);
        }
        /// <summary>
        /// Adds to pick list for an order detail.
        /// </summary>
        /// <param name="orderDetailID">The order detail ID.</param>
        /// <param name="itemId">The item id.</param>
        /// <param name="unitID">The unit ID.</param>
        /// <param name="initalApprovedQuantity">The inital approved quantity.</param>
        /// <param name="storeID">The store ID.</param>
        /// <param name="preferedManufacturer">The prefered manufacturer.</param>
        /// <param name="preferredPhysicalStore">The preferred physical store.</param>
        /// <param name="isDeliveryNote">if set to <c>true</c> [is delivery note].</param>
        /// <param name="preferredExpiry">The preferred expiry.</param>
        /// <exception cref="System.Exception"></exception>
        private void AddToPickListFor(int userID, int orderDetailID, int itemId, int? unitID, decimal initalApprovedQuantity, int storeID, int preferedManufacturer, int preferredPhysicalStore, bool isDeliveryNote, DateTime? preferredExpiry)
        {
            bool deliveryNoteWarning = false;

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

            decimal approvedQuantity = initalApprovedQuantity;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // this means the pick face has been setup.
                DataRowView drv = _replenishmentList.DefaultView.AddNew();
                drv["ItemID"] = itemId;
                drv["StoreID"] = storeID;
                drv.EndEdit();
            }
        }
 public static string GetUnitText(int itemUnitID)
 {
     BLL.ItemUnit iUnit = new ItemUnit();
     iUnit.LoadByPrimaryKey(itemUnitID);
     if(iUnit.RowCount>0)
     {
         return iUnit.Text;
     }
     return "";
 }
        private void ManageItems_Load(object sender, EventArgs e)
        {
            PopulateCatTree(SelectedType);

            lkCommodityTypes.Properties.DataSource = BLL.Type.GetAllTypes();
            lkCommodityTypes.ItemIndex = 0;

            var itemunit = new ItemUnit();
            var allunits = itemunit.GetAllUnits();
            unitBindingSource.DataSource = allunits.DefaultView;

            var stor = new Stores();
            stor.GetActiveStores();
            cboStores.Properties.DataSource = stor.DefaultView;

            string[] arr = {"All",
            "Stock Out",
            "Below EOP",
            "Near EOP",
            "Normal",
            "Over Stocked"};

            cboStatus.Properties.DataSource = arr;

            DataTable dtMonths = new DataTable();
            dtMonths.Columns.Add("Value");
            dtMonths.Columns.Add("Month");
            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            dtCur = ConvertDate.DateConverter(dtDate.Text);
            int currentMont = dtCur.Month;
            int year = ((currentMont < 11) ? dtCur.Year : dtCur.Year + 1);
            // this is just a try
            if (currentMont >= 11)
            {
                currentMont -= 11;
            }

            var dtyears = Items.AllYears();

            cboYear.Properties.DataSource = dtyears;
            cboYear.EditValue = year;
            if (cboYear.Properties.Columns.Count > 0)
                cboYear.Properties.Columns[0].Alignment = DevExpress.Utils.HorzAlignment.Near;
            var prog = new Programs();
            var dtProg = new DataTable();
            dtProg = prog.GetSubPrograms();
            object[] objProg = { 0, "All Programs", "", 0, "" };
            dtProg.Rows.Add(objProg);
            cboSubProgram.Properties.DataSource = dtProg;
            cboSubProgram.ItemIndex = -1;
            cboSubProgram.Text = "Select Program";

            var rec = new ReceivingUnits();
            var drRec = rec.GetAllApplicableDU();
            cboIssuedTo.Properties.DataSource = drRec;
            cboIssuedTo.ItemIndex = -1;
            cboIssuedTo.Text = "Select Issue Location";
            IsReady = true;

            var unitcolumn = ((GridView)gridItemsChoice.MainView).Columns[15];
            switch (VisibilitySetting.HandleUnits)
            {
                case 1:
                    unitcolumn.Visible = false;
                    break;
                case 2:
                    unitcolumn.Visible = true;
                    break;
                default:
                    unitcolumn.Visible = true;
                    break;
            }
            PopulateGrid();
        }
        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;
        }
        /// <summary>
        /// Populate the lookups and item lists.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReceiveingForm_Load(object sender, EventArgs e)
        {
            //gridRecieveView.Columns[4].Visible = VisibilitySetting.HandleUnits;
            var UnitColumn = ((GridView)receivingGrid.MainView).Columns[12];
            var UnitColumn1 = ((GridView)receivingGrid.MainView).Columns[5];
            var UnitColumn2 = ((GridView)gridItemsChoice.MainView).Columns[4];
            var qtyperpack = ((GridView)receivingGrid.MainView).Columns[3];
            var buqty = ((GridView)receivingGrid.MainView).Columns[4];
            switch (VisibilitySetting.HandleUnits)
            {
                case 3:
                    UnitColumn.Visible = true;
                    UnitColumn1.Visible = false;
                    UnitColumn2.Visible = false;
                    qtyperpack.Visible = false;
                    buqty.Visible = false;
                    break;
                case 2:
                    UnitColumn.Visible = true;
                    UnitColumn1.Visible = false;
                    UnitColumn2.Visible = false;
                    qtyperpack.Visible = false;
                    buqty.Visible = false;
                    break;
                case 1:
                    UnitColumn.Visible = false;
                    UnitColumn1.Visible = true;
                    qtyperpack.Visible = true;
                    UnitColumn2.Visible = true;
                    buqty.Visible = true;
                    break;
            }

            var stor = new Stores();
            stor.GetActiveStores();

            cboStores.Properties.DataSource = stor.DefaultView;
            cboStores.ItemIndex = 0;

            Programs prog = new Programs();
            DataTable dtProg = prog.GetSubPrograms();
            cboProgram.Properties.DataSource = dtProg;
            cboProgram.Properties.DisplayMember = "Name";
            cboProgram.Properties.ValueMember = "ID";

            var unit = new ItemUnit();
            var units = unit.GetAllUnits();
            UnitsbindingSource.DataSource = units.DefaultView;

            Supplier sup = new Supplier();
            DataTable dtSup = new DataTable();
            sup.GetActiveSuppliers();
            dtSup = sup.DefaultView.ToTable();
            cboSuppliers.DataSource = dtSup;
            cboSupplier.Properties.DataSource = sup.DefaultView;
            cboSuppliers.Text = "Select Supplier";
            cboSuppliers.ValueMember = "ID";
            cboSuppliers.DisplayMember = "CompanyName";

            // Bind the grid with only active items
            Items itm = new Items();
            //DataTable dtItem = itm.GetAllItems(1);
            DataTable dtItem = BLL.Items.GetActiveItemsByCommodityType(0);
            lkCategories.Properties.DataSource = BLL.Type.GetAllTypes();
            lkCategories.ItemIndex = 0;

            PopulateItemList(dtItem);
            selectedType = radioGroup1.EditValue.ToString();
            PopulateCatTree(selectedType);

            int userID = MainWindow.LoggedinId;
            User us = new User();
            us.LoadByPrimaryKey(userID);
            txtReceivedBy.Text = us.FullName;

            // bind the current date as the datetime field
            dtRecDate.Value = DateTime.Now;
        }