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

added validation for phone number in create spec #2730

Merged
merged 6 commits into from
Jan 14, 2025

Conversation

DraKen0009
Copy link
Contributor

@DraKen0009 DraKen0009 commented Jan 13, 2025

Proposed Changes

  • Added validation to patient create spec

Associated Issue

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

Release Notes

  • New Features

    • Enhanced phone number validation with support for Indian and international phone number formats.
    • Added robust phone number type checking and validation for patient records.
    • Introduced a method to generate random valid phone numbers for testing.
  • Dependencies

    • Added phonenumberslite library for phone number validation.
    • Added pydantic-extra-types for extended type support.
  • Improvements

    • Strengthened data integrity for patient contact information.
    • Implemented more precise phone number format validation.
    • Updated patient data generation process to include additional attributes.

Copy link

coderabbitai bot commented Jan 13, 2025

📝 Walkthrough

Walkthrough

This pull request introduces enhanced phone number validation capabilities across the project. By adding phonenumberslite and pydantic-extra-types dependencies, the team has implemented more robust type checking and validation for phone number fields. The changes span multiple files, updating type annotations, validation logic, and test data generation to ensure more precise phone number handling. It's quite the overhaul, really, as if the previous system was just getting by.

Changes

File Changes
Pipfile Added pydantic-extra-types = "2.10.1" and phonenumberslite = "8.13.52" dependencies
care/emr/resources/base.py Introduced PhoneNumber type annotation using Annotated and Union, updated imports for new dependencies
care/emr/resources/patient/spec.py Updated phone_number and emergency_phone_number attributes to use PhoneNumber type, modified imports
care/emr/tests/test_patient_api.py Removed PatientFactory, added generate_random_valid_phone_number, updated generate_patient_data method signature, added new test methods

Sequence Diagram

sequenceDiagram
    participant User
    participant PhoneValidator
    participant PatientSpec
    
    User->>PhoneValidator: Provide Phone Number
    PhoneValidator->>PhoneValidator: Validate Format
    alt Valid Number
        PhoneValidator-->>PatientSpec: Accept Number
    else Invalid Number
        PhoneValidator-->>User: Raise ValueError
    end
Loading

Poem

📞 In a world of digits, we now refine,
Phone numbers validated, oh so divine!
From strings to types, a structured embrace,
No more confusion, just a clear space!
With each new line, a better design,
Cheers to the changes, they surely align! ✨

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.

@DraKen0009 DraKen0009 marked this pull request as ready for review January 13, 2025 14:07
@DraKen0009 DraKen0009 requested a review from a team as a code owner January 13, 2025 14:07
Copy link

@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: 3

🧹 Nitpick comments (2)
care/emr/resources/base.py (1)

159-161: Consider restricting supported regions for international numbers.

The current configuration allows any region code. It might be worth considering a whitelist of supported countries to prevent potential abuse.

care/emr/resources/patient/spec.py (1)

81-83: Consider moving regex patterns to settings or constants.

These hardcoded regex patterns might need updates as phone number formats evolve. It would be slightly more maintainable to move them to a configuration file.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ce87462 and 23ac43b.

⛔ Files ignored due to path filters (1)
  • Pipfile.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • Pipfile (1 hunks)
  • care/emr/resources/base.py (2 hunks)
  • care/emr/resources/patient/spec.py (3 hunks)
  • care/emr/tests/test_patient_api.py (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test / test
🔇 Additional comments (1)
Pipfile (1)

45-46: LGTM!

The added dependencies with pinned versions look good and are compatible with the project's Python version.

care/emr/resources/base.py Show resolved Hide resolved
care/emr/resources/patient/spec.py Outdated Show resolved Hide resolved
care/emr/tests/test_patient_api.py Outdated Show resolved Hide resolved
care/emr/resources/base.py Outdated Show resolved Hide resolved
Copy link

@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_patient_api.py (3)

13-21: Oh, using example numbers instead of truly random ones, are we? 🙂

While the function works, using example numbers might not catch all edge cases. Consider using phonenumbers.parse() with randomly generated numbers for more thorough testing.

def generate_random_valid_phone_number() -> str:
-    regions = ["US", "IN", "GB", "DE", "FR", "JP", "AU", "CA"]
+    # Add more regions for better coverage
+    regions = ["US", "IN", "GB", "DE", "FR", "JP", "AU", "CA", "BR", "RU", "CN", "KR"]
-    example_number = phonenumbers.example_number_for_type(
-        random_region, PhoneNumberType.MOBILE
-    )
+    # Generate truly random numbers
+    country_code = phonenumbers.country_code_for_region(random_region)
+    local_number = ''.join([str(choice(range(10))) for _ in range(10)])
+    number_str = f"+{country_code}{local_number}"
+    try:
+        number = phonenumbers.parse(number_str, None)
+        if phonenumbers.is_valid_number(number):
+            return phonenumbers.format_number(number, PhoneNumberFormat.E164)
+    except phonenumbers.NumberParseException:
+        pass
+    return generate_random_valid_phone_number()  # Recursively try again

40-55: A docstring would be nice here... just saying

The method could use some documentation explaining the parameters and return value. Also, it might be worth documenting that either 'age' or 'date_of_birth' is required.

    def generate_patient_data(self, geo_organization, **kwargs):
+        """Generate test data for patient creation.
+        
+        Args:
+            geo_organization: The geographic organization identifier
+            **kwargs: Optional overrides for patient data fields
+                     (must include either 'age' or 'date_of_birth')
+        
+        Returns:
+            dict: A dictionary containing patient data
+        """

101-120: The test cases are... let's say, minimal

Consider adding more edge cases for invalid phone numbers:

  • Numbers with spaces or special characters (+1 (234) 567-8900)
  • Valid-looking but invalid area codes
  • Numbers that are valid in one region but invalid in another
  • Numbers with country codes but invalid local numbers
        invalid_phone_numbers = [
            "12345",
            "abcdef",
            "+1234567890123456",
            "",
+           "+1 (234) 567-8900",  # Formatted but invalid
+           "+19995551234",       # Invalid area code
+           "+44123456789",       # Valid format, invalid local number
+           "++1234567890",       # Double plus
+           "+",                  # Just plus
+           "١٢٣٤٥٦٧٨٩٠",       # Non-ASCII numerals
        ]
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 23ac43b and 61d94c3.

⛔ Files ignored due to path filters (1)
  • Pipfile.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • Pipfile (1 hunks)
  • care/emr/resources/base.py (2 hunks)
  • care/emr/resources/patient/spec.py (2 hunks)
  • care/emr/tests/test_patient_api.py (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • Pipfile
  • care/emr/resources/patient/spec.py
  • care/emr/resources/base.py
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)
🔇 Additional comments (2)
care/emr/tests/test_patient_api.py (2)

48-49: Noticed how emergency_phone_number validation isn't being tested?

Both phone_number and emergency_phone_number use the same validation, but only phone_number is being tested. Consider:

  1. Adding test cases for emergency phone number validation
  2. Testing scenarios where emergency number is same as primary number

Would you like me to generate the additional test cases for emergency phone number validation?


122-139: Testing with random data without checking the response... interesting choice

While testing with random valid numbers is good, consider:

  1. Adding some deterministic test cases for reproducibility
  2. Verifying the phone number in the response matches what was sent
  3. Adding assertions for other fields in the response
        valid_phone_numbers = [
+           "+14155552671",  # Fixed test case for US
+           "+919876543210", # Fixed test case for India
        ] + [generate_random_valid_phone_number() for _ in range(3)]

        for valid_number in valid_phone_numbers:
            patient_data = self.generate_patient_data(
                geo_organization=geo_organization.external_id,
                phone_number=valid_number
            )
            response = self.client.post(self.base_url, patient_data, format="json")
            self.assertEqual(response.status_code, status.HTTP_200_OK)
+           response_data = response.json()
+           self.assertEqual(response_data["phone_number"], valid_number)
+           self.assertEqual(response_data["name"], patient_data["name"])
✅ Verification successful

Oh, you're absolutely right about those missing assertions

The review suggestions are spot-on since the test creates a complete patient record with name, address, and other fields but only checks the status code. The phone validation is quite thorough (supporting multiple regions and types), so verifying the response data would ensure the validation actually worked as intended. Those fixed test cases would also make debugging so much... easier.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find patient model and serializer definitions
ast-grep --pattern 'class Patient' 
ast-grep --pattern 'class PatientSerializer'

# Look for phone number validation
rg "phone.*number.*valid" -g '!*.pyc'

# Find test helper methods
rg "generate_patient_data|generate_random_valid_phone_number" -g '*.py' -A 5

Length of output: 5503

Copy link

codecov bot commented Jan 14, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 60.43%. Comparing base (bf529b0) to head (86a2ec3).
Report is 7 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #2730   +/-   ##
========================================
  Coverage    60.42%   60.43%           
========================================
  Files          252      252           
  Lines        12695    12698    +3     
  Branches      1111     1111           
========================================
+ Hits          7671     7674    +3     
  Misses        4955     4955           
  Partials        69       69           

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

@vigneshhari vigneshhari merged commit a003588 into develop Jan 14, 2025
8 checks passed
@vigneshhari vigneshhari deleted the prafful/bugs/patient_phone_number_validator branch January 14, 2025 06:18
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.

Phone Number Field Allows Letters
3 participants