Пример #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["DB"] == null && Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
        {
            Session["DB"] = ConfigurationManager.AppSettings["Database"];
            Session["SystemVariables"] = SystemVariableDB.GetAll();
            Response.Redirect(Request.RawUrl, false);
            return;
        }

        // PC & Not FF => Message Suggesting To Use FF
        //recommendMozilla.Visible = !Utilities.IsMobileDevice(Request, false, false) && !Request.Browser.Type.ToLower().Contains("firefox");

        bool showPageHeader = Request.QueryString["show_header"] == null || Request.QueryString["show_header"] == "1";

        if (!showPageHeader)
        {
            Utilities.UpdatePageHeaderV2(Page.Master, true);
        }

        if (!Utilities.IsDev() && !IsPostBack)
        {
            this.DevPanel.Visible = false;
        }

        Page.Form.DefaultFocus = UserName.ClientID;
        System.Web.UI.HtmlControls.HtmlGenericControl currdiv = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("banner");
        currdiv.Style.Add("display", "none");
        System.Web.UI.HtmlControls.HtmlGenericControl nav = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("nav");
        nav.Style.Add("display", "none");
        System.Web.UI.HtmlControls.HtmlGenericControl footer = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("footer");
        footer.Style.Add("display", "none");
    }
Пример #2
0
    public static EPCInfo GetEPCInfo(int patient_id)
    {
        int MedicareMaxNbrServicesPerYear        = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);
        int NbrMedicareServicesUsedSoFarThisYear = (int)InvoiceDB.GetMedicareCountByPatientAndYear(patient_id, DateTime.Now.Year);

        return(new EPCInfo(MedicareMaxNbrServicesPerYear, NbrMedicareServicesUsedSoFarThisYear));
    }
Пример #3
0
    protected void btnUpdateNotificationInfo_Click(object sender, EventArgs e)
    {
        string amountREGEX = @"^\d+(\.\d{1,2})?$";

        txtSMSCreditNotificationEmailAddress.Text = txtSMSCreditNotificationEmailAddress.Text.Trim();

        if ((chkSMSCreditOutOfBalance_SendEmail.Checked || chkSMSCreditLowBalance_SendEmail.Checked) && !Utilities.IsValidEmailAddress(txtSMSCreditNotificationEmailAddress.Text))
        {
            SetErrorMessage("Invalid email address");
            return;
        }

        txtSMSCreditLowBalance_Threshold.Text = txtSMSCreditLowBalance_Threshold.Text.Trim();
        if (txtSMSCreditLowBalance_Threshold.Text.Length == 0)
        {
            txtSMSCreditLowBalance_Threshold.Text = "0";
        }
        if (!Regex.IsMatch(txtSMSCreditLowBalance_Threshold.Text, amountREGEX))
        {
            SetErrorMessage("Low Balance Warning Threshold can only be numbers and optional decimal place with 1 or 2 digits following.");
            return;
        }

        SystemVariableDB.Update("SMSCreditNotificationEmailAddress", txtSMSCreditNotificationEmailAddress.Text);
        SystemVariableDB.Update("SMSCreditLowBalance_Threshold", Convert.ToDouble(txtSMSCreditLowBalance_Threshold.Text).ToString("0.00"));
        SystemVariableDB.Update("SMSCreditOutOfBalance_SendEmail", chkSMSCreditOutOfBalance_SendEmail.Checked ? "1" : "0");
        SystemVariableDB.Update("SMSCreditLowBalance_SendEmail", chkSMSCreditLowBalance_SendEmail.Checked ? "1" : "0");
    }
Пример #4
0
    protected DateTime GetLastDateBatchSendTreatmentNotesAllReferrers()
    {
        SystemVariables systemVariables = SystemVariableDB.GetAll();
        string          strLastDate     = systemVariables["LastDateBatchSendTreatmentNotesAllReferrers"].Value;

        if (strLastDate.Length == 0)
        {
            return(DateTime.MinValue);
        }

        // "12:46:48 05-12-2012"
        string[] parts     = strLastDate.Split(' ');
        string[] timeParts = parts[0].Split(':');
        string[] dateParts = parts[1].Split('-');

        DateTime dateTime = new DateTime(
            Convert.ToInt32(dateParts[2]),
            Convert.ToInt32(dateParts[1]),
            Convert.ToInt32(dateParts[0]),
            Convert.ToInt32(timeParts[0]),
            Convert.ToInt32(timeParts[1]),
            Convert.ToInt32(timeParts[2])
            );

        return(dateTime);
    }
Пример #5
0
    public static void UnsubscribeAll(int patientID, string DB)
    {
        SystemVariables sysVariables = SystemVariableDB.GetAll(DB);

        if (sysVariables["AddressType"].Value == "Contact")
        {
            Contact[] emails = ContactDB.GetByEntityID(-1, patientID, 27, false, DB);
            foreach (Contact email in emails)
            {
                ContactDB.UpdateIsBillingIsNonbilling(email.ContactID, email.IsBilling, false, DB);
            }
        }
        else if (sysVariables["AddressType"].Value == "ContactAus")
        {
            ContactAus[] emails = ContactAusDB.GetByEntityID(-1, patientID, 27, false, DB);
            foreach (ContactAus email in emails)
            {
                ContactAusDB.UpdateIsBillingIsNonbilling(email.ContactID, email.IsBilling, false, DB);
            }
        }
        else
        {
            throw new Exception("Unknown AddressType in config: " + sysVariables["AddressType"].Value);
        }
    }
Пример #6
0
    protected void SetNotificationInfo()
    {
        chkEnableEmails.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendEmail").Value) == 1;
        txtEmailAddress.Text    = SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_EmailAddress").Value;

        chkIncClinicsAuto.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncClinic").Value) == 1;
        chkIncAgedCareAuto.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncAgedCare").Value) == 1;

        chkIncUnsentAuto.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncUnsent").Value) == 1;
        chkIncBatchedAuto.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncBatched").Value) == 1;

        rdioSendTypeAuto.SelectedValue = SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendMethod").Value;

        chkSendMondays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendMondays").Value) == 1;
        chkSendTuesdays.Checked   = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendTuesdays").Value) == 1;
        chkSendWednesdays.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendWednesdays").Value) == 1;
        chkSendThursdays.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendThursdays").Value) == 1;
        chkSendFridays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendFridays").Value) == 1;
        chkSendSaturdays.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendSaturdays").Value) == 1;
        chkSendSundays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendSundays").Value) == 1;


        btnUpdateNotificationInfo.CssClass = "hiddencol";
        btnRevertNotificationInfo.CssClass = "hiddencol";
    }
Пример #7
0
    protected void SetNotificationInfo()
    {
        chkEnableEmails.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendEmail").Value) == 1;
        txtEmailAddress.Text    = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_EmailAddress").Value;

        chkIncPatientsWithMobile.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_IncPatientsWithMobile").Value) == 1;
        chkIncPatientsWithEmail.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_IncPatientsWithEmail").Value) == 1;

        chkSendMondays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendMondays").Value) == 1;
        chkSendTuesdays.Checked   = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendTuesdays").Value) == 1;
        chkSendWednesdays.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendWednesdays").Value) == 1;
        chkSendThursdays.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendThursdays").Value) == 1;
        chkSendFridays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFridays").Value) == 1;
        chkSendSaturdays.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendSaturdays").Value) == 1;
        chkSendSundays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendSundays").Value) == 1;

        ddlFromDaysAheadMondays.SelectedValue     = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Mondays").Value;
        ddlUntilDaysAheadMondays.SelectedValue    = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Mondays").Value;
        ddlFromDaysAheadTuesdays.SelectedValue    = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Tuesdays").Value;
        ddlUntilDaysAheadTuesdays.SelectedValue   = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Tuesdays").Value;
        ddlFromDaysAheadWednesdays.SelectedValue  = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Wednesdays").Value;
        ddlUntilDaysAheadWednesdays.SelectedValue = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Wednesdays").Value;
        ddlFromDaysAheadThursdays.SelectedValue   = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Thursdays").Value;
        ddlUntilDaysAheadThursdays.SelectedValue  = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Thursdays").Value;
        ddlFromDaysAheadFridays.SelectedValue     = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Fridays").Value;
        ddlUntilDaysAheadFridays.SelectedValue    = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Fridays").Value;
        ddlFromDaysAheadSaturdays.SelectedValue   = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Saturdays").Value;
        ddlUntilDaysAheadSaturdays.SelectedValue  = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Saturdays").Value;
        ddlFromDaysAheadSundays.SelectedValue     = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Sundays").Value;
        ddlUntilDaysAheadSundays.SelectedValue    = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Sundays").Value;

        btnUpdateNotificationInfo.CssClass = "hiddencol";
        btnRevertNotificationInfo.CssClass = "hiddencol";
    }
Пример #8
0
    protected void btnTesty_Click(object sender, EventArgs e)
    {
        decimal cost = Convert.ToDecimal(SystemVariableDB.GetByDescr("SMSPrice").Value);

        SMSHistoryDataDB.Insert(1, -1, 62000, "61-nbr...", "msg", cost, txtMsgId.Text);
        UpdateDB();
    }
