Ejemplo n.º 1
0
    // used when adding new EPC
    //
    // often the user will add a new referrer and THEN add a new EPC card
    // so we need to get the referrer that was in the system yesterday to send last EPC letters.
    public static PatientReferrer GetMostRecentlyAddedBeforeToday(int patient_id, PatientReferrer[] patientReferrers)
    {
        PatientReferrer patRefMostRecentBeforeToday = null;

        if (patientReferrers.Length > 0)
        {
            for (int i = patientReferrers.Length - 1; i >= 0; i--)
            {
                //if (patientReferrers[i].PatientReferrerDateAdded >= DateTime.Today)
                //    continue;

                if (patRefMostRecentBeforeToday == null || patientReferrers[i].PatientReferrerDateAdded > patRefMostRecentBeforeToday.PatientReferrerDateAdded)
                {
                    patRefMostRecentBeforeToday = patientReferrers[i];
                }

                else if (patientReferrers[i].PatientReferrerDateAdded == patRefMostRecentBeforeToday.PatientReferrerDateAdded &&
                         patientReferrers[i].PatientReferrerID > patRefMostRecentBeforeToday.PatientReferrerID)
                {
                    patRefMostRecentBeforeToday = patientReferrers[i];
                }
            }
        }

        return(patRefMostRecentBeforeToday);
    }
Ejemplo n.º 2
0
    protected Tuple <Booking, PatientReferrer, bool, string, HealthCard> LoadRow(DataRow row)
    {
        Booking booking = BookingDB.Load(row, "booking_", true, false);

        booking.Offering = OfferingDB.Load(row, "offering_");

        PatientReferrer pr = PatientReferrerDB.Load(row, "pr_");

        pr.RegisterReferrer                       = RegisterReferrerDB.Load(row, "regref_");
        pr.RegisterReferrer.Referrer              = ReferrerDB.Load(row, "referrer_");
        pr.RegisterReferrer.Referrer.Person       = PersonDB.Load(row, "referrer_person_");
        pr.RegisterReferrer.Referrer.Person.Title = IDandDescrDB.Load(row, "referrer_person_title_title_id", "referrer_person_title_descr");
        if (row["organisation_organisation_id"] != DBNull.Value)
        {
            pr.RegisterReferrer.Organisation = OrganisationDB.Load(row, "organisation_");
        }
        pr.Patient              = PatientDB.Load(row, "patient_");
        pr.Patient.Person       = PersonDB.Load(row, "patient_person_");
        pr.Patient.Person.Title = IDandDescrDB.Load(row, "patient_person_title_title_id", "patient_person_title_descr");

        bool   refHasEmail = Convert.ToInt32(row["ref_has_email"]) == 1;
        string refEmail    = row["ref_email"] == DBNull.Value ? null : Convert.ToString(row["ref_email"]);

        HealthCard hc = HealthCardDB.Load(row, "hc_");

        return(new Tuple <Booking, PatientReferrer, bool, string, HealthCard>(booking, pr, refHasEmail, refEmail, hc));
    }
Ejemplo n.º 3
0
    // hashtable: register_referrer_id => PatientReferrer[]
    public static Hashtable GetHashtableByRegRef(bool onlyActive, bool show_deleted = false, bool show_deceased = false)
    {
        Hashtable hash = new Hashtable();

        DataTable dt = GetDataTable(onlyActive, show_deleted, show_deceased);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            PatientReferrer pr = LoadAll(dt.Rows[i]);

            if (hash[pr.RegisterReferrer.RegisterReferrerID] == null)
            {
                hash[pr.RegisterReferrer.RegisterReferrerID] = new ArrayList();
            }
            ((ArrayList)hash[pr.RegisterReferrer.RegisterReferrerID]).Add(pr);
        }

        // convert from arraylists to arrays
        ArrayList keys = new ArrayList();

        foreach (System.Collections.DictionaryEntry de in hash)
        {
            keys.Add(de.Key);
        }
        foreach (int key in keys)
        {
            hash[key] = (PatientReferrer[])((ArrayList)hash[key]).ToArray(typeof(PatientReferrer));
        }
        ;

        return(hash);
    }
