Beispiel #1
0
    protected void GrdReferrer_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label   lblId   = (Label)GrdReferrer.Rows[e.RowIndex].FindControl("lblId");
        TextBox txtName = (TextBox)GrdReferrer.Rows[e.RowIndex].FindControl("txtName");
        TextBox txtABN  = (TextBox)GrdReferrer.Rows[e.RowIndex].FindControl("txtABN");
        TextBox txtACN  = (TextBox)GrdReferrer.Rows[e.RowIndex].FindControl("txtACN");


        Organisation org = OrganisationDB.GetByID(Convert.ToInt32(lblId.Text));

        OrganisationDB.UpdateExtOrg(
            org.OrganisationID,
            org.OrganisationType.OrganisationTypeID,
            txtName.Text,
            txtACN.Text,
            txtABN.Text,
            DateTime.Now,
            org.IsDebtor,
            org.IsCreditor,
            org.BpayAccount,
            org.Comment);


        GrdReferrer.EditIndex = -1;
        FillGrid();
    }
    protected void GrdRegistration_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            DropDownList ddlReferrer           = (DropDownList)GrdRegistration.FooterRow.FindControl("ddlNewReferrer");
            TextBox      txtProviderNumber     = (TextBox)GrdRegistration.FooterRow.FindControl("txtNewProviderNumber");
            DropDownList ddlIsClinic           = (DropDownList)GrdRegistration.FooterRow.FindControl("ddlNewIsClinic");
            CheckBox     chkIsReportEveryVisit = (CheckBox)GrdRegistration.FooterRow.FindControl("chkNewIsReportEveryVisit");
            CheckBox     chkIsBatchSendAllPatientsTreatmentNotes = (CheckBox)GrdRegistration.FooterRow.FindControl("chkNewIsBatchSendAllPatientsTreatmentNotes");

            Organisation org = OrganisationDB.GetByID(GetFormID());
            if (org == null)
            {
                HideTableAndSetErrorMessage("");
                return;
            }

            try
            {
                RegisterReferrerDB.Insert(org.OrganisationID, Convert.ToInt32(ddlReferrer.SelectedValue), txtProviderNumber.Text, chkIsReportEveryVisit.Checked, chkIsBatchSendAllPatientsTreatmentNotes.Checked);
            }
            catch (UniqueConstraintException)
            {
                // happens when 2 forms allow adding - do nothing and let form re-update
            }
            FillGrid();
        }
    }
    protected void Select(int orgID)
    {
        Organisation org = OrganisationDB.GetByID(orgID);

        Session["OrgID"]   = org.OrganisationID.ToString();
        Session["OrgName"] = org.Name;

        if (Request.QueryString["from_url"] != null)
        {
            Response.Redirect(Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)));
        }
        else if (Session["PatientID"] != null)
        {
            Response.Redirect("~/BookingNextAvailableV2.aspx");
        }
        else
        {
            //Response.Redirect("~/Default.aspx");

            string ndays          = Session["PatientId"] == null ? "1" : "3"; // provider login shows just today, patient iew 3 days
            bool   isExternalView = Session["IsExternal"] != null && Convert.ToBoolean(Session["IsExternal"]);
            if (isExternalView)
            {
                ndays = (int)Session["StaffID"] != -5 ? "3" : "4";  // external login shows 3 days (less days looks better), but 4 days for call center (for more functionality)
            }
            Response.Redirect("~/BookingsV2.aspx?orgs=" + Session["OrgID"] + "&ndays=" + ndays);
        }
    }
Beispiel #4
0
 public static void Delete(int organisation_id)
 {
     try
     {
         Organisation o = OrganisationDB.GetByID(organisation_id);
         if (o != null)
         {
             DBBase.ExecuteNonResult("DELETE FROM Organisation WHERE organisation_id = " + organisation_id.ToString());
             if (EntityDB.NumForeignKeyDependencies(o.EntityID) == 0)
             {
                 EntityDB.Delete(o.EntityID, false);
             }
         }
     }
     catch (System.Data.SqlClient.SqlException sqlEx)
     {
         if (sqlEx.Errors.Count > 0 && sqlEx.Errors[0].Number == 547) // Assume the interesting stuff is in the first error
         {
             throw new ForeignKeyConstraintException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name, sqlEx);
         }
         else
         {
             throw;
         }
     }
 }
Beispiel #5
0
    protected void GrdRegistration_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label        lblId             = (Label)GrdRegistration.Rows[e.RowIndex].FindControl("lblId");
        DropDownList ddlStaff          = (DropDownList)GrdRegistration.Rows[e.RowIndex].FindControl("ddlStaff");
        TextBox      txtProviderNumber = (TextBox)GrdRegistration.Rows[e.RowIndex].FindControl("txtProviderNumber");
        CheckBox     chkMainProvider   = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkMainProvider");
        CheckBox     chkIncMondays     = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncMondays");
        CheckBox     chkIncTuesdays    = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncTuesdays");
        CheckBox     chkIncWednesdays  = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncWednesdays");
        CheckBox     chkIncThursdays   = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncThursdays");
        CheckBox     chkIncFridays     = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncFridays");
        CheckBox     chkIncSaturdays   = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncSaturdays");
        CheckBox     chkIncSundays     = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncSundays");

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

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

        RegisterStaffDB.Update(Convert.ToInt32(lblId.Text), org.OrganisationID, Convert.ToInt32(ddlStaff.SelectedValue), txtProviderNumber.Text, chkMainProvider.Checked,
                               !chkIncSundays.Checked, !chkIncMondays.Checked, !chkIncTuesdays.Checked, !chkIncWednesdays.Checked, !chkIncThursdays.Checked, !chkIncFridays.Checked, !chkIncSaturdays.Checked);
        if (chkMainProvider.Checked)
        {
            RegisterStaffDB.UpdateAllOtherStaffAsNotMainProviders(org.OrganisationID, Convert.ToInt32(ddlStaff.SelectedValue));
        }

        GrdRegistration.EditIndex = -1;
        FillGrid();
    }
    protected void UpdateList()
    {
        Staff        staff = IsValidFormStaffID() ? StaffDB.GetByID(GetFormStaffID()) : null;
        Organisation org   = IsValidFormOrgID()   ? OrganisationDB.GetByID(GetFormOrgID()) : null;

        UpdateList(org, staff);
    }
