Exemple #1
0
def delete(id):
    """Hard delete a patient. Soft-deleting is usually a better idea."""
    check_patient_permission(id)
    patient = Patient.query.get(id)
    db.session.delete(patient)
    db.session.commit()
    return redirect(url_for('screener.index'))
Exemple #2
0
def patient_details(id):
    """Display the full patient details form for an existing user."""
    check_patient_permission(id)
    patient = Patient.query.get(id)
    form = (
        get_unsaved_form(request, patient, 'patient_details', PatientForm)
        or PatientForm(obj=patient)
    )

    if request.method == 'POST' and form.validate_on_submit():
        update_patient(patient, form, request.files)
        db.session.commit()
        patient.update_stats()
        return render_template(
            'patient_details.html',
            patient=patient,
            form=form,
            save_message=True
        )

    # Delete empty rows at end of many-to-one tables
    remove_blank_rows(form)

    return render_template(
        'patient_details.html',
        patient=patient,
        form=form,
        save_message=False
    )
Exemple #3
0
def export_csv(patient_id):
    """Create a CSV of a patient's information."""
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    form = PatientForm(obj=patient)
    fieldnames = []
    data = {}
    for field in form:
        if field.name not in ('document_images', 'csrf_token'):
            if field.type == 'FieldList':
                for entry in field.entries:
                    for subfield in entry:
                        fieldnames.append(subfield.name)
                        data[subfield.name] = subfield.data
            else:
                fieldnames.append(field.name)
                data[field.name] = field.data

    filename = 'zipscreen_patient_' + str(patient_id) + '.csv'
    csvf = StringIO()
    writer = csv.DictWriter(csvf, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow(data)
    csvf.seek(0)
    return send_file(
        csvf,
        mimetype="text/csv",
        attachment_filename=filename,
        as_attachment=True
    )
Exemple #4
0
def delete(id):
    """Hard delete a patient. Soft-deleting is usually a better idea."""
    check_patient_permission(id)
    patient = Patient.query.get(id)
    db.session.delete(patient)
    db.session.commit()
    return redirect(url_for('screener.index'))
Exemple #5
0
def export_csv(patient_id):
    """Create a CSV of a patient's information."""
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    form = PatientForm(obj=patient)
    fieldnames = []
    data = {}
    for field in form:
        if field.name not in ('document_images', 'csrf_token'):
            if field.type == 'FieldList':
                for entry in field.entries:
                    for subfield in entry:
                        fieldnames.append(subfield.name)
                        data[subfield.name] = subfield.data
            else:
                fieldnames.append(field.name)
                data[field.name] = field.data

    filename = 'zipscreen_patient_' + str(patient_id) + '.csv'
    csvf = StringIO()
    writer = csv.DictWriter(csvf, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow(data)
    csvf.seek(0)
    return send_file(csvf,
                     mimetype="text/csv",
                     attachment_filename=filename,
                     as_attachment=True)
Exemple #6
0
def delete(id):
    """Soft delete a patient."""
    check_patient_permission(id)
    patient = Patient.query.get(id)
    patient.deleted = datetime.datetime.now()
    patient.deleted_by = current_user
    db.session.commit()
    return redirect(url_for('screener.index'))
def delete(id):
    """Soft delete a patient."""
    check_patient_permission(id)
    patient = Patient.query.get(id)
    patient.deleted = datetime.datetime.now()
    patient.deleted_by = current_user
    db.session.commit()
    return redirect(url_for('screener.index'))
Exemple #8
0
def add_referral():
    """Adds new referral to the database. Called when user clicks
    'Send Referral' button."""
    check_patient_permission(request.form['patient_id'])
    referral = PatientReferral(patient_id=request.form['patient_id'],
                               from_app_user_id=request.form['app_user_id'],
                               to_service_id=request.form['service_id'],
                               status='SENT')
    db.session.add(referral)
    db.session.commit()
    service = Service.query.get(request.form['service_id'])
    patient = Patient.query.get(request.form['patient_id'])
    send_referral_notification_email(service=service,
                                     patient=patient,
                                     from_app_user=current_user)
    return jsonify()
Exemple #9
0
def export_pdf(patient_id):
    """Create a PDF of a patient's information."""
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    form = PatientForm(obj=patient)
    filename = 'zipscreen_patient_' + str(patient_id) + '.pdf'
    html = render_template('pdf_export.html',
                           patient=patient,
                           form=form,
                           is_production=current_app.config['IS_PRODUCTION'])
    pdf = StringIO()
    pisa.CreatePDF(StringIO(html.encode('utf-8')), pdf)
    pdf.seek(0)
    return send_file(pdf,
                     mimetype="application/pdf",
                     attachment_filename=filename,
                     as_attachment=True)
def patient_share(patient_id):
    """Displays the 'Share Patient' page, which includes prescreening
    results and allows users to send referrals.
    """
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    patient.update_stats()
    services = Service.query.all()

    if not current_user.is_patient_user() and current_user.service:
        allowed_referral_service_ids = [
            service.id for service in current_user.service.can_send_referrals_to
        ]
    else:
        allowed_referral_service_ids = []

    # Get ids of services where the patient already has open referrals,
    # to prevent user from sending duplicates.
    open_referral_service_ids = [
        r.to_service_id for r in patient.referrals
        if (r.in_sent_status() or r.in_sent_status())
    ]

    return render_template(
        'patient_share.html',
        patient=patient,
        current_user=current_user,
        servicesAll=Service.query.all(),
        services=calculate_pre_screen_results(
            fpl=patient.fpl_percentage,
            has_health_insurance=patient.insurance_status,
            is_eligible_for_medicaid="",
            service_ids=[s.id for s in services if s.has_screening_yn == 'Y']
        ),
        household_size=patient.household_members.count() + 1,
        household_income=patient.total_annual_income,
        fpl=patient.fpl_percentage,
        has_health_insurance=patient.insurance_status,
        is_eligible_for_medicaid="",
        referral_buttons=True,
        allowed_referral_service_ids=allowed_referral_service_ids,
        open_referral_service_ids=open_referral_service_ids
    )
Exemple #11
0
def patient_share(patient_id):
    """Displays the 'Share Patient' page, which includes prescreening
    results and allows users to send referrals.
    """
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    patient.update_stats()
    services = Service.query.all()

    if not current_user.is_patient_user() and current_user.service:
        allowed_referral_service_ids = [
            service.id
            for service in current_user.service.can_send_referrals_to
        ]
    else:
        allowed_referral_service_ids = []

    # Get ids of services where the patient already has open referrals,
    # to prevent user from sending duplicates.
    open_referral_service_ids = [
        r.to_service_id for r in patient.referrals
        if (r.in_sent_status() or r.in_sent_status())
    ]

    return render_template(
        'patient_share.html',
        patient=patient,
        current_user=current_user,
        servicesAll=Service.query.all(),
        services=calculate_pre_screen_results(
            fpl=patient.fpl_percentage,
            has_health_insurance=patient.insurance_status,
            is_eligible_for_medicaid="",
            service_ids=[s.id for s in services if s.has_screening_yn == 'Y']),
        household_size=patient.household_members.count() + 1,
        household_income=patient.total_annual_income,
        fpl=patient.fpl_percentage,
        has_health_insurance=patient.insurance_status,
        is_eligible_for_medicaid="",
        referral_buttons=True,
        allowed_referral_service_ids=allowed_referral_service_ids,
        open_referral_service_ids=open_referral_service_ids)
Exemple #12
0
def add_referral():
    """Adds new referral to the database. Called when user clicks
    'Send Referral' button."""
    check_patient_permission(request.form['patient_id'])
    referral = PatientReferral(
        patient_id=request.form['patient_id'],
        from_app_user_id=request.form['app_user_id'],
        to_service_id=request.form['service_id'],
        status='SENT'
    )
    db.session.add(referral)
    db.session.commit()
    service = Service.query.get(request.form['service_id'])
    patient = Patient.query.get(request.form['patient_id'])
    send_referral_notification_email(
        service=service,
        patient=patient,
        from_app_user=current_user
    )
    return jsonify()
Exemple #13
0
def patient_details(id):
    """Display the full patient details form for an existing user."""
    check_patient_permission(id)
    patient = Patient.query.get(id)
    form = (
        get_unsaved_form(request, patient, 'patient_details', PatientForm)
        or PatientForm(obj=patient)
    )

    if request.method == 'POST' and form.validate_on_submit():
        update_patient(patient, form, request.files)
        db.session.commit()
        patient.update_stats()
        return render_template(
            'patient_details.html',
            patient=patient,
            form=form,
            save_message=True
        )
    else:
        if request.method == 'GET':
            # If this patient has a referral to the current organization in SENT status,
            # update it to RECEIVED
            sent_referrals = [
                r for r in patient.referrals
                if r.to_service_id == current_user.service_id
                and r.in_sent_status()
            ]
            for referral in sent_referrals:
                referral.mark_received()
            if sent_referrals:
                db.session.commit()

            patient.update_stats()

        return render_template(
            'patient_details.html',
            patient=patient,
            form=form,
            save_message=False
        )
Exemple #14
0
def export_pdf(patient_id):
    """Create a PDF of a patient's information."""
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    form = PatientForm(obj=patient)
    filename = 'zipscreen_patient_' + str(patient_id) + '.pdf'
    html = render_template(
        'pdf_export.html',
        patient=patient,
        form=form,
        is_production=current_app.config['IS_PRODUCTION']
    )
    pdf = StringIO()
    pisa.CreatePDF(StringIO(html.encode('utf-8')), pdf)
    pdf.seek(0)
    return send_file(
        pdf,
        mimetype="application/pdf",
        attachment_filename=filename,
        as_attachment=True
    )
Exemple #15
0
def patient_screening_history(patient_id):
    """Display a patient's past referrals and screening results, and a form
    to enter new screening results.
    """
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    patient.update_stats()
    form = ScreeningResultForm()
    sliding_scale_options = SlidingScale.query.filter(
        SlidingScale.service_id == current_user.service_id)
    # Add the current organization's sliding scale options to the dropdown
    form.sliding_scale_id.choices = [
        (str(option.id), option.scale_name) for option in sliding_scale_options
    ] or [("", "N/A")]

    if form.validate_on_submit():
        screening_result = PatientScreeningResult()
        screening_result.service_id = current_user.service_id
        screening_result.eligible_yn = form.eligible_yn.data
        screening_result.sliding_scale_id = form.sliding_scale_id.data or None
        screening_result.notes = form.notes.data
        patient.screening_results.append(screening_result)

        # If the patient has an open referral to the current organization, mark
        # as completed
        open_referrals = [
            r for r in patient.referrals
            if r.to_service_id == current_user.service.id
            and r.in_received_status()
        ]
        for referral in open_referrals:
            referral.mark_completed()

        db.session.commit()

    return render_template('patient_screening_history.html',
                           patient=patient,
                           form=form)
Exemple #16
0
def patient_details(id):
    """Display the full patient details form for an existing user."""
    check_patient_permission(id)
    patient = Patient.query.get(id)
    form = (get_unsaved_form(request, patient, 'patient_details', PatientForm)
            or PatientForm(obj=patient))

    if request.method == 'POST' and form.validate_on_submit():
        update_patient(patient, form, request.files)
        db.session.commit()
        patient.update_stats()
        return render_template('patient_details.html',
                               patient=patient,
                               form=form,
                               save_message=True)

    # Delete empty rows at end of many-to-one tables
    remove_blank_rows(form)

    return render_template('patient_details.html',
                           patient=patient,
                           form=form,
                           save_message=False)
Exemple #17
0
def patient_screening_history(patient_id):
    """Display a patient's past referrals and screening results, and a form
    to enter new screening results.
    """
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    patient.update_stats()
    form = ScreeningResultForm()
    sliding_scale_options = SlidingScale.query.filter(
        SlidingScale.service_id == current_user.service_id
    )
    # Add the current organization's sliding scale options to the dropdown
    form.sliding_scale_id.choices = [
        (str(option.id), option.scale_name) for option in sliding_scale_options
    ] or [("", "N/A")]

    if form.validate_on_submit():
        screening_result = PatientScreeningResult()
        screening_result.service_id = current_user.service_id
        screening_result.eligible_yn = form.eligible_yn.data
        screening_result.sliding_scale_id = form.sliding_scale_id.data or None
        screening_result.notes = form.notes.data
        patient.screening_results.append(screening_result)

        # If the patient has an open referral to the current organization, mark
        # as completed
        open_referrals = [
            r for r in patient.referrals
            if r.to_service_id == current_user.service.id
            and r.in_received_status()
        ]
        for referral in open_referrals:
            referral.mark_completed()

        db.session.commit()

    return render_template('patient_screening_history.html', patient=patient, form=form)
Exemple #18
0
def patient_screening_history(patient_id):
    """Display a patient's past referrals and screening results, and a form
    to enter new screening results.
    """
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    patient.update_stats()
    form = ReferralCommentForm()

    if form.validate_on_submit():
        referral = PatientReferral.query.get(form.referral_id.data)
        referral_comment = PatientReferralComment()
        referral_comment.patient_referral_id = form.referral_id.data
        referral_comment.notes = form.notes.data
        db.session.add(referral_comment)
        db.session.commit()
        send_referral_comment_email(service=referral.to_service,
                                    patient=patient,
                                    referral=referral,
                                    commented_user=current_user)

    return render_template('patient_screening_history.html',
                           patient=patient,
                           form=form)
def patient_screening_history(patient_id):
    """Display a patient's past referrals and screening results, and a form
    to enter new screening results.
    """
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    patient.update_stats()
    form = ReferralCommentForm()

    if form.validate_on_submit():
        referral = PatientReferral.query.get(form.referral_id.data)
        referral_comment = PatientReferralComment()
        referral_comment.patient_referral_id = form.referral_id.data
        referral_comment.notes = form.notes.data
        db.session.add(referral_comment)
        db.session.commit()
        send_referral_comment_email(
            service=referral.to_service,
            patient=patient,
            referral=referral,
            commented_user=current_user
        )

    return render_template('patient_screening_history.html', patient=patient, form=form)
Exemple #20
0
def patient_overview(id):

    check_patient_permission(id)
    patient = Patient.query.get(id)
    patient.update_stats()

    prescreen_results = calculate_pre_screen_results(
        fpl=patient.fpl_percentage,
        has_health_insurance=patient.insurance_status,
        is_eligible_for_medicaid="",
        service_ids=[current_user.service_id])

    form = ScreeningResultForm()
    sliding_scale_options = SlidingScale.query.filter(
        SlidingScale.service_id == current_user.service_id)
    form.sliding_scale_id.choices = [("", "N/A")] + [
        (str(option.id), option.scale_name) for option in sliding_scale_options
    ]

    if form.validate_on_submit():
        screening_result = PatientScreeningResult()
        screening_result.service_id = current_user.service_id
        screening_result.eligible_yn = form.eligible_yn.data
        screening_result.sliding_scale_id = form.sliding_scale_id.data or None
        screening_result.notes = form.notes.data
        patient.screening_results.append(screening_result)

        # If the patient has an open referral to the current organization, mark
        # as completed
        open_referrals = [
            r for r in patient.referrals if
            r.to_service_id == current_user.service.id and r.in_sent_status()
        ]
        if open_referrals:
            screening_result.patient_referral_id = open_referrals[0].id
        for referral in open_referrals:
            referral.mark_completed()
            send_referral_closed_email(service=referral.to_service,
                                       patient=patient,
                                       from_app_user=referral.from_app_user,
                                       closed_user=current_user)

        db.session.commit()

    past_results = [
        r for r in patient.screening_results
        if r.service_id == current_user.service_id
    ]
    new_form = ScreeningResultForm(formdata=None)
    new_form.sliding_scale_id.choices = [("", "N/A")] + [
        (str(option.id), option.scale_name) for option in sliding_scale_options
    ]

    # if there is no referral id, then this is a screening result being saved
    # that is not associated to a referral

    if request.form and 'referral_id' in request.form:

        referral_form = ReferralCommentForm()

        if referral_form.validate_on_submit(
        ) and referral_form.notes.data != '':
            referral = PatientReferral.query.get(
                referral_form.referral_id.data)
            referral_comment = PatientReferralComment()
            referral_comment.patient_referral_id = referral_form.referral_id.data
            referral_comment.notes = referral_form.notes.data
            db.session.add(referral_comment)
            db.session.commit()
            send_referral_comment_email(service=referral.to_service,
                                        patient=patient,
                                        referral=referral,
                                        commented_user=current_user)
    else:
        referral_form = ReferralCommentForm(formdata=None)

    has_open_referral = bool([
        r for r in patient.referrals
        if r.status == 'SENT' and r.to_service_id == current_user.service.id
    ])

    return render_template('patient_overview.html',
                           patient=patient,
                           form=new_form,
                           service=prescreen_results[0],
                           past_results=past_results,
                           referral_form=referral_form,
                           has_open_referral=has_open_referral)
Exemple #21
0
def patient_overview(id):

    check_patient_permission(id)
    patient = Patient.query.get(id)

    # If this patient has a referral to the current organization in SENT status,
    # update it to RECEIVED
    sent_referrals = [
        r for r in patient.referrals
        if r.to_service_id == current_user.service_id and r.in_sent_status()
    ]
    for referral in sent_referrals:
        referral.mark_received()
    if sent_referrals:
        db.session.commit()

    patient.update_stats()

    prescreen_results = calculate_pre_screen_results(
        fpl=patient.fpl_percentage,
        has_health_insurance=patient.insurance_status,
        is_eligible_for_medicaid="",
        service_ids=[current_user.service_id])

    form = ScreeningResultForm()
    sliding_scale_options = SlidingScale.query.filter(
        SlidingScale.service_id == current_user.service_id)
    form.sliding_scale_id.choices = [
        (str(option.id), option.scale_name) for option in sliding_scale_options
    ] or [("", "N/A")]
    if form.validate_on_submit():
        screening_result = PatientScreeningResult()
        screening_result.service_id = current_user.service_id
        screening_result.eligible_yn = form.eligible_yn.data
        screening_result.sliding_scale_id = form.sliding_scale_id.data or None
        screening_result.notes = form.notes.data
        patient.screening_results.append(screening_result)

        # If the patient has an open referral to the current organization, mark
        # as completed
        open_referrals = [
            r for r in patient.referrals
            if r.to_service_id == current_user.service.id
            and r.in_received_status()
        ]
        for referral in open_referrals:
            referral.mark_completed()

        db.session.commit()

    past_results = [
        r for r in patient.screening_results
        if r.service_id == current_user.service_id
    ]
    new_form = ScreeningResultForm(formdata=None)
    new_form.sliding_scale_id.choices = [
        (str(option.id), option.scale_name) for option in sliding_scale_options
    ] or [("", "N/A")]

    return render_template('patient_overview.html',
                           patient=patient,
                           form=new_form,
                           service=prescreen_results[0],
                           past_results=past_results)
Exemple #22
0
def patient_history(patient_id):
    """Display all past edits to the patient's information"""
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    patient.update_stats()

    history = ActionLog.query.\
        filter(or_(
            and_(
                ActionLog.row_id == patient_id,
                ActionLog.table_name == 'patient'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.phone_numbers]),
                ActionLog.table_name == 'phone_number'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.addresses]),
                ActionLog.table_name == 'address'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.emergency_contacts]),
                ActionLog.table_name == 'emergency_contact'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.employers]),
                ActionLog.table_name == 'employer'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.document_images]),
                ActionLog.table_name == 'document_image'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.income_sources]),
                ActionLog.table_name == 'income_source'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.household_members]),
                ActionLog.table_name == 'household_member'
            )
        )).\
        order_by(ActionLog.action_timestamp.desc())
    # Filter out history entries that are only last modified/last modified by changes
    history = [i for i in history if not (
        i.changed_fields
        and set(i.changed_fields).issubset(['last_modified', 'last_modified_by'])
    )]

    services = dict((x.id, x) for x in Service.query.all())

    readable_names = dict(
        (column.name, column.info) for column in (
            chain(
                Patient.__table__.columns,
                PhoneNumber.__table__.columns,
                Address.__table__.columns,
                EmergencyContact.__table__.columns,
                HouseholdMember.__table__.columns,
                IncomeSource.__table__.columns,
                Employer.__table__.columns,
                DocumentImage.__table__.columns
            )
        )
    )

    return render_template(
        'patient_history.html',
        patient=patient,
        history=history,
        services=services,
        readable_names=readable_names
    )
Exemple #23
0
def patient_print(patient_id):
    """Format the patient details page for printing."""
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    form = PatientForm(obj=patient)
    return render_template('patient_details.html', patient=patient, form=form)
Exemple #24
0
def export_document_image(image_id):
    """Display an uploaded document image."""
    _image = DocumentImage.query.get_or_404(image_id)
    check_patient_permission(_image.patient.id)
    return render_template('export_document_image.html', image_id=image_id)
Exemple #25
0
def export_document_image(image_id):
    """Display an uploaded document image."""
    _image = DocumentImage.query.get_or_404(image_id)
    check_patient_permission(_image.patient.id)
    return render_template('export_document_image.html', image_id=image_id)
Exemple #26
0
def patient_overview(id):

    check_patient_permission(id)
    patient = Patient.query.get(id)

    # If this patient has a referral to the current organization in SENT status,
    # update it to RECEIVED
    sent_referrals = [
        r for r in patient.referrals
        if r.to_service_id == current_user.service_id
        and r.in_sent_status()
    ]
    for referral in sent_referrals:
        referral.mark_received()
    if sent_referrals:
        db.session.commit()

    patient.update_stats()

    prescreen_results = calculate_pre_screen_results(
        fpl=patient.fpl_percentage,
        has_health_insurance=patient.insurance_status,
        is_eligible_for_medicaid="",
        service_ids=[current_user.service_id]
    )

    form = ScreeningResultForm()
    sliding_scale_options = SlidingScale.query.filter(
        SlidingScale.service_id == current_user.service_id
    )
    form.sliding_scale_id.choices = [
        (str(option.id), option.scale_name) for option in sliding_scale_options
    ] or [("", "N/A")]
    if form.validate_on_submit():
        screening_result = PatientScreeningResult()
        screening_result.service_id = current_user.service_id
        screening_result.eligible_yn = form.eligible_yn.data
        screening_result.sliding_scale_id = form.sliding_scale_id.data or None
        screening_result.notes = form.notes.data
        patient.screening_results.append(screening_result)

        # If the patient has an open referral to the current organization, mark
        # as completed
        open_referrals = [
            r for r in patient.referrals
            if r.to_service_id == current_user.service.id
            and r.in_received_status()
        ]
        for referral in open_referrals:
            referral.mark_completed()

        db.session.commit()

    past_results = [r for r in patient.screening_results if r.service_id == current_user.service_id]
    new_form = ScreeningResultForm(formdata=None)
    new_form.sliding_scale_id.choices = [
        (str(option.id), option.scale_name) for option in sliding_scale_options
    ] or [("", "N/A")]

    return render_template(
        'patient_overview.html',
        patient=patient,
        form=new_form,
        service=prescreen_results[0],
        past_results=past_results
    )
Exemple #27
0
def patient_print(patient_id):
    """Format the patient details page for printing."""
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    form = PatientForm(obj=patient)
    return render_template('patient_details.html', patient=patient, form=form)
Exemple #28
0
def patient_history(patient_id):
    """Display all past edits to the patient's information"""
    check_patient_permission(patient_id)
    patient = Patient.query.get(patient_id)
    patient.update_stats()

    history = ActionLog.query.\
        filter(or_(
            and_(
                ActionLog.row_id == patient_id,
                ActionLog.table_name == 'patient'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.phone_numbers]),
                ActionLog.table_name == 'phone_number'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.addresses]),
                ActionLog.table_name == 'address'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.emergency_contacts]),
                ActionLog.table_name == 'emergency_contact'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.employers]),
                ActionLog.table_name == 'employer'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.document_images]),
                ActionLog.table_name == 'document_image'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.income_sources]),
                ActionLog.table_name == 'income_source'
            ),
            and_(
                ActionLog.row_id.in_([p.id for p in patient.household_members]),
                ActionLog.table_name == 'household_member'
            )
        )).\
        order_by(ActionLog.action_timestamp.desc())
    # Filter out history entries that are only last modified/last modified by changes
    history = [
        i for i in history if not (i.changed_fields and set(
            i.changed_fields).issubset(['last_modified', 'last_modified_by']))
    ]

    services = dict((x.id, x) for x in Service.query.all())

    readable_names = dict((column.name, column.info) for column in (chain(
        Patient.__table__.columns, PhoneNumber.__table__.columns,
        Address.__table__.columns, EmergencyContact.__table__.columns,
        HouseholdMember.__table__.columns, IncomeSource.__table__.columns,
        Employer.__table__.columns, DocumentImage.__table__.columns)))

    return render_template('patient_history.html',
                           patient=patient,
                           history=history,
                           services=services,
                           readable_names=readable_names)
def patient_overview(id):

    check_patient_permission(id)
    patient = Patient.query.get(id)
    patient.update_stats()

    prescreen_results = calculate_pre_screen_results(
        fpl=patient.fpl_percentage,
        has_health_insurance=patient.insurance_status,
        is_eligible_for_medicaid="",
        service_ids=[current_user.service_id]
    )

    form = ScreeningResultForm()
    sliding_scale_options = SlidingScale.query.filter(
        SlidingScale.service_id == current_user.service_id
    )
    form.sliding_scale_id.choices = [("", "N/A")] + [
        (str(option.id), option.scale_name) for option in sliding_scale_options
    ]

    if form.validate_on_submit():
        screening_result = PatientScreeningResult()
        screening_result.service_id = current_user.service_id
        screening_result.eligible_yn = form.eligible_yn.data
        screening_result.sliding_scale_id = form.sliding_scale_id.data or None
        screening_result.notes = form.notes.data
        patient.screening_results.append(screening_result)

        # If the patient has an open referral to the current organization, mark
        # as completed
        open_referrals = [
            r for r in patient.referrals
            if r.to_service_id == current_user.service.id
            and r.in_sent_status()
        ]
        if open_referrals:
            screening_result.patient_referral_id = open_referrals[0].id
        for referral in open_referrals:
            referral.mark_completed()
            send_referral_closed_email(
                service=referral.to_service,
                patient=patient,
                from_app_user=referral.from_app_user,
                closed_user=current_user
            )

        db.session.commit()

    past_results = [r for r in patient.screening_results
                    if r.service_id == current_user.service_id]
    new_form = ScreeningResultForm(formdata=None)
    new_form.sliding_scale_id.choices = [("", "N/A")] + [
        (str(option.id), option.scale_name) for option in sliding_scale_options
    ]

    # if there is no referral id, then this is a screening result being saved
    # that is not associated to a referral

    if request.form and 'referral_id' in request.form:

        referral_form = ReferralCommentForm()

        if referral_form.validate_on_submit() and referral_form.notes.data != '':
            referral = PatientReferral.query.get(referral_form.referral_id.data)
            referral_comment = PatientReferralComment()
            referral_comment.patient_referral_id = referral_form.referral_id.data
            referral_comment.notes = referral_form.notes.data
            db.session.add(referral_comment)
            db.session.commit()
            send_referral_comment_email(
                service=referral.to_service,
                patient=patient,
                referral=referral,
                commented_user=current_user
            )
    else:
        referral_form = ReferralCommentForm(formdata=None)

    has_open_referral = bool(   
        [r for r in patient.referrals 
         if r.status == 'SENT' and r.to_service_id == current_user.service.id]
    )

    return render_template(
        'patient_overview.html',
        patient=patient,
        form=new_form,
        service=prescreen_results[0],
        past_results=past_results,
        referral_form=referral_form,
        has_open_referral=has_open_referral
    )