2.8 KiB
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
useStatsto 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_timetableto accepttimezone_offset: int = Query(0).get_daily_summaryandget_wake_sleep_timesto also accepttimezone_offset.
- Core Logic Change: In
get_timetable:- Use
timezone_offsetto translate the requestedfrom_date/to_date(local) into a UTC range for database queries. - When generating slots, calculate the
slot_start_timeandslot_end_timein 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.
- Use
3. Frontend Implementation (Integration)
- Update Hook: Modify
frontend/src/hooks/useStats.tsto accepttimezoneOffsetand pass it to the API calls (fetchTimetable, etc.). - Update Client: Modify
frontend/src/api/client.tsto include the offset in request parameters. - Update Component: In
frontend/src/components/stats/SleepTimetable.tsx, ensure the component retrieves the offset vianew Date().getTimezoneOffset()and passes it touseStats. - Cleanup: Remove the manual
adjustForTimezonecalls inSleepTimetable.tsxsince 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.