Beispiel #7
0
    protected void FillGrid()
    {
        Organisation org = IsValidFormOrgID() ? OrganisationDB.GetByID(GetFormOrgID()) : null;

        if (!IsValidFormOrgID())
        {
            lblHeading.Text = "Maintain Letters";
        }
        else if (org == null)
        {
            lblHeading.Text = "Maintain Default Letters";
        }
        else
        {
            lblHeading.Text         = "Maintain Letters For ";
            lnkToEntity.Text        = org.Name;
            lnkToEntity.NavigateUrl = "OrganisationDetailV2.aspx?type=view&id=" + org.OrganisationID;
        }

        DataTable dt = IsValidFormOrgID() ? LetterDB.GetDataTable_ByOrg(GetFormOrgID(), GetFormOrgID() == 0 ? Convert.ToInt32(Session["SiteID"]) : -1) : LetterDB.GetDataTable(Convert.ToInt32(Session["SiteID"]));

        Session["letter_data"] = dt;

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


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

            int TotalColumns = GrdLetter.Rows[0].Cells.Count;
            GrdLetter.Rows[0].Cells.Clear();
            GrdLetter.Rows[0].Cells.Add(new TableCell());
            GrdLetter.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdLetter.Rows[0].Cells[0].Text       = "No Record Found";
        }
    }
    protected void FillGrid()
    {
        Organisation org = null;

        if (IsValidFormID())
        {
            org = OrganisationDB.GetByID(GetFormID());
        }


        DataTable dt = org == null ? dt = StockDB.GetDataTable(!UserView.GetInstance().IsAgedCareView ? 5 : 6) : dt = StockDB.GetDataTable_ByOrg(org.OrganisationID);

        Session["registerstocktoorg_data"] = dt;

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


            try
            {
                GrdRegistration.DataBind();
            }
            catch (Exception ex)
            {
                SetErrorMessage("", 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 (org == null || hideFotter)
        {
            GrdRegistration.FooterRow.Visible = false;
        }
    }
Beispiel #9
0
 protected void ResetOrgName()
 {
     if (txtUpdateOrganisationID.Text.Length == 0)
     {
         txtUpdateOrganisationName.Text = "";
     }
     else
     {
         Organisation org = OrganisationDB.GetByID(Convert.ToInt32(txtUpdateOrganisationID.Text));
         txtUpdateOrganisationName.Text = org.Name;
     }
 }
    protected void FillGridUpdateHistory()
    {
        Organisation org = null;

        if (IsValidFormID())
        {
            org = OrganisationDB.GetByID(GetFormID());
        }

        DataTable dt = org == null?StockUpdateHistoryDB.GetDataTable() : StockUpdateHistoryDB.GetDataTable_ByOrg(org.OrganisationID);

        Session["registerstockupdatehistory_data"] = dt;

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


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

            int TotalColumns = GrdUpdateHistory.Rows[0].Cells.Count;
            GrdUpdateHistory.Rows[0].Cells.Clear();
            GrdUpdateHistory.Rows[0].Cells.Add(new TableCell());
            GrdUpdateHistory.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdUpdateHistory.Rows[0].Cells[0].Text       = "No Record Found";
        }
    }
    protected void btnExport_Click(object sender, EventArgs 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)
        {
            dt.Rows.RemoveAt(0);
        }


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

        sb.Append("ID").Append(",");
        sb.Append("Clinic/Fac").Append(",");
        sb.Append("Patient").Append(",");
        sb.Append("Date Added To Clinic/Fac").Append(",");
        sb.Append("Last Booking").Append(",");
        sb.Append("Next Booking").Append(",");
        sb.Append("EPC Expires").Append(",");
        sb.Append("EPC's Remaining").Append(",");
        sb.Append("Last Recall Letter Sent");
        sb.AppendLine();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sb.Append(dt.Rows[i]["patient_id"].ToString()).Append(",");
            sb.Append(org.Name).Append(",");
            sb.Append(dt.Rows[i]["firstname"].ToString() + " " + dt.Rows[i]["surname"].ToString()).Append(",");
            sb.Append(((DateTime)dt.Rows[i]["register_patient_date_added"]).ToString("dd-MM-yyyy")).Append(",");
            sb.Append(dt.Rows[i]["last_booking_date"] == DBNull.Value ? "" : ((DateTime)dt.Rows[i]["last_booking_date"]).ToString("dd-MM-yyyy")).Append(",");
            sb.Append(dt.Rows[i]["next_booking_date"] == DBNull.Value ? "" : ((DateTime)dt.Rows[i]["next_booking_date"]).ToString("dd-MM-yyyy")).Append(",");
            sb.Append(dt.Rows[i]["epc_expire_date"] == DBNull.Value ? "" : ((DateTime)dt.Rows[i]["epc_expire_date"]).ToString("dd-MM-yyyy")).Append(",");
            sb.Append(dt.Rows[i]["epc_count_remaining"].ToString()).Append(",");
            sb.Append(dt.Rows[i]["most_recent_recall_sent"] == DBNull.Value ? "" : ((DateTime)dt.Rows[i]["most_recent_recall_sent"]).ToString("dd-MM-yyyy"));
            sb.AppendLine();
        }

        ExportCSV(Response, sb.ToString(), "Patients of " + org.Name + ".csv");
    }
    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();
    }
