care icon indicating copy to clipboard operation
care copied to clipboard

Add configurable report templates

Open praffq opened this issue 8 months ago • 6 comments

Proposed Changes

  • configrable template

Associated Issue

  • Link to issue here, explain how the proposed solution will solve the reported issue/ feature request.

Architecture changes

  • Remove this section if not used

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 nested request validation and improved error handling for discharge summary generation.
    • Introduced ReportTemplateViewSet with full CRUD, filtering, and display report endpoints.
    • Added global registries for report renderers and sections with built-in Typst renderer.
    • Added modular, configuration-driven discharge summary rendering with flexible header and sections.
    • Added new report sections: patient info, diagnosis, symptoms, medication requests, allergies, observations, care team, files, discharge advice, and custom content.
    • Introduced ReportViewSet with filtering, secure read access, and report archiving API.
    • Added signed URL generation for report access with render format and template slug support.
    • Added dynamic file and report manager loading via settings.
  • Improvements

    • Refined image download caching with size and MIME type validation.
    • Replaced inline discharge summary template with JSON config and Typst templates.
    • Added abstract header builder and Typst header builder for flexible header layouts.
    • Enhanced permission checks and authorization handlers for templates and reports.
    • Migrated discharge summaries from file uploads to dedicated report model with archiving.
    • Expanded encounter permission contexts to include facility-level permissions.
    • Improved fixture loading to assign default discharge summary templates to facilities.
    • Added environment-configurable max image size limit for reports.
  • Bug Fixes

    • Removed development-only discharge summary preview endpoint and related routes.
    • Replaced generic permission errors with proper permission denied exceptions in file upload API.
  • Chores

    • Added detailed Pydantic schemas for report templates and reports with validation and serialization.
    • Registered report and template routes in API router.
    • Added new report templates and Typst layout files (list, table, text, page layout).
    • Added global imports for report and template models and authorization modules.

praffq avatar Apr 24 '25 11:04 praffq

📝 Walkthrough

Walkthrough

This change introduces a comprehensive, modular reporting system for discharge summaries and other reports in the EMR. It adds new models, APIs, permissions, renderers, registries, and Pydantic specs for report templates. The discharge summary logic is refactored to use a configuration-driven, pluggable rendering pipeline. Legacy template files and preview endpoints are removed.

Changes

