Ejemplo n.º 1
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();
        }
    }
    protected string GetMatches()
    {
        string surnameMatch = Request.QueryString["q"];

        if (surnameMatch == null || surnameMatch.Length == 0)
        {
            throw new CustomMessageException();
        }

        surnameMatch = surnameMatch.Replace("'", "''");

        surnameMatch = surnameMatch.Replace("[", "").Replace("]", "").Trim();

        if (surnameMatch.EndsWith(", "))
        {
            surnameMatch = surnameMatch.Substring(0, surnameMatch.Length - 2).Trim();
        }
        if (surnameMatch.EndsWith(","))
        {
            surnameMatch = surnameMatch.Substring(0, surnameMatch.Length - 1).Trim();
        }

        bool   containsFirstname = false;
        string firstnameMatch    = null;

        if (surnameMatch.Contains(", "))
        {
            containsFirstname = true;
            int index = surnameMatch.IndexOf(", ");
            firstnameMatch = surnameMatch.Substring(index + 2);
            surnameMatch   = surnameMatch.Substring(0, index);
        }


        int maxResults = 80;

        if (Request.QueryString["max_results"] != null)
        {
            if (!Regex.IsMatch(Request.QueryString["max_results"], @"^\d+$"))
            {
                throw new CustomMessageException();
            }
            maxResults = Convert.ToInt32(Request.QueryString["max_results"]);
        }

        string link_href = Request.QueryString["link_href"];

        if (link_href == null)
        {
            throw new CustomMessageException();
        }
        link_href = System.Web.HttpUtility.UrlDecode(link_href);

        string link_onclick = Request.QueryString["link_onclick"];

        if (link_onclick == null)
        {
            throw new CustomMessageException();
        }
        link_onclick = System.Web.HttpUtility.UrlDecode(link_onclick);


        DataTable dt = Session["patientinfo_data"] as DataTable;

        //dt = null;

        // if from patient list page, just use the data from the session, else retrieve it serperately
        if (dt == null)
        {
            UserView userView = UserView.GetInstance();
            bool     ProvsCanSeePatientsOfAllOrgs = ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Bookings_ProvsCanSeePatientsOfAllOrgs"].Value == "1";
            bool     canSeeAllPatients            = userView.IsAdminView || (userView.IsProviderView && ProvsCanSeePatientsOfAllOrgs);

            if (canSeeAllPatients && userView.IsClinicView)
            {
                dt = PatientDB.GetDataTable(false, false, userView.IsClinicView);
            }
            else if (canSeeAllPatients && !userView.IsClinicView)
            {
                dt = RegisterPatientDB.GetDataTable_PatientsOfOrgGroupType(false, "6", false, false, userView.IsClinicView);
            }
            else // no admin view - so org is set
            {
                dt = RegisterPatientDB.GetDataTable_PatientsOf(false, Convert.ToInt32(Session["OrgID"]), false, false, userView.IsClinicView);
            }

            // update AjaxLivePatientSurnameSearch and PatientInfo.aspx and PatientListPopup to disallow providers to see other patients.
            if (userView.IsProviderView && !canSeeAllPatients)  // remove any patients who they haven't had bookings with before
            {
                Patient[] patients = BookingDB.GetPatientsOfBookingsWithProviderAtOrg(Convert.ToInt32(Session["StaffID"]), Convert.ToInt32(Session["OrgID"]));
                System.Collections.Hashtable hash = new System.Collections.Hashtable();
                foreach (Patient p in patients)
                {
                    hash[p.PatientID] = 1;
                }

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

            Session["patientinfo_data"] = dt;
        }


        DataRow[] foundRows = containsFirstname ? dt.Select("surname='" + surnameMatch + "' AND firstname LIKE '" + firstnameMatch + "*'", "surname, firstname, middlename") : dt.Select("surname LIKE '" + surnameMatch + "*'", "surname, firstname, middlename");
        if (foundRows.Length > maxResults)
        {
            return("Too many results (" + foundRows.Length + ")");
        }
        if (foundRows.Length == 0)
        {
            return("No results matching that text");
        }

        string result      = string.Empty;
        string tableResult = string.Empty;

        foreach (DataRow row in foundRows)
        {
            string dob = row["dob"] == DBNull.Value ? "" : " [DOB: " + Convert.ToDateTime(row["dob"]).ToString("dd-MM-yyyy") + "]";

            string href    = link_href.Replace("[patient_id]", row["patient_id"].ToString()).Replace("[firstname]", row["firstname"].ToString()).Replace("[surname]", row["surname"].ToString());
            string onclick = link_onclick.Replace("[patient_id]", row["patient_id"].ToString()).Replace("[firstname]", row["firstname"].ToString()).Replace("[surname]", row["surname"].ToString().Replace("'", "\\'"));

            string link     = "<a " + (onclick.Length == 0 ? "" : " onclick=\"" + onclick + "\" ") + " href='" + href + @"' onmouseover=""show_patient_detail('patient_detail_" + row["patient_id"].ToString() + "', " + row["patient_id"].ToString() + @"); return true;"" onmouseout=""hide_patient_detail('patient_detail_" + row["patient_id"].ToString() + @"'); return true;"" >" + row["surname"] + ", " + row["firstname"] + (row["middlename"].ToString().Length == 0 ? "" : " " + row["middlename"]) + @"</a>";
            string hoverDiv = @"<div id=""patient_detail_" + row["patient_id"].ToString() + @""" style=""display: none;"" class=""FAQ"">IMAGE OR TEXT HERE<br> </div>";

            result      += (result.Length == 0 ? "" : "<br />") + link + dob;
            tableResult += "<tr><td>" + link + "</td><td>" + hoverDiv + dob + "</td></tr>";
        }


        bool useTableResult = true;

        if (useTableResult)
        {
            return("<table>" + tableResult + "</table>");
        }
        else
        {
            return(result);
        }
    }
Ejemplo n.º 3
0
    protected void FillGrid_Patients(Type type, int id)
    {
        UserView userView = UserView.GetInstance();

        DataTable dt = null;

        if (type == typeof(Organisation))
        {
            Organisation org = OrganisationDB.GetByID(id);
            lblPatientsHeading.Text = "Patients of &nbsp;&nbsp;<big><b>All Referrers</b></big>&nbsp;&nbsp; at &nbsp;&nbsp;<big><b>" + org.Name + "</b></big>";

            if (userView.IsAdminView && userView.IsClinicView)
            {
                dt = PatientDB.GetDataTable(false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", "", "", id.ToString(), false, false, false);
            }
            if (userView.IsAdminView && !userView.IsClinicView)
            {
                dt = RegisterPatientDB.GetDataTable_PatientsOfOrgGroupType(false, "6", false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", "", "", id.ToString(), false, false, false);
            }
            if (!userView.IsAdminView)
            {
                dt = RegisterPatientDB.GetDataTable_PatientsOf(false, Convert.ToInt32(Session["OrgID"]), false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", "", "", id.ToString(), false, false, false);
            }
        }
        else if (type == typeof(RegisterReferrer))
        {
            RegisterReferrer regRef = RegisterReferrerDB.GetByID(id);
            lblPatientsHeading.Text = "Patients of &nbsp;&nbsp;<big><b>" + regRef.Referrer.Person.FullnameWithoutMiddlename + "</b></big>&nbsp;&nbsp; at &nbsp;&nbsp;<big><b>" + regRef.Organisation.Name + "</b></big>";

            if (userView.IsAdminView && userView.IsClinicView)
            {
                dt = PatientDB.GetDataTable(false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", id.ToString(), "", "", false, false, false);
            }
            if (userView.IsAdminView && !userView.IsClinicView)
            {
                dt = RegisterPatientDB.GetDataTable_PatientsOfOrgGroupType(false, "6", false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", id.ToString(), "", "", false, false, false);
            }
            if (!userView.IsAdminView)
            {
                dt = RegisterPatientDB.GetDataTable_PatientsOf(false, Convert.ToInt32(Session["OrgID"]), false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", id.ToString(), "", "", false, false, false);
            }
        }
        else
        {
            SetErrorMessage("Unknown type: " + type.ToString());
            return;
        }


        lblPatientsHeading.Visible = true;
        GrdPatients.Visible        = true;



        // put in epc info into the table in a bulk call
        // epc exp date, if valid, how many epc's remaining...


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

        int MedicareMaxNbrServicesPerYear = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);

        Hashtable patientsMedicareCountThisYearCache = PatientsMedicareCardCountThisYearCacheDB.GetBullk(patientIDs, DateTime.Today.Year);
        Hashtable patientsMedicareCountNextYearCache = PatientsMedicareCardCountThisYearCacheDB.GetBullk(patientIDs, DateTime.Today.Year + 1);
        Hashtable patientsEPCRemainingCache          = PatientsEPCRemainingCacheDB.GetBullk(patientIDs, DateTime.MinValue);

        dt.Columns.Add("epc_signed_date", typeof(DateTime));
        dt.Columns.Add("epc_expiry_date", typeof(DateTime));
        dt.Columns.Add("epc_n_services_left", typeof(Int32));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            int patientID = Convert.ToInt32(dt.Rows[i]["patient_id"]);

            int  totalServicesAllowedLeft = (MedicareMaxNbrServicesPerYear - (int)patientsMedicareCountThisYearCache[patientID]);
            Pair totalEPCRemaining        = patientsEPCRemainingCache[patientID] as Pair;

            int nServicesLeft = 0;
            if (totalEPCRemaining != null)
            {
                DateTime referralSignedDate = (DateTime)totalEPCRemaining.Second;
                DateTime hcExpiredDate      = referralSignedDate.AddYears(1);
                if (DateTime.Today >= referralSignedDate.Date && DateTime.Today < hcExpiredDate.Date)
                {
                    nServicesLeft = (int)totalEPCRemaining.First;
                }
                if (totalServicesAllowedLeft < nServicesLeft)
                {
                    nServicesLeft = totalServicesAllowedLeft;
                }

                dt.Rows[i]["epc_signed_date"]     = referralSignedDate;
                dt.Rows[i]["epc_expiry_date"]     = hcExpiredDate;
                dt.Rows[i]["epc_n_services_left"] = nServicesLeft;
            }
            else
            {
                dt.Rows[i]["epc_signed_date"]     = DBNull.Value;
                dt.Rows[i]["epc_expiry_date"]     = DBNull.Value;
                dt.Rows[i]["epc_n_services_left"] = DBNull.Value;
            }
        }



        Session["referrerinfoclinic_patients_data"] = dt;

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


            try
            {
                GrdPatients.DataBind();
            }
            catch (Exception ex)
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdPatients.DataSource = dt;
            GrdPatients.DataBind();

            int TotalColumns = GrdPatients.Rows[0].Cells.Count;
            GrdPatients.Rows[0].Cells.Clear();
            GrdPatients.Rows[0].Cells.Add(new TableCell());
            GrdPatients.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdPatients.Rows[0].Cells[0].Text       = "No Patients";
        }
    }
    protected void FillPatientGrid()
    {
        UserView userView = UserView.GetInstance();

        lblHeading.Text = !userView.IsAgedCareView ? "Patients" : "Residents";


        int    regRefID = IsValidFormRef() ? GetFormRef(false) : -1;
        int    orgID    = IsValidFormOrg() ? GetFormOrg(false) : 0;
        string orgIDs   = orgID != 0 ? orgID.ToString() : (IsValidFormOrgs() ? GetFormOrgs(false) : string.Empty);


        DataTable dt = null;

        if (regRefID != -1)
        {
            dt = PatientReferrerDB.GetDataTable_PatientsOf(regRefID, false, false, userView.IsClinicView, userView.IsGPView, txtSearchSurname.Text.Trim(), chkSurnameSearchOnlyStartWith.Checked);
        }
        else if (orgIDs != string.Empty)
        {
            dt = RegisterPatientDB.GetDataTable_PatientsOf(false, orgIDs, false, false, userView.IsClinicView, userView.IsGPView, txtSearchSurname.Text.Trim(), chkSurnameSearchOnlyStartWith.Checked);
        }
        else
        {
            dt = PatientDB.GetDataTable(false, false, userView.IsClinicView, userView.IsGPView, txtSearchSurname.Text.Trim(), chkSurnameSearchOnlyStartWith.Checked);
        }

        // update AjaxLivePatientSurnameSearch and PatientListV2.aspx and PatientListPopup to disallow providers to see other patients.
        if (userView.IsProviderView)  // remove any patients who they haven't had bookings with before
        {
            Patient[] patients = BookingDB.GetPatientsOfBookingsWithProviderAtOrg(Convert.ToInt32(Session["StaffID"]), Convert.ToInt32(Session["OrgID"]));
            System.Collections.Hashtable hash = new System.Collections.Hashtable();
            foreach (Patient p in patients)
            {
                hash[p.PatientID] = 1;
            }

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

        Session["patientinfo_data"] = dt;

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

            try
            {
                GrdPatient.DataBind();
                GrdPatient.PagerSettings.FirstPageText = "1";
                GrdPatient.PagerSettings.LastPageText  = GrdPatient.PageCount.ToString();
                GrdPatient.DataBind();
            }
            catch (Exception ex)
            {
                this.lblErrorMessage.Visible = true;
                this.lblErrorMessage.Text    = ex.ToString();
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdPatient.DataSource = dt;
            GrdPatient.DataBind();

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