Beispiel #13
0
    protected void GetClashOneTimeBooking()
    {
        string org_id          = Request.QueryString["org"];
        string staff_id        = Request.QueryString["staff"];
        string booking_id      = Request.QueryString["edit_booking_id"];
        string booking_type_id = Request.QueryString["booking_type_id"];

        string start_datetime = Request.QueryString["start_datetime"];
        string end_datetime   = Request.QueryString["end_datetime"];


        if (start_datetime == null || !Regex.IsMatch(start_datetime, @"^\d{4}_\d{2}_\d{2}_\d{4}$") ||
            end_datetime == null || !Regex.IsMatch(end_datetime, @"^\d{4}_\d{2}_\d{2}_\d{4}$") ||
            org_id == null || !Regex.IsMatch(org_id, @"^\-?\d+$") ||
            staff_id == null || !Regex.IsMatch(staff_id, @"^\-?\d+$") ||
            booking_id == null || !Regex.IsMatch(booking_id, @"^\-?\d+$"))
        {
            throw new CustomMessageException();
        }

        Organisation org     = OrganisationDB.GetByID(Convert.ToInt32(org_id));
        Staff        staff   = StaffDB.GetByID(Convert.ToInt32(staff_id));
        Booking      booking = booking_id == "-1" ? null : BookingDB.GetByID(Convert.ToInt32(booking_id));

        if (booking != null && booking_type_id == "-1")
        {
            booking_type_id = booking.BookingTypeID.ToString();
        }

        if ((org_id != "0" && org == null) ||
            (staff_id != "-1" && staff == null) ||
            (booking_id != "-1" && booking == null) ||
            (booking_type_id == null || (booking_type_id != "34" && booking_type_id != "340" && booking_type_id != "341" && booking_type_id != "342")))
        {
            throw new CustomMessageException();
        }

        DateTime startDateTime = ConvertStringToDateTime(start_datetime);
        DateTime endDateTime   = ConvertStringToDateTime(end_datetime);

        Booking[] bookings            = BookingDB.GetToCheckOverlap_OneTime(startDateTime, endDateTime, staff, org, booking_type_id == "342", true, false);
        Booking[] overlappingBookings = Booking.GetOverlappingBookings(bookings, startDateTime, endDateTime, booking);
        Response.Write(GetLinks(overlappingBookings));
    }
Beispiel #14
0
    protected void UpdateInfo()
    {
        if (this.PatientID == -1)
        {
            return;
        }

        HealthCard[] healthcards   = HealthCardDB.GetAllByPatientID(this.PatientID, this.ShowOnlyActiveCard);
        HealthCard   medicareCard  = null;
        HealthCard   dvaCard       = null;
        HealthCard   insuranceCard = null;

        for (int i = 0; i < healthcards.Length; i++)
        {
            if (healthcards[i].Organisation.OrganisationID == -1)
            {
                medicareCard = healthcards[i];
            }
            else if (healthcards[i].Organisation.OrganisationID == -2)
            {
                dvaCard = healthcards[i];
            }
            else
            {
                healthcards[i].Organisation = OrganisationDB.GetByID(healthcards[i].Organisation.OrganisationID);
                if (healthcards[i].Organisation.OrganisationType.OrganisationTypeGroup.ID == 7)
                {
                    insuranceCard = healthcards[i];
                }
            }
        }

        if (this.ShowOnlyActiveCard)
        {
            HideInactiveCards(medicareCard == null || !medicareCard.IsActive, dvaCard == null || !dvaCard.IsActive, insuranceCard == null || !insuranceCard.IsActive);
        }

        no_epc_message_row.Visible = this.ShowNoEpcMessageRow && medicareCard == null && dvaCard == null && insuranceCard == null;

        UpdateCard(medicareCard, CardType.Medicare);
        UpdateCard(dvaCard, CardType.DVA);
        UpdateCard(insuranceCard, CardType.Insurance);
    }
    protected void ResetOrgName()
    {
        if (txtUpdateOrganisationID.Text.Length == 0)
        {
            txtUpdateOrganisationName.Text    = "";
            txtUpdateOrganisationName.Visible = true;
            lblUpdateOrganisationName.Visible = false;
        }
        else
        {
            Organisation org = OrganisationDB.GetByID(Convert.ToInt32(txtUpdateOrganisationID.Text));
            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;
        }

        UpdateTextbox(txtUpdateOrganisationName, lblUpdateOrganisationName, txtUpdateOrganisationID.Text.Length == 0);
    }
Beispiel #16
0
    public static void UpdateAndCheckWarning(int organisation_id, int offering_id, int qtyUsed)
    {
        Organisation org      = OrganisationDB.GetByID(organisation_id);
        Offering     offering = OfferingDB.GetByID(offering_id);

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

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

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

                StockDB.UpdateQuantity(stockList[i].StockID, postQty);
            }
        }
    }
Beispiel #17
0
    protected void GrdLetter_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            DropDownList ddlLetterType       = (DropDownList)GrdLetter.FooterRow.FindControl("ddlNewLetterType");
            DropDownList ddlSite             = (DropDownList)GrdLetter.FooterRow.FindControl("ddlNewSite");
            TextBox      txtCode             = (TextBox)GrdLetter.FooterRow.FindControl("txtNewCode");
            TextBox      txtMessage          = (TextBox)GrdLetter.FooterRow.FindControl("txtNewMessage");
            TextBox      txtDocName          = (TextBox)GrdLetter.FooterRow.FindControl("txtNewDocName");
            CheckBox     chkIsSendToMedico   = (CheckBox)GrdLetter.FooterRow.FindControl("chkNewIsSendToMedico");
            CheckBox     chkIsAllowedReclaim = (CheckBox)GrdLetter.FooterRow.FindControl("chkNewIsAllowedReclaim");
            //CheckBox     chkIsManualOverride = (CheckBox)GrdLetter.FooterRow.FindControl("chkNewIsManualOverride");
            //DropDownList ddlNumCopiesToPrint = (DropDownList)GrdLetter.FooterRow.FindControl("ddlNewNumCopiesToPrint");

            txtDocName.Text = txtDocName.Text.Trim();
            if (txtDocName.Text.Length > 0 &&
                (!txtDocName.Text.EndsWith(".docx") &&
                 !txtDocName.Text.EndsWith(".doc") &&
                 !txtDocName.Text.EndsWith(".dot")))
            {
                SetErrorMessage("Only .docx, .doc, and .dot files allowed");
                return;
            }


            if (txtCode.Text.Length == 0 &&
                (Convert.ToInt32(ddlLetterType.SelectedValue) == 235 ||  // dva reject letter
                 Convert.ToInt32(ddlLetterType.SelectedValue) == 234 ||  // medicare reject letter
                 Convert.ToInt32(ddlLetterType.SelectedValue) == 214 ||  // organisation reject letter
                 Convert.ToInt32(ddlLetterType.SelectedValue) == 3))     // patient reject letter
            {
                SetErrorMessage("Reject Code can not be empty for letters of type " + ddlLetterType.SelectedItem.Text);
                return;
            }

            Organisation org     = IsValidFormOrgID() ? OrganisationDB.GetByID(GetFormOrgID()) : null;
            int          site_id = (GrdLetter.FooterRow.Cells[3].CssClass == "hiddencol") ? Convert.ToInt32(Session["SiteID"]) : Convert.ToInt32(ddlSite.SelectedValue);
            LetterDB.Insert((org == null) ? 0 : org.OrganisationID, Convert.ToInt32(ddlLetterType.SelectedValue), site_id, txtCode.Text, txtMessage.Text, txtDocName.Text.Trim(), chkIsSendToMedico.Checked, chkIsAllowedReclaim.Checked, false, 1, false);

            FillGrid();
        }
    }