Пример #9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["DB"] == null && Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
        {
            Session["DB"] = ConfigurationManager.AppSettings["Database"];
            Session["SystemVariables"] = SystemVariableDB.GetAll();
            Response.Redirect(Request.RawUrl, false);
            return;
        }

        // PC & Not FF => Message Suggesting To Use FF
        recommendMozilla.Visible = !Utilities.IsMobileDevice(Request, false, false) && !Request.Browser.Type.ToLower().Contains("firefox");

        bool showPageHeader = Request.QueryString["show_header"] == null || Request.QueryString["show_header"] == "1";

        if (!showPageHeader)
        {
            Utilities.UpdatePageHeaderV2(Page.Master, true);
            beforeDevPanelSpace.Visible = false;
            beforeButtonSpace.Visible   = false;
            afterButtonSpace.Visible    = false;
            recommendMozilla.Visible    = false;
        }

        if (!Utilities.IsDev() && !IsPostBack)
        {
            this.DevPanel.Visible = false;
        }

        Page.Form.DefaultFocus = UserName.ClientID;
    }
    protected void SetLastDateBatchSendTreatmentNotesAllReferrers(DateTime dateTime)
    {
        string val = dateTime == DateTime.MinValue ? "" : dateTime.ToString("HH:mm:ss dd-MM-yyyy");

        SystemVariableDB.Update("LastDateBatchSendTreatmentNotesAllReferrers", val);
        GUI_SetBatchSendElements();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                Utilities.SetNoCache(Response);
            }
            HideErrorMessage();
            Utilities.UpdatePageHeaderV2(Page.Master, true);

            if (!IsPostBack)
            {
                Session.Remove("suburb_sortExpression");
                Session.Remove("suburb_data");


                ddlState.Items.Add(new ListItem("All", "All"));
                DataTable states = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Suburb", "", "state", "distinct state");
                foreach (DataRow row in states.Rows)
                {
                    ddlState.Items.Add(new ListItem(row["state"].ToString(), row["state"].ToString()));
                }

                SystemVariable sysVariable = SystemVariableDB.GetByDescr("DefaultState");
                if (sysVariable != null && sysVariable.Value.Trim() != "")
                {
                    ddlState.SelectedValue = sysVariable.Value.Trim();
                }

                FillSuburbGrid();
            }

            this.GrdSuburb.EnableViewState = true;
        }
        catch (CustomMessageException ex)
        {
            if (IsPostBack)
            {
                SetErrorMessage(ex.Message);
            }
            else
            {
                HideTableAndSetErrorMessage(ex.Message);
            }
        }
        catch (Exception ex)
        {
            if (IsPostBack)
            {
                SetErrorMessage("", ex.ToString());
            }
            else
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
    }
Пример #12
0
    protected void lnkBackToCallCenter_Click(object sender, EventArgs e)
    {
        if (Session == null || Session["PreviousDB"] == null)
        {
            Utilities.LogoutV2(Session, Response, Request);
            return;
        }

        Session["DB"] = (string)Session["PreviousDB"];
        Session["SystemVariables"] = SystemVariableDB.GetAll();

        // Set system staff variables of external staff member 'Call Center'
        Staff staff = StaffDB.GetByID(Convert.ToInt32(Session["PreviousStaffID"]));

        Session["IsLoggedIn"]    = true;
        Session["IsStakeholder"] = staff.IsStakeholder;
        Session["IsMasterAdmin"] = staff.IsMasterAdmin;
        Session["IsAdmin"]       = staff.IsAdmin;
        Session["IsPrincipal"]   = staff.IsPrincipal;
        Session["IsProvider"]    = staff.IsProvider;
        Session["IsExternal"]    = staff.IsExternal;
        Session["StaffID"]       = staff.StaffID;
        Session["StaffFullnameWithoutMiddlename"] = staff.Person.FullnameWithoutMiddlename;
        Session["StaffFirstname"] = staff.Person.Firstname;

        Site site = SiteDB.GetByID(Convert.ToInt32(Session["PreviousSiteID"]));

        Session["SiteID"]         = site.SiteID;
        Session["SiteName"]       = site.Name;
        Session["SiteIsClinic"]   = site.SiteType.ID == 1;
        Session["SiteIsAgedCare"] = site.SiteType.ID == 2;
        Session["SiteIsGP"]       = site.SiteType.ID == 3;
        Session["SiteTypeID"]     = site.SiteType.ID;
        Session["SiteTypeDescr"]  = site.SiteType.Descr;

        Session["IsMultipleSites"] = SiteDB.GetAll().Length > 1;



        Session.Remove("PreviousDB");
        Session.Remove("PreviousStaffID");
        Session.Remove("PreviousSiteID");


        // Set OrgID in session as external user has OrgID set
        Session.Remove("OrgID");
        Session.Remove("OrgName");

        // Remove patient list session data for pt searches
        Session.Remove("patientinfo_data");
        Session.Remove("patientlist_data");
        Session.Remove("patientlist_sortexpression");
        Session.Remove("patientinfo_sortexpression");

        // Go to call center page
        Response.Redirect("~/CallCenterV2.aspx", false);
        return;
    }
Пример #13
0
 protected void SetNotificationInfo()
 {
     txtSMSCreditNotificationEmailAddress.Text     = SystemVariableDB.GetByDescr("SMSCreditNotificationEmailAddress").Value;
     txtSMSCreditLowBalance_Threshold.Text         = SystemVariableDB.GetByDescr("SMSCreditLowBalance_Threshold").Value;
     chkSMSCreditOutOfBalance_SendEmail.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("SMSCreditOutOfBalance_SendEmail").Value) == 1;
     chkSMSCreditLowBalance_SendEmail.Checked      = Convert.ToInt32(SystemVariableDB.GetByDescr("SMSCreditLowBalance_SendEmail").Value) == 1;
     btnUpdateNotificationInfo.Style["visibility"] = "hidden";
     btnRevertNotificationInfo.Style["visibility"] = "hidden";
 }
Пример #14
0
    protected void btnSMSPriceUpdate_Click(object sender, EventArgs e)
    {
        if (!txtValidateSMSPriceRequired.IsValid || !txtValidateSMSPriceRegex.IsValid)
        {
            return;
        }

        SystemVariableDB.Update("SMSPrice", txtSMSPrice.Text);
        SetSMSPriceTextBox(false);
    }
Пример #15
0
    protected void btnMaxNbrProvidersUpdate_Click(object sender, EventArgs e)
    {
        if (!txtValidateMaxNbrProvidersRequired.IsValid || !txtValidateMaxNbrProvidersRegex.IsValid)
        {
            return;
        }

        SystemVariableDB.Update("MaxNbrProviders", txtMaxNbrProviders.Text);
        SetMaxNbrProvidersTextBox(false);
    }
Пример #16
0
    protected void btnUpdateNotificationInfo_Click(object sender, EventArgs e)
    {
        txtStockWarningLevelNotificationEmailAddress.Text = txtStockWarningLevelNotificationEmailAddress.Text.Trim();

        if (txtStockWarningLevelNotificationEmailAddress.Text.Length > 0 && !Utilities.IsValidEmailAddress(txtStockWarningLevelNotificationEmailAddress.Text))
        {
            SetErrorMessage("Invalid email address. It must be blank or a valid email address.");
            return;
        }

        SystemVariableDB.Update("StockWarningNotificationEmailAddress", txtStockWarningLevelNotificationEmailAddress.Text);
    }
Пример #17
0
    protected void Run(bool incDisplay, bool incSending)
    {
        // 1. get all fields from systemvariables

        int DaysBeforePaymentDueToSendReminder = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["DaysBeforePaymentDueToSendReminder"]);
        int PaymentDueDayOfMonth = Convert.ToInt32(SystemVariableDB.GetByDescr("PaymentDueDayOfMonth").Value);

        string CustomerEmail = SystemVariableDB.GetByDescr("AdminAlertEmail_To").Value;
        string DB            = System.Web.HttpContext.Current.Session["DB"].ToString();

        /*
         * // log for debugging
         * Hashtable logFile = new Hashtable();
         * logFile["SMSSender_Scheduled_LogFile_Eli-PC"]     = @"C:\Users\Eli\Documents\Mediclinic\SMSSender_Scheduled_LogFile2.txt";
         * logFile["SMSSender_Scheduled_LogFile_ELI-LAPTOP"] = @"D:\Dropbox\Mediclinic\SMSSender_Scheduled_LogFile2.txt";
         *      logFile["SMSSender_Scheduled_LogFile_box001"]     = @"C:\inetpub\sites\MediclinicDocs\SMSSender_Scheduled_LogFile2.txt";
         * Logger.WriteToFile(
         *  ((DateTime.Today.Date != GetDueDateThisMonth(PaymentDueDayOfMonth, DaysBeforePaymentDueToSendReminder, DateTime.Today)) ? "Not Sent -- " : "Sent -- ") +
         *  @"DB = " + DB + " Today = " + DateTime.Today.ToString("dd-MM") + " SendDate = " + GetDueDateThisMonth(PaymentDueDayOfMonth, DaysBeforePaymentDueToSendReminder, DateTime.Today).ToString("dd-MM") + Environment.NewLine,
         *  logFile["SMSSender_Scheduled_LogFile_" + Environment.MachineName].ToString());
         */


        // 2. validate

        if (DateTime.Today.Date != GetDueDateThisMonth(PaymentDueDayOfMonth, DaysBeforePaymentDueToSendReminder, DateTime.Today))
        {
            return;
        }


        // 3. run it -- send reminder email to marcus

        string emailBody = @"
Mediclinic payment due date is coming up for :
<br />
<br />
<table>
    <tr><td>Customer Email</td><td>" + CustomerEmail + @"</td></tr>
    <tr><td>Due Day Of Month</td><td>" + Utilities.GetDateOrdinal(PaymentDueDayOfMonth) + @"</td></tr>
    <tr><td>Database</td><td>" + DB + @"</td></tr>
</table>";

        Emailer.AsyncSimpleEmail(
            System.Configuration.ConfigurationManager.AppSettings["ErrorEmail_FromEmail"],
            System.Configuration.ConfigurationManager.AppSettings["ErrorEmail_FromName"],
            System.Configuration.ConfigurationManager.AppSettings["TopupEmail_To"],
            "Mediclinic Customer Payment Due",
            emailBody,
            true,
            null);
    }
