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 StockCardReport CreateStockCard(int activityID, int itemID, int unitID, int warehouse, int manufactuererID, DateTime? startDate = null, DateTime? endDate = null)
        {
            BLL.Balance balance = new Balance();

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

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

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

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

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

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

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

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

            report.AppVersion.Text = "HCMIS";
            return report;
        }
        private void 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);
            }
        }
        public void LoadPalletLocation(int palletId,int shlefId=0)
        {
            _pl = new BLL.PalletLocation();
            _pl.loadByPalletID(palletId);

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

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

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

            lkFreePalletLocations.Properties.DataSource = BLL.PalletLocation.GetAllFreeFor(_itm.ID, shlefId);
        }
        private void OrderDetailForm_Load(object sender, EventArgs e)
        {
            Item item = new Item();
            item.LoadByPrimaryKey(_itemID);

            txtItemName.Text = item.FullItemName;

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

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

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

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

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

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

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

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

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

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

            report.ItemSource.Text = activity.FullActivityName;

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

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

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

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

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

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

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

                        if (consolidate)
                        {

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

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

                }

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

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

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

            PalletizedGrid.DataSource = _dtPalletizedItemList;
            gridNonPalletized.DataSource = _dtNonPalletizedItemList;
            CalculateVolumes();
        }
        /// <summary>
        /// Saves the whole transaction for
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        /// <param name="dvOutstandingPickList">The dv outstanding pick list.</param>
        /// <param name="remark">The remark.</param>
        /// <param name="issuedBy">The issued by.</param>
        /// <param name="etCurrentDate">The et current date.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static Order SaveIssueTransaction(int orderID, ref DataView dvOutstandingPickList, string remark, string issuedBy, DateTime etCurrentDate)
        {
            // Add the IssueDocID field
            dvOutstandingPickList.Table.Columns.Add("IssueDocID");
            PickList   plst   = new PickList();
            IssueDoc   issDoc = new IssueDoc();
            ReceiveDoc recDoc = new ReceiveDoc();

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

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


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

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

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


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

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

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

                //long prevQuantityLeft = recDoc.QuantityLeft;

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

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

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

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

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

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

                rp.ReservedStock -= totReservedQty;
                if (rp.ReservedStock < 0) //If there has been a quantity problem somewhere
                {
                    rp.ReservedStock = 0;
                }
                rp.Save();
            }
            plst.IsConfirmed = true;
            ord.ChangeStatus(OrderStatus.Constant.ISSUED, CurrentContext.UserId);
            plst.Save();
            ord.Save();
            return(ord);
        }
        private void btnSetNewPrice_Click(object sender, EventArgs e)
        {
            bool validated = false;
            ReceiveDoc rd = new ReceiveDoc();

            validated = dxValidationProviderPrice.Validate();

            if (!validated)
            {
                XtraMessageBox.Show("Please fill in all required fields!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!isConfirmation)
            {
                if (XtraMessageBox.Show("Are u sure, you want to save the new price change?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    MyGeneration.dOOdads.TransactionMgr transactionMgr = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
                    transactionMgr.BeginTransaction();
                    try
                    {
                        rs.NewUnitCost = Convert.ToDouble(txtAverageCost.EditValue);
                        rs.Margin = Convert.ToDouble(txtMargin.EditValue);
                        rs.NewSellingPrice = Convert.ToDouble(txtSellingPrice.EditValue);
                        rs.NewPrice = rs.NewSellingPrice;
                        //rs.Remark = txtRemark.EditValue.ToString();
                        // set the item as  weighted average item
                        Item itm = new Item();
                        itm.LoadByPrimaryKey(rs.ItemID);
                        itm.IsFree = false;

                        itm.Save();

                        rd.SavePrice(rs, CurrentContext.UserId);

                        transactionMgr.CommitTransaction();
                        XtraMessageBox.Show("Price setting successful", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }
                    catch (Exception ex)
                    {
                        transactionMgr.RollbackTransaction();
                        XtraMessageBox.Show("Price setting failed", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        throw ex;

                    }
                }
            }
            else
            {
                if (XtraMessageBox.Show("Are you sure you want to approve the new price change.", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    rd.ConfirmMovingAverage(rs, CurrentContext.UserId);
                    XtraMessageBox.Show("Price setting successful", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

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

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

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

                }

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

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

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

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

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

                //long prevQuantityLeft = recDoc.QuantityLeft;

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

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

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

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

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

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

                rp.ReservedStock -= totReservedQty;
                if (rp.ReservedStock < 0) //If there has been a quantity problem somewhere
                    rp.ReservedStock = 0;
                rp.Save();
            }
            plst.IsConfirmed = true;
            ord.ChangeStatus(OrderStatus.Constant.ISSUED, CurrentContext.UserId);
            plst.Save();
            ord.Save();
            return ord;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            ReceiveDoc rd = new ReceiveDoc();
            if (!confirmation)
            {
                rs.NewUnitCost = Convert.ToDouble(txtAverageCost.EditValue);
                rs.Margin = Convert.ToDouble(txtMargin.EditValue);
                rs.NewSellingPrice = Convert.ToDouble(txtSellingPrice.EditValue);
                rs.NewPrice = rs.NewSellingPrice;

                // set the item as  weighted average item
                Item itm = new Item();
                itm.LoadByPrimaryKey(ItemID);
                itm.IsFree = false;

                itm.Save();

                rd.SavePrice(rs, CurrentContext.UserId);

                //if (!StoreType.IsFreeStore(StoreID))
                //{
                //    //Change the cost
                //    rs.NewCost = rs.NewUnitCost;
                //    rd.SaveNewCost(rs, NewMainWindow.UserId);
                //}

                //-----------
                XtraMessageBox.Show("New Price setting has been saved.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                rd.ConfirmMovingAverage(rs, CurrentContext.UserId);

            }
            this.Close();
        }
        private void gridInvoiceDetailView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e != null && e.Column.FieldName == "InvoiceCost")
            {
                DataRow drv = gridInvoiceDetailView.GetFocusedDataRow();
                // receipt.SaveFOBForEachReceiveDoc();

                var receipt = new BLL.Receipt(Convert.ToInt32(drv["ReceiptID"]));
                var receiptInvoice = new ReceiptInvoice(receipt.ReceiptInvoiceID);
                var po = new BLL.PO(receiptInvoice.POID);

                if (po.IsElectronic)
                {
                    var originalInvoiceCost = Convert.ToDecimal(drv["OriginalInvoiceCost"]);
                    var newInvoiceCost = Convert.ToDecimal(drv["InvoiceCost"]);
                    if (newInvoiceCost != originalInvoiceCost)
                    {
                        drv["InvoiceCost"] = originalInvoiceCost;
                        XtraMessageBox.Show("You are trying to change the Invoice Cost set by Center. Please enter the correct cost!","Invoice Cost Not Similar",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                    }
                }
                else if (drv["InvoiceCost"] != DBNull.Value)
                {
                    PricePerPackPage PricingForm = new PricePerPackPage(ReceiptID, Convert.ToInt32(drv["ItemID"]),
                        Convert.ToInt32(drv["ItemUnitID"]), Convert.ToInt32(drv["ManufacturerID"]),
                        Convert.ToInt32(drv["ActivityID"]), Convert.ToDouble(drv["InvoiceCost"]));
                    PricingForm.ShowDialog(this);
                    LoadSelectedGRVDetailForInvoiceEntry(ReceiptID);
                }

            }
            else if (e != null && e.Column.FieldName == "Margin")
            {
                DataRow drv = gridInvoiceDetailView.GetFocusedDataRow();
                // receipt.SaveFOBForEachReceiveDoc();
                var receipt = new BLL.Receipt(Convert.ToInt32(drv["ReceiptID"]));
                var receiptInvoice = new ReceiptInvoice(receipt.ReceiptInvoiceID);
                var po = new BLL.PO(receiptInvoice.POID);
                var item = new Item();
                item.LoadByPrimaryKey(Convert.ToInt32(drv["ItemID"]));

                if (po.IsElectronic && !item.IsVariableMargin)
                {
                    var originalMargin = Convert.ToDecimal(drv["OriginalMargin"]);
                    var newMargin = Convert.ToDecimal(drv["Margin"]);
                    if (newMargin != originalMargin)
                    {
                        drv["Margin"] = originalMargin;
                        XtraMessageBox.Show("You are trying to change the Margin set by Center. Please enter the correct Margin!", "Margin Not Similar", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }

                else if (drv["Margin"] != DBNull.Value)
                {
                    MarginPage MarginForm = new MarginPage(ReceiptID, Convert.ToInt32(drv["ItemID"]), Convert.ToInt32(drv["ItemUnitID"]), Convert.ToInt32(drv["ManufacturerID"]), Convert.ToInt32(drv["ActivityID"]), Convert.ToDouble(drv["Margin"]));
                    MarginForm.ShowDialog(this);
                    LoadSelectedGRVDetailForInvoiceEntry(ReceiptID);
                }

            }
        }
        /// <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 btnSave_Click(object sender, EventArgs e)
        {
            if (!AccountTypeSelectionValid())
            {
                XtraMessageBox.Show("Please choose to which account types this item applies to.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                gridViewStoreItemMatrix.SetColumnError(gridColAcctType, "At least one account type needs to be selected");
                return;
            }
            Item itm = new Item();
            ItemSupplier itmSup = new ItemSupplier();
            if (itemId != 0)
                itm.LoadByPrimaryKey(itemId);
            else
            {
                itm.AddNew();
                ItemCategory prodCate = new ItemCategory();
                prodCate.AddNew();
                prodCate.ItemId = itm.ID;
                prodCate.SubCategoryID = Convert.ToInt32(categoryId);
                prodCate.Save();
            }
            if(radioGroupABC.EditValue != null){
                itm.ABC = Convert.ToInt32(radioGroupABC.EditValue);
            }

            if (radioGroupVEN.EditValue != null)
            {
                itm.VEN = Convert.ToInt32(radioGroupVEN.EditValue);
            }
            itm.IsInHospitalList = ckExculed.Checked;
            itm.ProcessInDecimal = chkProcessDecimal.Checked;
            itm.Save();

            if (itm.IsInHospitalList)
            {
                SaveHubDetails();
            }
            else
            {
                // clear out the prefered locations
                // clear out the pick face locations
                // make sure that this item could be made not in the list

            }

            itmSup.DeleteAllSupForItem(itm.ID);
            Supplier sup = new Supplier();
            for (int i = 0; i < lstSuppliers.CheckedItems.Count;i++ )
            {
                sup.GetSupplierByName(lstSuppliers.CheckedItems[i].ToString());
                itmSup.AddNew();
                itmSup.ItemID = itm.ID;
                itmSup.SupplierID = sup.ID;
                itmSup.Save();
            }

            ItemProgram progItm = new ItemProgram();
            progItm.DeleteAllProgramsForItem(itemId);
            BLL.Program prog = new BLL.Program();
            for (int i = 0; i < lstPrograms.CheckedItems.Count; i++)
            {
                prog.GetProgramByName(lstPrograms.CheckedItems[i].ToString());
                progItm.AddNew();
                progItm.ItemID = itm.ID;
                progItm.ProgramID = prog.ID;
                progItm.Save();
            }

                XtraMessageBox.Show("Item Detail is Saved Successfully!", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            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;
                }
            }
        }
        /// <summary>
        /// Fix For Delivery Note When Converting Do not use under any other situation
        /// </summary>
        /// <param name="issueDocID"></param>
        /// <param name="picklistID"></param>
        /// <returns></returns>
        public PickListDetail FixDeliveryNoteCostReceiveDoc(int issueDocID, int picklistID)
        {
            IssueDoc issueDoc = new IssueDoc();
            issueDoc.LoadByPrimaryKey(issueDocID);
            PickListDetail pickList = new PickListDetail();
            pickList.LoadByPrimaryKey(picklistID);
            //safety first
            if (issueDoc.RecievDocID != pickList.ReceiveDocID)
            {
                Item item = new Item();
                item.LoadByPrimaryKey(picklistID);
                throw new Exception(String.Format("PicklistDetail vs IssueDoc Inconsistancy for Item {0}", item.FullItemName));

            }
            // now we are sure we have one ReceiveDocID
            ReceiveDoc receiveDoc = new ReceiveDoc();
            receiveDoc.LoadByPrimaryKey(pickList.ReceiveDocID);
            ReceiveDocConfirmation receiveDocConfirmation = new ReceiveDocConfirmation();
            receiveDocConfirmation.LoadByReceiveDocID(receiveDoc.ID);
            //Check if it has been Printed and that Selling Price and Cost is set
            if (receiveDocConfirmation.ReceiptConfirmationStatusID == ReceiptConfirmationStatus.Constants.GRV_PRINTED)
            {
                double unitPrice, unitCost, margin;
                if (Settings.IsCenter == true && !receiveDoc.IsColumnNull("Cost") && receiveDoc.Cost != 0)
                {
                    unitPrice = Math.Round(receiveDoc.Cost, 2);
                    unitCost = Math.Round(receiveDoc.Cost, 2);
                    margin = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;

                }
                else if (!receiveDoc.IsColumnNull("SellingPrice") && receiveDoc.SellingPrice != 0)
                {
                    unitPrice = Math.Round(receiveDoc.SellingPrice, 2);
                    unitCost = Math.Round(receiveDoc.SellingPrice, 2);
                    margin = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;

                }
                else
                {
                    var item = new Item();
                    item.LoadByPrimaryKey(pickList.ItemID);
                    throw new Exception(String.Format("Price Not set For item: {0}", item.FullItemName));
                }
                pickList.UnitPrice = unitPrice;
                pickList.Cost = Convert.ToDouble(pickList.Packs) * unitPrice;
                issueDoc.SellingPrice = Convert.ToDecimal(unitPrice);
                issueDoc.Cost = Convert.ToDouble(issueDoc.NoOfPack) * unitPrice;
                issueDoc.UnitCost = Convert.ToDecimal(unitCost);
                issueDoc.Margin = Convert.ToDecimal(margin);
                pickList.Save();
                issueDoc.Save();
            }
            else
            {
                var item = new Item();
                item.LoadByPrimaryKey(pickList.ItemID);
                throw new Exception(String.Format("GRV/IGRV Not Printed For Item: {0}", item.FullItemName));
            }
            return pickList;
        }
        private void btnCommit_Click(object sender, EventArgs e)
        {
            if (ValidateQuarantine())
            {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                 it.AddNew();
                                 it.ItemID = rd.ItemID;
                                 it.BoxLevel = 0;// im.PackageLevel;
                                 //it.ExpireDate = rd.ExpDate;
                                 if (!rd.IsColumnNull("ExpDate"))
                                 {
                                     it.ExpireDate = rd.ExpDate;
                                 }
                                 it.BatchNumber = rd.BatchNo;
                                 it.ManufacturerID = Convert.ToInt32(dr["ManufacturerID"]);//im.ManufacturerID;
                                 it.FromPalletLocationID = qPalletLocationID;
                                 it.ToPalletLocationID = int.Parse(dr["NewPalletLocation"].ToString()); //pl2.ID;
                                 it.QtyPerPack = 1;
                                //it.Packs = pack qty;
                                 it.ReceiveDocID = rp.ReceiveID;
                                 it.QuantityInBU = amount;// it.QtyPerPack;
                                 it.Type = "ReLocation";
                                 it.IssuedDate = DateTime.Today;
                                 it.Status = 0;
                                 it.PrintNumber = printNubmer;
                                 it.Save();
                             }
                         }
                    }
                    transaction.CommitTransaction();
                    BindQuarantine();
                    XtraMessageBox.Show("Quarantine Write off/Adjustment was commitd.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
 /// <summary>
 /// Gets the name of the Item
 /// </summary>
 /// <param name="itemId">The item id.</param>
 /// <returns></returns>
 public static string GetName(int itemId)
 {
     Item itm = new Item();
     itm.LoadByPrimaryKey(itemId);
     return itm.FullItemName;
 }
        private bool ValidatePickList()
        {
            foreach (DataRowView drv in _dvPickListMakeup)
            {
                int itemID = Convert.ToInt32(drv["ItemID"]);
                int storeID = Convert.ToInt32(drv["StoreID"]);
                int unitID = Convert.ToInt32(drv["UnitID"]);
                int manufacturerID = Convert.ToInt32(drv["ManufacturerID"]);

                ReceiveDoc rd = new ReceiveDoc();

                if (BLL.Settings.BlockWhenExpectingPriceChange && BLL.ReceiveDoc.DoesPriceNeedToBeChanged(storeID, itemID, unitID, manufacturerID) )
                {
                    OrderDetail odetail = new OrderDetail();
                    odetail.Where.ItemID.Value = itemID;
                    odetail.Where.OrderID.Value = _orderID;
                    odetail.Query.Load();
                    if (odetail.RowCount > 0)
                    {
                        if (odetail.ApprovedQuantity == 0)
                            continue;
                    }

                    Item itm = new Item();
                    itm.LoadByPrimaryKey(itemID);
                    XtraMessageBox.Show(
                        string.Format("The item {0} cannot be issued because it is waiting for price change.", itm.FullItemName),
                        "Price Pending", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return true;
                }
            }
            return false;
        }
        private void SaveReceive()
        {
            // Merge all Receives with Same Item information and Assigned to Same PhysicalStore as One Item , Quantity Sumed UP!
            MergeReceiveDocLines();

            BLL.ReceiveDoc rec = new ReceiveDoc();

            ////int receiptTypeID = srm
            ////    ? ReceiptType.CONSTANTS.STOCK_RETURN
            ////    : (deliveryNoteType != DeliveryNoteType.NotSet)
            ////        ? ReceiptType.CONSTANTS.DELIVERY_NOTE
            ////        : beginningBalance
            ////            ? ReceiptType.CONSTANTS.BEGINNING_BALANCE
            ////            : ReceiptType.CONSTANTS.STANDARD_RECEIPT;
            int receiptID;
            int warehouseID = Convert.ToInt32(lkWarehouse.EditValue);

            receiptID = SaveRelevantReceiptHeaders(_receiptTypeID, warehouseID);

            DataTable zeroQuantitiesDueToMultipleBatch = null;
            DataRow [] zeroQuantityRows =
                _dtRecGrid.Select(string.Format("[Pack Qty] = 0"),"[Ordering] ASC ");

            if (zeroQuantityRows.Any() && zeroQuantityRows.Any(r => r["ShortageReasonID"] == DBNull.Value))
            {
                zeroQuantityRows = CheckAndRemoveIfFullNotReceiveEntry(zeroQuantityRows);
                if (zeroQuantityRows.Any())
                    zeroQuantitiesDueToMultipleBatch =
                        zeroQuantityRows.Where(r => r["ShortageReasonID"] == DBNull.Value).CopyToDataTable();
            }

            var mergeableTables = _dtRecGrid.Select(string.Format("[Pack Qty] > 0 "), "[Ordering] ASC ");
            DataTable mergedDataTable = null;
            if (mergeableTables.Any())
            {
                mergedDataTable =
                    _dtRecGrid.Select(string.Format("[Pack Qty] > 0 "), "[Ordering] ASC ").CopyToDataTable();

                if (zeroQuantitiesDueToMultipleBatch != null)
                    mergedDataTable.Merge(zeroQuantitiesDueToMultipleBatch);

                if (grdShortageOrDamaged.DataSource != null)
                {
                    var shortageOrDamage = (DataTable) grdShortageOrDamaged.DataSource;
                    mergedDataTable.Merge(shortageOrDamage);
                }
            }
            else
            {
                if (grdShortageOrDamaged.DataSource != null)
                {
                    var shortageOrDamage = (DataTable)grdShortageOrDamaged.DataSource;
                    if (zeroQuantitiesDueToMultipleBatch != null)
                        shortageOrDamage.Merge(zeroQuantitiesDueToMultipleBatch);
                    //~ {"[ShortageReasonID] ASC} --> Just to give priority among shortages to Damaged reasons as we will create a receiveDoc entry for this ~//
                    mergedDataTable = mergedDataTable == null ? shortageOrDamage.Select(string.Format("[Pack Qty] >= 0 "), "[ShortageReasonID] ASC ").CopyToDataTable() : shortageOrDamage;

                }
            }

            foreach (DataRowView dr in mergedDataTable.DefaultView)
            {
                var shortageReasonID = dr["ShortageReasonID"];

                var onlyOneEntryFound = _dtRecGrid.Select(String.Format("GUID = '{0}'", dr["GUID"]));

                bool zeroQtyDueTomultipleBatchFound = (Convert.ToDecimal(dr["Pack Qty"]) == 0) && (shortageReasonID == DBNull.Value) && (onlyOneEntryFound.Count() == 1);
                bool fullNotReceivedEntry = (Convert.ToDecimal(dr["BU Qty"]) == 0) && (shortageReasonID != DBNull.Value) && (Convert.ToInt32(shortageReasonID) == ShortageReasons.Constants.NOT_RECEIVED) && (onlyOneEntryFound.Count() == 1);
                if (fullNotReceivedEntry)
                {
                    dr["Pack Qty"] = 0;
                }

                var item = new Item();
                item.LoadByPrimaryKey(Convert.ToInt32(dr["ID"]));

                if (item.NeedExpiryBatch || (shortageReasonID == DBNull.Value && ((dr["Expiry Date"] != DBNull.Value) && (Convert.ToDateTime(dr["Expiry Date"]) <= DateTimeHelper.ServerDateTime))))
                {

                    var expDate = Convert.ToDateTime(dr["Expiry Date"]);

                    if ((shortageReasonID == DBNull.Value && expDate > DateTimeHelper.ServerDateTime) || zeroQtyDueTomultipleBatchFound)
                    {
                        AddNewReceiveDoc(rec, receiptID, dr);
                    }
                    else
                    {
                        //for physically Damaged receives and expired receives
                        if ((shortageReasonID != DBNull.Value && Convert.ToInt32(shortageReasonID) == ShortageReasons.Constants.DAMAGED) || (shortageReasonID == DBNull.Value && expDate <= DateTimeHelper.ServerDateTime) || fullNotReceivedEntry)
                        {
                            AddNewReceiveDoc(rec, receiptID, dr, true);
                            if (shortageReasonID == DBNull.Value)
                            {
                                dr["ShortageReasonID"] = ShortageReasons.Constants.DAMAGED;
                            }
                        }
                        else
                        {

                            HandleReceiveDocShortage(dr, rec);
                        }
                    }
                }
                else
                {

                    if ((shortageReasonID == DBNull.Value) || zeroQtyDueTomultipleBatchFound)
                    {
                        AddNewReceiveDoc(rec, receiptID, dr);
                    }
                    else
                    {
                        //for physically Damaged receives
                        if (shortageReasonID != DBNull.Value && Convert.ToInt32(shortageReasonID) == ShortageReasons.Constants.DAMAGED || fullNotReceivedEntry)
                        {
                            AddNewReceiveDoc(rec, receiptID, dr, true);
                        }
                        else
                        {
                            HandleReceiveDocShortage(dr, rec);
                        }

                    }
                }

            }

            rec.SetStatusAsReceived(CurrentContext.UserId);

            BLL.Receipt receiptStatus = new BLL.Receipt();
            receiptStatus.LoadByPrimaryKey(receiptID);
            receiptStatus.ChangeStatus(ReceiptConfirmationStatus.Constants.RECEIVE_ENTERED, null,
                this.GetFormIdentifier(), CurrentContext.UserId, "Received");
            if (!BLL.Settings.HandleGRV) //If HandleGRV is true, the price isn't entered in the receive stage meaning
            {
                rec.Rewind();
                while (!rec.EOF)
                {
                    if (!ReceiveDoc.DoesPriceNeedToBeChanged(rec.StoreID, rec.ItemID, rec.UnitID, rec.ManufacturerId) &&
                        (deliveryNoteType == DeliveryNoteType.NotSet))
                    {
                        rec.SellingPrice = rec.Cost;
                        rec.UnitCost = Convert.ToDecimal(rec.Cost);
                        // Added by Heny In order to display Unit Cost on Vaccine
                        rec.Margin = 0;
                    }
                    rec.MoveNext();
                }
            }

            rec.Save(); //TODO: To be removed after the ShortageReasonID in receviedoc is discontinued.

            //SavePalletization(rdDamaged);
            _revDocRelatePalletGuid.Clear();
        }
        private void ResetForHub()
        {
            grpStorageSettings.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            // Bind the Storage Types

            cmbStorageType.DataSource = StorageType.PrimaryStorageTypes;

            Item itm = new Item();
            itm.LoadByPrimaryKey(itemId);
            if (!itm.IsColumnNull("StorageTypeID"))
            {
                cmbStorageType.SelectedValue = itm.StorageTypeID.ToString();
                if (itm.StorageTypeID.ToString() == StorageType.BulkStore)
                {
                    gridPickfaceLocationsContainer.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    if (itm.IsColumnNull("IsStackStored"))
                    {
                        chkIsStackStored.Checked = false;
                    }
                    else
                    {
                        chkIsStackStored.Checked = itm.IsStackStored;
                    }
                }

            }
            else
            {
                cmbStorageType.SelectedIndex = 0;
            }
            numNearExpiryTrigger.Visible = true;

            if (!itm.IsColumnNull("NearExpiryTrigger"))
                numNearExpiryTrigger.Value = Convert.ToDecimal(itm.NearExpiryTrigger);
        }
        private bool ValidateStep2()
        {
            //TODO: Do a better validation here
            var invoiceNo = lkReceiptInvoice.Text;
            var IsElectronic = ReceiptInvoice.IsInvoiceElectronic(invoiceNo);

            if (lcRefNo.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always && !dxValidateRefNo.Validate())
            {
                XtraMessageBox.Show("Please input STV/Invoice inorder to proceed.", "Input Invoice", MessageBoxButtons.OK);
                return false;
            }
            //TODO: use the dx validation provider.
            //or This has to be done on the first step.
            if (BLL.Settings.IsCenter && lcReceiptInvoice.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always && lkReceiptInvoice.Enabled == true && lkReceiptInvoice.EditValue == null)
            {
                XtraMessageBox.Show("Please choose invoice to proceed.", "Choose Invoice", MessageBoxButtons.OK);
                return false;
            }

            if (srm && !dxValidateRemark.Validate())
            {
                XtraMessageBox.Show("Please fill in the reason for the SRM to proceed.", "SRM Reason", MessageBoxButtons.OK);
                return false;
            }

            // Are all required fields filled in the grid?
            // and are those fields that accept decimal and not abused?
            bool isValid = true;
            foreach (DataRow dr in _dtRecGrid.Rows)
            {
                Item item = new Item();
                item.LoadByPrimaryKey(Convert.ToInt32(dr["ID"]));
                dr.ClearErrors();

                if (Convert.ToInt32(cboReceiveType.EditValue) != ReceiptType.CONSTANTS.STOCK_RETURN && !beginningBalance && dr["InvoicedQty"] == DBNull.Value)
                {
                    dr.SetColumnError("InvoicedQty", "Invoiced Quantity Cannot be Blank");
                    isValid = false;
                }
                else
                {

                    if (!item.ProcessInDecimal)
                    {
                        if (Convert.ToInt32(cboReceiveType.EditValue) != ReceiptType.CONSTANTS.STOCK_RETURN && dr["InvoicedQty"] != DBNull.Value && Convert.ToDecimal(dr["InvoicedQty"]) % 1 != 0)
                        {
                            dr.SetColumnError("InvoicedQty", "Invoiced Quantity Cannot Decimal for this Item");
                            isValid = false;
                        }

                    }
                }

                if (dr["Pack Qty"] == DBNull.Value)
                {
                    dr.SetColumnError("Pack Qty", "Received Quantity Cannot be Blank");
                    isValid = false;
                }
                else
                {
                    if (Convert.ToDecimal(dr["Pack Qty"]) % 1 != 0 && !item.ProcessInDecimal)
                    {
                        dr.SetColumnError("Pack Qty", "Invoiced Quantity Cannot Decimal for this Item");
                        isValid = false;
                    }
                }
            }

            // Before continuing to the next validation ... check if the previous once have passed.
            if (!isValid)
            {
                return false;
            }
            // do all the descrepancies have entry on the detail?
            isValid = true;
            DataTable descrepancyDetails = (DataTable)grdShortageOrDamaged.DataSource;

            foreach (DataRow dr in _dtRecGrid.Rows)
            {
                dr.ClearErrors();
                // find the descrepancy - if there is any
                decimal descrepancy = 0;
                decimal splittedQty = 0;

                if (Convert.ToInt32(cboReceiveType.EditValue) != ReceiptType.CONSTANTS.STOCK_RETURN && dr["InvoicedQty"] != DBNull.Value)
                {
                     descrepancy = Convert.ToDecimal(dr["NotReceived"]);
                    //dr["GUID"];
                }

                // if the descrepancy is 0, then there need not be any entry down there

               decimal sumOfDetails = 0;

               if (descrepancyDetails != null && descrepancyDetails.Rows.Count != 0)
               {
                   string batchNofilter = (Convert.ToString(dr["Batch No"]).Equals("")) ? "" : string.Format(" And [Batch No] = '{0}'", Convert.ToString(dr["Batch No"]));
                   string filterString = string.Format("ID = '{0}' AND UnitID = '{1}' AND Manufacturer = '{2}' {3} ", dr["ID"], dr["UnitID"], dr["Manufacturer"], batchNofilter);

                   if (!descrepancyDetails.Select(filterString).Any()) continue; //~Splitted Batch Case! Since Our Descrepancy is only one let us jump the Copied ones!~//
                    sumOfDetails =
                        descrepancyDetails.Select(filterString).Sum(r => r.Field<decimal>("Pack Qty"));

                }

                if (descrepancy <= 0)
                {
                    if (sumOfDetails > 0)
                    {
                        isValid = false;
                        dr.SetColumnError("Pack Qty", "This desrepancy Detail is not neccessary.");
                    }
                }
                // else, is the sum of the descrepancies = the actual discrepancy documented with the details?
                else
                {

                    if (sumOfDetails == 0)
                    {
                        dr.SetColumnError("Pack Qty", "There is no valid descrepancy detail. Please revisit your entries.");
                        isValid = false;
                    }
                    else if (sumOfDetails != descrepancy)
                    {
                        dr.SetColumnError("Pack Qty", "The descrepancy don't match with the sum of details you specified below.");
                        isValid = false;
                    }

                }
            }

            // is the reason specified?
            if (descrepancyDetails != null)
            {
                foreach (DataRow dr in descrepancyDetails.Rows)
                {
                    dr.ClearErrors();

                    if (dr["ShortageReasonID"] == DBNull.Value)
                    {
                        dr.SetColumnError("ShortageReasonID", "You should select the descrepancy reason.");
                        isValid = false;
                    }

                }
            }
            return isValid;
        }
        private void SaveHubDetails()
        {
            if (isStorageTypeChanged)
            {

                isStorageTypeChanged = false;
                BLL.ItemPrefferedLocation ipl = new ItemPrefferedLocation();
                ipl.LoadByItemID(itemId);
                while (!ipl.EOF)
                {
                    ipl.MarkAsDeleted();
                    ipl.MoveNext();
                }
                ipl.Save();

            }

            Item itm = new Item();

            if (cmbStorageType.SelectedValue != null)
            {
                if (cmbStorageType.SelectedValue.ToString() == StorageType.BulkStore)
                {
                    // store the stacked storage settings
                    itm.LoadByPrimaryKey(itemId);
                    itm.IsStackStored = chkIsStackStored.Checked;
                    itm.Save();

                    if (lstPreferredPalletLocation.ItemCount > 0)
                    {
                        //Items itm = new Items();

                        // save near expiry trigger point

                        ItemPrefferedLocation ipr = new ItemPrefferedLocation();
                        DataView dv = (DataView)lstPreferredPalletLocation.DataSource;
                        foreach (DataRowView drv in dv)
                        {
                            ipr.SaveNewItemPreferredRack(itemId, Convert.ToInt32(drv["ID"]),false);
                        }

                    }
                    // store pickface settings
                    pf.Rewind();
                    PickFace pfc = new PickFace();
                    while (!pf.EOF)
                    {
                        pf.AcceptChanges();
                        if (!pf.IsColumnNull("PalletLocationID"))
                        {
                            pfc.SavePickFaceLocation(itemId, pf.PalletLocationID, pf.LogicalStore);
                        }
                        else
                        {

                            pfc.LoadPickFaceFor(itemId, pf.LogicalStore);
                            if (pfc.RowCount> 0 && (pfc.IsColumnNull("Balance") || pfc.Balance == 0))
                            {
                                pfc.ClearPickFaceFor(itemId, pfc.LogicalStore);
                            }
                            else
                            {
                                //TODO: show the error message for the user
                            }

                        }
                        pf.MoveNext();
                    }

                }
                else
                {
                    // Save the fixed locations
                    var ipr = new ItemPrefferedLocation();
                    DataView dv = (DataView)lstPreferredPalletLocation.DataSource;
                    if (dv != null)
                    {
                        foreach (DataRowView drv in dv)
                        {
                            ipr.SaveNewItemPreferredRack(itemId, Convert.ToInt32(drv["ID"]), true);
                        }
                    }
                }

                itm.LoadByPrimaryKey(itemId);
                itm.StorageTypeID = int.Parse(cmbStorageType.SelectedValue.ToString());
                itm.NearExpiryTrigger = Convert.ToDouble(numNearExpiryTrigger.Value);
                itm.Save();

            }
        }
        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);
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Fix For Delivery Note When Converting Do not use under any other situation
        /// </summary>
        /// <param name="issueDocID"></param>
        /// <param name="picklistID"></param>
        /// <returns></returns>
        public PickListDetail FixDeliveryNoteCostReceiveDoc(int issueDocID, int picklistID)
        {
            IssueDoc issueDoc = new IssueDoc();

            issueDoc.LoadByPrimaryKey(issueDocID);
            PickListDetail pickList = new PickListDetail();

            pickList.LoadByPrimaryKey(picklistID);
            //safety first
            if (issueDoc.RecievDocID != pickList.ReceiveDocID)
            {
                Item item = new Item();
                item.LoadByPrimaryKey(picklistID);
                throw new Exception(String.Format("PicklistDetail vs IssueDoc Inconsistancy for Item {0}", item.FullItemName));
            }
            // now we are sure we have one ReceiveDocID
            ReceiveDoc receiveDoc = new ReceiveDoc();

            receiveDoc.LoadByPrimaryKey(pickList.ReceiveDocID);
            ReceiveDocConfirmation receiveDocConfirmation = new ReceiveDocConfirmation();

            receiveDocConfirmation.LoadByReceiveDocID(receiveDoc.ID);
            //Check if it has been Printed and that Selling Price and Cost is set
            if (receiveDocConfirmation.ReceiptConfirmationStatusID == ReceiptConfirmationStatus.Constants.GRV_PRINTED)
            {
                double unitPrice, unitCost, margin;
                if (Settings.IsCenter == true && !receiveDoc.IsColumnNull("Cost") && receiveDoc.Cost != 0)
                {
                    unitPrice = Math.Round(receiveDoc.Cost, 2);
                    unitCost  = Math.Round(receiveDoc.Cost, 2);
                    margin    = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;
                }
                else if (!receiveDoc.IsColumnNull("SellingPrice") && receiveDoc.SellingPrice != 0)
                {
                    unitPrice = Math.Round(receiveDoc.SellingPrice, 2);
                    unitCost  = Math.Round(receiveDoc.SellingPrice, 2);
                    margin    = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;
                }
                else
                {
                    var item = new Item();
                    item.LoadByPrimaryKey(pickList.ItemID);
                    throw new Exception(String.Format("Price Not set For item: {0}", item.FullItemName));
                }
                pickList.UnitPrice    = unitPrice;
                pickList.Cost         = Convert.ToDouble(pickList.Packs) * unitPrice;
                issueDoc.SellingPrice = Convert.ToDecimal(unitPrice);
                issueDoc.Cost         = Convert.ToDouble(issueDoc.NoOfPack) * unitPrice;
                issueDoc.UnitCost     = Convert.ToDecimal(unitCost);
                issueDoc.Margin       = Convert.ToDecimal(margin);
                pickList.Save();
                issueDoc.Save();
            }
            else
            {
                var item = new Item();
                item.LoadByPrimaryKey(pickList.ItemID);
                throw new Exception(String.Format("GRV/IGRV Not Printed For Item: {0}", item.FullItemName));
            }
            return(pickList);
        }
        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;
        }
        private bool ValidateForm()
        {
            _gridIsValid = true;

            if (gridOrderView.RowCount == 0)
            {
                XtraMessageBox.Show("You cannot save an Empty Wish list.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (!dxValidation1stTab.Validate())
            {
                return false;
            }

            if (lkPaymentType.Text == "Credit" && txtLetterNumber.Text == "")
            {

                XtraMessageBox.Show("You cannot save credit sales without letter number.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (lkForFacility.EditValue == null)
            {
                XtraMessageBox.Show("Please Fill Receiving Unit.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            for (int i = 0; i < gridOrderView.RowCount; i++)
            {

                DataRow dr = gridOrderView.GetDataRow(i);
                dr.ClearErrors();

                if (dr["Quantity"] == DBNull.Value)
                {

                    _gridIsValid = false;
                    dr.SetColumnError("Pack", @"Quantity couldn't be left empty");
                }
                // check if decimal is allowed.
                if (dr["Pack"] != DBNull.Value && Convert.ToDecimal(dr["Pack"]) % 1 != 0)
                {
                    Item itm = new Item();
                    itm.LoadByPrimaryKey(Convert.ToInt32(dr["ItemID"]));
                    if (!itm.ProcessInDecimal)
                    {
                        _gridIsValid = false;
                        dr.SetColumnError("Pack", @"Quantity couldn't be decimal for this Item.");
                    }
                }
            }

            return _gridIsValid;
        }
        private void SetPriceAndQuantity(DataRow dr, decimal dispatch, int buinsku, ReceivePallet rp, int itemId, bool isDeliveryNote)
        {
            dr["DeliveryNote"] = isDeliveryNote;
            dr["BoxLevel"] = 0;
            dr["QtyPerPack"] = buinsku;
            dr["Pack"] = dispatch / buinsku;
            decimal packs = dispatch / buinsku;
            dr["QtyInBU"] = dispatch;
            dr["approvedQuantity"] = dispatch;

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

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

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

            }

            dr["UnitsInSKU"] = buinsku;
        }
        /// <summary>
        /// This needs to be called after FillInReceiveDocInformation has been called.
        /// </summary>
        /// <param name="rec">ReceiveDoc should be passed to this function having been saved and with the id field different from null</param>
        /// <param name="dr">ReceiveDoc should be passed to this function having been saved and with the id field different from null</param>
        private void HandleReceiveDocShortage(DataRowView dr, ReceiveDoc rec, int receiveDocID = 0)
        {
            var recShortage = new ReceiveDocShortage();
            bool shortagetoBeAdded = false;

            if (receiveDocID == 0)
            {
                receiveDocID = Convert.ToInt32(rec.DefaultView.Table.Select(String.Format("GUID = '{0}'", dr["GUID"]))[0]["ID"]);
                shortagetoBeAdded = true;
            }

            //if (rec.GetColumn("ShortageReasonID") == System.DBNull.Value || Convert.ToInt32(rec.GetColumn("ShortageReasonID")) == 1) return;

            if ((srm && Convert.ToBoolean(dr["IsDamaged"])) || (Convert.ToDecimal(dr["InvoicedQty"]) >= Convert.ToDecimal(dr["Pack Qty"])))
            {
                var item = new Item();
                item.LoadByPrimaryKey(Convert.ToInt32(dr["id"]));

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

                if (dr["ShortageReasonID"] != DBNull.Value && (!(Convert.ToDecimal(dr["Pack Qty"]) == 0 && Convert.ToInt32(dr["ShortageReasonID"]) == ShortageReasons.Constants.NOT_RECEIVED)))
                {
                    int shortageReasonID = Convert.ToInt32(dr["ShortageReasonID"]);

                    recShortage.AddNew();
                    recShortage.ShortageReasonID = shortageReasonID;
                    recShortage.ReceiveDocID = receiveDocID;
                    recShortage.NoOfPacks = Convert.ToDecimal(dr["Pack Qty"]);

                    if (shortagetoBeAdded)
                    {
                        var receiveDoc = new ReceiveDoc();
                        receiveDoc.LoadByPrimaryKey(receiveDocID);
                        if (receiveDoc.InvoicedNoOfPack!=0 && receiveDoc.Quantity >= receiveDoc.InvoicedNoOfPack)
                        {
                            receiveDoc.InvoicedNoOfPack = receiveDoc.Quantity + recShortage.NoOfPacks;
                            receiveDoc.Save();
                        }

                    }
                }
                else
                {
                    XtraMessageBox.Show(
                        "Please enter the reason for the discrepancy in invoiced vs. received qty.", "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            recShortage.Save();
        }
        /// <summary>
        /// Issues the valid.
        /// </summary>
        /// <returns></returns>
        private bool IssueValid()
        {
            //check approved against
            // check if the order has not alrady been printed
            Order Order = new Order();
            Order.LoadByPrimaryKey(_orderID);

            if (Order.OrderStatusID < OrderStatus.Constant.PICK_LIST_CONFIRMED)
            {
                XtraMessageBox.Show("Order is not yet ready for printing Invoice");
                return false;
            }
            else if (Order.OrderStatusID == OrderStatus.Constant.ISSUED)
            {
                XtraMessageBox.Show("This Order has already been printed. Please select another one.");
                return false;
            }
            else if (Order.OrderStatusID == OrderStatus.Constant.CANCELED)
            {
                XtraMessageBox.Show("This Order has been canceled. Please select another one.");
                return false;
            }

            bool valid = true;
            DataView pl = gridOutstandingPicklistDetail.DataSource as DataView;
            foreach (DataRowView drv in pl)
            {
                ReceiveDoc rd = new ReceiveDoc();
                drv.Row.ClearErrors();
                if (drv["SKUPICKED"] == null || drv["SKUPICKED"] == DBNull.Value)
                {
                    drv.Row.SetColumnError("SKUPICKED", @"Field cannot be left empty");
                    valid = false;
                }
                else if (Convert.ToInt32(drv["SKUPICKED"]) > Convert.ToInt32(drv["SKUTOPICK"]))
                {
                    drv.Row.SetColumnError("SKUPICKED", @"You cannot issue more amount than the Approved Quantity");
                    valid = false;
                }

                else if (BLL.Settings.BlockWhenExpectingPriceChange && BLL.ReceiveDoc.DoesPriceNeedToBeChanged(int.Parse(drv["StoreID"].ToString()), int.Parse(drv["ItemID"].ToString()), int.Parse(drv["UnitID"].ToString()), int.Parse(drv["ManufacturerID"].ToString())) && Convert.ToInt32(drv["SKUPICKED"]) > 0) //rd.IsInNonPricedItemsList(int.Parse(drv["ItemID"].ToString())) && Convert.ToInt32(drv["SKUPICKED"]) > 0)
                {
                    drv.Row.SetColumnError("FullItemName", @"Price Pending!");
                    Item itm = new Item();
                    itm.LoadByPrimaryKey(int.Parse(drv["ItemID"].ToString()));
                    XtraMessageBox.Show(string.Format("The item {0} cannot be issued because it is waiting for price change.", itm.FullItemName), "Price Pending", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    valid = false;
                }
            }

            if (Order.PaymentTypeID != PaymentType.Constants.CASH && Order.PaymentTypeID != PaymentType.Constants.CREDIT && Order.PaymentTypeID != PaymentType.Constants.STV)
            {
                //TODO: This needs to be handled well.
                XtraMessageBox.Show(
                    string.Format("PaymentTypeID has a problem.  The order has a payment type id of {0}",
                                  Order.PaymentTypeID.ToString()), "Payment Type ID Problem");
                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                valid = false;
            }

            if (valid)
            {
                valid = dxValidationProvider1.Validate();
            }

            return valid;
        }
        private bool IsRecieveGridValid()
        {
            bool valid = true;
            for (int i = 0; i < gridRecieveView.RowCount; i++)
            {
                DataRow dr = gridRecieveView.GetDataRow(i);
                Item itm = new Item();
                itm.LoadByPrimaryKey(Convert.ToInt32(dr["ID"]));
                dr.ClearErrors();

                if (!BLL.Settings.HandleGRV && srm != true)
                //The price is entered right here if we don't handle the GRVs
                {
                    //Unless it is a receive by delivery note, price needs to be entered.
                    //txtSTVNo.Text = txtRefNo.Text;
                    if ((dr["Price/Pack"] == DBNull.Value || dr["Price/Pack"] == null ||
                         dr["Price/Pack"].ToString() == "") && deliveryNoteType == DeliveryNoteType.NotSet)
                    {
                        dr.SetColumnError("Price/Pack", @"Please fill the cost");

                        valid = false;
                    }

                    //If it is a delivery note receive, it cannot have price.
                    //var pricePerPack = "";
                    if (dr["Price/Pack"] != DBNull.Value && dr["Price/Pack"] != null)
                    {
                      var  pricePerPack = Convert.ToString(dr["Price/Pack"]);

                        if ((deliveryNoteType != DeliveryNoteType.NotSet) &&
                            (pricePerPack != "" && Convert.ToDouble(pricePerPack) != 0))
                        {
                            dr.SetColumnError("Price/Pack", @"A Delivery note receive cannot have price information");

                            valid = false;
                        }
                    }

                }

                // Require batch if the store (account type) is the program/Free store or if the EnforceBatch Setting is set to true.
                bool enforceBatch = BLL.Settings.EnforceBatchTracking;
                //Check if Empty before checking Batch
                if (lkAccounts.EditValue != null)
                {
                    var activity = new Activity();
                    activity.LoadByPrimaryKey(int.Parse(lkAccounts.EditValue.ToString()));

                    if (activity.IsHealthProgram() || enforceBatch)
                    {
                        if ((!itm.IsColumnNull("NeedExpiryBatch") && itm.NeedExpiryBatch) &&
                            (dr["Batch No"] == DBNull.Value || dr["Batch No"].ToString() == ""))
                        {
                            dr.SetColumnError("Batch No", @"Can not be Null");
                            valid = false;
                        }
                    }
                }

                if (dr["UnitID"] == DBNull.Value)
                {
                    dr.SetColumnError("UnitID", @"Can not be Null");
                    valid = false;
                }

                if (dr["Pack Qty"] == DBNull.Value)
                {
                    dr.SetColumnError("Pack Qty", @"Can not be Null");
                    valid = false;
                }

                else
                {
                    if (srm && !chkSRMForOldSystemIssues.Checked &&
                        Convert.ToDecimal(dr["Pack Qty"]) > Convert.ToDecimal(dr["IssuedQty"]))
                    {
                        dr.SetColumnError("Pack Qty", @"Can not exceed issued quantity!");
                        valid = false;
                        XtraMessageBox.Show(
                            "Returned quantity cannot be greater than the issued quantity.  Please review the grid.",
                            "SRM Error");
                    }
                }

                if ((!itm.IsColumnNull("NeedExpiryBatch") && itm.NeedExpiryBatch) && (dr["Expiry Date"] == DBNull.Value))
                {
                    dr.SetColumnError("Expiry Date", @"Can not be Null");
                    //gridRecieveView.SetColumnError(gridRecieveView.Columns[], );
                    valid = false;
                }
                else
                {
                    if (dr["Expiry Date"] != DBNull.Value)
                    {
                        DateTime expiryDate = Convert.ToDateTime(dr["Expiry Date"]);
                        if (DateTime.Today.Subtract(expiryDate).Days > 0)
                        {
                            dr["IsDamaged"] = true;
                        }
                    }
                }

                if (dr["Manufacturer"] == DBNull.Value || dr["Manufacturer"].ToString() == "")
                {
                    dr.SetColumnError("Manufacturer", @"Manufacturer cannot be left null");
                    valid = false;
                }
                gridRecieveView.RefreshData();
            }
            if (!beginningBalance && (deliveryNoteType == DeliveryNoteType.NotSet) && !srm && !BLL.Settings.HandleGRV &&
                !dxValidateRefNo.Validate())
            {
                //XtraMessageBox.Show("Please Fill the Goods Receive Note Number!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                valid = false;
            }
            else
            {
                // TODO: check if the reference number is unique.

            }

            return valid && ValidateStep2() && ValidateStep2DuplicateRows();
        }
        private void LoadSTVDetails()
        {
            int documentID = Convert.ToInt32(grdViewReceivedSTVs.GetFocusedDataRow()["DocumentID"]);
            BLL.Document document = new Document();
            document.LoadByPrimaryKey(documentID);
            DocumentExchange.Documents.XmlMappings.STV stv =
                DocumentExchange.Documents.XmlMappings.STV.Load(document.DocumentContent);

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

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

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

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

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

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

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

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

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

            grdSTVDetails.DataSource = receiveDoc.DefaultView;
        }
        private void OnSaveItemManufacturerClick(object sender, EventArgs e)
        {
            _isSaving = true;

            BLL.Item itm = new Item();

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

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

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

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

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

                itm.LoadByPrimaryKey( _itemID );
                if (itm.StorageTypeID.ToString() == StorageType.BulkStore && !itm.IsColumnNull("IsStackStored") && itm.IsStackStored)
                {
                    BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
                    imf.SaveStackStored( _itemID, im.ManufacturerID, Convert.ToDouble(txtStackedHeight.EditValue));
                }
                SaveItemUnits();
                XtraMessageBox.Show("Your changes have been saved.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            _isSaving = false;
               OnPackageLevelSelected(new object(), new EventArgs());
        }