Beispiel #18
0
    protected string GetDirectoryToUploadTo()
    {
        if (!IsValidFormOrgID())
        {
            throw new CustomMessageException("Invalid org");
        }

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

        string dir = Letter.GetLettersDirectory();

        if (org != null) // specific dir for that org
        {
            dir += org.OrganisationID + @"\";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            if (!Directory.Exists(dir))
            {
                throw new CustomMessageException("Letters directory doesn't exist");   // so they are currenty using default letters
            }
        }
        else // get default letters for the site
        {
            dir += @"Default\" + Session["SiteID"] + @"\";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            if (!Directory.Exists(dir))
            {
                throw new CustomMessageException("Letters directory doesn't exist");
            }
        }

        return(dir);
    }
    protected void GrdRegistration_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            DropDownList ddlPatient = (DropDownList)GrdRegistration.FooterRow.FindControl("ddlNewPatient");

            Organisation org = OrganisationDB.GetByID(GetFormID());
            if (org == null)
            {
                HideTableAndSetErrorMessage("");
                return;
            }

            try
            {
                RegisterPatientDB.Insert(org.OrganisationID, Convert.ToInt32(ddlPatient.SelectedValue));
            }
            catch (UniqueConstraintException)
            {
                // happens when 2 forms allow adding - do nothing and let form re-update
            }
            FillGrid();
        }
    }
    protected void GrdRegistration_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            Organisation org = OrganisationDB.GetByID(GetFormID());
            if (org == null)
            {
                HideTableAndSetErrorMessage("");
                return;
            }

            DropDownList ddlOffering          = (DropDownList)GrdRegistration.FooterRow.FindControl("ddlNewOffering");
            DropDownList ddlWarningAmount     = (DropDownList)GrdRegistration.FooterRow.FindControl("ddlNewWarningAmount");
            DropDownList ddlQuantity_Zeros    = (DropDownList)GrdRegistration.FooterRow.FindControl("ddlNewQuantity_Zeros");
            DropDownList ddlQuantity_Tens     = (DropDownList)GrdRegistration.FooterRow.FindControl("ddlNewQuantity_Tens");
            DropDownList ddlQuantity_Hundreds = (DropDownList)GrdRegistration.FooterRow.FindControl("ddlNewQuantity_Hundreds");

            try
            {
                Stock stock = StockDB.GetOfferingByOrgAndOffering(org.OrganisationID, Convert.ToInt32(ddlOffering.SelectedValue));
                if (stock == null)
                {
                    int qty = 100 * Convert.ToInt32(ddlQuantity_Hundreds.SelectedValue) + 10 * Convert.ToInt32(ddlQuantity_Tens.SelectedValue) + Convert.ToInt32(ddlQuantity_Zeros.SelectedValue);
                    StockDB.Insert(org.OrganisationID, Convert.ToInt32(ddlOffering.SelectedValue), qty, Convert.ToInt32(ddlWarningAmount.SelectedValue));
                    StockUpdateHistoryDB.Insert(org.OrganisationID, Convert.ToInt32(ddlOffering.SelectedValue), qty, true, false, Convert.ToInt32(Session["StaffID"]));
                }
            }
            catch (UniqueConstraintException)
            {
                // happens when 2 forms allow adding - do nothing and let form re-update
                ;
            }
            FillGrid();
            FillGridUpdateHistory();
        }
    }
    protected void GrdRegistration_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label        lblId                 = (Label)GrdRegistration.Rows[e.RowIndex].FindControl("lblId");
        DropDownList ddlReferrer           = (DropDownList)GrdRegistration.Rows[e.RowIndex].FindControl("ddlReferrer");
        TextBox      txtProviderNumber     = (TextBox)GrdRegistration.Rows[e.RowIndex].FindControl("txtProviderNumber");
        DropDownList ddlIsClinic           = (DropDownList)GrdRegistration.Rows[e.RowIndex].FindControl("ddlIsClinic");
        CheckBox     chkIsReportEveryVisit = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIsReportEveryVisit");
        CheckBox     chkIsBatchSendAllPatientsTreatmentNotes = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIsBatchSendAllPatientsTreatmentNotes");

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

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

        RegisterReferrer registerReferrer = RegisterReferrerDB.GetByID(Convert.ToInt32(lblId.Text));

        RegisterReferrerDB.Update(Convert.ToInt32(lblId.Text), org.OrganisationID, Convert.ToInt32(ddlReferrer.SelectedValue), txtProviderNumber.Text, chkIsReportEveryVisit.Checked, chkIsBatchSendAllPatientsTreatmentNotes.Checked, registerReferrer.DateLastBatchSendAllPatientsTreatmentNotes);

        GrdRegistration.EditIndex = -1;
        FillGrid();
    }
Beispiel #22
0
    protected void GoTo(string db, int orgID, int siteID, int patientID)
    {
        //lblInfo1.Text += "GET<br/>DB: " + db + "<br />Org: " + orgID;

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

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

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

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

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


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

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

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



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


        // Go to booking page with this org

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

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

        else
        {
            Response.Redirect("~/Default.aspx", false);
        }
        return;
    }
    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;
                }
            }
        }
    }