Cohort / File(s) Change Summary
API & Viewsets
care/emr/api/viewsets/encounter.py, care/emr/api/viewsets/report.py, care/emr/api/viewsets/template.py
Refactored encounter discharge summary generation with Pydantic spec, input validation, and async task update. Added new viewsets for report and report template management, including CRUD, filtering, and custom actions for rendering and listing templates.
Models & Migrations
care/emr/models/report.py, care/emr/models/template.py, care/emr/models/__init__.py, care/emr/migrations/0030_reporttemplate.py, care/emr/migrations/0031_report.py, care/emr/migrations/0032_auto_20250525_0228.py
Introduced Report and ReportTemplate models with associated migrations. Migrated discharge summary files from FileUpload to Report. Updated model imports.
Report Rendering System
care/emr/reports/__init__.py, care/emr/reports/discharge_summary.py, care/emr/reports/renderer/base.py, care/emr/reports/renderer/dummy.py, care/emr/reports/renderer/typst.py, care/emr/reports/renderer/__init__.py, care/emr/reports/headers/base.py, care/emr/reports/headers/typst_header.py, care/emr/reports/sections/*, care/emr/reports/utils.py, care/emr/registries/report/renderer.py, care/emr/registries/report/section.py
Added modular renderer and section registries, Typst-based rendering, header builders, and multiple report sections. Refactored discharge summary generation to use configuration and pluggable renderers/sections. Added utility for image caching and section registration.
Template & Report Spec System
care/emr/resources/template/spec.py, care/emr/resources/report/spec.py
Introduced detailed Pydantic models for report template configuration, validation, and serialization, including layout, header, and section specs. Added report spec models for serialization and API use.
Permissions & Authorization
care/security/authorization/template.py, care/security/authorization/__init__.py, care/security/permissions/template.py, care/security/permissions/base.py
Added template-specific permissions and authorization logic. Integrated template permissions into the internal permission controller.
Settings & Config
config/settings/base.py, config/settings/custom_limits.py, care/utils/csp/config.py
Added settings for report/file managers and image size limits. Updated bucket config for report storage.
Management & Utilities
care/emr/management/commands/load_fixtures.py, care/utils/reports/load_default_report_config.py
Added logic to batch-create default discharge summary templates for facilities and load default config from JSON.
Templates
care/templates/reports/typst/list.typ, care/templates/reports/typst/page_layout.typ, care/templates/reports/typst/table.typ, care/templates/reports/typst/text.typ, care/templates/reports/patient_discharge_summary_pdf_template.typ
Added new Typst templates for modular rendering. Removed the legacy monolithic discharge summary PDF template.
Data & Fixtures
data/reports/discharge_summary_config.json
Added a comprehensive JSON configuration for discharge summary report layout and sections.
Miscellaneous
care/emr/resources/file_upload/spec.py, care/emr/models/file_upload.py, care/emr/tasks/discharge_summary.py, care/emr/tasks/cleanup_incomplete_file_uploads.py, care/emr/resources/permissions.py, care/emr/api/viewsets/file_upload.py, .gitignore, config/api_router.py, config/urls.py, care/facility/models/facility.py
Updated file upload logic, task signatures, permission contexts, and cleaned up legacy endpoints and ignore rules. Minor code hygiene.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant RendererRegistry
    participant SectionRegistry
    participant Renderer
    participant Section
    participant Storage

    Client->>API: POST /encounter/{id}/generate_discharge_summary
    API->>RendererRegistry: get(render_format)
    RendererRegistry-->>API: Renderer class
    API->>SectionRegistry: get(section_name)
    SectionRegistry-->>API: Section class
    API->>Renderer: render_page_layout, render_header, etc.
    API->>Section: fetch_data, render
    Section-->>Renderer: render_table/list/text
    Renderer-->>API: Rendered output
    API->>Renderer: compile(template_code, images)
    Renderer->>Storage: Upload PDF
    Storage-->>API: File URL
    API-->>Client: Success / Signed URL

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~90+ minutes

Possibly related PRs

  • ohcnetwork/care#2700: Adds initial discharge summary generation, preview, and email actions. Related as both PRs modify discharge summary logic, but this PR supersedes with full modularization.
  • ohcnetwork/care#2971: Adds a discharge_summary_advice field to the encounter and integrates it into discharge summary data and template. This PR builds on that by modularizing and integrating the field into the new system.

Suggested labels

waiting-for-review

Suggested reviewers

  • vigneshhari

Poem

Reports now modular, templates in tow,
No more monoliths, just Typst’s clean flow.
Registries gather, renderers align,
Section by section, the summaries shine.
Goodbye old preview, hello config delight—
Reviewing this PR? Pack snacks for the night!
📝✨

[!NOTE]

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • [ ] 📝 Generate Docstrings
🧪 Generate unit tests
  • [ ] Create PR with unit tests
  • [ ] Post copyable unit tests in a comment
  • [ ] Commit unit tests in branch prafful/feat/configrable-templates

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot] avatar Apr 24 '25 11:04 coderabbitai[bot]

Codecov Report

Attention: Patch coverage is 44.83871% with 684 lines in your changes missing coverage. Please review.

Project coverage is 50.82%. Comparing base (692092c) to head (3ee244c).

Files with missing lines Patch % Lines
care/emr/resources/template/spec.py 54.40% 114 Missing :warning:
care/emr/reports/sections/base.py 26.82% 60 Missing :warning:
care/emr/reports/discharge_summary.py 23.68% 58 Missing :warning:
care/emr/api/viewsets/template.py 48.38% 48 Missing :warning:
care/emr/reports/headers/typst_header.py 14.89% 40 Missing :warning:
care/emr/reports/headers/base.py 26.00% 32 Missing and 5 partials :warning:
care/emr/reports/sections/medication_request.py 28.00% 36 Missing :warning:
care/emr/api/viewsets/report.py 50.00% 28 Missing :warning:
care/emr/reports/renderer/typst.py 41.66% 28 Missing :warning:
care/emr/reports/utils.py 25.00% 27 Missing :warning:
... and 23 more
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #3005      +/-   ##
===========================================
- Coverage    51.29%   50.82%   -0.47%     
===========================================
  Files          251      280      +29     
  Lines        11370    12505    +1135     
  Branches      1280     1419     +139     
===========================================
+ Hits          5832     6356     +524     
- Misses        5517     6123     +606     
- Partials        21       26       +5     

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

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

codecov[bot] avatar Apr 24 '25 12:04 codecov[bot]

@coderabbitai full review

praffq avatar May 07 '25 20:05 praffq

✅ Actions performed

Full review triggered.

coderabbitai[bot] avatar May 07 '25 20:05 coderabbitai[bot]

@coderabbitai full review

praffq avatar May 18 '25 16:05 praffq

✅ Actions performed

Full review triggered.

coderabbitai[bot] avatar May 18 '25 16:05 coderabbitai[bot]