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

Add chronic condition api #2775

Merged
merged 3 commits into from
Jan 24, 2025
Merged

Add chronic condition api #2775

merged 3 commits into from
Jan 24, 2025

Conversation

sainak
Copy link
Member

@sainak sainak commented Jan 24, 2025

Proposed Changes

  • Add chronic condition api

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 support for Chronic Conditions management in the patient record system.
    • Enhanced EMR (Electronic Medical Record) functionality with more flexible condition tracking.
  • Bug Fixes

    • Modified encounter field in conditions to allow null and blank entries.
    • Improved permission handling for clinical data access.
  • Refactor

    • Updated logging configuration for better audit trail tracking.
    • Streamlined API viewsets and resource specifications for conditions.
  • Tests

    • Added comprehensive test coverage for Chronic Condition ViewSet.
    • Improved test warning handling for datetime-related tests.
    • Removed outdated test case for unregistering non-existent flags.

@sainak sainak requested a review from a team as a code owner January 24, 2025 08:45
Copy link
Contributor

coderabbitai bot commented Jan 24, 2025

📝 Walkthrough

Walkthrough

This pull request introduces several modifications across multiple files, focusing on enhancing chronic condition management, updating migration scripts, and refining API viewsets. The changes primarily involve adding a new ChronicConditionViewSet, updating model relationships, modifying logging configurations, and adjusting test suites to handle datetime warnings. The modifications aim to improve data handling, permission checks, and overall system flexibility, though perhaps a touch more attention to detail wouldn't hurt.

Changes

File Change Summary
care/abdm/migrations/ Removed migration scripts related to patient-abhanumber relationship
care/audit_log/middleware.py Updated logger name from __name__ to "audit_log"
care/emr/api/viewsets/... Added ChronicConditionViewSet, updated viewset logic in condition.py
care/emr/models/condition.py Modified encounter field to allow null and blank values
care/emr/resources/condition/spec.py Renamed classes, added ChronicConditionUpdateSpec
care/emr/tests/... Added @ignore_warnings decorator to test classes
config/api_router.py Registered ChronicConditionViewSet for patient routes
config/settings/test.py Added "audit_log" logger configuration
pyproject.toml Updated coverage and linter configurations

Sequence Diagram

sequenceDiagram
    participant User
    participant ChronicConditionViewSet
    participant AuthorizationController
    participant Patient
    participant Encounter

    User->>ChronicConditionViewSet: Create/Update Chronic Condition
    ChronicConditionViewSet->>AuthorizationController: Check Permissions
    AuthorizationController-->>ChronicConditionViewSet: Permission Result
    ChronicConditionViewSet->>Patient: Validate Patient Access
    ChronicConditionViewSet->>Encounter: Check Encounter Status
    ChronicConditionViewSet->>ChronicConditionViewSet: Perform Create/Update
Loading

Possibly related PRs

Suggested reviewers

  • vigneshhari

Poem

🩺 Chronic conditions, code so neat
Migrations dance, permissions complete
Viewsets bloom like digital flowers
Warnings silenced in testing hours
CodeRabbit's magic, subtle and sweet! 🌟

✨ 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 (13)
care/emr/api/viewsets/condition.py (4)

6-15: Cohesive import structure
You’ve consistently imported necessary modules (mixins, models, specs, AuthorizationController). While it’s workable, a small check: be sure that all newly introduced dependencies are indeed used, to prevent build-up of unused imports over time.

Also applies to: 19-19, 25-28, 31-31


170-175: authorize_create
Good that you’re checking can_write_patient_obj for the identified patient_external_id. The error message, however, references updating an “encounter,” which may confuse the user if the real error pertains to the patient. Consider updating the message for clarity.

- raise PermissionDenied("You do not have permission to update encounter")
+ raise PermissionDenied("You do not have permission to create a condition for this patient")

