Пример #1
0
    protected static Hashtable GetPatientEmailCache(Patient[] patients)
    {
        ArrayList entityIDArrayList = new ArrayList();

        foreach (Patient patient in patients)
        {
            entityIDArrayList.Add(patient.Person.EntityID);
        }
        int[] entityIDs = (int[])entityIDArrayList.ToArray(typeof(int));

        Hashtable contactHash = PatientsContactCacheDB.GetBullkEmail(entityIDs, -1);

        return(contactHash);
    }
    protected static Hashtable GetOrgAddrCache(Booking[] bookings)
    {
        ArrayList entityIDArrayList = new ArrayList();

        foreach (Booking curBooking in bookings)
        {
            if (curBooking.Organisation != null)
            {
                entityIDArrayList.Add(curBooking.Organisation.EntityID);
            }
        }
        int[]     entityIDs   = (int[])entityIDArrayList.ToArray(typeof(int));
        Hashtable contactHash = PatientsContactCacheDB.GetBullkAddress(entityIDs, -1);

        return(contactHash);
    }
    protected static Hashtable GetPatientEmailCache(Booking[] bookings)
    {
        ArrayList entityIDArrayList = new ArrayList();

        foreach (Booking curBooking in bookings)
        {
            if (curBooking.Patient != null)
            {
                entityIDArrayList.Add(curBooking.Patient.Person.EntityID);
            }
        }
        int[] entityIDs = (int[])entityIDArrayList.ToArray(typeof(int));

        Hashtable contactHash = PatientsContactCacheDB.GetBullkEmail(entityIDs, -1);

        return(contactHash);
    }
    public static void GetCountsByEmailMobile(
        RegisterReferrer[] regRefs,
        ref int hasBothMobileEmail,
        ref int hasMobileNoEmail,
        ref int hasEmailNoMobile,
        ref int hasNeitherMobileEmail)
    {
        int[]     regRefIDs    = regRefs.Select(r => r.RegisterReferrerID).ToArray();
        int[]     entityIDs    = regRefs.Select(r => r.Organisation.EntityID).ToArray();
        Hashtable entityIDHash = RegisterReferrerDB.GetOrgEntityIDsHash(regRefIDs);
        Hashtable regRefIDHash = RegisterReferrerDB.GetByIDsInHashtable(regRefIDs);
        Hashtable emailHash    = PatientsContactCacheDB.GetBullkEmail(entityIDs, -1);
        Hashtable mobileHash   = PatientsContactCacheDB.GetBullkPhoneNumbers(entityIDs, -1, "30");

        hasBothMobileEmail    = 0;
        hasMobileNoEmail      = 0;
        hasEmailNoMobile      = 0;
        hasNeitherMobileEmail = 0;

        for (int i = 0; i < regRefs.Length; i++)
        {
            bool hasEmail  = emailHash[regRefs[i].Organisation.EntityID] != null;
            bool hasMobile = mobileHash[regRefs[i].Organisation.EntityID] != null;

            if (hasEmail && hasMobile)
            {
                hasBothMobileEmail++;
            }
            if (!hasEmail && hasMobile)
            {
                hasMobileNoEmail++;
            }
            if (hasEmail && !hasMobile)
            {
                hasEmailNoMobile++;
            }
            if (!hasEmail && !hasMobile)
            {
                hasNeitherMobileEmail++;
            }
        }
    }
    public static RegisterReferrer[] RemoveRegisterReferrersByEmailMobile(
        RegisterReferrer[] regRefs,
        bool incHasBothMobileEmail,
        bool incHasMobileNoEmail,
        bool incHasEmailNoMobile,
        bool incHasNeitherMobileEmail)
    {
        if (incHasBothMobileEmail && incHasMobileNoEmail && incHasEmailNoMobile && incHasNeitherMobileEmail)
        {
            return(regRefs);
        }
        if (!incHasBothMobileEmail && !incHasMobileNoEmail && !incHasEmailNoMobile && !incHasNeitherMobileEmail)
        {
            return new RegisterReferrer[] { }
        }
        ;

        int[]     regRefIDs    = regRefs.Select(r => r.RegisterReferrerID).ToArray();
        int[]     entityIDs    = regRefs.Select(r => r.Organisation.EntityID).ToArray();
        Hashtable entityIDHash = RegisterReferrerDB.GetOrgEntityIDsHash(regRefIDs);
        Hashtable regRefIDHash = RegisterReferrerDB.GetByIDsInHashtable(regRefIDs);
        Hashtable emailHash    = PatientsContactCacheDB.GetBullkEmail(entityIDs, -1);
        Hashtable mobileHash   = PatientsContactCacheDB.GetBullkPhoneNumbers(entityIDs, -1, "30");

        ArrayList newList = new ArrayList();

        for (int i = 0; i < regRefs.Length; i++)
        {
            bool hasEmail  = emailHash[regRefs[i].Organisation.EntityID] != null;
            bool hasMobile = mobileHash[regRefs[i].Organisation.EntityID] != null;

            if ((incHasBothMobileEmail && hasEmail && hasMobile) ||
                (incHasMobileNoEmail && !hasEmail && hasMobile) ||
                (incHasEmailNoMobile && hasEmail && !hasMobile) ||
                (incHasNeitherMobileEmail && !hasEmail && !hasMobile))
            {
                newList.Add(regRefs[i]);
            }
        }

        return((RegisterReferrer[])newList.ToArray(typeof(RegisterReferrer)));
    }
