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 SetupGUI() { mi_patient_add_with_id.Visible = Session != null && Session["DB"] != null && Session["DB"].ToString() == "Mediclinic_0030"; UserView userView = UserView.GetInstance(); bool isLoggedInAsCallCenter = Session != null && Session["StaffID"] != null && (new List <int> { -5, -7, -8 }).Contains((int)Session["StaffID"]); if (isLoggedInAsCallCenter) { nav.Style["background"] = nav_ul.Style["background"] = footer.Style["background"] = "#A3BEF5"; } lblSiteIsClinic.Value = userView.IsClinicView? "1" : "0"; lblSiteIsAgedCare.Value = userView.IsAgedCareView ? "1" : "0"; banner.Style["background"] = (Session["SystemVariables"] == null || ((SystemVariables)Session["SystemVariables"])["MainLogo"] == null) ? "url(../imagesV2/comp_logo.png) no-repeat center center" : "url(../imagesV2/" + ((SystemVariables)Session["SystemVariables"])["MainLogo"].Value + ") no-repeat center center"; lblSiteName.Text = Session["SystemVariables"] == null ? "Mediclinic" : ((SystemVariables)Session["SystemVariables"])["Site"].Value; lblSiteName.Visible = lblDataStoredAusServersMsg.Visible = lnkLiveSupport.Visible = Session["SystemVariables"] != null; // when call centre logged in, put call-centre prefix showing at the end of the sitename always visible if (isLoggedInAsCallCenter) { lblSiteName.Text += Session["SystemVariables"] == null ? "" : " <span style=\"color:#82cde9\">[" + ((SystemVariables)Session["SystemVariables"])["CallCenterPrefix"].Value + "]</span>"; } spn_login_display.Visible = userView.IsLoggedIn; if (userView.IsLoggedIn) { string siteOrgNameRaw = (userView.IsAdminView) ? (Session["SiteName"] == null ? "[No Site Selected]" : Utilities.TrimName((string)Session["SiteName"], 35, 2)) : (Session["SiteName"] == null ? "[No Site Selected]" : Utilities.TrimName((string)Session["SiteName"], 18, 2)) + (Session["SiteName"] == null ? " [" : " (") + (Session["OrgName"] == null ? "No Clinic Selected" : Utilities.TrimName((string)Session["OrgName"], 25, 2)) + (Session["SiteName"] == null ? "]" : ")"); lblSiteOrOrg.Text = siteOrgNameRaw; lblUsername.Text = (siteOrgNameRaw.Length > 35) ? Utilities.TrimName((string)Session["StaffFullnameWithoutMiddlename"], 25, 2) : Session["StaffFullnameWithoutMiddlename"].ToString(); if (Session["SiteID"] == null || Session["IsMultipleSites"] == null || (bool)Session["IsMultipleSites"] == false || Session["PatientID"] != null) { lnkSelectSite.Visible = lnkSelectSite_OpenBracket.Visible = lnkSelectSite_CloseBracket.Visible = false; } if (Session["OrgID"] == null || Session["IsMultipleOrgs"] == null || (bool)Session["IsMultipleOrgs"] == false) { lnkSelectOrg.Visible = lnkSelectOrg_OpenBracket.Visible = lnkSelectOrg_CloseBracket.Visible = false; } if (Session["SiteID"] == null || (!userView.IsAdminView && Session["OrgID"] == null)) { lnkChangePwd.Visible = lnkChangePwd_OpenBracket.Visible = lnkChangePwd_CloseBracket.Visible = false; } } /* * set and hide/show menu items depending on user privileges */ lblMenuOrganisations.Text = !userView.IsAgedCareView ? "Clinics / Ins." : "Facilities / Ins."; lnkMenuOrganisationList.Text = !userView.IsAgedCareView ? "Clinics List" : "Facilities List"; lnkMenuOrganisationList.NavigateUrl = !userView.IsAgedCareView ? "~/OrganisationListV2.aspx?type=clinic" : "~/OrganisationListV2.aspx?type=ac"; lnkMenuAddOrganisation.Text = !userView.IsAgedCareView ? "Add Clinic" : "Add Facility"; lnkMenuAddOrganisation.NavigateUrl = !userView.IsAgedCareView ? "~/OrganisationDetailV2.aspx?type=add&orgtype=clinic" : "~/OrganisationDetailV2.aspx?type=add&orgtype=ac"; lblMenuPatients.Text = !userView.IsAgedCareView ? "Patients" : "Residents"; lnkMenuPatientList.Text = !userView.IsAgedCareView ? "Patient List" : "Resident List"; lnkMenuPatientAdd.Text = !userView.IsAgedCareView ? "Add Patient" : "Add Resident"; lnkMenuPatientAddWithID.Text = !userView.IsAgedCareView ? "Add Patient <b>WITH ID</b>" : "Add Resident <b>WITH ID</b>"; bool hasClinics = false; bool hasAC = false; if (Session != null && Session["DB"] != null) { foreach (Site site in SiteDB.GetAll()) { if (site.SiteType.ID == 1 || site.SiteType.ID == 3) { hasClinics = true; } if (site.SiteType.ID == 2) { hasAC = true; } } } if (hasClinics && hasAC) { lnkMenuOrganisationCustomerTypes.Text = "Clinic/Facility Customer Types"; } else if (hasClinics) { lnkMenuOrganisationCustomerTypes.Text = "Clinic Customer Types"; } else if (hasAC) { lnkMenuOrganisationCustomerTypes.Text = "Facility Customer Types"; } mh_staff.Visible = mh_staff_spacer.Visible = userView.IsStakeholder || userView.IsMasterAdmin; mh_patients_space.Visible = mh_patients.Visible = userView.IsAdminView || userView.IsProviderView; mi_patient_cond_list.Visible = userView.IsAdminView; mh_organisation.Visible = mh_organisation_spacer.Visible = userView.IsAdminView; mh_referrers.Visible = mh_referrers_space.Visible = userView.IsAdminView || userView.IsProviderView; mh_bookings_space.Visible = mh_bookings.Visible = userView.IsAdminView || userView.IsProviderView; lblMenuBookings.Text = userView.IsAdminView ? "Bookings & Sales" : "Bookings"; mi_bookings_offerings_seperator.Visible = userView.IsAdminView; mi_bookings_offerings_products_and_services_list.Visible = userView.IsAdminView; mi_bookings_offerings_set_specific_prices.Visible = userView.IsAdminView || userView.IsProviderView; mi_bookings_offerings_stock.Visible = userView.IsAdminView || userView.IsProviderView; mi_bookings_offerings_set_specific_prices.Visible = userView.IsAdminView; mi_bookings_offerings_invoice_cash_add.Visible = userView.IsAdminView; mh_sales.Visible = mh_sales_space.Visible = userView.IsAdminView || userView.IsProviderView; mh_financials.Visible = mh_financials_spacer.Visible = userView.IsAdminView; mh_letters.Visible = mh_letters_space.Visible = userView.IsAdminView || userView.IsProviderView; mh_sms_and_email.Visible = mh_sms_and_email_spacer.Visible = userView.IsAdminView; mh_site_and_settings.Visible = userView.IsAdminView; mh_ext_patient_list.Visible = mh_ext_patient_list_space.Visible = userView.IsExternalView; mh_ext_patient_add.Visible = mh_ext_patient_add_space.Visible = userView.IsExternalView; mh_ext_next_booking_space.Visible = userView.IsExternalView; mh_ext_next_booking.Visible = mh_ext_bookings_space.Visible = userView.IsExternalView; mh_ext_bookings_space.Visible = false; mh_ext_bookings.Visible = userView.IsExternalView; //mh_ext_bookings.Visible = mh_ext_bookings_space.Visible = isExternal; mh_ext_return_to_callcenter.Visible = mh_ext_return_to_callcenter_space_post.Visible = isLoggedInAsCallCenter; mh_ext_return_to_callcenter_space_pre.Visible = false; if (isLoggedInAsCallCenter) { mh_ext_return_to_callcenter_space_pre.Visible = true; mh_ext_return_to_callcenter_space_post.Visible = false; } if (userView.IsExternalView) { lnkMenuPatientListExt.NavigateUrl = "~/PatientListV2.aspx"; lnkMenuPatientAddExt.NavigateUrl = "~/PatientAddV2.aspx"; lnkMenuBookingsExt.NavigateUrl = "~/BookingsV2.aspx?orgs=" + Session["OrgID"] + (Session != null && Session["StaffID"] != null && (int)Session["StaffID"] != -5 ? "&ndays=3" : "&ndays=4"); } mi_patient_ac_types.Visible = userView.IsAgedCareView && userView.IsAdminView; mi_patient_ac_types_prices_per_fac.Visible = userView.IsAgedCareView && userView.IsAdminView; mi_referrer_epc_letters_generate_unsent_list.Visible = userView.IsAdminView; mi_referrer_epc_letters_reprint_list.Visible = userView.IsAdminView; mi_link_bookings.InnerText = userView.IsAdminView ? "Make Booking" : "Bookings"; mi_bookings_call_center.Visible = userView.IsAdminView && !isLoggedInAsCallCenter && Session != null && Session["SystemVariables"] != null && ((SystemVariables)Session["SystemVariables"])["IsMediclinicCallCenter"].Value == "1"; if (userView.IsAdminView) { mi_bookings_list.Visible = false; } if (!userView.IsAdminView) { mi_link_bookings.HRef = "/BookingsV2.aspx?orgs=" + Session["OrgID"] + "&ndays=1"; mi_link_bookings_list.HRef = "/BookingsListV2.aspx?staff=" + Session["StaffID"] + "&start_date=" + DateTime.Today.ToString("yyyy_MM_dd") + "&end_date=" + DateTime.Today.ToString("yyyy_MM_dd"); mi_bookings_list.Visible = userView.IsAdminView || userView.IsProviderView; mi_bookings_report.Visible = userView.IsAdminView; mi_bookings_schedule_report.Visible = userView.IsAdminView || userView.IsProviderView; mi_bookings_hours_worked_report.Visible = userView.IsAdminView || userView.IsProviderView; mi_bookings_change_edit_reason.Visible = userView.IsAdminView; mi_bookings_change_unavailability_reason.Visible = userView.IsAdminView; } mi_link_offerings_set_specific_prices.InnerText = !userView.IsAgedCareView ? "Set Specific Prices Per Clinic" : "Set Specific Prices Per Facility/Wing/Unit"; mi_link_offerings_invoice_cash_add.HRef = userView.IsAdminView ? "/InvoiceCashAddV2.aspx" : "/InvoiceCashAddV2.aspx?org=" + (Session["OrgID"] == null ? "" : Session["OrgID"].ToString());; mh_sales.Visible = mh_sales_space.Visible = userView.IsProviderView; mi_link_sales_invoice_cash_add.HRef = userView.IsAdminView ? "/InvoiceCashAddV2.aspx" : "/InvoiceCashAddV2.aspx?org=" + (Session["OrgID"] == null ? "" : Session["OrgID"].ToString()); mi_financials_ezidebit_info.Visible = userView.IsStakeholder || userView.IsMasterAdmin; mi_financials_claim_nbr_allocation.Visible = userView.IsStakeholder; mi_financials_claim_nbrs_allocated.Visible = userView.IsStakeholder; mi_financials_hinx_generation.Visible = userView.IsStakeholder; if (!userView.IsAdminView) { mi_letters_maintain.Visible = false; mi_letters_maintain_treatment_letters.Visible = false; mi_letters_print_batch.Visible = false; mi_letters_print_batch_referrers.Visible = false; mi_letters_recall.Visible = false; mi_letters_service_specific_bk_reminders.Visible = false; mi_link_letters_print.HRef += (Session != null && Session["OrgID"] != null ? "?org=" + Session["OrgID"].ToString() : ""); mi_link_letters_sent_history.HRef += (Session != null && Session["OrgID"] != null ? "?org=" + Session["OrgID"].ToString() : ""); } else { mi_letters_recall.Visible = !userView.IsAgedCareView; } mi_website_settings.Visible = userView.IsStakeholder || userView.IsMasterAdmin; mi_add_aged_care_site.Visible = userView.IsStakeholder && SiteDB.GetSiteByType(SiteDB.SiteType.AgedCare) == null; mi_add_new_field.Visible = userView.IsStakeholder; mi_create_new_site.Visible = userView.IsStakeholder; if (HttpContext.Current.Request.Url.LocalPath.Contains("/Account/LoginV2.aspx") || HttpContext.Current.Request.Url.LocalPath.Contains("/Account/SelectOrgV2.aspx") || HttpContext.Current.Request.Url.LocalPath.Contains("/Account/SelectSiteV2.aspx") || HttpContext.Current.Request.Url.LocalPath.Contains("/Account/CreateNewLoginV2.aspx") || HttpContext.Current.Request.Url.LocalPath.Contains("/Account/LostPasswordV2.aspx") || HttpContext.Current.Request.Url.LocalPath.EndsWith("/Account/CreateNewPatientV2.aspx") || HttpContext.Current.Request.Url.LocalPath.EndsWith("/InvoicePaymentV2.aspx") || HttpContext.Current.Request.Url.LocalPath.EndsWith("/PatientUnsubscribeV2.aspx") || HttpContext.Current.Request.Url.LocalPath.EndsWith("/Invoice_WebPayV2.aspx") || HttpContext.Current.Request.Url.LocalPath.EndsWith("/CreateNewCustomerSiteV2.aspx") || HttpContext.Current.Request.Url.LocalPath.EndsWith("/TermsAndConditionsV2.aspx") ) { div_menu2.Visible = false; } if (Session["SystemVariables"] != null && !Page.Title.StartsWith(((SystemVariables)Session["SystemVariables"])["Site"].Value + " - ")) { Page.Title = ((SystemVariables)Session["SystemVariables"])["Site"].Value + " - " + Page.Title; } int s = Session["StaffID"] == null ? -1 : (int)Session["StaffID"]; string db = Session["DB"] == null ? "" : (string)Session["DB"]; if ((Session["DB"] != null && (string)Session["DB"] == "Mediclinic_0034") && (Session["StaffID"] != null && (new List <int> { -5, -7, -8 }).Contains((int)Session["StaffID"]))) { lnkLiveSupport.Attributes.Add("onclick", "open_new_tab('http://www.homevisitphysio.com.au/phoneadmin');return false"); lnkLiveSupport.NavigateUrl = "http://www.homevisitphysio.com.au/phoneadmin"; lnkLiveSupport.Text = " PHONE SCRIPT "; lnkLiveSupport.Style["background-color"] = "#BA9EB0"; lnkLiveSupport.Style["color"] = "white"; } }
public EventsController() { _db = new SiteDB(); }
protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { Utilities.SetNoCache(Response); } HideErrorMessage(); if (!IsPostBack) { PagePermissions.EnforcePermissions_RequireAny(Session, Response, true, true, true, false, false, false); Session.Remove("organisationcustomertype_sortexpression"); Session.Remove("organisationcustomertype_data"); bool hasClinics = false; bool hasAC = false; foreach (Site site in SiteDB.GetAll()) { if (site.SiteType.ID == 1 || site.SiteType.ID == 3) { hasClinics = true; } if (site.SiteType.ID == 2) { hasAC = true; } } if (hasClinics && hasAC) { lblHeading.Text = Page.Title = "Clinic/Facility Customer Types"; } else if (hasClinics) { lblHeading.Text = Page.Title = "Clinic Customer Types"; } else if (hasAC) { lblHeading.Text = Page.Title = "Facility Customer Types"; } FillGrid(); } if (!Utilities.IsDev()) { PagePermissions.EnforcePermissions_RequireAny(Session, Response, true, true, true, false, false, false); } this.GrdOrganisationCustomerType.EnableViewState = true; } 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 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; } }
private void LogIn(string login, string pwd) { try { Session.Remove("DB"); if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"])) { Session["DB"] = ConfigurationManager.AppSettings["Database"]; } else // Get DB from Mediclinic_Main { UserDatabaseMapper user = UserDatabaseMapperDB.GetByLogin(login); if (user == null) { this.FailureText.Text = "<div class=\"alert alert-danger\" runat=\"server\"><strong>Login Failed.</strong> Please ensure that your username and password are correct and try again.</div>"; return; } Session["DB"] = user.DBName; } Staff staff = StaffDB.GetByLogin(login); Patient patient = PatientDB.GetByLogin(login); bool allowPatientLogins = Convert.ToInt32(SystemVariableDB.GetByDescr("AllowPatientLogins").Value) == 1; bool validStaff = staff != null && staff.Pwd == pwd && !staff.IsFired; bool validPatient = allowPatientLogins && patient != null && patient.Pwd == pwd && !patient.IsDeleted; if (validStaff) { UserLogin curLogin = UserLoginDB.GetCurLoggedIn(staff.StaffID, -1, HttpContext.Current.Session.SessionID, -1); if (curLogin != null) { UserLoginDB.UpdateLastAccessTime(curLogin.UserloginID, DateTime.Now, Request.RawUrl); UserLoginDB.UpdateSetOtherSessionsOfThisUserLoggedOut(curLogin.UserloginID, staff.StaffID, -1); } else { UserLoginDB.UpdateSetAllSessionsLoggedOut(staff.StaffID, -1); UserLoginDB.Insert((staff == null) ? -1 : staff.StaffID, -1, login, -1, validStaff, HttpContext.Current.Session.SessionID, Request.UserHostAddress); } this.FailureText.Text = ""; 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; Session["NumDaysToDisplayOnBookingScreen"] = staff.NumDaysToDisplayOnBookingScreen; Session["HideBookingNotes"] = staff.HideBookingNotes; Session["ShowOtherProvidersOnBookingScreen"] = false; Session["ShowHeaderOnBookingScreen"] = staff.ShowHeaderOnBookingScreen; Session["SystemVariables"] = SystemVariableDB.GetAll(); Session["OfferingColors"] = OfferingDB.GetColorCodes(); System.Web.Security.FormsAuthentication.SetAuthCookie("--", true); // needed to use forms authentication UserView userView = UserView.GetInstance(); Site[] allowedSites = StaffSiteRestrictionDB.GetSitesNotRestricted(staff.StaffID, -1, false); // // until aged care is running, remove aged care from display // /* * System.Collections.ArrayList list = new System.Collections.ArrayList(); * for (int i = 0; i < allowedSites.Length; i++) * if (allowedSites[i].SiteType.ID == 1 || Utilities.IsDev()) * list.Add(allowedSites[i]); * allowedSites = (Site[])list.ToArray(typeof(Site)); */ Site[] allSites = SiteDB.GetAll(); if (allowedSites.Length == 0 && allSites.Length == 1) { Session["SiteID"] = allSites[0].SiteID; Session["SiteName"] = allSites[0].Name; Session["IsMultipleSites"] = false; Session["SiteIsClinic"] = allSites[0].SiteType.ID == 1; Session["SiteIsAgedCare"] = allSites[0].SiteType.ID == 2; Session["SiteIsGP"] = allSites[0].SiteType.ID == 3; Session["SiteTypeID"] = allSites[0].SiteType.ID; Session["SiteTypeDescr"] = allSites[0].SiteType.Descr; UserLoginDB.UpdateSite(staff.StaffID, -1, allSites[0].SiteID); if (!userView.IsAdminView) // need to choose org { if (Session["OrgID"] == null) // providers need to select an org, need to choose one { Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false); return; } } } if (allowedSites.Length == 1) { Session["SiteID"] = allowedSites[0].SiteID; Session["SiteName"] = allowedSites[0].Name; Session["IsMultipleSites"] = false; Session["SiteIsClinic"] = allowedSites[0].SiteType.ID == 1; Session["SiteIsAgedCare"] = allowedSites[0].SiteType.ID == 2; Session["SiteIsGP"] = allowedSites[0].SiteType.ID == 3; Session["SiteTypeID"] = allowedSites[0].SiteType.ID; Session["SiteTypeDescr"] = allowedSites[0].SiteType.Descr; UserLoginDB.UpdateSite(staff.StaffID, -1, allowedSites[0].SiteID); if (!userView.IsAdminView) // need to choose org { if (Session["OrgID"] == null) // providers need to select an org, need to choose one { Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false); return; } } } else // if more than one site, go to choose. if no sites this page will say to contact admin { if (Session["SiteID"] == null) // admins if yet to login to a site, need to choose one { Session["IsMultipleSites"] = true; Response.Redirect("~/Account/SelectSiteV2.aspx" + GetUrlCarryOverParams(), false); return; } } /* * * if (!staff.IsAdmin) * { * // provs only login to clinic site * Site site = SiteDB.GetByID(2); * Session["SiteID"] = site.SiteID; * Session["SiteName"] = site.Name; * * if (Session["OrgID"] == null) // providers et to login to select an org, need to choose one * { * if (Request.QueryString["from_url"] != null) * { * Response.Redirect("~/Account/SelectOrgV2.aspx?" + Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=")), false); * return; * } * else * { * Response.Redirect("~/Account/SelectOrgV2.aspx", false); * return; * } * } * } * else * { * if (Session["SiteID"] == null) // admins if yet to login to a site, need to choose one * { * if (Request.QueryString["from_url"] != null) * { * Response.Redirect("~/Account/SelectSiteV2.aspx?" + Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=")), false); * return; * } * else * { * Response.Redirect("~/Account/SelectSiteV2.aspx", false); * return; * } * } * } * */ 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; } } else if (validPatient) { UserLogin curLogin = UserLoginDB.GetCurLoggedIn(-1, patient.PatientID, HttpContext.Current.Session.SessionID, -1); if (curLogin != null) { UserLoginDB.UpdateLastAccessTime(curLogin.UserloginID, DateTime.Now, Request.RawUrl); UserLoginDB.UpdateSetOtherSessionsOfThisUserLoggedOut(curLogin.UserloginID, -1, patient.PatientID); } else { UserLoginDB.UpdateSetAllSessionsLoggedOut(-1, patient.PatientID); UserLoginDB.Insert(-1, (patient == null) ? -1 : patient.PatientID, login, -1, validPatient, HttpContext.Current.Session.SessionID, Request.UserHostAddress); } this.FailureText.Text = ""; Session["IsLoggedIn"] = true; Session["IsStakeholder"] = false; Session["IsMasterAdmin"] = false; Session["IsAdmin"] = false; Session["IsPrincipal"] = false; Session["IsProvider"] = false; Session["IsExternal"] = false; Session["PatientID"] = patient.PatientID; Session["StaffFullnameWithoutMiddlename"] = patient.Person.FullnameWithoutMiddlename; Session["StaffFirstname"] = patient.Person.Firstname; Session["NumDaysToDisplayOnBookingScreen"] = 3; Session["ShowOtherProvidersOnBookingScreen"] = false; Session["ShowHeaderOnBookingScreen"] = true; Session["SystemVariables"] = SystemVariableDB.GetAll(); Session["OfferingColors"] = OfferingDB.GetColorCodes(); System.Web.Security.FormsAuthentication.SetAuthCookie("--", true); // needed to use forms authentication Site[] allSites = SiteDB.GetAll(); Site[] allowedSites = SiteDB.GetAll(); // // remove aged care from display // System.Collections.ArrayList list = new System.Collections.ArrayList(); for (int i = 0; i < allSites.Length; i++) { if (allSites[i].SiteType.ID == 1) { list.Add(allSites[i]); } } allowedSites = (Site[])list.ToArray(typeof(Site)); if (allowedSites.Length == 0 && allSites.Length == 1) { Session["SiteID"] = allSites[0].SiteID; Session["SiteName"] = allSites[0].Name; Session["SiteIsClinic"] = allSites[0].SiteType.ID == 1; Session["SiteIsAgedCare"] = allSites[0].SiteType.ID == 2; Session["SiteIsGP"] = allSites[0].SiteType.ID == 3; Session["SiteTypeID"] = allSites[0].SiteType.ID; Session["SiteTypeDescr"] = allSites[0].SiteType.Descr; UserLoginDB.UpdateSite(-1, patient.PatientID, allSites[0].SiteID); if (Session["OrgID"] == null) // providers, ext staff, patient logins need to select an org, need to choose one { if (Request.QueryString["from_url"] != null) { string from_url = Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)); if (from_url.Contains("BookingsV2.aspx?") && from_url.Contains("orgs=")) { Uri theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + from_url); string orgs = HttpUtility.ParseQueryString(theRealURL.Query).Get("orgs"); if (Regex.IsMatch(orgs, @"^\d+$")) { Organisation org = OrganisationDB.GetByID(Convert.ToInt32(orgs)); if (org != null) { Session["OrgID"] = org.OrganisationID.ToString(); Session["OrgName"] = org.Name; Response.Redirect(from_url, false); return; } } } } Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false); return; } } if (allowedSites.Length == 1) { Session["SiteID"] = allowedSites[0].SiteID; Session["SiteName"] = allowedSites[0].Name; Session["SiteIsClinic"] = allowedSites[0].SiteType.ID == 1; Session["SiteIsAgedCare"] = allowedSites[0].SiteType.ID == 2; Session["SiteIsGP"] = allowedSites[0].SiteType.ID == 3; Session["SiteTypeID"] = allowedSites[0].SiteType.ID; Session["SiteTypeDescr"] = allowedSites[0].SiteType.Descr; UserLoginDB.UpdateSite(-1, patient.PatientID, allowedSites[0].SiteID); if (Session["OrgID"] == null) // providers need to select an org, need to choose one { if (Request.QueryString["from_url"] != null) { string from_url = Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)); if (from_url.Contains("BookingsV2.aspx?") && from_url.Contains("orgs=")) { Uri theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + from_url); string orgs = HttpUtility.ParseQueryString(theRealURL.Query).Get("orgs"); if (Regex.IsMatch(orgs, @"^\d+$")) { Organisation org = OrganisationDB.GetByID(Convert.ToInt32(orgs)); if (org != null) { Session["OrgID"] = org.OrganisationID.ToString(); Session["OrgName"] = org.Name; Response.Redirect(from_url, false); return; } } } } Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false); return; } } else // if more than one site, go to choose. if no sites this page will say to contact admin { if (Session["SiteID"] == null) // admins if yet to login to a site, need to choose one { Response.Redirect("~/Account/SelectSiteV2.aspx" + GetUrlCarryOverParams(), false); return; } } 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; } } else { //UserLoginDB.Insert((staff == null) ? -1 : staff.StaffID, login, -1, validStaff, HttpContext.Current.Session.SessionID, Request.UserHostAddress); this.FailureText.Text = "Login Failed."; } } catch (Exception ex) { Logger.LogException(ex); if (Utilities.IsDev()) { FailureText.Text = ex.ToString(); } else { throw; } } }
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 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))); }
public void CreateXML(Invoice[] invoices, bool validate = true) { if (validate) { Invoice[] tooOldList = GetInvoicesTooOldToClaim(invoices); if (tooOldList.Length > 0) { string invalids = string.Empty; foreach (Invoice i in tooOldList) { invalids += (invalids.Length == 0 ? "" : ",") + i.InvoiceID.ToString(); } throw new Exception("The following invoices are too old to claim: " + "<br />" + invalids); } } // get bulk invoice lines for less db calls in individual invoice create xml method [invoiceID => list of invoicelines] Hashtable bulkInvoiceLineHash = InvoiceLineDB.GetBulkInvoiceLinesByInvoiceID(invoices); ArrayList allInvoiceLines = new ArrayList(); foreach (DictionaryEntry pair in bulkInvoiceLineHash) { allInvoiceLines.AddRange((InvoiceLine[])pair.Value); } // get bluk health cards [patientID=>healthcard] // // NB: // A DVA invoice can only use a DVA card // A Medicare invoice can only use a Medicare card // The system can only create a DVA invoice is if DVA is set as the active card (vice versa for Medicare) // So when a DVA invoice is created the DVA card was active, and then someone switches it to be the Medicare card thatis active. // So, it's correct to get only the DVA cards for DVA invoices (and Medicare cards for Medicare invoices), and also would be correct to ignore the active flag and just get the most recent. int[] allPatientIDs = GetAllPatientIDs((InvoiceLine[])allInvoiceLines.ToArray(typeof(InvoiceLine))); Hashtable bulkHealthCardHash = PatientsHealthCardsCacheDB.GetBullkMostRecent(allPatientIDs, claimType == ClaimType.Medicare ? -1 : -2); // get bluk staff provider numbers from registerstaff table int[] allProviderStaffIDs = GetAllProviderStaffIDs(invoices); Hashtable bulkRegisterStaffHash = RegisterStaffDB.Get2DHashByStaffIDOrgID(allProviderStaffIDs); Hashtable bulkStaffHash = StaffDB.GetAllInHashtable(false, true, false, false); // get bluk healthcard actions to get EPC signed dates Hashtable bulkHealthCardActionsHash = HealthCardActionDB.GetReceivedActionsByPatientIDs(allPatientIDs); // get bluk epcreferrers Hashtable bulkEPCReferrersHash = PatientReferrerDB.GetEPCReferrersOf(allPatientIDs, false); // get all sites in one call Hashtable bulkSites = SiteDB.GetAllInHashtable(); Hashtable claimNumberInvoiceGroups = new Hashtable(); for (int i = 0; i < invoices.Length; i++) { if (claimNumberInvoiceGroups[(invoices[i]).HealthcareClaimNumber] == null) { claimNumberInvoiceGroups[(invoices[i]).HealthcareClaimNumber] = new ArrayList(); } ((ArrayList)claimNumberInvoiceGroups[(invoices[i]).HealthcareClaimNumber]).Add(invoices[i]); } string noPatientFailures = string.Empty; string noHealthcardFailures = string.Empty; foreach (string claimNbr in claimNumberInvoiceGroups.Keys) { Invoice[] invoiceList = (Invoice[])((ArrayList)claimNumberInvoiceGroups[claimNbr]).ToArray(typeof(Invoice)); try { CreateXML(invoiceList, bulkInvoiceLineHash, bulkHealthCardHash, bulkRegisterStaffHash, bulkStaffHash, bulkSites, bulkHealthCardActionsHash, bulkEPCReferrersHash); } catch (HINXNoPatientOnInvoiceLineException ex) { noPatientFailures += (noPatientFailures.Length == 0 ? "" : "<br />") + ex.Message; } catch (HINXNoHealthcardException ex) { noHealthcardFailures += (noHealthcardFailures.Length == 0 ? "" : "<br />") + ex.Message; } } string errors = string.Empty; if (noPatientFailures.Length > 0) { errors += (errors.Length == 0 ? "" : "<br /><br />") + "The following invoices have invoices lines with no patient set (Fix this and re-generate): <br />" + noPatientFailures; } if (noHealthcardFailures.Length > 0) { errors += (errors.Length == 0 ? "" : "<br /><br />") + "The following invoices have patients with no " + (claimType == ClaimType.Medicare ? "Medicare" : "DVA") + " card set (Fix this and re-generate): <br />" + noHealthcardFailures; } if (errors.Length > 0) { throw new HINXUnsuccessfulItemsException(errors); } }
public void FillCurrentFilesList() { bool allowDeletions = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["Letters_AllowDeletions"]); Organisation org = IsValidFormOrgID() ? OrganisationDB.GetByID(GetFormOrgID()) : null; string dir = Letter.GetLettersDirectory(); if (!IsValidFormOrgID()) { spn_manage_files.Visible = false; } else { spn_manage_files.Visible = true; if (org != null) // specific dir for that org { dir += org.OrganisationID + @"\"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (!Directory.Exists(dir)) { throw new CustomMessageException("Letters directory doesn't exist"); // so they are currenty using default letters } } else // get default letters for the site { dir += @"Default\" + Session["SiteID"] + @"\"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (!Directory.Exists(dir)) { throw new CustomMessageException("Letters directory doesn't exist"); } } DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("filename"), new DataColumn("filepath"), new DataColumn("text") }); string text = allowDeletions ? "x" : ""; // no deletions means link has no text foreach (FileInfo file in (new DirectoryInfo(dir)).GetFiles("*.*", SearchOption.TopDirectoryOnly)) { dt.Rows.Add(file.Name, file.FullName, text); } lstCurrentFiles.DataSource = dt; lstCurrentFiles.DataBind(); } DirectoryInfo d = new DirectoryInfo(dir); lblFileNameInvoice.Text = "InvoiceTemplate.docx"; lnkFileNameInvoice.CommandArgument = d.Parent.Parent.FullName + (d.Parent.Parent.FullName.EndsWith(@"\") ? "" : @"\") + "InvoiceTemplate.docx"; lblFileNamePrivateInvoice.Text = "PrivateInvoiceTemplate.docx"; lnkFileNamePrivateInvoice.CommandArgument = d.Parent.Parent.FullName + (d.Parent.Parent.FullName.EndsWith(@"\") ? "" : @"\") + "PrivateInvoiceTemplate.docx"; lblFileNameInvoiceAC.Text = "InvoiceTemplateAC.docx"; lnkFileNameInvoiceAC.CommandArgument = d.Parent.Parent.FullName + (d.Parent.Parent.FullName.EndsWith(@"\") ? "" : @"\") + "InvoiceTemplateAC.docx"; lblFileNameInvoiceOutstanding.Text = "OverdueInvoiceTemplate.docx"; lnkFileNameInvoiceOutstanding.CommandArgument = d.Parent.Parent.FullName + (d.Parent.Parent.FullName.EndsWith(@"\") ? "" : @"\") + "OverdueInvoiceTemplate.docx"; lblFileNameInvoiceOutstandingAC.Text = "OverdueInvoiceTemplateAC.docx"; lnkFileNameInvoiceOutstandingAC.CommandArgument = d.Parent.Parent.FullName + (d.Parent.Parent.FullName.EndsWith(@"\") ? "" : @"\") + "OverdueInvoiceTemplateAC.docx"; lblTreatmentList.Text = "TreatmentList.docx"; lnkTreatmentList.CommandArgument = d.Parent.Parent.FullName + (d.Parent.Parent.FullName.EndsWith(@"\") ? "" : @"\") + "TreatmentList.docx"; lblACTreatmentList.Text = "ACTreatmentList.docx"; lnkACTreatmentList.CommandArgument = d.Parent.Parent.FullName + (d.Parent.Parent.FullName.EndsWith(@"\") ? "" : @"\") + "ACTreatmentList.docx"; lblBlankTemplate.Text = "BlankTemplate.docx"; lnkBlankTemplate.CommandArgument = d.Parent.Parent.FullName + (d.Parent.Parent.FullName.EndsWith(@"\") ? "" : @"\") + "BlankTemplate.docx"; lblBlankTemplateAC.Text = "BlankTemplateAC.docx"; lnkBlankTemplateAC.CommandArgument = d.Parent.Parent.FullName + (d.Parent.Parent.FullName.EndsWith(@"\") ? "" : @"\") + "BlankTemplateAC.docx"; lnkFileNameInvoiceOutstanding.OnClientClick = File.Exists(lnkFileNameInvoiceOutstanding.CommandArgument) ? "return true;" : "javascript:alert('File OverdueInvoiceTemplate.docx Does Not Exist.');return false;"; lnkFileNameInvoiceOutstandingAC.OnClientClick = File.Exists(lnkFileNameInvoiceOutstandingAC.CommandArgument) ? "return true;" : "javascript:alert('File OverdueInvoiceTemplateAC.docx Does Not Exist.');return false;"; lnkTreatmentList.OnClientClick = File.Exists(lnkTreatmentList.CommandArgument) ? "return true;" : "javascript:alert('File TreatmentList.docx Does Not Exist.');return false;"; lnkACTreatmentList.OnClientClick = File.Exists(lnkACTreatmentList.CommandArgument) ? "return true;" : "javascript:alert('File ACTreatmentList.docx Does Not Exist.');return false;"; lnkBlankTemplate.OnClientClick = File.Exists(lnkBlankTemplate.CommandArgument) ? "return true;" : "javascript:alert('File BlankTemplate.docx Does Not Exist.');return false;"; lnkBlankTemplateAC.OnClientClick = File.Exists(lnkBlankTemplateAC.CommandArgument) ? "return true;" : "javascript:alert('File BlankTemplateAC.docx Does Not Exist.');return false;"; bool hasClinic = false; bool hasAC = false; bool hasGP = false; foreach (Site site in SiteDB.GetAll()) { if (site.SiteType.ID == 1) { hasClinic = true; } if (site.SiteType.ID == 2) { hasAC = true; } if (site.SiteType.ID == 3) { hasGP = true; } } if (!hasClinic && !hasGP) { rowInvoice.Visible = false; rowInvoicePrivate.Visible = false; rowInvoiceOutstanding.Visible = false; } if (!hasAC) { rowInvoiceAC.Visible = false; rowInvoiceOutstandingAC.Visible = false; rowBlankTemplateAC.Visible = false; rowACTreatmentList.Visible = false; } }
private bool SaveInvoiceFiles(string dir, bool allowOverwrite) { string allowedFileTypes = "docx|doc|dot"; // "docx|doc|dot|txt"; System.Text.StringBuilder _messageToUser = new System.Text.StringBuilder("Files Uploaded:<br>"); bool hasClinic = false; bool hasAC = false; bool hasGP = false; foreach (Site site in SiteDB.GetAll()) { if (site.SiteType.ID == 1) { hasClinic = true; } if (site.SiteType.ID == 2) { hasAC = true; } if (site.SiteType.ID == 3) { hasGP = true; } } try { HttpFileCollection _files = Request.Files; if (_files.Count == 0 || (_files.Count == 1 && System.IO.Path.GetFileName(_files[0].FileName) == string.Empty)) { lblUploadInvoiceMessage.Text = " <font color=\"red\">No Files Selected</font> <BR>"; return(true); } for (int i = 0; i < _files.Count; i++) { HttpPostedFile _postedFile = _files[i]; string _fileName = System.IO.Path.GetFileName(_postedFile.FileName); if (_fileName.Length == 0) { continue; } if (_postedFile.ContentLength > 8000000) { throw new Exception(_fileName + " <font color=\"red\">Failed!! Over allowable file size limit!</font> <BR>"); } if (!hasClinic && !hasGP) { if (_fileName != "InvoiceTemplate.docx" && _fileName != "PrivateInvoiceTemplate.docx" && _fileName != "OverdueInvoiceTemplate.docx" && _fileName != "InvoiceTemplateAC.docx" && _fileName != "OverdueInvoiceTemplateAC.docx" && _fileName != "TreatmentList.docx" && _fileName != "ACTreatmentList.docx" && _fileName != "BlankTemplate.docx" && _fileName != "BlankTemplateAC.docx") { throw new Exception(_fileName + " <font color=\"red\">Failed. Only file allowed are 'InvoiceTemplateAC.docx', 'OverdueInvoiceTemplateAC.docx', 'TreatmentList.docx', 'ACTreatmentList.docx', and 'BlankTemplateAC.docx'</font> <BR>"); } } else if (!hasAC) { if (_fileName != "InvoiceTemplate.docx" && _fileName != "PrivateInvoiceTemplate.docx" && _fileName != "OverdueInvoiceTemplate.docx" && _fileName != "InvoiceTemplateAC.docx" && _fileName != "OverdueInvoiceTemplateAC.docx" && _fileName != "TreatmentList.docx" && _fileName != "ACTreatmentList.docx" && _fileName != "BlankTemplate.docx" && _fileName != "BlankTemplateAC.docx") { throw new Exception(_fileName + " <font color=\"red\">Failed. Only files allowed are 'InvoiceTemplate.docx', 'PrivateInvoiceTemplate.docx', 'OverdueInvoiceTemplate.docx', 'TreatmentList.docx', and 'BlankTemplate.docx'</font> <BR>"); } } else { if (_fileName != "InvoiceTemplate.docx" && _fileName != "PrivateInvoiceTemplate.docx" && _fileName != "OverdueInvoiceTemplate.docx" && _fileName != "InvoiceTemplateAC.docx" && _fileName != "OverdueInvoiceTemplateAC.docx" && _fileName != "TreatmentList.docx" && _fileName != "ACTreatmentList.docx" && _fileName != "BlankTemplate.docx" && _fileName != "BlankTemplateAC.docx") { throw new Exception(_fileName + " <font color=\"red\">Failed. Only files allowed are 'InvoiceTemplate.docx', 'PrivateInvoiceTemplate.docx', 'OverdueInvoiceTemplate.docx', 'InvoiceTemplateAC.docx', 'OverdueInvoiceTemplateAC.docx', 'ACTreatmentList.docx', 'BlankTemplate.docx', and 'BlankTemplateAC.docx'</font> <BR>"); } } if (!ExtIn(System.IO.Path.GetExtension(_fileName), allowedFileTypes)) { throw new Exception(_fileName + " <font color=\"red\">Failed!! Only " + ExtToDisplay(allowedFileTypes) + " files allowed!</font> <BR>"); } if (!allowOverwrite && File.Exists(dir + "\\" + _fileName)) { throw new Exception(_fileName + " <font color=\"red\">Failed!! File already exists. To allow overwrite, check the \"Allowed File Overwrite\" box</font> <BR>"); } } int countZeroFileLength = 0; for (int i = 0; i < _files.Count; i++) { HttpPostedFile _postedFile = _files[i]; string _fileName = System.IO.Path.GetFileName(_postedFile.FileName); if (_fileName.Length == 0) { continue; } if (_postedFile.ContentLength > 0) { //_postedFile.SaveAs(Server.MapPath("MyFiles") + "\\" + System.IO.Path.GetFileName(_postedFile.FileName)); _postedFile.SaveAs(dir + "\\" + _fileName); _messageToUser.Append(_fileName + "<BR>"); } else { countZeroFileLength++; } } if (_files.Count > 0 && countZeroFileLength == _files.Count) { throw new Exception("<font color=\"red\">File" + (_files.Count > 1 ? "s are" : " is") + " 0 kb.</font>"); } else if (_files.Count > 0 && countZeroFileLength > 0) { throw new Exception("<font color=\"red\">File(s) of 0 kb were not uploaded.</font>"); } lblUploadInvoiceMessage.Text = _messageToUser.ToString(); return(true); } catch (System.Exception ex) { lblUploadInvoiceMessage.Text = ex.Message; return(false); } finally { FillCurrentFilesList(); FillGrid(); Page.ClientScript.RegisterStartupScript(this.GetType(), "download", @"<script language=javascript>addLoadEvent(function () { window.location.hash = ""invoice_templates_tag""; });</script>"); } }
protected void GrdLetter_RowDataBound(object sender, GridViewRowEventArgs e) { DataTable letterTypes = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "LetterType", "", "descr", "letter_type_id", "descr"); DataTable sites = SiteDB.GetDataTable(); DataTable dt = Session["letter_data"] as DataTable; bool tblEmpty = (dt.Rows.Count == 1 && dt.Rows[0][0] == DBNull.Value); if (!tblEmpty && e.Row.RowType == DataControlRowType.DataRow) { bool hasData = dt.Rows[0][0].ToString() != string.Empty; Label lblId = (Label)e.Row.FindControl("lblId"); DataRow[] foundRows = dt.Select("letter_letter_id=" + lblId.Text); DataRow thisRow = foundRows[0]; Letter letter = LetterDB.LoadAll(thisRow); DropDownList ddlLetterType = (DropDownList)e.Row.FindControl("ddlLetterType"); if (ddlLetterType != null) { ddlLetterType.DataSource = letterTypes; ddlLetterType.DataTextField = "descr"; ddlLetterType.DataValueField = "letter_type_id"; ddlLetterType.DataBind(); ddlLetterType.SelectedValue = thisRow["letter_letter_type_id"].ToString(); } DropDownList ddlSite = (DropDownList)e.Row.FindControl("ddlSite"); if (ddlSite != null) { ddlSite.DataSource = sites; ddlSite.DataTextField = "name"; ddlSite.DataValueField = "site_id"; ddlSite.DataBind(); ddlSite.SelectedValue = thisRow["letter_site_id"].ToString(); } Label lblFileExists = (Label)e.Row.FindControl("lblFileExists"); if (lblFileExists != null) { lblFileExists.Style.Remove("border-bottom"); lblFileExists.Font.Bold = false; if (letter.FileExists(Convert.ToInt32(Session["SiteID"]))) { lblFileExists.Text = "Yes"; } else { if (letter.LetterType.ID == 234 || letter.LetterType.ID == 235) // medicare/dva rejection codes { if (letter.Docname.Length == 0) { lblFileExists.Text = string.Empty; } if (letter.Docname.Length > 0) { lblFileExists.Text = "<span style=\"border-bottom:thin dotted black;\" title=\"This won't be in the list of available reject codes.\r\nTo have it in the available list of reject codes, either change the docname to be blank or change the docname to one that exists in the below list.\">No</span>"; lblFileExists.Font.Bold = true; } } else { lblFileExists.Text = "No"; if (letter.Docname.Length > 0) { lblFileExists.Text = "<span style=\"border-bottom:thin dotted black;\" title=\"This won't be in the list of available letters.\r\nTo have it in the available list of letters, change the docname to one that exists in the below list.\">No</span>"; lblFileExists.Font.Bold = true; } } } } Utilities.AddConfirmationBox(e); if ((e.Row.RowState & DataControlRowState.Edit) > 0) { Utilities.SetEditRowBackColour(e, System.Drawing.Color.LightGoldenrodYellow); } } if (e.Row.RowType == DataControlRowType.Footer) { DropDownList ddlLetterType = (DropDownList)e.Row.FindControl("ddlNewLetterType"); ddlLetterType.DataSource = letterTypes; ddlLetterType.DataTextField = "descr"; ddlLetterType.DataValueField = "letter_type_id"; ddlLetterType.DataBind(); DropDownList ddlSite = (DropDownList)e.Row.FindControl("ddlNewSite"); ddlSite.DataSource = sites; ddlSite.DataTextField = "name"; ddlSite.DataValueField = "site_id"; ddlSite.DataBind(); } }
public static string Run(bool incDisplay, bool incSending, DateTime date) { if (incSending) { RunBirthdaysWithoutSMSorEmail(); } date = date.Date; bool EnableBirthdaySMS = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableBirthdaySMS").Value) == 1; bool EnableBirthdayEmails = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableBirthdayEmails").Value) == 1; Site[] sites = SiteDB.GetAll(); Patient[] patients = PatientDB.GetBirthdays(date); Hashtable patientContactPhoneNbrHash = GetPatientPhoneNbrCache(patients); Hashtable patientContactEmailHash = GetPatientEmailCache(patients); Hashtable patientRegOrgHash = GetPatientRegOrgCache(patients); // get a hash of patient reg to org decimal balance = SMSCreditDataDB.GetTotal() - SMSHistoryDataDB.GetTotal(); decimal cost = Convert.ToDecimal(SystemVariableDB.GetByDescr("SMSPrice").Value); string callerId = System.Configuration.ConfigurationManager.AppSettings["SMSTech_callerId"]; // not here used as the callerId will be the org name string countryCode = System.Configuration.ConfigurationManager.AppSettings["SMSTech_CountryCode"]; ArrayList messagesToSMS = new ArrayList(); ArrayList messagesToEmail = new ArrayList(); string output = "<table class=\"table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center\" border=\"1\" style=\"border-collapse:collapse;\">"; int countWithPatient = 0; foreach (Patient patient in patients) { // get all info to send via sms or email Site site = null; foreach (Site curSite in sites) { if ((patient.IsClinicPatient && curSite.SiteType.ID == 1) || (!patient.IsClinicPatient && curSite.SiteType.ID == 2)) { site = curSite; } } ArrayList orgs = patientRegOrgHash[patient.PatientID] as ArrayList; string orgText = (orgs == null || orgs.Count == 0 || orgs.Count > 1) ? site.Name : ((Organisation)orgs[0]).Name; string phoneNumPatient = GetPhoneNbr(patientContactPhoneNbrHash, patient.Person.EntityID, true); if (phoneNumPatient != null) { phoneNumPatient = phoneNumPatient.StartsWith("0") ? countryCode + phoneNumPatient.Substring(1) : phoneNumPatient; } string emailPatient = GetEmail(patientContactEmailHash, patient.Person.EntityID); string smsText = GetSMSText(patient, site, patientRegOrgHash[patient.PatientID] as ArrayList); string emailText = GetEmailText(patient, site, patientRegOrgHash[patient.PatientID] as ArrayList); string emailSubjectText = GetEmailSubjectText(patient, site, patientRegOrgHash[patient.PatientID] as ArrayList); // display the info string tdTagStart = phoneNumPatient == null && emailPatient == null ? "<td class=\"nowrap\" style=\"color:grey;\">" : (phoneNumPatient == null ? "<td>" : "<td><b>"); string tdTagStartLeftAlign = phoneNumPatient == null && emailPatient == null ? "<td class=\"nowrap text_left\" style=\"color:grey;\">" : (phoneNumPatient == null ? "<td class=\"text_left\">" : "<td class=\"text_left\"><b>"); string tdTagEnd = phoneNumPatient == null && emailPatient == null ? "</td>" : (phoneNumPatient == null ? "</td>" : "</b></td>"); output += "<tr>"; output += tdTagStart + patient.PatientID + tdTagEnd; output += tdTagStart + patient.Person.Dob.ToString("dd-MM-yyyy") + tdTagEnd; output += tdTagStart + patient.Person.FullnameWithoutMiddlename + "<br />" + (phoneNumPatient == null ? "-- No Mobile --" : "<u>" + phoneNumPatient + "</u>") + "<br />" + (emailPatient == null ? "-- No Email --" : "<u>" + emailPatient + "</u>") + tdTagEnd; output += tdTagStartLeftAlign + (phoneNumPatient == null && emailPatient == null ? "" : "<u>" + emailSubjectText + "</u><br /><br />" + emailText) + tdTagEnd; output += "</tr>"; countWithPatient++; // add to lists to sms or email (or both) if (EnableBirthdaySMS && phoneNumPatient != null && balance >= cost) { messagesToSMS.Add(new Tuple <int, decimal, string, string, string>(patient.PatientID, cost, phoneNumPatient, smsText, orgText)); if (incSending) { balance -= cost; } } if (EnableBirthdayEmails && emailPatient != null) { messagesToEmail.Add(new Tuple <int, string, string, string, string>(patient.PatientID, orgText, emailPatient, emailText, emailSubjectText)); } } output += "</table>"; // run the sending and send off reminders -- but only if there was any bookings if (incSending && patients.Length > 0) { /* * run the sendings */ SendSMSes((Tuple <int, decimal, string, string, string>[])messagesToSMS.ToArray(typeof(Tuple <int, decimal, string, string, string>))); SendEmails((Tuple <int, string, string, string, string>[])messagesToEmail.ToArray(typeof(Tuple <int, string, string, string, string>))); /* * send balance warning */ SystemVariables systemVariables = SystemVariableDB.GetAll(); string warningEmail = systemVariables["SMSCreditNotificationEmailAddress"].Value; decimal warningThreshold = Convert.ToDecimal(systemVariables["SMSCreditLowBalance_Threshold"].Value); bool checkSMSCreditOutOfBalance = Convert.ToInt32(systemVariables["SMSCreditOutOfBalance_SendEmail"].Value) == 1; bool checkMSCreditLowBalance = Convert.ToInt32(systemVariables["SMSCreditLowBalance_SendEmail"].Value) == 1; if (warningEmail.Length > 0 && checkSMSCreditOutOfBalance && balance < cost) { SendEmail( warningEmail, "SMS Credit Used Up", "Please note that your SMS credit at mediclinic has been used up. To continue sending, please top up.<br /><br />Best regards,<br />Mediclinic"); } else if (warningEmail.Length > 0 && checkMSCreditLowBalance && balance <= warningThreshold) // dont send warning low balance if already sending out of credit email { SendEmail( warningEmail, "SMS Credit Warning - Don't Forget To Top-Up Before It Runs Out", "Hi! Just a friendly reminder that the SMS reminder threshold you set has been reached.<br /> To avoid missing SMS'es being sent, don't forget to top-up before the remainder runs out!<br /><br />Best regards,<br />Mediclinic"); } } if (incDisplay) { return("Count: <b>" + countWithPatient + "</b> [with mobile: <b>" + messagesToSMS.Count + "</b>] [with email: <b>" + messagesToEmail.Count + "</b>] " + "<br /><br />" + output); } else { return(string.Empty); } }
protected void btnSubmit_Click(object sender, EventArgs e) { if (SiteDB.GetSiteByType(SiteDB.SiteType.AgedCare) != null) { HideTableAndSetErrorMessage("Aged Care Site Already Exists"); return; } string errMsg = string.Empty; txtACSiteName.Text = Utilities.FormatName(txtACSiteName.Text.Trim()); if (txtACSiteName.Text == string.Empty) { errMsg += (errMsg.Length == 0 ? "" : "<br />") + "Site Name is required"; } if (errMsg.Length > 0) { SetErrorMessage(errMsg); return; } try { string sql = @" Declare @entity_id int INSERT INTO Entity DEFAULT VALUES; SET @entity_id = SCOPE_IDENTITY() SET IDENTITY_INSERT Site ON INSERT INTO Site ( site_id, entity_id, name, abn, acn, tfn, asic, is_provider, bank_bpay, bank_bsb, bank_account, bank_direct_debit_userid, bank_username, oustanding_balance_warning, print_epc, excl_sun, excl_mon, excl_tue, excl_wed, excl_thu, excl_fri, excl_sat, day_start_time, lunch_start_time, lunch_end_time, day_end_time, fiscal_yr_end, num_booking_months_to_get, site_type_id ) VALUES ( 2, @entity_id, '" + txtACSiteName.Text + @"', '', '', '', '', 0, '', '', '', '', '', 0.00, 1, 0, 0, 0, 0, 0, 0, 0, '08:00:00.0000000', '00:00:00.0000000', '00:00:00.0000000', '22:00:00.0000000', '2014-06-30 00:00:00.000', 54, 2 ) SET IDENTITY_INSERT Site OFF "; DBBase.ExecuteNonResult(sql); HideTableAndSetErrorMessage("Site Added!<br /><br /><font color=\"blue\"><center><table style=\"text-align:left;max-width:520px;\"><tr><td><ol><li>Logout and then log back in so the 'change site' link is showing</li><li>Go into the new AC site</li><li>Go to menu <b><u>Letters</u></b> ⇨ <b><u>Treatment Letters</u></b></li><li>Add a row for each profession until the row where you add is no longer showing (indicating there exists a row for all professions already)<br /><br /></li><li>You may also need to add <u>AC invoice</u> and <u>AC Overdue Invoice</u> templates in the letters page</li></ol></td></tr></table></center></font>"); SetupGUI(); } catch (CustomMessageException ex) { SetErrorMessage(ex.Message); } catch (Exception ex) { SetErrorMessage("", ex.ToString()); } }
private void FillEditViewForm(Site site, bool isEditMode) { Page.Title = ((SystemVariables)Session["SystemVariables"])["Site"].Value + " - " + site.Name; if (!Utilities.IsDev()) { idRow.Attributes["class"] = "hiddencol"; } string screen_id = "2"; string allFeatures = "dialogWidth:980px;dialogHeight:530px;center:yes;resizable:no; scroll:no"; string js = "javascript:window.showModalDialog('" + "NoteListV2.aspx?id=" + site.EntityID.ToString() + "&screen=" + screen_id + "', '', '" + allFeatures + "');document.getElementById('btnUpdateNotesIcon').click();return false;"; // lnkNotes.Attributes.Add("onclick", js); // lnkNotes.ImageUrl = NoteDB.HasNotes(site.EntityID) ? "~/images/notes-48.png" : "~/images/notes-bw-48.jpg"; lblId.Text = site.SiteID.ToString(); chkIncSunday.Checked = !site.ExclSun; chkIncMonday.Checked = !site.ExclMon; chkIncTuesday.Checked = !site.ExclTue; chkIncWednesday.Checked = !site.ExclWed; chkIncThursday.Checked = !site.ExclThu; chkIncFriday.Checked = !site.ExclFri; chkIncSaturday.Checked = !site.ExclSat; ddlDayStart_Hour.SelectedValue = site.DayStartTime.Hours.ToString(); ddlDayStart_Minute.SelectedValue = site.DayStartTime.Minutes.ToString(); ddlDayEnd_Hour.SelectedValue = site.DayEndTime.Hours.ToString(); ddlDayEnd_Minute.SelectedValue = site.DayEndTime.Minutes.ToString(); ddlLunchStart_Hour.SelectedValue = site.LunchStartTime.Hours.ToString(); ddlLunchStart_Minute.SelectedValue = site.LunchStartTime.Minutes.ToString(); ddlLunchEnd_Hour.SelectedValue = site.LunchEndTime.Hours.ToString(); ddlLunchEnd_Minute.SelectedValue = site.LunchEndTime.Minutes.ToString(); lblPrintEPCText.Text = site.SiteType.ID == 1 ? "Print EPC" : "Print Referral"; if (isEditMode) { DataTable dt = SiteDB.GetDataTable(); bool showClinicAddOption = true; bool showAgedCareAddOption = true; bool showGPAddOption = true; for (int i = 0; i < dt.Rows.Count; i++) { if (Convert.ToInt32(dt.Rows[i]["site_type_id"]) == 1) { showClinicAddOption = false; } if (Convert.ToInt32(dt.Rows[i]["site_type_id"]) == 2) { showAgedCareAddOption = false; } if (Convert.ToInt32(dt.Rows[i]["site_type_id"]) == 3) { showGPAddOption = false; } } if (site.SiteType.ID == 1) { showClinicAddOption = true; } if (site.SiteType.ID == 2) { showAgedCareAddOption = true; } if (site.SiteType.ID == 3) { showGPAddOption = true; } ddlClinic.Items.Clear(); if (showClinicAddOption) { ddlClinic.Items.Add(new ListItem("Clinic", "1")); } if (showAgedCareAddOption) { ddlClinic.Items.Add(new ListItem("Aged Care", "2")); } if (showGPAddOption) { ddlClinic.Items.Add(new ListItem("GP", "3")); } txtName.Text = site.Name; ddlClinic.SelectedValue = site.SiteType.ID.ToString(); txtABN.Text = site.Abn; txtACN.Text = site.Acn; txtTFN.Text = site.Tfn; txtASIC.Text = site.Asic; chkIsProvider.Checked = site.IsProvider; txtBPay.Text = site.BankBpay; txtBSB.Text = site.BankBsb; txtBankAccount.Text = site.BankAccount; txtBankDirectDebitUserID.Text = site.BankDirectDebitUserID; txtBankUsername.Text = site.BankUsername; txtOustandingBalanceWarning.Text = site.OustandingBalanceWarning.ToString(); chkIsPrintEPC.Checked = site.PrintEpc; ddlNumBookingMonthsToGet.SelectedValue = site.NumBookingMonthsToGet > 36 ? "36" : site.NumBookingMonthsToGet.ToString(); ddlFiscalYrEnd_Day.SelectedValue = site.FiscalYrEnd.Day.ToString(); ddlFiscalYrEnd_Month.SelectedValue = site.FiscalYrEnd.Month.ToString(); ddlFiscalYrEnd_Year.SelectedValue = site.FiscalYrEnd.Year.ToString(); lblName.Visible = false; lblClinic.Visible = false; lblABN.Visible = false; lblACN.Visible = false; lblTFN.Visible = false; lblASIC.Visible = false; lblIsProvider.Visible = false; lblBPay.Visible = false; lblBSB.Visible = false; lblBankAccount.Visible = false; lblBankDirectDebitUserID.Visible = false; lblBankUsername.Visible = false; lblOustandingBalanceWarning.Visible = false; lblIsPrintEPC.Visible = false; lblNumBookingMonthsToGet.Visible = false; lblFiscalYrEnd.Visible = false; } else { lblName.Text = site.Name; lblClinic.Text = site.SiteType.Descr; lblABN.Text = site.Abn.Length == 0 ? "--" : site.Abn; lblACN.Text = site.Acn.Length == 0 ? "--" : site.Acn; lblTFN.Text = site.Tfn.Length == 0 ? "--" : site.Tfn; lblASIC.Text = site.Asic.Length == 0 ? "--" : site.Asic; lblIsProvider.Text = site.IsProvider ? "Yes" : "No"; lblBPay.Text = site.BankBpay.Length == 0 ? "--" : site.BankBpay; lblBSB.Text = site.BankBsb.Length == 0 ? "--" : site.BankBsb; lblBankAccount.Text = site.BankAccount.Length == 0 ? "--" : site.BankAccount; lblBankDirectDebitUserID.Text = site.BankDirectDebitUserID.Length == 0 ? "--" : site.BankDirectDebitUserID; lblBankUsername.Text = site.BankUsername.Length == 0 ? "--" : site.BankUsername; lblOustandingBalanceWarning.Text = site.OustandingBalanceWarning.ToString(); lblIsPrintEPC.Text = site.PrintEpc ? "Yes" : "No"; lblNumBookingMonthsToGet.Text = site.NumBookingMonthsToGet.ToString(); lblFiscalYrEnd.Text = site.FiscalYrEnd == DateTime.MinValue ? "--" : site.FiscalYrEnd.ToString("dd-MM-yyyy"); txtName.Visible = false; ddlClinic.Visible = false; txtABN.Visible = false; txtACN.Visible = false; txtTFN.Visible = false; txtASIC.Visible = false; chkIsProvider.Visible = false; txtBPay.Visible = false; txtBSB.Visible = false; txtBankAccount.Visible = false; txtBankDirectDebitUserID.Visible = false; txtBankUsername.Visible = false; txtOustandingBalanceWarning.Visible = false; chkIsPrintEPC.Visible = false; ddlNumBookingMonthsToGet.Visible = false; ddlFiscalYrEnd_Day.Visible = false; ddlFiscalYrEnd_Month.Visible = false; ddlFiscalYrEnd_Year.Visible = false; chkIncSunday.Enabled = false; chkIncMonday.Enabled = false; chkIncTuesday.Enabled = false; chkIncWednesday.Enabled = false; chkIncThursday.Enabled = false; chkIncFriday.Enabled = false; chkIncSaturday.Enabled = false; ddlDayStart_Hour.Enabled = false; ddlDayStart_Minute.Enabled = false; ddlDayEnd_Hour.Enabled = false; ddlDayEnd_Minute.Enabled = false; ddlLunchStart_Hour.Enabled = false; ddlLunchStart_Minute.Enabled = false; ddlLunchEnd_Hour.Enabled = false; ddlLunchEnd_Minute.Enabled = false; } btnSubmit.Text = isEditMode ? "Update Details" : "Edit Details"; btnCancel.Visible = isEditMode; }
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); }
private void FillEmptyAddForm() { txtName.Focus(); Page.Title = ((SystemVariables)Session["SystemVariables"])["Site"].Value + " - " + "Add Site"; lblHeading.Text = "Add Site"; // this.lnkNotes.Visible = false; idRow.Visible = false; DataTable dt = SiteDB.GetDataTable(); bool showClinicAddOption = Convert.ToInt32(SystemVariableDB.GetByDescr("AllowAddSiteClinic").Value) == 1; bool showAgedCareAddOption = Convert.ToInt32(SystemVariableDB.GetByDescr("AllowAddSiteAgedCare").Value) == 1; bool showGPAddOption = Convert.ToInt32(SystemVariableDB.GetByDescr("AllowAddSiteGP").Value) == 1; for (int i = 0; i < dt.Rows.Count; i++) { if (Convert.ToInt32(dt.Rows[i]["site_type_id"]) == 1) { showClinicAddOption = false; } if (Convert.ToInt32(dt.Rows[i]["site_type_id"]) == 2) { showAgedCareAddOption = false; } if (Convert.ToInt32(dt.Rows[i]["site_type_id"]) == 3) { showGPAddOption = false; } } ddlClinic.Items.Clear(); if (showClinicAddOption) { ddlClinic.Items.Add(new ListItem("Clinic", "1")); } if (showAgedCareAddOption) { ddlClinic.Items.Add(new ListItem("Aged Care", "2")); } if (showGPAddOption) { ddlClinic.Items.Add(new ListItem("GP", "3")); } if (!showClinicAddOption && !showAgedCareAddOption) { HideTableAndSetErrorMessage("Unable to add either Clinic or Aged Care Facility or GP."); } ddlNumBookingMonthsToGet.SelectedValue = "9"; ddlFiscalYrEnd_Day.SelectedValue = "30"; ddlFiscalYrEnd_Month.SelectedValue = "6"; chkIncSunday.Checked = false; chkIncMonday.Checked = true; chkIncTuesday.Checked = true; chkIncWednesday.Checked = true; chkIncThursday.Checked = true; chkIncFriday.Checked = true; chkIncSaturday.Checked = false; ddlDayStart_Hour.SelectedValue = "8"; ddlDayStart_Minute.SelectedValue = "0"; ddlDayEnd_Hour.SelectedValue = "18"; ddlDayEnd_Minute.SelectedValue = "0"; ddlLunchStart_Hour.SelectedValue = "12"; ddlLunchStart_Minute.SelectedValue = "0"; ddlLunchEnd_Hour.SelectedValue = "13"; ddlLunchEnd_Minute.SelectedValue = "0"; addressControl.Visible = false; addressAusControl.Visible = false; btnSubmit.Text = "Add Site"; }
private void SetupGUI(string dbID, string orgID) { ddlClinic.Focus(); ddlDOB_Day.Items.Add(new ListItem("--", "-1")); ddlDOB_Month.Items.Add(new ListItem("--", "-1")); ddlDOB_Year.Items.Add(new ListItem("----", "-1")); for (int i = 1; i <= 31; i++) { ddlDOB_Day.Items.Add(new ListItem(i.ToString(), i.ToString())); } for (int i = 1; i <= 12; i++) { ddlDOB_Month.Items.Add(new ListItem(i.ToString(), i.ToString())); } for (int i = 1900; i <= DateTime.Today.Year; i++) { ddlDOB_Year.Items.Add(new ListItem(i.ToString(), i.ToString())); } string curDbName = Session == null || Session["DB"] == null ? null : Session["DB"].ToString(); try { Session["DB"] = "Mediclinic_" + dbID; Session["SystemVariables"] = SystemVariableDB.GetAll(); bool allowPatientsToCreateOwnRecords = ((SystemVariables)Session["SystemVariables"])["AllowPatientsToCreateOwnRecords"].Value == "1"; if (!allowPatientsToCreateOwnRecords) { throw new CustomMessageException("Invalid ID in URL"); } ddlTitle.DataSource = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Title", " title_id <> 0 ", " descr ", "title_id", "descr"); ddlTitle.DataBind(); ddlTitle.SelectedIndex = Utilities.IndexOf(ddlTitle, "mr", "mr."); DataTable phoneNumberTypes = ContactTypeDB.GetDataTable(2); for (int i = phoneNumberTypes.Rows.Count - 1; i >= 0; i--) { if (Convert.ToInt32(phoneNumberTypes.Rows[i]["at_contact_type_id"]) != 30 && Convert.ToInt32(phoneNumberTypes.Rows[i]["at_contact_type_id"]) != 33) { phoneNumberTypes.Rows.RemoveAt(i); } } ddlPhoneNumberType.DataSource = phoneNumberTypes; ddlPhoneNumberType.DataBind(); ddlPhoneNumberType.SelectedValue = "30"; // mobile lblSiteName.Text = ((SystemVariables)Session["SystemVariables"])["Site"].Value; Site[] sites = SiteDB.GetAll(); Site clinicSite = null; Site agedCareSite = null; for (int i = 0; i < sites.Length; i++) { if (sites[i].SiteType.ID == 1) { clinicSite = sites[i]; } if (sites[i].SiteType.ID == 2) { agedCareSite = sites[i]; } } List <Tuple <string, Organisation> > clinics = GetClinicList(); foreach (Tuple <string, Organisation> item in clinics) { ddlClinic.Items.Add(new ListItem(item.Item2.Name, "Mediclinic_" + dbID + "__" + clinicSite.SiteID + "__" + item.Item2.OrganisationID)); } if (orgID != null && Regex.IsMatch(orgID, @"^\d+$")) { Organisation org = OrganisationDB.GetByID(Convert.ToInt32(orgID)); if (org != null && ddlClinic.Items.FindByValue("Mediclinic_" + dbID + "__" + clinicSite.SiteID + "__" + org.OrganisationID) != null) { ddlClinic.SelectedValue = "Mediclinic_" + dbID + "__" + clinicSite.SiteID + "__" + org.OrganisationID; } } } finally { Session.Remove("DB"); Session.Remove("SystemVariables"); if (curDbName != null) { Session["DB"] = curDbName; Session["SystemVariables"] = SystemVariableDB.GetAll(); } } bool editable = true; Utilities.SetEditControlBackColour(ddlClinic, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlTitle, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtFirstname, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtSurname, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlGender, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlDOB_Day, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlDOB_Month, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlDOB_Year, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtPhoneNumber, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(ddlPhoneNumberType, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtEmailAddr, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtLogin, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); Utilities.SetEditControlBackColour(txtPwd, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Empty); }
public HomeController(IFormsAuthenticationService FormsAuthService) { _db = new SiteDB(); this.FormsAuthService = FormsAuthService; }
public static string Run(bool incDisplay, bool incSending, bool incPtSending, DateTime date) { date = date.Date; string batchEmail = SystemVariableDB.GetByDescr("ServiceSpecificBookingReminderLettersToBatch_EmailAddress").Value; // don't actually run it if email empty (ie deactivated) incSending = incSending && batchEmail.Length > 0; Site[] sites = SiteDB.GetAll(); string output = string.Empty; Hashtable lettersHash = LetterDB.GetHashTable(); Offering[] offerings = OfferingDB.GetAll(false, -1); for (int j = 0; j < offerings.Length; j++) { if (offerings[j].ReminderLetterMonthsLaterToSend == 0 || offerings[j].ReminderLetterID == -1) { continue; } Booking[] bookings = BookingDB.GetWhenLastServiceFromXMonthsAgoToGenerageReminderLetter(offerings[j].OfferingID, date, offerings[j].ReminderLetterMonthsLaterToSend); Hashtable distinctPatients = new Hashtable(); for (int i = 0; i < bookings.Length; i++) { if (bookings[i].Patient != null && distinctPatients[bookings[i].Patient.PatientID] == null) { distinctPatients[bookings[i].Patient.PatientID] = bookings[i].Patient; } } Patient[] patients = (Patient[])(new ArrayList(distinctPatients.Values)).ToArray(typeof(Patient)); Hashtable patientContactEmailHash = GetPatientEmailCache(patients); // Generate Letters ArrayList filesToPrint = new ArrayList(); for (int i = 0; i < bookings.Length; i++) { Booking curBooking = bookings[i]; if (curBooking.Patient == null) { continue; } Patient curPatient = curBooking.Patient; string curPatientEmail = GetEmail(patientContactEmailHash, curPatient.Person.EntityID); bool curPatientHasEmail = curPatientEmail != null; SendMethod sendMethod = incPtSending && curPatientHasEmail ? SendMethod.Email_To_Patient : SendMethod.Batch; if (incSending) { if (sendMethod == SendMethod.Email_To_Patient) { // generate and send email Letter.FileContents fileContents = GenerteLetter(curBooking, Letter.FileFormat.PDF, lettersHash, sites); fileContents.DocName = "Reminder" + System.IO.Path.GetExtension(fileContents.DocName); if (fileContents != null) { Site site = SiteDB.GetSiteByType(curBooking.Organisation.IsAgedCare ? SiteDB.SiteType.AgedCare : SiteDB.SiteType.Clinic); SendEmail(site.Name, curPatientEmail, "Important Reminder", "Hi " + curBooking.Patient.Person.Firstname + ",<br /><br />Please find attached a review reminder letter for a previous appointment.<br /><br/>Best regards,<br />" + site.Name, true, new Letter.FileContents[] { fileContents }); } } else { // generate and add to batch list (if batch email set) if (batchEmail.Length > 0) { Letter.FileContents fileContents = GenerteLetter(curBooking, Letter.FileFormat.Word, lettersHash, sites); if (fileContents != null) { filesToPrint.Add(fileContents); } } } } string addEditContactListPage; if (Utilities.GetAddressType().ToString() == "Contact") { addEditContactListPage = "AddEditContactList.aspx"; } else if (Utilities.GetAddressType().ToString() == "ContactAus") { addEditContactListPage = "ContactAusListV2.aspx"; } else { throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString()); } string allFeatures = "dialogWidth:555px;dialogHeight:350px;center:yes;resizable:no; scroll:no"; string onclick = "onclick=\"javascript:window.showModalDialog('" + addEditContactListPage + "?entity_type=referrer&id=" + curBooking.Patient.Person.EntityID.ToString() + "', '', '" + allFeatures + "');document.getElementById('btnUpdateList').click();return false;\""; string hrefUpdateEmail = "<u><a style=\"text-decoration: none\" title=\"Edit\" AlternateText=\"Edit\" " + onclick + " href=\"\">Update PT Email</a></u>"; output += @"<tr> <td class=""nowrap"">" + curBooking.BookingID + " [" + curBooking.DateStart.ToString("dd-MM-yyyy") + " " + curBooking.DateStart.ToString("HH:mm") + "-" + curBooking.DateEnd.ToString("HH:mm") + "]" + @"</td> <td class=""text_left"">" + curBooking.Organisation.Name + @"</td> <td class=""text_left"">" + curBooking.Offering.Name + @"</td> <td class=""text_left"">" + ((Letter)lettersHash[curBooking.Offering.ReminderLetterID]).Docname + @"</td> <td class=""text_left"">" + curPatient.Person.FullnameWithoutMiddlename + @"</td> <td class=""nowrap"">" + (curPatientHasEmail ? curPatientEmail : "Has No Email") + " (" + hrefUpdateEmail + ")" + @"</td> <td>" + sendMethod.ToString().Replace("_", " ") + @"</td> </tr>"; } // combine and email where the patient had no email if (incSending && filesToPrint.Count > 0) { Letter.FileContents filesContents = Letter.FileContents.Merge((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)), "Reminders.pdf"); // .pdf SendEmail( ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromName"].Value, batchEmail, "Batch Reminder Letters", string.Empty, true, new Letter.FileContents[] { filesContents }); } } if (output.Length == 0) { output += @"<tr> <td colspan=""7"">No Reminders To Send Today</td> </tr>"; } return(@" <table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" style=""border-style:solid;border-width:1px;border-collapse:collapse;padding:4px;""> <tr> <th>Booking (ID, Date/Time)</th> <th>Organisation</th> <th>Service</th> <th>Letter</th> <th>Patient</th> <th>PT Email</th> <th>Send Method</th> </tr> " + output + @" </table>"); }
protected void GrdNote_RowDataBound(object sender, GridViewRowEventArgs e) { try { UserView userView = UserView.GetInstance(); // if there exists note with the type not in the list of types offered on this screen, use this to add below with "foundRows" DataTable allNoteTypes = DBBase.GetGenericDataTable(null, "NoteType", "note_type_id", "descr"); DataTable allBodyParts = DBBase.GetGenericDataTable(null, "BodyPart", "body_part_id", "descr"); DataTable noteTypes = IsValidFormScreen() ? ScreenNoteTypesDB.GetDataTable_ByScreenID(GetFormScreen()) : allNoteTypes; DataTable sites = SiteDB.GetDataTable(); DataTable dt = ViewState["noteinfo_data"] as DataTable; bool tblEmpty = (dt.Rows.Count == 1 && dt.Rows[0][0] == DBNull.Value); if (!tblEmpty && e.Row.RowType == DataControlRowType.DataRow) { Label lblId = (Label)e.Row.FindControl("lblId"); DataRow[] foundRows = dt.Select("note_id=" + lblId.Text); DataRow thisRow = foundRows[0]; bool isDeleted = thisRow["deleted_by"] != DBNull.Value || thisRow["date_deleted"] != DBNull.Value; DropDownList ddlDate_Day = (DropDownList)e.Row.FindControl("ddlDate_Day"); DropDownList ddlDate_Month = (DropDownList)e.Row.FindControl("ddlDate_Month"); DropDownList ddlDate_Year = (DropDownList)e.Row.FindControl("ddlDate_Year"); if (ddlDate_Day != null && ddlDate_Month != null && ddlDate_Year != null) { ddlDate_Day.Items.Add(new ListItem("--", "-1")); ddlDate_Month.Items.Add(new ListItem("--", "-1")); ddlDate_Year.Items.Add(new ListItem("----", "-1")); for (int i = 1; i <= 31; i++) { ddlDate_Day.Items.Add(new ListItem(i.ToString(), i.ToString())); } for (int i = 1; i <= 12; i++) { ddlDate_Month.Items.Add(new ListItem(i.ToString(), i.ToString())); } for (int i = DateTime.Today.Year - 1; i <= DateTime.Today.Year + 1; i++) { ddlDate_Year.Items.Add(new ListItem(i.ToString(), i.ToString())); } if (thisRow["date_added"] != DBNull.Value) { DateTime Date = Convert.ToDateTime(thisRow["date_added"]); ddlDate_Day.SelectedValue = Date.Day.ToString(); ddlDate_Month.SelectedValue = Date.Month.ToString(); int firstYearSelectable = Convert.ToInt32(ddlDate_Year.Items[1].Value); int lastYearSelectable = Convert.ToInt32(ddlDate_Year.Items[ddlDate_Year.Items.Count - 1].Value); if (Date.Year < firstYearSelectable) { ddlDate_Year.Items.Insert(1, new ListItem(Date.Year.ToString(), Date.Year.ToString())); } if (Date.Year > lastYearSelectable) { ddlDate_Year.Items.Add(new ListItem(Date.Year.ToString(), Date.Year.ToString())); } ddlDate_Year.SelectedValue = Date.Year.ToString(); } } DropDownList ddlNoteType = (DropDownList)e.Row.FindControl("ddlNoteType"); if (ddlNoteType != null) { ddlNoteType.DataSource = noteTypes; ddlNoteType.DataTextField = "descr"; ddlNoteType.DataValueField = "note_type_id"; ddlNoteType.DataBind(); // if this note type is not in the list for this screen, add it to the edit list bool found = false; foreach (ListItem li in ddlNoteType.Items) { if (li.Value == thisRow["note_type_id"].ToString()) { found = true; } } if (!found) { ddlNoteType.Items.Add(new ListItem(thisRow["note_type_descr"].ToString(), thisRow["note_type_id"].ToString())); } ddlNoteType.SelectedValue = thisRow["note_type_id"].ToString(); } DropDownList ddlBodyPart = (DropDownList)e.Row.FindControl("ddlBodyPart"); if (ddlBodyPart != null) { ddlBodyPart.Items.Clear(); ddlBodyPart.Items.Add(new ListItem("", "-1")); for (int i = 0; i < allBodyParts.Rows.Count; i++) { ddlBodyPart.Items.Add(new ListItem(allBodyParts.Rows[i]["body_part_id"].ToString() + ". " + allBodyParts.Rows[i]["descr"].ToString(), allBodyParts.Rows[i]["body_part_id"].ToString())); } ddlBodyPart.SelectedValue = thisRow["body_part_id"].ToString(); } ImageButton lnkEdit = (ImageButton)e.Row.FindControl("lnkEdit"); if (lnkEdit != null) { lnkEdit.Visible = !isDeleted && (userView.IsAdminView || (thisRow["added_by_staff_id"] != DBNull.Value && Convert.ToInt32(thisRow["added_by_staff_id"]) == Convert.ToInt32(Session["StaffID"])) || (thisRow["modified_by_staff_id"] != DBNull.Value && Convert.ToInt32(thisRow["modified_by_staff_id"]) == Convert.ToInt32(Session["StaffID"]))); } /* * DropDownList ddlSite = (DropDownList)e.Row.FindControl("ddlSite"); * if (ddlSite != null) * { * ddlSite.Items.Add(new ListItem("--", "-1")); * foreach (DataRow row in sites.Rows) * ddlSite.Items.Add(new ListItem(row["name"].ToString(), row["site_id"].ToString())); * ddlSite.SelectedValue = thisRow["site_id"].ToString(); * } */ ImageButton lnkDelete = (ImageButton)e.Row.FindControl("lnkDelete"); if (lnkDelete != null) { lnkDelete.Visible = userView.IsAdminView || (thisRow["added_by_staff_id"] != DBNull.Value && Convert.ToInt32(thisRow["added_by_staff_id"]) == Convert.ToInt32(Session["StaffID"])) || (thisRow["modified_by_staff_id"] != DBNull.Value && Convert.ToInt32(thisRow["modified_by_staff_id"]) == Convert.ToInt32(Session["StaffID"])); if (isDeleted) { lnkDelete.CommandName = "_UnDelete"; lnkDelete.ImageUrl = "~/images/tick-24.png"; lnkDelete.ToolTip = "Un-Delete"; } } if (isDeleted) { e.Row.AddCssClass("deleted_note"); e.Row.Style["display"] = "none"; e.Row.Style["color"] = "gray"; } Utilities.AddConfirmationBox(e); if ((e.Row.RowState & DataControlRowState.Edit) > 0) { Utilities.SetEditRowBackColour(e, System.Drawing.Color.LightGoldenrodYellow); } } if (e.Row.RowType == DataControlRowType.Footer) { DropDownList ddlDate_Day = (DropDownList)e.Row.FindControl("ddlNewDate_Day"); DropDownList ddlDate_Month = (DropDownList)e.Row.FindControl("ddlNewDate_Month"); DropDownList ddlDate_Year = (DropDownList)e.Row.FindControl("ddlNewDate_Year"); if (ddlDate_Day != null && ddlDate_Month != null && ddlDate_Year != null) { ddlDate_Day.Items.Add(new ListItem("--", "-1")); ddlDate_Month.Items.Add(new ListItem("--", "-1")); ddlDate_Year.Items.Add(new ListItem("----", "-1")); for (int i = 1; i <= 31; i++) { ddlDate_Day.Items.Add(new ListItem(i.ToString(), i.ToString())); } for (int i = 1; i <= 12; i++) { ddlDate_Month.Items.Add(new ListItem(i.ToString(), i.ToString())); } for (int i = DateTime.Today.Year - 1; i <= DateTime.Today.Year + 1; i++) { ddlDate_Year.Items.Add(new ListItem(i.ToString(), i.ToString())); } ddlDate_Day.SelectedValue = DateTime.Today.Day.ToString(); ddlDate_Month.SelectedValue = DateTime.Today.Month.ToString(); ddlDate_Year.SelectedValue = DateTime.Today.Year.ToString(); } DropDownList ddlNoteType = (DropDownList)e.Row.FindControl("ddlNewNoteType"); ddlNoteType.DataSource = noteTypes; ddlNoteType.DataBind(); DropDownList ddlBodyPart = (DropDownList)e.Row.FindControl("ddlNewBodyPart"); ddlBodyPart.Items.Add(new ListItem("", "-1")); for (int i = 0; i < allBodyParts.Rows.Count; i++) { ddlBodyPart.Items.Add(new ListItem(allBodyParts.Rows[i]["body_part_id"].ToString() + ". " + allBodyParts.Rows[i]["descr"].ToString(), allBodyParts.Rows[i]["body_part_id"].ToString())); } // set note text in cookie in case user logged out, to keep note text for this user and this entity TextBox txtNewText = (TextBox)e.Row.FindControl("txtNewText"); txtNewText.Attributes["onkeyup"] = "set_note(document.getElementById('" + txtNewText.ClientID + "'), document.getElementById('" + userID.ClientID + "').value, document.getElementById('" + entityID.ClientID + "').value);"; /* * DropDownList ddlSite = (DropDownList)e.Row.FindControl("ddlNewSite"); * ddlSite.Items.Add(new ListItem("--", "-1")); * foreach (DataRow row in sites.Rows) * ddlSite.Items.Add(new ListItem(row["name"].ToString(), row["site_id"].ToString())); * ddlSite.SelectedValue = Session["SiteID"].ToString(); */ } } catch (Exception ex) { if (Utilities.IsDev()) { throw; } else { HideTableAndSetErrorMessage(ex is CustomMessageException ? ex.Message : ""); } } }
protected void Run(bool incDisplay, bool incSending) { // 1. get all fields from systemvariables bool EnableEmails = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendEmail").Value) == 1; string EmailAddress = SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_EmailAddress").Value; bool IncClinicsAuto = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncClinic").Value) == 1; bool IncAgedCareAuto = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncAgedCare").Value) == 1; bool IncUnsentAuto = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncUnsent").Value) == 1; bool IncBatchedAuto = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncBatched").Value) == 1; ReferrerEPCLettersSending.SendMethod sendMethod = SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendMethod").Value == "Email" ? ReferrerEPCLettersSending.SendMethod.Email_To_Referrer : ReferrerEPCLettersSending.SendMethod.Batch; bool SendMondays = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendMondays").Value) == 1; bool SendTuesdays = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendTuesdays").Value) == 1; bool SendWednesdays = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendWednesdays").Value) == 1; bool SendThursdays = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendThursdays").Value) == 1; bool SendFridays = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendFridays").Value) == 1; bool SendSaturdays = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendSaturdays").Value) == 1; bool SendSundays = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendSundays").Value) == 1; // 2. validate if (!EnableEmails) { return; } if (!Utilities.IsValidEmailAddresses(EmailAddress, false)) { return; } if (!IncClinicsAuto && !IncAgedCareAuto) { return; } if (DateTime.Today.DayOfWeek == DayOfWeek.Monday && !SendMondays) { return; } if (DateTime.Today.DayOfWeek == DayOfWeek.Tuesday && !SendTuesdays) { return; } if (DateTime.Today.DayOfWeek == DayOfWeek.Wednesday && !SendWednesdays) { return; } if (DateTime.Today.DayOfWeek == DayOfWeek.Thursday && !SendThursdays) { return; } if (DateTime.Today.DayOfWeek == DayOfWeek.Friday && !SendFridays) { return; } if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday && !SendSaturdays) { return; } if (DateTime.Today.DayOfWeek == DayOfWeek.Sunday && !SendSundays) { return; } // 3. run it int siteID = -1; if (IncClinicsAuto && IncAgedCareAuto) { siteID = -1; } else if (IncClinicsAuto && !IncAgedCareAuto) { foreach (Site s in SiteDB.GetAll()) { if (s.SiteType.ID == 1) { siteID = s.SiteID; } } } else if (!IncClinicsAuto && IncAgedCareAuto) { foreach (Site s in SiteDB.GetAll()) { if (s.SiteType.ID == 2) { siteID = s.SiteID; } } } string outputInfo; string outputList; Letter.FileContents fileContents = ReferrerEPCLettersSending.Run( sendMethod, siteID, -1, -1, IncBatchedAuto, IncUnsentAuto, !incSending, false, out outputInfo, out outputList, string.Empty ); if (incDisplay) { Response.Write(outputInfo + "<br /><br />" + outputList); } // 4. Put in file and email it if (fileContents != null) { string tmpLettersDirectory = Letter.GetTempLettersDirectory(); if (!System.IO.Directory.Exists(tmpLettersDirectory)) { throw new CustomMessageException("Temp letters directory doesn't exist"); } string tmpDir = FileHelper.GetTempDirectoryName(tmpLettersDirectory); System.IO.Directory.CreateDirectory(tmpDir); string tmpFileName = tmpDir + fileContents.DocName; System.IO.File.WriteAllBytes(tmpFileName, fileContents.Contents); Emailer.SimpleEmail(EmailAddress, "Automated Referral Letters [" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + "]", "Please find attached referral letters to send to referrers.<br /><br />Regards,<br />Mediclinic", true, new string[] { tmpFileName }, null); System.IO.File.Delete(tmpFileName); System.IO.Directory.Delete(tmpDir); } }
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 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); }
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 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 Run(bool viewListOnly) { try { if (SelectedSendMethod == SendMethod.None) { throw new CustomMessageException("Send method not selected"); } int staffID = Session != null && Session["StaffID"] != null?Convert.ToInt32(Session["StaffID"]) : -1; int siteID = -1; if (!chkIncClinics.Checked && !chkIncAgedCare.Checked) { throw new CustomMessageException("Plese check to generate for Clinics and/or Aged Care"); } else if (chkIncClinics.Checked && chkIncAgedCare.Checked) { siteID = -1; } else if (chkIncClinics.Checked) { foreach (Site s in SiteDB.GetAll()) { if (s.SiteType.ID == 1) { siteID = s.SiteID; } } } else if (chkIncAgedCare.Checked) { foreach (Site s in SiteDB.GetAll()) { if (s.SiteType.ID == 2) { siteID = s.SiteID; } } } /* * // if called by automated settings there will be no session setting for SiteID or StaffID * // but siteID is needed to know which letter template to use for generation * if (siteID == null) * { * Site[] sites = SiteDB.GetAll(); * siteID = (sites.Length == 1) ? sites[0].SiteID : sites[sites.Length - 1].SiteID; // if one site, use that -- else choose last one since clinics site developed first and exists * } */ string outputInfo; string outputList; Letter.FileContents fileContents = ReferrerEPCLettersSendingV2.Run( SelectedSendMethod == SendMethod.Email ? ReferrerEPCLettersSendingV2.SendMethod.Email_To_Referrer : ReferrerEPCLettersSendingV2.SendMethod.Batch, siteID, staffID, Convert.ToInt32(registerReferrerID.Value), chkIncBatching.Checked, chkIncUnsent.Checked, chkIncWithEmailOrFaxOnly.Checked, viewListOnly, chkShowFullList.Checked, out outputInfo, out outputList, btnViewList.ClientID ); lblInfo.Text = outputInfo; lblList.Text = outputList; if (fileContents != null) { 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>"); } } catch (CustomMessageException cmEx) { SetErrorMessage(cmEx.Message); } catch (Exception ex) { SetErrorMessage("", ex.ToString()); } return; bool debugMode = true; // // 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 // try { string sendMethod = rdioSendType.SelectedValue; if (!viewListOnly && SelectedSendMethod == SendMethod.None) { throw new CustomMessageException("Send method not selected"); } string tmpLettersDirectory = Letter.GetTempLettersDirectory(); if (!Directory.Exists(tmpLettersDirectory)) { throw new CustomMessageException("Temp letters directory doesn't exist"); } string debugOutput = string.Empty; int startTime = Environment.TickCount; DataTable bookingsWithUnsetnLetters = BookingDB.GetBookingsWithEPCLetters(DateTime.MinValue, DateTime.MinValue, Convert.ToInt32(registerReferrerID.Value), -1, false, true, chkIncBatching.Checked, chkIncUnsent.Checked); double queryExecutionTime = (double)(Environment.TickCount - startTime) / 1000.0; startTime = Environment.TickCount; ArrayList filesToPrint = new ArrayList(); int c = 0; int currentRegReferrerID = -1; ArrayList bookingsForCurrentReferrer = new ArrayList(); foreach (DataRow row in bookingsWithUnsetnLetters.Rows) { //c++; if (c % 15 != 1) continue; if (c > ReferrerEPCLettersSendingV2.MaxSending) { continue; } Tuple <Booking, PatientReferrer, bool, string, HealthCard> rowData = LoadRow(row); Booking booking = rowData.Item1; PatientReferrer pr = rowData.Item2; bool refHasEmail = rowData.Item3; string refEmail = rowData.Item4; HealthCard hc = rowData.Item5; if (pr.RegisterReferrer.RegisterReferrerID != currentRegReferrerID) { filesToPrint.AddRange(ProcessReferrersLetters(viewListOnly, bookingsForCurrentReferrer, ref debugOutput)); currentRegReferrerID = pr.RegisterReferrer.RegisterReferrerID; bookingsForCurrentReferrer = new ArrayList(); } bookingsForCurrentReferrer.Add(rowData); } // process last group filesToPrint.AddRange(ProcessReferrersLetters(viewListOnly, bookingsForCurrentReferrer, ref debugOutput)); bool zipSeperately = true; if (zipSeperately && filesToPrint.Count > 0) { // 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 + "EPC 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 = "EPC 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 Letter.FileContents zipFileContents = new Letter.FileContents(zipFilePath, zipFileName); Session["downloadFile_Contents"] = zipFileContents.Contents; 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 && filesToPrint.Count > 0) { Letter.FileContents fileContents = Letter.FileContents.Merge((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)), "Referral Letters.doc"); // .pdf Session["downloadFile_Contents"] = fileContents.Contents; 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 && Convert.ToInt32(registerReferrerID.Value) == -1 && chkIncBatching.Checked) { SetLastDateBatchSendTreatmentNotesAllReferrers(DateTime.Now); } double restExecutionTime = (double)(Environment.TickCount - startTime) / 1000.0; if (debugMode) { string countGenrated = bookingsWithUnsetnLetters.Rows.Count > ReferrerEPCLettersSendingV2.MaxSending ? ReferrerEPCLettersSendingV2.MaxSending + " of " + bookingsWithUnsetnLetters.Rows.Count + " generated" : bookingsWithUnsetnLetters.Rows.Count.ToString() + " generated"; string countShowing = bookingsWithUnsetnLetters.Rows.Count > ReferrerEPCLettersSendingV2.MaxSending ? ReferrerEPCLettersSendingV2.MaxSending + " of " + bookingsWithUnsetnLetters.Rows.Count + " showing to generate. <br />* If there are more than " + ReferrerEPCLettersSendingV2.MaxSending + ", the next " + ReferrerEPCLettersSendingV2.MaxSending + " will have to be generated seperately after this." : bookingsWithUnsetnLetters.Rows.Count.ToString(); if (!viewListOnly) { lblInfo.Text = @"<table cellpadding=""0""> <tr><td><b>Send Method</b></td><td style=""width:10px;""></td><td>" + SelectedSendMethod.ToString() + @"</td><td style=""width:25px;""></td><td><b>Query Time</b></td><td style=""width:10px;""></td><td>" + queryExecutionTime + @" 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>" + restExecutionTime + @" seconds</td></tr> </table>" + "<br />"; } if (viewListOnly) { lblInfo.Text = @"<table cellpadding=""0""> <tr><td valign=""top""><b>Count</b></td><td style=""width:10px;""></td><td>" + countShowing + @"</td></tr> </table>" + "<br />"; } if (viewListOnly) { lblList.Text = @"<table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" border=""1""> <tr> <th>Send By</th> <th>Booking</th> <th>Generate</th> <th>Referrer</th> <th>Email</th> <th>Patient</th> </tr>" + (debugOutput.Length == 0 ? "<tr><td colspan=\"6\">No Rows</td></tr>" : debugOutput) + "</table>"; } } } catch (CustomMessageException cmEx) { SetErrorMessage(cmEx.Message); } catch (Exception ex) { SetErrorMessage(ex.ToString()); } }
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(); } } }