176-179: authorize_update
Delegating to authorize_create is a pragmatic approach, though it might be slightly indirect. If the create permission check changes in the future, keep in mind to update this as well.


186-192: perform_update
Verifies can_update_encounter_obj before proceeding, which is crucial. The message references encounter updates, which can be relevant, but remember you’re also dealing with overall condition data.

care/emr/migrations/0011_alter_condition_encounter.py (1)

10-10: Convert single quotes to double quotes
The static analysis suggests using double quotes for consistency, which might be mandated by project style guidelines. While it's mostly a style concern, it prevents minor friction during lint checks.

-        ('emr', '0010_condition_abatement'),
+        ("emr", "0010_condition_abatement"),

-            model_name='condition',
-            name='encounter',
-            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='emr.encounter'),
+            model_name="condition",
+            name="encounter",
+            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to="emr.encounter"),

Also applies to: 15-17

🧰 Tools
🪛 Ruff (0.8.2)

10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

care/utils/tests/test_feature_flags.py (1)

3-3: Consider restoring coverage for flag unregistration.
The removal of test_unregister_flag_not_found decreases test coverage and could mask future regressions. While dropping tests may appear to simplify maintenance now, it might lead to nasty surprises later if the unregister logic breaks.

config/settings/test.py (1)

71-75: Ensure the logging level suits your needs.
Adding the "audit_log" logger is great, but setting the level to "ERROR" might hide critical warnings or informational messages. If you truly only need to see critical failures, this works; otherwise, consider a lower threshold.

care/emr/resources/condition/spec.py (2)

123-124: Consider a fallback for missing encounters.
The conditional avoids setting mapping["encounter"] if obj.encounter is None. This is a safe approach. If there's any scenario where an empty encounter must be surfaced differently, you may want to revisit.


149-154: Add robust validation logic.
ChronicConditionUpdateSpec elegantly extends ConditionUpdateSpec. You might still want additional validation that checks whether encounter can be safely updated for chronic conditions. This could avoid confusion if an encounter ID is introduced that doesn’t align with the current patient’s record.

care/emr/api/viewsets/base.py (1)

148-155: Keep an eye on partial update edge cases.
Introducing keep_fields in clean_update_data provides flexibility, but it may be worth verifying that you don’t accidentally pop essential fields during partial updates. A docstring or mini-test verifying expected behavior would help.

config/api_router.py (1)

11-15: Clean import grouping

Consider grouping imports consistently with other sections. It’s not a big deal, but standardizing import blocks might help keep imports structured.

care/emr/tests/test_chronic_condition_api.py (1)

209-228: Slight duplication in permission checks

Multiple tests repeat the same arrangement of permission checks for encounters. This is almost perfect, though you could consider using a helper method to reduce repetition and improve maintainability.

pyproject.toml (1)

3-6: Omitting concurrency flags

Commenting out concurrency-related coverage features might slow down coverage runs for larger codebases. If parallel execution was only temporarily disabled, consider re-enabling it for performance gains.

📜 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 ba0dbbd.

📒 Files selected for processing (16)
  • care/abdm/migrations/0014_replace_0013.py (0 hunks)
  • care/abdm/migrations_old/0013_abhanumber_patient.py (0 hunks)
  • care/audit_log/middleware.py (1 hunks)
  • care/emr/api/viewsets/allergy_intolerance.py (0 hunks)
  • care/emr/api/viewsets/base.py (1 hunks)
  • care/emr/api/viewsets/condition.py (4 hunks)
  • care/emr/migrations/0011_alter_condition_encounter.py (1 hunks)
  • care/emr/models/condition.py (1 hunks)
  • care/emr/resources/condition/spec.py (4 hunks)
  • care/emr/tests/test_booking_api.py (5 hunks)
  • care/emr/tests/test_chronic_condition_api.py (1 hunks)
  • care/emr/tests/test_schedule_api.py (4 hunks)
  • care/utils/tests/test_feature_flags.py (1 hunks)
  • config/api_router.py (2 hunks)
  • config/settings/test.py (1 hunks)
  • pyproject.toml (1 hunks)
