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

Disallow creating availabilities of duration not multiple of slot size duration; Prevent overlapping availability creation #2795

Conversation

rithviknishad
Copy link
Member

@rithviknishad rithviknishad commented Jan 30, 2025

Proposed Changes

  • disallow creating availability with duration not multiple of slot size duration
  • disallow creating availabilities that is overlapping with other availabilities

Associated Issue

Merge Checklist

  • Tests added/fixed
  • Linting Complete

@ohcnetwork/care-backend-maintainers @ohcnetwork/care-backend-admins

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced schedule and availability creation with improved validation mechanisms.
    • Introduced a new specification for creating availability linked to a schedule.
  • Bug Fixes

    • Implemented checks to prevent overlapping availability time ranges.
    • Added validation to ensure start time is before end time for availability entries.
  • Tests

    • Expanded test coverage for schedule and availability creation scenarios, focusing on overlapping conditions.
    • Added comprehensive validation tests for time ranges and scheduling conflicts.
    • Included tests to ensure availability duration adheres to specified slot sizes.

@rithviknishad rithviknishad requested a review from a team as a code owner January 30, 2025 08:04
Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

📝 Walkthrough

Walkthrough

The pull request introduces enhanced validation and management for scheduling and availability creation in the EMR system. The changes focus on preventing overlapping availability sessions, ensuring proper schedule linkage, and adding robust validation checks during availability and schedule creation. The modifications span across the viewset, specification, and test files to implement comprehensive validation logic. Clearly, a lot of thought went into making sure overlapping sessions are handled better—something we all should have been doing from the start.

Changes

File Change Summary
care/emr/api/viewsets/scheduling/schedule.py - Updated AvailabilityViewSet with new pydantic_model and pydantic_retrieve_model
- Added clean_create_data method to set schedule context
- Modified perform_create and perform_destroy methods
care/emr/resources/scheduling/schedule/spec.py - Introduced AvailabilityCreateSpec class
- Added check_for_overlaps method
- Implemented has_overlapping_availability function
- Enhanced validation for availability and schedule creation
care/emr/tests/test_schedule_api.py - Added multiple test methods for schedule and availability validation
- Included tests for overlapping availability, duration, and time range checks

Assessment against linked issues

Objective Addressed Explanation
Prevent overlapping schedule sessions [#10237]
Warn users about overlapping sessions Frontend warning pop-up not implemented

Possibly related PRs

  • Nullable slot related fields for non-appointment slot types; disallow update for availability #2721: The changes in the main PR are related to the modifications of the AvailabilityCreateSpec class and its usage in the AvailabilityViewSet, which directly connects to the updates made to the AvailabilityForScheduleSpec class in the retrieved PR.
  • Scheduling and Appointments: Validations and other minor fixes #2711: The changes in the main PR are related to the modifications in the AvailabilityViewSet class, particularly the introduction of the AvailabilityCreateSpec, which is also referenced in the retrieved PR's updates to the AvailabilityForScheduleSpec and AvailabilityCreateSpec classes, indicating a direct connection in their functionality.
  • Delete TokenSlots when availability is deleted #2786: The changes in the main PR and the retrieved PR are related as both modify the perform_destroy method in the AvailabilityViewSet class, with the main PR enhancing the method to check for future bookings before deletion, while the retrieved PR adds functionality to delete associated TokenSlot entries.

Suggested reviewers

  • vigneshhari

Poem

In schedules tight and times precise,
Where overlaps once danced with vice,
Validation's sword now cuts so clean,
No double-booked moments to glean! 🕰️✨
Code's rhythm finds its perfect slice! 🎯

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ 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: 2

🧹 Nitpick comments (5)
care/emr/api/viewsets/scheduling/schedule.py (1)

169-171: Good data consistency enforcement.

The method ensures schedule is properly set from URL parameters. Though, it might be worth adding a docstring to explain its purpose, you know, for those who come after us.

 def clean_create_data(self, request_data):
+    """Ensure schedule is set from URL parameters before creating availability."""
     request_data["schedule"] = self.kwargs["schedule_external_id"]
     return request_data
care/emr/resources/scheduling/schedule/spec.py (2)

71-82: Slot duration validation could be more efficient.

While the validation logic is correct, we're doing datetime operations that could be simplified to time-based calculations.

Consider this more efficient approach:

-    start_time = datetime.datetime.combine(datetime.date.today(), availability.start_time, tzinfo=None)
-    end_time = datetime.datetime.combine(datetime.date.today(), availability.end_time, tzinfo=None)
-    slot_size_in_seconds = self.slot_size_in_minutes * 60
-    if (end_time - start_time).total_seconds() % slot_size_in_seconds != 0:
+    minutes_diff = (
+        availability.end_time.hour * 60 + availability.end_time.minute
+        - (availability.start_time.hour * 60 + availability.start_time.minute)
+    )
+    if minutes_diff % self.slot_size_in_minutes != 0:
🧰 Tools
🪛 Ruff (0.8.2)

73-73: datetime.date.today() used

(DTZ011)


76-76: datetime.date.today() used

(DTZ011)

🪛 GitHub Actions: Lint Code Base

[error] 73-73: DTZ011: Use datetime.datetime.now(tz=...).date() instead of datetime.date.today()


[error] 76-76: DTZ011: Use datetime.datetime.now(tz=...).date() instead of datetime.date.today()


221-233: Document the overlap checking algorithm.

While the implementation is efficient by skipping different days, it would be nice to have some documentation explaining the algorithm.

 def has_overlapping_availability(availabilities: list[AvailabilityDateTimeSpec]):
+    """
+    Check if any two availabilities overlap in time on the same day.
+    
+    Args:
+        availabilities: List of availability specs to check
+    
+    Returns:
+        bool: True if any overlaps found, False otherwise
+    
+    Note:
+        Two time ranges overlap if start of one is before end of other
+        and vice versa. We optimize by skipping checks for different days.
+    """
     for i in range(len(availabilities)):
care/emr/tests/test_schedule_api.py (2)

193-236: Add more edge cases to the overlapping availability test.

While the current test is good, it would be even better to test more edge cases.

Consider adding these test cases:

# Test exact boundary overlap
{
    "day_of_week": 1,
    "start_time": "13:00:00",
    "end_time": "17:00:00",
}, {
    "day_of_week": 1,
    "start_time": "17:00:00",  # Boundary case
    "end_time": "20:00:00",
}

# Test complete containment
{
    "day_of_week": 1,
    "start_time": "09:00:00",
    "end_time": "17:00:00",
}, {
    "day_of_week": 1,
    "start_time": "11:00:00",  # Contained within first slot
    "end_time": "15:00:00",
}

932-956: Make the slot size validation test more explicit.

The test could be clearer about why it fails. The magic number 13:13:00 doesn't immediately show why it's invalid.

Consider making the test more explicit:

-                    "end_time": "13:13:00",
+                    # 4 hours and 13 minutes = 253 minutes
+                    # Not divisible by slot_size_in_minutes (30)
+                    "end_time": "13:13:00",  # Results in 253 minutes
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 73ff1bc and 525ca75.

📒 Files selected for processing (3)
  • care/emr/api/viewsets/scheduling/schedule.py (3 hunks)
  • care/emr/resources/scheduling/schedule/spec.py (4 hunks)
  • care/emr/tests/test_schedule_api.py (3 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
care/emr/resources/scheduling/schedule/spec.py

73-73: datetime.date.today() used

(DTZ011)


76-76: datetime.date.today() used

(DTZ011)

🪛 GitHub Actions: Lint Code Base
care/emr/resources/scheduling/schedule/spec.py

[error] 73-73: DTZ011: Use datetime.datetime.now(tz=...).date() instead of datetime.date.today()


[error] 76-76: DTZ011: Use datetime.datetime.now(tz=...).date() instead of datetime.date.today()

⏰ 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/scheduling/schedule.py (1)

22-22: Nice separation of create and retrieve models!

The change from AvailabilityForScheduleSpec to AvailabilityCreateSpec for creation while keeping AvailabilityForScheduleSpec for retrieval shows good attention to separation of concerns.

Also applies to: 136-137

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

54-58: ⚠️ Potential issue

Good validation logic, but let's fix those timezone warnings.

The validation checks for overlaps and time order are solid. However, there's a timezone-related issue that needs attention in the implementation.

The use of datetime.date.today() in the validation logic could lead to timezone-related issues. Consider using timezone-aware datetime objects consistently:

-    start_time = datetime.datetime.combine(datetime.date.today(), availability.start_time, tzinfo=None)
+    start_time = datetime.datetime.now(UTC).replace(
+        hour=availability.start_time.hour,
+        minute=availability.start_time.minute,
+        second=availability.start_time.second,
+        microsecond=0
+    )

Likely invalid or redundant comment.

care/emr/tests/test_schedule_api.py Outdated Show resolved Hide resolved
rithviknishad and others added 6 commits January 30, 2025 13:51
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
…uration-multiple-of-slot-size-in-minutes' into rithviknishad/fix/availability-duration-multiple-of-slot-size-in-minutes
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 (4)
care/emr/resources/scheduling/schedule/spec.py (4)

55-59: Perhaps we could make these error messages a tad more helpful?

The validation logic is correct, but the error messages could be more descriptive to help users understand exactly what went wrong.

-            raise ValueError("Availability time ranges are overlapping")
+            raise ValueError("Cannot create overlapping availability time ranges. Please ensure all time slots are distinct.")
-                raise ValueError("Start time must be earlier than end time")
+                raise ValueError(f"Invalid time range: start time ({availability.start_time}) must be earlier than end time ({availability.end_time})")

71-83: A tiny optimization opportunity presents itself...

The current implementation creates datetime objects just to calculate duration. We could simplify this by working directly with time objects.

-                start_time = datetime.datetime.combine(
-                    datetime.datetime.now(tz=UTC).date(), availability.start_time
-                )
-                end_time = datetime.datetime.combine(
-                    datetime.datetime.now(tz=UTC).date(), availability.end_time
-                )
-                slot_size_in_seconds = self.slot_size_in_minutes * 60
-                if (end_time - start_time).total_seconds() % slot_size_in_seconds != 0:
+                seconds_in_day = 24 * 60 * 60
+                start_seconds = availability.start_time.hour * 3600 + availability.start_time.minute * 60
+                end_seconds = availability.end_time.hour * 3600 + availability.end_time.minute * 60
+                if end_seconds < start_seconds:
+                    end_seconds += seconds_in_day
+                duration_seconds = end_seconds - start_seconds
+                if duration_seconds % (self.slot_size_in_minutes * 60) != 0:

136-146: Type hints would make this even better...

The implementation is clean, but adding return type hints would improve code maintainability.

     @classmethod
-    def validate_availabilities_not_overlapping(
-        cls, availabilities: list[AvailabilityForScheduleSpec]
-    ):
+    def validate_availabilities_not_overlapping(
+        cls, availabilities: list[AvailabilityForScheduleSpec]
+    ) -> list[AvailabilityForScheduleSpec]:

222-234: O(n²) might not be our best friend here...

The current implementation uses nested loops which could be inefficient for large datasets. Consider optimizing by sorting availabilities first.

 def has_overlapping_availability(availabilities: list[AvailabilityDateTimeSpec]):
+    # Sort availabilities by day_of_week and start_time
+    sorted_avail = sorted(availabilities, key=lambda x: (x.day_of_week, x.start_time))
+    
+    # Check adjacent pairs for overlap (O(n))
+    for i in range(len(sorted_avail) - 1):
+        if sorted_avail[i].day_of_week == sorted_avail[i + 1].day_of_week:
+            if sorted_avail[i].end_time > sorted_avail[i + 1].start_time:
+                return True
+    return False
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 525ca75 and 9186643.

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

90-112: That nested list comprehension issue is still lurking around...

The bug in extending availabilities still needs to be addressed as mentioned in the previous review.

@vigneshhari
Copy link
Member

@rithviknishad Fix Tests

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9186643 and f14a71a.

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

193-236: LGTM! The test case effectively validates overlapping availability rejection.

The test case thoroughly checks that schedule creation fails when availability sessions overlap on the same day.


775-792: LGTM! The test case effectively validates rejection of overlapping availabilities.

The test case thoroughly checks that availability creation fails when it overlaps with existing availabilities.


793-808: LGTM! The test case effectively validates acceptance of non-overlapping availabilities.

The test case thoroughly checks that availability creation succeeds when it doesn't overlap with existing availabilities.


969-991: LGTM! The test case effectively validates time order.

The test case thoroughly checks that availability creation fails when end time is before start time.

care/emr/tests/test_schedule_api.py Outdated Show resolved Hide resolved
Copy link

codecov bot commented Feb 4, 2025

Codecov Report

Attention: Patch coverage is 26.66667% with 33 lines in your changes missing coverage. Please review.

Project coverage is 56.34%. Comparing base (5d8cc0f) to head (5e4e593).
Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
care/emr/resources/scheduling/schedule/spec.py 22.50% 31 Missing ⚠️
care/emr/api/viewsets/scheduling/schedule.py 60.00% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2795      +/-   ##
===========================================
- Coverage    56.44%   56.34%   -0.11%     
===========================================
  Files          214      214              
  Lines        10130    10168      +38     
  Branches      1023     1032       +9     
===========================================
+ Hits          5718     5729      +11     
- Misses        4396     4423      +27     
  Partials        16       16              

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

rithviknishad and others added 2 commits February 4, 2025 15:57
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
care/emr/tests/test_schedule_api.py (1)

965-965: Please review the formatting changes made by ruff-format.

The line was reformatted by the ruff-format hook. While it's a minor change, it would be ever so slightly nice if you could review and confirm the formatting.

🧰 Tools
🪛 GitHub Actions: Lint Code Base

[warning] 965-965: File was reformatted by ruff-format hook. Please review the changes.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f14a71a and 7698a2e.

📒 Files selected for processing (1)
  • care/emr/tests/test_schedule_api.py (6 hunks)
🧰 Additional context used
🪛 GitHub Actions: Lint Code Base
care/emr/tests/test_schedule_api.py

[warning] 965-965: File was reformatted by ruff-format hook. Please review the changes.

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test / Test
  • GitHub Check: Analyze (python)
🔇 Additional comments (5)
care/emr/tests/test_schedule_api.py (5)

193-236: LGTM! Well-structured test for overlapping availabilities.

The test effectively validates that schedules with overlapping availabilities are rejected. The test data is clear and the assertion message accurately reflects the test case.


775-791: LGTM! Good test coverage for overlapping availability rejection.

The test effectively validates that new availabilities cannot overlap with existing ones.


793-808: LGTM! Good test coverage for non-overlapping availability acceptance.

The test effectively validates that non-overlapping availabilities are accepted, providing a nice complement to the rejection test.


944-967: LGTM! Good test for slot size duration validation.

The test effectively validates that availability duration must be a multiple of slot size. The test data cleverly uses a non-multiple duration (13:13:00) to trigger the validation.

🧰 Tools
🪛 GitHub Actions: Lint Code Base

[warning] 965-965: File was reformatted by ruff-format hook. Please review the changes.


968-989: LGTM! Good test for time order validation.

The test effectively validates that start time must be before end time. The test data and assertion message are clear and accurate.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
care/emr/tests/test_schedule_api.py (1)

944-968: The test description could be more specific.

The test description could mention that it's specifically testing for non-multiple durations being rejected, which would make the test's purpose clearer at first glance... if you're into that sort of thing.

Apply this diff to improve the test description:

-    """Test validation rules for ensuring availability duration is multiple of slot size in minutes."""
+    """Test that availability creation fails when duration is not a multiple of slot size in minutes."""
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7698a2e and 5e4e593.

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

193-236: LGTM! Nice test coverage for overlapping availabilities.

The test effectively validates that schedule creation fails when availability sessions overlap, with proper error message assertion.


775-792: LGTM! Good negative test case.

The test correctly verifies that overlapping availabilities are rejected.


793-808: LGTM! Good positive test case.

The test properly validates that non-overlapping availabilities are accepted.


969-991: The test description doesn't match the test case.

The comment "Try to create availability with overlapping time ranges for same day" is incorrect as this test is about time order validation.

Apply this diff to fix the comment:

-        # Try to create availability with overlapping time ranges for same day
+        # Try to create availability with end time before start time

@vigneshhari vigneshhari merged commit 9967353 into develop Feb 4, 2025
6 of 8 checks passed
@vigneshhari vigneshhari deleted the rithviknishad/fix/availability-duration-multiple-of-slot-size-in-minutes branch February 4, 2025 16:52
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.

Add Overlapping schedule session creation warning
2 participants