private void btnAddManufacturer_Click(object sender, EventArgs e)
        {
            Dialogs.AddManufacturerForItem amfi = new HCMIS.Desktop.Dialogs.AddManufacturerForItem(_itemID);
            DialogResult dr = amfi.ShowDialog();
            if (DialogResult.Yes ==dr)
            {
                int manufID = amfi.SelectedManufacturer;
                Manufacturer manufacturer = new Manufacturer();
                manufacturer.LoadByPrimaryKey(manufID);

                BLL.ItemManufacturer imm = new BLL.ItemManufacturer();
                imm.LoadManufacturerItemRelationsFor(_itemID, manufID);
                if (imm.RowCount > 0)
                {

                }
                else
                {
                    imm.AddNew();
                    imm.ItemID = _itemID;
                    imm.ManufacturerID = manufID;
                    imm.BoxHeight = 1;
                    imm.BoxLength = 1;
                    imm.BoxWidth = 1;
                    imm.PackageLevel = 0;
                    imm.RecevingDefault = false;
                    imm.QuantityPerLevel = 1;
                    imm.Save();
                }
                im.LoadManufacturersFor(_itemID);
                this.lstManufacturers.DataSource = im.DefaultView;
            }
        }
        private void LoadSTVDetails()
        {
            int documentID = Convert.ToInt32(grdViewReceivedSTVs.GetFocusedDataRow()["DocumentID"]);
            BLL.Document document = new Document();
            document.LoadByPrimaryKey(documentID);
            DocumentExchange.Documents.XmlMappings.STV stv =
                DocumentExchange.Documents.XmlMappings.STV.Load(document.DocumentContent);

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

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

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

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

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

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

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

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

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

            grdSTVDetails.DataSource = receiveDoc.DefaultView;
        }
        /// <summary>
        /// Computes the stock calculations for an order detail.
        /// </summary>
        /// <param name="currentMonth">The current month.</param>
        /// <param name="currentYear">The current year.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="orderDetail">The order detail.</param>
        /// <returns></returns>
        public DataRow ComputeStockCalculationsForAnOrderDetail(int currentMonth, int currentYear, int userID, OrderDetail orderDetail)
        {
            if (!IsOrderDetailTableReady(orderDetail))
            {
                PrepareOrderDetailTable(orderDetail);
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            //Populate Account
            Account Account = new Account();
            Account.LoadByPrimaryKey(StoreID);
            txtAccount.Text = Account.Name;
            if(BLL.Settings.IsCenter)
            layoutSellingPrice.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
        }
        /// <summary>
        /// Gets the pick list details for order.
        /// </summary>
        /// <param name="ordID">The ord ID.</param>
        /// <param name="Preparedby">The preparedby.</param>
        /// <returns></returns>
        public DataView GetPickListDetailsForOrder(int ordID, string Preparedby)
        {
            this.LoadByOrderID(ordID);
            var query = HCMIS.Repository.Queries.PickList.SelectGetPickListDetailsForOrder(this.ID);
            this.LoadFromRawSql(query);
            // Add important columns
            this.DataTable.Columns.Add("SKUTOPICK", typeof(decimal));
            this.DataTable.Columns.Add("SKUPICKED", typeof(decimal));
            this.DataTable.Columns.Add("BUPICKED", typeof(decimal));
            this.DataTable.Columns.Add("BoxSizeDisplay");
            this.DataTable.Columns.Add("SKUBU", typeof(decimal));
            this.DataTable.Columns.Add("IsManufacturerLocal", typeof(bool));
            this.DataTable.Columns.Add("PrintedSTVNumber", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreName", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreTypeID", typeof(int));
            this.DataTable.Columns.Add("PhysicalStoreTypeName", typeof(string));
            this.DataTable.Columns.Add("PreparedBy", typeof(string));
            int i = 1;
            while (!this.EOF)
            {
                decimal packs = Convert.ToDecimal(this.GetColumn("Packs"));

                int manufacturer = Convert.ToInt32(this.GetColumn("ManufacturerID"));
                Manufacturer m = new Manufacturer();
                m.LoadByPrimaryKey(manufacturer);
                if (!m.IsColumnNull("CountryOfOrigin") && m.CountryOfOrigin.Contains("Ethiopia"))
                    this.SetColumn("IsManufacturerLocal", true);
                else
                    this.SetColumn("IsManufacturerLocal", false);

                int recPalletID = Convert.ToInt32(this.GetColumn("ReceivePalletID"));
                ReceivePallet rp = new ReceivePallet();
                rp.LoadByPrimaryKey(recPalletID);
                try
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    Receipt receipt = new Receipt();
                    receiveDoc.LoadByPrimaryKey(rp.ReceiveID);
                    receipt.LoadByPrimaryKey(receiveDoc.ReceiptID);
                    this.SetColumn("PhysicalStoreName", rp.GetPhysicalStoreName());
                    int physicalStoreTypeID = rp.GetPhysicalStoreTypeID();
                    this.SetColumn("PhysicalStoreTypeID", physicalStoreTypeID);
                    Warehouse phyStoreType = new Warehouse();
                    phyStoreType.LoadByPrimaryKey(physicalStoreTypeID);
                    this.SetColumn("PhysicalStoreTypeName", phyStoreType.Name);
                    if (BLL.Settings.PrintUserNameOnInvoice)
                    {
                        this.SetColumn("PreparedBy", Preparedby);
                    }

                }
                catch
                {

                }

                int itemId = Convert.ToInt32(this.GetColumn("ItemID"));
                int boxLevel = Convert.ToInt32(this.GetColumn("BoxLevel"));
                decimal qtyPerPack = this.Getint("QtyPerPack");
                //im.LoadIMbyLevel(itemId, manufacturer, boxLevel);
                this.SetColumn("SKUTOPICK", (packs));
                this.SetColumn("SKUPICKED", this.GetColumn("SKUTOPICK"));
                // TODO:show the box size here for Program store
                this.SetColumn("BoxSizeDisplay", "");
                this.SetColumn("SKUBU", qtyPerPack);
                this.SetColumn("BUPICKED", qtyPerPack * Convert.ToDecimal(this.GetColumn("SKUPICKED")));
                this.SetColumn("LineNum", i++);
                if (this.IsColumnNull("DeliveryNote"))
                {
                    this.SetColumn("DeliveryNote", false);
                }
                this.MoveNext();
            }
            return this.DefaultView;
        }
        //,bool pricedItems)
        /// <summary>
        /// Gets picked order detail for item (Used by the IssueLog)
        /// </summary>
        /// <param name="ordID"></param>
        /// <param name="storeid"></param>
        /// <param name="pricedItems">True - For Priced Items Only, False - For Delivery Notes Only</param>
        /// <returns></returns>
        public DataView GetPickedOrderDetailForOrder(int stvLogID, bool includeDeleted)
        {
            string query;

            // remove this line ...
            // check if this has changed the dn to stv conversion
            // (pld.DeliveryNote is null or pld.DeliveryNote = 0 or (pld.DeliveryNote=1 and pld.UnitPrice<>0)) and
            query = HCMIS.Repository.Queries.PickList.SelectGetPickedOrderDetailForOrder(stvLogID);
            if (includeDeleted)
            {
                query = HCMIS.Repository.Queries.PickList.SelectGetPickedOrderDetailForOrderIncludeDeleted(stvLogID);
            }

            this.LoadFromRawSql(query);
            // Add important columns
            this.DataTable.Columns.Add("SKUTOPICK", typeof(int));
            this.DataTable.Columns.Add("SKUPICKED", typeof(int));
            this.DataTable.Columns.Add("BUPICKED", typeof(int));
            this.DataTable.Columns.Add("BoxSizeDisplay");
            this.DataTable.Columns.Add("SKUBU", typeof(int));
            this.DataTable.Columns.Add("IsManufacturerLocal", typeof(bool));
            this.DataTable.Columns.Add("PrintedSTVNumber", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreName", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreTypeID", typeof(int));
            this.DataTable.Columns.Add("PhysicalStoreTypeName", typeof(string));

            ItemManufacturer im = new ItemManufacturer();
            int i = 1;
            while (!this.EOF)
            {
                int packs = Convert.ToInt32(this.GetColumn("Packs"));
                int manufacturer = Convert.ToInt32(this.GetColumn("ManufacturerID"));
                Manufacturer m = new Manufacturer();
                m.LoadByPrimaryKey(manufacturer);
                if (!m.IsColumnNull("CountryOfOrigin") && m.CountryOfOrigin == "Ethiopia")
                    this.SetColumn("IsManufacturerLocal", true);
                else
                    this.SetColumn("IsManufacturerLocal", false);

                int recPalletID = Convert.ToInt32(this.GetColumn("ReceivePalletID"));
                ReceivePallet rp = new ReceivePallet();
                rp.LoadByPrimaryKey(recPalletID);
                try
                {
                    this.SetColumn("PhysicalStoreName", rp.GetPhysicalStoreName());
                    int physicalStoreTypeID = rp.GetPhysicalStoreTypeID();
                    this.SetColumn("PhysicalStoreTypeID", physicalStoreTypeID);
                    Warehouse phyStoreType = new Warehouse();
                    phyStoreType.LoadByPrimaryKey(physicalStoreTypeID);
                    this.SetColumn("PhysicalStoreTypeName", phyStoreType.Name);
                }
                catch
                {
                }

                int itemId = Convert.ToInt32(this.GetColumn("ItemID"));
                int boxLevel = Convert.ToInt32(this.GetColumn("BoxLevel"));
                int qtyPerPack = this.Getint("QtyPerPack");
                //im.LoadIMbyLevel(itemId, manufacturer, boxLevel);
                this.SetColumn("SKUTOPICK", (packs));
                this.SetColumn("SKUPICKED", this.GetColumn("SKUTOPICK"));
                // TODO:show the box size here for Program store
                this.SetColumn("BoxSizeDisplay", "");
                this.SetColumn("SKUBU", qtyPerPack);
                this.SetColumn("BUPICKED", qtyPerPack * Convert.ToInt32(this.GetColumn("SKUPICKED")));
                this.SetColumn("LineNum", i++);
                this.MoveNext();

            }
            return this.DefaultView;
        }
        private void PopulateListToGrid()
        {
            Item itm = new Item();

            if (_dtRecGrid.Columns.Count == 0)
            {
                string[] str =
                {
                    "ID", "Stock Code", "Item Name", "BoxLevel", "Unit", "Price/Pack", "Manufacturer",
                    "Batch No", "Expiry Date", "BasicUnitPerQ", "LevelView2"
                };
                foreach (string col in str)
                {
                    if (col.Contains("Date"))
                        _dtRecGrid.Columns.Add(col, typeof(DateTime));
                    else
                        _dtRecGrid.Columns.Add(col);
                }

                _dtRecGrid.Columns.Add("BU Qty", typeof (decimal));
                _dtRecGrid.Columns.Add("Pack Qty", typeof (decimal));
                _dtRecGrid.Columns.Add("NotReceived", typeof(decimal));
                _dtRecGrid.Columns.Add("IsDamaged", typeof (bool));
                _dtRecGrid.Columns.Add("Ordering", typeof (int));

                _dtRecGrid.Columns.Add("PalletComposition");
                _dtRecGrid.Columns.Add("PC", typeof(DataTable));
                _dtRecGrid.Columns.Add("UnitID", typeof(int));
                _dtRecGrid.Columns.Add("IssuedQty");
                _dtRecGrid.Columns.Add("IssueDocID"); //For srm only
                _dtRecGrid.Columns.Add("InvoicedQty", typeof(decimal));
                _dtRecGrid.Columns.Add("OriginalInvoicedQty", typeof(decimal));
                _dtRecGrid.Columns.Add("RemainingQty"); //For hasPreviousReceive is True
                _dtRecGrid.Columns.Add("StockCode");
                _dtRecGrid.Columns.Add("GUID");
                _dtRecGrid.Columns.Add("Margin");
                _dtRecGrid.Columns.Add("ShortageReasonID", typeof(int));

                _dtRecGrid.Columns.Add("Copy", typeof (string));
                _dtRecGrid.Columns.Add("CopyGUID");
                _dtRecGrid.Columns.Add("IsCopied",typeof(bool));
                    //this column will be used during splitting an Item on a Draft receive.
                _dtRecGrid.Columns.Add("Store", typeof (string));
            }

            int count = 1;
            // Bind the manufacturer editor
            BLL.Manufacturer mfs = new Manufacturer();
            BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
            mfs.LoadAll();
            editManufacturer.DataSource = mfs.DefaultView;

            editManuf2.DataSource = mfs.DefaultView;
            editManuf3.DataSource = mfs.DefaultView;
            EditRecivingBoxLevels.DataSource = BLL.ItemManufacturer.PackageLevelKeys;
            DataTable dtbl = (DataTable)gridSelected.DataSource;

            //bool srm = false;
            srm = Convert.ToInt32(cboReceiveType.EditValue) == ReceiptType.CONSTANTS.STOCK_RETURN;

            foreach (DataRow lst in dtbl.Rows)
            {

                if (lst["IsSelected"] == DBNull.Value || Convert.ToBoolean(lst["IsSelected"]))
                {
                    string itemName = lst["FullItemName"].ToString();

                    bool validateSRM = srm && !chkSRMForOldSystemIssues.Checked;

                    DataRow dr = _dtRecGrid.NewRow();
                    dr["ID"] = lst["ID"];
                    dr["StockCode"] = dr["Stock Code"] =lst["StockCode"];
                    dr["Item Name"] = itemName;

                    if (validateSRM || hasPreviousReceive || (standardRecType == StandardReceiptType.iGRVOnline) ||
                        (deliveryNoteType == DeliveryNoteType.Automatic))
                    {
                        dr["Unit"] = lst["Unit"];
                        dr["Manufacturer"] = lst["ManufacturerID"];
                        dr["Batch No"] = lst["BatchNo"];
                        dr["UnitID"] = lst["UnitID"];
                        dr["Expiry Date"] = lst["ExpDate"];
                        if (validateSRM)
                        {
                            dr["IssuedQty"] = lst["IssuedQty"];
                            dr["IssueDocID"] = lst["IssueDocID"];
                        }
                        if (hasPreviousReceive)
                        {
                            dr["OriginalInvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["InvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["RemainingQty"] = lst["RemainingQty"];
                        }
                        if (standardRecType == StandardReceiptType.iGRVOnline)
                        {
                            dr["OriginalInvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["InvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["Price/Pack"] = lst["UnitPrice"];
                            dr["Margin"] = lst["Margin"];
                        }
                        if (deliveryNoteType == DeliveryNoteType.Automatic)
                        {
                            dr["OriginalInvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["InvoicedQty"] = lst["InvoicedNoOfPack"];
                            dr["Price/Pack"] = lst["UnitPrice"];
                            dr["Margin"] = lst["Margin"];
                        }
                    }

                    count++;
                    lst["IsSelected"] = false;

                    dr["Ordering"] = _LastOrdering++;
                    dr["GUID"] = Guid.NewGuid();
                    dr["Copy"] = "Orginal";
                    dr["IsCopied"] = false;
                    dr["CopyGUID"] = Guid.NewGuid();
                    dr["IsDamaged"] = false;
                    _dtRecGrid.Rows.Add(dr);

                }
            }
            _dtRecGrid.DefaultView.Sort = "Ordering";
            receivingGrid.DataSource = _dtRecGrid.DefaultView;

            repoLkEditNotReceivedReason.DataSource = BLL.ShortageReasons.GetAllReasons();
            if (srm)
            {
                lcRemark.Text = "Reason for SRM";
            }
            dtRecDate.CustomFormat = "MMM dd,yyyy";
        }
        private void OnAnyPopupOpenedOnRecieveGrid(object sender, EventArgs e)
        {
            GridView view = sender as GridView;

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

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

            }
        }
        private void gridSelectedItemsView_ShownEditor(object sender, EventArgs e)
        {
            var view = sender as GridView;

            if (view != null && view.FocusedColumn.FieldName == "PreferredManufacturerID")
            {
                var lke = (LookUpEdit)view.ActiveEditor;
                lke.EditValue = null;
                DataRow dr = gridSelectedItemsView.GetDataRow(gridSelectedItemsView.GetSelectedRows()[0]);
                int id = Convert.ToInt32(dr["ItemID"]);
                var mfs = new Manufacturer();
                mfs.LoadForItem(id);
                lke.Properties.DataSource = mfs.DefaultView;
            }
        }
 private void BindCategoryAndManufacturerLookup()
 {
     lkCategories.Properties.DataSource = BLL.CommodityType.GetAllTypes().Select("Name <> 'Medical Supplies DUPLICATE DO NOT USE'").CopyToDataTable();
     var manufacturer = new Manufacturer();
     manufacturer.LoadAll();
     lookUpManufacturer.DataSource = manufacturer.DefaultView;
 }
 /// <summary>
 /// Gets the name of manufacturer
 /// </summary>
 /// <param name="manufacturerId">The manufacturer id.</param>
 /// <returns></returns>
 public static string GetName(int manufacturerId)
 {
     Manufacturer mfs = new Manufacturer();
     mfs.LoadByPrimaryKey(manufacturerId);
     return mfs.Name;
 }
 /// <summary>
 /// Gets all.
 /// </summary>
 /// <returns></returns>
 public static DataTable GetAll()
 {
     Manufacturer manufacturers = new Manufacturer();
     manufacturers.LoadAll();
     return manufacturers.DataTable;
 }
        private int SaveOrder()
        {
            int warehouseID;
            var order = GenerateOrder();
            PickList pickList = PickList.GeneratePickList(order.ID);
            int picklistId = pickList.ID;
            if (TransferTypeID != Transfer.Constants.HUB_TO_HUB)
            {
                warehouseID = GenerateTransfer(order.ID);
            }

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

            int LineNo = 0;

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

            DataView dv = orderGrid.DataSource as DataView;

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

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

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

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

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

                        drvpl["Unit"] = unit.Text;

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

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

            }
            if (LineNo == 0)
                throw new System.ArgumentException("Please review your list,you haven't approved any Quantity");
            string receivingUnit;
                Transfer transfer = new Transfer();
                transfer.LoadByOrderID(order.ID);
                if (TransferTypeID == Transfer.Constants.ACCOUNT_TO_ACCOUNT)
                {
                    var fromActivity = new Activity();
                    fromActivity.LoadByPrimaryKey(transfer.FromStoreID);
                    var toActivity = new Activity();
                    toActivity.LoadByPrimaryKey(transfer.ToStoreID);

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

                    var toStore = new PhysicalStore();

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

                XtraMessageBox.Show("Picklist Prepared!", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return order.ID;
        }
        private void lkItem_EditValueChanged(object sender, EventArgs e)
        {
            if (lkItem.EditValue != null)
            {
                ItemUnit itemUnit = new ItemUnit();
                itemUnit.LoadAllForItem(Convert.ToInt32(lkItem.EditValue));
                lkUnit.Properties.DataSource = itemUnit.DefaultView;

                Manufacturer itemManufacturer = new Manufacturer();
                itemManufacturer.LoadForItem(Convert.ToInt32(lkItem.EditValue));
                lkManufacturer.Properties.DataSource = itemManufacturer.DefaultView;
            }
        }
        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;
        }