public static DataTable GetAllFreeFor(int itemID)
 {
     string query = String.Format("select (st.Prefix + ' ' + pl.Label) as PalletLocationName  , * from PalletLocation pl join StorageType st on pl.StorageTypeID = st.ID join ItemPrefferedLocation ipl on ipl.PalletLocationID = pl.ID where ipl.ItemID = {0} and pl.PalletID is null", itemID);
     PalletLocation pl = new PalletLocation();
     pl.LoadFromRawSql(query);
     if (pl.RowCount == 0)
     {
         Items itm = new Items();
         itm.LoadByPrimaryKey(itemID);
         return PalletLocation.GetAllFree(itm.StorageTypeID.ToString());
     }
     return pl.DataTable;
 }
Exemplo n.º 2
0
 public static DataTable GetAllFreeFor(int itemID)
 {
     string query = String.Format("select (st.Prefix + ' ' + pl.Label) as PalletLocationName  , * from PalletLocation pl join StorageType st on pl.StorageTypeID = st.ID join ItemPrefferedLocation ipl on ipl.PalletLocationID = pl.ID where ipl.ItemID = {0} and pl.PalletID is null", itemID);
     PalletLocation pl = new PalletLocation();
     pl.LoadFromRawSql(query);
     if (pl.RowCount == 0)
     {
         Items itm = new Items();
         itm.LoadByPrimaryKey(itemID);
         return PalletLocation.GetAllFree(itm.StorageTypeID.ToString());
     }
     return pl.DataTable;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rrfID"></param>
        private void SendRRF(int rrfID)
        {
            // Do the webservice magic here.
            GeneralInfo ginfo = new GeneralInfo();
            ginfo.LoadAll();

            chkCalculateInPacks.Checked = false;
            ChooseGridView();

            if (ginfo.IsColumnNull("FacilityID"))
            {
                XtraMessageBox.Show("The Facility ID Was not set, Please correct that and try again.");
                return;
            }

            int facilityID = ginfo.FacilityID;
            int startMonth = Convert.ToInt32(cboFromMonth.EditValue);
            int endMonth = Convert.ToInt32(cboToMonth.EditValue); //startMonth + 1;
            int fromYear = Convert.ToInt32(cboFromYear.EditValue);
            int toYear = Convert.ToInt32(cboToYear.EditValue);

            bool check;
            RRFService.ServiceSoapClient sc = new RRFService.ServiceSoapClient();
            try
            {
                check = sc.RRFExists(facilityID, toYear, startMonth, endMonth);
            }
            catch
            {
                XtraMessageBox.Show("There was a network Error, Please connect to the internet and try again.",
                                    "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (check)
            {
                check =
                    (XtraMessageBox.Show(
                        "Another Report has been submitted for the period you specified, Are you sure you would like to overwrite it?",
                        "Confirm Overwritting", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
                     System.Windows.Forms.DialogResult.Yes);
            }

            if (!check)
            {
                RRFService.RrfSubmission rsubmission = new RrfSubmission
                                                           {
                                                               StartMonth = startMonth,
                                                               EndMonth = endMonth,
                                                               Year = toYear,
                                                               FacilityId = facilityID,
                                                               FacilityName = ginfo.HospitalName,
                                                               Items = new List<RRFItem>()
                                                           };

                DataTable dtbl = ((DataView) gridItemChoiceView.DataSource).Table;

                foreach (DataRow dr in dtbl.Rows)
                {
                    BLL.Items item = new Items();
                    item.LoadByPrimaryKey(Convert.ToInt32(dr["ID"]));

                    if (!item.MappingID.HasValue)
                    {
                        continue;
                    }

                    RRFService.RRFItem itm = new RRFService.RRFItem()
                                                 {
                                                     ItemID = item.MappingID.Value //  Convert.ToInt32(dr["ID"])
                                                     ,
                                                     BBalance = Convert.ToInt32(dr["BeginingBalance"])
                                                     ,
                                                     EBalance = Convert.ToInt32(dr["SOH"])
                                                     ,
                                                     Consumption = Convert.ToInt32(dr["Issued"])
                                                     ,
                                                     LossAdjustment = Convert.ToInt32(dr["LossAdj"])
                                                     ,
                                                     Max = Convert.ToInt32(dr["Max"])
                                                     ,
                                                     Received = Convert.ToInt32(dr["Received"])
                                                     ,
                                                     Requested = Convert.ToInt32(dr["Quantity"])
                                                 };

                    rsubmission.Items.Add(itm);
                }

                sc = new RRFService.ServiceSoapClient();
                try
                {
                    rsubmission.ReportedBy = "";
                    if (sc.SubmitRRF(rsubmission))
                    {
                        XtraMessageBox.Show("The Request has been submitted to PFSA.", "Confirmation",
                                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RRF rrf = new RRF();
                        rrf.LoadByPrimaryKey(rrfID);
                        rrf.DateOfSubmission = DateTime.Now;
                        rrf.LastRRFStatus = CheckRRFStatus(rrf.ID);
                        rrf.Save();
                    }
                }
                catch (Exception ex)
                {

                }
            }
        }
 /// <summary>
 /// Handles Delete of an item
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void toolBtnDelete_Click(object sender, EventArgs e)
 {
     DataRow drv = gridView1.GetFocusedDataRow();
     if (drv != null)
     {
         Items itm = new Items();
         ProductsCategory proCat = new ProductsCategory();
         int itemId = Convert.ToInt32(drv["ID"]);
         if (!itm.HasTransactions(itemId))
         {
             if (XtraMessageBox.Show("Are You Sure, You want to delete this Transaction? You will not be able to restore this data.", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
             {
                 proCat.GetCategoryByItem(itemId);
                 foreach (DataRowView drcat in proCat.DefaultView)
                 {
                     ProductsCategory cat = new ProductsCategory();
                     cat.LoadByPrimaryKey(Convert.ToInt32(drcat["ID"]));
                     cat.MarkAsDeleted();
                     cat.Save();
                 }
                 itm.LoadByPrimaryKey(itemId);
                 itm.MarkAsDeleted();
                 itm.Save();
                 XtraMessageBox.Show("Item Deleted!","Confirmation",MessageBoxButtons.OK,MessageBoxIcon.Information);
             }
         }
         else
         {
             XtraMessageBox.Show("Unable to Delete, This Item has been Received or Issued.", "Unable to Delete", MessageBoxButtons.OK, MessageBoxIcon.Stop);
         }
     }
 }
        private void repositoryItemButtonEdit1_Click(object sender, EventArgs e)
        {
            DataRow dr = grdViewYearEnd.GetDataRow(grdViewYearEnd.GetSelectedRows()[0]);
            if (dr != null)
            {
                string batchNo = dr["Batch No."].ToString();
                int recID = int.Parse(dr["RecID"].ToString());
                BLL.ReceiveDoc rec = new ReceiveDoc();

                if (recID == -1)
                {
                    XtraMessageBox.Show("Use this button only on invalid batches", "Nothing to Remove",
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                rec.LoadByPrimaryKey(recID);
                int itemID = rec.ItemID;

                //Do another validation here (Make sure that the items that they try to remove have issues like the Total SOH not being equal to the sum of the listed batches and so forth.
                int storeId = (cboStores.EditValue != null) ? Convert.ToInt32(cboStores.EditValue) : 1;
                int month = EthiopianDate.EthiopianDate.Now.Month;
                int year = EthiopianDate.EthiopianDate.Now.Year;

                BLL.Balance bal = new Balance();
                BLL.Items itm = new Items();
                itm.LoadByPrimaryKey(itemID);

                long currentBalance = bal.GetSOH(itemID, storeId, month, year);
                long totalQuantityLeftInBatches = itm.TotalQuantityLeftInAllBatches(storeId);

                if (currentBalance == totalQuantityLeftInBatches)
                {
                    XtraMessageBox.Show(
                        "You do not have to use this button to remove this batch.  Please set the physical inventory 0 instead.  Use this button only for items with discrepancies.",
                        "Unapplicable", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (XtraMessageBox.Show("This will make the quantity left for this received batch zero and remove it from this list.  Are you sure you want to continue?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (BLL.ReceiveDoc.MarkReceivedBatchAsEmpty(recID))
                    {
                        dr.Delete();

                    }
                }
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            var rec = new ReceiveDoc();

            var itm = new Items();
            var itemprogram = new ProgramProduct();
            string valid = ValidateFields();
            if (valid == "true")
            {
                if (
                    XtraMessageBox.Show("Are you sure you want to save this transaction?", "Confirmation",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        for (int i = 0; i < dtRecGrid.Rows.Count; i++)
                        {
                            if (dtRecGrid.Rows[i]["Expiry Date"] != DBNull.Value)
                            {
                                if (Convert.ToDateTime(dtRecGrid.Rows[i]["Expiry Date"]) <= DateTime.Now)
                                {
                                    var dialog =
                                        XtraMessageBox.Show(
                                            "The item " + dtRecGrid.Rows[i]["Item Name"].ToString() +
                                            " has already expired.  Are you sure you want to receive it?", "Warning",
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                                    if (dialog == DialogResult.No)
                                    {
                                        return;
                                    }

                                }
                            }
                            rec.AddNew();
                            rec.StoreID = Convert.ToInt32(cboStores.EditValue);
                            rec.RefNo = txtRefNo.Text.Trim();
                            rec.Remark = txtRemark.Text;
                            rec.ReceivedBy = txtReceivedBy.Text;

                            DateTime xx = dtRecDate.Value;
                            dtRecDate.CustomFormat = "MM/dd/yyyy";
                            DateTime dtRec = new DateTime();
                            rec.Date = ConvertDate.DateConverter(dtRecDate.Text);

                            dtRec = ConvertDate.DateConverter(dtRecDate.Text);
                            dtRecDate.IsGregorianCurrentCalendar = true;

                            rec.EurDate = dtRecDate.Value;

                            dtRecDate.IsGregorianCurrentCalendar = false;

                            rec.ItemID = Convert.ToInt32(dtRecGrid.Rows[i][0]);

                            switch (VisibilitySetting.HandleUnits)
                            {
                                case 1:
                                    rec.UnitID = 0;
                                    rec.QtyPerPack = Convert.ToInt32(dtRecGrid.Rows[i]["Qty/Pack"]);
                                    break;
                                case 2:
                                    rec.UnitID = Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);
                                    rec.QtyPerPack = 1;
                                    break;
                                case 3:
                                    rec.UnitID = Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);
                                    rec.QtyPerPack = 1;
                                    break;
                            }
                            rec.NoOfPack = Convert.ToInt32(dtRecGrid.Rows[i]["Pack Qty"]);

                            rec.Quantity = rec.NoOfPack * rec.QtyPerPack;
                            rec.QuantityLeft = rec.Quantity;
                            if (dtRecGrid.Rows[i]["Price/Pack"] != null &&
                                dtRecGrid.Rows[i]["Price/Pack"].ToString() != "")
                            {
                                double pre = Convert.ToDouble(dtRecGrid.Rows[i]["Price/Pack"]) / rec.QtyPerPack;
                                rec.Cost = Convert.ToDouble(pre);
                            }
                            else
                            {
                                rec.Cost = 0;
                            }
                            itm.LoadByPrimaryKey(Convert.ToInt32(dtRecGrid.Rows[i]["ID"]));
                            rec.BatchNo = dtRecGrid.Rows[i][8].ToString();
                            if (dtRecGrid.Rows[i]["Expiry Date"] != DBNull.Value)
                            {
                                rec.ExpDate = Convert.ToDateTime(dtRecGrid.Rows[i]["Expiry Date"]);
                            }

                            rec.SupplierID = Convert.ToInt32(cboSupplier.EditValue);
                            rec.SubProgramID = Convert.ToInt32(cboProgram.EditValue);
                            string batch = DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() +
                                           DateTime.Now.Minute.ToString() + rec.ItemID.ToString();
                            rec.LocalBatchNo = batch;

                            rec.Out = false;
                            rec.IsApproved = false;
                            dtRecDate.Value = xx;
                            rec.Save();

                            //check if there is any data on stockoutLog about this item on this store
                            //and update its enddate to today
                            StockoutLog stockoutLog = new StockoutLog();
                            DataTable tblStockoutLog = stockoutLog.LoadByStoreAndItemId(rec.ItemID, rec.StoreID, true);
                            if (tblStockoutLog != null)
                            {
                                if (tblStockoutLog.Rows.Count > 0)
                                {
                                    stockoutLog.LoadByPrimaryKey(int.Parse(tblStockoutLog.Rows[0]["ID"].ToString()));
                                    stockoutLog.EndDate = DateTime.Today;
                                    stockoutLog.Save();
                                }
                            }

                            itemprogram.LoadByOldProgramIdAndItemId(Convert.ToInt32(dtRecGrid.Rows[i][0]),
                                                                 Convert.ToInt32(cboProgram.EditValue));
                            if (itemprogram.RowCount != 0)
                            {
                                continue;
                            }
                            else
                            {
                                itemprogram.AddNew();
                                itemprogram.ItemID = Convert.ToInt32(dtRecGrid.Rows[i][0]);
                                itemprogram.ProgramID = Convert.ToInt32(cboProgram.EditValue);
                                itemprogram.Save();
                            }
                        }
                        XtraMessageBox.Show("Transaction Successfully Saved!", "Success", MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        ResetFields();
                        //  mgr.CommitTransaction();

                    }
                    catch (Exception exp)
                    {
                        //mgr.RollbackTransaction();
                        BLL.User user = new User();
                        user.LoadByPrimaryKey(MainWindow.LoggedinId);
                        if (user.UserType == UserType.Constants.SYSTEM_ADMIN)
                            XtraMessageBox.Show(exp.Message);
                        else
                            XtraMessageBox.Show("Saving Error!", "Error", MessageBoxButtons.OK);
                    }
                }

            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        /// <summary>
        /// Validates user input and returns "true" when valid and the error message when invalid.
        /// </summary>
        /// <returns></returns>
        private string ValidateFields()
        {
            //dtRecDate.Value = DateTime.Now;
            DateTime dtCurent = new DateTime();
            dtRecDate.CustomFormat = "MM/dd/yyyy";
            dtCurent = ConvertDate.DateConverter(dtRecDate.Text);

            string valid = "true";

            if (Convert.ToDateTime(dtRecDate.Value) > DateTime.Now)
            {
                valid = "You cannot pick a Date in a future!";
                return valid;
            }
            if (!dxValidationProvider1.Validate())
            {
                valid = "Please correct the highlighted filed!";
            }

            Items itm = new Items();
            for (int i = 0; i < gridRecieveView.DataRowCount; i++)
            {
                DataRow dr = gridRecieveView.GetDataRow(i);
                dr.ClearErrors();

                if (dr["Pack Qty"] == null || dr["Pack Qty"].ToString() == "" || Convert.ToInt64(dr["Pack Qty"]) == 0)
                {
                    dr.SetColumnError("Pack Qty", "This field cannot be left blank.");
                    valid = "Please fill the requested feild!";
                }

                itm.LoadByPrimaryKey(Convert.ToInt32(dtRecGrid.Rows[i]["ID"]));

                if (!itm.IsColumnNull("NeedExpiryBatch"))
                {
                    if (itm.NeedExpiryBatch)
                    {

                        if (dr["Expiry Date"].ToString() == "")
                        {
                            dr.SetColumnError("Expiry Date", "This field cannot be left blank.");
                            valid = "Please fill the requested feild!";
                        }

                        if (dr["Batch No"].ToString() == "")
                        {
                            dr.SetColumnError("Batch No", "This field cannot be left blank.");
                            valid = "Please fill the requested feild!";
                        }
                    }
                }
            }

            return valid;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            Items itm = new Items();
            if (_itemId != 0)
                itm.LoadByPrimaryKey(_itemId);
            else
            {
                itm.AddNew();
                itm.IsInHospitalList = true;
            }
            itm.IINID = Convert.ToInt32(cboIIN.EditValue);
            //itm.StockCode = txtCatCode.Text + "-" + txtStockCode.Text;
            itm.StockCode = txtStockCode.Text;
            itm.Strength = txtStrength.Text;
            itm.DosageFormID = Convert.ToInt32(cboDosageForm.EditValue);
            //itm.IsDiscontinued = false;
            //itm.IsFree = ckIsFree.Checked;
            //itm.EDL = ckIsEDL.Checked;
            itm.UnitID = Convert.ToInt32(cboUnit.EditValue);
            itm.NeedExpiryBatch = ckNeedExp.Checked ;
            //itm.Pediatric = ckIsPedatric.Checked;
            //itm.Refrigeratored = ckIsRefrigerated.Checked;

            itm.Save();

            ItemSupplyCategory prodCate = new ItemSupplyCategory();

                //int catId = Convert.ToInt32(lstC.Tag);
            if (_categoryId != 0)
            {
                if (!prodCate.CategoryExists(itm.ID, _categoryId))
                {

                    prodCate.AddNew();
                    prodCate.ItemID = itm.ID;
                    prodCate.CategoryID = _categoryId;
                    prodCate.Save();
                }
            }

            XtraMessageBox.Show("Supply is Saved Successfully!","Confirmation",MessageBoxButtons.OK,MessageBoxIcon.Information);
            this.Close();
        }
        private void PopulateFields()
        {
            if (_itemId == 0) return;

            Items itm = new Items();

            itm.LoadByPrimaryKey(_itemId);
            cboIIN.EditValue = itm.IINID;
            INN nInn = new INN();
            nInn.LoadByPrimaryKey(itm.IINID);
            txtStrength.Text = itm.Strength;
            cboDosageForm.EditValue = itm.DosageFormID;
            cboUnit.EditValue = itm.UnitID;
            string code = itm.StockCode;
            txtStockCode.Text = code;
            ckNeedExp.Checked = itm.NeedExpiryBatch;

            if (itm.HasTransactions(_itemId))
                ckNeedExp.Enabled = false;
        }
        /// <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();
        }
        private string ValidateFields()
        {
            dtRecDate.Value = DateTime.Now;
            DateTime dtCurent = new DateTime();
            dtRecDate.CustomFormat = "MM/dd/yyyy";
            dtCurent = ConvertDate.DateConverter(dtRecDate.Text);

            string valid = "true";

            if (Convert.ToDateTime(dtRecDate.Value) > DateTime.Now)
            {
                valid = "You cannot pick a Date in a future!";
                return valid;
            }

            if (lkFromStore != null && Convert.ToInt32(lkFromStore.EditValue) == Convert.ToInt32(lkToStore.EditValue))
            {
                valid = "You cannot transfer an item to the same store.";
                return valid;
            }

            if (!dxValidationProvider1.Validate())
            {
                valid = "Please correct the highlighted filed!";
            }

            var itm = new Items();
            for (int i = 0; i < gridRecieveView.DataRowCount; i++)
            {
                DataRow dr = gridRecieveView.GetDataRow(i);
                dr.ClearErrors();

                if (dr["Qty To Transfer"] == null || dr["Qty To Transfer"].ToString() == "" || Convert.ToInt64(dr["Qty To Transfer"]) == 0)
                {
                    dr.SetColumnError("Qty To Transfer", "This field cannot be left blank.");
                    valid = "Please fill the requested feild!";
                }

                if (Convert.ToInt32(dr["Qty To Transfer"]) > Convert.ToInt32(dr["BU Qty"]))
                {
                    dr.SetColumnError("Qty To Transfer", "Qty To Transfer should be less than BU Qty(Remaining).");
                    valid = "Qty To Transfer should be less than BU Qty(Remaining)";
                }
                itm.LoadByPrimaryKey(Convert.ToInt32(_dtRecGrid.Rows[i]["ID"]));

              }
            return valid;
        }
        /// <summary>
        /// Populates the picklist based on the selected issue configuration
        /// </summary>
        private void PopulatePickList()
        {
            var valid = ValidateFields();

            if (valid == "true")
            {
                var iss = new IssueDoc();
                var rec = new ReceiveDoc();
                var bal = new Balance();
                var itmB = new Items();
                var DUs = new ReceivingUnits();

                var dtIssueConf = new DataTable();
                string[] strr = { "No", "Stock Code", "Item Name", "Quantity", "BatchNo", "Expiry Date", "Pack Price", "Total Price",
                                    "ItemId", "RecId", "Unit Price", "No of Pack", "Qty per pack",
                                    "DUSOH", "DUAMC", "Near Expiry", "DURecomended","SOH Left","UnitID" };
                foreach (string col in strr)
                {
                    dtIssueConf.Columns.Add(col);
                }

                DUs.LoadByPrimaryKey(Convert.ToInt32(cboReceivingUnits.EditValue));
                double duMax = 0.5;
                try
                {
                    duMax = DUs.Max;
                }
                catch { }
                double duMaxDays = duMax * 30;
                lblNearExpiryComment.Text = "*Near Expiry means items that has expiry in the next " + duMaxDays.ToString() + " Days.";

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

                DateTime dtCurrent = new DateTime();// Convert.ToDateTime(dtIssueDate.Text);
                dtCurrent = ConvertDate.DateConverter(dtIssueDate.Text);
                dtIssueDate.Value = xx;
                dtIssueDate.CustomFormat = "MMM dd,yyyy";
                var dtIssueGrid = (DataTable)issueGrid.DataSource;
                for (int i = 0; i < dtIssueGrid.Rows.Count; i++)
                {
                    var unitid = Convert.ToInt32(dtIssueGrid.Rows[i]["UnitID"]);
                    Int64 expAmount = itmB.GetExpiredQtyItemsByID(Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), Convert.ToInt32(cboStores.EditValue));
                    Int64 sohQty = 0;
                    try
                    {

                        switch (VisibilitySetting.HandleUnits)
                        {

                            case 1:
                                sohQty = bal.GetSOH(Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), Convert.ToInt32(cboStores.EditValue), dtIss.Month, dtIss.Year) - expAmount;
                                break;
                            case 2:
                                sohQty = bal.GetSOHByUnit(Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), Convert.ToInt32(cboStores.EditValue), dtIss.Month, dtIss.Year, unitid) - expAmount;
                                break;
                            case 3:
                                sohQty = bal.GetSOHByUnit(Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), Convert.ToInt32(cboStores.EditValue), dtIss.Month, dtIss.Year, unitid) - expAmount;
                                break;
                        }
                    }
                    catch
                    {
                        XtraMessageBox.Show("Please check all the information you have input into the form including the issue date.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    if (sohQty >= Convert.ToInt64(dtIssueGrid.Rows[i]["Requested Qty"]))
                    {
                        var itm = new Items();
                        itm.LoadByPrimaryKey(Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]));
                        if (itm.IsColumnNull("NeedExpiryBatch"))
                        {
                            itm.NeedExpiryBatch = true;
                            itm.Save();
                        }
                        if (itm.NeedExpiryBatch && VisibilitySetting.HandleUnits == 1)
                        {
                            _dtRec = rec.GetBatchToIssue(Convert.ToInt32(cboStores.EditValue),
                                                         Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), dtIss);
                        }
                        else if (itm.NeedExpiryBatch && VisibilitySetting.HandleUnits == 2)
                        {
                            _dtRec = rec.GetBatchToIssueByUnit(Convert.ToInt32(cboStores.EditValue),
                                                        Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), dtIss ,unitid);
                        }
                        else if (itm.NeedExpiryBatch && VisibilitySetting.HandleUnits == 3)
                        {
                            _dtRec = rec.GetBatchToIssueByUnit(Convert.ToInt32(cboStores.EditValue),
                                                        Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), dtIss, unitid);
                        }
                        else
                            _dtRec = rec.GetSupplyToIssueWithOutBatch(Convert.ToInt32(cboStores.EditValue),
                                                                      Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]),
                                                                      dtIssueDate.Value);

                        // Extream measures:
                        // This has tobe properly mitigated
                        // if there is the balance an there is no batch to be issued, just select the last batch and add the balance to it.

                        if (rec.RowCount > 0)
                        {
                            int j = 0;
                            Int64 quantity = 0;
                            double sohbalance = 0;
                            switch (VisibilitySetting.HandleUnits)
                            {
                                case 1:
                                    quantity = Convert.ToInt64(dtIssueGrid.Rows[i]["Requested Qty"]);
                                    sohbalance = sohQty - quantity;
                                    break;
                                case 2:
                                    quantity = Convert.ToInt64(dtIssueGrid.Rows[i]["Pack Qty"]);
                                    sohbalance = sohQty - quantity;
                                    break;
                                default:
                                    quantity = Convert.ToInt64(dtIssueGrid.Rows[i]["Pack Qty"]);
                                    sohbalance = sohQty - quantity;
                                    break;
                            }

                            while (quantity >=0 && rec.RowCount > j)
                            {
                                var batch = itm.NeedExpiryBatch ? _dtRec.Rows[j]["BatchNo"].ToString() : "";
                                Int64 qu = ((quantity > Convert.ToInt32(_dtRec.Rows[j]["QuantityLeft"])) ? Convert.ToInt64(_dtRec.Rows[j]["QuantityLeft"]) : quantity);
                                double qtyPerPack = Convert.ToDouble(_dtRec.Rows[j]["QtyPerPack"]);
                                double unitPrice = Convert.ToDouble(_dtRec.Rows[j]["Cost"]);
                                double packPrice = unitPrice * qtyPerPack; //Convert.ToDouble(dtIssueGrid.Rows[i]["Qty Per Pack"]);
                                double reqPackQty = Convert.ToDouble(dtIssueGrid.Rows[i]["Pack Qty"]);
                                double totPrice = unitPrice * qu;
                                bool nearExp = false;
                                DateTime? dtx = new DateTime();

                                switch (VisibilitySetting.HandleUnits)
                                {
                                    case 1:
                                        rec.UnitID = 0;
                                        rec.QtyPerPack = Convert.ToInt32(dtIssueGrid.Rows[i]["Qty Per Pack"]);
                                        break;
                                    case 2:
                                        rec.UnitID = Convert.ToInt32(dtIssueGrid.Rows[i]["UnitID"]);
                                        rec.QtyPerPack = 1;
                                        break;
                                    case 3:
                                        rec.UnitID = Convert.ToInt32(dtIssueGrid.Rows[i]["UnitID"]);
                                        rec.QtyPerPack = 1;
                                        break;
                                }

                                if (itm.NeedExpiryBatch)
                                {
                                    dtx = Convert.ToDateTime(_dtRec.Rows[j]["ExpDate"]);
                                    if (dtx <= DateTime.Now.AddDays(duMaxDays))
                                        nearExp = true;
                                }
                                else if (!itm.NeedExpiryBatch)
                                {
                                    dtx = null;
                                    // nearExp = false;
                                }
                                int rowNo = j + 1;

                                object[] obj = { rowNo, dtIssueGrid.Rows[i]["Stock Code"],
                                                     dtIssueGrid.Rows[i]["Item Name"], qu, batch,dtx,
                                                     packPrice.ToString("#,##0.#0"), ((totPrice != double.NaN) ? totPrice.ToString("#,##0.#0") : "0"),
                                                     Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), Convert.ToInt32(_dtRec.Rows[j]["ID"]), unitPrice.ToString("#,##0.00"),
                                                     dtIssueGrid.Rows[i]["Pack Qty"], dtIssueGrid.Rows[i]["Qty Per Pack"], dtIssueGrid.Rows[i]["DU Remaining SOH"],
                                                     dtIssueGrid.Rows[i]["DU AMC"], ((nearExp) ? "Yes" : "No"), dtIssueGrid.Rows[i]["Recommended Qty"],
                                                     sohbalance,dtIssueGrid.Rows[i]["UnitID"]};
                                dtIssueConf.Rows.Add(obj);

                                quantity = quantity - Convert.ToInt64(_dtRec.Rows[j]["QuantityLeft"]);
                                j++;
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show("There is no enough Quantity in the store OR It has expired. Please check the issue date, quantity and try again!");
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("There is not enough Quantity in the store OR It has expired. Please check the issue date, quantity and try again!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                if (dtIssueConf.Rows.Count > 0)
                {
                    _tabPage = 2;

                    tabControl1.SelectedTabPageIndex = 2;
                    txtConfRef.Text = txtRefNo.Text;
                    txtIssuedDate.Value = dtIssueDate.Value;
                    txtIssuedTo.Text = cboReceivingUnits.Text;

                    txtStore.Text = cboStores.Text;
                    txtConIssuedBy.Text = txtIssuedBy.Text;
                    txtConRemark.Text = txtRemark.Text;
                    txtConRecipientName.Text = txtRecipientName.Text;
                    gridConfirmation.DataSource = dtIssueConf;
                }
            }
            else
            {
                tabControl1.SelectedTabPageIndex = 1;
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        /* private void GenerateBinCard()
         {
             ReceiveDoc rec = new ReceiveDoc();
             IssueDoc iss = new IssueDoc();
             Disposal dis = new Disposal();
             DisposalReasons res = new DisposalReasons();
             Balance bal = new Balance();
             GeneralInfo info = new GeneralInfo();
             YearEnd yEnd = new YearEnd();
             Items itm = new Items();
             info.LoadAll();
             year = Convert.ToInt32(cboYear.SelectedItem);

             DataTable dtRec = rec.GetAllTransaction(itemId,storeId,dtCurrent.Month,year);
             DataTable dtIss = iss.GetTransactionByItemId(storeId, itemId, year);
             DataTable dtDis = dis.GetTransactionByItemId(storeId, itemId, year);

             Int64[] cStockout = { 0, 0, 0 };
             Int64[] cOverStock = { 0, 0, 0 };
             Int64[] cNearStockOut = { 0, 0, 0 };
             Int64[] cBelowMin = { 0, 0, 0 };

             //DateTime dtThree = dtCurrent.AddMonths(3);

             DataTable dtbin = new DataTable();
             string[] col = { "Date", "Ref. No", "Receive", "Issue", "Unit Price", "Balance", "Batch No", "Expiry Date","To / From"};
             foreach (string str in col)
             {
                 dtbin.Columns.Add(str);
             }
             int i = 0;
             Int64 bBalance = 0;
             dtDate.Value = DateTime.Now;
             dtDate.CustomFormat = "MM/dd/yyyy";
             dtCurrent = ConvertDate.DateConverter(dtDate.Text);
             bBalance = yEnd.GetBBalance(year, storeId, itemId,dtCurrent.Month);
             Int64 balanceAmount = bBalance;
             Int64 mincon = 0;
             Int64 maxcon = 0;
             double eopcon = 0;

             DateTime dtT = new DateTime();
             string balanceAm = "";

             txtBBalance.Text = bBalance.ToString();
             string ddDate = "";
             string batNo = "";
                 foreach (DataRow dvRec in dtRec.Rows)
                 {
                     i++;
                     if (Convert.ToInt32(dvRec["Transact"]) == 1)
                     {
                         rec.LoadByPrimaryKey(Convert.ToInt32(dvRec["ID"]));
                         balanceAmount = balanceAmount + Convert.ToInt64(dvRec["Quantity"]);
                         balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                         itm.LoadByPrimaryKey(rec.ItemID);
                         if (itm.NeedExpiryBatch)
                         {
                             ddDate = rec.ExpDate.ToString("MMM dd,yyyy");
                             batNo = rec.BatchNo;
                         }
                         Supplier sup = new Supplier();
                         sup.LoadByPrimaryKey(rec.SupplierID);
                         object[] obj = { Convert.ToDateTime(dvRec["Date"]).ToString("MM dd,yyyy"), dvRec["RefNo"], Convert.ToInt64(dvRec["Quantity"]).ToString("#,###"), "", Convert.ToDouble(dvRec["Cost"]).ToString("C"), balanceAm, batNo, ddDate, sup.CompanyName};
                         dtbin.Rows.Add(obj);
                         //For stock Out
                         dtT = Convert.ToDateTime(dvRec["Date"]);
                         //int monb = (dtT.Month < 11) ? dtT.Month + 2 : ((dtT.Month == 11) ? 1 : 2);
                         //int yer = (dtT.Month < 11) ? dtT.Year : dtT.Year - 1;
                         Int64 bBal = bal.GetSOH(itemId, storeId, dtT.Month, dtT.Year);
                         Int64 bAmc = bal.CalculateAMC(itemId, storeId, dtT.Month, dtT.Year);

                         mincon = bAmc * info.Min;
                         maxcon = bAmc * info.Max;
                         eopcon = bAmc * info.EOP;

                         if (balanceAmount == 0)
                         {
                             if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                             {
                                 cStockout[0]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                             {
                                 cStockout[1]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                             {
                                 cStockout[2]++;
                             }
                         }
                         else if (balanceAmount > maxcon)
                         {
                             //For Over stock
                             if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                             {
                                 cOverStock[0]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                             {
                                 cOverStock[1]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                             {
                                 cOverStock[2]++;
                             }
                         }//For Below min
                         else if (balanceAmount > eopcon && balanceAmount <= mincon)
                         {
                             if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                             {
                                 cBelowMin[0]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                             {
                                 cBelowMin[1]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                             {
                                 cBelowMin[2]++;
                             }
                         }
                         else if (balanceAmount > 0 && balanceAmount < eopcon)
                         {
                             if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                             {
                                 cNearStockOut[0]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                             {
                                 cNearStockOut[1]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                             {
                                 cNearStockOut[2]++;
                             }
                         }
                     }else if(Convert.ToInt32(dvRec["Transact"]) == 0)
                     {
                         //DateTime dteIss = Convert.ToDateTime(drIss["Date"]);
                         //DateTime dteRec = Convert.ToDateTime(dvRec["Date"]);
                         //DateTime dTomorow = new DateTime(dtCurrent.Year, dtCurrent.Month, dtCurrent.Day + 1);
                         //DateTime dteNextRec = (i <= dtRec.Rows.Count - 1) ? Convert.ToDateTime(dtRec.Rows[i]["Date"]) : dTomorow;
                         iss.LoadByPrimaryKey(Convert.ToInt32(dvRec["ID"]));
                         try
                         {
                             rec.LoadByPrimaryKey(iss.RecievDocID);
                         }
                         catch
                         {
                             rec.GetTransactionByBatch(itemId, dvRec["BatchNo"].ToString(), storeId);
                         }

                         ReceivingUnits recUnit = new ReceivingUnits();
                         recUnit.LoadByPrimaryKey(iss.ReceivingUnitID);
                         string issuedTo = recUnit.Name;
                             balanceAmount = balanceAmount - Convert.ToInt64(dvRec["Quantity"]);

                         balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                         itm.LoadByPrimaryKey(iss.ItemID);
                         if (itm.NeedExpiryBatch)
                         {
                             ddDate = ((rec.RowCount > 0) ? rec.ExpDate.ToString("MMM dd,yyyy") : ""); ;
                             batNo = dvRec["BatchNo"].ToString(); //rec.BatchNo;
                         }
                         else
                         {
                             ddDate = "";
                             batNo = "";
                         }
                         object[] obj = { Convert.ToDateTime(dvRec["Date"]).ToString("MM dd,yyyy"), dvRec["RefNo"], "", Convert.ToInt64(dvRec["Quantity"]).ToString("#,###"), Convert.ToDouble(dvRec["Cost"]).ToString("C"), balanceAm,batNo, ddDate,issuedTo};
                         dtbin.Rows.Add(obj);
                         //For stock Out
                         dtT = Convert.ToDateTime(dvRec["Date"]);
                             //int monb1 = (dtT.Month < 11) ? dtT.Month + 2 : ((dtT.Month == 11) ? 1 : 2);
                             //int yer1 = (dtT.Month < 11) ? dtT.Year : dtT.Year - 1;
                            Int64 bBal = bal.GetSOH(itemId, storeId, dtT.Month, dtT.Year);
                             Int64 bAmc = bal.CalculateAMC(itemId, storeId, dtT.Month, dtT.Year);

                             mincon = bAmc * info.Min;
                             maxcon = bAmc * info.Max;
                             eopcon = bAmc * info.EOP;

                             if (balanceAmount == 0)
                             {
                                 if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                 {
                                     cStockout[0]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                 {
                                     cStockout[1]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                 {
                                     cStockout[2]++;
                                 }
                             }
                             else if (balanceAmount > maxcon)
                             {
                                 //For Over stock
                                 if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                 {
                                     cOverStock[0]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                 {
                                     cOverStock[1]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                 {
                                     cOverStock[2]++;
                                 }
                             }//For Below min
                             else if (balanceAmount > eopcon && balanceAmount <= mincon)
                             {
                                 if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                 {
                                     cBelowMin[0]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                 {
                                     cBelowMin[1]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                 {
                                     cBelowMin[2]++;
                                 }
                             }
                             else if (balanceAmount > 0 && balanceAmount < eopcon)
                             {
                                 if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                 {
                                     cNearStockOut[0]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                 {
                                     cNearStockOut[1]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                 {
                                     cNearStockOut[2]++;
                                 }
                             }

                         }

                         foreach (DataRow drDis in dtDis.Rows)
                         {
                             DateTime dteDis = Convert.ToDateTime(drDis["Date"]);
                             DateTime dteRec = Convert.ToDateTime(dvRec["Date"]);

                             res.LoadByPrimaryKey(Convert.ToInt32(drDis["ReasonId"]));
                             rec.GetTransactionByBatch(itemId,drDis["BatchNo"].ToString(),storeId);
                             DateTime dteNextRec = (i <= dtRec.Rows.Count - 1) ? Convert.ToDateTime(dtRec.Rows[i]["Date"]) : dtCurrent;
                             if ((dteRec <= dteDis) && (dteDis < dteNextRec))
                             {
                                 if (Convert.ToBoolean(drDis["Losses"]))
                                 {
                                     balanceAmount = balanceAmount - Convert.ToInt64(drDis["Quantity"]);
                                     balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                                     object[] objIss = { Convert.ToDateTime(drDis["Date"]).ToString("MM dd,yyyy"), drDis["RefNo"], "", Convert.ToInt64(drDis["Quantity"]).ToString("#,###"), Convert.ToDouble(drDis["Cost"]).ToString("C"), balanceAm, drDis["BatchNo"], rec.ExpDate.ToString("MMM dd,yyyy"), res.Reason};
                                     dtbin.Rows.Add(objIss);

                                 }
                                 else
                                 {
                                     balanceAmount = balanceAmount + Convert.ToInt64(drDis["Quantity"]);
                                     balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                                     object[] objIss2 = { Convert.ToDateTime(drDis["Date"]).ToString("MM dd,yyyy"), drDis["RefNo"], Convert.ToInt64(drDis["Quantity"]).ToString("#,###"), "", Convert.ToDouble(drDis["Cost"]).ToString("C"), balanceAm, drDis["BatchNo"], rec.ExpDate.ToString("MMM dd,yyyy"), res.Reason};
                                     dtbin.Rows.Add(objIss2);

                                 }

                                 dtT = Convert.ToDateTime(dvRec["Date"]);
                                 Int64 bAmc = bal.CalculateAMC(itemId, storeId, dtT.Month, dtT.Year);

                                 mincon = bAmc * info.Min;
                                 maxcon = bAmc * info.Max;
                                 eopcon = bAmc * info.EOP;
                                 if (balanceAmount == 0)
                                 {
                                     if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                     {
                                         cStockout[0]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                     {
                                         cStockout[1]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                     {
                                         cStockout[2]++;
                                     }
                                 }
                                 else if (balanceAmount > maxcon)
                                 {
                                     //For Over stock
                                     if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                     {
                                         cOverStock[0]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                     {
                                         cOverStock[1]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                     {
                                         cOverStock[2]++;
                                     }
                                 }//For Below min
                                 else if (balanceAmount > eopcon && balanceAmount <= mincon)
                                 {
                                     if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                     {
                                         cBelowMin[0]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                     {
                                         cBelowMin[1]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                     {
                                         cBelowMin[2]++;
                                     }
                                 }
                                 else if (balanceAmount > 0 && balanceAmount < eopcon)
                                 {
                                     if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                     {
                                         cNearStockOut[0]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                     {
                                         cNearStockOut[1]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                     {
                                         cNearStockOut[2]++;
                                     }
                                 }

                             }
                         }

                     }
             transactionGrid.DataSource = dtbin;
             //Stock Out
             lblThreeStockout.Text = cStockout[0].ToString();
             lblSixStockOut.Text = (cStockout[0] + cStockout[1]).ToString();
             lblTwelveStockOut.Text = (cStockout[0] + cStockout[1] + cStockout[2]).ToString();
             //Over Stock
             lblThreeOverStock.Text = cOverStock[0].ToString();
             lblSixOverStock.Text = (cOverStock[0] + cOverStock[1]).ToString();
             lblTwelveOverStock.Text = (cOverStock[0] + cOverStock[1] + cOverStock[2]).ToString();
             //Near eop
             lblThreeNearStock.Text = cNearStockOut[0].ToString();
             lblSixNearStock.Text = (cNearStockOut[0] + cNearStockOut[1]).ToString();
             lblTwelveNear.Text = (cNearStockOut[0] + cNearStockOut[1] + cNearStockOut[2]).ToString();
             //Below Min
             lblThreeBelowMin.Text = cBelowMin[0].ToString();
             lblSixBelowMin.Text = (cBelowMin[0] + cBelowMin[1]).ToString();
             lblTwelveBelowMin.Text = (cBelowMin[0] + cBelowMin[1] + cBelowMin[2]).ToString();
         }
          */
        /// <summary>
        /// Generates the bin card transaction
        /// </summary>
        private void GenerateBinCard()
        {
            #region NewCode
            ////Get the beginning balance.
            //Int64 begBalance = 0;
            //YearEnd yearEnd = new YearEnd();
            //begBalance = yearEnd.GetBeginningBalance(_storeId, _itemId);
            //txtBBalance.Text = begBalance.ToString();

            ////Get the bin card.
            //Balance balance = new Balance();
            //gridItemsList.DataSource = balance.GetBinCard(_storeId, _itemId);
            //return;
            #endregion
            #region Old Code
            ReceiveDoc rec = new ReceiveDoc();
            IssueDoc iss = new IssueDoc();
            Disposal dis = new Disposal();
            DisposalReasons res = new DisposalReasons();
            Balance bal = new Balance();
            GeneralInfo info = new GeneralInfo();
            YearEnd yEnd = new YearEnd();
            Items itm = new Items();
            info.LoadAll();
            if (cboFiscalYear.SelectedItem == null)
                PopulateBinCardYearCombo();
            //_year =  Convert.ToInt32(cboFiscalYear.SelectedItem);
            _year = Convert.ToInt32(cboYear.SelectedItem);
            int yer = _year;
            //int mth = (_year > _dtCurrent.Year) ? _dtCurrent.Month : 10;
            int mth = _dtCurrent.Month;
            EthiopianDate.EthiopianDate ethioDate = new EthiopianDate.EthiopianDate(_year, 1, 1);

            //if (_dtCurrent.Month < 11)
            //{
            //    yer = _year;
            //}
            //else
            //{
            //    yer = _year - 1;
            //}
            //DataTable dtRec = rec.GetAllTransaction(_itemId, _storeId, ethioDate.Month,ethioDate.Year);
            DataTable dtRec = rec.GetAllTransaction(_itemId, _storeId, ethioDate.FiscalYear);
            DataTable dtIss = iss.GetTransactionByItemId(_storeId, _itemId, ethioDate.FiscalYear);
            DataTable dtDis = dis.GetTransactionByItemId(_storeId, _itemId, ethioDate.FiscalYear);

            Int64[] cStockout = { 0, 0, 0 };
            Int64[] cOverStock = { 0, 0, 0 };
            Int64[] cNearStockOut = { 0, 0, 0 };
            Int64[] cBelowMin = { 0, 0, 0 };

            //DateTime dtThree = dtCurrent.AddMonths(3);

            DataTable dtbin = new DataTable();
            string[] col = { "Date", "RefNo", "Receive", "Issue", "Unit Price", "Balance", "Batch No", "Expiry Date", "ToFrom" };
            foreach (string str in col)
            {
                dtbin.Columns.Add(str);
            }
            int i = 0;
            Int64 bBalance = 0;
            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            _dtCurrent = ConvertDate.DateConverter(dtDate.Text);
            //bBalance = yEnd.GetBBalance(_year, _storeId, _itemId, _dtCurrent.Month);
            bBalance = yEnd.GetBBalance(_year, _storeId, _itemId);
            Int64 balanceAmount = bBalance;

            DateTime dtT = new DateTime();
            string balanceAm = "";

            string ddDate = "";
            string batNo = "";
            foreach (DataRow dvRec in dtRec.Rows)
            {
                i++;
                if (Convert.ToInt32(dvRec["Transact"]) == 1)
                {
                    rec.LoadByPrimaryKey(Convert.ToInt32(dvRec["ID"]));
                    if (dvRec["Quantity"] == DBNull.Value)
                    {
                        dvRec["Quantity"] = 0;
                    }
                    balanceAmount = balanceAmount + Convert.ToInt64(dvRec["Quantity"]);
                    balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                    itm.LoadByPrimaryKey(rec.ItemID);
                    if (itm.NeedExpiryBatch)
                    {
                        if (!rec.IsColumnNull("ExpDate"))
                        {
                            ddDate = rec.ExpDate.ToString("MMM dd,yyyy");
                            batNo = rec.BatchNo;
                        }
                    }
                    Supplier sup = new Supplier();
                    sup.LoadByPrimaryKey(rec.SupplierID);
                    object[] obj = { Convert.ToDateTime(dvRec["Date"]).ToString("MM dd,yyyy"), dvRec["RefNo"], Convert.ToInt64(dvRec["Quantity"]).ToString("#,###"), "", Convert.ToDouble(dvRec["Cost"]).ToString("C"), balanceAm, batNo, ddDate, sup.CompanyName };
                    dtbin.Rows.Add(obj);
                    //For stock Out
                    dtT = Convert.ToDateTime(dvRec["Date"]);

                }
                else if (Convert.ToInt32(dvRec["Transact"]) == 0)
                {
                    iss.LoadByPrimaryKey(Convert.ToInt32(dvRec["ID"]));
                    try
                    {
                        rec.LoadByPrimaryKey(iss.RecievDocID);
                    }
                    catch
                    {
                        rec.GetTransactionByBatch(_itemId, dvRec["BatchNo"].ToString(), _storeId);
                    }

                    ReceivingUnits recUnit = new ReceivingUnits();
                    recUnit.LoadByPrimaryKey(iss.ReceivingUnitID);
                    string issuedTo = recUnit.Name;
                    balanceAmount = balanceAmount - Convert.ToInt64(dvRec["Quantity"]);

                    balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                    itm.LoadByPrimaryKey(iss.ItemID);
                    if (itm.NeedExpiryBatch)
                    {
                        ddDate = ((rec.RowCount > 0) ? rec.ExpDate.ToString("MMM dd,yyyy") : ""); ;
                        batNo = dvRec["BatchNo"].ToString(); //rec.BatchNo;
                    }
                    else
                    {
                        ddDate = "";
                        batNo = "";
                    }
                    object[] obj = { Convert.ToDateTime(dvRec["Date"]).ToString("MM dd,yyyy"), dvRec["RefNo"], "", Convert.ToInt64(dvRec["Quantity"]).ToString("#,###"), Convert.ToDouble(dvRec["Cost"]).ToString("C"), balanceAm, batNo, ddDate, issuedTo };
                    dtbin.Rows.Add(obj);
                    //For stock Out
                    dtT = Convert.ToDateTime(dvRec["Date"]);

                }

                foreach (DataRow drDis in dtDis.Rows)
                {
                    DateTime dteDis = Convert.ToDateTime(drDis["Date"]);
                    DateTime dteRec = Convert.ToDateTime(dvRec["Date"]);

                    res.LoadByPrimaryKey(Convert.ToInt32(drDis["ReasonId"]));
                    rec.GetTransactionByBatch(_itemId, drDis["BatchNo"].ToString(), _storeId);
                    DateTime dteNextRec = (i <= dtRec.Rows.Count - 1) ? Convert.ToDateTime(dtRec.Rows[i]["Date"]) : _dtCurrent;
                    if ((dteRec <= dteDis) && (dteDis < dteNextRec))
                    {
                        if (Convert.ToBoolean(drDis["Losses"]))
                        {
                            balanceAmount = balanceAmount - Convert.ToInt64(drDis["Quantity"]);
                            balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                            if (rec.RowCount > 0)
                            {
                                object[] objIss = { Convert.ToDateTime(drDis["Date"]).ToString("MM dd,yyyy"), drDis["RefNo"], "", Convert.ToInt64(drDis["Quantity"]).ToString("#,###"), Convert.ToDouble(drDis["Cost"]).ToString("C"), balanceAm, drDis["BatchNo"], rec.ExpDate.ToString("MMM dd,yyyy"), res.Reason };
                                dtbin.Rows.Add(objIss);
                            }
                        }
                        else
                        {
                            balanceAmount = balanceAmount + Convert.ToInt64(drDis["Quantity"]);
                            balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                            object[] objIss2 = { Convert.ToDateTime(drDis["Date"]).ToString("MM dd,yyyy"), drDis["RefNo"], Convert.ToInt64(drDis["Quantity"]).ToString("#,###"), "", Convert.ToDouble(drDis["Cost"]).ToString("C"), balanceAm, drDis["BatchNo"], rec.ExpDate.ToString("MMM dd,yyyy"), res.Reason };
                            dtbin.Rows.Add(objIss2);

                        }

                        dtT = Convert.ToDateTime(dvRec["Date"]);

                    }
                }

            }

            gridItemsList.DataSource = dtbin;
            #endregion
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            Items itm = new Items();
            if (_itemId != 0)
                itm.LoadByPrimaryKey(_itemId);
            else
            {
                itm.AddNew();
                itm.IsInHospitalList = true;

                Items itms = new Items();
                itm.ID = itms.GetNextItemID();
                itm.StorageTypeID = 1;
                itm.NearExpiryTrigger = 0;
            }
            itm.IINID = Convert.ToInt32(cboIIN.SelectedValue);

            //itm.StockCode = txtCatCode.Text + "-" + txtStockCode.Text;
            itm.StockCode = txtStockCode.Text;
            itm.Code = txtStock2.Text;
            itm.StockCodeDACA = txtStock3.Text;
            itm.Strength = txtStrength.Text;
            itm.DosageFormID = Convert.ToInt32(cboDosageForm.SelectedValue);
            itm.IsDiscontinued = ckIsDiscontinued.Checked;
            itm.IsFree = ckIsFree.Checked;
            itm.EDL = ckIsEDL.Checked;
            itm.UnitID = Convert.ToInt32(cboUnit.SelectedValue);
            itm.Pediatric = ckIsPedatric.Checked;
            itm.Refrigeratored = ckIsRefrigerated.Checked;
            itm.NeedExpiryBatch = true;
            itm.Save();

            ProductsCategory prodCate = new ProductsCategory();
            foreach (ListViewItem lstC in lstCat.Items)
            {
                int catId = Convert.ToInt32(lstC.Tag);

                if (prodCate.CategoryExists(itm.ID, catId)) continue;

                prodCate.AddNew();
                prodCate.ItemId = itm.ID;
                prodCate.SubCategoryID = catId;
                prodCate.Save();
            }

            if (itm.IsColumnNull("StockCode"))
            {
                // Update the Stock Code

                prodCate.Rewind();
                SubCategory sc = new SubCategory();
                sc.LoadByPrimaryKey(prodCate.SubCategoryID);

                if(sc.RowCount > 0)
                {
                    itm.StockCode = string.Format("{0}.{1}.{2}.{3}",sc.SubCategoryCode, 1, itm.DosageFormID, 1);
                    itm.Save();
                }
            }
            XtraMessageBox.Show( "Item is Saved Successfully!" , "Confirmation" , MessageBoxButtons.OK, MessageBoxIcon.Information);

            this.Close();
        }
        private void PopulateFields()
        {
            try
            {
                if (_itemId == 0) return;

                Items itm = new Items();

                itm.LoadByPrimaryKey(_itemId);
                SubCategory cat = new SubCategory();
                DataTable dtCat = cat.GetSubCategoryOfItem(_itemId);
                foreach (DataRow drcat in dtCat.Rows)
                {
                    DataTable dtProd = cat.GetSubCategoryByID(Convert.ToInt32(drcat["SubCategoryID"]));
                    //txtCategory.Text = dtProd.Rows[0]["CategoryName"].ToString();
                    //txtSubCategory.Text = dtProd.Rows[0]["SubCategoryName"].ToString();
                    string[] categor = { dtProd.Rows[0]["CategoryName"].ToString(), dtProd.Rows[0]["SubCategoryName"].ToString() };
                    ListViewItem listCat = new ListViewItem(categor) { Tag = dtProd.Rows[0]["ID"] };
                    lstCat.Items.Add(listCat);
                }
                cboIIN.SelectedValue = itm.IINID.ToString();
                Product nInn = new Product();
                nInn.LoadByPrimaryKey(itm.IINID);
                //txtATC.Text = nInn.ATC;
                txtStrength.Text = itm.Strength;
                ckIsDiscontinued.Checked = itm.IsDiscontinued;
                ckIsEDL.Checked = itm.EDL;
                ckIsFree.Checked = itm.IsFree;
                ckIsPedatric.Checked = itm.Pediatric;
                ckIsRefrigerated.Checked = itm.Refrigeratored;
                cboDosageForm.SelectedValue = itm.DosageFormID.ToString();
                cboUnit.SelectedValue = itm.UnitID.ToString();
                string code = itm.StockCode;
                txtStockCode.Text = code;
                txtStock2.Text = itm.Code;
                txtStock3.Text = itm.StockCodeDACA;
            }
            catch
            {

            }
        }