示例#1
0
    protected void GrdLetter_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label  lblId     = (Label)GrdLetter.Rows[e.RowIndex].FindControl("lblId");
        int    letter_id = Convert.ToInt32(lblId.Text);
        Letter letter    = LetterDB.GetByID(letter_id);


        LetterTreatmentTemplate[] sysLetters = LetterTreatmentTemplateDB.GetAll();
        for (int i = 0; i < sysLetters.Length; i++)
        {
            if (sysLetters[i].FirstLetter.LetterID == letter_id)
            {
                SetErrorMessage("The letter '<b>" + letter.Docname + "</b>' is set as a Referrer '<b>first treatement letter</b>'. <br />Please unset it in menu '<b>Letters</b>' -> '<b>Treatment Letters</b>' before deleting this letter.");
                return;
            }
            if (sysLetters[i].LastLetter.LetterID == letter_id)
            {
                SetErrorMessage("The letter '<b>" + letter.Docname + "</b>' is set as a Referrer '<b>last treatment letter</b>'. <br />Please unset it in menu '<b>Letters</b>' -> '<b>Treatment Letters</b>' before deleting this letter.");
                return;
            }
            if (sysLetters[i].LastLetterWhenReplacingEPC.LetterID == letter_id)
            {
                SetErrorMessage("The letter '<b>" + letter.Docname + "</b>' is set as a Referrer '<b>last treatement when replacing EPC letter</b>'. <br />Please unset it in menu '<b>Letters</b>' -> '<b>Treatment Letters</b>' before deleting this letter.");
                return;
            }
            if (sysLetters[i].TreatmentNotesLetter.LetterID == letter_id)
            {
                SetErrorMessage("The letter '<b>" + letter.Docname + "</b>' is set as a Referrer '<b>treatment notes letter</b>'. <br />Please unset it in menu '<b>Letters</b>' -> '<b>Treatment Letters</b>' before deleting this letter.");
                return;
            }
        }


        bool canBeDeleted = false;

        try
        {
            LetterDB.Delete(letter_id);
            canBeDeleted = true;
        }
        catch (ForeignKeyConstraintException fkcEx)
        {
            //SetErrorMessage("Can not delete this letter because there are letters in the letter history that refer to this letter.");

            /*
             * if (Utilities.IsDev())
             *  SetErrorMessage("Can not delete because other records depend on this : " + fkcEx.Message);
             * else
             *  SetErrorMessage("Can not delete because other records depend on this");
             */
        }

        if (!canBeDeleted)
        {
            LetterDB.SetAsDeleted(letter_id, true);
        }


        FillGrid();
    }
    protected void SetUrlFields()
    {
        try
        {
            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;
                    }
                }
            }
        }
        catch (CustomMessageException)
        {
            SetErrorMessage();
        }
    }
示例#3
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";
        }
    }
