Пример #1
0
    protected void GrdRegistration_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            DropDownList ddlOrganisation = (DropDownList)GrdRegistration.FooterRow.FindControl("ddlNewOrganisation");

            Patient patient = PatientDB.GetByID(GetFormID());
            if (patient == null)
            {
                HideTableAndSetErrorMessage("");
                return;
            }

            try
            {
                RegisterPatientDB.Insert(Convert.ToInt32(ddlOrganisation.SelectedValue), patient.PatientID);
            }
            catch (UniqueConstraintException)
            {
                // happens when 2 forms allow adding
                // do nothing and let form re-update
            }

            FillGrid();
        }
    }
Пример #2
0
    protected void GrdRegistration_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label lblId = (Label)GrdRegistration.Rows[e.RowIndex].FindControl("lblId");

        RegisterPatient registerPatient = RegisterPatientDB.GetByID(Convert.ToInt32(lblId.Text));

        if (BookingDB.GetCountByPatientAndOrg(registerPatient.Patient.PatientID, registerPatient.Organisation.OrganisationID) > 0)
        {
            SetErrorMessage("Can not remove registration of '" + registerPatient.Patient.Person.FullnameWithoutMiddlename + "' to '" + registerPatient.Organisation.Name + "' because there exists a booking for this patient there.");
            return;
        }

        try
        {
            RegisterPatientDB.UpdateInactive(Convert.ToInt32(lblId.Text), false);
        }
        catch (ForeignKeyConstraintException fkcEx)
        {
            if (Utilities.IsDev())
            {
                HideTableAndSetErrorMessage("Can not delete because other records depend on this : " + fkcEx.Message);
            }
            else
            {
                HideTableAndSetErrorMessage("Can not delete because other records depend on this");
            }
        }

        FillGrid();
    }
Пример #3
0
    protected static Hashtable GetPatientRegOrgCache(Patient[] patients)
    {
        ArrayList patientIDArrayList = new ArrayList();

        foreach (Patient patient in patients)
        {
            patientIDArrayList.Add(patient.PatientID);
        }
        int[] patientIDs = (int[])patientIDArrayList.ToArray(typeof(int));

        Hashtable regOrgHash = new Hashtable();

        System.Data.DataTable tbl = RegisterPatientDB.GetDataTable_OrganisationsOf(patientIDs, true, false, false, true, true);
        for (int i = 0; i < tbl.Rows.Count; i++)
        {
            int          patientID = Convert.ToInt32(tbl.Rows[i]["patient_id"]);
            Organisation org       = OrganisationDB.Load(tbl.Rows[i], "", "organisation_entity_id", "organisation_is_deleted");

            if (regOrgHash[patientID] == null)
            {
                regOrgHash[patientID] = new System.Collections.ArrayList();
            }
            ((System.Collections.ArrayList)regOrgHash[patientID]).Add(org);
        }

        return(regOrgHash);
    }
    protected void FillOrganisationGrid()
    {
        UserView userView = UserView.GetInstance();

        lblHeading.Text = !userView.IsAgedCareView ? "Facilitys" : "Clinics";

        int       patientID = IsValidFormPatient() ? GetFormPatient(false) : -1;
        DataTable dt        = patientID == -1 ?
                              OrganisationDB.GetDataTable(0, false, true, !userView.IsClinicView && !userView.IsGPView, !userView.IsAgedCareView, true, true, txtSearchOrganisation.Text.Trim(), chkOrganisationSearchOnlyStartWith.Checked) :
                              RegisterPatientDB.GetDataTable_OrganisationsOf(patientID, true, !userView.IsClinicView && !userView.IsGPView, !userView.IsAgedCareView, true, true, txtSearchOrganisation.Text.Trim(), chkOrganisationSearchOnlyStartWith.Checked);

        Session["organisationlist_data"] = dt;

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


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

            int TotalColumns = GrdOrganisation.Rows[0].Cells.Count;
            GrdOrganisation.Rows[0].Cells.Clear();
            GrdOrganisation.Rows[0].Cells.Add(new TableCell());
            GrdOrganisation.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdOrganisation.Rows[0].Cells[0].Text       = "No Record Found";
        }
    }
    protected void GrdRegistration_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label        lblId      = (Label)GrdRegistration.Rows[e.RowIndex].FindControl("lblId");
        DropDownList ddlPatient = (DropDownList)GrdRegistration.Rows[e.RowIndex].FindControl("ddlPatient");

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

        if (org == null)
        {
            HideTableAndSetErrorMessage("");
            return;
        }

        RegisterPatientDB.Update(Convert.ToInt32(lblId.Text), org.OrganisationID, Convert.ToInt32(ddlPatient.SelectedValue));

        GrdRegistration.EditIndex = -1;
        FillGrid();
    }
Пример #6
0
    protected int AddOrgIfNotExists(Patient patient, int siteID, int orgID)
    {
        // add clinic if different from existing

        int register_patient_id = -1;

        bool orgAlreadyExists = false;

        Organisation[] orgs = RegisterPatientDB.GetOrganisationsOf(patient.PatientID);
        foreach (Organisation org in orgs)
        {
            if (org.OrganisationID == orgID)
            {
                orgAlreadyExists = true;
            }
        }

        if (!orgAlreadyExists)
        {
            register_patient_id = RegisterPatientDB.Insert(orgID, patient.PatientID);
        }

        return(register_patient_id);
    }
Пример #7
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";
        }
    }
