Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix medication statement and medication request #2777

Conversation

rithviknishad
Copy link
Member

@rithviknishad rithviknishad commented Jan 24, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced medication statement update functionality with a dedicated update specification.
    • Added validation for medication and encounter fields in medication requests and statements.
    • Introduced a new test class for validating medication statement API endpoints.
  • Bug Fixes

    • Improved data integrity checks for medication-related specifications, including encounter validation.
  • Refactor

    • Updated class inheritance and specification structures for medication-related resources.
    • Refined field validation methods for medication requests and statements.
  • Tests

    • Added new tests for medication statement API permissions and functionality.

@rithviknishad rithviknishad requested a review from a team as a code owner January 24, 2025 09:52
Copy link
Contributor

coderabbitai bot commented Jan 24, 2025

📝 Walkthrough

Walkthrough

The pull request introduces updates to medication-related specifications across multiple files in the care/emr directory. The changes primarily focus on enhancing the structure of medication statement and request specifications by reintroducing the encounter field, adding update specifications, and implementing validation methods. These modifications aim to improve the robustness of medication-related data handling and ensure more precise validation of medication-related resources. It’s almost as if they realized how important these updates were—how refreshing!

Changes

File Change Summary
care/emr/api/viewsets/medication_statement.py Added MedicationStatementUpdateSpec to MedicationStatementViewSet, including pydantic_update_model attribute.
care/emr/resources/medication/request/spec.py - Reintroduced encounter field in BaseMedicationRequestSpec and MedicationRequestSpec
- Added validate_encounter_exists method
- Updated MedicationRequestUpdateSpec to inherit from BaseMedicationRequestSpec
care/emr/resources/medication/statement/spec.py - Created MedicationStatementUpdateSpec
- Moved encounter to MedicationStatementSpec
- Added field validators for medication and encounter
care/emr/tests/test_medication_request.py Updated test_update_medication_request_with_permission to set intent field during update and added assertions.
care/emr/tests/test_medication_statement.py Added TestMedicationStatementApi class to test medication statement API endpoints with various permission scenarios.

Sequence Diagram

sequenceDiagram
    participant Client
    participant MedicationStatementViewSet
    participant MedicationStatementUpdateSpec
    participant Database

    Client->>MedicationStatementViewSet: Request Update
    MedicationStatementViewSet->>MedicationStatementUpdateSpec: Validate Update
    MedicationStatementUpdateSpec->>Database: Validate Encounter
    MedicationStatementUpdateSpec->>Database: Validate Medication
    Database-->>MedicationStatementUpdateSpec: Validation Result
    MedicationStatementUpdateSpec-->>MedicationStatementViewSet: Validated Data
    MedicationStatementViewSet-->>Client: Update Response
Loading

Possibly related PRs

  • Add requester to MedicationRequest and basic authzn. tests #2773: This PR adds a requester field to the MedicationRequest class, which is directly related to the changes in the main PR that enhance the MedicationStatementViewSet by introducing a new update specification. Both PRs involve modifications to the medication-related specifications and models.

Suggested reviewers

  • sainak
  • vigneshhari

Poem

🏥 Medication's dance of code so fine,
Encounters validated, specs now align.
Update specs bloom like digital spring,
Validators chirp, make data's heart sing!
A symphony of bytes, oh so divine. 🩺
Who knew updates could be this sublime?

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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. (Beta)
  • @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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
care/emr/resources/medication/statement/spec.py (1)

82-91: Thoughtful addition of MedicationStatementUpdateSpec.

Implementing a dedicated update spec is a clean way to validate medication statements during updates. You might eventually unify these patterns across your medication resources to reduce duplication.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2f9fa83 and 818a2fc.

📒 Files selected for processing (3)
  • care/emr/api/viewsets/medication_statement.py (2 hunks)
  • care/emr/resources/medication/request/spec.py (2 hunks)
  • care/emr/resources/medication/statement/spec.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)
🔇 Additional comments (5)
care/emr/api/viewsets/medication_statement.py (2)

12-12: Good import addition.

Adding MedicationStatementUpdateSpec import aligns well with your update flow.


27-27: Verify usage of the newly assigned update model.

Setting pydantic_update_model = MedicationStatementUpdateSpec is a strong improvement. It might be worth running a quick check to ensure all update calls are in sync with this new spec.

✅ Verification successful

Everything looks perfectly fine here, but you probably knew that already

The MedicationStatementUpdateSpec is properly configured in the viewset and follows the standard EMR pattern with EMRModelViewSet. The update operations will automatically use this spec for validation, just as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching for references to the update model within medication statement code.
rg 'MedicationStatementUpdateSpec' -A 5

