/// <summary>
 /// Determines whether [is performed for year] [the specified year].
 /// </summary>
 /// <param name="year">The year.</param>
 /// <returns>
 ///   <c>true</c> if [is performed for year] [the specified year]; otherwise, <c>false</c>.
 /// </returns>
 public static bool IsPerformedForYear(int year)
 {
     string query = HCMIS.Repository.Queries.YearEnd.SelectIsPerformedForYear(year);
     YearEnd yearend = new YearEnd();
     yearend.LoadFromRawSql(query);
     return (yearend.RowCount > 0);
 }
        /// <summary>
        /// Updates the year end value.
        /// </summary>
        /// <param name="yearEndQuantity2">The year end quantity2.</param>
        /// <param name="itemID">The item ID.</param>
        /// <param name="unitID">The unit ID.</param>
        /// <param name="year">The year.</param>
        public static void UpdateYearEndValue(long yearEndQuantity2, int itemID, int unitID, int year)
        {
            string query = HCMIS.Repository.Queries.YearEnd.UpdateUpdateYearEndValue(yearEndQuantity2, itemID, unitID, year);

            BLL.YearEnd ye = new YearEnd();
            ye.LoadFromRawSql(query);
        }
        /// <summary>
        /// Determines whether [is performed for year] [the specified year].
        /// </summary>
        /// <param name="year">The year.</param>
        /// <returns>
        ///   <c>true</c> if [is performed for year] [the specified year]; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsPerformedForYear(int year)
        {
            string  query   = HCMIS.Repository.Queries.YearEnd.SelectIsPerformedForYear(year);
            YearEnd yearend = new YearEnd();

            yearend.LoadFromRawSql(query);
            return(yearend.RowCount > 0);
        }
        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DataRow dr = gridView2.GetFocusedDataRow();
            if (dr == null) return;

            int year = Convert.ToInt32(dr["Year"]);
            YearEnd yEnd = new YearEnd();
            gridInventory.DataSource = yEnd.GetDocumentByYear(Convert.ToInt32(cboStores.SelectedValue), year);
        }
 private void LstTransactionsMouseDoubleClick(object sender, MouseEventArgs e)
 {
     string yr = lstRefNo.SelectedItems[0].Tag.ToString();
     if (yr != "")
     {
         YearEnd yEnd = new YearEnd();
         DataTable dtRec = yEnd.GetDocumentByYear(Convert.ToInt32(lkActivity.EditValue), yr);
         lblAdjDate.Text = yr;
         PopulateTransactions(dtRec);
     }
 }
 public static void PurgeAutomaticallyEnteredInventory(int itemID, int storeID, int year)
 {
     YearEnd yearEnd = new YearEnd();
     yearEnd.Where.ItemID.Value = itemID;
     yearEnd.Where.StoreID.Value = storeID;
     yearEnd.Where.Year.Value = year;
     yearEnd.Where.AutomaticallyEntered.Value = true;
     yearEnd.Query.Load();
     yearEnd.DeleteAll();
     yearEnd.Save();
 }
예제 #7
0
파일: YearEnd.cs 프로젝트: tomanye/facility
        public void GenerateAutomaticInventoryByUnit()
        {
            var ethDate = new EthiopianDate.EthiopianDate();
            var stores  = new Stores();

            stores.GetActiveStores();
            var rec     = new ReceiveDoc();
            var itm     = new Items();
            var yearEnd = new YearEnd();
            var balance = new Balance();

            if (!InventoryRequiredForHandlingUnit(false))
            {
                return;
            }
            while (!stores.EOF) //This needs to be done for each store and for each item
            {
                //bereket
                //itm.ExcludeNeverReceivedItemsNoCategoryForHandlingUnit(stores.ID);
                itm.ExcludeNeverReceivedItemsNoCategoryForHandlingUnitOptimized(stores.ID, ethDate.Year);
                while (!itm.EOF) //For each item
                {
                    var receivedoc = rec.GetDistinctUnitIDFromReceivedDoc(itm.ID);
                    foreach (var dr in receivedoc.Rows.Cast <DataRow>().Where(dr => !DoesBalanceExistByUnit(ethDate.Year, itm.ID, stores.ID, true, Convert.ToInt32(dr["UnitID"]))))
                    {
                        //need optimization
                        //we can exclude the already calculated items when we exclude never recieved items
                        yearEnd.LoadByItemIDStoreAndYearAndUnit(itm.ID, stores.ID, ethDate.Year, true, Convert.ToInt32(dr["UnitID"]));

                        if (yearEnd.RowCount > 0)
                        {
                            continue;
                        }

                        yearEnd.AddNew();
                        yearEnd.ItemID  = itm.ID;
                        yearEnd.StoreID = stores.ID;
                        yearEnd.Year    = ethDate.Year;

                        //need optimization
                        //atleast we can get the value directly by filtering using storeid and itemid rather than
                        //selecting all items in all stores and filter it by code
                        //yearEnd.EBalance = balance.GetSOHByUnit(itm.ID, stores.ID, ethDate.Month, ethDate.Year, Convert.ToInt32(dr["UnitID"]));
                        yearEnd.EBalance             = balance.GetSOHByUnitOptimized(itm.ID, stores.ID, ethDate.Month, ethDate.Year, Convert.ToInt32(dr["UnitID"]));
                        yearEnd.PhysicalInventory    = yearEnd.EBalance;
                        yearEnd.AutomaticallyEntered = true;
                        yearEnd.UnitID = Convert.ToInt32(dr["UnitID"]);
                        yearEnd.Save();
                    }
                    itm.MoveNext();
                }
                stores.MoveNext();
            }
        }
 /// <summary>
 /// Year End without the physical store information
 /// </summary>
 /// <param name="_itemID">The _item ID.</param>
 /// <param name="_storeID">The _store ID.</param>
 /// <param name="_unitID">The _unit ID.</param>
 /// <param name="_endingBal">The _ending bal.</param>
 /// <param name="_physicalInventory">The _physical inventory.</param>
 /// <param name="year">The year.</param>
 public static void AddNewYearEndEntry(int _itemID, int _storeID, int _unitID, long _endingBal, long _physicalInventory, int year)
 {
     BLL.YearEnd yEnd = new YearEnd();
     yEnd.AddNew();
     yEnd.StoreID           = _storeID;
     yEnd.ItemID            = _itemID;
     yEnd.UnitID            = _unitID;
     yEnd.PhysicalInventory = _physicalInventory;
     yEnd.EBalance          = _endingBal;
     yEnd.Year = year;
     yEnd.Save();
 }
 /// <summary>
 /// Year End without the physical store information
 /// </summary>
 /// <param name="_itemID">The _item ID.</param>
 /// <param name="_storeID">The _store ID.</param>
 /// <param name="_unitID">The _unit ID.</param>
 /// <param name="_endingBal">The _ending bal.</param>
 /// <param name="_physicalInventory">The _physical inventory.</param>
 /// <param name="year">The year.</param>
 public static void AddNewYearEndEntry(int _itemID, int _storeID, int _unitID, long _endingBal, long _physicalInventory, int year)
 {
     BLL.YearEnd yEnd = new YearEnd();
     yEnd.AddNew();
     yEnd.StoreID = _storeID;
     yEnd.ItemID = _itemID;
     yEnd.UnitID = _unitID;
     yEnd.PhysicalInventory = _physicalInventory;
     yEnd.EBalance = _endingBal;
     yEnd.Year = year;
     yEnd.Save();
 }
예제 #10
0
파일: YearEnd.cs 프로젝트: tomanye/facility
        public static void PurgeAutomaticallyEnteredInventory(int itemID, int storeID, int year)
        {
            YearEnd yearEnd = new YearEnd();

            yearEnd.Where.ItemID.Value  = itemID;
            yearEnd.Where.StoreID.Value = storeID;
            yearEnd.Where.Year.Value    = year;
            yearEnd.Where.AutomaticallyEntered.Value = true;
            yearEnd.Query.Load();
            yearEnd.DeleteAll();
            yearEnd.Save();
        }
        private void CboStoresSelectedValueChanged(object sender, EventArgs e)
        {
            if (lkActivity.EditValue != null)
            {
                YearEnd yEnd = new YearEnd();
                DataTable dtRec = yEnd.GetDistinctYear(Convert.ToInt32(lkActivity.EditValue));
                PopulateDocument(dtRec);

                dtRec = yEnd.GetDocumentAll(Convert.ToInt32(lkActivity.EditValue));
                lblAdjDate.Text = "All Years";
                PopulateTransactions(dtRec);
            }
        }
예제 #12
0
파일: YearEnd.cs 프로젝트: tomanye/facility
        public void GenerateAutomaticInventory()
        {
            var ethDate = new EthiopianDate.EthiopianDate();

            if (InventoryRequired(false))
            {
                Stores stores = new Stores();
                stores.GetActiveStores();
                while (!stores.EOF) //This needs to be done for each store
                {
                    if (!DoesBalanceExist(ethDate.Year, stores.ID, true))
                    //If Inventory information hasn't already been filled for this store
                    {
                        var itm = new Items();

                        //bereket
                        //itm.ExcludeNeverReceivedItemsNoCategory(stores.ID);
                        itm.ExcludeNeverReceivedItemsNoCategoryOptimized(stores.ID, ethDate.Year);
                        while (!itm.EOF) //For each time
                        {
                            var yearEnd = new YearEnd();
                            var balance = new Balance();

                            yearEnd.LoadByItemIDStoreAndYear(itm.ID, stores.ID, ethDate.Year, true);

                            if (yearEnd.RowCount > 0)
                            {
                                return;
                            }

                            //YearEnd.PurgeAutomaticallyEnteredInventory(itm.ID, stores.ID, ethDate.Year);
                            yearEnd.AddNew();
                            yearEnd.ItemID  = itm.ID;
                            yearEnd.StoreID = stores.ID;
                            yearEnd.Year    = ethDate.Year;

                            //bereket
                            //yearEnd.EBalance = balance.GetSOH(itm.ID, stores.ID, 10, ethDate.Year);
                            yearEnd.EBalance             = balance.GetSOHOptimized(itm.ID, stores.ID, 10, ethDate.Year);
                            yearEnd.PhysicalInventory    = yearEnd.EBalance;
                            yearEnd.AutomaticallyEntered = true;
                            yearEnd.UnitID = 0;
                            yearEnd.Save();
                            itm.MoveNext();
                        }
                    }
                    stores.MoveNext();
                }
            }
        }
        public DataTable BalanceAllItems(int storeId, int year, int month, string selectedType)
        {
            IssueDoc iss = new IssueDoc();
            ReceiveDoc rec = new ReceiveDoc();
            Disposal dis = new Disposal();
            YearEnd yEnd = new YearEnd();
            Items itm = new Items();
            DataTable dtResult = new DataTable();
            string[] col = { "FullItemName", "BBalance", "BBAmount", "ReceivedQty", "ReceivedAmount", "IssuedQty", "IssuedAmount", "LossesQty", "LossesAmount", "AdjustedQty", "AdjustedAmount", "SOH", "SOHAmount", "Received", "ID", "CategoryId", "SubCategoryID" };
            int i = 0;
            foreach (string s in col)
            {
                if (i > 0)
                {
                    dtResult.Columns.Add(s, typeof(double));
                }
                else
                {
                    dtResult.Columns.Add(s);
                }
                i++;
            }
            DataTable dtItem = ((selectedType == "Drug") ? itm.GetAllItems(1) : itm.GetAllSupply());
            foreach (DataRow dr in dtItem.Rows)
            {
                string itemName = dr["FullItemName"].ToString();// +" - " + dr["DosageForm"].ToString() + " - " + dr["Strength"].ToString();
                int itemId = Convert.ToInt32(dr["ID"]);
                Int64 bb = yEnd.GetBBalance(year, storeId, itemId, month);
                double bbAmount = yEnd.GetBBalanceAmount(year, storeId, itemId, month);
                Int64 recQuant = rec.GetReceivedQuantityTillMonth(itemId, storeId, month, year);
                double recPrice = rec.GetReceivedAmountTillMonth(itemId, storeId, month, year);
                Int64 issuedQuant = iss.GetIssuedQuantityTillMonth(itemId, storeId, month, year);
                double issPrice = iss.GetIssuedAmountTillMonth(itemId, storeId, month, year);
                Int64 lossQuant = dis.GetLossesQuantityTillMonth(itemId, storeId, month, year);
                double lossAmount = dis.GetLossesAmountTillMonth(itemId, storeId, month, year);
                Int64 adjQuant = dis.GetAdjustedQuantityTillMonth(itemId, storeId, month, year);
                double adjAmount = dis.GetAdjustedAmountTillMonth(itemId, storeId, month, year);
                Int64 SOH = bb + recQuant + adjQuant - issuedQuant - lossQuant;
                double SOHAmount = (bbAmount + recPrice + adjAmount - issPrice) - lossAmount;
                if (SOHAmount < 0)
                {
                    ;
                }

                int Isrec = ((bb == 0 && recQuant == 0) ? 0 : 1);
                object[] obj = { itemName, bb, bbAmount, recQuant, recPrice, issuedQuant, issPrice, lossQuant, lossAmount, adjQuant, adjAmount, SOH, SOHAmount, Isrec, itemId, Convert.ToInt32(dr["CategoryId"]), Convert.ToInt32(dr["SubCategoryID"]) };
                dtResult.Rows.Add(obj);
            }
            return dtResult;
        }
