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

            Items itm = new Items();

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

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

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

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

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

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

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

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

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

            DUsItemList duItem = new DUsItemList();

            foreach (DataRowView drDus in dus.DefaultView)
            {
                bool check = false;
                check = duItem.CheckIfExsits(_itemId, Convert.ToInt32(drDus["ID"]));
                lstDUs.Items.Add(drDus["Name"], check);
            }
        }
        /// <summary>
        /// Saves the item policy
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            var itm = new Items();
            var itmSup = new ItemSupplier();
            if (_itemId != 0)
                itm.LoadByPrimaryKey(_itemId);
            else
            {
                itm.AddNew();
                var prodCate = new ProductsCategory();
                prodCate.AddNew();
                prodCate.ItemId = itm.ID;
                prodCate.SubCategoryID = Convert.ToInt32(_categoryId);
                prodCate.Save();
            }
            //if (rdA.Checked || rdB.Checked || rdC.Checked)
            //    itm.ABC = ((rdA.Checked) ? 1 : (rdB.Checked) ? 2 : 3);

            //if (rdV.Checked || rdE.Checked || rdN.Checked)
            //    itm.VEN = ((rdV.Checked) ? 1 : (rdE.Checked) ? 2 : 3);

                itm.IsInHospitalList = ckExculed.Checked;
                //itm.NeedExpiryBatch = chkNeedExpiryBatch.Checked;

            string valid = ValidateFields();
            if (valid == "true")
            {
                itm.NeedExpiryBatch = chkNeedExpiryBatch.Checked;
                itm.StockCodeDACA = txtText.Text;
                itm.Cost = txtQuantityPerPack.Text;
                itm.Save();
            }

            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            //TODO: To add categories
            //Needs some modification on edit

            // this will only add the suppliers
            //do some thing on edit

            itmSup.DeleteAllSupForItem(itm.ID);
            Supplier sup = new Supplier();
            foreach (object t in lstSuppliers.CheckedItems)
            {
                sup.GetSupplierByName(t.ToString());
                itmSup.AddNew();
                itmSup.ItemID = itm.ID;
                itmSup.SupplierID = sup.ID;
                itmSup.Save();
            }

            var progItm = new ProgramProduct();
            progItm.DeleteAllProgramsForItem(_itemId);

            var prog = new Programs();
            //prog.AddNew();
            //prog.Name = cboPrograms.Text;
            //prog.Save();

            foreach (object t in lstPrograms.CheckedItems)
            {
                prog.GetProgramByName(t.ToString());
                progItm.AddNew();
                progItm.ItemID = itm.ID;
                progItm.ProgramID = prog.ID;
                progItm.Save();
            }

            var duItem = new DUsItemList();
            var dus = new ReceivingUnits();

            foreach (object t in lstDUs.CheckedItems)
            {
                dus.GetDUByName(t.ToString());
                duItem.AddNew();
                duItem.DUID = dus.ID;
                duItem.ItemID = _itemId;
                try
                {
                    duItem.Save();
                }
                catch
                {

                }
            }

            XtraMessageBox.Show("Item Detail is Saved Successfully!", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }
 /// <summary>
 /// When the cboPrograms changes, the program lists needs to be repopulated
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void cboPrograms_SelectedIndexChanged(object sender, EventArgs e)
 {
     lstPrograms.Items.Clear();
     Programs prog = new Programs();
     ProgramProduct progItem = new ProgramProduct();
     if (cboPrograms.SelectedValue != null)
     {
         prog.GetSubProgramsByParentId(Convert.ToInt32(cboPrograms.SelectedValue));
     }
     else
     {
         prog.GetSubPrograms();
     }
     foreach (DataRowView dv in prog.DefaultView)
     {
         bool check = false;
         check = progItem.CheckIfExists(_itemId, Convert.ToInt32(dv["ID"]));
         lstPrograms.Items.Add(dv["Name"], check);
     }
 }
        /// <summary>
        /// Prepares the Item Policy Form
        /// Loads combo boxes and populates fields
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ItemPolicy_Load(object sender, EventArgs e)
        {
            Shelf slf = new Shelf();
            DataTable dtSlf = slf.GetShelves();

            Programs prog = new Programs();
            prog.GetParentPrograms();
            cboPrograms.DataSource = prog.DefaultView;
            cboPrograms.SelectedIndex = -1;

            if(VisibilitySetting.HandleUnits ==2)
            {
                txtQuantityPerPack.Enabled = false;
                txtText.Enabled = false;
                listBox1.Visible = true;
            }
            else if (VisibilitySetting.HandleUnits == 3)
            {
                txtQuantityPerPack.Enabled = true;
                txtText.Enabled = true;
                listBox1.Visible = true;
            }
            else
            {
                txtQuantityPerPack.Enabled = true;
                txtText.Enabled = true;
                listBox1.Hide();
            }
            PopulateFields();
        }
        /// <summary>
        /// Load the dropdowns and the category tree
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ManageItems_Load(object sender, EventArgs e)
        {
            PopulateCatTree(_selectedType);

            Programs prog = new Programs();
            DataTable dtProg = prog.GetSubPrograms();
            object[] objProg = { 0, "All Programs", "", 0, "" };
            dtProg.Rows.Add(objProg);
            cboSubProgram.DataSource = dtProg;
            cboSubProgram.SelectedIndex = -1;
            cboSubProgram.Text = "Select Program";

            Stores stor = new Stores();
            stor.GetActiveStores();
            cboStores.DataSource = stor.DefaultView;
        }
        private void PopulateSStatusReport()
        {
            if (curMont != 0 && curYear != 0)
            {
                var storeId = Convert.ToInt32(cboStores.EditValue);
                curYear = Convert.ToInt32(cboYear.EditValue);

                Balance blnc = new Balance();
                DataTable dtbl = new DataTable();
                if (storeId == 0)
                {
                    dtbl = blnc.GetSOHForAllStores(curMont, Convert.ToInt32(cboYear.EditValue));
                }
                else
                {
                    dtbl = blnc.GetSOH(storeId, curMont, Convert.ToInt32(cboYear.EditValue));
                }

                Items itm = new Items();
                Balance bal = new Balance();
                ReceiveDoc rec = new ReceiveDoc();

                Programs prog = new Programs();
                prog.GetProgramByName("Family Planning");
                DataTable dtItm = itm.GetItemsByProgram(prog.ID);
                int totalECLS = dtItm.Rows.Count;
                int stockin, stockout, overstock, nearEOP, belowEOP, freeStockOut;

                if (Convert.ToInt32(lkCategory.EditValue) != 0)
                {
                    stockin = (from m in dtbl.AsEnumerable()
                                   where m["Status"].ToString() == "Normal"
                                   && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                   select m).Count();

                    stockout = (from m in dtbl.AsEnumerable()
                                    where m["Status"].ToString() == "Stock Out"
                                    && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                    select m).Count();

                    overstock = (from m in dtbl.AsEnumerable()
                                     where m["Status"].ToString() == "Over Stocked"
                                     && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                     select m).Count();

                    nearEOP = (from m in dtbl.AsEnumerable()
                                   where m["Status"].ToString() == "Near EOP"
                                   && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                   select m).Count();

                    belowEOP = (from m in dtbl.AsEnumerable()
                                    where m["Status"].ToString() == "Below EOP"
                                    && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                    select m).Count();

                    freeStockOut = (from m in dtbl.AsEnumerable()
                                        where m["Status"].ToString() == "Stock Out"
                                        && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                        select m).Count();
                }
                else
                {
                    stockin = (from m in dtbl.AsEnumerable()
                               where m["Status"].ToString() == "Normal"
                               && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                               select m).Count();

                    stockout = (from m in dtbl.AsEnumerable()
                                where m["Status"].ToString() == "Stock Out"
                                && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                select m).Count();

                    overstock = (from m in dtbl.AsEnumerable()
                                 where m["Status"].ToString() == "Over Stocked"
                                 && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                 select m).Count();

                    nearEOP = (from m in dtbl.AsEnumerable()
                               where m["Status"].ToString() == "Near EOP"
                               && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                               select m).Count();

                    belowEOP = (from m in dtbl.AsEnumerable()
                                where m["Status"].ToString() == "Below EOP"
                                && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                select m).Count();

                    freeStockOut = (from m in dtbl.AsEnumerable()
                                    where m["Status"].ToString() == "Stock Out"
                                    && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                    select m).Count();
                }

                object[] obj = { stockin, stockout, overstock, nearEOP, belowEOP };
                int totalItm = stockin + stockout + nearEOP + overstock;

                decimal percen = ((totalItm != 0) ? (Convert.ToDecimal(stockin) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);

                percen = ((totalItm != 0) ? (Convert.ToDecimal(stockout) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                percen = ((totalItm != 0) ? (Convert.ToDecimal(overstock) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                percen = ((totalItm != 0) ? (Convert.ToDecimal(nearEOP) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                percen = ((totalItm != 0) ? (Convert.ToDecimal(belowEOP) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                int totalFree = itm.CountFreeItems();
                percen = ((totalFree != 0) ? (Convert.ToDecimal(freeStockOut) / Convert.ToDecimal(totalFree)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                totalFree = itm.CountVitalItems();
                GenerateStockStatusPieChart(obj);
            }
        }
        /// <summary>
        /// Populates the programs and loads them into the TreeProgram
        /// </summary>
        private void PopulatePrograms()
        {
            BLL.Programs prog = new Programs();
            prog.LoadAll();
            cboProgram.DataSource = prog.DefaultView;

            TreeProgram.DataSource = prog.DefaultView;
        }
        private void ManageItems_Load(object sender, EventArgs e)
        {
            lkCommodityTypes.Properties.DataSource = BLL.Type.GetAllTypes();
            lkCommodityTypes.ItemIndex = 0;

            PopulateCatTree();

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

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

            Programs prog = new Programs();
            DataTable dtProg = new DataTable();
            dtProg = prog.GetSubPrograms();
            object[] objProg = { 0, "All Programs", "", 0, "" };
            dtProg.Rows.Add(objProg);
            cboSubProgram.DataSource = dtProg;
            cboSubProgram.SelectedIndex = -1;
            cboSubProgram.Text = "Select Program";

            ReceivingUnits rec = new ReceivingUnits();
            DataTable drRec = rec.GetAllApplicableDU();
            cboIssuedTo.DataSource = drRec;
            cboIssuedTo.SelectedIndex = -1;
            cboIssuedTo.Text = "Select Issue Location";

            int month = dtCurrent.Month;
            int year = ((dtCurrent.Month < 11) ? dtCurrent.Year : dtCurrent.Year + 1);

            DataTable dtyears = Items.AllYears();

            foreach (DataRow drYears in dtyears.Rows)
            {
                int yr = Convert.ToInt32(drYears["year"]);
                cboYear.Items.Add(yr);
            }
            bool added = true;
            for (int x = 0; x < cboYear.Items.Count; x++)//to check if the current year is included or not
            {
                if (Convert.ToInt64(cboYear.Items[x]) == year)
                {
                    added = false;
                    break;
                }
            }
            if (added)
            {
                cboYear.Items.Add(year);
            }
            cboYear.SelectedItem = year;
        }
        /// <summary>
        /// Handles the TreeProgram focused node changed and updates the form accordingly
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeProgram_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            int selected = Convert.ToInt32(TreeProgram.Selection[0]["ID"]);
            Programs prog = new Programs();
            prog.LoadByPrimaryKey(selected);

            if (prog.ParentID != 0)
            {
                cboProgram.SelectedValue = prog.ParentID.ToString();
                //lblProgram.Text = "Sub Program";
                cboProgram.Visible = true;
                //lbPro.Visible = true;
            }
            else
            {
                cboProgram.SelectedValue = prog.ID.ToString();
                cboProgram.Visible = false;
                //lbPro.Visible = false;
                //lblProgram.Text = "Program";
            }
            txtProgram.Text = prog.Name;
            txtProgramDescription.Text = prog.Description;
            _programId = prog.ID;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnProgramSave_Click(object sender, EventArgs e)
 {
     if (txtProgram.Text != "")
     {
         Programs prog = new Programs();
         if (_programId != 0)
             prog.LoadByPrimaryKey(_programId);
         else
             prog.AddNew();
         prog.Name = txtProgram.Text;
         prog.Description = txtProgramDescription.Text;
         prog.ParentID = cboProgram.Visible ? Convert.ToInt32(cboProgram.SelectedValue) : 0;
         prog.Save();
         PopulatePrograms();
         ResetProgram();
     }
     else
     {
         txtProgram.BackColor = Color.FromArgb(251, 214, 214);
     }
 }
        private void cboStores_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cboStores.SelectedValue != null)
            {
                dtDate.Value = DateTime.Now;
                dtDate.CustomFormat = "MM/dd/yyyy";
                DateTime dtCur = new DateTime();// Convert.ToDateTime(dtDate.Text);
                try
                {
                    dtCur = Convert.ToDateTime(dtDate.Text);
                }
                catch
                {
                    string dtValid = "";
                    string yer = "";
                    if (Convert.ToInt32(dtDate.Text.Substring(0, 2)) == 13)
                    {
                        dtValid = dtDate.Text;
                        yer = dtValid.Substring(dtValid.Length - 4, 4);
                        dtCur = Convert.ToDateTime("12/30/" + yer);
                    }
                    else if (Convert.ToInt32(dtDate.Text.Substring(0, 2)) == 2)
                    {
                        dtValid = dtDate.Text;
                        yer = dtValid.Substring(dtValid.Length - 4, 4);
                        dtCur = Convert.ToDateTime("2/28/" + yer);
                    }
                }
                int month = Convert.ToInt32(cboMonth.SelectedValue);
                int year = (month < 11) ? dtCur.Year : dtCur.Year - 1;

                Programs prog = new Programs();
                prog.GetProgramByName("Family Planning");
                Items itm = new Items();
                DataTable dtItm = itm.GetItemsByProgram(prog.ID);
                PopulateItemListByMonth(dtItm, month,year);
               // PopulateItemListBlance(dtItm);
            }
        }
        private void PopulateSStatusByCategoryAndYearForAllStore()
        {
            if (curMont != 0 && curYear != 0)
            {
                curYear = Convert.ToInt32(cboYear.EditValue);

                Balance blnc = new Balance();
                DataTable dtbl = blnc.GetSOHForAllStores(curMont, curYear);

                Items itm = new Items();
                Balance bal = new Balance();
                ReceiveDoc rec = new ReceiveDoc();

                Programs prog = new Programs();
                prog.GetProgramByName("Family Planning");
                DataTable dtItm = itm.GetItemsByProgram(prog.ID);
                int totalECLS = dtItm.Rows.Count;
                lblNoECLS.Text = totalECLS.ToString();
                int neverRec = rec.CountNeverReceivedItemsByCateogryAndYear(storeId, Convert.ToInt32(lkCategory.EditValue), Convert.ToInt32(cboYear.EditValue));
                int stockin = (from m in dtbl.AsEnumerable()
                               where m["Status"].ToString() == "Normal" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                               && ((ckExclude.Checked)? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                               select m).Count();
                if (stockin == 0)
                {
                    listInStock.Visible = false;
                }
                else
                {
                    listInStock.Visible = true;
                }

                //progressBar1.PerformStep();
                int stockout = (from m in dtbl.AsEnumerable()
                                where m["Status"].ToString() == "Stock Out" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                                && ((ckExclude.Checked) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                                select m).Count();
                if (stockout == 0)
                {
                    listStockOut.Visible = false;
                }
                else
                {
                    listStockOut.Visible = true;
                }
                //((ckExclude.Checked)? (bal.CountStockOut(storeId, curMont, curYear)- neverRec) : bal.CountStockOut(storeId, curMont, curYear));
                //progressBar1.PerformStep();
                int overstock = (from m in dtbl.AsEnumerable()
                                 where m["Status"].ToString() == "Over Stocked" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                                 && ((ckExclude.Checked) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                                 select m).Count();
                if (overstock == 0)
                {
                    listOverstock.Visible = false;
                }
                else
                {
                    listOverstock.Visible = true;
                }
                // progressBar1.PerformStep();
                int nearEOP = (from m in dtbl.AsEnumerable()
                               where m["Status"].ToString() == "Near EOP" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                               && ((ckExclude.Checked) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                               select m).Count();
                if (nearEOP == 0)
                {
                    listNearEOP.Visible = false;
                }
                else
                {
                    listNearEOP.Visible = true;
                }
                //progressBar1.PerformStep();
                int belowEOP = (from m in dtbl.AsEnumerable()
                                where m["Status"].ToString() == "Below EOP" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                                && ((ckExclude.Checked) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                                select m).Count();
                if (belowEOP == 0)
                {
                    listBelowEOP.Visible = false;
                }
                else
                {
                    listNearEOP.Visible = true;
                }
                // progressBar1.PerformStep();
                int belowMin = 0;//bal.CountBelowMin(storeId, curMont, curYear);
                // progressBar1.PerformStep();
                int freeStockOut = (from m in dtbl.AsEnumerable()
                                    where m["Status"].ToString() == "Stock Out" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                                    && ((ckExclude.Checked) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                                    select m).Count();
                if (freeStockOut == 0)
                {
                    lblFreeStockedout.Visible = false;
                }
                else
                {
                    lblFreeStockedout.Visible = true;
                }
                // progressBar1.PerformStep();
                int vitalStockOut = bal.CountVitalItemsStockOutForAllStore(curMont, curYear);
                //int eclsStockout = bal.CountECLSItemsStockOut(storeId, curMont, curYear);
                // progressBar1.PerformStep();
                object[] obj = { stockin, stockout, overstock, nearEOP, belowEOP };
                int totalItm = stockin + stockout + nearEOP + overstock;

                decimal percen = ((totalItm != 0) ? (Convert.ToDecimal(stockin) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblInStock.Text = stockin.ToString() + " (" + percen.ToString("#.0") + "%)";

                percen = ((totalItm != 0) ? (Convert.ToDecimal(stockout) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblStockOut.Text = stockout.ToString() + " (" + percen.ToString("#.0") + "%)";

                percen = ((totalItm != 0) ? (Convert.ToDecimal(overstock) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblOverStocked.Text = overstock.ToString() + " (" + percen.ToString("#.0") + "%)";

                percen = ((totalItm != 0) ? (Convert.ToDecimal(nearEOP) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblNearEOP.Text = nearEOP.ToString() + " (" + percen.ToString("#.0") + "%)";

                percen = ((totalItm != 0) ? (Convert.ToDecimal(belowEOP) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblBelowEOP.Text = belowEOP.ToString() + " (" + percen.ToString("#.0") + "%)";

                percen = ((totalItm != 0) ? (Convert.ToDecimal(belowMin) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblBelowMin.Text = belowMin.ToString() + " (" + percen.ToString("#.0") + "%)";

                lblFreeStockedout.Text = freeStockOut.ToString();
                if (freeStockOut == 0)
                {
                    linkLabel6.Visible = false;
                }
                else
                {
                    linkLabel6.Visible = true;
                }
                int totalFree = itm.CountFreeItems();
                percen = ((totalFree != 0) ? (Convert.ToDecimal(freeStockOut) / Convert.ToDecimal(totalFree)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblFreeStock.Text = freeStockOut.ToString() + " (" + percen.ToString("#.0") + "%)";

                lblVitalStockedout.Text = vitalStockOut.ToString();
                if (vitalStockOut == 0)
                {
                    linkLabel7.Visible = false;
                }
                else
                {
                    linkLabel7.Visible = true;
                }
                totalFree = itm.CountVitalItems();
                percen = ((totalFree != 0) ? (Convert.ToDecimal(vitalStockOut) / Convert.ToDecimal(totalFree)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblVitalStock.Text = vitalStockOut.ToString() + " (" + percen.ToString("#.0") + "%)";

                //totalFree = itm.CountVitalItems();
                //percen = ((totalECLS != 0)?(Convert.ToDecimal(eclsStockout) / Convert.ToDecimal(totalECLS)) * 100:0);
                //percen = Decimal.Round(percen, 0);
                //lblEclsStock.Text = eclsStockout.ToString() + " (" + percen.ToString("#.0") + "%)";

                GenerateStockStatusPieChart(obj);
            }
        }
 private void linkLabel20_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     Items itm = new Items();
     Programs prog = new Programs();
     prog.GetProgramByName("Family Planning");
     DataTable dtItm = itm.GetItemsByProgram(prog.ID);
     //groupList.Text = "ECLS Items ";
     PopulateList(dtItm, lstDetail);
 }
        /// <summary>
        /// Populate the lookups and item lists.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReceiveingForm_Load(object sender, EventArgs e)
        {
            //gridRecieveView.Columns[4].Visible = VisibilitySetting.HandleUnits;
            var UnitColumn = ((GridView)receivingGrid.MainView).Columns[12];
            var UnitColumn1 = ((GridView)receivingGrid.MainView).Columns[5];
            var UnitColumn2 = ((GridView)gridItemsChoice.MainView).Columns[4];
            var qtyperpack = ((GridView)receivingGrid.MainView).Columns[3];
            var buqty = ((GridView)receivingGrid.MainView).Columns[4];
            switch (VisibilitySetting.HandleUnits)
            {
                case 3:
                    UnitColumn.Visible = true;
                    UnitColumn1.Visible = false;
                    UnitColumn2.Visible = false;
                    qtyperpack.Visible = false;
                    buqty.Visible = false;
                    break;
                case 2:
                    UnitColumn.Visible = true;
                    UnitColumn1.Visible = false;
                    UnitColumn2.Visible = false;
                    qtyperpack.Visible = false;
                    buqty.Visible = false;
                    break;
                case 1:
                    UnitColumn.Visible = false;
                    UnitColumn1.Visible = true;
                    qtyperpack.Visible = true;
                    UnitColumn2.Visible = true;
                    buqty.Visible = true;
                    break;
            }

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

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

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

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

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

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

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

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

            // bind the current date as the datetime field
            dtRecDate.Value = DateTime.Now;
        }
 public int CountECLSItemsStockOut(int storeId, int month, int year)
 {
     Items itm = new Items();
     Programs prog = new Programs();
     prog.GetProgramByName("Family Planning");
     DataTable dtItem = itm.GetItemsByProgram(prog.ID);
     GeneralInfo pipline = new GeneralInfo();
     pipline.LoadAll();
     int min = pipline.Min;
     int max = pipline.Max;
     double eop = pipline.EOP;
     int count = 0;
     Balance bal = new Balance();
     foreach (DataRow dr in dtItem.Rows)
     {
         Int64 AMC = bal.CalculateAMC(Convert.ToInt32(dr["ID"]), storeId, month, year);
         Int64 MinCon = AMC * min;
         Int64 maxCon = AMC * max;
         double eopCon = AMC * (eop + 0.25);
         Int64 SOH = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, month, year);
         decimal MOS = (AMC != 0) ? (SOH / AMC) : 0;
         Int64 reorder = (maxCon > SOH) ? maxCon - SOH : 0;
         if (SOH == 0)
             count++;
         //string status = (SOH <= eopCon && SOH > 0) ? "Near EOP" : ((SOH > maxCon) ? "Excess Stock" : ((SOH <= 0) ? "Stock Out" : "Normal"));
     }
     return count;
 }
        private void ManageItems_Load(object sender, EventArgs e)
        {
            PopulateCatTree(SelectedType);

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

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

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

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

            cboStatus.Properties.DataSource = arr;

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

            var dtyears = Items.AllYears();

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

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

            var unitcolumn = ((GridView)gridItemsChoice.MainView).Columns[15];
            switch (VisibilitySetting.HandleUnits)
            {
                case 1:
                    unitcolumn.Visible = false;
                    break;
                case 2:
                    unitcolumn.Visible = true;
                    break;
                default:
                    unitcolumn.Visible = true;
                    break;
            }
            PopulateGrid();
        }
        public DataTable GetECLSItemsStockOut(int storeId, int month, int year)
        {
            Items itm = new Items();
            Programs prog = new Programs();
            prog.GetProgramByName("Family Planning");
            DataTable dtItem = itm.GetItemsByProgram(prog.ID);
            GeneralInfo pipline = new GeneralInfo();
            pipline.LoadAll();
            int min = pipline.Min;
            int max = pipline.Max;
            double eop = pipline.EOP;

            DataTable dt = new DataTable();
            string[] cols = { "ID", "FullItemName", "DosageForm", "Strength", "Unit", "StockCode" };
            foreach (string st in cols)
            {
                dt.Columns.Add(st);
            }
            Balance bal = new Balance();
            foreach (DataRow dr in dtItem.Rows)
            {
                Int64 AMC = bal.CalculateAMC(Convert.ToInt32(dr["ID"]), storeId, month, year);
                Int64 MinCon = AMC * min;
                Int64 maxCon = AMC * max;
                double eopCon = AMC * (eop + 0.25);
                Int64 SOH = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, month, year);
                decimal MOS = (AMC != 0) ? (SOH / AMC) : 0;
                Int64 reorder = (maxCon > SOH) ? maxCon - SOH : 0;

                if (SOH == 0)
                {
                    object[] obb = { dr["ID"], dr["ItemName"], dr["DosageForm"], dr["Strength"], dr["Unit"], dr["StockCode"] };
                    dt.Rows.Add(obb);
                }
                //string status = (SOH <= eopCon && SOH > 0) ? "Near EOP" : ((SOH > maxCon) ? "Excess Stock" : ((SOH <= 0) ? "Stock Out" : "Normal"));
            }
            return dt;
        }
        private void RRFForm_Load(object sender, EventArgs e)
        {
            btnAutoPushToPFSA.Enabled = false;
            btnSendEmergencyOrder.Enabled = false;
            var unitcolumn = ((GridView) gridItemsChoice.MainView).Columns[2];
            var unitcolumn1 = ((GridView) gridItemsChoice.MainView).Columns[13];
            layoutControlItem18.Visibility =LayoutVisibility.Never;
            switch (VisibilitySetting.HandleUnits)
            {
                case 3:
                    unitcolumn.Visible = false;
                    unitcolumn1.Visible = true;
                    break;
                case 2:
                    unitcolumn.Visible = false;
                    unitcolumn1.Visible = true;
                    break;
                default:
                    unitcolumn.Visible = true;
                    unitcolumn1.Visible = false;
                    break;
            }

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

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

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

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

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

            WindowVisibility(false);
            EnableDisableStatusCheck();

            var prog = new Programs();
            prog.GetSubPrograms();
            cboProgram.Properties.DataSource = prog.DefaultView;
            cboProgram.EditValue = 1000;
        }
        /// <summary>
        /// Load the lookups and Prepare the form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditReceive_Load(object sender, EventArgs e)
        {
            lkItemUnit.Enabled = VisibilitySetting.HandleUnits != 1;
            var str = new Stores();
            str.LoadAll();
            cboStores.DataSource = str.DefaultView;

            var sup = new Supplier();
            sup.GetActiveSuppliers();
            cboSupplier.DataSource = sup.DefaultView;

            if(_tranId != 0)
            {
                var rec = new ReceiveDoc();
                var itm = new Items();

                rec.LoadByPrimaryKey(_tranId);

                var dtItm = itm.GetItemById(rec.ItemID);

                var units = new ItemUnit();
                var unit = units.LoadFromSQl(rec.ItemID);
                lkItemUnit.Properties.DataSource = unit;
                lkItemUnit.Properties.DisplayMember = "Text";
                lkItemUnit.Properties.ValueMember = "ID";

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

                string itemName = dtItm.Rows[0]["ItemName"].ToString() + " - " + dtItm.Rows[0]["DosageForm"].ToString() + " - " + dtItm.Rows[0]["Strength"].ToString();

                txtRefNo.Text = rec.RefNo;
                txtBatchNo.Text = rec.BatchNo;
                try
                {
                    txtPack.Text = rec.NoOfPack.ToString();
                    txtQtyPack.Text =rec.QtyPerPack.ToString();
                    txtPrice.Text = (rec.Cost * rec.QtyPerPack).ToString();
                    //txtQuantityLeft.Text = rec.QuantityLeft.ToString();
                }
                catch
                {
                    txtPack.Text = "0";
                    txtQtyPack.Text = "0";
                    txtPrice.Text = (rec.Cost * 1).ToString();
                }
                txtQuantity.Text = rec.Quantity.ToString();
                lkPrograms.EditValue = rec.SubProgramID;
                DateTime dtDate = Convert.ToDateTime(rec.Date.ToString("MM/dd/yyyy"));
                txtDate.Text = dtDate.ToShortDateString();
                dtRecDate.Value = DateTime.Now;
                dtRecDate.CustomFormat = "MM/dd/yyyy";
                if (!rec.IsColumnNull("ExpDate"))
                    dtExpiryDate.Value = rec.ExpDate;
                cboStores.SelectedValue = rec.StoreID;
                cboSupplier.SelectedValue = rec.SupplierID;

                if (!rec.IsColumnNull("UnitID"))
                    lkItemUnit.EditValue = rec.UnitID;
                txtItemName.Text = itemName;
                txtReceivedBy.Text = rec.ReceivedBy;
                txtRemark.Text = rec.Remark;

            }
        }