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

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from

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.

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

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.

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

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! 🎯

✨ 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

@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

@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

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