protected static Tuple <BookingPatient, Offering, PatientReferrer, bool, string, string, HealthCard> LoadAgedCareRow(DataRow row)
    {
        BookingPatient bp = BookingPatientDB.Load(row, "bp_");

        bp.Booking                = BookingDB.Load(row, "booking_", false, false);
        bp.Booking.Patient        = PatientDB.Load(row, "patient_");
        bp.Booking.Patient.Person = PersonDB.Load(row, "patient_person_");


        Offering 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"]);

        if (UseDebugEmail)
        {
            refEmail = DebugEmail;
        }
        string refFax = row["ref_fax"] == DBNull.Value ? null : Convert.ToString(row["ref_fax"]);

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

        return(new Tuple <BookingPatient, Offering, PatientReferrer, bool, string, string, HealthCard>(bp, offering, pr, refHasEmail, refEmail, refFax, hc));
    }
    protected void SetBooking()
    {
        string booking_patient_id = Request.QueryString["bookingpatient"];
        string booking_id         = Request.QueryString["booking"];

        if (booking_patient_id != null)
        {
            if (!Regex.IsMatch(booking_patient_id, @"^\d+$"))
            {
                throw new CustomMessageException();
            }

            BookingPatient bookingPatient = BookingPatientDB.GetByID(Convert.ToInt32(booking_patient_id));
            if (bookingPatient == null)
            {
                throw new CustomMessageException();
            }
            if (bookingPatient.Booking.Organisation == null)
            {
                throw new CustomMessageException();
            }

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

            // get selected id's
            ArrayList selectedIDs = new ArrayList();
            foreach (RepeaterItem item in lstNotes.Items)
            {
                CheckBox chkUseNote = (CheckBox)item.FindControl("chkUseNote");
                Label    lblNoteID  = (Label)item.FindControl("lblNoteID");
                if (chkUseNote.Checked)
                {
                    selectedIDs.Add(lblNoteID.Text);
                }
            }

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

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



            // show booking info

            lnkBookingSheetForPatient.Text        = "Booking sheet for " + bookingPatient.Patient.Person.FullnameWithoutMiddlename;
            lnkBookingSheetForPatient.PostBackUrl = String.Format("~/BookingsV2.aspx?type=patient&patient={0}&org={1}&staff={2}&offering={3}&date={4}", bookingPatient.Patient.PatientID, bookingPatient.Booking.Organisation.OrganisationID, bookingPatient.Booking.Provider.StaffID, bookingPatient.Offering.OfferingID, bookingPatient.Booking.DateStart.ToString("yyyy_MM_dd"));

            lnkBookingListForPatient.Text        = "Booking list for " + bookingPatient.Patient.Person.FullnameWithoutMiddlename;
            lnkBookingListForPatient.PostBackUrl = String.Format("~/BookingsListV2.aspx?patient={0}", bookingPatient.Patient.PatientID);

            lblBooking_Provider.Text      = bookingPatient.Booking.Provider.Person.FullnameWithoutMiddlename;
            lblBooking_Offering.Text      = bookingPatient.Offering.Name;
            lblBooking_BookingStatus.Text = bookingPatient.Booking.BookingStatus.Descr.ToString();
            lblBooking_Time.Text          = bookingPatient.Booking.DateStart.Date.ToString("dd MMM yyyy") + " - " + bookingPatient.Booking.DateStart.ToString("hh:mm") + "-" + bookingPatient.Booking.DateEnd.ToString("hh:mm");
            lblBooking_Notes.Text         = Note.GetPopupLinkTextV2(15, bookingPatient.EntityID, bookingPatient.NoteCount > 0, true, 1050, 530, "images/notes-bw-24.jpg", "images/notes-24.png");


            // display list of notes in repeater
            DataTable notes = NoteDB.GetDataTable_ByEntityID(bookingPatient.EntityID);
            lstNotes.DataSource = notes;
            lstNotes.DataBind();

            // check id's that were previously checked
            foreach (RepeaterItem item in lstNotes.Items)
            {
                CheckBox chkUseNote      = (CheckBox)item.FindControl("chkUseNote");
                Label    lblNoteID       = (Label)item.FindControl("lblNoteID");
                Label    lblOriginalText = (Label)item.FindControl("lblOriginalText");
                chkUseNote.Checked = selectedIDs.Contains(lblNoteID.Text);
            }

            // hide if got from url ... no need to change it
            btnPatientListPopup.Visible      = false;
            btnClearPatient.Visible          = false;
            btnOrganisationListPopup.Visible = false;
            btnClearOrganisation.Visible     = false;
        }
        else if (booking_id != null)
        {
            if (!Regex.IsMatch(booking_id, @"^\d+$"))
            {
                throw new CustomMessageException();
            }

            Booking booking = BookingDB.GetByID(Convert.ToInt32(booking_id));
            if (booking == null)
            {
                throw new CustomMessageException();
            }

            if (booking.Patient != null)
            {
                btnOtherEmail.OnClientClick = "javascript: get_referrer_additional_emails(" + booking.Patient.PatientID + ");return false;";
            }

            if (booking.Patient == null)
            {
                DataTable dt = BookingPatientDB.GetDataTable_ByBookingID(booking.BookingID);
                lstBookingPatients.DataSource = dt;
                lstBookingPatients.DataBind();

                main_table.Visible = false;
                select_booking_patient_table.Visible = true;
                return;

                //throw new CustomMessageException();
            }
            if (booking.Organisation == null)
            {
                throw new CustomMessageException();
            }

            // get selected id's
            ArrayList selectedIDs = new ArrayList();
            foreach (RepeaterItem item in lstNotes.Items)
            {
                CheckBox chkUseNote = (CheckBox)item.FindControl("chkUseNote");
                Label    lblNoteID  = (Label)item.FindControl("lblNoteID");
                if (chkUseNote.Checked)
                {
                    selectedIDs.Add(lblNoteID.Text);
                }
            }

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

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



            // show booking info

            lnkBookingSheetForPatient.Text        = "Booking sheet for " + booking.Patient.Person.FullnameWithoutMiddlename;
            lnkBookingSheetForPatient.PostBackUrl = String.Format("~/BookingsV2.aspx?type=patient&patient={0}&org={1}&staff={2}&offering={3}&date={4}", booking.Patient.PatientID, booking.Organisation.OrganisationID, booking.Provider.StaffID, booking.Offering.OfferingID, booking.DateStart.ToString("yyyy_MM_dd"));

            lnkBookingListForPatient.Text        = "Booking list for " + booking.Patient.Person.FullnameWithoutMiddlename;
            lnkBookingListForPatient.PostBackUrl = String.Format("~/BookingsListV2.aspx?patient={0}", booking.Patient.PatientID);

            lblBooking_Provider.Text      = booking.Provider.Person.FullnameWithoutMiddlename;
            lblBooking_Offering.Text      = booking.Offering.Name;
            lblBooking_BookingStatus.Text = booking.BookingStatus.Descr.ToString();
            lblBooking_Time.Text          = booking.DateStart.Date.ToString("dd MMM yyyy") + " - " + booking.DateStart.ToString("hh:mm") + "-" + booking.DateEnd.ToString("hh:mm");
            lblBooking_Notes.Text         = Note.GetPopupLinkTextV2(15, booking.EntityID, booking.NoteCount > 0, true, 1050, 530, "images/notes-bw-24.jpg", "images/notes-24.png");


            // display list of notes in repeater
            DataTable notes = NoteDB.GetDataTable_ByEntityID(booking.EntityID);
            lstNotes.DataSource = notes;
            lstNotes.DataBind();

            // check id's that were previously checked
            foreach (RepeaterItem item in lstNotes.Items)
            {
                CheckBox chkUseNote      = (CheckBox)item.FindControl("chkUseNote");
                Label    lblNoteID       = (Label)item.FindControl("lblNoteID");
                Label    lblOriginalText = (Label)item.FindControl("lblOriginalText");
                chkUseNote.Checked = selectedIDs.Contains(lblNoteID.Text);
            }

            // hide if got from url ... no need to change it
            btnPatientListPopup.Visible      = false;
            btnClearPatient.Visible          = false;
            btnOrganisationListPopup.Visible = false;
            btnClearOrganisation.Visible     = false;
        }
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        try
        {
            //ScriptManager.RegisterClientScriptBlock(this, GetType(), "fancyBox", "alert('a');", true);

            int letterPrintHistorySendMethodID = 1; // send by mail


            // make sure org and patient selected
            if (txtUpdatePatientID.Text.Length == 0)
            {
                throw new CustomMessageException("Please select a patient.");
            }
            //if (txtUpdateOrganisationID.Text.Length == 0)    //--- checking in javascript .. cuz can be blank and use site info in place of org info
            //    throw new CustomMessageException("Please select an organisation.");


            if (lstLetters.GetSelectedIndices().Length == 0)
            {
                throw new CustomMessageException("Please select a letter.");
            }

            // get letter and make sure it exists
            Letter letter             = LetterDB.GetByID(Convert.ToInt32(lstLetters.SelectedValue));
            string sourchTemplatePath = letter.GetFullPath(Convert.ToInt32(Session["SiteID"]));
            if (!File.Exists(sourchTemplatePath))
            {
                throw new CustomMessageException("File doesn't exist.");
            }

            // get list of selected notes!
            ArrayList list = new ArrayList();
            foreach (RepeaterItem item in lstNotes.Items)
            {
                if (((CheckBox)item.FindControl("chkUseNote")).Checked)
                {
                    Label lblNoteID = (Label)item.FindControl("lblNoteID");
                    Note  note      = NoteDB.GetByID(Convert.ToInt32(lblNoteID.Text));
                    list.Add(Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + "Treatment Note (" + note.DateAdded.ToString("dd-MM-yyyy") + "):" + Environment.NewLine + Environment.NewLine + ((Label)item.FindControl("lblOriginalText")).Text);
                }
            }
            string[] notes = (string[])list.ToArray(typeof(string));

            int bookingID = -1;
            if (Request.QueryString["booking"] != null)
            {
                bookingID = Convert.ToInt32(Request.QueryString["booking"]);
            }
            if (Request.QueryString["bookingpatient"] != null)
            {
                BookingPatient bp = BookingPatientDB.GetByID(Convert.ToInt32(Request.QueryString["bookingpatient"]));
                bookingID = bp.Booking.BookingID;
            }

            Letter.SendLetter(Response,
                              Letter.FileFormat.Word, // .pdf
                              SiteDB.GetByID(Convert.ToInt32(Session["SiteID"])),
                              letter.LetterID,
                              txtUpdateOrganisationID.Text == "" ? 0 : Convert.ToInt32(txtUpdateOrganisationID.Text),
                              Convert.ToInt32(txtUpdatePatientID.Text),
                              Convert.ToInt32(Session["StaffID"]),
                              bookingID,
                              -1,
                              1,
                              notes,
                              true,
                              letterPrintHistorySendMethodID);
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
            return;
        }
    }
Beispiel #4
0
    protected void Button2_Click(object sender, EventArgs e)
    {
        Label2.Text = "Done";

        // find 3 bookings and 3 ac patients ... and put in below .. and run in


        int bk1 = 93602;
        int bk2 = 93603;
        int bk3 = 93604;

        int pt1 = 3378;
        int pt2 = 8665;
        int pt3 = 11455;

        /*
         * BookingPatientDB.Insert(bk1, pt1, Convert.ToInt32(Session["StaffID"]));
         * BookingPatientDB.Insert(bk1, pt2, Convert.ToInt32(Session["StaffID"]));
         * BookingPatientDB.Insert(bk1, pt3, Convert.ToInt32(Session["StaffID"]));
         *
         * BookingPatientDB.Insert(bk2, pt1, Convert.ToInt32(Session["StaffID"]));
         * BookingPatientDB.Insert(bk3, pt1, Convert.ToInt32(Session["StaffID"]));
         */


        BookingPatient[] bp1 = BookingPatientDB.GetByBookingID(bk1);
        BookingPatient[] bp2 = BookingPatientDB.GetByBookingID(bk2);
        BookingPatient[] bp3 = BookingPatientDB.GetByBookingID(bk3);

        BookingPatient[] bp4 = BookingPatientDB.GetByPatientID(pt1);
        BookingPatient[] bp5 = BookingPatientDB.GetByPatientID(pt2);
        BookingPatient[] bp6 = BookingPatientDB.GetByPatientID(pt3);


        string output = "<table border=\"1\">";

        foreach (BookingPatient bp in bp1)
        {
            output += GetBookingPatientText(bp);
        }
        output += GetBlankRow();
        foreach (BookingPatient bp in bp2)
        {
            output += GetBookingPatientText(bp);
        }
        output += GetBlankRow();
        foreach (BookingPatient bp in bp3)
        {
            output += GetBookingPatientText(bp);
        }
        output += GetBlankRow();
        foreach (BookingPatient bp in bp4)
        {
            output += GetBookingPatientText(bp);
        }
        output += GetBlankRow();
        foreach (BookingPatient bp in bp5)
        {
            output += GetBookingPatientText(bp);
        }
        output += GetBlankRow();
        foreach (BookingPatient bp in bp6)
        {
            output += GetBookingPatientText(bp);
        }

        output += "</table>";

        Label2.Text += output;


        /*
         * string output = string.Empty;
         *
         * Offering[] offerings = OfferingDB.GetAll(null);
         * for (int i = 0; i < offerings.Length; i++)
         * {
         *  if (offerings[i].ReminderLetterMonthsLaterToSend == 0 || offerings[i].ReminderLetterID == -1)
         *      continue;
         *
         *  Booking[] bookings = BookingDB.GetWhenLastServiceFromXMonthsAgoToGenerageReminderLetter(offerings[i].OfferingID, DateTime.Today, offerings[i].ReminderLetterMonthsLaterToSend);
         *
         *
         *  // generate letters....
         *
         *  // just copy ReferrerEPCLetters_GenerateUnsent.aspx now...
         *
         *
         *  output += "<br /><br /><u>" + offerings[i].OfferingID + ": " + offerings[i].Name + "</u>";
         *  for (int j = 0; j < bookings.Length; j++)
         *      output += "<br />" + "[" + bookings[j].Offering.OfferingID + "][" + offerings[i].ReminderLetterID + "] " + bookings[j].ToString();
         * }
         */



        /*
         * Booking[] bookings = BookingDB.GetFromXMonthsAgo(28, new DateTime(2013, 3, 1), 1);
         * //Booking[] bookings = BookingDB.GetFromXMonthsAgo(DateTime.Today.AddDays(-2), 1);
         *
         * string output = string.Empty;
         * for (int i = 0; i < bookings.Length; i++)
         *  output += "<br />" + "[" + bookings[i].Offering.OfferingID + "] " + bookings[i].ToString();
         */

        //Label2.Text = output.Length == 0 ? "No Bookings" : output;
    }
    protected static Letter.FileContents[] ProcessReferrersAgedCareLetters(SendMethod selectedSendMethod, bool viewListOnly, Site site, int staffID, ArrayList bookingsForCurrentReferrer, ref string debugOutput, string btnViewListClientID)
    {
        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();

        for (int i = 0; i < bookingsForCurrentReferrer.Count; i++)
        {
            Tuple <BookingPatient, Offering, PatientReferrer, bool, string, string, HealthCard> curTuple = (Tuple <BookingPatient, Offering, PatientReferrer, bool, string, string, HealthCard>)bookingsForCurrentReferrer[i];
            BookingPatient  curBP          = curTuple.Item1;
            Offering        curOffering    = curTuple.Item2;
            PatientReferrer curPR          = curTuple.Item3;
            bool            curRefHasEmail = curTuple.Item4;
            string          curRefEmail    = curTuple.Item5;
            string          curRefFax      = curTuple.Item6;
            HealthCard      curHC          = curTuple.Item7;

            bool needToGenerateLetters = curBP.NeedToGenerateFirstLetter || curBP.NeedToGenerateLastLetter;
            if (needToGenerateLetters)
            {
                SendMethod sendMethod = (curRefHasEmail && selectedSendMethod == SendMethod.Email_To_Referrer ? SendMethod.Email_To_Referrer : SendMethod.Batch);

                if (!viewListOnly)
                {
                    if (curRefHasEmail && selectedSendMethod == SendMethod.Email_To_Referrer)
                    {
                        Letter.FileContents[] fileContentsList = curBP.Booking.GetSystemLettersList(Letter.FileFormat.PDF, curBP.Patient, curHC, curOffering.Field.ID, curPR.RegisterReferrer.Referrer, true, curBP.NeedToGenerateFirstLetter, curBP.NeedToGenerateLastLetter, false, false, site.SiteID, staffID, sendMethod == SendMethod.Email_To_Referrer ? 2 : 1);
                        if (fileContentsList != null && fileContentsList.Length > 0)
                        {
                            if (ReferrerEPCLettersSending.LogDebugEmailInfo)
                            {
                                Logger.LogQuery("B ReferrerEPCLetters_GenerateUnsent -- Email Send Item Starting [" + curRefEmail + "][" + curBP.Booking.BookingID + "][" + curBP.Booking.Patient.PatientID + "][" + curBP.Booking.Patient.Person.FullnameWithoutMiddlename + "]", false, false, true);
                            }

                            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 (ReferrerEPCLettersSending.LogDebugEmailInfo)
                            {
                                Logger.LogQuery("B ReferrerEPCLetters_GenerateUnsent -- Email Send Item Done!", false, false, true);
                            }
                        }
                    }
                    else
                    {
                        Letter.FileContents[] fileContentsList = curBP.Booking.GetSystemLettersList(Letter.FileFormat.Word, curBP.Patient, curHC, curOffering.Field.ID, curPR.RegisterReferrer.Referrer, true, curBP.NeedToGenerateFirstLetter, curBP.NeedToGenerateLastLetter, false, false, site.SiteID, staffID, sendMethod == SendMethod.Email_To_Referrer ? 2 : 1);
                        if (fileContentsList != null && fileContentsList.Length > 0)
                        {
                            filesToPrint.AddRange(fileContentsList);
                        }
                    }

                    BookingPatientDB.UpdateSetGeneratedSystemLetters(curBP.BookingPatientID, curBP.NeedToGenerateFirstLetter, curBP.NeedToGenerateLastLetter, true);
                }

                ArrayList toGenerateList = new ArrayList();
                if (curBP.NeedToGenerateFirstLetter)
                {
                    toGenerateList.Add("First");
                }
                if (curBP.NeedToGenerateLastLetter)
                {
                    toGenerateList.Add("Last");
                }
                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 = "AddEditContactAusList.aspx";
                }
                else
                {
                    throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                }

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

                debugOutput += @"<tr>
                                    <td style=""white-space:nowrap;"">" + curBP.Booking.Organisation.GetSiteType().ToString() + @"</td>
                                    <td>" + sendMethod + @"</td>
                                    <td style=""white-space:nowrap;"">" + curBP.Booking.BookingID + " &nbsp;&nbsp;&nbsp;[" + curBP.Booking.DateStart.ToString("dd-MM-yyyy") + "&nbsp;&nbsp;&nbsp;" + curBP.Booking.DateStart.ToString("HH:mm") + "-" + curBP.Booking.DateEnd.ToString("HH:mm") + "]" + @"</td>
                                    <td>" + toGenerate + @"</td>
                                    <td>" + curPR.RegisterReferrer.Referrer.Person.FullnameWithoutMiddlename + @"</td>
                                    <td>" + (curRefHasEmail    ? curRefEmail : "") + @"</td>
                                    <td style=""white-space:nowrap;"">" + (curRefFax != null ? curRefFax : "") + @"</td>
                                    <td style=""white-space:nowrap;"">" + 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)));
    }
    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);
    }