Ejemplo n.º 4
0
    public static PatientReferrer GetByID(int patient_referrer_id)
    {
        //string sql = "SELECT patient_referrer_id,patient_id,register_referrer_id,patient_referrer_date_added,is_debtor,is_active FROM PatientReferrer WHERE patient_referrer_id = " + patient_referrer_id.ToString();
        string    sql = JoinedSQL() + " AND patient_referrer_id = " + patient_referrer_id.ToString();
        DataTable tbl = DBBase.ExecuteQuery(sql).Tables[0];

        if (tbl.Rows.Count == 0)
        {
            return(null);
        }
        else
        {
            PatientReferrer pr = Load(tbl.Rows[0]);
            pr.Patient              = PatientDB.Load(tbl.Rows[0]);
            pr.Patient.Person       = PersonDB.Load(tbl.Rows[0], "patient_person_");
            pr.Patient.Person.Title = IDandDescrDB.Load(tbl.Rows[0], "patient_person_title_title_id", "patient_person_title_descr");

            if (tbl.Rows[0]["pr_register_referrer_id"] != DBNull.Value)
            {
                pr.RegisterReferrer                       = RegisterReferrerDB.Load(tbl.Rows[0]);
                pr.RegisterReferrer.Referrer              = ReferrerDB.Load(tbl.Rows[0]);
                pr.RegisterReferrer.Referrer.Person       = PersonDB.Load(tbl.Rows[0], "referrer_person_");
                pr.RegisterReferrer.Referrer.Person.Title = IDandDescrDB.Load(tbl.Rows[0], "referrer_person_title_title_id", "referrer_person_title_descr");
                pr.RegisterReferrer.Organisation          = OrganisationDB.Load(tbl.Rows[0], "organisation_");
            }
            if (tbl.Rows[0]["pr_organisation_id"] != DBNull.Value)
            {
                pr.Organisation = OrganisationDB.Load(tbl.Rows[0], "nonepcorg_");
            }

            return(pr);
        }
    }
    protected void btnChangeToEditMode_Click(object sender, EventArgs e)
    {
        // dont allow editing

        displayHaveReferrerRow.Visible = false;
        editRow.Visible             = true;
        newReferrersLinkRow.Visible = true;

        PatientReferrer[] patientReferrer       = PatientReferrerDB.GetEPCPatientReferrersOf(this.PatientID);
        PatientReferrer   currentPatRegReferrer = patientReferrer[patientReferrer.Length - 1];

        setReferrersList(currentPatRegReferrer);
    }
Ejemplo n.º 6
0
    protected Tuple <string, string, string, string> GetReferrersEmail()
    {
        if (!IsValidFormID())
        {
            return(null);
        }

        Booking booking = BookingDB.GetByEntityID(GetFormID());

        if (booking == null || booking.Patient == null)
        {
            return(null);
        }

        PatientReferrer[] patientReferrer = PatientReferrerDB.GetActiveEPCPatientReferrersOf(booking.Patient.PatientID);
        if (patientReferrer.Length == 0)
        {
            return(null);
        }

        PatientReferrer  currentPatRegReferrer = patientReferrer[patientReferrer.Length - 1];
        RegisterReferrer curRegReferrer        = currentPatRegReferrer.RegisterReferrer;

        //string refName = curRegReferrer.Referrer.Person.Surname + ", " + curRegReferrer.Referrer.Person.Firstname + " [" + curRegReferrer.Organisation.Name + "]" + " [" + currentPatRegReferrer.PatientReferrerDateAdded.ToString("dd-MM-yyyy") + "]";
        //SetErrorMessage("Name: " + refName);

        string[] emails = ContactDB.GetEmailsByEntityID(currentPatRegReferrer.RegisterReferrer.Organisation.EntityID);
        if (emails.Length == 0)
        {
            return(null);
        }

        string refEmail           = string.Join(",", emails);
        string refName            = (curRegReferrer.Referrer.Person.Title.ID == 0 ? "Dr." : curRegReferrer.Referrer.Person.Title.Descr) + " " + curRegReferrer.Referrer.Person.Surname;
        string bookingOrg         = booking.Organisation.Name;
        string bookingPatientName = booking.Patient.Person.FullnameWithoutMiddlename;

        return(new Tuple <string, string, string, string>(refEmail, refName, bookingOrg, bookingPatientName));
    }
Ejemplo n.º 7
0
    public static PatientReferrer LoadAll(DataRow row)
    {
        PatientReferrer pr = PatientReferrerDB.Load(row, "pr_");

        pr.RegisterReferrer                       = RegisterReferrerDB.Load(row, "regref_");
        pr.RegisterReferrer.Referrer              = ReferrerDB.Load(row, "referrer_");
        pr.RegisterReferrer.Referrer.Person       = PersonDB.Load(row, "referrer_person_");
        pr.RegisterReferrer.Referrer.Person.Title = IDandDescrDB.Load(row, "referrer_person_title_title_id", "referrer_person_title_descr");
        if (row["organisation_organisation_id"] != DBNull.Value)
        {
            pr.RegisterReferrer.Organisation = OrganisationDB.Load(row, "organisation_");
        }
        pr.Patient              = PatientDB.Load(row, "patient_");
        pr.Patient.Person       = PersonDB.Load(row, "patient_person_");
        pr.Patient.Person.Title = IDandDescrDB.Load(row, "patient_person_title_title_id", "patient_person_title_descr");
        if (row["nonepcorg_entity_id"] != DBNull.Value)
        {
            pr.Organisation = OrganisationDB.Load(row, "nonepcorg_");
        }

        return(pr);
    }
    protected void SetOrUpdateReferrer(int newRegisterReferrerID)
    {
        // if change this back to  " = PatientReferrerDB.GetEPCPatientReferrersOf(patient.PatientID); "  then make sure go through whole list
        PatientReferrer[] patientReferrer = PatientReferrerDB.GetActiveEPCPatientReferrersOf(this.PatientID);
        if (patientReferrer.Length > 0)
        {
            PatientReferrer  currentPatRegReferrer = patientReferrer[patientReferrer.Length - 1];
            RegisterReferrer curRegReferrer        = currentPatRegReferrer.RegisterReferrer;

            if (curRegReferrer.RegisterReferrerID == newRegisterReferrerID)
            {
                return;
            }
            else
            {
                PatientReferrerDB.UpdateSetInactive(currentPatRegReferrer.PatientReferrerID);
            }
        }

        PatientReferrerDB.Insert(this.PatientID, newRegisterReferrerID, 0, false);
        InitForm();
    }
Ejemplo n.º 9
0
    private static PatientReferrer[] _GetEPCPatientReferrersOf(int patient_id, bool onlyActive)
    {
        DataTable tbl = onlyActive ? GetDataTable_ActiveEPCReferrersOf(patient_id) : GetDataTable_EPCReferrersOf(patient_id);

        PatientReferrer[] list = new PatientReferrer[tbl.Rows.Count];
        for (int i = 0; i < tbl.Rows.Count; i++)
        {
            PatientReferrer pr = Load(tbl.Rows[i], "pr_");
            pr.RegisterReferrer                       = RegisterReferrerDB.Load(tbl.Rows[i], "regref_");
            pr.RegisterReferrer.Referrer              = ReferrerDB.Load(tbl.Rows[i], "referrer_");
            pr.RegisterReferrer.Referrer.Person       = PersonDB.Load(tbl.Rows[i], "referrer_person_");
            pr.RegisterReferrer.Referrer.Person.Title = IDandDescrDB.Load(tbl.Rows[i], "referrer_person_title_title_id", "referrer_person_title_descr");
            if (tbl.Rows[i]["organisation_organisation_id"] != DBNull.Value)
            {
                pr.RegisterReferrer.Organisation = OrganisationDB.Load(tbl.Rows[i], "organisation_");
            }
            pr.Patient              = PatientDB.Load(tbl.Rows[i], "patient_");
            pr.Patient.Person       = PersonDB.Load(tbl.Rows[i], "patient_person_");
            pr.Patient.Person.Title = IDandDescrDB.Load(tbl.Rows[i], "patient_person_title_title_id", "patient_person_title_descr");
            list[i] = pr;
        }
        return(list);
    }
Ejemplo n.º 10
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());
        }
    }
Ejemplo n.º 11
0
 private static PatientReferrer[] _GetEPCPatientReferrersOf(int patient_id, bool onlyActive)
 {
     DataTable tbl = onlyActive ? GetDataTable_ActiveEPCReferrersOf(patient_id) : GetDataTable_EPCReferrersOf(patient_id);
     PatientReferrer[] list = new PatientReferrer[tbl.Rows.Count];
     for (int i = 0; i < tbl.Rows.Count; i++)
     {
         PatientReferrer pr = Load(tbl.Rows[i], "pr_");
         pr.RegisterReferrer = RegisterReferrerDB.Load(tbl.Rows[i], "regref_");
         pr.RegisterReferrer.Referrer = ReferrerDB.Load(tbl.Rows[i], "referrer_");
         pr.RegisterReferrer.Referrer.Person = PersonDB.Load(tbl.Rows[i], "referrer_person_");
         pr.RegisterReferrer.Referrer.Person.Title = IDandDescrDB.Load(tbl.Rows[i], "referrer_person_title_title_id", "referrer_person_title_descr");
         if (tbl.Rows[i]["organisation_organisation_id"] != DBNull.Value)
             pr.RegisterReferrer.Organisation = OrganisationDB.Load(tbl.Rows[i], "organisation_");
         pr.Patient = PatientDB.Load(tbl.Rows[i], "patient_");
         pr.Patient.Person = PersonDB.Load(tbl.Rows[i], "patient_person_");
         pr.Patient.Person.Title = IDandDescrDB.Load(tbl.Rows[i], "patient_person_title_title_id", "patient_person_title_descr");
         list[i] = pr;
     }
     return list;
 }
Ejemplo n.º 12
0
    // used when adding new EPC
    //
    // often the user will add a new referrer and THEN add a new EPC card
    // so we need to get the referrer that was in the system yesterday to send last EPC letters.
    public static PatientReferrer GetMostRecentlyAddedBeforeToday(int patient_id, PatientReferrer[] patientReferrers)
    {
        PatientReferrer patRefMostRecentBeforeToday = null;

        if (patientReferrers.Length > 0)
        {
            for (int i = patientReferrers.Length - 1; i >= 0; i--)
            {
                //if (patientReferrers[i].PatientReferrerDateAdded >= DateTime.Today)
                //    continue;

                if (patRefMostRecentBeforeToday == null || patientReferrers[i].PatientReferrerDateAdded > patRefMostRecentBeforeToday.PatientReferrerDateAdded)
                    patRefMostRecentBeforeToday = patientReferrers[i];

                else if (patientReferrers[i].PatientReferrerDateAdded == patRefMostRecentBeforeToday.PatientReferrerDateAdded &&
                         patientReferrers[i].PatientReferrerID        >  patRefMostRecentBeforeToday.PatientReferrerID)
                    patRefMostRecentBeforeToday = patientReferrers[i];
            }
        }

        return patRefMostRecentBeforeToday;
    }
    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);
    }
Ejemplo n.º 14
0
    public PatientReferrer GetPatient(long PatientID)
    {
        dl = new DataLayer();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "Portal_GetPatient";
        cmd.Parameters.AddWithValue("@PatientID", PatientID);

        DataTable dt = dl.Execute(cmd);

        foreach (DataRow dr in dt.Rows)
        {
            PatientReferrer patientReferrer = new PatientReferrer
            {
                ID = Int64.Parse(dr["ID"].ToString()),
                Guid = Guid.Parse(dr["PatientGUID"].ToString()),
                FirstName = dr["FirstName"].ToString(),
                LastName = dr["LastName"].ToString(),
                Gender = dr["Gender"].ToString(),
                DateOfBirth = Convert.ToDateTime(dr["DateOfBirth"].ToString()),
                ReferralDate = Convert.ToDateTime(dr["ReferralDate"].ToString()),
                Ethnicity = dr["Ethnicity"].ToString(),
                MedicaidNumber = dr["MedicaidNumber"].ToString(),
                SocialSecurityNumber = dr["SocialSecurityNumber"].ToString(),
                ResidingWithName = dr["ResidingWithName"].ToString(),
                ResidingWithRelationship = dr["ResidingWithRelationship"].ToString(),
                SchoolName = dr["SchoolName"].ToString(),
                SchoolGrade = dr["SchoolGrade"].ToString(),
                SchoolPhone = dr["SchoolPhone"].ToString(),
                EmployerName = dr["EmployerName"].ToString(),
                Occupation = dr["Occupation"].ToString(),
                ClientOnProbation = bool.Parse(dr["ClientOnProbation"].ToString()),
                EmailAddress = dr["EmailAddress"].ToString(),
                Diagnosis = dr["Diagnosis"].ToString(),
                ServiceRequested = dr["ServiceRequested"].ToString(),
                LocationofServices = dr["LocationofServices"].ToString(),
                FinanciallyResponsiblePerson = dr["FinanciallyResponsiblePerson"].ToString(),
                DateCreated = Convert.ToDateTime(dr["PatientDateCreated"].ToString()),
                CreatedBy = dr["PatientCreatedBy"].ToString(),
                LastUpdated = Convert.ToDateTime(dr["PatientLastUpdated"].ToString()),
                LastUpdatedBy = dr["PatientLastUpdatedBy"].ToString(),
                PaymentMethod = dr["PaymentMethod"].ToString(),
                PatientStreet = dr["PatientStreet"].ToString(),
                PatientSuite = dr["PatientSuite"].ToString(),
                PatientCity = dr["PatientCity"].ToString(),
                PatientState = dr["PatientState"].ToString(),
                PatientZipCode = dr["PatientZipCode"].ToString(),
                PatientCountry = dr["PatientCountry"].ToString(),
                SchoolPhoneType = dr["SchoolPhoneType"].ToString(),
                PresentingConcerns = dr["PresentingConcerns"].ToString(),
                LegalGuardian = dr["LegalGuardian"].ToString(),
                ReferralSourceName = dr["ReferralSourceName"].ToString(),
                ReferralSourceAgency = dr["ReferralSourceAgency"].ToString(),
                ReferrerPhone = dr["ReferrerPhone"].ToString(),
                ReferralFax = dr["ReferralFax"].ToString(),
                ReferralStreet = dr["ReferrerStreet"].ToString(),
                ReferralCity = dr["ReferrerCity"].ToString(),
                ReferraCountry = dr["ReferrerCountry"].ToString(),
                ReferralZipCode = dr["ReferrerZipCode"].ToString(),
                ReferralState = dr["ReferrerState"].ToString(),
                ReferralSuite = dr["ReferrerSuite"].ToString(),
                ReferrerPhoneType = dr["ReferrerPhoneType"].ToString(),

            };

            return patientReferrer;

        }

        return null;
    }
    protected void setReferrersList(PatientReferrer currentPatRegReferrer = null)
    {
        if (currentPatRegReferrer == null)
        {
            PatientReferrer[] patientReferrer = PatientReferrerDB.GetEPCPatientReferrersOf(this.PatientID);
            if (patientReferrer.Length > 0)
            {
                currentPatRegReferrer = patientReferrer[patientReferrer.Length - 1];
            }
        }

        int nItems = ddlReferrer.Items.Count;

        for (int i = 0; i < nItems; i++)
        {
            ddlReferrer.Items.RemoveAt(0);
        }

        DataTable rr = RegisterReferrerDB.GetDataTable(0, -1, false, new int[] { 191 });

        if (currentPatRegReferrer != null)
        {
            // if refererrer set as inactive (ie user set as deleted, but is still in system)
            // then it will show the referrer as his referrer, but when hitting update, the list will not contain it, and throws an error
            // so if set as inactive (deleted), then add to the list
            bool isDeletedReferrer = rr.Select("register_referrer_id=" + currentPatRegReferrer.RegisterReferrer.RegisterReferrerID).Length == 0;
            if (isDeletedReferrer)
            {
                DataRow newRow = rr.NewRow();
                newRow["surname"]              = currentPatRegReferrer.RegisterReferrer.Referrer.Person.Surname;
                newRow["firstname"]            = currentPatRegReferrer.RegisterReferrer.Referrer.Person.Firstname;
                newRow["middlename"]           = currentPatRegReferrer.RegisterReferrer.Referrer.Person.Middlename;
                newRow["name"]                 = currentPatRegReferrer.RegisterReferrer.Organisation.Name;
                newRow["register_referrer_id"] = currentPatRegReferrer.RegisterReferrer.RegisterReferrerID;

                bool inserted = false;
                for (int i = rr.Rows.Count - 1; i >= 0; i--)
                {
                    if (currentPatRegReferrer.RegisterReferrer.Referrer.Person.Surname.CompareTo(rr.Rows[i]["surname"].ToString()) < 0)
                    {
                        continue;
                    }
                    if (currentPatRegReferrer.RegisterReferrer.Referrer.Person.Surname.CompareTo(rr.Rows[i]["surname"].ToString()) == 0)
                    {
                        if (currentPatRegReferrer.RegisterReferrer.Referrer.Person.Firstname.CompareTo(rr.Rows[i]["firstname"].ToString()) < 0)
                        {
                            continue;
                        }
                        if (currentPatRegReferrer.RegisterReferrer.Referrer.Person.Middlename.CompareTo(rr.Rows[i]["surname"].ToString()) == 0)
                        {
                            if (currentPatRegReferrer.RegisterReferrer.Referrer.Person.Firstname.CompareTo(rr.Rows[i]["middlename"].ToString()) < 0)
                            {
                                continue;
                            }
                        }
                    }

                    // now insert before this one

                    if (i == rr.Rows.Count)
                    {
                        rr.Rows.Add(newRow);
                    }
                    else
                    {
                        rr.Rows.InsertAt(newRow, i + 1);
                    }

                    inserted = true;
                    break;
                }

                if (!inserted)
                {
                    if (rr.Rows.Count == 0)
                    {
                        rr.Rows.Add(newRow);
                    }
                    else
                    {
                        rr.Rows.InsertAt(newRow, 0);
                    }
                }
            }
        }
        foreach (DataRowView row in rr.DefaultView)
        {
            ddlReferrer.Items.Add(new ListItem(row["surname"].ToString() + ", " + row["firstname"].ToString() + " [" + row["name"].ToString() + "]", row["register_referrer_id"].ToString()));
        }

        if (currentPatRegReferrer != null)
        {
            ddlReferrer.SelectedValue = currentPatRegReferrer.RegisterReferrer.RegisterReferrerID.ToString();
        }
    }
    protected void InitForm(int patientID)
    {
        HideAllRows();

        string url     = "/PatientReferrerHistoryPopupV2.aspx?id=" + patientID;
        string text    = "History";
        string onclick = @"onclick=""open_new_tab('" + url + @"');return false;""";

        lblPatientReferrerHistoryPopup.Text = "<a " + onclick + " href=\"\">" + text + "</a>";


        PatientReferrer[] patientReferrer = PatientReferrerDB.GetActiveEPCPatientReferrersOf(patientID);  // = PatientReferrerDB.GetEPCPatientReferrersOf(patient.PatientID);
        if (patientReferrer.Length > 0)
        {
            PatientReferrer  currentPatRegReferrer = patientReferrer[patientReferrer.Length - 1]; // get latest
            RegisterReferrer curRegReferrer        = currentPatRegReferrer.RegisterReferrer;

            displayHaveReferrerRow.Visible = true;

            // only allow removing a referrer if no EPC set [ie no active healthcard, or healthcard with neither date set]
            HealthCard hc          = HealthCardDB.GetActiveByPatientID(patientID);
            bool       allowDelete = hc == null || !hc.HasEPC();
            btnDelete.Visible = allowDelete;
            lblDeleteRegistrationReferrerBtnSeperator.Visible = allowDelete;

            //lblReferrer.Text = curRegReferrer.Referrer.Person.Surname + ", " + curRegReferrer.Referrer.Person.Firstname + " [" + curRegReferrer.Organisation.Name + "]" + " [" + currentPatRegReferrer.PatientReferrerDateAdded.ToString("dd-MM-yyyy") + "]";

            string phNumTxt = string.Empty;

            if (Utilities.GetAddressType().ToString() == "Contact")
            {
                Contact[] phNums = ContactDB.GetByEntityID(2, curRegReferrer.Organisation.EntityID);
                for (int i = 0; i < phNums.Length; i++)
                {
                    phNumTxt += (i > 0 ? "<br />" : "") + Utilities.FormatPhoneNumber(phNums[i].AddrLine1) + " &nbsp;&nbsp; (" + phNums[i].ContactType.Descr + ")";
                }
            }
            else if (Utilities.GetAddressType().ToString() == "ContactAus")
            {
                ContactAus[] phNums = ContactAusDB.GetByEntityID(2, curRegReferrer.Organisation.EntityID);
                for (int i = 0; i < phNums.Length; i++)
                {
                    phNumTxt += (i > 0 ? "<br />" : "") + Utilities.FormatPhoneNumber(phNums[i].AddrLine1) + " &nbsp;&nbsp; (" + phNums[i].ContactType.Descr + ")";
                }
            }
            else
            {
                throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
            }

            lblReferrer.Text = curRegReferrer.Referrer.Person.Surname + ", " + curRegReferrer.Referrer.Person.Firstname + (curRegReferrer.Organisation.Name.Length == 0 ? "" : " [" + curRegReferrer.Organisation.Name + "]") + "<br />" + Environment.NewLine +
                               "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" + Environment.NewLine +
                               "<tr><td>" + "Provider Nbr:" + "</td><td style=\"width:12px\"></td><td><font color=\"#A52A2A\">" + currentPatRegReferrer.RegisterReferrer.ProviderNumber + "</font></td></tr>" + Environment.NewLine +
                               "<tr><td>" + "Date Added:" + "</td><td style=\"width:12px\"></td><td><font color=\"#A52A2A\">" + currentPatRegReferrer.PatientReferrerDateAdded.ToString("dd-MM-yyyy") + "</font></td></tr>" + Environment.NewLine +
                               "</table>" + Environment.NewLine +
                               (phNumTxt.Length == 0 ? "" : phNumTxt + "<br />"); // put in referrers fax and phone numbers

            lblReferrerRegisterID.Text = curRegReferrer.RegisterReferrerID.ToString();
        }
        else
        {
            displayNoReferrerRow.Visible = true;
        }
    }
    protected void setReferrersList(PatientReferrer currentPatRegReferrer = null)
    {
        if (currentPatRegReferrer == null)
        {
            PatientReferrer[] patientReferrer = PatientReferrerDB.GetEPCPatientReferrersOf(this.PatientID);
            if (patientReferrer.Length > 0)
                currentPatRegReferrer = patientReferrer[patientReferrer.Length - 1];
        }

        int nItems = ddlReferrer.Items.Count;
        for (int i = 0; i < nItems; i++)
            ddlReferrer.Items.RemoveAt(0);

        DataTable rr = RegisterReferrerDB.GetDataTable(0, -1, false, new int[] { 191 });
        if (currentPatRegReferrer != null)
        {
            // if refererrer set as inactive (ie user set as deleted, but is still in system)
            // then it will show the referrer as his referrer, but when hitting update, the list will not contain it, and throws an error
            // so if set as inactive (deleted), then add to the list
            bool isDeletedReferrer = rr.Select("register_referrer_id=" + currentPatRegReferrer.RegisterReferrer.RegisterReferrerID).Length == 0;
            if (isDeletedReferrer)
            {
                DataRow newRow = rr.NewRow();
                newRow["surname"]              = currentPatRegReferrer.RegisterReferrer.Referrer.Person.Surname;
                newRow["firstname"]            = currentPatRegReferrer.RegisterReferrer.Referrer.Person.Firstname;
                newRow["middlename"]           = currentPatRegReferrer.RegisterReferrer.Referrer.Person.Middlename;
                newRow["name"]                 = currentPatRegReferrer.RegisterReferrer.Organisation.Name;
                newRow["register_referrer_id"] = currentPatRegReferrer.RegisterReferrer.RegisterReferrerID;

                bool inserted = false;
                for (int i = rr.Rows.Count - 1; i >= 0; i--)
                {
                    if (currentPatRegReferrer.RegisterReferrer.Referrer.Person.Surname.CompareTo(rr.Rows[i]["surname"].ToString()) < 0)
                        continue;
                    if (currentPatRegReferrer.RegisterReferrer.Referrer.Person.Surname.CompareTo(rr.Rows[i]["surname"].ToString()) == 0)
                    {
                        if (currentPatRegReferrer.RegisterReferrer.Referrer.Person.Firstname.CompareTo(rr.Rows[i]["firstname"].ToString()) < 0)
                            continue;
                        if (currentPatRegReferrer.RegisterReferrer.Referrer.Person.Middlename.CompareTo(rr.Rows[i]["surname"].ToString()) == 0)
                        {
                            if (currentPatRegReferrer.RegisterReferrer.Referrer.Person.Firstname.CompareTo(rr.Rows[i]["middlename"].ToString()) < 0)
                                continue;
                        }
                    }

                    // now insert before this one

                    if (i == rr.Rows.Count)
                        rr.Rows.Add(newRow);
                    else
                        rr.Rows.InsertAt(newRow, i+1);

                    inserted = true;
                    break;
                }

                if (!inserted)
                {
                    if (rr.Rows.Count == 0)
                        rr.Rows.Add(newRow);
                    else
                        rr.Rows.InsertAt(newRow, 0);
                }
            }
        }
        foreach (DataRowView row in rr.DefaultView)
            ddlReferrer.Items.Add(new ListItem(row["surname"].ToString() + ", " + row["firstname"].ToString() + " [" + row["name"].ToString() + "]", row["register_referrer_id"].ToString()));

        if (currentPatRegReferrer != null)
            ddlReferrer.SelectedValue = currentPatRegReferrer.RegisterReferrer.RegisterReferrerID.ToString();
    }
Ejemplo n.º 18
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)));
    }
    protected void Run(bool viewListOnly)
    {
        bool debugMode = true;

        int bulkLetterSendingQueueBatchID = !viewListOnly && UseBulkLetterSender?BulkLetterSendingQueueBatchDB.Insert(DebugEmail, false) : -1;

        //
        //  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
        //
        //  just remember to process the emails first ... so if any interruptions/errors ... at least some will have been processed
        //



        try
        {
            bool AutoSendFaxesAsEmailsIfNoEmailExistsToGPs = Convert.ToInt32(SystemVariableDB.GetByDescr("AutoSendFaxesAsEmailsIfNoEmailExistsToGPs").Value) == 1;

            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;



            // NB.
            // start/emd date time __must__ refer to the treatment date because
            // as a letter can be generated any time (days or weeks) after a treatment, there is no way
            // to be sure which invoice it is attached to, only which booking
            if (txtStartDate.Text.Length > 0 && !Utilities.IsValidDate(txtStartDate.Text, "dd-mm-yyyy"))
            {
                throw new CustomMessageException("Start date must be empty or valid and of the format dd-mm-yyyy");
            }
            if (txtEndDate.Text.Length > 0 && !Utilities.IsValidDate(txtEndDate.Text, "dd-mm-yyyy"))
            {
                throw new CustomMessageException("End date must be empty or valid and of the format dd-mm-yyyy");
            }
            DateTime startDate = txtStartDate.Text.Length == 0 ? DateTime.MinValue : Utilities.GetDate(txtStartDate.Text, "dd-mm-yyyy");
            DateTime endDate   = txtEndDate.Text.Length == 0 ? DateTime.MinValue : Utilities.GetDate(txtEndDate.Text, "dd-mm-yyyy");


            DataTable bookingsWithSentLetters = BookingDB.GetBookingsWithEPCLetters(startDate, endDate, Convert.ToInt32(registerReferrerID.Value), Convert.ToInt32(patientID.Value), true, false);

            if (!viewListOnly && bookingsWithSentLetters.Rows.Count > MaxSending)
            {
                throw new CustomMessageException("Can not generate more than " + MaxSending + " letters at a time. Please narrow your date range.");
            }

            double queryExecutionTime = (double)(Environment.TickCount - startTime) / 1000.0;
            startTime = Environment.TickCount;


            ArrayList filesToPrint = new ArrayList();

            int       currentRegReferrerID       = -1;
            ArrayList bookingsForCurrentReferrer = new ArrayList();
            foreach (DataRow row in bookingsWithSentLetters.Rows)
            {
                Tuple <Booking, PatientReferrer, bool, bool, HealthCard> rowData = LoadRow(row);
                Booking         booking     = rowData.Item1;
                PatientReferrer pr          = rowData.Item2;
                bool            refHasEmail = rowData.Item3;
                bool            refHasFax   = rowData.Item4;
                HealthCard      hc          = rowData.Item5;


                if (pr.RegisterReferrer.RegisterReferrerID != currentRegReferrerID)
                {
                    filesToPrint.AddRange(ProcessReferrersLetters(viewListOnly, bookingsForCurrentReferrer, AutoSendFaxesAsEmailsIfNoEmailExistsToGPs, ref debugOutput, bulkLetterSendingQueueBatchID));
                    currentRegReferrerID       = pr.RegisterReferrer.RegisterReferrerID;
                    bookingsForCurrentReferrer = new ArrayList();
                }

                bookingsForCurrentReferrer.Add(rowData);
            }

            // process last group
            filesToPrint.AddRange(ProcessReferrersLetters(viewListOnly, bookingsForCurrentReferrer, AutoSendFaxesAsEmailsIfNoEmailExistsToGPs, ref debugOutput, bulkLetterSendingQueueBatchID));



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


            double restExecutionTime = (double)(Environment.TickCount - startTime) / 1000.0;

            if (debugMode)
            {
                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>" + bookingsWithSentLetters.Rows.Count + @"</td><td style=""width:25px;""></td><td><b>Runing Time</b></td><td style=""width:10px;""></td><td>" + restExecutionTime + @" seconds</td></tr>
                                 </table>";
                }

                string countShowing = bookingsWithSentLetters.Rows.Count > MaxSending ? bookingsWithSentLetters.Rows.Count + " showing to re-generate. <br /><font color=red>* You can not generate more than 175 at a time. Please narrow your search before printing.</font>" : bookingsWithSentLetters.Rows.Count.ToString();
                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>";
                }


                if (viewListOnly)
                {
                    lblList.Text = @"<table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" cellpadding=""4"" border=""1"">
                                        <tr>
                                            <th style=""white-space:nowrap;"">Send By</th>
                                            <th>Booking</th>
                                            <th>Generate</th>
                                            <th>Referrer</th>
                                            <th>Email</th>
                                            <th>Fax</th>
                                            <th>Patient</th>
                                        </tr>" +
                                   (debugOutput.Length == 0 ? "<tr><td colspan=\"7\">No Rows</td></tr>" : debugOutput) +
                                   "</table>";
                }
            }
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
        }
        catch (Exception ex)
        {
            SetErrorMessage("", ex.ToString());
        }
    }
    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)));
    }