Length of output: 1579


Script:

#!/bin/bash
# Search for update operations and PUT/PATCH endpoints
ast-grep --pattern 'def update($$$) { $$$ }'
rg -B 2 -A 2 'PUT|PATCH' care/emr/api/viewsets/medication_statement.py

Length of output: 119


Script:

#!/bin/bash
# Check the class hierarchy and router configurations
ast-grep --pattern 'class MedicationStatement$$$ViewSet($$$) { $$$ }'
rg -B 2 'class MedicationStatement.*ViewSet'

Length of output: 292


Script:

#!/bin/bash
# Get the complete class definition with context
rg -A 10 'class MedicationStatementViewSet' care/emr/api/viewsets/medication_statement.py

Length of output: 621

care/emr/resources/medication/request/spec.py (2)

231-231: Reintroducing encounter.

Re-introducing encounter: UUID4 in MedicationRequestSpec is consistent with the specifications you've outlined. Small caution: watch out for potential null or missing encounters in certain scenarios.


257-257: Unified inheritance approach for updates.

The shift to class MedicationRequestUpdateSpec(BaseMedicationRequestSpec): is a tidy choice, helping to keep request specs consistent. A quick integration test might be beneficial to confirm no subtle breaks.

✅ Verification successful

Oh look, a perfectly reasonable inheritance change

The inheritance structure is consistent with other specs in the file, and the update spec maintains its focused responsibility of handling status updates. I mean, it would have been concerning if it didn't, but thankfully it does.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching for usage of MedicationRequestUpdateSpec
rg 'MedicationRequestUpdateSpec' -A 5

Length of output: 1543


Script:

#!/bin/bash
# Check the base class implementation and other similar specs
ast-grep --pattern 'class BaseMedicationRequestSpec {
  $$$
}'

# Look for test files
rg -g '*test*.py' 'MedicationRequestUpdateSpec|BaseMedicationRequestSpec' -A 3

Length of output: 145


Script:

#!/bin/bash
# Check for base class definition and show context
rg "class BaseMedicationRequestSpec" -A 10

# Show the entire spec file to understand the structure
cat care/emr/resources/medication/request/spec.py

Length of output: 8339

care/emr/resources/medication/statement/spec.py (1)

55-56: Encounter field reintroduction.

Adding encounter: UUID4 here ensures the statement is properly linked to its encounter. Although this does duplicate logic from your medication request specs, it's still acceptable.

Copy link

codecov bot commented Jan 24, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 65.01%. Comparing base (2f9fa83) to head (ef08290).
Report is 5 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2777      +/-   ##
===========================================
+ Coverage    64.90%   65.01%   +0.10%     
===========================================
  Files          252      252              
  Lines        12761    12767       +6     
  Branches      1121     1121              
===========================================
+ Hits          8283     8300      +17     
+ Misses        4369     4355      -14     
- Partials       109      112       +3     

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
care/emr/tests/test_medication_statement.py (3)

11-43: Consider using setUpTestData for performance gains.
While setUp is acceptable, switching to setUpTestData can speed up repeated test runs by creating shared objects once—assuming test isolation is preserved. But if you fancy more runs, that's okay too.


101-123: Use HTTP 201 for creation responses.
A small best practice: resource creation typically returns HTTP 201. If the API is indeed returning 200, that’s acceptable but slightly unconventional. Just ensure consistency across endpoints to avoid confusion.


124-158: Consider including partial updates (HTTP PATCH).
Your coverage of full updates is thorough. Having a test for partial updates would be beneficial, especially if your view supports PATCH. By the look of things here, one can only guess if partial updates are relevant.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa9c256 and ef08290.

📒 Files selected for processing (1)
  • care/emr/tests/test_medication_statement.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)
🔇 Additional comments (5)
care/emr/tests/test_medication_statement.py (5)

1-2: Good usage of patch for mocking.
The imports for patch from unittest.mock are perfectly fine here and help isolate external dependencies in tests.


6-8: Commendable permission checks import.
Importing EncounterPermissions and PatientPermissions keeps the tests consistent with the security model.


44-52: Helper URL method is well-structured.
The _get_medication_statement_url helper keeps the code DRY and easy to follow. Kudos.


53-80: Data factories are well-handled.
Your approach to generating MedicationStatement data with create_medication_statement and get_medication_statement_data is neat and ensures test clarity.


81-100: Nice distinction between permission/no-permission in list tests.
Good job covering both success (can_view_clinical_data) and forbidden scenarios, ensuring robust test coverage for the read API.

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