/// <summary>
        /// Deletes the A receive doc entry.
        /// </summary>
        /// <param name="receiveDocID">The receive doc ID.</param>
        /// <param name="userID">The user ID.</param>
        /// <exception cref="System.Exception"></exception>
        public static void DeleteAReceiveDocEntry(int receiveDocID, int userID)
        {
            var rd = new ReceiveDoc();
                rd.LoadByPrimaryKey(receiveDocID);

                if (rd.RowCount > 0)
                {
                    if (rd.HasTransactions())
                    {
                        string printedIDs = "";

                        var issueDoc = new IssueDoc();
                        issueDoc.LoadByReceiveDocID(rd.ID);

                        issueDoc.Rewind();
                        while (!issueDoc.EOF)
                        {
                            var stvs = new BLL.Issue();
                            stvs.LoadByPrimaryKey(issueDoc.STVID);
                            printedIDs += stvs.IDPrinted.ToString(CultureInfo.InvariantCulture) + " ,";
                            issueDoc.MoveNext();
                        }

                        printedIDs = printedIDs.Remove(printedIDs.Length - 1, 1);
                        throw new Exception(
                            string.Format("Please cancel/void the following Stvs: With PrintedIDs : {0}", printedIDs));
                    }

                    HandleReceiveDocDeleting(receiveDocID, userID, rd);
                }
        }
 private static void AddIssueLodDelete(IssueDoc iss)
 {
     IssueDocDeleted isdelete = new IssueDocDeleted();
     isdelete.AddNew();
     isdelete.ID = iss.ID;
     isdelete.ItemID = iss.ItemID;
     isdelete.StoreId = iss.StoreId;
     isdelete.ReceivingUnitID = iss.ReceivingUnitID;
     isdelete.LocalBatchNo = iss.LocalBatchNo;
     isdelete.Quantity = iss.Quantity;
     isdelete.Date = iss.Date;
     isdelete.IsTransfer = iss.IsTransfer;
     isdelete.IssuedBy = iss.IssuedBy;
     isdelete.Remark = iss.Remark;
     isdelete.RefNo = iss.RefNo;
     isdelete.BatchNo = iss.BatchNo;
     isdelete.IsApproved = iss.IsApproved;
     isdelete.Cost = iss.Cost;
     isdelete.NoOfPack = iss.NoOfPack;
     isdelete.QtyPerPack = iss.QtyPerPack;
     isdelete.DUSOH = iss.DUSOH;
     isdelete.EurDate = iss.EurDate;
     isdelete.RecievDocID = iss.RecievDocID;
     isdelete.RecomendedQty = iss.RecomendedQty;
     isdelete.Save();
 }
Exemplo n.º 3
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);
        }
        /// <summary>
        /// Gets the cost of good sold.
        /// </summary>
        /// <param name="AccountID">The account ID.</param>
        /// <returns></returns>
        public static DataView GetCostOfGoodSold(int AccountID, DateTime aDate, DateTime bDate)
        {
            IssueDoc report = new IssueDoc();
            var      query  = HCMIS.Repository.Queries.IssueDoc.SelectGetCostOfGoodSold(AccountID, aDate, bDate);

            report.LoadFromRawSql(query);
            return(report.DefaultView);
        }
        /// <summary>
        /// Returns IssueDoc history for a receiving unit
        /// Columns: ID,Date(Converted to Ethiopian),Quantity,FullItemName
        /// </summary>
        /// <param name="receivingUnitID">The receiving unit ID.</param>
        /// <param name="startDate">In European Calendar</param>
        /// <param name="endDate">In European Calendar</param>
        /// <returns></returns>
        public static object GetIssueHistoryForFacility(int receivingUnitID, DateTime startDate, DateTime endDate)
        {
            var      query = HCMIS.Repository.Queries.IssueDoc.SelectGetIssueHistoryForFacility(receivingUnitID, startDate, endDate);
            IssueDoc issD  = new IssueDoc();

            issD.LoadFromRawSql(query);
            return(DateTimeHelper.AddEthiopianDateField(issD).DefaultView);
        }
        /// <summary>
        /// Gets the last issued date for the Facility
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public static DateTime GetLastIssuedDate()
        {
            BLL.IssueDoc id = new IssueDoc();
            id.LoadFromRawSql(String.Format("SELECT TOP (1) EurDate FROM IssueDoc ORDER BY EurDate DESC"));
            DateTime dt = (id.DataTable.Rows.Count > 0) ? Convert.ToDateTime(id.DataTable.Rows[0]["EurDate"]) : new DateTime();

            return dt;
        }
        /// <summary>
        /// Tops the item receivers.
        /// </summary>
        /// <param name="itemID">The item ID.</param>
        /// <returns></returns>
        public static DataTable TopItemReceivers(int itemID)
        {
            IssueDoc issueDoc = new IssueDoc();
            var      query    = HCMIS.Repository.Queries.IssueDoc.SelectTopItemReceivers(itemID);

            issueDoc.LoadFromRawSql(query);
            return(issueDoc.DataTable);
        }
        /// <summary>
        /// Returns the Issue summary by item by supplier.
        /// </summary>
        /// <param name="dtFrom">The dt from.</param>
        /// <param name="dtTo">The dt to.</param>
        /// <param name="storeTypeID">The store type ID.</param>
        /// <returns></returns>
        public static DataTable GetIssueBreakdownBySupplier(DateTime dtFrom, DateTime dtTo, int storeTypeID)
        {
            var      query = HCMIS.Repository.Queries.IssueDoc.SelectGetIssueBreakdownBySupplier(dtFrom, dtTo, storeTypeID);
            IssueDoc id    = new IssueDoc();

            id.LoadFromRawSql(query);
            return(id.DataTable);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Gets the last issued date for the Facility
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public static DateTime GetLastIssuedDate()
        {
            BLL.IssueDoc id = new IssueDoc();
            id.LoadFromRawSql(String.Format("SELECT TOP (1) EurDate FROM IssueDoc ORDER BY EurDate DESC"));
            DateTime dt = (id.DataTable.Rows.Count > 0) ? Convert.ToDateTime(id.DataTable.Rows[0]["EurDate"]) : new DateTime();

            return(dt);
        }
        public static DataTable GetOutstandingRequestedVoidForInvoice(int warehouseID = 0)
        {
            string query =
                HCMIS.Repository.Queries.IssueDoc.SelectGetOutstandingRequestedVoidForInvoice(warehouseID, OrderStatus.Constant.ORDER_APPROVED, OrderStatus.Constant.ISSUED);
            IssueDoc issueDoc = new IssueDoc();

            issueDoc.LoadFromRawSql(query);
            return(issueDoc.DataTable);
        }
        public static DataView CostOfSales(int ethiopianMonth, int ethiopianYear, int modeID)
        {
            IssueDoc issueDoc = new IssueDoc();
            string   query    =
                HCMIS.Repository.Queries.IssueDoc.SelectCostOfSales(ethiopianMonth, ethiopianYear, modeID);

            issueDoc.LoadFromRawSql(query);
            return(issueDoc.DefaultView);
        }
 public static void RecordDiscrepancy(Dictionary <int, decimal> _discrepancyIssueDoc)
 {
     foreach (int issueDocID in _discrepancyIssueDoc.Keys)
     {
         BLL.IssueDoc issueDoc = new IssueDoc();
         issueDoc.LoadByPrimaryKey(issueDocID);
         issueDoc.NoOfPackIssued = _discrepancyIssueDoc[issueDocID];
         issueDoc.Save();
     }
 }
 private void EditIssueDocRefrenceNo_Load(object sender, EventArgs e)
 {
     dtRecDate.Value = DateTime.Now;
     dtRecDate.CustomFormat = "MM/dd/yyyy";
     if(_refno!=null)
     {
         var iss = new IssueDoc();
         iss.GetTransactionByRefNo(_refno);
         DateTime dtDate = Convert.ToDateTime(iss.Date.ToString("MM/dd/yyyy"));
         txtDate.Text = dtDate.ToShortDateString();
         txtRefNo.Text = iss.RefNo;
     }
 }
        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;
        }
        public void PopulateItemList(DataTable dtItem)
        {
            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Value = 1;
            progressBar1.Maximum = dtItem.Rows.Count;

            lstItem.Items.Clear();
            int col = 0;
            int count = 1;
            int storeId = (cboStores.SelectedValue != null) ? Convert.ToInt32(cboStores.SelectedValue) : 1;
            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            DateTime dtCurrent = new DateTime();
            dtCurrent = ConvertDate.DateConverter(dtDate.Text);

            IssueDoc issues = new IssueDoc();
            foreach (DataRow dr in dtItem.Rows)
            {
                string itemName = dr["ItemName"].ToString() + " - " + dr["DosageForm"].ToString() + " - " + dr["Strength"].ToString();
                Int64[] obj = new Int64[recId.Length];
                int itemId = Convert.ToInt32(dr["ID"]);
                string[] str = new string[recId.Length + 2];
                str[0] = count.ToString();
                str[1] = itemName;
                for (int j = 0; j < recId.Length; j++)
                {
                   obj[j] =  issues.GetIssuedQuantityByReceivingUnit(itemId,storeId,recId[j],dtCurrent.Year);
                    str[j + 2] = (obj[j] != 0)?obj[j].ToString("#,###"): "0";
                }

                ListViewItem listItem = new ListViewItem(str);
                listItem.ToolTipText = itemName;
                listItem.Tag = dr["ID"];
                if (col != 0)
                {
                    listItem.BackColor = Color.FromArgb(233, 247, 248);
                    col = 0;
                }
                else
                {
                    col++;
                }
                lstItem.Items.Add(listItem);
                count++;
                progressBar1.PerformStep();
            }
            progressBar1.Visible = false;
        }
        public static bool CheckOutStandingIssues(int warehouseID = 0)
        {
            Warehouse warehouse = new Warehouse();

            warehouse.LoadAll();

            string query =
                HCMIS.Repository.Queries.IssueDoc.SelectCheckOutStandingIssues(warehouseID, warehouse.RowCount,
                                                                               OrderStatus.Constant.ORDER_APPROVED,
                                                                               OrderStatus.Constant.ISSUED);
            IssueDoc issueDoc = new IssueDoc();

            issueDoc.LoadFromRawSql(query);
            return(issueDoc.Getint("count") == 0);
        }
