Skip to content

refact:added patient age in patient retrive spec#3546

Open
nandkishorr wants to merge 8 commits intodevelopfrom
fix/show_patient_age
Open

refact:added patient age in patient retrive spec#3546
nandkishorr wants to merge 8 commits intodevelopfrom
fix/show_patient_age

Conversation

@nandkishorr
Copy link
Contributor

@nandkishorr nandkishorr commented Feb 26, 2026

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

    • Age is now included in patient retrieval responses, improving demographic visibility.
  • Improvements

    • Create/update flows consistently handle age and date of birth, reducing mismatches and improving data consistency.
  • Tests

    • Test data generation enhanced for patient records (phone numbers, gender, blood group, address, date of birth) to improve test realism.

@nandkishorr nandkishorr requested a review from a team as a code owner February 26, 2026 06:45
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 26, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 61696419-2023-4628-a8f6-e1fd63c6c014

📥 Commits

Reviewing files that changed from the base of the PR and between 35b6f0f and ac52f75.

📒 Files selected for processing (1)
  • care/emr/resources/patient/spec.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • care/emr/resources/patient/spec.py

📝 Walkthrough

Walkthrough

Added a public age: str field to PatientRetrieveSpec and emit it during serialization; create/update deserialization flows were adjusted to handle provided age and explicit date_of_birth. Test utilities for patient creation were extended to populate more realistic default fields.

Changes

Cohort / File(s) Summary
Patient Spec Updates
care/emr/resources/patient/spec.py
Added age: str to PatientRetrieveSpec; serialization now includes "age": obj.get_age(). PatientCreateSpec.perform_extra_deserialization and PatientUpdateSpec.perform_extra_deserialization updated to handle incoming age and explicit date_of_birth assignment/reset logic.
Test data utilities
care/utils/tests/base.py
Imported generate_unique_indian_phone_number, BloodGroupChoices, GenderChoices; create_patient now fills defaults for name, gender, phone_number, address, pincode, blood_group, and date_of_birth using Faker/secrets utilities.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is missing critical sections: no Proposed Changes, no Associated Issue, and no Architecture changes explanation. Only the Merge Checklist template remains, with all items unchecked. Add Proposed Changes section describing the modifications, link and explain the Associated Issue, detail Architecture changes, and confirm checklist items are actually completed before merge.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title mentions adding patient age to retrieve spec, which aligns with the main change of adding an age field to PatientRetrieveSpec, though it contains minor typos ('refact' and 'retrive').

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/show_patient_age

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 and usage tips.

@nandkishorr nandkishorr self-assigned this Feb 26, 2026
@nandkishorr nandkishorr changed the title fix:added patient age in retrive spec refact:added patient age in retrive spec Feb 26, 2026
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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
care/emr/resources/patient/spec.py (1)

140-145: ⚠️ Potential issue | 🟠 Major

Inconsistent age handling can silently drop newborn age updates.

Line 140 uses a truthy check (if self.age:), while Line 186 correctly uses is not None. So age=0 is ignored on create but handled on update. Subtle, but definitely not fun to debug later.

Suggested fix
-        if self.age:
+        if self.age is not None:
             # override dob if user chooses to update age
             obj.date_of_birth = None
             obj.year_of_birth = timezone.now().date().year - self.age

Also applies to: 186-191

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@care/emr/resources/patient/spec.py` around lines 140 - 145, The code uses a
truthy check on self.age (if self.age) which drops legitimate zero values
(newborn age); change the condition to explicit "is not None" wherever age is
checked (e.g., replace "if self.age:" with "if self.age is not None:" around the
block that sets obj.date_of_birth = None and obj.year_of_birth =
timezone.now().date().year - self.age) and make the same change in the other
occurrence handling update (the block currently at the later age handling) so
age=0 is accepted consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@care/emr/resources/patient/spec.py`:
- Around line 140-145: The code uses a truthy check on self.age (if self.age)
which drops legitimate zero values (newborn age); change the condition to
explicit "is not None" wherever age is checked (e.g., replace "if self.age:"
with "if self.age is not None:" around the block that sets obj.date_of_birth =
None and obj.year_of_birth = timezone.now().date().year - self.age) and make the
same change in the other occurrence handling update (the block currently at the
later age handling) so age=0 is accepted consistently.

ℹ️ Review info

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 76bd0c9 and 37913f8.

📒 Files selected for processing (1)
  • care/emr/resources/patient/spec.py

obj.date_of_birth = None
obj.year_of_birth = timezone.now().year - self.age
elif self.date_of_birth:
obj.date_of_birth = self.date_of_birth
Copy link
Member