示例#4
0
    protected bool LetterExists(int letterID)
    {
        Letter letter         = LetterDB.GetByID(letterID);
        bool   useDefaultDocs = letter.Organisation == null ? true : !LetterDB.OrgHasdocs(letter.Organisation.OrganisationID);

        string dir = Letter.GetLettersDirectory();

        return(File.Exists(dir + (useDefaultDocs ? "" : letter.Organisation.OrganisationID + @"\") + letter.Docname));
    }
示例#5
0
    public static Hashtable GetHashTable(int site_id = -1)
    {
        Hashtable hash = new Hashtable();

        DataTable tbl = GetDataTable(site_id);

        for (int i = 0; i < tbl.Rows.Count; i++)
        {
            Letter letter = LetterDB.LoadAll(tbl.Rows[i]);
            hash[letter.LetterID] = letter;
        }

        return(hash);
    }
示例#6
0
    protected void GrdLetter_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label lblId = (Label)GrdLetter.Rows[e.RowIndex].FindControl("lblId");

        DropDownList ddlLetterType       = (DropDownList)GrdLetter.Rows[e.RowIndex].FindControl("ddlLetterType");
        DropDownList ddlSite             = (DropDownList)GrdLetter.Rows[e.RowIndex].FindControl("ddlSite");
        TextBox      txtCode             = (TextBox)GrdLetter.Rows[e.RowIndex].FindControl("txtCode");
        TextBox      txtMessage          = (TextBox)GrdLetter.Rows[e.RowIndex].FindControl("txtMessage");
        TextBox      txtDocName          = (TextBox)GrdLetter.Rows[e.RowIndex].FindControl("txtDocName");
        CheckBox     chkIsSendToMedico   = (CheckBox)GrdLetter.Rows[e.RowIndex].FindControl("chkIsSendToMedico");
        CheckBox     chkIsAllowedReclaim = (CheckBox)GrdLetter.Rows[e.RowIndex].FindControl("chkIsAllowedReclaim");

        //CheckBox     chkIsManualOverride = (CheckBox)GrdLetter.Rows[e.RowIndex].FindControl("chkIsManualOverride");
        //DropDownList ddlNumCopiesToPrint = (DropDownList)GrdLetter.Rows[e.RowIndex].FindControl("ddlNumCopiesToPrint");

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

        int       letter_id = Convert.ToInt32(lblId.Text);
        DataTable dt        = Session["letter_data"] as DataTable;

        DataRow[] foundRows = dt.Select("letter_letter_id=" + letter_id.ToString());
        Letter    letter    = LetterDB.LoadAll(foundRows[0]);

        int orgID   = letter.Organisation == null ? 0 : letter.Organisation.OrganisationID;
        int site_id = (GrdLetter.Rows[e.RowIndex].Cells[3].CssClass == "hiddencol") ? letter.Site.SiteID : Convert.ToInt32(ddlSite.SelectedValue);

        LetterDB.Update(letter_id, orgID, Convert.ToInt32(ddlLetterType.SelectedValue), site_id, txtCode.Text, txtMessage.Text, txtDocName.Text.Trim(), chkIsSendToMedico.Checked, chkIsAllowedReclaim.Checked, false, 1, letter.IsDeleted);

        GrdLetter.EditIndex = -1;
        FillGrid();
    }
    public static LetterTreatmentTemplate LoadAll(DataRow row)
    {
        LetterTreatmentTemplate letters = Load(row, "lettertreatmenttemplate_");

        letters.Field = IDandDescrDB.Load(row, "field_field_id", "field_descr");

        letters.FirstLetter            = LetterDB.Load(row, "firstletter_");
        letters.FirstLetter.LetterType = IDandDescrDB.Load(row, "firstlettertype_letter_type_id", "firstlettertype_descr");
        letters.FirstLetter.Site       = SiteDB.Load(row, "firstsite_");
        if (row["firstletterorg_organisation_id"] != DBNull.Value)
        {
            letters.FirstLetter.Organisation = OrganisationDB.Load(row, "firstletterorg_");
        }

        letters.TreatmentNotesLetter            = LetterDB.Load(row, "treatmentnotesletter_");
        letters.TreatmentNotesLetter.LetterType = IDandDescrDB.Load(row, "treatmentnoteslettertype_letter_type_id", "treatmentnoteslettertype_descr");
        letters.TreatmentNotesLetter.Site       = SiteDB.Load(row, "treatmentnotessite_");
        if (row["treatmentnotesletterorg_organisation_id"] != DBNull.Value)
        {
            letters.TreatmentNotesLetter.Organisation = OrganisationDB.Load(row, "treatmentnotesletterorg_");
        }

        letters.LastLetter            = LetterDB.Load(row, "lastletter_");
        letters.LastLetter.LetterType = IDandDescrDB.Load(row, "lastlettertype_letter_type_id", "lastlettertype_descr");
        letters.LastLetter.Site       = SiteDB.Load(row, "lastsite_");
        if (row["lastletterorg_organisation_id"] != DBNull.Value)
        {
            letters.LastLetter.Organisation = OrganisationDB.Load(row, "lastletterorg_");
        }

        letters.LastLetterPT            = LetterDB.Load(row, "lastletterpt_");
        letters.LastLetterPT.LetterType = IDandDescrDB.Load(row, "lastlettertypept_letter_type_id", "lastlettertypept_descr");
        letters.LastLetterPT.Site       = SiteDB.Load(row, "lastsitept_");
        if (row["lastletterorgpt_organisation_id"] != DBNull.Value)
        {
            letters.LastLetterPT.Organisation = OrganisationDB.Load(row, "lastletterorgpt_");
        }

        letters.LastLetterWhenReplacingEPC            = LetterDB.Load(row, "lastletterwhenreplacingepc_");
        letters.LastLetterWhenReplacingEPC.LetterType = IDandDescrDB.Load(row, "lastletterwhenreplacingepctype_letter_type_id", "lastletterwhenreplacingepctype_descr");
        letters.LastLetterWhenReplacingEPC.Site       = SiteDB.Load(row, "lastwhenreplacingepcsite_");
        if (row["lastletterorg_organisation_id"] != DBNull.Value)
        {
            letters.LastLetterWhenReplacingEPC.Organisation = OrganisationDB.Load(row, "lastletterwhenreplacingepcorg_");
        }

        letters.Site = SiteDB.Load(row, "site_");

        return(letters);
    }
    protected void PopulateLettersList()
    {
        DataTable letters = LetterDB.GetDataTable_ByOrg(0, Convert.ToInt32(Session["SiteID"]));

        // remove ones that dont exists
        for (int i = letters.Rows.Count - 1; i >= 0; i--)
        {
            Letter letter = LetterDB.LoadAll(letters.Rows[i]);
            if (!letter.FileExists(Convert.ToInt32(Session["SiteID"])))
            {
                letters.Rows.RemoveAt(i);
            }
        }

        lstLetters.DataSource     = letters;
        lstLetters.DataTextField  = "letter_docname";
        lstLetters.DataValueField = "letter_letter_id";
        lstLetters.DataBind();
    }
示例#9
0
    protected void PopulateLettersList()
    {
        UserView userView = UserView.GetInstance();

        int orgID = (txtUpdateOrganisationID.Text.Length == 0) ? 0 : Convert.ToInt32(txtUpdateOrganisationID.Text);

        if (orgID == 0 && !userView.IsAdminView)
        {
            orgID = Convert.ToInt32(Session["OrgID"]);
        }
        bool      usingDeafultLetters = orgID == 0 || chkUseDefaultDocs.Checked; // || !LetterDB.OrgHasdocs(orgID);
        DataTable letters             = LetterDB.GetDataTable_ByOrg(usingDeafultLetters ? 0 : orgID, usingDeafultLetters ? Convert.ToInt32(Session["SiteID"]) : -1);

        lblSpaceBeforeUseDefaultDocsCheckbox.Visible = orgID != 0;
        chkUseDefaultDocs.Visible                    = orgID != 0;
        chkUseDefaultDocs.ForeColor                  = System.Drawing.Color.DarkOrchid;
        lblDefaultOrOrgSpecificDocs.Visible          = orgID == 0;
        lblSpaceBeforeUseDefaultDocsCheckbox.Visible = orgID == 0;
        if (usingDeafultLetters)
        {
            SetLabel(lblDefaultOrOrgSpecificDocs, "**Using Default Docs", System.Drawing.Color.Blue, false);
        }
        else
        {
            SetLabel(lblDefaultOrOrgSpecificDocs, "**Using Organisation Specific Docs", System.Drawing.Color.DarkOrchid, false);
        }

        // remove ones that dont exists
        for (int i = letters.Rows.Count - 1; i >= 0; i--)
        {
            Letter letter = LetterDB.LoadAll(letters.Rows[i]);
            if (!letter.FileExists(Convert.ToInt32(Session["SiteID"])))
            {
                letters.Rows.RemoveAt(i);
            }
        }

        lstLetters.DataSource     = letters;
        lstLetters.DataTextField  = "letter_docname";
        lstLetters.DataValueField = "letter_letter_id";
        lstLetters.DataBind();
    }
示例#10
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();
        }
    }
    protected void FillGrid()
    {
        int       bulk_letter_sending_queue_batch_id = IsValidFormBatchID() ? GetFormBatchID() : -1;
        DataTable dt = BulkLetterSendingQueueDB.GetDataTable(bulk_letter_sending_queue_batch_id);


        // send method hashtable
        DataTable sendMethodTbl  = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "LetterPrintHistorySendMethod", "", "", "letter_print_history_send_method_id", "descr");
        Hashtable sendMethodHash = new Hashtable();

        for (int i = 0; i < sendMethodTbl.Rows.Count; i++)
        {
            sendMethodHash[Convert.ToInt32(sendMethodTbl.Rows[i]["letter_print_history_send_method_id"])] = (string)sendMethodTbl.Rows[i]["descr"];
        }

        // patient hashtable
        ArrayList ptIDs = new ArrayList();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i]["patient_id"] != DBNull.Value)
            {
                ptIDs.Add((int)dt.Rows[i]["patient_id"]);
            }
        }
        Hashtable patientHash = PatientDB.GetByIDsInHashtable((int[])ptIDs.ToArray(typeof(int)));

        // staff hashtable
        Hashtable staffHash = StaffDB.GetAllInHashtable(true, true, true, false);

        // referrersHash
        Hashtable referrersHash = ReferrerDB.GetHashtableByReferrer();

        // letters hashtable
        Hashtable letterHash = LetterDB.GetHashTable();


        // add from hashtable
        dt.Columns.Add("letter_print_history_send_method_descr", typeof(String));
        dt.Columns.Add("added_by_name", typeof(String));
        dt.Columns.Add("patient_name", typeof(String));
        dt.Columns.Add("referrer_name", typeof(String));
        dt.Columns.Add("letter_doc_name", typeof(String));

        int SMSSent     = 0;
        int SMSUnSent   = 0;
        int EmailSent   = 0;
        int EmailUnSent = 0;
        int PrintSent   = 0;
        int PrintUnSent = 0;

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            int  letter_print_history_send_method_id = Convert.ToInt32(dt.Rows[i]["letter_print_history_send_method_id"]);
            bool sent = dt.Rows[i]["datetime_sent"] != DBNull.Value;

            dt.Rows[i]["letter_print_history_send_method_descr"] = (string)sendMethodHash[letter_print_history_send_method_id];
            dt.Rows[i]["added_by_name"] = dt.Rows[i]["added_by"] == DBNull.Value ? "" : ((Staff)staffHash[Convert.ToInt32(dt.Rows[i]["added_by"])]).Person.FullnameWithoutMiddlename;
            dt.Rows[i]["patient_name"]  = dt.Rows[i]["patient_id"] == DBNull.Value ? "" : ((Patient)patientHash[Convert.ToInt32(dt.Rows[i]["patient_id"])]).Person.FullnameWithoutMiddlename;

            dt.Rows[i]["referrer_name"] = dt.Rows[i]["referrer_id"] == DBNull.Value ? "" : ((Referrer)referrersHash[Convert.ToInt32(dt.Rows[i]["referrer_id"])]).Person.FullnameWithoutMiddlename;

            string source_template_path = dt.Rows[i]["email_letter_source_template_path"].ToString();
            string letter_doc_name      = source_template_path.Length == 0 ? "" : System.IO.Path.GetFileName(source_template_path);
            dt.Rows[i]["letter_doc_name"] = letter_doc_name;

            if (letter_print_history_send_method_id == 3 && sent)
            {
                SMSSent++;
            }
            if (letter_print_history_send_method_id == 3 && !sent)
            {
                SMSUnSent++;
            }
            if (letter_print_history_send_method_id == 2 && sent)
            {
                EmailSent++;
            }
            if (letter_print_history_send_method_id == 2 && !sent)
            {
                EmailUnSent++;
            }
            if (letter_print_history_send_method_id == 1 && sent)
            {
                PrintSent++;
            }
            if (letter_print_history_send_method_id == 1 && !sent)
            {
                PrintUnSent++;
            }
        }

        lblSMSSent.Text     = SMSSent.ToString();
        lblSMSUnSent.Text   = SMSUnSent.ToString();
        lblEmailSent.Text   = EmailSent.ToString();
        lblEmailUnSent.Text = EmailUnSent.ToString();
        lblPrintSent.Text   = PrintSent.ToString();
        lblPrintUnSent.Text = PrintUnSent.ToString();
        lblTotalSent.Text   = (SMSSent + EmailSent + PrintSent).ToString();
        lblTotalUnSent.Text = (SMSUnSent + EmailUnSent + PrintUnSent).ToString();


        DataView dv = new DataView(dt);

        dv.Sort = "letter_print_history_send_method_id";
        dt      = dv.ToTable();


        Session["lettersprintbatchstatus_data"] = dt;

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

            GrdBulkLetterSendingQueue.AllowPaging = false;

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

            int TotalColumns = GrdBulkLetterSendingQueue.Rows[0].Cells.Count;
            GrdBulkLetterSendingQueue.Rows[0].Cells.Clear();
            GrdBulkLetterSendingQueue.Rows[0].Cells.Add(new TableCell());
            GrdBulkLetterSendingQueue.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdBulkLetterSendingQueue.Rows[0].Cells[0].Text       = "No Record Found";
        }
    }
示例#12
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();
        }
    }
示例#13
0
    protected void GrdTreatmentTemplateLetters_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DataTable fields  = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "field_id <> 0 AND has_offerings = 1", "descr", "field_id", "descr");
        DataTable letters = LetterDB.GetDataTable_ByOrg(0, Convert.ToInt32(Session["SiteID"]));

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

        bool tblEmpty = (dt.Rows.Count == 1 && dt.Rows[0][0] == DBNull.Value);

        // remove offering flds that are used
        if (!tblEmpty)
        {
            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < fields.Rows.Count; i++)
                {
                    if (Convert.ToInt32(fields.Rows[i]["field_id"]) == Convert.ToInt32(row["lettertreatmenttemplate_field_id"]))
                    {
                        fields.Rows.RemoveAt(i);
                    }
                }
            }
        }


        if (!tblEmpty && e.Row.RowType == DataControlRowType.DataRow)
        {
            bool      hasData   = dt.Rows[0][0].ToString() != string.Empty;
            Label     lblId     = (Label)e.Row.FindControl("lblId");
            DataRow[] foundRows = dt.Select("lettertreatmenttemplate_letter_treatment_template_id=" + lblId.Text);
            DataRow   thisRow   = foundRows[0];

            DropDownList ddlField = (DropDownList)e.Row.FindControl("ddlField");
            if (ddlField != null)
            {
                ddlField.DataSource     = fields;
                ddlField.DataTextField  = "descr";
                ddlField.DataValueField = "field_id";
                ddlField.DataBind();
                ddlField.SelectedValue = thisRow["lettertreatmenttemplate_field_id"].ToString();
            }

            DropDownList ddlFirstLetter = (DropDownList)e.Row.FindControl("ddlFirstLetter");
            if (ddlFirstLetter != null)
            {
                ddlFirstLetter.DataSource     = letters;
                ddlFirstLetter.DataTextField  = "letter_docname";
                ddlFirstLetter.DataValueField = "letter_letter_id";
                ddlFirstLetter.DataBind();
                ddlFirstLetter.SelectedValue = thisRow["lettertreatmenttemplate_first_letter_id"].ToString();
            }

            DropDownList ddlTreatmentNoteLetter = (DropDownList)e.Row.FindControl("ddlTreatmentNoteLetter");
            if (ddlTreatmentNoteLetter != null)
            {
                ddlTreatmentNoteLetter.DataSource     = letters;
                ddlTreatmentNoteLetter.DataTextField  = "letter_docname";
                ddlTreatmentNoteLetter.DataValueField = "letter_letter_id";
                ddlTreatmentNoteLetter.DataBind();
                ddlTreatmentNoteLetter.SelectedValue = thisRow["lettertreatmenttemplate_treatment_notes_letter_id"].ToString();
            }

            DropDownList ddlLastLetter = (DropDownList)e.Row.FindControl("ddlLastLetter");
            if (ddlLastLetter != null)
            {
                ddlLastLetter.DataSource     = letters;
                ddlLastLetter.DataTextField  = "letter_docname";
                ddlLastLetter.DataValueField = "letter_letter_id";
                ddlLastLetter.DataBind();
                ddlLastLetter.SelectedValue = thisRow["lettertreatmenttemplate_last_letter_id"].ToString();
            }

            DropDownList ddlLastLetterPT = (DropDownList)e.Row.FindControl("ddlLastLetterPT");
            if (ddlLastLetterPT != null)
            {
                ddlLastLetterPT.DataSource     = letters;
                ddlLastLetterPT.DataTextField  = "letter_docname";
                ddlLastLetterPT.DataValueField = "letter_letter_id";
                ddlLastLetterPT.DataBind();
                ddlLastLetterPT.SelectedValue = thisRow["lettertreatmenttemplate_last_letter_pt_id"].ToString();
            }

            DropDownList ddlLastLetterWhenReplacingEPC = (DropDownList)e.Row.FindControl("ddlLastLetterWhenReplacingEPC");
            if (ddlLastLetterWhenReplacingEPC != null)
            {
                ddlLastLetterWhenReplacingEPC.DataSource     = letters;
                ddlLastLetterWhenReplacingEPC.DataTextField  = "letter_docname";
                ddlLastLetterWhenReplacingEPC.DataValueField = "letter_letter_id";
                ddlLastLetterWhenReplacingEPC.DataBind();
                ddlLastLetterWhenReplacingEPC.SelectedValue = thisRow["lettertreatmenttemplate_last_letter_when_replacing_epc_id"].ToString();
            }


            Utilities.AddConfirmationBox(e);
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                Utilities.SetEditRowBackColour(e, System.Drawing.Color.LightGoldenrodYellow);
            }
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            if (fields.Rows.Count == 0)
            {
                if (GrdTreatmentTemplateLetters.FooterRow != null)
                {
                    GrdTreatmentTemplateLetters.FooterRow.Visible = false;
                }
                hideFotter = true;
            }
            else
            {
                DropDownList ddlField = (DropDownList)e.Row.FindControl("ddlNewField");
                ddlField.DataSource     = fields;
                ddlField.DataTextField  = "descr";
                ddlField.DataValueField = "field_id";
                ddlField.DataBind();

                DropDownList ddlFirstLetter = (DropDownList)e.Row.FindControl("ddlNewFirstLetter");
                ddlFirstLetter.DataSource     = letters;
                ddlFirstLetter.DataTextField  = "letter_docname";
                ddlFirstLetter.DataValueField = "letter_letter_id";
                ddlFirstLetter.DataBind();

                DropDownList ddlTreatmentNoteLetter = (DropDownList)e.Row.FindControl("ddlNewTreatmentNoteLetter");
                ddlTreatmentNoteLetter.DataSource     = letters;
                ddlTreatmentNoteLetter.DataTextField  = "letter_docname";
                ddlTreatmentNoteLetter.DataValueField = "letter_letter_id";
                ddlTreatmentNoteLetter.DataBind();

                DropDownList ddlLastLetter = (DropDownList)e.Row.FindControl("ddlNewLastLetter");
                ddlLastLetter.DataSource     = letters;
                ddlLastLetter.DataTextField  = "letter_docname";
                ddlLastLetter.DataValueField = "letter_letter_id";
                ddlLastLetter.DataBind();

                DropDownList ddlLastLetterPT = (DropDownList)e.Row.FindControl("ddlNewLastLetterPT");
                ddlLastLetterPT.DataSource     = letters;
                ddlLastLetterPT.DataTextField  = "letter_docname";
                ddlLastLetterPT.DataValueField = "letter_letter_id";
                ddlLastLetterPT.DataBind();

                DropDownList ddlLastLetterWhenReplacingEPC = (DropDownList)e.Row.FindControl("ddlNewLastLetterWhenReplacingEPC");
                ddlLastLetterWhenReplacingEPC.DataSource     = letters;
                ddlLastLetterWhenReplacingEPC.DataTextField  = "letter_docname";
                ddlLastLetterWhenReplacingEPC.DataValueField = "letter_letter_id";
                ddlLastLetterWhenReplacingEPC.DataBind();
            }
        }
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        try
        {
            decimal smsBalance = SMSCreditDataDB.GetTotal() - SMSHistoryDataDB.GetTotal();
            decimal smsCost    = Convert.ToDecimal(SystemVariableDB.GetByDescr("SMSPrice").Value);

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


            //
            // Start Validation
            //

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


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


            string validationErrors = string.Empty;

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

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

            //
            // End Validation
            //



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

            ArrayList regRefIDsArr = new ArrayList();


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


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

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

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

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



            //
            // ok start the sending process
            //


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


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


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

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


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

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

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



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

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

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

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

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

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

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


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


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

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

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

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

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


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

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

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

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

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

                // Nothing gets past the "DownloadDocument" method because it outputs the file
                // which is writing a response to the client browser and calls Response.End()
                // So make sure any other code that functions goes before this
                Letter.DownloadDocument(Response, fileContents, letter.Docname.Replace(".dot", ".doc"));
            }
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
            return;
        }
    }