Пример #8
0
    protected void SetUrlFields()
    {
        try
        {
            string booking_patient_id = Request.QueryString["bookingpatient"];
            string booking_id         = Request.QueryString["booking"];

            if (booking_patient_id != null)
            {
                lblHeading.Text = "Print A Letter For Booking";
                SetBooking();
            }
            else if (booking_id != null)
            {
                lblHeading.Text = "Print A Letter For Booking";
                SetBooking();
            }
            else
            {
                lblHeading.Text = "Print A Letter";

                td_booking_space.Visible = false;
                td_booking.Visible       = false;

                string patient_id = Request.QueryString["patient"];
                if (patient_id != null && patient_id != "-1")
                {
                    if (!Regex.IsMatch(patient_id, @"^\d+$"))
                    {
                        throw new CustomMessageException();
                    }

                    Patient patient = PatientDB.GetByID(Convert.ToInt32(patient_id));
                    if (patient == null)
                    {
                        throw new CustomMessageException();
                    }

                    btnOtherEmail.OnClientClick = "javascript: get_referrer_additional_emails(" + patient.PatientID + ");return false;";

                    txtUpdatePatientID.Text      = patient.PatientID.ToString();
                    txtUpdatePatientName.Text    = patient.Person.FullnameWithoutMiddlename;
                    txtUpdatePatientName.Visible = false;
                    lblUpdatePatientName.Text    = "<a href=\"#=\" onclick=\"open_new_window('PatientDetailV2.aspx?type=view&id=" + patient.PatientID + "'); return false;\">" + patient.Person.FullnameWithoutMiddlename + "</a>";
                    lblUpdatePatientName.Visible = true;


                    // hide if got from url ... no need to change it
                    btnPatientListPopup.Visible = false;
                    btnClearPatient.Visible     = false;


                    // if patient only linked to 1 org, then set org
                    Organisation[] orgs = RegisterPatientDB.GetOrganisationsOf(patient.PatientID);
                    if (orgs.Length == 1)
                    {
                        txtUpdateOrganisationID.Text      = orgs[0].OrganisationID.ToString();
                        txtUpdateOrganisationName.Text    = orgs[0].Name;
                        txtUpdateOrganisationName.Visible = false;
                        lblUpdateOrganisationName.Text    = "<a href=\"#=\" onclick=\"open_new_window('OrganisationDetailV2.aspx?type=view&id=" + orgs[0].OrganisationID + "'); return false;\">" + orgs[0].Name + "</a>";
                        lblUpdateOrganisationName.Visible = true;

                        PopulateLettersList();

                        // hide if got from url ... no need to change it
                        btnOrganisationListPopup.Visible = false;
                        btnClearOrganisation.Visible     = false;
                    }
                }

                string org_id = Request.QueryString["org"];
                if (org_id != null && org_id != "0")
                {
                    if (!Regex.IsMatch(org_id, @"^\d+$"))
                    {
                        throw new CustomMessageException();
                    }

                    Organisation org = OrganisationDB.GetByID(Convert.ToInt32(org_id));
                    if (org == null)
                    {
                        throw new CustomMessageException();
                    }

                    txtUpdateOrganisationID.Text      = org.OrganisationID.ToString();
                    txtUpdateOrganisationName.Text    = org.Name;
                    txtUpdateOrganisationName.Visible = false;
                    lblUpdateOrganisationName.Text    = "<a href=\"#=\" onclick=\"open_new_window('OrganisationDetailV2.aspx?type=view&id=" + org.OrganisationID + "'); return false;\">" + org.Name + "</a>";
                    lblUpdateOrganisationName.Visible = true;

                    PopulateLettersList();

                    // hide if got from url ... no need to change it
                    btnOrganisationListPopup.Visible = false;
                    btnClearOrganisation.Visible     = false;
                }
            }


            UpdateTextbox(txtUpdatePatientName, lblUpdatePatientName, txtUpdatePatientID.Text.Length == 0);
            UpdateTextbox(txtUpdateOrganisationName, lblUpdateOrganisationName, txtUpdateOrganisationID.Text.Length == 0);

            string letter_id = Request.QueryString["letter"];
            if (letter_id != null && letter_id != "-1")
            {
                if (!Regex.IsMatch(letter_id, @"^\d+$"))
                {
                    throw new CustomMessageException();
                }

                Letter letter = LetterDB.GetByID(Convert.ToInt32(letter_id));
                if (letter == null)
                {
                    throw new CustomMessageException();
                }

                foreach (ListItem item in lstLetters.Items)
                {
                    if (item.Value == letter.LetterID.ToString())
                    {
                        item.Selected = true;
                    }
                }
            }


            txtSubject.Text   = SystemVariableDB.GetByDescr("LettersEmailDefaultSubject").Value;
            FreeTextBox1.Text = SystemVariableDB.GetByDescr("LettersEmailSignature").Value;
        }
        catch (CustomMessageException ex)
        {
            SetErrorMessage();
        }
    }
    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);
        }
    }