💤 Files with no reviewable changes (3)
  • care/abdm/migrations_old/0013_abhanumber_patient.py
  • care/abdm/migrations/0014_replace_0013.py
  • care/emr/api/viewsets/allergy_intolerance.py
✅ Files skipped from review due to trivial changes (3)
  • care/audit_log/middleware.py
  • care/emr/tests/test_schedule_api.py
  • care/emr/tests/test_booking_api.py
🧰 Additional context used
🪛 Ruff (0.8.2)
care/emr/migrations/0011_alter_condition_encounter.py

10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


15-15: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


16-16: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


17-17: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)
🔇 Additional comments (18)
care/emr/api/viewsets/condition.py (7)

3-4: Seamless permission/error import usage
The addition of PermissionDenied and ValidationError ensures better error handling. It's acceptable, though you might consider selectively raising exceptions if you foresee multiple failure scenarios to provide more context for clients.


69-70: SymptomViewSet model references updated
Switching to ConditionReadSpec and ConditionUpdateSpec aligns well with the renamed classes. This keeps the code cleaner and more consistent with the new spec naming.


109-110: DiagnosisViewSet spec usage
Likewise, using ConditionReadSpec and ConditionUpdateSpec ensures consistent naming. No concerns here.


142-142: Introduction of ChronicConditionViewSet
This class extends multiple mixins, making it flexible for CRUD operations on conditions designated as chronic. Just keep an eye on future expansions to avoid an overly large class.


165-168: get_patient_obj
Excellent approach to retrieving the Patient instance. Do confirm that your error handling is user-friendly when the patient is missing (though get_object_or_404 typically suffices).


183-185: clean_update_data
Preserving the encounter field is wise to ensure continuity of data. This is concise and consistent with the new approach of possibly having conditions without strict encounter ties.


193-209: get_queryset
Filtering by patient_external_id and category=chronic_condition helps isolate relevant conditions. The additional permission check with can_view_clinical_data is properly placed.

care/emr/models/condition.py (1)

14-16: Encounter field changes
Allowing null=True, blank=True is a practical step for chronic conditions that may not always associate with a specific encounter. However, in some edge cases, you might consider verifying how the rest of the code handles a Condition without an encounter, ensuring no subtle null pointer issues arise.

✅ Verification successful

Encounter field handling is properly implemented
After reviewing the codebase, I can confirm that null encounters are handled safely throughout. The code consistently uses Django's ORM features and proper null-safe filtering methods.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching references for Condition and verifying no code path incorrectly assumes a non-null encounter.
rg -A 5 "Condition" 

Length of output: 21973

care/emr/resources/condition/spec.py (4)

5-5: Validate custom exception handling.
Replacing manual lookups with get_object_or_404 is convenient, though keep in mind it raises Http404 directly. Confirm this aligns with how you handle errors in other parts of the codebase.


100-100: Renaming for clarity.
Renaming ConditionSpecRead to ConditionReadSpec is a neater naming convention. Small improvement that makes the class purpose less ambiguous.


132-132: Renaming for consistency.
Swapping ConditionSpecUpdate for ConditionUpdateSpec unifies naming. It's a subtle detail, but good for code clarity.


147-148: Empty lines.
The added blank lines appear intentional to separate sections. No immediate concerns here.

config/api_router.py (1)

250-252: Neat route addition

Registering the chronic_condition route is consistent with existing patterns. The name is well-chosen and helps keep endpoints scannable.

care/emr/tests/test_chronic_condition_api.py (3)

22-49: Robust test setup

The setUp and tearDown usage and mocking strategy are well-structured and thorough. This approach ensures consistent test data and environment, which is commendably detail-oriented.


280-304: Comprehensive scenario coverage

Good job covering both read and write permission checks. It’s refreshing to see such attention to detail, ensuring all angles are tested.


