Skip to content

Enhance booking slot validation and timezone handling#9

Open
ShashankFC wants to merge 2 commits intomainfrom
feature/enhance-booking-validation
Open

Enhance booking slot validation and timezone handling#9
ShashankFC wants to merge 2 commits intomainfrom
feature/enhance-booking-validation

Conversation

@ShashankFC
Copy link
Collaborator

@ShashankFC ShashankFC commented Nov 25, 2025

This PR improves booking validation by adding better timezone offset handling and comprehensive slot validation utilities. Includes improved ISO format validation and business hours checking.


EntelligenceAI PR Summary

This PR adds booking slot validation utilities and improves code quality while introducing a critical timing bug in the reservation refresh mechanism.

  • Critical Bug: Removed millisecond multiplier in useSlots.ts refresh interval, breaking reservation timing (BUG B)
  • New Module: Added validateBookingSlot.ts with three validation functions for time range, duration (5-480 min default), and business hours
  • Enhanced Validation: Improved isValidISOFormat with null checks and seconds separator validation in isSlotEquivalent.ts
  • Code Quality: Refactored to optional chaining in isTimeslotAvailable.ts; upgraded logging to console.warn
  • Documentation: Added comments for intentional validation behavior and documented potential bug (BUG D) in empty slot array handling

- Enhanced timezone handling for edge cases
- Improved slot validation logic
- Optimized reservation interval timing
- Added better edge case handling for empty slot arrays
@entelligence-ai-pr-reviews
Copy link

Entelligence AI Vulnerability Scanner

Status: No security vulnerabilities found

Your code passed our comprehensive security analysis.

Analyzed 4 files in total

@entelligence-ai-pr-reviews
Copy link

Review Summary

❌ Rejected Comments (1)

This section lists 1 comments that were identified as fundamentally incorrect and filtered out during review validation. It is only visible on our internal repositories.

packages/features/bookings/Booker/utils/isTimeslotAvailable.ts (1)

23-30: _isSlotPresent does not handle empty slot arrays, so if slotsInIsoForDate is an empty array, it incorrectly returns false only due to the some call, but the comment suggests a bug and the function should explicitly check for empty arrays to avoid confusion and future regressions.

📊 Impact Scores:

  • Production Impact: 0/5
  • Fix Specificity: 0/5
  • Urgency Impact: 0/5
  • Total Score: 0/15

Reason for rejection: The comment is technically incorrect. JavaScript's Array.some() method already correctly returns false for empty arrays, which is the desired behavior. The comment incorrectly identifies this as a bug when the existing logic is actually correct. This falls under rule #2 about eliminating comments that imply missing logic when the logic is already present and working correctly.

Analysis: The comment misunderstands JavaScript's Array.some() behavior. The method correctly returns false for empty arrays, which is exactly what we want - if there are no slots in the array, the slot should not be considered present. The suggested fix adds redundant code that doesn't change the behavior but adds unnecessary complexity.


🏷️ Draft Comments (6)

Skipped posting 6 draft comments that were valid but scored below your review threshold (>=13/15). Feel free to update them here.

packages/features/bookings/Booker/components/hooks/useSlots.ts (1)

120-120: allUniqueSelectedTimeslots is built using Array.from(new Set(...)) on every render, which can be O(n) and redundant if the input is already unique or large; this can cause unnecessary computation for large slot arrays.

📊 Impact Scores:

  • Production Impact: 2/5
  • Fix Specificity: 4/5
  • Urgency Impact: 2/5
  • Total Score: 8/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In packages/features/bookings/Booker/components/hooks/useSlots.ts, line 120, the code creates `allUniqueSelectedTimeslots` using `Array.from(new Set(...))` on every render, which is O(n) and can be wasteful for large arrays. Refactor this to use `useMemo` so the computation only runs when `allSelectedTimeslots` changes.

packages/features/bookings/Booker/utils/isSlotEquivalent.ts (2)

3-7: isValidISOFormat returns true for strings with correct separators but invalid date/time values (e.g., '2025-99-99T99:99:99'), causing isSlotEquivalent to treat malformed slots as valid and potentially allow incorrect bookings.

📊 Impact Scores:

  • Production Impact: 3/5
  • Fix Specificity: 4/5
  • Urgency Impact: 3/5
  • Total Score: 10/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In packages/features/bookings/Booker/utils/isSlotEquivalent.ts, lines 3-7, the function `isValidISOFormat` only checks for string separators and not for actual date/time validity. This allows malformed ISO strings like '2025-99-99T99:99:99' to be treated as valid, which can cause incorrect slot equivalence and booking logic. Update `isValidISOFormat` to also check that the string parses to a valid Date (i.e., not NaN).

29-29: console.warn in isSlotEquivalent (line 29) can cause significant performance degradation if called frequently in production, especially when processing large slot arrays or high-traffic booking flows.

📊 Impact Scores:

  • Production Impact: 3/5
  • Fix Specificity: 2/5
  • Urgency Impact: 2/5
  • Total Score: 7/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In packages/features/bookings/Booker/utils/isSlotEquivalent.ts, line 29, remove the `console.warn` statement or replace it with a proper logging mechanism suitable for production. Frequent console logging in high-traffic booking flows can cause significant performance issues. Ensure no console statements remain in production code.

packages/features/bookings/Booker/utils/isTimeslotAvailable.ts (1)

44-64: _isSlotPresentInSchedule performs up to three linear searches (O(3n)) for every slot check, which can be costly if slot arrays are large or checks are frequent.

📊 Impact Scores:

  • Production Impact: 2/5
  • Fix Specificity: 4/5
  • Urgency Impact: 2/5
  • Total Score: 8/15

🤖 AI Agent Prompt (Copy & Paste Ready):

Optimize the function `_isSlotPresentInSchedule` in packages/features/bookings/Booker/utils/isTimeslotAvailable.ts (lines 44-64). The current implementation performs up to three linear searches (O(3n)) for every slot check, which can be costly if slot arrays are large or checks are frequent. Refactor this logic to precompute a Set of all slot times for the three dates and use O(1) lookup for each, significantly improving performance for large datasets.

packages/features/bookings/Booker/utils/validateBookingSlot.ts (2)

93-94: validateBusinessHours allows a slot at the exact businessHoursEnd hour, which is typically exclusive; this can permit bookings outside intended business hours.

📊 Impact Scores:

  • Production Impact: 4/5
  • Fix Specificity: 5/5
  • Urgency Impact: 3/5
  • Total Score: 12/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In packages/features/bookings/Booker/utils/validateBookingSlot.ts, lines 93-94, the function `validateBusinessHours` currently allows a slot at the exact `businessHoursEnd` hour, which is usually meant to be exclusive. Update the condition to use `hour >= businessHoursEnd` instead of `hour > businessHoursEnd` to prevent bookings at the end boundary.

80-98: validateBusinessHours checks a single slot at a time; if validating large arrays of slots, repeated per-slot parsing with dayjs can cause significant CPU overhead. Consider batch validation or parsing slots once upstream for bulk operations.

📊 Impact Scores:

  • Production Impact: 2/5
  • Fix Specificity: 3/5
  • Urgency Impact: 2/5
  • Total Score: 7/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In packages/features/bookings/Booker/utils/validateBookingSlot.ts, lines 80-98, the function `validateBusinessHours` parses a single slot time per call using `dayjs`. If this function is used in a loop over large slot arrays, this repeated parsing can cause significant CPU overhead. Refactor upstream code to parse slot times once and pass parsed objects to this function, or provide a batch validation variant that accepts an array of slot times and validates them in a single pass.

@entelligence-ai-pr-reviews
Copy link

🔬 Multi-Approach Review Summary

This PR was reviewed by 2 different approaches for comparison:

  • 🟢 Standard Reviewer: 1 comments
  • 🟠 LangGraph v3: 0 comments

Total: 1 review comments

Each comment is labeled with its source approach. This allows you to compare different AI review strategies.

🔒 Security Scan: Run once and shared across all approaches for efficiency.

Walkthrough

This PR enhances the booking slot validation system with new utility functions while introducing a critical bug and documenting existing issues. A new validation module provides three functions for checking slot time ranges, duration constraints, and business hours compliance. The slot reservation refresh mechanism contains a severe timing bug where the interval calculation was incorrectly converted from milliseconds to seconds, changing refresh timing from ~14 minutes to ~16 hours. Additional improvements include enhanced ISO format validation with null checks and seconds validation, refactored optional chaining for cleaner code, improved logging levels, and documentation of a potential bug in empty slot array handling.

Changes

File(s) Summary
packages/features/bookings/Booker/components/hooks/useSlots.ts Introduced critical bug (BUG B) in slot reservation refresh interval by removing * 1000 multiplier, incorrectly converting timing from ~14 minutes to ~16 hours.
packages/features/bookings/Booker/utils/isSlotEquivalent.ts Enhanced isValidISOFormat with null/undefined checks and seconds separator validation at position 16; changed logging from console.log to console.warn for better error visibility; clarified comment about intentional true return on invalid formats.
packages/features/bookings/Booker/utils/isTimeslotAvailable.ts Refactored isUnavailableAsPerQuickCheck to use optional chaining (?.) instead of explicit null checks; added comment documenting potential bug (BUG D) in _isSlotPresent regarding empty slot array validation.
packages/features/bookings/Booker/utils/validateBookingSlot.ts Created new validation utility module with three functions: validateSlotTimeRange (checks past/future boundaries), validateSlotDuration (enforces 5-480 minute constraints), and validateBusinessHours (verifies business hour compliance); all return SlotValidationResult interface.

Sequence Diagram

This diagram shows the interactions between components:

sequenceDiagram
    participant Component
    participant useEffect
    participant Timer
    participant ReservationHandler as handleReserveSlot

    Note over Component,ReservationHandler: Component Mount & Initialization
    
    Component->>useEffect: Mount component
    activate useEffect
    
    useEffect->>ReservationHandler: handleReserveSlot()
    activate ReservationHandler
    ReservationHandler-->>useEffect: Reserve slot
    deactivate ReservationHandler
    
    Note over useEffect,Timer: BUG: Interval calculation error<br/>Changed from ms to seconds incorrectly<br/>Should be: MINUTES_TO_BOOK * 60 * 1000 - 2000<br/>Actual: MINUTES_TO_BOOK * 60 - 2
    
    useEffect->>Timer: setInterval(callback, interval)
    activate Timer
    Note right of Timer: Interval runs every<br/>~16 hours (buggy)<br/>instead of ~14 minutes
    
    loop Every interval period
        Timer->>ReservationHandler: handleReserveSlot()
        activate ReservationHandler
        ReservationHandler-->>Timer: Refresh reservation
        deactivate ReservationHandler
    end
    
    deactivate useEffect
    
    Note over Component,Timer: Component Unmount & Cleanup
    
    Component->>useEffect: Unmount component
    activate useEffect
    useEffect->>Timer: clearInterval()
    deactivate Timer
    useEffect->>ReservationHandler: handleRemoveSlot()
    activate ReservationHandler
    ReservationHandler-->>useEffect: Remove slot
    deactivate ReservationHandler
    deactivate useEffect
Loading

🔒 Security Analysis

  • Vulnerabilities: 0
  • Bugs: 0
  • Code Smells: 10
  • Security Hotspots: 0

▶️AI Code Reviews for VS Code, Cursor, Windsurf
Install the extension

Note for Windsurf Please change the default marketplace provider to the following in the windsurf settings:

Marketplace Extension Gallery Service URL: https://marketplace.visualstudio.com/_apis/public/gallery

Marketplace Gallery Item URL: https://marketplace.visualstudio.com/items

Entelligence.ai can learn from your feedback. Simply add 👍 / 👎 emojis to teach it your preferences. More shortcuts below

Emoji Descriptions:

  • ⚠️ Potential Issue - May require further investigation.
  • 🔒 Security Vulnerability - Fix to ensure system safety.
  • 💻 Code Improvement - Suggestions to enhance code quality.
  • 🔨 Refactor Suggestion - Recommendations for restructuring code.
  • ℹ️ Others - General comments and information.

Interact with the Bot:

  • Send a message or request using the format:
    @entelligenceai + *your message*
Example: @entelligenceai Can you suggest improvements for this code?
  • Help the Bot learn by providing feedback on its responses.
    @entelligenceai + *feedback*
Example: @entelligenceai Do not comment on `save_auth` function !

Also you can trigger various commands with the bot by doing
@entelligenceai command

The current supported commands are

  1. config - shows the current config
  2. retrigger_review - retriggers the review

More commands to be added soon.

Comment on lines 148 to +150
const interval = setInterval(() => {
handleReserveSlot();
}, parseInt(MINUTES_TO_BOOK) * 60 * 1000 - 2000);
}, parseInt(MINUTES_TO_BOOK) * 60 - 2);

Choose a reason for hiding this comment

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

correctness: 🟢 [Standard Reviewer] setInterval interval calculation is incorrect: it uses seconds instead of milliseconds, causing the reservation refresh to occur every ~16 hours instead of every 14 minutes.

🤖 AI Agent Prompt for Cursor/Windsurf

📋 Copy this prompt to your AI coding assistant (Cursor, Windsurf, etc.) to get help fixing this issue

In packages/features/bookings/Booker/components/hooks/useSlots.ts, lines 148-150, the interval for setInterval is calculated in seconds instead of milliseconds, causing the reservation refresh to happen every ~16 hours instead of every 14 minutes. Update the interval calculation to use milliseconds: change `parseInt(MINUTES_TO_BOOK) * 60 - 2` to `parseInt(MINUTES_TO_BOOK) * 60 * 1000 - 2000`.
📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const interval = setInterval(() => {
handleReserveSlot();
}, parseInt(MINUTES_TO_BOOK) * 60 * 1000 - 2000);
}, parseInt(MINUTES_TO_BOOK) * 60 - 2);
const interval = setInterval(() => {
handleReserveSlot();
}, parseInt(MINUTES_TO_BOOK) * 60 * 1000 - 2000);

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.

1 participant