Пример #10
0
    protected void btnBlah_Click(object sender, EventArgs e)
    {
        DataTable dt = InvoiceDB.GetAllOutstandingByPatientAsReport(Convert.ToInt32(Session["SiteID"]));

        dt.DefaultView.Sort = "total_due DESC";
        dt = dt.DefaultView.ToTable();

        // now can put into gridview so can sort by amount owing or name etc..  -- and put sum at bottum and have paging

        // GridView1.Columns[ColumnIndex].HeaderText = "Patient (Count: " + dt.Rows.Count + ")";


        string output = string.Empty;

        output += "<table cellpadding=\"4\"><tr><th>Patient</th><th>Total due (Count)</th><th>View PT Invoices</th></tr>";
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            output += "<tr valign=\"top\"><td><a href='AddEditPatient.aspx?type=view&id=" + dt.Rows[i]["patient_id"] + "'>" + dt.Rows[i]["patient_fullname"] + "</a></td><td><b>" + string.Format("{0:C}", Convert.ToDecimal(dt.Rows[i]["total_due"])) + "</b> (" + dt.Rows[i]["total_inv_count"] + ")</td><td><a href='InvoiceInfo.aspx?patient=" + dt.Rows[i]["patient_id"] + "&inc_medicare=0&inc_dva=0&inc_private=1&inc_paid=0&inc_unpaid=1'>Unpaid Invoices</a> &nbsp;&nbsp; <a href='InvoiceInfo.aspx?patient=" + dt.Rows[i]["patient_id"] + "'>All Invoices</a></td></tr>";
        }
        output += "</table>";

        string totalInfoTbl = @"
            <table>
                <tr><td>Total Patients</td><td> = <b>" + dt.Rows.Count + @"</b></td></tr>
                <tr><td>Total Owed</td><td> = <b>" + string.Format("{0:C}", (decimal)dt.Compute("Sum(total_due)", "")) + @"</b></td></tr>
            </table>";

        lblBlah.Text = totalInfoTbl + output;

        return;



        RegisterPatient[] regPts = RegisterPatientDB.GetAll(true, true, true, "6,2,3");
        //RegisterPatient[] regPts = RegisterPatientDB.GetAll(false, false, true, "6,2,3");
        Hashtable patHash = new Hashtable();
        Hashtable orgHash = new Hashtable();

        for (int i = 0; i < regPts.Length; i++)
        {
            if (patHash[regPts[i].Patient.PatientID] == null)
            {
                patHash[regPts[i].Patient.PatientID] = new ArrayList();
            }
            if (orgHash[regPts[i].Organisation.OrganisationID] == null)
            {
                orgHash[regPts[i].Organisation.OrganisationID] = new ArrayList();
            }

            ((ArrayList)patHash[regPts[i].Patient.PatientID]).Add(regPts[i]);
            ((ArrayList)orgHash[regPts[i].Organisation.OrganisationID]).Add(regPts[i]);
        }



        string output1 = string.Empty, output2 = string.Empty;

        output1 += "<table>";


        Organisation[] flattenedTree = OrganisationTree.GetFlattenedTree(null, false, 0, false, "139,367,372");
        for (int i = 0; i < flattenedTree.Length; i++)
        {
            Organisation org = flattenedTree[i];

            string       parentsList = string.Empty;
            Organisation curOrg      = org.ParentOrganisation;
            while (curOrg != null)
            {
                parentsList += (parentsList.Length == 0 ? "" : ", ") + "<b>" + curOrg.Name + "</b>";
                curOrg       = curOrg.ParentOrganisation;
            }

            int nPatients = orgHash[org.OrganisationID] == null ? 0 : ((ArrayList)orgHash[org.OrganisationID]).Count;

            output1 += "<tr>";
            output1 += "<td><a href='/AddEditOrganisation.aspx?type=view&id=" + org.OrganisationID + "'>" + org.Name + "</a></td>";
            output1 += "<td>" + org.OrganisationID + "</td>";
            output1 += "<td>" + (org.ParentOrganisation == null ? "0" : org.ParentOrganisation.OrganisationID.ToString()) + "</td>";
            output1 += "<td>" + org.TreeLevel + "</td>";
            output1 += "<td>" + parentsList + "</td>";
            output1 += "</tr>";


            // link:   "~/AddEditOrganisation.aspx?type=view&id=" + org.OrganisationID

            if (org.TreeLevel == 0)
            {
                output2 += "<br />";
            }
            for (int j = 0; j < org.TreeLevel; j++)
            {
                output2 += "&nbsp;&nbsp;&nbsp;&nbsp;";
            }
            output2 += "<a href='/AddEditOrganisation.aspx?type=view&id=" + org.OrganisationID + "'>" + org.Name + "</a>" + " (" + org.OrganisationType.Descr.Replace("Aged Care ", "") + " " + nPatients + " pts)<br />";
            //output2 += " - [<b>" + org.OrganisationType.Descr + "</b>] " + "<a href='/AddEditOrganisation.aspx?type=view&id=" + org.OrganisationID + "'>" + org.Name + "</a>" + "[" + org.OrganisationID + "] [<b>" + nPatients + "</b>]<br />";
        }

        lblBlah.Text = output2;


        regPts  = null;
        patHash = null;
        orgHash = null;
        GC.Collect();



        /*
         * bool onlyWithValidMedicareEPCRemaining = true;
         * bool onlyWithValidDVAEPCRemaining      = false;
         *
         *
         * string sql = @"
         *
         * SELECT * FROM Patient WHERE 1=1 "
         + (!onlyWithValidMedicareEPCRemaining ? "" :
         +      @" AND (SELECT COALESCE(SUM(num_services_remaining),0)
         +          FROM   HealthCardEPCRemaining epcRemaining LEFT JOIN HealthCard AS hc ON epcRemaining.health_card_id = hc.health_card_id
         +          WHERE  hc.is_active = 1 AND hc.patient_id = Patient.patient_id AND hc.organisation_id = -1 AND hc.date_referral_signed > DATEADD(year,-1,GETDATE())) > 0 ")
         + (!onlyWithValidDVAEPCRemaining ? "" :
         +  @" AND (SELECT COUNT(*) FROM HealthCard AS hc WHERE is_active = 1 AND hc.patient_id = Patient.patient_id AND organisation_id = -2 AND date_referral_signed > DATEADD(year,-1,GETDATE())) > 0 ");
         +
         + DataTable tbl = DBBase.ExecuteQuery(sql).Tables[0];
         +
         + // valid_medicare_epc_remaining
         + // valid_dva_epc_remaining
         +
         + if (onlyWithValidMedicareEPCRemaining)
         +  tbl = PatientDB.RemooveIfMedicareYearQuotaUsed(tbl);
         +
         + string output1 = string.Empty;
         + for (int i = 0; i < tbl.Rows.Count; i++)
         +  output1 += (output1.Length == 0 ? "" : ", ") + Convert.ToInt32(tbl.Rows[i]["patient_id"]);
         + output1 = "<u>Has Medicare still valid (" + tbl.Rows.Count + ")</u><br>" + output1;
         +
         + Label3.Text = output1;
         */



        // move this into
        //     Booking.SendReminderEmail()   .. throw custom message exception if they have no email)

        // also, if they dont have an email set when about to make a booking, popup message warning them and allowing them to add one first...

        //Booking booking = BookingDB.GetByID(89219);
        //if (booking != null)
        //    booking.SendReminderEmail(booking);
    }
Пример #11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        try
        {
            UserView userView = UserView.GetInstance();

            string patient_id = Request.QueryString["patient_id"];
            if (patient_id == null || !Regex.IsMatch(patient_id, @"^\d+$"))
            {
                throw new CustomMessageException();
            }

            Patient patient = PatientDB.GetByID(Convert.ToInt32(patient_id));
            if (patient == null)
            {
                throw new CustomMessageException();
            }

            Organisation[] orgs = RegisterPatientDB.GetOrganisationsOf(patient.PatientID);

            ArrayList list = new ArrayList();
            for (int i = 0; i < orgs.Length; i++)
            {
                if (userView.IsClinicView && orgs[i].OrganisationType.OrganisationTypeID == 218)
                {
                    list.Add(orgs[i]);
                }
                if (userView.IsAgedCareView && (new List <int> {
                    139, 367, 372
                }).Contains(orgs[i].OrganisationType.OrganisationTypeID))
                {
                    list.Add(orgs[i]);
                }
            }
            orgs = (Organisation[])list.ToArray(typeof(Organisation));


            if (orgs.Length == 0)
            {
                Response.Redirect("~/RegisterOrganisationsToPatientV2.aspx?id=" + patient.PatientID + "&type=select_to_go_to_bookings");
                return;
            }
            else
            {
                string strOrgs = string.Empty;
                foreach (Organisation o in orgs)
                {
                    strOrgs = strOrgs + (strOrgs.Length == 0 ? "" : "_") + o.OrganisationID;
                }

                Response.Redirect("~/BookingsV2.aspx?orgs=" + strOrgs + (userView.IsAgedCareView ? "" : "&patient=" + patient.PatientID));
                return;
            }
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + (Utilities.IsDev() ? ex.ToString() : "Error - please contact system administrator."));
        }
    }
Пример #12
0
    protected void GrdRegistration_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Patient patient = PatientDB.GetByID(GetFormID());

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

        UserView userView = UserView.GetInstance();

        DataTable dt       = Session["registerorgtopatient_data"] as DataTable;
        bool      tblEmpty = (dt.Rows.Count == 1 && dt.Rows[0][0] == DBNull.Value);

        if (!tblEmpty && e.Row.RowType == DataControlRowType.DataRow)
        {
            Label     lblId     = (Label)e.Row.FindControl("lblId");
            DataRow[] foundRows = dt.Select("register_patient_id=" + lblId.Text);
            DataRow   thisRow   = foundRows[0];


            DropDownList ddlOrganisation = (DropDownList)e.Row.FindControl("ddlOrganisation");
            if (ddlOrganisation != null)
            {
                Organisation[] incList_orig = RegisterPatientDB.GetOrganisationsOf(patient.PatientID);
                Organisation[] incList      = Organisation.RemoveByID(incList_orig, Convert.ToInt32(thisRow["organisation_id"]));
                DataTable      orgs         = OrganisationDB.GetDataTable_AllNotInc(incList, true, !userView.IsClinicView, !userView.IsAgedCareView, true, true);
                orgs.DefaultView.Sort = "name ASC";
                foreach (DataRowView row in orgs.DefaultView)
                {
                    ddlOrganisation.Items.Add(new ListItem(row["name"].ToString(), row["organisation_id"].ToString()));
                }
                ddlOrganisation.SelectedValue = thisRow["organisation_id"].ToString();
            }

            HyperLink lnkBookings = (HyperLink)e.Row.FindControl("lnkBookings");
            if (lnkBookings != null)
            {
                lnkBookings.NavigateUrl = string.Format("~/BookingsV2.aspx?orgs={0}&patient={1}", Convert.ToInt32(thisRow["organisation_id"]), patient.PatientID);
            }


            Utilities.AddConfirmationBox(e);
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                Utilities.SetEditRowBackColour(e, System.Drawing.Color.LightGoldenrodYellow);
            }
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList ddlOrganisation = (DropDownList)e.Row.FindControl("ddlNewOrganisation");
            if (ddlOrganisation != null)
            {
                Organisation[] incList = RegisterPatientDB.GetOrganisationsOf(patient.PatientID);
                DataTable      orgs    = OrganisationDB.GetDataTable_AllNotInc(incList, true, !userView.IsClinicView, !userView.IsAgedCareView, true, true);
                orgs.DefaultView.Sort = "name ASC";

                foreach (DataRowView row in orgs.DefaultView)
                {
                    ddlOrganisation.Items.Add(new ListItem(row["name"].ToString(), row["organisation_id"].ToString()));
                }

                if (orgs.Rows.Count == 0)
                {
                    hideFotter = true;
                }
            }
        }
    }
    protected void FillGrid()
    {
        if (!IsValidFormID())
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

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

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

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



        string searchSurname = "";

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

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


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


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


        // get last and next booking dates

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

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



        // get epc info

        Hashtable mostRecentRecallHashByPatientID = LetterPrintHistoryDB.GetMostRecentRecallHashByPatients(ptIDs);

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


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

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

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

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

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

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

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

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

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



        Session["registerpatienttoorg_data"] = dt;

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


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

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

        if (hideFotter)
        {
            GrdRegistration.FooterRow.Visible = false;
        }
    }
    protected void GrdRegistration_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Organisation org = OrganisationDB.GetByID(GetFormID());

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

        DataTable dt       = Session["registerpatienttoorg_data"] as DataTable;
        bool      tblEmpty = (dt.Rows.Count == 1 && dt.Rows[0][0] == DBNull.Value);

        if (!tblEmpty && e.Row.RowType == DataControlRowType.DataRow)
        {
            Label     lblId     = (Label)e.Row.FindControl("lblId");
            DataRow[] foundRows = dt.Select("register_patient_id=" + lblId.Text);
            DataRow   thisRow   = foundRows[0];


            DropDownList ddlPatient = (DropDownList)e.Row.FindControl("ddlPatient");
            if (ddlPatient != null)
            {
                Patient[] incList_orig = RegisterPatientDB.GetPatientsOf(GetFormViewOnlyLast(), org.OrganisationID);
                Patient[] incList      = Patient.RemoveByID(incList_orig, Convert.ToInt32(thisRow["patient_id"]));
                DataTable patient      = PatientDB.GetDataTable_AllNotInc(incList);
                patient.DefaultView.Sort = "surname ASC";
                foreach (DataRowView row in patient.DefaultView)
                {
                    ddlPatient.Items.Add(new ListItem(row["surname"].ToString() + ", " + row["firstname"].ToString() + " " + row["middlename"].ToString(), row["patient_id"].ToString()));
                }
                ddlPatient.SelectedValue = thisRow["patient_id"].ToString();
            }

            Label lblEPCExpiry     = (Label)e.Row.FindControl("lblEPCExpiry");
            Label lblEPCsRemaining = (Label)e.Row.FindControl("lblEPCsRemaining");
            if (lblEPCExpiry != null && lblEPCsRemaining != null)
            {
                if (!Convert.ToBoolean(thisRow["has_valid_epc"]))
                {
                    lblEPCExpiry.ForeColor     = System.Drawing.Color.Red;
                    lblEPCsRemaining.ForeColor = System.Drawing.Color.Red;
                }
            }

            HyperLink lnkBookings = (HyperLink)e.Row.FindControl("lnkBookings");
            if (lnkBookings != null)
            {
                lnkBookings.NavigateUrl = string.Format("~/BookingsV2.aspx?orgs={0}&patient={1}", org.OrganisationID, Convert.ToInt32(thisRow["patient_id"]));
            }

            Label lnkPatient = (Label)e.Row.FindControl("lnkPatient");
            if (lnkPatient != null)
            {
                string URL = "PatientDetailV2.aspx?type=view&id=" + Convert.ToInt32(thisRow["patient_id"]);
                if (URL.StartsWith("~"))
                {
                    URL = URL.Substring(1);
                }
                lnkPatient.Text = "<a href=\"#\" onclick=\"var win=window.open('" + URL + "', '_blank'); win.focus();return false;\" >" + thisRow["firstname"] + " " + thisRow["surname"] + "</a>";
            }


            Utilities.AddConfirmationBox(e);
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                Utilities.SetEditRowBackColour(e, System.Drawing.Color.LightGoldenrodYellow);
            }
        }
        if (e.Row.RowType == DataControlRowType.Footer && GrdRegistration.ShowFooter)
        {
            DropDownList ddlPatient = (DropDownList)e.Row.FindControl("ddlNewPatient");
            if (ddlPatient != null)
            {
                Patient[] incList = RegisterPatientDB.GetPatientsOf(GetFormViewOnlyLast(), org.OrganisationID);
                DataTable patient = PatientDB.GetDataTable_AllNotInc(incList);
                patient.DefaultView.Sort = "surname ASC";
                foreach (DataRowView row in patient.DefaultView)
                {
                    ddlPatient.Items.Add(new ListItem(row["surname"].ToString() + ", " + row["firstname"].ToString() + " " + row["middlename"].ToString(), row["patient_id"].ToString()));
                }

                if (patient.Rows.Count == 0)
                {
                    hideFotter = true;
                }
            }
        }
    }
Пример #15
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");
        }
    }