680-766: Encounter reassignment logic

The tests for changing an encounter’s ID on an existing chronic condition are invaluable. However, a quick verification for partial updates (PATCH) might help ensure we don’t inadvertently swap encounters or break partial updates.

pyproject.toml (2)

16-25: Improved coverage exclusions

Shifting to exclude_also with more conditions is well-planned, though do ensure that critical lines are not inadvertently excluded. Overly broad rules can hide coverage gaps.


35-36: Python version alignment

Updating the Ruff target to py313 is great, but please confirm the environment is prepared for Python 3.13. It’d be unfortunate if your build environment is still pinned to 3.12.

@sainak sainak force-pushed the sainak/chronic-condition branch from ba0dbbd to 237fa80 Compare January 24, 2025 10:02
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: 2

🧹 Nitpick comments (6)
pyproject.toml (1)

16-31: Oh, I see we're being thorough with our exclusions... very thorough.

The switch to exclude_also is good (it's the newer recommended approach), but we might want to consider:

  1. Do we really need to duplicate the omit patterns from the run section? It feels a bit... excessive.
  2. The exclusion of if settings.DEBUG might hide important debug-only code paths.

Consider consolidating the omit patterns into a single variable:

[tool]
omit_patterns = [
 "care/facility/**",
 "care/users/**",
 "*/tests/**",
 "*/migrations/**"
]

[tool.coverage.run]
omit = "${tool.omit_patterns}"

[tool.coverage.report]
omit = "${tool.omit_patterns}"
care/emr/api/viewsets/condition.py (2)

142-150: Add docstrings to describe the viewset's purpose and permissions.

The viewset could use some documentation about its purpose and required permissions. You know, just in case someone else needs to maintain this code someday... 😊


170-174: Consider consolidating duplicate permission checks.

The permission check for can_write_patient is duplicated in authorize_create and perform_update. Perhaps we could extract this into a shared method?

+    def _check_write_permission(self):
+        if not AuthorizationController.call(
+            "can_write_patient", self.request.user, self.get_patient_obj()
+        ):
+            raise PermissionDenied("You do not have permission to update encounter")
+
     def authorize_create(self, instance):
-        if not AuthorizationController.call(
-            "can_write_patient", self.request.user, self.get_patient_obj()
-        ):
-            raise PermissionDenied("You do not have permission to update encounter")
+        self._check_write_permission()

     def perform_update(self, instance):
-        if not AuthorizationController.call(
-            "can_update_encounter_obj", self.request.user, instance.encounter
-        ):
-            raise PermissionDenied("You do not have permission to update encounter")
+        self._check_write_permission()
         super().perform_update(instance)

Also applies to: 186-191

care/emr/tests/test_chronic_condition_api.py (2)

60-78: Consider extracting test data creation into helper methods.

The create_chronic_condition and generate_data_for_chronic_condition methods have quite a bit of duplicated code. Maybe we could make them a tiny bit more DRY? 😊

+    def _get_default_condition_data(self, **kwargs):
+        return {
+            "clinical_status": kwargs.pop(
+                "clinical_status", choice(list(ClinicalStatusChoices)).value
+            ),
+            "verification_status": kwargs.pop(
+                "verification_status", choice(list(VerificationStatusChoices)).value
+            ),
+            "severity": kwargs.pop("severity", choice(list(SeverityChoices)).value),
+        }
+
     def create_chronic_condition(self, encounter, patient, **kwargs):
-        clinical_status = kwargs.pop(
-            "clinical_status", choice(list(ClinicalStatusChoices)).value
-        )
-        verification_status = kwargs.pop(
-            "verification_status", choice(list(VerificationStatusChoices)).value
-        )
-        severity = kwargs.pop("severity", choice(list(SeverityChoices)).value)
+        condition_data = self._get_default_condition_data(**kwargs)
         return baker.make(
             Condition,
             encounter=encounter,
             patient=patient,
             category=CategoryChoices.chronic_condition.value,
-            clinical_status=clinical_status,
-            verification_status=verification_status,
-            severity=severity,
+            **condition_data,
             **kwargs,
         )

     def generate_data_for_chronic_condition(self, encounter, **kwargs):
-        clinical_status = kwargs.pop(
-            "clinical_status", choice(list(ClinicalStatusChoices)).value
-        )
-        verification_status = kwargs.pop(
-            "verification_status", choice(list(VerificationStatusChoices)).value
-        )
-        severity = kwargs.pop("severity", choice(list(SeverityChoices)).value)
+        condition_data = self._get_default_condition_data(**kwargs)
         code = self.valid_code
         return {
             "encounter": encounter.external_id,
             "category": CategoryChoices.chronic_condition.value,
-            "clinical_status": clinical_status,
-            "verification_status": verification_status,
-            "severity": severity,
+            **condition_data,
             "code": code,
             **kwargs,
         }

Also applies to: 80-97


527-590: Consider breaking down long test methods.

The update test methods are quite lengthy. Perhaps we could split the setup and assertions into smaller, more focused test methods? Just a thought! 🤔

care/emr/migrations/0012_alter_condition_encounter.py (1)

10-10: Use double quotes consistently.

The code uses single quotes for strings. While it works, the project's static analysis tools suggest using double quotes for consistency.

-    dependencies = [
-        ('emr', '0011_medicationrequest_requester'),
-    ]
+    dependencies = [
+        ("emr", "0011_medicationrequest_requester"),
+    ]

     operations = [
         migrations.AlterField(
-            model_name='condition',
-            name='encounter',
-            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='emr.encounter'),
+            model_name="condition",
+            name="encounter",
+            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to="emr.encounter"),
         ),
     ]

