Пример #1
0
        public MainWindow()
        {
            InitializeComponent();
            var xlsxPath = Directory.GetCurrentDirectory() + "\\temp.xlsx"; //Laba2\Laba2\bin\Release\temp.xlsx
            var dataPath = Directory.GetCurrentDirectory() + "\\data.xml";  //Laba2\Laba2\bin\Release\data.xml

            if (File.Exists(dataPath))
            {
                db = NoteDB.DeSerializeObject <NoteDB>(dataPath);
            }
            else
            {
                DownloadFile(xlsxPath);
                db = new NoteDB();
                db.Parse(xlsxPath);
            }

            NoteDB.SerializeObject <NoteDB>(db, dataPath);

            this._cview = new PagingCollectionView(db.list
                                                   ,
                                                   20
                                                   );
            this.DataContext = this._cview;
        }
Пример #2
0
        //  Notes/
        public ActionResult UnLiked(int id)
        {
            NoteDB noteDB = db.Notes.Find(id);

            SubLikes(noteDB, User.Identity.GetUserName());
            return(PartialView("_LikesPartialView", noteDB));
            //return RedirectToAction("Index");
        }
Пример #3
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            NoteDB noteDB = await db.Notes.FindAsync(id);

            db.Notes.Remove(noteDB);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
Пример #4
0
    public static void SetNotDeleted(int note_id, int un_deleted_by)
    {
        Note note = NoteDB.GetByID(note_id);

        NoteHistoryDB.Insert(note.NoteID, note.NoteType.ID, note.BodyPart.ID, note.Text, note.DateAdded, note.DateModified, note.DateDeleted, note.AddedBy == null ? -1 : note.AddedBy.StaffID, note.ModifiedBy == null ? -1 : note.ModifiedBy.StaffID, note.DeletedBy == null ? -1 : note.DeletedBy.StaffID, note.Site == null ? -1 : note.Site.SiteID);

        string sql = "UPDATE Note SET date_deleted = NULL, deleted_by = NULL, date_modified = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',modified_by = " + un_deleted_by + " WHERE note_id = " + note_id.ToString();

        DBBase.ExecuteNonResult(sql);
    }
Пример #5
0
        public JsonResult Liked1(int id)
        {
            NoteDB noteDB = db.Notes.Find(id);

            AddLikes(noteDB, User.Identity.GetUserName());
            return(new JsonResult()
            {
                Data = noteDB, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
            //return RedirectToAction("Index");
        }
Пример #6
0
    public static void Update(int note_id, DateTime date_added, int modified_by, int note_type_id, int body_part_id, int medical_service_type_id, string text, int site_id)
    {
        Note note = NoteDB.GetByID(note_id);

        NoteHistoryDB.Insert(note.NoteID, note.NoteType.ID, note.BodyPart.ID, note.Text, note.DateAdded, note.DateModified, note.DateDeleted, note.AddedBy == null ? -1 : note.AddedBy.StaffID, note.ModifiedBy == null ? -1 : note.ModifiedBy.StaffID, note.DeletedBy == null ? -1 : note.DeletedBy.StaffID, note.Site == null ? -1 : note.Site.SiteID);

        text = text.Replace("'", "''");
        string sql = "UPDATE Note SET note_type_id = " + note_type_id + ",body_part_id = " + (body_part_id == -1 ? "NULL" : body_part_id.ToString()) + ",medical_service_type_id = " + (medical_service_type_id == -1 ? "NULL" : medical_service_type_id.ToString()) + ",date_added = '" + date_added.ToString("yyyy-MM-dd HH:mm:ss") + "'" + ",text = '" + text + "',date_modified = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',modified_by = " + modified_by + ",site_id = " + (site_id == -1 ? "NULL" : site_id.ToString()) + " WHERE note_id = " + note_id.ToString();

        DBBase.ExecuteNonResult(sql);
    }
Пример #7
0
        public async Task <ActionResult> Edit([Bind(Include = "Id,Username,Text,Time,Likes,Forward")] NoteDB noteDB)
        {
            if (ModelState.IsValid)
            {
                noteDB.Time            = DateTime.Now;
                db.Entry(noteDB).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(noteDB));
        }
 private Note GetFormNote()
 {
     try
     {
         string id = Request.QueryString["id"];
         return((id == null || !Regex.IsMatch(id, @"^\d+$")) ? null : NoteDB.GetByID(Convert.ToInt32(id)));
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
 public IHttpActionResult Get()
 {
     try
     {
         Note[] temp = NoteDB.GetAllNote().ToArray();
         return(Ok(temp));
     }
     catch (Exception ex)
     {
         return(Content(HttpStatusCode.BadRequest, ex));
     }
 }
 public IHttpActionResult Get(bool isToday)
 {
     try
     {
         NoteWithToken[] temp = NoteDB.GetAllTodaysNotes().ToArray();
         return(Ok(temp));
     }
     catch (Exception ex)
     {
         return(Content(HttpStatusCode.BadRequest, ex));
     }
 }
Пример #11
0
 private void SubLikes(NoteDB n, string user)
 {
     string[] Users = n.Likes.Split(',');
     //使用lambda表达式过滤掉user
     Users = Users.Where(s => s != user).ToArray();
     if (Users.Count() == 0)
     {
         Users = new string[] { "无" };
     }
     n.Likes           = string.Join(",", Users);
     db.Entry(n).State = EntityState.Modified;
     db.SaveChanges();
 }
 public IHttpActionResult Post([FromBody] Note n)
 {
     try
     {
         int newCode = NoteDB.InsertNewNote(n.FamilyCode, n.Description, n.TimeAndDate);
         n.NoteCode = newCode;
         return(Created(new Uri(Request.RequestUri.AbsoluteUri + newCode), n));
     }
     catch (Exception ex)
     {
         return(Content(HttpStatusCode.BadRequest, ex));
     }
 }
Пример #13
0
        // GET: Notes/Details/5
        public async Task <ActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            NoteDB noteDB = await db.Notes.FindAsync(id);

            if (noteDB == null)
            {
                return(HttpNotFound());
            }
            return(View(noteDB));
        }
Пример #14
0
 private void AddLikes(NoteDB n, string user)
 {
     if (n.Likes == "无")
     {
         n.Likes = user;
     }
     else
     {
         n.Likes += ",";
         n.Likes += user;
     }
     db.Entry(n).State = EntityState.Modified;
     db.SaveChanges();
 }
Пример #15
0
        public async Task <ActionResult> Create([Bind(Include = "Id,Username,Text,Time,Likes,Forward")] NoteDB noteDB)
        {
            if (ModelState.IsValid)
            {
                noteDB.Username = User.Identity.GetUserName();
                noteDB.Likes    = "无";
                noteDB.Time     = DateTime.Now;
                db.Notes.Add(noteDB);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(noteDB));
        }
 public IHttpActionResult Get(int id)
 {
     try
     {
         Note[] temp = NoteDB.GetAllNotesByFamilyCode(id).ToArray();
         if (temp.Length > 0)
         {
             return(Ok(temp));
         }
         return(Content(HttpStatusCode.NotFound, $"Note of family {id} dont found!"));
     }
     catch (Exception ex)
     {
         return(Content(HttpStatusCode.BadRequest, ex));
     }
 }
Пример #17
0
        //Обновление БД
        private void OnRenewClicked(object sender, RoutedEventArgs e)
        {
            //скачиваем файл и сверяем каждую строку в xlsx с каждой записью в БД
            var xlsxPath = Directory.GetCurrentDirectory() + "\\temp.xlsx"; //Laba2\Laba2\bin\Release\temp.xlsx
            var dataPath = Directory.GetCurrentDirectory() + "\\data.xml";  //Laba2\Laba2\bin\Release\data.xml

            DownloadFile(xlsxPath);
            db.AnotherParse(xlsxPath);
            NoteDB.SerializeObject <NoteDB>(db, dataPath);


            this._cview = new PagingCollectionView(db.list
                                                   ,
                                                   20
                                                   );
            this.DataContext = this._cview;
        }
 public IHttpActionResult Put(int id, [FromBody] Note n)
 {
     try
     {
         int val = NoteDB.UpdateNote(n.FamilyCode, n.NoteCode, n.Description, n.TimeAndDate);
         if (val > 0)
         {
             return(Content(HttpStatusCode.OK, n));
         }
         else
         {
             return(Content(HttpStatusCode.NotFound, $"Note {n.Description} of family {n.FamilyCode} was not found to update!"));
         }
     }
     catch (Exception ex)
     {
         return(Content(HttpStatusCode.BadRequest, ex));
     }
 }
Пример #19
0
    protected void GrdNote_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            if (!IsValidFormID())
            {
                throw new CustomMessageException();
            }

            Label        lblId                 = (Label)GrdNote.FooterRow.FindControl("lblId");
            DropDownList ddlNoteType           = (DropDownList)GrdNote.FooterRow.FindControl("ddlNewNoteType");
            DropDownList ddlBodyPart           = (DropDownList)GrdNote.FooterRow.FindControl("ddlNewBodyPart");
            DropDownList ddlMedicalServiceType = (DropDownList)GrdNote.FooterRow.FindControl("ddlNewMedicalServiceType");
            TextBox      txtText               = (TextBox)GrdNote.FooterRow.FindControl("txtNewText");
            //DropDownList ddlSite = (DropDownList)GrdNote.FooterRow.FindControl("ddlNewSite");
            DropDownList ddlDate_Day   = (DropDownList)GrdNote.FooterRow.FindControl("ddlNewDate_Day");
            DropDownList ddlDate_Month = (DropDownList)GrdNote.FooterRow.FindControl("ddlNewDate_Month");
            DropDownList ddlDate_Year  = (DropDownList)GrdNote.FooterRow.FindControl("ddlNewDate_Year");

            if (!IsValidDate(ddlDate_Day.SelectedValue, ddlDate_Month.SelectedValue, ddlDate_Year.SelectedValue))
            {
                return;
            }

            DateTime date = GetDate(ddlDate_Day.SelectedValue, ddlDate_Month.SelectedValue, ddlDate_Year.SelectedValue);
            NoteDB.Insert(GetFormID(), date, Convert.ToInt32(Session["StaffID"]), Convert.ToInt32(ddlNoteType.SelectedValue), Convert.ToInt32(ddlBodyPart.SelectedValue), Convert.ToInt32(ddlMedicalServiceType.SelectedValue), txtText.Text, Convert.ToInt32(Session["SiteID"]));

            FillNoteGrid();

            string clear_saved_note = "clear_note(document.getElementById('" + ((TextBox)GrdNote.FooterRow.FindControl("txtNewText")).ClientID + "'), document.getElementById('" + userID.ClientID + "').value, document.getElementById('" + entityID.ClientID + "').value);";
            ScriptManager.RegisterStartupScript(GrdNote, this.GetType(), "unset_cookie", clear_saved_note, true);
        }
        if (e.CommandName == "_Delete")
        {
            NoteDB.SetDeleted(Convert.ToInt32(e.CommandArgument), Convert.ToInt32(Session["StaffID"]));
            FillNoteGrid();
        }
        if (e.CommandName == "_UnDelete")
        {
            NoteDB.SetNotDeleted(Convert.ToInt32(e.CommandArgument), Convert.ToInt32(Session["StaffID"]));
            FillNoteGrid();
        }
    }
        public IHttpActionResult Delete(int NoteCode, int FamilyCode)
        {
            try
            {
                int val = NoteDB.DeleteNote(NoteCode, FamilyCode);

                if (val > 0)
                {
                    return(Ok($"Note with NoteCode {NoteCode} and FamilyCode {FamilyCode} Successfully deleted!"));
                }
                else
                {
                    return(Content(HttpStatusCode.NotFound, $"Note {NoteCode} of family {FamilyCode} was not found to delete!"));
                }
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.BadRequest, ex));
            }
        }
Пример #21
0
    public static void Delete(int entity_id, bool checkForeignKeys = true)
    {
        if (checkForeignKeys)
        {
            // do NOT delete the "entity" that this is for - that should be done "explicitly" elsewhere
            // but make sure there is no entity that it relies on
            if (SiteDB.GetCountByEntityID(entity_id) > 0)
            {
                throw new ForeignKeyConstraintException("Can not delete entity_id " + entity_id + " because a ForeignKey Site record depends on it ");
            }
            if (PersonDB.GetCountByEntityID(entity_id) > 0)
            {
                throw new ForeignKeyConstraintException("Can not delete entity_id " + entity_id + " because a ForeignKey Person record depends on it ");
            }
            if (OrganisationDB.GetCountByEntityID(entity_id) > 0)
            {
                throw new ForeignKeyConstraintException("Can not delete entity_id " + entity_id + " because a ForeignKey Organisation record depends on it ");
            }
            if (BookingDB.GetCountByEntityID(entity_id) > 0)
            {
                throw new ForeignKeyConstraintException("Can not delete entity_id " + entity_id + " because a ForeignKey Booking record depends on it ");
            }
            if (InvoiceDB.GetCountByEntityID(entity_id) > 0)
            {
                throw new ForeignKeyConstraintException("Can not delete entity_id " + entity_id + " because a ForeignKey Invoice record depends on it ");
            }
        }

        // delete all things associated with the entity
        if (Utilities.GetAddressType().ToString() == "Contact")
        {
            ContactDB.DeleteByEntityID(entity_id);
        }
        else if (Utilities.GetAddressType().ToString() == "ContactAus")
        {
            ContactAusDB.DeleteByEntityID(entity_id);
        }
        NoteDB.DeleteByEntityID(entity_id);

        DBBase.ExecuteNonResult("DELETE FROM Entity WHERE entity_id = " + entity_id.ToString() + "; DBCC CHECKIDENT(Entity,RESEED,1); DBCC CHECKIDENT(Entity);");
    }
Пример #22
0
        // POST: Notes/Relay/5
        public async Task <ActionResult> Relay(int?id, [Bind(Include = "Id,Username,Text,Time,Likes,Forward")] NoteDB n)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            NoteDB noteDB = await db.Notes.FindAsync(id);

            if (noteDB == null)
            {
                return(HttpNotFound());
            }
            //填写后
            if (ModelState.IsValid && n.Text != null)
            {
                n.Username = User.Identity.GetUserName();
                if (noteDB.Forward == 0)
                {
                    n.Forward = noteDB.Id;
                }
                else
                {
                    n.Forward = noteDB.Forward;
                }
                n.Likes = "无";
                n.Time  = DateTime.Now;
                db.Notes.Add(n);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            //填写前
            if (noteDB.Forward == 0)
            {
                return(View(noteDB));
            }
            else
            {
                return(View(db.Notes.Find(noteDB.Forward)));
            }
        }
Пример #23
0
                    public LaunchData( )
                    {
                        //ALWAYS INCREMENT THIS IF UPDATING THE MODEL
                        ClientModelVersion = 3;
                        //

                        Campuses         = new List <Rock.Client.Campus>( );
                        PrayerCategories = new List <KeyValuePair <string, int> >( );

                        Genders = new List <string>( );
                        Genders.Add("Unknown");
                        Genders.Add("Male");
                        Genders.Add("Female");

                        // in debug builds, turn developer mode on by default
#if DEBUG
                        DeveloperModeEnabled = true;
#endif

                        News   = new List <RockNews>( );
                        NoteDB = new NoteDB( );

                        // for the hardcoded news, leave OFF the image extensions, so that we can add them with scaling for iOS.
                        UpgradeNewsItem = new RockNews(
                            NewsConfig.UpgradeNews[0],

                            NewsConfig.UpgradeNews[1],

                            NewsConfig.UpgradeNews[2],

                            true,
                            false,
                            false,

                            "",
                            NewsConfig.UpgradeNews[3],

                            new List <System.Guid>( ));
                    }
Пример #24
0
                    public LaunchData( )
                    {
                        //ALWAYS INCREMENT THIS IF UPDATING THE MODEL
                        ClientModelVersion = 1;
                        //

                        GeneralDataServerTime = DateTime.MinValue;

                        News = new List<RockNews>( );
                        NoteDB = new NoteDB( );

                        // for the hardcoded news, leave OFF the image extensions, so that we can add them with scaling for iOS.
                        DefaultNews = new List<RockNews>( );
                        DefaultNews.Add( new RockNews( 
                            NewsConfig.DefaultNews_A[ 0 ], 

                            NewsConfig.DefaultNews_A[ 1 ],

                            NewsConfig.DefaultNews_A[ 2 ],

                            false,
                            false,
                            false,

                            "",
                            NewsConfig.DefaultNews_A[ 3 ],

                            "",
                            NewsConfig.DefaultNews_A[ 4 ],

                            new List<System.Guid>( ) ) );

                        DefaultNews.Add( new RockNews( 
                            NewsConfig.DefaultNews_B[ 0 ], 

                            NewsConfig.DefaultNews_B[ 1 ],

                            NewsConfig.DefaultNews_B[ 2 ],

                            false,
                            false,
                            false,

                            "",
                            NewsConfig.DefaultNews_B[ 3 ],

                            "",
                            NewsConfig.DefaultNews_B[ 4 ],

                            new List<System.Guid>( ) ) );


                        DefaultNews.Add( new RockNews( 
                            NewsConfig.DefaultNews_C[ 0 ], 

                            NewsConfig.DefaultNews_C[ 1 ],

                            NewsConfig.DefaultNews_C[ 2 ],

                            false,
                            false,
                            false,

                            "",
                            NewsConfig.DefaultNews_C[ 3 ],

                            "",
                            NewsConfig.DefaultNews_C[ 4 ],

                            new List<System.Guid>( ) ) );
                    }
Пример #25
0
    protected void Send()
    {
        string[] attachments = null;

        try
        {
            // Output.Text = FreeTextBox1.Text;

            if (txtEmailTo.Text.Trim().Length == 0)
            {
                Page.Form.DefaultFocus = txtSubject.ClientID;
                throw new CustomMessageException("Please enter an email address to send to");
            }
            if (!Utilities.IsValidEmailAddresses(txtEmailTo.Text.Trim(), false))
            {
                Page.Form.DefaultFocus = txtSubject.ClientID;
                throw new CustomMessageException("Please enter valid email address(es) to send to");
            }
            if (txtSubject.Text.Trim().Length == 0)
            {
                Page.Form.DefaultFocus = txtSubject.ClientID;
                throw new CustomMessageException("Please enter an email subject");
            }

            string to      = txtEmailTo.Text;
            string subject = txtSubject.Text;
            string message = FreeTextBox1.Text;

            attachments = GetAttachments(new System.Web.UI.HtmlControls.HtmlInputFile[] { inpAttachment1, inpAttachment2, inpAttachment3 });


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


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

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

            string tmpFinalFileName = null;
            if (letter != null)
            {
                tmpFinalFileName = Letter.CreateLetterAndReturnTempFile(
                    Letter.FileFormat.PDF,
                    SiteDB.GetByID(Convert.ToInt32(Session["SiteID"])),
                    letter.LetterID,
                    txtUpdateOrganisationID.Text == "" ? 0 : Convert.ToInt32(txtUpdateOrganisationID.Text),
                    Convert.ToInt32(txtUpdatePatientID.Text),
                    Convert.ToInt32(Session["StaffID"]),
                    Request.QueryString["booking"] == null ? -1 : Convert.ToInt32(Request.QueryString["booking"]),
                    -1,
                    1,
                    notes,
                    true,
                    1);

                if (attachments == null)
                {
                    attachments = new string[] { }
                }
                ;
                string[] newAttachments = new string[attachments.Length + 1];
                newAttachments[0] = tmpFinalFileName;
                Array.Copy(attachments, 0, newAttachments, 1, attachments.Length);
                attachments = newAttachments;
            }

            Emailer.SimpleEmail(
                (string)Session["SiteName"],
                to,
                subject,
                message,
                true,
                attachments,
                null);

            //RemoveDraft();

            SetErrorMessage("Email Sent!");
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
        }
        catch (Exception ex)
        {
            SetErrorMessage("", ex.ToString());
        }
        finally
        {
            if (attachments != null)
            {
                foreach (string file in attachments)
                {
                    System.IO.File.Delete(file);
                }
            }
        }
    }
Пример #26
0
    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;
        }
    }
Пример #27
0
    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;
        }
    }
Пример #28
0
    protected void GrdNote_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label        lblId       = (Label)GrdNote.Rows[e.RowIndex].FindControl("lblId");
        DropDownList ddlNoteType = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlNoteType");
        DropDownList ddlBodyPart = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlBodyPart");
        TextBox      txtText     = (TextBox)GrdNote.Rows[e.RowIndex].FindControl("txtText");
        //DropDownList ddlSite = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlSite");
        DropDownList ddlDate_Day   = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlDate_Day");
        DropDownList ddlDate_Month = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlDate_Month");
        DropDownList ddlDate_Year  = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlDate_Year");

        DataTable dt = ViewState["noteinfo_data"] as DataTable;

        DataRow[] foundRows = dt.Select("note_id=" + lblId.Text);
        Note      note      = NoteDB.Load(foundRows[0]);

        DateTime date = GetDate(ddlDate_Day.SelectedValue, ddlDate_Month.SelectedValue, ddlDate_Year.SelectedValue);

        NoteDB.Update(Convert.ToInt32(lblId.Text), date, Convert.ToInt32(Session["StaffID"]), Convert.ToInt32(ddlNoteType.SelectedValue), Convert.ToInt32(ddlBodyPart.SelectedValue), txtText.Text, note.Site.SiteID);



        // if its a booking note
        // email admin so they know if a provider is sabotaging the system (it has happened before)

        int loggedInStaffID = Session["StaffID"] == null ? -1 : Convert.ToInt32(Session["StaffID"]);

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

        if (booking != null)  // if note is for a booking
        {
            int thresholdCharacters   = 50;
            int totalCharactersBefore = note.Text.Trim().Length;
            int totalCharactersAfter  = txtText.Text.Trim().Length;
            int difference            = totalCharactersAfter - totalCharactersBefore;

            if (totalCharactersBefore > thresholdCharacters && totalCharactersAfter < thresholdCharacters && difference < -20)
            {
                string mailText = @"This is an administrative email to notify you that notes for a booking may have been deleted.

<u>Logged-in user performing the udate</u>
" + StaffDB.GetByID(loggedInStaffID).Person.FullnameWithoutMiddlename + @"

<u>Original Text (Characters: " + totalCharactersBefore + @")</u>
<font color=""blue"">" + note.Text.Replace(Environment.NewLine, "<br />") + @"</font>

<u>Updated Text (Characters: " + totalCharactersAfter + @")</u>
<font color=""blue"">" + txtText.Text.Replace(Environment.NewLine, "<br />") + @"</font>

<u>Booking details</u>
<table border=""0"" cellpadding=""2"" cellspacing=""2""><tr><td>Booking ID:</td><td>" + booking.BookingID + @"</td></tr><tr><td>Booking Date:</td><td>" + booking.DateStart.ToString("d MMM, yyyy") + " " + booking.DateStart.ToString("h:mm") + (booking.DateStart.Hour < 12 ? "am" : "pm") + @"</td></tr><tr><td>Organisation:</td><td>" + booking.Organisation.Name + @"</td></tr><tr><td>Provider:</td><td>" + booking.Provider.Person.FullnameWithoutMiddlename + @"</td></tr><tr><td>Patient:</td><td>" + (booking.Patient == null ? "" : booking.Patient.Person.FullnameWithoutMiddlename + " [ID:" + booking.Patient.PatientID + "]") + @"</td></tr><tr><td>Status:</td><td>" + booking.BookingStatus.Descr + @"</td></tr></table>

Regards,
Mediclinic
";
                bool   EnableDeletedBookingsAlerts = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableDeletedBookingsAlerts").Value) == 1;

                if (EnableDeletedBookingsAlerts && !Utilities.IsDev())
                {
                    Emailer.AsyncSimpleEmail(
                        ((SystemVariables)Session["SystemVariables"])["Email_FromEmail"].Value,
                        ((SystemVariables)Session["SystemVariables"])["Email_FromName"].Value,
                        ((SystemVariables)Session["SystemVariables"])["AdminAlertEmail_To"].Value,
                        "Notification that booking notes may have been deleted",
                        mailText.Replace(Environment.NewLine, "<br />"),
                        true,
                        null);
                }
            }
        }



        GrdNote.Columns[7].Visible = true;
        GrdNote.EditIndex          = -1;
        FillNoteGrid();
    }
Пример #29
0
    protected void FillNoteGrid()
    {
        if (!IsValidFormID())
        {
            if (!Utilities.IsDev() || Request.QueryString["id"] != null)
            {
                HideTableAndSetErrorMessage();
                return;
            }

            // can still view all if dev and no id set .. but no insert/edit
            GrdNote.Columns[5].Visible = false;
        }

        if (!IsValidFormScreen() && !Utilities.IsDev())
        {
            HideTableAndSetErrorMessage();
            return;
        }


        DataTable dt = IsValidFormID() ? NoteDB.GetDataTable_ByEntityID(GetFormID(), null, true, true) : NoteDB.GetDataTable(true);


        if (IsValidFormScreen())
        {
            Hashtable allowedNoteTypes = new Hashtable();
            DataTable noteTypes        = ScreenNoteTypesDB.GetDataTable_ByScreenID(GetFormScreen());
            for (int i = 0; i < noteTypes.Rows.Count; i++)
            {
                allowedNoteTypes[Convert.ToInt32(noteTypes.Rows[i]["note_type_id"])] = 1;
            }

            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                if (allowedNoteTypes[Convert.ToInt32(dt.Rows[i]["note_type_id"])] == null)
                {
                    dt.Rows.RemoveAt(i);
                }
            }
        }

        UserView userView         = UserView.GetInstance();
        bool     canSeeModifiedBy = userView.IsStakeholder || userView.IsMasterAdmin;

        dt.Columns.Add("last_modified_note_info_visible", typeof(Boolean));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["last_modified_note_info_visible"] = canSeeModifiedBy;
        }


        ViewState["noteinfo_data"] = dt;



        // add note info to hidden field to use when emailing notes

        string emailBodyText = string.Empty;

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

        if (booking != null)
        {
            emailBodyText += @"<br /><br />
<u>Treatment Information</u>
<br />
<table border=""0"" cellpadding=""0"" cellspacing=""0"">" +
                             (booking.Patient == null ? "" : @"<tr><td>Patient</td><td style=""width:10px;""></td><td>" + booking.Patient.Person.FullnameWithoutMiddlename + @"</td></tr>") +
                             (booking.Offering == null ? "" : @"<tr><td>Service</td><td></td><td>" + booking.Offering.Name + @"</td></tr>") + @"
    <tr><td>Date</td><td></td><td>" + booking.DateStart.ToString("dd-MM-yyyy") + @"</td></tr>
    <tr><td>Provider</td><td></td><td>" + booking.Provider.Person.FullnameWithoutMiddlename + @"</td></tr>
</table>";
        }

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            Note n = NoteDB.Load(dt.Rows[i]);
            emailBodyText += "<br /><br /><u>Note (" + n.DateAdded.ToString("dd-MM-yyyy") + ")</u><br />" + n.Text.Replace(Environment.NewLine, "<br />");
        }
        emailText.Value = emailBodyText + "<br /><br />" + SystemVariableDB.GetByDescr("LettersEmailSignature").Value;;



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


            try
            {
                GrdNote.DataBind();
            }
            catch (Exception ex)
            {
                this.lblErrorMessage.Visible = true;
                this.lblErrorMessage.Text    = ex.ToString();
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdNote.DataSource = dt;
            GrdNote.DataBind();

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


        Tuple <string, string, string, string> refsEmailInfo = GetReferrersEmail();
        ImageButton btnEmail = GrdNote.HeaderRow.FindControl("btnEmail") as ImageButton;

        if (refsEmailInfo != null)
        {
            btnEmail.Visible = true;
            ((HiddenField)GrdNote.HeaderRow.FindControl("hiddenRefEmail")).Value           = refsEmailInfo.Item1;
            ((HiddenField)GrdNote.HeaderRow.FindControl("hiddenRefName")).Value            = refsEmailInfo.Item2;
            ((HiddenField)GrdNote.HeaderRow.FindControl("hiddenBookingOrg")).Value         = refsEmailInfo.Item3;
            ((HiddenField)GrdNote.HeaderRow.FindControl("HiddenBookingPatientName")).Value = refsEmailInfo.Item4;
        }
        else
        {
            btnEmail.Visible = false;
        }

        DisallowAddEditIfNoPermissions(); // place this after databinding
    }
    public static string[] BulkGetAllTreatmentNotes(DateTime date_start, DateTime date_end, string newline = "\n", bool incNoteIDForDebug = false)
    {
        string recurring_condition     = string.Empty;
        string non_recurring_condition = string.Empty;

        if (date_start != DateTime.MinValue && date_end != DateTime.MinValue)
        {
            recurring_condition     = "AND (  booking.date_start >= '" + date_start.ToString("yyyy-MM-dd HH:mm:ss") + "' AND booking.date_end <= '" + date_end.ToString("yyyy-MM-dd HH:mm:ss") + @"' )";
            non_recurring_condition = "AND (  booking.date_end IS NULL OR booking.date_end > '" + date_start.Date.ToString("yyyy-MM-dd HH:mm:ss") + "') " + (date_end == DateTime.MinValue ? "" : " AND booking.date_start < '" + date_end.Date.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss") + "'") + @"";
        }
        else if (date_start != DateTime.MinValue)
        {
            recurring_condition     = "AND (  booking.date_start >= '" + date_start.ToString("yyyy-MM-dd HH:mm:ss") + "')";
            non_recurring_condition = "AND (  booking.date_end IS NULL OR booking.date_end > '" + date_start.Date.ToString("yyyy-MM-dd HH:mm:ss") + "') " + @"";
        }
        else if (date_end != DateTime.MinValue)
        {
            recurring_condition     = "AND (  booking.date_end  <= '" + date_end.ToString("yyyy-MM-dd HH:mm:ss") + @"' )";
            non_recurring_condition = "AND (  booking.date_start < '" + date_end.Date.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss") + @"' )";
        }
        else
        {
            recurring_condition     = "";
            non_recurring_condition = "";
        }


        string sql = @"

                SELECT 
                    note.note_id as note_note_id, note.entity_id as note_entity_id, note.note_type_id as note_note_type_id, note.body_part_id as note_body_part_id, note.text as note_text, note.date_added as note_date_added, note.date_modified as note_date_modified, note.added_by as note_added_by, note.modified_by as note_modified_by, note.site_id as note_site_id,


                    booking.booking_id as booking_booking_id,booking.entity_id as booking_entity_id,
                    booking.date_start as booking_date_start,booking.date_end as booking_date_end,booking.organisation_id as booking_organisation_id,
                    booking.provider as booking_provider,booking.patient_id as booking_patient_id,booking.offering_id as booking_offering_id,booking.booking_type_id as booking_booking_type_id,
                    booking.booking_status_id as booking_booking_status_id,booking.booking_unavailability_reason_id as booking_booking_unavailability_reason_id,booking.added_by as booking_added_by,booking.date_created as booking_date_created,
                    booking.booking_confirmed_by_type_id as booking_booking_confirmed_by_type_id,booking.confirmed_by as booking_confirmed_by,booking.date_confirmed as booking_date_confirmed,
                    booking.deleted_by as booking_deleted_by, booking.date_deleted as booking_date_deleted,
                    booking.cancelled_by as booking_cancelled_by, booking.date_cancelled as booking_date_cancelled,
                    booking.is_patient_missed_appt as booking_is_patient_missed_appt,booking.is_provider_missed_appt as booking_is_provider_missed_appt,
                    booking.is_emergency as booking_is_emergency,
                    booking.need_to_generate_first_letter as booking_need_to_generate_first_letter,booking.need_to_generate_last_letter as booking_need_to_generate_last_letter,booking.has_generated_system_letters as booking_has_generated_system_letters,
                    booking.arrival_time              as booking_arrival_time,
                    booking.sterilisation_code        as booking_sterilisation_code,
                    booking.informed_consent_added_by as booking_informed_consent_added_by, 
                    booking.informed_consent_date     as booking_informed_consent_date,
                    booking.is_recurring as booking_is_recurring,booking.recurring_weekday_id as booking_recurring_weekday_id,
                    booking.recurring_start_time as booking_recurring_start_time,booking.recurring_end_time as booking_recurring_end_time,
                    (SELECT 0) AS booking_note_count,
                    (SELECT 0) AS booking_inv_count,

                    patient.patient_id as patient_patient_id, patient.person_id as patient_person_id, patient.patient_date_added as patient_patient_date_added, 
                    patient.is_clinic_patient as patient_is_clinic_patient,patient.is_gp_patient as patient_is_gp_patient,patient.is_deleted as patient_is_deleted,patient.is_deceased as patient_is_deceased, 
                    patient.flashing_text as patient_flashing_text, patient.flashing_text_added_by as patient_flashing_text_added_by, patient.flashing_text_last_modified_date as patient_flashing_text_last_modified_date, 
                    patient.private_health_fund as patient_private_health_fund, patient.concession_card_number as patient_concession_card_number, patient.concession_card_expiry_date as patient_concession_card_expiry_date, patient.is_diabetic as patient_is_diabetic, patient.is_member_diabetes_australia as patient_is_member_diabetes_australia, patient.diabetic_assessment_review_date as patient_diabetic_assessment_review_date, patient.ac_inv_offering_id as patient_ac_inv_offering_id, patient.ac_pat_offering_id as patient_ac_pat_offering_id, patient.login as patient_login, patient.pwd as patient_pwd, patient.is_company as patient_is_company, patient.abn as patient_abn, 
                    patient.next_of_kin_name as patient_next_of_kin_name, patient.next_of_kin_relation as patient_next_of_kin_relation, patient.next_of_kin_contact_info as patient_next_of_kin_contact_info,

                    " + PersonDB.GetFields("person_patient_", "person_patient") + @", 
                    title_patient.title_id as title_patient_title_id, title_patient.descr as title_patient_descr,


                    rr.register_referrer_id as rr_register_referrer_id, rr.organisation_id as rr_organisation_id, rr.referrer_id as rr_referrer_id, 
                    rr.provider_number as rr_provider_number, rr.report_every_visit_to_referrer as rr_report_every_visit_to_referrer, 
                    rr.batch_send_all_patients_treatment_notes as rr_batch_send_all_patients_treatment_notes, 
                    rr.date_last_batch_send_all_patients_treatment_notes as rr_date_last_batch_send_all_patients_treatment_notes, 
                    rr.register_referrer_date_added as rr_register_referrer_date_added, rr.is_deleted as rr_is_deleted,

                    ref.referrer_id as ref_referrer_id, ref.person_id as ref_person_id, ref.referrer_date_added as ref_referrer_date_added, 
                    " + PersonDB.GetFields("p_", "p") + @", 
                    t.title_id as t_title_id, t.descr as t_descr

                FROM
                    Note note
                    INNER JOIN Booking          booking           ON booking.entity_id                      = note.entity_id
                    INNER JOIN Patient          patient           ON patient.patient_id                     = booking.patient_id
                    INNER JOIN Person           person_patient    ON person_patient.person_id               = patient.person_id
                    INNER JOIN Title            title_patient     ON title_patient.title_id                 = person_patient.title_id

                    INNER Join PatientReferrer  patient_referrer  ON patient_referrer.patient_id            = patient.patient_id
                    INNER Join RegisterReferrer rr                ON rr.register_referrer_id                = patient_referrer.register_referrer_id
                    INNER JOIN Referrer         ref               ON ref.referrer_id                        = rr.referrer_id 
                    INNER JOIN Person           p                 ON p.person_id                            = ref.person_id
                    INNER JOIN Title            t                 ON t.title_id                             = p.title_id

                WHERE
                    note.note_type_id = 252             -- only provider treatment notes
                    AND booking.booking_status_id = 187 -- only get completed bookings
                    AND booking.booking_type_id   = 34  -- only get bookings for patients (not blockout-prov/org-timeslot bookings)
                    AND (
                            (booking.is_recurring = 0 " + recurring_condition + @") OR  
                            (booking.is_recurring = 1 " + non_recurring_condition + @") 
                        )
                    AND rr.is_deleted = 0
                    AND rr.batch_send_all_patients_treatment_notes = 1

                ORDER BY 
                    rr.register_referrer_id, person_patient.surname, person_patient.firstname, booking.date_start, note.note_id
                    ";

        DataTable tbl = DBBase.ExecuteQuery(sql).Tables[0];

        string[] notes = new string[tbl.Rows.Count];
        for (int i = 0; i < tbl.Rows.Count; i++)
        {
            Booking booking = BookingDB.Load(tbl.Rows[i], "booking_");
            booking.Patient              = PatientDB.Load(tbl.Rows[i], "patient_");
            booking.Patient.Person       = PersonDB.Load(tbl.Rows[i], "person_patient_");
            booking.Patient.Person.Title = IDandDescrDB.Load(tbl.Rows[i], "title_patient_title_id", "title_patient_descr");

            Note note = NoteDB.Load(tbl.Rows[i], "note_");

            RegisterReferrer rr = RegisterReferrerDB.Load(tbl.Rows[i], "rr_");
            rr.Referrer              = ReferrerDB.Load(tbl.Rows[i], "ref_");
            rr.Referrer.Person       = PersonDB.Load(tbl.Rows[i], "p_");
            rr.Referrer.Person.Title = IDandDescrDB.Load(tbl.Rows[i], "t_title_id", "t_descr");

            notes[i] = booking.GetNoteTextForTreatmentLetter(rr.Referrer, note, newline, incNoteIDForDebug);
        }

        return(notes);
    }