-
Notifications
You must be signed in to change notification settings - Fork 342
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
📝 WalkthroughWalkthroughThe 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
Assessment against linked issues
Possibly related PRs
Suggested reviewers
Poem
Tip 🌐 Web search-backed reviews and chat
✨ Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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
📒 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
toAvailabilityCreateSpec
for creation while keepingAvailabilityForScheduleSpec
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 issueGood 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.
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
There was a problem hiding this 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
📒 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.
@rithviknishad Fix Tests |
There was a problem hiding this 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
📒 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.
Codecov ReportAttention: Patch coverage is
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. |
…ultiple-of-slot-size-in-minutes
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
There was a problem hiding this 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
📒 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.
There was a problem hiding this 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
📒 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
Proposed Changes
Associated Issue
Merge Checklist
@ohcnetwork/care-backend-maintainers @ohcnetwork/care-backend-admins
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Tests