Пример #6
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();
        }
    }
Пример #7
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>");
        }
    }
Пример #8
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();
        }
    }
Пример #9
0
    protected void FillGrid()
    {
        string searchName = "";

        if (Request.QueryString["name_search"] != null && Request.QueryString["name_search"].Length > 0)
        {
            searchName         = Request.QueryString["name_search"];
            txtSearchName.Text = Request.QueryString["name_search"];
        }
        bool searchNameOnlyStartsWith = true;

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

        int orgID = 0;

        if (Request.QueryString["org"] != null && Regex.IsMatch(Request.QueryString["org"], @"\d{1,10}") && OrganisationDB.Exists(Convert.ToInt32(Request.QueryString["org"])))
        {
            orgID = Convert.ToInt32(Request.QueryString["org"]);
        }

        // get count
        Hashtable countHash        = new Hashtable();
        Hashtable countDeletedHash = new Hashtable();
        DataTable dt_reg_refs      = RegisterReferrerDB.GetDataTable(orgID, -1, true, new int[] { 191 }, "", false, "", "", "", false);

        foreach (DataRow row in dt_reg_refs.Rows)
        {
            int org_id = Convert.ToInt32(row["organisation_id"]);

            if (!Convert.ToBoolean(row["is_deleted"]))
            {
                countHash[org_id] = (countHash[org_id] == null) ? 1 : ((int)countHash[org_id]) + 1;
            }
            else
            {
                countDeletedHash[org_id] = (countDeletedHash[org_id] == null) ? 1 : ((int)countDeletedHash[org_id]) + 1;
            }
        }


        DataTable dt = null;

        if (Request.QueryString["referrer"] == null)
        {
            dt = OrganisationDB.GetDataTable(orgID, chkShowDeleted.Checked, true, true, true, true, false, searchName, searchNameOnlyStartsWith, "191");

            dt.Columns.Add("count", typeof(Int32));
            dt.Columns.Add("count_deleted", typeof(Int32));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int org_id = Convert.ToInt32(dt.Rows[i]["organisation_id"]);
                dt.Rows[i]["count"]         = countHash[org_id] == null ? 0 : (int)countHash[org_id];
                dt.Rows[i]["count_deleted"] = countDeletedHash[org_id] == null ? 0 : (int)countDeletedHash[org_id];
            }
        }
        else
        {
            if (!Regex.IsMatch(Request.QueryString["referrer"], @"^\d+$"))
            {
                HideTableAndSetErrorMessage("Invalid url referrer");
                return;
            }
            Referrer referrer = ReferrerDB.GetByID(Convert.ToInt32(Request.QueryString["referrer"]));
            if (referrer == null)
            {
                HideTableAndSetErrorMessage("Invalid url referrer");
                return;
            }

            lblHeading.Text = "Referrer Clinics of " + referrer.Person.FullnameWithoutMiddlename;

            dt = RegisterReferrerDB.GetDataTable_OrganisationsOf(referrer.ReferrerID, true, chkShowDeleted.Checked, searchName, searchNameOnlyStartsWith);

            dt.Columns.Add("is_deleted", typeof(Boolean));
            dt.Columns.Add("entity_id", typeof(Int32));
            dt.Columns.Add("count", typeof(Int32));
            dt.Columns.Add("count_deleted", typeof(Int32));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int org_id = Convert.ToInt32(dt.Rows[i]["organisation_id"]);
                dt.Rows[i]["count"]         = countHash[org_id] == null ? 0 : (int)countHash[org_id];
                dt.Rows[i]["count_deleted"] = countDeletedHash[org_id] == null ? 0 : (int)countDeletedHash[org_id];

                // update these so when delete/undelete - it removes the connection, not the org
                dt.Rows[i]["organisation_id"] = dt.Rows[i]["register_referrer_id"];
                dt.Rows[i]["is_deleted"]      = dt.Rows[i]["register_referrer_is_deleted"];
                dt.Rows[i]["entity_id"]       = dt.Rows[i]["organisation_entity_id"];
            }
        }



        // add suburb_name

        Hashtable entityIDsHash = new Hashtable();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            entityIDsHash[Convert.ToInt32(dt.Rows[i]["entity_id"])] = 1;
        }

        int[] entityIDs = new int[entityIDsHash.Keys.Count];
        entityIDsHash.Keys.CopyTo(entityIDs, 0);

        Hashtable emailHash = PatientsContactCacheDB.GetBullkAddress(entityIDs, -1);

        dt.Columns.Add("suburb_name", typeof(string));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            int    entityID   = Convert.ToInt32(dt.Rows[i]["entity_id"]);
            string suburbName = GetSuburb(emailHash, entityID);
            dt.Rows[i]["suburb_name"] = suburbName == null ? "" : suburbName;
        }



        Session["referrerinfoclinic_data"] = dt;

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


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

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

        if (Request.QueryString["referrer"] != null)
        {
            GrdReferrer.FooterRow.Visible = false;
            GrdReferrer.Columns[GrdReferrer.Columns.Count - 2].Visible = false;
        }
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        try
        {
            decimal smsBalance = SMSCreditDataDB.GetTotal() - SMSHistoryDataDB.GetTotal();
            decimal smsCost    = Convert.ToDecimal(SystemVariableDB.GetByDescr("SMSPrice").Value);

            int maxSMSCountCanAfford = smsCost == 0 ? 1000000 : (int)(smsBalance / smsCost);
            int smsCountSending      = 0;


            //
            // Start Validation
            //

            txtEmailSubject.Text     = txtEmailSubject.Text.Trim();
            txtEmailForPrinting.Text = txtEmailForPrinting.Text.Trim();
            txtSMSText.Text          = txtSMSText.Text.Trim();


            bool printSelected = (ddlBothMobileAndEmail.SelectedValue == "1" || ddlEmailNoMobile.SelectedValue == "1" ||
                                  ddlMobileNoEmail.SelectedValue == "1" || ddlNeitherMobileOrEmail.SelectedValue == "1");
            bool emailSelected = (ddlBothMobileAndEmail.SelectedValue == "2" || ddlEmailNoMobile.SelectedValue == "2" ||
                                  ddlMobileNoEmail.SelectedValue == "2" || ddlNeitherMobileOrEmail.SelectedValue == "2");
            bool smsSelected = (ddlBothMobileAndEmail.SelectedValue == "3" || ddlEmailNoMobile.SelectedValue == "3" ||
                                ddlMobileNoEmail.SelectedValue == "3" || ddlNeitherMobileOrEmail.SelectedValue == "3");


            string validationErrors = string.Empty;

            if (printSelected)
            {
                if (txtEmailForPrinting.Text.Length == 0)
                {
                    validationErrors += "<li>Printed Batch Letters Email Address To Send To can not be empty.</li>";
                }
                else if (!Utilities.IsValidEmailAddress(txtEmailForPrinting.Text))
                {
                    validationErrors += "<li>Printed Batch Letters Email Address To Send To must look like a valid email address.</li>";
                }
            }
            if (emailSelected)
            {
                if (txtEmailSubject.Text.Length == 0)
                {
                    validationErrors += "<li>Email Subject can not be empty.</li>";
                }
                if (FreeTextBox1.Text.Length == 0)
                {
                    validationErrors += "<li>Email Text can not be empty.</li>";
                }
            }
            if (smsSelected)
            {
                if (smsCost > 0 && smsBalance == 0)
                {
                    validationErrors += "<li>Can not send SMS's - your SMS balance is empty. Please topup or unselect sending by SMS.</li>";
                }
                else if (txtSMSText.Text.Length == 0)
                {
                    validationErrors += "<li>SMS Text can not be empty.</li>";
                }
            }

            if (validationErrors.Length > 0)
            {
                throw new CustomMessageException("<ul>" + validationErrors + "</ul>");
            }

            //
            // End Validation
            //



            //
            // get hashtables of those with mobiles and emails
            //

            ArrayList regRefIDsArr = new ArrayList();


            foreach (ListItem referrerItem in lstReferrers.Items)  // regrefid
            {
                if (referrerItem.Selected)
                {
                    regRefIDsArr.Add(Convert.ToInt32(referrerItem.Value));
                }
            }


            int[]     regRefIDs    = (int[])regRefIDsArr.ToArray(typeof(int));
            int[]     entityIDs    = RegisterReferrerDB.GetOrgEntityIDs(regRefIDs);
            Hashtable entityIDHash = RegisterReferrerDB.GetOrgEntityIDsHash(regRefIDs);
            Hashtable regRefIDHash = RegisterReferrerDB.GetByIDsInHashtable(regRefIDs);

            Hashtable emailHash  = PatientsContactCacheDB.GetBullkEmail(entityIDs, -1);
            Hashtable mobileHash = PatientsContactCacheDB.GetBullkPhoneNumbers(entityIDs, -1, "30");

            string email_from_address = ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromEmail"].Value;
            string email_from_name    = ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromName"].Value;

            //bool StoreLettersHistoryInDB       = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["StoreLettersHistoryInDB"]);
            //bool StoreLettersHistoryInFlatFile = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["StoreLettersHistoryInFlatFile"]);
            bool StoreLettersHistoryInDB       = false; // don't store bulk marketing letters
            bool StoreLettersHistoryInFlatFile = false; // don't store bulk marketing letters



            //
            // ok start the sending process
            //


            int bulkLetterSendingQueueBatchID = UseBulkLetterSender ? BulkLetterSendingQueueBatchDB.Insert(txtEmailForPrinting.Text, false) : -1;


            // TODO: Send Letter By Email
            int letterPrintHistorySendMethodID = 1; // send by mail


            // make sure at least one referrer selected
            if (lstReferrers.GetSelectedIndices().Length == 0)
            {
                throw new CustomMessageException("Please select at least one referrer.");
            }

            // make sure at least one letter selected
            if (lstLetters.GetSelectedIndices().Length == 0)
            {
                throw new CustomMessageException("Please select a letter.");
            }


            // get letter and make sure it exists
            Letter letter             = LetterDB.GetByID(Convert.ToInt32(lstLetters.SelectedValue));
            string sourchTemplatePath = letter.GetFullPath(Convert.ToInt32(Session["SiteID"]));
            if (!File.Exists(sourchTemplatePath))
            {
                throw new CustomMessageException("File doesn't exist.");
            }

            // get temp directory
            string tmpLettersDirectory = Letter.GetTempLettersDirectory();
            if (!Directory.Exists(tmpLettersDirectory))
            {
                throw new CustomMessageException("Temp letters directory doesn't exist");
            }

            // delete old tmp files
            FileHelper.DeleteOldFiles(tmpLettersDirectory, new TimeSpan(1, 0, 0));



            // create individual merged docs and put into list of docsToMerge - only if there is an org-patient relationship
            ArrayList docsToMerge = new ArrayList();

            Site site    = SiteDB.GetByID(Convert.ToInt32(Session["SiteID"]));
            int  StaffID = Convert.ToInt32(Session["StaffID"]);
            foreach (ListItem referrerItem in lstReferrers.Items)
            {
                if (!referrerItem.Selected)
                {
                    continue;
                }

                if (UseBulkLetterSender)
                {
                    int        refEntityID    = (int)entityIDHash[Convert.ToInt32(referrerItem.Value)];
                    string     refPhoneNumber = GetPhoneNbr(mobileHash, refEntityID, true);
                    string     refEmail       = GetEmail(emailHash, refEntityID);
                    SendMethod sendMethod     = GetSendMethod(refEmail != null, refPhoneNumber != null);

                    RegisterReferrer regRef = RegisterReferrerDB.GetByID(Convert.ToInt32(referrerItem.Value));

                    if (sendMethod != SendMethod.None)
                    {
                        string text = string.Empty;
                        if (sendMethod == SendMethod.SMS)
                        {
                            text = txtSMSText.Text;
                        }
                        if (sendMethod == SendMethod.Email)
                        {
                            text = FreeTextBox1.Text;
                        }

                        text = ReplaceMergeFields(text, regRefIDHash, Convert.ToInt32(referrerItem.Value));

                        bool generateLetter = false;
                        if (sendMethod == SendMethod.SMS)
                        {
                            generateLetter = false;
                        }
                        if (sendMethod == SendMethod.Email)
                        {
                            generateLetter = lstLetters.GetSelectedIndices().Length != 0;
                        }
                        if (sendMethod == SendMethod.Print)
                        {
                            generateLetter = true;
                        }


                        if (sendMethod == SendMethod.SMS)  // copy to other methods!!
                        {
                            smsCountSending++;
                        }


                        BulkLetterSendingQueueDB.Insert
                        (
                            bulkLetterSendingQueueBatchID,
                            (int)sendMethod,                                              // bulk_letter_sending_queue_method_id
                            StaffID,                                                      // added_by
                            -1,                                                           // patient_id
                            regRef.Referrer.ReferrerID,                                   // referrer_id
                            -1,                                                           // booking_id
                            (sendMethod == SendMethod.SMS)   ? refPhoneNumber       : "", // phone_number
                            (sendMethod == SendMethod.Email) ? refEmail             : "", // email_to_address
                            "",                                                           // email_to_name
                            (sendMethod == SendMethod.Email) ? email_from_address   : "", // email_from_address
                            (sendMethod == SendMethod.Email) ? email_from_name      : "", // email_from_name
                            text,                                                         // text
                            (sendMethod == SendMethod.Email) ? txtEmailSubject.Text : "", // email_subject
                            "",                                                           // email_attachment_location
                            false,                                                        // email_attachment_delete_after_sending
                            false,                                                        // email_attachment_folder_delete_after_sending

                            !generateLetter ? -1    : letter.LetterID,
                            !generateLetter ? false : chkKeepInHistory.Checked && StoreLettersHistoryInDB,
                            !generateLetter ? false : chkKeepInHistory.Checked && StoreLettersHistoryInFlatFile,
                            !generateLetter ? -1    : letterPrintHistorySendMethodID,
                            !generateLetter ? ""    : Letter.GetLettersHistoryDirectory(0),
                            !generateLetter ? ""    : letter.Docname.Replace(".dot", ".doc"),
                            !generateLetter ? -1    : site.SiteID,
                            0,                                                             // organisation_id
                            -1,                                                            // booking id
                            -1,                                                            // patient_id

                            !generateLetter ? -1    : Convert.ToInt32(referrerItem.Value), // register_referrer_id_to_use_instead_of_patients_reg_ref
                            !generateLetter ? -1    : StaffID,
                            -1,                                                            //healthcardactionid
                            !generateLetter ? ""    : sourchTemplatePath,
                            !generateLetter ? ""    : tmpLettersDirectory + letter.Docname.Replace(".dot", ".doc"),
                            !generateLetter ? false : true,

                            "",    // email_letter_extra_pages
                            "",    // email_letter_item_seperator
                            "",    // sql_to_run_on_completion
                            ""     // sql_to_run_on_failure
                        );
                    }
                }
                else
                {
                    // create doc
                    string tmpSingleFileName = Letter.CreateMergedDocument(
                        letter.LetterID,
                        chkKeepInHistory.Checked && StoreLettersHistoryInDB,
                        chkKeepInHistory.Checked && StoreLettersHistoryInFlatFile,
                        letterPrintHistorySendMethodID,
                        Letter.GetLettersHistoryDirectory(0),
                        letter.Docname.Replace(".dot", ".doc"),
                        site,
                        0,  // org id
                        -1, // booking id
                        -1, // patient id
                        Convert.ToInt32(referrerItem.Value),
                        StaffID,
                        -1, //healthcardactionid
                        sourchTemplatePath,
                        tmpLettersDirectory + letter.Docname.Replace(".dot", ".doc"),
                        true);

                    // record name of merged doc
                    docsToMerge.Add(tmpSingleFileName);
                }
            }


            if (UseBulkLetterSender)
            {
                if ((smsCountSending * smsCost) > smsBalance)
                {
                    BulkLetterSendingQueueDB.DeleteByBatchID(bulkLetterSendingQueueBatchID);
                    BulkLetterSendingQueueBatchDB.Delete(bulkLetterSendingQueueBatchID);

                    SetErrorMessage("Not Enough Credit To Send SMS's. Please Top Up You SMS Credit or Choose Methods Other Than SMS.");
                    return;
                }

                BulkLetterSendingQueueBatchDB.UpdateReadyToProcess(bulkLetterSendingQueueBatchID, true);
                SetErrorMessage("Items Added To Sending Queue. View Details <a href='/Letters_PrintBatch_StatusV2.aspx?batch_id=" + bulkLetterSendingQueueBatchID + "'>Here</a>");
            }
            else
            {
                // merge all tmp files
                string tmpFinalFileName = Letter.MergeMultipleDocuments(
                    ((string[])docsToMerge.ToArray(typeof(string))),
                    tmpLettersDirectory + letter.Docname.Replace(".dot", ".doc"));

                // delete all single tmp files
                foreach (string file in docsToMerge)
                {
                    File.Delete(file);
                }

                // download the document
                byte[] fileContents = File.ReadAllBytes(tmpFinalFileName);
                System.IO.File.Delete(tmpFinalFileName);

                // Nothing gets past the "DownloadDocument" method because it outputs the file
                // which is writing a response to the client browser and calls Response.End()
                // So make sure any other code that functions goes before this
                Letter.DownloadDocument(Response, fileContents, letter.Docname.Replace(".dot", ".doc"));
            }
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
            return;
        }
    }
    protected void FillGrid()
    {
        string searchSurname = "";

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

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

        string searchProviderNbr = "";

        if (Request.QueryString["provider_nbr_search"] != null && Request.QueryString["provider_nbr_search"].Length > 0)
        {
            searchProviderNbr         = Request.QueryString["provider_nbr_search"];
            txtSearchProviderNbr.Text = Request.QueryString["provider_nbr_search"];
        }
        bool searchProviderNbrOnlyStartsWith = true;

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

        string searchPhoneNbr = "";

        if (Request.QueryString["phone_nbr_search"] != null && Request.QueryString["phone_nbr_search"].Length > 0)
        {
            searchPhoneNbr         = Request.QueryString["phone_nbr_search"];
            txtSearchPhoneNbr.Text = Request.QueryString["phone_nbr_search"];
        }
        bool searchPhoneNbrOnlyStartsWith = true;

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

        DataTable dt = RegisterReferrerDB.GetDataTable(0, -1, chkShowDeleted.Checked, new int[] { 191 }, searchSurname, searchSurnameOnlyStartsWith, "", "", searchProviderNbr, searchProviderNbrOnlyStartsWith, searchPhoneNbr, searchPhoneNbrOnlyStartsWith);

        Hashtable regRefHash = PatientReferrerDB.GetHashtableByRegRef(true, false, false);

        dt.Columns.Add("count", typeof(int));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            int regRefID = Convert.ToInt32(dt.Rows[i]["register_referrer_id"]);
            dt.Rows[i]["count"] = regRefHash[regRefID] == null ? 0 : ((PatientReferrer[])regRefHash[regRefID]).Length;
        }


        // add suburb_name

        Hashtable entityIDsHash = new Hashtable();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            entityIDsHash[Convert.ToInt32(dt.Rows[i]["organisation_entity_id"])] = 1;
        }

        int[] entityIDs = new int[entityIDsHash.Keys.Count];
        entityIDsHash.Keys.CopyTo(entityIDs, 0);

        Hashtable emailHash = PatientsContactCacheDB.GetBullkAddress(entityIDs, -1);

        dt.Columns.Add("suburb_name", typeof(string));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            int    entityID   = Convert.ToInt32(dt.Rows[i]["organisation_entity_id"]);
            string suburbName = GetSuburb(emailHash, entityID);
            dt.Rows[i]["suburb_name"] = suburbName == null ? "" : suburbName;
        }


        Session["referrerinfolist_data"] = dt;

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


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

            int TotalColumns = GrdReferrer.Rows[0].Cells.Count;
            GrdReferrer.Rows[0].Cells.Clear();
            GrdReferrer.Rows[0].Cells.Add(new TableCell());
            GrdReferrer.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdReferrer.Rows[0].Cells[0].Text       = "No Record Found";
        }
    }
Пример #12
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);
        }
    }