Choose a reason for hiding this comment

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

Why?

Copy link
Contributor Author

@nandkishorr nandkishorr Feb 26, 2026

Choose a reason for hiding this comment

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

while creating and updating , on de serialization the date_of_birth is converted to str (in-memory) So on serialize the get_age() will crash since using data from the same in-memory obj !

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 (1)
care/utils/tests/base.py (1)

10-12: Avoid pulling shared test helpers from a management command module.

This works, but importing from care.emr.management.commands.load_fixtures couples test utilities to command-layer code a bit more than needed. Please move this helper to a neutral utility module and import from there.

As per coding guidelines, **/*.py: Prioritize readability and maintainability; follow Django's coding style guide (PEP 8 compliance).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@care/utils/tests/base.py` around lines 10 - 12, The test is importing
generate_unique_indian_phone_number from a management command; extract that
helper into a neutral utility module (e.g., a new function in a tests or utils
module) and update imports: move the implementation of
generate_unique_indian_phone_number out of the management command and into the
new module, change care/utils/tests/base.py to import
generate_unique_indian_phone_number from the new utility module, and update the
original management command (load_fixtures) to import the helper from the new
location so both tests and command use the shared, neutral utility.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@care/utils/tests/base.py`:
- Line 100: Replace the non-deterministic default in the test factory call
kwargs.setdefault("date_of_birth", self.fake.date_of_birth()) with a stable
deterministic date (e.g., a fixed datetime.date like 1990-01-01) so age-based
assertions don't drift; keep using kwargs.setdefault so individual tests can
still override date_of_birth when needed and update any docstring/comment to
note the fixed default.

---

Nitpick comments:
In `@care/utils/tests/base.py`:
- Around line 10-12: The test is importing generate_unique_indian_phone_number
from a management command; extract that helper into a neutral utility module
(e.g., a new function in a tests or utils module) and update imports: move the
implementation of generate_unique_indian_phone_number out of the management
command and into the new module, change care/utils/tests/base.py to import
generate_unique_indian_phone_number from the new utility module, and update the
original management command (load_fixtures) to import the helper from the new
location so both tests and command use the shared, neutral utility.

ℹ️ Review info

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 37913f8 and 87394be.

📒 Files selected for processing (1)
  • care/utils/tests/base.py

kwargs.setdefault("address", self.fake.address())
kwargs.setdefault("pincode", self.fake.random_int(min=100000, max=999999))
kwargs.setdefault("blood_group", secrets.choice(list(BloodGroupChoices)).value)
kwargs.setdefault("date_of_birth", self.fake.date_of_birth())
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 | 🟡 Minor

Use a deterministic date_of_birth default to reduce flaky age-based tests.

Line 100 currently randomizes DOB, which can make age assertions drift over time. A fixed default is more reliable, and specific tests can still override it.

Proposed change
+from datetime import date
 import secrets
 import sys
 from secrets import choice
@@
-        kwargs.setdefault("date_of_birth", self.fake.date_of_birth())
+        kwargs.setdefault("date_of_birth", date(1990, 1, 1))

As per coding guidelines, **/tests/**/*.py: Use Django’s built-in tools for testing (unittest and pytest-django) to ensure code quality and reliability.

📝 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
kwargs.setdefault("date_of_birth", self.fake.date_of_birth())
from datetime import date
import secrets
import sys
from secrets import choice
kwargs.setdefault("date_of_birth", date(1990, 1, 1))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@care/utils/tests/base.py` at line 100, Replace the non-deterministic default
in the test factory call kwargs.setdefault("date_of_birth",
self.fake.date_of_birth()) with a stable deterministic date (e.g., a fixed
datetime.date like 1990-01-01) so age-based assertions don't drift; keep using
kwargs.setdefault so individual tests can still override date_of_birth when
needed and update any docstring/comment to note the fixed default.

@codecov
Copy link

codecov bot commented Feb 26, 2026

Codecov Report

❌ Patch coverage is 80.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 75.20%. Comparing base (924ca74) to head (ac52f75).

Files with missing lines Patch % Lines
care/emr/resources/patient/spec.py 80.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #3546      +/-   ##
===========================================
- Coverage    76.22%   75.20%   -1.03%     
===========================================
  Files          474      475       +1     
  Lines        22270    22687     +417     
  Branches      2325     2364      +39     
===========================================
+ Hits         16976    17061      +85     
- Misses        4765     5096     +331     
- Partials       529      530       +1     

☔ View full report in Codecov by Sentry.
📢 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.

@nandkishorr nandkishorr changed the title refact:added patient age in retrive spec refact:added patient age in patient retrive spec Mar 9, 2026
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