Пример #16
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            main_content.Style["background"] = (Session["SystemVariables"] == null) ? "url(../imagesV2/login_bg.png) center top no-repeat #EDEDED" : "url(../imagesV2/" + ((SystemVariables)Session["SystemVariables"])["MainLogoBackground"].Value + ") center top no-repeat #EDEDED";
        }

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

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

        int type_group_id = -1;

        if (Session["SiteTypeID"] != null && (Convert.ToInt32(Session["SiteTypeID"]) == 1 || Convert.ToInt32(Session["SiteTypeID"]) == 3))
        {
            lblHeading.InnerHtml = "Select A Clinic";
            type_group_id        = 5;
        }
        else if (Session["SiteTypeID"] != null && Convert.ToInt32(Session["SiteTypeID"]) == 2)
        {
            lblHeading.InnerHtml = "Select A Facility/Wing";
            type_group_id        = 6;
        }
        else
        {
            throw new Exception("Unknown SiteTypeID in session");
        }


        if (Session["PatientID"] != null)
        {
            DataTable dt = RegisterPatientDB.GetDataTable_OrganisationsOf(Convert.ToInt32(Session["PatientID"]), true, false, true, true, true);

            if (dt.Rows.Count == 1)  // if only org, auto select it
            {
                Session["IsMultipleOrgs"] = false;
                Select(Convert.ToInt32(dt.Rows[0]["organisation_id"]));
            }
            else
            {
                Session["IsMultipleOrgs"] = true;
                lstOrgs.DataSource        = dt;
                lstOrgs.DataBind();
            }
        }
        else // if (Session["StaffID"] != null)
        {
            DataTable dt = RegisterStaffDB.GetDataTable_OrganisationsOf(Convert.ToInt32(Session["StaffID"]), type_group_id.ToString());

            if (dt.Rows.Count == 1)  // if only org, auto select it
            {
                Session["IsMultipleOrgs"] = false;
                Select(Convert.ToInt32(dt.Rows[0]["organisation_id"]));
            }
            else
            {
                Session["IsMultipleOrgs"] = true;
                lstOrgs.DataSource        = dt;
                lstOrgs.DataBind();
            }
        }
    }
    protected void AddBooking()
    {
        //UrlReturnPage returnPage    = GetUrlReturnPage();
        bool?checkClashAllOrgs = UrlCheckClashAllOrgs;

        DateTime?    startDateTime = UrlStartDateTime;
        DateTime?    endDateTime   = UrlEndDateTime;
        int?         bookingTypeID = UrlBookingTypeID;
        Patient      patient       = UrlPatient;
        Organisation org           = UrlOrg;
        Staff        staff         = UrlStaff;
        Offering     offering      = UrlOffering;
        bool?        confirmed     = UrlIsConfirmed;

        if (startDateTime == null)
        {
            throw new Exception("Invalid url field start_datetime");
        }
        if (endDateTime == null)
        {
            throw new Exception("Invalid url field end_datetime");
        }
        if (bookingTypeID == null)
        {
            throw new Exception("Invalid url field booking_type_id");
        }
        if (org == null)
        {
            throw new Exception("Invalid url field org_id");
        }
        if (staff == null)
        {
            throw new Exception("Invalid url field staff_id");
        }
        if (confirmed == null)
        {
            throw new Exception("Invalid url field is_confirmed");
        }


        int      booking_confirmed_by_type_id = !confirmed.Value ? -1 : 1;
        int      confirmedBy   = !confirmed.Value ? -1                : GetStaffID();
        DateTime dateConfirmed = !confirmed.Value ? DateTime.MinValue : DateTime.Now;

        if (bookingTypeID.Value == 34)
        {
            // check booking is valid ie no overlapping with current bookings
            Booking[] bookings = BookingDB.GetToCheckOverlap_OneTime(startDateTime.Value, endDateTime.Value, staff, checkClashAllOrgs.Value ? null : org, bookingTypeID.Value == 342, true, false);
            if (Booking.HasOverlap(bookings, startDateTime.Value, endDateTime.Value))
            {
                string fromTime = startDateTime.Value.Hour.ToString().PadLeft(2, '0') + ":" + startDateTime.Value.Minute.ToString().PadLeft(2, '0');
                string toTime   = endDateTime.Value.Hour.ToString().PadLeft(2, '0') + ":" + endDateTime.Value.Minute.ToString().PadLeft(2, '0');
                throw new CustomMessageException("Can not book " + startDateTime.Value.ToString(@"ddd MMM d") + " " + fromTime + "-" + toTime + " due to overlap with existing booking");
            }


            // set prev for this pt/org inactive and put new one so that the most recent orgs for reg-pt items is the org with the most recent booking
            //if (!RegisterPatientDB.IsPatientRegisteredToOrg(patient.PatientID, org.OrganisationID))
            //    RegisterPatientDB.Insert(org.OrganisationID, patient.PatientID);
            if (patient != null && org != null)
            {
                RegisterPatientDB.UpdateInactive(patient.PatientID, org.OrganisationID, false);
                RegisterPatientDB.Insert(org.OrganisationID, patient.PatientID);
            }

            int newBookingID = BookingDB.Insert(startDateTime.Value, endDateTime.Value, org == null ? 0 : org.OrganisationID, staff == null ? 0 : staff.StaffID, patient == null ? -1 : patient.PatientID, offering == null ? -1 : offering.OfferingID,
                                                bookingTypeID.Value, 0, -1, GetStaffID(), booking_confirmed_by_type_id, confirmedBy, dateConfirmed, -1, DateTime.MinValue, -1, DateTime.MinValue, false, false, false, false, startDateTime.Value.DayOfWeek, TimeSpan.Zero, TimeSpan.Zero);

            Booking newBooking = BookingDB.GetByID(newBookingID);
            newBooking.SendReminderEmail();
        }
        else
        {
            // make sepertae booking for each day so that they can delete individual days
            int nDays = (int)endDateTime.Value.Subtract(startDateTime.Value).TotalHours / 24;
            for (int i = 0; i < nDays; i++)
            {
                // check if have booking for this day already
                Booking[] bookings = BookingDB.GetUnavailableDaysByStartEndDate(startDateTime.Value.AddDays(i), startDateTime.Value.AddDays(i + 1), staff, org);
                if (bookings.Length == 0)
                {
                    BookingDB.Insert(startDateTime.Value.AddDays(i), startDateTime.Value.AddDays(i).Date.AddHours(23).AddMinutes(59).AddSeconds(59), org == null ? 0 : org.OrganisationID, staff == null ? -1 : staff.StaffID, patient == null ? -1 : patient.PatientID, offering == null ? -1 : offering.OfferingID,
                                     bookingTypeID.Value, 0, -1, GetStaffID(), booking_confirmed_by_type_id, confirmedBy, dateConfirmed, -1, DateTime.MinValue, -1, DateTime.MinValue, false, false, false, false, startDateTime.Value.DayOfWeek, TimeSpan.Zero, TimeSpan.Zero);
                }
            }
        }
    }
    protected void EditBooking()
    {
        //UrlReturnPage returnPage    = GetUrlReturnPage();
        bool?checkClashAllOrgs = UrlCheckClashAllOrgs;

        Booking      booking       = UrlBooking;
        DateTime?    startDateTime = UrlStartDateTime;
        DateTime?    endDateTime   = UrlEndDateTime;
        Patient      patient       = UrlPatient;
        Organisation org           = UrlOrg;
        Staff        staff         = UrlStaff;
        Offering     offering      = UrlOffering;
        bool?        confirmed     = UrlIsConfirmed;
        int?         editReason    = UrlEditReasonID;

        if (booking == null)
        {
            throw new Exception("Invalid url field booking_id");
        }
        if (startDateTime == null)
        {
            throw new Exception("Invalid url field start_datetime");
        }
        if (endDateTime == null)
        {
            throw new Exception("Invalid url field end_datetime");
        }
        if (org == null)
        {
            throw new Exception("Invalid url field org_id");
        }
        if (staff == null)
        {
            throw new Exception("Invalid url field staff_id");
        }
        if (confirmed == null)
        {
            throw new Exception("Invalid url field is_confirmed");
        }
        if (editReason == null)
        {
            throw new Exception("Invalid url field edit_reason_id");
        }

        if (booking.AddedBy == null)
        {
            throw new CustomMessageException("Error - please contact system administrator.\r\n\r\nError Details:\r\nBooking 'Added By' is not set and must be set. BK ID: " + booking.BookingID);
        }

        // check booking is valid ie no overlapping with current bookings
        Booking[] bookings = BookingDB.GetToCheckOverlap_OneTime(startDateTime.Value, endDateTime.Value, staff, checkClashAllOrgs.Value ? null : org, booking.BookingTypeID == 342, true, false);
        if (Booking.HasOverlap(bookings, startDateTime.Value, endDateTime.Value, booking))
        {
            string fromTime = startDateTime.Value.Hour.ToString().PadLeft(2, '0') + ":" + startDateTime.Value.Minute.ToString().PadLeft(2, '0');
            string toTime   = endDateTime.Value.Hour.ToString().PadLeft(2, '0') + ":" + endDateTime.Value.Minute.ToString().PadLeft(2, '0');
            throw new CustomMessageException("Can not book " + startDateTime.Value.ToString(@"ddd MMM d") + " " + fromTime + "-" + toTime + " due to overlap with existing booking");
        }


        int      booking_confirmed_by_type_id = !confirmed.Value ? -1 : 1;
        int      confirmedBy   = !confirmed.Value ? -1                : (booking.ConfirmedBy == null ? GetStaffID() : booking.ConfirmedBy.StaffID);
        DateTime dateConfirmed = !confirmed.Value ? DateTime.MinValue : (booking.ConfirmedBy == null ? DateTime.Now : booking.DateConfirmed);

        if (patient != null && !RegisterPatientDB.IsPatientRegisteredToOrg(patient.PatientID, org.OrganisationID))
        {
            RegisterPatientDB.Insert(org.OrganisationID, patient.PatientID);
        }

        BookingChangeHistoryDB.Insert(booking.BookingID, GetStaffID(), Convert.ToInt32(editReason.Value), booking.DateStart);
        BookingDB.Update(booking.BookingID, startDateTime.Value, endDateTime.Value, org.OrganisationID, staff.StaffID, patient == null ? -1 : patient.PatientID, offering == null ? -1 : offering.OfferingID,
                         booking.BookingTypeID, booking.BookingStatus.ID, -1, booking.AddedBy.StaffID, booking_confirmed_by_type_id, confirmedBy, dateConfirmed,
                         booking.DeletedBy == null ? -1 : booking.DeletedBy.StaffID, booking.DateDeleted, booking.CancelledBy == null ? -1 : booking.CancelledBy.StaffID, booking.DateCancelled, booking.IsPatientMissedAppt, booking.IsProviderMissedAppt, booking.IsEmergency, booking.IsRecurring, booking.RecurringDayOfWeek, booking.RecurringStartTime, booking.RecurringEndTime);

        if (booking.BookingTypeID == 34)
        {
            Booking newBooking = BookingDB.GetByID(booking.BookingID);
            newBooking.SendReminderEmail(booking);
        }

        if (booking.ArrivalTime != DateTime.MinValue && booking.DateStart != startDateTime)
        {
            BookingDB.RemoveArrivalTime(booking.BookingID);
        }
    }
    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";
        }
    }
