Esempio n. 1
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);
        }
    }
Esempio n. 2
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;
    }
Esempio n. 3
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");
    }
Esempio n. 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);
    }
Esempio n. 5
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;
    }
    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);
    }
Esempio n. 7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        bool isLoggedIn  = Session != null && Session["DB"] != null;
        bool useConfigDB = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseConfigDB"]);

        try
        {
            string staff_id = Request.QueryString["staff"];
            if (staff_id == null || !Regex.IsMatch(staff_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException();
            }
            string org_id = Request.QueryString["org"];
            if (org_id == null || !Regex.IsMatch(staff_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException();
            }


            if (!isLoggedIn && useConfigDB)
            {
                Session["DB"] = System.Configuration.ConfigurationManager.AppSettings["Database"];
                Session["SystemVariables"] = SystemVariableDB.GetAll();
            }
            if (!isLoggedIn && !useConfigDB)
            {
                string _output = @"<table>
                        <tr>
                            <td align=""left"" colspan=""5""><b>Patients Waiting" + @"</b><font color=""#8a8a8a""> &nbsp;&nbsp;  @ " + DateTime.Now.ToString("h:mm:ss") + @"</font></td>
                        </tr>
                        <tr style=""height:10px"">
                            <td colspan=""5""></td>
                        </tr>
                        <tr><td colspan=""5""><font color=""#8a8a8a"">Unable to retrieve patients while logged out.</font></td></tr>
                        </table>";
                Response.Write(_output);
                return;
            }


            Staff staff = StaffDB.GetByID(Convert.ToInt32(staff_id));
            if (staff_id == "-1" || staff == null)
            {
                throw new CustomMessageException();
            }
            Organisation org = OrganisationDB.GetByID(Convert.ToInt32(org_id));
            if (staff_id == "0" || staff == null)
            {
                throw new CustomMessageException();
            }


            string output = string.Empty;

            int       count    = 0;
            Booking[] bookings = BookingDB.GetBetween(DateTime.Now.AddMinutes(-45), DateTime.Now.AddMinutes(120), new Staff[] { staff }, new Organisation[] { org }, null, null, false, "0");
            foreach (Booking b in bookings)
            {
                if (b.ArrivalTime == DateTime.MinValue)
                {
                    continue;
                }

                output += @"<tr><td>" + b.Patient.Person.FullnameWithoutMiddlename + @"</td><td style=""width:10px""></td><td>" + b.DateStart.ToString("h:mm") + @"</td><td style=""width:10px""></td><td><a href=""javascript:void(0)"" onclick=""ajax_unset_arrival_time(" + b.BookingID + @");return false;"" title=""Remove from list"" style=""text-decoration:none;""><font color=""red"">X</font></a></td></tr>";
                count++;
            }

            if (count == 0)
            {
                output += @"<tr><td colspan=""5""><font color=""#8a8a8a"">No patients waiting</font></td></tr>";
            }


//                               <td align=""left"" colspan=""5""><b>Patients Waiting (" + count + ")" + @"</b><font color=""#8a8a8a""> &nbsp;&nbsp;  @ " + DateTime.Now.ToString("h:mm:ss") + @"</font></td>
//                               <td align=""left"" colspan=""5""><b>Patients Waiting (" + count + ")" + @"</td>
            output = @"<table>
                           <tr>
                                <td align=""left"" colspan=""5""><b>Patients Waiting (" + count + ")" + @"</b><font color=""#8a8a8a""> &nbsp;&nbsp;  @ " + DateTime.Now.ToString("h:mm:ss") + @"</font></td>
                           </tr>
                           <tr style=""height:10px"">
                               <td colspan=""5""></td>
                           </tr>" + output + "</table>";

            Response.Write(output);
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + (Utilities.IsDev() ? ex.ToString() : "please contact system administrator."));
        }
        finally
        {
            if (!isLoggedIn && useConfigDB)
            {
                Session.Remove("DB");
                Session.Remove("SystemVariables");
            }
        }
    }
Esempio n. 8
0
    // http://portal.mediclinic.com.au:803/Reminder/RunServiceSpecificBookingReminderLetters.aspx?pwd=mah_sms_reminder
    // http://portal.mediclinic.com.au:803/Reminder/RunServiceSpecificBookingReminderLetters.aspx?pwd=mah_sms_reminder&inc_sending=false


    #region Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        try
        {
            string pwd = Request.Form["pwd"];

            if (pwd != null)  // sent by http post
            {
                if (pwd == null || pwd != System.Configuration.ConfigurationManager.AppSettings["SMSRunRemindersPwd"])
                {
                    throw new CustomMessageException("Incorrect password");
                }

                string exceptionOutput = string.Empty;

                if (Session != null && Session["DB"] != null)
                {
                    ServiceSpecificBookingReminderLettersSending.Run(false, true, true, DateTime.Now.Date);
                }
                else
                {
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseConfigDB"]))
                    {
                        Session["DB"] = System.Configuration.ConfigurationManager.AppSettings["Database"];
                        Session["SystemVariables"] = SystemVariableDB.GetAll();
                        ServiceSpecificBookingReminderLettersSending.Run(false, true, true, DateTime.Now.Date);
                        Session.Remove("DB");
                        Session.Remove("SystemVariables");
                    }
                    else // Get all DB's and run it on all of them
                    {
                        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;
                            }

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

                                ServiceSpecificBookingReminderLettersSending.Run(false, true, true, DateTime.Now.Date);
                            }
                            catch (Exception ex)
                            {
                                exceptionOutput += Environment.NewLine + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + " " + "DB: " + databaseName;
                                exceptionOutput += Environment.NewLine + ex.ToString();
                            }
                            finally
                            {
                                Session.Remove("DB");
                                Session.Remove("SystemVariables");
                            }
                        }
                    }
                }

                if (exceptionOutput.Length > 0)
                {
                    Response.Write("Run Completed But With Errors!");
                    Response.Write(Environment.NewLine + exceptionOutput);
                }
                else
                {
                    Response.Write("Run Completed!");
                }
            }
            else // send in url by http get
            {
                pwd = Request.QueryString["pwd"];
                if (pwd == null || pwd != System.Configuration.ConfigurationManager.AppSettings["SMSRunRemindersPwd"])
                {
                    throw new CustomMessageException("Incorrect password");
                }

                string inc_sending = Request.QueryString["inc_sending"];
                if (inc_sending != null && inc_sending != "true" && inc_sending != "false")
                {
                    throw new CustomMessageException("Incorrect inc_sending value");
                }
                bool incSending = inc_sending != null && inc_sending == "true";


                if (Session != null && Session["DB"] != null)
                {
                    string displayData = ServiceSpecificBookingReminderLettersSending.Run(true, incSending, true, DateTime.Now.Date);
                    Response.Write(displayData);
                }
                else
                {
                    if (!Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseConfigDB"]))
                    {
                        throw new CustomMessageException("Can not run for logged out user where UseConfigDB = false");
                    }
                    else
                    {
                        Session["DB"] = System.Configuration.ConfigurationManager.AppSettings["Database"];
                        Session["SystemVariables"] = SystemVariableDB.GetAll();

                        string displayData = ServiceSpecificBookingReminderLettersSending.Run(true, incSending, true, DateTime.Now.Date);
                        Response.Write(displayData);

                        Session.Remove("DB");
                        Session.Remove("SystemVariables");
                    }
                }
            }
        }
        catch (CustomMessageException ex)
        {
            Response.Write(ex.Message);
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + (ex.ToString()));
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        try
        {
            // [message_id] => 100000 [mobile] => 6140000000 [datetime] => 2012-04-27 10:38:00 [status] => ok
            string message_id = Request.Form["message_id"];
            string mobile     = Request.Form["mobile"];
            string datetime   = Request.Form["datetime"];
            string status     = Request.Form["status"];

            string info =
                "message_id  : " + message_id + Environment.NewLine +
                "mobile      : " + mobile + Environment.NewLine +
                "datetime    : " + datetime + Environment.NewLine +
                "status      : " + status + Environment.NewLine;

            if (message_id != 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;
                    }

                    Session["DB"] = databaseName;
                    Session["SystemVariables"] = SystemVariableDB.GetAll();
                    SMSHistoryDataDB.Update(message_id, status);
                    Session.Remove("DB");
                    Session.Remove("SystemVariables");
                }
            }


            //
            // NO NEED TO RELAY TO OTHER SITES - WE ALREADY UPDATED ALL DATABASES
            //


            //
            // relay to other site(s)
            //


            /*
             * string is_relay = Request.Form["is_relay"];
             * if (is_relay == null)
             * {
             *
             *  string[] urls = System.Configuration.ConfigurationManager.AppSettings["SMSDeliveryOtherSites"].Length == 0 ? new string[] { } : System.Configuration.ConfigurationManager.AppSettings["SMSDeliveryOtherSites"].Split(';');
             *
             *  for (int i = 0; i < urls.Length; i++)
             *  {
             *      string url = urls[i];
             *
             *      try
             *      {
             *          //string response = HttpGet(((SystemVariables)Session["SystemVariables"])["Url1"].Value);
             *          string response = Utilities.HttpPost(url, new System.Collections.Specialized.NameValueCollection() {
             *                                              { "message_id", message_id },
             *                                              { "mobile",     mobile     },
             *                                              { "datetime",   datetime   },
             *                                              { "status",     status     },
             *                                              { "is_relay",   "1"        }
             *                                      });
             *      }
             *      catch (Exception ex)
             *      {
             *          Logger.LogSMSDelivery("Timestamp: " + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + " [" + url + "]" + Environment.NewLine + Environment.NewLine + ex.ToString(), true);
             *      }
             *
             *  }
             * }
             */
        }
        catch (Exception ex)
        {
            Logger.LogSMSDelivery(ex.ToString(), true);
        }
    }
