/// <summary>
        /// Saves the and print STV.
        /// </summary>
        /// <param name="pickListDetail">The pick list detail.</param>
        /// <param name="deliveryNotePrinter">The delivery note printer.</param>
        /// <param name="stvPrinterName">Name of the STV printer.</param>
        /// <param name="dtDate">The dt date.</param>
        /// <param name="dtCurrent">The dt current.</param>
        /// <exception cref="System.Exception"></exception>
        private XtraReport SaveAndPrintSTV(DataView pickListDetail, bool isDeliveryNote, string printerName, DateTimePickerEx dtDate, DateTime dtCurrent)
        {
            HCMIS.Core.Distribution.Services.PrintLogService pLogService = new HCMIS.Core.Distribution.Services.PrintLogService();

            pLogService.StartPrintingSession();

            Order ord = IssueDoc.SaveIssueTransaction(_orderID, ref pickListDetail, txtRemarks.Text,
                                                      CurrentContext.LoggedInUserName, dtCurrent);

            if (pickListDetail.Count == 0)
                throw new Exception("An error occurred during saving the issue.  Please contact your administrator.");

            string sendToString = "";
            BLL.Order ordr = new BLL.Order();
            ordr.LoadByPrimaryKey(_orderID);
            BLL.Institution rus = new Institution();
            if (!ordr.IsColumnNull("RequestedBy"))
            {
                rus.LoadByPrimaryKey(ordr.RequestedBy);
                sendToString = rus.Name;
            }

            else if (!ordr.IsColumnNull("OrderTypeID") &&
                     ordr.OrderTypeID == BLL.OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER)
            {
                BLL.Transfer transfer = new Transfer();
                transfer.LoadByOrderID(_orderID);
                var activity = new Activity();
                activity.LoadByPrimaryKey(transfer.ToStoreID);
                sendToString = activity.FullActivityName;
            }

            PickList pl = new PickList();
            pl.LoadByOrderID(ord.ID);

            var xtraReport = new XtraReport();

            if (ord.PaymentTypeID == PaymentType.Constants.CASH)
            {
                xtraReport = FormatCashInvoice(ord, pickListDetail.Table, rus, pl, isDeliveryNote,
                                  printerName, pLogService);
            }
            else if (ord.PaymentTypeID == PaymentType.Constants.CREDIT)
            {
                xtraReport = FormatCreditInvoice(ord, pickListDetail.Table, rus, pl, isDeliveryNote,
                                    printerName, pLogService);
            }
            else if (ord.PaymentTypeID == PaymentType.Constants.STV)
            {
                xtraReport = FormatSTV(ord, pickListDetail.Table, sendToString, pl, isDeliveryNote,
                          printerName,
                          pLogService, _orderID);
            }

            SavePdfReport(pLogService, xtraReport);
            pLogService.CommitPrintLog();
            return xtraReport;
        }
        /// <summary>
        /// Formats the STV.
        /// </summary>
        /// <param name="ord">The ord.</param>
        /// <param name="dvPriced">The dv priced.</param>
        /// <param name="stvSentTo">The STV sent to.</param>
        /// <param name="pl">The pl.</param>
        /// <param name="deliveryNote">if set to <c>true</c> [delivery note].</param>
        /// <param name="allowCancelByUser">if set to <c>true</c> [allow cancel by user].</param>
        /// <exception cref="System.Exception"></exception>
        private XtraReport FormatSTV(Order ord, DataTable dvPriced, string stvSentTo, PickList pl, bool deliveryNote, string printerName, HCMIS.Core.Distribution.Services.PrintLogService pLogService, int orderID)
        {
            bool hasInsurance = chkIncludeInsurance.Checked;
            string accountName = txtConfirmFromStore.Text;
            string transferType = null;

            int? orderTypeID = null;
            BLL.Order order = new Order();
            order.LoadByPrimaryKey(orderID);

            if (!order.IsColumnNull("OrderTypeID"))
                orderTypeID = Convert.ToInt32(ord.GetColumn("OrderTypeID"));
            string transferDetail = "";
            if (orderTypeID.HasValue)
            {
                BLL.Transfer transfer = new Transfer();

                if (orderTypeID == OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER)
                {
                    transfer.LoadByOrderID(orderID);
                    PhysicalStore toStore = new PhysicalStore();
                    toStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);
                    BLL.Warehouse toWarehouse = new BLL.Warehouse();
                    toWarehouse.LoadByPrimaryKey(toStore.PhysicalStoreTypeID);
                    transferType = "Store to Store Transfer";
                    stvSentTo = toWarehouse.Name;
                }

                if (orderTypeID == OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER)
                {
                    transfer.LoadByOrderID(orderID);
                    Activity fromActivity = new Activity();
                    fromActivity.LoadByPrimaryKey(transfer.FromStoreID);
                    Activity toActivity = new Activity();
                    toActivity.LoadByPrimaryKey(transfer.ToStoreID);
                    transferType = "Account to Account Transfer";
                    transferDetail = string.Format("From: {0} To: {1}", fromActivity.FullActivityName, toActivity.FullActivityName);
                }
            }

            if (!deliveryNote)
            {
                if(InstitutionIType.IsVaccine(GeneralInfo.Current))
                {
                    return WorkflowReportFactory.CreateModel22(ord, dvPriced, stvSentTo, pl.ID, null, false, true, hasInsurance, transferType);
                }
                var stvReport = WorkflowReportFactory.CreateSTVonHeadedPaper(ord, dvPriced, stvSentTo, pl.ID, null, false, true, hasInsurance, transferType);
                if (transferDetail != "")
                {
                    stvReport.TransferDetails.Text = transferDetail;
                    stvReport.TransferDetails.Visible = true;
                }
                else
                {
                    stvReport.TransferDetails.Visible = false;
                }

                return stvReport;
            }
            else
            {
                return WorkflowReportFactory.CreateDeliveryNote(ord, dvPriced, stvSentTo, pl.ID, null, false, true, hasInsurance, transferType);

            }
        }
        /// <summary>
        /// Commits the account to account transfer.
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="convertedEthDate">The converted eth date.</param>
        public void CommitAccountToAccountTransfer(int orderID, int userID, DateTime convertedEthDate)
        {
            int? supplierID = null;
            BLL.Transfer transfer = new Transfer();
            transfer.LoadByOrderID(orderID);
            if (transfer.RowCount == 0)
                return;

            int newStoreID, newPhysicalStoreID;
            newStoreID = transfer.ToStoreID;
            newPhysicalStoreID = transfer.ToPhysicalStoreID;

            PhysicalStore toPhysicalStore = new PhysicalStore();
            toPhysicalStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);

            BLL.PickList picklist = new PickList();
            picklist.LoadByOrderID(orderID);
            BLL.PickListDetail pld = new PickListDetail();
            pld.LoadByPickListIDWithStvlogID(picklist.ID);
            BLL.ReceiveDoc rdOriginal = new ReceiveDoc();
            rdOriginal.LoadByPrimaryKey(pld.ReceiveDocID);

            BLL.Order order=new Order();
            order.LoadByPrimaryKey(orderID);
            if(order.OrderTypeID == OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER)
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(newStoreID);
                supplierID = activity.SupplierID;
            }
            else if(order.OrderTypeID == OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER)
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(newPhysicalStoreID);
                supplierID = activity.SupplierID;
            }
            PO po = PO.CreatePOforStandard( (int) order.GetColumn("OrderTypeID"),transfer.ToStoreID,supplierID,"Transfer",CurrentContext.LoggedInUser.ID);
            int IDPrinted = Convert.ToInt32(pld.GetColumn("IDPrinted"));
            int receiptTypeID = order.OrderTypeID == OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER
                                    ? ReceiptType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER
                                    :order.OrderTypeID == OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER
                                          ? ReceiptType.CONSTANTS.STORE_TO_STORE_TRANSFER
                                          : order.OrderTypeID == OrderType.CONSTANTS.ERROR_CORRECTION_TRANSFER
                                          ? ReceiptType.CONSTANTS.ERROR_CORRECTION:ReceiptType.CONSTANTS.STANDARD_RECEIPT;

            Receipt receipt = ReceiptInvoice.CreateReceiptInvoiceAndReceiptForTransfer(receiptTypeID,po.ID,toPhysicalStore.PhysicalStoreTypeID,IDPrinted,userID);

            var mergedPickLists = MergePickListsOfSameInfo(pld); // Picklists of the same info means: Based on all constraints we have on receiveDoc(Batch,Exp,ItemID,UnitID...): should be merged with summed quantity.

            pld.Rewind();
            while (!pld.EOF)
            {
                if(IDPrinted != Convert.ToInt32(pld.GetColumn("IDPrinted")))
                {
                    IDPrinted = Convert.ToInt32(pld.GetColumn("IDPrinted"));
                    receipt = ReceiptInvoice.CreateReceiptInvoiceAndReceiptForTransfer(receiptTypeID,po.ID, toPhysicalStore.PhysicalStoreTypeID, IDPrinted, userID);
                }

                var rDoc = new ReceiveDoc();
                if (!mergedPickLists.ContainsKey(pld.ID))
                {
                    pld.MoveNext();
                    continue;
                }

                rDoc.SaveNewReceiveDocEntryFromPicklistDetail(pld, userID, newStoreID, newPhysicalStoreID,
                                                              convertedEthDate,receipt.ID,supplierID);
                pld.MoveNext();
            }
        }
        private static string GetReceivingUnitName(Order order)
        {
            if (!order.IsColumnNull("RequestedBy"))
            {
                var rus = new Institution();
                rus.LoadByPrimaryKey(order.RequestedBy);
                return rus.Name;
            }

            if (!order.IsColumnNull("OrderTypeID") && order.OrderTypeID == OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER)
            {
                var transfer = new Transfer();
                transfer.LoadByOrderID(order.ID);

                var activity = new Activity();
                activity.LoadByPrimaryKey(transfer.ToStoreID);
                return activity.FullActivityName;
            }
            return "";
        }
        /// <summary>
        /// Commits the account to account transfer.
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="convertedEthDate">The converted eth date.</param>
        public void CommitAccountToAccountTransfer(int orderID, int userID, DateTime convertedEthDate)
        {
            int?supplierID = null;

            BLL.Transfer transfer = new Transfer();
            transfer.LoadByOrderID(orderID);
            if (transfer.RowCount == 0)
            {
                return;
            }

            int newStoreID, newPhysicalStoreID;

            newStoreID         = transfer.ToStoreID;
            newPhysicalStoreID = transfer.ToPhysicalStoreID;

            PhysicalStore toPhysicalStore = new PhysicalStore();

            toPhysicalStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);

            BLL.PickList picklist = new PickList();
            picklist.LoadByOrderID(orderID);
            BLL.PickListDetail pld = new PickListDetail();
            pld.LoadByPickListIDWithStvlogID(picklist.ID);
            BLL.ReceiveDoc rdOriginal = new ReceiveDoc();
            rdOriginal.LoadByPrimaryKey(pld.ReceiveDocID);


            BLL.Order order = new Order();
            order.LoadByPrimaryKey(orderID);
            if (order.OrderTypeID == OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER)
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(newStoreID);
                supplierID = activity.SupplierID;
            }
            else if (order.OrderTypeID == OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER)
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(newPhysicalStoreID);
                supplierID = activity.SupplierID;
            }
            PO  po            = PO.CreatePOforStandard((int)order.GetColumn("OrderTypeID"), transfer.ToStoreID, supplierID, "Transfer", CurrentContext.LoggedInUser.ID);
            int IDPrinted     = Convert.ToInt32(pld.GetColumn("IDPrinted"));
            int receiptTypeID = order.OrderTypeID == OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER
                                    ? ReceiptType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER
                                    :order.OrderTypeID == OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER
                                          ? ReceiptType.CONSTANTS.STORE_TO_STORE_TRANSFER
                                          : order.OrderTypeID == OrderType.CONSTANTS.ERROR_CORRECTION_TRANSFER
                                          ? ReceiptType.CONSTANTS.ERROR_CORRECTION:ReceiptType.CONSTANTS.STANDARD_RECEIPT;



            Receipt receipt = ReceiptInvoice.CreateReceiptInvoiceAndReceiptForTransfer(receiptTypeID, po.ID, toPhysicalStore.PhysicalStoreTypeID, IDPrinted, userID);

            var mergedPickLists = MergePickListsOfSameInfo(pld); // Picklists of the same info means: Based on all constraints we have on receiveDoc(Batch,Exp,ItemID,UnitID...): should be merged with summed quantity.

            pld.Rewind();
            while (!pld.EOF)
            {
                if (IDPrinted != Convert.ToInt32(pld.GetColumn("IDPrinted")))
                {
                    IDPrinted = Convert.ToInt32(pld.GetColumn("IDPrinted"));
                    receipt   = ReceiptInvoice.CreateReceiptInvoiceAndReceiptForTransfer(receiptTypeID, po.ID, toPhysicalStore.PhysicalStoreTypeID, IDPrinted, userID);
                }

                var rDoc = new ReceiveDoc();
                if (!mergedPickLists.ContainsKey(pld.ID))
                {
                    pld.MoveNext();
                    continue;
                }

                rDoc.SaveNewReceiveDocEntryFromPicklistDetail(pld, userID, newStoreID, newPhysicalStoreID,
                                                              convertedEthDate, receipt.ID, supplierID);
                pld.MoveNext();
            }
        }
        private int SaveOrder()
        {
            int warehouseID;
            var order = GenerateOrder();
            PickList pickList = PickList.GeneratePickList(order.ID);
            int picklistId = pickList.ID;
            if (TransferTypeID != Transfer.Constants.HUB_TO_HUB)
            {
                warehouseID = GenerateTransfer(order.ID);
            }

            // Log
            this.LogActivity("Transfer", order.ID);

            int LineNo = 0;

            // This is a kind of initializing the data table.

            DataView dv = orderGrid.DataSource as DataView;

            foreach (DataRowView r in dv)
            {
                if (r["ApprovedPacks"] != null && r["ApprovedPacks"] != DBNull.Value && r["ApprovedPacks"].ToString()!= "")
                    if (Convert.ToDecimal(r["ApprovedPacks"]) != 0)
                    {
                        LineNo = LineNo + 1;
                        int itemId = Convert.ToInt32(r["ItemID"]);
                        int unitId = Convert.ToInt32(r["UnitID"]);
                        decimal pack = Convert.ToDecimal(r["ApprovedPacks"]);
                        int qtyPerPack = Convert.ToInt32(r["QtyPerPack"]);
                        int activityId = Convert.ToInt32(lkFromActivity.EditValue);
                        int manufacturerId = Convert.ToInt32(Convert.ToInt32(r["ManufacturerID"]));
                        int receivePalletId = Convert.ToInt32(r["ReceivingLocationID"]);
                        int palletLocationId = Convert.ToInt32(r["LocationID"]);
                        double? unitPrice;
                        string batchNumber = r["BatchNo"].ToString();
                        string expireDate ="" ;
                        int receiveDocId = Convert.ToInt32(r["ReceiveDocID"]);
                        if((r["UnitPrice"] != DBNull.Value))
                        {
                            unitPrice = Convert.ToDouble(r["UnitPrice"]);
                        }
                        else
                        {
                            unitPrice = null;
                        }

                        if (r["ExpDate"] != DBNull.Value)
                             expireDate= r["ExpDate"].ToString();

                        OrderDetail ord = OrderDetail.GenerateOrderDetail(unitId, activityId, pack, order.ID, qtyPerPack, itemId);
                        PalletLocation palletLocation = new PalletLocation();
                        palletLocation.LoadByPrimaryKey(palletLocationId);
                        int palletID = palletLocation.PalletID;
                        PickListDetail pkDetail = PickListDetail.GeneratePickListDetail(pack, unitPrice, receiveDocId, manufacturerId, receivePalletId, qtyPerPack, activityId, unitId, itemId, picklistId, palletID, expireDate, batchNumber);
                        ReceivePallet.ReserveQty(pack, receivePalletId);
                        //To Print The Picklist
                        //Then reserve Items

                       Item item = new Item();
                        item.LoadByPrimaryKey(itemId);
                        DataRow drvpl = dvPickList.NewRow();
                        drvpl["FullItemName"] = item.FullItemName;
                        drvpl["StockCode"] = item.StockCode;
                        drvpl["BatchNo"] = batchNumber;
                        if (expireDate != "" )
                            drvpl["ExpDate"] = Convert.ToDateTime(expireDate).ToString("MMM/yyyy");
                        else
                            drvpl["ExpDate"] = DBNull.Value;
                        drvpl["LineNum"] = LineNo + 1;
                        var manufacturer = new Manufacturer();
                        manufacturer.LoadByPrimaryKey(manufacturerId);
                        drvpl["ManufacturerName"] = manufacturer.Name;

                        drvpl["Pack"] = pack;
                        drvpl["UnitPrice"] = unitPrice;
                        var unit = new ItemUnit();
                        unit.LoadByPrimaryKey(unitId);

                        drvpl["Unit"] = unit.Text;

                        drvpl["QtyInSKU"] = pack;
                        if (unitPrice != null)
                             drvpl["CalculatedCost"] = pack *Convert.ToDecimal(unitPrice);

                         palletLocation.LoadByPrimaryKey(pkDetail.PalletLocationID);
                         drvpl["PalletLocation"] = palletLocation.Label;
                         drvpl["WarehouseName"] = palletLocation.WarehouseName;
                        drvpl["PhysicalStoreName"] = palletLocation.PhysicalStoreName;
                        var activity = new Activity();
                        activity.LoadByPrimaryKey(pkDetail.StoreID);
                        drvpl["ActivityConcat"] = activity.FullActivityName;
                        drvpl["AccountName"] = activity.AccountName;
                        dvPickList.Rows.Add(drvpl);
                    }

            }
            if (LineNo == 0)
                throw new System.ArgumentException("Please review your list,you haven't approved any Quantity");
            string receivingUnit;
                Transfer transfer = new Transfer();
                transfer.LoadByOrderID(order.ID);
                if (TransferTypeID == Transfer.Constants.ACCOUNT_TO_ACCOUNT)
                {
                    var fromActivity = new Activity();
                    fromActivity.LoadByPrimaryKey(transfer.FromStoreID);
                    var toActivity = new Activity();
                    toActivity.LoadByPrimaryKey(transfer.ToStoreID);

                    receivingUnit = String.Format("Account to Account from {0} to {1}", fromActivity.FullActivityName,
                                                toActivity.FullActivityName);
                }
                else if (TransferTypeID == Transfer.Constants.STORE_TO_STORE)
                {

                    var toStore = new PhysicalStore();

                    toStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);
                    receivingUnit = string.Format("Store to Store transfer to: {0}", toStore.WarehouseName);
                }
                else
                {
                    receivingUnit = lkForHub.Text;
                }
            var plr = HCMIS.Desktop.Reports.WorkflowReportFactory.CreatePicklistReport(order, receivingUnit,
                                                                                       dvPickList.DefaultView);
            plr.PrintDialog();

                XtraMessageBox.Show("Picklist Prepared!", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return order.ID;
        }