Exemplo n.º 17
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);
        }
        public static bool CanInventoryBeStarted(int physicalStoreID)
        {
            BLL.PhysicalStore ps = new PhysicalStore();
            ps.LoadByPrimaryKey(physicalStoreID);
            int warehouseID = ps.PhysicalStoreTypeID;

            if (!ReceiveDoc.checkOutstandingReceives(warehouseID))
            {
                return(false);
            }
            if (!IssueDoc.CheckOutStandingIssues(warehouseID))
            {
                return(false);
            }
            return(true);
        }
        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)
                {
                    IssueDoc iss = new IssueDoc();
                    ReceiveDoc rec = new ReceiveDoc();

                    iss.LoadByPrimaryKey(_tranId);

                    string batchNo = iss.BatchNo;
                    Int64 qty = iss.Quantity;
                    rec.GetTransactionByBatch(iss.ItemID, iss.BatchNo, iss.StoreId);

                    iss.RefNo = txtRefNo.Text;
                    iss.BatchNo = txtBatchNo.Text;
                    iss.NoOfPack = Convert.ToInt32(txtPack.Text);
                    iss.QtyPerPack = Convert.ToInt32(txtQtyPack.Text);
                    iss.Quantity = Convert.ToInt32(txtPack.Text) * Convert.ToInt32(txtQtyPack.Text);
                    iss.StoreId = Convert.ToInt32(cboStores.SelectedValue);
                    iss.ReceivingUnitID = Convert.ToInt32(cboReceivingUnit.SelectedValue);
                    iss.Remark = txtRemark.Text;
                    iss.IssuedBy = txtReceivedBy.Text;
                    iss.Save();

                    Int64 newQty = 0;
                    if(qty > iss.Quantity)
                        newQty = rec.QuantityLeft + (qty - iss.Quantity);
                    else
                        newQty = rec.QuantityLeft - (iss.Quantity - qty);

                    rec.QuantityLeft = newQty;
                    if(rec.QuantityLeft >0)
                        rec.Out = false;
                    rec.Save();

                    XtraMessageBox.Show("Transaction Succsfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        /// <summary>
        /// Gets the weekly transaction summary.
        /// </summary>
        /// <param name="days">-1 for all</param>
        /// <returns></returns>
        public static DataView GetWeeklyTransactionSummary(int days)
        {
            string query;

            if (days == -1)
            {
                query = HCMIS.Repository.Queries.IssueDoc.SelectGetWeeklyTransactionSummary();
            }
            else
            {
                query = HCMIS.Repository.Queries.IssueDoc.SelectGetWeeklyTransactionSummary(days);
            }

            IssueDoc issueDoc = new IssueDoc();

            issueDoc.LoadFromRawSql(query);
            return(issueDoc.DefaultView);
        }
        /// <summary>
        /// Returns issue summary Date against value
        /// </summary>
        /// <param name="days">For the past how many days (Enter -1 for all)</param>
        /// <returns></returns>
        public static object GetIssueSummary(int days)
        {
            //For use in the dashboard primarily
            string query;

            if (days == -1)
            {
                query = HCMIS.Repository.Queries.IssueDoc.SelectGetIssueSummary();
            }
            else
            {
                query = HCMIS.Repository.Queries.IssueDoc.SelectGetIssueSummary(days);
            }
            IssueDoc iss = new IssueDoc();

            iss.LoadFromRawSql(query);
            return(iss.DefaultView);
        }
        public static DataView IssuedAmoutByYear(int ethiopianYear, int accountID, bool showBySellingPrice)
        {
            IssueDoc issueDoc = new IssueDoc();
            string   query;

            if (showBySellingPrice)
            {
                query =
                    HCMIS.Repository.Queries.IssueDoc.SelectIssuedAmoutByYearShowBySellingPrice(ethiopianYear, accountID);
            }
            else
            {
                query =
                    HCMIS.Repository.Queries.IssueDoc.SelectIssuedAmoutByYear(ethiopianYear, accountID);
            }

            issueDoc.LoadFromRawSql(query);
            return(issueDoc.DefaultView);
        }
        /// <summary>
        /// Get begining balance by item, store and month
        /// </summary>
        /// <param name="year">The year.</param>
        /// <param name="storeId">The store id.</param>
        /// <param name="itemId">The item id.</param>
        /// <param name="month">The month.</param>
        /// <returns></returns>
        public Int64 GetBBalance(int year, int storeId, int itemId, int month)
        {
            this.FlushData();
            Int64 bb    = 0;
            int   bYear = ((month > 10) ? year : year - 1);

            this.LoadFromRawSql(HCMIS.Repository.Queries.YearEnd.SelectGetBBalance(storeId, itemId, bYear));
            if (this.DataTable.Rows.Count > 0)
            {
                bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
            }
            else
            {
                this.LoadFromRawSql(HCMIS.Repository.Queries.YearEnd.SelectGetBBalanceSelectElse(year, storeId, itemId));
                if (this.DataTable.Rows.Count > 0)
                {
                    bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
                }
                else if (((year + 8) > DateTimeHelper.ServerDateTime.Year) || (month > 10 && (year + 8) == DateTimeHelper.ServerDateTime.Year)) // to check if it is different year from current
                {
                    Int64             cons = 0;
                    IssueDoc          iss  = new IssueDoc();
                    ReceiveDoc        rec  = new ReceiveDoc();
                    LossAndAdjustment dis  = new LossAndAdjustment();
                    if ((year + 8) > DateTimeHelper.ServerDateTime.Year) // to check if it is hamle and Nehase
                    {
                        year = year - 1;
                    }
                    month = 10;
                    //}

                    long receivedQuantity = rec.GetReceivedQuantityTillMonth(itemId, storeId, month, year);
                    long adjustedQuantity = dis.GetAdjustedQuantityTillMonth(itemId, storeId, month, year);
                    long issuedQuantity   = iss.GetIssuedQuantityTillMonth(itemId, storeId, month, year);
                    long lostQuantity     = dis.GetLossesQuantityTillMonth(itemId, storeId, month, year);
                    cons = (receivedQuantity + adjustedQuantity - issuedQuantity - lostQuantity);
                    bb   = cons;
                }
            }

            return(bb);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Marks as dispatched.
        /// </summary>
        /// <param name="userID">The user ID.</param>
        /// <param name="prePrintedSTV">The pre printed STV.</param>
        /// <returns></returns>
        public bool MarkAsDispatched(int userID, int?prePrintedSTV)
        {
            if (!this.IsColumnNull("VoidRequest"))
            {
                if ((this.VoidRequest && this.IsColumnNull("VoidApprovedByUserID"))) //If the approver hasn't acted on the void request.
                {
                    return(false);
                }
            }
            //Mark the NoOfPackIssued equal to the NoOfPack.  Discrepancies are supposed to be saved after this function has finished running.
            var query = HCMIS.Repository.Queries.Issue.UpdateMarkAsDispatched(userID, this.ID);

            var queryConfirmIssue = HCMIS.Repository.Queries.Issue.UpdateMarkAsDispatched(this.ID);

            if (prePrintedSTV.HasValue)
            {
                this.PrePrintedInvoiceNo = prePrintedSTV.Value;
                this.Save();
            }

            BLL.Issue s = new Issue();
            s.LoadFromRawSql(query);
            s.LoadFromRawSql(queryConfirmIssue);

            BLL.IssueDoc isDoc = new IssueDoc();
            isDoc.Where.STVID.Value = this.ID;
            isDoc.Query.Load();
            if (isDoc.RowCount > 0)
            {
                int       orderID = isDoc.OrderID;
                BLL.Order ord     = new Order();
                ord.LoadByPrimaryKey(orderID);
                if (ord.RowCount > 0)
                {
                    ord.ChangeStatus(OrderStatus.Constant.DISPATCH_CONFIRMED, CurrentContext.UserId);
                    ord.Save();
                }
            }

            return(true);
        }
Exemplo n.º 25
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);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Adds a new delete log
        /// </summary>
        /// <param name="deletedissDoc">The IssueDoc Object to be deleted</param>
        /// <param name="userID">The user ID.</param>
        public static void AddNewLog(IssueDoc deletedissDoc, int userID)
        {
            while (!deletedissDoc.EOF)
            {
                BLL.IssueDocDeleted issLog = new IssueDocDeleted();
                issLog.AddNew();
                foreach (DataColumn col in deletedissDoc.DefaultView.Table.Columns)
                {// the try catch is to make sure the database schema change doesn't mess this method
                    try
                    {
                        issLog.SetColumn(col.ColumnName, deletedissDoc.GetColumn(col.ColumnName));
                    }
                    catch
                    {
                    }
                }

                issLog.DeletedBy   = userID;
                issLog.DateDeleted = DateTimeHelper.ServerDateTime;
                issLog.Save();
                deletedissDoc.MoveNext();
            }
        }
        private void cboStores_EditValueChanged(object sender, EventArgs e)
        {
            if (cboStores.EditValue != null)
            {
                IssueDoc iss = new IssueDoc();
                //TODO: To be implemented

               // DataTable dtRec = iss.GetDistinctIssueDocments(Convert.ToInt32(cboStores.EditValue));
               // /*PopulateDocument(dtRec);*/lstTree.DataSource = dtRec;
               // DateTime dt1 = new DateTime();
               // DateTime dt2 = new DateTime();
               // CalendarLib.DateTimePickerEx dtDate = new CalendarLib.DateTimePickerEx();
               // dtDate.Value = DateTime.Now;
               // dtDate.CustomFormat = "MM/dd/yyyy";
               // DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);
               // int yr = ((dtCurrent.Month > 10) ? dtCurrent.Year : dtCurrent.Year - 1);
               // dt1 = new DateTime(yr, 11, 1);
               // dt2 = new DateTime(dtCurrent.Year, dtCurrent.Month, dtCurrent.Day);
               // dtRec = iss.GetTransactionByDateRange(Convert.ToInt32(cboStores.EditValue), dt1, dt2);
               // lblIssDate.Text = "Current Year";
               //gridIssues.DataSource = dtRec;
            }
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            var isd = new IssueDoc();
            DataTable dtbl = isd.GetTransactionByRefNo(_refno);
            if (isd.RowCount > 0)
            {
                foreach (DataRow datarow in dtbl.Rows)
                {
                    datarow["RefNo"] = txtRefNo.Text;
                    datarow["Date"] = txtDate.Text;

                }
                isd.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();
        }
        /// <summary>
        /// Adds a new delete log
        /// </summary>
        /// <param name="deletedissDoc">The IssueDoc Object to be deleted</param>
        /// <param name="userID">The user ID.</param>
        public static void AddNewLog(IssueDoc deletedissDoc, int userID)
        {
            while (!deletedissDoc.EOF)
            {
                BLL.IssueDocDeleted issLog = new IssueDocDeleted();
                issLog.AddNew();
                foreach (DataColumn col in deletedissDoc.DefaultView.Table.Columns)
                {// the try catch is to make sure the database schema change doesn't mess this method
                    try
                    {
                        issLog.SetColumn(col.ColumnName, deletedissDoc.GetColumn(col.ColumnName));
                    }
                    catch
                    {

                    }
                }

                issLog.DeletedBy = userID;
                issLog.DateDeleted = DateTimeHelper.ServerDateTime;
                issLog.Save();
                deletedissDoc.MoveNext();
            }
        }
        private void tpDelete_Click(object sender, EventArgs e)
        {
            DataRow dr = gridViewBinCard.GetFocusedDataRow();
             if (Convert.ToInt32(dr["Precedance"]) != 3)
             {
             XtraMessageBox.Show("You cannot delete this");
             return;
             }
             if (CurrentContext.LoggedInUser.UserType == UserType.Constants.DISTRIBUTION_MANAGER_WITH_DELETE)
             {

             if (
                 XtraMessageBox.Show(
                     "Are you sure you want to delete this transaction? You will not be able to undo this.",
                     "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
             {
                 MyGeneration.dOOdads.TransactionMgr tranMgr =
                     MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

                 try
                 {
                     tranMgr.BeginTransaction();

                     ReceiveDoc rdoc = new ReceiveDoc();
                     ReceivePallet rp = new ReceivePallet();
                     IssueDoc idoc = new IssueDoc();

                     PickListDetail pld = new PickListDetail();
                     int issueID = Convert.ToInt32(dr["ID"]);
                     //pld.LoadByOrderAndItem(Convert.ToInt32(dr["OrderID"]), Convert.ToInt32(dr["ItemID"]),
                     //                       Convert.ToInt32(dr["Quantity"]));
                     idoc.LoadByPrimaryKey(issueID);
                     pld.LoadByPrimaryKey(idoc.PLDetailID);

                     string RefNo = idoc.RefNo;

                     rdoc.LoadByPrimaryKey(idoc.RecievDocID);

                     //if (pld.RowCount == 0)
                     //{
                     //    pld.LoadByOrderAndItem(Convert.ToInt32(dr["OrderID"]), Convert.ToInt32(dr["ItemID"]));
                     //}

                     rp.LoadByPrimaryKey(pld.ReceivePalletID);
                     PalletLocation pl = new PalletLocation();
                     pl.loadByPalletID(rp.PalletID);

                     if (pl.RowCount == 0)
                     {
                         pl.LoadByPrimaryKey(pld.PalletLocationID);
                         if (pl.IsColumnNull("PalletID"))
                         {
                             pl.PalletID = rp.PalletID;
                             pl.Save();
                         }
                         //rp.LoadNonZeroRPByReceiveID(rdoc.ID);
                     }

                     if (rp.RowCount == 0)
                     {
                         XtraMessageBox.Show("You cannot delete this item, please contact the administrator", "Error");
                         return;
                     }
                     if (rp.RowCount > 0)
                     {
                         rdoc.QuantityLeft += idoc.Quantity;
                         rp.Balance += idoc.Quantity;
                         pld.QuantityInBU = 0;

                         // are we adding it the pick face?
                         // if so add it to the balance of the pick face also
                         pl.loadByPalletID(rp.PalletID);

                         if (pl.RowCount == 0)
                         {
                             PutawayLocation plocation = new PutawayLocation(rdoc.ItemID);

                             // we don't have a location for this yet,
                             // select a new location
                             //PutawayLocataion pl = new PutawayLocataion();
                             if (plocation.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                             {
                                 pl.LoadByPrimaryKey(plocation.PalletLocationID);
                                 if (pl.RowCount > 0)
                                 {
                                     pl.PalletID = rp.PalletID;
                                     pl.Save();
                                 }
                             }
                         }

                         if (pl.RowCount > 0)
                         {

                             PickFace pf = new PickFace();
                             pf.LoadByPalletLocation(pl.ID);
                             if (pf.RowCount > 0)
                             {
                                 pf.Balance += Convert.ToInt32(idoc.Quantity);
                                 pf.Save();
                             }

                             IssueDocDeleted.AddNewLog(idoc, CurrentContext.UserId);
                             idoc.MarkAsDeleted();
                             rdoc.Save();
                             rp.Save();
                             idoc.Save();

                             // now refresh the window
                             XtraMessageBox.Show("Issue Deleted!", "Confirmation", MessageBoxButtons.OK,
                                                 MessageBoxIcon.Information);
                             tranMgr.CommitTransaction();
                             //TODO: refresh the list
                             // gridViewReferences_FocusedRowChanged(null, null);
                         }

                     }
                     else
                     {
                         XtraMessageBox.Show(
                             "This delete is not successfull because a free pick face location was not selected. please select a free location and try again.",
                             "Error Deleteing issue transaction", MessageBoxButtons.OK, MessageBoxIcon.Error);
                         tranMgr.RollbackTransaction();
                     }
                 }
                 catch
                 {
                     XtraMessageBox.Show("This delete is not successfull", "Warning ...", MessageBoxButtons.OK,
                                         MessageBoxIcon.Warning);
                     tranMgr.RollbackTransaction();
                 }
             }
             }
             else
             {
             XtraMessageBox.Show(
                 "You cannot delete this transaction because you don't have previlage. Please contact the administrator if you thing this is an error.",
                 "Delete is not allowed");
             }
        }
        /// <summary>
        /// Get begining balance by item, store and month
        /// </summary>
        /// <param name="year">The year.</param>
        /// <param name="storeId">The store id.</param>
        /// <param name="itemId">The item id.</param>
        /// <param name="month">The month.</param>
        /// <returns></returns>
        public Int64 GetBBalance(int year, int storeId, int itemId, int month)
        {
            this.FlushData();
            Int64 bb = 0;
            int bYear = ((month > 10) ? year : year - 1);
            this.LoadFromRawSql(HCMIS.Repository.Queries.YearEnd.SelectGetBBalance(storeId, itemId, bYear));
            if (this.DataTable.Rows.Count > 0)
            {
                bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
            }
            else
            {
                this.LoadFromRawSql(HCMIS.Repository.Queries.YearEnd.SelectGetBBalanceSelectElse(year, storeId, itemId));
                if (this.DataTable.Rows.Count > 0)
                {
                    bb = Convert.ToInt64(this.DataTable.Rows[0]["PhysicalInventory"]);
                }
                else if (((year + 8) > DateTimeHelper.ServerDateTime.Year) || (month > 10 && (year + 8) == DateTimeHelper.ServerDateTime.Year)) // to check if it is different year from current
                {
                    Int64 cons = 0;
                    IssueDoc iss = new IssueDoc();
                    ReceiveDoc rec = new ReceiveDoc();
                    LossAndAdjustment dis = new LossAndAdjustment();
                    if ((year + 8) > DateTimeHelper.ServerDateTime.Year) // to check if it is hamle and Nehase
                        year = year - 1;
                    month = 10;
                    //}

                    long receivedQuantity = rec.GetReceivedQuantityTillMonth(itemId, storeId, month, year);
                    long adjustedQuantity = dis.GetAdjustedQuantityTillMonth(itemId, storeId, month, year);
                    long issuedQuantity = iss.GetIssuedQuantityTillMonth(itemId, storeId, month, year);
                    long lostQuantity = dis.GetLossesQuantityTillMonth(itemId, storeId, month, year);
                    cons = (receivedQuantity + adjustedQuantity - issuedQuantity - lostQuantity);
                    bb = cons;
                }
            }

            return bb;
        }
        /// <summary>
        /// Fix For Delivery Note When Converting Do not use under any other situation
        /// </summary>
        /// <param name="issueDocID"></param>
        /// <param name="picklistID"></param>
        /// <returns></returns>
        public PickListDetail FixDeliveryNoteCostReceiveDoc(int issueDocID, int picklistID)
        {
            IssueDoc issueDoc = new IssueDoc();
            issueDoc.LoadByPrimaryKey(issueDocID);
            PickListDetail pickList = new PickListDetail();
            pickList.LoadByPrimaryKey(picklistID);
            //safety first
            if (issueDoc.RecievDocID != pickList.ReceiveDocID)
            {
                Item item = new Item();
                item.LoadByPrimaryKey(picklistID);
                throw new Exception(String.Format("PicklistDetail vs IssueDoc Inconsistancy for Item {0}", item.FullItemName));

            }
            // now we are sure we have one ReceiveDocID
            ReceiveDoc receiveDoc = new ReceiveDoc();
            receiveDoc.LoadByPrimaryKey(pickList.ReceiveDocID);
            ReceiveDocConfirmation receiveDocConfirmation = new ReceiveDocConfirmation();
            receiveDocConfirmation.LoadByReceiveDocID(receiveDoc.ID);
            //Check if it has been Printed and that Selling Price and Cost is set
            if (receiveDocConfirmation.ReceiptConfirmationStatusID == ReceiptConfirmationStatus.Constants.GRV_PRINTED)
            {
                double unitPrice, unitCost, margin;
                if (Settings.IsCenter == true && !receiveDoc.IsColumnNull("Cost") && receiveDoc.Cost != 0)
                {
                    unitPrice = Math.Round(receiveDoc.Cost, 2);
                    unitCost = Math.Round(receiveDoc.Cost, 2);
                    margin = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;

                }
                else if (!receiveDoc.IsColumnNull("SellingPrice") && receiveDoc.SellingPrice != 0)
                {
                    unitPrice = Math.Round(receiveDoc.SellingPrice, 2);
                    unitCost = Math.Round(receiveDoc.SellingPrice, 2);
                    margin = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;

                }
                else
                {
                    var item = new Item();
                    item.LoadByPrimaryKey(pickList.ItemID);
                    throw new Exception(String.Format("Price Not set For item: {0}", item.FullItemName));
                }
                pickList.UnitPrice = unitPrice;
                pickList.Cost = Convert.ToDouble(pickList.Packs) * unitPrice;
                issueDoc.SellingPrice = Convert.ToDecimal(unitPrice);
                issueDoc.Cost = Convert.ToDouble(issueDoc.NoOfPack) * unitPrice;
                issueDoc.UnitCost = Convert.ToDecimal(unitCost);
                issueDoc.Margin = Convert.ToDecimal(margin);
                pickList.Save();
                issueDoc.Save();
            }
            else
            {
                var item = new Item();
                item.LoadByPrimaryKey(pickList.ItemID);
                throw new Exception(String.Format("GRV/IGRV Not Printed For Item: {0}", item.FullItemName));
            }
            return pickList;
        }
        private void PrintReceiptConfirmation(string referenceNumber, int? reprintOfReceiptConfirmationPrintoutID)
        {
            var rc = new ReceiptConfirmationPrintout();
            var srmPrintout = new HCMIS.Desktop.Reports.SRMPrintout(CurrentContext.LoggedInUserName);

            int ReceiptID = Convert.ToInt32(gridReceiveView.GetFocusedDataRow()["ReceiptID"]);
            var receiveDoc = new ReceiveDoc();
            receiveDoc.LoadByReceiptID(ReceiptID);
            ReceiptConfirmationPrintout.GetGRNFNo(ReceiptID);
            srmPrintout.BranchName.Text = GeneralInfo.Current.HospitalName;
            rc.PrepareDataForPrintout(ReceiptID, CurrentContext.UserId, false, 3, null,
                                                  reprintOfReceiptConfirmationPrintoutID,FiscalYear.Current);
            srmPrintout.DataSource = rc.DefaultView.ToTable();

            var rUnit = new Institution();
            var idoc = new IssueDoc();
            if (!receiveDoc.IsColumnNull("ReturnedFromIssueDocID"))
            {
                idoc.LoadByPrimaryKey(receiveDoc.ReturnedFromIssueDocID);
                rUnit.LoadByPrimaryKey(idoc.ReceivingUnitID);
            }
            else
            {
                var po = new PO();
                po.LoadByReceiptID(receiveDoc.ReceiptID);
                rUnit.LoadByPrimaryKey(int.Parse(po.RefNo));
            }

            srmPrintout.xrFromValue.Text = rUnit.Name;
            srmPrintout.xrWoredaValue.Text = rUnit.WoredaText;
            srmPrintout.xrRegionValue.Text = rUnit.Region;
            srmPrintout.xrZoneValue.Text = rUnit.ZoneText;

            if (!receiveDoc.IsColumnNull("ReturnedFromIssueDocID"))
            {
                var stvLog = new BLL.Issue();
                stvLog.LoadByPrimaryKey(idoc.STVID);

                srmPrintout.xrIssueDateValue.Text = idoc.Date.ToString("M/d/yyyy");
                var activity = new Activity();
                activity.LoadByPrimaryKey(idoc.StoreId);
                 srmPrintout.xrAccountName.Text = activity.FullActivityName;
                var rct = new BLL.Receipt();
                rct.LoadByPrimaryKey(ReceiptID);
                var rctInvoice = new ReceiptInvoice();
                rctInvoice.LoadByPrimaryKey(rct.ReceiptInvoiceID);
                srmPrintout.xrSTVNoValue.Text = rctInvoice.STVOrInvoiceNo;
            }
            else
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(receiveDoc.StoreID);
                srmPrintout.xrAccountName.Text = activity.FullActivityName;
                srmPrintout.xrSTVNoValue.Text = receiveDoc.RefNo;
            }

            var dtDate = new DateTimePickerEx();
            dtDate.Value = receiveDoc.EurDate;
            srmPrintout.Date.Text = dtDate.Text;
            if (srmPrintout.PrintDialog() != DialogResult.OK)
            {
                throw new Exception("Print cancelled by user!");
            }

            //Successfully printed

            //Release Product
            var GRV = new CostCalculator();
            GRV.LoadGRV(ReceiptID);
            GRV.ReleaseForIssue();

            String reference = gridReceiveView.GetFocusedDataRow()["RefNo"].ToString();
            var recDoc = new ReceiveDoc();
            recDoc.LoadByReferenceNo(reference);
            recDoc.ConfirmGRVPrinted(CurrentContext.UserId);
            BLL.Receipt receiptStatus = new BLL.Receipt();
            receiptStatus.LoadByPrimaryKey(ReceiptID);
            receiptStatus.ChangeStatus(ReceiptConfirmationStatus.Constants.GRV_PRINTED, null, this.GetFormIdentifier(), CurrentContext.UserId, "GRV Printed");
            BindFormContents();
        }
 /// <summary>
 /// Saves the STVI dby pick list details.
 /// </summary>
 /// <param name="plDetailIDs">The pl detail I ds.</param>
 /// <param name="stvID">The STV ID.</param>
 private static void SaveSTVIDbyPickListDetails(string plDetailIDs, int stvID)
 {
     IssueDoc iDoc = new IssueDoc();
     iDoc.LoadByIDs(plDetailIDs);
     while (!iDoc.EOF)
     {
         iDoc.STVID = stvID;
         iDoc.Save();
         iDoc.MoveNext();
     }
 }
Exemplo n.º 35
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;
        }
        /// <summary>
        /// Filters the STV log.
        /// </summary>
        private void FilterStvLog()
        {
            if (lkAccount.EditValue != null)
            {
                var iss = new IssueDoc();
                gridReferences.DataSource = lkRoute.EditValue == null ? iss.GetDistinctIssueDocmentsForAccount(Convert.ToInt32(lkAccount.EditValue), chkDeliveryNotes.Checked) : iss.GetDistinctIssueDocmentsForAccountAndRoute(Convert.ToInt32(lkAccount.EditValue), Convert.ToInt32(lkRoute.EditValue), chkDeliveryNotes.Checked);

                // apply the filter
                txtFilterFacilityName_EditValueChanged(null, null);
                // show details of the first entry in the table
               // gridViewReferences_FocusedRowChanged(null, null);

            }
        }
        public static void DeleteIssueDoc(int issueID)
        {
            MyGeneration.dOOdads.TransactionMgr tranMgr =
                MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                tranMgr.BeginTransaction();

                var pld = new PickListDetail();
                var rdoc = new ReceiveDoc();
                var rp = new ReceivePallet();
                var idoc = new IssueDoc();

                idoc.LoadByPrimaryKey(issueID);
                pld.LoadByPrimaryKey(idoc.PLDetailID);
                rdoc.LoadByPrimaryKey(idoc.RecievDocID);

                rp.LoadByPrimaryKey(pld.ReceivePalletID);
                var pl = new PalletLocation();
                pl.loadByPalletID(rp.PalletID);

                if (pl.RowCount == 0)
                {
                    pl.LoadByPrimaryKey(pld.PalletLocationID);
                    if (pl.IsColumnNull("PalletID"))
                    {
                        pl.PalletID = rp.PalletID;
                        pl.Save();
                    }
                }

                if (rp.RowCount == 0)
                {
                    XtraMessageBox.Show("You cannot delete this item, please contact the administrator", "Error");
                    return;
                }
                if (rp.RowCount > 0)
                {
                    // in error cases this could lead to a number greater than the received quantity
                    // instead of being an error, it should just delete the respective issue and
                    // adjust the remaining quantity to the received quantity.
                    if (rdoc.QuantityLeft + idoc.Quantity > rdoc.Quantity)
                    {
                        rdoc.QuantityLeft = rp.Balance = rdoc.Quantity;
                    }
                    else
                    {
                        rdoc.QuantityLeft += idoc.Quantity;
                        rp.Balance += idoc.Quantity;
                    }

                    //Delete from picklistDetail and add to pickListDetailDeleted
                    PickListDetailDeleted.AddNewLog(pld, BLL.CurrentContext.UserId);
                    pld.MarkAsDeleted();

                    // are we adding it the pick face?
                    // if so add it to the balance of the pick face also
                    pl.loadByPalletID(rp.PalletID);

                    if (pl.RowCount == 0)
                    {
                        var plocation = new PutawayLocation(rdoc.ItemID);

                        // we don't have a location for this yet,
                        // select a new location
                        //PutawayLocataion pl = new PutawayLocataion();
                        if (plocation.ShowDialog() == DialogResult.OK)
                        {
                            pl.LoadByPrimaryKey(plocation.PalletLocationID);
                            if (pl.RowCount > 0)
                            {
                                pl.PalletID = rp.PalletID;
                                pl.Save();
                            }
                        }
                    }

                    if (pl.RowCount > 0)
                    {
                        var pf = new PickFace();
                        pf.LoadByPalletLocation(pl.ID);
                        if (pf.RowCount > 0)
                        {
                            pf.Balance += Convert.ToInt32(idoc.Quantity);
                            pf.Save();
                        }

                        IssueDocDeleted.AddNewLog(idoc, CurrentContext.UserId);
                        idoc.MarkAsDeleted();
                        rdoc.Save();
                        rp.Save();
                        idoc.Save();
                        pld.Save();

                        // now refresh the window
                        XtraMessageBox.Show("Issue Deleted!", "Confirmation", MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        tranMgr.CommitTransaction();

                    }
                }
                else
                {
                    XtraMessageBox.Show(
                        "This delete is not successfull because a free pick face location was not selected. please select a free location and try again.",
                        "Error Deleteing issue transaction", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    tranMgr.RollbackTransaction();
                }
            }
            catch
            {
                XtraMessageBox.Show("This delete is not successfull", "Warning ...", MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                tranMgr.RollbackTransaction();
            }
        }
        /// <summary>
        /// Saves the whole transaction for
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        /// <param name="dvOutstandingPickList">The dv outstanding pick list.</param>
        /// <param name="remark">The remark.</param>
        /// <param name="issuedBy">The issued by.</param>
        /// <param name="etCurrentDate">The et current date.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static Order SaveIssueTransaction(int orderID, ref DataView dvOutstandingPickList, string remark, string issuedBy, DateTime etCurrentDate)
        {
            // Add the IssueDocID field
            dvOutstandingPickList.Table.Columns.Add("IssueDocID");
            PickList   plst   = new PickList();
            IssueDoc   issDoc = new IssueDoc();
            ReceiveDoc recDoc = new ReceiveDoc();

            BLL.Order ord = new BLL.Order();
            ord.LoadByPrimaryKey(orderID);
            plst.LoadByOrderID(ord.ID);

            foreach (DataRowView drv in dvOutstandingPickList)
            {
                // Pseudo:
                // for each row in the picklist
                // undate the issue document
                // subtract the issued quantity from the receive doc
                // subtract the issued quantity from recieve pallet
                // subtract the issued the reserved quantity irregardless of the quantity issued.


                //Saving the new Issue issue
                if (Convert.ToDecimal(drv["BUPICKED"]) == 0)
                {
                    continue;
                }

                if (Convert.ToDecimal(drv["SKUPicked"]) != Convert.ToDecimal(drv["SKUTOPICK"]))
                {
                    drv["Cost"] = Convert.ToDecimal(drv["SKUPicked"]) * Convert.ToDecimal(drv["UnitPrice"]);
                }

                // Select the receive doc that is associated with this issue.
                recDoc.LoadByPrimaryKey(Convert.ToInt32(drv["ReceiveDocID"]));


                issDoc.AddNew();
                issDoc.StoreId = Convert.ToInt32(drv["StoreID"]);
                issDoc.RefNo   = ord.RefNo;
                if (!ord.IsColumnNull("RequestedBy"))
                {
                    issDoc.ReceivingUnitID = ord.RequestedBy;
                }
                // TOFIX:
                // TODO:
                // Lord have mercy kind of hack to avoid the feb date problem
                // this needs to be fixed for pagume also
                issDoc.Date           = etCurrentDate;
                issDoc.EurDate        = DateTimeHelper.ServerDateTime;
                issDoc.RecievDocID    = Convert.ToInt32(drv["ReceiveDocID"]);
                issDoc.IsApproved     = true;
                issDoc.IsTransfer     = false;
                issDoc.Remark         = remark;
                issDoc.ItemID         = Convert.ToInt32(drv["ItemID"]);
                issDoc.Quantity       = Convert.ToDecimal(drv["BUPICKED"]);
                issDoc.NoOfPack       = Convert.ToDecimal(drv["SKUPICKED"]);
                issDoc.QtyPerPack     = Convert.ToInt32(drv["SKUBU"]);
                issDoc.BatchNo        = drv["BatchNumber"].ToString();
                issDoc.UnitID         = recDoc.UnitID;
                issDoc.ManufacturerID = recDoc.ManufacturerId;
                if (drv["Cost"] != DBNull.Value)
                {
                    issDoc.Cost = Convert.ToDouble(drv["Cost"]);

                    issDoc.SellingPrice = Convert.ToDecimal(drv["UnitPrice"]);
                    if (!recDoc.IsColumnNull("Cost"))
                    {
                        issDoc.UnitCost = Convert.ToDecimal(recDoc.Cost);
                    }
                }
                issDoc.OrderID  = orderID;
                issDoc.IssuedBy = issuedBy;
                // TODO: is this the right place where we need to pick the physical store ID from?
                // check it against the receipt pallet physical store.
                if (!recDoc.IsColumnNull("PhysicalStoreID"))
                {
                    issDoc.PhysicalStoreID = recDoc.PhysicalStoreID;
                }
                if (!recDoc.IsColumnNull("InventoryPeriodID"))
                {
                    //Todo: Remove for Inventory
                    issDoc.InventoryPeriodID = recDoc.InventoryPeriodID;
                }
                if (!recDoc.IsColumnNull("Margin"))
                {
                    issDoc.Margin = (decimal)recDoc.Margin;
                }
                //Replaced by
                issDoc.PLDetailID = Convert.ToInt32(drv["PLDetailID"]);
                BLL.Balance    bal = new Balance();
                BLL.ReceiveDoc rd  = new ReceiveDoc();
                rd.LoadByPrimaryKey(issDoc.RecievDocID);
                decimal currentBalance = bal.GetSoh(issDoc.ItemID, rd.UnitID, issDoc.StoreId, issDoc.Date.Month, issDoc.Date.Year);
                if (currentBalance < issDoc.NoOfPack)
                {
                    throw new Exception(string.Format("The item {0} is not available in {1} Qty.", drv["FullItemName"].ToString(), issDoc.NoOfPack));
                }

                // This is a field that is not applicable on the hub edition
                // It is about the dispensing unit quantity and there is no such thing as Dispensing unit
                // in the hub edition
                issDoc.DUSOH         = 0;
                issDoc.RecomendedQty = 0;// ((recQty > 0) ? Convert.ToInt64(recQty) : 0);
                // End DU
                issDoc.DispatchConfirmed = false;
                issDoc.Save();
                drv["IssueDocID"] = issDoc.ID;
                // updating the receiving doc

                //long prevQuantityLeft = recDoc.QuantityLeft;

                recDoc.QuantityLeft = recDoc.QuantityLeft - issDoc.Quantity;

                if (recDoc.QuantityLeft < 0)
                {
                    //Possibly the wrong ReceiveDoc Entry chosen
                    BLL.Item itm = new Item();
                    itm.LoadByPrimaryKey(recDoc.ItemID);
                    throw new Exception(string.Format("Quantity problem detected for the item {0}", itm.FullItemName));
                }
                //long
                recDoc.Out = (recDoc.QuantityLeft == 0) ? true : false;
                recDoc.Save();

                ReceivePallet rp = new ReceivePallet();
                int           id = Convert.ToInt32(drv["ReceivePalletID"]);
                rp.LoadByPrimaryKey(id);
                if (rp.IsColumnNull("Balance"))
                {
                    rp.Balance = rp.ReceivedQuantity;
                }
                rp.Balance -= issDoc.Quantity;

                if (rp.Balance < 0)
                {
                    BLL.Item itm = new Item();
                    itm.LoadByPrimaryKey(recDoc.ItemID);
                    throw new Exception(string.Format("Quantity problem detected for the item {0}", itm.FullItemName));
                }

                decimal totReservedQty = Convert.ToDecimal(drv["QuantityInBU"]);

                if (rp.IsColumnNull("ReservedStock"))
                {
                    rp.ReservedStock = 0;
                }

                rp.ReservedStock -= totReservedQty;
                if (rp.ReservedStock < 0) //If there has been a quantity problem somewhere
                {
                    rp.ReservedStock = 0;
                }
                rp.Save();
            }
            plst.IsConfirmed = true;
            ord.ChangeStatus(OrderStatus.Constant.ISSUED, CurrentContext.UserId);
            plst.Save();
            ord.Save();
            return(ord);
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            var transfer = new Transfer();
            var newreceiveDoc = new ReceiveDoc();
            var receiveDoc = new ReceiveDoc();
            var issuedoc = new IssueDoc();
            var valid = ValidateFields();
            if (valid == "true")
            {
                if (XtraMessageBox.Show("Are you sure you want to save this transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                try{
                      var dtRecGrid = (DataTable)receivingGrid.DataSource;
                        for (int i = 0; i < dtRecGrid.Rows.Count; i++)
                        {
                            transfer.AddNew();
                            var receiveid = Convert.ToInt32(dtRecGrid.Rows[i]["RecID"]);
                            transfer.ItemID = _itemID = Convert.ToInt32(dtRecGrid.Rows[i]["ID"]);
                            transfer.RecID = receiveid;
                            transfer.BatchNo = dtRecGrid.Rows[i]["Batch No"].ToString();
                            transfer.FromStoreID = Convert.ToInt32(lkFromStore.EditValue);
                            transfer.ToStoreID = Convert.ToInt32(lkToStore.EditValue);
                            transfer.Quantity = Convert.ToInt64(dtRecGrid.Rows[i]["Qty To Transfer"]);
                            transfer.RefNo = txtRefNo.Text;
                            transfer.UnitID = VisibilitySetting.HandleUnits == 1 ? 0 : Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);

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

                            transfer.EurDate = dtRecDate.Value;
                            dtRecDate.IsGregorianCurrentCalendar = false;

                            transfer.TransferReason = txtTransferReason.Text;
                            transfer.ApprovedBy = txtApprovedBy.Text;
                            transfer.TransferRequestedBy = txtRequestedBy.Text;
                            transfer.Save();

                           transfer.GetTransfered(receiveid, _itemID, Convert.ToInt32(lkFromStore.EditValue));
                           issuedoc.AddNew();
                           issuedoc.StoreId = transfer.FromStoreID;
                           issuedoc.ItemID = transfer.ItemID;
                           issuedoc.Quantity = transfer.Quantity;
                           issuedoc.Date = transfer.Date;
                           issuedoc.BatchNo = transfer.BatchNo;
                           issuedoc.UnitID = transfer.UnitID;
                           issuedoc.RecievDocID = transfer.RecID;
                           issuedoc.IsTransfer = true;
                           issuedoc.RefNo = transfer.RefNo;
                           var allstores = new Stores();
                           allstores.LoadByPrimaryKey(transfer.ToStoreID);
                           issuedoc.ReceivingUnitID = (int) allstores.GetColumn("ReceivingUnitID");
                           issuedoc.Save();

                            receiveDoc.GetReceivedItems(receiveid,_itemID, Convert.ToInt32(lkFromStore.EditValue));
                            receiveDoc.QuantityLeft = receiveDoc.QuantityLeft - transfer.Quantity;

                            newreceiveDoc.AddNew();

                            newreceiveDoc.StoreID = transfer.ToStoreID;
                            newreceiveDoc.RefNo = transfer.RefNo;
                            newreceiveDoc.BatchNo = transfer.BatchNo;
                            newreceiveDoc.ItemID = transfer.ItemID;
                            newreceiveDoc.Quantity = transfer.Quantity;
                            newreceiveDoc.QuantityLeft = transfer.Quantity;
                            newreceiveDoc.NoOfPack =  Convert.ToInt32(transfer.Quantity) / receiveDoc.QtyPerPack;
                            newreceiveDoc.QtyPerPack = receiveDoc.QtyPerPack;
                            newreceiveDoc.Cost = receiveDoc.Cost;

                            newreceiveDoc.Date = transfer.Date;
                            newreceiveDoc.UnitID = transfer.UnitID;
                            newreceiveDoc.Out = false;
                            newreceiveDoc.ReceivedBy = transfer.ApprovedBy;
                            newreceiveDoc.ExpDate = receiveDoc.ExpDate;

                            allstores.LoadByPrimaryKey(transfer.FromStoreID);
                            newreceiveDoc.SupplierID = (int) allstores.GetColumn("SupplierID");
                            newreceiveDoc.BoxLevel = 1;
                            newreceiveDoc.Save();
                            receiveDoc.Save();
                        }

                        XtraMessageBox.Show("Transaction Successfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ResetFields();

                    }
                    catch (Exception exp)
                    {
                       XtraMessageBox.Show(exp.InnerException.Message ,"Error");
                    }
                }

            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        internal void Commit(DateTime ethiopianDate, BackgroundWorker backgroundWorker = null)
        {
            InventoryCommitMemberInstance.Transaction.BeginTransaction();
            //TODO: Create the order detail, pass the order id above this inventory object
            int count = 0;

            if (backgroundWorker != null)
            {
                backgroundWorker.ReportProgress(0, "Detail");
            }
            //Add the System Damaged quantity, System Sound Quantity and System Expired Quantity to generate this.
            decimal endingSoundBalance, endingDamagedBalance, endExpiredBalance;

            endingSoundBalance   = !IsColumnNull("SystemSoundQuantity") ? SystemSoundQuantity : 0;
            endingDamagedBalance = !IsColumnNull("SystemDamagedQuantity") ? SystemDamagedQuantity : 0;
            endExpiredBalance    = !IsColumnNull("SystemExpiredQuantity") ? SystemExpiredQuantity : 0;

            decimal endingTotalBalance = endingSoundBalance + endingDamagedBalance + endExpiredBalance;

            ItemUnit itemUnit = new ItemUnit();

            itemUnit.LoadByPrimaryKey(UnitID);
            if (IsColumnNull("ReceiveDocID") && IsColumnNull("DamagedReceiveDocID")) // This has been recently added to
            {
                if (endingTotalBalance > 0)
                {
                    OrderDetail.GenerateOrderDetail(UnitID, ActivityID, endingTotalBalance,
                                                    InventoryCommitMemberInstance.Order.ID, itemUnit.QtyPerUnit, ItemID);

                    //TODO: Get the receive doc details for this inventory object
                    ReceivePallet receivePallet = new ReceivePallet();
                    receivePallet.LoadForInventory(this);
                    receivePallet.Rewind();

                    while (!receivePallet.EOF)
                    {
                        //Review: New Code
                        PickListDetail pickListDetail = PickListDetail.GeneratePickListDetail(receivePallet,
                                                                                              InventoryCommitMemberInstance
                                                                                              .PickList.ID,
                                                                                              Convert.ToDecimal(
                                                                                                  receivePallet.Balance));

                        //TODO: Create the issueDoc, pass the picklistdetail, orderid and picklist above
                        IssueService issueService = new IssueService();

                        IssueDoc issueDoc = issueService.CreateIssueFromPicklist(pickListDetail,
                                                                                 InventoryCommitMemberInstance.Order,
                                                                                 ethiopianDate,
                                                                                 InventoryCommitMemberInstance.Issue,
                                                                                 InventoryCommitMemberInstance.User);

                        //Link IssueDoc to InventoryTable
                        // Could have put it on the issueService method but it would have decrease the useablity
                        IssueDocInventory issueDocInventory = new IssueDocInventory();
                        issueDocInventory.AddNew();
                        issueDocInventory.InventoryID = ID;
                        issueDocInventory.IssueDocID  = issueDoc.ID;
                        issueDocInventory.Save();

                        receivePallet.MoveNext();
                        count++;
                        if (backgroundWorker != null)
                        {
                            backgroundWorker.ReportProgress(
                                Convert.ToInt32((Convert.ToDecimal(count) / Convert.ToDecimal(receivePallet.RowCount)) * 100),
                                "Detail");
                        }
                    }
                }
                //TODO: Create the receive (use the inventory object itself)
                ReceiveService receiveService = new ReceiveService();
                if (!IsColumnNull("InventorySoundQuantity") && InventorySoundQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                  ID, QuantityType.Sound,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    ReceiveDocID = receiveDoc.ID;
                }

                if (!IsColumnNull("InventoryExpiredQuantity") && InventoryExpiredQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                  ID, QuantityType.Expired,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    ReceiveDocID = receiveDoc.ID;
                }

                if (!IsColumnNull("InventoryDamagedQuantity") && InventoryDamagedQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                  ID, QuantityType.Damaged,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    DamagedReceiveDocID = receiveDoc.ID;
                }

                if (backgroundWorker != null)
                {
                    backgroundWorker.ReportProgress(100, "Detail");
                }
            }
            else
            {
                if (!IsColumnNull("ReceiveDocID"))
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(ReceiveDocID);
                    receiveDoc.ChangeQuantity(!IsColumnNull("InventorySoundQuantity") ? InventorySoundQuantity
                                                            : !IsColumnNull("InventoryExpiredQuantity") ? InventoryExpiredQuantity
                                                                                        : 0);
                }

                if (!IsColumnNull("DamagedReceiveDocID"))
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(DamagedReceiveDocID);
                    receiveDoc.ChangeQuantity(InventoryDamagedQuantity);
                }
            }
            IsDraft = false;
            Save();
            InventoryCommitMemberInstance.Transaction.CommitTransaction();
        }
        private void gridViewMissingOrders_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            // disable all the buttons.
            DataRow dataRow = gridViewMissingOrders.GetFocusedDataRow();
            if (dataRow != null)
            {
                btnExport.Enabled = btnPrint.Enabled = btnReprint.Enabled = false;

                // now just show the details of the order
                IssueDoc issueDoc = new IssueDoc();
                issueDoc.LoadMissingByOrderID(Convert.ToInt32(dataRow["ID"]));
                gridTransactions.DataSource = issueDoc.DefaultView;
            }
        }
        /// <summary>
        /// Needs to be the first function to be called when saving a new receive doc entry.
        /// </summary>
        /// <param name="rec"></param>
        /// <param name="receiptID"></param>
        /// <param name="dr"></param>
        private void FillInReceiveDocInformation(ReceiveDoc rec, int receiptID, DataRowView dr)
        {
            try
            {
                rec.GetColumn("GUID");
            }
            catch
            {
                rec.AddColumn("GUID", typeof(string));
                //rec.AddColumn("IsDamaged", typeof(bool));
                //This is only used if the Check box is used to receive damaged receives (For SRM only)
            }

            rec.StoreID = Convert.ToInt32(lkAccounts.EditValue);
            rec.RefNo = txtRefNo.Text;
            rec.Remark = txtRemark.Text;

            rec.ReceivedBy = CurrentContext.LoggedInUserName;

            DateTime xx = dtRecDate.Value;
            dtRecDate.CustomFormat = "MM/dd/yyyy";
            DateTime dtRec = new DateTime();
            rec.Date = ConvertDate.DateConverter(dtRecDate.Text);
            dtRec = ConvertDate.DateConverter(dtRecDate.Text);
            rec.EurDate = BLL.DateTimeHelper.ServerDateTime;
            rec.ItemID = Convert.ToInt32(dr["ID"]);
            rec.NoOfPack = Convert.ToDecimal(dr["Pack Qty"]);
            rec.SetColumn("GUID", dr["GUID"].ToString());
            rec.IsDamaged = Convert.ToBoolean(dr["IsDamaged"]);

            if (standardRecType == StandardReceiptType.iGRVOnline)
            {
                rec.SetColumn("PricePerPack", dr["Price/Pack"]);
                rec.SetColumn("Margin", dr["Margin"]);
                rec.SetColumn("UnitCost", dr["Price/Pack"]);
            }

            //TODO: This if is a garbage. Remove
            if (dr["InvoicedQty"] == DBNull.Value)
            {
                rec.InvoicedNoOfPack = rec.NoOfPack;
            }

            rec.InvoicedNoOfPack = srm ? Convert.ToDecimal(dr["IssuedQty"]) : Convert.ToDecimal(dr["OriginalInvoicedQty"]);

            rec.ManufacturerId = Convert.ToInt32(dr["Manufacturer"]);
            BLL.ItemManufacturer im = new BLL.ItemManufacturer();

            im.LoadIMbyLevel(rec.ItemID, rec.ManufacturerId, 0);
            if (dr["UnitID"] != DBNull.Value)
            {
                // if unit has been set, pick the qty per pack from the unit
                rec.UnitID = Convert.ToInt32(dr["UnitID"]);
                ItemUnit itemUnit = new ItemUnit();
                itemUnit.LoadByPrimaryKey(rec.UnitID);

                rec.QtyPerPack = itemUnit.QtyPerUnit;
            }
            else
            {
                rec.QtyPerPack = im.QuantityInBasicUnit;
            }
            rec.Quantity = rec.QuantityLeft = rec.NoOfPack * rec.QtyPerPack;

            try
            {
                if ((deliveryNoteType == DeliveryNoteType.NotSet))
                {
                    if (!BLL.Settings.HandleGRV && !srm)
                    {
                        rec.PricePerPack = Convert.ToDouble(dr["Price/Pack"]);
                        double pre = (Convert.ToDouble(dr["Price/Pack"]) / 1); //rec.QtyPerPack);
                        rec.Cost = pre;
                    }
                    rec.DeliveryNote = false;
                }
                else
                {
                    rec.DeliveryNote = true;
                    if (deliveryNoteType == DeliveryNoteType.Automatic)
                    {
                        rec.SetColumn("PricePerPack", dr["Price/Pack"]);
                        rec.SetColumn("Margin", dr["Margin"]);
                        rec.SetColumn("UnitCost", dr["Price/Pack"]);
                    }
                }
            }
            catch
            {
                // catch the error if the recieve doesn't have cost information
                // NOTE: this shall never happen.
            }

            if (dr["Batch No"] != DBNull.Value)
            {
                rec.BatchNo = dr["Batch No"].ToString(); // receivingGrid.Rows[i].Cells[8].Value.ToString();
            }

            if (dr["Expiry Date"] != DBNull.Value)
            {
                rec.ExpDate = Convert.ToDateTime(dr["Expiry Date"]); //receivingGrid.Rows[i].Cells[9].Value);
            }

            if (!srm)
            {
                rec.SupplierID = _supplierID;
            }
            else
            {
                rec.SupplierID = BLL.Supplier.CONSTANTS.RETURNED_FROM_FACILITY;
                //TODO: Returned From Supplier: To be removed.  This is an unacceptable hack.
                rec.RefNo = lkSTVInvoiceNo.Text;
                if (string.IsNullOrEmpty(txtRemark.Text))
                {
                    XtraMessageBox.Show(
                        "Please enter the reason for the SRM.", "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    throw new Exception("Reason not entered for SRM");
                }
                else
                {
                    rec.Remark = txtRemark.Text;
                }
            }

            rec.ReturnedStock = srm;

            if (srm && !chkSRMForOldSystemIssues.Checked)
            {
                rec.ReturnedFromIssueDocID = int.Parse(dr["IssueDocID"].ToString());
                int issueDocID = int.Parse(dr["IssueDocID"].ToString());
                BLL.IssueDoc iss = new IssueDoc();
                iss.LoadByPrimaryKey(issueDocID);
                BLL.ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByPrimaryKey(iss.RecievDocID);
                //If it was a delivery note, then the return will not have price information associated with it.

                // HW-2189
                decimal? UnitCost, SellingPrice, Margin;
                UnitCost = SellingPrice = Margin = null;

                if (!BLL.Settings.HandleGRV)
                {
                    if (!iss.IsColumnNull("UnitCost") && iss.IsColumnNull("SellingPrice"))
                    {
                        UnitCost = iss.UnitCost;
                        SellingPrice = iss.SellingPrice;
                        Margin = !iss.IsColumnNull("Margin") ? iss.Margin : 0;
                    }
                    else if (!iss.IsColumnNull("Cost"))
                    {
                        Margin = !rd.IsColumnNull("Margin") ? Convert.ToDecimal(rd.Margin) : 0;
                        SellingPrice = Convert.ToDecimal(iss.Cost / Convert.ToDouble(iss.NoOfPack));
                        UnitCost = BLL.Settings.IsCenter ? SellingPrice : SellingPrice / Convert.ToDecimal(Margin + 1);
                    }
                }
                else
                {
                    if (!iss.IsColumnNull("UnitCost") && iss.IsColumnNull("SellingPrice") && iss.UnitCost != 0 &&
                        iss.SellingPrice != 0)
                    {
                        UnitCost = iss.UnitCost;
                        SellingPrice = iss.SellingPrice;
                        Margin = !iss.IsColumnNull("Margin") ? iss.Margin : 0;
                    }
                    else if (!iss.IsColumnNull("Cost") && iss.Cost != 0)
                    {
                        Margin = !rd.IsColumnNull("Margin") ? Convert.ToDecimal(rd.Margin) : 0;
                        SellingPrice = Convert.ToDecimal(iss.Cost / Convert.ToDouble(iss.NoOfPack));
                        UnitCost = BLL.Settings.IsCenter ? SellingPrice : SellingPrice / Convert.ToDecimal(Margin + 1);
                    }
                }

                if (UnitCost.HasValue)
                {
                    rec.PricePerPack = Convert.ToDouble(UnitCost);
                    rec.Cost = Convert.ToDouble(UnitCost);
                    rec.UnitCost = UnitCost.Value;
                }

                if (SellingPrice.HasValue)
                {
                    rec.SellingPrice = Convert.ToDouble(SellingPrice);
                }

                if (Margin.HasValue)
                {
                    rec.Margin = Convert.ToDouble(Margin);
                }

                if (!rd.IsColumnNull("SupplierID"))
                    rec.SupplierID = rd.SupplierID;
            }

            rec.ReceiptID = receiptID;
            if (BLL.Settings.HandleGRV && !beginningBalance)
            {
                rec.RefNo = receiptID.ToString();
            }
            else if (beginningBalance)
            {
                rec.RefNo = "BeginningBalance";
            }

            //Needs to be fixed! Garbage
            string batch = DateTimeHelper.ServerDateTime.Day.ToString() + DateTimeHelper.ServerDateTime.Hour.ToString() +
                           DateTimeHelper.ServerDateTime.Minute.ToString() + rec.ItemID.ToString();
            rec.LocalBatchNo = batch;
            rec.Out = false;
            rec.IsApproved = false;
            if (dr["ShortageReasonID"] != DBNull.Value)
            {
                rec.ShortageReasonID = Convert.ToInt32(dr["ShortageReasonID"]);
            }
            var item = new Item();
            item.LoadByPrimaryKey(Convert.ToInt32(dr["id"]));

            if (dr["ShortageReasonID"] == DBNull.Value && (item.NeedExpiryBatch || rec.ExpDate <= DateTimeHelper.ServerDateTime))
            {
                rec.ShortageReasonID = ShortageReasons.Constants.DAMAGED;
            }

            dtRecDate.Value = xx;
            _receiptID = receiptID; //Assign it to the global variable so it can be used later on.
        }
        /// <summary>
        /// Handles the FocusedRowChanged event of the gridViewReferences control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs" /> instance containing the event data.</param>
        private void gridViewReferences_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e != null && e.PrevFocusedRowHandle < -1)
                return;

            dtDate.Value = DateTimeHelper.ServerDateTime;
            _reprintId = null;
            DataRow dr = gridViewReferences.GetFocusedDataRow();
            if (dr == null)
            {
                return;
            }

            string[] referenceNo = new string[2];
            referenceNo[0] = dr["RefNo"].ToString();

            if (Convert.ToBoolean(dr["isConvertedDN"]))
            {
                _isConvertedDn = true;
                _stvLogIdChosen = (int?)dr["IsReprintOf"];
            }
            else if (dr != null && dr["ID"] != DBNull.Value)
            {
                _isConvertedDn = false;
                _stvLogIdChosen = (int?)dr["ID"];
            }

            UpdateReprintedNumbers(dr);

            // Enable and disable STV reprint
            // STV SHouldn't be reprinted off a reprint.
            if (dr["IsReprintOf"] != DBNull.Value && !Convert.ToBoolean(dr["isConvertedDN"]))
            {
                btnExport.Enabled = btnReprint.Enabled = false;
                var permission = (BLL.Settings.UseNewUserManagement) ? this.HasPermission("Print") : true;
                btnPrint.Enabled = permission;
                _reprintId = _stvLogIdChosen;
                _stvLogIdChosen = Convert.ToInt32(dr["IsReprintOf"]);
            }
            else if (dr["IsDeliveryNote"] != DBNull.Value && Convert.ToBoolean(dr["IsDeliveryNote"]))
            {
                btnExport.Enabled = false;
                btnReprint.Enabled = (BLL.Settings.UseNewUserManagement) ? this.HasPermission("Re-Print") : true;
                btnPrint.Enabled = false;
            }
            else
            {
                btnPrint.Enabled = this.HasPermission("Print");
                btnReprint.Enabled = this.HasPermission("Re-Print");
                btnExport.Enabled = this.HasPermission("Export");
            }

            if (_stvLogIdChosen != null)
            {
                Issue log = new Issue();
                log.LoadByPrimaryKey(_stvLogIdChosen.Value);

                Institution rus = new Institution();
                IssueDoc iss = new IssueDoc();
                if (!log.IsColumnNull("ReceivingUnitID"))
                {
                    rus.LoadByPrimaryKey(log.ReceivingUnitID);
                    //FacilityName.Text = rus.Name;

                    HeaderSection.Text = rus.Name;

                    var activity = new Activity();
                    activity.LoadByPrimaryKey(log.StoreID);
                    lblActivity.Text = activity.Name;
                    lblSubAccount.Text = activity.SubAccountName;
                    lblMode.Text = activity.ModeName;
                    lblAccount.Text = activity.AccountName;

                    lblRegion.Text = rus.RegionName;
                    lblWoreda.Text = rus.WoredaName;
                    lblZone.Text = rus.ZoneName;
                    lblInstType.Text = rus.InstitutionTypeName;

                    var ownership = new OwnershipType();
                    ownership.LoadByPrimaryKey(rus.Ownership);
                    lblOwnership.Text = ownership.Name;

                    lblVoidConDate.Text = (dr["approvalDate"]) != DBNull.Value ? Convert.ToDateTime(dr["approvalDate"]).ToShortDateString(): "-";
                    lblIssueType.Text = (string)dr["OrderType"];
                    User user = new User();

                    if (dr["approvedBy"] != DBNull.Value)
                    {
                        user.LoadByPrimaryKey(Convert.ToInt32(dr["approvedBy"]));
                        lblConfirmedBy.Text = user.FullName;
                    }
                    else
                    {
                        lblConfirmedBy.Text = "-";
                    }

                    var doc = new DocumentType();
                    doc.LoadByPrimaryKey(log.DocumentTypeID);
                    lblDocType.Text = doc.Name;

                    lblPrintedDate.Text = log.PrintedDate.ToShortDateString();

                    var pt = new PaymentType();

                    if (!rus.IsColumnNull("PaymentTypeID"))
                    {
                        pt.LoadByPrimaryKey(rus.PaymentTypeID);
                        lblPaymentType.Text = pt.Name;
                    }

                    else
                    {
                        lblPaymentType.Text = "-";
                    }

                    // Show user name

                    user.LoadByPrimaryKey(log.UserID);
                    lblPrintedBy.Text = (user.FullName == "") ? user.UserName : user.FullName;

                    // show contact person
                    PickList pl = new PickList();
                    pl.LoadByPrimaryKey(log.PickListID);
                    Order order = new Order();
                    order.LoadByPrimaryKey(pl.OrderID);

                    var os = new OrderStatus();
                    os.LoadByPrimaryKey(order.OrderStatusID);
                    lblIssueStatus.Text = os.OrderStatus;

                    if (!order.IsColumnNull("ContactPerson"))
                    {
                        lblRecivedBy.Text = order.ContactPerson;
                    }
                    else
                    {
                        lblRecivedBy.Text = @"-";
                    }

                    lblReceivedDate.Text = order.EurDate.ToShortDateString();

                }

                dtDate.Value = log.PrintedDate;
                //PrintedDate.Text = dtDate.Text;
                lblPrintedDate.Text = dtDate.Text;

                gridTransactions.DataSource = iss.GetIssueBySTV(_stvLogIdChosen.Value);

                layoutUnconfirmedSTVs.Visibility = LayoutVisibility.Never;
                if (BLL.Settings.ShowMissingSTVsOnIssueLog)
                {
                    DataView view = iss.GetPossibleUnconfirmedIssues(_stvLogIdChosen.Value);
                    if (view.Count > 0)
                    {
                        gridUnconfirmed.DataSource = view;
                        layoutUnconfirmedSTVs.Visibility = LayoutVisibility.Always;
                    }
                    else
                    {
                        layoutUnconfirmedSTVs.Visibility = LayoutVisibility.Never;
                    }
                }

            }
        }
        private void unconfirmedMenuClicked_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            DataRow dataRow = gridUnconfirmedView.GetFocusedDataRow();
            if (dataRow != null)
            {
                if (e.ClickedItem.Text == "Delete")
                {
                    if (DialogResult.Yes ==
                        XtraMessageBox.Show("Are you sure you would like to delete this?", "Confirmation",
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        DeleteIssueDoc(Convert.ToInt32(dataRow["ID"]));
                        // Refresh it
                        gridViewReferences_FocusedRowChanged(null, null);
                        //XtraMessageBox.Show("Issue has been deleted");
                    }
                }
                else if (e.ClickedItem.Text == "Confirm")
                {

                    IssueDoc doc = new IssueDoc();
                    doc.LoadByPrimaryKey(Convert.ToInt32(dataRow["ID"]));

                    // do some validations
                    if (doc.IsColumnNull("STVID"))
                    {
                        doc.STVID = _stvLogIdChosen.Value;
                        doc.Save();
                    }

                    // refresh
                    XtraMessageBox.Show("You have confirmed the STV", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    gridViewReferences_FocusedRowChanged(null, null);
                }
            }
        }
        public void PopulateItemListByDU(DataTable dtItem)
        {
            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Value = 1;
            progressBar1.Maximum = dtItem.Rows.Count;

            GeneralInfo pipline = new GeneralInfo();
            pipline.LoadAll();
            int min = pipline.Min;
            int max = pipline.Max;
            int storeId = (cboStores.SelectedValue != null) ? Convert.ToInt32(cboStores.SelectedValue) : 1;
            int duId = Convert.ToInt32(cboIssuedTo.SelectedValue);
            lstItem.Items.Clear();
            int col = 0;
            int count = 1;
            Balance bal = new Balance();
            IssueDoc itmIssues = new IssueDoc();
            foreach (DataRow dr in dtItem.Rows)
            {
                int itemId = Convert.ToInt32(dr["ID"]);
                string itemName = dr["ItemName"].ToString() + " - " + dr["DosageForm"].ToString() + " - " + dr["Strength"].ToString();

                int year = Convert.ToInt32(cboYear.SelectedItem);
                Int64 SOH = bal.GetDUSOH(Convert.ToInt32(dr["ID"]), duId, dtCurrent.Month, year);

                int[] mon = { 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

                long[] cons = new long[12];
                for (int i = 0; i < mon.Length; i++)
                {
                    int yr = (mon[i] > 10) ? year - 1 : year;
                    cons[i] = itmIssues.GetDUConsumptionByMonth(itemId,duId,mon[i], yr);
                }
                string[] str = { count.ToString(), itemName, ((SOH != 0) ? SOH.ToString("#,###") : "0"), ((cons[0] != 0) ? cons[0].ToString("#,###") : "0"), ((cons[1] != 0) ? cons[1].ToString("#,###") : "0"), ((cons[2] != 0) ? cons[2].ToString("#,###") : "0"), ((cons[3] != 0) ? cons[3].ToString("#,###") : "0"), ((cons[4] != 0) ? cons[4].ToString("#,###") : "0"), ((cons[5] != 0) ? cons[5].ToString("#,###") : "0"), ((cons[6] != 0) ? cons[6].ToString("#,###") : "0"), ((cons[7] != 0) ? cons[7].ToString("#,###") : "0"), ((cons[8] != 0) ? cons[8].ToString("#,###") : "0"), ((cons[9] != 0) ? cons[9].ToString("#,###") : "0"), ((cons[10] != 0) ? cons[10].ToString("#,###") : "0"), ((cons[11] != 0) ? cons[11].ToString("#,###") : "0") };
                ListViewItem listItem = new ListViewItem(str);
                listItem.ToolTipText = itemName;
                listItem.Tag = dr["ID"];
                if (col != 0)
                {
                    listItem.BackColor = Color.FromArgb(233, 247, 248);
                    col = 0;
                }
                else
                {
                    col++;
                }
                lstItem.Items.Add(listItem);
                count++;
                progressBar1.PerformStep();
            }
            progressBar1.Visible = false;
        }
        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;
        }
        private void cboReceivingUnits_SelectedValueChanged(object sender, EventArgs e)
        {
            DataTable issGrid = (DataTable)issueGrid.DataSource;
            if (issGrid != null)
            {
                if (cboReceivingUnits.EditValue != null && issGrid.Rows.Count > 0)
                {
                    DateTime xx = dtIssueDate.Value;
                    dtIssueDate.Value = DateTime.Now;
                    dtIssueDate.CustomFormat = "MM/dd/yyyy";
                    DateTime dtCurrent = ConvertDate.DateConverter(dtIssueDate.Text);
                    dtIssueDate.Value = xx;

                    var iss = new IssueDoc();
                    var bal = new Balance();
                    int receivingUnit = Convert.ToInt32(cboReceivingUnits.EditValue);
                    var DUs = new ReceivingUnits();
                    DUs.LoadByPrimaryKey(receivingUnit);
                    double dumax = 0.5;
                    try
                    {
                        dumax = DUs.Max;
                    }
                    catch(Exception EX)
                    {

                    }

                    for (int i = 0; i < issGrid.Rows.Count; i++)
                    {
                        int itmId = Convert.ToInt32(issGrid.Rows[i]["ID"]);
                        int lastIssueQty = iss.GetDULastIssueQty(itmId, receivingUnit);
                        int lastDUSOH = iss.GetDULastSOH(itmId, receivingUnit);
                        issGrid.Rows[i]["MR Issue Qty"] = lastIssueQty;
                        issGrid.Rows[i]["MR DU SOH"] = lastDUSOH;
                        const int lstSOH = 0;
                        issGrid.Rows[i]["DU Remaining SOH"] = 0;
                        int yer = (dtCurrent.Month < 11) ? dtCurrent.Year : dtCurrent.Year - 1;
                        Int64 duAmc = bal.CalculateDUAMC(itmId, receivingUnit, dtCurrent.Month, dtCurrent.Year, lstSOH);
                        issGrid.Rows[i]["DU AMC"] = duAmc;
                        double recQty = (duAmc * dumax) - Convert.ToInt32(issGrid.Rows[i]["DU Remaining SOH"]);
                        issGrid.Rows[i]["Recommended Qty"] = ((recQty > 0) ? Convert.ToInt64(recQty) : 0);
                    }
                }
            }
        }
        private void EditIssue_Load(object sender, EventArgs e)
        {
            Stores str = new Stores();
            str.LoadAll();
            cboStores.DataSource = str.DefaultView;

            ReceivingUnits rUnit = new ReceivingUnits();
            rUnit.GetActiveDispensaries();
            cboReceivingUnit.DataSource = rUnit.DefaultView;

            if (_tranId != 0)
            {
                IssueDoc iss = new IssueDoc();
                Items itm = new Items();

                iss.LoadByPrimaryKey(_tranId);

                DataTable dtItm = itm.GetItemById(iss.ItemID);
                string itemName = dtItm.Rows[0]["ItemName"].ToString() + " - " + dtItm.Rows[0]["DosageForm"].ToString() + " - " + dtItm.Rows[0]["Strength"].ToString();

                txtRefNo.Text = iss.RefNo;
                txtBatchNo.Text = iss.BatchNo;
                try
                {
                    txtPack.Text = iss.NoOfPack.ToString();
                    txtQtyPack.Text = iss.QtyPerPack.ToString();
                    txtPrice.Text = (iss.Cost * iss.QtyPerPack).ToString();
                }
                catch
                {
                    txtPack.Text = "0";
                    txtQtyPack.Text = "0";
                    txtPrice.Text = (iss.Cost * 1).ToString();
                }
                txtQuantity.Text = iss.Quantity.ToString();
                DateTime dtDate = Convert.ToDateTime(iss.Date.ToString("MM/dd/yyyy"));
                txtDate.Text = dtDate.ToShortDateString();
                //dtIssDate.Value = DateTime.Now;
                //dtIssDate.CustomFormat = "MM/dd/yyyy";
                //DateTime dtCurrent = Convert.ToDateTime(dtIssDate.Text);

                //long tic = (DateTime.Now.Ticks - dtCurrent.Ticks);
                //DateTime dtIssG = dtDate.AddTicks(tic);

                //dtIssDate.Value = dtIssG;
                cboStores.SelectedValue = iss.StoreId;
                cboReceivingUnit.SelectedValue = iss.ReceivingUnitID;
                txtItemName.Text = itemName;
                txtReceivedBy.Text = iss.IssuedBy;
                txtRemark.Text = iss.Remark;

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

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

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

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

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

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

                        switch (VisibilitySetting.HandleUnits)
                        {

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

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

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

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

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

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

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

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

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

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

                    txtStore.Text = cboStores.Text;
                    txtConIssuedBy.Text = txtIssuedBy.Text;
                    txtConRemark.Text = txtRemark.Text;
                    txtConRecipientName.Text = txtRecipientName.Text;
                    gridConfirmation.DataSource = dtIssueConf;
                }
            }
            else
            {
                tabControl1.SelectedTabPageIndex = 1;
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        /// <summary>
        /// Reorganizes the data view for STV print_ program.
        /// </summary>
        /// <param name="dv">The dv.</param>
        /// <param name="refNo">The ref no.</param>
        /// <param name="pickListId">The pick list id.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="stvLogID">The STV log ID.</param>
        /// <param name="convertDNtoSTV">if set to <c>true</c> [convert D nto STV].</param>
        /// <param name="generateNewPrintID">if set to <c>true</c> [generate new print ID].</param>
        /// <param name="hasInsurance">if set to <c>true</c> [has insurance].</param>
        /// <returns></returns>
        public static DataTable ReorganizeDataViewForSTVPrint_Program(DataView dv, int orderID, int pickListId, int userID, int? stvLogID, bool convertDNtoSTV, bool generateNewPrintID, bool hasInsurance)
        {
            BLL.Order order = new Order();
            order.LoadByPrimaryKey(orderID);
            int? paymentTypeID = null;

            if (order.PaymentTypeID == PaymentType.Constants.CASH || order.PaymentTypeID == PaymentType.Constants.CREDIT || order.PaymentTypeID == PaymentType.Constants.STV)
            {
                paymentTypeID = order.PaymentTypeID;
            }

            // This is just to make the delivery notes print a separate series of numbers.
            // This section completely asks for a re-write.
            if (dv.Count > 0 && (dv[0]["Cost"] == DBNull.Value || Convert.ToDecimal(dv[0]["Cost"]) == 0M))
            {
                paymentTypeID = PaymentType.Constants.DELIVERY_NOTE;
            }
            else if (stvLogID != null)
            {
                Issue issue = new Issue();
                issue.LoadByPrimaryKey(stvLogID.Value);

                if (!issue.IsColumnNull("IsDeliveryNote") && issue.IsDeliveryNote && !convertDNtoSTV)
                {
                    paymentTypeID = PaymentType.Constants.DELIVERY_NOTE;
                }
            }

            // prepare the pick list for printing.
            // this method only merges the items that come in different rows but ...
            // that have same price same item.
            DataTable dtbl = dv.Table.Clone();

            if (!dtbl.Columns.Contains("Supplier"))
            {
                dtbl.Columns.Add("Supplier");
            }
            if (!dtbl.Columns.Contains("SupplierID"))
            {
                dtbl.Columns.Add("SupplierID");
            }
            dtbl.Columns.Add("STVNumber");
            dtbl.Columns.Add("StoreName");
            dtbl.Columns.Add("ContactPerson");
            dtbl.Columns.Add("PhysicalStoreType"); //The virtual store (The grouping for the stores) for the display on the stv

            dtbl.Clear();
            foreach (DataRowView drv in dv)
            {
                if (dtbl.Rows.Count == 0)
                {
                    dtbl.ImportRow(drv.Row);
                }

                else
                {

                    //check if items with same expiry exists in the table
                    //TOFIX: Add the supplier in this mix

                    string qItemID = "", qbatchNumberID = "", qUnitPriceID = "", qPhysicalStoreName = "", qStoreID = "";

                    qItemID = string.Format("ItemID={0} and UnitID={1}", drv["ItemID"].ToString(), drv["UnitID"]);

                    if (drv["BatchNumber"] != DBNull.Value)
                        qbatchNumberID = string.Format(" and BatchNumber='{0}'", drv["BatchNumber"].ToString());
                    if (drv["UnitPrice"] != DBNull.Value)
                        qUnitPriceID = string.Format(" and UnitPrice = {0} ", drv["UnitPrice"].ToString());
                    if (drv["PhysicalStoreName"] != DBNull.Value)
                        qPhysicalStoreName = string.Format(" and PhysicalStoreName= '{0}'",
                                                           drv["PhysicalStoreName"].ToString());
                    if (drv["StoreID"] != DBNull.Value)
                        qStoreID = string.Format(" and StoreID= '{0}'", drv["StoreID"].ToString());

                    string query = string.Format("{0}{1}{2}{3}{4}", qItemID, qbatchNumberID, qUnitPriceID,
                                                 qPhysicalStoreName, qStoreID);
                    DataRow[] ar = dtbl.Select(query);
                    if (ar.Length > 0)
                    {
                        //
                        foreach (var dataRow in ar)
                        {
                            dataRow["SKUPICKED"] = Convert.ToInt32(dataRow["SKUPICKED"]) +
                                                   Convert.ToInt32(drv["SKUPICKED"]);
                            dataRow["Cost"] = (dataRow["Cost"] != DBNull.Value ? Convert.ToDouble(dataRow["Cost"]) : 0) +
                                              (drv["Cost"] != DBNull.Value ? Convert.ToDouble(drv["Cost"]) : 0);
                            dataRow["IssueDocID"] = dataRow["IssueDocID"].ToString() + ',' +
                                                    drv["IssueDocID"].ToString();
                            dataRow.EndEdit();
                            // If we have been here before, no need to do it again.
                            // this means the same amount is printed duplicated.
                            break;
                        }
                    }
                    else
                    {
                        dtbl.ImportRow(drv.Row);
                    }
                }

            }

            Supplier supplier = new Supplier();
            ReceiveDoc rd = new ReceiveDoc();

            // First sort the Data Table by Supplier
            // then create STV Number for each supplier

            foreach (DataRowView drw in dtbl.DefaultView)
            {
                rd.LoadByPrimaryKey(Convert.ToInt32(drw["ReceiveDocID"]));
                if (rd.RowCount > 0)
                {
                    supplier.LoadByPrimaryKey(rd.SupplierID);
                    // Add the supplier to the table
                    drw["SupplierID"] = supplier.ID;
                    drw["Supplier"] = supplier.CompanyName;
                    drw.EndEdit();
                }
            }

            int supplierId = 0;
            int storeID = 0;
            int phyStoreTypeID = 0;
            bool isManufacturerLocal = false;
            int storeGroupID = 0;
            string storeName = "";

            int lineNumber = 1;
            int rowsOnPaper = 1;
            int maxLinesOnPage = 15;

            string stvNo = "";
            string stvNoForPrint = "";
            int stvID = -1;

            dtbl.DefaultView.Sort = "PhysicalStoreTypeName, StoreGroupID,StoreID,IsManufacturerLocal, CommodityType, FullItemName";

            string commodityType = "";
            foreach (DataRowView drw in dtbl.DefaultView)
            {
                //if ((BLL.Settings.IsRdfMode && (palletLocationID != Convert.ToInt32(drw["PalletLocationID"]) || storeID != Convert.ToInt32(drw["StoreID"]))) || (Convert.ToInt32(drw["SupplierID"]) != supplierId) || lineNumber > 13)

                if (commodityType == "")
                    commodityType = drw["CommodityType"].ToString();

                if ((drw["PhysicalStoreTypeID"] != DBNull.Value) && phyStoreTypeID != Convert.ToInt32(drw["PhysicalStoreTypeID"]) || (commodityType != drw["CommodityType"].ToString() && !BLL.Settings.PrintMultipleCommodityTypesPerPage) || (isManufacturerLocal != bool.Parse(drw["IsManufacturerLocal"].ToString()) || storeGroupID != Convert.ToInt32(drw["StoreGroupID"]) || storeID != Convert.ToInt32(drw["StoreID"]) || (rowsOnPaper + (Convert.ToInt32(drw["FullItemName"].ToString().Length / 32))) > maxLinesOnPage))// lineNumber > 10)
                {

                    lineNumber = 1;
                    rowsOnPaper = 1;

                    supplierId = Convert.ToInt32(drw["SupplierID"]);
                    storeGroupID = Convert.ToInt32(drw["StoreGroupID"]);
                    storeID = Convert.ToInt32(drw["StoreID"]);
                    var activity = new Activity();
                    activity.LoadByPrimaryKey(storeID);
                    storeName = activity.FullActivityName;

                    isManufacturerLocal = Convert.ToBoolean(drw["IsManufacturerLocal"]);

                    if (drw["PhysicalStoreTypeID"] != DBNull.Value)
                    {
                        phyStoreTypeID = Convert.ToInt32(drw["PhysicalStoreTypeID"]);
                    }

                    // Pseudo:
                    // Get hub details from the general info table
                    // prepare the printable data
                    // bind the printable data and GO

                    Issue stvLog = new Issue();
                    if (BLL.Settings.UseHeadedSTV && generateNewPrintID)
                    {
                        stvLog.AddNew();
                        stvLog.PrintedDate = DateTimeHelper.ServerDateTime;
                        stvLog.RefNo = order.RefNo;
                        stvLog.PickListID = pickListId;
                        stvLog.SupplierID = supplierId;
                        stvLog.UserID = userID;
                        stvLog.StoreID = storeID;
                         stvLog.IsDeliveryNote = (paymentTypeID == PaymentType.Constants.DELIVERY_NOTE);
                        stvLog.HasInsurance = hasInsurance;
                        stvLog.FiscalYearID = FiscalYear.Current.ID;
                        stvLog.AccountID = activity.AccountID;
                        if (paymentTypeID == PaymentType.Constants.DELIVERY_NOTE)
                        {
                            stvLog.DocumentTypeID = DocumentType.documentTypes.DeliveryNote.DocumentTypeID;
                        }
                        else if (paymentTypeID == PaymentType.Constants.CASH)
                        {
                            stvLog.DocumentTypeID = DocumentType.documentTypes.Cash.DocumentTypeID;
                        }
                        else if (paymentTypeID == PaymentType.Constants.CREDIT)
                        {
                            stvLog.DocumentTypeID = DocumentType.documentTypes.Credit.DocumentTypeID;
                        }
                        else if(paymentTypeID == PaymentType.Constants.STV)
                        {
                            stvLog.DocumentTypeID = DocumentType.documentTypes.STV.DocumentTypeID;
                        }
                        stvLog.IDPrinted = DocumentType.GetNextSequenceNo(stvLog.DocumentTypeID,stvLog.AccountID,stvLog.FiscalYearID);
                        stvLog.PaymentTypeID = order.PaymentTypeID;

                        if (!order.IsColumnNull("RequestedBy"))
                            stvLog.ReceivingUnitID = order.RequestedBy;
                        if (stvLogID.HasValue)
                        {
                            stvLog.IsReprintOf = stvLogID.Value;
                            //this means the STV is from replaced
                            Issue s = new Issue();
                            s.LoadByPrimaryKey(stvLogID.Value);
                            stvLog.IsDeliveryNote=(!s.IsColumnNull("IsDeliveryNote") && s.IsDeliveryNote && !convertDNtoSTV);
                        }

                        stvLog.Save();

                        stvNo = stvLog.ID.ToString("00000"); //If we wanted  to show just the ID of the sql table on the printout. We Use this
                        stvNoForPrint = FiscalYear.Current.GetCode(stvLog.IDPrinted);
                        stvID = stvLog.ID;
                    }
                    else if (!generateNewPrintID && stvLogID.HasValue)
                    {
                        // this assumes that we don't have to export
                        stvLog.LoadByPrimaryKey(stvLogID.Value);

                        stvNo = stvLog.ID.ToString("00000");//If we wanted  to show just the ID of the sql table on the printout. Use this
                       FiscalYear fiscalYear = new FiscalYear();
                        fiscalYear.LoadByPrimaryKey(stvLog.FiscalYearID);
                        stvNoForPrint = fiscalYear.GetCode(stvLog.IDPrinted);
                    }
                }

                if (commodityType != drw["CommodityType"].ToString()) //Check if the commodity type has changed.  Meaning that there will be a new group on the same paper (Pharmaceuticals, Chemicals, etc.) therefore we have to make the number of items that come to that page lower (Because we have headings for each group)
                {
                    commodityType = drw["CommodityType"].ToString();
                    rowsOnPaper = rowsOnPaper + 5;
                }
                else
                {
                    if (drw["FullItemName"].ToString().Length > 30) //The reason behind this code.  If the item name is a long one, it wraps and goes into the next line, making the number of row numbers more than just 1, so we don't just add one
                        rowsOnPaper += Convert.ToInt32(drw["FullItemName"].ToString().Length / 30) + 1;
                    else
                        rowsOnPaper++;
                }

                drw["STVNumber"] = stvNo;
                drw["LineNum"] = lineNumber++;
                drw["StoreName"] = storeName;
                drw["PrintedSTVNumber"] = stvNoForPrint;

                //Save the STVID into the IssueDoc Table.

                BLL.IssueDoc issDoc = new IssueDoc();

                int itemID = Convert.ToInt32(drw["ItemID"]);
                int receiveDocID = Convert.ToInt32(drw["ReceiveDocID"]);
                int picklistID = Convert.ToInt32(drw["PicklistID"]);
                drw["ContactPerson"] = BLL.Order.GetContactPerson(picklistID);
                BLL.Order orderInfo = new Order();

                // the only time the STVLog ID should be an entry in the Issue Doc should be when this is a fresh printout.
                if (stvID != -1 && stvLogID == null)
                {
                    SaveSTVIDbyPickListDetails(drw["IssueDocID"].ToString(), stvID);
                    //SaveSTVIDIntoIssueData(supplierId, itemID, stvID, issDoc, orderInfo.LoadByPickListID(picklistID), receiveDocID, storeID);
                }

                if (stvID == -1 && stvLogID == null)
                {
                    throw new Exception("An error occurred during save.  Please contact your administrator if this happens again.");
                }
                //SaveSTVIDIntoIssueData(supplierId, itemID, stvID, issDoc, order.LoadByPickListID(picklistID), receiveDocID);
            }
            return dtbl;
        }
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            var confirmedItemsQuantity = new Dictionary<int, long>();
            var confirmedItems = new List<int>();
            var valid = ValidateFields();
            if (valid == "true")
            {
                if (XtraMessageBox.Show("Are You Sure, You Want To Save This Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    var issDoc = new IssueDoc();
                    var recDoc = new ReceiveDoc();
                    DataTable dtConfirm;
                    long currentSOH = 0;
                    var storeId = 0;
                    var itemId = 0;

                    using (dtConfirm = (DataTable)gridConfirmation.DataSource)
                    {
                        for (int i = 0; i < dtConfirm.Rows.Count; i++)
                        {
                           var receivedocid = Convert.ToInt32(dtConfirm.Rows[i]["RecId"]);
                            issDoc.GetDULastIssue(Convert.ToInt32(dtConfirm.Rows[i]["ItemID"]), Convert.ToInt32(cboReceivingUnits.EditValue));
                            confirmedItems.Add(Convert.ToInt32(dtConfirm.Rows[i]["ItemID"]));
                            if (issDoc.RowCount > 0)
                            {
                                //issDoc.DUSOH = ((dtConfirmation.Rows[i]["DUSOH"] != null) ? Convert.ToInt64(dtConfirmation.Rows[i]["DUSOH"]) : 0);
                                //issDoc.Save();
                            }
                            //Saving the issue
                            issDoc.AddNew();
                            issDoc.StoreId = Convert.ToInt32(cboStores.EditValue);
                            issDoc.RefNo = txtRefNo.Text.Trim();
                            issDoc.ReceivingUnitID = Convert.ToInt32(cboReceivingUnits.EditValue);
                            DateTime xx = dtIssueDate.Value;
                            dtIssueDate.CustomFormat = "MM/dd/yyyy";

                            DateTime dtCurrent = ConvertDate.DateConverter(dtIssueDate.Text);
                            issDoc.Date = dtCurrent;
                            dtIssueDate.IsGregorianCurrentCalendar = true;
                            issDoc.EurDate = dtIssueDate.Value;
                            dtIssueDate.IsGregorianCurrentCalendar = false;
                            issDoc.RecievDocID =Convert.ToInt32(dtConfirm.Rows[i]["RecId"]); // Used to have 8 as an index
                            recDoc.LoadByPrimaryKey(receivedocid);
                            issDoc.IsApproved = true;
                            issDoc.IsTransfer = false;

                            issDoc.Remark = txtRemark.Text;
                            issDoc.RecipientName = txtRecipientName.Text;
                            issDoc.IssuedBy = txtIssuedBy.Text;
                            issDoc.DUSOH = Convert.ToInt32(dtConfirm.Rows[i]["DUSOH"]);
                            issDoc.ItemID = Convert.ToInt32(dtConfirm.Rows[i]["ItemId"]);
                            issDoc.Quantity = Convert.ToInt64(dtConfirm.Rows[i]["Quantity"]);

                            issDoc.NoOfPack = Convert.ToInt32(dtConfirm.Rows[i]["No Of Pack"]);
                            issDoc.QtyPerPack = Convert.ToInt32(dtConfirm.Rows[i]["Qty Per Pack"]);
                            switch (VisibilitySetting.HandleUnits)
                            {
                                case 1:
                                    issDoc.UnitID = 0;
                                    break;
                                case 2:
                                    issDoc.UnitID = Convert.ToInt32(dtConfirm.Rows[i]["UnitID"]);
                                    break;
                                default:
                                    issDoc.UnitID = Convert.ToInt32(dtConfirm.Rows[i]["UnitID"]);
                                    break;
                            }
                            issDoc.BatchNo = dtConfirm.Rows[i]["BatchNo"].ToString();
                            issDoc.Cost = Convert.ToDouble(dtConfirm.Rows[i]["Unit Price"]);
                            issDoc.RecomendedQty = Convert.ToInt32(dtConfirm.Rows[i]["DURecomended"]);// ((recQty > 0) ? Convert.ToInt64(recQty) : 0);
                            //End DU
                            issDoc.Save();
                            //updating the receiving doc
                            recDoc.LoadByPrimaryKey(Convert.ToInt32(dtConfirm.Rows[i]["RecId"]));
                            //this line calculates the current SOH
                            recDoc.QuantityLeft = recDoc.QuantityLeft - issDoc.Quantity;
                            currentSOH = currentSOH + recDoc.QuantityLeft;

                            itemId = Convert.ToInt32(dtConfirm.Rows[i]["ItemId"]);
                            var unitId = Convert.ToInt32(dtConfirm.Rows[i]["UnitID"]);
                            if (recDoc.QuantityLeft != 0)
                                recDoc.Out = false;
                            else
                                recDoc.Out = true;

                            if (confirmedItemsQuantity.ContainsKey(itemId))
                                confirmedItemsQuantity[itemId] += recDoc.QuantityLeft;
                            else
                            {
                                confirmedItemsQuantity.Add(itemId, recDoc.QuantityLeft);
                            }
                            recDoc.Save();

                            storeId = Convert.ToInt32(cboStores.EditValue);

                            //Log Activity
                            dtIssueDate.Value = xx;
                            Builder.RefreshAMCValues(storeId, confirmedItemsQuantity,unitId);
                        }

                        //save stockout information for the current item in current store
                        //if current SOH after this issue is 0
                        if (currentSOH == 0)
                        {
                            StockoutLog stockoutLog = new StockoutLog();
                            stockoutLog.AddNew();
                            stockoutLog.StoreID = storeId;
                            stockoutLog.ItemID = itemId;
                            stockoutLog.StartDate = DateTime.Today;
                            stockoutLog.Save();
                        }
                    }
                    XtraMessageBox.Show("Transaction Successfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            xpButton2_Click(sender, e);
            issueGrid.DataSource = null;
            issueGridView.RefreshData();
            RefreshItems();
        }
        public DataTable GetRRFReportWithOutUnit(int storeId, int fromYear, int fromMonth, int toYear, int toMonth)
        {
            var balance = new Balance();
            var issue = new IssueDoc();
            var startDate = EthiopianDate.EthiopianDate.EthiopianToGregorian(String.Format("{0}/{1}/{2}", 1, fromMonth, fromYear));
            var endDate = EthiopianDate.EthiopianDate.EthiopianToGregorian(String.Format("{0}/{1}/{2}", 30, toMonth, toYear));
            if (fromMonth != 1)
                fromMonth--;
            else
            {
                fromYear--;
                fromMonth = 12;
            }
            var dtbl = balance.GetSOHForProgramRRF(storeId, fromMonth, fromYear);
            var dtbl2 = balance.GetSOHForProgramRRF(storeId, toMonth, toYear);

            var dt1 = new DateTime(fromYear, fromMonth, DateTime.DaysInMonth(fromYear, fromMonth));
            var dt2 = new DateTime(toYear, toMonth, DateTime.DaysInMonth(toYear, toMonth));

            var query = string.Format("select distinct Items.ID, isnull(Quantity,0) as Quantity from" +
                                         " Items left join (select ItemID, sum(Quantity) as Quantity from ReceiveDoc rd " +
                                         "where [Date] between '{0}' and '{1}' and" + " StoreID = {2} group by ItemID) as" +
                                         " A on Items.ID = A.ItemID", dt1, dt2, storeId);
            //var query = string.Format("SELECT  ItemID ID,SUM(Quantity) AS Quantity FROM ReceiveDoc rd WHERE   [Date] BETWEEN '{0}' AND '{1}'AND StoreID = {2} GROUP BY ItemID ", dt1, dt2, storeId);
            this.LoadFromRawSql(query);
            var received = this.DataTable;

            query = string.Format("select distinct Items.ID, isnull(Quantity,0) as Quantity " +
                                  "from Items left join (select ItemID,sum(Quantity) Quantity " +
                                  "from IssueDoc " +
                                  "where [Date] between '{0}' and '{1}' and StoreID = {2} and IsTransfer = 0 " +
                                  "group by ItemID ) as A on Items.ID = A.ItemID "
                                  , dt1, dt2, storeId);

            //query = string.Format(" SELECT ItemID ID ,SUM(Quantity) Quantity FROM IssueDoc WHERE   [Date] BETWEEN '{0}' AND '{1}' AND StoreID = {2} AND IsTransfer = 0 GROUP BY ItemID", dt1, dt2, storeId);
            this.LoadFromRawSql(query);
            var issued = this.DataTable;

            query = string.Format("select distinct Items.ID, isnull(Quantity,0) as Quantity from " +
                                  "Items left join (select ItemID,sum(case when Losses = 1 then - Quantity else " +
                                  "Quantity end) Quantity from Disposal where [Date] between '{0}' and '{1}' " +
                                  "and StoreID = {2} group by ItemID) as A on Items.ID = A.ItemID "
                                 , dt1, dt2, storeId);

            //query = string.Format("select ItemID ID ,sum(case when Losses = 1 then - Quantity else Quantity end) Quantity from Disposal where [Date] between '{0}' and '{1}' and StoreID = {2} group by ItemID", dt1, dt2, storeId);
            this.LoadFromRawSql(query);
            var lost = this.DataTable;

            query = string.Format("select distinct Items.ID,Items.StockCodeDACA,Items.Cost, case Items.Cost when 0 then 1 else isnull(Items.Cost,1) end as QtyPerPack from Items");
            this.LoadFromRawSql(query);
            var preferredPackSizetbl = DataTable;
            var daysOutOfStock = this.GetItemsWithLastIssuedOrDisposedDate();

            var x = (from y in dtbl.AsEnumerable()
                     join z in dtbl2.AsEnumerable()
                     on y["ID"] equals z["ID"]
                     join p in preferredPackSizetbl.AsEnumerable()
                     on y["ID"] equals p["ID"]
                     where Convert.ToInt32(y["EverReceived"]) == 1
                     select new
                     {
                         ID = y["ID"],
                         FullItemName = y["FullItemName"],
                         Unit = y["Unit"],
                         StockCode = y["StockCode"],
                         BeginingBalance = Convert.ToDouble(y["SOH"]),
                         ProgramID = y["ProgramID"],
                         SOH = Convert.ToDouble(z["SOH"]),
                         USOH = Convert.ToDouble(z["Dispatchable"]),
                         Max = Convert.ToInt32(z["Max"]),
                         QtyPerPack = Convert.ToDouble(p["QtyPerPack"]),
                         StockCodeDACA = p["StockCodeDACA"],
                         Status=y["Status"],
                         TypeID=y["TypeID"]
                     }).Distinct().ToArray();

            var m = (from n in x
                     join z in received.AsEnumerable()
                     on n.ID equals z["ID"]
                     select new
                     {
                         ID = n.ID,
                         FullItemName = n.FullItemName,
                         Unit = n.Unit,
                         StockCode = n.StockCode,
                         BeginingBalance = n.BeginingBalance,
                         SOH = n.SOH,
                         USOH = n.USOH,
                         Max = n.Max,
                         QtyPerPack = n.QtyPerPack,
                         StockCodeDACA = n.StockCodeDACA,
                         ProgramID = n.ProgramID,
                         Received = z["Quantity"],
                         Status = n.Status,
                         TypeID = n.TypeID
                        }).ToArray();

            var l = (from n in m
                     join z in issued.AsEnumerable()
                         on n.ID equals z["ID"]
                     select
                         new
                         {
                             ID = n.ID,
                             FullItemName = n.FullItemName,
                             Unit = n.Unit,
                             StockCode = n.StockCode,
                             BeginingBalance = n.BeginingBalance,
                             SOH = n.SOH,
                             USOH = n.USOH ,
                             Max = Convert.ToInt32(z["Quantity"]) * 2,
                             StockCodeDACA = n.StockCodeDACA,
                             QtyPerPack = n.QtyPerPack,
                             Received = n.Received,
                             ProgramID = n.ProgramID,
                             Status=n.Status,
                             Issued = Convert.ToInt32(z["Quantity"]),
                             TypeID=n.TypeID
                             }).ToArray();

            var t = (from n in l
                     join z in lost.AsEnumerable()
                     on n.ID equals z["ID"]
                     select new
                     {
                         ID = n.ID,
                         FullItemName = n.FullItemName,
                         Unit = n.Unit,
                         StockCode = n.StockCode,
                         BeginingBalance = n.BeginingBalance,
                         SOH = n.SOH,
                         USOH = n.USOH ,
                         Max = n.Max,
                         StockCodeDACA = n.StockCodeDACA,
                         QtyPerPack = n.QtyPerPack,
                         Received = n.Received,
                         ProgramID = n.ProgramID,
                         Issued = n.Issued,
                         Status =n.Status,
                         LossAdj = z["Quantity"],
                         Quantity = (n.Max - n.SOH < 0) ? 0 : n.Max - n.SOH,
                         TypeID=n.TypeID
                         }).ToArray();
            if (t.Length == 0)
            {
                var t2 = (from n in l
                          select
                              new
                                  {
                                      ID = n.ID,
                                      FullItemName = n.FullItemName,
                                      Unit = n.Unit,
                                      StockCode = n.StockCode,
                                      BeginingBalance = n.BeginingBalance,
                                      SOH = n.SOH,
                                      USOH = n.USOH,
                                      Max = n.Max,
                                      StockCodeDACA = n.StockCodeDACA,
                                      QtyPerPack = n.QtyPerPack,
                                      Received = n.Received,
                                      Issued = n.Issued,
                                      LossAdj = 0,
                                      ProgramID = n.ProgramID,
                                      Status = n.Status,
                                      Quantity = (n.Max - n.SOH < 0) ? 0 : n.Max - n.SOH,
                                      DaysOutOfStock =Builder.CalculateStockoutDays(Convert.ToInt32(n.ID), storeId, startDate, endDate),
                                      //TODO: This is a quick fix.  We need to take stock status from the last three months.
                                      //TODO: This is a quick fix.  We need to take stock status from the last three months.
                                     // MaxStockQty =((120*n.Issued)/(60 -Convert.ToInt32(Builder.CalculateStockoutDays(Convert.ToInt32(n.ID), storeId, startDate,
                                                                             // endDate)))),
                                      TypeID = n.TypeID
                                  }).ToArray();

                var value = new DataTable();
                value.Columns.Add("ID", typeof (int));
                value.Columns.Add("FullItemName");
                value.Columns.Add("Unit");
                value.Columns.Add("StockCode");
                value.Columns.Add("BeginingBalance", typeof (double));
                value.Columns.Add("SOH", typeof (double));
                value.Columns.Add("Max", typeof (double));
                value.Columns.Add("StockCodeDACA", typeof (string));
                value.Columns.Add("QtyPerPack", typeof (double));
                value.Columns.Add("Issued", typeof (double));
                value.Columns.Add("Received", typeof (double));
                value.Columns.Add("LossAdj", typeof (double));
                value.Columns.Add("Quantity", typeof (double));
                value.Columns.Add("DaysOutOfStock", typeof (int));
                //value.Columns.Add("MaxStockQty", typeof (double));
                value.Columns.Add("ProgramID", typeof (int));
                value.Columns.Add("Status", typeof (string));
                value.Columns.Add("TypeID", typeof (int));
                value.Columns.Add("LastDUSoh", typeof (decimal));
                value.Columns.Add("USOH", typeof (decimal));
                value.Columns.Add("TotalSOH", typeof (decimal));

                foreach (var v in t2)
                {
                    DataRowView drv = value.DefaultView.AddNew();
                    drv["ID"] = v.ID;
                    drv["FullItemName"] = v.FullItemName;
                    drv["Unit"] = v.Unit;
                    drv["StockCode"] = v.StockCode;
                    drv["BeginingBalance"] = v.BeginingBalance;
                    drv["SOH"] = v.SOH;
                    drv["USOH"] = v.USOH;
                    drv["Max"] = v.Max;
                    drv["StockCodeDACA"] = v.StockCodeDACA;
                    drv["QtyPerPack"] = v.QtyPerPack;
                    drv["Issued"] = v.Issued;
                    drv["Received"] = v.Received;
                    drv["LossAdj"] = v.LossAdj;
                    drv["Quantity"] = v.Quantity;
                    drv["ProgramID"] = v.ProgramID;
                    drv["DaysOutOfStock"] = v.DaysOutOfStock;
                    //drv["MaxStockQty"] = v.MaxStockQty;
                    drv["Status"] = v.Status;
                    drv["TypeID"] = v.TypeID;
                    drv["LastDUSoh"] = issue.GetDULastSOH1(Convert.ToInt32(v.ID), dt1, dt2);
                    drv["TotalSOH"] = v.USOH + issue.GetDULastSOH1(Convert.ToInt32(v.ID), dt1, dt2);
                }

                return value;
            }
            else
            {
                var t2 = (from n in t
                          select
                              new
                              {
                                  ID = n.ID,
                                  FullItemName = n.FullItemName,
                                  Unit = n.Unit,
                                  StockCode = n.StockCode,
                                  BeginingBalance = n.BeginingBalance,
                                  SOH = n.SOH,
                                  USOH = n.USOH,
                                  Max = n.Max,
                                  StockCodeDACA = n.StockCodeDACA,
                                  QtyPerPack = n.QtyPerPack,
                                  Received = n.Received,
                                  Issued = n.Issued,
                                  LossAdj = n.LossAdj,
                                  ProgramID = n.ProgramID,
                                  Status = n.Status,
                                  Quantity = (n.Max - n.SOH < 0) ? 0 : n.Max - n.SOH,
                                  DaysOutOfStock =Builder.CalculateStockoutDays(Convert.ToInt32(n.ID), storeId, startDate, endDate),
                                  //TODO: This is a quick fix.  We need to take stock status from the last three months.
                                  //TODO: This is a quick fix.  We need to take stock status from the last three months.
                                  //MaxStockQty =((120 * n.Issued) /(60 -Convert.ToInt32(Builder.CalculateStockoutDays(Convert.ToInt32(n.ID), storeId, startDate,endDate)))),
                                  TypeID = n.TypeID
                              }).ToArray();

                var value = new DataTable();
                value.Columns.Add("ID", typeof(int));
                value.Columns.Add("FullItemName");
                value.Columns.Add("Unit");
                value.Columns.Add("StockCode");
                value.Columns.Add("BeginingBalance", typeof(double));
                value.Columns.Add("SOH", typeof(double));
                value.Columns.Add("Max", typeof(double));
                value.Columns.Add("StockCodeDACA", typeof(string));
                value.Columns.Add("QtyPerPack", typeof(double));
                value.Columns.Add("Issued", typeof(double));
                value.Columns.Add("Received", typeof(double));
                value.Columns.Add("LossAdj", typeof(double));
                value.Columns.Add("Quantity", typeof(double));
                value.Columns.Add("DaysOutOfStock", typeof(int));
                //value.Columns.Add("MaxStockQty", typeof(double));
                value.Columns.Add("ProgramID", typeof(int));
                value.Columns.Add("Status", typeof(string));
                value.Columns.Add("TypeID", typeof(int));
                value.Columns.Add("LastDUSoh", typeof(decimal));
                value.Columns.Add("USOH", typeof(decimal));
                value.Columns.Add("TotalSOH", typeof(decimal));

                foreach (var v in t2)
                {
                    DataRowView drv = value.DefaultView.AddNew();
                    drv["ID"] = v.ID;
                    drv["FullItemName"] = v.FullItemName;
                    drv["Unit"] = v.Unit;
                    drv["StockCode"] = v.StockCode;
                    drv["BeginingBalance"] = v.BeginingBalance;
                    drv["SOH"] = v.SOH;
                    drv["USOH"] = v.USOH;
                    drv["Max"] = v.Max;
                    drv["StockCodeDACA"] = v.StockCodeDACA;
                    drv["QtyPerPack"] = v.QtyPerPack;
                    drv["Issued"] = v.Issued;
                    drv["Received"] = v.Received;
                    drv["LossAdj"] = v.LossAdj;
                    drv["Quantity"] = v.Quantity;
                    drv["ProgramID"] = v.ProgramID;
                    drv["DaysOutOfStock"] = v.DaysOutOfStock;
                    //drv["MaxStockQty"] = v.MaxStockQty;
                    drv["Status"] = v.Status;
                    drv["TypeID"] = v.TypeID;
                    drv["LastDUSoh"] = issue.GetDULastSOH1(Convert.ToInt32(v.ID), dt1, dt2);
                    drv["TotalSOH"] = v.USOH + issue.GetDULastSOH1(Convert.ToInt32(v.ID), dt1, dt2);
                }

                return value;
            }
        }
Exemplo n.º 53
0
        /// <summary>
        /// Fix For Delivery Note When Converting Do not use under any other situation
        /// </summary>
        /// <param name="issueDocID"></param>
        /// <param name="picklistID"></param>
        /// <returns></returns>
        public PickListDetail FixDeliveryNoteCostReceiveDoc(int issueDocID, int picklistID)
        {
            IssueDoc issueDoc = new IssueDoc();

            issueDoc.LoadByPrimaryKey(issueDocID);
            PickListDetail pickList = new PickListDetail();

            pickList.LoadByPrimaryKey(picklistID);
            //safety first
            if (issueDoc.RecievDocID != pickList.ReceiveDocID)
            {
                Item item = new Item();
                item.LoadByPrimaryKey(picklistID);
                throw new Exception(String.Format("PicklistDetail vs IssueDoc Inconsistancy for Item {0}", item.FullItemName));
            }
            // now we are sure we have one ReceiveDocID
            ReceiveDoc receiveDoc = new ReceiveDoc();

            receiveDoc.LoadByPrimaryKey(pickList.ReceiveDocID);
            ReceiveDocConfirmation receiveDocConfirmation = new ReceiveDocConfirmation();

            receiveDocConfirmation.LoadByReceiveDocID(receiveDoc.ID);
            //Check if it has been Printed and that Selling Price and Cost is set
            if (receiveDocConfirmation.ReceiptConfirmationStatusID == ReceiptConfirmationStatus.Constants.GRV_PRINTED)
            {
                double unitPrice, unitCost, margin;
                if (Settings.IsCenter == true && !receiveDoc.IsColumnNull("Cost") && receiveDoc.Cost != 0)
                {
                    unitPrice = Math.Round(receiveDoc.Cost, 2);
                    unitCost  = Math.Round(receiveDoc.Cost, 2);
                    margin    = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;
                }
                else if (!receiveDoc.IsColumnNull("SellingPrice") && receiveDoc.SellingPrice != 0)
                {
                    unitPrice = Math.Round(receiveDoc.SellingPrice, 2);
                    unitCost  = Math.Round(receiveDoc.SellingPrice, 2);
                    margin    = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;
                }
                else
                {
                    var item = new Item();
                    item.LoadByPrimaryKey(pickList.ItemID);
                    throw new Exception(String.Format("Price Not set For item: {0}", item.FullItemName));
                }
                pickList.UnitPrice    = unitPrice;
                pickList.Cost         = Convert.ToDouble(pickList.Packs) * unitPrice;
                issueDoc.SellingPrice = Convert.ToDecimal(unitPrice);
                issueDoc.Cost         = Convert.ToDouble(issueDoc.NoOfPack) * unitPrice;
                issueDoc.UnitCost     = Convert.ToDecimal(unitCost);
                issueDoc.Margin       = Convert.ToDecimal(margin);
                pickList.Save();
                issueDoc.Save();
            }
            else
            {
                var item = new Item();
                item.LoadByPrimaryKey(pickList.ItemID);
                throw new Exception(String.Format("GRV/IGRV Not Printed For Item: {0}", item.FullItemName));
            }
            return(pickList);
        }