Esempio n. 10
0
    public static string Run(bool incDisplay, bool incSending, DateTime date)
    {
        date = date.Date;

        bool   EnableDailyStaffBookingsReminderSMS    = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableDailyStaffBookingsReminderSMS").Value) == 1;
        bool   EnableDailyStaffBookingsReminderEmails = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableDailyStaffBookingsReminderEmails").Value) == 1;
        string Staff_Reminders_HasBothSMSandEmail     = SystemVariableDB.GetByDescr("Staff_Reminders_HasBothSMSandEmail").Value;

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

        //string  callerId    = System.Configuration.ConfigurationManager.AppSettings["SMSTech_callerId"];  // not here used as the callerId will be the org name
        string callerId    = ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromName"].Value;
        string countryCode = System.Configuration.ConfigurationManager.AppSettings["SMSTech_CountryCode"];


        // get bookings and organise the data to send/display
        Booking[] bookings = GetBookingsSortedByProviderTimeOrganisation(date);
        ArrayList list     = OrganiseData(bookings);

        // get phone nbr and email hash in one db call
        int[] entityIDs = new int[list.Count];
        for (int i = 0; i < list.Count; i++)
        {
            entityIDs[i] = ((Tuple <Staff, ArrayList>)list[i]).Item1.Person.EntityID;
        }
        Hashtable staffContactPhoneNbrHash = PatientsContactCacheDB.GetBullkPhoneNumbers(entityIDs, -1);
        Hashtable staffContactEmailHash    = PatientsContactCacheDB.GetBullkEmail(entityIDs, -1);;



        // lists to send
        ArrayList messagesToSMS   = new ArrayList();
        ArrayList messagesToEmail = new ArrayList();


        // display all bookings for debugging
        string bkOutput = "<a href=\"#\" onclick=\"   var e = document.getElementById('div_bk'); e.style.display = (e.style.display == '') ? 'none' : ''; return false; \">Show/Hide Bookings</a><br /><br />";

        bkOutput += "<div id=\"div_bk\" style=\"display:none;\" ><table border=\"1\" cellpadding=\"4\" style=\"border-collapse:collapse;\">";
        for (int i = 0; i < bookings.Length; i++)
        {
            bkOutput += "<tr><td>" + bookings[i].BookingID + "</td><td>" + bookings[i].Provider.Person.FullnameWithoutMiddlename + " [" + bookings[i].Provider.StaffID + "]</td><td>" + bookings[i].Organisation.OrganisationID + "</td><td>" + bookings[i].DateStart.ToString("HH:mm") + " - " + bookings[i].DateEnd.ToString("HH:mm") + "</td></tr>";
        }
        bkOutput += "</table></div>";


        // go through all items to add to send lists and to display for debugging
        string output = "<table border=\"1\" cellpadding=\"4\" style=\"border-collapse:collapse;\">";

        for (int i = 0; i < list.Count; i++)
        {
            Tuple <Staff, ArrayList> t = (Tuple <Staff, ArrayList>)list[i];

            string phoneNum = GetPhoneNbr(staffContactPhoneNbrHash, t.Item1.Person.EntityID, true);
            if (phoneNum != null)
            {
                phoneNum = phoneNum.StartsWith("0") ? countryCode + phoneNum.Substring(1) : phoneNum;
            }

            string email = GetEmail(staffContactEmailHash, t.Item1.Person.EntityID);


            // ignore if setting is to not sending sms's or emails
            if (phoneNum != null && (!EnableDailyStaffBookingsReminderSMS || !t.Item1.EnableDailyReminderSMS))
            {
                phoneNum = null;
            }
            if (email != null && (!EnableDailyStaffBookingsReminderEmails || !t.Item1.EnableDailyReminderEmail))
            {
                email = null;
            }

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

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


            output += "<tr>";
            output += "<td>" + "<b><u>" + t.Item1.Person.FullnameWithoutMiddlename + " [ID:" + t.Item1.StaffID + "]</u></b>";
            output += "    <table cellpadding=\"0\" cellspacing=\"0\">";
            output += "        <tr><td>" + "Mobile:</td><td>" + (phoneNum == null ? "NONE" : "<b>" + phoneNum + "</b>") + "</td></tr>";
            output += "        <tr><td>" + "Email:</td><td>" + (email == null ? "NONE" : "<b>" + email + "</b>") + "</td></tr>";
            output += "    </table>";
            output += "</td>";

            string smsText   = "Hi " + t.Item1.Person.Firstname + Environment.NewLine + "Tomorrow (" + date.ToString("dddd") + " " + Utilities.GetDateOrdinal(date.Day) + ") you have appointments at:" + Environment.NewLine;
            string emailText = "Hi " + t.Item1.Person.Firstname + "," + "<br />" + "Tomorrow (" + date.ToString("dddd") + " " + Utilities.GetDateOrdinal(date.Day) + ") you have appointments at:" + "<br /><br />";

            emailText += "<table>";
            string times = string.Empty;
            for (int j = 0; j < t.Item2.Count; j++)
            {
                Tuple <Organisation, DateTime, DateTime> t2 = (Tuple <Organisation, DateTime, DateTime>)t.Item2[j];

                smsText   += Environment.NewLine + "[" + ConvertTime(t2.Item2) + " - " + ConvertTime(t2.Item3) + "] " + t2.Item1.Name;
                emailText += "<tr><td>" + "[" + ConvertTime(t2.Item2) + " - " + ConvertTime(t2.Item3) + "]" + "</td><td><b>" + t2.Item1.Name + "</b></td></tr>";

                times += (times.Length == 0 ? "" : "<br />") + t2.Item1.Name + " [ID:" + t2.Item1.OrganisationID + "] " + ConvertTime(t2.Item2) + " - " + ConvertTime(t2.Item3);
            }
            emailText += "</table><br />Regards,<br />" + callerId;

            output += "<td>" + times + "</td>";
            output += "<td>" + "<b><font color=\"blue\">" + smsText.Replace(Environment.NewLine, "<br />") + "</font></b>" + "</td>";



            // add to lists to sms or email (or both)
            if (phoneNum != null)
            {
                messagesToSMS.Add(new Tuple <Staff, decimal, string, string, string>(t.Item1, cost, phoneNum, smsText, callerId));
                if (incSending)
                {
                    balance -= cost;
                }
            }
            if (email != null)
            {
                messagesToEmail.Add(new Tuple <Staff, string, string, string, string>(t.Item1, callerId, email, emailText, "Work locations for " + date.ToString("d MMM, yyyy")));
            }
        }

        output += "</table>";


        // run the sending and send off reminders

        if (incSending)
        {
            /*
             * run the sendings
             */

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


            /*
             * 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(output + "<br />" + bkOutput);
        }
        else
        {
            return(string.Empty);
        }
    }
    protected void CreateLogin(string email)
    {
        email = email.Replace("'", "''");

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

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


            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;

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

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


                bool allowPatientLogins            = ((SystemVariables)Session["SystemVariables"])["AllowPatientLogins"].Value == "1";
                bool allowPatientsToCreateOwnLogin = ((SystemVariables)Session["SystemVariables"])["AllowPatientsToCreateOwnLogin"].Value == "1";

                if (!allowPatientLogins || !allowPatientsToCreateOwnLogin)
                {
                    continue;
                }


                int[] entityIDs;
                if (Utilities.GetAddressType().ToString() == "Contact")
                {
                    entityIDs = ContactDB.GetByAddrLine1(null, email, 27).Select(r => r.EntityID).ToArray();
                }
                else if (Utilities.GetAddressType().ToString() == "ContactAus")
                {
                    entityIDs = ContactAusDB.GetByAddrLine1(null, email, 27).Select(r => r.EntityID).ToArray();
                }
                else
                {
                    throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                }


                foreach (int entityID in entityIDs)
                {
                    Patient patient = PatientDB.GetByEntityID(entityID);
                    if (patient == null || patient.IsDeceased || patient.IsDeleted)
                    {
                        continue;
                    }

                    bool hasLoginDetails = patient.Login.Length > 0;
                    if (!hasLoginDetails)
                    {
                        string login    = Regex.Replace(patient.Person.Firstname, @"[^A-Za-z]+", "").ToLower() + Regex.Replace(patient.Person.Surname, @"[^A-Za-z]+", "").ToLower();
                        string loginTry = login;

                        Random rnd = new Random();
                        int    nbr = rnd.Next(11, 999);

                        do
                        {
                            bool loginUsed = (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(loginTry)) ||
                                             (PatientDB.LoginExists(loginTry));

                            if (!loginUsed)
                            {
                                patient.Login = loginTry;
                                patient.Pwd   = loginTry == login ? login + nbr : loginTry;

                                PatientDB.UpdateLoginPwd(patient.PatientID, patient.Login, patient.Pwd);
                                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                                {
                                    UserDatabaseMapperDB.Insert(loginTry, Session["DB"].ToString());
                                }

                                break;
                            }

                            nbr++;
                            loginTry = login + nbr;
                        } while (true);
                    }

                    SendPasswordRetrievalEmail(patient.Login, patient.Pwd, email);
                    list.Add(new Tuple <string, Patient, bool>(databaseName, patient, hasLoginDetails));
                }

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


            System.Text.StringBuilder finalOutput = new System.Text.StringBuilder();
            foreach (Tuple <string, Patient, bool> item in list)
            {
                finalOutput.Append("<tr><td>" + item.Item1 + "</td><td>" + item.Item2.Person.FullnameWithoutMiddlename + "</td><td>" + item.Item3 + "</td><td>" + item.Item2.Login + " | " + item.Item2.Pwd + "</td></tr>");
            }


            //FailureText.Text = "Count: " + list.Count + "<br /><table border=\"1\" class=\"block_center padded-table-2px\">" + finalOutput.ToString() + "</table>";


            if (list.Count == 0)
            {
                throw new CustomMessageException("No patients found with this email");
            }

            this.FailureText.Text = "An email has been sent with new login details";
        }
        catch (CustomMessageException cmEx)
        {
            this.FailureText.Text = cmEx.Message;
        }
        finally
        {
            //Session["DB"] = curDbName;
            //Session["SystemVariables"] = SystemVariableDB.GetAll();
            Session.Remove("DB");
            Session.Remove("SystemVariables");
        }
    }
    // http://portal.mediclinic.com.au:803/Hinx/HinxGeneration.aspx?pwd=mah_sms_reminder
    // http://portal.mediclinic.com.au:803/Hinx/HinxGeneration.aspx?pwd=mah_sms_reminder&inc_sending=false


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        try
        {
            string pwd = Request.Form["pwd"];

            if (pwd == null)
            {
                pwd = Request.QueryString["pwd"];
            }

            if (pwd != null)  // sent by http post
            {
                if (pwd == null || pwd != System.Configuration.ConfigurationManager.AppSettings["SMSRunRemindersPwd"])
                {
                    throw new CustomMessageException("Incorrect password");
                }

                string exceptionOutput = string.Empty;

                if (Session != null && Session["DB"] != null)
                {
                    throw new CustomMessageException("Can not run this while logged in.");
                }
                else
                {
                    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_0026")
                        {
                            continue;
                        }

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

                            if (Convert.ToInt32(SystemVariableDB.GetByDescr("AutoMedicareClaiming").Value) == 1)
                            {
                                GenerateMedicareHinxFiles();
                                GenerateDVAHinxFiles();
                            }
                        }
                        catch (Exception ex)
                        {
                            exceptionOutput += Environment.NewLine + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + " " + "DB: " + databaseName;
                            exceptionOutput += Environment.NewLine + ex.ToString();
                        }
                        finally
                        {
                            Session.Remove("DB");
                            Session.Remove("SystemVariables");
                        }
                    }
                }


                if (exceptionOutput.Length > 0)
                {
                    Response.Write("Run Completed But With Errors!");
                    Response.Write(Environment.NewLine + exceptionOutput);
                }
                else
                {
                    Response.Write("Run Completed!");
                }
            }
        }
        catch (CustomMessageException ex)
        {
            Response.Write(ex.Message);
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + ex.ToString());
        }
    }
    /*
     * Put this into grid - page and menu only can be seen by stakeholder
     *
     *           0000-0999          1000-1999          2000-2999          3000-3999          ....
     * A      • Total Podiatry
     * B      • PodiatryClinics
     * C
     * D
     * ..
     *
     */

    protected void Run()
    {
        string curDbName = Session["DB"].ToString();

        try
        {
            ArrayList claimNbrRangeList = new ArrayList();
            for (char l = 'A'; l <= 'Z'; l++)
            {
                for (int i = 0; i <= 9; i++)
                {
                    claimNbrRangeList.Add("" + l + i + "000" + "_" + l + i + "999");
                }
            }


            ArrayList dbList          = new ArrayList();
            ArrayList siteNameList    = new ArrayList();
            ArrayList allocationsList = new ArrayList();

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

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


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

                string sql       = "SELECT COUNT(*) FROM InvoiceHealthcareClaimNumbers WHERE last_date_used IS NOT NULL OR is_active = 1";
                int    countUsed = Convert.ToInt32(DBBase.ExecuteSingleResult(sql));
                if (countUsed > 0)
                {
                    dbList.Add(databaseName);
                    siteNameList.Add(((SystemVariables)Session["SystemVariables"])["Site"].Value);
                    allocationsList.Add(GetClaimsAllocated(claimNbrRangeList));
                }

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



            string outputHeaderRow = string.Empty;
            string outputBody      = string.Empty;

            DataTable results = new DataTable();
            for (int i = 0; i < 11; i++)
            {
                results.Columns.Add("");
            }

            DataRow dtRow = results.NewRow();
            dtRow[0] = "";
            for (int i = 0; i < 10; i++)
            {
                dtRow[i + 1] = i.ToString() + "000-" + i.ToString() + "999";
            }
            results.Rows.Add(dtRow);

            for (int i = 0; i <= 9; i++)          // each row
            {
                for (char l = 'A'; l <= 'Z'; l++) // each col
                {
                    DataRow dtNewRow = results.NewRow();
                    results.Rows.Add(dtNewRow);
                }
            }


            int r = 1;
            for (char l = 'A'; l <= 'Z'; l++)  // each row
            {
                string row = "<tr><th>" + l + "</th>";

                for (int i = 0; i <= 9; i++)  // each col
                {
                    if (l == 'A')
                    {
                        outputHeaderRow += "<th style=\"text-align:center;\">" + "" + i + "000" + "-" + i + "999" + "</th>";
                    }

                    if (i == 0)
                    {
                        results.Rows[r][i] = l;
                    }

                    string range      = "" + l + i + "000" + "_" + l + i + "999";
                    string startRange = range.Split('_')[0];
                    string endRange   = range.Split('_')[1];
                    string firstChar  = range[0].ToString();


                    string sites = string.Empty;
                    for (int j = 0; j < siteNameList.Count; j++)
                    {
                        DataTable tbl       = (DataTable)allocationsList[j];
                        bool      allocated = Convert.ToBoolean(tbl.Rows[0][range]);
                        if (allocated)
                        {
                            sites += (sites.Length > 0 ? "<br />" : "") + "• " + siteNameList[j];
                        }
                    }

                    row += "<td" + (sites.Length > 0 ? " class=\"nowrap\"" : "") + ">" + sites + "</td>";
                    results.Rows[r][i + 1] = sites.Replace("• ", "").Replace("<br />", Environment.NewLine);
                }


                row        += "</tr>";
                outputBody += row;

                r++;
            }

            outputHeaderRow = "<tr><th></th>" + outputHeaderRow + "<tr>";

            outputBody     = "<table class=\"table table-bordered table-striped table-grid table-grid-top-bottum-padding-normal auto_width block_center\" border=\"1\">" + outputHeaderRow + outputBody + "</table>";
            lblOutput.Text = outputBody;


            ViewState["results"] = results;
        }
        finally
        {
            Session["DB"] = curDbName;
            Session["SystemVariables"] = SystemVariableDB.GetAll();
        }
    }
    protected void Retrieve(string username)
    {
        try
        {
            Session.Remove("DB");
            if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseConfigDB"]))
            {
                Session["DB"] = System.Configuration.ConfigurationManager.AppSettings["Database"];
            }
            else // Get DB from Mediclinic_Main
            {
                UserDatabaseMapper user = UserDatabaseMapperDB.GetByLogin(username);
                if (user == null)
                {
                    this.FailureText.Text = "Login Failed.";
                    return;
                }

                Session["DB"] = user.DBName;
            }

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


            if (username.Length > 0)
            {
                Staff   staff   = StaffDB.GetByLogin(username);
                Patient patient = PatientDB.GetByLogin(username);

                if (staff != null && !staff.IsFired)
                {
                    string[] emails = ContactDB.GetEmailsByEntityID(staff.Person.EntityID);

                    if (emails.Length == 0)
                    {
                        throw new CustomMessageException("No email is set for user: "******",", emails));

                    this.FailureText.Text = "An email has been sent with login details for '" + username + "' to the email address(es) associated with that user";
                }
                else if (patient != null && !patient.IsDeleted)
                {
                    string[] emails = ContactDB.GetEmailsByEntityID(patient.Person.EntityID);

                    if (emails.Length == 0)
                    {
                        throw new CustomMessageException("No email is set for user: "******",", emails));

                    this.FailureText.Text = "An email has been sent with login details for '" + username + "' to the email address(es) associated with that user";
                }
                else
                {
                    throw new CustomMessageException("Username does not exist");
                }
            }
            else
            {
                throw new CustomMessageException("Please enter a username");
            }
        }
        catch (CustomMessageException cmEx)
        {
            this.FailureText.Text = cmEx.Message;
        }
        finally
        {
            Session.Remove("DB");
            Session.Remove("SystemVariables");
        }
    }
Esempio n. 15
0
    private void FillEmptyAddForm()
    {
        Tuple <string, int> formParams = GetFormParams(false);

        Invoice invoice = InvoiceDB.GetByID(formParams.Item2, formParams.Item1);

        if (invoice == null)
        {
            HideTableAndSetErrorMessage("Invalid invoice ID");
            return;
        }


        lblInvoiceNbr.Text  = invoice.InvoiceID.ToString();
        lblAmountOwing.Text = "$" + invoice.TotalDue.ToString();


        DataTable dt = DBBase.GetGenericDataTable(formParams.Item1, "ReceiptPaymentType", "receipt_payment_type_id", "descr");

        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            if (Convert.ToInt32(dt.Rows[i]["receipt_payment_type_id"]) != 133)
            {
                dt.Rows.RemoveAt(i);
            }
        }

        // add column for displaying data in first few rows with invoice id and invoice amount owing
        dt.Columns.Add("text");
        dt.Columns.Add("tab_index");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["text"] = "";
        }

        lstPayments.DataSource = dt;
        lstPayments.DataBind();

        for (int i = lstPayments.Items.Count - 1; i >= 0; i--)
        {
            Label   lblReceiptPaymentTypeID     = (Label)lstPayments.Items[i].FindControl("lblTypeID");
            TextBox txtReceiptPaymentTypeAmount = (TextBox)lstPayments.Items[i].FindControl("txtAmount");
            Button  btnWebPay = (Button)lstPayments.Items[i].FindControl("btnWebPay");

            if (lblReceiptPaymentTypeID.Text != "133" && lblReceiptPaymentTypeID.Text != "362")
            {
                btnWebPay.Visible = false;
            }

            txtReceiptPaymentTypeAmount.Text = invoice.TotalDue.ToString();

            SystemVariables sysVariables = SystemVariableDB.GetAll(formParams.Item1);
            if (sysVariables["EziDebit_Enabled"].Value != "1")
            {
                btnWebPay.Visible = false;
            }

            Utilities.SetEditControlBackColour(txtReceiptPaymentTypeAmount, true, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        }

        if (invoice.IsPaID)
        {
            maintable.Visible = false;
            SetErrorMessage("Invoice already paid");
        }
    }
Esempio n. 16
0
    private void SetupGUI(string dbID, string orgID)
    {
        ddlClinic.Focus();

        ddlDOB_Day.Items.Add(new ListItem("--", "-1"));
        ddlDOB_Month.Items.Add(new ListItem("--", "-1"));
        ddlDOB_Year.Items.Add(new ListItem("----", "-1"));

        for (int i = 1; i <= 31; i++)
        {
            ddlDOB_Day.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
        for (int i = 1; i <= 12; i++)
        {
            ddlDOB_Month.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
        for (int i = 1900; i <= DateTime.Today.Year; i++)
        {
            ddlDOB_Year.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }



        string curDbName = Session == null || Session["DB"] == null ? null : Session["DB"].ToString();

        try
        {
            Session["DB"] = "Mediclinic_" + dbID;
            Session["SystemVariables"] = SystemVariableDB.GetAll();

            bool allowPatientsToCreateOwnRecords = ((SystemVariables)Session["SystemVariables"])["AllowPatientsToCreateOwnRecords"].Value == "1";
            if (!allowPatientsToCreateOwnRecords)
            {
                throw new CustomMessageException("Invalid ID in URL");
            }

            ddlTitle.DataSource = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Title", " title_id <> 0 ", " descr ", "title_id", "descr");
            ddlTitle.DataBind();
            ddlTitle.SelectedIndex = Utilities.IndexOf(ddlTitle, "mr", "mr.");

            DataTable phoneNumberTypes = ContactTypeDB.GetDataTable(2);
            for (int i = phoneNumberTypes.Rows.Count - 1; i >= 0; i--)
            {
                if (Convert.ToInt32(phoneNumberTypes.Rows[i]["at_contact_type_id"]) != 30 && Convert.ToInt32(phoneNumberTypes.Rows[i]["at_contact_type_id"]) != 33)
                {
                    phoneNumberTypes.Rows.RemoveAt(i);
                }
            }
            ddlPhoneNumberType.DataSource = phoneNumberTypes;
            ddlPhoneNumberType.DataBind();
            ddlPhoneNumberType.SelectedValue = "30"; // mobile

            lblSiteName.Text = ((SystemVariables)Session["SystemVariables"])["Site"].Value;

            Site[] sites        = SiteDB.GetAll();
            Site   clinicSite   = null;
            Site   agedCareSite = null;
            for (int i = 0; i < sites.Length; i++)
            {
                if (sites[i].SiteType.ID == 1)
                {
                    clinicSite = sites[i];
                }
                if (sites[i].SiteType.ID == 2)
                {
                    agedCareSite = sites[i];
                }
            }

            List <Tuple <string, Organisation> > clinics = GetClinicList();
            foreach (Tuple <string, Organisation> item in clinics)
            {
                ddlClinic.Items.Add(new ListItem(item.Item2.Name, "Mediclinic_" + dbID + "__" + clinicSite.SiteID + "__" + item.Item2.OrganisationID));
            }

            if (orgID != null && Regex.IsMatch(orgID, @"^\d+$"))
            {
                Organisation org = OrganisationDB.GetByID(Convert.ToInt32(orgID));
                if (org != null && ddlClinic.Items.FindByValue("Mediclinic_" + dbID + "__" + clinicSite.SiteID + "__" + org.OrganisationID) != null)
                {
                    ddlClinic.SelectedValue = "Mediclinic_" + dbID + "__" + clinicSite.SiteID + "__" + org.OrganisationID;
                }
            }
        }
        finally
        {
            Session.Remove("DB");
            Session.Remove("SystemVariables");

            if (curDbName != null)
            {
                Session["DB"] = curDbName;
                Session["SystemVariables"] = SystemVariableDB.GetAll();
            }
        }



        bool editable = true;

        Utilities.SetEditControlBackColour(ddlClinic, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(ddlTitle, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(txtFirstname, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(txtSurname, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(ddlGender, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(ddlDOB_Day, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(ddlDOB_Month, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(ddlDOB_Year, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(txtPhoneNumber, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(ddlPhoneNumberType, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(txtEmailAddr, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(txtLogin, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
        Utilities.SetEditControlBackColour(txtPwd, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty);
    }
Esempio n. 17
0
    protected void CreatePatientButton_Click(object sender, EventArgs e)
    {
        if (!ddlDOBValidateAllSet.IsValid)
        {
            return;
        }

        int  person_id           = -1;
        int  patient_id          = -1;
        int  register_patient_id = -1;
        bool patient_added       = false;
        int  mainDbUserID        = -1;

        int  phone_id       = -1;
        int  email_id       = -1;
        bool contacts_added = false;

        try
        {
            string[] clinicInfo = ddlClinic.SelectedValue.Split(new string[] { "__" }, StringSplitOptions.None);
            string   dbID       = clinicInfo[0];
            int      siteID     = Convert.ToInt32(clinicInfo[1]);
            int      orgID      = Convert.ToInt32(clinicInfo[2]);

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

            txtEmailAddr.Text   = txtEmailAddr.Text.Trim();
            txtPhoneNumber.Text = txtPhoneNumber.Text.Trim();
            if (!Utilities.IsValidEmailAddress(txtEmailAddr.Text))
            {
                throw new CustomMessageException("Email must be in valid email format.");
            }

            txtLogin.Text = txtLogin.Text.Trim();
            txtPwd.Text   = txtPwd.Text.Trim();

            txtFirstname.Text = txtFirstname.Text.Trim();
            txtSurname.Text   = txtSurname.Text.Trim();



            // check if patient exists in the system, if so use existing patietn

            bool patientAlreadyExists = false;

            // check if email exists in the system
            if (!patientAlreadyExists)
            {
                if (ExistsAndCreatedLogin_FromEmail(orgID, txtPhoneNumber.Text, txtEmailAddr.Text, siteID, ref register_patient_id, ref phone_id, ref email_id))
                {
                    patientAlreadyExists      = true;
                    patient_added             = true;
                    contacts_added            = true;
                    this.lblErrorMessage.Text = "Your email alrady exist in this sytem.<br/>An email has been sent with new login details.<br/>When you receieve it, use the login link below.";
                }
            }

            // check if firstname / surname / DOB exists in the system
            if (!patientAlreadyExists)
            {
                if (ExistsAndCreatedLogin_FromNameAndDOB(orgID, txtPhoneNumber.Text, txtEmailAddr.Text, txtFirstname.Text, txtSurname.Text, GetDOBFromForm(), siteID, ref register_patient_id, ref phone_id, ref email_id))
                {
                    patientAlreadyExists      = true;
                    patient_added             = true;
                    contacts_added            = true;
                    this.lblErrorMessage.Text = "You alrady exist in this sytem.<br/>An email has been sent with new login details.<br/>When you receieve it, use the login link below.";
                }
            }



            if (!patientAlreadyExists)
            {
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
                {
                    throw new CustomMessageException("Login name already in use. Please choose another");
                }
                if (PatientDB.LoginExists(txtLogin.Text))
                {
                    throw new CustomMessageException("Login name already in use. Please choose another");
                }


                // 1. Create Patient

                Staff loggedInStaff = StaffDB.GetByID(-6);
                person_id           = PersonDB.Insert(loggedInStaff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), "", Utilities.FormatName(txtSurname.Text), "", ddlGender.SelectedValue, GetDOBFromForm());
                patient_id          = PatientDB.Insert(person_id, true, false, false, "", -1, DateTime.MinValue, "", "", DateTime.MinValue, false, false, DateTime.MinValue, -1, -1, txtLogin.Text, txtPwd.Text, false, "", "", "", "");
                register_patient_id = RegisterPatientDB.Insert(orgID, patient_id);
                patient_added       = true;   // added this because was throwing a thread aborted exception after patient added before Response.Redirect


                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    if (txtLogin.Text.Length > 0)
                    {
                        mainDbUserID = UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
                    }
                }


                // 2. Add Contact Info

                Patient patient = PatientDB.GetByID(patient_id);

                phone_id            = AddPhoneNbrIfNotExists(patient, siteID, txtPhoneNumber.Text);
                email_id            = AddEmailIfNotExists(patient, siteID, txtEmailAddr.Text);
                register_patient_id = AddOrgIfNotExists(patient, siteID, orgID);
                contacts_added      = true;


                SendInfoEmail(txtEmailAddr.Text, txtLogin.Text, txtPwd.Text);

                this.lblErrorMessage.Text = "An email has been sent with new login details.<br />When you receieve it, use the login link below.";
            }
        }
        catch (Exception ex)
        {
            if (!patient_added || !contacts_added)
            {
                // roll back - backwards of creation order

                if (Utilities.GetAddressType().ToString() == "Contact")
                {
                    ContactDB.Delete(phone_id);
                    ContactDB.Delete(email_id);
                }
                else if (Utilities.GetAddressType().ToString() == "ContactAus")
                {
                    ContactAusDB.Delete(phone_id);
                    ContactAusDB.Delete(email_id);
                }
                else
                {
                    throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                }

                RegisterPatientDB.Delete(register_patient_id);
                PatientDB.Delete(patient_id);
                PersonDB.Delete(person_id);

                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    UserDatabaseMapperDB.Delete(mainDbUserID);
                }

                if (ex is CustomMessageException)
                {
                    this.lblErrorMessage.Text = ex.Message;
                }
                else
                {
                    lblErrorMessage.Text = ex.ToString();
                }
            }
        }
        finally
        {
            //Session["DB"] = curDbName;
            //Session["SystemVariables"] = SystemVariableDB.GetAll();
            Session.Remove("DB");
            Session.Remove("SystemVariables");
        }
    }
Esempio n. 18
0
    // http://portal.mediclinic.com.au:803/Reconcilliations/TyroReconcilliation.aspx?pwd=mah_sms_reminder


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        try
        {
            string pwd = Request.Form["pwd"];

            if (pwd != null)  // sent by http post
            {
                if (pwd == null || pwd != System.Configuration.ConfigurationManager.AppSettings["SMSRunRemindersPwd"])
                {
                    throw new CustomMessageException("Incorrect password");
                }


                if (Session != null && Session["DB"] != null)
                {
                    throw new CustomMessageException("Can not run this while logged in.");
                }
                else
                {
                    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;
                        }

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

                Response.Write("Run Completed!");
            }
            else // send in url by http get
            {
                pwd = Request.QueryString["pwd"];
                if (pwd == null || pwd != System.Configuration.ConfigurationManager.AppSettings["SMSRunRemindersPwd"])
                {
                    throw new CustomMessageException("Incorrect password");
                }


                if (Session != null && Session["DB"] != null)
                {
                    Run();
                }
                else
                {
                    if (!Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseConfigDB"]))
                    {
                        throw new CustomMessageException("Can not run for logged out user where UseConfigDB = false");
                    }
                    else
                    {
                        Session["DB"] = System.Configuration.ConfigurationManager.AppSettings["Database"];
                        Session["SystemVariables"] = SystemVariableDB.GetAll();
                        Run();
                        Session.Remove("DB");
                        Session.Remove("SystemVariables");
                    }
                }
            }
        }
        catch (CustomMessageException ex)
        {
            Response.Write(ex.Message);
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + (ex.ToString()));
        }
    }
Esempio n. 19
0
    // http://localhost:2524/SMS/SendOverdueReminders.aspx?pwd=mah_sms_reminder
    // http://localhost:2524/SMS/SendOverdueReminders.aspx?pwd=mah_sms_reminder&inc_sending=false

    // http://portal.mediclinic.com.au:803/SMS/SendOverdueReminders.aspx?pwd=mah_sms_reminder
    // http://portal.mediclinic.com.au:803/SMS/SendOverdueReminders.aspx?pwd=mah_sms_reminder&inc_sending=false

    // can upload and let marcus add booking, view, mobile nbr, view, then try send to his nbr in aus...


    #region Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        try
        {
            string pwd = Request.Form["pwd"];

            if (pwd != null)  // sent by http post
            {
                if (pwd == null || pwd != System.Configuration.ConfigurationManager.AppSettings["SMSRunRemindersPwd"])
                {
                    throw new CustomMessageException("Incorrect password");
                }


                if (Session != null && Session["DB"] != null)
                {
                    Run(false, true);
                }
                else
                {
                    if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseConfigDB"]))
                    {
                        Session["DB"] = System.Configuration.ConfigurationManager.AppSettings["Database"];
                        Session["SystemVariables"] = SystemVariableDB.GetAll();
                        Run(false, true);
                        Session.Remove("DB");
                        Session.Remove("SystemVariables");
                    }
                    else // Get all DB's and run it on all of them
                    {
                        string logFile      = ConfigurationManager.AppSettings["SMSSender_Scheduled_LogFile" + "_" + System.Environment.MachineName];
                        string fileNameOnly = System.IO.Path.GetFileNameWithoutExtension(logFile);
                        string extension    = System.IO.Path.GetExtension(logFile);
                        string path         = System.IO.Path.GetDirectoryName(logFile);
                        logFile = System.IO.Path.Combine(path, string.Format("{0}({1})", fileNameOnly, "_2") + extension);


                        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;
                            }

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

                            Logger.WriteToFile("[" + DateTime.Now.ToString("dd MMM HH:mm:ss.fff") + "] " + "Starting SendOverdueReminders.aspx DB: " + databaseName + Environment.NewLine, logFile);

                            Run(false, true);

                            Logger.WriteToFile("[" + DateTime.Now.ToString("dd MMM HH:mm:ss.fff") + "] " + "Finished SendOverdueReminders.aspx DB: " + databaseName + Environment.NewLine, logFile);

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

                Response.Write("Run Completed!");
            }
            else // send in url by http get
            {
                pwd = Request.QueryString["pwd"];
                if (pwd == null || pwd != System.Configuration.ConfigurationManager.AppSettings["SMSRunRemindersPwd"])
                {
                    throw new CustomMessageException("Incorrect password");
                }


                string inc_sending = Request.QueryString["inc_sending"];
                if (inc_sending != null && inc_sending != "true" && inc_sending != "false")
                {
                    throw new CustomMessageException("Incorrect inc_sending value");
                }
                bool incSending = inc_sending != null && inc_sending == "true";


                string exceptionOutput = string.Empty;

                if (Session != null && Session["DB"] != null)
                {
                    string displayData = Run(true, incSending);
                    Response.Write(displayData);
                }
                else
                {
                    string displayData = "<center>" + Environment.NewLine;

                    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;
                        }

                        displayData += "<br /><h2>" + databaseName + "</h2>" + Environment.NewLine;

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

                            displayData += Run(true, incSending);
                        }
                        catch (Exception ex)
                        {
                            exceptionOutput += Environment.NewLine + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + " " + "DB: " + databaseName;
                            exceptionOutput += Environment.NewLine + ex.ToString();
                        }
                        finally
                        {
                            Session.Remove("DB");
                            Session.Remove("SystemVariables");
                        }
                    }

                    displayData += Environment.NewLine + "</center>";
                    displayData += exceptionOutput;
                    Response.Write(displayData.Replace("<br />", "<br />" + Environment.NewLine));
                }
            }
        }
        catch (CustomMessageException ex)
        {
            Response.Write(ex.Message);
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + (ex.ToString()));
        }
    }
Esempio n. 20
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();
        }
    }
    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);
        }
    }
Esempio n. 22
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>");
        }
    }