Also applies to: 15-17

🧰 Tools
🪛 Ruff (0.8.2)

10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ba0dbbd and 237fa80.

📒 Files selected for processing (16)
  • care/abdm/migrations/0014_replace_0013.py (0 hunks)
  • care/abdm/migrations_old/0013_abhanumber_patient.py (0 hunks)
  • care/audit_log/middleware.py (1 hunks)
  • care/emr/api/viewsets/allergy_intolerance.py (0 hunks)
  • care/emr/api/viewsets/base.py (1 hunks)
  • care/emr/api/viewsets/condition.py (4 hunks)
  • care/emr/migrations/0012_alter_condition_encounter.py (1 hunks)
  • care/emr/models/condition.py (1 hunks)
  • care/emr/resources/condition/spec.py (4 hunks)
  • care/emr/tests/test_booking_api.py (5 hunks)
  • care/emr/tests/test_chronic_condition_api.py (1 hunks)
  • care/emr/tests/test_schedule_api.py (4 hunks)
  • care/utils/tests/test_feature_flags.py (1 hunks)
  • config/api_router.py (2 hunks)
  • config/settings/test.py (1 hunks)
  • pyproject.toml (1 hunks)
💤 Files with no reviewable changes (3)
  • care/abdm/migrations/0014_replace_0013.py
  • care/emr/api/viewsets/allergy_intolerance.py
  • care/abdm/migrations_old/0013_abhanumber_patient.py
🚧 Files skipped from review as they are similar to previous changes (9)
  • care/audit_log/middleware.py
  • config/settings/test.py
  • care/emr/models/condition.py
  • care/utils/tests/test_feature_flags.py
  • config/api_router.py
  • care/emr/api/viewsets/base.py
  • care/emr/resources/condition/spec.py
  • care/emr/tests/test_schedule_api.py
  • care/emr/tests/test_booking_api.py
🧰 Additional context used
🪛 Ruff (0.8.2)
care/emr/migrations/0012_alter_condition_encounter.py

10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


15-15: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


16-16: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


17-17: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)
🔇 Additional comments (2)
care/emr/api/viewsets/condition.py (1)

