Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Fix app-wide timezone handling for workouts, food queries, and server defaults (#83)
DisplacedForesteebb9a30849c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2a622fd..4e6ebcc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -84,7 +84,7 @@ jobs:go-version: '1.26'cache-dependency-path: backend/go.sum- run: cd backend && go mod download- - run: cd backend && go test ./controllers/ -timeout 30s+ - run: cd backend && go test ./controllers/ ./db/ ./routes/ -timeout 30sunit:name: Web unit testsdiff --git a/backend/controllers/food.go b/backend/controllers/food.goindex 6f581f4..16a3fd8 100644--- a/backend/controllers/food.go+++ b/backend/controllers/food.go@@ -27,11 +27,14 @@ const offUserAgent = "Lyftr/1.0 (https://lyftr.app; nutrition-tracker)"func (h *Handler) ListFoodLogs(c *gin.Context) {uid := middleware.UserID(c)- date := c.Query("date")- if date == "" {- date = time.Now().Format("2006-01-02")+ // `date=` names a day in the diary, and entries carry the day they were filed+ // under, so this is a lookup rather than a zone conversion. The zone is consulted+ // only to answer "what is today" when the parameter is omitted.+ date, ok := h.resolveQueryDay(uid, c.Query("date"))+ if !ok {+ utils.BadRequest(c, "date must be YYYY-MM-DD")+ return}-logs, err := h.s.Food.ListByDay(uid, date)if utils.DBError(c, err) {return@@ -39,6 +42,7 @@ func (h *Handler) ListFoodLogs(c *gin.Context) {utils.OK(c, logs)}+func (h *Handler) GetFoodLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)@@ -86,14 +90,18 @@ func (h *Handler) LogFood(c *gin.Context) {return}- if req.LoggedAt.IsZero() {- req.LoggedAt = time.Now()- }+ req.LoggedAt = normalizeLoggedAt(req.LoggedAt)if req.Servings == 0 {req.Servings = 1}- f, err := h.s.Food.Create(uid, req)+ day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)+ if !ok {+ utils.BadRequest(c, "logged_on must be YYYY-MM-DD")+ return+ }++ f, err := h.s.Food.Create(uid, req, day)if utils.DBError(c, err) {return}@@ -133,11 +141,18 @@ func (h *Handler) UpdateFoodLog(c *gin.Context) {utils.BadRequest(c, "image_url exceeds 500 characters")return}+ req.LoggedAt = normalizeLoggedAt(req.LoggedAt)if req.Servings == 0 {req.Servings = 1}- f, err := h.s.Food.Update(uid, lid, req)+ day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)+ if !ok {+ utils.BadRequest(c, "logged_on must be YYYY-MM-DD")+ return+ }++ f, err := h.s.Food.Update(uid, lid, req, day)if err == sql.ErrNoRows {utils.NotFound(c, "log entry not found")return@@ -169,17 +184,20 @@ func (h *Handler) DeleteFoodLog(c *gin.Context) {func (h *Handler) GetDailyStats(c *gin.Context) {uid := middleware.UserID(c)- date := c.Query("date")- if date == "" {- date = time.Now().Format("2006-01-02")+ date, ok := h.resolveQueryDay(uid, c.Query("date"))+ if !ok {+ utils.BadRequest(c, "date must be YYYY-MM-DD")+ return}-stats, err := h.s.Food.DailyMacros(uid, date)if utils.DBError(c, err) {return}stats.Date = date- if stats.WorkoutCount, err = h.s.Workout.CountOn(uid, date); utils.DBError(c, err) {+ // Both halves answer for the same named day: macros from the diary's stored day,+ // the workout count from each workout's own recorded offset. Neither is resolved+ // through the account's current zone, so they cannot drift apart.+ if stats.WorkoutCount, err = h.s.Workout.CountOnLocalDay(uid, date); utils.DBError(c, err) {return}utils.OK(c, stats)@@ -193,7 +211,10 @@ func (h *Handler) GetFoodHistory(c *gin.Context) {days = d}- points, err := h.s.Food.History(uid, days)+ // The window is counted back from the user's today — the one question a stored+ // day still cannot answer on its own.+ since := time.Now().In(h.userLocation(uid)).AddDate(0, 0, -days).Format("2006-01-02")+ points, err := h.s.Food.History(uid, since)if utils.DBError(c, err) {return}diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.goindex 6fd714b..3e9e3ab 100644--- a/backend/controllers/food_test.go+++ b/backend/controllers/food_test.go@@ -17,10 +17,14 @@ import (func insertFoodLog(t *testing.T, uid int64, name, meal string, calories, protein, carbs, fat float64, loggedAt time.Time) int64 {t.Helper()res, err := db.DB.Exec(- `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at)- VALUES (?, ?, ?, ?, ?, ?, ?, 0, 1, '', '', '', ?)`,+ `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, logged_on)+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, 1, '', '', '', ?, ?)`,uid, name, meal, calories, protein, carbs, fat,- loggedAt.Format("2006-01-02T15:04:05Z"),+ // Bound as time.Time, the way the stores do. Formatting to a string here+ // wrote a row shape production never creates, which hid exactly the class of+ // bug where a range comparison depends on the stored encoding.+ loggedAt,+ localDayFor(t, uid, loggedAt),)if err != nil {t.Fatalf("insertFoodLog: %v", err)@@ -29,6 +33,24 @@ func insertFoodLog(t *testing.T, uid int64, name, meal string, calories, proteinreturn id}+// localDayFor is the day a fixture row files itself under: the instant resolved in+// the user's stored zone, which is exactly what the handlers do for a client that+// sends no logged_on. Fixtures must derive it the same way production does — writing+// a day the app would never write is how a test ends up asserting a behaviour that+// does not exist.+func localDayFor(t *testing.T, uid int64, instant time.Time) string {+ t.Helper()+ var zone string+ if err := db.DB.QueryRow(`SELECT timezone FROM user_settings WHERE user_id = ?`, uid).Scan(&zone); err != nil {+ zone = "UTC" // no settings row is normal for a freshly created test user+ }+ loc, err := time.LoadLocation(zone)+ if err != nil {+ loc = time.UTC+ }+ return instant.In(loc).Format("2006-01-02")+}+func insertSavedFood(t *testing.T, uid int64, name string) int64 {t.Helper()res, err := db.DB.Exec(@@ -99,7 +121,7 @@ func TestListFoodLogs_scopedByDateAndUser(t *testing.T) {uid := createTestUser(t)other := otherUser(t)- today := time.Now()+ today := time.Now().UTC()yesterday := today.AddDate(0, 0, -1)insertFoodLog(t, uid, "Breakfast today", "breakfast", 400, 30, 50, 10, today)@@ -321,6 +343,57 @@ func TestUpdateFoodLog_success(t *testing.T) {}}+func TestUpdateFoodLog_omittedLoggedAtDefaultsToNow(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ id := insertFoodLog(t, uid, "Old name", "breakfast", 300, 20, 40, 10, time.Now())++ body := map[string]any{+ "name": "New name", "meal": "lunch",+ "calories": 450.0, "protein": 35.0, "carbs": 55.0, "fat": 12.0,+ }+ c, w := newContext(uid, http.MethodPatch, "/api/v1/food/"+fmt.Sprint(id), body)+ setParam(c, "id", fmt.Sprint(id))+ th.UpdateFoodLog(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ loggedAt, err := time.Parse(time.RFC3339, data["logged_at"].(string))+ if err != nil {+ t.Fatalf("parse logged_at %v: %v", data["logged_at"], err)+ }+ if age := time.Since(loggedAt); age < 0 || age > time.Minute {+ t.Fatalf("expected omitted logged_at to default to now, got %v (%v old)", loggedAt, age)+ }+}++func TestUpdateFoodLog_suppliedLoggedAtStoredAsUTC(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ id := insertFoodLog(t, uid, "Old name", "breakfast", 300, 20, 40, 10, time.Now())++ body := map[string]any{+ "name": "New name", "meal": "lunch",+ "calories": 450.0, "protein": 35.0, "carbs": 55.0, "fat": 12.0,+ "logged_at": "2026-07-16T20:00:00-05:00",+ }+ c, w := newContext(uid, http.MethodPatch, "/api/v1/food/"+fmt.Sprint(id), body)+ setParam(c, "id", fmt.Sprint(id))+ th.UpdateFoodLog(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if got := data["logged_at"].(string); got != "2026-07-17T01:00:00Z" {+ t.Fatalf("expected logged_at stored as UTC, got %q", got)+ }+}+func TestUpdateFoodLog_ownershipEnforced(t *testing.T) {setupTestDB(t)uid := createTestUser(t)@@ -409,7 +482,7 @@ func TestGetDailyStats_empty(t *testing.T) {setupTestDB(t)uid := createTestUser(t)- date := time.Now().Format("2006-01-02")+ date := time.Now().UTC().Format("2006-01-02")c, w := newContext(uid, http.MethodGet, "/api/v1/food/stats?date="+date, nil)th.GetDailyStats(c)@@ -427,7 +500,7 @@ func TestGetDailyStats_sumsMacrosCorrectly(t *testing.T) {setupTestDB(t)uid := createTestUser(t)- today := time.Now()+ today := time.Now().UTC()insertFoodLog(t, uid, "Breakfast", "breakfast", 500, 30, 60, 15, today)insertFoodLog(t, uid, "Lunch", "lunch", 700, 50, 80, 20, today)// Different date — must be excluded@@ -460,7 +533,7 @@ func TestGetDailyStats_scopedByUser(t *testing.T) {setupTestDB(t)uid := createTestUser(t)other := otherUser(t)- today := time.Now()+ today := time.Now().UTC()insertFoodLog(t, uid, "Mine", "breakfast", 400, 25, 50, 10, today)insertFoodLog(t, other, "Theirs", "lunch", 9999, 999, 999, 999, today)@@ -498,7 +571,7 @@ func TestGetFoodHistory_empty(t *testing.T) {func TestGetFoodHistory_groupsByDay(t *testing.T) {setupTestDB(t)uid := createTestUser(t)- now := time.Now()+ now := time.Now().UTC()// Two entries on same day → should be one aggregated pointinsertFoodLog(t, uid, "A", "breakfast", 400, 20, 50, 10, now.AddDate(0, 0, -1))@@ -931,3 +1004,326 @@ func TestDeleteSavedFood_ownershipEnforced(t *testing.T) {t.Fatal("saved food was deleted by wrong user")}}++// insertFoodLogAt is the common case of insertFoodLog: a dinner entry with only+// calories set. One insert path, so a change to the row shape can't leave a second+// fixture stale.+func insertFoodLogAt(t *testing.T, uid int64, name string, calories float64, loggedAt time.Time) int64 {+ t.Helper()+ return insertFoodLog(t, uid, name, "dinner", calories, 0, 0, 0, loggedAt)+}++// A west-of-UTC user's late-evening entry belongs to their day, not the UTC day.+// Originally written against an explicit from/to range; the range is gone, so this+// now asserts the same user-visible outcome through the stored zone — which is the+// only path a client actually takes.+func TestListFoodLogs_localDayWestTimezone(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ setUserTimezone(t, uid, "America/Los_Angeles") // UTC-7 in April++ // 03:00 UTC on the 25th is 20:00 on the 24th in Los Angeles.+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", map[string]any{+ "name": "Late dinner", "meal": "dinner", "calories": 800,+ "logged_at": "2026-04-25T03:00:00Z",+ })+ th.LogFood(c)+ // 08:00 UTC on the 25th is 01:00 on the 25th — the next local day.+ // The recorder is checked, not discarded: if this seed fails the "excluded from+ // the local day" assertion below passes for the wrong reason — the entry was+ // never there to leak in.+ c2, w2 := newContext(uid, http.MethodPost, "/api/v1/food", map[string]any{+ "name": "Next local day", "meal": "snacks", "calories": 500,+ "logged_at": "2026-04-25T08:00:00Z",+ })+ th.LogFood(c2)+ if w2.Code != http.StatusCreated {+ t.Fatalf("seed the next-local-day entry: %d %s", w2.Code, w2.Body.String())+ }++ c, w = newContext(uid, http.MethodGet, "/api/v1/food?date=2026-04-24", nil)+ th.ListFoodLogs(c)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ data := decodeResponse(t, w)["data"].([]any)+ if len(data) != 1 {+ t.Fatalf("expected 1 entry on the local day, got %d", len(data))+ }+ if name := data[0].(map[string]any)["name"].(string); name != "Late dinner" {+ t.Errorf("expected the local-evening entry, got %v", name)+ }+}++// Macros come from the stored day; the workout count still resolves through the+// zone, because a workout is an instant with no day of its own. Both halves of the+// payload must describe the same date.+func TestGetDailyStats_localDayWestTimezone(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ setUserTimezone(t, uid, "America/Los_Angeles")++ c, w := newContext(uid, http.MethodPost, "/api/v1/food", map[string]any{+ "name": "Late dinner", "meal": "dinner", "calories": 800,+ "logged_at": "2026-04-25T03:00:00Z",+ })+ th.LogFood(c)+ if w.Code != http.StatusCreated {+ t.Fatalf("seed the local-evening entry: %d %s", w.Code, w.Body.String())+ }+ // Checked for the same reason as above — an unseeded boundary entry cannot leak.+ c, w = newContext(uid, http.MethodPost, "/api/v1/food", map[string]any{+ "name": "Next local day", "meal": "snacks", "calories": 500,+ "logged_at": "2026-04-25T08:00:00Z",+ })+ th.LogFood(c)+ if w.Code != http.StatusCreated {+ t.Fatalf("seed the next-local-day entry: %d %s", w.Code, w.Body.String())+ }+ // -420 = Los Angeles in April. 03:30Z minus 7h is 20:30 on the 24th, so the+ // workout names the 24th itself rather than being resolved through a zone.+ if _, err := db.DB.Exec(+ `INSERT INTO workouts (user_id, name, started_at, tz_offset_minutes) VALUES (?, ?, ?, ?)`,+ uid, "Evening lift", time.Date(2026, 4, 25, 3, 30, 0, 0, time.UTC), -420,+ ); err != nil {+ t.Fatalf("insert workout: %v", err)+ }++ c, w = newContext(uid, http.MethodGet, "/api/v1/food/stats?date=2026-04-24", nil)+ th.GetDailyStats(c)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ data := decodeResponse(t, w)["data"].(map[string]any)+ if got := data["total_calories"].(float64); got != 800 {+ t.Errorf("expected total_calories=800 (local day only), got %v", got)+ }+ if got := data["workout_count"].(float64); got != 1 {+ t.Errorf("expected workout_count=1 on the same local day, got %v", got)+ }+ if got := data["date"].(string); got != "2026-04-24" {+ t.Errorf("expected date label 2026-04-24, got %v", got)+ }+}++// setUserTimezone stores an IANA zone for the user, the way a client's settings+// PATCH would.+func setUserTimezone(t *testing.T, uid int64, tz string) {+ t.Helper()+ if _, err := db.DB.Exec(+ `INSERT INTO user_settings (user_id, timezone) VALUES (?, ?)+ ON CONFLICT(user_id) DO UPDATE SET timezone = excluded.timezone`,+ uid, tz,+ ); err != nil {+ t.Fatalf("set timezone: %v", err)+ }+}++// An entry's day is decided by the user's zone at read time — so a client that only+// ever sends an instant (every build shipped) lands on the right day.+func TestListFoodLogs_bucketsByUserTimezone(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ setUserTimezone(t, uid, "America/New_York")++ // 01:00 UTC on the 25th is 21:00 on the 24th in New York.+ insertFoodLogAt(t, uid, "Late dinner", 800, time.Date(2026, 4, 25, 1, 0, 0, 0, time.UTC))+ // 05:00 UTC on the 25th is 01:00 on the 25th — the next local day.+ insertFoodLogAt(t, uid, "Midnight snack", 200, time.Date(2026, 4, 25, 5, 0, 0, 0, time.UTC))++ c, w := newContext(uid, http.MethodGet, "/api/v1/food?date=2026-04-24", nil)+ th.ListFoodLogs(c)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ logs := decodeResponse(t, w)["data"].([]any)+ if len(logs) != 1 {+ t.Fatalf("expected only the 24th's local entry, got %d", len(logs))+ }+ if name := logs[0].(map[string]any)["name"].(string); name != "Late dinner" {+ t.Errorf("expected the 21:00-local entry, got %q", name)+ }+}++// UTC+14 is the case noon-anchoring alone cannot survive: local noon on the 24th is+// 22:00 UTC on the *23rd*, so a UTC date prefix files it a day early. This is the+// whole reason the server needs to know the zone.+func TestListFoodLogs_farEastTimezone(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ setUserTimezone(t, uid, "Pacific/Kiritimati") // UTC+14++ insertFoodLogAt(t, uid, "Local noon", 600, time.Date(2026, 4, 23, 22, 0, 0, 0, time.UTC))++ c, w := newContext(uid, http.MethodGet, "/api/v1/food?date=2026-04-24", nil)+ th.ListFoodLogs(c)+ if n := len(decodeResponse(t, w)["data"].([]any)); n != 1 {+ t.Fatalf("expected the entry on its local day 2026-04-24, got %d", n)+ }+}++// Spring forward: 2026-03-08 is 23 hours long in New York, so the day must end at+// the next local midnight rather than 24h after the first.+func TestGetDailyStats_dstSpringForwardDayIs23Hours(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ setUserTimezone(t, uid, "America/New_York")++ // 2026-03-08 is 23 hours long in New York: the day starts at 05:00 UTC (EST) and+ // ends at 04:00 UTC on the 9th (EDT), because the clocks jump at 02:00 local.+ //+ // The fixture that matters is the one in [04:00, 05:00) UTC on the 9th. That hour+ // is *outside* the real day but *inside* a naive start+24h window, so it is the+ // only entry that can tell the two apart. Without it this test passes whether+ // localDayRange uses AddDate(0, 0, 1) or Add(24 * time.Hour).+ insertFoodLogAt(t, uid, "Inside, 23:00 local on the 8th", 400, time.Date(2026, 3, 9, 3, 0, 0, 0, time.UTC))+ insertFoodLogAt(t, uid, "The 24th hour that does not exist", 900, time.Date(2026, 3, 9, 4, 30, 0, 0, time.UTC))++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/stats?date=2026-03-08", nil)+ th.GetDailyStats(c)+ if got := decodeResponse(t, w)["data"].(map[string]any)["total_calories"].(float64); got != 400 {+ t.Errorf("expected 400 — the 23h day ends at 04:00 UTC, so the 04:30 entry belongs to the 9th; got %v", got)+ }+}++// The mirror case: 2026-11-01 is 25 hours long in New York, so the day must not end+// an hour early. An entry in [04:00, 05:00) UTC on the 2nd is inside the real day and+// outside a naive start+24h window — the opposite failure from spring forward.+func TestGetDailyStats_dstFallBackDayIs25Hours(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ setUserTimezone(t, uid, "America/New_York")++ insertFoodLogAt(t, uid, "The 25th hour", 400, time.Date(2026, 11, 2, 4, 30, 0, 0, time.UTC))+ insertFoodLogAt(t, uid, "Next local day", 900, time.Date(2026, 11, 2, 5, 30, 0, 0, time.UTC))++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/stats?date=2026-11-01", nil)+ th.GetDailyStats(c)+ if got := decodeResponse(t, w)["data"].(map[string]any)["total_calories"].(float64); got != 400 {+ t.Errorf("expected 400 — the 25h day runs to 05:00 UTC on the 2nd; got %v", got)+ }+}++// The chart and the totals above it must agree about which day an entry is on —+// they now resolve it the same way, which is the point of having one mechanism.+func TestGetFoodHistory_agreesWithDailyTotals(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ setUserTimezone(t, uid, "America/New_York")++ // A fixed instant with a hard-coded expected day, rather than deriving the day+ // with the same zone lookup the endpoints use — that would let a wrong lookup+ // agree with itself. 01:00 UTC on Aug 8 is 21:00 on Aug 7 in New York.+ insertFoodLogAt(t, uid, "Late dinner", 700, time.Date(2026, 8, 8, 1, 0, 0, 0, time.UTC))+ const day = "2026-08-07"++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/stats?date="+day, nil)+ th.GetDailyStats(c)+ dailyCals := decodeResponse(t, w)["data"].(map[string]any)["total_calories"].(float64)+ if dailyCals != 700 {+ t.Fatalf("daily totals put the 21:00-local entry somewhere else: got %v for %s", dailyCals, day)+ }++ c, w = newContext(uid, http.MethodGet, "/api/v1/food/history?days=400", nil)+ th.GetFoodHistory(c)+ for _, p := range decodeResponse(t, w)["data"].([]any) {+ if pt := p.(map[string]any); pt["date"].(string) == day {+ if pt["calories"].(float64) != dailyCals {+ t.Errorf("history says %v for %s, daily totals say %v", pt["calories"], day, dailyCals)+ }+ return+ }+ }+ t.Errorf("history has no bucket for %s, but the daily total is %v", day, dailyCals)+}++func mustLoad(t *testing.T, name string) *time.Location {+ t.Helper()+ loc, err := ParseLocation(name)+ if err != nil {+ t.Fatalf("load %s: %v", name, err)+ }+ return loc+}++// An unloadable zone must be rejected at write time rather than silently making+// every later query fall back to UTC.+func TestUpdateSettings_rejectsUnknownTimezone(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ c, w := newContext(uid, http.MethodPatch, "/api/v1/settings", map[string]any{"timezone": "Mars/Olympus_Mons"})+ th.UpdateSettings(c)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for an unknown zone, got %d: %s", w.Code, w.Body.String())+ }+}++func TestUpdateSettings_acceptsIANAZoneAndPreservesOtherFields(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ c, w := newContext(uid, http.MethodPatch, "/api/v1/settings", map[string]any{"calorie_target": 2500})+ th.UpdateSettings(c)+ if w.Code != http.StatusOK {+ t.Fatalf("seed settings: %d %s", w.Code, w.Body.String())+ }++ c, w = newContext(uid, http.MethodPatch, "/api/v1/settings", map[string]any{"timezone": "Europe/Berlin"})+ th.UpdateSettings(c)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ data := decodeResponse(t, w)["data"].(map[string]any)+ if data["timezone"].(string) != "Europe/Berlin" {+ t.Errorf("expected stored zone, got %v", data["timezone"])+ }+ // The COALESCE merge must not let a timezone-only PATCH reset the target.+ if data["calorie_target"].(float64) != 2500 {+ t.Errorf("timezone-only update clobbered calorie_target: %v", data["calorie_target"])+ }+}++// Changing zones must NOT move an entry, at any distance.+//+// This is the inverse of the test it replaces. While the day was derived from the+// account's zone at read time, a New York entry read from Tokyo — 13 hours away —+// landed on the following day, because a noon anchor only absorbs a shift while+// |offset delta| < 12. Now the day is stored on the row, so no distance is far+// enough. Tokyo is kept as a case precisely because it is the one that used to fail.+func TestListFoodLogs_zoneChangeDoesNotMoveStoredDay(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ setUserTimezone(t, uid, "America/New_York")+ // Local noon on the 4th for a New York account (UTC-4 in August).+ insertFoodLogAt(t, uid, "Lunch", 600, time.Date(2026, 8, 4, 16, 0, 0, 0, time.UTC))++ countOn := func(zone, date string) int {+ t.Helper()+ setUserTimezone(t, uid, zone)+ c, w := newContext(uid, http.MethodGet, "/api/v1/food?date="+date, nil)+ th.ListFoodLogs(c)+ if w.Code != http.StatusOK {+ t.Fatalf("%s %s: expected 200, got %d: %s", zone, date, w.Code, w.Body.String())+ }+ return len(decodeResponse(t, w)["data"].([]any))+ }++ for _, tc := range []struct {+ zone, date string+ want int+ why string+ }{+ {"America/New_York", "2026-08-04", 1, "the day it was filed under"},+ {"Pacific/Honolulu", "2026-08-04", 1, "6h away, still the 4th"},+ {"Pacific/Honolulu", "2026-08-05", 0, "and not also on the 5th"},+ {"Asia/Tokyo", "2026-08-04", 1, "13h away — this is the case that used to move"},+ {"Asia/Tokyo", "2026-08-05", 0, "it must not appear on the 5th any more"},+ {"Pacific/Kiritimati", "2026-08-04", 1, "UTC+14, the widest gap there is"},+ } {+ if got := countOn(tc.zone, tc.date); got != tc.want {+ t.Errorf("%s on %s: got %d entries, want %d (%s)", tc.zone, tc.date, got, tc.want, tc.why)+ }+ }+}diff --git a/backend/controllers/testhelper_test.go b/backend/controllers/testhelper_test.goindex 670ec9f..da787a4 100644--- a/backend/controllers/testhelper_test.go+++ b/backend/controllers/testhelper_test.go@@ -41,141 +41,8 @@ func setupTestDB(t *testing.T) {}func applySchema() error {- schema := `-CREATE TABLE IF NOT EXISTS users (- id INTEGER PRIMARY KEY AUTOINCREMENT,- email TEXT NOT NULL UNIQUE,- password_hash TEXT NOT NULL,- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP-);-CREATE TABLE IF NOT EXISTS user_settings (- user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,- weight_unit TEXT NOT NULL DEFAULT 'lbs',- calorie_target INTEGER NOT NULL DEFAULT 2000,- protein_target INTEGER NOT NULL DEFAULT 150,- carb_target INTEGER NOT NULL DEFAULT 250,- fat_target INTEGER NOT NULL DEFAULT 65-);-CREATE TABLE IF NOT EXISTS exercises (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NOT NULL,- muscle_group TEXT NOT NULL DEFAULT '',- secondary_muscles TEXT NOT NULL DEFAULT '[]',- category TEXT NOT NULL DEFAULT 'strength',- equipment TEXT NOT NULL DEFAULT '',- description TEXT NOT NULL DEFAULT '',- image_url TEXT NOT NULL DEFAULT '',- video_url TEXT NOT NULL DEFAULT ''-);-CREATE UNIQUE INDEX IF NOT EXISTS idx_exercises_name ON exercises(name);-CREATE TABLE IF NOT EXISTS workouts (- id INTEGER PRIMARY KEY AUTOINCREMENT,- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,- name TEXT NOT NULL,- notes TEXT NOT NULL DEFAULT '',- duration INTEGER NOT NULL DEFAULT 0,- started_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- program_id INTEGER,- program_day_id INTEGER REFERENCES program_days(id) ON DELETE SET NULL,- program_day_dropped INTEGER NOT NULL DEFAULT 0-);-CREATE INDEX IF NOT EXISTS idx_workouts_program ON workouts(program_id);-CREATE INDEX IF NOT EXISTS idx_workouts_program_day ON workouts(program_day_id);-CREATE TABLE IF NOT EXISTS workout_exercises (- id INTEGER PRIMARY KEY AUTOINCREMENT,- workout_id INTEGER NOT NULL REFERENCES workouts(id) ON DELETE CASCADE,- exercise_id INTEGER NOT NULL REFERENCES exercises(id),- order_index INTEGER NOT NULL DEFAULT 0,- notes TEXT NOT NULL DEFAULT '',- rest_seconds INTEGER NOT NULL DEFAULT 90-);-CREATE TABLE IF NOT EXISTS sets (- id INTEGER PRIMARY KEY AUTOINCREMENT,- workout_exercise_id INTEGER NOT NULL REFERENCES workout_exercises(id) ON DELETE CASCADE,- set_number INTEGER NOT NULL DEFAULT 1,- reps INTEGER NOT NULL DEFAULT 0,- weight REAL NOT NULL DEFAULT 0,- duration INTEGER NOT NULL DEFAULT 0,- distance REAL NOT NULL DEFAULT 0,- rpe REAL NOT NULL DEFAULT 0,- is_warmup INTEGER NOT NULL DEFAULT 0-);-CREATE TABLE IF NOT EXISTS programs (- id INTEGER PRIMARY KEY AUTOINCREMENT,- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,- name TEXT NOT NULL,- notes TEXT NOT NULL DEFAULT '',- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP-);-CREATE TABLE IF NOT EXISTS program_days (- id INTEGER PRIMARY KEY AUTOINCREMENT,- program_id INTEGER NOT NULL REFERENCES programs(id) ON DELETE CASCADE,- order_index INTEGER NOT NULL DEFAULT 0,- is_rest_day INTEGER NOT NULL DEFAULT 0,- name TEXT NOT NULL DEFAULT ''-);-CREATE TABLE IF NOT EXISTS program_exercises (- id INTEGER PRIMARY KEY AUTOINCREMENT,- program_id INTEGER NOT NULL REFERENCES programs(id) ON DELETE CASCADE,- program_day_id INTEGER REFERENCES program_days(id) ON DELETE CASCADE,- exercise_id INTEGER NOT NULL REFERENCES exercises(id),- order_index INTEGER NOT NULL DEFAULT 0,- notes TEXT NOT NULL DEFAULT '',- rest_seconds INTEGER NOT NULL DEFAULT 90-);-CREATE TABLE IF NOT EXISTS program_sets (- id INTEGER PRIMARY KEY AUTOINCREMENT,- program_exercise_id INTEGER NOT NULL REFERENCES program_exercises(id) ON DELETE CASCADE,- set_number INTEGER NOT NULL DEFAULT 1,- target_reps INTEGER NOT NULL DEFAULT 0,- target_weight REAL NOT NULL DEFAULT 0,- suggested_weight REAL,- suggested_reps INTEGER,- suggested_is_pr INTEGER NOT NULL DEFAULT 0-);-CREATE TABLE IF NOT EXISTS weight_logs (- id INTEGER PRIMARY KEY AUTOINCREMENT,- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,- weight REAL NOT NULL,- notes TEXT NOT NULL DEFAULT '',- logged_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP-);-CREATE TABLE IF NOT EXISTS food_logs (- id INTEGER PRIMARY KEY AUTOINCREMENT,- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,- name TEXT NOT NULL,- meal TEXT NOT NULL DEFAULT 'snacks',- calories REAL NOT NULL DEFAULT 0,- protein REAL NOT NULL DEFAULT 0,- carbs REAL NOT NULL DEFAULT 0,- fat REAL NOT NULL DEFAULT 0,- fiber REAL NOT NULL DEFAULT 0,- servings REAL NOT NULL DEFAULT 1,- serving_size TEXT NOT NULL DEFAULT '',- barcode TEXT NOT NULL DEFAULT '',- image_url TEXT NOT NULL DEFAULT '',- logged_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP-);-CREATE TABLE IF NOT EXISTS saved_foods (- id INTEGER PRIMARY KEY AUTOINCREMENT,- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,- name TEXT NOT NULL,- brand TEXT NOT NULL DEFAULT '',- calories REAL NOT NULL DEFAULT 0,- protein REAL NOT NULL DEFAULT 0,- carbs REAL NOT NULL DEFAULT 0,- fat REAL NOT NULL DEFAULT 0,- fiber REAL NOT NULL DEFAULT 0,- serving_size TEXT NOT NULL DEFAULT '',- barcode TEXT NOT NULL DEFAULT '',- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP-);`- _, err := db.DB.Exec(schema)- return err+ // The real migrations, not a copy of them — see db.BuildSchema.+ return db.BuildSchema()}func createTestUser(t *testing.T) int64 {diff --git a/backend/controllers/timezone.go b/backend/controllers/timezone.gonew file mode 100644index 0000000..0021440--- /dev/null+++ b/backend/controllers/timezone.go@@ -0,0 +1,98 @@+package controllers++import (+ "time"++ // Embeds the IANA tz database in the binary. The production image is+ // golang:1.26-alpine, which ships no /usr/share/zoneinfo, so without this+ // time.LoadLocation would fail for every real zone and silently fall back to+ // UTC — the exact bug this feature exists to fix, in a form no test on a+ // developer machine (which does have zoneinfo) would ever reproduce.+ _ "time/tzdata"+)++// ParseLocation resolves an IANA zone name ("America/New_York") to a Location.+//+// Validation is deliberately "can the runtime load it" rather than a pattern+// match: the tz database is the only authority on what names exist, and it+// changes (zones are added, renamed, and merged between releases). An empty name+// means "not set" and resolves to UTC, which is what every row written before+// this feature was bucketed under.+func ParseLocation(name string) (*time.Location, error) {+ if name == "" {+ return time.UTC, nil+ }+ return time.LoadLocation(name)+}++// userLocation is the caller's stored zone, falling back to UTC.+//+// Read failures fall back rather than erroring: a missing settings row is normal+// for a new account, and a zone that no longer exists in a newer tz database+// shouldn't make the food diary return 500. Both cases degrade to the pre-feature+// behaviour instead of breaking the request.+//+// The zone is no longer what decides which day an entry belongs to — each row+// records that itself (food_logs/weight_logs.logged_on, workouts.tz_offset_minutes),+// so history does not move when the account's zone changes. What remains here are+// the two questions a stored day genuinely cannot answer:+//+// 1. "What is today?" — for a read with no date parameter.+// 2. "What day is this?" — for a write from a client too old to send one.+//+// Both are questions about *now*, where the current zone is the right answer.+func (h *Handler) userLocation(uid int64) *time.Location {+ st, err := h.s.User.GetSettings(uid)+ if err != nil {+ return time.UTC+ }+ loc, err := ParseLocation(st.Timezone)+ if err != nil {+ return time.UTC+ }+ return loc+}++// resolveDay is the single place a write decides which calendar day an entry belongs+// to. Every create/update path goes through it, so there is one rule rather than one+// per handler.+//+// A client-supplied day wins. The device knows its own zone with certainty; the+// account zone is a cached copy that may not have synced yet, so preferring it would+// mean a user who just crossed a border files entries under the day they left. When+// no day is sent — every already-installed client — it falls back to deriving one+// from the account zone, which is exactly what the server did before this column+// existed. That fallback is what keeps old clients correct rather than blank.+func (h *Handler) resolveDay(uid int64, supplied string, instant time.Time) (string, bool) {+ if supplied != "" {+ if _, err := time.Parse("2006-01-02", supplied); err != nil {+ return "", false+ }+ return supplied, true+ }+ return instant.In(h.userLocation(uid)).Format("2006-01-02"), true+}++// resolveQueryDay picks the day a read is asking about: the supplied YYYY-MM-DD, or+// today in the user's zone when the parameter is omitted. "Today" is the one question+// that still needs a zone after this change — a stored day cannot tell you which day+// is the current one.+func (h *Handler) resolveQueryDay(uid int64, supplied string) (string, bool) {+ if supplied == "" {+ return time.Now().In(h.userLocation(uid)).Format("2006-01-02"), true+ }+ if _, err := time.Parse("2006-01-02", supplied); err != nil {+ return "", false+ }+ return supplied, true+}++// tzOffsetMinutes is the user's UTC offset at a given instant, for stamping onto a+// workout. Resolved through the zone at that instant rather than a fixed number, so+// a summer workout gets the summer offset.+func (h *Handler) tzOffsetMinutes(uid int64, instant time.Time) int {+ _, seconds := instant.In(h.userLocation(uid)).Zone()+ return seconds / 60+}++diff --git a/backend/controllers/user.go b/backend/controllers/user.goindex d80de6f..a0099c3 100644--- a/backend/controllers/user.go+++ b/backend/controllers/user.go@@ -50,10 +50,30 @@ func (h *Handler) UpdateSettings(c *gin.Context) {utils.BadRequest(c, err.Error())return}+ // A zone name is only valid if the runtime can load it, so check it here rather+ // than with a struct tag. Storing an unloadable name would be quietly corrosive:+ // every later food query falls back to UTC, so the diary would look subtly wrong+ // with nothing pointing at the cause.+ if req.Timezone != nil {+ // Explicitly reject "", which ParseLocation accepts as "not set" for reads.+ // Sending it here means overwriting a correctly detected zone with a value+ // that silently reverts every day boundary to UTC — a 200 OK, a stored value+ // that is neither null nor rejected, and nothing to point at afterwards.+ if *req.Timezone == "" {+ utils.BadRequest(c, "timezone cannot be empty")+ return+ }+ if _, err := ParseLocation(*req.Timezone); err != nil {+ utils.BadRequest(c, "unknown timezone: "+*req.Timezone)+ return+ }+ }+s, err := h.s.User.UpsertSettings(uid, req)if utils.DBError(c, err) {return}+utils.OK(c, s)}diff --git a/backend/controllers/weight.go b/backend/controllers/weight.goindex de4476a..943806a 100644--- a/backend/controllers/weight.go+++ b/backend/controllers/weight.go@@ -22,25 +22,28 @@ func (h *Handler) ListWeightLogs(c *gin.Context) {f.Offset = o}- // Date params are calendar days in the user's local timezone. We don't know- // the client's UTC offset, so for bare YYYY-MM-DD we widen the window by ±12h- // to cover any plausible client TZ. A full RFC3339 timestamp is used exactly.+ // Two kinds of bound, matching the two kinds of question. A bare YYYY-MM-DD asks+ // about the user's calendar and compares against the day stored on the row — no+ // zone, no conversion, nothing that can move later. A full RFC3339 timestamp asks+ // about instants and still compares against logged_at.if from := c.Query("from"); from != "" {if t, exact, ok := parseDayOrTime(from); ok {- lo := t- if !exact {- lo = t.Add(-12 * time.Hour)+ if exact {+ f.From = &t+ } else {+ day := t.Format("2006-01-02")+ f.FromDay = &day}- f.From = &lo}}if to := c.Query("to"); to != "" {if t, exact, ok := parseDayOrTime(to); ok {- hi := t- if !exact {- hi = t.Add(36 * time.Hour)+ if exact {+ f.To = &t+ } else {+ day := t.Format("2006-01-02")+ f.ToDay = &day}- f.To = &hi}}@@ -64,7 +67,12 @@ func (h *Handler) LogWeight(c *gin.Context) {}req.LoggedAt = normalizeLoggedAt(req.LoggedAt)- log, err := h.s.Weight.UpsertForDay(uid, req)+ day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)+ if !ok {+ utils.BadRequest(c, "logged_on must be YYYY-MM-DD")+ return+ }+ log, err := h.s.Weight.UpsertForDay(uid, req, day)if utils.DBError(c, err) {return}@@ -107,7 +115,12 @@ func (h *Handler) UpdateWeightLog(c *gin.Context) {}req.LoggedAt = normalizeLoggedAt(req.LoggedAt)- log, err := h.s.Weight.Update(uid, lid, req)+ day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)+ if !ok {+ utils.BadRequest(c, "logged_on must be YYYY-MM-DD")+ return+ }+ log, err := h.s.Weight.Update(uid, lid, req, day)if err == sql.ErrNoRows {utils.NotFound(c, "log entry not found")returndiff --git a/backend/controllers/weight_test.go b/backend/controllers/weight_test.goindex 8b7d03f..fbdfa79 100644--- a/backend/controllers/weight_test.go+++ b/backend/controllers/weight_test.go@@ -3,17 +3,19 @@ package controllersimport ("fmt""net/http"+ "strconv""testing""time""github.com/Cawlumm/lyftr-backend/db"+ "github.com/gin-gonic/gin")func insertWeightLog(t *testing.T, uid int64, weight float64, loggedAt time.Time) int64 {t.Helper()res, err := db.DB.Exec(- `INSERT INTO weight_logs (user_id, weight, notes, logged_at) VALUES (?, ?, '', ?)`,- uid, weight, loggedAt,+ `INSERT INTO weight_logs (user_id, weight, notes, logged_at, logged_on) VALUES (?, ?, '', ?, ?)`,+ uid, weight, loggedAt, localDayFor(t, uid, loggedAt),)if err != nil {t.Fatalf("insert weight log: %v", err)@@ -45,7 +47,7 @@ func TestListWeightLogs_orderedDescAndScopedByUser(t *testing.T) {other, _ := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, "[email protected]", "x")otherUID, _ := other.LastInsertId()- now := time.Now()+ now := time.Now().UTC()insertWeightLog(t, uid, 180.0, now.AddDate(0, 0, -2))insertWeightLog(t, uid, 181.5, now.AddDate(0, 0, -1))insertWeightLog(t, uid, 179.0, now)@@ -119,7 +121,7 @@ func TestGetWeightStats_latestPrefersNewestSameDay(t *testing.T) {func TestListWeightLogs_dateRange(t *testing.T) {setupTestDB(t)uid := createTestUser(t)- now := time.Now()+ now := time.Now().UTC()insertWeightLog(t, uid, 180.0, now.AddDate(0, 0, -10))insertWeightLog(t, uid, 181.0, now.AddDate(0, 0, -5))insertWeightLog(t, uid, 182.0, now)@@ -416,7 +418,7 @@ func TestDeleteWeightLog_ownershipEnforced(t *testing.T) {func TestGetWeightStats_richFields(t *testing.T) {setupTestDB(t)uid := createTestUser(t)- now := time.Now()+ now := time.Now().UTC()insertWeightLog(t, uid, 180.0, now.AddDate(0, 0, -40))insertWeightLog(t, uid, 178.0, now.AddDate(0, 0, -20))insertWeightLog(t, uid, 176.0, now.AddDate(0, 0, -5))@@ -475,3 +477,147 @@ func TestGetWeightStats_noData(t *testing.T) {t.Errorf("expected change_7d=0 with no data, got %v", data["change_7d"])}}++// Regression: moving an entry's date must move that entry and leave the day it+// moves onto intact. The one-entry-per-day rule is evaluated over the user's local+// day, so both halves are asserted — either alone would pass a broken version.+func TestUpdateWeightLog_movingTheDayDoesNotDeleteTheTargetDaysEntry(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ setUserTimezone(t, uid, "America/New_York")++ // Local noon on each day, the anchor every client writes.+ c, w := newContext(uid, http.MethodPost, "/api/v1/weight", map[string]any{+ "weight": 200, "logged_at": "2026-08-05T16:00:00Z",+ })+ th.LogWeight(c)+ if w.Code != http.StatusCreated {+ t.Fatalf("seed Aug 5: %d %s", w.Code, w.Body.String())+ }+ movedID := int64(decodeResponse(t, w)["data"].(map[string]any)["id"].(float64))++ c, w = newContext(uid, http.MethodPost, "/api/v1/weight", map[string]any{+ "weight": 201, "logged_at": "2026-08-06T16:00:00Z",+ })+ th.LogWeight(c)+ if w.Code != http.StatusCreated {+ t.Fatalf("seed Aug 6: %d %s", w.Code, w.Body.String())+ }++ // Move the Aug 5 entry onto Aug 6, the way the edit form does.+ c, w = newContext(uid, http.MethodPatch, "/api/v1/weight/"+strconv.FormatInt(movedID, 10),+ map[string]any{"weight": 200, "logged_at": "2026-08-06T16:00:00Z"})+ c.Params = gin.Params{{Key: "id", Value: strconv.FormatInt(movedID, 10)}}+ th.UpdateWeightLog(c)+ if w.Code != http.StatusOK {+ t.Fatalf("update: %d %s", w.Code, w.Body.String())+ }++ // Bounds are hard-coded, not re-derived through localDayRange. Verifying with the+ // function under test means a wrong day window agrees with itself and the test+ // passes anyway. New York in August is UTC-4, so the local day runs 04:00 UTC to+ // 04:00 UTC the next morning.+ // Bound as time.Time, not as strings: the driver encodes a DATETIME column its+ // own way, and a string literal doesn't compare against it — the same trap that+ // made these range queries silently match nothing earlier in this branch.+ countBetween := func(fromUTC, toUTC string) int {+ t.Helper()+ from, err := time.Parse(time.RFC3339, fromUTC)+ if err != nil {+ t.Fatal(err)+ }+ to, err := time.Parse(time.RFC3339, toUTC)+ if err != nil {+ t.Fatal(err)+ }+ var n int+ if err := db.DB.QueryRow(+ `SELECT COUNT(*) FROM weight_logs WHERE user_id = ? AND logged_at >= ? AND logged_at < ?`,+ uid, from, to,+ ).Scan(&n); err != nil {+ t.Fatal(err)+ }+ return n+ }++ if n := countBetween("2026-08-06T04:00:00Z", "2026-08-07T04:00:00Z"); n != 1 {+ t.Errorf("expected exactly one entry on the target day, got %d", n)+ }+ if n := countBetween("2026-08-05T04:00:00Z", "2026-08-06T04:00:00Z"); n != 0 {+ t.Errorf("expected nothing left on the old day, got %d", n)+ }+}+++// The bare-day from/to filter resolves through the user's stored zone now that the+// -12h/+36h widening is gone. TestListWeightLogs_dateRange covers the UTC default;+// this covers a real zone, where a device-derived day and a UTC day disagree.+func TestListWeightLogs_bareDayRangeUsesStoredTimezone(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ setUserTimezone(t, uid, "Pacific/Auckland") // UTC+12/+13++ // 2026-04-24 local noon in Auckland is 2026-04-24T00:00:00Z. A UTC-bucketed+ // filter for the 24th would still include it, so the discriminating entry is the+ // one at 23:00Z on the 23rd — local 11:00 on the 24th.+ insertWeightLog(t, uid, 180.0, time.Date(2026, 4, 23, 23, 0, 0, 0, time.UTC))+ // Local 11:00 on the 25th — outside the requested day either way.+ insertWeightLog(t, uid, 181.0, time.Date(2026, 4, 24, 23, 0, 0, 0, time.UTC))++ c, w := newContext(uid, http.MethodGet, "/api/v1/weight?from=2026-04-24&to=2026-04-24", nil)+ th.ListWeightLogs(c)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ data := decodeResponse(t, w)["data"].([]any)+ if len(data) != 1 {+ t.Fatalf("expected the entry on the user's local 24th, got %d", len(data))+ }+ if got := data[0].(map[string]any)["weight"].(float64); got != 180.0 {+ t.Errorf("expected the 11:00-local entry (180), got %v", got)+ }+}++// One-entry-per-day on the CREATE path. The update path is covered above; this is+// UpsertForDay's dedup, which replaced dayBounds' UTC window with zone-resolved+// bounds and had no test over a non-UTC day.+func TestLogWeight_oneEntryPerLocalDayOnCreate(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ setUserTimezone(t, uid, "America/New_York")++ // Both are the same New York day (Aug 7): 20:00 local and 23:00 local. They are+ // also the same UTC day, so this alone wouldn't discriminate — the second pair+ // below does.+ for _, at := range []string{"2026-08-08T00:00:00Z", "2026-08-08T03:00:00Z"} {+ c, w := newContext(uid, http.MethodPost, "/api/v1/weight", map[string]any{"weight": 200, "logged_at": at})+ th.LogWeight(c)+ if w.Code != http.StatusCreated {+ t.Fatalf("log at %s: %d %s", at, w.Code, w.Body.String())+ }+ }++ var n int+ if err := db.DB.QueryRow(`SELECT COUNT(*) FROM weight_logs WHERE user_id = ?`, uid).Scan(&n); err != nil {+ t.Fatal(err)+ }+ if n != 1 {+ t.Fatalf("both entries are on the user's Aug 7; expected one row, got %d", n)+ }++ // A different local day that shares a UTC day with the first: 2026-08-07T20:00Z+ // is Aug 7 in UTC but 16:00 on Aug 7 local... and 2026-08-08T00:00Z (already+ // logged) is Aug 8 in UTC. A UTC-bucketed dedup would treat these as different+ // days and leave two rows; the local-day rule collapses them.+ c, w := newContext(uid, http.MethodPost, "/api/v1/weight", map[string]any{"weight": 202, "logged_at": "2026-08-07T20:00:00Z"})+ th.LogWeight(c)+ if w.Code != http.StatusCreated {+ t.Fatalf("log the same local day from a different UTC day: %d %s", w.Code, w.Body.String())+ }+ if err := db.DB.QueryRow(`SELECT COUNT(*) FROM weight_logs WHERE user_id = ?`, uid).Scan(&n); err != nil {+ t.Fatal(err)+ }+ if n != 1 {+ t.Errorf("all three instants fall on the user's Aug 7; expected one row, got %d", n)+ }+}diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.goindex 1d1d523..9e3566e 100644--- a/backend/controllers/workouts.go+++ b/backend/controllers/workouts.go@@ -82,6 +82,14 @@ func (h *Handler) CreateWorkout(c *gin.Context) {// (ProgramStore.currentDayIndex). normalizeLoggedAt both defaults a zero time// to now and forces UTC, same as weight logs.req.StartedAt = normalizeLoggedAt(req.StartedAt)+ // Record where the workout happened, not just when. The client sends its own+ // offset; older clients send none, so fall back to the account zone at that+ // instant. Either way the row can name its own local day forever without asking+ // what zone the account is set to today.+ if req.TZOffsetMinutes == nil {+ off := h.tzOffsetMinutes(uid, req.StartedAt)+ req.TZOffsetMinutes = &off+ }// Snapshot, insert, and stage routine target suggestions in one transaction (issue// #40) — closes a TOCTOU race where two concurrent submissions could both read the// same stale prior best. Staging is still best-effort internally: a failure therediff --git a/backend/db/migrations.go b/backend/db/migrations.goindex fbca86d..a8e85f0 100644--- a/backend/db/migrations.go+++ b/backend/db/migrations.go@@ -2,9 +2,15 @@ package dbimport ("database/sql"+ "fmt""log""strings""time"++ // The backfill resolves stored zones, and the production image (alpine) ships no+ // /usr/share/zoneinfo. controllers blank-imports this too; both are needed, since+ // relying on another package's import would break silently if that one moved.+ _ "time/tzdata")func migrate() error {@@ -70,9 +76,208 @@ func alterMigrations() {ensureColumn("workouts", "program_id", `ALTER TABLE workouts ADD COLUMN program_id INTEGER`)ensureIndex("idx_workouts_program", `CREATE INDEX IF NOT EXISTS idx_workouts_program ON workouts(program_id)`)+ // The zone the server buckets this user's day-scoped data in. Defaults to UTC,+ // which is exactly the behaviour every existing row was written under, so this+ // column changes nothing until a client reports a real zone.+ ensureColumn("user_settings", "timezone", `ALTER TABLE user_settings ADD COLUMN timezone TEXT NOT NULL DEFAULT 'UTC'`)+workoutProgramDayMigration()normalizeWorkoutStartedAt()+ normalizeFoodLoggedAt()++ // The day a diary entry belongs to, and the offset a workout started at, stored+ // ON THE ROW instead of derived from the account's current zone at read time.+ //+ // This is the split Fitbit and wger arrived at independently. Fitbit's food log+ // entry is `logDate: "2019-03-21"` with no time component at all, and its weight+ // entry carries separate local `date` and `time`; its *activity* keeps a real+ // instant with the offset inline (`2019-01-03T12:08:29.000-08:00`). wger stores+ // WorkoutSession.date as a plain DateField while its log rows stay timestamps.+ //+ // Why a date for the diary but an offset for the workout, rather than one shape+ // for both: a back-dated meal has no real instant — we invent local noon for it —+ // so an offset on that invented instant would be invented too. The date is the+ // honest primitive there. A workout genuinely happened at a moment, and duration+ // and ordering depend on that moment, so it keeps the instant and gains the+ // offset that makes its local day recoverable forever.+ //+ // These run AFTER the normalize* calls above: the backfill derives days from+ // logged_at/started_at, so those must already be UTC or the derived day inherits+ // the stale zone.+ ensureColumn("food_logs", "logged_on", `ALTER TABLE food_logs ADD COLUMN logged_on TEXT NOT NULL DEFAULT ''`)+ ensureColumn("weight_logs", "logged_on", `ALTER TABLE weight_logs ADD COLUMN logged_on TEXT NOT NULL DEFAULT ''`)+ ensureColumn("workouts", "tz_offset_minutes", `ALTER TABLE workouts ADD COLUMN tz_offset_minutes INTEGER`)+ ensureIndex("idx_food_logs_user_day", `CREATE INDEX IF NOT EXISTS idx_food_logs_user_day ON food_logs(user_id, logged_on)`)+ ensureIndex("idx_weight_logs_user_day", `CREATE INDEX IF NOT EXISTS idx_weight_logs_user_day ON weight_logs(user_id, logged_on)`)+ backfillLocalDays()+}++// backfillLocalDays fills the stored day/offset for rows written before those+// columns existed.+//+// Deliberately behaviour-preserving: it derives each row's day with exactly the rule+// the read path used before this change — the instant, resolved in that user's stored+// zone. So upgrading an existing server moves nothing. What changes is that the answer+// is now frozen on the row instead of recomputed against a zone that can change.+//+// That also means the backfill inherits whatever the account zone says today. For a+// user who already travelled before upgrading, their old entries are pinned to the+// day their *current* zone implies, which may not be the day they lived through. That+// is not recoverable — the write-time zone was never stored, which is the whole reason+// for this change — and it is strictly no worse than the derive-every-time behaviour+// it replaces.+func backfillLocalDays() {+ done, err := hasMigrationFlag("backfill_local_days")+ if err != nil {+ log.Printf("backfillLocalDays: check flag: %v (skipping this boot)", err)+ return+ }+ if done {+ return+ }+ locs := map[string]*time.Location{}+ loadLoc := func(name string) *time.Location {+ if l, ok := locs[name]; ok {+ return l+ }+ l, err := time.LoadLocation(name)+ if err != nil {+ log.Printf("backfillLocalDays: unknown zone %q, using UTC for those rows", name)+ l = time.UTC+ }+ locs[name] = l+ return l+ }++ for _, t := range []struct{ table, column string }{+ {"food_logs", "logged_at"},+ {"weight_logs", "logged_at"},+ } {+ if err := backfillDayColumn(t.table, t.column, loadLoc); err != nil {+ log.Printf("backfillLocalDays(%s): %v (skipping this boot, will retry)", t.table, err)+ return+ }+ }+ if err := backfillWorkoutOffsets(loadLoc); err != nil {+ log.Printf("backfillLocalDays(workouts): %v (skipping this boot, will retry)", err)+ return+ }+ setMigrationFlag("backfill_local_days")+}++// backfillDayColumn sets table.logged_on from table.<column> resolved in the owning+// user's zone. Users with no settings row fall back to UTC, matching userLocation.+func backfillDayColumn(table, column string, loadLoc func(string) *time.Location) error {+ rows, err := DB.Query(fmt.Sprintf(`+ SELECT t.id, t.%[2]s, COALESCE(s.timezone, 'UTC')+ FROM %[1]s t LEFT JOIN user_settings s ON s.user_id = t.user_id+ WHERE t.logged_on = ''`, table, column))+ if err != nil {+ return err+ }+ type fix struct {+ id int64+ day string+ }+ var fixes []fix+ for rows.Next() {+ var id int64+ var at time.Time+ var zone string+ if err := rows.Scan(&id, &at, &zone); err != nil {+ rows.Close()+ return err+ }+ fixes = append(fixes, fix{id, at.In(loadLoc(zone)).Format("2006-01-02")})+ }+ rows.Close()+ if err := rows.Err(); err != nil {+ return err+ }+ if len(fixes) == 0 {+ return nil+ }+ tx, err := DB.Begin()+ if err != nil {+ return err+ }+ stmt, err := tx.Prepare(fmt.Sprintf(`UPDATE %s SET logged_on = ? WHERE id = ?`, table))+ if err != nil {+ tx.Rollback()+ return err+ }+ for _, f := range fixes {+ if _, err := stmt.Exec(f.day, f.id); err != nil {+ stmt.Close()+ tx.Rollback()+ return err+ }+ }+ stmt.Close()+ if err := tx.Commit(); err != nil {+ return err+ }+ log.Printf("migration: backfilled %s.logged_on for %d rows", table, len(fixes))+ return nil+}++// backfillWorkoutOffsets sets workouts.tz_offset_minutes from the owning user's zone+// at that workout's instant — .Zone() rather than a fixed offset, so a workout logged+// in July gets the summer offset and one logged in January gets the winter one.+func backfillWorkoutOffsets(loadLoc func(string) *time.Location) error {+ rows, err := DB.Query(`+ SELECT w.id, w.started_at, COALESCE(s.timezone, 'UTC')+ FROM workouts w LEFT JOIN user_settings s ON s.user_id = w.user_id+ WHERE w.tz_offset_minutes IS NULL`)+ if err != nil {+ return err+ }+ type fix struct {+ id int64+ minutes int+ }+ var fixes []fix+ for rows.Next() {+ var id int64+ var at time.Time+ var zone string+ if err := rows.Scan(&id, &at, &zone); err != nil {+ rows.Close()+ return err+ }+ _, offsetSeconds := at.In(loadLoc(zone)).Zone()+ fixes = append(fixes, fix{id, offsetSeconds / 60})+ }+ rows.Close()+ if err := rows.Err(); err != nil {+ return err+ }+ if len(fixes) == 0 {+ return nil+ }+ tx, err := DB.Begin()+ if err != nil {+ return err+ }+ stmt, err := tx.Prepare(`UPDATE workouts SET tz_offset_minutes = ? WHERE id = ?`)+ if err != nil {+ tx.Rollback()+ return err+ }+ for _, f := range fixes {+ if _, err := stmt.Exec(f.minutes, f.id); err != nil {+ stmt.Close()+ tx.Rollback()+ return err+ }+ }+ stmt.Close()+ if err := tx.Commit(); err != nil {+ return err+ }+ log.Printf("migration: backfilled workouts.tz_offset_minutes for %d rows", len(fixes))+ return nil}// normalizeWorkoutStartedAt rewrites any workouts.started_at stored with a non-UTC@@ -82,9 +287,19 @@ func alterMigrations() {// zone — so a row written before the controllers' write-side UTC normalization// (e.g. a third-party API client sending '+08:00') compares by wall-clock text, not// instant, and could permanently win or lose the most-recent-anchor lookup against-// newer UTC rows. Normalizing here also repairs reads: a fixed-offset zone with no-// name is stored as its offset twice ('… +0800 +0800'), which the driver can't-// parse back into a time.Time at all. The WHERE matches only offset-bearing+// newer UTC rows.+func normalizeWorkoutStartedAt() {+ normalizeUTCTimestamps("normalize_workout_started_at", "workouts", "started_at")+}++func normalizeFoodLoggedAt() {+ normalizeUTCTimestamps("normalize_food_logged_at", "food_logs", "logged_at")+}++// normalizeUTCTimestamps rewrites any table.column value stored with a non-UTC zone+// offset to its UTC equivalent. Normalizing also repairs reads: a fixed-offset zone+// with no name is stored as its offset twice ('… +0800 +0800'), which the driver+// can't parse back into a time.Time at all. The WHERE matches only offset-bearing// non-UTC rows, so this is idempotent and a no-op on every boot after the first;// a row whose text can't be parsed is logged and left as-is (retried next boot).//@@ -95,21 +310,21 @@ func alterMigrations() {// flag is deliberately keyed off the MATCH count, not len(fixes): a boot can match// rows yet fix none of them (all unparseable), and flagging done there would break// the retry-next-boot this function promises above.-func normalizeWorkoutStartedAt() {- done, err := hasMigrationFlag("normalize_workout_started_at")+func normalizeUTCTimestamps(flag, table, column string) {+ done, err := hasMigrationFlag(flag)if err != nil {- log.Printf("normalizeWorkoutStartedAt: check flag: %v (skipping this boot)", err)+ log.Printf("normalizeUTCTimestamps(%s.%s): check flag: %v (skipping this boot)", table, column, err)return}if done {return}- rows, err := DB.Query(`- SELECT id, started_at FROM workouts- WHERE (started_at LIKE '% +%' OR started_at LIKE '% -%')- AND started_at NOT LIKE '%+0000%'`)+ rows, err := DB.Query(fmt.Sprintf(`+ SELECT id, %[2]s FROM %[1]s+ WHERE (%[2]s LIKE '%% +%%' OR %[2]s LIKE '%% -%%')+ AND %[2]s NOT LIKE '%%+0000%%'`, table, column))if err != nil {- log.Printf("normalizeWorkoutStartedAt: query: %v (skipping this boot)", err)+ log.Printf("normalizeUTCTimestamps(%s.%s): query: %v (skipping this boot)", table, column, err)return}type fix struct {@@ -124,7 +339,7 @@ func normalizeWorkoutStartedAt() {var v anyif err := rows.Scan(&id, &v); err != nil {rows.Close()- log.Printf("normalizeWorkoutStartedAt: scan: %v (skipping this boot)", err)+ log.Printf("normalizeUTCTimestamps(%s.%s): scan: %v (skipping this boot)", table, column, err)return}switch tv := v.(type) {@@ -134,29 +349,29 @@ func normalizeWorkoutStartedAt() {if t, ok := parseStoredTime(tv); ok {fixes = append(fixes, fix{id, t.UTC()})} else {- log.Printf("normalizeWorkoutStartedAt: workout %d: unparseable started_at %q left as-is", id, tv)+ log.Printf("normalizeUTCTimestamps(%s.%s): row %d: unparseable value %q left as-is", table, column, id, tv)}default:- log.Printf("normalizeWorkoutStartedAt: workout %d: unexpected started_at type %T left as-is", id, v)+ log.Printf("normalizeUTCTimestamps(%s.%s): row %d: unexpected type %T left as-is", table, column, id, v)}}if err := rows.Err(); err != nil {rows.Close()- log.Printf("normalizeWorkoutStartedAt: rows: %v (skipping this boot)", err)+ log.Printf("normalizeUTCTimestamps(%s.%s): rows: %v (skipping this boot)", table, column, err)return}rows.Close() // release the process's only connection BEFORE the updates (SetMaxOpenConns(1))for _, f := range fixes {- if _, err := DB.Exec(`UPDATE workouts SET started_at = ? WHERE id = ?`, f.t, f.id); err != nil {- log.Fatalf("normalizeWorkoutStartedAt: update workout %d: %v", f.id, err)+ if _, err := DB.Exec(fmt.Sprintf(`UPDATE %s SET %s = ? WHERE id = ?`, table, column), f.t, f.id); err != nil {+ log.Fatalf("normalizeUTCTimestamps(%s.%s): update row %d: %v", table, column, f.id, err)}}if len(fixes) > 0 {- log.Printf("migration: normalized %d non-UTC workouts.started_at row(s) to UTC", len(fixes))+ log.Printf("migration: normalized %d non-UTC %s.%s row(s) to UTC", len(fixes), table, column)}if matched == 0 {- setMigrationFlag("normalize_workout_started_at")+ setMigrationFlag(flag)}}@@ -418,7 +633,8 @@ CREATE TABLE IF NOT EXISTS user_settings (calorie_target INTEGER NOT NULL DEFAULT 2000,protein_target INTEGER NOT NULL DEFAULT 150,carb_target INTEGER NOT NULL DEFAULT 250,- fat_target INTEGER NOT NULL DEFAULT 65+ fat_target INTEGER NOT NULL DEFAULT 65,+ timezone TEXT NOT NULL DEFAULT 'UTC');CREATE TABLE IF NOT EXISTS exercises (@@ -545,3 +761,5 @@ CREATE TABLE IF NOT EXISTS program_sets (target_weight REAL NOT NULL DEFAULT 0);`++diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.goindex 987e60b..9bb0386 100644--- a/backend/db/migrations_test.go+++ b/backend/db/migrations_test.go@@ -5,6 +5,7 @@ import ("fmt""math/rand""testing"+ "time"_ "modernc.org/sqlite")@@ -255,6 +256,76 @@ func TestNormalizeWorkoutStartedAt_RewritesPreFixOffsetRows(t *testing.T) {}}+func TestNormalizeFoodLoggedAt_RewritesPreFixOffsetRows(t *testing.T) {+ setupMigrationTestDB(t)+ if _, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('tz@food', 'x')`); err != nil {+ t.Fatalf("seed user: %v", err)+ }+ insert := func(name, loggedAt string) int64 {+ t.Helper()+ res, err := DB.Exec(`INSERT INTO food_logs (user_id, name, logged_at) VALUES (1, ?, ?)`, name, loggedAt)+ if err != nil {+ t.Fatalf("seed food log %s: %v", name, err)+ }+ id, _ := res.LastInsertId()+ return id+ }+ storedText := func(id int64) string {+ t.Helper()+ var s string+ if err := DB.QueryRow(`SELECT CAST(logged_at AS TEXT) FROM food_logs WHERE id = ?`, id).Scan(&s); err != nil {+ t.Fatalf("read logged_at of %d: %v", id, err)+ }+ return s+ }++ fixedOffset := insert("fixed-offset", "2026-07-19 02:00:00 +0800 +0800")+ utc := insert("utc", "2026-07-18 20:00:00 +0000 UTC")+ namedZone := insert("named-zone", "2026-07-18 21:00:00 -0500 EST")+ plain := insert("plain", "2026-07-10 08:00:00")++ normalizeFoodLoggedAt()++ if got := storedText(fixedOffset); got != "2026-07-18 18:00:00 +0000 UTC" {+ t.Fatalf("fixed-offset row not normalized: %q", got)+ }+ if got := storedText(namedZone); got != "2026-07-19 02:00:00 +0000 UTC" {+ t.Fatalf("named-zone row not normalized: %q", got)+ }+ if got := storedText(utc); got != "2026-07-18 20:00:00 +0000 UTC" {+ t.Fatalf("UTC row must be untouched: %q", got)+ }+ if got := storedText(plain); got != "2026-07-10 08:00:00" {+ t.Fatalf("zoneless row must be untouched: %q", got)+ }+ var inRange int+ if err := DB.QueryRow(+ `SELECT COUNT(*) FROM food_logs WHERE logged_at >= ? AND logged_at < ?`,+ "2026-07-18 00:00:00 +0000 UTC", "2026-07-19 00:00:00 +0000 UTC",+ ).Scan(&inRange); err != nil {+ t.Fatalf("range query: %v", err)+ }+ if inRange != 2 {+ t.Fatalf("expected 2 rows in the July 18 UTC window after normalization, got %d", inRange)+ }++ normalizeFoodLoggedAt()+ if got := storedText(fixedOffset); got != "2026-07-18 18:00:00 +0000 UTC" {+ t.Fatalf("second run changed an already-normalized row: %q", got)+ }++ done, err := hasMigrationFlag("normalize_food_logged_at")+ if err != nil {+ t.Fatalf("check flag: %v", err)+ }+ if !done {+ t.Fatalf("expected normalize_food_logged_at flag set once a run finds nothing to rewrite")+ }+ if wDone, err := hasMigrationFlag("normalize_workout_started_at"); err != nil || wDone {+ t.Fatalf("food normalization must not touch the workouts flag (done=%v, err=%v)", wDone, err)+ }+}+// TestProgramDayBackfillTransitionalWindow simulates the deployment window that ran// the multi-day release (program_days + workouts.program_id exist) but predates the// program_day_id fix: its program workouts carry program_id and no day linkage. The@@ -312,3 +383,109 @@ func TestProgramDayBackfillTransitionalWindow(t *testing.T) {t.Fatalf("backfill re-ran on an already-migrated DB and overwrote SET NULL rows")}}++// An existing server upgrading to stored days must not move anything a user can see.+//+// This is the one property no fresh-database test can check: the app worked before by+// deriving each day from the account's zone at read time, and works after by reading a+// day off the row. The upgrade is only safe if the backfill reproduces the old answer+// exactly — so the assertion is against the *old* rule, computed independently here.+func TestBackfillLocalDays_reproducesThePreMigrationDay(t *testing.T) {+ setupMigrationTestDB(t)++ if _, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('old@user', 'x')`); err != nil {+ t.Fatalf("seed user: %v", err)+ }+ // A user already living west of UTC, the case the whole feature exists for.+ if _, err := DB.Exec(`INSERT INTO user_settings (user_id, timezone) VALUES (1, 'America/New_York')`); err != nil {+ t.Fatalf("seed settings: %v", err)+ }++ // Instants chosen to straddle both midnights: 03:00Z is the previous day in New+ // York, 16:00Z is the same day, and 23:30Z is still the same day there.+ instants := []time.Time{+ time.Date(2026, 8, 5, 3, 0, 0, 0, time.UTC),+ time.Date(2026, 8, 5, 16, 0, 0, 0, time.UTC),+ time.Date(2026, 8, 5, 23, 30, 0, 0, time.UTC),+ }+ for i, at := range instants {+ if _, err := DB.Exec(+ `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, servings, logged_at)+ VALUES (1, ?, 'dinner', 100, 0, 0, 0, 1, ?)`, fmt.Sprintf("meal-%d", i), at); err != nil {+ t.Fatalf("seed food %d: %v", i, err)+ }+ if _, err := DB.Exec(`INSERT INTO weight_logs (user_id, weight, logged_at) VALUES (1, 180, ?)`, at); err != nil {+ t.Fatalf("seed weight %d: %v", i, err)+ }+ if _, err := DB.Exec(`INSERT INTO workouts (user_id, name, started_at) VALUES (1, ?, ?)`,+ fmt.Sprintf("lift-%d", i), at); err != nil {+ t.Fatalf("seed workout %d: %v", i, err)+ }+ }++ alterMigrations()++ // The pre-migration rule, spelled out rather than reused, so a bug in the+ // migration's helper cannot also define what "correct" means here.+ ny, err := time.LoadLocation("America/New_York")+ if err != nil {+ t.Fatalf("load zone: %v", err)+ }+ for i, at := range instants {+ want := at.In(ny).Format("2006-01-02")++ var foodDay, weightDay string+ if err := DB.QueryRow(`SELECT logged_on FROM food_logs WHERE name = ?`, fmt.Sprintf("meal-%d", i)).Scan(&foodDay); err != nil {+ t.Fatalf("read food day %d: %v", i, err)+ }+ if foodDay != want {+ t.Errorf("food %d (%s): backfilled %q, pre-migration read gave %q", i, at.Format(time.RFC3339), foodDay, want)+ }+ if err := DB.QueryRow(`SELECT logged_on FROM weight_logs WHERE logged_at = ?`, at).Scan(&weightDay); err != nil {+ t.Fatalf("read weight day %d: %v", i, err)+ }+ if weightDay != want {+ t.Errorf("weight %d: backfilled %q, want %q", i, weightDay, want)+ }++ // The workout stores an offset instead of a day; applying it must name the+ // same day. -240 in August (EDT), -300 in winter.+ var offset int+ if err := DB.QueryRow(`SELECT tz_offset_minutes FROM workouts WHERE name = ?`, fmt.Sprintf("lift-%d", i)).Scan(&offset); err != nil {+ t.Fatalf("read workout offset %d: %v", i, err)+ }+ if got := at.Add(time.Duration(offset) * time.Minute).Format("2006-01-02"); got != want {+ t.Errorf("workout %d: offset %d puts it on %q, want %q", i, offset, got, want)+ }+ }+}++// The backfill must not run twice, and must leave already-filled rows alone — a+// second boot re-deriving days would undo any day a client had since corrected.+func TestBackfillLocalDays_isIdempotent(t *testing.T) {+ setupMigrationTestDB(t)+ if _, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('old@user', 'x')`); err != nil {+ t.Fatalf("seed user: %v", err)+ }+ if _, err := DB.Exec(+ `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, servings, logged_at)+ VALUES (1, 'meal', 'dinner', 100, 0, 0, 0, 1, ?)`,+ time.Date(2026, 8, 5, 16, 0, 0, 0, time.UTC)); err != nil {+ t.Fatalf("seed food: %v", err)+ }+ alterMigrations()++ // Stand in for a client that has since filed this entry under a different day.+ if _, err := DB.Exec(`UPDATE food_logs SET logged_on = '1999-01-01' WHERE name = 'meal'`); err != nil {+ t.Fatalf("overwrite day: %v", err)+ }+ alterMigrations()++ var day string+ if err := DB.QueryRow(`SELECT logged_on FROM food_logs WHERE name = 'meal'`).Scan(&day); err != nil {+ t.Fatalf("read day: %v", err)+ }+ if day != "1999-01-01" {+ t.Errorf("second migration pass rewrote a filled day to %q", day)+ }+}diff --git a/backend/db/sqlite.go b/backend/db/sqlite.goindex 6dde2d3..d0037d4 100644--- a/backend/db/sqlite.go+++ b/backend/db/sqlite.go@@ -12,6 +12,22 @@ import (var DB *sql.DB+// BuildSchema brings an already-open DB to the current schema: base tables, then+// every migration, in the same order Connect uses.+//+// Exists so tests outside this package build their database the way production does+// instead of keeping a copy of the DDL. The controller tests used to carry a+// hand-maintained 138-line schema, which had already drifted — it created+// program_days (a migration artifact, not a base table) and omitted active_sessions+// entirely — so a column added to a migration compiled fine and failed at runtime.+func BuildSchema() error {+ if err := migrate(); err != nil {+ return err+ }+ alterMigrations()+ return nil+}+func Connect() {dbPath := config.C.DBPathdiff --git a/backend/models/models.go b/backend/models/models.goindex b10716f..717aaa4 100644--- a/backend/models/models.go+++ b/backend/models/models.go@@ -17,6 +17,12 @@ type UserSettings struct {ProteinTarget int `json:"protein_target" db:"protein_target"`CarbTarget int `json:"carb_target" db:"carb_target"`FatTarget int `json:"fat_target" db:"fat_target"`+ // IANA zone name (e.g. "America/New_York"). The server buckets day-scoped data+ // — food diary, daily macros, nutrition history — against this, so a client+ // asking for "2026-08-07" gets that user's local day rather than the UTC day.+ // "UTC" is the default and keeps the pre-existing behaviour for anyone who+ // never sets one.+ Timezone string `json:"timezone" db:"timezone"`}// DefaultUserSettings is the single source of truth for a brand-new user's@@ -30,6 +36,7 @@ func DefaultUserSettings(uid int64) UserSettings {ProteinTarget: 150,CarbTarget: 250,FatTarget: 65,+ Timezone: "UTC",}}@@ -52,8 +59,14 @@ type Workout struct {Notes string `json:"notes,omitempty" db:"notes"`Duration int `json:"duration" db:"duration"` // secondsStartedAt time.Time `json:"started_at" db:"started_at"`- CreatedAt time.Time `json:"created_at" db:"created_at"`- Exercises []WorkoutExercise `json:"exercises,omitempty"`+ // TZOffsetMinutes is the user's UTC offset when the workout started, e.g. -240+ // for New York in summer. StartedAt plus this offset gives the local day and the+ // local clock time, permanently — a workout is a real moment, so unlike the+ // diary it keeps the instant and records where it happened rather than flattening+ // to a date. Nil for rows older than the column whose zone could not be resolved.+ TZOffsetMinutes *int `json:"tz_offset_minutes,omitempty" db:"tz_offset_minutes"`+ CreatedAt time.Time `json:"created_at" db:"created_at"`+ Exercises []WorkoutExercise `json:"exercises,omitempty"`// Progression is set in-memory on the create response when finishing this// workout auto-progressed routine targets (issue #40). Never persisted.Progression *ProgressionResult `json:"progression,omitempty"`@@ -108,6 +121,9 @@ type WeightLog struct {Weight float64 `json:"weight" db:"weight"` // raw value in user's preferred unit (lbs or kg)Notes string `json:"notes,omitempty" db:"notes"`LoggedAt time.Time `json:"logged_at" db:"logged_at"`+ // LoggedOn is the calendar day this weigh-in belongs to (see FoodLog.LoggedOn).+ // It is also what "one entry per day" is enforced against.+ LoggedOn string `json:"logged_on" db:"logged_on"`CreatedAt time.Time `json:"created_at" db:"created_at"`}@@ -126,7 +142,12 @@ type FoodLog struct {Barcode string `json:"barcode,omitempty" db:"barcode"`ImageURL string `json:"image_url,omitempty" db:"image_url"`LoggedAt time.Time `json:"logged_at" db:"logged_at"`- CreatedAt time.Time `json:"created_at" db:"created_at"`+ // LoggedOn is the calendar day this entry belongs to, YYYY-MM-DD, in the user's+ // zone at the moment they logged it. It is the day the diary groups by — stored,+ // never re-derived, so it survives the user changing zones. LoggedAt remains the+ // instant, for time-of-day display and ordering within a day.+ LoggedOn string `json:"logged_on" db:"logged_on"`+ CreatedAt time.Time `json:"created_at" db:"created_at"`}type SavedFood struct {@@ -204,6 +225,10 @@ type CreateWorkoutRequest struct {Notes string `json:"notes"`Duration int `json:"duration"`StartedAt time.Time `json:"started_at"`+ // TZOffsetMinutes is the client's UTC offset when the workout started, e.g. -240.+ // Optional: nil from clients older than the stored-offset change, in which case+ // the server derives it from the account zone at StartedAt.+ TZOffsetMinutes *int `json:"tz_offset_minutes"`// ProgramID is set when the workout was started from a routine — it enables// per-set auto-progression of that routine's targets (issue #40). nil for// freestyle/quick workouts, which never progress a routine.@@ -245,6 +270,9 @@ type LogWeightRequest struct {Weight float64 `json:"weight" validate:"required,gt=0,lte=2000"`Notes string `json:"notes"`LoggedAt time.Time `json:"logged_at"`+ // LoggedOn is the calendar day this weigh-in belongs to, YYYY-MM-DD. Optional —+ // see LogFoodRequest.LoggedOn.+ LoggedOn string `json:"logged_on"`}type LogFoodRequest struct {@@ -260,6 +288,10 @@ type LogFoodRequest struct {Barcode string `json:"barcode"`ImageURL string `json:"image_url"`LoggedAt time.Time `json:"logged_at"`+ // LoggedOn is the calendar day the client files this under, YYYY-MM-DD. Optional:+ // omitted by clients older than the stored-day change, in which case the server+ // derives it from the account zone (see Handler.resolveDay).+ LoggedOn string `json:"logged_on"`}type SaveFoodRequest struct {@@ -283,6 +315,9 @@ type UpdateSettingsRequest struct {ProteinTarget *int `json:"protein_target" validate:"omitempty,gte=0"`CarbTarget *int `json:"carb_target" validate:"omitempty,gte=0"`FatTarget *int `json:"fat_target" validate:"omitempty,gte=0"`+ // Validated by loading it, not by a pattern: the only definition of a usable+ // zone is one the runtime can resolve (see controllers.ParseLocation).+ Timezone *string `json:"timezone"`}type Program struct {diff --git a/backend/seed/demo_data.go b/backend/seed/demo_data.goindex 46f9e42..94aad24 100644--- a/backend/seed/demo_data.go+++ b/backend/seed/demo_data.go@@ -225,12 +225,14 @@ func seedWorkouts(db *sql.DB, userID, progID int64) error {17+rng.Intn(3), rng.Intn(60), 0, 0, time.UTC)res, err := db.Exec(- `INSERT INTO workouts (user_id, name, notes, duration, started_at, program_id) VALUES (?, ?, ?, ?, ?, ?)`,+ `INSERT INTO workouts (user_id, name, notes, duration, started_at, tz_offset_minutes, program_id) VALUES (?, ?, ?, ?, ?, ?, ?)`,userID,workoutNames[tmplIdx],"",workoutDurations[tmplIdx]+rng.Intn(600)-300,startedAt,+ // startedAt is built in UTC, so UTC is the offset it actually happened at.+ 0,progID,)if err != nil {@@ -295,8 +297,8 @@ func seedWeightLogs(db *sql.DB, userID int64) {w += (rng.Float64()*3 - 1.5)loggedAt := time.Date(day.Year(), day.Month(), day.Day(), 7, 30, 0, 0, time.UTC)db.Exec(- `INSERT INTO weight_logs (user_id, weight, notes, logged_at) VALUES (?, ?, ?, ?)`,- userID, fmt.Sprintf("%.1f", w), "", loggedAt,+ `INSERT INTO weight_logs (user_id, weight, notes, logged_at, logged_on) VALUES (?, ?, ?, ?, ?)`,+ userID, fmt.Sprintf("%.1f", w), "", loggedAt, loggedAt.Format("2006-01-02"),)}}@@ -339,9 +341,14 @@ func seedFoodLogs(db *sql.DB, userID int64) {for _, m := range pattern {loggedAt := time.Date(day.Year(), day.Month(), day.Day(), 12, 0, 0, 0, time.UTC)db.Exec(- `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, logged_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,+ `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, logged_at, logged_on) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,userID, m.name, m.meal, m.calories, m.protein, m.carbs, m.fat,loggedAt,+ // Seeded rows must carry their own day like every other write. The+ // boot-time backfill cannot cover them — it is flag-guarded and runs+ // once, while accounts are seeded long after. Without this the diary+ // filters them out entirely.+ loggedAt.Format("2006-01-02"),)}}diff --git a/backend/stores/food.go b/backend/stores/food.goindex d9f626b..e75a7a7 100644--- a/backend/stores/food.go+++ b/backend/stores/food.go@@ -2,7 +2,6 @@ package storesimport ("database/sql"- "fmt""github.com/Cawlumm/lyftr-backend/models")@@ -12,21 +11,26 @@ type FoodStore struct{ db *sql.DB }func NewFoodStore(db *sql.DB) *FoodStore { return &FoodStore{db: db} }-const foodLogSelect = `SELECT id, user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, created_at FROM food_logs`+const foodLogSelect = `SELECT id, user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, logged_on, created_at FROM food_logs`func scanFoodLog(row interface{ Scan(...any) error }, f *models.FoodLog) error {return row.Scan(&f.ID, &f.UserID, &f.Name, &f.Meal,&f.Calories, &f.Protein, &f.Carbs, &f.Fat, &f.Fiber,&f.Servings, &f.ServingSize, &f.Barcode, &f.ImageURL,- &f.LoggedAt, &f.CreatedAt,+ &f.LoggedAt, &f.LoggedOn, &f.CreatedAt,)}-func (s *FoodStore) ListByDay(uid int64, date string) ([]models.FoodLog, error) {+// ListByDay returns the entries the user filed under `day` (YYYY-MM-DD).+//+// A plain equality on the stored day, not an instant range: the day was decided when+// the entry was written, so reading it needs no zone and cannot move. Ordered by the+// instant so entries still read in the order they happened within the day.+func (s *FoodStore) ListByDay(uid int64, day string) ([]models.FoodLog, error) {rows, err := s.db.Query(- foodLogSelect+` WHERE user_id = ? AND substr(logged_at, 1, 10) = ? ORDER BY logged_at ASC`,- uid, date,+ foodLogSelect+` WHERE user_id = ? AND logged_on = ? ORDER BY logged_at ASC, id ASC`,+ uid, day,)if err != nil {return nil, err@@ -43,6 +47,7 @@ func (s *FoodStore) ListByDay(uid int64, date string) ([]models.FoodLog, error)return logs, rows.Err()}+// Get returns one user-owned food log, or sql.ErrNoRows.func (s *FoodStore) Get(uid, id int64) (models.FoodLog, error) {var f models.FoodLog@@ -50,12 +55,14 @@ func (s *FoodStore) Get(uid, id int64) (models.FoodLog, error) {return f, err}-func (s *FoodStore) Create(uid int64, req models.LogFoodRequest) (models.FoodLog, error) {+// Create inserts an entry. day is the calendar day the user files it under, resolved+// by the controller (client-supplied when sent, else from the account zone).+func (s *FoodStore) Create(uid int64, req models.LogFoodRequest, day string) (models.FoodLog, error) {res, err := s.db.Exec(- `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, logged_on)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,uid, req.Name, req.Meal, req.Calories, req.Protein, req.Carbs, req.Fat, req.Fiber,- req.Servings, req.ServingSize, req.Barcode, req.ImageURL, req.LoggedAt,+ req.Servings, req.ServingSize, req.Barcode, req.ImageURL, req.LoggedAt, day,)if err != nil {return models.FoodLog{}, err@@ -64,13 +71,13 @@ func (s *FoodStore) Create(uid int64, req models.LogFoodRequest) (models.FoodLogreturn s.Get(uid, id)}-func (s *FoodStore) Update(uid, id int64, req models.LogFoodRequest) (models.FoodLog, error) {+func (s *FoodStore) Update(uid, id int64, req models.LogFoodRequest, day string) (models.FoodLog, error) {res, err := s.db.Exec(`UPDATE food_logs SET name=?, meal=?, calories=?, protein=?, carbs=?, fat=?, fiber=?,- servings=?, serving_size=?, barcode=?, image_url=?, logged_at=?+ servings=?, serving_size=?, barcode=?, image_url=?, logged_at=?, logged_on=?WHERE id=? AND user_id=?`,req.Name, req.Meal, req.Calories, req.Protein, req.Carbs, req.Fat, req.Fiber,- req.Servings, req.ServingSize, req.Barcode, req.ImageURL, req.LoggedAt,+ req.Servings, req.ServingSize, req.Barcode, req.ImageURL, req.LoggedAt, day,id, uid,)if err != nil {@@ -94,31 +101,41 @@ func (s *FoodStore) Delete(uid, id int64) (int64, error) {// DailyMacros returns the day's summed macros (WorkoutCount/Date are filled by// the caller, which composes a WorkoutStore count — cross-entity stays in the// controller, not in a store).-func (s *FoodStore) DailyMacros(uid int64, date string) (models.DailyStats, error) {+func (s *FoodStore) DailyMacros(uid int64, day string) (models.DailyStats, error) {var stats models.DailyStatserr := s.db.QueryRow(`SELECT COALESCE(SUM(calories),0), COALESCE(SUM(protein),0),COALESCE(SUM(carbs),0), COALESCE(SUM(fat),0), COALESCE(SUM(fiber),0)- FROM food_logs WHERE user_id = ? AND substr(logged_at, 1, 10) = ?`,- uid, date,+ FROM food_logs WHERE user_id = ? AND logged_on = ?`,+ uid, day,).Scan(&stats.TotalCalories, &stats.TotalProtein, &stats.TotalCarbs, &stats.TotalFat, &stats.TotalFiber)return stats, err}-func (s *FoodStore) History(uid int64, days int) ([]models.FoodHistoryPoint, error) {++// History returns per-day macro totals from sinceDay (YYYY-MM-DD) onward.+//+// Grouped in SQL now that the day is a stored column. The previous version read every+// row in the window and bucketed it in Go, because the day had to be derived through+// an IANA zone that SQLite cannot represent. Nothing needs deriving any more, so the+// chart totals and the daily totals are the same GROUP BY over the same column and+// cannot disagree about which day an entry belongs to.+func (s *FoodStore) History(uid int64, sinceDay string) ([]models.FoodHistoryPoint, error) {rows, err := s.db.Query(- `SELECT substr(logged_at, 1, 10) as d,+ `SELECT logged_on,COALESCE(SUM(calories),0), COALESCE(SUM(protein),0),COALESCE(SUM(carbs),0), COALESCE(SUM(fat),0)FROM food_logs- WHERE user_id = ? AND logged_at >= date('now', ?)- GROUP BY d ORDER BY d ASC`,- uid, fmt.Sprintf("-%d days", days),+ WHERE user_id = ? AND logged_on >= ?+ GROUP BY logged_on+ ORDER BY logged_on ASC`,+ uid, sinceDay,)if err != nil {return nil, err}defer rows.Close()+points := []models.FoodHistoryPoint{}for rows.Next() {var p models.FoodHistoryPointdiff --git a/backend/stores/user.go b/backend/stores/user.goindex 9363d24..8a61a59 100644--- a/backend/stores/user.go+++ b/backend/stores/user.go@@ -27,14 +27,14 @@ func (s *UserStore) GetByEmail(email string) (models.User, error) {return u, err}-const userSettingsSelect = `SELECT user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target FROM user_settings`+const userSettingsSelect = `SELECT user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target, timezone FROM user_settings`// GetSettings returns the user's settings row, or sql.ErrNoRows if none (the// controller owns the default fallback).func (s *UserStore) GetSettings(uid int64) (models.UserSettings, error) {var st models.UserSettingserr := s.db.QueryRow(userSettingsSelect+` WHERE user_id = ?`, uid).- Scan(&st.UserID, &st.WeightUnit, &st.CalorieTarget, &st.ProteinTarget, &st.CarbTarget, &st.FatTarget)+ Scan(&st.UserID, &st.WeightUnit, &st.CalorieTarget, &st.ProteinTarget, &st.CarbTarget, &st.FatTarget, &st.Timezone)return st, err}@@ -50,23 +50,25 @@ func (s *UserStore) UpsertSettings(uid int64, req models.UpdateSettingsRequest)d := models.DefaultUserSettings(uid)var st models.UserSettingserr := s.db.QueryRow(- `INSERT INTO user_settings (user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target)- VALUES (?, COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?))+ `INSERT INTO user_settings (user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target, timezone)+ VALUES (?, COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?))ON CONFLICT(user_id) DO UPDATE SETweight_unit = COALESCE(?, user_settings.weight_unit),calorie_target = COALESCE(?, user_settings.calorie_target),protein_target = COALESCE(?, user_settings.protein_target),carb_target = COALESCE(?, user_settings.carb_target),- fat_target = COALESCE(?, user_settings.fat_target)- RETURNING user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target`,+ fat_target = COALESCE(?, user_settings.fat_target),+ timezone = COALESCE(?, user_settings.timezone)+ RETURNING user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target, timezone`,uid,req.WeightUnit, d.WeightUnit,req.CalorieTarget, d.CalorieTarget,req.ProteinTarget, d.ProteinTarget,req.CarbTarget, d.CarbTarget,req.FatTarget, d.FatTarget,- req.WeightUnit, req.CalorieTarget, req.ProteinTarget, req.CarbTarget, req.FatTarget,- ).Scan(&st.UserID, &st.WeightUnit, &st.CalorieTarget, &st.ProteinTarget, &st.CarbTarget, &st.FatTarget)+ req.Timezone, d.Timezone,+ req.WeightUnit, req.CalorieTarget, req.ProteinTarget, req.CarbTarget, req.FatTarget, req.Timezone,+ ).Scan(&st.UserID, &st.WeightUnit, &st.CalorieTarget, &st.ProteinTarget, &st.CarbTarget, &st.FatTarget, &st.Timezone)if err != nil {return models.UserSettings{}, err}@@ -95,3 +97,4 @@ func (s *UserStore) Delete(uid int64) error {_, err := s.db.Exec(`DELETE FROM users WHERE id = ?`, uid)return err}+diff --git a/backend/stores/weight.go b/backend/stores/weight.goindex cb3c48a..e9135f5 100644--- a/backend/stores/weight.go+++ b/backend/stores/weight.go@@ -12,11 +12,15 @@ type WeightStore struct{ db *sql.DB }func NewWeightStore(db *sql.DB) *WeightStore { return &WeightStore{db: db} }-// WeightFilter holds resolved (already TZ-adjusted) query bounds. The controller-// owns the calendar-day → UTC-window widening and passes the resolved bounds.+// WeightFilter holds resolved query bounds.+//+// Two kinds, because the API accepts two kinds. A bare YYYY-MM-DD is a question about+// the user's calendar and filters on the stored day; a full RFC3339 timestamp is a+// question about instants and filters on logged_at. Neither consults a zone.type WeightFilter struct {Limit, Offset int- From, To *time.Time // nil = unbounded+ From, To *time.Time // instant bounds, for an exact RFC3339 range+ FromDay, ToDay *string // inclusive day bounds, for a bare YYYY-MM-DD range}// WeightStats is the computed summary for GetWeightStats.@@ -26,7 +30,7 @@ type WeightStats struct {Change7d, Change30d float64}-const weightCols = `id, user_id, weight, notes, logged_at, created_at`+const weightCols = `id, user_id, weight, notes, logged_at, logged_on, created_at`func (s *WeightStore) List(uid int64, f WeightFilter) ([]models.WeightLog, error) {q := `SELECT ` + weightCols + ` FROM weight_logs WHERE user_id = ?`@@ -39,6 +43,15 @@ func (s *WeightStore) List(uid int64, f WeightFilter) ([]models.WeightLog, errorq += ` AND logged_at < ?`args = append(args, *f.To)}+ if f.FromDay != nil {+ q += ` AND logged_on >= ?`+ args = append(args, *f.FromDay)+ }+ if f.ToDay != nil {+ // Inclusive: the caller asked for a day, not an exclusive bound.+ q += ` AND logged_on <= ?`+ args = append(args, *f.ToDay)+ }q += ` ORDER BY logged_at DESC, id DESC LIMIT ? OFFSET ?`args = append(args, f.Limit, f.Offset)@@ -50,7 +63,7 @@ func (s *WeightStore) List(uid int64, f WeightFilter) ([]models.WeightLog, errorlogs := []models.WeightLog{}for rows.Next() {var w models.WeightLog- if err := rows.Scan(&w.ID, &w.UserID, &w.Weight, &w.Notes, &w.LoggedAt, &w.CreatedAt); err != nil {+ if err := rows.Scan(&w.ID, &w.UserID, &w.Weight, &w.Notes, &w.LoggedAt, &w.LoggedOn, &w.CreatedAt); err != nil {return nil, err}logs = append(logs, w)@@ -62,7 +75,7 @@ func (s *WeightStore) List(uid int64, f WeightFilter) ([]models.WeightLog, errorfunc (s *WeightStore) get(id int64) (models.WeightLog, error) {var w models.WeightLogerr := s.db.QueryRow(`SELECT `+weightCols+` FROM weight_logs WHERE id = ?`, id).- Scan(&w.ID, &w.UserID, &w.Weight, &w.Notes, &w.LoggedAt, &w.CreatedAt)+ Scan(&w.ID, &w.UserID, &w.Weight, &w.Notes, &w.LoggedAt, &w.LoggedOn, &w.CreatedAt)return w, err}@@ -70,43 +83,39 @@ func (s *WeightStore) get(id int64) (models.WeightLog, error) {func (s *WeightStore) Get(uid, id int64) (models.WeightLog, error) {var w models.WeightLogerr := s.db.QueryRow(`SELECT `+weightCols+` FROM weight_logs WHERE id = ? AND user_id = ?`, id, uid).- Scan(&w.ID, &w.UserID, &w.Weight, &w.Notes, &w.LoggedAt, &w.CreatedAt)+ Scan(&w.ID, &w.UserID, &w.Weight, &w.Notes, &w.LoggedAt, &w.LoggedOn, &w.CreatedAt)return w, err}-// dayBounds returns [00:00, next 00:00) for the given instant's calendar day.-// Range match (not SQLite date()) because timestamps store in Go's time.String-// format which date() can't parse.-func dayBounds(t time.Time) (time.Time, time.Time) {- start := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())- return start, start.AddDate(0, 0, 1)-}-// UpsertForDay enforces one entry per calendar day: update the day's existing// entry if present, else insert. req.LoggedAt must already be normalized to UTC.-func (s *WeightStore) UpsertForDay(uid int64, req models.LogWeightRequest) (models.WeightLog, error) {- dayStart, dayEnd := dayBounds(req.LoggedAt)+func (s *WeightStore) UpsertForDay(uid int64, req models.LogWeightRequest, day string) (models.WeightLog, error) {+ // Keyed on the stored day, so "one per day" means one per the day the user filed+ // it under. The previous instant-range version answered the same question through+ // the account zone, which meant a zone change could make two entries collide on a+ // day neither was written for.+ //// Atomic check-then-write: without the transaction the connection is released// between the SELECT and the write, so two same-day logs could both miss the// row and both insert (duplicate day).id, err := inTx(s.db, func(tx *sql.Tx) (int64, error) {var id int64err := tx.QueryRow(- `SELECT id FROM weight_logs WHERE user_id = ? AND logged_at >= ? AND logged_at < ? ORDER BY id DESC LIMIT 1`,- uid, dayStart, dayEnd,+ `SELECT id FROM weight_logs WHERE user_id = ? AND logged_on = ? ORDER BY id DESC LIMIT 1`,+ uid, day,).Scan(&id)switch err {case nil:if _, e := tx.Exec(- `UPDATE weight_logs SET weight = ?, notes = ?, logged_at = ? WHERE id = ?`,- req.Weight, req.Notes, req.LoggedAt, id,+ `UPDATE weight_logs SET weight = ?, notes = ?, logged_at = ?, logged_on = ? WHERE id = ?`,+ req.Weight, req.Notes, req.LoggedAt, day, id,); e != nil {return 0, e}case sql.ErrNoRows:res, e := tx.Exec(- `INSERT INTO weight_logs (user_id, weight, notes, logged_at) VALUES (?, ?, ?, ?)`,- uid, req.Weight, req.Notes, req.LoggedAt,+ `INSERT INTO weight_logs (user_id, weight, notes, logged_at, logged_on) VALUES (?, ?, ?, ?, ?)`,+ uid, req.Weight, req.Notes, req.LoggedAt, day,)if e != nil {return 0, e@@ -125,12 +134,12 @@ func (s *WeightStore) UpsertForDay(uid int64, req models.LogWeightRequest) (mode// Update edits an entry the user owns (sql.ErrNoRows if not theirs), then drops// any other same-day entry so the day keeps a single entry. req.LoggedAt UTC.-func (s *WeightStore) Update(uid, id int64, req models.LogWeightRequest) (models.WeightLog, error) {+func (s *WeightStore) Update(uid, id int64, req models.LogWeightRequest, day string) (models.WeightLog, error) {// Atomic: the row update + the same-day dedup delete must commit together.if err := inTxDo(s.db, func(tx *sql.Tx) error {res, err := tx.Exec(- `UPDATE weight_logs SET weight = ?, notes = ?, logged_at = ? WHERE id = ? AND user_id = ?`,- req.Weight, req.Notes, req.LoggedAt, id, uid,+ `UPDATE weight_logs SET weight = ?, notes = ?, logged_at = ?, logged_on = ? WHERE id = ? AND user_id = ?`,+ req.Weight, req.Notes, req.LoggedAt, day, id, uid,)if err != nil {return err@@ -138,10 +147,11 @@ func (s *WeightStore) Update(uid, id int64, req models.LogWeightRequest) (modelsif n, _ := res.RowsAffected(); n == 0 {return sql.ErrNoRows}- dayStart, dayEnd := dayBounds(req.LoggedAt)+ // Same day as the upsert keys on — one entry per the *user's* day. Runs after+ // the update above, so it matches the row's new day, not the one it left._, err = tx.Exec(- `DELETE FROM weight_logs WHERE user_id = ? AND id != ? AND logged_at >= ? AND logged_at < ?`,- uid, id, dayStart, dayEnd,+ `DELETE FROM weight_logs WHERE user_id = ? AND id != ? AND logged_on = ?`,+ uid, id, day,)return err}); err != nil {diff --git a/backend/stores/workout.go b/backend/stores/workout.goindex 4e19a6b..882b945 100644--- a/backend/stores/workout.go+++ b/backend/stores/workout.go@@ -19,10 +19,10 @@ type WorkoutFilter struct {Query string}-const workoutCols = `id, user_id, name, notes, duration, started_at, created_at`+const workoutCols = `id, user_id, name, notes, duration, started_at, tz_offset_minutes, created_at`func scanWorkout(row interface{ Scan(...any) error }, w *models.Workout) error {- return row.Scan(&w.ID, &w.UserID, &w.Name, &w.Notes, &w.Duration, &w.StartedAt, &w.CreatedAt)+ return row.Scan(&w.ID, &w.UserID, &w.Name, &w.Notes, &w.Duration, &w.StartedAt, &w.TZOffsetMinutes, &w.CreatedAt)}func (s *WorkoutStore) List(uid int64, f WorkoutFilter) ([]models.Workout, error) {@@ -139,8 +139,8 @@ func createWorkoutTx(tx *sql.Tx, uid int64, req models.CreateWorkoutRequest) (in}}res, err := tx.Exec(- `INSERT INTO workouts (user_id, name, notes, duration, started_at, program_id, program_day_id) VALUES (?, ?, ?, ?, ?, ?, ?)`,- uid, req.Name, req.Notes, req.Duration, req.StartedAt, req.ProgramID, dayID,+ `INSERT INTO workouts (user_id, name, notes, duration, started_at, tz_offset_minutes, program_id, program_day_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,+ uid, req.Name, req.Notes, req.Duration, req.StartedAt, req.TZOffsetMinutes, req.ProgramID, dayID,)if err != nil {return 0, err@@ -294,13 +294,26 @@ func (s *WorkoutStore) loadSets(workoutExerciseID int64) ([]models.Set, error) {return sets, rows.Err()}-// CountOn returns how many workouts the user started on the given calendar day-// (YYYY-MM-DD). Used by the food daily-stats view (cross-entity composition).-func (s *WorkoutStore) CountOn(uid int64, date string) (int, error) {++// CountOnLocalDay counts workouts whose own recorded offset puts them on `day`.+//+// Shifting the instant by the row's stored offset is exact and needs no zone: a+// workout at 2026-08-04T16:00Z with offset -240 was 12:00 on the 4th where it+// happened, and always will be. Rows predating the column have a NULL offset and are+// counted as UTC, which is the day they were counted under before it existed.+func (s *WorkoutStore) CountOnLocalDay(uid int64, day string) (int, error) {var n int+ // substr(...,1,19) takes the "YYYY-MM-DD HH:MM:SS" prefix. The driver writes a+ // time.Time in Go's String() form — "2026-04-25 03:30:00 +0000 UTC" — which+ // SQLite's date() cannot parse at all, returning NULL and matching nothing. The+ // prefix is a format it does accept, and is UTC because every write path+ // normalizes to UTC before storing (normalizeLoggedAt, plus the boot-time+ // normalizeUTCTimestamps for older rows).err := s.db.QueryRow(- `SELECT COUNT(*) FROM workouts WHERE user_id = ? AND substr(started_at, 1, 10) = ?`,- uid, date,+ `SELECT COUNT(*) FROM workouts+ WHERE user_id = ?+ AND date(substr(started_at, 1, 19), CAST(COALESCE(tz_offset_minutes, 0) AS TEXT) || ' minutes') = ?`,+ uid, day,).Scan(&n)return n, err}diff --git a/mobile/app.json b/mobile/app.jsonindex e133166..3be80e5 100644--- a/mobile/app.json+++ b/mobile/app.json@@ -59,6 +59,7 @@],"expo-font","@react-native-community/datetimepicker",+ "expo-localization",["expo-network-security-config",{diff --git a/mobile/app/(tabs)/index.tsx b/mobile/app/(tabs)/index.tsxindex caa77e4..ebc140a 100644--- a/mobile/app/(tabs)/index.tsx+++ b/mobile/app/(tabs)/index.tsx@@ -9,10 +9,7 @@ import {import {Activity, AlertCircle, ArrowRight, BookOpen, ChevronRight, Dumbbell, Play, Plus, Scale, Timer, TrendingUp,} from 'lucide-react-native'-import {- activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, isDayStartable, sessionNameForDay,- todaysDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout,-} from '@lyftr/shared'+import { activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, isDayStartable, sessionNameForDay, todaysDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay } from '@lyftr/shared'import { AppText, Card, IconButton, Label, Screen, SectionHeader, SegmentedControl } from '../../src/components/ui'import { ExerciseImage } from '../../src/components/workouts/ExerciseImage'import {@@ -236,7 +233,8 @@ export default function Dashboard() {const heatmapDays = eachDayOfInterval({ start: heatmapStart, end: heatmapEnd })const workoutDayMap = new Map<string, number>()workouts.forEach((w) => {- const k = format(new Date(w.started_at), 'yyyy-MM-dd')+ // See web Dashboard: bucket by the workout's recorded day, not the device's.+ const k = workoutDay(w)workoutDayMap.set(k, (workoutDayMap.get(k) || 0) + 1)})const heatmapWeeks: Date[][] = []@@ -277,7 +275,7 @@ export default function Dashboard() {const fatPct = Math.min(100, (food.total_fat / settings.fat_target) * 100) || 0const sparkData = [...weightLogs].reverse().map((l) => ({- date: format(new Date(l.logged_at), 'M/d'),+ date: format(new Date(entryDay(l) + 'T12:00:00'), 'M/d'),weight: displayWeight(l.weight, unit),}))@@ -401,7 +399,7 @@ export default function Dashboard() {</View><View className="mt-4 flex-row items-center justify-between px-0.5">{weekDays.map((day, i) => {- const hasWorkout = workouts.some((w) => isSameDay(new Date(w.started_at), day))+ const hasWorkout = workouts.some((w) => workoutDay(w) === format(day, 'yyyy-MM-dd'))const isToday = isSameDay(day, now)const isFuture = day > nowreturn (@@ -520,7 +518,7 @@ export default function Dashboard() {<Label className="mb-1">Last workout</Label><Text className="font-sans-semibold text-base text-tx-primary" numberOfLines={1}>{lastWorkout.name}</Text><AppText variant="caption" color="muted" className="mt-0.5">- {format(new Date(lastWorkout.started_at), 'MMM d')}+ {format(new Date(workoutDay(lastWorkout) + 'T12:00:00'), 'MMM d')}{mins > 0 ? ` · ${mins} min` : ''}{totalSets > 0 ? ` · ${totalSets} sets` : ''}{totalVolume > 0 ? ` · ${totalVolume.toLocaleString()} ${wUnit}` : ''}diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsxindex 1257cfa..04ac0a0 100644--- a/mobile/app/(tabs)/nutrition/log.tsx+++ b/mobile/app/(tabs)/nutrition/log.tsx@@ -6,7 +6,7 @@ import {AlertCircle, ArrowLeft, Bookmark, BookmarkCheck, ChevronRight, Minus, Plus, Scan, Utensils, Zap,} from 'lucide-react-native'import {- dayToIsoNoon, todayStr,+ dayToInstant, todayStr,type FoodLog, type FoodSearchResult, type SavedFood,} from '@lyftr/shared'import {@@ -219,7 +219,7 @@ export default function LogFood() {servings,serving_size: selected.serving_size ?? '',image_url: selected.image_url ?? '',- logged_at: dayToIsoNoon(date),+ logged_at: dayToInstant(date),}if (editId) {await client.foodAPI.update(editId, payload)diff --git a/mobile/app/(tabs)/weight/[id].tsx b/mobile/app/(tabs)/weight/[id].tsxindex e55d498..3203b2b 100644--- a/mobile/app/(tabs)/weight/[id].tsx+++ b/mobile/app/(tabs)/weight/[id].tsx@@ -4,10 +4,7 @@ import { router, useLocalSearchParams } from 'expo-router'import { format, parseISO } from 'date-fns'import * as Haptics from 'expo-haptics'import { AlertCircle, ArrowLeft, Edit2, Scale, Trash2 } from 'lucide-react-native'-import {- apiErrorMessage, dayToIsoNoon, displayWeight, isoToDayInput, maxWeight, resolveWeightLbs,- weightError, weightShort, type WeightLog,-} from '@lyftr/shared'+import { apiErrorMessage, dayToInstant, displayWeight, instantToDay, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay } from '@lyftr/shared'import {AppText, Button, Card, ConfirmSheet, DateInput, Field, Label, Loading, NumberField,NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, Screen, StepperTile, deleteConfirmProps,@@ -46,7 +43,7 @@ export default function WeightDetail() {.then((data) => {setLog(data)setEditWeight(String(displayWeight(data.weight, unit)))- setEditDate(isoToDayInput(data.logged_at))+ setEditDate(entryDay(data))setEditNotes(data.notes ?? '')// Deep-link from the list kebab's Edit action opens straight into edit mode.if (edit) setEditing(true)@@ -59,7 +56,7 @@ export default function WeightDetail() {const startEdit = () => {if (!log) returnsetEditWeight(String(displayWeight(log.weight, unit)))- setEditDate(isoToDayInput(log.logged_at))+ setEditDate(entryDay(log))setEditNotes(log.notes ?? '')setEditError('')setEditing(true)@@ -81,7 +78,7 @@ export default function WeightDetail() {// (avoids kg round-trip drift); only converts when the user actually edited it.weight: resolveWeightLbs(editWeight, log.weight, unit),notes: editNotes.trim(),- logged_at: dayToIsoNoon(editDate),+ logged_at: dayToInstant(editDate, log.logged_at),})Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})setLog(updated)diff --git a/mobile/app/(tabs)/weight/index.tsx b/mobile/app/(tabs)/weight/index.tsxindex cae8cf5..8066d70 100644--- a/mobile/app/(tabs)/weight/index.tsx+++ b/mobile/app/(tabs)/weight/index.tsx@@ -7,10 +7,7 @@ import {Activity, AlertCircle, ArrowDown, ArrowUp, Calendar, Minus, Scale, Sunrise,TrendingDown, TrendingUp, X,} from 'lucide-react-native'-import {- apiErrorMessage, dayToIsoNoon, displayToLbs, displayWeight, isoToDayInput, maxWeight, todayStr,- weightError, weightShort, type WeightLog, type WeightStats,-} from '@lyftr/shared'+import { apiErrorMessage, dayToInstant, daysAgoStr, displayToLbs, displayWeight, instantToDay, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay } from '@lyftr/shared'import {AppText, Button, Card, DateInput, Field, Label, NumberField, NumericKeyboardAccessory,NUMERIC_ACCESSORY_ID, PageHeader, Screen, SegmentedControl, StepperTile,@@ -50,7 +47,7 @@ export default function Weight() {// Returns the fetch promise so pull-to-refresh can await a full refresh.const refetchChart = useCallback(() => {const days = PERIOD_DAYS[period]- const from = days != null ? format(subDays(new Date(), days), 'yyyy-MM-dd') : undefined+ const from = days != null ? daysAgoStr(days) : undefinedreturn client.weightAPI.list({ limit: 1000, from }).then((data) => setChartLogs(data || [])).catch(() => {})}, [period])useEffect(() => { refetchChart() }, [refetchChart])@@ -126,7 +123,7 @@ export default function Weight() {}// Guard against a same-day double-log (unless already waved through).- if (!duplicateWarningDismissedRef.current && items.length > 0 && isoToDayInput(items[0].logged_at) === newDate) {+ if (!duplicateWarningDismissedRef.current && items.length > 0 && entryDay(items[0]) === newDate) {setShowDuplicateWarning(true)return}@@ -139,7 +136,7 @@ export default function Weight() {const real = await client.weightAPI.log({weight: displayToLbs(w, unit),notes: newNotes.trim(),- logged_at: dayToIsoNoon(newDate),+ logged_at: dayToInstant(newDate),})Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})setNewWeight(String(displayWeight(real.weight, unit)))diff --git a/mobile/app/(tabs)/workouts/[id].tsx b/mobile/app/(tabs)/workouts/[id].tsxindex 154dec3..ad8394f 100644--- a/mobile/app/(tabs)/workouts/[id].tsx+++ b/mobile/app/(tabs)/workouts/[id].tsx@@ -5,10 +5,7 @@ import { format } from 'date-fns'import {AlertCircle, ArrowLeft, ChevronRight, Clock, Edit2, Layers, Pause, TimerOff, Trash2, TrendingUp,} from 'lucide-react-native'-import {- apiErrorMessage, displayVolume, displayWeight, weightShort,- type Workout, type Set as WorkoutSet,-} from '@lyftr/shared'+import { apiErrorMessage, displayVolume, displayWeight, weightShort, type Workout, type Set as WorkoutSet, workoutDay } from '@lyftr/shared'import { AppText, ConfirmSheet, Loading, Screen, deleteConfirmProps } from '../../../src/components/ui'import { ExerciseImage } from '../../../src/components/workouts/ExerciseImage'import { client, useSettingsStore } from '../../../src/lib/lyftr'@@ -188,7 +185,7 @@ export default function WorkoutDetail() {<View className="flex-1"><AppText variant="heading">{workout.name}</AppText><AppText variant="body" color="muted" className="mt-0.5">- {format(new Date(workout.started_at), 'EEEE, MMMM d, yyyy')}+ {format(new Date(workoutDay(workout) + 'T12:00:00'), 'EEEE, MMMM d, yyyy')}</AppText></View></View>diff --git a/mobile/app/(tabs)/workouts/[id]/edit.tsx b/mobile/app/(tabs)/workouts/[id]/edit.tsxindex 0d69b63..53a1167 100644--- a/mobile/app/(tabs)/workouts/[id]/edit.tsx+++ b/mobile/app/(tabs)/workouts/[id]/edit.tsx@@ -5,9 +5,7 @@ import {AlertCircle, ArrowLeft, CalendarDays, Clock, Dumbbell, FileText, Plus, Zap,} from 'lucide-react-native'import type { LucideIcon } from 'lucide-react-native'-import {- apiErrorMessage, displayToLbs, lbsToDisplay, weightShort, type Exercise,-} from '@lyftr/shared'+import { apiErrorMessage, dayToInstant, instantToDay, displayToLbs, lbsToDisplay, weightShort, type Exercise, workoutDay } from '@lyftr/shared'import { AppText, Button, DateInput, EmptyState, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'import { ExerciseFormCard } from '../../../../src/components/workouts/ExerciseFormCard'import { DurationField } from '../../../../src/components/workouts/DurationField'@@ -38,16 +36,6 @@ const KEYPAD_DONE_ID = 'workout-edit-keypad-done'// started_at (full ISO timestamp) ⇄ the DateInput's local calendar date. Editing the// date should only move the *day* — the original time-of-day is preserved so a// workout logged at 6pm doesn't jump to midnight just because the date was touched.-const pad = (n: number) => String(n).padStart(2, '0')-const startedAtToDate = (iso: string): string => {- const d = new Date(iso)- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`-}-const applyDateKeepTime = (iso: string, ymd: string): string => {- const orig = new Date(iso)- const [y, m, d] = ymd.split('-').map(Number)- return new Date(y, (m ?? 1) - 1, d ?? 1, orig.getHours(), orig.getMinutes(), orig.getSeconds()).toISOString()-}function FieldHeader({ icon: Icon, label, hint }: { icon: LucideIcon; label: string; hint?: string }) {// Muted (not accent) field icons — matches new.tsx: with every header cyan the@@ -104,7 +92,10 @@ export default function EditWorkout() {setFormData({name: workout.name,notes: workout.notes || '',- date: startedAtToDate(startedAt),+ // The day the workout was recorded at, from its own offset — not the day+ // the device would put that instant on now. Prefilling the latter and+ // saving it would move the workout for anyone viewing from another zone.+ date: workoutDay(workout),duration: Math.round(workout.duration / 60),exercises: (workout.exercises || []).map((ex) => ({exercise_id: ex.exercise_id,@@ -201,7 +192,7 @@ export default function EditWorkout() {duration: formData.duration * 60,// Move only the day; keep the logged time-of-day from the original timestamp.started_at: formData.date- ? applyDateKeepTime(originalStartedAt || new Date().toISOString(), formData.date)+ ? dayToInstant(formData.date, originalStartedAt || undefined): originalStartedAt || new Date().toISOString(),exercises: formData.exercises.map((ex) => ({...ex,diff --git a/mobile/app/(tabs)/workouts/new.tsx b/mobile/app/(tabs)/workouts/new.tsxindex ea7667e..2e6a206 100644--- a/mobile/app/(tabs)/workouts/new.tsx+++ b/mobile/app/(tabs)/workouts/new.tsx@@ -5,7 +5,7 @@ import {AlertCircle, ArrowLeft, BookOpen, CalendarDays, Clock, Dumbbell, FileText, Plus, Zap,} from 'lucide-react-native'import type { LucideIcon } from 'lucide-react-native'-import { apiErrorMessage, displayToLbs, lbsToDisplay, weightShort, type Exercise, type Program, type ProgramDay } from '@lyftr/shared'+import { apiErrorMessage, displayToLbs, lbsToDisplay, weightShort, type Exercise, type Program, type ProgramDay, dayToInstant, todayStr } from '@lyftr/shared'import { AppText, Button, DateInput, EmptyState, Field, IconButton, Label, Screen } from '../../../src/components/ui'import { ExerciseFormCard } from '../../../src/components/workouts/ExerciseFormCard'import { DurationField } from '../../../src/components/workouts/DurationField'@@ -63,7 +63,7 @@ export default function AddWorkout() {name: '',notes: '',duration: 0,- date: new Date().toISOString().slice(0, 10),+ date: todayStr(),exercises: [],})const scrollRef = useRef<ScrollView>(null)@@ -173,7 +173,7 @@ export default function AddWorkout() {const payload = {...formData,duration: formData.duration * 60,- started_at: new Date(formData.date).toISOString(),+ started_at: dayToInstant(formData.date),exercises: formData.exercises.map((ex) => ({...ex,sets: ex.sets.map((s) => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),diff --git a/mobile/package.json b/mobile/package.jsonindex 91e011c..98137e4 100644--- a/mobile/package.json+++ b/mobile/package.json@@ -33,6 +33,7 @@"expo-keep-awake": "~15.0.8","expo-linear-gradient": "~15.0.8","expo-linking": "~8.0.12",+ "expo-localization": "~17.0.9","expo-network-security-config": "^1.1.2","expo-router": "~6.0.24","expo-secure-store": "~15.0.8",diff --git a/mobile/src/components/dashboard/QuickWeighInSheet.tsx b/mobile/src/components/dashboard/QuickWeighInSheet.tsxindex 2c3c4a3..ad7e271 100644--- a/mobile/src/components/dashboard/QuickWeighInSheet.tsx+++ b/mobile/src/components/dashboard/QuickWeighInSheet.tsx@@ -2,10 +2,7 @@ import { useEffect, useState } from 'react'import { Pressable, Text, View } from 'react-native'import * as Haptics from 'expo-haptics'import { AlertCircle, Scale, X } from 'lucide-react-native'-import {- apiErrorMessage, dayToIsoNoon, displayToLbs, isoToDayInput, maxWeight, todayStr,- weightError, weightShort, type WeightLog,-} from '@lyftr/shared'+import { apiErrorMessage, dayToInstant, displayToLbs, instantToDay, maxWeight, todayStr, weightError, weightShort, type WeightLog, entryDay } from '@lyftr/shared'import {AppText, Button, DateInput, Field, NumberField, NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID,Sheet, StepperTile,@@ -63,7 +60,7 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccesssetError(wErr)return}- if (!(forceDismissed || dupDismissed) && lastLog && isoToDayInput(lastLog.logged_at) === date) {+ if (!(forceDismissed || dupDismissed) && lastLog && entryDay(lastLog) === date) {setShowDuplicateWarning(true)return}@@ -74,7 +71,7 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccessconst log = await client.weightAPI.log({weight: displayToLbs(w, unit),notes: notes.trim(),- logged_at: dayToIsoNoon(date),+ logged_at: dayToInstant(date),})Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})onSuccess(log)diff --git a/mobile/src/components/workouts/WorkoutCard.tsx b/mobile/src/components/workouts/WorkoutCard.tsxindex 1fd8dd3..e7639ba 100644--- a/mobile/src/components/workouts/WorkoutCard.tsx+++ b/mobile/src/components/workouts/WorkoutCard.tsx@@ -3,7 +3,7 @@ import { Pressable, View } from 'react-native'import { router } from 'expo-router'import { format } from 'date-fns'import { ChevronRight, Clock, Dumbbell, MoreVertical, TrendingUp } from 'lucide-react-native'-import { displayVolume, type Workout } from '@lyftr/shared'+import { displayVolume, type Workout, workoutDay } from '@lyftr/shared'import { ActionSheet, AppText, Card, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'import { useTheme } from '../../theme/useTheme'import { client } from '../../lib/lyftr'@@ -62,7 +62,7 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {then exercises + volume — three items on one line truncated at 390pt. */}<View className="flex-row items-center gap-x-2 mt-0.5"><AppText variant="caption" color="muted" numberOfLines={1}>- {format(new Date(workout.started_at), 'MMM d, yyyy')}+ {format(new Date(workoutDay(workout) + 'T12:00:00'), 'MMM d, yyyy')}</AppText>{durationMin > 0 && (<>@@ -121,7 +121,7 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {<View className="flex-1"><AppText variant="subheading" numberOfLines={1}>{workout.name}</AppText><AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">- {format(new Date(workout.started_at), 'MMM d, yyyy')}+ {format(new Date(workoutDay(workout) + 'T12:00:00'), 'MMM d, yyyy')}{durationMin > 0 ? ` · ${durationMin} min` : ''}{` · ${workout.exercises?.length || 0} exercises`}</AppText>diff --git a/mobile/src/lib/lyftr.ts b/mobile/src/lib/lyftr.tsindex 9b0e602..5763502 100644--- a/mobile/src/lib/lyftr.ts+++ b/mobile/src/lib/lyftr.ts@@ -1,6 +1,7 @@// App-wide singletons: one API client + the Zustand stores, all bound to the mobile// SecureStore/AsyncStorage adapter. Import these hooks anywhere in the app.import { router } from 'expo-router'+import * as Localization from 'expo-localization'import {createClient,createAuthStore,@@ -24,7 +25,12 @@ export const client = createClient(storage, {export const useAuthStore = createAuthStore(client, storage)export const useServerStore = createServerStore(storage)-export const useSettingsStore = createSettingsStore(client, storage)+// Ask the OS, not Intl: Hermes doesn't expose the device zone to JavaScript, so a+// polyfilled Intl.DateTimeFormat().resolvedOptions().timeZone reports "UTC" on+// every phone — which would look like the feature worked while doing nothing.+const detectTimezone = () => Localization.getCalendars()[0]?.timeZone ?? null++export const useSettingsStore = createSettingsStore(client, storage, detectTimezone)// Light-first on mobile (per product); mirrors the web's theme logic + 'theme' key.export const useThemeStore = createThemeStore(storage, 'light')// Workout session state (active workout + gym UI position) — device-local viadiff --git a/package-lock.json b/package-lock.jsonindex dee6139..8ff1e81 100644--- a/package-lock.json+++ b/package-lock.json@@ -34,6 +34,7 @@"expo-keep-awake": "~15.0.8","expo-linear-gradient": "~15.0.8","expo-linking": "~8.0.12",+ "expo-localization": "~17.0.9","expo-network-security-config": "^1.1.2","expo-router": "~6.0.24","expo-secure-store": "~15.0.8",@@ -8550,6 +8551,18 @@"react-native": "*"}},+ "node_modules/expo-localization": {+ "version": "17.0.9",+ "resolved": "https://registry.npmjs.org/expo-localization/-/expo-localization-17.0.9.tgz",+ "integrity": "sha512-k5eYHr7iLMob3M8cHH6bgDrDRmqnZG8xKGLhpx8ST+LsFXmSgYpJ/t0VwWm0gz64C/K669XhObdG3D6QwCGqhw==",+ "dependencies": {+ "rtl-detect": "^1.0.2"+ },+ "peerDependencies": {+ "expo": "*",+ "react": "*"+ }+ },"node_modules/expo-modules-autolinking": {"version": "3.0.26","resolved": "https://registry.npmjs.org/expo-modules-autolinking/-/expo-modules-autolinking-3.0.26.tgz",@@ -15079,6 +15092,11 @@"node": "*"}},+ "node_modules/rtl-detect": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/rtl-detect/-/rtl-detect-1.1.2.tgz",+ "integrity": "sha512-PGMBq03+TTG/p/cRB7HCLKJ1MgDIi07+QU1faSjiYRfmY5UsAttV9Hs08jDAHVwcOwmVLcSJkpwyfXszVjWfIQ=="+ },"node_modules/run-parallel": {"version": "1.2.0","resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",diff --git a/packages/shared/jest.config.js b/packages/shared/jest.config.jsindex 67b4ad8..b3db9ac 100644--- a/packages/shared/jest.config.js+++ b/packages/shared/jest.config.js@@ -1,4 +1,6 @@/** Jest config for the platform-agnostic shared core. Runs on Linux/node. */+process.env.TZ = 'America/New_York'+module.exports = {preset: 'ts-jest',testEnvironment: 'node',diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.tsnew file mode 100644index 0000000..3fe9dec--- /dev/null+++ b/packages/shared/src/client.test.ts@@ -0,0 +1,47 @@+import { createClient } from './client'+import { StorageAdapter } from './storage'++const memStorage = (): StorageAdapter => {+ const m = new Map<string, string>()+ return {+ get: async (k) => m.get(k) ?? null,+ set: async (k, v) => { m.set(k, v) },+ remove: async (k) => { m.delete(k) },+ }+}++const captureClient = () => {+ const calls: Array<{ url?: string; params?: any }> = []+ const client = createClient(memStorage())+ client.api.defaults.adapter = async (config: any) => {+ calls.push({ url: config.url, params: config.params })+ return { data: { data: [] }, status: 200, statusText: 'OK', headers: {}, config }+ }+ return { client, calls }+}++describe('foodAPI day windowing', () => {+ it('list sends only the day — the server buckets it in the user timezone', async () => {+ const { client, calls } = captureClient()+ await client.foodAPI.list('2026-06-15')+ expect(calls[0].url).toBe('/food')+ expect(calls[0].params).toEqual({+ date: '2026-06-15',+ })+ })++ it('stats sends only the day — the server buckets it in the user timezone', async () => {+ const { client, calls } = captureClient()+ await client.foodAPI.stats('2026-11-01')+ expect(calls[0].url).toBe('/food/stats')+ expect(calls[0].params).toEqual({+ date: '2026-11-01',+ })+ })++ it('sends no day params when date is omitted', async () => {+ const { client, calls } = captureClient()+ await client.foodAPI.list()+ expect(calls[0].params).toEqual({})+ })+})diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.tsindex 42a88db..d0bf243 100644--- a/packages/shared/src/client.ts+++ b/packages/shared/src/client.ts@@ -3,6 +3,7 @@ import * as types from './types'import { StorageAdapter, STORAGE_KEYS } from './storage'import { normalizeServerUrl } from './utils/serverUrl'import { networkFailureMessage } from './utils/networkError'+import { withLoggedOn, utcOffsetMinutes } from './utils/dateUtils'// Every API call lives under this versioned path. `origin` is an absolute server// origin for a cross-origin backend, or '' for the same-origin reverse proxy (web).@@ -141,7 +142,13 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})list: (params?: { limit?: number; offset?: number; q?: string }) =>api.get<{ data: types.Workout[] }>('/workouts', { params }).then(unwrap),get: (id: number) => api.get<{ data: types.Workout }>(`/workouts/${id}`).then(unwrap),- create: (data: any) => api.post<{ data: types.Workout }>('/workouts', data).then(unwrap),+ // A workout keeps its instant and records the offset it happened at, rather than+ // flattening to a day like the diary does — duration and ordering need the moment.+ create: (data: any) =>+ api.post<{ data: types.Workout }>('/workouts', {+ ...data,+ tz_offset_minutes: utcOffsetMinutes(data?.started_at),+ }).then(unwrap),update: (id: number, data: any) => api.put<{ data: types.Workout }>(`/workouts/${id}`, data).then(unwrap),delete: (id: number) => api.delete(`/workouts/${id}`),}@@ -192,18 +199,18 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})api.get<{ data: types.WeightLog[] }>('/weight', { params }).then(unwrap),get: (id: number) => api.get<{ data: types.WeightLog }>(`/weight/${id}`).then(unwrap),log: (data: { weight: number; notes?: string; logged_at?: string }) =>- api.post<{ data: types.WeightLog }>('/weight', data).then(unwrap),+ api.post<{ data: types.WeightLog }>('/weight', withLoggedOn(data)).then(unwrap),update: (id: number, data: { weight: number; notes?: string; logged_at?: string }) =>- api.patch<{ data: types.WeightLog }>(`/weight/${id}`, data).then(unwrap),+ api.patch<{ data: types.WeightLog }>(`/weight/${id}`, withLoggedOn(data)).then(unwrap),delete: (id: number) => api.delete(`/weight/${id}`),stats: () => api.get<{ data: types.WeightStats }>('/weight/stats').then(unwrap),}const foodAPI = {list: (date?: string) => api.get<{ data: types.FoodLog[] }>('/food', { params: { date } }).then(unwrap),- log: (data: any) => api.post<{ data: types.FoodLog }>('/food', data).then(unwrap),+ log: (data: any) => api.post<{ data: types.FoodLog }>('/food', withLoggedOn(data)).then(unwrap),get: (id: number) => api.get<{ data: types.FoodLog }>(`/food/${id}`).then(unwrap),- update: (id: number, data: any) => api.patch<{ data: types.FoodLog }>(`/food/${id}`, data).then(unwrap),+ update: (id: number, data: any) => api.patch<{ data: types.FoodLog }>(`/food/${id}`, withLoggedOn(data)).then(unwrap),delete: (id: number) => api.delete(`/food/${id}`),stats: (date?: string) => api.get<{ data: types.DailyStats }>('/food/stats', { params: { date } }).then(unwrap),history: (days = 30) => api.get<{ data: types.FoodHistoryPoint[] }>('/food/history', { params: { days } }).then(unwrap),diff --git a/packages/shared/src/stores/settings.test.ts b/packages/shared/src/stores/settings.test.tsnew file mode 100644index 0000000..2218667--- /dev/null+++ b/packages/shared/src/stores/settings.test.ts@@ -0,0 +1,141 @@+import { createSettingsStore } from './settings'+import { createMemoryStorage } from '../testing/memoryStorage'+import type { LyftrClient } from '../client'+import type { UserSettings } from '../types'++const serverSettings = (over: Partial<UserSettings> = {}): UserSettings => ({+ user_id: 1,+ weight_unit: 'lbs',+ calorie_target: 2000,+ protein_target: 150,+ carb_target: 250,+ fat_target: 65,+ workout_layout: 'list',+ rest_enabled: true,+ rest_seconds_default: 90,+ timezone: 'UTC',+ ...over,+})++// Records what updateSettings was called with so a test can assert the PATCH did or+// did not happen, and can control when it resolves.+function fakeClient(stored: UserSettings, opts: { fail?: boolean; defer?: boolean } = {}) {+ const calls: Partial<UserSettings>[] = []+ let release: (() => void) | undefined+ const gate = opts.defer ? new Promise<void>((r) => { release = r }) : Promise.resolve()++ const client = {+ userAPI: {+ getSettings: async () => stored,+ updateSettings: async (patch: Partial<UserSettings>) => {+ calls.push(patch)+ await gate+ if (opts.fail) throw new Error('network')+ return { ...stored, ...patch }+ },+ },+ } as unknown as LyftrClient++ return { client, calls, release: () => release?.() }+}++const flush = () => new Promise((r) => setTimeout(r, 0))++describe('settings store — timezone sync', () => {+ it('pushes the device zone up when it differs from the stored one', async () => {+ const { client, calls } = fakeClient(serverSettings({ timezone: 'UTC' }))+ const store = createSettingsStore(client, createMemoryStorage(), () => 'America/New_York')++ await store.getState().fetch()+ await flush()++ expect(calls).toEqual([{ timezone: 'America/New_York' }])+ expect(store.getState().settings.timezone).toBe('America/New_York')+ })++ it('does not PATCH when the stored zone already matches', async () => {+ const { client, calls } = fakeClient(serverSettings({ timezone: 'America/New_York' }))+ const store = createSettingsStore(client, createMemoryStorage(), () => 'America/New_York')++ await store.getState().fetch()+ await flush()++ expect(calls).toEqual([])+ })++ it('sends nothing when the platform cannot resolve a zone', async () => {+ // Hermes does not expose the device zone to JS, so mobile's detector can return+ // null. That must leave the server's value alone rather than writing a guess.+ const { client, calls } = fakeClient(serverSettings({ timezone: 'Europe/Berlin' }))+ const store = createSettingsStore(client, createMemoryStorage(), () => null)++ await store.getState().fetch()+ await flush()++ expect(calls).toEqual([])+ expect(store.getState().settings.timezone).toBe('Europe/Berlin')+ })++ it('sends nothing when no detector is injected at all', async () => {+ const { client, calls } = fakeClient(serverSettings())+ const store = createSettingsStore(client, createMemoryStorage())++ await store.getState().fetch()+ await flush()++ expect(calls).toEqual([])+ })++ it('survives a detector that throws', async () => {+ const { client, calls } = fakeClient(serverSettings())+ const store = createSettingsStore(client, createMemoryStorage(), () => {+ throw new Error('no Intl')+ })++ await expect(store.getState().fetch()).resolves.toBeUndefined()+ await flush()+ expect(calls).toEqual([])+ expect(store.getState().loaded).toBe(true)+ })++ it('swallows a failed PATCH and keeps the settings it already loaded', async () => {+ const { client } = fakeClient(serverSettings({ timezone: 'UTC', calorie_target: 2222 }), { fail: true })+ const store = createSettingsStore(client, createMemoryStorage(), () => 'America/New_York')++ await store.getState().fetch()+ await flush()++ expect(store.getState().loaded).toBe(true)+ expect(store.getState().settings.calorie_target).toBe(2222)+ })++ it('marks settings loaded without waiting for the timezone PATCH', async () => {+ // The sync is a background nicety. Awaiting it would hold every settings-gated+ // screen on its loading state behind a stalled write.+ const { client, release } = fakeClient(serverSettings({ timezone: 'UTC' }), { defer: true })+ const store = createSettingsStore(client, createMemoryStorage(), () => 'America/New_York')++ await store.getState().fetch()+ expect(store.getState().loaded).toBe(true)++ release()+ await flush()+ expect(store.getState().settings.timezone).toBe('America/New_York')+ })++ it('does not clobber a settings change made while the PATCH was in flight', async () => {+ // The PATCH response carries the pre-edit values for every other field, so+ // writing it wholesale would silently revert the user's edit.+ const { client, release } = fakeClient(serverSettings({ timezone: 'UTC', weight_unit: 'lbs' }), { defer: true })+ const store = createSettingsStore(client, createMemoryStorage(), () => 'America/New_York')++ await store.getState().fetch()+ store.setState((s) => ({ settings: { ...s.settings, weight_unit: 'kg' } }))++ release()+ await flush()++ expect(store.getState().settings.weight_unit).toBe('kg')+ expect(store.getState().settings.timezone).toBe('America/New_York')+ })+})diff --git a/packages/shared/src/stores/settings.ts b/packages/shared/src/stores/settings.tsindex 856adc0..465a0f8 100644--- a/packages/shared/src/stores/settings.ts+++ b/packages/shared/src/stores/settings.ts@@ -35,6 +35,7 @@ const BASE_DEFAULTS: types.UserSettings = {workout_layout: 'list',rest_enabled: true,rest_seconds_default: 90,+ timezone: 'UTC',}export interface SettingsStore {@@ -48,7 +49,41 @@ export interface SettingsStore {reset: () => void}-export function createSettingsStore(client: LyftrClient, storage: StorageAdapter) {+// Reports the device's IANA zone, or null when it can't be determined. Injected+// per platform because the two runtimes disagree: browsers answer through Intl,+// but Hermes does not expose the device zone to JS at all (a polyfilled Intl+// reports "UTC" everywhere), so mobile has to ask the OS via expo-localization.+// Returning null is the honest answer when detection fails — the store then sends+// nothing and the server keeps whatever it has.+export type TimezoneDetector = () => string | null++export function createSettingsStore(+ client: LyftrClient,+ storage: StorageAdapter,+ detectTimezone?: TimezoneDetector,+) {+ // Push the device zone up if it differs from what the server has. Runs after+ // every settings fetch, which both apps already do on launch, so travel and a+ // moved device are picked up without any explicit "sync timezone" step.+ //+ // Failures are swallowed: a wrong timezone degrades the day boundaries, but a+ // throw here would break loading settings entirely, which is far worse.+ const syncTimezone = async (current: types.UserSettings) => {+ if (!detectTimezone) return current+ let detected: string | null = null+ try {+ detected = detectTimezone()+ } catch {+ return current+ }+ if (!detected || detected === current.timezone) return current+ try {+ return await client.userAPI.updateSettings({ timezone: detected })+ } catch {+ return current+ }+ }+return create<SettingsStore>((set, get) => ({settings: BASE_DEFAULTS,loaded: false,@@ -58,7 +93,20 @@ export function createSettingsStore(client: LyftrClient, storage: StorageAdapterconst prefs = await clientPrefs(storage)try {const s = await client.userAPI.getSettings()+ // Render on what we already have, then reconcile the zone in the background.+ // Awaiting the PATCH would put a write on the critical path of loading+ // settings — on a stalled connection every screen that gates on `loaded`+ // waits for a socket timeout instead of showing data already in hand.set({ settings: { ...s, ...prefs }, loaded: true })+ void syncTimezone(s).then((synced) => {+ // Only the timezone is written back. Splatting the whole response would+ // undo anything the user changed while the PATCH was in flight — flipping+ // to kg mid-sync would silently revert, because the response carries the+ // pre-edit values for every other field.+ if (synced !== s) {+ set((state) => ({ settings: { ...state.settings, timezone: synced.timezone } }))+ }+ })} catch {set({ settings: { ...get().settings, ...prefs }, loaded: true })}diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.tsindex f4aeeff..c379846 100644--- a/packages/shared/src/types.ts+++ b/packages/shared/src/types.ts@@ -17,6 +17,8 @@ export interface UserSettings {// Client-only (device storage, not persisted server-side):rest_enabled?: boolean // master rest-timer on/offrest_seconds_default?: number // default rest seconds, seeds new exercises+ /** IANA zone the server buckets this user's day-scoped data in. */+ timezone: string}export interface Exercise {@@ -60,6 +62,8 @@ export interface Workout {notes?: stringduration: numberstarted_at: string+ /** UTC offset in minutes when the workout started, e.g. -240. Absent on pre-migration rows. */+ tz_offset_minutes?: numbercreated_at: stringexercises: WorkoutExercise[]// Present on the create response when finishing auto-progressed routine targets (#40).@@ -80,6 +84,8 @@ export interface WeightLog {weight: numbernotes?: stringlogged_at: string+ /** Calendar day the entry is filed under, YYYY-MM-DD. Stored server-side, never re-derived. */+ logged_on: stringcreated_at?: string}@@ -98,6 +104,8 @@ export interface FoodLog {barcode?: stringimage_url?: stringlogged_at: string+ /** Calendar day the entry is filed under, YYYY-MM-DD. Stored server-side, never re-derived. */+ logged_on: stringcreated_at?: string}@@ -232,6 +240,8 @@ export interface ActiveSession {program_day_id?: numbername: stringstarted_at: string+ /** UTC offset in minutes when the workout started, e.g. -240. Absent on pre-migration rows. */+ tz_offset_minutes?: numberexercises: ActiveSessionExercise[]device_id?: string}diff --git a/packages/shared/src/utils/dateUtils.test.ts b/packages/shared/src/utils/dateUtils.test.tsnew file mode 100644index 0000000..f53a071--- /dev/null+++ b/packages/shared/src/utils/dateUtils.test.ts@@ -0,0 +1,132 @@+import { todayStr, dayToInstant, instantToDay, entryDay, workoutDay } from './dateUtils'++const hours = (from: string, to: string) =>+ (new Date(to).getTime() - new Date(from).getTime()) / 3_600_000+++describe('dayToInstant', () => {+ it('defaults to local noon, expressed in UTC', () => {+ expect(dayToInstant('2026-06-15')).toBe('2026-06-15T16:00:00.000Z')+ })++ it('round-trips through instantToDay', () => {+ expect(instantToDay(dayToInstant('2026-01-31'))).toBe('2026-01-31')+ expect(instantToDay(dayToInstant('2026-11-01'))).toBe('2026-11-01')+ })++ // The bug this replaced: `new Date('2026-06-15')` parses as UTC midnight, which is+ // the previous evening for anyone west of UTC, so the entry landed a day early.+ it('never lands on the previous day west of UTC', () => {+ expect(instantToDay(dayToInstant('2026-06-15'))).toBe('2026-06-15')+ })++ it('keeps the original time-of-day when moving an existing entry', () => {+ const original = new Date(2026, 5, 15, 18, 30, 0).toISOString()+ const moved = dayToInstant('2026-06-20', original)+ expect(instantToDay(moved)).toBe('2026-06-20')+ expect(new Date(moved).getHours()).toBe(18)+ expect(new Date(moved).getMinutes()).toBe(30)+ })++ it('falls back to noon when the previous timestamp is unusable', () => {+ expect(dayToInstant('2026-06-15', 'not-a-date')).toBe(dayToInstant('2026-06-15'))+ })+})++describe('todayStr', () => {+ it('formats as YYYY-MM-DD', () => {+ expect(todayStr()).toMatch(/^\d{4}-\d{2}-\d{2}$/)+ })+})++describe('todayStr — the date a form prefills', () => {+ // The mobile New Workout screen seeded its date with+ // `new Date().toISOString().slice(0, 10)`, the UTC day. West of UTC those differ+ // for the last hours of every evening, so the form offered tomorrow and the entry+ // was saved there. Suites run under America/New_York (see jest.config / the web+ // test script), so 23:00 local is already tomorrow in UTC.+ const at = (iso: string, fn: () => string) => {+ const RealDate = Date+ // @ts-expect-error — narrow stub, only the no-arg constructor is used here+ globalThis.Date = class extends RealDate {+ constructor(...args: unknown[]) {+ // @ts-expect-error — passthrough+ super(...(args.length ? args : [iso]))+ }+ static now() { return new RealDate(iso).getTime() }+ }+ try { return fn() } finally { globalThis.Date = RealDate }+ }++ it('returns the local day, not the UTC day, late in the evening', () => {+ // 2026-08-08T23:30 in New York is 2026-08-09T03:30Z.+ const local = at('2026-08-09T03:30:00.000Z', () => todayStr())+ expect(local).toBe('2026-08-08')+ })++ it('differs from the UTC slice the regression used', () => {+ const iso = '2026-08-09T03:30:00.000Z'+ const utcSlice = iso.slice(0, 10)+ const local = at(iso, () => todayStr())+ expect(utcSlice).toBe('2026-08-09')+ expect(local).not.toBe(utcSlice)+ })++ it('round-trips into an instant that stays on the same local day', () => {+ const local = at('2026-08-09T03:30:00.000Z', () => todayStr())+ expect(instantToDay(dayToInstant(local))).toBe(local)+ })+})++describe('entryDay — the server is the source of truth', () => {+ it('uses the stored day even when the device would derive another one', () => {+ // Filed on the 4th in New York (16:00Z). A device in Tokyo puts that instant on+ // the 5th. Before the day was stored, that re-derivation is what moved entries —+ // and on the edit screens it got saved back.+ expect(entryDay({ logged_on: '2026-08-04', logged_at: '2026-08-04T16:00:00.000Z' }))+ .toBe('2026-08-04')+ })++ it('falls back to the instant when the server sent no day', () => {+ // A response from a server older than the column. Suites run in America/New_York.+ expect(entryDay({ logged_at: '2026-08-04T16:00:00.000Z' })).toBe('2026-08-04')+ })++ it('treats an empty stored day as absent rather than as a day', () => {+ expect(entryDay({ logged_on: '', logged_at: '2026-08-04T16:00:00.000Z' })).toBe('2026-08-04')+ })+})++describe('workoutDay — recovered from the recorded offset', () => {+ it('applies the offset rather than the device zone', () => {+ // 16:00Z at -240 is noon on the 4th. Correct from any device, anywhere.+ expect(workoutDay({ started_at: '2026-08-04T16:00:00.000Z', tz_offset_minutes: -240 }))+ .toBe('2026-08-04')+ })++ it('keeps the day the workout happened on across the UTC boundary', () => {+ // 02:00Z on the 5th, logged at -240, was 22:00 on the 4th where it happened.+ expect(workoutDay({ started_at: '2026-08-05T02:00:00.000Z', tz_offset_minutes: -240 }))+ .toBe('2026-08-04')+ })++ it('handles a positive offset past midnight the other way', () => {+ // 16:00Z at +540 (Tokyo) is 01:00 on the 5th.+ expect(workoutDay({ started_at: '2026-08-04T16:00:00.000Z', tz_offset_minutes: 540 }))+ .toBe('2026-08-05')+ })++ it('supports a half-hour offset', () => {+ // Kathmandu, +5:45. 20:00Z on the 4th is 01:45 on the 5th.+ expect(workoutDay({ started_at: '2026-08-04T20:00:00.000Z', tz_offset_minutes: 345 }))+ .toBe('2026-08-05')+ })++ it('falls back to the device zone for a row written before the offset existed', () => {+ expect(workoutDay({ started_at: '2026-08-04T16:00:00.000Z' })).toBe('2026-08-04')+ })++ it('does not throw on an unparseable instant', () => {+ expect(() => workoutDay({ started_at: 'nonsense', tz_offset_minutes: -240 })).not.toThrow()+ })+})diff --git a/packages/shared/src/utils/dateUtils.ts b/packages/shared/src/utils/dateUtils.tsindex 6a13c20..cd377dd 100644--- a/packages/shared/src/utils/dateUtils.ts+++ b/packages/shared/src/utils/dateUtils.ts@@ -14,27 +14,117 @@ export const todayStr = (): string => {return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`}++/**- * Convert a YYYY-MM-DD calendar date to an ISO timestamp anchored at the user's- * local noon, then expressed in UTC. Noon-anchoring keeps the entry on the intended- * calendar day for every timezone within ±12h.+ * The calendar day an instant falls on, in the device's local timezone.*- * Built without `new Date('YYYY-MM-DDTHH:MM:SS')` because old mobile Safari- * (pre-iOS 14.5) parsed that as UTC instead of local; the explicit-component- * constructor is locale-safe everywhere.+ * The inverse of `dayToInstant`, and the read half of the same loop: load an entry,+ * show its day in a date field, save the picked day back as an instant. The pair is+ * lossy in one direction only — this discards the time, which is why the other one+ * takes the previous timestamp to put it back.*/-export const dayToIsoNoon = (yyyyMmDd: string): string => {+export const instantToDay = (iso: string): string => {+ const d = new Date(iso)+ const pad = (n: number) => String(n).padStart(2, '0')+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`+}++/**+ * The instant to store for a user-picked calendar day. The inverse of+ * `instantToDay`.+ *+ * One rule for every date the user chooses, replacing the four this codebase grew:+ * a fake noon anchor, a bare `new Date(ymd)` (which parses as UTC midnight and put+ * west-of-UTC users on the previous day), a real `new Date()`, and a local+ * keep-the-time helper that existed in exactly one screen.+ *+ * `previousIso` is the entry's current timestamp when editing: the day moves and the+ * time-of-day is preserved, so re-dating an entry doesn't silently restamp when it+ * happened. Without it the time defaults to local noon — furthest from either+ * midnight, so the entry stays on the intended day under any offset the server might+ * later resolve it in.+ *+ * Built from explicit components rather than `new Date('YYYY-MM-DDTHH:MM:SS')`:+ * pre-iOS 14.5 Safari parsed that string form as UTC, the same class of bug this+ * function exists to remove.+ */+export const dayToInstant = (yyyyMmDd: string, previousIso?: string): string => {const [y, m, d] = yyyyMmDd.split('-').map(Number)- return new Date(y, m - 1, d, 12, 0, 0, 0).toISOString()+ const prev = previousIso ? new Date(previousIso) : null+ const valid = prev && !Number.isNaN(prev.getTime())+ return new Date(+ y, (m ?? 1) - 1, d ?? 1,+ valid ? prev.getHours() : 12,+ valid ? prev.getMinutes() : 0,+ valid ? prev.getSeconds() : 0,+ 0,+ ).toISOString()}/**- * Extract a YYYY-MM-DD string in the device's local timezone from any ISO- * timestamp. Use this to populate date fields when editing an existing entry so the- * displayed date matches what the user originally picked.+ * The local calendar day `n` days before today.+ *+ * Exists so range queries build their day the same way everything else does. The+ * weight chart previously used date-fns `format(subDays(new Date(), n), 'yyyy-MM-dd')`,+ * which is a fourth path to a day string and drifts from the server's idea of one:+ * the server resolves a bare day through the *stored* zone, so a device-derived day+ * silently clips the oldest point whenever the two disagree.*/-export const isoToDayInput = (iso: string): string => {- const d = new Date(iso)- const pad = (n: number) => String(n).padStart(2, '0')- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`+export const daysAgoStr = (n: number): string => {+ const d = new Date()+ d.setDate(d.getDate() - n)+ return instantToDay(d.toISOString())+}++/**+ * The device's UTC offset in minutes at `iso` (default: now). New York in summer is+ * -240.+ *+ * Sign is flipped from `Date.getTimezoneOffset()`, which counts minutes *behind* UTC+ * (+240 for New York) — the opposite of every other convention, including the one the+ * server stores. Resolved at the given instant rather than now, so a workout logged+ * in July keeps the summer offset even if it is saved in December.+ */+export const utcOffsetMinutes = (iso?: string): number =>+ -(iso ? new Date(iso) : new Date()).getTimezoneOffset()++/**+ * Attach the calendar day an entry belongs to, for diary writes (food, weight).+ *+ * The day is what the server files the entry under, permanently — it is never+ * re-derived from the account's zone afterwards, so travelling cannot move it. Doing+ * this once in the API layer rather than at each call site means no screen can forget+ * it: a missing `logged_on` silently falls back to the server's guess.+ */+export const withLoggedOn = <T extends { logged_at?: string }>(data: T): T & { logged_on: string } => ({+ ...data,+ logged_on: instantToDay(data.logged_at ?? new Date().toISOString()),+})++/**+ * The day a diary entry belongs to.+ *+ * Prefer the server's stored answer over re-deriving one. `instantToDay(logged_at)`+ * resolves in the *device's* zone, which stopped being the same question the moment+ * the day became a stored column: an entry filed on the 4th in New York, viewed from+ * Tokyo, re-derives as the 5th. Screens that then save that value move the entry.+ * The fallback covers responses from a server older than the column.+ */+export const entryDay = (e: { logged_on?: string; logged_at: string }): string =>+ e.logged_on || instantToDay(e.logged_at)++/**+ * The day a workout happened, from the offset recorded when it started.+ *+ * A workout stores an instant plus its offset rather than a day, so the local day is+ * recovered by applying one to the other. Reading the shifted value back in UTC is+ * correct precisely *because* the offset has already been applied — this is the one+ * place `slice(0, 10)` names a local day rather than a UTC one. Falls back to the+ * device zone for rows written before the offset existed.+ */+export const workoutDay = (w: { started_at: string; tz_offset_minutes?: number }): string => {+ if (w.tz_offset_minutes == null) return instantToDay(w.started_at)+ const shifted = new Date(new Date(w.started_at).getTime() + w.tz_offset_minutes * 60_000)+ return Number.isNaN(shifted.getTime()) ? instantToDay(w.started_at) : shifted.toISOString().slice(0, 10)}diff --git a/web/src/components/QuickWeighInSheet.tsx b/web/src/components/QuickWeighInSheet.tsxindex 526077b..32fad3a 100644--- a/web/src/components/QuickWeighInSheet.tsx+++ b/web/src/components/QuickWeighInSheet.tsx@@ -5,7 +5,7 @@ import { weightAPI } from '../services/api'import { useSettingsStore, weightShort, displayToLbs , weightError, maxWeight } from '../stores/settings'import { useBodyScrollLock } from '../hooks/useBodyScrollLock'import { useEscapeKey } from '../hooks/useEscapeKey'-import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'+import { todayStr, dayToInstant, entryDay } from '../utils/dateUtils'import StepperTile from './ui/StepperTile'import NumberField from './ui/NumberField'import { BODYWEIGHT_STEP, clampStep } from '../utils/number'@@ -62,7 +62,7 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,return}- if (!duplicateWarningDismissedRef.current && lastLog && isoToDayInput(lastLog.logged_at) === date) {+ if (!duplicateWarningDismissedRef.current && lastLog && entryDay(lastLog) === date) {setShowDuplicateWarning(true)return}@@ -74,7 +74,7 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,const log = await weightAPI.log({weight: displayToLbs(w, settings.weight_unit),notes: notes.trim(),- logged_at: dayToIsoNoon(date),+ logged_at: dayToInstant(date),})onSuccess(log)onClose()diff --git a/web/src/pages/AddWorkout.tsx b/web/src/pages/AddWorkout.tsxindex 77c3221..e85cd5c 100644--- a/web/src/pages/AddWorkout.tsx+++ b/web/src/pages/AddWorkout.tsx@@ -8,6 +8,7 @@ import ExercisePicker from '../components/ExercisePicker'import ProgramPicker from '../components/ProgramPicker'import RestPicker from '../components/RestPicker'import * as types from '../types'+import { todayStr, dayToInstant } from '../utils/dateUtils'interface WorkoutFormData {name: string@@ -26,7 +27,7 @@ export default function AddWorkout() {const [loading, setLoading] = useState(false)const [error, setError] = useState('')const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})- const [formData, setFormData] = useState<WorkoutFormData>({ name: '', notes: '', duration: 0, date: new Date().toISOString().slice(0, 10), exercises: [] })+ const [formData, setFormData] = useState<WorkoutFormData>({ name: '', notes: '', duration: 0, date: todayStr(), exercises: [] })useEffect(() => { if (error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error])@@ -92,7 +93,7 @@ export default function AddWorkout() {const payload = {...formData,duration: formData.duration * 60,- started_at: new Date(formData.date).toISOString(),+ started_at: dayToInstant(formData.date),exercises: formData.exercises.map(ex => ({...ex,sets: ex.sets.map(s => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),@@ -145,7 +146,7 @@ export default function AddWorkout() {<CalendarDays className="w-4 h-4 text-brand-500" /><label className="label">Date</label></div>- <input type="date" value={formData.date} onChange={e => setFormData(prev => ({ ...prev, date: e.target.value }))} className="input" max={new Date().toISOString().slice(0, 10)} />+ <input type="date" value={formData.date} onChange={e => setFormData(prev => ({ ...prev, date: e.target.value }))} className="input" max={todayStr()} /></div><div>diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsxindex 313db55..95d4a0a 100644--- a/web/src/pages/Dashboard.tsx+++ b/web/src/pages/Dashboard.tsx@@ -16,6 +16,7 @@ import { workoutAPI, foodAPI, weightAPI, userAPI, programAPI } from '../servicesimport { useWorkoutSession } from '../stores/workoutSession'import { useAuthStore } from '../stores/auth'import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'+import { workoutDay, entryDay } from '../utils/dateUtils'import { useNavigate, Link } from 'react-router-dom'import * as types from '../types'import { muscleColor } from '../utils/exerciseUtils'@@ -39,7 +40,7 @@ const DEFAULT_FOOD: types.DailyStats = {}const DEFAULT_SETTINGS: types.UserSettings = {user_id: 0, weight_unit: 'lbs', calorie_target: 2000,- protein_target: 150, carb_target: 250, fat_target: 65,+ protein_target: 150, carb_target: 250, fat_target: 65, timezone: 'UTC',}// Hex colors for recharts (can't use Tailwind classes)@@ -215,7 +216,9 @@ export default function Dashboard() {// map dateString → countconst workoutDayMap = new Map<string, number>()workouts.forEach(w => {- const k = format(new Date(w.started_at), 'yyyy-MM-dd')+ // The workout's own day, so the heatmap counts it under the day it happened+ // rather than the day the viewing device would place that instant on.+ const k = workoutDay(w)workoutDayMap.set(k, (workoutDayMap.get(k) || 0) + 1)})// chunk into weeks@@ -265,7 +268,7 @@ export default function Dashboard() {// Weight sparklineconst sparkData = [...weightLogs].reverse().map(l => ({- date: format(new Date(l.logged_at), 'M/d'),+ date: format(new Date(entryDay(l) + 'T12:00:00'), 'M/d'),weight: displayWeight(l.weight, settings.weight_unit),}))@@ -439,7 +442,7 @@ export default function Dashboard() {{/* Current week day dots */}<div className="flex items-center justify-between mt-4 px-1">{weekDays.map((day, i) => {- const hasWorkout = workouts.some(w => isSameDay(new Date(w.started_at), day))+ const hasWorkout = workouts.some(w => workoutDay(w) === format(day, 'yyyy-MM-dd'))const isToday = isSameDay(day, TODAY)const isFuture = day > TODAYreturn (@@ -544,7 +547,7 @@ export default function Dashboard() {<div className="min-w-0"><p className="text-sm font-semibold text-tx-primary truncate">{lastWorkout.name}</p><p className="text-xs text-tx-muted mt-0.5">- {format(new Date(lastWorkout.started_at), 'MMM d')}+ {format(new Date(workoutDay(lastWorkout) + 'T12:00:00'), 'MMM d')}{mins > 0 && ` · ${mins} min`}{totalSets > 0 && ` · ${totalSets} sets`}{totalVolume > 0 && ` · ${totalVolume.toLocaleString()} ${wUnit}`}diff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsxindex c4c0046..654ee61 100644--- a/web/src/pages/LogFood.tsx+++ b/web/src/pages/LogFood.tsx@@ -6,7 +6,7 @@ import {Coffee, Sun, Moon, Cookie, ChevronRight,} from 'lucide-react'import { foodAPI, savedFoodsAPI } from '../services/api'-import { todayStr, dayToIsoNoon } from '../utils/dateUtils'+import { todayStr, dayToInstant } from '../utils/dateUtils'import { MACRO_COLORS } from '../utils/macroColors'import BarcodeScanner from '../components/BarcodeScanner'import IconButton from '../components/ui/IconButton'@@ -202,7 +202,7 @@ export default function LogFood() {servings,serving_size: selected.serving_size ?? '',image_url: selected.image_url ?? '',- logged_at: dayToIsoNoon(date),+ logged_at: dayToInstant(date),}if (editId) {await foodAPI.update(editId, payload)diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsxindex b835a6c..a5bfe7f 100644--- a/web/src/pages/Weight.tsx+++ b/web/src/pages/Weight.tsx@@ -1,6 +1,6 @@import { useState, useEffect, useMemo, useRef } from 'react'import { TrendingDown, TrendingUp, Minus, Plus, Calendar, Sunrise, AlertCircle, ChevronRight, Scale, Activity, ArrowDown, ArrowUp, X } from 'lucide-react'-import { format, subDays } from 'date-fns'+import { format } from 'date-fns'import { Link } from 'react-router-dom'import { HelpTip } from '../components/Tooltip'import Loading from '../components/Loading'@@ -11,7 +11,7 @@ import StepperTile from '../components/ui/StepperTile'import NumberField from '../components/ui/NumberField'import { BODYWEIGHT_STEP, clampStep } from '../utils/number'import { useServerInfiniteList } from '../hooks/useServerInfiniteList'-import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'+import { todayStr, daysAgoStr, dayToInstant, entryDay } from '../utils/dateUtils'import { weightAPI } from '../services/api'import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs, displayWeight, round1 , weightError, maxWeight } from '../stores/settings'import * as types from '../types'@@ -224,7 +224,7 @@ export default function Weight() {useEffect(() => {const days = PERIOD_DAYS[period]- const from = days != null ? format(subDays(new Date(), days), 'yyyy-MM-dd') : undefined+ const from = days != null ? daysAgoStr(days) : undefinedweightAPI.list({ limit: 1000, from }).then(data => setChartLogs(data || [])).catch(() => { /* chart keeps the previous series rather than blanking on a failed refetch */ })@@ -273,7 +273,7 @@ export default function Weight() {return}- if (!duplicateWarningDismissedRef.current && items.length > 0 && isoToDayInput(items[0].logged_at) === newDate) {+ if (!duplicateWarningDismissedRef.current && items.length > 0 && entryDay(items[0]) === newDate) {setShowDuplicateWarning(true)return}@@ -286,7 +286,7 @@ export default function Weight() {const real = await weightAPI.log({weight: displayToLbs(w, settings.weight_unit),notes: newNotes.trim(),- logged_at: dayToIsoNoon(newDate),+ logged_at: dayToInstant(newDate),})setNewWeight(String(displayWeight(real.weight, settings.weight_unit)))setNewNotes('')@@ -296,7 +296,7 @@ export default function Weight() {reload()weightAPI.stats().then(setStats).catch(() => {})const days = PERIOD_DAYS[period]- const from = days != null ? format(subDays(new Date(), days), 'yyyy-MM-dd') : undefined+ const from = days != null ? daysAgoStr(days) : undefinedweightAPI.list({ limit: 1000, from }).then(data => setChartLogs(data || [])).catch(() => {})} catch (err: any) {setError(err?.response?.data?.error || 'Failed to log weight')@@ -555,7 +555,7 @@ export default function Weight() {{Math.round(displayW)} {wUnit}</p><p className="text-xs text-tx-muted mt-0.5">- {format(new Date(entry.logged_at), 'MMM d, yyyy')}+ {format(new Date(entryDay(entry) + 'T12:00:00'), 'MMM d, yyyy')}</p>{(deltaLbs !== 0 || entry.notes) && (<div className="flex items-center gap-x-2 mt-0.5 min-w-0 overflow-hidden">diff --git a/web/src/pages/WeightDetail.tsx b/web/src/pages/WeightDetail.tsxindex 6d6159a..1dd8f16 100644--- a/web/src/pages/WeightDetail.tsx+++ b/web/src/pages/WeightDetail.tsx@@ -7,7 +7,7 @@ import { weightAPI } from '../services/api'import { useSettingsStore, weightShort, displayWeight, weightError, maxWeight, resolveWeightLbs } from '../stores/settings'import { useBodyScrollLock } from '../hooks/useBodyScrollLock'import { useEscapeKey } from '../hooks/useEscapeKey'-import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'+import { todayStr, dayToInstant, entryDay } from '../utils/dateUtils'import StepperTile from '../components/ui/StepperTile'import NumberField from '../components/ui/NumberField'import { BODYWEIGHT_STEP, clampStep } from '../utils/number'@@ -44,7 +44,7 @@ export default function WeightDetail() {.then(data => {setLog(data)setEditWeight(String(displayWeight(data.weight, settings.weight_unit)))- setEditDate(isoToDayInput(data.logged_at))+ setEditDate(entryDay(data))setEditNotes(data.notes ?? '')}).catch(err => setError(err?.response?.data?.error || 'Failed to load entry'))@@ -54,7 +54,7 @@ export default function WeightDetail() {const startEdit = () => {if (!log) returnsetEditWeight(String(displayWeight(log.weight, settings.weight_unit)))- setEditDate(isoToDayInput(log.logged_at))+ setEditDate(entryDay(log))setEditNotes(log.notes ?? '')setEditError('')setEditing(true)@@ -75,7 +75,7 @@ export default function WeightDetail() {const updated = await weightAPI.update(log.id, {weight: resolveWeightLbs(editWeight, log.weight, settings.weight_unit),notes: editNotes.trim(),- logged_at: dayToIsoNoon(editDate),+ logged_at: dayToInstant(editDate, log.logged_at),})setLog(updated)setEditing(false)@@ -164,7 +164,7 @@ export default function WeightDetail() {<span className="text-tx-muted text-lg mb-1">{wUnit}</span></div><p className="text-sm text-tx-muted mt-1">- {format(new Date(log.logged_at), 'EEEE, MMMM d, yyyy')}+ {format(new Date(entryDay(log) + 'T12:00:00'), 'EEEE, MMMM d, yyyy')}</p>{log.notes && (<p className="text-sm text-tx-secondary mt-2 italic">"{log.notes}"</p>@@ -248,7 +248,7 @@ export default function WeightDetail() {<div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" /><h3 className="font-display font-bold text-lg text-tx-primary mb-1">Delete Entry?</h3><p className="text-sm text-tx-muted mb-5">- {format(new Date(log.logged_at), 'MMMM d, yyyy')} · {displayWeight(log.weight, settings.weight_unit)} {wUnit} will be permanently deleted.+ {format(new Date(entryDay(log) + 'T12:00:00'), 'MMMM d, yyyy')} · {displayWeight(log.weight, settings.weight_unit)} {wUnit} will be permanently deleted.</p><div className="flex gap-3"><buttondiff --git a/web/src/pages/WorkoutDetail.tsx b/web/src/pages/WorkoutDetail.tsxindex 6dfb451..b997d73 100644--- a/web/src/pages/WorkoutDetail.tsx+++ b/web/src/pages/WorkoutDetail.tsx@@ -9,6 +9,7 @@ import { workoutAPI } from '../services/api'import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'import * as types from '../types'import { muscleColor } from '../utils/exerciseUtils'+import { workoutDay } from '../utils/dateUtils'function SetChip({ set, isBest, unit }: { set: types.Set; isBest: boolean; unit: string }) {return (@@ -153,7 +154,7 @@ export default function WorkoutDetail() {<div className="min-w-0 flex-1"><h1 className="font-display font-bold text-xl text-tx-primary leading-tight">{workout.name}</h1><p className="text-sm text-tx-muted mt-0.5">- {format(new Date(workout.started_at), 'EEEE, MMMM d, yyyy')}+ {format(new Date(workoutDay(workout) + 'T12:00:00'), 'EEEE, MMMM d, yyyy')}</p></div></div>diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsxindex a6ddccb..c7a73dd 100644--- a/web/src/pages/Workouts.tsx+++ b/web/src/pages/Workouts.tsx@@ -11,6 +11,7 @@ import { useServerInfiniteList } from '../hooks/useServerInfiniteList'import { workoutAPI } from '../services/api'import { useSettingsStore, weightShort, displayVolume } from '../stores/settings'import * as types from '../types'+import { workoutDay } from '../utils/dateUtils'function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; onEdit: (id: number) => void; onDelete: (id: number) => void }) {const navigate = useNavigate()@@ -98,7 +99,7 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on)}<div className="min-w-0 flex-1"><p className="text-sm font-semibold text-tx-primary truncate">{workout.name}</p>- <p className="text-xs text-tx-muted mt-0.5 whitespace-nowrap">{format(new Date(workout.started_at), 'MMM d, yyyy')}</p>+ <p className="text-xs text-tx-muted mt-0.5 whitespace-nowrap">{format(new Date(workoutDay(workout) + 'T12:00:00'), 'MMM d, yyyy')}</p><div className="flex items-center gap-x-2 mt-0.5 min-w-0 overflow-hidden">{durationMin > 0 && (<span className="flex items-center gap-1 text-xs text-tx-muted whitespace-nowrap">diff --git a/web/src/services/api.ts b/web/src/services/api.tsindex 222c01f..0f47bb1 100644--- a/web/src/services/api.ts+++ b/web/src/services/api.ts@@ -1,6 +1,7 @@import axios, { AxiosInstance } from 'axios'import * as types from '../types'import { normalizeServerUrl } from '../stores/server'+import { withLoggedOn, utcOffsetMinutes } from '../utils/dateUtils'// Every API call lives under this versioned path. `origin` is an absolute server// origin for a cross-origin backend, or '' for the same-origin reverse proxy.@@ -122,7 +123,13 @@ export const workoutAPI = {list: (params?: { limit?: number; offset?: number; q?: string }) =>api.get<{ data: types.Workout[] }>('/workouts', { params }).then(res => unwrap(res)),get: (id: number) => api.get<{ data: types.Workout }>(`/workouts/${id}`).then(res => unwrap(res)),- create: (data: any) => api.post<{ data: types.Workout }>('/workouts', data).then(res => unwrap(res)),+ // A workout keeps its instant and records the offset it happened at, rather than+ // flattening to a day like the diary does — duration and ordering need the moment.+ create: (data: any) =>+ api.post<{ data: types.Workout }>('/workouts', {+ ...data,+ tz_offset_minutes: utcOffsetMinutes(data?.started_at),+ }).then(res => unwrap(res)),update: (id: number, data: any) => api.put<{ data: types.Workout }>(`/workouts/${id}`, data).then(res => unwrap(res)),delete: (id: number) => api.delete(`/workouts/${id}`),}@@ -170,18 +177,18 @@ export const weightAPI = {api.get<{ data: types.WeightLog[] }>('/weight', { params }).then(res => unwrap(res)),get: (id: number) => api.get<{ data: types.WeightLog }>(`/weight/${id}`).then(res => unwrap(res)),log: (data: { weight: number; notes?: string; logged_at?: string }) =>- api.post<{ data: types.WeightLog }>('/weight', data).then(res => unwrap(res)),+ api.post<{ data: types.WeightLog }>('/weight', withLoggedOn(data)).then(res => unwrap(res)),update: (id: number, data: { weight: number; notes?: string; logged_at?: string }) =>- api.patch<{ data: types.WeightLog }>(`/weight/${id}`, data).then(res => unwrap(res)),+ api.patch<{ data: types.WeightLog }>(`/weight/${id}`, withLoggedOn(data)).then(res => unwrap(res)),delete: (id: number) => api.delete(`/weight/${id}`),stats: () => api.get<{ data: types.WeightStats }>('/weight/stats').then(res => unwrap(res)),}export const foodAPI = {list: (date?: string) => api.get<{ data: types.FoodLog[] }>('/food', { params: { date } }).then(res => unwrap(res)),- log: (data: any) => api.post<{ data: types.FoodLog }>('/food', data).then(res => unwrap(res)),+ log: (data: any) => api.post<{ data: types.FoodLog }>('/food', withLoggedOn(data)).then(res => unwrap(res)),get: (id: number) => api.get<{ data: types.FoodLog }>(`/food/${id}`).then(res => unwrap(res)),- update: (id: number, data: any) => api.patch<{ data: types.FoodLog }>(`/food/${id}`, data).then(res => unwrap(res)),+ update: (id: number, data: any) => api.patch<{ data: types.FoodLog }>(`/food/${id}`, withLoggedOn(data)).then(res => unwrap(res)),delete: (id: number) => api.delete(`/food/${id}`),stats: (date?: string) => api.get<{ data: types.DailyStats }>('/food/stats', { params: { date } }).then(res => unwrap(res)),history: (days = 30) => api.get<{ data: types.FoodHistoryPoint[] }>('/food/history', { params: { days } }).then(res => unwrap(res)),diff --git a/web/src/stores/settings.ts b/web/src/stores/settings.tsindex 9be2021..ec38536 100644--- a/web/src/stores/settings.ts+++ b/web/src/stores/settings.ts@@ -35,6 +35,32 @@ const DEFAULTS: types.UserSettings = {carb_target: 250,fat_target: 65,...clientPrefs(),+ timezone: 'UTC',+}++// Browsers expose the device zone through Intl reliably (unlike Hermes on mobile,+// which needs expo-localization). Guarded anyway: a null return sends nothing and+// leaves whatever the server already has.+const detectTimezone = (): string | null => {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || null+ } catch {+ return null+ }+}++// Push the device zone up when it differs from the server's. Runs on every settings+// fetch — which App.tsx already does on load — so moving or travelling is picked up+// without an explicit sync step. Failures are swallowed: a stale zone shifts day+// boundaries, but throwing here would break settings loading entirely.+const syncTimezone = async (current: types.UserSettings): Promise<types.UserSettings> => {+ const detected = detectTimezone()+ if (!detected || detected === current.timezone) return current+ try {+ return await userAPI.updateSettings({ timezone: detected })+ } catch {+ return current+ }}export const useSettingsStore = create<SettingsStore>((set, get) => ({@@ -45,7 +71,16 @@ export const useSettingsStore = create<SettingsStore>((set, get) => ({if (get().loaded) returntry {const s = await userAPI.getSettings()+ // Render on what we already have; reconcile the zone in the background so a+ // stalled PATCH can't hold every settings-gated screen on its loading state.set({ settings: { ...s, ...clientPrefs() }, loaded: true })+ void syncTimezone(s).then(synced => {+ // Only the timezone is written back — see the note in the shared store: a+ // full splat would revert a settings edit made while the PATCH was in flight.+ if (synced !== s) {+ set(state => ({ settings: { ...state.settings, timezone: synced.timezone } }))+ }+ })} catch {set({ loaded: true })}diff --git a/web/src/types.ts b/web/src/types.tsindex c48184a..49b4f98 100644--- a/web/src/types.ts+++ b/web/src/types.ts@@ -16,6 +16,8 @@ export interface UserSettings {// Client-only (localStorage, not persisted server-side):rest_enabled?: boolean // master rest-timer on/offrest_seconds_default?: number // default rest seconds, seeds new exercises+ /** IANA zone the server buckets this user's day-scoped data in. */+ timezone: string}export interface Exercise {@@ -59,6 +61,8 @@ export interface Workout {notes?: stringduration: numberstarted_at: string+ /** UTC offset in minutes when the workout started, e.g. -240. Absent on pre-migration rows. */+ tz_offset_minutes?: numbercreated_at: stringexercises: WorkoutExercise[]// Present on the create response when finishing auto-progressed routine targets (#40).@@ -79,6 +83,8 @@ export interface WeightLog {weight: numbernotes?: stringlogged_at: string+ /** Calendar day the entry is filed under, YYYY-MM-DD. Stored server-side, never re-derived. */+ logged_on: stringcreated_at?: string}@@ -97,6 +103,8 @@ export interface FoodLog {barcode?: stringimage_url?: stringlogged_at: string+ /** Calendar day the entry is filed under, YYYY-MM-DD. Stored server-side, never re-derived. */+ logged_on: stringcreated_at?: string}@@ -231,6 +239,8 @@ export interface ActiveSession {program_day_id?: numbername: stringstarted_at: string+ /** UTC offset in minutes when the workout started, e.g. -240. Absent on pre-migration rows. */+ tz_offset_minutes?: numberexercises: ActiveSessionExercise[]device_id?: string}diff --git a/web/src/utils/dateUtils.test.ts b/web/src/utils/dateUtils.test.tsindex 194f48b..589c2ee 100644--- a/web/src/utils/dateUtils.test.ts+++ b/web/src/utils/dateUtils.test.ts@@ -1,33 +1,50 @@import { describe, it, expect, vi, afterEach } from 'vitest'-import { todayStr, dayToIsoNoon, isoToDayInput } from './dateUtils'+import { todayStr, dayToInstant, instantToDay } from './dateUtils'// Runs under TZ=America/New_York (set in the npm script) so these local<->UTC// assertions are deterministic and exercise a real, DST-aware non-UTC offset.-describe('dayToIsoNoon', () => {- it('anchors a calendar day at local noon, expressed in UTC (EDT, summer)', () => {- // Noon EDT (UTC-4) = 16:00 UTC- expect(dayToIsoNoon('2026-04-25')).toBe('2026-04-25T16:00:00.000Z')+describe('dayToInstant', () => {+ it('defaults to local noon, expressed in UTC', () => {+ expect(dayToInstant('2026-06-15')).toBe('2026-06-15T16:00:00.000Z')})- it('accounts for daylight saving (EST, winter)', () => {- // Noon EST (UTC-5) = 17:00 UTC- expect(dayToIsoNoon('2026-01-15')).toBe('2026-01-15T17:00:00.000Z')+ it('round-trips through instantToDay', () => {+ expect(instantToDay(dayToInstant('2026-01-31'))).toBe('2026-01-31')+ expect(instantToDay(dayToInstant('2026-11-01'))).toBe('2026-11-01')+ })++ // The bug this replaced: `new Date('2026-06-15')` parses as UTC midnight, which is+ // the previous evening for anyone west of UTC, so the entry landed a day early.+ it('never lands on the previous day west of UTC', () => {+ expect(instantToDay(dayToInstant('2026-06-15'))).toBe('2026-06-15')+ })++ it('keeps the original time-of-day when moving an existing entry', () => {+ const original = new Date(2026, 5, 15, 18, 30, 0).toISOString()+ const moved = dayToInstant('2026-06-20', original)+ expect(instantToDay(moved)).toBe('2026-06-20')+ expect(new Date(moved).getHours()).toBe(18)+ expect(new Date(moved).getMinutes()).toBe(30)+ })++ it('falls back to noon when the previous timestamp is unusable', () => {+ expect(dayToInstant('2026-06-15', 'not-a-date')).toBe(dayToInstant('2026-06-15'))})})-describe('isoToDayInput', () => {+describe('instantToDay', () => {it('returns the local calendar day for an instant', () => {- expect(isoToDayInput('2026-04-25T16:00:00.000Z')).toBe('2026-04-25')+ expect(instantToDay('2026-04-25T16:00:00.000Z')).toBe('2026-04-25')})it('maps a UTC-midnight instant to the previous local day (what noon-anchoring avoids)', () => {- expect(isoToDayInput('2026-04-25T00:00:00.000Z')).toBe('2026-04-24')+ expect(instantToDay('2026-04-25T00:00:00.000Z')).toBe('2026-04-24')})- it('round-trips with dayToIsoNoon across the year', () => {+ it('round-trips with dayToInstant across the year', () => {for (const day of ['2026-01-15', '2026-04-25', '2026-07-04', '2026-12-31']) {- expect(isoToDayInput(dayToIsoNoon(day))).toBe(day)+ expect(instantToDay(dayToInstant(day))).toBe(day)}})})@@ -47,3 +64,42 @@ describe('todayStr', () => {expect(todayStr()).toBe('2026-04-24')})})++describe('todayStr — the date a form prefills', () => {+ // The mobile New Workout screen seeded its date with+ // `new Date().toISOString().slice(0, 10)`, the UTC day. West of UTC those differ+ // for the last hours of every evening, so the form offered tomorrow and the entry+ // was saved there. Suites run under America/New_York (see jest.config / the web+ // test script), so 23:00 local is already tomorrow in UTC.+ const at = (iso: string, fn: () => string) => {+ const RealDate = Date+ // @ts-expect-error — narrow stub, only the no-arg constructor is used here+ globalThis.Date = class extends RealDate {+ constructor(...args: unknown[]) {+ // @ts-expect-error — passthrough+ super(...(args.length ? args : [iso]))+ }+ static now() { return new RealDate(iso).getTime() }+ }+ try { return fn() } finally { globalThis.Date = RealDate }+ }++ it('returns the local day, not the UTC day, late in the evening', () => {+ // 2026-08-08T23:30 in New York is 2026-08-09T03:30Z.+ const local = at('2026-08-09T03:30:00.000Z', () => todayStr())+ expect(local).toBe('2026-08-08')+ })++ it('differs from the UTC slice the regression used', () => {+ const iso = '2026-08-09T03:30:00.000Z'+ const utcSlice = iso.slice(0, 10)+ const local = at(iso, () => todayStr())+ expect(utcSlice).toBe('2026-08-09')+ expect(local).not.toBe(utcSlice)+ })++ it('round-trips into an instant that stays on the same local day', () => {+ const local = at('2026-08-09T03:30:00.000Z', () => todayStr())+ expect(instantToDay(dayToInstant(local))).toBe(local)+ })+})diff --git a/web/src/utils/dateUtils.ts b/web/src/utils/dateUtils.tsindex c728905..54096d0 100644--- a/web/src/utils/dateUtils.ts+++ b/web/src/utils/dateUtils.ts@@ -15,19 +15,7 @@ export const todayStr = (): string => {return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`}-/**- * Convert a YYYY-MM-DD calendar date to an ISO timestamp anchored at the- * user's local noon, then expressed in UTC. Noon-anchoring keeps the entry- * on the intended calendar day for every timezone within ±12h.- *- * Built without `new Date('YYYY-MM-DDTHH:MM:SS')` because old mobile Safari- * (pre-iOS 14.5) parsed that as UTC instead of local; the explicit-component- * constructor is locale-safe everywhere.- */-export const dayToIsoNoon = (yyyyMmDd: string): string => {- const [y, m, d] = yyyyMmDd.split('-').map(Number)- return new Date(y, m - 1, d, 12, 0, 0, 0).toISOString()-}+/*** Extract a YYYY-MM-DD string in the browser's local timezone from any ISO@@ -35,8 +23,107 @@ export const dayToIsoNoon = (yyyyMmDd: string): string => {* an existing entry so the displayed date matches what the user originally* picked.*/-export const isoToDayInput = (iso: string): string => {+export const instantToDay = (iso: string): string => {const d = new Date(iso)const pad = (n: number) => String(n).padStart(2, '0')return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`}++/**+ * The instant to store for a user-picked calendar day. The inverse of+ * `instantToDay`.+ *+ * One rule for every date the user chooses, replacing the four this codebase grew:+ * a fake noon anchor, a bare `new Date(ymd)` (which parses as UTC midnight and put+ * west-of-UTC users on the previous day), a real `new Date()`, and a local+ * keep-the-time helper that existed in exactly one screen.+ *+ * `previousIso` is the entry's current timestamp when editing: the day moves and the+ * time-of-day is preserved, so re-dating an entry doesn't silently restamp when it+ * happened. Without it the time defaults to local noon — furthest from either+ * midnight, so the entry stays on the intended day under any offset the server might+ * later resolve it in.+ *+ * Built from explicit components rather than `new Date('YYYY-MM-DDTHH:MM:SS')`:+ * pre-iOS 14.5 Safari parsed that string form as UTC, the same class of bug this+ * function exists to remove.+ */+export const dayToInstant = (yyyyMmDd: string, previousIso?: string): string => {+ const [y, m, d] = yyyyMmDd.split('-').map(Number)+ const prev = previousIso ? new Date(previousIso) : null+ const valid = prev && !Number.isNaN(prev.getTime())+ return new Date(+ y, (m ?? 1) - 1, d ?? 1,+ valid ? prev.getHours() : 12,+ valid ? prev.getMinutes() : 0,+ valid ? prev.getSeconds() : 0,+ 0,+ ).toISOString()+}++/**+ * The local calendar day `n` days before today.+ *+ * Exists so range queries build their day the same way everything else does. The+ * weight chart previously used date-fns `format(subDays(new Date(), n), 'yyyy-MM-dd')`,+ * which is a fourth path to a day string and drifts from the server's idea of one:+ * the server resolves a bare day through the *stored* zone, so a device-derived day+ * silently clips the oldest point whenever the two disagree.+ */+export const daysAgoStr = (n: number): string => {+ const d = new Date()+ d.setDate(d.getDate() - n)+ return instantToDay(d.toISOString())+}++/**+ * The device's UTC offset in minutes at `iso` (default: now). New York in summer is+ * -240.+ *+ * Sign is flipped from `Date.getTimezoneOffset()`, which counts minutes *behind* UTC+ * (+240 for New York) — the opposite of every other convention, including the one the+ * server stores. Resolved at the given instant rather than now, so a workout logged+ * in July keeps the summer offset even if it is saved in December.+ */+export const utcOffsetMinutes = (iso?: string): number =>+ -(iso ? new Date(iso) : new Date()).getTimezoneOffset()++/**+ * Attach the calendar day an entry belongs to, for diary writes (food, weight).+ *+ * The day is what the server files the entry under, permanently — it is never+ * re-derived from the account's zone afterwards, so travelling cannot move it. Doing+ * this once in the API layer rather than at each call site means no screen can forget+ * it: a missing `logged_on` silently falls back to the server's guess.+ */+export const withLoggedOn = <T extends { logged_at?: string }>(data: T): T & { logged_on: string } => ({+ ...data,+ logged_on: instantToDay(data.logged_at ?? new Date().toISOString()),+})++/**+ * The day a diary entry belongs to.+ *+ * Prefer the server's stored answer over re-deriving one. `instantToDay(logged_at)`+ * resolves in the *device's* zone, which stopped being the same question the moment+ * the day became a stored column: an entry filed on the 4th in New York, viewed from+ * Tokyo, re-derives as the 5th. Screens that then save that value move the entry.+ * The fallback covers responses from a server older than the column.+ */+export const entryDay = (e: { logged_on?: string; logged_at: string }): string =>+ e.logged_on || instantToDay(e.logged_at)++/**+ * The day a workout happened, from the offset recorded when it started.+ *+ * A workout stores an instant plus its offset rather than a day, so the local day is+ * recovered by applying one to the other. Reading the shifted value back in UTC is+ * correct precisely *because* the offset has already been applied — this is the one+ * place `slice(0, 10)` names a local day rather than a UTC one. Falls back to the+ * device zone for rows written before the offset existed.+ */+export const workoutDay = (w: { started_at: string; tz_offset_minutes?: number }): string => {+ if (w.tz_offset_minutes == null) return instantToDay(w.started_at)+ const shifted = new Date(new Date(w.started_at).getTime() + w.tz_offset_minutes * 60_000)+ return Number.isNaN(shifted.getTime()) ? instantToDay(w.started_at) : shifted.toISOString().slice(0, 10)+}