Beispiel #25
0
    protected void SetUrlFieldsAndHeading()
    {
        lblHeading.Text = "Create Cash Invoice";

        try
        {
            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();
                }

                txtUpdatePatientID.Text   = patient.PatientID.ToString();
                txtUpdatePatientName.Text = patient.Person.FullnameWithoutMiddlename;
            }

            string org_id = Request.QueryString["org"];
            if (org_id != null && org_id != "-1")
            {
                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;
            }


            if (txtUpdatePatientID.Text.Length > 0 && txtUpdateOrganisationID.Text.Length > 0)
            {
                lblHeading.Text = "Create Cash Invoice : " + txtUpdatePatientName.Text + " at " + txtUpdateOrganisationName.Text;
                patient_row.Attributes["class"] = "hiddencol";
                org_row.Attributes["class"]     = "hiddencol";
            }
            if (txtUpdatePatientID.Text.Length > 0)
            {
                lblHeading.Text = "Create Cash Invoice : " + txtUpdatePatientName.Text;
                patient_row.Attributes["class"] = "hiddencol";
            }
            if (txtUpdateOrganisationID.Text.Length > 0)
            {
                lblHeading.Text             = "Create Cash Invoice : " + txtUpdateOrganisationName.Text;
                org_row.Attributes["class"] = "hiddencol";
            }
        }
        catch (CustomMessageException)
        {
            SetErrorMessage();
        }
    }
Beispiel #26
0
    private void InvoiceItemsControl_SubmitButtonClicked(object sender, EventArgs e)
    {
        try
        {
            if (txtUpdateOrganisationID.Text.Length == 0)
            {
                throw new CustomMessageException("Please select an organisation.");
            }

            Organisation org = OrganisationDB.GetByID(Convert.ToInt32(txtUpdateOrganisationID.Text));
            if (org == null)
            {
                throw new Exception("Unknown organisation selected. Pelase contact your system administrator.");
            }


            // keep id's to delete if exception and need to roll back
            int       invID            = -2;
            ArrayList invLineIDs       = new ArrayList();
            ArrayList offeringOrderIDs = new ArrayList();

            // used to check update stock and check warning level emails sent
            ArrayList invoiceLines = new ArrayList();


            try
            {
                int patientID = txtUpdatePatientID.Text.Length == 0 ? -1 : Convert.ToInt32(txtUpdatePatientID.Text);

                DataTable dt_selected_list = this.invoiceItemsControl.GetSelectedList();

                decimal total = 0;
                decimal gst   = 0;
                for (int i = 0; i < dt_selected_list.Rows.Count; i++)
                {
                    total += Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_price"]);
                    gst   += Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_gst"]);
                }

                invID = InvoiceDB.Insert(108, -1, 0, patientID, org.OrganisationID, "", "", Convert.ToInt32(Session["StaffID"]), Convert.ToInt32(Session["SiteID"]), total + gst, gst, false, false, false, DateTime.MinValue);
                for (int i = 0; i < dt_selected_list.Rows.Count; i++)
                {
                    int offeringOrderID = -1;
                    if (Convert.ToBoolean(dt_selected_list.Rows[i]["on_order"]))
                    {
                        OfferingOrderDB.Insert(
                            Convert.ToInt32(dt_selected_list.Rows[i]["offering_id"]),
                            org.OrganisationID,
                            Convert.ToInt32(Session["StaffID"]),
                            patientID,
                            Convert.ToInt32(dt_selected_list.Rows[i]["quantity"]),
                            DateTime.Today,
                            DateTime.MinValue,
                            DateTime.MinValue,
                            string.Empty
                            );
                        offeringOrderIDs.Add(offeringOrderID);
                    }


                    int invoiceLineID = InvoiceLineDB.Insert(invID, -1, Convert.ToInt32(dt_selected_list.Rows[i]["offering_id"]), Convert.ToInt32(dt_selected_list.Rows[i]["quantity"]), Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_price"]) + Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_gst"]), Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_gst"]), "", "", offeringOrderID);
                    invLineIDs.Add(invoiceLineID);
                    invoiceLines.Add(new InvoiceLine(invoiceLineID, invID, -1, Convert.ToInt32(dt_selected_list.Rows[i]["offering_id"]), Convert.ToInt32(dt_selected_list.Rows[i]["quantity"]), Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_price"]) + Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_gst"]), Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_gst"]), "", "", offeringOrderID));
                }

                Session.Remove("data_selected");


                // successfully completed, so update and check warning level for stocks
                foreach (InvoiceLine invoiceLine in invoiceLines)
                {
                    if (invoiceLine.OfferingOrder == null) // stkip counting down if item is on order
                    {
                        StockDB.UpdateAndCheckWarning(org.OrganisationID, invoiceLine.Offering.OfferingID, (int)invoiceLine.Quantity);
                    }
                }
            }
            catch (Exception ex)
            {
                // roll back...
                foreach (int invLineID in invLineIDs)
                {
                    InvoiceLineDB.Delete(invLineID);
                }
                foreach (int offeringOrderID in offeringOrderIDs)
                {
                    OfferingOrderDB.Delete(offeringOrderID);
                }
                InvoiceDB.Delete(invID);

                throw;
            }

            Response.Redirect("~/Invoice_ViewV2.aspx?invoice_id=" + invID + "&is_popup=0");
            //Response.Redirect("~/InvoiceListV2.aspx?start_date=" + DateTime.Today.ToString("yyyy_MM_dd") + "&end_date=" + DateTime.Today.AddDays(1).ToString("yyyy_MM_dd") + "&inc_medicare=0&inc_dva=0&inc_private=1");
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
            return;
        }
        catch (Exception ex)
        {
            SetErrorMessage("", ex.ToString());
            return;
        }
    }
