Ejemplo n.º 1
0
        public Int64 GetBBalanceByUnit(int year, int storeId, int itemId, int month, int unitId)
        {
            //CALENDAR:
            this.FlushData();
            Int64 bb = 0;

            //int bYear = ((month > 10) ? year : year - 1);
            EthiopianDate.EthiopianDate ethioDate = new EthiopianDate.EthiopianDate(year, month, 30);
            int    bYear = ethioDate.FiscalYear;
            string query =
                String.Format(
                    "Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2}  and UnitID={3} and (AutomaticallyEntered = 0 or AutomaticallyEntered is null) order by PhysicalInventory desc",
                    storeId, itemId, bYear, unitId);

            this.LoadFromRawSql(query);
            if (this.DataTable.Rows.Count > 0 && this.DataTable.Rows[0]["PhysicalInventory"] != DBNull.Value)
            {
                bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
            }
            else
            {
                this.LoadFromRawSql(
                    String.Format(
                        "Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2} and UnitID={3} and (AutomaticallyEntered = 0  or AutomaticallyEntered is null)",
                        storeId, itemId, year - 1, unitId));
                if (this.DataTable.Rows.Count > 0)
                {
                    bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
                }
                else if (((year + 8) > DateTime.Now.Year) || (month > 10 && (year + 8) == DateTime.Now.Year))
                // to check if it is different year from current
                {
                    Int64      cons = 0;
                    IssueDoc   iss  = new IssueDoc();
                    ReceiveDoc rec  = new ReceiveDoc();
                    Disposal   dis  = new Disposal();
                    if ((year + 8) > DateTime.Now.Year) // to check if it is hamle and Nehase
                    {
                        year = year - 1;
                    }
                    month = 10;
                    //}

                    long RecievedQuantity = rec.GetReceivedQuantityTillMonthByUnit(itemId, storeId, month, year,
                                                                                   unitId);
                    long AdjustedQuantity = dis.GetAdjustedQuantityTillMonthByUnit(itemId, storeId, month, year,
                                                                                   unitId);
                    long IssuedQuantity = iss.GetIssuedQuantityTillMonthByUnit(itemId, storeId, month, year, unitId);
                    long LossQuantity   = dis.GetLossesQuantityTillMonthByUnit(itemId, storeId, month, year, unitId);
                    // long BalanceQuantity = yEnd.GetBBalance(year, storeId, itemId, month);
                    cons = (RecievedQuantity + AdjustedQuantity - IssuedQuantity - LossQuantity);

                    //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));
                    bb = cons;
                }
            }

            return(bb);
        }
 private void EditLossAndAdjustment_Load(object sender, EventArgs e)
 {
     dtRecDate.Value = DateTime.Now;
     dtRecDate.CustomFormat = "MM/dd/yyyy";
     var dis = new Disposal();
     if (_refno != null)
     {
         dis.GetTransactionByRefNo(_refno);
         txtRefNo.Text = dis.RefNo;
         DateTime dtDate = Convert.ToDateTime(dis.Date.ToString("MM/dd/yyyy"));
         txtDate.Text = dtDate.ToShortDateString();
         // dtLossDate.Value = dis.Date;
     }
 }
        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;
        }
Ejemplo n.º 4
0
        /* public Int64 GetBBalanceAll(int year, int itemId)
         * {
         *   this.FlushData();
         *   this.LoadFromRawSql(String.Format("Select * from YearEnd where  ItemID = {0} AND Year = {1}", itemId, year));
         *
         *   Int64 bb = (this.DataTable.Rows.Count > 0) ? Convert.ToInt64(this.DataTable.Rows[0]["BBalance"]) : 0;
         *
         *   return bb;
         * }*/

        /// <summary>
        /// Gets the beginning balance of an item in a store
        /// </summary>
        /// <param name="fiscalYear">The Fiscal year in Ethiopian Calendar</param>
        /// <param name="storeId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public Int64 GetBBalance(int fiscalYear, int storeId, int itemId)
        {
            //CALENDAR:
            this.FlushData();
            Int64  bb    = 0;
            int    year  = fiscalYear;
            int    month = 10;
            string query =
                String.Format(
                    "Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2} order by PhysicalInventory desc",
                    storeId, itemId, fiscalYear - 1);

            this.LoadFromRawSql(query);

            if (this.DataTable.Rows.Count > 0)
            {
                bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
            }
            else
            {
                if (((year + 8) > DateTime.Now.Year) || (month > 10 && (year + 8) == DateTime.Now.Year))
                // to check if it is different year from current
                {
                    Int64      cons = 0;
                    IssueDoc   iss  = new IssueDoc();
                    ReceiveDoc rec  = new ReceiveDoc();
                    Disposal   dis  = new Disposal();
                    if ((year + 8) > DateTime.Now.Year) // to check if it is hamle and Nehase
                    {
                        year = year - 1;
                    }
                    month = 10;
                    //}

                    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 = (RecievedQuantity + AdjustedQuantity - IssuedQuantity - LossQuantity);

                    //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));
                    bb = cons;
                }
            }

            return(bb);
        }
 private static void AddDeletedDisposal(Disposal disposal, out DisposalDelete ddel)
 {
     ddel = new DisposalDelete();
     ddel.AddNew();
     ddel.ID = disposal.ID;
     ddel.ItemID = disposal.ItemID;
     ddel.StoreId = disposal.StoreId;
     ddel.ReasonId = disposal.ReasonId;
     ddel.Quantity = disposal.Quantity;
     ddel.Date = disposal.Date;
     ddel.ApprovedBy = disposal.ApprovedBy;
     ddel.Losses = disposal.Losses;
     ddel.BatchNo = disposal.BatchNo;
     ddel.Remark = disposal.Remark;
     ddel.Cost = disposal.Cost;
     ddel.RefNo = disposal.RefNo;
     ddel.EurDate = disposal.EurDate;
     ddel.RecID = disposal.RecID;
     ddel.Save();
 }