Esempio n. 23
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;
    }
    public static string Run(bool incDisplay, bool incSending, DateTime date)
    {
        if (incSending)
        {
            RunBirthdaysWithoutSMSorEmail();
        }

        date = date.Date;


        bool EnableBirthdaySMS    = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableBirthdaySMS").Value) == 1;
        bool EnableBirthdayEmails = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableBirthdayEmails").Value) == 1;


        Site[] sites = SiteDB.GetAll();

        Patient[] patients = PatientDB.GetBirthdays(date);
        Hashtable patientContactPhoneNbrHash = GetPatientPhoneNbrCache(patients);
        Hashtable patientContactEmailHash    = GetPatientEmailCache(patients);
        Hashtable patientRegOrgHash          = GetPatientRegOrgCache(patients);   // get a hash of patient reg to org


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


        string    callerId        = System.Configuration.ConfigurationManager.AppSettings["SMSTech_callerId"];           // not here used as the callerId will be the org name
        string    countryCode     = System.Configuration.ConfigurationManager.AppSettings["SMSTech_CountryCode"];
        ArrayList messagesToSMS   = new ArrayList();
        ArrayList messagesToEmail = 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 (Patient patient in patients)
        {
            // get all info to send via sms or email

            Site site = null;
            foreach (Site curSite in sites)
            {
                if ((patient.IsClinicPatient && curSite.SiteType.ID == 1) || (!patient.IsClinicPatient && curSite.SiteType.ID == 2))
                {
                    site = curSite;
                }
            }

            ArrayList orgs    = patientRegOrgHash[patient.PatientID] as ArrayList;
            string    orgText = (orgs == null || orgs.Count == 0 || orgs.Count > 1) ? site.Name : ((Organisation)orgs[0]).Name;


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

            string emailPatient = GetEmail(patientContactEmailHash, patient.Person.EntityID);

            string smsText          = GetSMSText(patient, site, patientRegOrgHash[patient.PatientID] as ArrayList);
            string emailText        = GetEmailText(patient, site, patientRegOrgHash[patient.PatientID] as ArrayList);
            string emailSubjectText = GetEmailSubjectText(patient, site, patientRegOrgHash[patient.PatientID] as ArrayList);



            // display the info

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

            output += "<tr>";
            output += tdTagStart + patient.PatientID + tdTagEnd;
            output += tdTagStart + patient.Person.Dob.ToString("dd-MM-yyyy") + tdTagEnd;
            output += tdTagStart + patient.Person.FullnameWithoutMiddlename + "<br />" +
                      (phoneNumPatient == null ? "-- No Mobile --" : "<u>" + phoneNumPatient + "</u>") + "<br />" +
                      (emailPatient == null ? "-- No Email --" : "<u>" + emailPatient + "</u>") + tdTagEnd;
            output += tdTagStartLeftAlign + (phoneNumPatient == null && emailPatient == null ? "" : "<u>" + emailSubjectText + "</u><br /><br />" + emailText) + tdTagEnd;
            output += "</tr>";

            countWithPatient++;



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

            if (EnableBirthdaySMS && phoneNumPatient != null && balance >= cost)
            {
                messagesToSMS.Add(new Tuple <int, decimal, string, string, string>(patient.PatientID, cost, phoneNumPatient, smsText, orgText));
                if (incSending)
                {
                    balance -= cost;
                }
            }
            if (EnableBirthdayEmails && emailPatient != null)
            {
                messagesToEmail.Add(new Tuple <int, string, string, string, string>(patient.PatientID, orgText, emailPatient, emailText, emailSubjectText));
            }
        }
        output += "</table>";


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

        if (incSending && patients.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>)));


            /*
             * 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; [with mobile: <b>" + messagesToSMS.Count + "</b>] &nbsp;&nbsp; [with email: <b>" + messagesToEmail.Count + "</b>] " + "<br /><br />" + output);
        }
        else
        {
            return(string.Empty);
        }
    }
Esempio n. 25
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();
        }
    }
Esempio n. 26
0
    private void LogIn(string login, string pwd)
    {
        try
        {
            Session.Remove("DB");
            if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
            {
                Session["DB"] = ConfigurationManager.AppSettings["Database"];
            }
            else // Get DB from Mediclinic_Main
            {
                UserDatabaseMapper user = UserDatabaseMapperDB.GetByLogin(login);
                if (user == null)
                {
                    this.FailureText.Text = "<div class=\"alert alert-danger\" runat=\"server\"><strong>Login Failed.</strong> Please ensure that your username and password are correct and try again.</div>";
                    return;
                }

                Session["DB"] = user.DBName;
            }



            Staff   staff              = StaffDB.GetByLogin(login);
            Patient patient            = PatientDB.GetByLogin(login);
            bool    allowPatientLogins = Convert.ToInt32(SystemVariableDB.GetByDescr("AllowPatientLogins").Value) == 1;
            bool    validStaff         = staff != null && staff.Pwd == pwd && !staff.IsFired;
            bool    validPatient       = allowPatientLogins && patient != null && patient.Pwd == pwd && !patient.IsDeleted;

            if (validStaff)
            {
                UserLogin curLogin = UserLoginDB.GetCurLoggedIn(staff.StaffID, -1, HttpContext.Current.Session.SessionID, -1);
                if (curLogin != null)
                {
                    UserLoginDB.UpdateLastAccessTime(curLogin.UserloginID, DateTime.Now, Request.RawUrl);
                    UserLoginDB.UpdateSetOtherSessionsOfThisUserLoggedOut(curLogin.UserloginID, staff.StaffID, -1);
                }
                else
                {
                    UserLoginDB.UpdateSetAllSessionsLoggedOut(staff.StaffID, -1);
                    UserLoginDB.Insert((staff == null) ? -1 : staff.StaffID, -1, login, -1, validStaff, HttpContext.Current.Session.SessionID, Request.UserHostAddress);
                }


                this.FailureText.Text = "";

                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;
                Session["NumDaysToDisplayOnBookingScreen"] = staff.NumDaysToDisplayOnBookingScreen;
                Session["HideBookingNotes"] = staff.HideBookingNotes;
                Session["ShowOtherProvidersOnBookingScreen"] = false;
                Session["ShowHeaderOnBookingScreen"]         = staff.ShowHeaderOnBookingScreen;
                Session["SystemVariables"] = SystemVariableDB.GetAll();
                Session["OfferingColors"]  = OfferingDB.GetColorCodes();
                System.Web.Security.FormsAuthentication.SetAuthCookie("--", true);  // needed to use forms authentication


                UserView userView = UserView.GetInstance();

                Site[] allowedSites = StaffSiteRestrictionDB.GetSitesNotRestricted(staff.StaffID, -1, false);


                //
                // until aged care is running, remove aged care from display
                //

                /*
                 * System.Collections.ArrayList list = new System.Collections.ArrayList();
                 * for (int i = 0; i < allowedSites.Length; i++)
                 *  if (allowedSites[i].SiteType.ID == 1 || Utilities.IsDev())
                 *      list.Add(allowedSites[i]);
                 * allowedSites = (Site[])list.ToArray(typeof(Site));
                 */

                Site[] allSites = SiteDB.GetAll();
                if (allowedSites.Length == 0 && allSites.Length == 1)
                {
                    Session["SiteID"]          = allSites[0].SiteID;
                    Session["SiteName"]        = allSites[0].Name;
                    Session["IsMultipleSites"] = false;
                    Session["SiteIsClinic"]    = allSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"]  = allSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]        = allSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]      = allSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]   = allSites[0].SiteType.Descr;

                    UserLoginDB.UpdateSite(staff.StaffID, -1, allSites[0].SiteID);

                    if (!userView.IsAdminView)        // need to choose org
                    {
                        if (Session["OrgID"] == null) // providers need to select an org, need to choose one
                        {
                            Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                            return;
                        }
                    }
                }



                if (allowedSites.Length == 1)
                {
                    Session["SiteID"]          = allowedSites[0].SiteID;
                    Session["SiteName"]        = allowedSites[0].Name;
                    Session["IsMultipleSites"] = false;
                    Session["SiteIsClinic"]    = allowedSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"]  = allowedSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]        = allowedSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]      = allowedSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]   = allowedSites[0].SiteType.Descr;

                    UserLoginDB.UpdateSite(staff.StaffID, -1, allowedSites[0].SiteID);

                    if (!userView.IsAdminView)        // need to choose org
                    {
                        if (Session["OrgID"] == null) // providers need to select an org, need to choose one
                        {
                            Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                            return;
                        }
                    }
                }
                else // if more than one site, go to choose. if no sites this page will say to contact admin
                {
                    if (Session["SiteID"] == null)  // admins if yet to login to a site, need to choose one
                    {
                        Session["IsMultipleSites"] = true;
                        Response.Redirect("~/Account/SelectSiteV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }



                /*
                 *
                 * if (!staff.IsAdmin)
                 * {
                 *  // provs only login to clinic site
                 *  Site site = SiteDB.GetByID(2);
                 *  Session["SiteID"]   = site.SiteID;
                 *  Session["SiteName"] = site.Name;
                 *
                 *  if (Session["OrgID"] == null)  // providers et to login to select an org, need to choose one
                 *  {
                 *      if (Request.QueryString["from_url"] != null)
                 *      {
                 *          Response.Redirect("~/Account/SelectOrgV2.aspx?" + Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=")), false);
                 *          return;
                 *      }
                 *      else
                 *      {
                 *          Response.Redirect("~/Account/SelectOrgV2.aspx", false);
                 *          return;
                 *      }
                 *  }
                 * }
                 * else
                 * {
                 *  if (Session["SiteID"] == null)  // admins if yet to login to a site, need to choose one
                 *  {
                 *      if (Request.QueryString["from_url"] != null)
                 *      {
                 *          Response.Redirect("~/Account/SelectSiteV2.aspx?" + Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=")), false);
                 *          return;
                 *      }
                 *      else
                 *      {
                 *          Response.Redirect("~/Account/SelectSiteV2.aspx", false);
                 *          return;
                 *      }
                 *  }
                 * }
                 *
                 */

                if (Request.QueryString["from_url"] != null)
                {
                    Response.Redirect(Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)), false);
                    return;
                }
                else
                {
                    Response.Redirect(Convert.ToInt32(Session["StaffID"]) >= 0 ? "~/Default.aspx" : "~/StaffLoginsV2.aspx", false);
                    return;
                }
            }
            else if (validPatient)
            {
                UserLogin curLogin = UserLoginDB.GetCurLoggedIn(-1, patient.PatientID, HttpContext.Current.Session.SessionID, -1);
                if (curLogin != null)
                {
                    UserLoginDB.UpdateLastAccessTime(curLogin.UserloginID, DateTime.Now, Request.RawUrl);
                    UserLoginDB.UpdateSetOtherSessionsOfThisUserLoggedOut(curLogin.UserloginID, -1, patient.PatientID);
                }
                else
                {
                    UserLoginDB.UpdateSetAllSessionsLoggedOut(-1, patient.PatientID);
                    UserLoginDB.Insert(-1, (patient == null) ? -1 : patient.PatientID, login, -1, validPatient, HttpContext.Current.Session.SessionID, Request.UserHostAddress);
                }


                this.FailureText.Text = "";

                Session["IsLoggedIn"]    = true;
                Session["IsStakeholder"] = false;
                Session["IsMasterAdmin"] = false;
                Session["IsAdmin"]       = false;
                Session["IsPrincipal"]   = false;
                Session["IsProvider"]    = false;
                Session["IsExternal"]    = false;
                Session["PatientID"]     = patient.PatientID;
                Session["StaffFullnameWithoutMiddlename"] = patient.Person.FullnameWithoutMiddlename;
                Session["StaffFirstname"] = patient.Person.Firstname;
                Session["NumDaysToDisplayOnBookingScreen"]   = 3;
                Session["ShowOtherProvidersOnBookingScreen"] = false;
                Session["ShowHeaderOnBookingScreen"]         = true;
                Session["SystemVariables"] = SystemVariableDB.GetAll();
                Session["OfferingColors"]  = OfferingDB.GetColorCodes();
                System.Web.Security.FormsAuthentication.SetAuthCookie("--", true);  // needed to use forms authentication


                Site[] allSites     = SiteDB.GetAll();
                Site[] allowedSites = SiteDB.GetAll();


                //
                // remove aged care from display
                //
                System.Collections.ArrayList list = new System.Collections.ArrayList();
                for (int i = 0; i < allSites.Length; i++)
                {
                    if (allSites[i].SiteType.ID == 1)
                    {
                        list.Add(allSites[i]);
                    }
                }
                allowedSites = (Site[])list.ToArray(typeof(Site));

                if (allowedSites.Length == 0 && allSites.Length == 1)
                {
                    Session["SiteID"]         = allSites[0].SiteID;
                    Session["SiteName"]       = allSites[0].Name;
                    Session["SiteIsClinic"]   = allSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"] = allSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]       = allSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]     = allSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]  = allSites[0].SiteType.Descr;


                    UserLoginDB.UpdateSite(-1, patient.PatientID, allSites[0].SiteID);

                    if (Session["OrgID"] == null)  // providers, ext staff, patient logins need to select an org, need to choose one
                    {
                        if (Request.QueryString["from_url"] != null)
                        {
                            string from_url = Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9));
                            if (from_url.Contains("BookingsV2.aspx?") && from_url.Contains("orgs="))
                            {
                                Uri    theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + from_url);
                                string orgs       = HttpUtility.ParseQueryString(theRealURL.Query).Get("orgs");
                                if (Regex.IsMatch(orgs, @"^\d+$"))
                                {
                                    Organisation org = OrganisationDB.GetByID(Convert.ToInt32(orgs));
                                    if (org != null)
                                    {
                                        Session["OrgID"]   = org.OrganisationID.ToString();
                                        Session["OrgName"] = org.Name;
                                        Response.Redirect(from_url, false);
                                        return;
                                    }
                                }
                            }
                        }


                        Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }

                if (allowedSites.Length == 1)
                {
                    Session["SiteID"]         = allowedSites[0].SiteID;
                    Session["SiteName"]       = allowedSites[0].Name;
                    Session["SiteIsClinic"]   = allowedSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"] = allowedSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]       = allowedSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]     = allowedSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]  = allowedSites[0].SiteType.Descr;

                    UserLoginDB.UpdateSite(-1, patient.PatientID, allowedSites[0].SiteID);

                    if (Session["OrgID"] == null)  // providers need to select an org, need to choose one
                    {
                        if (Request.QueryString["from_url"] != null)
                        {
                            string from_url = Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9));
                            if (from_url.Contains("BookingsV2.aspx?") && from_url.Contains("orgs="))
                            {
                                Uri    theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + from_url);
                                string orgs       = HttpUtility.ParseQueryString(theRealURL.Query).Get("orgs");
                                if (Regex.IsMatch(orgs, @"^\d+$"))
                                {
                                    Organisation org = OrganisationDB.GetByID(Convert.ToInt32(orgs));
                                    if (org != null)
                                    {
                                        Session["OrgID"]   = org.OrganisationID.ToString();
                                        Session["OrgName"] = org.Name;
                                        Response.Redirect(from_url, false);
                                        return;
                                    }
                                }
                            }
                        }

                        Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }
                else // if more than one site, go to choose. if no sites this page will say to contact admin
                {
                    if (Session["SiteID"] == null)  // admins if yet to login to a site, need to choose one
                    {
                        Response.Redirect("~/Account/SelectSiteV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }


                if (Request.QueryString["from_url"] != null)
                {
                    Response.Redirect(Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)), false);
                    return;
                }
                else
                {
                    Response.Redirect(Convert.ToInt32(Session["StaffID"]) >= 0 ? "~/Default.aspx" : "~/StaffLoginsV2.aspx", false);
                    return;
                }
            }

            else
            {
                //UserLoginDB.Insert((staff == null) ? -1 : staff.StaffID, login, -1, validStaff, HttpContext.Current.Session.SessionID, Request.UserHostAddress);
                this.FailureText.Text = "Login Failed.";
            }
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
            if (Utilities.IsDev())
            {
                FailureText.Text = ex.ToString();
            }
            else
            {
                throw;
            }
        }
    }
