コード例 #1
0
    protected void lnkBackToCallCenter_Click(object sender, EventArgs e)
    {
        if (Session == null || Session["PreviousDB"] == null)
        {
            Utilities.LogoutV2(Session, Response, Request);
            return;
        }

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

        // Set system staff variables of external staff member 'Call Center'
        Staff staff = StaffDB.GetByID(Convert.ToInt32(Session["PreviousStaffID"]));

        Session["IsLoggedIn"]    = true;
        Session["IsStakeholder"] = staff.IsStakeholder;
        Session["IsMasterAdmin"] = staff.IsMasterAdmin;
        Session["IsAdmin"]       = staff.IsAdmin;
        Session["IsPrincipal"]   = staff.IsPrincipal;
        Session["IsProvider"]    = staff.IsProvider;
        Session["IsExternal"]    = staff.IsExternal;
        Session["StaffID"]       = staff.StaffID;
        Session["StaffFullnameWithoutMiddlename"] = staff.Person.FullnameWithoutMiddlename;
        Session["StaffFirstname"] = staff.Person.Firstname;

        Site site = SiteDB.GetByID(Convert.ToInt32(Session["PreviousSiteID"]));

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

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



        Session.Remove("PreviousDB");
        Session.Remove("PreviousStaffID");
        Session.Remove("PreviousSiteID");


        // Set OrgID in session as external user has OrgID set
        Session.Remove("OrgID");
        Session.Remove("OrgName");

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

        // Go to call center page
        Response.Redirect("~/CallCenterV2.aspx", false);
        return;
    }
コード例 #2
0
 protected void GenerateDVAHinxFiles()
 {
     Site[] allSites = SiteDB.GetAll();
     foreach (Site site in allSites)
     {
         GenerateClaimNumbers(-2, site.SiteID);
         GenerateHinxFiles(HinxFile.ClaimType.DVA, GetFromDate(), GetToDate(), site.SiteID);
     }
 }
コード例 #3
0
    public static string Run(bool incDisplay, bool incSending)
    {
        bool EnableAutoMontlyOverdueReminders = Convert.ToInt32(((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["EnableAutoMontlyOverdueReminders"].Value) == 1;

        if (!EnableAutoMontlyOverdueReminders)
        {
            incSending = false;
        }

        string output = string.Empty;

        foreach (Site site in SiteDB.GetAll())
        {
            output += (output.Length == 0 ? string.Empty : "<br /><br /><br />") + Run(incDisplay, incSending, site);
        }
        return(output);
    }
コード例 #4
0
    protected void SetupGUI()
    {
        if (SiteDB.GetAll().Length <= 1)
        {
            select_sites_row.Attributes.Add("class", "hiddencol");
            select_sites_row_trailingspace.Attributes.Add("class", "hiddencol");

            select_sites_row_auto.Attributes.Add("class", "hiddencol");
            select_sites_row_trailingspace.Attributes.Add("class", "hiddencol");
        }

        for (int i = 0; i < rdioSendTypeAuto.Items.Count; i++)
        {
            rdioSendTypeAuto.Items[i].Attributes["onclick"] = "notification_info_edited();";
            rdioSendTypeAuto.Items[i].Attributes["class"]   = "nowrap";
        }

        for (int i = 0; i < rdioSendType.Items.Count; i++)
        {
            rdioSendType.Items[i].Attributes["class"] = "nowrap";
        }
    }
コード例 #5
0
    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());
        }
    }
