private void chkEditInprocess_CheckedChanged(object sender, EventArgs e)
 {
     DataRow dr = grdViewClientStatus.GetFocusedDataRow();
         int id = Convert.ToInt32(dr["ID"]);
         BLL.Institution ru = new BLL.Institution();
         ru.LoadByPrimaryKey(id);
         bool PreviousValue;
         if (!dr.IsNull("InProcess"))
             PreviousValue = Convert.ToBoolean(dr["InProcess"]);
         else
             PreviousValue = false;
         if (!Convert.ToBoolean(dr["Active"]))
         {
             ru.InProcess = PreviousValue;
             LoadReceivingUnits();
             XtraMessageBox.Show(string.Format("The {0} is inactive, you are not allow to change any status", dr["Name"].ToString().ToUpper()), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
         else if (XtraMessageBox.Show(string.Format("Are you sure you want to allow {0} to get service ", dr["Name"].ToString()), "Are you Sure", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
         {
             ru.InProcess = !PreviousValue;
             ru.Save();
         }
         else
         ru.InProcess = PreviousValue;
         LoadReceivingUnits();
 }
        private void chkEditInprocess_CheckedChanged(object sender, EventArgs e)
        {
            DataRow dr = grdViewClientStatus.GetFocusedDataRow();
            int     id = Convert.ToInt32(dr["ID"]);

            BLL.Institution ru = new BLL.Institution();
            ru.LoadByPrimaryKey(id);
            bool PreviousValue;

            if (!dr.IsNull("InProcess"))
            {
                PreviousValue = Convert.ToBoolean(dr["InProcess"]);
            }
            else
            {
                PreviousValue = false;
            }
            if (!Convert.ToBoolean(dr["Active"]))
            {
                ru.InProcess = PreviousValue;
                LoadReceivingUnits();
                XtraMessageBox.Show(string.Format("The {0} is inactive, you are not allow to change any status", dr["Name"].ToString().ToUpper()), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (XtraMessageBox.Show(string.Format("Are you sure you want to allow {0} to get service ", dr["Name"].ToString()), "Are you Sure", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                ru.InProcess = !PreviousValue;
                ru.Save();
            }
            else
            {
                ru.InProcess = PreviousValue;
            }
            LoadReceivingUnits();
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            var dvPickListMakeup = (DataTable)gridTransactions.DataSource;

            var ord = new BLL.Order();
            ord.LoadByPrimaryKey(OrderID);

            var rus = new Institution();
            rus.LoadByPrimaryKey(ord.RequestedBy);

            if (BLL.Settings.IsCenter)
            {
                dvPickListMakeup.Columns["PhysicalStoreTypeName"].ColumnName = "WarehouseName";
                dvPickListMakeup.Columns["SKUTOPICK"].ColumnName = "QtyInSKU";
                dvPickListMakeup.Columns["StoreGroupName"].ColumnName = "AccountName";
                dvPickListMakeup.Columns.Add("ActivityConcat");

                foreach (DataRow r in dvPickListMakeup.Rows)
                {
                    var activity = new Activity();
                    activity.LoadByPrimaryKey(Convert.ToInt32(r["StoreID"]));
                    r["ActivityConcat"] = activity.FullActivityName;
                }
            }
            var pl = HCMIS.Desktop.Reports.WorkflowReportFactory.CreatePicklistReport(ord, rus.Name, dvPickListMakeup.DefaultView);

            pl.ShowPreviewDialog();
            // refresh the display
            lstRefNo_FocusedNodeChanged(null, null);
        }
 /// <summary>
 /// Returns 0 if there is no limit
 /// </summary>
 /// <param name="itemID"></param>
 /// <param name="receivingUnitID"></param>
 /// <returns></returns>
 internal long GetMaxIssueQuantity(int itemID, int receivingUnitID)
 {
     Institution ru = new Institution();
     ru.LoadByPrimaryKey(receivingUnitID);
     this.FlushData();
     this.Where.ItemID.Value = itemID;
     this.Where.ReceivingUnitTypeID.Value = ru.RUType;
     this.Query.Load();
     if (this.RowCount > 0)
         return this.MaxIssueQty;
     return 0;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Returns the product Allow status as an integer
        /// </summary>
        /// <param name="productID"></param>
        /// <param name="receivingUnitID"></param>
        /// <returns>1=AllowFully, 0=Warning, -1 = Restricted</returns>
        public int ProductAllowStatus(int productID, int receivingUnitID)
        {
            Institution              institution     = new Institution();
            ProductOwnershipType     ownershipStatus = new ProductOwnershipType();
            ProductReceivingUnitType ruTypeStatus    = new ProductReceivingUnitType();

            institution.LoadByPrimaryKey(receivingUnitID);

            ownershipStatus.Where.RUOwnershipTypeID.Value = institution.Ownership;
            ownershipStatus.Where.ProductID.Value         = productID;
            ownershipStatus.Query.Load();

            if (ownershipStatus.RowCount > 0)
            {
                if (!ownershipStatus.IsColumnNull("Restriction") && ownershipStatus.Restriction)
                {
                    return(-1);
                }
                else if (!ownershipStatus.IsColumnNull("Warning") && ownershipStatus.Warning)
                {
                    return(0);
                }
                else if (!ownershipStatus.IsColumnNull("AllowFully") && ownershipStatus.AllowFully)
                {
                    return(1);
                }
            }

            ruTypeStatus.Where.ReceivingUnitTypeID.Value = institution.RUType;
            ruTypeStatus.Where.ProductID.Value           = productID;
            ruTypeStatus.Query.Load();

            if (ruTypeStatus.RowCount > 0)
            {
                if (!ruTypeStatus.IsColumnNull("Restriction") && ruTypeStatus.Restriction)
                {
                    return(-1);
                }
                if (!ruTypeStatus.IsColumnNull("Warning") && ruTypeStatus.Warning)
                {
                    return(0);
                }
                if (!ruTypeStatus.IsColumnNull("AllowFully") && ruTypeStatus.AllowFully)
                {
                    return(1);
                }
            }
            //If it gets here, this means there is no entry in the table about the allow status for this product.  Therefore we give full allow status.
            return(1);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Returns 0 if there is no limit
        /// </summary>
        /// <param name="itemID"></param>
        /// <param name="receivingUnitID"></param>
        /// <returns></returns>
        internal long GetMaxIssueQuantity(int itemID, int receivingUnitID)
        {
            Institution ru = new Institution();

            ru.LoadByPrimaryKey(receivingUnitID);
            this.FlushData();
            this.Where.ItemID.Value = itemID;
            this.Where.ReceivingUnitTypeID.Value = ru.RUType;
            this.Query.Load();
            if (this.RowCount > 0)
            {
                return(this.MaxIssueQty);
            }
            return(0);
        }
        /// <summary>
        /// Returns the product Allow status as an integer
        /// </summary>
        /// <param name="productID"></param>
        /// <param name="receivingUnitID"></param>
        /// <returns>1=AllowFully, 0=Warning, -1 = Restricted</returns>
        public int ProductAllowStatus(int productID, int receivingUnitID)
        {
            Institution institution = new Institution();
            ProductOwnershipType ownershipStatus = new ProductOwnershipType();
            ProductReceivingUnitType ruTypeStatus = new ProductReceivingUnitType();

            institution.LoadByPrimaryKey(receivingUnitID);

            ownershipStatus.Where.RUOwnershipTypeID.Value = institution.Ownership;
            ownershipStatus.Where.ProductID.Value = productID;
            ownershipStatus.Query.Load();

            if (ownershipStatus.RowCount > 0)
            {
                if (!ownershipStatus.IsColumnNull("Restriction") && ownershipStatus.Restriction)
                    return -1;
                else if (!ownershipStatus.IsColumnNull("Warning") && ownershipStatus.Warning)
                    return 0;
                else if (!ownershipStatus.IsColumnNull("AllowFully") && ownershipStatus.AllowFully)
                    return 1;
            }

            ruTypeStatus.Where.ReceivingUnitTypeID.Value = institution.RUType;
            ruTypeStatus.Where.ProductID.Value = productID;
            ruTypeStatus.Query.Load();

            if (ruTypeStatus.RowCount > 0)
            {
                if (!ruTypeStatus.IsColumnNull("Restriction") && ruTypeStatus.Restriction)
                    return -1;
                if (!ruTypeStatus.IsColumnNull("Warning") && ruTypeStatus.Warning)
                    return 0;
                if (!ruTypeStatus.IsColumnNull("AllowFully") && ruTypeStatus.AllowFully)
                    return 1;
            }
            //If it gets here, this means there is no entry in the table about the allow status for this product.  Therefore we give full allow status.
            return 1;
        }
        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>
        /// 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 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 "";
        }
 public string ZoneName()
 {
     if (!IsColumnNull("RequestedBy"))
     {
         var rus = new Institution();
         rus.LoadByPrimaryKey(RequestedBy);
         return rus.ZoneName;
     }
     return "";
 }
        private void lkForFacility_EditValueChanged(object sender, EventArgs e)
        {
            if (lkForFacility.EditValue == null)
                return;
            FacilityChanged(lkForFacility);

            Institution ru = new Institution();
            ru.LoadByPrimaryKey(Convert.ToInt32(lkForFacility.EditValue));

            if (!ru.IsColumnNull("Woreda"))
            {
                BLL.Woreda woreda = new BLL.Woreda();
                woreda.LoadByPrimaryKey(ru.Woreda);

                BLL.Zone zone = new BLL.Zone();
                zone.LoadByPrimaryKey(woreda.ZoneID);

                lkRegion.EditValue = zone.RegionId;
                lkZone.EditValue = zone.ID;
                lkWoreda.EditValue = ru.Woreda;

            }

            lkOwnership.EditValue = ru.Ownership;

            lkType.EditValue = ru.RUType;

            //Fill facility visit history
            DataRow facilityHis = BLL.Issue.GetVisitHistoryForFacility((int)lkForFacility.EditValue);
            NoOfVisitLabel.Text = facilityHis != null ? Convert.ToInt32(facilityHis["VisitCount"]).ToString(CultureInfo.InvariantCulture) : "0";
            LastVisitlabel.Text = facilityHis != null ? Convert.ToDateTime(facilityHis["LastVisit"]).TimeAgo() : "Never";

            //Reset Requisitoin Type
            if(!BLL.Settings.IsCenter && OrderID == null && Type == RequisitionType.History) lkRequisitionType_EditValueChanged(null, null);
        }
        public void EditRequisition(int orderID)
        {
            OrderID = orderID;
            Order ord = new Order();
            ord.LoadByPrimaryKey(orderID);
            txtRefNo.Text = ord.RefNo;
            txtLetterNumber.Text = ord.LetterNo;
            labelControl4.Text = ord.RefNo;
            Institution ru = new Institution();
            ru.LoadByPrimaryKey(ord.RequestedBy);

            if (!ru.IsColumnNull("Zone"))
            {
                // Just because the region Property on the Receiving Unit is not working as desired.
                Zone zone = new Zone();
                zone.LoadByPrimaryKey(ru.Zone);

                lkRegion.EditValue = zone.RegionId;
                lkZone.EditValue = ru.Zone;
            }
            lkForFacility.EditValue = ru.ID;

            lkModes.EditValue = ord.FromStore;
            lkModes_EditValueChanged(null, null);

            lkPaymentType.EditValue = ord.PaymentTypeID;
            txtContactPerson.EditValue = ord.ContactPerson;

            BLL.OrderDetail or = new BLL.OrderDetail();
            or.LoadAllByOrderID(orderID);

            DataView selectables = (DataView)gridItemChoiceView.DataSource;

            if (_dtSelectedTable != null)
            {
                _dtSelectedTable.Clear();
            }
            else
            {
                PopulateItemsList();
            }

            while (!or.EOF)
            {
                // select the items and put it in the dtselected table.
                if (selectables != null)
                {
                    DataRow[] dataRows = selectables.Table.Select(String.Format("ID = {0} and UnitID = {1}", or.ItemID, or.UnitID));
                    if (dataRows.Length > 0)
                    {
                        _dtSelectedTable.ImportRow(dataRows[0]);
                        dataRows[0]["IsSelected"] = true;
                    }
                }
                or.MoveNext();
            }

            _dvOrderTable = or.DefaultView;
            orderGrid.DataSource = _dvOrderTable;
            EnableDisableButtons();
        }
        private void OnUndispatchedIssueClicked(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            var dr = gridUndispatchedIssuesView.GetFocusedDataRow();
            _activeSTVID = Convert.ToInt32(dr["STVID"]);
            gridUndispatchedIssueDetails.DataSource = BLL.Issue.GetIssueDetails(_activeSTVID);

            User usr = new User();
            //usr.LoadByPrimaryKey(NewMainWindow.UserId);
            usr = CurrentContext.LoggedInUser;
            BLL.Issue stv = new BLL.Issue();
            stv.LoadByPrimaryKey(_activeSTVID);

            var activity = new Activity();
            activity.LoadByPrimaryKey(stv.StoreID);
            lblMode.Text = activity.ModeName ??"-" ;

            lblAccount.Text = activity.AccountName ?? "-";

            lblActivity.Text = activity.FullActivityName ?? "-";
            lblSubAccount.Text = activity.SubAccountName ?? "-";

            lblIssueStatus.Text = (string)dr["OrderStatus"] ?? "-";
            lblIssueType.Text = (string) dr["OrderType"] ?? "-";

            if (!stv.IsColumnNull("ReceivingUnitID"))
            {
                var institution = new Institution();
                institution.LoadByPrimaryKey(stv.ReceivingUnitID);

                var ownership = new BLL.OwnershipType();
                ownership.LoadByPrimaryKey(institution.Ownership);

                lblRegion.Text = institution.RegionName ?? "-";
                lblZone.Text = institution.ZoneName ?? "-";
                lblWoreda.Text = institution.WoredaName ?? "-";
                var space = "";
                int length =  (institution.Name).Length;
                if(stv.IsColumnNull("IsReprintOf"))
                    FacilityGroup.Text = institution.Name ?? "" +space.PadRight(180 - length) + "Invoice No: " + stv.IDPrinted.ToString("00000");

                lblInstitutionType.Text = institution.InstitutionTypeName;
                lblOwnership.Text = ownership.Name;
            }
            else
            {
                lblRegion.Text =
                    lblZone.Text = lblWoreda.Text  = "NA";
                lblInstitutionType.Text = lblOwnership.Text = "-";
                FacilityGroup.Text = "";
            }

            if (!stv.IsColumnNull("PaymentTypeID"))
            {
                var paymentType = new BLL.PaymentType();
                paymentType.LoadByPrimaryKey(stv.PaymentTypeID);
                lblPaymentType.Text = paymentType.Name;
            }
            else
            {
                lblPaymentType.Text = "-";
            }

            if (!stv.IsColumnNull("DocumentTypeID"))
            {
                lblDocumentedType.Text = DocumentType.GetDocumentType(stv.DocumentTypeID).Name;
            }
            else
                lblDocumentedType.Text = "-";

            lblRequistedDate.Text = dr["VoidRequestDateTime"] == DBNull.Value
                ? "NA"
                : DateTime.Parse(dr["VoidRequestDateTime"].ToString()).ToShortDateString();

            lblVoidRequestedBy.Text = dr["VoidRequestedBy"] == DBNull.Value ? "NA" : (string) dr["VoidRequestedBy"];

            var user = new BLL.User();
            if (dr["VoidApprovedByUserID"] != DBNull.Value)
            {
                user.LoadByPrimaryKey(Convert.ToInt32(dr["VoidApprovedByUserID"]));
                lblVoidConfirmedBy.Text = user.FullName;
            }
            else
            {
                lblVoidConfirmedBy.Text = "NA";
            }

            lblVoidConfirmedDate.Text = dr["VoidApprovalDateTime"] == DBNull.Value
                ? "NA"
                : DateTime.Parse(dr["VoidApprovalDateTime"].ToString()).ToShortDateString();

            stv.LoadLatestReprint();
            txtIssuedBy.Text = usr.FullName ?? "-";
            lblDispatchConfirmedBy.Text = usr.FullName ?? "-";

               // txtSTVInvoiceNo.Text = stv.IDPrinted.ToString("00000");
            lblSTVNo.Text = stv.IDPrinted.ToString("00000") ?? "-";
            lblSTVDate.Text = stv.PrintedDate.ToShortDateString() ?? "-";

            user.LoadByPrimaryKey(stv.UserID);
            lblSTVPrintedBy.Text = user.FullName ?? "-";

            txtPreprintedInvoiceNo.Text = stv.IsColumnNull("PrePrintedInvoiceNo") ? "" : stv.PrePrintedInvoiceNo.ToString();
        }
 private void PrintPicklistItems(object sender, EventArgs e)
 {
     BLL.Order ord = new BLL.Order();
     ord.LoadByPrimaryKey(_orderID);
     BLL.Institution rus = new Institution();
     rus.LoadByPrimaryKey(ord.RequestedBy);
     XtraReport pickList;
     pickList = WorkflowReportFactory.CreatePicklistReport(ord, rus.Name,_dvPickListMakeup);
     pickList.ShowPreviewDialog();
 }
        private void OnApprovedOrderRowClicked(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e != null && e.RowHandle < -1)
                return;

            var gv = (GridView)sender;
            var dr = gv.GetFocusedDataRow();
            _orderID = Convert.ToInt32(dr["ID"].ToString());

            order.LoadByPrimaryKey(_orderID);
            // populate the general order variables
            txtPickListFromStore.Text = order.GetFromStore();
            lblMode.Text = order.GetFromStore() ?? "-";

            txtPickListRequestedBy.Text = order.GetRequestedBy();
            labelControl9.Text = order.GetRequestedBy() ?? "-";

            var us = new BLL.User();

            us.LoadByPrimaryKey(order.FilledBy);
            lblFilledBy.Text = us.FullName ?? "-";
            string s = "";

            lblLetterNum.Text = String.IsNullOrEmpty(order.LetterNo) ? "-" : order.LetterNo;

            var orderDetail = new OrderDetail();
            orderDetail.LoadAllByOrderID(order.ID);

            var paymentType = new BLL.PaymentType();
            paymentType.LoadByPrimaryKey(order.PaymentTypeID);

            if (!orderDetail.IsColumnNull("StoreID"))
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(orderDetail.StoreID);
                lblMode.Text = activity.ModeName ?? "-";
            }

            lblIssueStatus.Text = (string)dr["OrderStatus"] ?? "-";
            lblIssueType.Text = (string)dr["Description"] ?? "-";

            if (!order.IsColumnNull("RequestedBy"))
            {
                var ins = new Institution();
                ins.LoadByPrimaryKey(order.RequestedBy);

                var ownership = new BLL.OwnershipType();
                ownership.LoadByPrimaryKey(ins.Ownership);

                int length = ins.Name.Length;
                HeaderSection.Text = ins.Name + s.PadRight(150 - length) + "Order Number: " + order.RefNo;
                lblOwnership.Text = ownership.Name ?? "-";
                lblZone.Text = ins.ZoneName ?? "-";
                lblWoreda.Text = ins.WoredaName ?? "-";
                lblRegion.Text = ins.RegionName ?? "-";
                lblInstitutionType.Text = ins.InstitutionTypeName ?? "-";
            }
            else
            {
                HeaderSection.Text =lblOwnership.Text = lblZone.Text =lblWoreda.Text =lblRegion.Text = lblInstitutionType.Text = "-";
            }

            lblPaymentType.Text = paymentType.Name;
            lblOrderDate.Text = order.Date.ToShortDateString();

            txtPickListOrderNumber.Text = order.RefNo;
            labelControl12.Text = order.RefNo;

            txtPickListApprovedBy.Text = order.GetApprovedBy();
            labelControl13.Text = order.GetApprovedBy();

            if (order.OrderStatusID == OrderStatus.Constant.PICK_LIST_GENERATED)
            {
                PickList pl = new PickList();
                gridPickListDetail.DataSource = pl.GetPickListDetailsForOrder(_orderID);

                btnPrintAndSavePickList.Text = @"Confirm";
                colPrice.FieldName = "Cost";
                colSKU.FieldName = "Packs";
                btnCancelPickList.Enabled = (BLL.Settings.UseNewUserManagement)? this.HasPermission("Cancel-Pick-List"):true;

                pl.LoadByOrderID(_orderID);
                if (!pl.IsColumnNull("PickedBy"))
                {
                    us.LoadByPrimaryKey(pl.PickedBy);
                    lblPicklistPrintedBy.Text = us.FullName;
                }
                else lblPicklistPrintedBy.Text = "-";

                lblPicklistPrintedDate.Text = !pl.IsColumnNull("SavedDate") ? pl.SavedDate.ToShortDateString() : "-";
                lblPicklistNo.Text = !pl.IsColumnNull("PrintedID") ? pl.PrintedID.ToString() : "-";

            }
            //gridPickListView.EndSummaryUpdate();
        }
        private void gridRequisitionListView_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            if (e != null && e.PrevFocusedRowHandle < -1)
                return;

            try
            {
                DataRow dr = gridRequisitionListView.GetFocusedDataRow();
                if (dr == null)
                    return;
                int orderID = Convert.ToInt32(dr["ID"]);
                gridRequisitionDetails.DataSource = Order.GetRequisitionDetails(orderID);
                //lblOrderStatus.Text = Order.GetOrderStatus(orderID);

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

                Institution ins = new Institution();

                ins.LoadByPrimaryKey(order.RequestedBy);

                lblWoreda.Text = ins.WoredaName;
                lblZone.Text = ins.ZoneName;
                lblRegion.Text = ins.RegionName;
                lblRequestedDate.Text = order.EurDate.ToShortDateString();
                lblRequestedBy.Text = order.GetFilledBy();

                OrderStatus os = new OrderStatus();
                os.LoadByPrimaryKey(order.OrderStatusID);

                lblStatus.Text = os.OrderStatus;

                int length = order.GetRequestedBy().Length;

                string s = "";

                headerSection.Text = order.GetRequestedBy() + s.PadRight(200 - length) + "Order Number: " + order.RefNo;

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

                var paymentType = new BLL.PaymentType();
                paymentType.LoadByPrimaryKey(order.PaymentTypeID);
                lblPaymentType.Text = paymentType.Name;
                lblMode.Text = order.GetFromStore();
                DataRow facilityHis = BLL.Issue.GetVisitHistoryForFacility(Convert.ToInt32(dr["InstitutionID"]));

                if (facilityHis != null)
                {
                    lblLastVisit.Text = Convert.ToDateTime(facilityHis["LastVisit"]).TimeAgo() ?? "-";
                    lblNoOfReq.Text = Convert.ToString(facilityHis["VisitCount"]) ?? "-";
                    lblIssueType.Text = Convert.ToString(facilityHis["Description"]) ?? "-";
                }

                else
                {
                    lblLastVisit.Text = lblNoOfReq.Text = lblIssueType.Text = "-";

                }
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);

            }
        }
        private void SavePickListItems(object sender, EventArgs e)
        {
            var ord = new Order();
            var rus = new Institution();
            ord.LoadByPrimaryKey(_orderID);
            rus.LoadByPrimaryKey(ord.RequestedBy);

            if (_dvPickListMakeup == null || ValidatePickList())
            {
              return;
            }

            // First of all .. print the pick list
                var pls = new PickList();
                PrintPickList(ord, rus);

                MyGeneration.dOOdads.TransactionMgr mgr = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
                try
                {
                    mgr.BeginTransaction();
                        pls.SavePickList(_orderID, _dvPickListMakeup, CurrentContext.UserId);
                    mgr.CommitTransaction();

                    BindApprovedOrders();
                    this.LogActivity("Print-Pick-List", ord.ID);
                    XtraMessageBox.Show("Your pick list has been saved! please continue to the next step or prepare another Picklist here.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception exp)
                {
                    mgr.RollbackTransaction();
                        ViewHelper.ShowErrorMessage("System couldn't save the Pick List, Please contact administrator for additional help", exp);
                    ErrorHandler.Handle(exp);
                }
        }
        private void OnApprovedOrderRowClicked(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            var gv = (GridView)sender;
            var dr = gv.GetFocusedDataRow();
            var or = new BLL.Order();
            _orderID = Convert.ToInt32(gv.GetFocusedDataRow()["ID"].ToString());

            order.LoadByPrimaryKey(_orderID);
            // populate the general order variables
            txtPickListFromStore.Text = order.GetFromStore();
            lblMode.Text = order.GetFromStore();

            txtPickListRequestedBy.Text = order.GetFilledBy();

            if (!order.IsColumnNull("RequestedBy"))
            {
                var ins = new Institution();
                ins.LoadByPrimaryKey(order.RequestedBy);

                var ownership = new BLL.OwnershipType();
                ownership.LoadByPrimaryKey(ins.Ownership);

                lblOwnership.Text = ownership.Name;
                lblInstitutionType.Text = ins.InstitutionTypeName;
                lblFacility.Text = ins.Name;
                lblWoreda.Text = ins.WoredaName;
                lblZone.Text = ins.ZoneName;
                lblRegion.Text = ins.RegionName;
                lblLetterNum.Text = String.IsNullOrEmpty(order.LetterNo) ? "-" : order.LetterNo;

            }
            else
            {
                lblFacility.Text = lblWoreda.Text = lblZone.Text = lblRegion.Text = lblOwnership.Text = "";// lblType.Text = "";
            }

            int length = order.GetRequestedBy().Length;

            string s = "";

            HeaderLayoutGroup.Text = order.GetRequestedBy() + s.PadRight(150 - length) + "Order Number:" + order.RefNo;

            txtPickListOrderNumber.Text = order.RefNo;
            lblOrderNum.Text = order.RefNo;

            txtPickListApprovedBy.Text = order.GetApprovedBy();
            lblApprovedBy.Text = order.GetApprovedBy();

            var orderDetail = new OrderDetail();
            orderDetail.LoadAllByOrderID(order.ID);

            if (!orderDetail.IsColumnNull("StoreID"))
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(orderDetail.StoreID);
                lblMode.Text = activity.ModeName;
            }

            lblOrderDate.Text = order.Date.ToShortDateString();

            var us = new BLL.User();
            us.LoadByPrimaryKey(order.FilledBy);
            lblFilledBy.Text = us.FirstName;

            lblIssueStatus.Text = (string)dr["OrderStatus"] ?? "-";
            lblIssueType.Text = (string)dr["Description"] ?? "-";

            var paymentType = new BLL.PaymentType();
            paymentType.LoadByPrimaryKey(order.PaymentTypeID);
            lblPaymentType.Text = paymentType.Name;

            if (order.OrderStatusID == OrderStatus.Constant.ORDER_APPROVED)
            {
                progressBarControl.Properties.Maximum = order.CountOfDetailItems();
                progressBarControl.Properties.DisplayFormat.FormatString = "{0: #,##0}" + string.Format(" of {0}", progressBarControl.Properties.Maximum);
                progressBarControl.Properties.DisplayFormat.FormatType = FormatType.Custom;
                progressBarControl.EditValue = 0;
                this.Enabled = false;
                progressBarControl.Visible = true;
                bgWorker.RunWorkerAsync(_orderID);
            }
        }
        /// <summary>
        /// The code supports manufacturer preference here too but we choose not to prefer manufacturers when looking into the stores.
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="orderDetailID"></param>
        /// <param name="pricedUnpricedBoth"></param>
        /// <param name="bal"> </param>
        /// <param name="markStockoutBit"> </param>
        /// <param name="usableStock"> </param>
        /// <param name="approved"> </param>
        public decimal LoadOptionsForOrderDetail(int userID, int orderDetailID, PriceSettings pricedUnpricedBoth, Balance bal, bool markStockoutBit, out decimal usableStock, out decimal approved)
        {
            decimal avQuantity = 0;

            BLL.OrderDetail orderDetail = new OrderDetail();
            orderDetail.LoadByPrimaryKey(orderDetailID);
            BLL.Order order = new Order();
            order.LoadByPrimaryKey(orderDetail.OrderID);

            Institution ru = new Institution();
            ru.LoadByPrimaryKey(order.RequestedBy);

            int month = EthiopianDate.EthiopianDate.Now.Month;
            int year = EthiopianDate.EthiopianDate.Now.Year;

            decimal availableQty = 0;
            usableStock = 0;
            approved = 0;
            int? manufacturerPrefrence = null, unitID = null;
            if (!orderDetail.IsColumnNull("PreferredManufacturerID"))
            {
                manufacturerPrefrence = orderDetail.PreferredManufacturerID;
            }

            DateTime? expPreferrence = null;
            if(!orderDetail.IsColumnNull("PreferredExpiryDate"))
            {
                expPreferrence = orderDetail.PreferredExpiryDate;
            }

            int? preferredPhysicalStoreID = null;
            if (!orderDetail.IsColumnNull("PreferredPhysicalStoreID"))
            {
                preferredPhysicalStoreID = orderDetail.PreferredPhysicalStoreID;
            }

            //--------------------------------------------------------------------------
            //manufacturerPrefrence = null; //We are overriding the manufacturer preference.
            //expPreferrence = null;
            //--------------------------------------------------------------------------
            if (!orderDetail.IsColumnNull("UnitID"))
            {
                unitID = orderDetail.UnitID;
            }

            BLL.UserActivity userStore = new UserActivity();

            // Definitely a danger zone
            userStore.LoadByUserIDAndStoreType(userID, order.FromStore, orderDetail.ItemID, unitID.Value);

            while (!userStore.EOF)
            {
                var activity = new Activity();
                 activity.LoadByPrimaryKey(userStore.ActivityID);

                if(order.FromStore == Mode.Constants.RDF && !BLL.Settings.IsCenter && !BLL.Settings.PrivateCanGetFromMDGAndPBS && ru.Ownership == OwnershipType.Constants.Private && activity.IsSubsidized ){
                    userStore.MoveNext();
                    continue;
                }

               // Load the Activity Selection that has PRiced Commodities.
                Balance balance = new Balance();
                if (pricedUnpricedBoth == PriceSettings.PRICED_ONLY || pricedUnpricedBoth == PriceSettings.BOTH)
                {
                    BLL.Order.MakeStockCalculations(userID, month, year, PriceSettings.PRICED_ONLY, orderDetail,
                                                    userStore.ActivityID, orderDetail.ItemID, order, balance, unitID,
                                                    manufacturerPrefrence, expPreferrence, preferredPhysicalStoreID, out usableStock, out approved,
                                                    out availableQty, markStockoutBit);
                    avQuantity += availableQty;

                    if (availableQty > 0)
                    {

                        this.AddNew();
                        this.ID = userStore.ActivityID;
                        this.Name = string.Format("{0} ({1})", activity.FullActivityName, availableQty.ToString("#,##0"));
                        PrepareColumnsForApproval();
                        this.SetColumn("AvailableSKU", availableQty);
                        this.SetColumn("IsDeliveryNote", false);
                        this.SetColumn("TextID",string.Format("N{0}",this.ID));
                    }
                }

                // Load Activity Selections for Delivery Note Items.
                if (pricedUnpricedBoth == PriceSettings.DELIVERY_NOTE_ONLY || pricedUnpricedBoth == PriceSettings.BOTH)
                {
                    BLL.Order.MakeStockCalculations(userID, month, year, PriceSettings.DELIVERY_NOTE_ONLY, orderDetail,
                                                    userStore.ActivityID, orderDetail.ItemID, order, balance, unitID,
                                                    manufacturerPrefrence, expPreferrence, preferredPhysicalStoreID, out usableStock, out approved,
                                                    out availableQty, markStockoutBit);

                    avQuantity += availableQty;

                    if (availableQty > 0)
                    {
                        this.AddNew();
                        this.ID = userStore.ActivityID; //Just to give it a different ID so we know there is a change only.
                        this.Name = string.Format("+-- {0} - Delivery Notes - ({1})", userStore.GetColumn("ActivityName"),
                                                       availableQty.ToString("#,##0"));
                        PrepareColumnsForApproval();
                        this.SetColumn("AvailableSKU", availableQty);
                        this.SetColumn("IsDeliveryNote", true);
                        this.SetColumn("TextID", string.Format("D{0}", this.ID));

                    }

                }
                userStore.MoveNext();
            }
            return avQuantity;
        }
        private void gridItemsView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DataRow dr = gridItemsView.GetFocusedDataRow();

            lblIssueType.Text = dr["OrderType"]!=DBNull.Value ? (string) dr["OrderType"] : "-";

            if ((dr["ReceivingUnitID"]) != DBNull.Value)
            {
                var ins = new Institution();
                ins.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivingUnitID"]));

                lblRegion.Text = ins.RegionName ?? "-";
                lblWoreda.Text = ins.WoredaName ?? "-";
                lblZone.Text = ins.ZoneName ?? "-";

                var own = new OwnershipType();
                own.LoadByPrimaryKey(ins.Ownership);
                lblOwnership.Text = own.Name ?? "-";

                var iss = new Issue();
                iss.LoadByPrimaryKey(Convert.ToInt32(dr["STVID"]));

                if (!iss.IsColumnNull("PaymentTypeID"))
                {
                    var pType = new PaymentType();

                     pType.LoadByPrimaryKey(iss.PaymentTypeID);
                    lblPaymentType.Text = pType.Name;

                }
                lblPaymentType.Text = "-";

                if (!iss.IsColumnNull("VoidRequestDateTime"))
                    lblVoidRequestedDate.Text = iss.VoidRequestDateTime.ToShortDateString();
                else
                {
                    lblVoidRequestedDate.Text = "-";
                }
               if(!iss.IsColumnNull("VoidApprovalDateTime"))
                lblVoidConfirmedDate.Text= iss.VoidApprovalDateTime.ToShortDateString();
               else
               {
                   lblVoidConfirmedDate.Text = "-";

               }
               var user = new User();
                if (!iss.IsColumnNull("VoidRequestUserID"))
                {

                    user.LoadByPrimaryKey(iss.VoidRequestUserID);
                    lblVoidRequestedBy.Text = user.FullName;
                }
                else lblVoidRequestedBy.Text = "-";
                if (!iss.IsColumnNull("VoidApprovedByUserID"))
                {
                    user.LoadByPrimaryKey(iss.VoidApprovedByUserID);
                    lblVoidConfirmedBy.Text = user.FullName;
                }
                else lblVoidConfirmedBy.Text = "-";

                lblInstitutionType.Text = ins.InstitutionTypeName;

                if (!iss.IsColumnNull("DocumentTypeID"))
                {
                    lblDocumentType.Text = DocumentType.GetDocumentType(iss.DocumentTypeID).Name;
                }
                else
                    lblDocumentType.Text = "";

            }
            else
            {
                lblRegion.Text = lblWoreda.Text = lblZone.Text = "-";
            }

            lblPrintedDate.Text = string.IsNullOrEmpty((Convert.ToDateTime(dr["PrintedDate"].ToString())).ToShortDateString()) ? "-" : (Convert.ToDateTime(dr["PrintedDate"].ToString())).ToShortDateString();
            lblAccount.Text = string.IsNullOrEmpty(dr["AccountName"].ToString()) ? "-" : dr["AccountName"].ToString();
            lblSubAccount.Text = string.IsNullOrEmpty(dr["SubAccountName"].ToString()) ? "-" : dr["SubAccountName"].ToString();
            lblActivity.Text = string.IsNullOrEmpty(dr["ActivityName"].ToString()) ? "-" : dr["ActivityName"].ToString();
            lblPrintedBy.Text = string.IsNullOrEmpty(dr["IssuedBy"].ToString()) ? "-" : dr["IssuedBy"].ToString();

            lblIssueStatus.Text = string.IsNullOrEmpty(dr["Status"].ToString()) ? "-" : dr["Status"].ToString();
               int accountid =  Convert.ToInt32(dr["AccountID"]);
               Account account = new Account();
               account.LoadByPrimaryKey(accountid);
               Mode mode = new Mode();
               mode.LoadByPrimaryKey(account.ModeID);
               lblMode.Text = mode.TypeName;
        }
        private void ReceivingUnitsDetails_Load(object sender, EventArgs e)
        {
            LoadReceivingUnits();

            if (ID != -1)
            {

                lcExistingInstitutions.Visibility = LayoutVisibility.Never;
                lcIsUsedInFacility.Visibility = LayoutVisibility.Always;

                int selected = ID;
                Institution recUnit = new Institution();
                recUnit.LoadByPrimaryKey(selected);
                txtReceivingUnit.Text = recUnit.IsColumnNull("Name") ? "" : recUnit.Name;;
                txtReceivingUnit.Enabled = false;
                txtDescription.Text = recUnit.IsColumnNull("Description") ? "" : recUnit.Description;
                txtPhone.Text = recUnit.IsColumnNull("Phone") ? "" : recUnit.Phone;

                if (!recUnit.IsColumnNull("Ownership"))
                    lkOwnership.EditValue = recUnit.Ownership;
                if (!recUnit.IsColumnNull("RUType"))
                    lkRUType.EditValue = recUnit.RUType;
                txtLicenseNo.Text = recUnit.IsColumnNull("LicenseNo") ? "" : recUnit.LicenseNo;
                txtVATNo.Text = recUnit.IsColumnNull("VATNo") ? "" : recUnit.VATNo;
                txtTinNo.Text = recUnit.IsColumnNull("TinNo") ? "" : recUnit.TinNo;

                chkIsInstitutionUsedAtFacility.Checked = recUnit.IsColumnNull("IsUsedAtFacility") ? false : recUnit.IsUsedAtFacility;
                dtRegistration.Value = recUnit.IsColumnNull("DateOfRegistration") ? DateTimeHelper.ServerDateTime : recUnit.DateOfRegistration;
                if (!recUnit.IsColumnNull("Woreda"))
                {
                    BLL.Woreda woreda = new Woreda();
                    woreda.LoadByPrimaryKey(recUnit.Woreda);

                    BLL.Zone zone = new Zone();
                    zone.LoadByPrimaryKey(woreda.ZoneID);

                    BLL.Region region = new BLL.Region();
                    region.LoadByPrimaryKey(zone.RegionId);

                    lkRegion.EditValue = region.ID;

                    lkZone.Properties.DataSource = BLL.Zone.GetZoneByRegion(region.ID).DefaultView;
                    lkZone.EditValue = zone.ID;

                    Woreda.GetWoredaByZone(zone.ID);
                    lkWoreda.Properties.DataSource = woreda.DefaultView;
                    lkWoreda.EditValue = recUnit.Woreda;
                }
                else if (!recUnit.IsColumnNull("Zone")) //We allow the Woreda to be empty so, let's check the zone now.
                {
                    BLL.Zone zone = new Zone();
                    zone.LoadByPrimaryKey(recUnit.Zone);

                    BLL.Region region = new BLL.Region();
                    region.LoadByPrimaryKey(zone.RegionId);

                    lkRegion.EditValue = region.ID;

                    lkZone.Properties.DataSource = BLL.Zone.GetZoneByRegion(region.ID).DefaultView;
                    lkZone.EditValue = zone.ID;
                }
                else
                {
                    lkRegion.EditValue = null;
                    lkZone.EditValue = null;
                    lkWoreda.EditValue = null;
                }

                Route r = new Route();
                r.LoadAll();
                lkRoute.Properties.DataSource = r.DefaultView;

                lkRoute.EditValue = (recUnit.IsColumnNull("Route")) ? 0 : recUnit.Route;
                receivingUnitId = recUnit.ID;

                bool isItDraft = !recUnit.IsColumnNull("IsDraft") && recUnit.IsDraft &&
                                 (BLL.Order.GetTotalForAnInstitution(recUnit.ID) == 0);

                lkRegion.Enabled = isItDraft;
                lkZone.Enabled = isItDraft;
                lkWoreda.Enabled = isItDraft;
                lkRUType.Enabled = isItDraft;
                lkOwnership.Enabled = isItDraft;
                txtReceivingUnit.Enabled = isItDraft;

            }
            else
            {
                lcExistingInstitutions.Visibility=LayoutVisibility.Always;
                lcIsUsedInFacility.Visibility = LayoutVisibility.Never;
            }
        }
        private void FacilityChanged(GridLookUpEdit lkRecUnit)
        {
            if (lkRecUnit.EditValue != null)
            {
                int facilityID = Convert.ToInt32(lkRecUnit.EditValue);
                Institution institution = new Institution();
                institution.LoadByPrimaryKey(facilityID);
                string facilityPaymentType = "";
                if (!institution.IsColumnNull("PaymentTypeID"))
                    facilityPaymentType = PaymentType.GetPaymentTypeString(institution.PaymentTypeID);

                txtVatRegistration.Text = (!institution.IsColumnNull("VATNo")) ? institution.VATNo : "";

                labelControl2.Text = (!institution.IsColumnNull("VATNo")) ? institution.VATNo : "";
                txtTin.Text = (!institution.IsColumnNull("TinNo")) ? institution.TinNo : "";

                labelControl1.Text = (!institution.IsColumnNull("TinNo")) ? institution.TinNo : "";

                txtRegistrationNo.Text = (!institution.IsColumnNull("LicenseNo")) ? institution.LicenseNo : "";

                labelControl3.Text = (!institution.IsColumnNull("LicenseNo")) ? institution.LicenseNo : "";
            }
        }
        /// <summary>
        /// Called when [outstanding picklist selected].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="DevExpress.XtraGrid.Views.Grid.RowClickEventArgs" /> instance containing the event data.</param>
        private void OnOutstandingPicklistSelected(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            var dr = gridOutstandingPickListView.GetFocusedDataRow();
            _orderID = Convert.ToInt32(dr["ID"]);

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

            // load payment type options
            int? requestedBy = null;

            var usr = new User();

            lblIssueStatus.Text = (string)dr["OrderStatus"];
            lblIssueTypes.Text = (string) dr["Description"];

            if (!order.IsColumnNull("RequestedBy"))
            {
                var ins = new Institution();
                requestedBy = order.RequestedBy;
                lkPaymentType.Properties.DataSource = PaymentType.GetAllowedTypes(order.FromStore, requestedBy);
                ins.LoadByPrimaryKey(order.RequestedBy);

                try
                {
                    lblWoreda.Text = ins.WoredaName ?? "-";
                    lblRegion.Text = ins.RegionName ?? "-";
                    lblZone.Text = ins.ZoneName ?? "-";
                    lblInstitutionType.Text = ins.InstitutionTypeName ?? "-";

                    var ownership = new BLL.OwnershipType();
                    if (!ins.IsColumnNull("Ownership"))
                    {
                        ownership.LoadByPrimaryKey(ins.Ownership);
                        lblOwnership.Text = ownership.Name;
                    }

                }
                catch (NullReferenceException ex)
                {
                    //when transfer, institution has no woreda, zone or region, ignore the error
                }
            }
            else
                lblWoreda.Text = lblRegion.Text = lblZone.Text = lblInstitutionType.Text = lblOwnership.Text = "NA";

            //usr.LoadByPrimaryKey(NewMainWindow.UserId);
            usr = CurrentContext.LoggedInUser;
            txtIssuedBy.Text = usr.FullName ?? "-";

            PickList pl = new PickList();
            _dvOutstandingPickList = pl.GetPickListDetailsForOrder(_orderID, CurrentContext.LoggedInUserName);
            gridOutstandingPicklistDetail.DataSource = _dvOutstandingPickList;

            if (order.FromStore != Mode.Constants.HEALTH_PROGRAM)
            {
                colSKUPicked.Visible = false;
            }
            else
            {
                colSKUPicked.Visible = true;
            }

            txtConfirmFromStore.Text = order.GetFromStore();
            txtConfirmRequestedBy.Text = order.GetRequestedBy();

            int length = order.GetRequestedBy().Length;

            string s = "";

            HeaderSection.Text = order.GetRequestedBy() + s.PadRight(150-length)+"Order Number: " + order.RefNo;

            txtConfirmOrderNumber.Text = order.RefNo;
            //txtConfirmApprovedBy.Text = order.GetApprovedBy() ?? "-";
            lblApprovedBy.Text = order.GetApprovedBy() ?? "-";

            lkPaymentType.EditValue = order.PaymentTypeID;
            // Temporarily copy the STV
            txtIssueRefNo.Text = order.RefNo; //"";
            lblRefNo.Text = order.RefNo ?? "-";

            var paymentType = new BLL.PaymentType();
            paymentType.LoadByPrimaryKey(order.PaymentTypeID);
            lblPaymentType.Text = paymentType.Name ?? "-";

            lblMode.Text = order.GetFromStore() ?? "-";
            lblissuedDate.Text = order.Date.ToShortDateString();
            lblIssuedBy.Text = order.GetFilledBy();
            lblPicklistPrintedDate.Text = pl.PickedDate.ToShortDateString()!="" ? pl.PickedDate.ToShortDateString() : "-";

            var us = new User();
            pl.LoadByOrderID(_orderID);
            if (!pl.IsColumnNull("PickedBy"))
            {
                us.LoadByPrimaryKey(pl.PickedBy);
                lblPicklistConfirmedBy.Text = us.FullName;
            }
            else lblPicklistConfirmedBy.Text = "-";
        }
        public void getFacilityInfo()
        {
            string region, woreda, zone;
            if (!IsColumnNull("RequestedBy"))
            {
                var rus = new Institution();
                rus.LoadByPrimaryKey(RequestedBy);
                 region = rus.RegionName;
                woreda = rus.WoredaName;
                zone = rus.ZoneName;

            }
        }
        private void SavePickListItems(object sender, EventArgs e)
        {
            BLL.Order ord = new BLL.Order();
            BLL.Institution rus = new Institution();
            ord.LoadByPrimaryKey(_orderID);

            // if the pick list has already been printed ... go ahead and pass it to the next level
            if (ord.OrderStatusID == OrderStatus.Constant.PICK_LIST_GENERATED)
            {
                ord.OrderStatusID = OrderStatus.Constant.PICK_LIST_CONFIRMED;
                ord.Save();
                BindApprovedOrders();
                gridPickListDetail.DataSource = null;
                XtraMessageBox.Show("The Pick List has been Confirmed", "Confirmation", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                return;
            }

            if (_dvPickListMakeup != null)
            {

                MyGeneration.dOOdads.TransactionMgr mgr = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
                try
                {
                    mgr.BeginTransaction();
                    // First of all .. print the pick list

                    rus.LoadByPrimaryKey(ord.RequestedBy);

                    var pl = HCMIS.Desktop.Reports.WorkflowReportFactory.CreatePicklistReport(ord, rus,
                                                                                              _dvPickListMakeup);
                    pl.PrintDialog();
                    var pls = new PickList();

                    pls.SavePickList(_orderID, _dvPickListMakeup, CurrentContext.UserId);

                    // Refresh the current window
                    BindApprovedOrders();
                    // clear the working grid
                    gridPickListDetail.DataSource = null;
                    mgr.CommitTransaction();
                    XtraMessageBox.Show("Your pick list has been saved! please continue to the next step or prepare another Picklist here.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception exp)
                {
                    mgr.RollbackTransaction();
                    BLL.User user = new User();
                    //user.LoadByPrimaryKey(NewMainWindow.UserId);
                    user = CurrentContext.LoggedInUser;
                    if (user.UserType == UserType.Constants.ADMIN || user.UserType == UserType.Constants.SUPER_ADMINISTRATOR)
                    {
                        XtraMessageBox.Show(exp.Message);
                    }
                    else
                    {
                        XtraMessageBox.Show("System couldn't save the Pick List, Please contact administrator for additional help", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    ErrorHandler.Handle(exp);
                }
            }
        }
        private void btnIssueSave_Click(object sender, EventArgs e)
        {
            // do the validation here
            if (issueLocationValidation.Validate())
            {
                Institution recUnit = new Institution();

                if (ID != -1) //This is not new.
                {
                    recUnit.LoadByPrimaryKey(receivingUnitId);
                    recUnit.IsUsedAtFacility = chkIsInstitutionUsedAtFacility.Checked;
                }
                else
                {
                    recUnit.AddNew();
                    recUnit.IsDraft = true; //If it is locally added, we mark it as draft until confirmed centrally.
                    recUnit.Active = true;
                    recUnit.IsUsedAtFacility = true;
                    recUnit.IsLocalSite = true;
                    recUnit.OperationalStatus = true;
                    recUnit.Rowguid = Guid.NewGuid();
                    recUnit.NUrowguid = Guid.NewGuid();
                    recUnit.ModifiedBy = CurrentContext.LoggedInUser.ID.ToString();
                    recUnit.ModifiedDate = DateTimeHelper.ServerDateTime;
                    recUnit.SN = 1; //Saving default value here.  The actual value to come from the directory services.
                }

                recUnit.Name = txtReceivingUnit.Text;
                recUnit.Phone = txtPhone.Text;
                recUnit.Description = txtDescription.Text;
                recUnit.Route = Convert.ToInt32(lkRoute.EditValue);
                recUnit.Ownership = Convert.ToInt32(lkOwnership.EditValue);
                recUnit.RUType = Convert.ToInt32(lkRUType.EditValue);

                if (lkWoreda.EditValue != null) recUnit.Woreda = int.Parse(lkWoreda.EditValue.ToString());
                if (lkZone.EditValue != null) recUnit.Zone = int.Parse(lkZone.EditValue.ToString());

                if (BLL.OwnershipType.IsPrivate(recUnit.Ownership))
                {
                    if (string.IsNullOrEmpty(txtLicenseNo.Text))
                    {
                        XtraMessageBox.Show("Please fill in the license number!", "Missing Information", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    recUnit.LicenseNo = txtLicenseNo.Text;
                    recUnit.VATNo = txtVATNo.Text;
                    recUnit.TinNo = txtTinNo.Text;
                    recUnit.DateOfRegistration = dtRegistration.Value;
                }
                if (ID == -1)
                {
                    if (XtraMessageBox.Show(string.Format("Are you sure you want to add a new Receiving Unit", recUnit.Name.ToString()), "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        recUnit.Save();
                        this.Close();
                    }
                }
                else if (XtraMessageBox.Show(string.Format("Are you sure you want to save change to {0}", recUnit.Name.ToString()), "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                        recUnit.Save();
                        this.Close();
                }
            }
        }
        /// <summary>
        /// Re print STV.
        /// </summary>
        /// <param name="dv">The dv.</param>
        /// <param name="orderId">The order id.</param>
        /// <param name="pl">The pl.</param>
        /// <param name="stvLogID">The STV log ID.</param>
        /// <param name="isConversion">if set to <c>true</c> [is conversion].</param>
        /// <param name="generateNewPrintID">if set to <c>true</c> [generate new print ID].</param>
        //public XtraReport RePrintSTV(DataView dv,int orderId, PickList pl,int? stvLogID, bool isConversion, bool generateNewPrintID = true)
        //{
        //     var includeInsurance =XtraMessageBox.Show("Include insurance?", "Insurance",MessageBoxButtons.YesNo,MessageBoxIcon.Question)== DialogResult.Yes;
        //     var ord = new Order();
        //    ord.LoadByPrimaryKey(orderId);
        //    var order = new Order();
        //    order.LoadByPrimaryKey(orderId);
        //    if (!order.IsPaymentTypeValid())
        //    {
        //        //TODO: This needs to be handled well.
        //        throw new Exception(
        //            string.Format("PaymentTypeID has a problem.  The order has a payment type id of {0}",
        //                          ord.PaymentTypeID));
        //    }
        //    var stores = new Activity();
        //    stores.LoadByPrimaryKey(order.FromStore);
        //    var textDeliveryNote = "";
        //    var sendToString = GetReceivingUnitName(order);
        //    if (stvLogID != null)
        //    {
        //        var stvLog = new Issue();
        //        stvLog.LoadByPrimaryKey(stvLogID.Value);
        //        if (!stvLog.IsColumnNull("IsDeliveryNote") && stvLog.IsDeliveryNote && isConversion)
        //        {
        //            textDeliveryNote = stvLog.IDPrinted.ToString("00000");
        //        }
        //    }
        //    if (PaymentType.Constants.CASH == ord.PaymentTypeID)
        //    {
        //        var rus = new Institution();
        //        rus.LoadByPrimaryKey(order.RequestedBy);
        //        var stvReport = new HCMIS.Desktop.Reports.CashInvoice(CurrentContext.LoggedInUserName);
        //        pl.LoadByOrderID(orderId);
        //        PrepareTheReport(stvReport);
        //        stvReport.DeliveryNoteNo.Text = textDeliveryNote;
        //        stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
        //        stvReport.From.Text = GeneralInfo.Current.HospitalName;
        //        stvReport.To.Text = sendToString;
        //        stvReport.TIN.Text = rus.TinNo;
        //        stvReport.VAT.Text = rus.VATNo;
        //        stvReport.Town.Text = rus.Town;
        //        stvReport.Woreda.Text = rus.WoredaText;
        //        stvReport.Zone.Text = rus.ZoneText;
        //        stvReport.Region.Text = rus.Region;
        //        stvReport.License.Text = (!rus.IsColumnNull("Ownership") && rus.IsPrivatelyOwned) ? rus.LicenseNo : (!ord.IsColumnNull("LetterNo")) ? ord.LetterNo : "";
        //        //stvReport.Program.Text = stores.StoreName;
        //        DateTimePickerEx dtDate = new DateTimePickerEx();
        //        dtDate.Value = DateTimeHelper.ServerDateTime;
        //        stvReport.Date.Text = dtDate.Text;
        //        return stvReport;
        //    }
        //    else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID)
        //    {
        //        var rus = new Institution();
        //        rus.LoadByPrimaryKey(order.RequestedBy);
        //        HCMIS.Desktop.Reports.CreditInvoice stvReport =
        //            new HCMIS.Desktop.Reports.CreditInvoice(CurrentContext.LoggedInUserName);
        //        pl.LoadByOrderID(orderId);
        //        PrepareTheReport(stvReport);
        //        stvReport.DeliveryNoteNo.Text = textDeliveryNote;
        //        stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID,
        //            CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
        //        stvReport.From.Text = GeneralInfo.Current.HospitalName;
        //        stvReport.To.Text = sendToString;
        //        //stvReport.Region.Text = rus.Woreda;
        //        stvReport.Zone.Text = rus.Town;
        //        stvReport.Letter.Text = ord.LetterNo;
        //        //stvReport.Program.Text = stores.StoreName;
        //        DateTimePickerEx dtDate = new DateTimePickerEx();
        //        dtDate.Value = DateTimeHelper.ServerDateTime;
        //        stvReport.Date.Text = dtDate.Text;
        //    }
        //}
        /// <summary>
        /// Re print STV.
        /// </summary>
        /// <param name="dv">The dv.</param>
        /// <param name="orderId">The order id.</param>
        /// <param name="pl">The pl.</param>
        /// <param name="stvLogID">The STV log ID.</param>
        /// <param name="isConversion">if set to <c>true</c> [is conversion].</param>
        /// <param name="generateNewPrintID">if set to <c>true</c> [generate new print ID].</param>
        public XtraReport RePrintSTV(DataView dv, int orderId, PickList pl, int? stvLogID, bool isConversion, bool generateNewPrintID = true)
        {
            HCMIS.Core.Distribution.Services.PrintLogService pLogService = new HCMIS.Core.Distribution.Services.PrintLogService();

            pLogService.StartPrintingSession();

            includeInsurance = XtraMessageBox.Show("Include insurance?", "Insurance", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;
            var ord = new Order();
            ord.LoadByPrimaryKey(orderId);
            //loading two times
            var order = new Order();
            order.LoadByPrimaryKey(orderId);

            if (!order.IsPaymentTypeValid())
            {

                //TODO: This needs to be handled well.
                throw new Exception(
                    string.Format("PaymentTypeID has a problem.  The order has a payment type id of {0}", ord.PaymentTypeID));
            }

            var rus = new Institution();
            if (ord.PaymentTypeID == PaymentType.Constants.CASH || ord.PaymentTypeID == PaymentType.Constants.CREDIT)
            {
                rus.LoadByPrimaryKey(order.RequestedBy);
            }

            var stores = new Activity();

            stores.LoadByPrimaryKey(order.FromStore);
            var textDeliveryNote = "";
            var sendToString = GetReceivingUnitName(order);
            if (stvLogID != null)
            {
                var stvLog = new Issue();
                stvLog.LoadByPrimaryKey(stvLogID.Value);
                if (!stvLog.IsColumnNull("IsDeliveryNote") && stvLog.IsDeliveryNote && isConversion)
                {
                    textDeliveryNote = stvLog.IDPrinted.ToString("00000");
                }
            }
            var xtraReport = new XtraReport();
            string stvPrinterName = "";
            if (PaymentType.Constants.CASH == ord.PaymentTypeID && !chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCashRePrintInvoice(ord, dv.Table, rus, pl, false, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return xtraReport;
            }

            else if (PaymentType.Constants.CASH == ord.PaymentTypeID && chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCashRePrintInvoice(ord, pl.DefaultView.ToTable(), rus, pl, true, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return xtraReport;
            }

            else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID && !chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCreditRePrintInvoice(ord, pl.DefaultView.ToTable(), rus, pl, false, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return xtraReport;
            }

            else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID && chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCreditRePrintInvoice(ord, pl.DefaultView.ToTable(), rus, pl, true, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return xtraReport;
            }
            //if (PaymentType.Constants.CASH == ord.PaymentTypeID)
            //{
            //    var stvReport = new HCMIS.Desktop.Reports.CashInvoice(CurrentContext.LoggedInUserName);
            //    pl.LoadByOrderID(orderId);
            //    PrepareTheReport(stvReport);
            //    stvReport.DeliveryNoteNo.Text = textDeliveryNote;
            //    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
            //    stvReport.From.Text = GeneralInfo.Current.HospitalName;
            //    stvReport.To.Text = sendToString;
            //    stvReport.TIN.Text = rus.TinNo;
            //    stvReport.VAT.Text = rus.VATNo;
            //    stvReport.Town.Text = rus.Town;
            //    stvReport.Woreda.Text = rus.WoredaText;
            //    stvReport.Zone.Text = rus.ZoneText;
            //    stvReport.Region.Text = rus.Region;

            //    stvReport.License.Text = (!rus.IsColumnNull("Ownership") && rus.IsPrivatelyOwned) ? rus.LicenseNo : (!ord.IsColumnNull("LetterNo")) ? ord.LetterNo : "";
            //    //stvReport.Program.Text = stores.StoreName;
            //    DateTimePickerEx dtDate = new DateTimePickerEx();
            //    dtDate.Value = DateTimeHelper.ServerDateTime;
            //    stvReport.Date.Text = dtDate.Text;

            //    return stvReport;
            //}
            //else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID)
            //{
            //    HCMIS.Desktop.Reports.CreditInvoice stvReport = new HCMIS.Desktop.Reports.CreditInvoice(CurrentContext.LoggedInUserName);
            //    pl.LoadByOrderID(orderId);
            //    PrepareTheReport(stvReport);
            //    stvReport.DeliveryNoteNo.Text = textDeliveryNote;
            //    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
            //    stvReport.From.Text = GeneralInfo.Current.HospitalName;
            //    stvReport.To.Text = sendToString;

            //    //stvReport.Region.Text = rus.Woreda;
            //    stvReport.Zone.Text = rus.Town;
            //    stvReport.Letter.Text = ord.LetterNo;
            //    //stvReport.Program.Text = stores.StoreName;
            //    DateTimePickerEx dtDate = new DateTimePickerEx();
            //    dtDate.Value = DateTimeHelper.ServerDateTime;
            //    stvReport.Date.Text = dtDate.Text;

            //    return stvReport;
            //}
            else if (PaymentType.Constants.STV == ord.PaymentTypeID && generateNewPrintID)
            {
                pl.LoadByOrderID(orderId);

                // check if this is a delivery note
                Issue sl = new Issue();
                sl.LoadByPrimaryKey(stvLogID.Value);
                if (!sl.IsColumnNull("IsDeliveryNote") && sl.IsDeliveryNote && !isConversion)
                {
                    var stvReport = new HCMIS.Desktop.Reports.DeliveryNoteForIssue(ord.ID, includeInsurance, CurrentContext.LoggedInUserName);

                    PrepareTheReport(stvReport);
                    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
                    stvReport.From.Text = GeneralInfo.Current.HospitalName;
                    stvReport.To.Text = sendToString;
                    stvReport.STVNO.Text = Issue.GetLogFor(ord.RefNo);
                    //stvReport.Date.Text = @"(Reprint) " + Convert.ToDateTime(dv[0]["IssueDate"]).ToString("MM/dd/yyyy");
                    DateTimePickerEx dtDate = new DateTimePickerEx();
                    dtDate.Value = DateTimeHelper.ServerDateTime;
                    stvReport.Date.Text = dtDate.Text;
                    //stvReport.ShowPreview();

                    return stvReport;
                }
                else
                {
                    var stvReport = new HCMIS.Desktop.Reports.STVonHeadedPaper(ord.ID, includeInsurance, CurrentContext.LoggedInUserName);
                    stvReport.DeliveryNoteNo.Text = textDeliveryNote;

                    PrepareTheReport(stvReport);
                    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
                    stvReport.From.Text = GeneralInfo.Current.HospitalName;
                    stvReport.To.Text = sendToString;
                    stvReport.STVNO.Text = Issue.GetLogFor(ord.RefNo);
                    //stvReport.Date.Text = @"(Reprint) " + Convert.ToDateTime(dv[0]["IssueDate"]).ToString("MM/dd/yyyy");
                    DateTimePickerEx dtDate = new DateTimePickerEx();
                    dtDate.Value = DateTimeHelper.ServerDateTime;
                    stvReport.Date.Text = dtDate.Text;
                    //stvReport.ShowPreview();

                    return stvReport;
                }
            }
            else if (PaymentType.Constants.STV == ord.PaymentTypeID && !generateNewPrintID)
            {
                pl.LoadByOrderID(orderId);
                //System.Windows.Forms.DialogResult result = XtraMessageBox.Show("Include insurance?", "Insurance",
                //MessageBoxButtons.YesNo,
                //MessageBoxIcon.Question);
                Issue log = new Issue();
                log.LoadByPrimaryKey((_reprintId != null) ? _reprintId.Value : stvLogID.Value);

                if (log.IsColumnNull("HasInsurance") || BLL.Settings.IsCenter) //If it is null, we have no idea about what the insurance status was.  So let's ask the user.
                {
                    System.Windows.Forms.DialogResult result = XtraMessageBox.Show("Include insurance?", "Insurance",
                                                                                   MessageBoxButtons.YesNo,
                                                                                   MessageBoxIcon.Question);
                    includeInsurance = result == DialogResult.Yes ? true : false;
                    log.HasInsurance = includeInsurance;
                    log.Save();
                }
                else
                {
                    includeInsurance = log.HasInsurance;
                }

                //bool includeInsurance = (!log.IsColumnNull("HasInsurance"))? log.HasInsurance : false;
                var stvReport = new HCMIS.Desktop.Reports.STVonA4(ord.ID, includeInsurance,
                                                                  CurrentContext.LoggedInUserName);
                stvReport.DeliveryNoteNo.Text = textDeliveryNote;

                PrepareTheReport(stvReport);
                stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, (_reprintId != null) ? _reprintId : stvLogID, isConversion, generateNewPrintID, includeInsurance);
                stvReport.From.Text = GeneralInfo.Current.HospitalName;
                stvReport.To.Text = sendToString;
                //stvReport.STVNO.Text =  //STVLog.GetLogFor(ord.RefNo);
                //stvReport.Date.Text = @"(Reprint) " + Convert.ToDateTime(dv[0]["IssueDate"]).ToString("MM/dd/yyyy");
                DateTimePickerEx dtDate = new DateTimePickerEx();
                dtDate.Value = DateTimeHelper.ServerDateTime;
                stvReport.Date.Text = dtDate.Text;
                return stvReport;
            }
            return null;
        }
        /// <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 void PrintPicklistItems(object sender, EventArgs e)
        {
            var ord = new BLL.Order();
            ord.LoadByPrimaryKey(_orderID);

            var rus = new Institution();
            rus.LoadByPrimaryKey(ord.RequestedBy);

            var pl = Desktop.Reports.WorkflowReportFactory.CreatePicklistReport(ord, rus, _dvPickListMakeup);
            pl.ShowPreviewDialog();
        }