timetable maybe working, very cloase at least

This commit is contained in:
2026-06-03 22:14:18 +02:00
parent db0f717560
commit 7d4e2a376c
6 changed files with 126 additions and 136 deletions
+32 -31
View File
@@ -1,37 +1,38 @@
# Plan: Add Median Statistic to Wakeup and Bedtime Plots
# Implementation Plan: Fix Sleep Timetable Timezone Issue
## Overview
The goal is to add a fourth statistic, "Median", to the summary section below the Wakeup and Bedtime trend graphs in `WakeupPlot.tsx` and `BedtimePlot.tsx`. Currently, these components display "Earliest", "Latest", and "Average".
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 Tasks
## Detailed Steps
### 1. Update `frontend/src/components/stats/WakeupPlot.tsx`
- **Sub-task 1.1: Update Statistics Calculation**
- Locate the `stats` `useMemo` block.
- Calculate the median of `validMinutes`.
- *Note*: To calculate the median, sort the array and pick the middle element (or average of two middle elements if even).
- Include `median` in the returned object: `{ min, max, avg, median }`.
- **Sub-task 1.2: Update UI Layout**
- Find the statistics container div (currently `grid grid-cols-3`).
- Change the Tailwind class from `grid-cols-3` to `grid-cols-4`.
- **Sub-task 1.3: Add Median Display**
- Add a new `div` for the "Median" statistic.
- Use identical styling to the existing three blocks.
- Display the value using `formatMinutesAfter(Math.round(stats.median), wakeup_ref)`.
### 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. Update `frontend/src/components/stats/BedtimePlot.tsx`
- **Sub-task 2.1: Update Statistics Calculation**
- Locate the `stats` `useMemo` block.
- Calculate the median of `validMinutes`.
- Include `median` in the returned object: `{ min, max, avg, median }`.
- **Sub-task 2.2: Update UI Layout**
- Find the statistics container div (currently `grid grid-cols-3`).
- Change the Tailwind class from `grid-cols-3` to `grid-cols-4`.
- **Sub-task 2.3: Add Median Display**
- Add a new `div` for the "Median" statistic.
- Use identical styling to the existing three blocks.
- Display the value using `formatMinutesAfter(Math.round(stats.median), bedtime_ref)`.
### 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.
## Verification Plan
1. **Visual Inspection**: Ensure the four statistics are evenly spaced and aligned in a single row below each graph.
2. **Logic Check**: Manually verify with a small set of known numbers (e.g., [10, 20, 30] -> median 20; [10, 20, 30, 40] -> median 25) that the calculation is correct.
### 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.