Пример #18
0
    public static void UpdateAndCheckWarning(int organisation_id, int offering_id, int qtyUsed)
    {
        Organisation org      = OrganisationDB.GetByID(organisation_id);
        Offering     offering = OfferingDB.GetByID(offering_id);

        Stock[] stockList    = StockDB.GetByOrg(org.OrganisationID);
        string  warningEmail = SystemVariableDB.GetByDescr("StockWarningNotificationEmailAddress").Value;

        for (int i = 0; i < stockList.Length; i++)
        {
            if (offering.OfferingID == stockList[i].Offering.OfferingID && stockList[i].Quantity >= 0)
            {
                int prevQty = stockList[i].Quantity;
                int postQty = stockList[i].Quantity - qtyUsed;
                if (postQty < 0)
                {
                    postQty = 0;
                }

                if (warningEmail.Length > 0 && stockList[i].WarningAmount >= 0 && qtyUsed > 0 && stockList[i].WarningAmount < prevQty && stockList[i].WarningAmount >= postQty)
                {
                    try
                    {
                        Emailer.SimpleEmail(
                            warningEmail,
                            "Stock Warning Level Reached For " + stockList[i].Offering.Name + " at " + org.Name,
                            "This is an automated email to notify you that the stock warning level of <b>" + stockList[i].WarningAmount + "</b> items that was set for <b>" + stockList[i].Offering.Name + "</b> at <b>" + org.Name + "</b> has been reached and you may need to re-stock.<br /><br />Best regards,<br />Mediclinic",
                            true,
                            null,
                            null
                            );
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException(ex, true);
                    }
                }

                StockDB.UpdateQuantity(stockList[i].StockID, postQty);
            }
        }
    }
    protected void btnUpdateNotificationInfo_Click(object sender, EventArgs e)
    {
        txtEmailAddress.Text = txtEmailAddress.Text.Trim();

        try
        {
            if (txtEmailAddress.Text.Length > 0 && !Utilities.IsValidEmailAddress(txtEmailAddress.Text))
            {
                throw new CustomMessageException("Invalid email address");
            }
        }
        catch (CustomMessageException ex)
        {
            SetErrorMessage(ex.Message);
            return;
        }

        SystemVariableDB.Update("ServiceSpecificBookingReminderLettersToBatch_EmailAddress", txtEmailAddress.Text);

        SetNotificationInfo(); // re-set to show it was update in the db
    }
Пример #20
0
    protected void SetMaxNbrProvidersTextBox(bool editable)
    {
        int maxNbrProviders = Convert.ToInt32(SystemVariableDB.GetByDescr("MaxNbrProviders").Value);

        txtMaxNbrProviders.Text      = maxNbrProviders.ToString();
        txtMaxNbrProviders.ReadOnly  = !editable;
        txtMaxNbrProviders.Enabled   = editable;
        txtMaxNbrProviders.ForeColor = System.Drawing.Color.Black;

        btnMaxNbrProvidersSetEditMode.Visible    = !editable;
        btnMaxNbrProvidersCancelEditMode.Visible = editable;
        btnMaxNbrProvidersUpdate.Visible         = editable;
        Utilities.SetEditControlBackColour(txtMaxNbrProviders, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Transparent, editable);

        if (editable)
        {
            // set cursor at "end" of the text
            string jsSetCursorEnd = @"var b98 = document.getElementById('" + txtMaxNbrProviders.ID.ToString() + @"'); b98.focus(); var val = b98.value; b98.value = ''; b98.value = val;";
            ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), Page.ClientID, jsSetCursorEnd, true);
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string InvoiceID        = Request.QueryString["InvoiceID"];
        string PT_CustomerName  = Request.QueryString["PT_CustomerName"];
        string PT_PaymentAmount = Request.QueryString["PT_PaymentAmount"];
        string PT_ReturnUrl     = Request.QueryString["PT_ReturnUrl"];

        string DB = null;

        if (Request.QueryString["id"] != null)
        {
            Tuple <string, int> formParams = GetFormParams(false);

            Invoice invoice = InvoiceDB.GetByID(formParams.Item2, formParams.Item1);
            if (invoice == null)
            {
                HideTableAndSetErrorMessage("Invalid invoice ID");
                return;
            }
            InvoiceID = invoice.InvoiceID.ToString();
            DB        = formParams.Item1;
        }
        else
        {
            DB = Session["DB"].ToString();
        }


        int paymentPendingID = PaymentPendingDB.Insert(DB, Convert.ToInt32(InvoiceID), Convert.ToDecimal(PT_PaymentAmount), PT_CustomerName);

        string url = ConfigurationManager.AppSettings["EziDebit_URL"] + "/Payment.aspx" +
                     "?PT_DigitalKey=" + SystemVariableDB.GetAll(DB)["EziDebit_DigitalKey"].Value +
                     "&PT_PaymentReference=" + paymentPendingID +
                     "&PT_CustomerName=" + PT_CustomerName +
                     "&PT_PaymentAmount=" + PT_PaymentAmount +
                     "&PT_ReturnURL=" + PT_ReturnUrl;

        Response.Redirect(url);
    }
Пример #22
0
    protected void SetSMSPriceTextBox(bool editable)
    {
        decimal smsPrice = Convert.ToDecimal(SystemVariableDB.GetByDescr("SMSPrice").Value);

        sms_credit_div.Style["width"] = editable ? "575px" : "350px";

        txtSMSPrice.Text      = smsPrice.ToString("0.00");
        txtSMSPrice.ReadOnly  = !editable;
        txtSMSPrice.Enabled   = editable;
        txtSMSPrice.ForeColor = System.Drawing.Color.Black;

        btnSMSPriceSetEditMode.Visible    = !editable;
        btnSMSPriceCancelEditMode.Visible = editable;
        btnSMSPriceUpdate.Visible         = editable;
        Utilities.SetEditControlBackColour(txtSMSPrice, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Transparent, editable);

        if (editable)
        {
            // set cursor at "end" of the text
            string jsSetCursorEnd = @"var b98 = document.getElementById('" + txtSMSPrice.ID.ToString() + @"'); b98.focus(); var val = b98.value; b98.value = ''; b98.value = val;";
            ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), Page.ClientID, jsSetCursorEnd, true);
        }
    }
