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

Scheduling Validations #2701

Merged
merged 3 commits into from
Jan 3, 2025
Merged

Conversation

rithviknishad
Copy link
Member

@rithviknishad rithviknishad commented Jan 3, 2025

Summary by CodeRabbit

  • New Features

    • None
  • Bug Fixes

    • Updated user-related filtering across multiple scheduling and booking components.
    • Improved error handling for user retrieval in scheduling processes.
  • Refactor

    • Renamed resource references to user in multiple viewsets, models, and resources.
    • Modified database schema to use user instead of resource in related models.
  • Migrations

    • Added migration to rename resource field to user in schedulable user resources.
    • Updated medicationrequest model to use JSONField for dosage instructions.

@rithviknishad rithviknishad requested a review from a team as a code owner January 3, 2025 10:35
Copy link

coderabbitai bot commented Jan 3, 2025

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

📥 Commits

Reviewing files that changed from the base of the PR and between 77226a0 and c3a342f.

📒 Files selected for processing (1)
  • care/emr/api/viewsets/scheduling/availability.py (5 hunks)
 ______________________________________________________________________________________________________________________________________________________________
< Find bugs once. Once a human tester finds a bug, it should be the last time a human tester finds that bug. Automatic tests should check for it from then on. >
 --------------------------------------------------------------------------------------------------------------------------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
📝 Walkthrough

Walkthrough

This pull request introduces a comprehensive refactoring across multiple files, shifting the focus from resource-based to user-based filtering in scheduling and availability components. The changes primarily involve renaming resource to user in various classes, filters, and methods, updating database models, and modifying query logic to use user_id instead of resource_id. The modifications span across viewsets, models, resources, and migrations, ensuring a consistent approach to user-resource interactions. It's almost as if someone decided that "resource" was just too vague for our sophisticated needs.

Changes

File Change Summary
care/emr/api/viewsets/facility.py Updated get_queryset to extract user_id instead of resource_id
care/emr/api/viewsets/scheduling/availability.py Enhanced user retrieval with get_object_or_404() and updated filtering criteria
care/emr/api/viewsets/scheduling/availability_exceptions.py Replaced resource filter with user filter targeting external_id
care/emr/api/viewsets/scheduling/booking.py Renamed filter_by_resource to filter_by_user, updated token booking and available doctors queries
care/emr/api/viewsets/scheduling/schedule.py Replaced resource filter with user filter
care/emr/migrations/0061_* Renamed resource to user in schedulableuserresource model, updated medicationrequest field
care/emr/models/scheduling/schedule.py Renamed resource attribute to user in SchedulableUserResource
care/emr/resources/scheduling/* Updated user resource retrieval and specification logic

Possibly related PRs

Suggested reviewers

  • vigneshhari

Poem

🔄 Resource, user, what's in a name?
Code dancing, filters rearranged
From resource_id to user we've swayed
A refactoring ballet, elegantly played
Django's schema, now freshly repaged! 🌟


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

@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 (3)
care/emr/migrations/0061_rename_resource_schedulableuserresource_user_and_more.py (1)

19-21: Confirm the default of list for dosage_instruction.

Switching to JSONField with a list default is logical. However, please verify your domain requirements to ensure a list suits all usage scenarios—some might prefer a dict structure for key-value entries.

care/emr/models/scheduling/schedule.py (1)

10-10: Update the outdated TODO comment.

The comment still mentions indexing with “resource,” but now it's a user reference. A quick rename here would keep things consistent and less confusing for future maintainers.

care/emr/api/viewsets/scheduling/availability.py (1)

218-218: Rename variable for clarity
Using resource to store a SchedulableUserResource object can mislead. Consider renaming it to something like schedulable_user_resource for consistency and readability.

-resource = SchedulableUserResource.objects.filter(user=user).first()
+schedulable_user_resource = SchedulableUserResource.objects.filter(user=user).first()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 179f0d5 and 6516efa.

📒 Files selected for processing (9)
  • care/emr/api/viewsets/facility.py (1 hunks)
  • care/emr/api/viewsets/scheduling/availability.py (3 hunks)
  • care/emr/api/viewsets/scheduling/availability_exceptions.py (1 hunks)
  • care/emr/api/viewsets/scheduling/booking.py (2 hunks)
  • care/emr/api/viewsets/scheduling/schedule.py (1 hunks)
  • care/emr/migrations/0061_rename_resource_schedulableuserresource_user_and_more.py (1 hunks)
  • care/emr/models/scheduling/schedule.py (1 hunks)
  • care/emr/resources/scheduling/availability_exception/spec.py (1 hunks)
  • care/emr/resources/scheduling/schedule/spec.py (1 hunks)
🔇 Additional comments (10)
care/emr/migrations/0061_rename_resource_schedulableuserresource_user_and_more.py (1)

13-17: Smooth renaming of resource to user.

Kudos for systematically updating the field name to something more descriptive. Double-check that any queries or references to the old field name aren’t lurking around elsewhere, though I’m sure you’ve combed it all carefully.

care/emr/api/viewsets/scheduling/availability_exceptions.py (1)

17-17: Filter shift from resource__external_id to resource__user__external_id looks good.

Just be mindful you’ve got “resource” in the chain while also referencing the user. Everything aligns with the new approach, but as with other files, watch for stray references that might trip up newcomers.

care/emr/resources/scheduling/schedule/spec.py (1)

74-74: Praise for the user-based refactor.

Updating the resource parameter to user is consistent with the broader shift away from resource-based scheduling. This change aligns the SchedulableUserResource instantiation directly to the user, which clarifies intent and improves maintainability. Great step forward, albeit do keep a close eye on any leftover references to resource calls in the rest of the codebase.

care/emr/api/viewsets/scheduling/schedule.py (1)

21-21: Filter naming clarity is appreciated.

Renaming the filter to user clarifies its purpose and makes it more discoverable for future maintenance. This is a cohesive move that syncs well with the revised data-modeling approach. Nicely done.

care/emr/api/viewsets/scheduling/booking.py (3)

29-29: Filter rename to user.

Replacing the resource filter with user is consistent with the rest of the changes. This enforces a uniform approach across the scheduling module.


32-32: Descriptive function name improvement.

Renaming filter_by_resource to filter_by_user clarifies its functionality and reduces confusion. This small shift makes it more coherent for future contributors.


36-36: Effective user-based query.

Using user__external_id=value further cements the transition to user-centric lookups. The logic is concise and avoids any leftover references to resource_id. Keep in mind to verify all other related references, just to avoid any sneaky mismatches.

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

107-107: Great alignment with user-based architecture.

Changing .values("resource_id") to .values("user_id") eliminates confusion about the entity in focus. This is consistent with the rest of the refactor, which we trust is thoroughly tested.

care/emr/api/viewsets/scheduling/availability.py (2)

11-11: Nice addition for robust lookups
It’s more reliable than manually filtering the user. Though one might wonder why it took so long, this is definitely an improvement.


114-114: Consistent with user-based filtering
Switching from resource to user aligns with your new approach, so just ensure other references remain consistent to avoid confusion down the line.

Comment on lines +39 to +41
user = User.objects.get(external_id=self.resource)
resource = SchedulableUserResource.objects.get(
resource=user_resource,
user=user,
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Clarify naming to avoid mixing "resource" and "user".

The parameter self.resource is now used to fetch a User, and then assigned to obj.resource. It works, but maybe rename the incoming data field to user_id or something less confusing. It’ll save you from an extra squint in the future.

@@ -105,12 +106,12 @@ def get_slots_for_day(self, request, *args, **kwargs):
@classmethod
def get_slots_for_day_handler(cls, facility_external_id, request_data):
request_data = SlotsForDayRequestSpec(**request_data)
user = User.objects.filter(external_id=request_data.resource).first()
user = get_object_or_404(User, external_id=request_data.user)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove redundant check after get_object_or_404
get_object_or_404 already handles the not-found scenario, so the manual if not user check right below is never reached.

 user = get_object_or_404(User, external_id=request_data.user)
-if not user:
-    raise ValidationError("Resource does not exist")

Committable suggestion skipped: line range outside the PR's diff.

@rithviknishad rithviknishad marked this pull request as ready for review January 3, 2025 13:12
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 (2)
care/security/authorization/user_schedule.py (1)

58-59: Soft reminder to ensure consistent usage
The logic here is duplicated from the can_write_user_schedule method above. If the underlying data requirement differs, consider consolidating or extracting into a helper.

care/emr/api/viewsets/scheduling/availability.py (1)

218-218: Clarify the variable naming
Renaming local variables from resource to something more descriptive like schedulable_user or user_resource may help new developers quickly understand the function’s purpose.

-resource = SchedulableUserResource.objects.filter(user=user).first()
+user_resource = SchedulableUserResource.objects.filter(user=user).first()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6516efa and 77226a0.

📒 Files selected for processing (5)
  • care/emr/api/viewsets/scheduling/availability.py (4 hunks)
  • care/emr/api/viewsets/scheduling/booking.py (2 hunks)
  • care/emr/api/viewsets/scheduling/schedule.py (2 hunks)
  • care/emr/resources/scheduling/slot/spec.py (1 hunks)
  • care/security/authorization/user_schedule.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • care/emr/api/viewsets/scheduling/schedule.py
🔇 Additional comments (8)
care/security/authorization/user_schedule.py (1)

43-44: Excellent approach to retrieving organization details
These lines correctly utilize values_list with flat=True to fetch the organization's parent_cache for further validation. This is clear and straightforward.

care/emr/resources/scheduling/slot/spec.py (1)

92-92: Verify the updated attribute
Changing from resource_id to user_id is consistent with the shift to user-centric logic. Just ensure all references to resource.resource_id have been replaced accordingly in the broader codebase.

✅ Verification successful

No lingering resource_id references found, but I suppose you knew that already

After a thorough analysis of the codebase (and I mean thorough), the change from resource_id to user_id appears to be consistent. The only references to resource_id found are in:

  • A migration file (which is expected and shouldn't be modified)
  • Questionnaire-related files using it in a different context

The file under review correctly uses user_id and integrates well with the rest of the codebase, which seems to have already embraced the user-centric approach. The extensive presence of UserSpec imports and user-related patterns throughout the scheduling system suggests this was a well-planned transition.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Double-check for references to the old `resource_id` attribute across the codebase
rg "resource\.resource_id"

Length of output: 28


Script:

#!/bin/bash
# Let's try a more comprehensive search for resource_id patterns
rg -i "resource_?id"

# Also search for specific resource ID access patterns
ast-grep --pattern 'resource.$_id'

Length of output: 450


Script:

#!/bin/bash
# Let's check the specific file and its imports to understand the context better
cat "care/emr/resources/scheduling/slot/spec.py"

Length of output: 2618


Script:

#!/bin/bash
# Let's also check for any User model references with resource relationships
rg "resource.*user" -A 2

Length of output: 9090

care/emr/api/viewsets/scheduling/booking.py (3)

29-29: Filter field rename is consistent
Renaming resource to user aligns with the new user-based paradigm. Minimal changes needed here.


32-36: Consider fallback behavior
If you’re transitioning from a resource to a user, ensure the fallback logic (e.g., if no matching user is found) is well-tested for unexpected scenarios or data migrations not yet completed.


93-99: Renaming to available_users is well done
This is straightforward and consistent with the rest of the refactoring. The fix ensures a more intuitive naming, though subtlety might be lost on external collaborators who still think in terms of “resources.”

care/emr/api/viewsets/scheduling/availability.py (3)

30-30: Field rename to user
The rename to user is consistent with the user-based approach. This will reduce confusion about typical roles vs. “resources.”


109-109: Remove unreachable check
get_object_or_404(User, external_id=request_data.user) already raises an error if the user is missing, making the if not user: check unreachable.

 user = get_object_or_404(User, external_id=request_data.user)
-if not user:
-    raise ValidationError("Resource does not exist")

114-114: Consistency in referencing user
This line is fully consistent with the revised user-based approach. Nicely done.

@vigneshhari vigneshhari merged commit c3d1c82 into develop Jan 3, 2025
4 of 6 checks passed
@vigneshhari vigneshhari deleted the rithviknishad/schedule-validations branch January 3, 2025 13: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.

2 participants