Esempio n. 1
0
    public static string Run(bool incDisplay, bool incSending, bool incPtSending, DateTime date)
    {
        date = date.Date;

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

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

        Site[] sites = SiteDB.GetAll();


        string output = string.Empty;

        Hashtable lettersHash = LetterDB.GetHashTable();

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

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


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

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



            // Generate Letters

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

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


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

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

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

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

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


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


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

        return(@"
            <table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" style=""border-style:solid;border-width:1px;border-collapse:collapse;padding:4px;"">
            <tr>
              <th>Booking (ID, Date/Time)</th>
              <th>Organisation</th>
              <th>Service</th>
              <th>Letter</th>
              <th>Patient</th>
              <th>PT Email</th>
              <th>Send Method</th>
            </tr>
            " + output + @"
            </table>");
    }
    protected void FillGrid()
    {
        int       bulk_letter_sending_queue_batch_id = IsValidFormBatchID() ? GetFormBatchID() : -1;
        DataTable dt = BulkLetterSendingQueueDB.GetDataTable(bulk_letter_sending_queue_batch_id);


        // send method hashtable
        DataTable sendMethodTbl  = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "LetterPrintHistorySendMethod", "", "", "letter_print_history_send_method_id", "descr");
        Hashtable sendMethodHash = new Hashtable();

        for (int i = 0; i < sendMethodTbl.Rows.Count; i++)
        {
            sendMethodHash[Convert.ToInt32(sendMethodTbl.Rows[i]["letter_print_history_send_method_id"])] = (string)sendMethodTbl.Rows[i]["descr"];
        }

        // patient hashtable
        ArrayList ptIDs = new ArrayList();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i]["patient_id"] != DBNull.Value)
            {
                ptIDs.Add((int)dt.Rows[i]["patient_id"]);
            }
        }
        Hashtable patientHash = PatientDB.GetByIDsInHashtable((int[])ptIDs.ToArray(typeof(int)));

        // staff hashtable
        Hashtable staffHash = StaffDB.GetAllInHashtable(true, true, true, false);

        // referrersHash
        Hashtable referrersHash = ReferrerDB.GetHashtableByReferrer();

        // letters hashtable
        Hashtable letterHash = LetterDB.GetHashTable();


        // add from hashtable
        dt.Columns.Add("letter_print_history_send_method_descr", typeof(String));
        dt.Columns.Add("added_by_name", typeof(String));
        dt.Columns.Add("patient_name", typeof(String));
        dt.Columns.Add("referrer_name", typeof(String));
        dt.Columns.Add("letter_doc_name", typeof(String));

        int SMSSent     = 0;
        int SMSUnSent   = 0;
        int EmailSent   = 0;
        int EmailUnSent = 0;
        int PrintSent   = 0;
        int PrintUnSent = 0;

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            int  letter_print_history_send_method_id = Convert.ToInt32(dt.Rows[i]["letter_print_history_send_method_id"]);
            bool sent = dt.Rows[i]["datetime_sent"] != DBNull.Value;

            dt.Rows[i]["letter_print_history_send_method_descr"] = (string)sendMethodHash[letter_print_history_send_method_id];
            dt.Rows[i]["added_by_name"] = dt.Rows[i]["added_by"] == DBNull.Value ? "" : ((Staff)staffHash[Convert.ToInt32(dt.Rows[i]["added_by"])]).Person.FullnameWithoutMiddlename;
            dt.Rows[i]["patient_name"]  = dt.Rows[i]["patient_id"] == DBNull.Value ? "" : ((Patient)patientHash[Convert.ToInt32(dt.Rows[i]["patient_id"])]).Person.FullnameWithoutMiddlename;

            dt.Rows[i]["referrer_name"] = dt.Rows[i]["referrer_id"] == DBNull.Value ? "" : ((Referrer)referrersHash[Convert.ToInt32(dt.Rows[i]["referrer_id"])]).Person.FullnameWithoutMiddlename;

            string source_template_path = dt.Rows[i]["email_letter_source_template_path"].ToString();
            string letter_doc_name      = source_template_path.Length == 0 ? "" : System.IO.Path.GetFileName(source_template_path);
            dt.Rows[i]["letter_doc_name"] = letter_doc_name;

            if (letter_print_history_send_method_id == 3 && sent)
            {
                SMSSent++;
            }
            if (letter_print_history_send_method_id == 3 && !sent)
            {
                SMSUnSent++;
            }
            if (letter_print_history_send_method_id == 2 && sent)
            {
                EmailSent++;
            }
            if (letter_print_history_send_method_id == 2 && !sent)
            {
                EmailUnSent++;
            }
            if (letter_print_history_send_method_id == 1 && sent)
            {
                PrintSent++;
            }
            if (letter_print_history_send_method_id == 1 && !sent)
            {
                PrintUnSent++;
            }
        }

        lblSMSSent.Text     = SMSSent.ToString();
        lblSMSUnSent.Text   = SMSUnSent.ToString();
        lblEmailSent.Text   = EmailSent.ToString();
        lblEmailUnSent.Text = EmailUnSent.ToString();
        lblPrintSent.Text   = PrintSent.ToString();
        lblPrintUnSent.Text = PrintUnSent.ToString();
        lblTotalSent.Text   = (SMSSent + EmailSent + PrintSent).ToString();
        lblTotalUnSent.Text = (SMSUnSent + EmailUnSent + PrintUnSent).ToString();


        DataView dv = new DataView(dt);

        dv.Sort = "letter_print_history_send_method_id";
        dt      = dv.ToTable();


        Session["lettersprintbatchstatus_data"] = dt;

        if (dt.Rows.Count > 0)
        {
            if (IsPostBack && Session["lettersprintbatchstatus_sortexpression"] != null && Session["lettersprintbatchstatus_sortexpression"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort = Session["lettersprintbatchstatus_sortexpression"].ToString();
                GrdBulkLetterSendingQueue.DataSource = dataView;
            }
            else
            {
                GrdBulkLetterSendingQueue.DataSource = dt;
            }

            GrdBulkLetterSendingQueue.AllowPaging = false;

            try
            {
                GrdBulkLetterSendingQueue.DataBind();
                GrdBulkLetterSendingQueue.PagerSettings.FirstPageText = "1";
                GrdBulkLetterSendingQueue.PagerSettings.LastPageText  = GrdBulkLetterSendingQueue.PageCount.ToString();
                GrdBulkLetterSendingQueue.DataBind();
            }
            catch (Exception ex)
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdBulkLetterSendingQueue.DataSource = dt;
            GrdBulkLetterSendingQueue.DataBind();

            int TotalColumns = GrdBulkLetterSendingQueue.Rows[0].Cells.Count;
            GrdBulkLetterSendingQueue.Rows[0].Cells.Clear();
            GrdBulkLetterSendingQueue.Rows[0].Cells.Add(new TableCell());
            GrdBulkLetterSendingQueue.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdBulkLetterSendingQueue.Rows[0].Cells[0].Text       = "No Record Found";
        }
    }