Пример #20
0
    protected DataTable GetPatientDataTable(int organisation_id)
    {
        Organisation org = OrganisationDB.GetByID(organisation_id);

        Hashtable staffHashOriginal = StaffDB.GetAllInHashtable(true, true, true, false);
        Hashtable staffHash         = new Hashtable();

        foreach (Staff s in staffHashOriginal.Values)
        {
            staffHash[s.Person.PersonID] = s;
        }

        DataTable tbl = RegisterPatientDB.GetPatientsAddedByOrg(organisation_id, GetFromDate(), GetToDate());

        tbl.Columns.Add("organisation_name");
        tbl.Columns.Add("organisation_id");
        for (int i = 0; i < tbl.Rows.Count; i++)
        {
            tbl.Rows[i]["organisation_name"] = org.Name;
            tbl.Rows[i]["organisation_id"]   = org.OrganisationID;
        }

        // sort by most common referrer
        tbl.Columns.Add("referrer_count", typeof(int));
        tbl.Columns.Add("added_by_count", typeof(int));
        tbl.Columns.Add("added_by", typeof(String));
        for (int i = 0; i < tbl.Rows.Count; i++)
        {
            int refCount = 0;
            if (tbl.Rows[i]["referrer_info_referrer_id"] != DBNull.Value)
            {
                for (int j = 0; j < tbl.Rows.Count; j++)
                {
                    if (tbl.Rows[j]["referrer_info_referrer_id"] != DBNull.Value && Convert.ToInt32(tbl.Rows[j]["referrer_info_referrer_id"]) == Convert.ToInt32(tbl.Rows[i]["referrer_info_referrer_id"]))
                    {
                        refCount++;
                    }
                }
            }

            tbl.Rows[i]["referrer_count"] = refCount;

            int addedByCount = 0;
            if (tbl.Rows[i]["patient_person_added_by"] != DBNull.Value)
            {
                for (int j = 0; j < tbl.Rows.Count; j++)
                {
                    if (tbl.Rows[j]["patient_person_added_by"] != DBNull.Value && Convert.ToInt32(tbl.Rows[j]["patient_person_added_by"]) == Convert.ToInt32(tbl.Rows[i]["patient_person_added_by"]))
                    {
                        addedByCount++;
                    }
                }
            }

            tbl.Rows[i]["added_by_count"] = addedByCount;


            if (tbl.Rows[i]["patient_person_added_by"] != DBNull.Value)
            {
                int    staffID = Convert.ToInt32(tbl.Rows[i]["patient_person_added_by"]);
                Staff  s1      = (Staff)staffHash[staffID];
                string s2      = s1.Person.FullnameWithoutMiddlename;
            }


            tbl.Rows[i]["added_by"] = tbl.Rows[i]["patient_person_added_by"] == DBNull.Value ? (object)DBNull.Value : ((Staff)staffHash[Convert.ToInt32(tbl.Rows[i]["patient_person_added_by"])]).Person.FullnameWithoutMiddlename;
        }
        tbl.DefaultView.Sort = "referrer_count DESC, referrer_info_surname, referrer_info_firstname, patient_person_surname, patient_person_firstname, patient_person_middlename";
        tbl = tbl.DefaultView.ToTable();

        return(tbl);
    }