Пример #23
0
    protected void ExportAllUsers(string DB = null)
    {
        string curDbName = Session["DB"].ToString();

        try
        {
            DataTable tblAllStaff = null;

            System.Data.DataTable tbl = DBBase.ExecuteQuery("EXEC sp_databases;", "master").Tables[0];
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                string databaseName = tbl.Rows[i][0].ToString();

                if (!Regex.IsMatch(databaseName, @"Mediclinic_\d{4}"))
                {
                    continue;
                }

                if (DB != null && databaseName != DB)
                {
                    continue;
                }

                Session["DB"] = databaseName;
                Session["SystemVariables"] = SystemVariableDB.GetAll();


                DataTable tblStaff = StaffDB.GetDataTable();


                // get entity ID's so we can get all emails into a hashtable in one db query
                int[] entityIDs = new int[tblStaff.Rows.Count];
                for (int j = 0; j < tblStaff.Rows.Count; j++)
                {
                    entityIDs[j] = Convert.ToInt32(tblStaff.Rows[j]["person_entity_id"]);
                }
                Hashtable emailHash = PatientsContactCacheDB.GetBullkEmail(entityIDs, -1);

                // add the emails to the datatable - as comma-seperated string
                tblStaff.Columns.Add("database_name", typeof(String));
                tblStaff.Columns.Add("emails", typeof(String));
                tblStaff.Columns.Add("site", typeof(String));
                for (int j = 0; j < tblStaff.Rows.Count; j++)
                {
                    Staff s = StaffDB.LoadAll(tblStaff.Rows[j]);

                    string emails = string.Empty;
                    if (emailHash[s.Person.EntityID] != null)
                    {
                        if (Utilities.GetAddressType().ToString() == "Contact")
                        {
                            if (emailHash[s.Person.EntityID] != null)
                            {
                                foreach (Contact c in (Contact[])emailHash[s.Person.EntityID])
                                {
                                    if (c.AddrLine1.Trim().Length > 0 && Utilities.IsValidEmailAddress(c.AddrLine1.Trim()))
                                    {
                                        emails += (emails.Length == 0 ? "" : ",") + c.AddrLine1.Trim();
                                    }
                                }
                            }
                        }
                        else if (Utilities.GetAddressType().ToString() == "ContactAus")
                        {
                            if (emailHash[s.Person.EntityID] != null)
                            {
                                foreach (ContactAus c in (ContactAus[])emailHash[s.Person.EntityID])
                                {
                                    if (c.AddrLine1.Trim().Length > 0 && Utilities.IsValidEmailAddress(c.AddrLine1.Trim()))
                                    {
                                        emails += (emails.Length == 0 ? "" : ",") + c.AddrLine1.Trim();
                                    }
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                        }
                    }

                    tblStaff.Rows[j]["database_name"] = databaseName;
                    tblStaff.Rows[j]["emails"]        = emails;
                    tblStaff.Rows[j]["site"]          = ((SystemVariables)Session["SystemVariables"])["Site"].Value;
                }


                // if first table, set alldb's to this, else add this to alldb's list
                if (tblAllStaff == null)
                {
                    tblAllStaff = tblStaff;
                }
                else
                {
                    tblAllStaff.Merge(tblStaff);
                }

                Session.Remove("DB");
                Session.Remove("SystemVariables");
            }


            // create output

            System.Text.StringBuilder htmlOoutput   = new System.Text.StringBuilder();
            System.Text.StringBuilder exportOoutput = new System.Text.StringBuilder();

            htmlOoutput.Append("<table border=\"1\">");

            htmlOoutput.Append("<tr>");
            htmlOoutput.Append("<th>Database</td>");
            htmlOoutput.Append("<th>Site Name</td>");
            htmlOoutput.Append("<th>Firstname</td>");
            htmlOoutput.Append("<th>Surname</td>");
            htmlOoutput.Append("<th>Fullname</td>");
            htmlOoutput.Append("<th>Stakeholder</td>");
            htmlOoutput.Append("<th>Master Admin</td>");
            htmlOoutput.Append("<th>Admin</td>");
            htmlOoutput.Append("<th>Principal</td>");
            htmlOoutput.Append("<th>Provider</td>");
            htmlOoutput.Append("<th>Email(s)</td>");
            htmlOoutput.Append("</tr>");

            exportOoutput.Append("Database").Append(",");
            exportOoutput.Append("Site Name").Append(",");
            exportOoutput.Append("Firstname").Append(",");
            exportOoutput.Append("Surname").Append(",");
            exportOoutput.Append("Fullname").Append(",");
            exportOoutput.Append("Stakeholder").Append(",");
            exportOoutput.Append("Master Admin").Append(",");
            exportOoutput.Append("Admin").Append(",");
            exportOoutput.Append("Principal").Append(",");
            exportOoutput.Append("Provider").Append(",");
            exportOoutput.Append("Email(s)").Append(",");
            exportOoutput.AppendLine();

            if (tblAllStaff != null)
            {
                for (int i = 0; i < tblAllStaff.Rows.Count; i++)
                {
                    Staff s = StaffDB.LoadAll(tblAllStaff.Rows[i]);

                    htmlOoutput.Append("<tr>");
                    htmlOoutput.Append("<td>" + tblAllStaff.Rows[i]["database_name"] + "</td>");
                    htmlOoutput.Append("<td>" + tblAllStaff.Rows[i]["site"] + "</td>");
                    htmlOoutput.Append("<td>" + s.Person.Firstname + "</td>");
                    htmlOoutput.Append("<td>" + s.Person.Surname + "</td>");
                    htmlOoutput.Append("<td>" + s.Person.Fullname + "</td>");
                    htmlOoutput.Append("<td>" + (s.IsStakeholder ? "Yes" : "No") + "</td>");
                    htmlOoutput.Append("<td>" + (s.IsMasterAdmin ? "Yes" : "No") + "</td>");
                    htmlOoutput.Append("<td>" + (s.IsAdmin       ? "Yes" : "No") + "</td>");
                    htmlOoutput.Append("<td>" + (s.IsPrincipal   ? "Yes" : "No") + "</td>");
                    htmlOoutput.Append("<td>" + (s.IsProvider    ? "Yes" : "No") + "</td>");
                    htmlOoutput.Append("<td>" + tblAllStaff.Rows[i]["emails"] + "</td>");
                    htmlOoutput.Append("</tr>");

                    exportOoutput.Append(tblAllStaff.Rows[i]["database_name"]).Append(",");
                    exportOoutput.Append(tblAllStaff.Rows[i]["site"]).Append(",");
                    exportOoutput.Append(s.Person.Firstname).Append(",");
                    exportOoutput.Append(s.Person.Surname).Append(",");
                    exportOoutput.Append(s.Person.Fullname).Append(",");
                    exportOoutput.Append(s.IsStakeholder ? "Yes" : "No").Append(",");
                    exportOoutput.Append(s.IsMasterAdmin ? "Yes" : "No").Append(",");
                    exportOoutput.Append(s.IsAdmin       ? "Yes" : "No").Append(",");
                    exportOoutput.Append(s.IsPrincipal   ? "Yes" : "No").Append(",");
                    exportOoutput.Append(s.IsProvider    ? "Yes" : "No").Append(",");
                    exportOoutput.Append(tblAllStaff.Rows[i]["emails"]).Append(",");
                    exportOoutput.AppendLine();
                }
            }

            htmlOoutput.Append("</table>");

            // send the output

            //lblResultMessage2.Text = htmlOoutput.ToString();
            ExportCSV(Response, exportOoutput.ToString(), "All Users All Sites.csv");
        }
        finally
        {
            Session["DB"] = curDbName;
            Session["SystemVariables"] = SystemVariableDB.GetAll();
        }
    }
Пример #24
0
    protected void DisplayInfo()
    {
        string curDbName = Session["DB"].ToString();

        ddlDBs.Items.Clear();
        ddlDBs.Items.Add(new ListItem("All Clients", "0"));

        ddlDBs2.Items.Clear();
        ddlDBs2.Items.Add(new ListItem("All Clients", "0"));

        ArrayList dbNames = new ArrayList();
        Hashtable dbHash  = new Hashtable();

        try
        {
            bool isSupportStaff3 = Session != null && Session["StaffID"] != null && Convert.ToInt32(Session["StaffID"]) == -4;

            List <Tuple <string, string> > list = new List <Tuple <string, string> >();


            System.Data.DataTable tbl = DBBase.ExecuteQuery("EXEC sp_databases;", "master").Tables[0];
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                string databaseName = tbl.Rows[i][0].ToString();

                if (!Regex.IsMatch(databaseName, @"Mediclinic_\d{4}"))
                {
                    continue;
                }
                //if (databaseName == "Mediclinic_0001")
                //    continue;


                SystemVariables sysVariables = SystemVariableDB.GetAll(databaseName);

                dbNames.Add(sysVariables["Site"].Value);
                dbHash[sysVariables["Site"].Value] = databaseName;


                System.Text.StringBuilder output = new System.Text.StringBuilder();

                Session["DB"] = databaseName;
                Session["SystemVariables"] = SystemVariableDB.GetAll();

                string callCenterPrefix = ((SystemVariables)Session["SystemVariables"])["CallCenterPrefix"].Value;

                int loginsPastWeek_Total = UserLoginDB.GetCount(7);
                int loginsPastWeek_Staff = UserLoginDB.GetStaffCount(7);


                if (((SystemVariables)Session["SystemVariables"])["UseMediclinicCallCenter"].Value == "1")
                {
                    Organisation[] orgs = OrganisationDB.GetAll(false, true, false, false, true, true);


                    Site[] sites          = SiteDB.GetAll();
                    int    clinicSiteID   = -1;
                    int    agedCareSiteID = -1;
                    for (int j = 0; j < sites.Length; j++)
                    {
                        if (sites[j].SiteType.ID == 1)
                        {
                            clinicSiteID = sites[j].SiteID;
                        }
                        if (sites[j].SiteType.ID == 2)
                        {
                            agedCareSiteID = sites[j].SiteID;
                        }
                    }


                    string showHideID1   = "heading_" + databaseName;
                    string showHideLink1 = @"<a href=""javascript:void(0)"" onclick=""hide_show_all('" + showHideID1 + @"');return false;"">Show/Hide Clinics/Facs</a>";

                    string siteTitleLink = @"<span style=""display:inline-block;vertical-align:middle;max-width:300px;min-width:300px;overflow:hidden;text-overflow:ellipsis;""><a style=""white-space:nowrap;"" class=""call_centre_header"" title=""" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @""" href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @""" onclick=""http_post('" + databaseName + @"','0','0',-1);return false;"">" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @"</a></span>";
                    //string siteTitleLink      = @"<span style=""display:inline-block;min-width:250px;""><a class=""call_centre_header"" title=""" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @""" href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @""" onclick=""http_post('" + databaseName + @"','0','0',-1);return false;"">" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @"</a></span>";
                    string callCentrePrefixText = @"<span style=""display:inline-block;min-width:160px;"">[Call Center Prefix: " + callCenterPrefix + "]</span>";

                    output.AppendLine("<tr>");
                    //output.AppendLine("    <td><u>" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + "</u> &nbsp;&nbsp; [Call Center Prefix: " + callCenterPrefix + "] &nbsp;&nbsp; [" + Session["DB"] + "]</td>");
                    output.AppendLine("    <td>" + showHideLink1 + " &nbsp;&nbsp; " + (isSupportStaff3 ? @"<span style=""display:inline-block;min-width:55px;"">" + (loginsPastWeek_Staff == 0 && loginsPastWeek_Total == 0 ? "" : "[" + loginsPastWeek_Staff + "," + loginsPastWeek_Total + "]") + "</span>" + " &nbsp;&nbsp; " : "") + siteTitleLink + " &nbsp;&nbsp; " + callCentrePrefixText + " &nbsp;&nbsp; [" + Session["DB"] + "]</td>");
                    output.AppendLine("</tr>");

                    if (orgs.Length > 0)
                    {
                        for (int j = 0; j < orgs.Length; j++)
                        {
                            string showHideID  = databaseName + "_" + orgs[j].OrganisationID;
                            string contactInfo = GetContactInfo(orgs[j].EntityID, 60, showHideID);

                            string titleLink    = @"<a href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @"&org=" + orgs[j].OrganisationID + @""" onclick=""http_post('" + databaseName + "','" + orgs[j].OrganisationID + @"','" + (orgs[j].IsClinic ? clinicSiteID : agedCareSiteID) + @"',-1);return false;"">" + orgs[j].Name + " " + (orgs[j].IsClinic ? @"(Clinic)" : "(Aged Care)") + @"</a>";
                            string showHideLink = @"<a href=""javascript:void(0)"" onclick=""hide_show('" + showHideID + @"');return false;"">Show/Hide Details</a>";


                            output.AppendLine(@"<tr id=""" + showHideID1 + j.ToString() + @""" style=""margin:0 0;display:none;"">");
                            output.AppendLine(@"    <td style=""margin:0 0;"">");
                            output.AppendLine(@"            <table><tr style=""vertical-align:top;""><td style=""width:500px;""><ul style=""margin:0 0;""><li>" + titleLink + @"</li></ul></td><td style=""min-width:10px;""></td><td>" + (contactInfo.Length > 0 ? showHideLink : "") + "</td></tr></table>");

                            if (contactInfo.Length > 0)
                            {
                                output.AppendLine(contactInfo);
                            }

                            output.AppendLine(@"    </td>");
                            output.AppendLine(@"</tr>");
                        }
                    }
                }

                list.Add(new Tuple <string, string>(((SystemVariables)Session["SystemVariables"])["Site"].Value, output.ToString()));

                Session.Remove("DB");
                Session.Remove("SystemVariables");
            }


            dbNames.Sort();
            foreach (string siteName in dbNames)
            {
                ddlDBs.Items.Add(new ListItem("[" + dbHash[siteName] + "] " + siteName, dbHash[siteName].ToString()));
                ddlDBs2.Items.Add(new ListItem("[" + dbHash[siteName] + "] " + siteName, dbHash[siteName].ToString()));
            }


            list.Sort((a, b) => a.Item1.CompareTo(b.Item1));
            System.Text.StringBuilder finalOutput = new System.Text.StringBuilder();
            foreach (Tuple <string, string> item in list)
            {
                finalOutput.Append(item.Item2);
            }

            lblInfo1.Text = "<table>" + finalOutput.ToString() + "</table>";
        }
        finally
        {
            Session["DB"] = curDbName;
            Session["SystemVariables"] = SystemVariableDB.GetAll();
        }
    }
Пример #25
0
    protected void GoTo(string db, int orgID, int siteID, int patientID)
    {
        //lblInfo1.Text += "GET<br/>DB: " + db + "<br />Org: " + orgID;

        bool isExternalStaff = orgID != 0 && patientID == -1;
        bool isStakeHolder   = !isExternalStaff && Convert.ToBoolean(Session["IsStakeholder"]);

        if (db != Session["DB"].ToString())
        {
            // Set previous StaffID, pervious DB
            Session["PreviousStaffID"] = Session["StaffID"];
            Session["PreviousDB"]      = Session["DB"];
            Session["PreviousSiteID"]  = Session["SiteID"];

            // Change to new DB & SystemVariables
            Session["DB"] = db;
            Session["SystemVariables"] = SystemVariableDB.GetAll();

            // Set system staff variables
            int   callCentreStaffID = isExternalStaff ? -5 : (!isStakeHolder ? -7 : -8);
            Staff staff             = StaffDB.GetByID(callCentreStaffID);
            Session["IsLoggedIn"]    = true;
            Session["IsStakeholder"] = staff.IsStakeholder;
            Session["IsMasterAdmin"] = staff.IsMasterAdmin;
            Session["IsAdmin"]       = staff.IsAdmin;
            Session["IsPrincipal"]   = staff.IsPrincipal;
            Session["IsProvider"]    = staff.IsProvider;
            Session["IsExternal"]    = staff.IsExternal;
            Session["StaffID"]       = staff.StaffID;
            Session["StaffFullnameWithoutMiddlename"] = staff.Person.FullnameWithoutMiddlename;
            Session["StaffFirstname"] = staff.Person.Firstname;

            // Set OrgID in session as external user has OrgID set
            if (isExternalStaff)
            {
                Organisation org = OrganisationDB.GetByID(orgID);
                Session["OrgID"]   = orgID;
                Session["OrgName"] = org.Name;
            }


            Site site = null;
            if (siteID != 0)
            {
                site = SiteDB.GetByID(siteID);
            }
            else
            {
                // log in to same site type if possible, else just log in to site 1
                site = SiteDB.GetSiteByType((SiteDB.SiteType)Convert.ToInt32(Session["SiteTypeID"]), null, db);
                if (site == null)
                {
                    site = SiteDB.GetByID(1);
                }
            }

            Session["SiteID"]         = site.SiteID;
            Session["SiteName"]       = site.Name;
            Session["SiteIsClinic"]   = site.SiteType.ID == 1;
            Session["SiteIsAgedCare"] = site.SiteType.ID == 2;
            Session["SiteIsGP"]       = site.SiteType.ID == 3;
            Session["SiteTypeID"]     = site.SiteType.ID;
            Session["SiteTypeDescr"]  = site.SiteType.Descr;

            Session["IsMultipleSites"] = SiteDB.GetAll().Length > 1;



            // Remove patient list session data for pt searches
            Session.Remove("patientinfo_data");
            Session.Remove("patientlist_data");
            Session.Remove("patientlist_sortexpression");
            Session.Remove("patientinfo_sortexpression");
        }


        // Go to booking page with this org

        if (isExternalStaff)
        {
            Response.Redirect("~/BookingsV2.aspx?orgs=" + Session["OrgID"] + "&ndays=4", false);
        }

        else if (patientID != -1 && orgID != 0)
        {
            Response.Redirect("~/BookingsV2.aspx?orgs=" + orgID + "&patient=" + patientID + "&ndays=4", false);
        }
        else if (patientID != -1 && orgID == 0)
        {
            Response.Redirect("~/PatientDetailV2.aspx?type=view&id=" + patientID, false);
        }

        else
        {
            Response.Redirect("~/Default.aspx", false);
        }
        return;
    }
Пример #26
0
    protected void btnUpdateNotificationInfo_Click(object sender, EventArgs e)
    {
        txtEmailAddress.Text = txtEmailAddress.Text.Trim();

        try
        {
            if (chkEnableEmails.Checked && txtEmailAddress.Text.Length == 0)
            {
                throw new CustomMessageException("To enable this, please set an email address");
            }

            txtEmailAddress.Text = Utilities.CleanEmailAddresses(txtEmailAddress.Text);
            if (txtEmailAddress.Text.Length > 0 && !Utilities.IsValidEmailAddresses(txtEmailAddress.Text, false))
            {
                throw new CustomMessageException("Invalid email address");
            }

            if (select_sites_row_auto.Attributes["class"] != "hiddencol" && !chkIncAgedCareAuto.Checked && !chkIncClinicsAuto.Checked)
            {
                throw new CustomMessageException("Plese check to generate for Clinics and/or Aged Care");
            }

            if (rdioSendTypeAuto.SelectedValue != "Print" && rdioSendTypeAuto.SelectedValue != "Email")
            {
                throw new ArgumentException("Please select a send method of Email or Print");
            }

            if (chkEnableEmails.Checked &&
                (!chkSendMondays.Checked &&
                 !chkSendTuesdays.Checked &&
                 !chkSendWednesdays.Checked &&
                 !chkSendThursdays.Checked &&
                 !chkSendFridays.Checked &&
                 !chkSendSaturdays.Checked &&
                 !chkSendSundays.Checked))
            {
                throw new CustomMessageException("To enable this, please set at least one day to send");
            }
        }
        catch (CustomMessageException ex)
        {
            SetErrorMessage(ex.Message, "", lblErrorMessageAutoSending);
            return;
        }


        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_SendEmail", chkEnableEmails.Checked ? "1" : "0");
        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_EmailAddress", txtEmailAddress.Text);

        if (select_sites_row_auto.Attributes["class"] != "hiddencol")
        {
            SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_IncClinic", chkIncClinicsAuto.Checked ? "1" : "0");
            SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_IncAgedCare", chkIncAgedCareAuto.Checked ? "1" : "0");
        }

        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_IncUnsent", chkIncUnsentAuto.Checked ? "1" : "0");
        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_IncBatched", chkIncBatchedAuto.Checked ? "1" : "0");

        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_SendMethod", rdioSendTypeAuto.SelectedValue);

        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_SendMondays", chkSendMondays.Checked ? "1" : "0");
        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_SendTuesdays", chkSendTuesdays.Checked ? "1" : "0");
        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_SendWednesdays", chkSendWednesdays.Checked ? "1" : "0");
        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_SendThursdays", chkSendThursdays.Checked ? "1" : "0");
        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_SendFridays", chkSendFridays.Checked ? "1" : "0");
        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_SendSaturdays", chkSendSaturdays.Checked ? "1" : "0");
        SystemVariableDB.Update("ReferrerEPCAutoGenerateLettersEmail_SendSundays", chkSendSundays.Checked ? "1" : "0");

        SetNotificationInfo(); // re-set to show it was update in the db
    }
    protected void FillGrid()
    {
        if (!IsValidFormID())
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

        Organisation org = OrganisationDB.GetByID(GetFormID());

        if (org == null)
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

        lblHeading.Text             = Page.Title = "Manage Registrations For :  " + org.Name;
        this.lnkThisOrg.NavigateUrl = "~/OrganisationDetailV2.aspx?type=view&id=" + GetFormID().ToString();
        this.lnkThisOrg.Text        = "Back to details for " + org.Name;



        string searchSurname = "";

        if (Request.QueryString["surname_search"] != null && Request.QueryString["surname_search"].Length > 0)
        {
            searchSurname         = Request.QueryString["surname_search"];
            txtSearchSurname.Text = Request.QueryString["surname_search"];
        }
        bool searchSurnameOnlyStartsWith = true;

        if (Request.QueryString["surname_starts_with"] != null && Request.QueryString["surname_starts_with"].Length > 0)
        {
            searchSurnameOnlyStartsWith           = Request.QueryString["surname_starts_with"] == "0" ? false : true;
            chkSurnameSearchOnlyStartWith.Checked = searchSurnameOnlyStartsWith;
        }
        else
        {
            chkSurnameSearchOnlyStartWith.Checked = searchSurnameOnlyStartsWith;
        }


        DataTable dt = RegisterPatientDB.GetDataTable_PatientsOf(GetFormViewOnlyLast(), org.OrganisationID, false, false, false, false, searchSurname, searchSurnameOnlyStartsWith);


        int[] ptIDs = new int[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ptIDs[i] = Convert.ToInt32(dt.Rows[i]["patient_id"]);
        }


        // get last and next booking dates

        Hashtable lastBookingDates = BookingDB.GetLastBookingDates(ptIDs, org.OrganisationID);
        Hashtable nextBookingDates = BookingDB.GetNextBookingDates(ptIDs, org.OrganisationID);

        dt.Columns.Add("last_booking_date", typeof(DateTime));
        dt.Columns.Add("next_booking_date", typeof(DateTime));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["last_booking_date"] = lastBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])] == null ? (object)DBNull.Value : (DateTime)lastBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])];
            dt.Rows[i]["next_booking_date"] = nextBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])] == null ? (object)DBNull.Value : (DateTime)nextBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])];
        }



        // get epc info

        Hashtable mostRecentRecallHashByPatientID = LetterPrintHistoryDB.GetMostRecentRecallHashByPatients(ptIDs);

        Hashtable patientHealthCardCache        = PatientsHealthCardsCacheDB.GetBullkActive(ptIDs);
        Hashtable epcRemainingCache             = GetEPCRemainingCache(patientHealthCardCache);
        Hashtable patientsMedicareCountCache    = PatientsMedicareCardCountThisYearCacheDB.GetBullk(ptIDs, DateTime.Today.Year);
        Hashtable patientsEPCRemainingCache     = PatientsEPCRemainingCacheDB.GetBullk(ptIDs, DateTime.Today.AddYears(-1));
        int       MedicareMaxNbrServicesPerYear = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);


        dt.Columns.Add("epc_expire_date", typeof(DateTime));
        dt.Columns.Add("has_valid_epc", typeof(Boolean));
        dt.Columns.Add("epc_count_remaining", typeof(Int32));

        dt.Columns.Add("most_recent_recall_sent", typeof(DateTime));
        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            int patientID = Convert.ToInt32(dt.Rows[i]["patient_id"]);

            HealthCard hc     = GetHealthCardFromCache(patientHealthCardCache, patientID);
            bool       hasEPC = hc != null && hc.DateReferralSigned != DateTime.MinValue;
            HealthCardEPCRemaining[] epcsRemaining = !hasEPC ? new HealthCardEPCRemaining[] { } : GetEPCRemainingFromCache(epcRemainingCache, hc);
            int totalServicesAllowedLeft           = !hasEPC ? 0 : (MedicareMaxNbrServicesPerYear - (int)patientsMedicareCountCache[patientID]);

            int totalEpcsRemaining = 0;
            for (int j = 0; j < epcsRemaining.Length; j++)
            {
                totalEpcsRemaining += epcsRemaining[j].NumServicesRemaining;
            }

            DateTime referralSignedDate = !hasEPC ? DateTime.MinValue : hc.DateReferralSigned.Date;
            DateTime hcExpiredDate      = !hasEPC ? DateTime.MinValue : referralSignedDate.AddYears(1);
            bool     isExpired          = !hasEPC ? true              : hcExpiredDate <= DateTime.Today;

            int nServicesLeft = 0;
            if (hc != null && DateTime.Today >= referralSignedDate.Date && DateTime.Today < hcExpiredDate.Date)
            {
                nServicesLeft = totalEpcsRemaining;
            }
            if (hc != null && totalServicesAllowedLeft < nServicesLeft)
            {
                nServicesLeft = totalServicesAllowedLeft;
            }

            bool has_valid_epc       = hasEPC && !isExpired && (hc.Organisation.OrganisationID == -2 || (hc.Organisation.OrganisationID == -1 && nServicesLeft > 0));
            int  epc_count_remaining = hasEPC && hc.Organisation.OrganisationID == -1 ? nServicesLeft : -1;

            dt.Rows[i]["has_valid_epc"]       = has_valid_epc;
            dt.Rows[i]["epc_expire_date"]     = hasEPC ? hcExpiredDate : (object)DBNull.Value;
            dt.Rows[i]["epc_count_remaining"] = epc_count_remaining != -1 ? epc_count_remaining : (object)DBNull.Value;

            dt.Rows[i]["most_recent_recall_sent"] = mostRecentRecallHashByPatientID[patientID] == null ? (object)DBNull.Value : ((LetterPrintHistory)mostRecentRecallHashByPatientID[patientID]).Date;
        }



        Session["registerpatienttoorg_data"] = dt;

        if (dt.Rows.Count > 0)
        {
            if (IsPostBack && Session["registerpatienttoorg_sortexpression"] != null && Session["registerpatienttoorg_sortexpression"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort = Session["registerpatienttoorg_sortexpression"].ToString();
                GrdRegistration.DataSource = dataView;
            }
            else
            {
                GrdRegistration.DataSource = dt;
            }


            try
            {
                GrdRegistration.DataBind();
                GrdRegistration.PagerSettings.FirstPageText = "1";
                GrdRegistration.PagerSettings.LastPageText  = GrdRegistration.PageCount.ToString();
                GrdRegistration.DataBind();
            }
            catch (Exception ex)
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdRegistration.DataSource = dt;
            GrdRegistration.DataBind();

            int TotalColumns = GrdRegistration.Rows[0].Cells.Count;
            GrdRegistration.Rows[0].Cells.Clear();
            GrdRegistration.Rows[0].Cells.Add(new TableCell());
            GrdRegistration.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdRegistration.Rows[0].Cells[0].Text       = "No Record Found";
        }

        if (hideFotter)
        {
            GrdRegistration.FooterRow.Visible = false;
        }
    }
Пример #28
0
    protected void EmailAllUsers(bool previewOnly, string DB = null)
    {
        bool IsDebug = Utilities.IsDev();


        string curDbName = Session["DB"].ToString();

        try
        {
            txtSubject.Text = txtSubject.Text.Trim();
            if (txtSubject.Text.Length == 0)
            {
                lblEmailErrorMessage.Text = "<br />No Subject Entered<br /><br />";
                return;
            }
            if (FreeTextBox1.Text.Trim().Length == 0)
            {
                lblEmailErrorMessage.Text = "<br />No Email Text Entered<br /><br />";
                return;
            }


            string fromEmail = IsDebug ? "*****@*****.**" : ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromEmail"].Value;
            string fromName  = ((SystemVariables)Session["SystemVariables"])["Email_FromName"].Value;


            DataTable tblAllStaff = null;

            ArrayList emailInfoList = new ArrayList(); // list of Tuple<site, person, email>

            System.Data.DataTable tbl = DBBase.ExecuteQuery("EXEC sp_databases;", "master").Tables[0];
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                string databaseName = tbl.Rows[i][0].ToString();

                if (!Regex.IsMatch(databaseName, @"Mediclinic_\d{4}"))
                {
                    continue;
                }

                if (chkIgnore0001.Checked && databaseName == @"Mediclinic_0001")
                {
                    continue;
                }

                if (DB != null && databaseName != DB)
                {
                    continue;
                }

                Session["DB"] = databaseName;
                Session["SystemVariables"] = SystemVariableDB.GetAll();

                string clientSiteName = ((SystemVariables)Session["SystemVariables"])["Site"].Value;

                DataTable tblStaff = StaffDB.GetDataTable();


                // get entity ID's so we can get all emails into a hashtable in one db query
                int[] entityIDs = new int[tblStaff.Rows.Count];
                for (int j = 0; j < tblStaff.Rows.Count; j++)
                {
                    entityIDs[j] = Convert.ToInt32(tblStaff.Rows[j]["person_entity_id"]);
                }
                Hashtable emailHash = PatientsContactCacheDB.GetBullkEmail(entityIDs, -1);

                // add the emails to the datatable - as comma-seperated string
                tblStaff.Columns.Add("database_name", typeof(String));
                tblStaff.Columns.Add("emails", typeof(String));
                tblStaff.Columns.Add("site", typeof(String));
                for (int j = 0; j < tblStaff.Rows.Count; j++)
                {
                    Staff s = StaffDB.LoadAll(tblStaff.Rows[j]);

                    if (chkMasterAdminOnly.Checked && !s.IsMasterAdmin)
                    {
                        continue;
                    }

                    if (emailHash[s.Person.EntityID] != null)
                    {
                        if (Utilities.GetAddressType().ToString() == "Contact")
                        {
                            if (emailHash[s.Person.EntityID] != null)
                            {
                                foreach (Contact c in (Contact[])emailHash[s.Person.EntityID])
                                {
                                    if (Utilities.IsValidEmailAddress(c.AddrLine1.Trim()))
                                    {
                                        emailInfoList.Add(new Tuple <string, string, string>(clientSiteName, s.Person.FullnameWithoutMiddlename, c.AddrLine1.Trim()));
                                    }
                                }
                            }
                        }
                        else if (Utilities.GetAddressType().ToString() == "ContactAus")
                        {
                            if (emailHash[s.Person.EntityID] != null)
                            {
                                foreach (ContactAus c in (ContactAus[])emailHash[s.Person.EntityID])
                                {
                                    if (Utilities.IsValidEmailAddress(c.AddrLine1.Trim()))
                                    {
                                        emailInfoList.Add(new Tuple <string, string, string>(clientSiteName, s.Person.FullnameWithoutMiddlename, c.AddrLine1.Trim()));
                                    }
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                        }
                    }
                }


                // if first table, set alldb's to this, else add this to alldb's list
                if (tblAllStaff == null)
                {
                    tblAllStaff = tblStaff;
                }
                else
                {
                    tblAllStaff.Merge(tblStaff);
                }

                Session.Remove("DB");
                Session.Remove("SystemVariables");
            }


            // send the email

            string output = "<h4>" + (previewOnly ? "Message Preview" : "Message Sent") + "</h4>" + Environment.NewLine +

                            "<table style=\"min-width:400px;border:1px solid black;text-align:center;background-color:#FFFFFF;border-spacing:2px;border-collapse:separate;\"><tr><td><b>" + txtSubject.Text + "</b></td></tr></table><div style=\"height:10px;\"></div>" + Environment.NewLine +



                            "<table style=\"min-width:500px;border:1px solid black;text-align:left;background-color:#FFFFFF;border-spacing:10px;border-collapse:separate;\"><tr style=\"min-height:200px;\"><td>" + (FreeTextBox1.Text.Length == 0 ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : FreeTextBox1.Text) + "</td></tr></table><br />";

            output += "<h4>" + (previewOnly ? "Will Be Sent To" : "Sent To") + "</h4><table border=\"1\" class=\"table table-bordered table-striped table-grid table-grid-top-bottum-padding-normal auto_width block_center\" >";
            string emails = string.Empty;

            foreach (Tuple <string, string, string> emailInfo in emailInfoList)
            {
                output += "<tr><td style=\"padding-left:4px;padding-right:4px;text-align:left !important;\">" + emailInfo.Item1 + "</td><td style=\"padding-left:4px;padding-right:4px;text-align:left !important;\">" + emailInfo.Item2 + "</td><td style=\"padding-left:4px;padding-right:4px;text-align:left !important;\">" + emailInfo.Item3 + "</td></tr>";
                emails  = (emails.Length == 0 ? "" : ",") + emailInfo.Item3;
            }
            if (emailInfoList.Count == 0)
            {
                output += "<tr><td style=\"padding-left:4px;padding-right:4px;text-align:left !important;\">&nbsp;No Staff Have Emails In The Selected Site(s)&nbsp;</td></tr>";
            }
            output += "</table>";



            if (!previewOnly && emails.Length > 0)
            {
                // email: put to addresss as from address
                // email: put all emails in BCC
                EmailerNew.SimpleEmail(
                    fromEmail,
                    fromName,
                    fromEmail,
                    txtSubject.Text.Trim(),
                    FreeTextBox1.Text,
                    true,
                    null,
                    false,
                    null,
                    IsDebug ? "*****@*****.**" : emails
                    );
            }

            lblEmailOutput.Text = output;
        }
        finally
        {
            Session["DB"] = curDbName;
            Session["SystemVariables"] = SystemVariableDB.GetAll();

            Page.ClientScript.RegisterStartupScript(this.GetType(), "download", @"<script language=javascript>addLoadEvent(function () { window.location.hash = ""emailing_tag""; });</script>");
        }
    }
Пример #29
0
    protected void Search(string phoneNumberIn = null, string surnameIn = null, string dob_day = null, string dob_month = null, string dob_year = null)
    {
        string phoneNumberSearch = phoneNumberIn == null ? "" : Regex.Replace(phoneNumberIn, "[^0-9]", "");
        string surnameSearch     = surnameIn == null ? "" : surnameIn.Trim();

        if (phoneNumberSearch == "" && surnameSearch == "" && dob_day == "-1" && dob_month == "-1" && dob_year == "-1")
        {
            lblSearchResults.Text = "<font color=\"red\"><br />Please enter a phone number or surname or DOB to search</font>";
            return;
        }


        string curDbName = Session["DB"].ToString();


        ArrayList dbNames = new ArrayList();
        Hashtable dbHash  = new Hashtable();

        string searchResults = string.Empty;

        try
        {
            List <Tuple <string, string> > list = new List <Tuple <string, string> >();


            System.Data.DataTable tbl = DBBase.ExecuteQuery("EXEC sp_databases;", "master").Tables[0];
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                string databaseName = tbl.Rows[i][0].ToString();

                if (!Regex.IsMatch(databaseName, @"Mediclinic_\d{4}"))
                {
                    continue;
                }


                SystemVariables sysVariables = SystemVariableDB.GetAll(databaseName);

                dbNames.Add(sysVariables["Site"].Value);
                dbHash[sysVariables["Site"].Value] = databaseName;


                StringBuilder output = new StringBuilder();

                Session["DB"] = databaseName;
                Session["SystemVariables"] = SystemVariableDB.GetAll();

                string callCenterPrefix = ((SystemVariables)Session["SystemVariables"])["CallCenterPrefix"].Value;


                string siteName = ((SystemVariables)Session["SystemVariables"])["Site"].Value;

                list.Add(new Tuple <string, string>(((SystemVariables)Session["SystemVariables"])["Site"].Value, output.ToString()));


                Site[] sites          = SiteDB.GetAll();
                int    clinicSiteID   = -1;
                int    agedCareSiteID = -1;
                for (int j = 0; j < sites.Length; j++)
                {
                    if (sites[j].SiteType.ID == 1)
                    {
                        clinicSiteID = sites[j].SiteID;
                    }
                    if (sites[j].SiteType.ID == 2)
                    {
                        agedCareSiteID = sites[j].SiteID;
                    }
                }


                DataTable dt = PatientDB.GetDataTable(false, false, false, false, surnameSearch, true, "", false, "", "", phoneNumberSearch, "", "", false, Convert.ToInt32(dob_day), Convert.ToInt32(dob_month), Convert.ToInt32(dob_year));
                if (dt.Rows.Count > 0)
                {
                    int[] entityIDs  = new int[dt.Rows.Count];
                    int[] patientIDs = new int[dt.Rows.Count];
                    for (int p = 0; p < dt.Rows.Count; p++)
                    {
                        entityIDs[p]  = Convert.ToInt32(dt.Rows[p]["entity_id"]);
                        patientIDs[p] = Convert.ToInt32(dt.Rows[p]["patient_id"]);
                    }
                    Hashtable bullkPhoneNumbers = PatientsContactCacheDB.GetBullkPhoneNumbers(entityIDs, -1);

                    Hashtable ptOrgsHash = RegisterPatientDB.GetMostRecentOrganisationOf(patientIDs);

                    for (int p = 0; p < dt.Rows.Count; p++)
                    {
                        string   ptName   = dt.Rows[p]["firstname"].ToString() + " " + dt.Rows[p]["surname"].ToString();
                        DateTime dob      = dt.Rows[p]["dob"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dt.Rows[p]["dob"]);
                        int      ptID     = Convert.ToInt32(dt.Rows[p]["patient_id"]);
                        int      entityID = Convert.ToInt32(dt.Rows[p]["entity_id"]);

                        Organisation org = ptOrgsHash[ptID] as Organisation;

                        string phoneNbrs = string.Empty;
                        if (bullkPhoneNumbers[entityID] != null)
                        {
                            if (Utilities.GetAddressType().ToString() == "Contact")
                            {
                                foreach (Contact c in ((Contact[])bullkPhoneNumbers[entityID]))
                                {
                                    string phoneNumber = Regex.Replace(c.AddrLine1, "[^0-9]", "");
                                    phoneNbrs += (phoneNbrs.Length == 0 ? string.Empty : "<br />") + Utilities.FormatPhoneNumber(phoneNumber).Replace(" ", "-");
                                }
                            }
                            else if (Utilities.GetAddressType().ToString() == "ContactAus")
                            {
                                foreach (ContactAus c in ((ContactAus[])bullkPhoneNumbers[entityID]))
                                {
                                    string phoneNumber = Regex.Replace(c.AddrLine1, "[^0-9]", "");
                                    if (phoneNumber.StartsWith(phoneNumberSearch))
                                    {
                                        phoneNbrs += (phoneNbrs.Length == 0 ? string.Empty : "<br />") + Utilities.FormatPhoneNumber(phoneNumber).Replace(" ", "-");
                                    }
                                }
                            }
                            else
                            {
                                throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                            }
                        }

                        string orgLink = org == null ? "" : @"<a href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @"&org=" + org.OrganisationID + @"&patient=" + ptID + @""" onclick=""http_post('" + databaseName + "','" + org.OrganisationID + @"','" + (org.IsClinic ? clinicSiteID : agedCareSiteID) + @"'," + ptID + @");return false;"">" + org.Name + @"</a>";
                        string ptLink  = @"<a href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @"&org=0" + @"&patient=" + ptID + @""" onclick=""http_post('" + databaseName + "','" + "0" + @"','" + clinicSiteID + @"'," + ptID + @");return false;"">" + ptName + @"</a>";

                        output.AppendLine("<tr><td>" + siteName + "</td><td>" + ptLink + "</td><td>" + orgLink + "</td><td style=\"white-space:nowrap\">" + (dob == DateTime.MinValue ? "" : dob.ToString("d MMM, yyyy")) + "</td>" + (phoneNumberSearch == null ? "" : "<td>" + phoneNbrs + "</td>") + "</tr>");
                    }
                }


                list.Add(new Tuple <string, string>(((SystemVariables)Session["SystemVariables"])["Site"].Value, output.ToString()));

                Session.Remove("DB");
                Session.Remove("SystemVariables");
            }



            list.Sort((a, b) => a.Item1.CompareTo(b.Item1));
            System.Text.StringBuilder finalOutput = new System.Text.StringBuilder();
            foreach (Tuple <string, string> item in list)
            {
                finalOutput.Append(item.Item2);
            }


            if (finalOutput.Length == 0)
            {
                lblSearchResults.Text = "<font color=\"red\"><br />No patient found with the search parameters entered</font>";
            }
            else
            {
                lblSearchResults.Text = @"<br />
<table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-normal auto_width block_center"">
  <tr>
    <th>Site</th>
    <th>Patient</th>
    <th>Book</th>
    <th>D.O.B</th>
    " + (phoneNumberSearch == null ? "" : "<th>Phone Nbr</th>") + @"  
  </tr>
" + finalOutput.ToString() + "</table>";
            }
        }
        finally
        {
            Session["DB"] = curDbName;
            Session["SystemVariables"] = SystemVariableDB.GetAll();
        }
    }
    public static string Run(bool incDisplay, bool incSending, DateTime date)
    {
        date = date.Date;


        bool   EnableDailyBookingReminderSMS             = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableDailyBookingReminderSMS").Value) == 1;
        bool   EnableDailyBookingReminderEmails          = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableDailyBookingReminderEmails").Value) == 1;
        int    NbrDaysAheadToSendDailyBookingReminderSMS = Convert.ToInt32(SystemVariableDB.GetByDescr("NbrDaysAheadToSendDailyBookingReminderSMS").Value);
        string SendDailyBookingReminderText_SMS          = SystemVariableDB.GetByDescr("SendDailyBookingReminderText_SMS").Value;
        string SendDailyBookingReminderText_Email        = SystemVariableDB.GetByDescr("SendDailyBookingReminderText_Email").Value;
        string SendDailyBookingReminderText_EmailSubject = SystemVariableDB.GetByDescr("SendDailyBookingReminderText_EmailSubject").Value;
        string PT_Reminders_HasBothSMSandEmail           = SystemVariableDB.GetByDescr("PT_Reminders_HasBothSMSandEmail").Value;

        date = date.AddDays(NbrDaysAheadToSendDailyBookingReminderSMS - 1);


        Booking[] bookings = BookingDB.GetBetween(date, date.AddDays(1).AddMinutes(-1), null, null, null, null, false, "0", false, null);
        Hashtable patientContactPhoneNbrHash = GetPatientPhoneNbrCache(bookings);
        Hashtable patientContactEmailHash    = GetPatientEmailCache(bookings);
        Hashtable orgContactHash             = GetOrgPhoneNbrCache(bookings);
        Hashtable orgAddrContactHash         = GetOrgAddrCache(bookings);



        decimal balance = SMSCreditDataDB.GetTotal() - SMSHistoryDataDB.GetTotal();
        decimal cost    = Convert.ToDecimal(SystemVariableDB.GetByDescr("SMSPrice").Value);


        string    callerId                 = System.Configuration.ConfigurationManager.AppSettings["SMSTech_callerId"];  // not used here as the callerId will be the org name
        string    countryCode              = System.Configuration.ConfigurationManager.AppSettings["SMSTech_CountryCode"];
        ArrayList messagesToSMS            = new ArrayList();
        ArrayList messagesToEmail          = new ArrayList();
        ArrayList bookingIDsConfirmedSMS   = new ArrayList();
        ArrayList bookingIDsConfirmedEmail = new ArrayList();


        string output           = "<table class=\"table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center\" border=\"1\" style=\"border-collapse:collapse;\">";
        int    countWithPatient = 0;

        foreach (Booking booking in bookings)
        {
            if (booking.BookingTypeID != 34)  // only bookings, not days marked off
            {
                continue;
            }

            if (booking.Patient == null || booking.Offering == null)      // prob aged care booking
            {
                continue;
            }

            // Marcus: send sms even if booking is confirmed
            //if (booking.ConfirmedBy != null)  // don't send reminders to those already confirmed
            //    continue;

            // get all info to send via sms or email

            string phoneNumPatient = GetPhoneNbr(patientContactPhoneNbrHash, booking.Patient.Person.EntityID, true);
            if (phoneNumPatient != null)
            {
                phoneNumPatient = phoneNumPatient.StartsWith("0") ? countryCode + phoneNumPatient.Substring(1) : phoneNumPatient;
            }

            string emailPatient = GetEmail(patientContactEmailHash, booking.Patient.Person.EntityID);
            string phoneNumOrg  = GetPhoneNbrs(orgContactHash, booking.Organisation.EntityID);
            string addrOrg      = GetAddr(orgAddrContactHash, booking.Organisation.EntityID);

            string smsText          = GetSMSText(booking, phoneNumOrg, addrOrg, SendDailyBookingReminderText_SMS);
            string emailText        = GetEmailText(booking, phoneNumOrg, addrOrg, SendDailyBookingReminderText_Email);
            string emailSubjectText = GetEmailSubjectText(booking, phoneNumOrg, addrOrg, SendDailyBookingReminderText_EmailSubject);


            // kept just to show their email/phone number exists even though we may not be sending to there due to settings or low balance.
            string phoneNumPatient_Original = phoneNumPatient;
            string emailPatient_Original    = emailPatient;


            // ignore if setting is to not sending sms's or emails
            if (phoneNumPatient != null && !EnableDailyBookingReminderSMS)
            {
                phoneNumPatient = null;
            }
            if (emailPatient != null && !EnableDailyBookingReminderEmails)
            {
                emailPatient = null;
            }

            // if balance too low, can not send by SMS
            if (phoneNumPatient != null && balance < cost)
            {
                phoneNumPatient = null;
            }

            // if has both, then send based on setting
            if (phoneNumPatient != null && emailPatient != null)
            {
                if (PT_Reminders_HasBothSMSandEmail == "Email") // setting is - when both, send only via email
                {
                    phoneNumPatient = null;
                }
                if (PT_Reminders_HasBothSMSandEmail == "SMS")   // setting is - when both, send only via sms
                {
                    emailPatient = null;
                }
            }


            string textToDisplay = string.Empty;
            if (phoneNumPatient != null)
            {
                textToDisplay += "<b>" + smsText.Replace(Environment.NewLine, "<br />") + "</b>";
            }
            if (emailPatient != null)
            {
                textToDisplay += (textToDisplay.Length == 0 ? "" : "<br><hr>") + "<u>" + emailSubjectText + "</u><br /><br />" + emailText;
            }



            // display the info

            string tdTagStart          = phoneNumPatient == null && emailPatient == null ? "<td class=\"nowrap\" style=\"color:grey;\">" : (phoneNumPatient == null ? "<td>"  : "<td>");
            string tdTagStartLeftAlign = phoneNumPatient == null && emailPatient == null ? "<td class=\"nowrap text_left\" style=\"color:grey;\">" : (phoneNumPatient == null ? "<td class=\"text_left\">" : "<td class=\"text_left\">");
            string tdTagEnd            = phoneNumPatient == null && emailPatient == null ? "</td>" : (phoneNumPatient == null ? "</td>" : "</td>");

            output += "<tr>";
            output += tdTagStart + booking.BookingID + tdTagEnd;
            output += tdTagStart + booking.DateStart.ToString("dd-MM-yy") + "<br />" + booking.DateStart.ToString("HH:mm") + " - " + booking.DateEnd.ToString("HH:mm") + tdTagEnd;
            output += tdTagStart + booking.Organisation.Name + "<br />" + (phoneNumOrg == null ? "-- No Phone --" : phoneNumOrg.Replace(",", "<br />").Replace("or", "<br />")) + tdTagEnd;
            output += tdTagStart + booking.Patient.Person.FullnameWithoutMiddlename + "<br />" +
                      (phoneNumPatient_Original == null ? "-- No Mobile --" : "<u>" + phoneNumPatient_Original + "</u>") + "<br />" +
                      (emailPatient_Original == null ? "-- No Email --"  : "<u>" + emailPatient_Original + "</u>") + tdTagEnd;
            output += tdTagStartLeftAlign + textToDisplay + tdTagEnd;
            output += "</tr>";

            countWithPatient++;



            /*
             *  add to lists to sms or email (or both)
             */

            if (phoneNumPatient != null)
            {
                messagesToSMS.Add(new Tuple <int, decimal, string, string, string>(booking.BookingID, cost, phoneNumPatient, smsText, booking.Organisation.Name));
                bookingIDsConfirmedSMS.Add(booking.BookingID);
                if (incSending)
                {
                    balance -= cost;
                }
            }
            if (emailPatient != null)
            {
                messagesToEmail.Add(new Tuple <int, string, string, string, string>(booking.BookingID, booking.Organisation.Name, emailPatient, emailText, emailSubjectText));
                bookingIDsConfirmedEmail.Add(booking.BookingID);
            }


            /*
             * bool sendingAlready = false;
             * if (EnableDailyBookingReminderSMS && phoneNumPatient != null && balance >= cost)
             * {
             *  messagesToSMS.Add(new Tuple<int, decimal, string, string, string>(booking.BookingID, cost, phoneNumPatient, smsText, booking.Organisation.Name));
             *  bookingIDsConfirmedSMS.Add(booking.BookingID);
             *  sendingAlready = true;
             *  if (incSending)
             *      balance -= cost;
             * }
             * if (EnableDailyBookingReminderEmails && emailPatient != null)
             * {
             *  messagesToEmail.Add(new Tuple<int, string, string, string, string>(booking.BookingID, booking.Organisation.Name, emailPatient, emailText, emailSubjectText));
             *  if (!sendingAlready)  // if not already added for sms sending
             *      bookingIDsConfirmedEmail.Add(booking.BookingID);
             * }
             */
        }
        output += "</table>";


        // run the sending and send off reminders -- but only if there was any bookings

        if (incSending && bookings.Length > 0)
        {
            /*
             * run the sendings
             */

            SendSMSes((Tuple <int, decimal, string, string, string>[])messagesToSMS.ToArray(typeof(Tuple <int, decimal, string, string, string>)));
            SendEmails((Tuple <int, string, string, string, string>[])messagesToEmail.ToArray(typeof(Tuple <int, string, string, string, string>)));

            /*
             * if sms or email sent, set booking as confirmed
             */
            BookingDB.UpdateSetConfirmed((int[])bookingIDsConfirmedSMS.ToArray(typeof(int)), 2, -1);
            BookingDB.UpdateSetConfirmed((int[])bookingIDsConfirmedEmail.ToArray(typeof(int)), 3, -1);

            /*
             * send balance warning
             */

            SystemVariables systemVariables            = SystemVariableDB.GetAll();
            string          warningEmail               = systemVariables["SMSCreditNotificationEmailAddress"].Value;
            decimal         warningThreshold           = Convert.ToDecimal(systemVariables["SMSCreditLowBalance_Threshold"].Value);
            bool            checkSMSCreditOutOfBalance = Convert.ToInt32(systemVariables["SMSCreditOutOfBalance_SendEmail"].Value) == 1;
            bool            checkMSCreditLowBalance    = Convert.ToInt32(systemVariables["SMSCreditLowBalance_SendEmail"].Value) == 1;


            if (warningEmail.Length > 0 && checkSMSCreditOutOfBalance && balance < cost)
            {
                SendEmail(
                    warningEmail,
                    "SMS Credit Used Up",
                    "Please note that your SMS credit at mediclinic has been used up. To continue sending, please top up.<br /><br />Best regards,<br />Mediclinic");
            }
            else if (warningEmail.Length > 0 && checkMSCreditLowBalance && balance <= warningThreshold)  // dont send warning low balance if already sending out of credit email
            {
                SendEmail(
                    warningEmail,
                    "SMS Credit Warning - Don't Forget To Top-Up Before It Runs Out",
                    "Hi! Just a friendly reminder that the SMS reminder threshold you set has been reached.<br /> To avoid missing SMS'es being sent, don't forget to top-up before the remainder runs out!<br /><br />Best regards,<br />Mediclinic");
            }
        }

        if (incDisplay)
        {
            return("Count: <b>" + countWithPatient + "</b> &nbsp;&nbsp; [Sending Via SMS: <b>" + messagesToSMS.Count + "</b>] &nbsp;&nbsp; [Sending Via Email: <b>" + messagesToEmail.Count + "</b>] " + "<br /><br />" + output);
        }
        else
        {
            return(string.Empty);
        }
    }