Files

2.8 KiB

Implementation Plan: Fix Sleep Timetable Timezone Issue

Overview

The SleepTimetable component incorrectly attributes sleep segments spanning midnight to the wrong day because the backend calculates time-slots in UTC without awareness of the user's local timezone. This plan implements a timezone-aware API to ensure sleep sessions are correctly mapped to the user's local dates.

Detailed Steps

1. Reproduction (Frontend Test)

  • Create a new test file or add to frontend/tests/unit/components/stats/SleepTimetable.test.tsx.
  • Mock useStats to return a timetable containing a session that spans midnight (e.g., Wed 23:00 - Thu 06:00).
  • The mock data should reflect what the backend currently returns (which is incorrectly attributed to the wrong day due to timezone mismatch).
  • Assert that for a user in a non-UTC timezone, the green slots for 00:00-02:00 are on the correct day (Thu).
  • This test is expected to fail initially because the current implementation attributes them to Wed.

2. Backend Implementation (API & Logic)

  • Modify API: Update backend/app/routers/stats.py:
    • get_timetable to accept timezone_offset: int = Query(0).
    • get_daily_summary and get_wake_sleep_times to also accept timezone_offset.
  • Core Logic Change: In get_timetable:
    • Use timezone_offset to translate the requested from_date/to_date (local) into a UTC range for database queries.
    • When generating slots, calculate the slot_start_time and slot_end_time in UTC for comparison with session times.
    • When creating the response object, convert those UTC times to Local Time and attach the correct Local Date.
    • This ensures that a session spanning midnight is correctly mapped to its local date segments.

3. Frontend Implementation (Integration)

  • Update Hook: Modify frontend/src/hooks/useStats.ts to accept timezoneOffset and pass it to the API calls (fetchTimetable, etc.).
  • Update Client: Modify frontend/src/api/client.ts to include the offset in request parameters.
  • Update Component: In frontend/src/components/stats/SleepTimetable.tsx, ensure the component retrieves the offset via new Date().getTimezoneOffset() and passes it to useStats.
  • Cleanup: Remove the manual adjustForTimezone calls in SleepTimetable.tsx since the backend will now provide correctly adjusted local times.

4. Verification

  • Run the frontend unit tests.
  • Verify the fix against the reported issue using a manual test or e2e test if possible.

Note to Developer: To maintain a high-quality context window and avoid hallucinations, you MUST delegate complex tasks to sub-agents. Break down each phase above into smaller, atomic objectives for sub-agents (e.g., one agent for backend API changes, another for frontend hook updates). Do not attempt to execute the entire plan in a single thread.