Пример #21
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();
        }
    }
Пример #22
0
    protected void FillGrid()
    {
        if (!IsValidFormID())
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

        Patient patient = PatientDB.GetByID(GetFormID());

        if (patient == null)
        {
            HideTableAndSetErrorMessage(Utilities.IsDev() ? "No patient exists with this ID" : "");
            return;
        }
        patient.Person = PersonDB.GetByID(patient.Person.PersonID);

        lblHeading.Text = Page.Title = "Manage Registrations For :  " + patient.Person.Firstname + " " + patient.Person.Surname;
        this.lnkThisPatient.NavigateUrl = "~/PatientDetailV2.aspx?type=view&id=" + GetFormID().ToString();
        this.lnkThisPatient.Text        = "Back to details for " + patient.Person.FullnameWithoutMiddlename;


        DataTable dt = RegisterPatientDB.GetDataTable_OrganisationsOf(patient.PatientID);

        Session["registerorgtopatient_data"] = dt;


        spn_booking_screen_link.Visible   = UserView.GetInstance().IsAdminView;
        lblSelectOrgBeforeBooking.Visible = dt.Rows.Count == 0 && GetUrlParamType() == UrlParamType.SelectToGoToBookings;
        lnkBookingScreen.Visible          = dt.Rows.Count > 0;
        lnkBookingScreen.NavigateUrl      = String.Format("~/BookingScreenGetPatientOrgsV2.aspx?patient_id={0}", Request["id"]);
        lnkBookingScreen.Text             = "Make Booking";


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


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

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

        if (hideFotter)
        {
            GrdRegistration.FooterRow.Visible = false;
        }
    }