예제 #14
0
파일: YearEnd.cs 프로젝트: tomanye/facility
        public static void PurgeAutomaticallyEnteredInventoryForUnit(int itemID, int storeID, int year, int unitID)
        {
            YearEnd yearEnd = new YearEnd();

            yearEnd.Where.ItemID.Value  = itemID;
            yearEnd.Where.StoreID.Value = storeID;
            yearEnd.Where.Year.Value    = year;
            yearEnd.Where.AutomaticallyEntered.Value = true;
            yearEnd.Where.UnitID.Value = unitID;
            yearEnd.Query.Load();
            DataTable dt = yearEnd.DefaultView.ToTable();

            PurgeAutomaticallyEnteredInventoryDetail(dt);
            yearEnd.DeleteAll();
            yearEnd.Save();
        }
        /// <summary>
        /// Year End with the physical store information
        /// </summary>
        /// <param name="_itemID">The _item ID.</param>
        /// <param name="_storeID">The _store ID.</param>
        /// <param name="_unitID">The _unit ID.</param>
        /// <param name="_endingBal">The _ending bal.</param>
        /// <param name="_physicalInventory">The _physical inventory.</param>
        /// <param name="year">The year.</param>
        /// <param name="physicalStoreID">The physical store ID.</param>
        public static void AddNewYearEndEntry(int _itemID, int _storeID, int _unitID, long _endingBal, long _physicalInventory, int year, int physicalStoreID)
        {
            BLL.YearEnd yEnd = new YearEnd();
            yEnd.LoadByItemUnitStoreAndPhysicalStore(_itemID, _unitID, _storeID, physicalStoreID, year);

            if (yEnd.RowCount == 0)
                yEnd.AddNew();
            yEnd.StoreID = _storeID;
            yEnd.ItemID = _itemID;
            yEnd.UnitID = _unitID;
            yEnd.PhysicalInventory = _physicalInventory;
            yEnd.EBalance = _endingBal;
            yEnd.Year = year;
            yEnd.PhysicalStoreID = physicalStoreID;
            yEnd.Save();
        }
        /// <summary>
        /// Year End with the physical store information
        /// </summary>
        /// <param name="_itemID">The _item ID.</param>
        /// <param name="_storeID">The _store ID.</param>
        /// <param name="_unitID">The _unit ID.</param>
        /// <param name="_endingBal">The _ending bal.</param>
        /// <param name="_physicalInventory">The _physical inventory.</param>
        /// <param name="year">The year.</param>
        /// <param name="physicalStoreID">The physical store ID.</param>
        public static void AddNewYearEndEntry(int _itemID, int _storeID, int _unitID, long _endingBal, long _physicalInventory, int year, int physicalStoreID)
        {
            BLL.YearEnd yEnd = new YearEnd();
            yEnd.LoadByItemUnitStoreAndPhysicalStore(_itemID, _unitID, _storeID, physicalStoreID, year);

            if (yEnd.RowCount == 0)
            {
                yEnd.AddNew();
            }
            yEnd.StoreID           = _storeID;
            yEnd.ItemID            = _itemID;
            yEnd.UnitID            = _unitID;
            yEnd.PhysicalInventory = _physicalInventory;
            yEnd.EBalance          = _endingBal;
            yEnd.Year            = year;
            yEnd.PhysicalStoreID = physicalStoreID;
            yEnd.Save();
        }
        private void cboStores_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cboStores.SelectedValue == null) return;

            YearEnd yEnd = new YearEnd();
            DataTable dtRec = yEnd.GetDistinctYear(Convert.ToInt32(cboStores.SelectedValue));
            PopulateDocument(dtRec);

            dtRec = yEnd.GetDocumentAll(Convert.ToInt32(cboStores.SelectedValue));
            lblAdjDate.Text = @"All Years";
            if (dtRec.Rows.Count == 0)
            {
                txtEmpty.Visible = true;
                gridInventory.Visible = false;
            }
            else
            {
                gridInventory.Visible = true;
                gridInventory.DataSource = dtRec;
            }
        }
        private void BuildStoreInventoryListForHandleUnit(int year, int storeId, DataTable dtItm)
        {
            string[] str = { "Item Name", "Batch No.", "Remark" };
            foreach (string co in str)
            {
                dtBB.Columns.Add(co);
            }
            str = new string[] { "ItemId", "No.", "Beginning Balance", "Ending Balance(SOH)", "Physical Inventory", "ID", "RecID", "UnitID" };//, "Change Since Sene 30" };

            foreach (string co in str)
            {
                dtBB.Columns.Add(co, typeof(int));
            }
            int count = 1;
            var yProcess = new YearEnd();
            var bal = new Balance();

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

            var recDoc = new ReceiveDoc();
            int month = dtCurent.Month;

            if ((dtCurent.Month == 10 && dtCurent.Day == 30) || dtCurent.Month == 11)
            {
                btnSave.Enabled = ((!yProcess.IsInventoryComplete(year, storeId)));
               //btnSave.Enabled = true;
                month = 10;
            }
            else
                btnSave.Enabled = false;

            var yEnd = new YearEnd();
            foreach (DataRow dr in dtItm.Rows)//For each item
            {
                var itemName = dr["ItemName"].ToString() + " - " + dr["DosageForm"].ToString() + " - " + dr["Strength"].ToString();
                int itemId= Convert.ToInt32(dr["ID"]);
                var unitid = Convert.ToInt32(dr["UnitID"]);
                var BalanceExists = (yProcess.DoesBalanceExistByUnit(year, itemId,storeId, false,unitid));

                //We don't want to display those items whose inventory has already been done.
                if (BalanceExists)
                    continue;

               // Int64 soh = bal.GetSOHByUnit(Convert.ToInt32(dr["ID"]), storeId, month, year,unitid);
                Int64 soh = bal.GetSOHByUnitOptimized(Convert.ToInt32(dr["ID"]), storeId, month, year, unitid);
                Int64 bbal = yEnd.GetBBalanceByUnit(year, storeId, Convert.ToInt32(dr["ID"]), month,unitid);

                yProcess.GetBalanceByItemIdByUnitID(year, storeId, Convert.ToInt32(dr["ID"]),unitid);

                Int64 BB = (yProcess.RowCount > 0) ? yProcess.BBalance : bbal;
                Int64 EB = ((yProcess.RowCount > 0 && yProcess.EBalance != 0) ? yProcess.EBalance : soh);
                string Phy = (yProcess.RowCount > 0) ? yProcess.PhysicalInventory.ToString() : (_defaultValueToPhysicalInventory ? EB.ToString() : "");
                string remark = (yProcess.RowCount > 0) ? yProcess.Remark : "";

                DataRowView drv = dtBB.DefaultView.AddNew();
                if (yProcess.RowCount > 0)
                {
                    drv["ID"] = yProcess.ID;
                }
                drv["ItemId"] = dr["ID"];
                drv["No."] = count;
                drv["Item Name"] = itemName;
                drv["Beginning Balance"] = BB;
                drv["Ending Balance(SOH)"] = EB;
                drv["UnitID"] = unitid;

                if (Phy != "")
                {
                    drv["Physical Inventory"] = Phy;
                }
                drv["RecID"] = -1;
                drv["Remark"] = remark;
                count++;

                int theLastBalance = 0;
                DataTable dtBatchs = recDoc.GetBatchWithValueByUnit(storeId, Convert.ToInt32(dr["ID"]), dtCurent ,unitid);
                foreach (DataRow drBatch in dtBatchs.Rows) //For each batch
                {
                    if (drBatch["QuantityLeft"] != DBNull.Value && Convert.ToInt64(drBatch["QuantityLeft"]) != 0)
                    {
                       drv = dtBB.DefaultView.AddNew();

                        drv["Item Name"] = ">>";
                        drv["UnitID"] =drBatch["UnitID"];
                        drv["Batch No."] = drBatch["BatchNo"];
                        drv["Ending Balance(SOH)"] = Convert.ToInt64(drBatch["QuantityLeft"]);
                        //Now if the physical inventory is chosen to be default value, we set it to the ending balance of last year.
                        if (_defaultValueToPhysicalInventory)
                            drv["Physical Inventory"] = drBatch["QuantityLeft"].ToString();

                        theLastBalance += Convert.ToInt32(drBatch["QuantityLeft"]);
                        drv["RecID"] = drBatch["ID"];
                    }
                }
                //}
            }

            grdYearEnd.DataSource = dtBB;
            dtDate.CustomFormat = "MMMM dd, yyyy"; //throw new NotImplementedException();
        }
 /// <summary>
 /// Updates the year end value.
 /// </summary>
 /// <param name="yearEndQuantity2">The year end quantity2.</param>
 /// <param name="itemID">The item ID.</param>
 /// <param name="unitID">The unit ID.</param>
 /// <param name="year">The year.</param>
 public static void UpdateYearEndValue(long yearEndQuantity2, int itemID, int unitID,int year)
 {
     string query = HCMIS.Repository.Queries.YearEnd.UpdateUpdateYearEndValue(yearEndQuantity2, itemID, unitID, year);
     BLL.YearEnd ye = new YearEnd();
     ye.LoadFromRawSql(query);
 }
        /// <summary>
        /// Change the UnitID of one item to another UnitID.
        /// </summary>
        /// <param name="storeID"></param>
        /// <param name="itemID"></param>
        /// <param name="fromUnitID"></param>
        /// <param name="toUnitID"></param>
        public static void ChangeItemUnit(int storeID, int itemID, int fromUnitID, int toUnitID)
        {
            MyGeneration.dOOdads.TransactionMgr transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
            try
            {
                transaction.BeginTransaction();
                ItemUnit iuFrom = new ItemUnit(), iuTo = new ItemUnit(), iuExecute = new ItemUnit();
                iuFrom.LoadByPrimaryKey(fromUnitID);
                iuTo.LoadByPrimaryKey(toUnitID);

                var receiveTableFilterQuery = HCMIS.Repository.Queries.ItemUnit.SelectChangeItemUnit(storeID, itemID, iuFrom.ID);

                string query;
                // Update Issue Doc
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitIssueDoc(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);
                iuExecute.LoadFromRawSql(query);

                // Update disposal table
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitLossAndAdjustment(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);
                iuExecute.LoadFromRawSql(query);

                // Update Order.
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitOrderDetail(itemID, iuFrom.ID, iuFrom.QtyPerUnit, iuTo.QtyPerUnit);

                iuExecute.LoadFromRawSql(query);

                // Update Pick List Detail
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitPickListDetail(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);

                iuExecute.LoadFromRawSql(query);

                // change the Weighted Average Log
                try
                {
                    query = HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitMovingAverageHistory(storeID, iuTo.ID, iuFrom.ID);

                    iuExecute.LoadFromRawSql(query);
                }

                catch
                {

                }

                BLL.ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByItemIDUnitIDStoreID(itemID, iuFrom.ID, storeID);
                rd.ChangeUnitID(iuTo.ID);

                //Change the YearEnd
                //If there is already an entry with the other UnitID, we need to merge the two.

                BLL.YearEnd yEndFrom = new YearEnd();
                yEndFrom.Where.UnitID.Value = iuFrom.ID;
                yEndFrom.Where.ItemID.Value = itemID;
                yEndFrom.Where.StoreID.Value = storeID;
                yEndFrom.Query.Load();

                if (yEndFrom.RowCount > 0)
                {
                    //There is a year end entry.
                    //If there is one by the new UnitID, we merge them.  If there is no entry by the new UnitID, we just change the values.
                    BLL.YearEnd yEndTo = new YearEnd();
                    yEndTo.Where.UnitID.Value = iuTo.ID;
                    yEndTo.Where.ItemID.Value = itemID;
                    yEndTo.Where.StoreID.Value = storeID;
                    yEndTo.Query.Load();
                    if (yEndTo.RowCount > 0)
                    {
                        //We need to merge.
                        if (!yEndTo.IsColumnNull("EndingPrice"))
                            yEndTo.EndingPrice += yEndFrom.EndingPrice;
                        else
                            yEndTo.EndingPrice = yEndFrom.EndingPrice;
                        if (!yEndTo.IsColumnNull("EBalance"))
                            yEndTo.EBalance += yEndFrom.EBalance;
                        else
                            yEndTo.EBalance = yEndFrom.EBalance;
                        if (!yEndTo.IsColumnNull("PhysicalInventory"))
                            yEndTo.PhysicalInventory += yEndFrom.PhysicalInventory;
                        else
                            yEndTo.PhysicalInventory = yEndFrom.PhysicalInventory;
                        if (!yEndTo.IsColumnNull("PhysicalInventoryPrice"))
                            yEndTo.PhysicalInventoryPrice += yEndFrom.PhysicalInventoryPrice;
                        else
                            yEndTo.PhysicalInventoryPrice = yEndFrom.PhysicalInventoryPrice;

                        yEndTo.Save();
                        yEndFrom.MarkAsDeleted();
                        yEndFrom.Save();
                    }
                    else
                    {
                        yEndFrom.UnitID = iuTo.ID;
                        yEndFrom.Save();
                    }
                }
                transaction.CommitTransaction();
            }
            catch(Exception ex)
            {
                transaction.RollbackTransaction();
                throw ex;
            }
        }
 public long GetBeginningBalanceByUnit(int year, int item, int storeID,int unitID)
 {
     var yearEnd = new YearEnd();
     yearEnd.LoadByItemIDStoreAndYearAndUnit(item, storeID, year - 1, false,unitID);
     if (yearEnd.RowCount > 0)
     {
         return yearEnd.PhysicalInventory;
     }
     return 0;
 }
        /// <summary>
        /// Handles the processing of balance
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProcessBalance_Click(object sender, EventArgs e)
        {
            Items itm = new Items();
            YearEnd yEnd = new YearEnd();
            Balance bal = new Balance();

            DataTable dtItm = itm.GetAllItems(1);
            dtDate.Value = DateTime.Now;
            DateTime dtCurent = Convert.ToDateTime(dtDate.Text);

            foreach (DataRow dr in dtItm.Rows)
            {
                yEnd.AddNew();
                yEnd.StoreID = Convert.ToInt32(cboStore.SelectedValue);
                yEnd.ItemID = Convert.ToInt32(dr["ID"]);
                yEnd.Year = Convert.ToInt32(cboYear.SelectedItem);
                yEnd.Month = (Convert.ToInt32(cboYear.SelectedItem) == dtCurent.Year) ? dtCurent.Month : 10;
                yEnd.BBalance = 0;
                yEnd.EBalance = 0;
                yEnd.PhysicalInventory = 0;
                yEnd.Save();
            }
        }
        /// <summary>
        /// Gets SOH of a specific item for the end of the specified Ethipian Fiscal Month Item
        /// </summary>
        /// <param name="itemId"></param>
        /// <param name="storeId"></param>
        /// <param name="month"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        public Int64 GetSOHOld(int itemId, int storeId, int month, int year)
        {
            //ask by normal u get soh on normal month
            IssueDoc iss = new IssueDoc();
            ReceiveDoc rec = new ReceiveDoc();
            Disposal dis = new Disposal();
            YearEnd yEnd = new YearEnd();
            //int month = (mon > 2) ? mon - 2 : ((mon == 1) ? 11 : 12);
            //int year = (mon > 2) ? yr : yr - 1;
            Int64 cons = 0;
            long recievedQuantity = rec.GetReceivedQuantityTillMonth(itemId, storeId, month, year);
            long adjustedQuantity = dis.GetAdjustedQuantityTillMonth(itemId, storeId, month, year);
            long issuedQuantity = iss.GetIssuedQuantityTillMonth(itemId, storeId, month, year);
            long lossQuantity = dis.GetLossesQuantityTillMonth(itemId, storeId, month, year);
            long balanceQuantity = yEnd.GetBBalance(year, storeId, itemId, month);
            cons = (balanceQuantity + recievedQuantity + adjustedQuantity - issuedQuantity - lossQuantity);
            this.FlushData();
            // this.LoadFromRawSql(String.Format("SELECT SUM(QuantityLeft) AS Quantity FROM ReceiveDoc WHERE (ItemID = {0}) AND (StoreID = {1} AND ((Month(Date) <= {2} AND Year(Date) = {3}) OR (Month(Date) > 10 AND Year(Date) = {4})))", itemId, storeId, month, year, year - 1));

            // cons = (this.DataTable.Rows[0]["Quantity"].ToString() != "") ? Convert.ToInt64(this.DataTable.Rows[0]["Quantity"]) : 0;

            return cons;
        }
        /* 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 cboStores_EditValueChanged(object sender, EventArgs e)
 {
     var inventory = new YearEnd();
     if (inventory.IsInventoryCompleteToReceive(2006, Convert.ToInt32(cboStores.EditValue)) != false) return;
         XtraMessageBox.Show("Please First Finish All Inventory and come back!","Error", MessageBoxButtons.OK , MessageBoxIcon.Exclamation);
         btnSave.Enabled = false;
 }
        /// <summary>
        /// Generates the charts one by one.
        /// </summary>
        /// <param name="du"></param>
        private void GenerateCharts(int du)
        {
            Balance bal = new Balance();
            GeneralInfo info = new GeneralInfo();
            info.LoadAll();
            DataTable dtList = new DataTable();
            DataTable dtAmc = new DataTable();
            DataTable dtMOS = new DataTable();
            DataTable dtIss = new DataTable();
            DataTable dtRec = new DataTable();
            DataTable dtBB = new DataTable();
            //CALENDAR:
            //  DataTable dtCons = new DataTable();
            string[] co = { "Ham", "Neh", "Mes", "Tek", "Hed", "Tah", "Tir", "Yek", "Meg", "Miz", "Gen", "Sen" };

            //foreach(string s in co)
            //{
            dtList.Columns.Add("Month");
            dtList.Columns.Add("Value");
            dtList.Columns[1].DataType = typeof(Int64);

            dtMOS.Columns.Add("Month");
            dtMOS.Columns.Add("Value");
            dtMOS.Columns[1].DataType = typeof(decimal);

            dtAmc.Columns.Add("Month");
            dtAmc.Columns.Add("Value");
            dtAmc.Columns[1].DataType = typeof(Int64);

            dtIss.Columns.Add("Month");
            dtIss.Columns.Add("Value");
            dtIss.Columns[1].DataType = typeof(Int64);

            dtRec.Columns.Add("Month");
            dtRec.Columns.Add("Value");
            dtRec.Columns[1].DataType = typeof(Int64);

            dtBB.Columns.Add("Month");
            dtBB.Columns.Add("Value");
            dtBB.Columns[1].DataType = typeof(Int64);

            int[] mon = { 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            long[] cons = new long[12];
            double[] amc = new double[12];
            long[] con = new long[12];
            long[] issval = new long[12];
            DataTable dtBal = new DataTable();
            IssueDoc issd = new IssueDoc();
            Items recd = new Items();
            YearEnd yEnd = new YearEnd();
            Int64 bb = yEnd.GetBBalance(_year, _storeId, _itemId, 10);
            object[] objBB = { "Ham", bb };
            dtBB.Rows.Add(objBB);
            //dtDate.Value = DateTime.Now;
            //dtDate.CustomFormat = "MM/dd/yyyy";
            //DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);

            for (int i = 0; i < mon.Length; i++)
            {
                int cMonth = _dtCurrent.Month;
                //if (!(year == dtCurrent.Year && mon[i] > dtCurrent.Month && mon[i] < 11))
                if (((mon[i] == 11 || mon[i] == 12) && (mon[i] <= cMonth || _year == _dtCurrent.Year)) || (mon[i] < 11 && mon[i] <= cMonth && _year == _dtCurrent.Year))
                {
                    int yr = (mon[i] < 11) ? _year : _year - 1;
                    // dtBal = bal.GetSOH(itemId,storeId,mon[i],yr);
                    con[i] = ((du == 0) ? bal.GetSOH(_itemId, _storeId, mon[i], yr) : bal.GetDUSOH(_itemId, du, mon[i], yr));
                    object xSOH = null;
                    if (con[i] == 0)
                    {
                        for (int li = i; li >= 0; li--)
                        {
                            if (con[li] != 0)
                            {
                                xSOH = 0;
                                break;
                            }
                        }
                    }
                    else
                        xSOH = con[i];
                    object[] str = { co[i], xSOH };
                    amc[i] = ((du == 0) ? Builder.CalculateAverageConsumption(_itemId, _storeId, _dtCurrent.Subtract(TimeSpan.FromDays(180)), _dtCurrent, CalculationOptions.Monthly) : bal.CalculateDUAMC(_itemId, du, mon[i], yr, 0));//bal.CalculateAMC(_itemId, _storeId, mon[i], yr)
                    object xAmc = null;
                    if (amc[i] == 0)
                    {
                        for (int li = i; li >= 0; li--)
                        {
                            if (amc[li] != 0)
                            {
                                xAmc = 0;
                                break;
                            }
                        }
                    }
                    else
                        xAmc = amc[i];
                    object[] objAmc = { co[i], xAmc };

                    // for mos check the diff b/n null and zero
                    // And also mos = soh/amc right???
                    decimal mos = (amc[i] > 0) ? (Convert.ToDecimal(con[i]) / Convert.ToDecimal(amc[i])) : 0;
                    object[] objMos = { co[i], mos };
                    int fYear = (mon[i] < 11) ? yr : yr - 1;

                    issval[i] = ((du == 0) ? issd.GetIssuedQuantityByMonth(_itemId, _storeId, mon[i], yr) : issd.GetDUConsumptionByMonth(_itemId, du, mon[i], yr));
                    object xIss = null;
                    if (issval[i] == 0)
                    {
                        for (int li = i; li >= 0; li--)
                        {
                            if (issval[li] != 0)
                            {
                                xIss = 0;
                                break;
                            }
                        }
                    }
                    else
                        xIss = issval[i];
                    object[] objIss = { co[i], xIss };

                    Int64 recVal = ((du == 0) ? recd.GetQuantityReceiveByItemPerMonth(mon[i], _itemId, _storeId, yr) : issd.GetDUReceiveByMonth(_itemId, du, mon[i], yr));
                    object[] objrec = { co[i], recVal };

                    dtList.Rows.Add(str);
                    dtAmc.Rows.Add(objAmc);
                    dtMOS.Rows.Add(objMos);
                    dtIss.Rows.Add(objIss);
                    dtRec.Rows.Add(objrec);
                }
            }

            // string[] str = { ((cons[0] != 0) ? cons[0].ToString("") : "0"), ((cons[1] != 0) ? cons[1].ToString() : "0"), ((cons[2] != 0) ? cons[2].ToString() : "0"), ((cons[3] != 0) ? cons[3].ToString() : "0"), ((cons[4] != 0) ? cons[4].ToString() : "0"), ((cons[5] != 0) ? cons[5].ToString() : "0"), ((cons[6] != 0) ? cons[6].ToString() : "0"), ((cons[7] != 0) ? cons[7].ToString() : "0"), ((cons[8] != 0) ? cons[8].ToString() : "0"), ((cons[9] != 0) ? cons[9].ToString() : "0"), ((cons[10] != 0) ? cons[10].ToString() : "0"), ((cons[11] != 0) ? cons[11].ToString() : "0")};
            chartAmc.Series.Clear(); //AMC
            chartComp.Series.Clear();//Activity
            chartBar.Series.Clear(); //SOH
            chartMOS.Series.Clear(); // MOS
            consuTrend.Series.Clear();

            Series ser = new Series("Stock On Hand", ViewType.Line);
            ser.DataSource = dtList;
            ser.ArgumentScaleType = ScaleType.Qualitative;
            ser.ArgumentDataMember = "Month";
            ser.ValueScaleType = ScaleType.Numerical;
            ser.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            ser.PointOptions.ValueNumericOptions.Precision = 0;
            ser.ValueDataMembers.AddRange(new string[] { "Value" });

            chartBar.Series.Add(ser);
            ((XYDiagram)chartBar.Diagram).AxisY.NumericOptions.Format = NumericFormat.Number;
            ((XYDiagram)chartBar.Diagram).AxisY.NumericOptions.Precision = 0;

            Series serB = new Series("Begining Balance", ViewType.Bar);
            serB.DataSource = dtBB;
            serB.ArgumentScaleType = ScaleType.Qualitative;
            serB.ArgumentDataMember = "Month";
            serB.ValueScaleType = ScaleType.Numerical;
            serB.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            serB.PointOptions.ValueNumericOptions.Precision = 0;
            serB.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serB);

            Series serRec = new Series("Received Qty", ViewType.Bar);
            serRec.DataSource = dtRec;
            serRec.ArgumentScaleType = ScaleType.Qualitative;
            serRec.ArgumentDataMember = "Month";
            serRec.ValueScaleType = ScaleType.Numerical;
            serRec.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            serRec.PointOptions.ValueNumericOptions.Precision = 0;
            serRec.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serRec);

            Series serAmc = new Series("AMC", ViewType.Line);
            serAmc.DataSource = dtAmc;
            serAmc.ArgumentScaleType = ScaleType.Qualitative;
            serAmc.ArgumentDataMember = "Month";
            serAmc.ValueScaleType = ScaleType.Numerical;
            serAmc.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            serAmc.PointOptions.ValueNumericOptions.Precision = 0;
            serAmc.ValueDataMembers.AddRange(new string[] { "Value" });
            chartAmc.Series.Add(serAmc);
            ((XYDiagram)chartAmc.Diagram).AxisY.NumericOptions.Format = NumericFormat.Number;
            ((XYDiagram)chartAmc.Diagram).AxisY.NumericOptions.Precision = 0;

            Series serIss = new Series("Issue Qty", ViewType.Bar);
            serIss.DataSource = dtIss;
            serIss.ArgumentScaleType = ScaleType.Qualitative;
            serIss.ArgumentDataMember = "Month";
            serIss.ValueScaleType = ScaleType.Numerical;
            serIss.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            serIss.PointOptions.ValueNumericOptions.Precision = 0;
            serIss.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serIss);

            //Int64 amcCurent = bal.CalculateAMC(_itemId, _storeId, _dtCurrent.Month, _dtCurrent.Year);
            double amcCurent = Builder.CalculateAverageConsumption(_itemId, _storeId,
                                                                   _dtCurrent.Subtract(TimeSpan.FromDays(180)),
                                                                   _dtCurrent, CalculationOptions.Monthly);
            double min = info.Min * amcCurent;
            double max = info.Max * amcCurent;
            Int64 nearEOP = Convert.ToInt64(amcCurent * (info.EOP + 0.25));
            ConstantLine target = new ConstantLine();
            ConstantLine targetEOP = new ConstantLine();
            target.AxisValue = min;
            //which min and max to show month
            ((XYDiagram)chartComp.Diagram).AxisY.ConstantLines.Clear();
            target.Visible = true;
            target.Title.Text = "Current Min value is " + Convert.ToInt64(target.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            target.Color = Color.Red;
            target.LineStyle.Thickness = 2;
            target.LegendText = "Min";
            ((XYDiagram)chartComp.Diagram).AxisY.ConstantLines.Add(target);

            targetEOP = new ConstantLine();
            targetEOP.AxisValue = nearEOP;
            //which min and max to show month
            //((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Clear();
            targetEOP.Visible = true;
            targetEOP.Title.Text = "Current EOP value is " + Convert.ToInt64(targetEOP.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            targetEOP.Color = Color.Yellow;
            targetEOP.LineStyle.Thickness = 2;
            targetEOP.LegendText = "EOP";
            ((XYDiagram)chartComp.Diagram).AxisY.ConstantLines.Add(targetEOP);

            ConstantLine targetMax = new ConstantLine();
            targetMax.AxisValue = max;
            //which min and max to show month
            targetMax.Visible = true;
            targetMax.Title.Text = "Current Max value is " + Convert.ToInt64(targetMax.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            targetMax.Color = Color.Blue;
            targetMax.LineStyle.Thickness = 2;
            targetMax.LegendText = "Max";
            ((XYDiagram)chartComp.Diagram).AxisY.ConstantLines.Add(targetMax);

            Series sercons = new Series("Consumption", ViewType.Line);
            sercons.DataSource = dtIss;
            sercons.ArgumentScaleType = ScaleType.Qualitative;
            sercons.ArgumentDataMember = "Month";
            sercons.ValueScaleType = ScaleType.Numerical;
            sercons.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            sercons.PointOptions.ValueNumericOptions.Precision = 0;
            sercons.ValueDataMembers.AddRange(new string[] { "Value" });
            consuTrend.Series.Add(sercons);
            ((XYDiagram)consuTrend.Diagram).AxisY.NumericOptions.Format = NumericFormat.Number;
            ((XYDiagram)consuTrend.Diagram).AxisY.NumericOptions.Precision = 0;

            Series serSOH = new Series("SOH", ViewType.Bar);
            serSOH.DataSource = dtList;
            serSOH.ArgumentScaleType = ScaleType.Qualitative;
            serSOH.ArgumentDataMember = "Month";
            serSOH.ValueScaleType = ScaleType.Numerical;
            serSOH.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            ((XYDiagram)chartComp.Diagram).AxisY.NumericOptions.Format = NumericFormat.Number;
            ((XYDiagram)chartComp.Diagram).AxisY.NumericOptions.Precision = 0;
            serSOH.PointOptions.ValueNumericOptions.Precision = 0;

            serSOH.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serSOH);

            Series serMos = new Series("Month Of Stock", ViewType.Line);
            serMos.DataSource = dtMOS;
            serMos.ArgumentScaleType = ScaleType.Qualitative;
            serMos.ArgumentDataMember = "Month";
            serMos.ValueScaleType = ScaleType.Numerical;
            serMos.PointOptions.ValueNumericOptions.Format = NumericFormat.FixedPoint;
            serMos.PointOptions.ValueNumericOptions.Precision = 1;
            serMos.ValueDataMembers.AddRange(new string[] { "Value" });

            chartMOS.Series.Add(serMos);
            if (Convert.ToInt32(((XYDiagram)chartMOS.Diagram).AxisY.Range.MaxValue) <= 12)
            {
                ((XYDiagram)chartMOS.Diagram).AxisY.Range.MaxValue = 12;
            }

            //Int64 soh = bal.GetSOH(itemId,storeId,dtCurrent.Month,year);
            //if (bal.RowCount > 0)
            //{
            //Int64 amcCurent = bal.CalculateAMC(_itemId, _storeId, _dtCurrent.Month, _year);
            amcCurent = Builder.CalculateAverageConsumption(_itemId, _storeId,
                                                                  _dtCurrent.Subtract(TimeSpan.FromDays(180)),
                                                                  _dtCurrent, CalculationOptions.Monthly);
            min = info.Min * amcCurent;
            max = info.Max * amcCurent;
            nearEOP = Convert.ToInt64(amcCurent * (info.EOP + 0.25));
            target = new ConstantLine();
            target.AxisValue = min;
            //which min and max to show month
            ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Clear();
            target.Visible = true;
            target.Title.Text = "Current Min value is " + Convert.ToInt64(target.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            target.Color = Color.Red;
            target.LineStyle.Thickness = 2;
            target.LegendText = "Min";
            ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Add(target);

            targetEOP = new ConstantLine();
            targetEOP.AxisValue = nearEOP;
            //which min and max to show month
            //((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Clear();
            targetEOP.Visible = true;
            targetEOP.Title.Text = "Current EOP value is " + Convert.ToInt64(targetEOP.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            targetEOP.Color = Color.Yellow;
            targetEOP.LineStyle.Thickness = 2;
            targetEOP.LegendText = "EOP";
            ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Add(targetEOP);

            targetMax = new ConstantLine();
            targetMax.AxisValue = max;
            //which min and max to show month
            targetMax.Visible = true;
            targetMax.Title.Text = "Current Max value is " + Convert.ToInt64(targetMax.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            targetMax.Color = Color.Blue;
            targetMax.LineStyle.Thickness = 2;
            targetMax.LegendText = "Max";
            ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Add(targetMax);

            ConstantLine targetMos = new ConstantLine();
            ConstantLine targetMosMin = new ConstantLine();
            ((XYDiagram)chartMOS.Diagram).AxisY.ConstantLines.Clear();
            targetMos = new ConstantLine();
            targetMos.AxisValue = info.Max;
            //which min and max to show month
            targetMos.Visible = true;
            targetMos.Title.Text = "Current Max is " + info.Max.ToString() + " months";
            targetMos.Color = Color.Blue;
            targetMos.LineStyle.Thickness = 2;
            targetMos.LegendText = "Max";
            ((XYDiagram)chartMOS.Diagram).AxisY.ConstantLines.Add(targetMos);

            targetMosMin = new ConstantLine();
            targetMosMin.AxisValue = info.Min;
            //which min and max to show month
            targetMosMin.Visible = true;
            targetMosMin.Title.Text = "Current Min is " + info.Min.ToString() + " months";
            targetMosMin.Color = Color.Red;
            targetMosMin.LineStyle.Thickness = 2;
            targetMosMin.LegendText = "Max";
            ((XYDiagram)chartMOS.Diagram).AxisY.ConstantLines.Add(targetMosMin);
            //}

            // Generate the pie Chart for the Current SOH and EXpired Drugs

            ReceiveDoc rec = new ReceiveDoc();
            chartPie.Series.Clear();
            Items itm = new Items();
            object[] objExp = itm.GetExpiredQtyAmountItemsByID(_itemId, _storeId);
            Int64 expAmount = Convert.ToInt64(objExp[0]);
            Double expCost = Convert.ToDouble(objExp[1]);

            object[] nearObj = itm.GetNearlyExpiredQtyAmountItemsByID(_itemId, _storeId);
            Int64 nearExpAmount = Convert.ToInt64(nearObj[0]);
            double nearExpCost = Convert.ToDouble(nearObj[1]);

            Int64 soh = bal.GetSOH(_itemId, _storeId, _dtCurrent.Month, _dtCurrent.Year);
            double sohPrice = bal.GetSOHAmount(_itemId, _storeId, _dtCurrent.Month, _dtCurrent.Year);

            Int64 normal = (soh - nearExpAmount - expAmount);
            Int64 nearExpiry = nearExpAmount;
            Int64 expired = expAmount;

            object[] obj = { normal, nearExpiry, expired };

            DataTable dtSOHList = new DataTable();
            dtSOHList.Columns.Add("Type");
            dtSOHList.Columns.Add("Value");
            dtSOHList.Columns[1].DataType = typeof(Int64);
            double normalPrice = (sohPrice - nearExpCost - expAmount);

            object[] oo = { "Normal : " + normalPrice.ToString("C"), obj[0] };
            dtSOHList.Rows.Add(oo);

            object[] oo3 = { "Expired : " + expCost.ToString("C"), obj[2] };
            dtSOHList.Rows.Add(oo3);

            object[] oo2 = { "Near Expiry : " + nearExpCost.ToString("C"), obj[1] };
            dtSOHList.Rows.Add(oo2);

            Series serExpired = new Series("pie", ViewType.Pie3D);
            if (!(Convert.ToInt32(obj[0]) == 0 && Convert.ToInt32(obj[1]) == 0 && Convert.ToInt32(obj[2]) == 0))
            {
                serExpired.DataSource = dtSOHList;

                serExpired.ArgumentScaleType = ScaleType.Qualitative;
                serExpired.ArgumentDataMember = "Type";
                serExpired.ValueScaleType = ScaleType.Numerical;
                serExpired.ValueDataMembers.AddRange(new string[] { "Value" });
                serExpired.PointOptions.PointView = PointView.ArgumentAndValues;
                serExpired.LegendText = "Key";
                serExpired.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
                serExpired.PointOptions.ValueNumericOptions.Precision = 0;
                ((PieSeriesLabel)serExpired.Label).Position = PieSeriesLabelPosition.TwoColumns;
                // ((PieSeriesLabel)serExpired.Label).ColumnIndent = 2;
                ((PiePointOptions)serExpired.PointOptions).PointView = PointView.ArgumentAndValues;
                // ((PiePointOptions)serExpired.PointOptions).Separator = " , ";
                chartPie.Series.Add(serExpired);
                chartPie.Size = new System.Drawing.Size(1000, 500);
            }
        }
        private void btnDoEndOfYear_Click(object sender, EventArgs e)
        {
            var result = XtraMessageBox.Show("Are you sure you want to perform the year End activity automatically?",
                                             "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if(result==System.Windows.Forms.DialogResult.No)
            {
                return;
            }

            var confirm =
                XtraMessageBox.Show(
                    "Performing the year end automatically will make HCMIS take the present stock as the beginning balance of the next fiscal year.  You will not be able to use the Inventory page to input inventory data.  Do you want to proceed?",
                    "Confirmation", MessageBoxButtons.YesNo);
            if(confirm==DialogResult.No)
            {
                return;
            }

            btnDoEndOfYear.Enabled = false;
            int year = ConvertDate.GetEthiopianYear(DateTimeHelper.ServerDateTime);
            Activity stores = new Activity();
            stores.LoadAll();

            BLL.CommodityType commodityType = new BLL.CommodityType();
            commodityType.LoadAll();

            while (!commodityType.EOF)
            {
                while (!stores.EOF)
                {
                    DataTable dtbl = Balance.GetSohForAllItems(stores.ID, commodityType.ID, year, 10);
                    YearEnd ye = new YearEnd();
                    foreach (DataRow dr in dtbl.Rows)
                    {
                        if (dr["ID"] == DBNull.Value || dr["UnitID"] == DBNull.Value)
                            continue;

                        ye.AddNew();

                        ye.ItemID = Convert.ToInt32(dr["ID"]);
                        ye.UnitID = Convert.ToInt32(dr["UnitID"]);
                        ye.StoreID = stores.ID;
                        ye.Year = year;

                        ye.PhysicalInventory = ye.EBalance = Convert.ToInt32(dr["SOH"]);
                        ye.PhysicalInventoryPrice = ye.EndingPrice = Convert.ToDecimal(Convert.ToDouble(dr["Price"]));
                        ye.Save();
                    }
                    stores.MoveNext();
                }
                commodityType.MoveNext();
            }
            XtraMessageBox.Show("Year End has been populated");
            btnDoEndOfYear.Enabled = !BLL.YearEnd.IsPerformedForYear(EthiopianDate.EthiopianDate.Now.Year);
        }
        /// <summary>
        /// Validate the input based on which tab is active right now. And retuns true if input is valid.
        /// When the input is invalid, the function returns false.
        /// </summary>
        /// <returns>True - If input is valid, False - If input is invalid</returns>
        private bool Validation()
        {
            var inventory = new YearEnd();
            if (_tabPage == 0)
            {
                if (_dtSelectedTable != null && _dtSelectedTable.Rows.Count > 0 && gridItemChoiceView.SelectedRowsCount > 0)
                {
                    PopulateGridList();
                }
                else
                {
                    XtraMessageBox.Show("You must select a drug to populate.", "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return false;
                }
            }
            else if (_tabPage == 1)
            {
                if (tabControl1.SelectedTabPageIndex != 1)
                    _tabPage = tabControl1.SelectedTabPageIndex;
                if (tabControl1.SelectedTabPageIndex == 2)
                {
                    PopulatePickList();

                }
            }
            else if (_tabPage == 2)
            {
                if (tabControl1.SelectedTabPageIndex != 2)
                    _tabPage = tabControl1.SelectedTabPageIndex;
            }
            else if(inventory.DoesBalanceExist(2006 ,10 ,false) ==false)
            {
                XtraMessageBox.Show("You must enter Inventory data before issue.", "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
            return true;
        }
        public double GetSOHAmount(int itemId, int storeId, int month, int year)
        {
            //ask by normal u get soh on normal month
            IssueDoc iss = new IssueDoc();
            ReceiveDoc rec = new ReceiveDoc();
            Disposal dis = new Disposal();
            YearEnd yEnd = new YearEnd();
            //int month = (mon > 2) ? mon - 2 : ((mon == 1) ? 11 : 12);
            //int year = (mon > 2) ? yr : yr - 1;
            double cons = 0;
            cons = (yEnd.GetBBalanceAmount(year, storeId, itemId, month) + rec.GetReceivedAmount(itemId, storeId, year) + dis.GetAdjustedAmount(itemId, storeId, year) - iss.GetIssuedAmount(itemId, storeId, year) - dis.GetLossesAmount(itemId, storeId, year));
            this.FlushData();
            // this.LoadFromRawSql(String.Format("SELECT SUM(QuantityLeft) AS Quantity FROM ReceiveDoc WHERE (ItemID = {0}) AND (StoreID = {1} AND ((Month(Date) <= {2} AND Year(Date) = {3}) OR (Month(Date) > 10 AND Year(Date) = {4})))", itemId, storeId, month, year, year - 1));

            // cons = (this.DataTable.Rows[0]["Quantity"].ToString() != "") ? Convert.ToInt64(this.DataTable.Rows[0]["Quantity"]) : 0;

            return cons;
        }
 public Int64 GetSOHAll(int itemId, int month, int year)
 {
     //ask by normal u get soh on normal month
     IssueDoc iss = new IssueDoc();
     ReceiveDoc rec = new ReceiveDoc();
     Disposal dis = new Disposal();
     YearEnd yEnd = new YearEnd();
     Int64 cons = 0;
     cons = (yEnd.GetBBalanceAll(year, itemId) + rec.GetReceivedQuantityTillMonthAll(itemId, month, year) + dis.GetAdjustedQuantityTillMonthAll(itemId, month, year) - iss.GetIssuedQuantityTillMonthAll(itemId, month, year) - dis.GetLossesQuantityTillMonthAll(itemId, month, year));
     this.FlushData();
     return cons;
 }
        /// <summary>
        /// Change the UnitID of one item to another UnitID.
        /// </summary>
        /// <param name="storeID"></param>
        /// <param name="itemID"></param>
        /// <param name="fromUnitID"></param>
        /// <param name="toUnitID"></param>
        public static void ChangeItemUnit(int storeID, int itemID, int fromUnitID, int toUnitID)
        {
            MyGeneration.dOOdads.TransactionMgr transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
            try
            {
                transaction.BeginTransaction();
                ItemUnit iuFrom = new ItemUnit(), iuTo = new ItemUnit(), iuExecute = new ItemUnit();
                iuFrom.LoadByPrimaryKey(fromUnitID);
                iuTo.LoadByPrimaryKey(toUnitID);

                var receiveTableFilterQuery = HCMIS.Repository.Queries.ItemUnit.SelectChangeItemUnit(storeID, itemID, iuFrom.ID);

                string query;
                // Update Issue Doc
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitIssueDoc(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);
                iuExecute.LoadFromRawSql(query);

                // Update disposal table
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitLossAndAdjustment(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);
                iuExecute.LoadFromRawSql(query);

                // Update Order.
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitOrderDetail(itemID, iuFrom.ID, iuFrom.QtyPerUnit, iuTo.QtyPerUnit);

                iuExecute.LoadFromRawSql(query);

                // Update Pick List Detail
                query =
                    HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitPickListDetail(iuTo.QtyPerUnit, iuFrom.QtyPerUnit, receiveTableFilterQuery);

                iuExecute.LoadFromRawSql(query);

                // change the Weighted Average Log
                try
                {
                    query = HCMIS.Repository.Queries.ItemUnit.UpdateChangeItemUnitMovingAverageHistory(storeID, iuTo.ID, iuFrom.ID);

                    iuExecute.LoadFromRawSql(query);
                }

                catch
                {
                }

                BLL.ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByItemIDUnitIDStoreID(itemID, iuFrom.ID, storeID);
                rd.ChangeUnitID(iuTo.ID);

                //Change the YearEnd
                //If there is already an entry with the other UnitID, we need to merge the two.

                BLL.YearEnd yEndFrom = new YearEnd();
                yEndFrom.Where.UnitID.Value  = iuFrom.ID;
                yEndFrom.Where.ItemID.Value  = itemID;
                yEndFrom.Where.StoreID.Value = storeID;
                yEndFrom.Query.Load();

                if (yEndFrom.RowCount > 0)
                {
                    //There is a year end entry.
                    //If there is one by the new UnitID, we merge them.  If there is no entry by the new UnitID, we just change the values.
                    BLL.YearEnd yEndTo = new YearEnd();
                    yEndTo.Where.UnitID.Value  = iuTo.ID;
                    yEndTo.Where.ItemID.Value  = itemID;
                    yEndTo.Where.StoreID.Value = storeID;
                    yEndTo.Query.Load();
                    if (yEndTo.RowCount > 0)
                    {
                        //We need to merge.
                        if (!yEndTo.IsColumnNull("EndingPrice"))
                        {
                            yEndTo.EndingPrice += yEndFrom.EndingPrice;
                        }
                        else
                        {
                            yEndTo.EndingPrice = yEndFrom.EndingPrice;
                        }
                        if (!yEndTo.IsColumnNull("EBalance"))
                        {
                            yEndTo.EBalance += yEndFrom.EBalance;
                        }
                        else
                        {
                            yEndTo.EBalance = yEndFrom.EBalance;
                        }
                        if (!yEndTo.IsColumnNull("PhysicalInventory"))
                        {
                            yEndTo.PhysicalInventory += yEndFrom.PhysicalInventory;
                        }
                        else
                        {
                            yEndTo.PhysicalInventory = yEndFrom.PhysicalInventory;
                        }
                        if (!yEndTo.IsColumnNull("PhysicalInventoryPrice"))
                        {
                            yEndTo.PhysicalInventoryPrice += yEndFrom.PhysicalInventoryPrice;
                        }
                        else
                        {
                            yEndTo.PhysicalInventoryPrice = yEndFrom.PhysicalInventoryPrice;
                        }

                        yEndTo.Save();
                        yEndFrom.MarkAsDeleted();
                        yEndFrom.Save();
                    }
                    else
                    {
                        yEndFrom.UnitID = iuTo.ID;
                        yEndFrom.Save();
                    }
                }
                transaction.CommitTransaction();
            }
            catch (Exception ex)
            {
                transaction.RollbackTransaction();
                throw ex;
            }
        }
        private bool SaveInventoryWithOutUnit()
        {
            var yEnd = new YearEnd();
            var rec = new ReceiveDoc();

            if (IsValid())
            {
                dtDate.Value = DateTime.Now;
                DateTime dtCurent = new DateTime();
                dtDate.CustomFormat = "MM/dd/yyyy";
                dtCurent = ConvertDate.DateConverter(dtDate.Text);

                int year = dtCurent.Year;
                if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DataTable yearEndTable = (DataTable)grdYearEnd.DataSource;

                    for (int i = 0; i < dtBB.Rows.Count; i++)
                    {
                        int id = 0;
                        int storeID = Convert.ToInt32(cboStores.EditValue);
                        if (dtBB.Rows[i]["ItemID"] != DBNull.Value)
                        {
                            var itemID = Convert.ToInt32(dtBB.Rows[i]["ItemID"]);
                            //var unitID = Convert.ToInt32(dtBB.Rows[i]["UnitID"]);
                            id = yEnd.LoadByItemIDStoreAndYear(itemID, storeID, year, false);
                        }
                        if (id != 0 && !ReferenceEquals(yearEndTable.Rows[i]["Physical Inventory"], string.Empty))//There is already a manual entry in the yearend table.
                        {
                            //yEnd.LoadByPrimaryKey(id);
                            yEnd.BBalance = Convert.ToInt64(FilterNumbers(yearEndTable.Rows[i]["Beginning Balance"].ToString()));
                            yEnd.EBalance = Int64.Parse(FilterNumbers(yearEndTable.Rows[i]["Ending Balance(SOH)"].ToString()), NumberStyles.AllowThousands);
                            yEnd.PhysicalInventory = Convert.ToInt64(FilterNumbers(yearEndTable.Rows[i]["Physical Inventory"].ToString()));
                            //yEnd.BatchNo = yearEndTable.Rows[i]["Batch No."].ToString();
                            yEnd.UnitID = 0;
                            yEnd.Remark = yearEndTable.Rows[i]["Remark"].ToString();
                            yEnd.AutomaticallyEntered = false;
                            yEnd.Save();
                        }
                        else//There is no entry in the yearend table under this item name that has been entered manually.
                        {
                            DataRow cRow = dtBB.Rows[i];
                            if (!ReferenceEquals(cRow["Physical Inventory"], string.Empty) && cRow["ItemID"] != DBNull.Value)
                            {
                                var itemID = Convert.ToInt32(cRow["ItemID"]);
                                var unitID = 0;
                                YearEnd.PurgeAutomaticallyEnteredInventoryForUnit(itemID, storeID, year, unitID);
                                //if (areAllBatchesPhyInventoryNullValue == false) //We want to add an inventory record if at least one of the batches has a non empty value.
                                //{
                                yEnd.AddNew();
                                yEnd.ItemID = itemID;
                                yEnd.StoreID = storeID;
                                yEnd.Year = year;
                                yEnd.BBalance = Convert.ToInt64(cRow["Beginning Balance"]);
                                Int64 endBal = Convert.ToInt64(cRow["Ending Balance(SOH)"]);
                                //yEnd.BatchNo = cRow["Batch No."].ToString();
                                yEnd.EBalance = endBal;// Convert.ToInt64(yearEndTable.Rows[i].Cells[5].Value);

                                if (cRow["Physical Inventory"] != DBNull.Value)
                                    yEnd.PhysicalInventory = Convert.ToInt64(cRow["Physical Inventory"]);

                                //yEnd.PhysicalInventory = physicalInventoryTotal;
                                yEnd.UnitID = 0;
                                 yEnd.Remark = cRow["Remark"].ToString();

                                yEnd.AutomaticallyEntered = cRow["Physical Inventory"] == DBNull.Value;
                                yEnd.Save();
                                //}

                                //long physicalInventoryTotal = 0;
                                //bool areAllBatchesPhyInventoryNullValue = true;
                                //if (endBal != yEnd.PhysicalInventory)
                                if (true)
                                {
                                    int k = i + 1;

                                    if (k < dtBB.Rows.Count)
                                    {
                                        while (Convert.ToInt32(dtBB.Rows[k]["RecID"]) != -1)
                                        {
                                            if (dtBB.Rows[k]["Physical Inventory"] != DBNull.Value)
                                            {
                                                //areAllBatchesPhyInventoryNullValue = false;
                                                long batchPhysicalInventory =
                                                    Convert.ToInt64(dtBB.Rows[k]["Physical Inventory"]);
                                                //physicalInventoryTotal += batchPhysicalInventory;
                                                rec.LoadByPrimaryKey(Convert.ToInt32(dtBB.Rows[k]["RecID"]));
                                                rec.QuantityLeft = Convert.ToInt64(batchPhysicalInventory);
                                                rec.Remark = "Physical Inventory";
                                                rec.UnitID = 0;
                                                rec.Out = rec.QuantityLeft == 0;
                                                rec.Save();
                                            }
                                            k++;
                                            if (k >= yearEndTable.Rows.Count)
                                                break;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    XtraMessageBox.Show("Transaction Succsfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        public void GenerateAutomaticInventoryByUnit()
        {
            var ethDate = new EthiopianDate.EthiopianDate();
            var stores = new Stores();
            stores.GetActiveStores();
            var rec = new ReceiveDoc();
            var itm = new Items();
            var yearEnd = new YearEnd();
            var balance = new Balance();

            if (!InventoryRequiredForHandlingUnit(false)) return;
            while (!stores.EOF) //This needs to be done for each store and for each item
            {
                //bereket
                //itm.ExcludeNeverReceivedItemsNoCategoryForHandlingUnit(stores.ID);
                itm.ExcludeNeverReceivedItemsNoCategoryForHandlingUnitOptimized(stores.ID, ethDate.Year);
                while (!itm.EOF) //For each item
                {
                    var receivedoc = rec.GetDistinctUnitIDFromReceivedDoc(itm.ID);
                    foreach (var dr in receivedoc.Rows.Cast<DataRow>().Where(dr =>!DoesBalanceExistByUnit(ethDate.Year, itm.ID, stores.ID, true,Convert.ToInt32(dr["UnitID"]))))
                    {
                        //need optimization
                        //we can exclude the already calculated items when we exclude never recieved items
                        yearEnd.LoadByItemIDStoreAndYearAndUnit(itm.ID, stores.ID, ethDate.Year, true, Convert.ToInt32(dr["UnitID"]));

                        if (yearEnd.RowCount > 0) continue;

                        yearEnd.AddNew();
                        yearEnd.ItemID = itm.ID;
                        yearEnd.StoreID = stores.ID;
                        yearEnd.Year = ethDate.Year;

                        //need optimization
                        //atleast we can get the value directly by filtering using storeid and itemid rather than
                        //selecting all items in all stores and filter it by code
                        //yearEnd.EBalance = balance.GetSOHByUnit(itm.ID, stores.ID, ethDate.Month, ethDate.Year, Convert.ToInt32(dr["UnitID"]));
                        yearEnd.EBalance = balance.GetSOHByUnitOptimized(itm.ID, stores.ID, ethDate.Month, ethDate.Year, Convert.ToInt32(dr["UnitID"]));
                        yearEnd.PhysicalInventory = yearEnd.EBalance;
                        yearEnd.AutomaticallyEntered = true;
                        yearEnd.UnitID = Convert.ToInt32(dr["UnitID"]);
                        yearEnd.Save();

                    }
                    itm.MoveNext();
                }
                stores.MoveNext();
            }
        }
        private void BuildStoreInventoryList(int year, int storeId, DataTable dtItm)
        {
            string[] str = { "Item Name", "Batch No.", "Remark" };
            foreach (string co in str)
            {
                dtBB.Columns.Add(co);
            }
            str = new string[] { "ItemId", "No.", "Beginning Balance", "Ending Balance(SOH)", "Physical Inventory", "ID", "RecID"};//, "Change Since Sene 30" };

            foreach (string co in str)
            {
                dtBB.Columns.Add(co, typeof(int));
            }
            int count = 1;
            var yProcess = new YearEnd();
            var bal = new Balance();

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

            var recDoc = new ReceiveDoc();
            int month = dtCurent.Month;
            //btnSave.Enabled = true;
            //CALENDAR:

            //if ((dtCurent.Month == 10 && dtCurent.Day == 30) || dtCurent.Month == 11)
            //{
            //    //btnSave.Enabled = ((!yProcess.IsInventoryComplete(year, storeId)));
            //    btnSave.Enabled =true;
            //    month = 10;

            //}
            //else
            //    btnSave.Enabled = false;

            var yEnd = new YearEnd();

            foreach (DataRow dr in dtItm.Rows)//For each item
            {
                string itemName = dr["ItemName"].ToString() + " - " + dr["DosageForm"].ToString() + " - " + dr["Strength"].ToString();
                int itemID = Convert.ToInt32(dr["ID"]);
                bool BalanceExists = (yProcess.DoesBalanceExist(year, storeId, itemID, false));

                //We don't want to display those items whose inventory has already been done.
                if (BalanceExists)
                    continue;

                //bereket
                //Int64 soh = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, month, year);
                Int64 soh = bal.GetSOHOptimized(Convert.ToInt32(dr["ID"]), storeId, month, year);
                Int64 bbal = yEnd.GetBBalance(year, storeId, Convert.ToInt32(dr["ID"]), month);

                yProcess.GetBalanceByItemId(year, storeId, Convert.ToInt32(dr["ID"]));

                Int64 BB = (yProcess.RowCount > 0) ? yProcess.BBalance : bbal;
                Int64 EB = ((yProcess.RowCount > 0 && yProcess.EBalance != 0) ? yProcess.EBalance : soh);
                //Now if the physical inventory is chosen to be default value, we set it to the ending balance of last year.
                string Phy = (yProcess.RowCount > 0) ? yProcess.PhysicalInventory.ToString() : (_defaultValueToPhysicalInventory ? EB.ToString() : "");
                int id = (yProcess.RowCount > 0) ? yProcess.ID : 0;
                string remark = (yProcess.RowCount > 0) ? yProcess.Remark : "";
                //object[] obj = {Convert.ToInt32(dr["ID"]),count,itemName,"",BB,((EB != 0)?EB.ToString("#,###"):"0"),Phy,remark,id,-1};
                //dtBB.Rows.Add(obj);
                DataRowView drv = dtBB.DefaultView.AddNew();
                if (yProcess.RowCount > 0)
                {
                    drv["ID"] = yProcess.ID;
                }
                drv["ItemId"] = dr["ID"];
                drv["No."] = count;
                drv["Item Name"] = itemName;
                drv["Beginning Balance"] = BB;
                drv["Ending Balance(SOH)"] = EB;

                if (Phy != "")
                {
                    drv["Physical Inventory"] = Phy;
                }
                drv["RecID"] = -1;
                drv["Remark"] = remark;
                var ethioDate = new EthiopianDate.EthiopianDate(year, 1, 1);
                //drv["Change Since Sene 30"] = BLL.Balance.GetChangeAfterDate(itemID, storeId, ethioDate.EndOfFiscalYear.ToGregorianDate());
                count++;
                //if (!BalanceExists)
                //{
                int theLastBalance = 0;
                DataTable dtBatchs = recDoc.GetBatchWithValue(storeId, Convert.ToInt32(dr["ID"]), dtCurent);
                foreach (DataRow drBatch in dtBatchs.Rows) //For each batch
                {
                    if (drBatch["QuantityLeft"] != DBNull.Value && Convert.ToInt64(drBatch["QuantityLeft"]) != 0)
                    {
                        drv = dtBB.DefaultView.AddNew();

                        drv["Item Name"] = ">>";
                        drv["Batch No."] = drBatch["BatchNo"];
                        drv["Ending Balance(SOH)"] = Convert.ToInt64(drBatch["QuantityLeft"]);
                        //Now if the physical inventory is chosen to be default value, we set it to the ending balance of last year.
                        if (_defaultValueToPhysicalInventory)
                            drv["Physical Inventory"] = drBatch["QuantityLeft"].ToString();

                        theLastBalance += Convert.ToInt32(drBatch["QuantityLeft"]);
                        drv["RecID"] = drBatch["ID"];
                    }
                }
                //}
            }

            grdYearEnd.DataSource = dtBB;
            dtDate.CustomFormat = "MMMM dd, yyyy";
        }
        public void GenerateAutomaticInventory()
        {
            var ethDate = new EthiopianDate.EthiopianDate();
            if (InventoryRequired(false))
            {
                Stores stores = new Stores();
                stores.GetActiveStores();
                while (!stores.EOF) //This needs to be done for each store
                {
                  if (!DoesBalanceExist(ethDate.Year, stores.ID, true))
                        //If Inventory information hasn't already been filled for this store
                    {
                        var itm = new Items();

                      //bereket
                      //itm.ExcludeNeverReceivedItemsNoCategory(stores.ID);
                        itm.ExcludeNeverReceivedItemsNoCategoryOptimized(stores.ID, ethDate.Year);
                        while (!itm.EOF) //For each time
                        {
                            var yearEnd = new YearEnd();
                            var balance = new Balance();

                            yearEnd.LoadByItemIDStoreAndYear(itm.ID, stores.ID, ethDate.Year, true);

                            if (yearEnd.RowCount > 0)
                            {
                                return;
                            }

                            //YearEnd.PurgeAutomaticallyEnteredInventory(itm.ID, stores.ID, ethDate.Year);
                            yearEnd.AddNew();
                            yearEnd.ItemID = itm.ID;
                            yearEnd.StoreID = stores.ID;
                            yearEnd.Year = ethDate.Year;

                            //bereket
                            //yearEnd.EBalance = balance.GetSOH(itm.ID, stores.ID, 10, ethDate.Year);
                            yearEnd.EBalance = balance.GetSOHOptimized(itm.ID, stores.ID, 10, ethDate.Year);
                            yearEnd.PhysicalInventory = yearEnd.EBalance;
                            yearEnd.AutomaticallyEntered = true;
                            yearEnd.UnitID = 0;
                            yearEnd.Save();
                            itm.MoveNext();
                        }
                    }
                    stores.MoveNext();
                }

            }
        }
        /// <summary>
        /// Loads a form to the panel
        /// </summary>
        /// <param name="tag">The tag of the button - Here is stored what type of form is supposed to be opened</param>
        private void LoadForm(string tag)
        {
            var yEnd = new YearEnd();
            if (yEnd.InventoryRequired(false))
            {
                switch (VisibilitySetting.HandleUnits)
                {
                    case 1:
                        yEnd.GenerateAutomaticInventory();
                        break;
                    case 2:
                        yEnd.GenerateAutomaticInventoryByUnit();
                        break;
                    case 3:
                        yEnd.GenerateAutomaticInventoryByUnit();
                        break;
                }
            }

            Form frm;
            switch (tag)
            {
                case "Receives":
                    frm = new ReceivingForm();
                    AddTab("Receiving Form", frm);
                    break;
                case "Issues":
                    frm = new IssueForm();
                    AddTab("Issue Form", frm);
                    break;
                case "AMCs":
                    frm = new AMCView();
                    AddTab("AMC Report", frm);
                    break;
                case "menuItemPriceOnlyReport":
                    frm = new ItemPriceOnlyReport();
                    AddTab("Item Price Only", frm);
                    break;
                case "stockoutindexer":
                    frm = new StockOutIndicesBuilder();
                    AddTab("Stockout Indices Builder",frm);
                    break;
                case "Facility Settings":
                    frm = new Hospital();
                    AddTab("Facility Settings", frm);
                    break;
                case "Drug List":
                    frm = new ManageItems();
                    AddTab("Manage Drug List", frm);
                    break;
                case "Supplies List":
                    //frm = new ManageItems();
                    frm = new ManageSupplies();
                    AddTab("Manage Supplies List", frm);
                    break;
               case "Item Consolidator":
                    //frm = new ManageItems();
                    frm = new ItemConsolidator();
                    AddTab("Update Items List From The Directory Service", frm);
                    break;

                case "Customize Druglist":
                    frm = new CustomDrugList();
                    AddTab("Customize Drug List", frm);
                    break;
                case "System Settings":
                    frm = new SystemSetting();
                    AddTab("System Settings", frm);
                    break;
                case "Facility Details":
                    frm = new HospitalSettings();
                    AddTab("Facility Details", frm);
                    break;
                case "User Accounts":
                    frm = new UserAccounts();
                    AddTab("Manage Users", frm);
                    break;
                case "Pipeline":
                    frm = new Pipeline();
                    AddTab("Pipeline", frm);
                    break;
                case "Change Password":
                    frm = new ChangePassword(UserId);
                    AddTab("Change Password", frm);
                    break;
                    break;
                case "Transfer Log":
                    frm = new LogTransfer();
                    AddTab("Transfer Log", frm);
                    break;
                case "Losses/Adjustment":
                    frm = new LossesAdjustment();
                    AddTab("Losses and Adjustment", frm);
                    break;
                case "Receive Log":
                    frm = new LogReceive();
                    AddTab("Receive Transaction Log", frm);
                    break;
                case "Issue Log":
                    frm = new LogIssues();
                    AddTab("Issue Transaction Log", frm);
                    break;
                case "Adjustment Log":
                    frm = new LogAdjustment();
                    AddTab("Loss / Adjustment Transaction Log", frm);
                    break;
                case "Inventory Log":
                    frm = new LogInventory();
                    AddTab("Inventory Log", frm);
                    break;
                case "Stock Status":
                    frm = new ItemReport();
                    AddTab("Stock Status", frm);
                    break;
                case "Over Stocked":
                    frm = new OtherItemReport("Over Stocked");
                    AddTab("Over Stock Items", frm);
                    break;
                case "Transfers":
                    frm = new TransferForm();
                    AddTab("Transfer Form", frm);
                    break;
                case "Stock Out":
                    frm = new OtherItemReport("Stock Out");
                    AddTab("Stocked Out Items", frm);
                    break;
                case "ConsumptionTrend":
                    frm = new ConsumptionTrendReport();
                    AddTab("Consumption Trend", frm);
                    break;
                case "Issues By Receiving Unit":
                    frm = new IssuesByDep();
                    AddTab("Issues By Receiving Unit", frm);
                    break;
                case "Expired Products":
                    frm = new ExpiredProducts();
                    AddTab("Expired Products", frm);
                    break;
                case "Near Expiry":
                    frm = new NearlyExpired();
                    AddTab("Near Expiry Products", frm);
                    break;
                case "SOH Trend":
                    frm = new SOHTrend();
                    AddTab("SOH Trend", frm);
                    break;
                case "Receive Trend":
                    frm = new ReceiveTrend();
                    AddTab("Receive Trend", frm);
                    break;
                case "Balance":
                    frm = new BalanceReport();
                    AddTab("Balance", frm);
                    break;
                case "Summary Report":
                    frm = new GeneralReport();
                    AddTab("Summary Report", frm);
                    break;
                case "Cost Summary":
                    frm = new GeneralCostChart();
                    AddTab("Cost Summary", frm);
                    break;
                case "Summary Chart":
                    frm = new GeneralChart();
                    AddTab("General Chart", frm);
                    break;
                case "ECLS":
                    frm = new ECLS();
                    AddTab("CS Stock Status", frm);
                    break;
                case "Year End Process":
                    frm = new YearEndProcess();
                    AddTab("Inventory", frm);
                    break;
                case "Default Year End Process":
                    frm = new YearEndProcess(true);
                    AddTab("Inventory", frm);
                    break;
                case "Stock Expiry Status":
                    frm = new GeneralExpiryChart();
                    AddTab("Stock Expiry Status", frm);
                    break;
                case "DataBase":
                    frm = new DatabaseActions();
                    AddTab("Database Actions", frm);
                    break;
                case "PDA":
                    frm = new ItemReport();
                    AddTab("Stock Status", frm);
                    break;
                case "Consumables List":
                    frm = new ManageSupplies();
                    AddTab("Supplies List", frm);
                    break;
                case "RRF Form":
                    frm = new RRFForm();
                    AddTab("Report and Requisition Form", frm);
                    break;
                case "LossReport":
                    frm = new ExpiredProductsReport();
                    AddTab("Loss / Adjustment Reporting View", frm);
                    break;
                case "CostReport":
                    frm = new CostReport();
                    AddTab("Cost Report", frm);
                    break;
                case "ConsumptionByUnit" :
                    frm = new ConsumptionByUnits();
                    AddTab("Consumption By Dispensary Unit", frm);
                    break;
                case "About":
                    Program.ShowHCMISVersionInfoMessageBox();
                    break;

            }
        }
        public Int64 GetSOHperMonth(int itemId, int storeId, int month, int year)
        {
            IssueDoc iss = new IssueDoc();
            ReceiveDoc rec = new ReceiveDoc();
            Disposal dis = new Disposal();
            YearEnd yEnd = new YearEnd();
            //int month = (mon > 2) ? mon - 2 : ((mon == 1) ? 11 : 12);
            //int year = (mon > 2) ? yr : yr - 1;
            Int64 cons = 0;
            cons = (this.GetSOH(itemId, storeId, month - 1, year) + rec.GetReceivedQuantityPerMonth(itemId, storeId, month, year) + dis.GetAdjustedQuantityPerMonth(itemId, storeId, month, year) - iss.GetIssuedQuantityPerMonth(itemId, storeId, month, year) - dis.GetLossesQuantityPerMonth(itemId, storeId, month, year));

            return cons;
        }
        /// <summary>
        /// Generates Past 12 Months charts
        /// </summary>
        private void GenerateChartsPastMonths()
        {
            Balance bal = new Balance();
            GeneralInfo info = new GeneralInfo();
            info.LoadAll();
            DataTable dtList = new DataTable();
            DataTable dtAmc = new DataTable();
            DataTable dtMOS = new DataTable();
            DataTable dtIss = new DataTable();
            DataTable dtRec = new DataTable();
            DataTable dtBB = new DataTable();

            //foreach(string s in co)
            //{
            dtList.Columns.Add("Month");
            dtList.Columns.Add("Value");
            dtList.Columns[1].DataType = typeof(Int64);

            dtMOS.Columns.Add("Month");
            dtMOS.Columns.Add("Value");
            dtMOS.Columns[1].DataType = typeof(Int32);

            dtAmc.Columns.Add("Month");
            dtAmc.Columns.Add("Value");
            dtAmc.Columns[1].DataType = typeof(Int64);

            dtIss.Columns.Add("Month");
            dtIss.Columns.Add("Value");
            dtIss.Columns[1].DataType = typeof(Int64);

            dtRec.Columns.Add("Month");
            dtRec.Columns.Add("Value");
            dtRec.Columns[1].DataType = typeof(Int64);

            dtBB.Columns.Add("Month");
            dtBB.Columns.Add("Value");
            dtBB.Columns[1].DataType = typeof(Int64);

            //dtDate.Value = DateTime.Now;
            //dtDate.CustomFormat = "MM/dd/yyyy";
            //DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);
            DateTime dtPast = _dtCurrent.AddMonths(-11);
            //CALENDAR:
            string[] wer = { "Mes", "Tek", "Hed", "Tah", "Tir", "Yek", "Meg", "Miz", "Gen", "Sen", "Ham", "Neh" };
            string[] co = new string[12];
            int[] mon = new int[12];
            int[] yr = new int[12];
            int intialM = dtPast.Month;
            int j = 0;
            while (dtPast <= _dtCurrent && j < 12)
            {
                //mon[j] = intialM;
                //co[j] = wer[intialM-1];
                //yr[j] = (intialM < 11)?dtPast.Year: dtPast.Year +1;
                //dtPast = dtPast.AddMonths(1);
                //intialM = dtPast.Month;
                mon[j] = dtPast.Month;
                co[j] = wer[intialM - 1];
                yr[j] = dtPast.Year;
                dtPast = dtPast.AddMonths(1);
                intialM = dtPast.Month;
                j++;
            }
            //{ 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            long[] cons = new long[12];
            long[] amc = new long[12];
            DataTable dtBal = new DataTable();
            IssueDoc issd = new IssueDoc();
            Items recd = new Items();

            YearEnd yEnd = new YearEnd();
            Int64 bb = yEnd.GetBBalance(_year, _storeId, _itemId, 10);
            object[] objBB = { "Ham", bb };
            dtBB.Rows.Add(objBB);

            for (int i = 0; i < mon.Length; i++)
            {
                Int64 con = bal.GetSOH(_itemId, _storeId, mon[i], yr[i]);
                object[] str = { co[i], con };
                amc[i] = bal.CalculateAMC(_itemId, _storeId, mon[i], yr[i]);
                object[] objAmc = { co[i], amc[i] };
                decimal mos = (amc[i] > 0) ? (Convert.ToDecimal(con) / Convert.ToDecimal(amc[i])) : 0;
                mos = Decimal.Round(mos, 1);

                object[] objMos = { co[i], mos };
                Int64 issval = issd.GetIssuedQuantityByMonth(_itemId, _storeId, mon[i], yr[i]);
                object[] objIss = { co[i], issval };

                Int64 recVal = recd.GetQuantityReceiveByItemPerMonth(mon[i], _itemId, _storeId, yr[i]);
                object[] objrec = { co[i], recVal };

                dtList.Rows.Add(str);
                dtAmc.Rows.Add(objAmc);
                dtMOS.Rows.Add(objMos);
                dtIss.Rows.Add(objIss);
                dtRec.Rows.Add(objrec);
                //}
            }
            // string[] str = { ((cons[0] != 0) ? cons[0].ToString("") : "0"), ((cons[1] != 0) ? cons[1].ToString() : "0"), ((cons[2] != 0) ? cons[2].ToString() : "0"), ((cons[3] != 0) ? cons[3].ToString() : "0"), ((cons[4] != 0) ? cons[4].ToString() : "0"), ((cons[5] != 0) ? cons[5].ToString() : "0"), ((cons[6] != 0) ? cons[6].ToString() : "0"), ((cons[7] != 0) ? cons[7].ToString() : "0"), ((cons[8] != 0) ? cons[8].ToString() : "0"), ((cons[9] != 0) ? cons[9].ToString() : "0"), ((cons[10] != 0) ? cons[10].ToString() : "0"), ((cons[11] != 0) ? cons[11].ToString() : "0")};
            chartAmc.Series.Clear();
            chartComp.Series.Clear();
            chartBar.Series.Clear();
            chartMOS.Series.Clear();
            consuTrend.Series.Clear();

            Series ser = new Series("Stock On Hand", ViewType.Line);
            ser.DataSource = dtList;
            ser.ArgumentScaleType = ScaleType.Qualitative;
            ser.ArgumentDataMember = "Month";
            ser.ValueScaleType = ScaleType.Numerical;
            ser.ValueDataMembers.AddRange(new string[] { "Value" });
            chartBar.Series.Add(ser);

            Series serB = new Series("Begining Balance", ViewType.Bar);
            serB.DataSource = dtBB;
            serB.ArgumentScaleType = ScaleType.Qualitative;
            serB.ArgumentDataMember = "Month";
            serB.ValueScaleType = ScaleType.Numerical;
            serB.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            serB.PointOptions.ValueNumericOptions.Precision = 0;
            serB.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serB);

            Series serRec = new Series("Received Qty", ViewType.Bar);
            serRec.DataSource = dtRec;
            serRec.ArgumentScaleType = ScaleType.Qualitative;
            serRec.ArgumentDataMember = "Month";
            serRec.ValueScaleType = ScaleType.Numerical;
            serRec.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serRec);

            Series serAmc = new Series("Average Monthly Consumption", ViewType.Line);
            serAmc.DataSource = dtAmc;
            serAmc.ArgumentScaleType = ScaleType.Qualitative;
            serAmc.ArgumentDataMember = "Month";
            serAmc.ValueScaleType = ScaleType.Numerical;
            serAmc.ValueDataMembers.AddRange(new string[] { "Value" });
            chartAmc.Series.Add(serAmc);

            Series serIss = new Series("Issue Qty", ViewType.Bar);
            serIss.DataSource = dtIss;
            serIss.ArgumentScaleType = ScaleType.Qualitative;
            serIss.ArgumentDataMember = "Month";
            serIss.ValueScaleType = ScaleType.Numerical;
            serIss.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serIss);

            Series serSOH = new Series("SOH", ViewType.Bar);
            serSOH.DataSource = dtList;
            serSOH.ArgumentScaleType = ScaleType.Qualitative;
            serSOH.ArgumentDataMember = "Month";
            serSOH.ValueScaleType = ScaleType.Numerical;
            serSOH.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serSOH);

            Series sercons = new Series("Consumption Trend", ViewType.Line);
            sercons.DataSource = dtIss;
            sercons.ArgumentScaleType = ScaleType.Qualitative;
            sercons.ArgumentDataMember = "Month";
            sercons.ValueScaleType = ScaleType.Numerical;
            sercons.ValueDataMembers.AddRange(new string[] { "Value" });
            consuTrend.Series.Add(sercons);

            Series serMos = new Series("Month Of Stock", ViewType.Line);
            serMos.DataSource = dtMOS;
            serMos.ArgumentScaleType = ScaleType.Qualitative;
            serMos.ArgumentDataMember = "Month";
            serMos.ValueScaleType = ScaleType.Numerical;
            serMos.ValueDataMembers.AddRange(new string[] { "Value" });

            chartMOS.Series.Add(serMos);
            ((XYDiagram)chartMOS.Diagram).AxisY.Range.MaxValue = 12;

            Int64 amcCurent = bal.CalculateAMC(_itemId, _storeId, _dtCurrent.Month, _year);
            //Int64 soh = bal.GetSOH(itemId,storeId,dtCurrent.Month,year);
            //if (bal.RowCount > 0)
            //{
            Int64 min = info.Min * amcCurent;
            Int64 max = info.Max * amcCurent;
            ConstantLine target = new ConstantLine();
            target.AxisValue = min;
            //which min and max to show month
            ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Clear();
            target.Visible = true;
            target.Title.Text = "Current Min value is " + target.AxisValue.ToString() + " " + lblBUnit.Text;
            target.Color = Color.Red;
            target.LineStyle.Thickness = 2;
            // ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Add(target);

            ConstantLine targetMax = new ConstantLine();
            targetMax.AxisValue = max;
            //which min and max to show month
            targetMax.Visible = true;
            targetMax.Title.Text = "Current Max value is " + targetMax.AxisValue.ToString() + " " + lblBUnit.Text;
            targetMax.Color = Color.Blue;
            targetMax.LineStyle.Thickness = 2;
            //((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Add(targetMax);
            //}
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="itemId"></param>
        /// <param name="storeId"></param>
        /// <param name="mon"></param>
        /// <param name="yr"></param>
        /// <returns></returns>
        public Int64 CalculateSOH(int itemId, int storeId, int mon, int yr)
        {
            //ask by normal u get soh on fiscal month
            IssueDoc iss = new IssueDoc();
            ReceiveDoc rec = new ReceiveDoc();
            Disposal dis = new Disposal();
            YearEnd yEnd = new YearEnd();

            int month = (mon > 2) ? mon - 2 : ((mon == 1) ? 11 : 12);
            int year = (mon > 2) ? yr : yr - 1;
            Int64 cons = 0;
            cons = (rec.GetReceivedQuantityTillMonth(itemId, storeId, month, year) + dis.GetAdjustedQuantityTillMonth(itemId, storeId, month, year) - iss.GetIssuedQuantityTillMonth(itemId, storeId, month, year) - dis.GetLossesQuantityTillMonth(itemId, storeId, month, year));

            return cons;
        }