コード例 #6
0
    protected void DisplayInfo()
    {
        string curDbName = Session["DB"].ToString();

        ddlDBs.Items.Clear();
        ddlDBs.Items.Add(new ListItem("All Clients", "0"));

        ddlDBs2.Items.Clear();
        ddlDBs2.Items.Add(new ListItem("All Clients", "0"));

        ArrayList dbNames = new ArrayList();
        Hashtable dbHash  = new Hashtable();

        try
        {
            bool isSupportStaff3 = Session != null && Session["StaffID"] != null && Convert.ToInt32(Session["StaffID"]) == -4;

            List <Tuple <string, string> > list = new List <Tuple <string, string> >();


            System.Data.DataTable tbl = DBBase.ExecuteQuery("EXEC sp_databases;", "master").Tables[0];
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                string databaseName = tbl.Rows[i][0].ToString();

                if (!Regex.IsMatch(databaseName, @"Mediclinic_\d{4}"))
                {
                    continue;
                }
                //if (databaseName == "Mediclinic_0001")
                //    continue;


                SystemVariables sysVariables = SystemVariableDB.GetAll(databaseName);

                dbNames.Add(sysVariables["Site"].Value);
                dbHash[sysVariables["Site"].Value] = databaseName;


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

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

                string callCenterPrefix = ((SystemVariables)Session["SystemVariables"])["CallCenterPrefix"].Value;

                int loginsPastWeek_Total = UserLoginDB.GetCount(7);
                int loginsPastWeek_Staff = UserLoginDB.GetStaffCount(7);


                if (((SystemVariables)Session["SystemVariables"])["UseMediclinicCallCenter"].Value == "1")
                {
                    Organisation[] orgs = OrganisationDB.GetAll(false, true, false, false, true, true);


                    Site[] sites          = SiteDB.GetAll();
                    int    clinicSiteID   = -1;
                    int    agedCareSiteID = -1;
                    for (int j = 0; j < sites.Length; j++)
                    {
                        if (sites[j].SiteType.ID == 1)
                        {
                            clinicSiteID = sites[j].SiteID;
                        }
                        if (sites[j].SiteType.ID == 2)
                        {
                            agedCareSiteID = sites[j].SiteID;
                        }
                    }


                    string showHideID1   = "heading_" + databaseName;
                    string showHideLink1 = @"<a href=""javascript:void(0)"" onclick=""hide_show_all('" + showHideID1 + @"');return false;"">Show/Hide Clinics/Facs</a>";

                    string siteTitleLink = @"<span style=""display:inline-block;vertical-align:middle;max-width:300px;min-width:300px;overflow:hidden;text-overflow:ellipsis;""><a style=""white-space:nowrap;"" class=""call_centre_header"" title=""" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @""" href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @""" onclick=""http_post('" + databaseName + @"','0','0',-1);return false;"">" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @"</a></span>";
                    //string siteTitleLink      = @"<span style=""display:inline-block;min-width:250px;""><a class=""call_centre_header"" title=""" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @""" href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @""" onclick=""http_post('" + databaseName + @"','0','0',-1);return false;"">" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @"</a></span>";
                    string callCentrePrefixText = @"<span style=""display:inline-block;min-width:160px;"">[Call Center Prefix: " + callCenterPrefix + "]</span>";

                    output.AppendLine("<tr>");
                    //output.AppendLine("    <td><u>" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + "</u> &nbsp;&nbsp; [Call Center Prefix: " + callCenterPrefix + "] &nbsp;&nbsp; [" + Session["DB"] + "]</td>");
                    output.AppendLine("    <td>" + showHideLink1 + " &nbsp;&nbsp; " + (isSupportStaff3 ? @"<span style=""display:inline-block;min-width:55px;"">" + (loginsPastWeek_Staff == 0 && loginsPastWeek_Total == 0 ? "" : "[" + loginsPastWeek_Staff + "," + loginsPastWeek_Total + "]") + "</span>" + " &nbsp;&nbsp; " : "") + siteTitleLink + " &nbsp;&nbsp; " + callCentrePrefixText + " &nbsp;&nbsp; [" + Session["DB"] + "]</td>");
                    output.AppendLine("</tr>");

                    if (orgs.Length > 0)
                    {
                        for (int j = 0; j < orgs.Length; j++)
                        {
                            string showHideID  = databaseName + "_" + orgs[j].OrganisationID;
                            string contactInfo = GetContactInfo(orgs[j].EntityID, 60, showHideID);

                            string titleLink    = @"<a href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @"&org=" + orgs[j].OrganisationID + @""" onclick=""http_post('" + databaseName + "','" + orgs[j].OrganisationID + @"','" + (orgs[j].IsClinic ? clinicSiteID : agedCareSiteID) + @"',-1);return false;"">" + orgs[j].Name + " " + (orgs[j].IsClinic ? @"(Clinic)" : "(Aged Care)") + @"</a>";
                            string showHideLink = @"<a href=""javascript:void(0)"" onclick=""hide_show('" + showHideID + @"');return false;"">Show/Hide Details</a>";


                            output.AppendLine(@"<tr id=""" + showHideID1 + j.ToString() + @""" style=""margin:0 0;display:none;"">");
                            output.AppendLine(@"    <td style=""margin:0 0;"">");
                            output.AppendLine(@"            <table><tr style=""vertical-align:top;""><td style=""width:500px;""><ul style=""margin:0 0;""><li>" + titleLink + @"</li></ul></td><td style=""min-width:10px;""></td><td>" + (contactInfo.Length > 0 ? showHideLink : "") + "</td></tr></table>");

                            if (contactInfo.Length > 0)
                            {
                                output.AppendLine(contactInfo);
                            }

                            output.AppendLine(@"    </td>");
                            output.AppendLine(@"</tr>");
                        }
                    }
                }

                list.Add(new Tuple <string, string>(((SystemVariables)Session["SystemVariables"])["Site"].Value, output.ToString()));

                Session.Remove("DB");
                Session.Remove("SystemVariables");
            }


            dbNames.Sort();
            foreach (string siteName in dbNames)
            {
                ddlDBs.Items.Add(new ListItem("[" + dbHash[siteName] + "] " + siteName, dbHash[siteName].ToString()));
                ddlDBs2.Items.Add(new ListItem("[" + dbHash[siteName] + "] " + siteName, dbHash[siteName].ToString()));
            }


            list.Sort((a, b) => a.Item1.CompareTo(b.Item1));
            System.Text.StringBuilder finalOutput = new System.Text.StringBuilder();
            foreach (Tuple <string, string> item in list)
            {
                finalOutput.Append(item.Item2);
            }

            lblInfo1.Text = "<table>" + finalOutput.ToString() + "</table>";
        }
        finally
        {
            Session["DB"] = curDbName;
            Session["SystemVariables"] = SystemVariableDB.GetAll();
        }
    }
コード例 #7
0
    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;
        }
    }
コード例 #8
0
    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);
        }
    }
コード例 #9
0
    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;
            }
        }
    }
コード例 #10
0
    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);
    }
コード例 #11
0
    public static string Run(bool incDisplay, bool incSending, bool incPtSending, DateTime date)
    {
        date = date.Date;

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

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

        Site[] sites = SiteDB.GetAll();


        string output = string.Empty;

        Hashtable lettersHash = LetterDB.GetHashTable();

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

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


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

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



            // Generate Letters

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

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


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

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

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

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

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


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


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

        return(@"
            <table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" style=""border-style:solid;border-width:1px;border-collapse:collapse;padding:4px;"">
            <tr>
              <th>Booking (ID, Date/Time)</th>
              <th>Organisation</th>
              <th>Service</th>
              <th>Letter</th>
              <th>Patient</th>
              <th>PT Email</th>
              <th>Send Method</th>
            </tr>
            " + output + @"
            </table>");
    }
コード例 #12
0
    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);
    }
コード例 #13
0
    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 + " &nbsp;&nbsp;&nbsp;[" + curBooking.DateStart.ToString("dd-MM-yyyy") + "&nbsp;&nbsp;&nbsp;" + 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)));
    }
コード例 #14
0
    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>");
        }
    }
コード例 #15
0
    protected Letter.FileContents[] ProcessReferrersLetters(bool viewListOnly, ArrayList bookingsForCurrentReferrer, ref string debugOutput)
    {
        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();


        // an email belongs to the regRef.Org ... so one referrer can have multiple.
        // keep in hash to avoid continued lookups.
        Hashtable refEmailHash = new Hashtable();

        ArrayList regRefIDsToUpdateDateTimeOfLastBatchSend = new ArrayList();

        Site[] sites = SiteDB.GetAll();
        for (int i = 0; i < bookingsForCurrentReferrer.Count; i++)
        {
            Tuple <Booking, PatientReferrer, bool, string, HealthCard> curTuple = (Tuple <Booking, PatientReferrer, bool, string, HealthCard>)bookingsForCurrentReferrer[i];
            Booking         curBooking     = curTuple.Item1;
            PatientReferrer curPR          = curTuple.Item2;
            bool            curRefHasEmail = curTuple.Item3;
            string          curRefEmail    = 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)
                {
                    if (curRefHasEmail && this.SelectedSendMethod == SendMethod.Email)
                    {
                        Letter.FileContents[] fileContentsList = curBooking.GetSystemLettersList(Letter.FileFormat.PDF, curBooking.Patient, curHC, curBooking.Offering.Field.ID, curPR.RegisterReferrer.Referrer, true, 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)
                        {
                            if (ReferrerEPCLettersSendingV2.LogDebugEmailInfo)
                            {
                                Logger.LogQuery("C ReferrerEPCLetters_GenerateUnsent -- Email Send Item Starting [" + curRefEmail + "]", false, false, true);
                            }

                            Site site = SiteDB.GetSiteByType(curBooking.Organisation.IsAgedCare ? SiteDB.SiteType.AgedCare : SiteDB.SiteType.Clinic, sites);
                            Letter.EmailSystemLetter(site.Name, curRefEmail, fileContentsList,
                                                     "Referral/Treatment Note Letters From Mediclinic" + (curPR.Patient == null ? string.Empty : " For " + curPR.Patient.Person.FullnameWithoutMiddlename),
                                                     "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);

                            if (ReferrerEPCLettersSendingV2.LogDebugEmailInfo)
                            {
                                Logger.LogQuery("C ReferrerEPCLetters_GenerateUnsent -- Email Send Item Done!", false, false, true);
                            }
                        }
                    }
                    else
                    {
                        Letter.FileContents[] fileContentsList = curBooking.GetSystemLettersList(Letter.FileFormat.Word, curBooking.Patient, curHC, curBooking.Offering.Field.ID, curPR.RegisterReferrer.Referrer, true, 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)));

                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:525px;dialogHeight:430px;center:yes;resizable:no; scroll:no";
                string onclick         = "onclick=\"javascript:window.showModalDialog('" + addEditContactListPage + "?entity_type=referrer&id=" + curPR.RegisterReferrer.Organisation.EntityID.ToString() + "', '', '" + allFeatures + "');document.getElementById('" + btnViewList.ClientID + "').click();return false;\"";
                string hrefUpdateEmail = "<u><a style=\"text-decoration: none\" title=\"Edit\" AlternateText=\"Edit\" " + onclick + " href=\"\">Update Clinic Email</a></u>";

                debugOutput += @"<tr>
                                    <td>" + sendMethod + @"</td>
                                    <td style=""white-space:nowrap;"">" + curBooking.BookingID + " &nbsp;&nbsp;&nbsp;[" + curBooking.DateStart.ToString("dd-MM-yyyy") + "&nbsp;&nbsp;&nbsp;" + curBooking.DateStart.ToString("HH:mm") + "-" + curBooking.DateEnd.ToString("HH:mm") + "]" + @"</td>
                                    <td>" + toGenerate + @"</td>
                                    <td>" + curPR.RegisterReferrer.Referrer.Person.FullnameWithoutMiddlename + @"</td>
                                    <td style=""white-space:nowrap;"">" + (curRefHasEmail ? curRefEmail : "Has No Email") + " (" + hrefUpdateEmail + ")" + @"</td>
                                    <td>" + curPR.Patient.Person.FullnameWithoutMiddlename + @"</td>
                                </tr>";
            }

            if (curPR.RegisterReferrer.BatchSendAllPatientsTreatmentNotes)
            {
                regRefIDsToUpdateDateTimeOfLastBatchSend.Add(curPR.RegisterReferrer.RegisterReferrerID);
            }
        }

        RegisterReferrerDB.UpdateLastBatchSendAllPatientsTreatmentNotes((int[])regRefIDsToUpdateDateTimeOfLastBatchSend.ToArray(typeof(int)), DateTime.Now);

        return((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)));
    }
コード例 #16
0
    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());
            }
        }
    }
コード例 #17
0
    protected void GoTo(string db, int orgID, int siteID, int patientID)
    {
        //lblInfo1.Text += "GET<br/>DB: " + db + "<br />Org: " + orgID;

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

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

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

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

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


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

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

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



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


        // Go to booking page with this org

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

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

        else
        {
            Response.Redirect("~/Default.aspx", false);
        }
        return;
    }
コード例 #18
0
    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 ? "&nbsp;[" : "&nbsp;(") + (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        = "&nbsp;PHONE SCRIPT&nbsp;";
            lnkLiveSupport.Style["background-color"] = "#BA9EB0";
            lnkLiveSupport.Style["color"]            = "white";
        }
    }
コード例 #19
0
    protected void Search(string phoneNumberIn = null, string surnameIn = null, string dob_day = null, string dob_month = null, string dob_year = null)
    {
        string phoneNumberSearch = phoneNumberIn == null ? "" : Regex.Replace(phoneNumberIn, "[^0-9]", "");
        string surnameSearch     = surnameIn == null ? "" : surnameIn.Trim();

        if (phoneNumberSearch == "" && surnameSearch == "" && dob_day == "-1" && dob_month == "-1" && dob_year == "-1")
        {
            lblSearchResults.Text = "<font color=\"red\"><br />Please enter a phone number or surname or DOB to search</font>";
            return;
        }


        string curDbName = Session["DB"].ToString();


        ArrayList dbNames = new ArrayList();
        Hashtable dbHash  = new Hashtable();

        string searchResults = string.Empty;

        try
        {
            List <Tuple <string, string> > list = new List <Tuple <string, string> >();


            System.Data.DataTable tbl = DBBase.ExecuteQuery("EXEC sp_databases;", "master").Tables[0];
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                string databaseName = tbl.Rows[i][0].ToString();

                if (!Regex.IsMatch(databaseName, @"Mediclinic_\d{4}"))
                {
                    continue;
                }


                SystemVariables sysVariables = SystemVariableDB.GetAll(databaseName);

                dbNames.Add(sysVariables["Site"].Value);
                dbHash[sysVariables["Site"].Value] = databaseName;


                StringBuilder output = new StringBuilder();

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

                string callCenterPrefix = ((SystemVariables)Session["SystemVariables"])["CallCenterPrefix"].Value;


                string siteName = ((SystemVariables)Session["SystemVariables"])["Site"].Value;

                list.Add(new Tuple <string, string>(((SystemVariables)Session["SystemVariables"])["Site"].Value, output.ToString()));


                Site[] sites          = SiteDB.GetAll();
                int    clinicSiteID   = -1;
                int    agedCareSiteID = -1;
                for (int j = 0; j < sites.Length; j++)
                {
                    if (sites[j].SiteType.ID == 1)
                    {
                        clinicSiteID = sites[j].SiteID;
                    }
                    if (sites[j].SiteType.ID == 2)
                    {
                        agedCareSiteID = sites[j].SiteID;
                    }
                }


                DataTable dt = PatientDB.GetDataTable(false, false, false, false, surnameSearch, true, "", false, "", "", phoneNumberSearch, "", "", false, Convert.ToInt32(dob_day), Convert.ToInt32(dob_month), Convert.ToInt32(dob_year));
                if (dt.Rows.Count > 0)
                {
                    int[] entityIDs  = new int[dt.Rows.Count];
                    int[] patientIDs = new int[dt.Rows.Count];
                    for (int p = 0; p < dt.Rows.Count; p++)
                    {
                        entityIDs[p]  = Convert.ToInt32(dt.Rows[p]["entity_id"]);
                        patientIDs[p] = Convert.ToInt32(dt.Rows[p]["patient_id"]);
                    }
                    Hashtable bullkPhoneNumbers = PatientsContactCacheDB.GetBullkPhoneNumbers(entityIDs, -1);

                    Hashtable ptOrgsHash = RegisterPatientDB.GetMostRecentOrganisationOf(patientIDs);

                    for (int p = 0; p < dt.Rows.Count; p++)
                    {
                        string   ptName   = dt.Rows[p]["firstname"].ToString() + " " + dt.Rows[p]["surname"].ToString();
                        DateTime dob      = dt.Rows[p]["dob"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dt.Rows[p]["dob"]);
                        int      ptID     = Convert.ToInt32(dt.Rows[p]["patient_id"]);
                        int      entityID = Convert.ToInt32(dt.Rows[p]["entity_id"]);

                        Organisation org = ptOrgsHash[ptID] as Organisation;

                        string phoneNbrs = string.Empty;
                        if (bullkPhoneNumbers[entityID] != null)
                        {
                            if (Utilities.GetAddressType().ToString() == "Contact")
                            {
                                foreach (Contact c in ((Contact[])bullkPhoneNumbers[entityID]))
                                {
                                    string phoneNumber = Regex.Replace(c.AddrLine1, "[^0-9]", "");
                                    phoneNbrs += (phoneNbrs.Length == 0 ? string.Empty : "<br />") + Utilities.FormatPhoneNumber(phoneNumber).Replace(" ", "-");
                                }
                            }
                            else if (Utilities.GetAddressType().ToString() == "ContactAus")
                            {
                                foreach (ContactAus c in ((ContactAus[])bullkPhoneNumbers[entityID]))
                                {
                                    string phoneNumber = Regex.Replace(c.AddrLine1, "[^0-9]", "");
                                    if (phoneNumber.StartsWith(phoneNumberSearch))
                                    {
                                        phoneNbrs += (phoneNbrs.Length == 0 ? string.Empty : "<br />") + Utilities.FormatPhoneNumber(phoneNumber).Replace(" ", "-");
                                    }
                                }
                            }
                            else
                            {
                                throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                            }
                        }

                        string orgLink = org == null ? "" : @"<a href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @"&org=" + org.OrganisationID + @"&patient=" + ptID + @""" onclick=""http_post('" + databaseName + "','" + org.OrganisationID + @"','" + (org.IsClinic ? clinicSiteID : agedCareSiteID) + @"'," + ptID + @");return false;"">" + org.Name + @"</a>";
                        string ptLink  = @"<a href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @"&org=0" + @"&patient=" + ptID + @""" onclick=""http_post('" + databaseName + "','" + "0" + @"','" + clinicSiteID + @"'," + ptID + @");return false;"">" + ptName + @"</a>";

                        output.AppendLine("<tr><td>" + siteName + "</td><td>" + ptLink + "</td><td>" + orgLink + "</td><td style=\"white-space:nowrap\">" + (dob == DateTime.MinValue ? "" : dob.ToString("d MMM, yyyy")) + "</td>" + (phoneNumberSearch == null ? "" : "<td>" + phoneNbrs + "</td>") + "</tr>");
                    }
                }


                list.Add(new Tuple <string, string>(((SystemVariables)Session["SystemVariables"])["Site"].Value, output.ToString()));

                Session.Remove("DB");
                Session.Remove("SystemVariables");
            }



            list.Sort((a, b) => a.Item1.CompareTo(b.Item1));
            System.Text.StringBuilder finalOutput = new System.Text.StringBuilder();
            foreach (Tuple <string, string> item in list)
            {
                finalOutput.Append(item.Item2);
            }


            if (finalOutput.Length == 0)
            {
                lblSearchResults.Text = "<font color=\"red\"><br />No patient found with the search parameters entered</font>";
            }
            else
            {
                lblSearchResults.Text = @"<br />
<table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-normal auto_width block_center"">
  <tr>
    <th>Site</th>
    <th>Patient</th>
    <th>Book</th>
    <th>D.O.B</th>
    " + (phoneNumberSearch == null ? "" : "<th>Phone Nbr</th>") + @"  
  </tr>
" + finalOutput.ToString() + "</table>";
            }
        }
        finally
        {
            Session["DB"] = curDbName;
            Session["SystemVariables"] = SystemVariableDB.GetAll();
        }
    }
コード例 #20
0
    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> &nbsp;&nbsp; [with mobile: <b>" + messagesToSMS.Count + "</b>] &nbsp;&nbsp; [with email: <b>" + messagesToEmail.Count + "</b>] " + "<br /><br />" + output);
        }
        else
        {
            return(string.Empty);
        }
    }