69-70: LGTM: Model name updates are consistent.

The updates to use ConditionReadSpec and ConditionUpdateSpec are consistent across both viewsets.

Also applies to: 109-110

care/emr/migrations/0012_alter_condition_encounter.py (1)

17-17: Consider data integrity implications of nullable encounter.

Making the encounter field nullable could lead to orphaned conditions. Are we sure we want to allow conditions without encounters? 🤔

✅ Verification successful

Nullable encounter field is actually correct per FHIR standards

While it might seem counterintuitive, making the encounter field nullable is the right approach here. In FHIR, conditions can exist independently of encounters (e.g., chronic conditions, pre-existing conditions). However, you might want to:

  • Add a comment in the model explaining this FHIR compliance decision
  • Consider adding validation logic for scenarios where encounters should be required
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any existing conditions without encounters
ast-grep --pattern 'class Condition {
  $$$
  encounter = models.ForeignKey($$$)
  $$$
}'

Length of output: 91


Script:

#!/bin/bash
# Find and show the Condition model definition
rg "class Condition" -A 10 --type py

# Look for any references to Condition and encounter together
rg "Condition.*encounter|encounter.*Condition" --type py

# Check for any tests or business logic related to conditions
fd "test.*\.py" --exec rg "Condition" {} \;

Length of output: 7072

🧰 Tools
🪛 Ruff (0.8.2)

17-17: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

pyproject.toml Show resolved Hide resolved
pyproject.toml Show resolved Hide resolved
@sainak sainak force-pushed the sainak/chronic-condition branch from 237fa80 to 843f0fd Compare January 24, 2025 10:36
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: 1

🧹 Nitpick comments (4)
care/emr/migrations/0012_alter_condition_encounter.py (1)

9-11: Inconsistent quote style detected.

I see we're using single quotes. The static analyzer gently suggests using double quotes for consistency. Not that it matters much, but consistency is nice, isn't it?

-        ('emr', '0011_medicationrequest_requester'),
+        ("emr", "0011_medicationrequest_requester"),
🧰 Tools
🪛 Ruff (0.8.2)

10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

care/emr/api/viewsets/condition.py (3)

176-177: Questionable authorization implementation.

The authorize_update method just calls authorize_create with an empty dict. While it works, it feels a bit... creative? Maybe we should have separate logic for updates?

-    def authorize_update(self, request_obj, model_instance):
-        self.authorize_create({})
+    def authorize_update(self, request_obj, model_instance):
+        if not AuthorizationController.call(
+            "can_write_patient_obj", self.request.user, self.get_patient_obj()
+        ):
+            raise PermissionDenied("You do not have permission to update chronic conditions for this patient")

183-184: Potential improvement in update data cleaning.

The keep_fields parameter is passed as a set with a single item. If we're only ever keeping 'encounter', maybe we could make this more explicit?

-        return super().clean_update_data(request_data, keep_fields={"encounter"})
+        PRESERVED_FIELDS = {"encounter"}
+        return super().clean_update_data(request_data, keep_fields=PRESERVED_FIELDS)

193-206: Query optimization opportunity.

The queryset method makes an authorization check and then performs a database query. We could potentially optimize this by:

  1. Caching the patient object
  2. Using prefetch_related for reverse relationships if needed
     def get_queryset(self):
+        patient = self.get_patient_obj()  # Cache the patient object
         if not AuthorizationController.call(
-            "can_view_clinical_data", self.request.user, self.get_patient_obj()
+            "can_view_clinical_data", self.request.user, patient
         ):
             raise PermissionDenied("Permission denied for patient data")
         return (
             super()
             .get_queryset()
             .filter(
-                patient__external_id=self.kwargs["patient_external_id"],
+                patient=patient,  # Use cached patient object
                 category=CategoryChoices.chronic_condition.value,
             )
             .select_related("patient", "encounter", "created_by", "updated_by")
+            .prefetch_related("condition_related_fields")  # Add if needed
         )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 237fa80 and 843f0fd.

