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();
        }
    }
示例#2
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();
    }
示例#3
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));
    }
示例#4
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);
                }
            }
        }
    }
示例#5
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;
        }
    }
示例#6
0
    protected void SetUrlFields()
    {
        try
        {
            string booking_patient_id = Request.QueryString["bookingpatient"];
            string booking_id         = Request.QueryString["booking"];

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

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

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

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

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

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


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


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

                        PopulateLettersList();

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

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

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

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

                    PopulateLettersList();

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


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

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

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

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


            txtSubject.Text   = SystemVariableDB.GetByDescr("LettersEmailDefaultSubject").Value;
            FreeTextBox1.Text = SystemVariableDB.GetByDescr("LettersEmailSignature").Value;
        }
        catch (CustomMessageException ex)
        {
            SetErrorMessage();
        }
    }
    protected 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;
        }
    }
    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,
                   "",
                   ""
                   ));
    }
示例#9
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();
            }
        }
    }