/// <summary>
 /// Gets the detail for store transfer.
 /// </summary>
 /// <param name="PickListID">The pick list ID.</param>
 /// <returns></returns>
 public static DataView GetDetailForStoreTransfer(int PickListID)
 {
     Transfer transfer = new Transfer();
     string query = HCMIS.Repository.Queries.Transfer.SelectGetDetailForStoreTransfer(PickListID);
     transfer.LoadFromRawSql(query);
     return transfer.DefaultView;
 }
        /// <summary>
        /// Gets the transfer report.
        /// </summary>
        /// <returns></returns>
        public static DataView GetTransferReport()
        {
            Transfer transfer = new Transfer();

            string query = HCMIS.Repository.Queries.Transfer.SelectGetTransferReport();
            transfer.LoadFromRawSql(query);
            return transfer.DefaultView;
        }
        private void lkToStore_EditValueChanged(object sender, EventArgs e)
        {
            if (lkToStore.EditValue == null) return;
            var rec = new Transfer();
            dtRec = rec.GetDistinctRecDocments(Convert.ToInt32(lkToStore.EditValue));

            PopulateDocuments(dtRec);
        }
        /// <summary>
        /// Gets the store transfer.
        /// </summary>
        /// <param name="PicklistID">The picklist ID.</param>
        /// <returns></returns>
        public static DataRowView GetStoreTransfer(int PicklistID)
        {
            Transfer transfer = new Transfer();

            string query = HCMIS.Repository.Queries.Transfer.SelectGetStoreTransfer(PicklistID);
            transfer.LoadFromRawSql(query);
            foreach (DataRowView drv in transfer.DefaultView)
            {
                return drv;
            }
            return null;
        }
        private void dtFrom_ValueChanged(object sender, EventArgs e)
        {
            var rec = new Transfer();
            dtFrom.CustomFormat = "MM/dd/yyyy";
            dtTo.CustomFormat = "MM/dd/yyyy";

            DateTime dteFrom = ConvertDate.DateConverter(dtFrom.Text);
            DateTime dteTo = ConvertDate.DateConverter(dtTo.Text);

            DataTable dtRec = dteFrom < dteTo
                                  ? rec.GetTransactionByDateRange(Convert.ToInt32(lkToStore.EditValue), dteFrom, dteTo)
                                  : rec.GetAllTransaction(Convert.ToInt32(lkToStore.EditValue));
            gridControl1.DataSource = dtRec;
            dtFrom.CustomFormat = "MMMM dd, yyyy";
            dtTo.CustomFormat = "MMMM dd, yyyy";
        }
        /// <summary>
        /// Handles the Click event of the btnConfirmIssue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        /// <exception cref="System.Exception"></exception>
        private void btnConfirmIssue_Click(object sender, EventArgs e)
        {
            // This is where the Issue is actually recorded and the stv is printed.
            // Do all kinds of validations.
            XtraReport STVReport = null; XtraReport DeliveryNoteReport = null;
            btnConfirmIssue1.Enabled = false;
            if (!IssueValid())
            {
                XtraMessageBox.Show("Please Correct the Items Marked in Red before Proceeding with Issue", "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                return;
            }

            if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                DateTimePickerEx dtDate = ConvertDate.GetCurrentEthiopianDateText();

                DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);
                // The User is now sure that the STV has to be printed and that
                // the order is also good to save.
                // This is the section that does the saving.

                BLL.Order order = new Order();
                order.LoadByPrimaryKey(_orderID);

                // what are the pick lists, do we have devliery notes too?
                DataView dv = _dvOutstandingPickList;
                DataTable dvUnpriced = new DataTable();
                DataTable dvPriced = dv.ToTable();

                if (BLL.Settings.HandleGRV)
                {
                    if (BLL.Settings.IsCenter)
                        dv.RowFilter = "(Cost is null or Cost=0)";
                    else
                        dv.RowFilter = "DeliveryNote = true and (Cost is null or Cost=0)";
                    dvUnpriced = dv.ToTable();

                    dv.RowFilter = "Cost is not null and Cost <> 0";
                    dvPriced = dv.ToTable();
                }
                else
                {
                    dvPriced = dv.ToTable();
                }

                string stvPrinterName = "";
                string deliveryNotePrinter = "";

                if (!ConfirmPrinterSettings(dvPriced, dvUnpriced, out stvPrinterName, out deliveryNotePrinter)) return;
                bool saveSuccessful = false;

                MyGeneration.dOOdads.TransactionMgr mgr = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
                try
                {
                    if (dvPriced.Rows.Count == 0 && dvUnpriced.Rows.Count == 0) throw new Exception("The Items doesn’t meet the requirement: please check the price status for non-delivery notes!");

                    mgr.BeginTransaction();

                    if (dvPriced.Rows.Count > 0)
                    {
                        STVReport = SaveAndPrintSTV(dvPriced.DefaultView, false, stvPrinterName, dtDate, dtCurrent);
                    }

                    if (dvUnpriced.Rows.Count > 0)
                    {
                        DeliveryNoteReport = SaveAndPrintSTV(dvUnpriced.DefaultView, true, deliveryNotePrinter, dtDate,
                                                         dtCurrent);
                    }
                    var ordr = new Order();
                    ordr.LoadByPrimaryKey(_orderID);

                    if (!ordr.IsColumnNull("OrderTypeID") &&

                        (ordr.OrderTypeID == BLL.OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER || ordr.OrderTypeID == BLL.OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER))
                    {
                        var transfer = new Transfer();
                        DateTime convertedEthDate = ConvertDate.DateConverter(dtDate.Text);
                        transfer.CommitAccountToAccountTransfer(ordr.ID, CurrentContext.UserId, convertedEthDate);
                    }

                    mgr.CommitTransaction();

                    saveSuccessful = true;

                }
                catch (Exception exp)
                {
                    mgr.RollbackTransaction();
                    //Removed the reset logic
                    //MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgrReset();
                    XtraMessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ErrorHandler.Handle(exp);
                    saveSuccessful = false;
                }

                if (saveSuccessful)
                {
                    if (STVReport != null)
                    {
                        if (InstitutionIType.IsVaccine(GeneralInfo.Current))
                        {
                            for (int i = 0; i < BLL.Settings.STVCopies; i++)
                            {
                                STVReport.Print(stvPrinterName);
                            }
                        }
                        else
                        {
                            STVReport.Print(stvPrinterName);
                        }
                    }

                    if (DeliveryNoteReport != null)
                    { DeliveryNoteReport.Print(deliveryNotePrinter); }

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

                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                BindOutstandingPicklists();
                gridOutstandingPicklistDetail.DataSource = null;
                PalletLocation.GarbageCollection();

                if (BLL.Settings.AllowOnlineOrders)
                {
                    Helpers.RRFServiceIntegration.SubmitOnlineIssue(_orderID);
                }

            }
        }
        /// <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();
            }
        }
        /// <summary>
        /// Transfers to store.
        /// </summary>
        /// <param name="PicklistID">The picklist ID.</param>
        public static void TransferToStore(int PicklistID)
        {
            Transfer transfer = new Transfer();

            string query = HCMIS.Repository.Queries.Transfer.SelectTransferToStore(PicklistID);
            transfer.LoadFromRawSql(query);
        }
        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;
        }
        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);
            }
        }
        private void GenerateTransfer(int OrderID)
        {
            Transfer transfer = new Transfer();
            transfer.AddNew();
            transfer.OrderID = OrderID;
            transfer.FromStoreID = Convert.ToInt32(lkAccountType.EditValue);
            transfer.SetColumn("TransferTypeID",TransferTypeID);
            transfer.FromPhysicalStoreID = Convert.ToInt32(lkFromStore.EditValue);

            if (TransferTypeID == 2)
            {
                transfer.ToStoreID = Convert.ToInt32(lkForHub.EditValue);
            }
            else if (TransferTypeID == 3)
            {
                transfer.ToStoreID = Convert.ToInt32(lkAccountType.EditValue);
                transfer.ToPhysicalStoreID = Convert.ToInt32(lkForHub.EditValue);
            }

            transfer.Save();
        }
        private void LogTransfer_Load(object sender, EventArgs e)
        {
            var stor = new Stores();
            stor.GetActiveStores();
               // lkFromStore.ItemIndex = 0;
            storeBindingSource.DataSource = stor.DefaultView;

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

            // bind the supplier lookup for the grid.

            var unitcolumn = ((GridView)gridControl1.MainView).Columns[4];
            switch (VisibilitySetting.HandleUnits)
            {
                case 1:
                    unitcolumn.Visible = false;
                    break;
                case 2:
                    unitcolumn.Visible = true;
                    break;
                default:
                    unitcolumn.Visible = true;
                    break;
            }

            lkToStore.Properties.DataSource = stor.DefaultView;
            lkToStore.ItemIndex = 0;
            // bind the current dates

            try
            {
                var dr = (DataRowView)lstTree.GetDataRecordByNode(lstTree.Nodes[0].FirstNode);
                if (dr == null) return;
                var rec = new Transfer();
                if (dr["ParentID"] == DBNull.Value)
                {
                    // int yr = ((dtCurrent.Month > 10) ? dtCurrent.Year : dtCurrent.Year - 1);
                    var dt1 = new DateTime(Convert.ToInt32(dr["ID"]) - 1, 11, 1);
                    var dt2 = new DateTime(Convert.ToInt32(dr["ID"]), 11, 1);
                    dtRec = rec.GetTransactionByDateRange(Convert.ToInt32(lkToStore.EditValue), dt1, dt2);
                    lblTransferedDate.Text = dr["RefNo"].ToString();
                }
                else
                {
                    dtRec = rec.GetTransactionByRefNo(dr["RefNo"].ToString(), Convert.ToInt32(lkToStore.EditValue), dr["Date"].ToString());
                    lblTransferedDate.Text = Convert.ToDateTime(dr["Date"]).ToString("MM dd,yyyy");
                }
                gridControl1.DataSource = dtRec;
            }
            catch (Exception ex)
            {

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

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

            gridControl1.DataSource = dtRec;
        }
        /// <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);

            }
        }
        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>
        /// 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;
        }
        private int GenerateTransfer(int OrderID)
        {
            Transfer transfer = new Transfer();
            transfer.AddNew();
            transfer.OrderID = OrderID;
            transfer.FromStoreID = Convert.ToInt32(lkFromActivity.EditValue);
            transfer.SetColumn("TransferTypeID",TransferTypeID);
            transfer.FromPhysicalStoreID = Convert.ToInt32(lkFromStore.EditValue);

            if (TransferTypeID != 1)
            {
                transfer.ToPhysicalStoreID = Convert.ToInt32(lkToStore.EditValue);
                transfer.ToStoreID = Convert.ToInt32(lkToActivity.EditValue);
            }

            transfer.Save();
            var physicalStore = new PhysicalStore();
            physicalStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);
            return physicalStore.PhysicalStoreTypeID;
        }