Esempio n. 27
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();
        }
    }
Esempio n. 28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        string previousDB = Session == null || Session["DB"] == null ? null : (string)Session["DB"];

        try
        {
            string db = Request.QueryString["db"];
            if (db == null || !Regex.IsMatch(db, @"^Mediclinic_\d{4}$"))
            {
                throw new CustomMessageException("Invalid URL Parameter: db");
            }

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


            string letter_id = Request.QueryString["letter_id"];
            if (letter_id == null || !Regex.IsMatch(letter_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException("Invalid URL Parameter: letter_id");
            }

            string keep_history_in_db = Request.QueryString["keep_history_in_db"];
            if (keep_history_in_db == null || (keep_history_in_db != "0" && keep_history_in_db != "1"))
            {
                throw new CustomMessageException("Invalid URL Parameter: keep_history_in_db");
            }

            string keep_history_in_file = Request.QueryString["keep_history_in_file"];
            if (keep_history_in_file == null || (keep_history_in_file != "0" && keep_history_in_file != "1"))
            {
                throw new CustomMessageException("Invalid URL Parameter: keep_history_in_file");
            }

            string send_method_id = Request.QueryString["send_method_id"];
            if (send_method_id == null || !Regex.IsMatch(send_method_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException("Invalid URL Parameter: send_method_id");
            }

            string site_id = Request.QueryString["site_id"];
            if (site_id == null || !Regex.IsMatch(site_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException("Invalid URL Parameter: site_id");
            }

            string org_id = Request.QueryString["org_id"];
            if (org_id == null || !Regex.IsMatch(org_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException("Invalid URL Parameter: org_id");
            }

            string bk_id = Request.QueryString["bk_id"];
            if (bk_id == null || !Regex.IsMatch(bk_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException("Invalid URL Parameter: bk_id");
            }

            string pt_id = Request.QueryString["pt_id"];
            if (pt_id == null || !Regex.IsMatch(pt_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException("Invalid URL Parameter: pt_id");
            }

            string reg_ref_id = Request.QueryString["reg_ref_id"];
            if (reg_ref_id == null || !Regex.IsMatch(reg_ref_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException("Invalid URL Parameter: reg_ref_id");
            }

            string staff_id = Request.QueryString["staff_id"];
            if (staff_id == null || !Regex.IsMatch(staff_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException("Invalid URL Parameter: staff_id");
            }

            string hc_action_id = Request.QueryString["hc_action_id"];
            if (hc_action_id == null || !Regex.IsMatch(hc_action_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException("Invalid URL Parameter: hc_action_id");
            }

            string source_path = Request.QueryString["source_path"];
            if (source_path == null)
            {
                throw new CustomMessageException("Invalid URL Parameter: source_path");
            }

            string dest_path = Request.QueryString["dest_path"];
            if (dest_path == null)
            {
                throw new CustomMessageException("Invalid URL Parameter: dest_path");
            }

            string dbl_sided_printing = Request.QueryString["dbl_sided_printing"];
            if (dbl_sided_printing == null || (dbl_sided_printing != "1" && dbl_sided_printing != "0"))
            {
                throw new CustomMessageException("Invalid URL Parameter: dbl_sided_printing");
            }


            Site site = SiteDB.GetByID(Convert.ToInt32(site_id));
            if (site == null)
            {
                throw new CustomMessageException("Invalid URL Parameter: site_id");
            }

            Letter letter = LetterDB.GetByID(Convert.ToInt32(letter_id));
            if (letter == null)
            {
                throw new CustomMessageException("Invalid URL Parameter: letter_id");
            }



            // create doc for that org-patient relation
            string tmpSingleFileName = Letter.CreateMergedDocument(
                Convert.ToInt32(letter_id),
                keep_history_in_db == "1",
                keep_history_in_file == "1",
                Convert.ToInt32(send_method_id),
                Letter.GetLettersHistoryDirectory(Convert.ToInt32(org_id)),
                letter.Docname.Replace(".dot", ".doc"),
                site,
                Convert.ToInt32(org_id),
                Convert.ToInt32(bk_id),
                Convert.ToInt32(pt_id),
                Convert.ToInt32(reg_ref_id), // register_referrer_id_to_use_instead_of_patients_reg_ref
                Convert.ToInt32(staff_id),
                Convert.ToInt32(hc_action_id),
                source_path,
                dest_path,
                dbl_sided_printing == "1");



            Response.Write("Success: " + tmpSingleFileName);
        }
        catch (CustomMessageException ex)
        {
            Response.Write(ex.Message);
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + (Utilities.IsDev() ? ex.ToString() : "please contact system administrator."));
        }
        finally
        {
            if (previousDB == null)
            {
                Session.Remove("DB");
                Session.Remove("SystemVariables");
            }
            else
            {
                Session["DB"] = previousDB;
                Session["SystemVariables"] = SystemVariableDB.GetAll();
            }
        }
    }