Ejemplo n.º 6
0
        public Int64 GetBBalanceAll(int year, int itemId)
        {
            this.FlushData();
            Int64 bb = 0;

            this.LoadFromRawSql(String.Format("Select * from YearEnd where ItemID = {0} AND Year = {1}", itemId, year));
            if (this.DataTable.Rows.Count > 0)
            {
                bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
            }
            else
            {
                this.LoadFromRawSql(String.Format("Select * from YearEnd where ItemID = {0} AND Year = {1}", itemId,
                                                  year - 1));
                if (this.DataTable.Rows.Count > 0)
                {
                    bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
                }
                else if (((year + 8) > DateTime.Now.Year)) // to check if it is different year from current
                {
                    Int64      cons = 0;
                    IssueDoc   iss  = new IssueDoc();
                    ReceiveDoc rec  = new ReceiveDoc();
                    Disposal   dis  = new Disposal();

                    if ((year + 8) > DateTime.Now.Year) // to check if it is hamle and Nehase
                    {
                        year = year - 1;
                    }
                    int month = 10;
                    cons = (rec.GetReceivedQuantityTillMonthAll(itemId, month, year) +
                            dis.GetAdjustedQuantityTillMonthAll(itemId, month, year) -
                            iss.GetIssuedQuantityTillMonthAll(itemId, month, year) -
                            dis.GetLossesQuantityTillMonthAll(itemId, month, year));
                    bb = cons;
                }
            }
            return(bb);
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            var dis =new Disposal();
            var dtbl=dis.GetTransactionByRefNo(_refno);
                if (dis.RowCount > 0)
                {
                    foreach (DataRow datarow in dtbl.Rows)
                    {
                        datarow["RefNo"] = txtRefNo.Text;
                        datarow["Date"] = txtDate.Text;
                    }
                    dis.Save();
                    Close();
                    XtraMessageBox.Show("Refrence No and Date is successfully updated", "Success");
                }

                else
                {
                    XtraMessageBox.Show("There is no refrence no to edit");
                    return;
                }
                this.Close();
        }
        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 GetBBalance(int year, int storeId, int itemId)
        {
            this.FlushData();
            this.LoadFromRawSql(String.Format("Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2}",storeId,itemId,year));

            Int64 bb = ( this.DataTable.Rows.Count > 0)? Convert.ToInt64(this.DataTable.Rows[0]["BBalance"]):0;

            return bb;
        }*/
        public double GetBBalanceAmount(int year, int storeId, int itemId, int month)
        {
            //CALENDAR:
            this.FlushData();
            double bb = 0;
            EthiopianDate.EthiopianDate ethioDate = new EthiopianDate.EthiopianDate(year, month, 30);
            //int bYear = ((month > 10) ? year : year - 1);
            int bYear = ethioDate.StartOfFiscalYear.Year;
            string query = String.Format("Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2}",
                                         storeId, itemId, bYear);
            this.LoadFromRawSql(query);
            if (this.DataTable.Rows.Count > 0)
            {
                bb = ((this.DataTable.Rows[0]["PhysicalInventoryPrice"].ToString() != "")
                          ? Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventoryPrice"])
                          : 0);
            }
            else
            {
                string queryString =
                    String.Format("Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2}", storeId,
                                  itemId, year - 1);
                this.LoadFromRawSql(queryString);
                if (this.DataTable.Rows.Count > 0)
                {
                    bb = ((this.DataTable.Rows[0]["PhysicalInventoryPrice"].ToString() != "")
                              ? Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventoryPrice"])
                              : 0);
                }
                else if (((year + 8) > DateTime.Now.Year) || (month > 10 && (year + 8) == DateTime.Now.Year))
                    // to check if it is different year from current
                {
                    double cons = 0;
                    IssueDoc iss = new IssueDoc();
                    ReceiveDoc rec = new ReceiveDoc();
                    Disposal dis = new Disposal();
                    if ((year + 8) > DateTime.Now.Year) // to check if it is hamle and Nehase
                        year = year - 1;
                    month = 10;
                    //}

                    double ReceivedAmount = rec.GetReceivedAmountTillMonth(itemId, storeId, month, year);
                    double AdjustedAmount = dis.GetAdjustedAmountTillMonth(itemId, storeId, month, year);
                    double IssuedAmount = iss.GetIssuedAmountTillMonth(itemId, storeId, month, year);
                    double LostAmount = dis.GetLossesAmountTillMonth(itemId, storeId, month, year);
                    cons = ((ReceivedAmount + AdjustedAmount - IssuedAmount) - LostAmount);
                    bb = cons;
                }
            }
            if (bb < 0)
            {

            }
            return bb;

            //this.FlushData();
            //this.LoadFromRawSql(String.Format("Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2}", storeId, itemId, year-1));

            //double bb = (this.DataTable.Rows.Count > 0) ? ((this.DataTable.Rows[0]["PhysicalInventoryPrice"].ToString() != "") ? Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventoryPrice"]) : 0) : 0;

            //return bb;
        }
        private void cboStores_EditValueChanged(object sender, EventArgs e)
        {
            if (cboStores.EditValue == null) return;
            var adj = new Disposal();
            dtRec = adj.GetDistinctAdjustmentDocments(Convert.ToInt32(cboStores.EditValue));
            PopulateDocuments(dtRec);

            //var dr = (DataRowView)lstTree.GetDataRecordByNode(lstTree.Nodes[0].FirstNode);
            //if (dr == null) return;

            //dtRec = adj.GetDocumentByRefNo(dr["RefNo"].ToString(), Convert.ToInt32(cboStores.EditValue), dr["Date"].ToString());
            //lblAdjDate.Text = Convert.ToDateTime(dr["Date"]).ToString("MM dd,yyyy");
            //gridAdjustments.DataSource = dtRec;
        }
 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;
 }
        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>
        /// 
        /// </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;
        }
 private void cboReasons_EditValueChanged(object sender, EventArgs e)
 {
     if (cboStores.EditValue != null && cboReasons.EditValue != null)
     {
         var adj = new Disposal();
         dtRec = adj.GetTransactionByReason(Convert.ToInt32(cboStores.EditValue),Convert.ToInt32(cboReasons.EditValue));
         //PopulateDocuments(dtRec);
         gridAdjustments.DataSource = dtRec;
     }
 }
        /// <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;
        }
        /// <summary>
        /// Delete a row of adjustmen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var us = new User();
            var userID = MainWindow.LoggedinId;
            us.LoadByPrimaryKey(userID);

            var dataRow = gridView1.GetFocusedDataRow();
            if (dataRow == null) return;

            if (us.UserName != "admin")
            {
                XtraMessageBox.Show("You don't have the privilege to update reference number!", "Caution");
                return;
            }
            //get the primary key of the row
            var ID = Convert.ToInt32(dataRow["ID"]);

            var disposal = new Disposal();
            var receiveDoc = new ReceiveDoc();

            //Retrieve the adjustment with the value of the primary key(id)
            disposal.LoadByPrimaryKey(ID);

             int recieveID = disposal.RecID;

            receiveDoc.LoadByPrimaryKey(recieveID);
            if (XtraMessageBox.Show("Are You Sure, You want to delete this?", "Confirmation", MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //check for losss

                if (disposal.Losses) //it was loss
                {
                    receiveDoc.LoadByPrimaryKey(recieveID);
                    var s = receiveDoc.Quantity;
                    receiveDoc.Quantity = receiveDoc.Quantity + disposal.Quantity;
                    receiveDoc.QuantityLeft = receiveDoc.QuantityLeft + disposal.Quantity;
                    if (receiveDoc.Out)
                        receiveDoc.Out = false;
                    disposal.Quantity = 0;
                }
                else // it was adjustment
                {
                    receiveDoc.LoadByPrimaryKey(recieveID);
                    var s = receiveDoc.Quantity;
                    receiveDoc.Quantity = receiveDoc.Quantity - disposal.Quantity;
                    receiveDoc.QuantityLeft = receiveDoc.QuantityLeft - disposal.Quantity;
                    if (receiveDoc.Quantity == 0)
                        receiveDoc.Out = true;
                    disposal.Quantity = 0;
                }

                // proceed deletion and make the necessary changes on the database tables.
                DisposalDelete ddel;
                AddDeletedDisposal(disposal, out ddel);

                receiveDoc.Save();
                disposal.MarkAsDeleted();
                disposal.Save();

                //Repopulate the grid
                DataTable dtRec;
                dtFrom.CustomFormat = "MM/dd/yyyy";
                dtTo.CustomFormat = "MM/dd/yyyy";
                DateTime from = ConvertDate.DateConverter(dtFrom.Text);
                DateTime to = ConvertDate.DateConverter(dtTo.Text);
                dtRec = disposal.GetTransactionByDateRange(Convert.ToInt32(cboStores.EditValue), from, to);
                gridAdjustments.DataSource = dtRec;
            }
        }
        private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var us = new User();
            var userID = MainWindow.LoggedinId;
            us.LoadByPrimaryKey(userID);

            var dr = (DataRowView)lstTree.GetDataRecordByNode(lstTree.FocusedNode);
            if (dr == null) return;
            if (us.UserName != "admin")
            {
                XtraMessageBox.Show("You don't have the privilege to update reference number!", "Caution");
                return;
            }
            if (XtraMessageBox.Show("Are You Sure, You want to delete this?", "Confirmation", MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == DialogResult.Yes)
            {
               var dis = new Disposal();
               DataTable dtbl =  dis.GetTransactionByRefNo((string) dr["RefNo"]);
                foreach (DataRow dataRow in dtbl.Rows)
                {
                    AddlossDeleted(dataRow);
                    dataRow.Delete();
                }
                dis.MarkAsDeleted();
                dis.Save();
                XtraMessageBox.Show("Item successfully deleted.","Success");
            }
        }
        private void dtTo_ValueChanged(object sender, EventArgs e)
        {
            //CALENDAR:
            Disposal adj = new Disposal();
            DataTable dtRec;
            dtFrom.CustomFormat = "MM/dd/yyyy";
            dtTo.CustomFormat = "MM/dd/yyyy";
            DateTime dteFrom = ConvertDate.DateConverter(dtFrom.Text);
            DateTime dteTo = ConvertDate.DateConverter(dtTo.Text);

            dtRec = dteFrom < dteTo ? adj.GetTransactionByDateRange(Convert.ToInt32(cboStores.EditValue), dteFrom,dteTo) : adj.GetAllTransaction(Convert.ToInt32(cboStores.EditValue));
            gridAdjustments.DataSource = dtRec;
        }
        public Int64 GetBBalanceAll(int year, int itemId)
        {
            this.FlushData();
            Int64 bb = 0;
            this.LoadFromRawSql(String.Format("Select * from YearEnd where ItemID = {0} AND Year = {1}", itemId, year));
            if (this.DataTable.Rows.Count > 0)
            {
                bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
            }
            else
            {
                this.LoadFromRawSql(String.Format("Select * from YearEnd where ItemID = {0} AND Year = {1}", itemId,
                                                  year - 1));
                if (this.DataTable.Rows.Count > 0)
                {
                    bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
                }
                else if (((year + 8) > DateTime.Now.Year)) // to check if it is different year from current
                {
                    Int64 cons = 0;
                    IssueDoc iss = new IssueDoc();
                    ReceiveDoc rec = new ReceiveDoc();
                    Disposal dis = new Disposal();

                    if ((year + 8) > DateTime.Now.Year) // to check if it is hamle and Nehase
                        year = year - 1;
                    int month = 10;
                    cons = (rec.GetReceivedQuantityTillMonthAll(itemId, month, year) +
                            dis.GetAdjustedQuantityTillMonthAll(itemId, month, year) -
                            iss.GetIssuedQuantityTillMonthAll(itemId, month, year) -
                            dis.GetLossesQuantityTillMonthAll(itemId, month, year));
                    bb = cons;
                }
            }
            return bb;
        }
        /* public Int64 GetBBalanceAll(int year, int itemId)
         {
             this.FlushData();
             this.LoadFromRawSql(String.Format("Select * from YearEnd where  ItemID = {0} AND Year = {1}", itemId, year));

             Int64 bb = (this.DataTable.Rows.Count > 0) ? Convert.ToInt64(this.DataTable.Rows[0]["BBalance"]) : 0;

             return bb;
         }*/
        /// <summary>
        /// Gets the beginning balance of an item in a store
        /// </summary>
        /// <param name="fiscalYear">The Fiscal year in Ethiopian Calendar</param>
        /// <param name="storeId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public Int64 GetBBalance(int fiscalYear, int storeId, int itemId)
        {
            //CALENDAR:
            this.FlushData();
            Int64 bb = 0;
            int year = fiscalYear;
            int month = 10;
            string query =
                String.Format(
                    "Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2} order by PhysicalInventory desc",
                    storeId, itemId, fiscalYear - 1);
            this.LoadFromRawSql(query);

            if (this.DataTable.Rows.Count > 0)
            {
                bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
            }
            else
            {
                if (((year + 8) > DateTime.Now.Year) || (month > 10 && (year + 8) == DateTime.Now.Year))
                    // to check if it is different year from current
                {
                    Int64 cons = 0;
                    IssueDoc iss = new IssueDoc();
                    ReceiveDoc rec = new ReceiveDoc();
                    Disposal dis = new Disposal();
                    if ((year + 8) > DateTime.Now.Year) // to check if it is hamle and Nehase
                        year = year - 1;
                    month = 10;
                    //}

                    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 = (RecievedQuantity + AdjustedQuantity - IssuedQuantity - LossQuantity);

                    //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));
                    bb = cons;
                }
            }

            return bb;
        }
        private void lstTree_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            var dtDate = new DateTimePickerEx
            {
                CustomFormat = "MM/dd/yyyy",
                Value = DateTime.Now
            };
            DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);
            var dr = (DataRowView)lstTree.GetDataRecordByNode(lstTree.FocusedNode);
            if (dr == null) return;

            var adj = new Disposal();
            DataTable dtRec;
            if (dr["ParentID"] == DBNull.Value)
            {
                int yr = ((dtCurrent.Month > 10) ? dtCurrent.Year : dtCurrent.Year - 1);
                DateTime dt1 = new DateTime(Convert.ToInt32(dr["ID"]) - 1, 11, 1);
                DateTime dt2 = new DateTime(Convert.ToInt32(dr["ID"]), 11, 1);
                dtRec = adj.GetTransactionByDateRange(Convert.ToInt32(cboStores.EditValue), dt1, dt2);
                lblAdjDate.Text = dr["RefNo"].ToString();
            }
            else
            {
                dtRec = adj.GetDocumentByRefNo(dr["RefNo"].ToString(), Convert.ToInt32(cboStores.EditValue), dr["Date"].ToString());
                lblAdjDate.Text = Convert.ToDateTime(dr["Date"]).ToString("MM dd,yyyy");
            }

            gridAdjustments.DataSource = dtRec;
        }
        /// <summary>
        /// Prepare all lookups
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ManageItems_Load(object sender, EventArgs e)
        {
            var stor = new Stores();
            stor.GetActiveStores();
            cboStores.Properties.DataSource = stor.DefaultView;
            cboStores.ItemIndex = 0;

            var rec = new DisposalReasons();
            var dtDis = rec.GetAvailableReasons();
            cboReasons.Properties.DataSource = dtDis.DefaultView;
            reasonBindingSource.DataSource = dtDis.DefaultView;
               // cboReasons.ItemIndex = 0;

            var itemunit = new ItemUnit();
            var units = itemunit.GetAllUnits();
            unitbindingSource.DataSource = units.DefaultView;

            var unitcolumn = ((GridView)gridAdjustments.MainView).Columns[10];
            switch (VisibilitySetting.HandleUnits)
            {
                case 1:
                    unitcolumn.Visible = false;
                    break;
                case 2:
                    unitcolumn.Visible = true;
                    break;
                default:
                    unitcolumn.Visible = true;
                    break;
            }
             try
            {
                //CALENDAR:
                var dtDate = new CalendarLib.DateTimePickerEx
                {
                    CustomFormat = "MM/dd/yyyy",
                    Value = DateTime.Now
                };
                var dr = (DataRowView)lstTree.GetDataRecordByNode(lstTree.Nodes[0].FirstNode);
                if (dr == null) return;

                var disp = new Disposal();
                if (dr["ParentID"] == DBNull.Value)
                {
                    var dt1 = new DateTime(Convert.ToInt32(dr["ID"]) - 1, 11, 1);
                    var dt2 = new DateTime(Convert.ToInt32(dr["ID"]), 11, 1);
                    dtRec = disp.GetTransactionByDateRange(Convert.ToInt32(cboStores.EditValue),dt1,dt2);
                    lblAdjDate.Text = dr["RefNo"].ToString();
                }
                else
                {
                    dtRec = disp.GetDocumentByRefNo(dr["RefNo"].ToString(), Convert.ToInt32(cboStores.EditValue), dr["Date"].ToString());
                    lblAdjDate.Text = Convert.ToDateTime(dr["Date"]).ToString("MM dd,yyyy");
                }
                gridAdjustments.DataSource = dtRec;
            }
            catch (Exception ex)
            {

            }
        }
