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();
        }
        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);
            }
        }
        /// <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);
        }