示例#15
0
    public static string Run(bool incDisplay, bool incSending, bool incPtSending, DateTime date)
    {
        date = date.Date;

        string batchEmail = SystemVariableDB.GetByDescr("ServiceSpecificBookingReminderLettersToBatch_EmailAddress").Value;

        // don't actually run it if email empty (ie deactivated)
        incSending = incSending && batchEmail.Length > 0;

        Site[] sites = SiteDB.GetAll();


        string output = string.Empty;

        Hashtable lettersHash = LetterDB.GetHashTable();

        Offering[] offerings = OfferingDB.GetAll(false, -1);
        for (int j = 0; j < offerings.Length; j++)
        {
            if (offerings[j].ReminderLetterMonthsLaterToSend == 0 || offerings[j].ReminderLetterID == -1)
            {
                continue;
            }

            Booking[] bookings = BookingDB.GetWhenLastServiceFromXMonthsAgoToGenerageReminderLetter(offerings[j].OfferingID, date, offerings[j].ReminderLetterMonthsLaterToSend);


            Hashtable distinctPatients = new Hashtable();
            for (int i = 0; i < bookings.Length; i++)
            {
                if (bookings[i].Patient != null && distinctPatients[bookings[i].Patient.PatientID] == null)
                {
                    distinctPatients[bookings[i].Patient.PatientID] = bookings[i].Patient;
                }
            }

            Patient[] patients = (Patient[])(new ArrayList(distinctPatients.Values)).ToArray(typeof(Patient));
            Hashtable patientContactEmailHash = GetPatientEmailCache(patients);



            // Generate Letters

            ArrayList filesToPrint = new ArrayList();
            for (int i = 0; i < bookings.Length; i++)
            {
                Booking curBooking = bookings[i];
                if (curBooking.Patient == null)
                {
                    continue;
                }

                Patient curPatient         = curBooking.Patient;
                string  curPatientEmail    = GetEmail(patientContactEmailHash, curPatient.Person.EntityID);
                bool    curPatientHasEmail = curPatientEmail != null;


                SendMethod sendMethod = incPtSending && curPatientHasEmail ? SendMethod.Email_To_Patient : SendMethod.Batch;

                if (incSending)
                {
                    if (sendMethod == SendMethod.Email_To_Patient)
                    {
                        // generate and send email
                        Letter.FileContents fileContents = GenerteLetter(curBooking, Letter.FileFormat.PDF, lettersHash, sites);
                        fileContents.DocName = "Reminder" + System.IO.Path.GetExtension(fileContents.DocName);
                        if (fileContents != null)
                        {
                            Site site = SiteDB.GetSiteByType(curBooking.Organisation.IsAgedCare ? SiteDB.SiteType.AgedCare : SiteDB.SiteType.Clinic);
                            SendEmail(site.Name, curPatientEmail, "Important Reminder", "Hi " + curBooking.Patient.Person.Firstname + ",<br /><br />Please find attached a review reminder letter for a previous appointment.<br /><br/>Best regards,<br />" + site.Name, true, new Letter.FileContents[] { fileContents });
                        }
                    }
                    else
                    {
                        // generate and add to batch list (if batch email set)
                        if (batchEmail.Length > 0)
                        {
                            Letter.FileContents fileContents = GenerteLetter(curBooking, Letter.FileFormat.Word, lettersHash, sites);
                            if (fileContents != null)
                            {
                                filesToPrint.Add(fileContents);
                            }
                        }
                    }
                }

                string addEditContactListPage;
                if (Utilities.GetAddressType().ToString() == "Contact")
                {
                    addEditContactListPage = "AddEditContactList.aspx";
                }
                else if (Utilities.GetAddressType().ToString() == "ContactAus")
                {
                    addEditContactListPage = "ContactAusListV2.aspx";
                }
                else
                {
                    throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                }

                string allFeatures     = "dialogWidth:555px;dialogHeight:350px;center:yes;resizable:no; scroll:no";
                string onclick         = "onclick=\"javascript:window.showModalDialog('" + addEditContactListPage + "?entity_type=referrer&id=" + curBooking.Patient.Person.EntityID.ToString() + "', '', '" + allFeatures + "');document.getElementById('btnUpdateList').click();return false;\"";
                string hrefUpdateEmail = "<u><a style=\"text-decoration: none\" title=\"Edit\" AlternateText=\"Edit\" " + onclick + " href=\"\">Update PT Email</a></u>";

                output += @"<tr>
                                <td class=""nowrap"">" + curBooking.BookingID + " &nbsp;&nbsp;&nbsp;[" + curBooking.DateStart.ToString("dd-MM-yyyy") + "&nbsp;&nbsp;&nbsp;" + curBooking.DateStart.ToString("HH:mm") + "-" + curBooking.DateEnd.ToString("HH:mm") + "]" + @"</td>
                                <td class=""text_left"">" + curBooking.Organisation.Name + @"</td>
                                <td class=""text_left"">" + curBooking.Offering.Name + @"</td>
                                <td class=""text_left"">" + ((Letter)lettersHash[curBooking.Offering.ReminderLetterID]).Docname + @"</td>
                                <td class=""text_left"">" + curPatient.Person.FullnameWithoutMiddlename + @"</td>
                                <td class=""nowrap"">" + (curPatientHasEmail ? curPatientEmail : "Has No Email") + " (" + hrefUpdateEmail + ")" + @"</td>
                                <td>" + sendMethod.ToString().Replace("_", " ") + @"</td>
                            </tr>";
            }


            // combine and email where the patient had no email
            if (incSending && filesToPrint.Count > 0)
            {
                Letter.FileContents filesContents = Letter.FileContents.Merge((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)), "Reminders.pdf"); // .pdf
                SendEmail(
                    ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromName"].Value,
                    batchEmail,
                    "Batch Reminder Letters",
                    string.Empty,
                    true,
                    new Letter.FileContents[] { filesContents });
            }
        }


        if (output.Length == 0)
        {
            output += @"<tr>
                            <td colspan=""7"">No Reminders To Send Today</td>
                        </tr>";
        }

        return(@"
            <table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" style=""border-style:solid;border-width:1px;border-collapse:collapse;padding:4px;"">
            <tr>
              <th>Booking (ID, Date/Time)</th>
              <th>Organisation</th>
              <th>Service</th>
              <th>Letter</th>
              <th>Patient</th>
              <th>PT Email</th>
              <th>Send Method</th>
            </tr>
            " + output + @"
            </table>");
    }