Ejemplo n.º 23
0
        /* public Int64 GetBBalance(int year, int storeId, int itemId)
         * {
         *  this.FlushData();
         *  this.LoadFromRawSql(String.Format("Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2}",storeId,itemId,year));
         *
         *  Int64 bb = ( this.DataTable.Rows.Count > 0)? Convert.ToInt64(this.DataTable.Rows[0]["BBalance"]):0;
         *
         *  return bb;
         * }*/

        public double GetBBalanceAmount(int year, int storeId, int itemId, int month)
        {
            //CALENDAR:
            this.FlushData();
            double bb = 0;

            EthiopianDate.EthiopianDate ethioDate = new EthiopianDate.EthiopianDate(year, month, 30);
            //int bYear = ((month > 10) ? year : year - 1);
            int    bYear = ethioDate.StartOfFiscalYear.Year;
            string query = String.Format("Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2}",
                                         storeId, itemId, bYear);

            this.LoadFromRawSql(query);
            if (this.DataTable.Rows.Count > 0)
            {
                bb = ((this.DataTable.Rows[0]["PhysicalInventoryPrice"].ToString() != "")
                          ? Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventoryPrice"])
                          : 0);
            }
            else
            {
                string queryString =
                    String.Format("Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2}", storeId,
                                  itemId, year - 1);
                this.LoadFromRawSql(queryString);
                if (this.DataTable.Rows.Count > 0)
                {
                    bb = ((this.DataTable.Rows[0]["PhysicalInventoryPrice"].ToString() != "")
                              ? Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventoryPrice"])
                              : 0);
                }
                else if (((year + 8) > DateTime.Now.Year) || (month > 10 && (year + 8) == DateTime.Now.Year))
                // to check if it is different year from current
                {
                    double     cons = 0;
                    IssueDoc   iss  = new IssueDoc();
                    ReceiveDoc rec  = new ReceiveDoc();
                    Disposal   dis  = new Disposal();
                    if ((year + 8) > DateTime.Now.Year) // to check if it is hamle and Nehase
                    {
                        year = year - 1;
                    }
                    month = 10;
                    //}

                    double ReceivedAmount = rec.GetReceivedAmountTillMonth(itemId, storeId, month, year);
                    double AdjustedAmount = dis.GetAdjustedAmountTillMonth(itemId, storeId, month, year);
                    double IssuedAmount   = iss.GetIssuedAmountTillMonth(itemId, storeId, month, year);
                    double LostAmount     = dis.GetLossesAmountTillMonth(itemId, storeId, month, year);
                    cons = ((ReceivedAmount + AdjustedAmount - IssuedAmount) - LostAmount);
                    bb   = cons;
                }
            }
            if (bb < 0)
            {
            }
            return(bb);


            //this.FlushData();
            //this.LoadFromRawSql(String.Format("Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2}", storeId, itemId, year-1));

            //double bb = (this.DataTable.Rows.Count > 0) ? ((this.DataTable.Rows[0]["PhysicalInventoryPrice"].ToString() != "") ? Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventoryPrice"]) : 0) : 0;

            //return bb;
        }
        public Int64 GetBBalanceByUnit(int year, int storeId, int itemId, int month, int unitId)
        {
            //CALENDAR:
            this.FlushData();
            Int64 bb = 0;
            //int bYear = ((month > 10) ? year : year - 1);
            EthiopianDate.EthiopianDate ethioDate = new EthiopianDate.EthiopianDate(year, month, 30);
            int bYear = ethioDate.FiscalYear;
            string query =
                String.Format(
                    "Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2}  and UnitID={3} and (AutomaticallyEntered = 0 or AutomaticallyEntered is null) order by PhysicalInventory desc",
                    storeId, itemId, bYear, unitId);
            this.LoadFromRawSql(query);
            if (this.DataTable.Rows.Count > 0 && this.DataTable.Rows[0]["PhysicalInventory"] != DBNull.Value)
            {
                bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
            }
            else
            {
                this.LoadFromRawSql(
                    String.Format(
                        "Select * from YearEnd where StoreID = {0} AND ItemID = {1} AND Year = {2} and UnitID={3} and (AutomaticallyEntered = 0  or AutomaticallyEntered is null)",
                        storeId, itemId, year - 1, unitId));
                if (this.DataTable.Rows.Count > 0)
                {
                    bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
                }
                else if (((year + 8) > DateTime.Now.Year) || (month > 10 && (year + 8) == DateTime.Now.Year))
                    // to check if it is different year from current
                {
                    Int64 cons = 0;
                    IssueDoc iss = new IssueDoc();
                    ReceiveDoc rec = new ReceiveDoc();
                    Disposal dis = new Disposal();
                    if ((year + 8) > DateTime.Now.Year) // to check if it is hamle and Nehase
                        year = year - 1;
                    month = 10;
                    //}

                    long RecievedQuantity = rec.GetReceivedQuantityTillMonthByUnit(itemId, storeId, month, year,
                                                                                   unitId);
                    long AdjustedQuantity = dis.GetAdjustedQuantityTillMonthByUnit(itemId, storeId, month, year,
                                                                                   unitId);
                    long IssuedQuantity = iss.GetIssuedQuantityTillMonthByUnit(itemId, storeId, month, year, unitId);
                    long LossQuantity = dis.GetLossesQuantityTillMonthByUnit(itemId, storeId, month, year, unitId);
                    // long BalanceQuantity = yEnd.GetBBalance(year, storeId, itemId, month);
                    cons = (RecievedQuantity + AdjustedQuantity - IssuedQuantity - LossQuantity);

                    //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));
                    bb = cons;
                }
            }

            return bb;
        }
        /* 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 toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var us = new User();
            var userID = MainWindow.LoggedinId;
            us.LoadByPrimaryKey(userID);
            var dr = gridView1.GetFocusedDataRow();

            if (dr == null) return;

            //if (us.UserName != "admin")
            //{
            //    XtraMessageBox.Show("You don't have the privilege to update reference number!", "Caution");
            //    return;
            //}

            int tranId = Convert.ToInt32(dr["ID"]);
            var rec = new ReceiveDoc();
            var iss = new IssueDoc();
            var dis = new Disposal();
            rec.LoadByPrimaryKey(tranId);
            iss.GetIssueByBatchAndId(rec.ItemID, rec.BatchNo, rec.ID);
            _dtDate.Value = DateTime.Now;
            _dtDate.CustomFormat = "MM/dd/yyyy";

            //if (iss.RowCount == 0)
            //{
                if ((iss.RowCount != 0) && (iss.RecievDocID != null && iss.RecievDocID == rec.ID))
                {
                    var edRec = new EditReceive(tranId, true);
                    MainWindow.ShowForms(edRec);
                }
            //}
            else if(iss.RowCount ==0)
            {
                var edRec = new EditReceive(tranId, false);
                MainWindow.ShowForms(edRec);
            }
        }
        public List<Order> GetStandardRRFOrders()
        {
            var client = new ServiceRRFLookupClient();
            var orders = new List<Order>();
            var ginfo = new GeneralInfo();
            ginfo.LoadAll();

            var dataView = gridItemChoiceView.DataSource as DataView;
            if (dataView != null)
            {
                dataView.RowFilter = gridItemChoiceView.ActiveFilterString;
                tblRRF = dataView.ToTable();
            }

            var periods = client.GetCurrentReportingPeriod(ginfo.FacilityID, ginfo.ScmsWSUserName, ginfo.ScmsWSPassword);
            var form = client.GetForms(ginfo.FacilityID, ginfo.ScmsWSUserName, ginfo.ScmsWSPassword);

            var rrfs = client.GetFacilityRRForm(ginfo.FacilityID, form[0].Id, periods[0].Id, 1, ginfo.ScmsWSUserName, ginfo.ScmsWSPassword);
            var formCategories = rrfs.First().FormCategories;
            var chosenCategoryBody = formCategories.First(x => x.Id == 1); //TODO:Hard coding to be removed.
            var items = chosenCategoryBody.Pharmaceuticals;

            var user = new User();
            user.LoadByPrimaryKey(MainWindow.LoggedinId);

            var order = new Order
                            {
                                RequestCompletedDate = DateTime.Now,
                                OrderCompletedBy = user.FullName,
                                RequestVerifiedDate = DateTime.Now,
                                OrderTypeId = STANDARD_ORDER,
                                SubmittedBy = user.FullName,
                                SubmittedDate = DateTime.Now,
                                SupplyChainUnitId = ginfo.FacilityID,
                                OrderStatus = 1, //TODO: hardcoding
                                FormId = form[0].Id, //TODO: hardcoding
                                ReportingPeriodId = periods[0].Id //TODO: hardcoding
                            };

            var details = new List<RRFTransactionService.OrderDetail>();

            foreach (DataRow rrfLine in tblRRF.Rows)
            {
                var detail = new RRFTransactionService.OrderDetail();
                var hcmisItemID = Convert.ToInt32(rrfLine["DSItemID"]);
                var rrFormPharmaceutical = items.SingleOrDefault(x => x.PharmaceuticalId == hcmisItemID);
                if (rrFormPharmaceutical != null && Convert.ToString(rrfLine["Status"]) != "Below EOP")
                {
                        detail.BeginningBalance = Convert.ToInt32(rrfLine["BeginingBalance"]);
                        detail.EndingBalance = Convert.ToInt32(rrfLine["SOH"]);
                        detail.QuantityReceived = Convert.ToInt32(rrfLine["Received"]);
                        detail.QuantityOrdered = Convert.ToInt32(rrfLine["Quantity"]);
                        detail.LossAdjustment = Convert.ToInt32(rrfLine["LossAdj"]);
                        detail.ItemId = rrFormPharmaceutical.ItemId;
                        var rdDoc = new ReceiveDoc();
                        var disposal = new Disposal();

                        rdDoc.GetAllWithQuantityLeft(hcmisItemID, _storeID);
                        disposal.GetLossAdjustmentsForLastRrfPeriod(hcmisItemID, _storeID, periods[0].StartDate,
                                                                    periods[0].EndDate);
                        int receiveDocEntries = rdDoc.RowCount;
                        int disposalEntries = disposal.RowCount;

                        if (rdDoc.RowCount == 0 && detail.EndingBalance == 0)
                            detail.Expiries = null;

                        detail.Expiries = new Expiry[receiveDocEntries];
                        detail.Adjustments = new Adjustment[disposalEntries];

                        rdDoc.Rewind();
                        int expiryAmountTotal = 0;

                        for (int j = 0; j < receiveDocEntries; j++)
                        {
                            var exp = new Expiry
                                          {
                                              Amount = Convert.ToInt32(rdDoc.QuantityLeft)
                                          };
                            expiryAmountTotal += exp.Amount;

                            exp.BatchNo = rdDoc.BatchNo;
                            exp.ExpiryDate = rdDoc.ExpDate;
                            if(exp.ExpiryDate > periods[0].EndDate.AddDays(ExpiryTreshHold))
                                exp.Amount = Convert.ToInt32(rdDoc.QuantityLeft);
                                exp.ExpiryDate = periods[0].EndDate;
                            detail.Expiries[j] = exp;
                            rdDoc.MoveNext();
                        }

                        disposal.Rewind();

                        int lossadjamt = 0;
                        for (int j = 0; j < disposalEntries; j++)
                        {
                            var adj = new Adjustment
                            {
                                Amount = Convert.ToInt32(disposal.Quantity),
                                TypeId = 1,
                                ReasonId = 1
                            };
                            lossadjamt += adj.Amount;

                            if (lossadjamt >= detail.LossAdjustment)
                                detail.LossAdjustment = lossadjamt;

                            detail.Adjustments[j] = adj;
                            disposal.MoveNext();
                        }

                        var stockoutIndexedLists = StockoutIndexBuilder.Builder.GetStockOutHistory(hcmisItemID, _storeID);
                        var DOSPerStockOut = stockoutIndexedLists.Count();
                        detail.DaysOutOfStocks = new DaysOutOfStock[stockoutIndexedLists.Count()];

                        for (int j = 0; j < stockoutIndexedLists.Count(); j++)
                        {
                            var dos = new DaysOutOfStock
                                          {
                                              NumberOfDaysOutOfStock = 5,
                                              StockOutReasonId = 5
                                          };
                            detail.DaysOutOfStocks[j] = dos;
                        }
                }
                else if(rrFormPharmaceutical != null && Convert.ToString(rrfLine["Status"]) == "Below EOP")
                {
                        detail.BeginningBalance = null;
                        detail.EndingBalance = null;
                        detail.QuantityReceived = null;
                        detail.QuantityOrdered = null;
                        detail.LossAdjustment = null;
                        detail.ItemId = rrFormPharmaceutical.ItemId;

                        var rdDoc = new ReceiveDoc();
                        var disposal = new Disposal();
                        rdDoc.GetAllWithQuantityLeft(hcmisItemID, _storeID);
                        disposal.GetLossAdjustmentsForLastRrfPeriod(hcmisItemID, _storeID, periods[0].StartDate,periods[0].EndDate);

                        int receiveDocEntries = rdDoc.RowCount;
                        int disposalEntries = disposal.RowCount;

                        if (rdDoc.RowCount == 0 && detail.EndingBalance == 0)
                            detail.Expiries = null;

                        detail.Expiries = new Expiry[receiveDocEntries];
                        detail.Adjustments = new Adjustment[disposalEntries];

                        rdDoc.Rewind();
                        int expiryAmountTotal = 0;
                        for (int j = 0; j < receiveDocEntries; j++)
                        {
                            var exp = new Expiry {Amount = Convert.ToInt32(rdDoc.QuantityLeft)};
                            expiryAmountTotal += exp.Amount;

                            exp.BatchNo = rdDoc.BatchNo;
                            exp.ExpiryDate = rdDoc.ExpDate;
                            if (expiryAmountTotal >= detail.EndingBalance)
                                if (detail.EndingBalance != null)
                                    exp.Amount = exp.Amount - (expiryAmountTotal - detail.EndingBalance.Value);
                            detail.Expiries[j] = null;
                            rdDoc.MoveNext();
                        }

                        disposal.Rewind();

                        int lossadjamt = 0;
                        for (int j = 0; j < disposalEntries; j++)
                        {
                            var adj = new Adjustment
                            {
                                Amount = Convert.ToInt32(disposal.Quantity),
                                TypeId = 11,
                                ReasonId = 39
                            };
                            lossadjamt += adj.Amount;

                            if (lossadjamt >= detail.LossAdjustment)
                                detail.LossAdjustment = lossadjamt;

                            detail.Adjustments[j] = null;
                            disposal.MoveNext();
                        }

                        var stockoutIndexedLists = StockoutIndexBuilder.Builder.GetStockOutHistory(hcmisItemID, _storeID);
                        var DOSPerStockOut = stockoutIndexedLists.Count();
                        detail.DaysOutOfStocks = new DaysOutOfStock[stockoutIndexedLists.Count()];

                        for (int j = 0; j < stockoutIndexedLists.Count(); j++)
                        {
                            var dos = new DaysOutOfStock();
                            dos.NumberOfDaysOutOfStock = 5;
                            dos.StockOutReasonId = 5;
                            detail.DaysOutOfStocks[j] = null;
                        }
                 }
                details.Add(detail);
            }
            order.OrderDetails = details.ToArray();
            orders.Add(order);
            // loop through each record and create order & order details objects
            return orders;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            string valid = ValidateFields();
            if (valid == "true")
            {
                if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Disposal dis = new Disposal();
                    Balance bal = new Balance();
                    ReceiveDoc rec = new ReceiveDoc();
                    DataTable dtAdjVal = (DataTable)AdjustmentGrid.DataSource;
                    for (int i = 0; i < dtAdjVal.Rows.Count; i++)
                    {

                        dis.AddNew();
                        dis.StoreId = Convert.ToInt32(cboStores.EditValue);
                        dis.ItemID = Convert.ToInt32(dtAdjVal.Rows[i]["ID"]);
                        dis.ApprovedBy = txtApprovedBy.Text;
                        DateTime xx = dtAdjustDate.Value;
                        dtAdjustDate.CustomFormat = "MM/dd/yyyy";
                        DateTime dtRec = new DateTime();

                        dis.Date = ConvertDate.DateConverter(dtAdjustDate.Text);
                        dtRec = ConvertDate.DateConverter(dtAdjustDate.Text);

                        dis.RefNo = txtRefNo.Text;
                        dis.BatchNo = dtAdjVal.Rows[i]["Batch No"].ToString();
                        double price = ((Convert.ToDouble(dtAdjVal.Rows[i]["BU Qty"]) != 0) ? (Convert.ToDouble(dtAdjVal.Rows[i]["Price"]) / Convert.ToDouble(dtAdjVal.Rows[i]["BU Qty"])) : 0);
                        dis.Cost = price;
                        dis.Remark = txtRemark.Text;
                        if (dtAdjVal.Rows[i]["Losses"].ToString() != "")
                        {
                            if (Convert.ToInt64(dtAdjVal.Rows[i]["Losses"]) <= Convert.ToInt64(dtAdjVal.Rows[i]["BU Qty"]))
                            {
                                dis.Losses = true;
                                dis.Quantity = Convert.ToInt64(dtAdjVal.Rows[i]["Losses"]);
                            }
                            else
                            {
                                XtraMessageBox.Show("You can't loss more quantity than what you have in the store!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                ResetFields();
                                return;
                            }
                        }
                        else
                        {
                            dis.Losses = false;
                            dis.Quantity = Convert.ToInt64(dtAdjVal.Rows[i]["Adjustment"]);
                        }
                        dis.ReasonId = Convert.ToInt32(dtAdjVal.Rows[i]["Reason"]);
                        if (VisibilitySetting.HandleUnits == 1)
                        {
                            dis.UnitID = 0;
                        }
                        else if (VisibilitySetting.HandleUnits == 2)
                        {
                            dis.UnitID = Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);
                        }
                        else if (VisibilitySetting.HandleUnits == 3)
                        {
                            dis.UnitID = Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);
                        }
                        dis.RecID = Convert.ToInt32(dtAdjVal.Rows[i]["RecID"]);
                        dis.EurDate = dtAdjustDate.Value;
                        dis.Save();

                        rec.LoadByPrimaryKey(Convert.ToInt32(dtAdjVal.Rows[i]["RecID"]));

                        if (rec.RowCount > 0)
                        {
                            if (dis.Losses)
                            {
                                rec.QuantityLeft = rec.QuantityLeft - dis.Quantity;
                                if (rec.QuantityLeft == 0)
                                    rec.Out = true;
                                else
                                    rec.Out = false;
                                //  rec.UnitID = Convert.ToInt32(dtAdjVal.Rows[i]["UnitID"]);
                                rec.Save();
                                //Log Activity, ActivityID for save is 1
                                // logger.SaveAction(1, 1, "Transaction\\LossesAdjustment.cs", "Loss/Adjustmet of " + dis.Quantity +" LOSS has been made.");
                            }
                            else
                            {
                                rec.QuantityLeft = rec.QuantityLeft + dis.Quantity;
                                if (rec.QuantityLeft != 0)
                                    rec.Out = false;
                                else
                                    rec.Out = true;
                                rec.Save();
                                //Log Activity, ActivityID for save is 1
                                //logger.SaveAction(1, 1, "Transaction\\LossesAdjustment.cs", "Loss/Adjustmet of " + dis.Quantity + " ADJUSTMENT has been made.");
                            }
                        }

                        dtAdjustDate.Value = xx;
                    }
                    XtraMessageBox.Show("Transaction successfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ResetFields();
                }
            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }