Skip to content

[Eng-765] feat :add patient appointment support in report builder - #3716

Open
nandkishorr wants to merge 6 commits into
developfrom
ENG-765-add-patient-appointment-support-in-report-builder
Open

[Eng-765] feat :add patient appointment support in report builder#3716
nandkishorr wants to merge 6 commits into
developfrom
ENG-765-add-patient-appointment-support-in-report-builder

Conversation

@nandkishorr

@nandkishorr nandkishorr commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Proposed Changes

  • Added context builders for EMR models

    • TokenBooking,TokenSlot,Token,Token,ScheduleResource,Availability,Schedule.

Merge Checklist

  • Tests added/fixed
  • Update docs in /docs
  • Linting Complete
  • Any other necessary step

Only PR's with test cases included and passing lint and test pipelines will be reviewed

@ohcnetwork/care-backend-maintainers @ohcnetwork/care-backend-admins

Summary by CodeRabbit

  • New Features
    • Added report data for token bookings (resource, availability, start/end times, booking status, booked-by, optional notes, charges, and token details).
    • Added appointment-related encounter fields (facility appointments and encounter-linked appointment).
    • Added schedule and availability report fields (resource/user info, validity windows, slot types, durations, and reasons).
    • Added token reporting fields (token number/status/notes and token category details, including resource types).
  • Bug Fixes
    • Improved charge item context retrieval so charge items are pulled using the correct parent/attribute.

@nandkishorr
nandkishorr requested a review from a team as a code owner July 24, 2026 06:54
Copilot AI review requested due to automatic review settings July 24, 2026 06:54
@nandkishorr nandkishorr self-assigned this Jul 24, 2026
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fc3f9f54-357e-487f-8ce0-ce4f20e10732

📥 Commits

Reviewing files that changed from the base of the PR and between a881387 and e562379.

📒 Files selected for processing (4)
  • care/emr/reports/context_builder/data_points/booking.py
  • care/emr/reports/context_builder/data_points/charge_items.py
  • care/emr/reports/context_builder/data_points/encounter.py
  • care/emr/reports/context_builder/data_points/schedule.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • care/emr/reports/context_builder/data_points/schedule.py
  • care/emr/reports/context_builder/data_points/encounter.py

📝 Walkthrough

Walkthrough

Adds context-builder schemas for tokens, schedules, availabilities, token bookings, and appointment-related encounter fields. Charge-item resolution is split between queryset, category, and single-object builders.

Changes

Appointment context

Layer / File(s) Summary
Token, schedule, and availability context builders
care/emr/reports/context_builder/data_points/token.py, care/emr/reports/context_builder/data_points/schedule.py
Adds mapped fields and parent-derived builders for token categories, tokens, resources, schedules, and availabilities.
Token booking and charge-item context builders
care/emr/reports/context_builder/data_points/booking.py, care/emr/reports/context_builder/data_points/charge_items.py
Adds token slot and booking field definitions, queryset and single-object builders, and dedicated charge-item context resolution.
Encounter appointment wiring
care/emr/reports/context_builder/data_points/encounter.py
Adds patient-facility and encounter-associated appointment builders and exposes both through EncounterReportContext.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • ohcnetwork/care#3706: Refactors encounter context structure in the same EncounterReportContext area, which may affect alignment with the added appointment fields.

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: adding patient appointment support in the report builder.
Description check ✅ Passed It includes the proposed changes and merge checklist, though the associated issue section from the template is missing.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ENG-765-add-patient-appointment-support-in-report-builder

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Appointment-related report contexts are added across encounter, booking, scheduling, token, and charge-item data points.

  • Adds patient-facility and encounter-associated appointment fields to encounter reports.
  • Adds report builders for token bookings, slots, tokens, categories, schedules, resources, and availability.
  • Introduces a reusable single-charge-item context builder.

Confidence Score: 4/5

The PR is not safe to merge until the encounter-associated appointment builder returns a single booking or None rather than a QuerySet.

The attempted fix for encounters without appointments violates the single-object context contract, so accessing an associated appointment field can still terminate report rendering.

care/emr/reports/context_builder/data_points/encounter.py

Important Files Changed

Filename Overview
care/emr/reports/context_builder/data_points/encounter.py Adds appointment report fields, but the encounter-associated single-object builder still supplies a QuerySet and breaks nested field rendering.
care/emr/reports/context_builder/data_points/booking.py Adds token booking and slot report contexts with nested scheduling, billing, user, and token fields.
care/emr/reports/context_builder/data_points/charge_items.py Refactors shared charge-item fields and adds a single-object charge-item context builder.
care/emr/reports/context_builder/data_points/schedule.py Adds single-object report contexts for schedules, resources, and availability.
care/emr/reports/context_builder/data_points/token.py Adds report contexts for tokens and token categories.

Reviews (2): Last reviewed commit: "fix:review changes" | Re-trigger Greptile

Comment thread care/emr/reports/context_builder/data_points/encounter.py Outdated
Comment thread care/emr/reports/context_builder/data_points/booking.py Fixed
Comment thread care/emr/reports/context_builder/data_points/booking.py Fixed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds report-builder context support for scheduling/appointment-related EMR models so encounter reports can include token bookings (“appointments”) and their nested scheduling/token details.

Changes:

  • Introduces new nested context builders for Token/TokenCategory, Schedule/Availability, and TokenBooking/TokenSlot.
  • Extends the Encounter report context with fields for patient facility appointments and encounter-associated appointment.
  • Refactors ChargeItemContextBuilder.get_context() to use parent attribute (but currently introduces a queryset/single-object mismatch risk).

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
care/emr/reports/context_builder/data_points/token.py Adds nested contexts for token + token category fields for report templates.
care/emr/reports/context_builder/data_points/schedule.py Adds nested contexts for schedule resources, schedules, and availability.
care/emr/reports/context_builder/data_points/booking.py Adds nested contexts for token booking + token slot, linking in schedule/token/user/charge item contexts.
care/emr/reports/context_builder/data_points/encounter.py Adds encounter-level fields/context builders to fetch bookings (appointments) for facility/patient and for an encounter.
care/emr/reports/context_builder/data_points/charge_items.py Changes charge item context sourcing logic (needs adjustment to avoid runtime iteration failures).

Comment on lines +249 to +253
class EncounterAssociatedAppointmentContextBuilder(SingleTokenBookingContextBuilder):
def get_context(self):
return TokenBooking.objects.get(
associated_encounter_id=self.parent_context.id,
)
Comment thread care/emr/reports/context_builder/data_points/charge_items.py Outdated
Comment thread care/emr/reports/context_builder/data_points/schedule.py
Comment thread care/emr/reports/context_builder/data_points/booking.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@care/emr/reports/context_builder/data_points/booking.py`:
- Around line 72-75: Update the charge_item field in TokenBooking to use a
dedicated single-object charge-item context builder instead of
ChargeItemContextBuilder. Keep ChargeItemContextBuilder collection-oriented so
its override returns a queryset compatible with _filter(); in charge_items.py,
extract or reuse shared fields between the single-object and collection builders
as needed.

In `@care/emr/reports/context_builder/data_points/encounter.py`:
- Around line 249-253: Update
EncounterAssociatedAppointmentContextBuilder.get_context and the corresponding
logic around the additional referenced location to avoid assuming a unique
TokenBooking association: handle missing bookings without breaking report
generation and select duplicates deterministically, or enforce a one-to-one
model invariant if that is the intended contract. Preserve the existing
associated_encounter lookup behavior for valid single-booking cases.

In `@care/emr/reports/context_builder/data_points/schedule.py`:
- Around line 26-29: Update the resource_type Field declaration to apply the
existing RESOURCE_TYPE_CHOICES display mapping, ensuring values such as
healthcare_service are rendered with report-friendly labels instead of raw
identifiers. Preserve the field’s current display and description metadata.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 489011f4-e3fe-41f4-a06f-656feecc4015

📥 Commits

Reviewing files that changed from the base of the PR and between 6eb0df0 and a881387.

📒 Files selected for processing (5)
  • care/emr/reports/context_builder/data_points/booking.py
  • care/emr/reports/context_builder/data_points/charge_items.py
  • care/emr/reports/context_builder/data_points/encounter.py
  • care/emr/reports/context_builder/data_points/schedule.py
  • care/emr/reports/context_builder/data_points/token.py

Comment thread care/emr/reports/context_builder/data_points/booking.py Outdated
Comment thread care/emr/reports/context_builder/data_points/encounter.py
Comment thread care/emr/reports/context_builder/data_points/schedule.py
@codecov

codecov Bot commented Jul 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.60759% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.48%. Comparing base (6eb0df0) to head (e562379).

Files with missing lines Patch % Lines
...mr/reports/context_builder/data_points/schedule.py 87.50% 3 Missing ⚠️
...r/reports/context_builder/data_points/encounter.py 80.00% 2 Missing ⚠️
...e/emr/reports/context_builder/data_points/token.py 86.66% 2 Missing ⚠️
...emr/reports/context_builder/data_points/booking.py 95.83% 1 Missing ⚠️
...eports/context_builder/data_points/charge_items.py 83.33% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #3716      +/-   ##
===========================================
+ Coverage    79.45%   79.48%   +0.03%     
===========================================
  Files          480      483       +3     
  Lines        23215    23289      +74     
  Branches      2420     2420              
===========================================
+ Hits         18446    18512      +66     
- Misses        4165     4173       +8     
  Partials       604      604              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copilot AI review requested due to automatic review settings July 24, 2026 09:29
Comment on lines +250 to +252
def get_context(self):
return TokenBooking.objects.filter(
associated_encounter_id=self.parent_context.id

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Single appointment remains a QuerySet

When a report accesses a field such as associated_appointment.status, this single-object context stores the QuerySet returned by filter() and resolves the field against that QuerySet rather than a TokenBooking. The resulting attribute lookup fails during report rendering; an empty QuerySet also bypasses the context builder's None handling, so the optional-appointment crash remains.



class AccountChargeItemContextBuilder(ChargeItemContextBuilder):
class AccountChargeItemContextBuilder(ChargeItemContextBuilder, QuerysetContextBuilder):
Comment on lines +125 to +127
class CategoryChargeItemContextBuilder(
ChargeItemContextBuilder, QuerysetContextBuilder
):

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Comments suppressed due to low confidence (3)

care/emr/reports/context_builder/data_points/encounter.py:253

  • EncounterAssociatedAppointmentContextBuilder inherits SingleTokenBookingContextBuilder (single-object), but get_context currently returns a QuerySet. That will break field access (the TokenBooking fields will be resolved against a QuerySet). The Encounter model already has an appointment FK to TokenBooking, so this can be returned directly and avoids an extra query.
class EncounterAssociatedAppointmentContextBuilder(SingleTokenBookingContextBuilder):
    def get_context(self):
        return TokenBooking.objects.filter(
            associated_encounter_id=self.parent_context.id
        )

care/emr/reports/context_builder/data_points/token.py:26

  • TokenCategoryContextBuilder.resource_type mapping assumes rc is always present. If the category is missing (e.g., because the parent Token is null), the mapping lambda will raise. Guarding for falsy contexts makes templates safer to evaluate.
    resource_type = Field(
        display="Resource Type",
        description="Type of the resource associated with the token category",
        mapping=lambda rc: RESOURCE_CATEGORY_RESOURCE_TYPE.get(
            rc.resource_type, rc.resource_type.replace("_", " ").title()
        ),

care/emr/reports/context_builder/data_points/schedule.py:78

  • TokenSlot.availability is nullable (Availability FK is null=True). When availability is null, AvailabilityContextBuilder.context becomes None and the slot_type mapping lambda will raise on a.slot_type. Guard for missing availability so templates can safely dereference slot_type, and update the description to match SlotTypeOptions (open/appointment/closed).
    slot_type = Field(
        display="Slot Type",
        description="Type of the slot (e.g., token, appointment)",
        mapping=lambda a: AVAILABILITY_SLOT_TYPE.get(
            a.slot_type, a.slot_type.replace("_", " ").title()
        ),
    )

Comment on lines +241 to +246
class PatientFacilityAppointmentContextBuilder(TokenBookingContextBuilder):
def get_context(self):
return TokenBooking.objects.filter(
patient_id=self.parent_context.patient.id,
token_slot__resource__facility_id=self.parent_context.facility.id,
)
Comment on lines +135 to +136
def get_context(self):
return getattr(self.parent_context, self.parent_attribute)
Comment on lines +14 to +16
def get_context(self):
return getattr(self.parent_context, self.parent_attribute)

Comment on lines +41 to +42
def get_context(self):
return getattr(self.parent_context, self.parent_attribute)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants