protected void lnkBackToCallCenter_Click(object sender, EventArgs e) { if (Session == null || Session["PreviousDB"] == null) { Utilities.LogoutV2(Session, Response, Request); return; } Session["DB"] = (string)Session["PreviousDB"]; Session["SystemVariables"] = SystemVariableDB.GetAll(); // Set system staff variables of external staff member 'Call Center' Staff staff = StaffDB.GetByID(Convert.ToInt32(Session["PreviousStaffID"])); Session["IsLoggedIn"] = true; Session["IsStakeholder"] = staff.IsStakeholder; Session["IsMasterAdmin"] = staff.IsMasterAdmin; Session["IsAdmin"] = staff.IsAdmin; Session["IsPrincipal"] = staff.IsPrincipal; Session["IsProvider"] = staff.IsProvider; Session["IsExternal"] = staff.IsExternal; Session["StaffID"] = staff.StaffID; Session["StaffFullnameWithoutMiddlename"] = staff.Person.FullnameWithoutMiddlename; Session["StaffFirstname"] = staff.Person.Firstname; Site site = SiteDB.GetByID(Convert.ToInt32(Session["PreviousSiteID"])); Session["SiteID"] = site.SiteID; Session["SiteName"] = site.Name; Session["SiteIsClinic"] = site.SiteType.ID == 1; Session["SiteIsAgedCare"] = site.SiteType.ID == 2; Session["SiteIsGP"] = site.SiteType.ID == 3; Session["SiteTypeID"] = site.SiteType.ID; Session["SiteTypeDescr"] = site.SiteType.Descr; Session["IsMultipleSites"] = SiteDB.GetAll().Length > 1; Session.Remove("PreviousDB"); Session.Remove("PreviousStaffID"); Session.Remove("PreviousSiteID"); // Set OrgID in session as external user has OrgID set Session.Remove("OrgID"); Session.Remove("OrgName"); // Remove patient list session data for pt searches Session.Remove("patientinfo_data"); Session.Remove("patientlist_data"); Session.Remove("patientlist_sortexpression"); Session.Remove("patientinfo_sortexpression"); // Go to call center page Response.Redirect("~/CallCenterV2.aspx", false); return; }
protected void Select(int siteID) { Site site = SiteDB.GetByID(siteID); Session["SiteID"] = site.SiteID; Session["SiteName"] = site.Name; Session["SiteIsClinic"] = site.SiteType.ID == 1; Session["SiteIsAgedCare"] = site.SiteType.ID == 2; Session["SiteIsGP"] = site.SiteType.ID == 3; Session["SiteTypeID"] = site.SiteType.ID; Session["SiteTypeDescr"] = site.SiteType.Descr; if (Session["PatientID"] == null) { UserLoginDB.UpdateSite(Convert.ToInt32(Session["StaffID"]), -1, siteID); } else { UserLoginDB.UpdateSite(-1, Convert.ToInt32(Session["PatientID"]), siteID); } if (!Convert.ToBoolean(Session["IsAdmin"]) && Session["OrgID"] == null) // need to choose org { Response.Redirect("~/Account/SelectOrgV2.aspx" + (Request.QueryString["from_url"] == null ? "" : "?" + Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url="))), false); return; } else { if (Request.QueryString["from_url"] != null) { Response.Redirect(Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)), false); return; } else { Response.Redirect(Convert.ToInt32(Session["StaffID"]) >= 0 ? "~/Default.aspx" : "~/StaffLoginsV2.aspx", false); return; } } }
protected void GoTo(string db, int orgID, int siteID, int patientID) { //lblInfo1.Text += "GET<br/>DB: " + db + "<br />Org: " + orgID; bool isExternalStaff = orgID != 0 && patientID == -1; bool isStakeHolder = !isExternalStaff && Convert.ToBoolean(Session["IsStakeholder"]); if (db != Session["DB"].ToString()) { // Set previous StaffID, pervious DB Session["PreviousStaffID"] = Session["StaffID"]; Session["PreviousDB"] = Session["DB"]; Session["PreviousSiteID"] = Session["SiteID"]; // Change to new DB & SystemVariables Session["DB"] = db; Session["SystemVariables"] = SystemVariableDB.GetAll(); // Set system staff variables int callCentreStaffID = isExternalStaff ? -5 : (!isStakeHolder ? -7 : -8); Staff staff = StaffDB.GetByID(callCentreStaffID); Session["IsLoggedIn"] = true; Session["IsStakeholder"] = staff.IsStakeholder; Session["IsMasterAdmin"] = staff.IsMasterAdmin; Session["IsAdmin"] = staff.IsAdmin; Session["IsPrincipal"] = staff.IsPrincipal; Session["IsProvider"] = staff.IsProvider; Session["IsExternal"] = staff.IsExternal; Session["StaffID"] = staff.StaffID; Session["StaffFullnameWithoutMiddlename"] = staff.Person.FullnameWithoutMiddlename; Session["StaffFirstname"] = staff.Person.Firstname; // Set OrgID in session as external user has OrgID set if (isExternalStaff) { Organisation org = OrganisationDB.GetByID(orgID); Session["OrgID"] = orgID; Session["OrgName"] = org.Name; } Site site = null; if (siteID != 0) { site = SiteDB.GetByID(siteID); } else { // log in to same site type if possible, else just log in to site 1 site = SiteDB.GetSiteByType((SiteDB.SiteType)Convert.ToInt32(Session["SiteTypeID"]), null, db); if (site == null) { site = SiteDB.GetByID(1); } } Session["SiteID"] = site.SiteID; Session["SiteName"] = site.Name; Session["SiteIsClinic"] = site.SiteType.ID == 1; Session["SiteIsAgedCare"] = site.SiteType.ID == 2; Session["SiteIsGP"] = site.SiteType.ID == 3; Session["SiteTypeID"] = site.SiteType.ID; Session["SiteTypeDescr"] = site.SiteType.Descr; Session["IsMultipleSites"] = SiteDB.GetAll().Length > 1; // Remove patient list session data for pt searches Session.Remove("patientinfo_data"); Session.Remove("patientlist_data"); Session.Remove("patientlist_sortexpression"); Session.Remove("patientinfo_sortexpression"); } // Go to booking page with this org if (isExternalStaff) { Response.Redirect("~/BookingsV2.aspx?orgs=" + Session["OrgID"] + "&ndays=4", false); } else if (patientID != -1 && orgID != 0) { Response.Redirect("~/BookingsV2.aspx?orgs=" + orgID + "&patient=" + patientID + "&ndays=4", false); } else if (patientID != -1 && orgID == 0) { Response.Redirect("~/PatientDetailV2.aspx?type=view&id=" + patientID, false); } else { Response.Redirect("~/Default.aspx", false); } return; }
protected void 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); } } } }
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; } }
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; } }
protected void CreateNoteFile(string tmpFilename) { string header = string.Empty; Booking booking = BookingDB.GetByEntityID(GetFormID()); if (booking != null) { Site site = SiteDB.GetByID(Convert.ToInt32(Session["SiteID"])); string[] phNums; if (Utilities.GetAddressType().ToString() == "Contact") { phNums = ContactDB.GetByEntityID(-1, booking.Organisation.EntityID, 34).Select(r => r.AddrLine1).ToArray(); } else if (Utilities.GetAddressType().ToString() == "ContactAus") { phNums = ContactAusDB.GetByEntityID(-1, booking.Organisation.EntityID, 34).Select(r => r.AddrLine1).ToArray(); } else { throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString()); } if (phNums.Length == 0) { if (Utilities.GetAddressType().ToString() == "Contact") { phNums = ContactDB.GetByEntityID(-1, site.EntityID, 34).Select(r => r.AddrLine1).ToArray(); } else if (Utilities.GetAddressType().ToString() == "ContactAus") { phNums = ContactAusDB.GetByEntityID(-1, site.EntityID, 34).Select(r => r.AddrLine1).ToArray(); } else { throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString()); } } string numbers = string.Empty; if (phNums.Length > 0) { numbers += " - TEL " + phNums[0]; } if (phNums.Length > 1) { numbers += ", " + phNums[1]; } header += site.Name + numbers + Environment.NewLine; header += "Clinic: " + booking.Organisation.Name + Environment.NewLine; if (booking.Patient != null) { header += "Patient: " + booking.Patient.Person.FullnameWithoutMiddlename + Environment.NewLine; } if (booking.Offering != null) { header += "Service: " + booking.Offering.Name + Environment.NewLine; } header += "Provider: " + booking.Provider.Person.FullnameWithoutMiddlename + Environment.NewLine; header += "Date of Consultation: " + booking.DateStart.ToString("d MMM yyyy") + Environment.NewLine + Environment.NewLine + "Treatment Note:" + Environment.NewLine; } System.Collections.ArrayList notesList = new System.Collections.ArrayList(); foreach (GridViewRow row in GrdNote.Rows) { Label lblId = row.FindControl("lblId") as Label; Label lblText = row.FindControl("lblText") as Label; CheckBox chkPrint = row.FindControl("chkPrint") as CheckBox; if (lblId == null || lblText == null || chkPrint == null) { continue; } if (chkPrint.Checked) { notesList.Add(header + lblText.Text.Replace("<br/>", "\n")); } } if (notesList.Count == 0) { throw new CustomMessageException("Please select at least one note to print."); } UserView userView = UserView.GetInstance(); bool isAgedCare = booking != null && booking.Organisation != null ? booking.Organisation.IsAgedCare : userView.IsAgedCareView; string filename = isAgedCare ? "BlankTemplateAC.docx" : "BlankTemplate.docx"; string originalFile = Letter.GetLettersDirectory() + filename; if (!System.IO.File.Exists(originalFile)) { throw new CustomMessageException("Template File '" + filename + "' does not exist."); } string errorString = string.Empty; if (!WordMailMerger.Merge(originalFile, tmpFilename, null, null, 0, false, true, (string[])notesList.ToArray(typeof(string)), false, null, out errorString)) { throw new CustomMessageException("Error:" + errorString); } }
protected void btnUpdateNotesIcon_Click(object sender, EventArgs e) { Site site = SiteDB.GetByID(GetFormID()); // lnkNotes.ImageUrl = NoteDB.HasNotes(site.EntityID) ? "~/images/notes-48.png" : "~/images/notes-bw-48.jpg"; }
protected void Page_Load(object sender, EventArgs e) { try { HideErrorMessage(); SetupGUI(); if (!IsPostBack) { PagePermissions.EnforcePermissions_RequireAll(Session, Response, false, false, true, false, false, true); if ((GetUrlParamType() == UrlParamType.Edit || GetUrlParamType() == UrlParamType.View) && IsValidFormID()) { Site site = SiteDB.GetByID(GetFormID()); if (site != null) { FillEditViewForm(site, GetUrlParamType() == UrlParamType.Edit); } else { HideTableAndSetErrorMessage(); } if (Utilities.GetAddressType().ToString() == "Contact") { addressControl.Visible = true; addressControl.Set(site.EntityID, true, EntityType.GetByType(EntityType.EntityTypeEnum.Site)); } else if (Utilities.GetAddressType().ToString() == "ContactAus") { addressAusControl.Visible = true; addressAusControl.Set(site.EntityID, true, EntityType.GetByType(EntityType.EntityTypeEnum.Site)); } else { throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString()); } } else if (GetUrlParamType() == UrlParamType.Add) { FillEmptyAddForm(); } else { HideTableAndSetErrorMessage(); } } } catch (CustomMessageException ex) { if (IsPostBack) { SetErrorMessage(ex.Message); } else { HideTableAndSetErrorMessage(ex.Message); } } catch (Exception ex) { if (IsPostBack) { SetErrorMessage("", ex.ToString()); } else { HideTableAndSetErrorMessage("", ex.ToString()); } } }
protected void SetupGUI() { for (int i = 0; i < 24; i++) { ddlDayStart_Hour.Items.Add(new ListItem(i.ToString().PadLeft(2, '0'), i.ToString())); ddlLunchStart_Hour.Items.Add(new ListItem(i.ToString().PadLeft(2, '0'), i.ToString())); ddlLunchEnd_Hour.Items.Add(new ListItem(i.ToString().PadLeft(2, '0'), i.ToString())); ddlDayEnd_Hour.Items.Add(new ListItem(i.ToString().PadLeft(2, '0'), i.ToString())); } for (int i = 0; i < 60; i += 15) { ddlDayStart_Minute.Items.Add(new ListItem(i.ToString().PadLeft(2, '0'), i.ToString())); ddlLunchStart_Minute.Items.Add(new ListItem(i.ToString().PadLeft(2, '0'), i.ToString())); ddlLunchEnd_Minute.Items.Add(new ListItem(i.ToString().PadLeft(2, '0'), i.ToString())); ddlDayEnd_Minute.Items.Add(new ListItem(i.ToString().PadLeft(2, '0'), i.ToString())); } for (int i = 1; i < 37; i++) { ddlNumBookingMonthsToGet.Items.Add(new ListItem(i.ToString(), i.ToString())); } for (int i = 1; i < 32; i++) { ddlFiscalYrEnd_Day.Items.Add(new ListItem(i.ToString(), i.ToString())); } int fiscalYearEnd = -1; if ((GetUrlParamType() == UrlParamType.Edit || GetUrlParamType() == UrlParamType.View) && IsValidFormID()) { Site site = SiteDB.GetByID(GetFormID()); if (site != null) { if (site.FiscalYrEnd != DateTime.MinValue) { fiscalYearEnd = site.FiscalYrEnd.Year; } } } int ddlFirstYear = DateTime.Now.Year - 5; int ddlLastYear = DateTime.Today.Year + 5; if (fiscalYearEnd != -1 && fiscalYearEnd < ddlFirstYear) { ddlFiscalYrEnd_Year.Items.Add(new ListItem(fiscalYearEnd.ToString(), fiscalYearEnd.ToString())); } for (int i = ddlFirstYear; i <= ddlLastYear; i++) { ddlFiscalYrEnd_Year.Items.Add(new ListItem(i.ToString(), i.ToString())); } if (fiscalYearEnd != -1 && fiscalYearEnd >= ddlLastYear) { ddlFiscalYrEnd_Year.Items.Add(new ListItem(fiscalYearEnd.ToString(), fiscalYearEnd.ToString())); } bool editable = GetUrlParamType() == UrlParamType.Add || GetUrlParamType() == UrlParamType.Edit; Utilities.SetEditControlBackColour(txtName, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlClinic, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtABN, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtACN, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtTFN, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtASIC, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtBPay, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtBSB, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtBankAccount, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtBankDirectDebitUserID, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtBankUsername, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtOustandingBalanceWarning, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlNumBookingMonthsToGet, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlFiscalYrEnd_Day, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlFiscalYrEnd_Month, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlFiscalYrEnd_Year, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlDayStart_Hour, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlDayStart_Minute, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlLunchStart_Hour, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlLunchStart_Minute, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlLunchEnd_Hour, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlLunchEnd_Minute, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlDayEnd_Hour, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlDayEnd_Minute, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); }
public static Letter.FileContents Run(SendMethod sendMethod, int siteID, int staffID, int registerReferrerID, bool incBatching, bool incUnsent, bool viewListOnly, bool viewFullList, out string outputInfo, out string outputList, string btnViewListClientID) { RndPageID = (new Random()).Next().ToString(); bool debugMode = true; string tmpLettersDirectory = Letter.GetTempLettersDirectory(); if (!Directory.Exists(tmpLettersDirectory)) { throw new CustomMessageException("Temp letters directory doesn't exist"); } int startTime = 0; double queryExecutionTimeClinic = 0; double generateFilesToPrintExecutionTimeClinic = 0; double queryExecutionTimeAgedCare = 0; double generateFilesToPrintExecutionTimeAgedCare = 0; outputInfo = string.Empty; outputList = string.Empty; // // We can not send email all their patients in one email - will be too big with attachments and rejected by their mail provider // So if via email - need to send one at a time // Then if cuts out or times out, it has processed some so don't need to re-process those when it's run again // // remember to process the emails first ... so if any interruptions/errors ... at least some will have been processed // Site[] allSites = SiteDB.GetAll(); bool runAllSites = siteID == -1; Site agedCareSite = null; Site clinicSite = null; Site[] sitesToRun = runAllSites ? allSites : new Site[] { SiteDB.GetByID(siteID) }; foreach (Site s in sitesToRun) { if (s.SiteType.ID == 1) { clinicSite = s; } else if (s.SiteType.ID == 2) { agedCareSite = s; } } ArrayList filesToPrintClinic = new ArrayList(); ArrayList filesToPrintAgedCare = new ArrayList(); string debugOutput = string.Empty; int numGenerated = 0; DataTable bookingsWithUnsetnLettersClinic = null; DataTable bookingsWithUnsetnLettersAgedCare = null; if (clinicSite != null) { startTime = Environment.TickCount; bookingsWithUnsetnLettersClinic = BookingDB.GetBookingsWithEPCLetters(DateTime.MinValue, DateTime.MinValue, registerReferrerID, -1, false, true, incBatching, incUnsent); queryExecutionTimeClinic = (double)(Environment.TickCount - startTime) / 1000.0; startTime = Environment.TickCount; int currentRegReferrerID = -1; ArrayList bookingsForCurrentReferrer = new ArrayList(); foreach (DataRow row in bookingsWithUnsetnLettersClinic.Rows) { numGenerated++; //if (numGenerated % 15 != 1) continue; if ((!viewListOnly || !viewFullList) && (numGenerated > MaxSending)) { continue; } Tuple <Booking, PatientReferrer, bool, string, string, HealthCard> rowData = LoadClinicRow(row); Booking booking = rowData.Item1; PatientReferrer pr = rowData.Item2; bool refHasEmail = rowData.Item3; string refEmail = rowData.Item4; string refFax = rowData.Item5; HealthCard hc = rowData.Item6; //if (booking.Patient == null || (booking.Patient.PatientID != 31522 && booking.Patient.PatientID != 27654)) //{ // numGenerated--; // continue; //} if (pr.RegisterReferrer.RegisterReferrerID != currentRegReferrerID) { filesToPrintClinic.AddRange(ProcessReferrersClinicLetters(sendMethod, viewListOnly, clinicSite, staffID, bookingsForCurrentReferrer, ref debugOutput, btnViewListClientID)); currentRegReferrerID = pr.RegisterReferrer.RegisterReferrerID; bookingsForCurrentReferrer = new ArrayList(); } bookingsForCurrentReferrer.Add(rowData); } // process last group filesToPrintClinic.AddRange(ProcessReferrersClinicLetters(sendMethod, viewListOnly, clinicSite, staffID, bookingsForCurrentReferrer, ref debugOutput, btnViewListClientID)); generateFilesToPrintExecutionTimeClinic = (double)(Environment.TickCount - startTime) / 1000.0; } if (agedCareSite != null) { startTime = Environment.TickCount; bookingsWithUnsetnLettersAgedCare = BookingPatientDB.GetBookingsPatientOfferingsWithEPCLetters(DateTime.MinValue, DateTime.MinValue, registerReferrerID, -1, false, true, incBatching, incUnsent); queryExecutionTimeAgedCare = (double)(Environment.TickCount - startTime) / 1000.0; startTime = Environment.TickCount; int currentRegReferrerID = -1; ArrayList bookingsForCurrentReferrer = new ArrayList(); foreach (DataRow row in bookingsWithUnsetnLettersAgedCare.Rows) { numGenerated++; //if (numGenerated % 15 != 1) continue; if ((!viewListOnly || !viewFullList) && (numGenerated > MaxSending)) { continue; } Tuple <BookingPatient, Offering, PatientReferrer, bool, string, string, HealthCard> rowData = LoadAgedCareRow(row); BookingPatient bp = rowData.Item1; Offering offering = rowData.Item2; PatientReferrer pr = rowData.Item3; bool refHasEmail = rowData.Item4; string refEmail = rowData.Item5; string refFax = rowData.Item6; HealthCard hc = rowData.Item7; //if (bp.Booking.Patient == null || (bp.Booking.Patient.PatientID != 31522 && bp.Booking.Patient.PatientID != 27654)) //{ // numGenerated--; // continue; //} if (pr.RegisterReferrer.RegisterReferrerID != currentRegReferrerID) { filesToPrintAgedCare.AddRange(ProcessReferrersAgedCareLetters(sendMethod, viewListOnly, agedCareSite, staffID, bookingsForCurrentReferrer, ref debugOutput, btnViewListClientID)); currentRegReferrerID = pr.RegisterReferrer.RegisterReferrerID; bookingsForCurrentReferrer = new ArrayList(); } bookingsForCurrentReferrer.Add(rowData); } // process last group filesToPrintAgedCare.AddRange(ProcessReferrersAgedCareLetters(sendMethod, viewListOnly, agedCareSite, staffID, bookingsForCurrentReferrer, ref debugOutput, btnViewListClientID)); generateFilesToPrintExecutionTimeAgedCare = (double)(Environment.TickCount - startTime) / 1000.0; } startTime = Environment.TickCount; bool zipSeperately = true; Letter.FileContents zipFileContents = null; if (zipSeperately && (filesToPrintClinic.Count + filesToPrintAgedCare.Count) > 0) { // if 2 sites exist in the system - change doc names to have "[AgedCare]" or "[Clinics]" before docname if (allSites.Length > 1) { for (int i = 0; i < filesToPrintClinic.Count; i++) { ((Letter.FileContents)filesToPrintClinic[i]).DocName = "[Clinics] " + ((Letter.FileContents)filesToPrintClinic[i]).DocName; } for (int i = 0; i < filesToPrintAgedCare.Count; i++) { ((Letter.FileContents)filesToPrintAgedCare[i]).DocName = "[AgedCare] " + ((Letter.FileContents)filesToPrintAgedCare[i]).DocName; } } ArrayList filesToPrint = new ArrayList(); filesToPrint.AddRange(filesToPrintClinic); filesToPrint.AddRange(filesToPrintAgedCare); // seperate into doc types because can only merge docs with docs of same template (ie docname) Hashtable filesToPrintHash = new Hashtable(); for (int i = 0; i < filesToPrint.Count; i++) { Letter.FileContents curFileContents = (Letter.FileContents)filesToPrint[i]; if (filesToPrintHash[curFileContents.DocName] == null) { filesToPrintHash[curFileContents.DocName] = new ArrayList(); } ((ArrayList)filesToPrintHash[curFileContents.DocName]).Add(curFileContents); } // merge and put merged files into temp dir string baseTmpDir = FileHelper.GetTempDirectoryName(tmpLettersDirectory); string tmpDir = baseTmpDir + "Referral Letters" + @"\"; Directory.CreateDirectory(tmpDir); string[] tmpFiles = new string[filesToPrintHash.Keys.Count]; IDictionaryEnumerator enumerator = filesToPrintHash.GetEnumerator(); for (int i = 0; enumerator.MoveNext(); i++) { ArrayList files = (ArrayList)enumerator.Value; string docName = (string)enumerator.Key; // last file is screwing up, so just re-add the last file again for a temp fix files.Add(files[files.Count - 1]); Letter.FileContents fileContents = Letter.FileContents.Merge((Letter.FileContents[])files.ToArray(typeof(Letter.FileContents)), docName); // .pdf string tmpFileName = tmpDir + fileContents.DocName; System.IO.File.WriteAllBytes(tmpFileName, fileContents.Contents); tmpFiles[i] = tmpFileName; } // zip em string zipFileName = "Referral Letters.zip"; string zipFilePath = baseTmpDir + zipFileName; ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip(); zip.CreateEmptyDirectories = true; zip.CreateZip(zipFilePath, tmpDir, true, ""); // get filecontents of zip here zipFileContents = new Letter.FileContents(zipFilePath, zipFileName); //Letter.FileContents zipFileContents = new Letter.FileContents(zipFilePath, zipFileName); //System.Web.HttpContext.Current.Session["downloadFile_Contents"] = zipFileContents.Contents; //System.Web.HttpContext.Current.Session["downloadFile_DocName"] = zipFileContents.DocName; // delete files for (int i = 0; i < tmpFiles.Length; i++) { System.IO.File.SetAttributes(tmpFiles[i], FileAttributes.Normal); System.IO.File.Delete(tmpFiles[i]); } System.IO.File.SetAttributes(zipFilePath, FileAttributes.Normal); System.IO.File.Delete(zipFilePath); System.IO.Directory.Delete(tmpDir, false); System.IO.Directory.Delete(baseTmpDir, false); // put in session variables so when it reloads to this page, we can popup the download window //Page.ClientScript.RegisterStartupScript(this.GetType(), "download", "<script language=javascript>window.open('DownloadFile.aspx','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30');</script>"); } if (!zipSeperately && (filesToPrintClinic.Count + filesToPrintAgedCare.Count) > 0) { ArrayList filesToPrint = new ArrayList(); filesToPrint.AddRange(filesToPrintClinic); filesToPrint.AddRange(filesToPrintAgedCare); zipFileContents = Letter.FileContents.Merge((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)), "Referral Letters.doc"); // .pdf //Letter.FileContents fileContents = Letter.FileContents.Merge((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)), "Referral Letters.doc"); // .pdf //System.Web.HttpContext.Current.Session["downloadFile_Contents"] = fileContents.Contents; //System.Web.HttpContext.Current.Session["downloadFile_DocName"] = fileContents.DocName; // put in session variables so when it reloads to this page, we can popup the download window //Page.ClientScript.RegisterStartupScript(this.GetType(), "download", "<script language=javascript>window.open('DownloadFile.aspx','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30');</script>"); } if (!viewListOnly && registerReferrerID == -1 && incBatching) { SetLastDateBatchSendTreatmentNotesAllReferrers(DateTime.Now); } double restExecutionTime = (double)(Environment.TickCount - startTime) / 1000.0; if (debugMode) { int total = (bookingsWithUnsetnLettersClinic == null ? 0 : bookingsWithUnsetnLettersClinic.Rows.Count) + (bookingsWithUnsetnLettersAgedCare == null ? 0 : bookingsWithUnsetnLettersAgedCare.Rows.Count); string countGenrated = total > MaxSending ? MaxSending + " of " + total + " generated" : total.ToString() + " generated"; string countShowing = total > MaxSending ? MaxSending + " of " + total + " showing to generate. <br />* If there are more than " + MaxSending + ", the next " + MaxSending + " will have to be generated seperately after this." : total.ToString(); if (total > MaxSending && viewFullList) { countShowing = total + " showing to generate. <br />* If there are more than " + MaxSending + ", only the first " + MaxSending + " will be generated and batches of " + MaxSending + " will have to be generated seperately after."; } string queryExecutionTimeText = string.Empty; if (agedCareSite == null && clinicSite == null) { queryExecutionTimeText = "0"; } if (agedCareSite == null && clinicSite != null) { queryExecutionTimeText = queryExecutionTimeClinic.ToString(); } if (agedCareSite != null && clinicSite == null) { queryExecutionTimeText = queryExecutionTimeAgedCare.ToString(); } if (agedCareSite != null && clinicSite != null) { queryExecutionTimeText = "[Clinics: " + queryExecutionTimeClinic + "] [AgedCare: " + queryExecutionTimeAgedCare + "]"; } string restExecutionTimeText = string.Empty; if (agedCareSite == null && clinicSite == null) { restExecutionTimeText = "0"; } if (agedCareSite == null && clinicSite != null) { restExecutionTimeText = (generateFilesToPrintExecutionTimeClinic + restExecutionTime).ToString(); } if (agedCareSite != null && clinicSite == null) { restExecutionTimeText = (generateFilesToPrintExecutionTimeAgedCare + restExecutionTime).ToString(); } if (agedCareSite != null && clinicSite != null) { restExecutionTimeText = "[Clinics: " + generateFilesToPrintExecutionTimeClinic + "] [AgedCare: " + generateFilesToPrintExecutionTimeAgedCare + "] [Merging" + restExecutionTime + "]"; } if (!viewListOnly) { outputInfo = @"<table cellpadding=""0""> <tr><td><b>Send Method</b></td><td style=""width:10px;""></td><td>" + sendMethod.ToString() + @"</td><td style=""width:25px;""></td><td><b>Query Time</b></td><td style=""width:10px;""></td><td>" + queryExecutionTimeText + @" seconds</td></tr> <tr><td><b>Count</b></td><td style=""width:10px;""></td><td>" + countGenrated + @"</td><td style=""width:25px;""></td><td><b>Runing Time</b></td><td style=""width:10px;""></td><td>" + restExecutionTimeText + @" seconds</td></tr> </table>"; } if (viewListOnly) { outputInfo = @"<table cellpadding=""0""> <tr><td valign=""top""><b>Count</b></td><td style=""width:10px;""></td><td>" + countShowing + @"</td></tr> </table>"; } if (viewListOnly) { outputList = @"<table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" border=""1""> <tr> <th>Site</th> <th>Send By</th> <th>Booking</th> <th>Generate</th> <th>Referrer</th> <th>Email</th> <th>Fax</th> <th>Update Email/Fax</th> <th>Patient</th> </tr>" + (debugOutput.Length == 0 ? "<tr><td colspan=\"6\">No Rows</td></tr>" : debugOutput) + "</table>"; } } return(zipFileContents); }
protected Letter.FileContents[] ProcessReferrersLetters(bool viewListOnly, ArrayList bookingsForCurrentReferrer, bool autoSendFaxesAsEmailsIfNoEmailExistsToGPs, ref string debugOutput, int bulkLetterSendingQueueBatchID) { if (bookingsForCurrentReferrer.Count == 0) { return(new Letter.FileContents[0]); } // to return - only files to print, as emailing will have been completed ArrayList filesToPrint = new ArrayList(); // single db lookup per referrer to get email Tuple <Booking, PatientReferrer, bool, bool, HealthCard> firstTuple = (Tuple <Booking, PatientReferrer, bool, bool, HealthCard>)bookingsForCurrentReferrer[0]; PatientReferrer firstPR = firstTuple.Item2; int s = firstPR.RegisterReferrer.RegisterReferrerID; string[] refEmails = ContactDB.GetEmailsByEntityID(firstPR.RegisterReferrer.Organisation.EntityID); string[] refFaxes = ContactDB.GetFaxesByEntityID(firstPR.RegisterReferrer.Organisation.EntityID); bool firstRefHasEmail = refEmails.Length > 0; string refEmail = refEmails.Length > 0 ? string.Join(",", refEmails) : null; bool firstRefHasFax = refFaxes.Length > 0; string refFax = refFaxes.Length > 0 ? refFaxes[0] : null; int siteID = Convert.ToInt32(Session["SiteID"]); Site site = SiteDB.GetByID(siteID); int staffID = Convert.ToInt32(Session["StaffID"]); Site[] sites = SiteDB.GetAll(); for (int i = 0; i < bookingsForCurrentReferrer.Count; i++) { Tuple <Booking, PatientReferrer, bool, bool, HealthCard> curTuple = (Tuple <Booking, PatientReferrer, bool, bool, HealthCard>)bookingsForCurrentReferrer[i]; Booking curBooking = curTuple.Item1; PatientReferrer curPR = curTuple.Item2; bool curRefHasEmail = curTuple.Item3; bool curRefHasFax = curTuple.Item4; HealthCard curHC = curTuple.Item5; bool needToGenerateLetters = curBooking.NeedToGenerateFirstLetter || curBooking.NeedToGenerateLastLetter || (curPR.RegisterReferrer.ReportEveryVisitToReferrer && curBooking.NoteCount > 0); if (needToGenerateLetters) { SendMethod sendMethod = (curRefHasEmail && this.SelectedSendMethod == SendMethod.Email ? SendMethod.Email : SendMethod.Print); if (!viewListOnly) { bool sendViaEmail = autoSendFaxesAsEmailsIfNoEmailExistsToGPs ? (curRefHasEmail || curRefHasFax) : curRefHasEmail; if (sendViaEmail && this.SelectedSendMethod == SendMethod.Email) { string toEmail = autoSendFaxesAsEmailsIfNoEmailExistsToGPs ? (curRefHasEmail ? refEmail : Regex.Replace(refFax, "[^0-9]", "") + "@fax.houseofit.com.au") : refEmail; if (UseBulkLetterSender) { BulkLetterSendingQueueAdditionalLetter[] filesList = GetFilesInfo(curBooking, Letter.FileFormat.PDF, curBooking.Patient, curHC, curBooking.Offering.Field.ID, curPR.RegisterReferrer.Referrer, false, curBooking.NeedToGenerateFirstLetter, curBooking.NeedToGenerateLastLetter, curPR.RegisterReferrer.ReportEveryVisitToReferrer, siteID, staffID, sendMethod == SendMethod.Email ? 2 : 1); if (filesList != null && filesList.Length > 0) { string from_email = ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromEmail"].Value; string subject = "Referral/Treatment Note Letters From Mediclinic" + (curPR.Patient == null ? string.Empty : " For " + curPR.Patient.Person.FullnameWithoutMiddlename); string text = "Dr. " + curPR.RegisterReferrer.Referrer.Person.FullnameWithoutMiddlename + "<br /><br />Please find attached referral/treatment note letters for your referrered patient" + (curPR.Patient == null ? string.Empty : " <b>" + curPR.Patient.Person.FullnameWithoutMiddlename + "</b>") + "<br /><br />Best regards,<br />" + site.Name; int bulk_letter_sending_queue_id = BulkLetterSendingQueueDB.Insert ( bulkLetterSendingQueueBatchID, 2, // bulk_letter_sending_queue_method_id (2 = email) staffID, // added_by curPR.Patient.PatientID, // patient_id curPR.RegisterReferrer.Referrer.ReferrerID, // referrer_id curBooking.BookingID, // booking_id "", // phone_number toEmail, // email_to_address "", // email_to_name from_email, // email_from_address site.Name, // email_from_name text, // text subject, // email_subject "", // email_attachment_location false, // email_attachment_delete_after_sending false, // email_attachment_folder_delete_after_sending filesList[0].EmailLetterLetterID, filesList[0].EmailLetterKeepHistoryInDb, filesList[0].EmailLetterKeepHistoryInFile, filesList[0].EmailLetterLetterPrintHistorySendMethodID, filesList[0].EmailLetterHistoryDir, filesList[0].EmailLetterHistoryFilename, filesList[0].EmailLetterSiteID, filesList[0].EmailLetterOrganisationID, filesList[0].EmailLetterBookingID, filesList[0].EmailLetterPatientID, filesList[0].EmailLetterRegisterReferrerIdToUseInsteadOfPatientsRegRef, filesList[0].EmailLetterStaffID, filesList[0].EmailLetterHealthCardActionID, filesList[0].EmailLetterSourceTemplatePath, filesList[0].EmailLetterOutputDocPath, false, // filesList[0].EmailLetterIsDoubleSidedPrinting, filesList[0].EmailLetterExtraPages, filesList[0].EmailLetterItemSeperator, "", // sql_to_run_on_completion "" // sql_to_run_on_failure ); for (int f = 1; f < filesList.Length; f++) { BulkLetterSendingQueueAdditionalLetterDB.Insert( bulk_letter_sending_queue_id, filesList[f].EmailLetterLetterID, filesList[f].EmailLetterKeepHistoryInDb, filesList[f].EmailLetterKeepHistoryInFile, filesList[f].EmailLetterLetterPrintHistorySendMethodID, filesList[f].EmailLetterHistoryDir, filesList[f].EmailLetterHistoryFilename, filesList[f].EmailLetterSiteID, filesList[f].EmailLetterOrganisationID, filesList[f].EmailLetterBookingID, filesList[f].EmailLetterPatientID, filesList[f].EmailLetterRegisterReferrerIdToUseInsteadOfPatientsRegRef, filesList[f].EmailLetterStaffID, filesList[f].EmailLetterHealthCardActionID, filesList[f].EmailLetterSourceTemplatePath, filesList[f].EmailLetterOutputDocPath, false, // filesList[f].EmailLetterIsDoubleSidedPrinting, filesList[f].EmailLetterExtraPages, filesList[f].EmailLetterItemSeperator); } } } else { Letter.FileContents[] fileContentsList = curBooking.GetSystemLettersList(Letter.FileFormat.PDF, curBooking.Patient, curHC, curBooking.Offering.Field.ID, curPR.RegisterReferrer.Referrer, false, curBooking.NeedToGenerateFirstLetter, curBooking.NeedToGenerateLastLetter, curPR.RegisterReferrer.ReportEveryVisitToReferrer, false, Convert.ToInt32(Session["SiteID"]), Convert.ToInt32(Session["StaffID"]), sendMethod == SendMethod.Email ? 2 : 1); if (fileContentsList != null && fileContentsList.Length > 0) { //Logger.LogQuery("ReferrerEPCLetters_Reprint -- Email Send Item Starting!"); Site bkSite = SiteDB.GetSiteByType(curBooking.Organisation.IsAgedCare ? SiteDB.SiteType.AgedCare : SiteDB.SiteType.Clinic, sites); Letter.EmailSystemLetter(bkSite.Name, toEmail, fileContentsList); //Logger.LogQuery("ReferrerEPCLetters_Reprint -- Email Send Item Done!"); } } } else { Letter.FileContents[] fileContentsList = curBooking.GetSystemLettersList(Letter.FileFormat.Word, curBooking.Patient, curHC, curBooking.Offering.Field.ID, curPR.RegisterReferrer.Referrer, false, curBooking.NeedToGenerateFirstLetter, curBooking.NeedToGenerateLastLetter, curPR.RegisterReferrer.ReportEveryVisitToReferrer, false, Convert.ToInt32(Session["SiteID"]), Convert.ToInt32(Session["StaffID"]), sendMethod == SendMethod.Email ? 2 : 1); if (fileContentsList != null && fileContentsList.Length > 0) { filesToPrint.AddRange(fileContentsList); } } BookingDB.UpdateSetGeneratedSystemLetters(curBooking.BookingID, curBooking.NeedToGenerateFirstLetter, curBooking.NeedToGenerateLastLetter, true); } ArrayList toGenerateList = new ArrayList(); if (curBooking.NeedToGenerateFirstLetter) { toGenerateList.Add("First"); } if (curBooking.NeedToGenerateLastLetter) { toGenerateList.Add("Last"); } if (curPR.RegisterReferrer.ReportEveryVisitToReferrer && curBooking.NoteCount > 0) { toGenerateList.Add("Notes"); } string toGenerate = string.Join(",", (string[])toGenerateList.ToArray(typeof(string))); debugOutput += @"<tr> <td>" + sendMethod + @"</td> <td style=""white-space:nowrap;"">" + curBooking.BookingID + " [" + curBooking.DateStart.ToString("dd-MM-yyyy") + " " + curBooking.DateStart.ToString("HH:mm") + "-" + curBooking.DateEnd.ToString("HH:mm") + "]" + @"</td> <td>" + toGenerate + @"</td> <td>" + curPR.RegisterReferrer.Referrer.Person.FullnameWithoutMiddlename + @"</td> <td style=""white-space:nowrap;"">" + (curRefHasEmail ? refEmail : "") + @"</td> <td style=""white-space:nowrap;"">" + (curRefHasFax ? refFax : "") + @"</td> <td>" + curPR.Patient.Person.FullnameWithoutMiddlename + @"</td> </tr>"; } } return((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents))); }
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(); } } }