Beispiel #27
0
    protected void GrdOrganisation_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label        lblId     = (Label)GrdOrganisation.Rows[e.RowIndex].FindControl("lblId");
        DropDownList ddlParent = (DropDownList)GrdOrganisation.Rows[e.RowIndex].FindControl("ddlParent");
        DropDownList ddlUseParentOffernigPrices = (DropDownList)GrdOrganisation.Rows[e.RowIndex].FindControl("ddlUseParentOffernigPrices");
        TextBox      txtName         = (TextBox)GrdOrganisation.Rows[e.RowIndex].FindControl("txtName");
        DropDownList ddlType         = (DropDownList)GrdOrganisation.Rows[e.RowIndex].FindControl("ddlType");
        DropDownList ddlCustType     = (DropDownList)GrdOrganisation.Rows[e.RowIndex].FindControl("ddlCustType");
        TextBox      txtABN          = (TextBox)GrdOrganisation.Rows[e.RowIndex].FindControl("txtABN");
        TextBox      txtACN          = (TextBox)GrdOrganisation.Rows[e.RowIndex].FindControl("txtACN");
        TextBox      txtBPayAccount  = (TextBox)GrdOrganisation.Rows[e.RowIndex].FindControl("txtBPayAccount");
        DropDownList ddlServiceCycle = (DropDownList)GrdOrganisation.Rows[e.RowIndex].FindControl("ddlServiceCycle");
        DropDownList ddlIsDebtor     = (DropDownList)GrdOrganisation.Rows[e.RowIndex].FindControl("ddlIsDebtor");
        DropDownList ddlIsCreditor   = (DropDownList)GrdOrganisation.Rows[e.RowIndex].FindControl("ddlIsCreditor");
        DropDownList ddlFreeServices = (DropDownList)GrdOrganisation.Rows[e.RowIndex].FindControl("ddlFreeServices");
        TextBox      txtStartDate    = (TextBox)GrdOrganisation.Rows[e.RowIndex].FindControl("txtStartDate");
        TextBox      txtEndDate      = (TextBox)GrdOrganisation.Rows[e.RowIndex].FindControl("txtEndDate");


        Organisation org = OrganisationDB.GetByID(Convert.ToInt32(lblId.Text));

        UrlParamType urlParamType = GetUrlParamType();
        int          orgTypeID    = Convert.ToInt32(ddlType.SelectedValue);

        if (urlParamType == UrlParamType.Clinic)
        {
            orgTypeID = 218;
        }

        DateTime startDate = GetDate(txtStartDate.Text.Trim());
        DateTime endDate   = GetDate(txtEndDate.Text.Trim());

        if (urlParamType == UrlParamType.External)
        {
            if (urlParamType == UrlParamType.External && IsValidFormOrgTypeIDs() && GetFormOrgTypeIDs() == "191")
            {
                OrganisationDB.UpdateExtOrg(Convert.ToInt32(lblId.Text), Convert.ToInt32(GetFormOrgTypeIDs()), txtName.Text, txtACN.Text, txtABN.Text, DateTime.Now,
                                            org.IsDebtor, org.IsCreditor, org.BpayAccount, org.Comment);
            }
            else
            {
                OrganisationDB.Update(Convert.ToInt32(lblId.Text), Convert.ToInt32(ddlParent.SelectedValue), org.UseParentOffernigPrices, Convert.ToInt32(ddlType.SelectedValue), Convert.ToInt32(ddlCustType.SelectedValue), txtName.Text,

                                      org.Acn, org.Abn, org.IsDebtor, org.IsCreditor, org.BpayAccount, org.WeeksPerServiceCycle, org.StartDate, org.EndDate, org.Comment, org.FreeServices,
                                      //txtACN.Text, txtABN.Text,
                                      //Convert.ToBoolean(ddlIsDebtor.SelectedValue), Convert.ToBoolean(ddlIsCreditor.SelectedValue), txtBPayAccount.Text, Convert.ToInt32(ddlServiceCycle.SelectedValue),
                                      //org.StartDate, org.EndDate, org.Comment, Convert.ToInt32(ddlFreeServices.SelectedValue),

                                      org.ExclSun, org.ExclMon, org.ExclTue, org.ExclWed, org.ExclThu, org.ExclFri, org.ExclSat,
                                      org.SunStartTime, org.SunEndTime,
                                      org.MonStartTime, org.MonEndTime,
                                      org.TueStartTime, org.TueEndTime,
                                      org.WedStartTime, org.WedEndTime,
                                      org.ThuStartTime, org.ThuEndTime,
                                      org.FriStartTime, org.FriEndTime,
                                      org.SatStartTime, org.SatEndTime,
                                      org.SunLunchStartTime, org.SunLunchEndTime,
                                      org.MonLunchStartTime, org.MonLunchEndTime,
                                      org.TueLunchStartTime, org.TueLunchEndTime,
                                      org.WedLunchStartTime, org.WedLunchEndTime,
                                      org.ThuLunchStartTime, org.ThuLunchEndTime,
                                      org.FriLunchStartTime, org.FriLunchEndTime,
                                      org.SatLunchStartTime, org.SatLunchEndTime,
                                      org.LastBatchRun);
            }
        }
        else
        {
            OrganisationDB.Update(Convert.ToInt32(lblId.Text), Convert.ToInt32(ddlParent.SelectedValue), Convert.ToBoolean(ddlUseParentOffernigPrices.SelectedValue), Convert.ToInt32(ddlType.SelectedValue), Convert.ToInt32(ddlCustType.SelectedValue), txtName.Text, txtACN.Text, txtABN.Text,
                                  org.IsDebtor, org.IsCreditor, txtBPayAccount.Text, Convert.ToInt32(ddlServiceCycle.SelectedValue),
                                  startDate, endDate, org.Comment, Convert.ToInt32(ddlFreeServices.SelectedValue),
                                  org.ExclSun, org.ExclMon, org.ExclTue, org.ExclWed, org.ExclThu, org.ExclFri, org.ExclSat,
                                  org.SunStartTime, org.SunEndTime,
                                  org.MonStartTime, org.MonEndTime,
                                  org.TueStartTime, org.TueEndTime,
                                  org.WedStartTime, org.WedEndTime,
                                  org.ThuStartTime, org.ThuEndTime,
                                  org.FriStartTime, org.FriEndTime,
                                  org.SatStartTime, org.SatEndTime,
                                  org.SunLunchStartTime, org.SunLunchEndTime,
                                  org.MonLunchStartTime, org.MonLunchEndTime,
                                  org.TueLunchStartTime, org.TueLunchEndTime,
                                  org.WedLunchStartTime, org.WedLunchEndTime,
                                  org.ThuLunchStartTime, org.ThuLunchEndTime,
                                  org.FriLunchStartTime, org.FriLunchEndTime,
                                  org.SatLunchStartTime, org.SatLunchEndTime, org.LastBatchRun);
        }


        GrdOrganisation.EditIndex = -1;
        FillGrid();
    }
    protected void FillGrid()
    {
        DateTime fromDate = IsValidDate(txtStartDate.Text) ? GetDate(txtStartDate.Text)                             : DateTime.MinValue;
        DateTime toDate   = IsValidDate(txtEndDate.Text)   ? GetDate(txtEndDate.Text).Add(new TimeSpan(23, 59, 59)) : DateTime.MinValue;

        ArrayList list = new ArrayList();

        if (chkIncCompleted.Checked)
        {
            list.Add("187");
        }
        if (chkIncCancelled.Checked)
        {
            list.Add("188");
        }
        if (chkIncIncomplete.Checked)
        {
            list.Add("0");
        }
        if (chkIncDeleted.Checked)
        {
            list.Add("-1");
        }
        string statusIDsToInclude = string.Join(",", (string[])list.ToArray(Type.GetType("System.String")));


        DataTable dt = null;

        /*
         * if (IsValidFormPatient())
         * {
         *  int patient_id = GetFormPatient(false);
         *  Patient patient = PatientDB.GetByID(patient_id);
         *  if (patient == null)
         *      throw new CustomMessageException("Invalid patient ID");
         *
         *  heading.InnerText = "Bookings List for : ";
         *  lnkToEntity.Text = patient.Person.FullnameWithoutMiddlename;
         *  lnkToEntity.NavigateUrl = "PatientDetailV2.aspx?type=view&id=" + patient.PatientID;
         *
         *  dt = BookingDB.GetDataTable_Between(fromDate, toDate, null, null, patient, chkIncDeleted.Checked, statusIDsToInclude, false, txtBookingNbrSearch.Text.Trim());
         * }
         * else if (IsValidFormOrganisation())
         * {
         *  int org_id = GetFormOrganisation(false);
         *  Organisation org = OrganisationDB.GetByID(org_id);
         *  if (org == null)
         *      throw new CustomMessageException("Invalid organisation ID");
         *
         *  heading.InnerText = "Bookings List for : ";
         *  lnkToEntity.Text = org.Name;
         *  lnkToEntity.NavigateUrl = "OrganisationDetailV2.aspx?type=view&id=" + org.OrganisationID;
         *
         *  dt = BookingDB.GetDataTable_Between(fromDate, toDate, null, new Organisation[] { org }, null, chkIncDeleted.Checked, statusIDsToInclude, false, txtBookingNbrSearch.Text.Trim());
         * }
         * else if (IsValidFormProvider())
         * {
         *  int provider_id = GetFormProvider(false);
         *  Staff provider = StaffDB.GetByID(provider_id);
         *  if (provider == null)
         *      throw new CustomMessageException("Invalid provider ID");
         *
         *  heading.InnerText = "Bookings List for : ";
         *  lnkToEntity.Text = provider.Person.FullnameWithoutMiddlename;
         *  lnkToEntity.NavigateUrl = "StaffDetailV2.aspx?type=view&id=" + provider.StaffID;
         *
         *  dt = BookingDB.GetDataTable_Between(fromDate, toDate, new Staff[] { provider }, null, null, chkIncDeleted.Checked, statusIDsToInclude, false, txtBookingNbrSearch.Text.Trim());
         * }
         * else
         *  throw new CustomMessageException("No entity to get bookings for");
         */

        Patient      patient  = null;
        Organisation org      = null;
        Staff        provider = null;


        if (IsValidFormPatient())
        {
            int patientID = GetFormPatient(false);
            patient = PatientDB.GetByID(patientID);
            if (patient == null)
            {
                throw new CustomMessageException("Invalid patient ID");
            }
        }
        if (IsValidFormOrganisation())
        {
            int orgID = GetFormOrganisation(false);
            org = OrganisationDB.GetByID(orgID);
            if (org == null)
            {
                throw new CustomMessageException("Invalid organisation ID");
            }
        }
        if (IsValidFormProvider())
        {
            int provID = GetFormProvider(false);
            provider = StaffDB.GetByID(provID);
            if (provider == null)
            {
                throw new CustomMessageException("Invalid provider ID");
            }
        }


        if (patient == null && org == null && provider == null)
        {
            throw new CustomMessageException("No entity to get bookings for");
        }

        UserView userView = UserView.GetInstance();

        lblHeading.Text = "Bookings List for:";
        int items = (patient == null ? 0 : 1) + (provider == null ? 0 : 1) + (org == null ? 0 : 1);

        if (patient != null)
        {
            lblHeading.Text += (items > 1 ? "<br />&nbsp;&nbsp;Patient " : " ") + "<a href=\"PatientDetailV2.aspx?type=view&id=" + patient.PatientID + "\">" + patient.Person.FullnameWithoutMiddlename + "</a>";
        }
        if (provider != null && userView.IsAdminView)
        {
            lblHeading.Text += (items > 1 ? "<br />&nbsp;&nbsp;Provider " : " ") + "<a href=\"StaffDetailV2.aspx?type=view&id=" + provider.StaffID + "\">" + provider.Person.FullnameWithoutMiddlename + "</a>";
        }
        if (provider != null && !userView.IsAdminView)
        {
            lblHeading.Text += (items > 1 ? "<br />&nbsp;&nbsp;Provider " : " ") + provider.Person.FullnameWithoutMiddlename;
        }
        if (org != null)
        {
            lblHeading.Text += (items > 1 ? "<br />&nbsp;&nbsp;Clinic " : " ") + "<a href=\"OrganisationDetailV2.aspx?type=view&id=" + org.OrganisationID + "\">" + org.Name + "</a>";
        }


        if (txtBookingNbrSearch.Text.Trim().Length > 0)
        {
            fromDate = DateTime.MinValue;
            toDate   = DateTime.MinValue;
        }

        dt = BookingDB.GetDataTable_Between(fromDate, toDate, provider == null ? null : new Staff[] { provider }, org == null ? null : new Organisation[] { org }, patient, null, chkIncDeleted.Checked, statusIDsToInclude, false, txtBookingNbrSearch.Text.Trim());

        // above query gets for org OR prov .. so remove those
        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            Booking booking = BookingDB.LoadFull(dt.Rows[i]);

            if ((patient != null && (booking.Patient == null || booking.Patient.PatientID != patient.PatientID)) ||
                (org != null && (booking.Organisation == null || booking.Organisation.OrganisationID != org.OrganisationID)) ||
                (provider != null && (booking.Provider == null || booking.Provider.StaffID != provider.StaffID)) ||
                (booking.BookingTypeID != 34))
            {
                dt.Rows.RemoveAt(i);
            }
        }


        // if confirmed by email/sms, display booking_confirmed_by_type.descr
        // if confirmed by person, display their name
        dt.Columns.Add("confirmed_by_text", typeof(string));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i]["booking_booking_confirmed_by_type_id"] == DBNull.Value)
            {
                dt.Rows[i]["confirmed_by_text"] = DBNull.Value;
            }
            else if (Convert.ToInt32(dt.Rows[i]["booking_booking_confirmed_by_type_id"]) == 2 || Convert.ToInt32(dt.Rows[i]["booking_booking_confirmed_by_type_id"]) == 3)
            {
                dt.Rows[i]["confirmed_by_text"] = dt.Rows[i]["booking_confirmed_by_type_descr"];
            }
            else if (Convert.ToInt32(dt.Rows[i]["booking_booking_confirmed_by_type_id"]) == 1)
            {
                dt.Rows[i]["confirmed_by_text"] = dt.Rows[i]["person_confirmed_by_person_id"] == DBNull.Value ? (object)DBNull.Value : dt.Rows[i]["person_confirmed_by_firstname"] + " " + dt.Rows[i]["person_confirmed_by_surname"];
            }
        }

        Session["bookinglist_data"] = dt;

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


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

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



        bool hasInvoices          = false;
        bool hasCompletedInvoices = false;

        foreach (GridViewRow row in GrdBooking.Rows)
        {
            if (row.RowType == DataControlRowType.Pager)
            {
                continue;
            }
            if (row.FindControl("lblViewInvoice") != null && ((Label)row.FindControl("lblViewInvoice")).Text.Length > 0)
            {
                hasInvoices = true;
            }
            if (row.FindControl("lblGeneratedSystemLetters") != null && ((Label)row.FindControl("lblGeneratedSystemLetters")).Text.Length > 0 && ((Label)row.FindControl("lblGeneratedSystemLetters")).Visible)
            {
                hasCompletedInvoices = true;
            }
        }
        GrdBooking.Columns[12].Visible = hasInvoices;
        GrdBooking.Columns[9].Visible  = hasCompletedInvoices;
    }
    public static string Run(bool incDisplay, bool incSending, Site site)
    {
        int daysOverdueAtleast = 7;

        string output = string.Empty;

        DataTable dtPTs = InvoiceDB.GetAllOutstandingByPatientAsReport(site.SiteID, daysOverdueAtleast);

        dtPTs.DefaultView.Sort = "patient_surname";
        dtPTs = dtPTs.DefaultView.ToTable();


        output += "<br /><br /><font color=\"blue\"><u>" + site.Name + " - <b>PTs</b></u></font><br />";
        output += "<table border=\"1\">";
        for (int i = 0; i < (dtPTs.Rows.Count); i++)
        {
            Patient patient = PatientDB.GetByID(Convert.ToInt32(dtPTs.Rows[i]["patient_id"]));
            string  emails  = string.Empty;

            try
            {
                emails = SendEmailToPT(incSending, dtPTs, patient, site);
            }
            catch (Exception ex)
            {
                output += Environment.NewLine + "    <tr><td>" + patient.Person.FullnameWithoutMiddlename + "</td><td>" + patient.PatientID + "</td><td>" + ex.ToString().Replace(Environment.NewLine, "<br />") + "</td></tr>";
            }

            output += Environment.NewLine + "    <tr><td>" + patient.Person.FullnameWithoutMiddlename + "</td><td>" + patient.PatientID + "</td><td>" + emails + "</td></tr>";
        }
        output += "</table>";


        bool      insuranceCompanies = site.SiteType.ID != 2; // in clinics system, generate for insurance companies, in aged care, run for aged care facs
        DataTable dtOrgs             = InvoiceDB.GetAllOutstandingByOrgAsReport(site.SiteID, daysOverdueAtleast, insuranceCompanies);

        dtOrgs.DefaultView.Sort = "name";
        dtOrgs = dtOrgs.DefaultView.ToTable();

        output += "<br /><br /><font color=\"blue\"><u>" + site.Name + " - <b>Orgs</b></u></font><br />";
        output += "<table border=\"1\">";
        for (int i = 0; i < (dtOrgs.Rows.Count); i++)
        {
            Organisation org    = OrganisationDB.GetByID(Convert.ToInt32(dtOrgs.Rows[i]["organisation_id"]));
            string       emails = string.Empty;

            try
            {
                emails = SendEmailToOrgs(incSending, dtOrgs, org, site);
            }
            catch (Exception ex)
            {
                output += Environment.NewLine + "    <tr><td>" + org.Name + "</td><td>" + org.OrganisationID + "</td><td>" + ex.ToString().Replace(Environment.NewLine, "<br />") + "</td></tr>";
            }

            output += Environment.NewLine + "    <tr><td>" + org.Name + "</td><td>" + org.OrganisationID + "</td><td>" + emails + "</td></tr>";
        }
        output += "</table>";


        return(output);
    }
Beispiel #30
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";
        }
    }