📒 Files selected for processing (7)
  • care/emr/api/viewsets/base.py (1 hunks)
  • care/emr/api/viewsets/condition.py (4 hunks)
  • care/emr/migrations/0012_alter_condition_encounter.py (1 hunks)
  • care/emr/models/condition.py (1 hunks)
  • care/emr/resources/condition/spec.py (4 hunks)
  • care/emr/tests/test_chronic_condition_api.py (1 hunks)
  • config/api_router.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • config/api_router.py
  • care/emr/models/condition.py
  • care/emr/resources/condition/spec.py
  • care/emr/api/viewsets/base.py
  • care/emr/tests/test_chronic_condition_api.py
🧰 Additional context used
🪛 Ruff (0.8.2)
care/emr/migrations/0012_alter_condition_encounter.py

10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


10-10: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


15-15: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


16-16: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


17-17: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)
🔇 Additional comments (2)
care/emr/migrations/0012_alter_condition_encounter.py (1)

14-18: Consider the implications of nullable encounters.

While making the encounter field optional might seem convenient, it could lead to data inconsistencies. Perhaps we should discuss whether all conditions should be tied to an encounter for proper medical record keeping?

Also, the CASCADE deletion might be a bit... aggressive? Consider using SET_NULL instead to preserve condition history even after encounter deletion.

🧰 Tools
🪛 Ruff (0.8.2)

15-15: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


16-16: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


17-17: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

care/emr/api/viewsets/condition.py (1)

69-70: Model updates look good, but...

The updates to pydantic_read_model and pydantic_update_model in both viewsets are fine, though it might have been nice to see some comments explaining why we're switching from the old spec classes. Just saying...

Also applies to: 109-110

Comment on lines +170 to +174
def authorize_create(self, instance):
if not AuthorizationController.call(
"can_write_patient_obj", self.request.user, self.get_patient_obj()
):
raise PermissionDenied("You do not have permission to update encounter")
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Duplicate authorization logic detected.

The authorize_create method seems to reimplement what can_write_patient_obj already does. Also, the error message mentions "update encounter" in a create method. A bit confusing, don't you think?

-            raise PermissionDenied("You do not have permission to update encounter")
+            raise PermissionDenied("You do not have permission to create chronic conditions for this patient")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def authorize_create(self, instance):
if not AuthorizationController.call(
"can_write_patient_obj", self.request.user, self.get_patient_obj()
):
raise PermissionDenied("You do not have permission to update encounter")
def authorize_create(self, instance):
if not AuthorizationController.call(
"can_write_patient_obj", self.request.user, self.get_patient_obj()
):
raise PermissionDenied("You do not have permission to create chronic conditions for this patient")

Copy link

codecov bot commented Jan 24, 2025

Codecov Report

Attention: Patch coverage is 64.40678% with 21 lines in your changes missing coverage. Please review.

Project coverage is 56.66%. Comparing base (2f9fa83) to head (e8ac11b).
Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
care/emr/api/viewsets/condition.py 69.23% 12 Missing ⚠️
care/emr/api/viewsets/base.py 16.66% 5 Missing ⚠️
care/emr/resources/condition/spec.py 60.00% 4 Missing ⚠️

❗ There is a different number of reports uploaded between BASE (2f9fa83) and HEAD (e8ac11b). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (2f9fa83) HEAD (e8ac11b)
2 1
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2775      +/-   ##
===========================================
- Coverage    64.90%   56.66%   -8.25%     
===========================================
  Files          252      208      -44     
  Lines        12761     9539    -3222     
  Branches      1121      939     -182     
===========================================
- Hits          8283     5405    -2878     
+ Misses        4369     4118     -251     
+ Partials       109       16      -93     

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