示例#16
0
    public static LetterPrintHistory LoadAll(DataRow row)
    {
        LetterPrintHistory lph = Load(row, "lph_");

        lph.Letter = LetterDB.Load(row, "letter_");

        lph.SendMethod = new IDandDescr(Convert.ToInt32(row["lph_send_method_letter_print_history_send_method_id"]), Convert.ToString(row["lph_send_method_descr"]));

        lph.Letter.LetterType = IDandDescrDB.Load(row, "lettertype_letter_type_id", "lettertype_descr");
        if (row["letterorg_organisation_id"] != DBNull.Value)
        {
            lph.Letter.Organisation = OrganisationDB.Load(row, "letterorg_");
        }

        if (row["organisation_organisation_id"] != DBNull.Value)
        {
            lph.Organisation = OrganisationDB.Load(row, "organisation_");
        }

        if (row["patient_patient_id"] != DBNull.Value)
        {
            lph.Patient = PatientDB.Load(row, "patient_");
        }
        if (row["patient_patient_id"] != DBNull.Value)
        {
            lph.Patient.Person       = PersonDB.Load(row, "person_patient_");
            lph.Patient.Person.Title = IDandDescrDB.Load(row, "title_patient_title_id", "title_patient_descr");
        }

        if (row["staff_staff_id"] != DBNull.Value)
        {
            lph.Staff = StaffDB.Load(row, "staff_");
        }
        if (row["staff_staff_id"] != DBNull.Value)
        {
            lph.Staff.Person       = PersonDB.Load(row, "person_staff_");
            lph.Staff.Person.Title = IDandDescrDB.Load(row, "title_staff_title_id", "title_staff_descr");
        }

        if (row["regref_register_referrer_id"] != DBNull.Value)
        {
            lph.RegisterReferrer = RegisterReferrerDB.Load(row, "regref_");
        }
        if (row["regreforg_organisation_id"] != DBNull.Value)
        {
            lph.RegisterReferrer.Organisation = OrganisationDB.Load(row, "regreforg_");
        }
        if (row["referrer_referrer_id"] != DBNull.Value)
        {
            lph.RegisterReferrer.Referrer = ReferrerDB.Load(row, "referrer_");
        }
        if (row["referrer_referrer_id"] != DBNull.Value)
        {
            lph.RegisterReferrer.Referrer.Person       = PersonDB.Load(row, "person_referrer_");
            lph.RegisterReferrer.Referrer.Person.Title = IDandDescrDB.Load(row, "title_referrer_title_id", "title_referrer_descr");
        }

        if (row["lph_health_card_action_id"] != DBNull.Value)
        {
            lph.HealthCardAction = HealthCardActionDB.Load(row, "hca_");
            lph.HealthCardAction.healthCardActionType = IDandDescrDB.Load(row, "hcat_health_card_action_type_id", "hcat_descr");
            lph.HealthCardAction.HealthCard           = HealthCardDB.Load(row, "hc_");
        }

        if (row["lph_booking_id"] != DBNull.Value)
        {
            lph.Booking = BookingDB.Load(row, "booking_");
        }

        return(lph);
    }
示例#17
0
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        try
        {
            //ScriptManager.RegisterClientScriptBlock(this, GetType(), "fancyBox", "alert('a');", true);

            int letterPrintHistorySendMethodID = 1; // send by mail


            // make sure org and patient selected
            if (txtUpdatePatientID.Text.Length == 0)
            {
                throw new CustomMessageException("Please select a patient.");
            }
            //if (txtUpdateOrganisationID.Text.Length == 0)    //--- checking in javascript .. cuz can be blank and use site info in place of org info
            //    throw new CustomMessageException("Please select an organisation.");


            if (lstLetters.GetSelectedIndices().Length == 0)
            {
                throw new CustomMessageException("Please select a letter.");
            }

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

            // get list of selected notes!
            ArrayList list = new ArrayList();
            foreach (RepeaterItem item in lstNotes.Items)
            {
                if (((CheckBox)item.FindControl("chkUseNote")).Checked)
                {
                    Label lblNoteID = (Label)item.FindControl("lblNoteID");
                    Note  note      = NoteDB.GetByID(Convert.ToInt32(lblNoteID.Text));
                    list.Add(Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + "Treatment Note (" + note.DateAdded.ToString("dd-MM-yyyy") + "):" + Environment.NewLine + Environment.NewLine + ((Label)item.FindControl("lblOriginalText")).Text);
                }
            }
            string[] notes = (string[])list.ToArray(typeof(string));

            int bookingID = -1;
            if (Request.QueryString["booking"] != null)
            {
                bookingID = Convert.ToInt32(Request.QueryString["booking"]);
            }
            if (Request.QueryString["bookingpatient"] != null)
            {
                BookingPatient bp = BookingPatientDB.GetByID(Convert.ToInt32(Request.QueryString["bookingpatient"]));
                bookingID = bp.Booking.BookingID;
            }

            Letter.SendLetter(Response,
                              Letter.FileFormat.Word, // .pdf
                              SiteDB.GetByID(Convert.ToInt32(Session["SiteID"])),
                              letter.LetterID,
                              txtUpdateOrganisationID.Text == "" ? 0 : Convert.ToInt32(txtUpdateOrganisationID.Text),
                              Convert.ToInt32(txtUpdatePatientID.Text),
                              Convert.ToInt32(Session["StaffID"]),
                              bookingID,
                              -1,
                              1,
                              notes,
                              true,
                              letterPrintHistorySendMethodID);
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
            return;
        }
    }
    public static BulkLetterSendingQueueAdditionalLetter GetFileInfo(Letter.FileFormat fileFormat, Booking booking, Patient patient, HealthCard hc, Letter.TreatmentLetterType treatmentLetterType, Booking.InvoiceType invType, int fieldID, int siteID, int staffID, Referrer referrer, bool keepInHistory, int letterPrintHistorySendMethodID)
    {
        // 1. Add to healthcardaction
        int healthCardActionID = -1;

        if (treatmentLetterType == Letter.TreatmentLetterType.First || treatmentLetterType == Letter.TreatmentLetterType.Last || treatmentLetterType == Letter.TreatmentLetterType.LastWhenReplacingEPC)
        {
            healthCardActionID = HealthCardActionDB.Insert(hc.HealthCardID, Letter.GetHealthCardActionTypeID(treatmentLetterType), DateTime.Now);
        }

        // 2.create document and put it in history
        int letterID = Letter.GetLetterIDByTreatmentLetterTypeAndInvoiceType(treatmentLetterType, invType, fieldID, siteID);

        if (letterID == -1)
        {
            return(null);
        }


        string lettersDir = Letter.GetLettersDirectory();

        if (!Directory.Exists(lettersDir))
        {
            throw new CustomMessageException("Letters directory doesn't exist");
        }

        Letter letter             = LetterDB.GetByID(letterID);
        bool   useDefaultDocs     = letter.Organisation == null ? true : !LetterDB.OrgHasdocs(letter.Organisation.OrganisationID);
        string sourceTemplatePath = lettersDir + (useDefaultDocs ? @"Default\" + letter.Site.SiteID + @"\" : letter.Organisation.OrganisationID + @"\") + letter.Docname;

        if (!File.Exists(sourceTemplatePath))
        {
            throw new CustomMessageException("File doesn't exist: " + Path.GetFileName(sourceTemplatePath));
        }

        // get temp directory
        string tmpLettersDirectory = Letter.GetTempLettersDirectory();

        if (!Directory.Exists(tmpLettersDirectory))
        {
            throw new CustomMessageException("Temp letters directory doesn't exist");
        }

        return(new BulkLetterSendingQueueAdditionalLetter(
                   -1,
                   -1,
                   letter.LetterID,
                   keepInHistory && Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["StoreLettersHistoryInDB"]),
                   keepInHistory && Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["StoreLettersHistoryInFlatFile"]),
                   letterPrintHistorySendMethodID,
                   Letter.GetLettersHistoryDirectory(booking.Organisation.OrganisationID),
                   letter.Docname.Replace(".dot", ".doc"),
                   siteID,
                   booking.Organisation.OrganisationID,
                   booking.BookingID,
                   patient.PatientID,
                   -1, // register_referrer_id_to_use_instead_of_patients_reg_ref
                   staffID,
                   healthCardActionID,
                   sourceTemplatePath,
                   tmpLettersDirectory + letter.Docname.Replace(".dot", ".doc"),
                   true,
                   "",
                   ""
                   ));
    }
    protected void GrdOffering_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DataTable offeringTypes = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "OfferingType", "offering_type_id <> 90", "", "offering_type_id", "descr");
        DataTable fields        = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "has_offerings = 1", "descr", "field_id", "descr");
        DataTable offeringPatientSubcategories = DBBase.GetGenericDataTable(null, "AgedCarePatientType", "aged_care_patient_type_id", "descr");
        DataTable offeringInvoiceTypes         = DBBase.GetGenericDataTable(null, "OfferingInvoiceType", "offering_invoice_type_id", "descr");
        DataTable letters = LetterDB.GetDataTable_ByLetterType(391);

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

        // move 'None' item to the top
        for (int i = 0; i < fields.Rows.Count; i++)
        {
            if (fields.Rows[i]["descr"].ToString() != "None")
            {
                continue;
            }

            DataRow newRow = fields.NewRow();
            newRow.ItemArray = fields.Rows[i].ItemArray;
            fields.Rows.RemoveAt(i);
            fields.Rows.InsertAt(newRow, 0);
            break;
        }


        DataTable dt       = Session["offeringinfo_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("o_offering_id=" + lblId.Text);
            DataRow   thisRow   = foundRows[0];


            int offering_id = Convert.ToInt32(thisRow["o_offering_id"]);


            TextBox txtName = (TextBox)e.Row.FindControl("txtName");
            if (txtName != null)
            {
                if (Session["DB"] != null && Session["DB"].ToString() == "Mediclinic_0040")
                {
                    txtName.MaxLength = 2000;
                    txtName.TextMode  = TextBoxMode.MultiLine;
                }
                else if (thisRow["o_name"].ToString().Contains(Environment.NewLine))
                {
                    txtName.TextMode = TextBoxMode.MultiLine;
                }
            }


            DropDownList ddlOfferingType = (DropDownList)e.Row.FindControl("ddlOfferingType");
            if (ddlOfferingType != null)
            {
                ddlOfferingType.DataSource     = offeringTypes;
                ddlOfferingType.DataTextField  = "descr";
                ddlOfferingType.DataValueField = "offering_type_id";
                ddlOfferingType.DataBind();
                ddlOfferingType.SelectedValue = thisRow["o_offering_type_id"].ToString();
            }

            DropDownList ddlField = (DropDownList)e.Row.FindControl("ddlField");
            if (ddlField != null)
            {
                ddlField.DataSource     = fields;
                ddlField.DataTextField  = "descr";
                ddlField.DataValueField = "field_id";
                ddlField.DataBind();
                ddlField.SelectedValue = thisRow["o_field_id"].ToString();
            }

            DropDownList ddlOfferingPatientSubcategory = (DropDownList)e.Row.FindControl("ddlOfferingPatientSubcategory");
            if (ddlOfferingPatientSubcategory != null)
            {
                ddlOfferingPatientSubcategory.DataSource     = offeringPatientSubcategories;
                ddlOfferingPatientSubcategory.DataTextField  = "descr";
                ddlOfferingPatientSubcategory.DataValueField = "aged_care_patient_type_id";
                ddlOfferingPatientSubcategory.DataBind();
                ddlOfferingPatientSubcategory.SelectedValue = thisRow["o_aged_care_patient_type_id"].ToString();
            }

            DropDownList ddlOfferingInvoiceType = (DropDownList)e.Row.FindControl("ddlOfferingInvoiceType");
            if (ddlOfferingInvoiceType != null)
            {
                if (IsValidFormInvType())
                {
                    IDandDescr invType = GetFormInvType();
                    ddlOfferingInvoiceType.Items.Add(new ListItem(invType.Descr, invType.ID.ToString()));
                }
                else
                {
                    string v = thisRow["o_offering_invoice_type_id"].ToString();

                    ddlOfferingInvoiceType.DataSource     = offeringInvoiceTypes;
                    ddlOfferingInvoiceType.DataTextField  = "descr";
                    ddlOfferingInvoiceType.DataValueField = "offering_invoice_type_id";
                    ddlOfferingInvoiceType.DataBind();
                    ddlOfferingInvoiceType.SelectedValue = thisRow["o_offering_invoice_type_id"].ToString();
                }
            }

            DropDownList ddlServiceTimeMinutes = (DropDownList)e.Row.FindControl("ddlServiceTimeMinutes");
            if (ddlServiceTimeMinutes != null)
            {
                ddlServiceTimeMinutes.Items.AddRange(GetListOfTimes());
                int valueToSelect = Convert.ToInt32(dt.Rows[e.Row.RowIndex]["o_service_time_minutes"]);
                if (ddlServiceTimeMinutes.Items.FindByValue(valueToSelect.ToString()) != null)
                {
                    ddlServiceTimeMinutes.SelectedValue = valueToSelect.ToString();
                }
                else
                {
                    ddlServiceTimeMinutes.Items.Clear();
                    ddlServiceTimeMinutes.Items.AddRange(GetListOfTimes(valueToSelect));
                    ddlServiceTimeMinutes.SelectedValue = valueToSelect.ToString();
                }
            }

            DropDownList ddlNumClinicVisitsAllowedPerYear = (DropDownList)e.Row.FindControl("ddlNumClinicVisitsAllowedPerYear");
            if (ddlNumClinicVisitsAllowedPerYear != null)
            {
                for (int i = 0; i < 6; i++)
                {
                    ddlNumClinicVisitsAllowedPerYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                ddlNumClinicVisitsAllowedPerYear.SelectedValue = thisRow["o_num_clinic_visits_allowed_per_year"].ToString();
            }

            DropDownList ddlMaxNbrClaimable = (DropDownList)e.Row.FindControl("ddlMaxNbrClaimable");
            if (ddlMaxNbrClaimable != null)
            {
                for (int i = 0; i < 10; i++)
                {
                    ddlMaxNbrClaimable.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                ddlMaxNbrClaimable.SelectedValue = thisRow["o_max_nbr_claimable"].ToString();
            }

            DropDownList ddlMaxNbrClaimableMonths = (DropDownList)e.Row.FindControl("ddlMaxNbrClaimableMonths");
            if (ddlMaxNbrClaimableMonths != null)
            {
                for (int i = 0; i <= 24; i++)
                {
                    ddlMaxNbrClaimableMonths.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                ddlMaxNbrClaimableMonths.SelectedValue = thisRow["o_max_nbr_claimable_months"].ToString();
            }

            DropDownList ddlReminderLetterMonthsLaterToSend = (DropDownList)e.Row.FindControl("ddlReminderLetterMonthsLaterToSend");
            if (ddlReminderLetterMonthsLaterToSend != null)
            {
                for (int i = 0; i <= 24; i++)
                {
                    ddlReminderLetterMonthsLaterToSend.Items.Add(new ListItem((i == 0 ? "Disabled" : i.ToString()), i.ToString()));
                }
                ddlReminderLetterMonthsLaterToSend.SelectedValue = thisRow["o_reminder_letter_months_later_to_send"].ToString();
            }

            DropDownList ddlReminderLetter = (DropDownList)e.Row.FindControl("ddlReminderLetter");
            if (ddlReminderLetter != null)
            {
                ddlReminderLetter.Items.Add(new ListItem("--", "-1"));
                for (int i = 0; i < letters.Rows.Count; i++)
                {
                    ddlReminderLetter.Items.Add(new ListItem(letters.Rows[i]["letter_docname"].ToString(), letters.Rows[i]["letter_letter_id"].ToString()));
                }
                if (thisRow["o_reminder_letter_id"] != DBNull.Value)
                {
                    ddlReminderLetter.SelectedValue = thisRow["o_reminder_letter_id"].ToString();
                }
            }

            Label lblReminderLetter = (Label)e.Row.FindControl("lblReminderLetter");
            if (lblReminderLetter != null)
            {
                if (thisRow["o_reminder_letter_id"] == DBNull.Value)
                {
                    lblReminderLetter.Text = string.Empty;
                }

                else
                {
                    for (int i = 0; i < letters.Rows.Count; i++)
                    {
                        if (Convert.ToInt32(letters.Rows[i]["letter_letter_id"]) == Convert.ToInt32(thisRow["o_reminder_letter_id"]))
                        {
                            lblReminderLetter.Text = letters.Rows[i]["letter_docname"].ToString();
                            break;
                        }
                    }
                }
            }



            ImageButton lnkPopupMessage = (ImageButton)e.Row.FindControl("lnkPopupMessage");
            if (lnkPopupMessage != null)
            {
                string allFeatures = "dialogWidth:550px;dialogHeight:400px;center:yes;resizable:no; scroll:no";
                string js          = "javascript:window.showModalDialog('OfferingPopupMessageDetailV2.aspx?type=edit&id=" + offering_id.ToString() + "', '', '" + allFeatures + "');return false;";

                lnkPopupMessage.Visible     = true;
                lnkPopupMessage.PostBackUrl = "  ";
                lnkPopupMessage.Attributes.Add("onclick", js);
            }


            ImageButton btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
            if (btnDelete != null)
            {
                bool is_deleted = Convert.ToBoolean(thisRow["o_is_deleted"]);
                if (is_deleted)
                {
                    btnDelete.CommandName   = "_UnDelete";
                    btnDelete.ImageUrl      = "~/images/tick-24.png";
                    btnDelete.AlternateText = "UnDelete";
                    btnDelete.ToolTip       = "UnDelete";
                }
            }


            LinkButton lnkUpdate = (LinkButton)e.Row.FindControl("lnkUpdate");
            if (lnkUpdate != null)
            {
                TextBox txtMedicareCharge = (TextBox)e.Row.FindControl("txtMedicareCharge");
                TextBox txtDvaCharge      = (TextBox)e.Row.FindControl("txtDvaCharge");
                TextBox txtTacCharge      = (TextBox)e.Row.FindControl("txtTacCharge");

                lnkUpdate.OnClientClick = "set_if_empty_price(document.getElementById('" + txtMedicareCharge.ClientID + "'),document.getElementById('" + txtDvaCharge.ClientID + "'),document.getElementById('" + txtTacCharge.ClientID + "'));";
            }

            Image imgBookingScreenDefaultService = (Image)e.Row.FindControl("imgBookingScreenDefaultService");
            imgBookingScreenDefaultService.Visible = offering_id == BookingScreenDefaultServiceID;

            LinkButton btnSetAsBookingScreenDefaultService = (LinkButton)e.Row.FindControl("btnSetAsBookingScreenDefaultService");
            btnSetAsBookingScreenDefaultService.Visible = offering_id != BookingScreenDefaultServiceID;


            Utilities.AddConfirmationBox(e);
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                Utilities.SetEditRowBackColour(e, System.Drawing.Color.LightGoldenrodYellow);
            }
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList ddlOfferingType = (DropDownList)e.Row.FindControl("ddlNewOfferingType");
            ddlOfferingType.DataSource = offeringTypes;
            ddlOfferingType.DataBind();

            DropDownList ddlField = (DropDownList)e.Row.FindControl("ddlNewField");
            ddlField.DataSource = fields;
            ddlField.DataBind();

            DropDownList ddlOfferingPatientSubcategory = (DropDownList)e.Row.FindControl("ddlNewOfferingPatientSubcategory");
            ddlOfferingPatientSubcategory.DataSource = offeringPatientSubcategories;
            ddlOfferingPatientSubcategory.DataBind();

            bool isAgedCareResidentTypes = IsValidIsAgedCareResidentTypes() ? GetFormIsAgedCareResidentTypes() : false;
            if (isAgedCareResidentTypes)
            {
                ddlOfferingPatientSubcategory.Items.RemoveAt(0);
            }

            DropDownList ddlOfferingInvoiceType = (DropDownList)e.Row.FindControl("ddlNewOfferingInvoiceType");
            if (IsValidFormInvType())
            {
                IDandDescr invType = GetFormInvType();
                ddlOfferingInvoiceType.Items.Add(new ListItem(invType.Descr, invType.ID.ToString()));
            }
            else
            {
                //ddlOfferingInvoiceType.DataSource = offeringInvoiceTypes;
                //ddlOfferingInvoiceType.DataBind();
                foreach (DataRow row in offeringInvoiceTypes.Rows)
                {
                    if (row["offering_invoice_type_id"].ToString() != "0")
                    {
                        ddlOfferingInvoiceType.Items.Add(new ListItem(row["descr"].ToString(), row["offering_invoice_type_id"].ToString()));
                    }
                }

                ddlOfferingInvoiceType.SelectedValue = UserView.GetInstance().IsClinicView ? "1" : "4"; // 1 = clinics, 4 = aged care
            }

            DropDownList ddlServiceTimeMinutes = (DropDownList)e.Row.FindControl("ddlNewServiceTimeMinutes");
            for (int i = 0; i < 20; i++)
            {
                ddlServiceTimeMinutes.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            for (int i = 20; i <= 90; i++)
            {
                if (i % 5 == 0)
                {
                    ddlServiceTimeMinutes.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
            }
            for (int i = 91; i <= 480; i++)
            {
                if (i % 30 == 0)
                {
                    ddlServiceTimeMinutes.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
            }


            DropDownList ddlNumClinicVisitsAllowedPerYear = (DropDownList)e.Row.FindControl("ddlNewNumClinicVisitsAllowedPerYear");
            if (ddlNumClinicVisitsAllowedPerYear != null)
            {
                for (int i = 0; i < 6; i++)
                {
                    ddlNumClinicVisitsAllowedPerYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
            }

            DropDownList ddlMaxNbrClaimable = (DropDownList)e.Row.FindControl("ddlNewMaxNbrClaimable");
            for (int i = 0; i < 10; i++)
            {
                ddlMaxNbrClaimable.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }

            DropDownList ddlMaxNbrClaimableMonths = (DropDownList)e.Row.FindControl("ddlNewMaxNbrClaimableMonths");
            for (int i = 0; i <= 24; i++)
            {
                ddlMaxNbrClaimableMonths.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }

            DropDownList ddlReminderLetterMonthsLaterToSend = (DropDownList)e.Row.FindControl("ddlNewReminderLetterMonthsLaterToSend");
            for (int i = 0; i <= 24; i++)
            {
                ddlReminderLetterMonthsLaterToSend.Items.Add(new ListItem((i == 0 ? "Disabled" : i.ToString()), i.ToString()));
            }

            DropDownList ddlReminderLetter = (DropDownList)e.Row.FindControl("ddlNewReminderLetter");
            ddlReminderLetter.Items.Add(new ListItem("--", "-1"));
            for (int i = 0; i < letters.Rows.Count; i++)
            {
                ddlReminderLetter.Items.Add(new ListItem(letters.Rows[i]["letter_docname"].ToString(), letters.Rows[i]["letter_letter_id"].ToString()));
            }


            LinkButton lnkAdd            = (LinkButton)e.Row.FindControl("lnkAdd");
            TextBox    txtMedicareCharge = (TextBox)e.Row.FindControl("txtNewMedicareCharge");
            TextBox    txtDvaCharge      = (TextBox)e.Row.FindControl("txtNewDvaCharge");
            TextBox    txtTacCharge      = (TextBox)e.Row.FindControl("txtNewTacCharge");
            lnkAdd.OnClientClick = "set_if_empty_price(document.getElementById('" + txtMedicareCharge.ClientID + "'),document.getElementById('" + txtDvaCharge.ClientID + "'),document.getElementById('" + txtTacCharge.ClientID + "'));";
        }
    }
示例#20
0
    protected void GrdLetter_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DataTable letterTypes = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "LetterType", "", "descr", "letter_type_id", "descr");
        DataTable sites       = SiteDB.GetDataTable();


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

        bool tblEmpty = (dt.Rows.Count == 1 && dt.Rows[0][0] == DBNull.Value);

        if (!tblEmpty && e.Row.RowType == DataControlRowType.DataRow)
        {
            bool      hasData   = dt.Rows[0][0].ToString() != string.Empty;
            Label     lblId     = (Label)e.Row.FindControl("lblId");
            DataRow[] foundRows = dt.Select("letter_letter_id=" + lblId.Text);
            DataRow   thisRow   = foundRows[0];
            Letter    letter    = LetterDB.LoadAll(thisRow);

            DropDownList ddlLetterType = (DropDownList)e.Row.FindControl("ddlLetterType");
            if (ddlLetterType != null)
            {
                ddlLetterType.DataSource     = letterTypes;
                ddlLetterType.DataTextField  = "descr";
                ddlLetterType.DataValueField = "letter_type_id";
                ddlLetterType.DataBind();
                ddlLetterType.SelectedValue = thisRow["letter_letter_type_id"].ToString();
            }

            DropDownList ddlSite = (DropDownList)e.Row.FindControl("ddlSite");
            if (ddlSite != null)
            {
                ddlSite.DataSource     = sites;
                ddlSite.DataTextField  = "name";
                ddlSite.DataValueField = "site_id";
                ddlSite.DataBind();
                ddlSite.SelectedValue = thisRow["letter_site_id"].ToString();
            }


            Label lblFileExists = (Label)e.Row.FindControl("lblFileExists");
            if (lblFileExists != null)
            {
                lblFileExists.Style.Remove("border-bottom");
                lblFileExists.Font.Bold = false;

                if (letter.FileExists(Convert.ToInt32(Session["SiteID"])))
                {
                    lblFileExists.Text = "Yes";
                }
                else
                {
                    if (letter.LetterType.ID == 234 || letter.LetterType.ID == 235) // medicare/dva rejection codes
                    {
                        if (letter.Docname.Length == 0)
                        {
                            lblFileExists.Text = string.Empty;
                        }
                        if (letter.Docname.Length > 0)
                        {
                            lblFileExists.Text      = "<span style=\"border-bottom:thin dotted black;\" title=\"This won't be in the list of available reject codes.\r\nTo have it in the available list of reject codes, either change the docname to be blank or change the docname to one that exists in the below list.\">No</span>";
                            lblFileExists.Font.Bold = true;
                        }
                    }
                    else
                    {
                        lblFileExists.Text = "No";
                        if (letter.Docname.Length > 0)
                        {
                            lblFileExists.Text      = "<span style=\"border-bottom:thin dotted black;\" title=\"This won't be in the list of available letters.\r\nTo have it in the available list of letters, change the docname to one that exists in the below list.\">No</span>";
                            lblFileExists.Font.Bold = true;
                        }
                    }
                }
            }


            Utilities.AddConfirmationBox(e);
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                Utilities.SetEditRowBackColour(e, System.Drawing.Color.LightGoldenrodYellow);
            }
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList ddlLetterType = (DropDownList)e.Row.FindControl("ddlNewLetterType");
            ddlLetterType.DataSource     = letterTypes;
            ddlLetterType.DataTextField  = "descr";
            ddlLetterType.DataValueField = "letter_type_id";
            ddlLetterType.DataBind();

            DropDownList ddlSite = (DropDownList)e.Row.FindControl("ddlNewSite");
            ddlSite.DataSource     = sites;
            ddlSite.DataTextField  = "name";
            ddlSite.DataValueField = "site_id";
            ddlSite.DataBind();
        }
    }
示例#21
0
    protected void Send()
    {
        string[] attachments = null;

        try
        {
            // Output.Text = FreeTextBox1.Text;

            if (txtEmailTo.Text.Trim().Length == 0)
            {
                Page.Form.DefaultFocus = txtSubject.ClientID;
                throw new CustomMessageException("Please enter an email address to send to");
            }
            if (!Utilities.IsValidEmailAddresses(txtEmailTo.Text.Trim(), false))
            {
                Page.Form.DefaultFocus = txtSubject.ClientID;
                throw new CustomMessageException("Please enter valid email address(es) to send to");
            }
            if (txtSubject.Text.Trim().Length == 0)
            {
                Page.Form.DefaultFocus = txtSubject.ClientID;
                throw new CustomMessageException("Please enter an email subject");
            }

            string to      = txtEmailTo.Text;
            string subject = txtSubject.Text;
            string message = FreeTextBox1.Text;

            attachments = GetAttachments(new System.Web.UI.HtmlControls.HtmlInputFile[] { inpAttachment1, inpAttachment2, inpAttachment3 });


            // make sure org and patient selected
            if (txtUpdatePatientID.Text.Length == 0)
            {
                throw new CustomMessageException("Please select a patient.");
            }
            //if (txtUpdateOrganisationID.Text.Length == 0)    //--- checking in javascript .. cuz can be blank and use site info in place of org info
            //    throw new CustomMessageException("Please select an organisation.");


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

            // get list of selected notes!
            ArrayList list = new ArrayList();
            foreach (RepeaterItem item in lstNotes.Items)
            {
                if (((CheckBox)item.FindControl("chkUseNote")).Checked)
                {
                    Label lblNoteID = (Label)item.FindControl("lblNoteID");
                    Note  note      = NoteDB.GetByID(Convert.ToInt32(lblNoteID.Text));
                    list.Add(Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + "Treatment Note (" + note.DateAdded.ToString("dd-MM-yyyy") + "):" + Environment.NewLine + Environment.NewLine + ((Label)item.FindControl("lblOriginalText")).Text);
                }
            }
            string[] notes = (string[])list.ToArray(typeof(string));

            string tmpFinalFileName = null;
            if (letter != null)
            {
                tmpFinalFileName = Letter.CreateLetterAndReturnTempFile(
                    Letter.FileFormat.PDF,
                    SiteDB.GetByID(Convert.ToInt32(Session["SiteID"])),
                    letter.LetterID,
                    txtUpdateOrganisationID.Text == "" ? 0 : Convert.ToInt32(txtUpdateOrganisationID.Text),
                    Convert.ToInt32(txtUpdatePatientID.Text),
                    Convert.ToInt32(Session["StaffID"]),
                    Request.QueryString["booking"] == null ? -1 : Convert.ToInt32(Request.QueryString["booking"]),
                    -1,
                    1,
                    notes,
                    true,
                    1);

                if (attachments == null)
                {
                    attachments = new string[] { }
                }
                ;
                string[] newAttachments = new string[attachments.Length + 1];
                newAttachments[0] = tmpFinalFileName;
                Array.Copy(attachments, 0, newAttachments, 1, attachments.Length);
                attachments = newAttachments;
            }

            Emailer.SimpleEmail(
                (string)Session["SiteName"],
                to,
                subject,
                message,
                true,
                attachments,
                null);

            //RemoveDraft();

            SetErrorMessage("Email Sent!");
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
        }
        catch (Exception ex)
        {
            SetErrorMessage("", ex.ToString());
        }
        finally
        {
            if (attachments != null)
            {
                foreach (string file in attachments)
                {
                    System.IO.File.Delete(file);
                }
            }
        }
    }
示例#22
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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



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



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