@vigneshhari vigneshhari merged commit ca3345e into develop Jan 24, 2025
5 of 6 checks passed
@vigneshhari vigneshhari deleted the sainak/chronic-condition branch January 24, 2025 11:14
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: 1

♻️ Duplicate comments (1)
care/emr/api/viewsets/condition.py (1)

170-174: ⚠️ Potential issue

That error message seems... interesting.

The error message mentions "update encounter" in a create method. We've been through this before, haven't we?

Apply this fix:

-            raise PermissionDenied("You do not have permission to update encounter")
+            raise PermissionDenied("You do not have permission to create chronic conditions for this patient")
🧹 Nitpick comments (2)
care/emr/api/viewsets/condition.py (2)

142-164: Would it kill you to add some docstrings?

The new viewset could use some documentation explaining its purpose and functionality. Consider adding class and method docstrings.


189-191: A docstring explaining the keep_fields parameter would be lovely.

The clean_update_data method uses a keep_fields parameter, but its purpose isn't immediately clear.

Add a docstring:

     def clean_update_data(self, request_data):
+        """
+        Clean update data while preserving specified fields.
+        
+        Args:
+            request_data: The data to be cleaned
+            
+        Returns:
+            Cleaned data with 'encounter' field preserved
+        """
         return super().clean_update_data(request_data, keep_fields={"encounter"})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 843f0fd and e8ac11b.

📒 Files selected for processing (3)
  • care/emr/api/viewsets/condition.py (4 hunks)
  • care/emr/resources/condition/spec.py (4 hunks)
  • care/emr/tests/test_chronic_condition_api.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • care/emr/resources/condition/spec.py
  • care/emr/tests/test_chronic_condition_api.py
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)
🔇 Additional comments (3)
care/emr/api/viewsets/condition.py (3)

3-4: LGTM! The imports look perfectly organized.

The new imports are well-structured and all seem to be used appropriately in the code.

Also applies to: 19-19, 25-26, 28-28


69-70: Oh look, matching updates to both viewsets. How... consistent.

The pydantic model updates in both viewsets align perfectly with the spec file changes.

Also applies to: 109-110


192-205: The queryset method looks almost perfect.

Consider adding an index on category field if not already present, as it's used in filtering across all viewsets.

Let's check if the index exists:

Comment on lines +176 to +184
def authorize_update(self, request_obj, model_instance):
encounter = get_object_or_404(Encounter, external_id=request_obj.encounter)
if not AuthorizationController.call(
"can_update_encounter_obj",
self.request.user,
encounter,
):
raise PermissionDenied("You do not have permission to update encounter")

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

The authorization flow could use some love.

The authorize_update method fetches the encounter but doesn't verify if it belongs to the correct patient. This could lead to potential security issues.

Add patient verification:

     def authorize_update(self, request_obj, model_instance):
         encounter = get_object_or_404(Encounter, external_id=request_obj.encounter)
+        if str(encounter.patient.external_id) != self.kwargs["patient_external_id"]:
+            raise ValidationError("Patient external ID mismatch with encounter's patient")
         if not AuthorizationController.call(
             "can_update_encounter_obj",
             self.request.user,
             encounter,
         ):
             raise PermissionDenied("You do not have permission to update encounter")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def authorize_update(self, request_obj, model_instance):
encounter = get_object_or_404(Encounter, external_id=request_obj.encounter)
if not AuthorizationController.call(
"can_update_encounter_obj",
self.request.user,
encounter,
):
raise PermissionDenied("You do not have permission to update encounter")
def authorize_update(self, request_obj, model_instance):
encounter = get_object_or_404(Encounter, external_id=request_obj.encounter)
if str(encounter.patient.external_id) != self.kwargs["patient_external_id"]:
raise ValidationError("Patient external ID mismatch with encounter's patient")
if not AuthorizationController.call(
"can_update_encounter_obj",
self.request.user,
encounter,
):
raise PermissionDenied("You do not have permission to update encounter")

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