Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

Multi-day program routines with rest days (wger-style) (#72)

Carter0ed1d55d13d9
diff --git a/backend/controllers/concurrency_test.go b/backend/controllers/concurrency_test.go
index f5223e0..1c3bd46 100644
--- a/backend/controllers/concurrency_test.go
+++ b/backend/controllers/concurrency_test.go
@@ -85,8 +85,13 @@ func TestListProgramsConcurrentDoesNotExhaustPool(t *testing.T) {
t.Fatalf("insert program: %v", err)
}
pid, _ := res.LastInsertId()
+ dayRes, err := db.DB.Exec(`INSERT INTO program_days (program_id, order_index, is_rest_day, name) VALUES (?, 0, 0, '')`, pid)
+ if err != nil {
+ t.Fatalf("insert program_day: %v", err)
+ }
+ dayID, _ := dayRes.LastInsertId()
peRes, err := db.DB.Exec(
- `INSERT INTO program_exercises (program_id, exercise_id, order_index) VALUES (?, ?, 0)`, pid, exID,
+ `INSERT INTO program_exercises (program_id, program_day_id, exercise_id, order_index) VALUES (?, ?, ?, 0)`, pid, dayID, exID,
)
if err != nil {
t.Fatalf("insert program_exercise: %v", err)
diff --git a/backend/controllers/programs.go b/backend/controllers/programs.go
index f070bb5..8279829 100644
--- a/backend/controllers/programs.go
+++ b/backend/controllers/programs.go
@@ -9,8 +9,33 @@ import (
"github.com/Cawlumm/lyftr-backend/stores"
"github.com/Cawlumm/lyftr-backend/utils"
"github.com/gin-gonic/gin"
+ "github.com/go-playground/validator/v10"
)
+// Days/Exercises/Sets in CreateProgramRequest each cap at max=500 independently
+// (models.go), which doesn't bound their product across three nested levels — a
+// request with 500 days x 500 exercises x 500 sets still passes those tags. This
+// struct-level check enforces the total-rows bound (models.MaxProgramRows) that
+// insertProgramDays's single-transaction processing actually needs, since
+// db.DB.SetMaxOpenConns(1) means that transaction holds the process's only SQLite
+// connection for the whole request. Mirrors controllers/workouts.go's init().
+func init() {
+ validate.RegisterStructValidation(func(sl validator.StructLevel) {
+ req := sl.Current().Interface().(models.CreateProgramRequest)
+ total := 0
+ for _, d := range req.Days {
+ total++
+ for _, ex := range d.Exercises {
+ total++
+ total += len(ex.Sets)
+ }
+ }
+ if total > models.MaxProgramRows {
+ sl.ReportError(req.Days, "Days", "Days", "maxtotalrows", "")
+ }
+ }, models.CreateProgramRequest{})
+}
+
func (h *Handler) ListPrograms(c *gin.Context) {
uid := middleware.UserID(c)
f := stores.ProgramFilter{Limit: 20, Query: c.Query("q")}
diff --git a/backend/controllers/programs_current_day_test.go b/backend/controllers/programs_current_day_test.go
new file mode 100644
index 0000000..f76688c
--- /dev/null
+++ b/backend/controllers/programs_current_day_test.go
@@ -0,0 +1,621 @@
+package controllers
+
+import (
+ "fmt"
+ "net/http"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/models"
+)
+
+// seedProgramDays creates a program owned by uid with Days in the given rest-day
+// pattern (true = rest, false = workout), in order_index order, and returns the
+// program id.
+func seedProgramDays(t *testing.T, uid int64, isRest []bool) int64 {
+ t.Helper()
+ res, err := db.DB.Exec(`INSERT INTO programs (user_id, name) VALUES (?, 'Cycle Program')`, uid)
+ if err != nil {
+ t.Fatalf("seed program: %v", err)
+ }
+ pid, _ := res.LastInsertId()
+ for i, rest := range isRest {
+ restInt := 0
+ if rest {
+ restInt = 1
+ }
+ if _, err := db.DB.Exec(
+ `INSERT INTO program_days (program_id, order_index, is_rest_day, name) VALUES (?, ?, ?, '')`,
+ pid, i, restInt,
+ ); err != nil {
+ t.Fatalf("seed program day %d: %v", i, err)
+ }
+ }
+ return pid
+}
+
+// dayIDsOf returns the program's day row ids in cycle (order_index) order.
+func dayIDsOf(t *testing.T, pid int64) []int64 {
+ t.Helper()
+ rows, err := db.DB.Query(`SELECT id FROM program_days WHERE program_id = ? ORDER BY order_index`, pid)
+ if err != nil {
+ t.Fatalf("query day ids: %v", err)
+ }
+ defer rows.Close()
+ ids := []int64{}
+ for rows.Next() {
+ var id int64
+ if err := rows.Scan(&id); err != nil {
+ t.Fatalf("scan day id: %v", err)
+ }
+ ids = append(ids, id)
+ }
+ return ids
+}
+
+// logWorkouts inserts n day-less workout rows attributed to the program — the shape
+// an older client (predating day tracking) writes. These advance the due-day
+// tracker count-based.
+func logWorkouts(t *testing.T, uid, pid int64, n int) {
+ t.Helper()
+ for i := 0; i < n; i++ {
+ if _, err := db.DB.Exec(
+ `INSERT INTO workouts (user_id, name, program_id) VALUES (?, 'logged', ?)`, uid, pid,
+ ); err != nil {
+ t.Fatalf("log workout %d: %v", i, err)
+ }
+ }
+}
+
+// logWorkoutOnDay inserts one workout linked to a specific program day at the given
+// started_at (a 'YYYY-MM-DD HH:MM:SS' literal so text ordering is deterministic in
+// the test), returning the workout id.
+func logWorkoutOnDay(t *testing.T, uid, pid, dayID int64, startedAt string) int64 {
+ t.Helper()
+ res, err := db.DB.Exec(
+ `INSERT INTO workouts (user_id, name, program_id, program_day_id, started_at) VALUES (?, 'logged', ?, ?, ?)`,
+ uid, pid, dayID, startedAt,
+ )
+ if err != nil {
+ t.Fatalf("log workout on day %d: %v", dayID, err)
+ }
+ wid, _ := res.LastInsertId()
+ return wid
+}
+
+// workoutDayLinkOf reads back a workout's stored day linkage.
+func workoutDayLinkOf(t *testing.T, wid int64) (dayID *int64, dropped int) {
+ t.Helper()
+ if err := db.DB.QueryRow(
+ `SELECT program_day_id, program_day_dropped FROM workouts WHERE id = ?`, wid,
+ ).Scan(&dayID, &dropped); err != nil {
+ t.Fatalf("read workout %d day link: %v", wid, err)
+ }
+ return dayID, dropped
+}
+
+func currentDayIndexOf(t *testing.T, uid, pid int64) int {
+ t.Helper()
+ c, w := newContext(uid, http.MethodGet, "/api/v1/programs/"+fmt.Sprint(pid), nil)
+ setParam(c, "id", fmt.Sprint(pid))
+ th.GetProgram(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetProgram: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ resp := decodeResponse(t, w)
+ data := resp["data"].(map[string]any)
+ idx, ok := data["current_day_index"].(float64)
+ if !ok {
+ t.Fatalf("current_day_index missing or wrong type: %T = %v", data["current_day_index"], data["current_day_index"])
+ }
+ return int(idx)
+}
+
+// updateProgram PUTs the given day list (names/ids/rest flags, no exercises) through
+// the real UpdateProgram handler.
+func updateProgram(t *testing.T, uid, pid int64, days []models.CreateProgramDayReq) {
+ t.Helper()
+ body := models.CreateProgramRequest{Name: "Cycle Program", Days: days}
+ c, w := newContext(uid, http.MethodPut, "/api/v1/programs/"+fmt.Sprint(pid), body)
+ setParam(c, "id", fmt.Sprint(pid))
+ th.UpdateProgram(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateProgram: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+// ── Day-less (older-client) fallback ─────────────────────────────────────────────
+
+// TestCurrentDayIndex_DaylessLogsSkipRestDays: rows with no day linkage (older
+// clients) advance the tracker count-based through the WORKOUT days only — a rest
+// day is never due. Cycle [A, B, Rest, Rest, C, Rest].
+func TestCurrentDayIndex_DaylessLogsSkipRestDays(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ // index: 0=A 1=B 2=Rest 3=Rest 4=C 5=Rest
+ pid := seedProgramDays(t, uid, []bool{false, false, true, true, false, true})
+
+ if got := currentDayIndexOf(t, uid, pid); got != 0 {
+ t.Fatalf("no workouts logged yet: expected due index 0 (A), got %d", got)
+ }
+ logWorkouts(t, uid, pid, 1) // A done
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after logging A: expected due index 1 (B), got %d", got)
+ }
+ logWorkouts(t, uid, pid, 1) // B done
+ if got := currentDayIndexOf(t, uid, pid); got != 4 {
+ t.Fatalf("after logging A,B: expected due index 4 (C — rest slots are never due), got %d", got)
+ }
+ logWorkouts(t, uid, pid, 1) // C done — cycle wraps
+ if got := currentDayIndexOf(t, uid, pid); got != 0 {
+ t.Fatalf("after logging A,B,C: expected due index 0 (wrap to A), got %d", got)
+ }
+}
+
+// TestCurrentDayIndex_SingleRestDayWrapsBackToStart covers the [A, Rest, B] case:
+// once both workout days in the cycle are done, the due slot must wrap back to A
+// (index 0), not sit on B.
+func TestCurrentDayIndex_SingleRestDayWrapsBackToStart(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, true, false}) // 0=A 1=Rest 2=B
+
+ logWorkouts(t, uid, pid, 2) // A then B
+ if got := currentDayIndexOf(t, uid, pid); got != 0 {
+ t.Fatalf("after logging A,B: expected due index 0 (wrap back to A), got %d", got)
+ }
+}
+
+// TestCurrentDayIndex_NeverFreezesAcrossMultipleCycles: the due index must keep
+// alternating between the two workout days of [A, Rest, B, Rest] across repeated
+// cycles — a frozen tracker reports only one of them after the first couple of logs.
+func TestCurrentDayIndex_NeverFreezesAcrossMultipleCycles(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, true, false, true}) // 0=A 1=Rest 2=B 3=Rest
+
+ seen := map[int]bool{}
+ for i := 0; i < 10; i++ { // 5 full A/B cycles
+ logWorkouts(t, uid, pid, 1)
+ seen[currentDayIndexOf(t, uid, pid)] = true
+ }
+ if !seen[0] || !seen[2] {
+ t.Fatalf("expected current_day_index to alternate between 0 (A) and 2 (B) across repeated cycles, saw %v", seen)
+ }
+}
+
+// ── Day-accurate tracking (workouts.program_day_id) ──────────────────────────────
+
+// TestCurrentDayIndex_RepeatingADayDoesNotSkip: logging the same day twice in a row
+// must leave the due day parked on the NEXT day in sequence — a blind count would
+// advance through the cycle as if the repeats were done in order.
+func TestCurrentDayIndex_RepeatingADayDoesNotSkip(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false, false}) // 0=A 1=B 2=C
+ ids := dayIDsOf(t, pid)
+
+ logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-01 10:00:00")
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after logging A: expected due index 1 (B), got %d", got)
+ }
+ logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-02 10:00:00") // A again
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after repeating A: expected due index still 1 (B), got %d", got)
+ }
+ logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-03 10:00:00") // and again
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after repeating A twice: expected due index still 1 (B), got %d", got)
+ }
+}
+
+// TestCurrentDayIndex_OutOfOrderLoggingFollowsLastLogged: manually picking a day
+// other than the due one moves the tracker to whatever follows THAT day — it does
+// not try to remember the skipped day (deliberate simplification).
+func TestCurrentDayIndex_OutOfOrderLoggingFollowsLastLogged(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false, false}) // 0=A 1=B 2=C
+ ids := dayIDsOf(t, pid)
+
+ logWorkoutOnDay(t, uid, pid, ids[2], "2026-07-01 10:00:00") // C first
+ if got := currentDayIndexOf(t, uid, pid); got != 0 {
+ t.Fatalf("after logging C out of order: expected due index 0 (wrap to A), got %d", got)
+ }
+ logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-02 10:00:00") // then A
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after logging A: expected due index 1 (B), got %d", got)
+ }
+ logWorkoutOnDay(t, uid, pid, ids[1], "2026-07-03 10:00:00") // then B
+ if got := currentDayIndexOf(t, uid, pid); got != 2 {
+ t.Fatalf("after logging B: expected due index 2 (C), got %d", got)
+ }
+}
+
+// TestCurrentDayIndex_FullCycleWithRestDays walks a whole day-linked cycle of
+// [A, Rest, B, Rest, C]: the due index always lands on the next WORKOUT day after
+// the one just logged, skipping over rest days, and wraps at the end.
+func TestCurrentDayIndex_FullCycleWithRestDays(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, true, false, true, false}) // 0=A 1=R 2=B 3=R 4=C
+ ids := dayIDsOf(t, pid)
+
+ logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-01 10:00:00") // A
+ if got := currentDayIndexOf(t, uid, pid); got != 2 {
+ t.Fatalf("after A: expected due index 2 (B), got %d", got)
+ }
+ logWorkoutOnDay(t, uid, pid, ids[2], "2026-07-02 10:00:00") // B
+ if got := currentDayIndexOf(t, uid, pid); got != 4 {
+ t.Fatalf("after B: expected due index 4 (C), got %d", got)
+ }
+ logWorkoutOnDay(t, uid, pid, ids[4], "2026-07-03 10:00:00") // C — wraps
+ if got := currentDayIndexOf(t, uid, pid); got != 0 {
+ t.Fatalf("after C: expected due index 0 (wrap to A), got %d", got)
+ }
+}
+
+// ── Program edits must not corrupt day linkage ───────────────────────────────────
+
+// TestCurrentDayIndex_SurvivesProgramRename: an id-carrying update that only renames
+// days keeps every workout linked to its original day row — the tracker must not
+// reset.
+func TestCurrentDayIndex_SurvivesProgramRename(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false, false}) // 0=A 1=B 2=C
+ ids := dayIDsOf(t, pid)
+
+ wid := logWorkoutOnDay(t, uid, pid, ids[1], "2026-07-01 10:00:00") // B
+ updateProgram(t, uid, pid, []models.CreateProgramDayReq{
+ {ID: ids[0], Name: "Push"},
+ {ID: ids[1], Name: "Pull"},
+ {ID: ids[2], Name: "Legs"},
+ })
+ if got := currentDayIndexOf(t, uid, pid); got != 2 {
+ t.Fatalf("after rename: expected due index 2 (day after B), got %d", got)
+ }
+ dayID, dropped := workoutDayLinkOf(t, wid)
+ if dayID == nil || *dayID != ids[1] || dropped != 0 {
+ t.Fatalf("rename must keep the workout linked to its day: got dayID=%v dropped=%d", dayID, dropped)
+ }
+}
+
+// TestCurrentDayIndex_ReorderKeepsDayLinkage is the regression check for the
+// positional-matching bug: moving days around must keep every workout attributed to
+// the SAME day (matched by id), so the due day follows the day's new position
+// instead of silently re-attributing the history.
+func TestCurrentDayIndex_ReorderKeepsDayLinkage(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false, false}) // 0=Push 1=Pull 2=Legs
+ ids := dayIDsOf(t, pid)
+
+ wid := logWorkoutOnDay(t, uid, pid, ids[1], "2026-07-01 10:00:00") // Pull
+ if got := currentDayIndexOf(t, uid, pid); got != 2 {
+ t.Fatalf("after Pull: expected due index 2 (Legs), got %d", got)
+ }
+
+ // Move Legs to the front: [Legs, Push, Pull].
+ updateProgram(t, uid, pid, []models.CreateProgramDayReq{
+ {ID: ids[2], Name: "Legs"},
+ {ID: ids[0], Name: "Push"},
+ {ID: ids[1], Name: "Pull"},
+ })
+
+ // The anchor workout is still a Pull workout; Pull now sits at index 2, so the
+ // day after it wraps to Legs at index 0. Positional matching would have turned
+ // the anchor into "Push" and reported Pull — the day just completed — as due.
+ if got := currentDayIndexOf(t, uid, pid); got != 0 {
+ t.Fatalf("after reorder: expected due index 0 (Legs, next after Pull), got %d", got)
+ }
+ dayID, dropped := workoutDayLinkOf(t, wid)
+ if dayID == nil || *dayID != ids[1] || dropped != 0 {
+ t.Fatalf("reorder must keep the workout linked to Pull's row: got dayID=%v dropped=%d", dayID, dropped)
+ }
+}
+
+// TestCurrentDayIndex_MiddleRemovalDropsOnlyThatDaysLinkage: removing a day from the
+// MIDDLE of the cycle must drop linkage for exactly that day's workouts (marked as
+// residue) and leave every kept day's history attached.
+func TestCurrentDayIndex_MiddleRemovalDropsOnlyThatDaysLinkage(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false, false}) // 0=A 1=B 2=C
+ ids := dayIDsOf(t, pid)
+
+ widA := logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-01 10:00:00")
+ widB := logWorkoutOnDay(t, uid, pid, ids[1], "2026-07-02 10:00:00")
+ widC := logWorkoutOnDay(t, uid, pid, ids[2], "2026-07-03 10:00:00")
+
+ // Remove B: [A, C].
+ updateProgram(t, uid, pid, []models.CreateProgramDayReq{
+ {ID: ids[0], Name: "A"},
+ {ID: ids[2], Name: "C"},
+ })
+
+ if dayID, dropped := workoutDayLinkOf(t, widA); dayID == nil || *dayID != ids[0] || dropped != 0 {
+ t.Fatalf("A's workout must stay linked to A: got dayID=%v dropped=%d", dayID, dropped)
+ }
+ if dayID, dropped := workoutDayLinkOf(t, widC); dayID == nil || *dayID != ids[2] || dropped != 0 {
+ t.Fatalf("C's workout must stay linked to C: got dayID=%v dropped=%d", dayID, dropped)
+ }
+ if dayID, dropped := workoutDayLinkOf(t, widB); dayID != nil || dropped != 1 {
+ t.Fatalf("B's workout must be un-linked and marked dropped: got dayID=%v dropped=%d", dayID, dropped)
+ }
+ // Most recent linked workout is C's; the day after C wraps to A at index 0.
+ if got := currentDayIndexOf(t, uid, pid); got != 0 {
+ t.Fatalf("after removing B: expected due index 0 (wrap after C), got %d", got)
+ }
+}
+
+// TestCurrentDayIndex_DeletedDayResidueDoesNotSwingDueDay: deleting a day with a
+// long logged history must not decide the new due day by the parity of that
+// history's count — with no anchor left, the first workout day is due (the spec's
+// "no qualifying workout yet" case).
+func TestCurrentDayIndex_DeletedDayResidueDoesNotSwingDueDay(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false, false}) // 0=A 1=B 2=C
+ ids := dayIDsOf(t, pid)
+
+ for i := 0; i < 5; i++ { // 5 workouts, all on A — an odd count
+ logWorkoutOnDay(t, uid, pid, ids[0], fmt.Sprintf("2026-07-0%d 10:00:00", i+1))
+ }
+ // Delete A: [B, C]. All 5 rows become residue at once.
+ updateProgram(t, uid, pid, []models.CreateProgramDayReq{
+ {ID: ids[1], Name: "B"},
+ {ID: ids[2], Name: "C"},
+ })
+ // No anchor remains; residue is ignored, so the first workout day (B) is due.
+ // Counting the residue would report workoutIdx[5 % 2] = C instead.
+ if got := currentDayIndexOf(t, uid, pid); got != 0 {
+ t.Fatalf("after deleting A: expected due index 0 (B, first workout day), got %d", got)
+ }
+}
+
+// TestCurrentDayIndex_ToggleWorkoutDayToRest: editing a logged-against day into a
+// rest day sheds that day's workout linkage (rest days can never be due) and marks
+// the shed rows dropped, exactly like a deleted day — residue, ignored by the
+// tracker rather than miscounted as count-based advances.
+func TestCurrentDayIndex_ToggleWorkoutDayToRest(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false, false}) // 0=A 1=B 2=C
+ ids := dayIDsOf(t, pid)
+
+ logWorkoutOnDay(t, uid, pid, ids[2], "2026-07-01 10:00:00") // C
+ widA := logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-02 10:00:00") // then A
+
+ // Toggle A to rest: [Rest, B, C].
+ updateProgram(t, uid, pid, []models.CreateProgramDayReq{
+ {ID: ids[0], Name: "A", IsRestDay: true},
+ {ID: ids[1], Name: "B"},
+ {ID: ids[2], Name: "C"},
+ })
+
+ dayID, dropped := workoutDayLinkOf(t, widA)
+ if dayID != nil || dropped != 1 {
+ t.Fatalf("rest-toggled day's workout must be un-linked AND marked dropped: got dayID=%v dropped=%d", dayID, dropped)
+ }
+ // The anchor falls back to the C workout; the shed A row is residue and is
+ // ignored (its cycle position no longer exists), so the day after C wraps past
+ // the new rest slot to B at index 1.
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after toggling A to rest: expected due index 1 (B, next after anchor C), got %d", got)
+ }
+}
+
+// TestCurrentDayIndex_ToggleWithOddRepeatsDoesNotSwingDueDay: rest-toggling a day
+// with an ODD number of logged repeats must not swing the due day — the shed rows
+// are residue (dropped), never count-based advances. Counting them would report
+// workoutIdx[3 % 2] = C here.
+func TestCurrentDayIndex_ToggleWithOddRepeatsDoesNotSwingDueDay(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false, false}) // 0=A 1=B 2=C
+ ids := dayIDsOf(t, pid)
+
+ // Log A three times (repeating the same day)
+ logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-01 10:00:00") // A
+ logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-02 10:00:00") // A
+ logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-03 10:00:00") // A
+
+ // At this point, due should be B (repeats don't advance)
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after three A repeats: expected due index 1 (B), got %d", got)
+ }
+
+ // Now toggle A to rest: [Rest, B, C]
+ updateProgram(t, uid, pid, []models.CreateProgramDayReq{
+ {ID: ids[0], Name: "A", IsRestDay: true},
+ {ID: ids[1], Name: "B"},
+ {ID: ids[2], Name: "C"},
+ })
+
+ // All three A rows became dropped residue: no anchor remains, residue is
+ // ignored, so the first workout day (B, index 1) is due — same as before the
+ // toggle.
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after toggling A to rest with 3 repeats: expected due index 1 (B), got %d", got)
+ }
+}
+
+// TestCurrentDayIndex_ToggleWithEvenRepeatsDoesNotSwingDueDay: same scenario with an
+// EVEN repeat count — counting the shed rows would report workoutIdx[2 % 2] = B by
+// luck of parity here and C for the odd case above; both must stay B.
+func TestCurrentDayIndex_ToggleWithEvenRepeatsDoesNotSwingDueDay(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false, false}) // 0=A 1=B 2=C
+ ids := dayIDsOf(t, pid)
+
+ // Log A twice
+ logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-01 10:00:00") // A
+ logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-02 10:00:00") // A
+
+ // At this point, due should be B
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after two A repeats: expected due index 1 (B), got %d", got)
+ }
+
+ // Now toggle A to rest: [Rest, B, C]
+ updateProgram(t, uid, pid, []models.CreateProgramDayReq{
+ {ID: ids[0], Name: "A", IsRestDay: true},
+ {ID: ids[1], Name: "B"},
+ {ID: ids[2], Name: "C"},
+ })
+
+ // Dropped residue is ignored: no anchor → first workout day (B) is due.
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after toggling A to rest with 2 repeats: expected due index 1 (B), got %d", got)
+ }
+}
+
+// TestUpdateProgram_LegacyIDlessRequestMatchesByPosition: a request carrying no day
+// ids (a client predating the id round-trip) still updates day rows in place by
+// position — a same-shape edit must not scrub the program's workout history.
+func TestUpdateProgram_LegacyIDlessRequestMatchesByPosition(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false}) // 0=A 1=B
+ ids := dayIDsOf(t, pid)
+
+ wid := logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-01 10:00:00") // A
+ updateProgram(t, uid, pid, []models.CreateProgramDayReq{
+ {Name: "Renamed A"},
+ {Name: "Renamed B"},
+ })
+ dayID, dropped := workoutDayLinkOf(t, wid)
+ if dayID == nil || *dayID != ids[0] || dropped != 0 {
+ t.Fatalf("legacy positional update must keep the workout linked: got dayID=%v dropped=%d", dayID, dropped)
+ }
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("after legacy rename: expected due index 1 (B), got %d", got)
+ }
+}
+
+// TestUpdateProgram_ModernReplaceAllDaysDropsOldHistory: a modern client
+// (day_ids_known) that deletes EVERY existing day and adds only new (id-less) ones
+// sends zero ids — indistinguishable by content from a legacy payload. The flag must
+// force id matching so the old days are really deleted (history dropped as residue)
+// instead of positionally renamed in place, which would silently re-attribute the
+// deleted days' workout history to the brand-new days.
+func TestUpdateProgram_ModernReplaceAllDaysDropsOldHistory(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false}) // 0=Push 1=Pull
+ ids := dayIDsOf(t, pid)
+
+ wid := logWorkoutOnDay(t, uid, pid, ids[0], "2026-07-01 10:00:00") // Push
+
+ // Delete Push and Pull, add Squat — no ids, but the client declares it knows them.
+ body := models.CreateProgramRequest{
+ Name: "Cycle Program",
+ DayIDsKnown: true,
+ Days: []models.CreateProgramDayReq{{Name: "Squat"}},
+ }
+ c, w := newContext(uid, http.MethodPut, "/api/v1/programs/"+fmt.Sprint(pid), body)
+ setParam(c, "id", fmt.Sprint(pid))
+ th.UpdateProgram(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateProgram: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ newIDs := dayIDsOf(t, pid)
+ if len(newIDs) != 1 || newIDs[0] == ids[0] || newIDs[0] == ids[1] {
+ t.Fatalf("expected one brand-new Squat day row, got ids %v (old were %v)", newIDs, ids)
+ }
+ dayID, dropped := workoutDayLinkOf(t, wid)
+ if dayID != nil || dropped != 1 {
+ t.Fatalf("deleted Push's workout must be un-linked and marked dropped, not re-attributed: got dayID=%v dropped=%d", dayID, dropped)
+ }
+ // No anchor remains and residue is ignored → the (only) new workout day is due.
+ if got := currentDayIndexOf(t, uid, pid); got != 0 {
+ t.Fatalf("after replace-all: expected due index 0 (Squat), got %d", got)
+ }
+}
+
+// TestUpdateProgram_ForeignDayIDCannotHijack: an update carrying another user's day
+// id must not touch that row — the id is treated as a new day of the caller's own
+// program (ownership-on-every-write convention).
+func TestUpdateProgram_ForeignDayIDCannotHijack(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ // createTestUser has a fixed UNIQUE email — insert the second user manually.
+ res, err := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'hashed')`)
+ if err != nil {
+ t.Fatalf("create second user: %v", err)
+ }
+ otherUID, _ := res.LastInsertId()
+ otherPID := seedProgramDays(t, otherUID, []bool{false})
+ otherDayID := dayIDsOf(t, otherPID)[0]
+
+ pid := seedProgramDays(t, uid, []bool{false})
+ updateProgram(t, uid, pid, []models.CreateProgramDayReq{
+ {ID: otherDayID, Name: "Hijack"},
+ })
+
+ var name string
+ var victimPID int64
+ if err := db.DB.QueryRow(`SELECT name, program_id FROM program_days WHERE id = ?`, otherDayID).Scan(&name, &victimPID); err != nil {
+ t.Fatalf("read victim day: %v", err)
+ }
+ if name != "" || victimPID != otherPID {
+ t.Fatalf("foreign day row was modified: name=%q program_id=%d", name, victimPID)
+ }
+}
+
+// ── Write-path guards ────────────────────────────────────────────────────────────
+
+// TestCreateWorkout_RestDayLinkageScrubsToNull: POSTing a workout claiming a REST
+// day's id must store a NULL day link (like a stale/foreign id) — a persisted
+// rest-day link would be invisible to the due-day tracker forever.
+func TestCreateWorkout_RestDayLinkageScrubsToNull(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, true, false}) // 0=A 1=Rest 2=B
+ restDayID := dayIDsOf(t, pid)[1]
+
+ body := models.CreateWorkoutRequest{Name: "Rest?", ProgramID: &pid, ProgramDayID: &restDayID}
+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)
+ th.CreateWorkout(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateWorkout: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ resp := decodeResponse(t, w)
+ wid := int64(resp["data"].(map[string]any)["id"].(float64))
+ dayID, dropped := workoutDayLinkOf(t, wid)
+ if dayID != nil || dropped != 0 {
+ t.Fatalf("rest-day id must degrade to NULL: got dayID=%v dropped=%d", dayID, dropped)
+ }
+}
+
+// TestCurrentDayIndex_OffsetTimestampsOrderChronologically: the tracker orders rows
+// by started_at as stored text, so the write path must normalize offsets to UTC —
+// otherwise a workout sent with a +08:00 wall-clock later than a UTC row's (but an
+// EARLIER instant) would wrongly become the anchor.
+func TestCurrentDayIndex_OffsetTimestampsOrderChronologically(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ pid := seedProgramDays(t, uid, []bool{false, false}) // 0=A 1=B
+ ids := dayIDsOf(t, pid)
+
+ post := func(dayID int64, startedAt string) {
+ t.Helper()
+ body := map[string]any{"name": "tz", "program_id": pid, "program_day_id": dayID, "started_at": startedAt}
+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)
+ th.CreateWorkout(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateWorkout: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ }
+ post(ids[0], "2026-07-18T20:00:00Z") // A at 20:00Z — the true most recent
+ post(ids[1], "2026-07-19T02:00:00+08:00") // B at 18:00Z, wall-clock "later"
+
+ // Chronologically the A workout is most recent → B is due. Comparing raw
+ // wall-clock text would anchor on the B row and report A as due.
+ if got := currentDayIndexOf(t, uid, pid); got != 1 {
+ t.Fatalf("expected due index 1 (B — A's row is the true most recent), got %d", got)
+ }
+}
diff --git a/backend/controllers/programs_test.go b/backend/controllers/programs_test.go
index 5be3239..1eaa057 100644
--- a/backend/controllers/programs_test.go
+++ b/backend/controllers/programs_test.go
@@ -36,14 +36,19 @@ func TestCreateProgram_success(t *testing.T) {
body := map[string]any{
"name": "PPL Program",
"notes": "Push Pull Legs 6 days",
- "exercises": []map[string]any{
+ "days": []map[string]any{
{
- "exercise_id": exID,
- "notes": "Focus on form",
- "sets": []map[string]any{
- {"set_number": 1, "target_reps": 5, "target_weight": 100.0},
- {"set_number": 2, "target_reps": 5, "target_weight": 100.0},
- {"set_number": 3, "target_reps": 5, "target_weight": 100.0},
+ "is_rest_day": false,
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID,
+ "notes": "Focus on form",
+ "sets": []map[string]any{
+ {"set_number": 1, "target_reps": 5, "target_weight": 100.0},
+ {"set_number": 2, "target_reps": 5, "target_weight": 100.0},
+ {"set_number": 3, "target_reps": 5, "target_weight": 100.0},
+ },
+ },
},
},
},
@@ -60,9 +65,14 @@ func TestCreateProgram_success(t *testing.T) {
if data["name"] != "PPL Program" {
t.Errorf("expected name 'PPL Program', got %v", data["name"])
}
- exercises, ok := data["exercises"].([]any)
+ days, ok := data["days"].([]any)
+ if !ok || len(days) != 1 {
+ t.Fatalf("days field missing or wrong shape: %T = %v", data["days"], data["days"])
+ }
+ day0 := days[0].(map[string]any)
+ exercises, ok := day0["exercises"].([]any)
if !ok {
- t.Fatalf("exercises field missing or wrong type: %T = %v", data["exercises"], data["exercises"])
+ t.Fatalf("exercises field missing or wrong type: %T = %v", day0["exercises"], day0["exercises"])
}
if len(exercises) != 1 {
t.Fatalf("expected 1 exercise, got %d", len(exercises))
@@ -82,8 +92,8 @@ func TestCreateProgram_missingName(t *testing.T) {
uid := createTestUser(t)
body := map[string]any{
- "name": "",
- "exercises": []map[string]any{},
+ "name": "",
+ "days": []map[string]any{},
}
c, w := newContext(uid, http.MethodPost, "/api/v1/programs", body)
th.CreateProgram(c)
@@ -144,10 +154,12 @@ func TestUpdateProgram_replacesExercises(t *testing.T) {
res, _ := db.DB.Exec(`INSERT INTO exercises (name, muscle_group, category) VALUES (?, ?, ?)`, "Test Exercise 2", "back", "strength")
exID2, _ := res.LastInsertId()
- // Create program with 1 exercise
+ // Create program with 1 day, 1 exercise
progRes, _ := db.DB.Exec(`INSERT INTO programs (user_id, name) VALUES (?, ?)`, uid, "Original")
pid, _ := progRes.LastInsertId()
- exRes, _ := db.DB.Exec(`INSERT INTO program_exercises (program_id, exercise_id, order_index) VALUES (?, ?, 0)`, pid, exID)
+ dayRes, _ := db.DB.Exec(`INSERT INTO program_days (program_id, order_index, is_rest_day, name) VALUES (?, 0, 0, '')`, pid)
+ dayID, _ := dayRes.LastInsertId()
+ exRes, _ := db.DB.Exec(`INSERT INTO program_exercises (program_id, program_day_id, exercise_id, order_index) VALUES (?, ?, ?, 0)`, pid, dayID, exID)
peid, _ := exRes.LastInsertId()
db.DB.Exec(`INSERT INTO program_sets (program_exercise_id, set_number, target_reps) VALUES (?, 1, 5)`, peid)
@@ -155,11 +167,16 @@ func TestUpdateProgram_replacesExercises(t *testing.T) {
body := map[string]any{
"name": "Updated Program",
"notes": "",
- "exercises": []map[string]any{
+ "days": []map[string]any{
{
- "exercise_id": exID2,
- "notes": "",
- "sets": []map[string]any{{"set_number": 1, "target_reps": 8, "target_weight": 60.0}},
+ "is_rest_day": false,
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID2,
+ "notes": "",
+ "sets": []map[string]any{{"set_number": 1, "target_reps": 8, "target_weight": 60.0}},
+ },
+ },
},
},
}
@@ -194,10 +211,15 @@ func TestCreateProgram_setNumberNormalized(t *testing.T) {
// Send set_number: 0 — backend should normalize to 1
body := map[string]any{
"name": "Norm Test",
- "exercises": []map[string]any{
+ "days": []map[string]any{
{
- "exercise_id": exID,
- "sets": []map[string]any{{"set_number": 0, "target_reps": 10, "target_weight": 50.0}},
+ "is_rest_day": false,
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID,
+ "sets": []map[string]any{{"set_number": 0, "target_reps": 10, "target_weight": 50.0}},
+ },
+ },
},
},
}
@@ -211,7 +233,8 @@ func TestCreateProgram_setNumberNormalized(t *testing.T) {
resp := decodeResponse(t, w)
data := resp["data"].(map[string]any)
- exercises := data["exercises"].([]any)
+ days := data["days"].([]any)
+ exercises := days[0].(map[string]any)["exercises"].([]any)
sets := exercises[0].(map[string]any)["sets"].([]any)
setNum := sets[0].(map[string]any)["set_number"].(float64)
if setNum != 1 {
diff --git a/backend/controllers/progression_test.go b/backend/controllers/progression_test.go
index e0567e6..49a52c1 100644
--- a/backend/controllers/progression_test.go
+++ b/backend/controllers/progression_test.go
@@ -21,7 +21,12 @@ func seedProgram(t *testing.T, uid, exID int64, targets []ptTarget) (int64, []in
t.Fatalf("seed program: %v", err)
}
pid, _ := res.LastInsertId()
- peRes, err := db.DB.Exec(`INSERT INTO program_exercises (program_id, exercise_id, order_index) VALUES (?, ?, 0)`, pid, exID)
+ dayRes, err := db.DB.Exec(`INSERT INTO program_days (program_id, order_index, is_rest_day, name) VALUES (?, 0, 0, '')`, pid)
+ if err != nil {
+ t.Fatalf("seed program day: %v", err)
+ }
+ dayID, _ := dayRes.LastInsertId()
+ peRes, err := db.DB.Exec(`INSERT INTO program_exercises (program_id, program_day_id, exercise_id, order_index) VALUES (?, ?, ?, 0)`, pid, dayID, exID)
if err != nil {
t.Fatalf("seed program exercise: %v", err)
}
@@ -213,8 +218,8 @@ func TestResolveSuggestions_AcceptAndDismiss(t *testing.T) {
if err != nil {
t.Fatalf("ResolveSuggestions: %v", err)
}
- if len(prog.Exercises) != 1 {
- t.Fatalf("expected 1 exercise, got %d", len(prog.Exercises))
+ if len(prog.Days) != 1 || len(prog.Days[0].Exercises) != 1 {
+ t.Fatalf("expected 1 day with 1 exercise, got %d days", len(prog.Days))
}
// set0: target applied to 105, suggestion cleared.
if r, w := getTarget(t, ids[0]); r != 5 || w != 105 {
diff --git a/backend/controllers/rest_timer_test.go b/backend/controllers/rest_timer_test.go
index 083f50e..7f754e7 100644
--- a/backend/controllers/rest_timer_test.go
+++ b/backend/controllers/rest_timer_test.go
@@ -35,8 +35,13 @@ func TestProgramRestSecondsRoundTrips(t *testing.T) {
body := map[string]any{
"name": "Rest RT",
- "exercises": []map[string]any{
- {"exercise_id": exID, "rest_seconds": 0, "sets": []map[string]any{{"target_reps": 5, "target_weight": 100}}},
+ "days": []map[string]any{
+ {
+ "is_rest_day": false,
+ "exercises": []map[string]any{
+ {"exercise_id": exID, "rest_seconds": 0, "sets": []map[string]any{{"target_reps": 5, "target_weight": 100}}},
+ },
+ },
},
}
c, w := newContext(uid, http.MethodPost, "/api/v1/programs", body)
@@ -45,7 +50,8 @@ func TestProgramRestSecondsRoundTrips(t *testing.T) {
t.Fatalf("create program: %d (%s)", w.Code, w.Body.String())
}
// 0 = "off" must round-trip as 0, not get defaulted away.
- exs := decodeResponse(t, w)["data"].(map[string]any)["exercises"].([]any)
+ days := decodeResponse(t, w)["data"].(map[string]any)["days"].([]any)
+ exs := days[0].(map[string]any)["exercises"].([]any)
if rest := exs[0].(map[string]any)["rest_seconds"].(float64); rest != 0 {
t.Errorf("program exercise rest_seconds = %v, want 0", rest)
}
diff --git a/backend/controllers/testhelper_test.go b/backend/controllers/testhelper_test.go
index 43e7faa..670ec9f 100644
--- a/backend/controllers/testhelper_test.go
+++ b/backend/controllers/testhelper_test.go
@@ -76,8 +76,13 @@ CREATE TABLE IF NOT EXISTS workouts (
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
+ 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,
@@ -104,9 +109,17 @@ CREATE TABLE IF NOT EXISTS programs (
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 '',
diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.go
index 43ca530..1d1d523 100644
--- a/backend/controllers/workouts.go
+++ b/backend/controllers/workouts.go
@@ -3,7 +3,6 @@ package controllers
import (
"database/sql"
"strconv"
- "time"
"github.com/Cawlumm/lyftr-backend/middleware"
"github.com/Cawlumm/lyftr-backend/models"
@@ -77,9 +76,12 @@ func (h *Handler) CreateWorkout(c *gin.Context) {
utils.ValidationError(c, err)
return
}
- if req.StartedAt.IsZero() {
- req.StartedAt = time.Now()
- }
+ // The due-day tracker orders workouts by started_at as stored TEXT, and the
+ // driver stores a time.Time with its zone suffix — a non-UTC offset would
+ // compare by wall-clock text, not instant, mis-ordering the anchor lookup
+ // (ProgramStore.currentDayIndex). normalizeLoggedAt both defaults a zero time
+ // to now and forces UTC, same as weight logs.
+ req.StartedAt = normalizeLoggedAt(req.StartedAt)
// 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 there
@@ -112,6 +114,11 @@ func (h *Handler) UpdateWorkout(c *gin.Context) {
utils.ValidationError(c, err)
return
}
+ // Same UTC normalization as CreateWorkout — stored started_at text ordering is
+ // load-bearing for the due-day tracker. A zero StartedAt (request omitted it)
+ // stays zero: the store then preserves the stored timestamp instead of
+ // rewriting it to 0001-01-01 (WorkoutStore.Update).
+ req.StartedAt = req.StartedAt.UTC()
w, err := h.s.Workout.Update(uid, wid, req)
if err == sql.ErrNoRows {
utils.NotFound(c, "workout not found")
diff --git a/backend/controllers/workouts_test.go b/backend/controllers/workouts_test.go
index 90a954b..2bef031 100644
--- a/backend/controllers/workouts_test.go
+++ b/backend/controllers/workouts_test.go
@@ -203,6 +203,48 @@ func TestUpdateWorkout_preservesStartedAt(t *testing.T) {
}
}
+// TestUpdateWorkout_OmittedStartedAtKeepsStoredValue: a PUT that omits started_at
+// (name/notes-only patch) must not rewrite the stored timestamp to the zero time —
+// stored started_at ordering is the due-day tracker's anchor
+// (ProgramStore.currentDayIndex), so a 0001-01-01 rewrite would silently drop the
+// workout to oldest and rewire which row anchors the tracker.
+func TestUpdateWorkout_OmittedStartedAtKeepsStoredValue(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ originalTime := "2024-03-01T08:00:00Z"
+ res, _ := db.DB.Exec(
+ `INSERT INTO workouts (user_id, name, started_at) VALUES (?, ?, ?)`,
+ uid, "Original Name", originalTime,
+ )
+ wid, _ := res.LastInsertId()
+
+ body := map[string]any{ // no started_at
+ "name": "Renamed",
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID,
+ "sets": []map[string]any{{"set_number": 1, "reps": 10, "weight": 50.0}},
+ },
+ },
+ }
+ c, w := newContext(uid, http.MethodPut, "/api/v1/workouts/"+fmt.Sprint(wid), body)
+ setParam(c, "id", fmt.Sprint(wid))
+ th.UpdateWorkout(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var stored string
+ if err := db.DB.QueryRow(`SELECT CAST(started_at AS TEXT) FROM workouts WHERE id = ?`, wid).Scan(&stored); err != nil {
+ t.Fatalf("read stored started_at: %v", err)
+ }
+ if stored != originalTime {
+ t.Fatalf("started_at rewritten by an update that omitted it: got %q, want %q", stored, originalTime)
+ }
+}
+
func TestListWorkouts_limitCap(t *testing.T) {
setupTestDB(t)
uid := createTestUser(t)
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index d778070..fbca86d 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -1,6 +1,11 @@
package db
-import "log"
+import (
+ "database/sql"
+ "log"
+ "strings"
+ "time"
+)
func migrate() error {
_, err := DB.Exec(schema)
@@ -55,15 +60,279 @@ func alterMigrations() {
ensureColumn("program_sets", "suggested_weight", `ALTER TABLE program_sets ADD COLUMN suggested_weight REAL`)
ensureColumn("program_sets", "suggested_reps", `ALTER TABLE program_sets ADD COLUMN suggested_reps INTEGER`)
ensureColumn("program_sets", "suggested_is_pr", `ALTER TABLE program_sets ADD COLUMN suggested_is_pr INTEGER NOT NULL DEFAULT 0`)
+
+ multiDayProgramsMigration()
+
+ // Lets a logged workout be attributed back to the routine it came from, so a
+ // program's cycle position (Program.CurrentDayIndex) can be derived from what was
+ // actually logged — see ProgramStore.currentDayIndex. Best-effort/no FK:
+ // deleting a program must never take workout history down with it.
+ 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)`)
+
+ workoutProgramDayMigration()
+
+ normalizeWorkoutStartedAt()
}
-// ensureColumn adds a column to a table if it's missing — idempotent on every boot.
-func ensureColumn(table, column, alterSQL string) {
- rows, err := DB.Query("PRAGMA table_info(" + table + ")")
+// normalizeWorkoutStartedAt rewrites any workouts.started_at stored with a non-UTC
+// zone offset to its UTC equivalent. The due-day tracker compares started_at as
+// stored TEXT (ProgramStore.currentDayIndex orders by it and compares rows against
+// the anchor lexicographically), and the driver's default write format embeds the
+// 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
+// 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).
+//
+// The WHERE's leading-wildcard LIKEs can't use an index, so once a boot finds zero
+// matching rows (every offending row fixed — new rows are already written UTC by
+// the controllers' write-side normalization), a migration_flags row records that so
+// every later boot skips the scan entirely instead of re-running it forever. The
+// 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")
+ if err != nil {
+ log.Printf("normalizeWorkoutStartedAt: check flag: %v (skipping this boot)", 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%'`)
if err != nil {
+ log.Printf("normalizeWorkoutStartedAt: query: %v (skipping this boot)", err)
return
}
- has := false
+ type fix struct {
+ id int64
+ t time.Time
+ }
+ var fixes []fix
+ matched := 0
+ for rows.Next() {
+ matched++
+ var id int64
+ var v any
+ if err := rows.Scan(&id, &v); err != nil {
+ rows.Close()
+ log.Printf("normalizeWorkoutStartedAt: scan: %v (skipping this boot)", err)
+ return
+ }
+ switch tv := v.(type) {
+ case time.Time:
+ fixes = append(fixes, fix{id, tv.UTC()})
+ case string:
+ 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)
+ }
+ default:
+ log.Printf("normalizeWorkoutStartedAt: workout %d: unexpected started_at type %T left as-is", id, v)
+ }
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ log.Printf("normalizeWorkoutStartedAt: rows: %v (skipping this boot)", 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 len(fixes) > 0 {
+ log.Printf("migration: normalized %d non-UTC workouts.started_at row(s) to UTC", len(fixes))
+ }
+ if matched == 0 {
+ setMigrationFlag("normalize_workout_started_at")
+ }
+}
+
+// parseStoredTime parses a stored started_at the driver itself couldn't convert to
+// a time.Time. The driver's default write format is time.Time.String(); a fixed-
+// offset zone with no name (what encoding/json produces for a '+08:00' timestamp)
+// renders the offset twice ('2026-07-19 02:00:00 +0800 +0800'), which the MST
+// layout element can't match — drop the trailing zone-name token and parse
+// offset-only. Tried before that: the offset-only layout against the untouched
+// string, for rows that are already plain "date time -0700" with no name to
+// strip — chopping the last token there would eat the offset itself and always
+// fail.
+func parseStoredTime(s string) (time.Time, bool) {
+ s = strings.TrimSpace(s)
+ if t, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", s); err == nil {
+ return t, true
+ }
+ if t, err := time.Parse("2006-01-02 15:04:05.999999999 -0700", s); err == nil {
+ return t, true
+ }
+ if i := strings.LastIndexByte(s, ' '); i > 0 {
+ if t, err := time.Parse("2006-01-02 15:04:05.999999999 -0700", s[:i]); err == nil {
+ return t, true
+ }
+ }
+ return time.Time{}, false
+}
+
+// workoutProgramDayMigration adds workouts.program_day_id: WHICH specific program Day
+// a workout was logged under, so the due-day tracker follows what was actually logged
+// instead of a blind workout count (which desyncs when a day is repeated or logged out
+// of order). ON DELETE SET NULL, not CASCADE — a workout's history must survive its
+// day later being deleted/edited; only the day linkage drops.
+//
+// The backfill runs ONLY when the column is first added: pre-existing program workouts
+// are attributed to their program's first workout day (lowest order_index, non-rest).
+// That's a best-effort default for the transitional window between the multi-day
+// migration above and this one — not expected to be exact for every historical row.
+// It must never re-run on a later boot: a NULL program_day_id can then also mean "its
+// day was deleted" (the SET NULL path), which a re-run would wrongly overwrite.
+func workoutProgramDayMigration() {
+ has, err := hasColumn("workouts", "program_day_id")
+ if err != nil {
+ // Unknown schema state: skip entirely (retried next boot) rather than risk a
+ // duplicate-column ALTER or, far worse, re-running the never-re-run backfill.
+ log.Printf("workoutProgramDayMigration: check column: %v (skipping this boot)", err)
+ return
+ }
+ if !has {
+ // ALTER + backfill must land atomically (SQLite DDL is transactional): if the
+ // backfill died after a committed ALTER, every later boot would see the column
+ // and skip the backfill forever — the transitional rows would stay NULL with
+ // no recovery path, since re-running is forbidden per above.
+ tx, err := DB.Begin()
+ if err != nil {
+ log.Fatalf("workoutProgramDayMigration: begin: %v", err)
+ }
+ if _, err := tx.Exec(`ALTER TABLE workouts ADD COLUMN program_day_id INTEGER REFERENCES program_days(id) ON DELETE SET NULL`); err != nil {
+ tx.Rollback()
+ log.Fatalf("alter workouts add program_day_id: %v", err)
+ }
+ if _, err := tx.Exec(`
+ UPDATE workouts SET program_day_id = (
+ SELECT pd.id FROM program_days pd
+ WHERE pd.program_id = workouts.program_id AND pd.is_rest_day = 0
+ ORDER BY pd.order_index LIMIT 1
+ )
+ WHERE program_id IS NOT NULL AND program_day_id IS NULL`); err != nil {
+ tx.Rollback()
+ log.Fatalf("backfill workouts.program_day_id: %v", err)
+ }
+ if err := tx.Commit(); err != nil {
+ log.Fatalf("workoutProgramDayMigration: commit: %v", err)
+ }
+ log.Println("migration: added workouts.program_day_id (+ first-workout-day backfill)")
+ }
+ ensureIndex("idx_workouts_program_day", `CREATE INDEX IF NOT EXISTS idx_workouts_program_day ON workouts(program_day_id)`)
+
+ // program_day_dropped = 1 marks a workout whose day linkage was deliberately
+ // removed by a routine edit deleting that day (ProgramStore.Update sets it
+ // alongside the NULL). It splits the two meanings of a NULL program_day_id the
+ // due-day tracker must treat differently: an old-client day-less log advances
+ // the tracker count-based, but deletion residue must not — deleting a day with
+ // a long logged history would otherwise swing the due day by the parity of an
+ // arbitrary lifetime count (see ProgramStore.currentDayIndex). NULL rows that
+ // predate this column can't be told apart retroactively and stay count-based;
+ // acceptable for the transitional window between the column-add above and this.
+ ensureColumn("workouts", "program_day_dropped", `ALTER TABLE workouts ADD COLUMN program_day_dropped INTEGER NOT NULL DEFAULT 0`)
+}
+
+// multiDayProgramsMigration adds the program_days table + program_exercises'
+// program_day_id FK (multi-day routines w/ rest days). Non-destructive: every
+// program that predates this migration gets wrapped in exactly one auto-created
+// workout Day (order_index 0) that takes over its existing program_exercises rows —
+// no data loss, and the routine keeps behaving exactly as a single-session template
+// until the user edits it into multiple days.
+func multiDayProgramsMigration() {
+ if _, err := DB.Exec(`
+ 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 ''
+ )`); err != nil {
+ log.Fatalf("create program_days: %v", err)
+ }
+ ensureIndex("idx_program_days_program", `CREATE INDEX IF NOT EXISTS idx_program_days_program ON program_days(program_id, order_index)`)
+
+ ensureColumn("program_exercises", "program_day_id",
+ `ALTER TABLE program_exercises ADD COLUMN program_day_id INTEGER REFERENCES program_days(id) ON DELETE CASCADE`)
+ ensureIndex("idx_program_exercises_day", `CREATE INDEX IF NOT EXISTS idx_program_exercises_day ON program_exercises(program_day_id)`)
+
+ // Backfill: every pre-existing program (whether or not it has any exercises yet —
+ // an empty routine was a valid state under the old flat model) gets a single
+ // wrapper Day. Idempotent — a program only ever lacks a Day once. Gated behind a
+ // migration_flags row (same pattern as normalizeWorkoutStartedAt) once a boot
+ // finds zero orphaned programs, so this anti-join isn't rescanning the whole
+ // programs table on every single startup forever — every program gets a Day
+ // right here or at Create time from now on, so "zero orphans" is permanent.
+ done, err := hasMigrationFlag("multi_day_programs_backfilled")
+ if err != nil {
+ log.Printf("multiDayProgramsMigration: check flag: %v (skipping this boot)", err)
+ return
+ }
+ if done {
+ return
+ }
+ rows, err := DB.Query(`
+ SELECT p.id
+ FROM programs p
+ WHERE NOT EXISTS (SELECT 1 FROM program_days pd WHERE pd.program_id = p.id)`)
+ if err != nil {
+ log.Fatalf("multiDayProgramsMigration: query orphaned programs: %v", err)
+ }
+ var programIDs []int64
+ for rows.Next() {
+ var pid int64
+ if err := rows.Scan(&pid); err != nil {
+ rows.Close()
+ log.Fatalf("multiDayProgramsMigration: scan: %v", err)
+ }
+ programIDs = append(programIDs, pid)
+ }
+ rows.Close()
+
+ for _, pid := range programIDs {
+ res, err := DB.Exec(`INSERT INTO program_days (program_id, order_index, is_rest_day, name) VALUES (?, 0, 0, '')`, pid)
+ if err != nil {
+ log.Fatalf("multiDayProgramsMigration: insert wrapper day for program %d: %v", pid, err)
+ }
+ dayID, err := res.LastInsertId()
+ if err != nil {
+ log.Fatalf("multiDayProgramsMigration: wrapper day id for program %d: %v", pid, err)
+ }
+ if _, err := DB.Exec(`UPDATE program_exercises SET program_day_id = ? WHERE program_id = ? AND program_day_id IS NULL`, dayID, pid); err != nil {
+ log.Fatalf("multiDayProgramsMigration: backfill program_day_id for program %d: %v", pid, err)
+ }
+ log.Printf("migration: wrapped program %d in a single Day", pid)
+ }
+ if len(programIDs) == 0 {
+ setMigrationFlag("multi_day_programs_backfilled")
+ }
+}
+
+// hasColumn reports whether a table already has a column (PRAGMA table_info).
+// A query/scan failure is returned as an error, never as "column absent" — a
+// false negative would send callers into an ALTER that dies on "duplicate
+// column name" (or worse, re-runs a never-re-run backfill).
+func hasColumn(table, column string) (bool, error) {
+ rows, err := DB.Query("PRAGMA table_info(" + table + ")")
+ if err != nil {
+ return false, err
+ }
+ defer rows.Close()
+ found := false
for rows.Next() {
var cid int
var name, typ string
@@ -71,13 +340,25 @@ func ensureColumn(table, column, alterSQL string) {
var dflt interface{}
var pk int
if err := rows.Scan(&cid, &name, &typ, &notnull, &dflt, &pk); err != nil {
- continue
+ return false, err
}
if name == column {
- has = true
+ found = true
}
}
- rows.Close()
+ return found, rows.Err()
+}
+
+// ensureColumn adds a column to a table if it's missing — idempotent on every boot.
+// If the existence check itself fails, the alter is skipped (retried next boot),
+// matching the pre-refactor silent-skip behavior rather than risking a fatal
+// duplicate-column ALTER off an unknown schema state.
+func ensureColumn(table, column, alterSQL string) {
+ has, err := hasColumn(table, column)
+ if err != nil {
+ log.Printf("migrations: check %s.%s: %v (skipping alter this boot)", table, column, err)
+ return
+ }
if !has {
if _, err := DB.Exec(alterSQL); err != nil {
log.Fatalf("alter %s add %s: %v", table, column, err)
@@ -86,6 +367,42 @@ func ensureColumn(table, column, alterSQL string) {
}
}
+// ensureIndex creates an index if it's missing — IF NOT EXISTS already makes this
+// idempotent at the SQL level, so unlike ensureColumn there's no existence check to
+// get wrong; this just gives the 3-line "Exec + Fatalf" shape a name instead of
+// repeating it at every call site.
+func ensureIndex(name, createSQL string) {
+ if _, err := DB.Exec(createSQL); err != nil {
+ log.Fatalf("create %s: %v", name, err)
+ }
+}
+
+// migration_flags records one-off migrations that must run at most once total,
+// never again per boot — distinct from ensureColumn/ensureIndex, whose underlying
+// SQL is already idempotent and safe to re-issue every boot. hasMigrationFlag creates
+// the table lazily (rather than via the schema/alterMigrations startup path) so a
+// caller can check it standalone.
+func hasMigrationFlag(name string) (bool, error) {
+ if _, err := DB.Exec(`CREATE TABLE IF NOT EXISTS migration_flags (name TEXT PRIMARY KEY)`); err != nil {
+ return false, err
+ }
+ var n string
+ err := DB.QueryRow(`SELECT name FROM migration_flags WHERE name = ?`, name).Scan(&n)
+ if err == sql.ErrNoRows {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
+func setMigrationFlag(name string) {
+ if _, err := DB.Exec(`INSERT OR IGNORE INTO migration_flags (name) VALUES (?)`, name); err != nil {
+ log.Printf("setMigrationFlag(%s): %v", name, err)
+ }
+}
+
const schema = `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.go
new file mode 100644
index 0000000..987e60b
--- /dev/null
+++ b/backend/db/migrations_test.go
@@ -0,0 +1,314 @@
+package db
+
+import (
+ "database/sql"
+ "fmt"
+ "math/rand"
+ "testing"
+
+ _ "modernc.org/sqlite"
+)
+
+// setupMigrationTestDB points the package-level DB at a fresh in-memory sqlite and
+// runs the base schema (but NOT alterMigrations — callers seed pre-migration rows in
+// between the two, same as a real upgrade of an existing database). Foreign keys are
+// on, matching the production DSN — the program_day_id ON DELETE SET NULL behavior
+// under test only exists with them enforced.
+func setupMigrationTestDB(t *testing.T) {
+ t.Helper()
+ name := fmt.Sprintf("file:migtestdb_%d?mode=memory&cache=shared&_pragma=foreign_keys(on)", rand.Int63())
+ conn, err := sql.Open("sqlite", name)
+ if err != nil {
+ t.Fatalf("open test db: %v", err)
+ }
+ t.Cleanup(func() { conn.Close() })
+ DB = conn
+ if err := migrate(); err != nil {
+ t.Fatalf("apply base schema: %v", err)
+ }
+}
+
+// TestMultiDayProgramsMigration_WrapsExerciselessProgram is the regression check for
+// the review finding: a pre-existing program with zero program_exercises rows (a
+// valid state under the old flat model) must still come out of the migration with
+// exactly one auto-created wrapper Day, not zero Days.
+func TestMultiDayProgramsMigration_WrapsExerciselessProgram(t *testing.T) {
+ setupMigrationTestDB(t)
+
+ res, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'x')`)
+ if err != nil {
+ t.Fatalf("seed user: %v", err)
+ }
+ uid, _ := res.LastInsertId()
+ res, err = DB.Exec(`INSERT INTO programs (user_id, name) VALUES (?, 'Empty Routine')`, uid)
+ if err != nil {
+ t.Fatalf("seed program: %v", err)
+ }
+ pid, _ := res.LastInsertId()
+
+ multiDayProgramsMigration()
+
+ var count int
+ if err := DB.QueryRow(`SELECT COUNT(*) FROM program_days WHERE program_id = ?`, pid).Scan(&count); err != nil {
+ t.Fatalf("count program_days: %v", err)
+ }
+ if count != 1 {
+ t.Fatalf("expected the exerciseless program to get exactly 1 wrapper Day, got %d", count)
+ }
+ var orderIndex, isRest int
+ if err := DB.QueryRow(`SELECT order_index, is_rest_day FROM program_days WHERE program_id = ?`, pid).
+ Scan(&orderIndex, &isRest); err != nil {
+ t.Fatalf("read wrapper day: %v", err)
+ }
+ if orderIndex != 0 || isRest != 0 {
+ t.Fatalf("expected wrapper day order_index=0 is_rest_day=0, got order_index=%d is_rest_day=%d", orderIndex, isRest)
+ }
+}
+
+// TestMultiDayProgramsMigration_IsIdempotent running it twice must not create a
+// second wrapper Day for a program that already has one (matches the real boot path,
+// where alterMigrations runs on every startup).
+func TestMultiDayProgramsMigration_IsIdempotent(t *testing.T) {
+ setupMigrationTestDB(t)
+
+ res, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'x')`)
+ if err != nil {
+ t.Fatalf("seed user: %v", err)
+ }
+ uid, _ := res.LastInsertId()
+ res, err = DB.Exec(`INSERT INTO programs (user_id, name) VALUES (?, 'Routine')`, uid)
+ if err != nil {
+ t.Fatalf("seed program: %v", err)
+ }
+ pid, _ := res.LastInsertId()
+
+ multiDayProgramsMigration()
+ multiDayProgramsMigration()
+
+ var count int
+ if err := DB.QueryRow(`SELECT COUNT(*) FROM program_days WHERE program_id = ?`, pid).Scan(&count); err != nil {
+ t.Fatalf("count program_days: %v", err)
+ }
+ if count != 1 {
+ t.Fatalf("expected exactly 1 wrapper Day after running the migration twice, got %d", count)
+ }
+}
+
+func countRow(t *testing.T, query string, args ...any) int {
+ t.Helper()
+ var n int
+ if err := DB.QueryRow(query, args...).Scan(&n); err != nil {
+ t.Fatalf("count %q: %v", query, err)
+ }
+ return n
+}
+
+// TestUpgradeFromPreDayStructureDeployment simulates upgrading a REAL older install
+// straight to HEAD: the base schema plus the progressive-overload (#40) columns is
+// exactly what a deployment running #40 but predating the multi-day rework had on
+// disk. Seed old-shape user data — a flat program with exercises, an UNRESOLVED
+// staged suggestion, logged workout history — then run the full alterMigrations()
+// sequence (the multi-day rework AND the program_day_id fix in one boot) and assert
+// zero data loss.
+func TestUpgradeFromPreDayStructureDeployment(t *testing.T) {
+ setupMigrationTestDB(t)
+ // The #40-era columns that deployment already had (same ensureColumn calls its
+ // boots ran).
+ ensureColumn("program_sets", "suggested_weight", `ALTER TABLE program_sets ADD COLUMN suggested_weight REAL`)
+ ensureColumn("program_sets", "suggested_reps", `ALTER TABLE program_sets ADD COLUMN suggested_reps INTEGER`)
+ ensureColumn("program_sets", "suggested_is_pr", `ALTER TABLE program_sets ADD COLUMN suggested_is_pr INTEGER NOT NULL DEFAULT 0`)
+
+ 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 exercises (name) VALUES ('Bench Press')`); err != nil {
+ t.Fatalf("seed exercise: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO programs (user_id, name) VALUES (1, 'Old Flat Program')`); err != nil {
+ t.Fatalf("seed program: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO program_exercises (program_id, exercise_id, order_index) VALUES (1, 1, 0)`); err != nil {
+ t.Fatalf("seed program exercise: %v", err)
+ }
+ if _, err := DB.Exec(
+ `INSERT INTO program_sets (program_exercise_id, set_number, target_reps, target_weight, suggested_weight, suggested_reps, suggested_is_pr)
+ VALUES (1, 1, 5, 135, 140, 5, 1)`); err != nil {
+ t.Fatalf("seed program set: %v", err)
+ }
+ // Logged history — pre-day workouts had no program linkage at all.
+ if _, err := DB.Exec(`INSERT INTO workouts (user_id, name) VALUES (1, 'Old Workout')`); err != nil {
+ t.Fatalf("seed workout: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO workout_exercises (workout_id, exercise_id) VALUES (1, 1)`); err != nil {
+ t.Fatalf("seed workout exercise: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO sets (workout_exercise_id, reps, weight) VALUES (1, 5, 135)`); err != nil {
+ t.Fatalf("seed set: %v", err)
+ }
+
+ alterMigrations()
+
+ // The flat program got wrapped in exactly one workout Day that owns its exercises.
+ if n := countRow(t, `SELECT COUNT(*) FROM program_days WHERE program_id = 1 AND is_rest_day = 0 AND order_index = 0`); n != 1 {
+ t.Fatalf("expected exactly 1 wrapper day, got %d", n)
+ }
+ if n := countRow(t, `SELECT COUNT(*) FROM program_exercises WHERE program_id = 1 AND program_day_id IS NULL`); n != 0 {
+ t.Fatalf("expected no orphaned program_exercises, got %d", n)
+ }
+ // The staged (#40) suggestion survived both migrations untouched.
+ var sw float64
+ var sr, spr int
+ if err := DB.QueryRow(`SELECT suggested_weight, suggested_reps, suggested_is_pr FROM program_sets WHERE id = 1`).Scan(&sw, &sr, &spr); err != nil {
+ t.Fatalf("read staged suggestion: %v", err)
+ }
+ if sw != 140 || sr != 5 || spr != 1 {
+ t.Fatalf("staged suggestion mutated by migrations: got weight=%v reps=%d is_pr=%d", sw, sr, spr)
+ }
+ // Workout history intact; the pre-day workout has no program linkage, so the
+ // program_day_id backfill must NOT invent one (it only touches program_id rows).
+ if n := countRow(t, `SELECT COUNT(*) FROM workouts`); n != 1 {
+ t.Fatalf("workout history lost: %d rows", n)
+ }
+ if n := countRow(t, `SELECT COUNT(*) FROM workouts WHERE program_day_id IS NOT NULL`); n != 0 {
+ t.Fatalf("backfill wrongly linked a non-program workout")
+ }
+ if n := countRow(t, `SELECT COUNT(*) FROM sets WHERE reps = 5 AND weight = 135`); n != 1 {
+ t.Fatalf("logged sets lost")
+ }
+ // Invariant (#40 / day-delete safety): logged sets never persist a program_set_id
+ // FK back to the routine — the column must not exist after any migration.
+ if has, err := hasColumn("sets", "program_set_id"); err != nil {
+ t.Fatalf("check sets.program_set_id: %v", err)
+ } else if has {
+ t.Fatalf("sets grew a program_set_id column — logged history must never hold a live FK into program_sets")
+ }
+ // Re-running the whole sequence is idempotent (every boot runs it).
+ alterMigrations()
+ if n := countRow(t, `SELECT COUNT(*) FROM program_days WHERE program_id = 1`); n != 1 {
+ t.Fatalf("second boot duplicated wrapper days: %d", n)
+ }
+}
+
+// TestNormalizeWorkoutStartedAt_RewritesPreFixOffsetRows seeds started_at text in
+// every shape a pre-UTC-normalization deployment could have written — a no-name
+// fixed-offset zone ('+0800 +0800', the driver's String() of a JSON '+08:00'
+// timestamp, unreadable as time.Time), a named-zone offset ('-0500 EST'), a UTC row,
+// and a CURRENT_TIMESTAMP-shaped row — and asserts the backfill rewrites only the
+// non-UTC rows to UTC so stored-text ordering matches instant ordering.
+func TestNormalizeWorkoutStartedAt_RewritesPreFixOffsetRows(t *testing.T) {
+ setupMigrationTestDB(t)
+ if _, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('tz@user', 'x')`); err != nil {
+ t.Fatalf("seed user: %v", err)
+ }
+ insert := func(name, startedAt string) int64 {
+ t.Helper()
+ res, err := DB.Exec(`INSERT INTO workouts (user_id, name, started_at) VALUES (1, ?, ?)`, name, startedAt)
+ if err != nil {
+ t.Fatalf("seed workout %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(started_at AS TEXT) FROM workouts WHERE id = ?`, id).Scan(&s); err != nil {
+ t.Fatalf("read started_at of %d: %v", id, err)
+ }
+ return s
+ }
+
+ // Wall-clock 02:00 the "next day" but instant 2026-07-18 18:00Z — raw text
+ // ordering would wrongly rank it newest.
+ fixedOffset := insert("fixed-offset", "2026-07-19 02:00:00 +0800 +0800")
+ utc := insert("utc", "2026-07-18 20:00:00 +0000 UTC")
+ // Instant 2026-07-19 02:00Z — the true most recent.
+ namedZone := insert("named-zone", "2026-07-18 21:00:00 -0500 EST")
+ plain := insert("plain", "2026-07-10 08:00:00")
+
+ normalizeWorkoutStartedAt()
+
+ 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)
+ }
+ // Text ordering is now chronological: the named-zone row is the true most recent.
+ var newest int64
+ if err := DB.QueryRow(`SELECT id FROM workouts ORDER BY started_at DESC, id DESC LIMIT 1`).Scan(&newest); err != nil {
+ t.Fatalf("order query: %v", err)
+ }
+ if newest != namedZone {
+ t.Fatalf("expected the -0500 row (id %d) to text-order newest after normalization, got id %d", namedZone, newest)
+ }
+ // Idempotent: a second boot finds nothing to rewrite.
+ normalizeWorkoutStartedAt()
+ if got := storedText(fixedOffset); got != "2026-07-18 18:00:00 +0000 UTC" {
+ t.Fatalf("second run changed an already-normalized row: %q", got)
+ }
+}
+
+// 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
+// backfill must attribute those rows to the program's FIRST workout day (lowest
+// order_index, non-rest — not merely order_index 0, which can be a rest slot) — and
+// must never re-run once the column exists, because a NULL can then also mean "its
+// day was deleted" (ON DELETE SET NULL), which a re-run would wrongly overwrite.
+func TestProgramDayBackfillTransitionalWindow(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 programs (user_id, name) VALUES (1, 'Cycle')`); err != nil {
+ t.Fatalf("seed program: %v", err)
+ }
+
+ // Bring the DB to the multi-day release's shape, then rebuild the cycle so its
+ // FIRST slot is a rest day.
+ multiDayProgramsMigration()
+ ensureColumn("workouts", "program_id", `ALTER TABLE workouts ADD COLUMN program_id INTEGER`)
+ if _, err := DB.Exec(`DELETE FROM program_days WHERE program_id = 1`); err != nil {
+ t.Fatalf("clear wrapper day: %v", err)
+ }
+ var dayIDs [3]int64
+ for i, rest := range []int{1, 0, 0} { // 0=Rest 1=A 2=B
+ res, err := DB.Exec(`INSERT INTO program_days (program_id, order_index, is_rest_day, name) VALUES (1, ?, ?, '')`, i, rest)
+ if err != nil {
+ t.Fatalf("seed day %d: %v", i, err)
+ }
+ dayIDs[i], _ = res.LastInsertId()
+ }
+ // Two transitional-window workouts: attributed to the program, day unknown.
+ for i := 0; i < 2; i++ {
+ if _, err := DB.Exec(`INSERT INTO workouts (user_id, name, program_id) VALUES (1, 'w', 1)`); err != nil {
+ t.Fatalf("seed transitional workout: %v", err)
+ }
+ }
+
+ workoutProgramDayMigration()
+
+ if n := countRow(t, `SELECT COUNT(*) FROM workouts WHERE program_id = 1 AND program_day_id = ?`, dayIDs[1]); n != 2 {
+ t.Fatalf("expected both transitional workouts backfilled to the first WORKOUT day (A), got %d", n)
+ }
+
+ // Delete day A → SET NULL on its workouts; a re-run must NOT re-backfill them.
+ if _, err := DB.Exec(`DELETE FROM program_days WHERE id = ?`, dayIDs[1]); err != nil {
+ t.Fatalf("delete day A: %v", err)
+ }
+ if n := countRow(t, `SELECT COUNT(*) FROM workouts WHERE program_day_id IS NULL`); n != 2 {
+ t.Fatalf("ON DELETE SET NULL didn't drop the linkage: %d null rows", n)
+ }
+ workoutProgramDayMigration()
+ if n := countRow(t, `SELECT COUNT(*) FROM workouts WHERE program_day_id IS NULL`); n != 2 {
+ t.Fatalf("backfill re-ran on an already-migrated DB and overwrote SET NULL rows")
+ }
+}
diff --git a/backend/models/models.go b/backend/models/models.go
index b13326b..b10716f 100644
--- a/backend/models/models.go
+++ b/backend/models/models.go
@@ -200,14 +200,19 @@ type RefreshRequest struct {
const MaxWorkoutSets = 500
type CreateWorkoutRequest struct {
- Name string `json:"name" validate:"required"`
- Notes string `json:"notes"`
- Duration int `json:"duration"`
- StartedAt time.Time `json:"started_at"`
+ Name string `json:"name" validate:"required"`
+ Notes string `json:"notes"`
+ Duration int `json:"duration"`
+ StartedAt time.Time `json:"started_at"`
// 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.
- ProgramID *int64 `json:"program_id"`
+ ProgramID *int64 `json:"program_id"`
+ // ProgramDayID is WHICH day of that routine's cycle the workout was started
+ // under (the client's day picker knows) — drives the day-accurate due-day
+ // tracker (ProgramStore.currentDayIndex). nil when not from a routine, or from
+ // an older client that predates day tracking.
+ ProgramDayID *int64 `json:"program_day_id"`
// Exercises/Sets each cap at max=500 as an outer sanity bound, but that bounds
// each dimension independently, not their product — see MaxWorkoutSets above for
// the cap that actually matters.
@@ -281,23 +286,44 @@ type UpdateSettingsRequest struct {
}
type Program struct {
- ID int64 `json:"id"`
- UserID int64 `json:"user_id,omitempty"`
- Name string `json:"name"`
- Notes string `json:"notes"`
- CreatedAt time.Time `json:"created_at"`
- Exercises []ProgramExercise `json:"exercises"`
+ ID int64 `json:"id"`
+ UserID int64 `json:"user_id,omitempty"`
+ Name string `json:"name"`
+ Notes string `json:"notes"`
+ CreatedAt time.Time `json:"created_at"`
+ Days []ProgramDay `json:"days"`
+ // CurrentDayIndex is which entry of Days is due today — computed, never
+ // persisted, from WHICH day the most recent program workout was logged against
+ // (workouts.program_day_id): the next workout day after it in cycle order,
+ // wrapping past rest days (rest days are never "due") — see
+ // ProgramStore.currentDayIndex. Advancing only on an actual logged workout
+ // means there's no calendar-week alignment (a 6-day cycle repeats every 6 days
+ // regardless of which weekday it lands on). Always a workout day's index when
+ // the program has any; 0 for a program with no days (or only rest days).
+ CurrentDayIndex int `json:"current_day_index"`
+}
+
+// ProgramDay is one slot in a program's repeating cycle: either a workout day (its
+// own ordered Exercises/Sets) or a rest day (Exercises always empty). Days repeat in
+// OrderIndex order once the sequence is exhausted — see Program.CurrentDayIndex.
+type ProgramDay struct {
+ ID int64 `json:"id,omitempty"`
+ ProgramID int64 `json:"program_id,omitempty"`
+ OrderIndex int `json:"order_index"`
+ IsRestDay bool `json:"is_rest_day"`
+ Name string `json:"name"`
+ Exercises []ProgramExercise `json:"exercises"`
}
type ProgramExercise struct {
- ID int64 `json:"id,omitempty"`
- ProgramID int64 `json:"program_id,omitempty"`
- ExerciseID int64 `json:"exercise_id"`
- OrderIndex int `json:"order_index,omitempty"`
- Notes string `json:"notes"`
- RestSeconds int `json:"rest_seconds"`
- Exercise Exercise `json:"exercise"`
- Sets []ProgramSet `json:"sets"`
+ ID int64 `json:"id,omitempty"`
+ ProgramDayID int64 `json:"program_day_id,omitempty"`
+ ExerciseID int64 `json:"exercise_id"`
+ OrderIndex int `json:"order_index,omitempty"`
+ Notes string `json:"notes"`
+ RestSeconds int `json:"rest_seconds"`
+ Exercise Exercise `json:"exercise"`
+ Sets []ProgramSet `json:"sets"`
}
type ProgramSet struct {
@@ -314,17 +340,50 @@ type ProgramSet struct {
SuggestedIsPR bool `json:"suggested_is_pr,omitempty"`
}
+// MaxProgramRows bounds the TOTAL number of rows (days + exercises + sets combined)
+// a CreateProgramRequest can insert in one transaction — enforced by the
+// struct-level validation registered in controllers/programs.go's init(). Days/
+// Exercises/Sets each also carry their own max=500 per-list cap below as a
+// belt-and-suspenders bound, but a program nests three levels (Days x Exercises x
+// Sets), so those alone don't bound the product (500 x 500 x 500 rows) — see
+// MaxWorkoutSets above for the two-level version of this same reasoning.
+// insertProgramDays (program.go) issues one tx.Exec per row inside a single
+// transaction holding the process's only SQLite connection (db.DB.SetMaxOpenConns(1)).
+const MaxProgramRows = 2000
+
type CreateProgramRequest struct {
- Name string `json:"name" validate:"required"`
- Notes string `json:"notes"`
- Exercises []CreateProgramExerciseReq `json:"exercises"`
+ Name string `json:"name" validate:"required"`
+ Notes string `json:"notes"`
+ Days []CreateProgramDayReq `json:"days" validate:"max=500,dive"`
+ // DayIDsKnown marks a client that round-trips day ids (CreateProgramDayReq.ID)
+ // on update. Update falls back to positional day matching for id-less requests
+ // (clients predating the id round-trip), but request content alone can't
+ // distinguish such a client from a modern one that deleted every existing day
+ // and added only new ones — zero ids either way. Without this flag that edit
+ // would positionally re-attribute the deleted days' workout history to the
+ // brand-new days (see ProgramStore.Update). Ignored on create.
+ DayIDsKnown bool `json:"day_ids_known"`
+}
+
+// CreateProgramDayReq is one Day in a program's cycle. Exercises is ignored (and
+// should be empty) when IsRestDay is true.
+type CreateProgramDayReq struct {
+ // ID ties this request day back to an existing program_days row on update (0 =
+ // new day). Position alone can't distinguish "renamed day 0" from "deleted day
+ // 0", so without it any reorder or mid-list removal would silently re-attribute
+ // the program's workout history (workouts.program_day_id) to the wrong days —
+ // see ProgramStore.Update. Ignored on create.
+ ID int64 `json:"id"`
+ IsRestDay bool `json:"is_rest_day"`
+ Name string `json:"name"`
+ Exercises []CreateProgramExerciseReq `json:"exercises" validate:"max=500,dive"`
}
type CreateProgramExerciseReq struct {
ExerciseID int64 `json:"exercise_id" validate:"required"`
Notes string `json:"notes"`
RestSeconds int `json:"rest_seconds"`
- Sets []CreateProgramSetReq `json:"sets"`
+ Sets []CreateProgramSetReq `json:"sets" validate:"max=500"`
}
type CreateProgramSetReq struct {
diff --git a/backend/seed/demo_data.go b/backend/seed/demo_data.go
index d8d622a..46f9e42 100644
--- a/backend/seed/demo_data.go
+++ b/backend/seed/demo_data.go
@@ -109,10 +109,11 @@ func DemoData(db *sql.DB) {
return
}
- if err := seedProgram(db, userID); err != nil {
+ progID, err := seedProgram(db, userID)
+ if err != nil {
log.Printf("seed: program: %v", err)
}
- if err := seedWorkouts(db, userID); err != nil {
+ if err := seedWorkouts(db, userID, progID); err != nil {
log.Printf("seed: workouts: %v", err)
}
seedWeightLogs(db, userID)
@@ -131,23 +132,50 @@ func lookupExercise(db *sql.DB, patterns []string) (int64, bool) {
return 0, false
}
-func seedProgram(db *sql.DB, userID int64) error {
+// seedProgram builds a 7-day PPL cycle (order matches weekSchedule Mon→Sun) so the
+// demo account showcases multi-day routines with a rest day baked in, not just a
+// flat exercise list. Targets seed at peakWeight (week-8 numbers) — this is the
+// routine as it stands "today", separate from the logged history in seedWorkouts,
+// which progresses from baseWeight up to it over the 8 seeded weeks.
+func seedProgram(db *sql.DB, userID int64) (int64, error) {
res, err := db.Exec(`INSERT INTO programs (user_id, name, notes) VALUES (?, ?, ?)`,
userID, "PPL — Push Pull Legs", "Classic 6-day PPL split for strength and hypertrophy.")
if err != nil {
- return err
+ return 0, err
}
progID, _ := res.LastInsertId()
- for dayIdx, template := range workoutTemplates {
- for exOrder, exDef := range template {
+ // 0=PushA 1=PullA 2=LegsA 3=PushB 4=PullB 5=LegsB, -1=rest — Mon..Sun order.
+ cycle := []struct {
+ tmplIdx int
+ name string
+ }{
+ {0, "Push A"}, {1, "Pull A"}, {2, "Legs A"},
+ {3, "Push B"}, {4, "Pull B"}, {5, "Legs B"},
+ {-1, "Rest"},
+ }
+
+ for dayIdx, day := range cycle {
+ isRest := day.tmplIdx < 0
+ dayRes, err := db.Exec(
+ `INSERT INTO program_days (program_id, order_index, is_rest_day, name) VALUES (?, ?, ?, ?)`,
+ progID, dayIdx, isRest, day.name,
+ )
+ if err != nil {
+ continue
+ }
+ dayID, _ := dayRes.LastInsertId()
+ if isRest {
+ continue
+ }
+ for exOrder, exDef := range workoutTemplates[day.tmplIdx] {
exID, ok := lookupExercise(db, exDef.patterns)
if !ok {
continue
}
pexRes, err := db.Exec(
- `INSERT INTO program_exercises (program_id, exercise_id, order_index) VALUES (?, ?, ?)`,
- progID, exID, exOrder,
+ `INSERT INTO program_exercises (program_id, program_day_id, exercise_id, order_index) VALUES (?, ?, ?, ?)`,
+ progID, dayID, exID, exOrder,
)
if err != nil {
continue
@@ -159,13 +187,12 @@ func seedProgram(db *sql.DB, userID int64) error {
pexID, s, exDef.reps, exDef.peakWeight,
)
}
- _ = dayIdx
}
}
- return nil
+ return progID, nil
}
-func seedWorkouts(db *sql.DB, userID int64) error {
+func seedWorkouts(db *sql.DB, userID, progID int64) error {
rng := rand.New(rand.NewSource(42))
now := time.Now()
// 8 weeks of workouts ending 3 days ago
@@ -198,12 +225,13 @@ func seedWorkouts(db *sql.DB, userID 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) VALUES (?, ?, ?, ?, ?)`,
+ `INSERT INTO workouts (user_id, name, notes, duration, started_at, program_id) VALUES (?, ?, ?, ?, ?, ?)`,
userID,
workoutNames[tmplIdx],
"",
workoutDurations[tmplIdx]+rng.Intn(600)-300,
- startedAt.Format("2006-01-02T15:04:05Z"),
+ startedAt,
+ progID,
)
if err != nil {
return fmt.Errorf("workout insert: %w", err)
@@ -268,7 +296,7 @@ func seedWeightLogs(db *sql.DB, userID int64) {
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.Format("2006-01-02T15:04:05Z"),
+ userID, fmt.Sprintf("%.1f", w), "", loggedAt,
)
}
}
@@ -313,7 +341,7 @@ func seedFoodLogs(db *sql.DB, userID int64) {
db.Exec(
`INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, logged_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
userID, m.name, m.meal, m.calories, m.protein, m.carbs, m.fat,
- loggedAt.Format("2006-01-02T15:04:05Z"),
+ loggedAt,
)
}
}
diff --git a/backend/stores/program.go b/backend/stores/program.go
index 0de521b..53dd2d6 100644
--- a/backend/stores/program.go
+++ b/backend/stores/program.go
@@ -7,7 +7,8 @@ import (
"github.com/Cawlumm/lyftr-backend/models"
)
-// ProgramStore owns all SQL for programs, program_exercises and program_sets.
+// ProgramStore owns all SQL for programs, program_days, program_exercises and
+// program_sets.
type ProgramStore struct{ db *sql.DB }
func NewProgramStore(db *sql.DB) *ProgramStore { return &ProgramStore{db: db} }
@@ -56,17 +57,29 @@ func (s *ProgramStore) List(uid int64, f ProgramFilter) ([]models.Program, error
}
rows.Close() // close the parent cursor BEFORE loading children (#36)
+ // loadDays (exercises/sets) stays a per-program call — pre-existing N+1, out of
+ // scope here. currentDayIndex is batched below instead of called per-program:
+ // unlike loadDays it added 2 brand-new sequential round trips per program on top
+ // of that, and SetMaxOpenConns(1) serializes every one of them on the process's
+ // single connection.
for i := range programs {
- ex, err := s.loadExercises(programs[i].ID)
+ days, err := s.loadDays(programs[i].ID)
if err != nil {
return nil, err
}
- programs[i].Exercises = ex
+ programs[i].Days = days
+ }
+ idxByID, err := s.currentDayIndex(uid, programs)
+ if err != nil {
+ return nil, err
+ }
+ for i := range programs {
+ programs[i].CurrentDayIndex = idxByID[programs[i].ID]
}
return programs, nil
}
-// Get returns a user-owned program with its exercises/sets, or sql.ErrNoRows.
+// Get returns a user-owned program with its days/exercises/sets, or sql.ErrNoRows.
func (s *ProgramStore) Get(uid, id int64) (models.Program, error) {
var p models.Program
if err := scanProgram(
@@ -74,11 +87,9 @@ func (s *ProgramStore) Get(uid, id int64) (models.Program, error) {
); err != nil {
return models.Program{}, err
}
- ex, err := s.loadExercises(id)
- if err != nil {
+ if err := s.hydrate(&p); err != nil {
return models.Program{}, err
}
- p.Exercises = ex
return p, nil
}
@@ -87,14 +98,163 @@ func (s *ProgramStore) get(id int64) (models.Program, error) {
if err := scanProgram(s.db.QueryRow(`SELECT `+programCols+` FROM programs WHERE id = ?`, id), &p); err != nil {
return models.Program{}, err
}
- ex, err := s.loadExercises(id)
- if err != nil {
+ if err := s.hydrate(&p); err != nil {
return models.Program{}, err
}
- p.Exercises = ex
return p, nil
}
+// hydrate loads a program's Days (with their Exercises/Sets) and computes
+// CurrentDayIndex in place.
+func (s *ProgramStore) hydrate(p *models.Program) error {
+ days, err := s.loadDays(p.ID)
+ if err != nil {
+ return err
+ }
+ p.Days = days
+ idxByID, err := s.currentDayIndex(p.UserID, []models.Program{{ID: p.ID, Days: days}})
+ if err != nil {
+ return err
+ }
+ p.CurrentDayIndex = idxByID[p.ID]
+ return nil
+}
+
+// currentDayIndex computes, for every given program, which Days[] entry is due
+// today, in a small constant number of queries regardless of how many programs
+// are passed (a single query via a CTE, whether called with one program from
+// hydrate or a whole page of them from List — see ProgramStore.List). The due day
+// is derived from WHICH specific day the most recently started program workout
+// was logged against (workouts.program_day_id), not from a blind workout count —
+// a count is blind to repeats and out-of-order logging, silently desyncing
+// "today's workout" from what was actually done. The due day is the next workout
+// day after the last-logged one in cycle order, wrapping to the first workout day
+// past the end; rest days are never "due" and are skipped over. Repeating the
+// same day therefore doesn't skip anything (due stays the next day in sequence),
+// and logging an out-of-cycle day deliberately moves the tracker to whatever
+// follows THAT day — no "remaining incomplete days" bookkeeping, by design.
+//
+// Only workouts whose program_day_id maps to one of THIS program's current non-rest
+// days can anchor the tracker to a specific day; rows carrying a day from some other
+// program are ignored outright. Rows with a NULL day and no dropped mark — clients
+// that predate day tracking — can't anchor, but each one newer than the anchor still
+// ADVANCES the tracker by one workout day, count-based: without that fallback a user
+// on an older app build would log forever while the due day stayed parked, a
+// regression from the pre-linkage COUNT-based algorithm which advanced on every
+// workout. The exception is rows marked program_day_dropped (their day was
+// deliberately deleted — or toggled into a rest day — by a routine edit): their
+// cycle position is unknowable, and counting them as advances would let one edit
+// swing the due day by the parity of an arbitrary lifetime count — deleting or
+// rest-toggling a day with 50 logged workouts must not make "today's workout"
+// depend on 50 mod cycle length. Dropped rows are ignored entirely. No qualifying
+// workout at all → the first workout day is due. A program with no workout days
+// (every day is rest, or no days yet) has nothing to be due → 0.
+func (s *ProgramStore) currentDayIndex(uid int64, programs []models.Program) (map[int64]int, error) {
+ result := make(map[int64]int, len(programs))
+ workoutIdx := make(map[int64][]int, len(programs))
+ progByID := make(map[int64]models.Program, len(programs))
+ var ids []int64
+ for _, p := range programs {
+ progByID[p.ID] = p
+ var idx []int
+ for i, d := range p.Days {
+ if !d.IsRestDay {
+ idx = append(idx, i)
+ }
+ }
+ if len(idx) == 0 {
+ result[p.ID] = 0 // no workout days at all — nothing to be due
+ continue
+ }
+ workoutIdx[p.ID] = idx
+ ids = append(ids, p.ID)
+ }
+ if len(ids) == 0 {
+ return result, nil
+ }
+
+ idSelects := make([]string, len(ids))
+ inPlaceholders := make([]string, len(ids))
+ for i := range ids {
+ idSelects[i] = "SELECT ? AS program_id"
+ inPlaceholders[i] = "?"
+ }
+ idsCSV := strings.Join(inPlaceholders, ",")
+
+ query := `
+ WITH ids(program_id) AS (` + strings.Join(idSelects, " UNION ALL ") + `),
+ anchors AS (
+ SELECT w.program_id AS program_id, w.program_day_id AS anchor_day_id,
+ w.id AS anchor_wid, w.started_at AS anchor_started_at
+ FROM workouts w
+ JOIN program_days pd ON pd.id = w.program_day_id
+ WHERE w.user_id = ? AND pd.is_rest_day = 0 AND w.program_id IN (` + idsCSV + `)
+ AND NOT EXISTS (
+ SELECT 1 FROM workouts w2
+ JOIN program_days pd2 ON pd2.id = w2.program_day_id
+ WHERE w2.user_id = w.user_id AND w2.program_id = w.program_id AND pd2.is_rest_day = 0
+ AND (w2.started_at > w.started_at OR (w2.started_at = w.started_at AND w2.id > w.id))
+ )
+ )
+ SELECT ids.program_id, a.anchor_day_id, a.anchor_wid, a.anchor_started_at,
+ (SELECT COUNT(*) FROM workouts w
+ WHERE w.user_id = ? AND w.program_id = ids.program_id
+ AND w.program_day_id IS NULL AND w.program_day_dropped = 0
+ AND (a.anchor_started_at IS NULL
+ OR w.started_at > a.anchor_started_at
+ OR (w.started_at = a.anchor_started_at AND w.id > a.anchor_wid))
+ ) AS unlinked
+ FROM ids
+ LEFT JOIN anchors a ON a.program_id = ids.program_id`
+
+ args := make([]any, 0, 2*len(ids)+2)
+ for _, id := range ids {
+ args = append(args, id)
+ }
+ args = append(args, uid)
+ for _, id := range ids {
+ args = append(args, id)
+ }
+ args = append(args, uid)
+
+ rows, err := s.db.Query(query, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var pid int64
+ var anchorDayID sql.NullInt64
+ var anchorWID sql.NullInt64
+ var anchorStarted sql.NullString
+ var unlinked int
+ if err := rows.Scan(&pid, &anchorDayID, &anchorWID, &anchorStarted, &unlinked); err != nil {
+ return nil, err
+ }
+ idx := workoutIdx[pid]
+ if !anchorDayID.Valid {
+ result[pid] = idx[unlinked%len(idx)]
+ continue
+ }
+ p := progByID[pid]
+ found := false
+ for pos, wi := range idx {
+ if p.Days[wi].ID == anchorDayID.Int64 {
+ result[pid] = idx[(pos+1+unlinked)%len(idx)]
+ found = true
+ break
+ }
+ }
+ if !found {
+ // Anchor day vanished between the query and here — fall through as if its
+ // log were day-less too (mirrors currentDayIndex's own fallback).
+ result[pid] = idx[(unlinked+1)%len(idx)]
+ }
+ }
+ return result, rows.Err()
+}
+
func (s *ProgramStore) Create(uid int64, req models.CreateProgramRequest) (models.Program, error) {
pid, err := inTx(s.db, func(tx *sql.Tx) (int64, error) {
res, err := tx.Exec(`INSERT INTO programs (user_id, name, notes) VALUES (?, ?, ?)`, uid, req.Name, req.Notes)
@@ -105,7 +265,7 @@ func (s *ProgramStore) Create(uid int64, req models.CreateProgramRequest) (model
if err != nil {
return 0, err
}
- if err := insertProgramExercises(tx, pid, req.Exercises); err != nil {
+ if err := insertProgramDays(tx, pid, req.Days); err != nil {
return 0, err
}
return pid, nil
@@ -116,8 +276,36 @@ func (s *ProgramStore) Create(uid int64, req models.CreateProgramRequest) (model
return s.get(pid)
}
-// Update replaces a user-owned program and its children in one tx. sql.ErrNoRows
-// if the program isn't theirs (nothing is mutated).
+// Update replaces a user-owned program and its days/exercises/sets in one tx.
+// sql.ErrNoRows if the program isn't theirs (nothing is mutated).
+//
+// Day rows are updated IN PLACE, matched to the request by day id (CreateProgramDayReq.ID)
+// — never deleted + recreated wholesale. workouts.program_day_id references
+// program_days ON DELETE SET NULL, so recreating every day on any edit (even a name
+// typo) would scrub the day linkage off the program's entire workout history and
+// reset the due-day tracker to Day 1 — the exact silent desync the linkage exists to
+// prevent. Id matching (not position) keeps that linkage correct across reorders and
+// mid-list removals too: position alone can't tell "renamed day 0" from "deleted
+// day 0". Request content alone can't distinguish a legacy id-less payload from a
+// modern client that deleted every existing day and added only new ones (zero ids
+// either way), so modern clients also send DayIDsKnown to force id matching for
+// that edit — the deleted days' history is dropped as residue instead of being
+// positionally re-attributed to the brand-new days. Only requests with no ids AND
+// no flag (clients predating the id round-trip) fall back to positional matching —
+// their same-position edits keep working; only their structural edits carry the old
+// positional mis-attribution.
+//
+// Only days actually absent from the request are deleted; their workouts' linkage is
+// dropped AND marked program_day_dropped so the due-day tracker ignores those rows
+// as residue instead of miscounting them as day-less logs (see currentDayIndex).
+// A day edited into a rest day sheds its workouts' linkage the same way (NULL +
+// dropped): a rest day can never be due, so keeping the link would make those
+// workouts invisible to the tracker, and counting them as day-less advances would
+// swing the due day by the parity of that day's logged history. Each day's
+// exercises/sets are still replaced wholesale: nothing persists a reference to them
+// (a logged set's program_set_id is request-only, never stored), so recreating them
+// is safe — the delete cascades to program_sets via the program_exercise_id FK,
+// same layered cascade the flat model relied on.
func (s *ProgramStore) Update(uid, id int64, req models.CreateProgramRequest) (models.Program, error) {
if err := inTxDo(s.db, func(tx *sql.Tx) error {
var ownedID int64
@@ -127,16 +315,118 @@ func (s *ProgramStore) Update(uid, id int64, req models.CreateProgramRequest) (m
if _, err := tx.Exec(`UPDATE programs SET name = ?, notes = ? WHERE id = ?`, req.Name, req.Notes, id); err != nil {
return err
}
- if _, err := tx.Exec(`DELETE FROM program_exercises WHERE program_id = ?`, id); err != nil {
+ existing, err := dayIDsInOrder(tx, id)
+ if err != nil {
return err
}
- return insertProgramExercises(tx, id, req.Exercises)
+ hasIDs := req.DayIDsKnown
+ for _, day := range req.Days {
+ if day.ID != 0 {
+ hasIDs = true
+ break
+ }
+ }
+ isExisting := make(map[int64]bool, len(existing))
+ for _, dayID := range existing {
+ isExisting[dayID] = true
+ }
+ kept := make(map[int64]bool, len(existing))
+ for i, day := range req.Days {
+ // Which existing row this request day is: by id when the client sends ids
+ // (an id from some other program — or a duplicate — is treated as a new
+ // day, so a crafted request can't touch rows outside this owned program),
+ // by position for legacy id-less requests. 0 = a genuinely new day.
+ var dayID int64
+ if hasIDs {
+ if day.ID != 0 && isExisting[day.ID] && !kept[day.ID] {
+ dayID = day.ID
+ }
+ } else if i < len(existing) {
+ dayID = existing[i]
+ }
+ if dayID == 0 {
+ if err := insertProgramDay(tx, id, i, day); err != nil {
+ return err
+ }
+ continue
+ }
+ kept[dayID] = true
+ if _, err := tx.Exec(
+ `UPDATE program_days SET order_index = ?, is_rest_day = ?, name = ? WHERE id = ?`,
+ i, day.IsRestDay, day.Name, dayID,
+ ); err != nil {
+ return err
+ }
+ if _, err := tx.Exec(`DELETE FROM program_exercises WHERE program_day_id = ?`, dayID); err != nil {
+ return err
+ }
+ if day.IsRestDay {
+ // Un-link workouts logged against this now-rest day (also lazily scrubs
+ // any pre-existing rest-day linkage): rest days are excluded from the
+ // tracker's anchor lookup, so a kept link would strand those workouts —
+ // neither anchoring nor advancing. Marked dropped exactly like a deleted
+ // day's rows: the day's cycle position is gone either way, and counting
+ // the shed rows as day-less advances would swing the due day by the
+ // parity of the day's whole logged history (see currentDayIndex).
+ if err := dropDayLinkage(tx, dayID); err != nil {
+ return err
+ }
+ continue // rest days never carry exercises, even if the client sent some
+ }
+ if err := insertProgramExercises(tx, id, dayID, day.Exercises); err != nil {
+ return err
+ }
+ }
+ for _, dayID := range existing {
+ if kept[dayID] {
+ continue
+ }
+ // Deliberately removed day: drop its workouts' linkage (per the ON DELETE
+ // SET NULL contract) but mark them dropped — their cycle position is
+ // unknowable, and counting them as day-less advances would swing the due
+ // day by the parity of an arbitrary historical count (see currentDayIndex).
+ if err := dropDayLinkage(tx, dayID); err != nil {
+ return err
+ }
+ if _, err := tx.Exec(`DELETE FROM program_days WHERE id = ?`, dayID); err != nil {
+ return err
+ }
+ }
+ return nil
}); err != nil {
return models.Program{}, err
}
return s.get(id)
}
+// dropDayLinkage severs workouts.program_day_id for a day that's being deleted or
+// rest-toggled, marking them program_day_dropped so currentDayIndex's "unlinked rows
+// advance the tracker" fallback skips them — their cycle position became unknowable
+// the moment the day went away, so counting them would swing the due day by the
+// parity of an arbitrary historical count (see currentDayIndex's own comment).
+func dropDayLinkage(tx *sql.Tx, dayID int64) error {
+ _, err := tx.Exec(`UPDATE workouts SET program_day_id = NULL, program_day_dropped = 1 WHERE program_day_id = ?`, dayID)
+ return err
+}
+
+// dayIDsInOrder returns a program's existing day row ids in cycle order, within tx.
+func dayIDsInOrder(tx *sql.Tx, programID int64) ([]int64, error) {
+ rows, err := tx.Query(`SELECT id FROM program_days WHERE program_id = ? ORDER BY order_index`, programID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ ids := []int64{}
+ for rows.Next() {
+ var id int64
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ ids = append(ids, id)
+ }
+ return ids, rows.Err()
+}
+
// ProgressInput is one logged working set to consider for auto-progression:
// the routine set it came from, what the user logged, and whether that logged set
// was also an all-time best (computed by the controller from a pre-save PR snapshot).
@@ -173,7 +463,9 @@ func (s *ProgramStore) SuggestTargets(uid, programID int64, sets []ProgressInput
// caller can serialize it with an earlier PR-snapshot read and workout insert (see
// WorkoutStore.CreateWithProgression) — closes a TOCTOU race where two concurrent
// workout submissions could both compute suggested_is_pr against the same stale prior
-// best (issue #40 progression review).
+// best (issue #40 progression review). program_exercises keeps a denormalized
+// program_id column (alongside program_day_id) specifically so this join — and the
+// ownership guard below — never had to change when routines grew a day layer.
func suggestTargetsTx(tx *sql.Tx, uid, programID int64, sets []ProgressInput) (string, int, bool, error) {
var name string
count, anyPR := 0, false
@@ -298,11 +590,45 @@ func (s *ProgramStore) Delete(uid, id int64) (int64, error) {
return n, nil
}
-func insertProgramExercises(tx *sql.Tx, pid int64, exercises []models.CreateProgramExerciseReq) error {
+// insertProgramDays writes a program's Days (in request order — OrderIndex on the
+// request is trusted as-is, matching the pre-existing convention for exercise/set
+// ordering) plus each Day's exercises/sets within tx.
+func insertProgramDays(tx *sql.Tx, programID int64, days []models.CreateProgramDayReq) error {
+ for i, day := range days {
+ if err := insertProgramDay(tx, programID, i, day); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// insertProgramDay writes one Day at the given cycle position. orderIndex is the
+// request array position (same convention as insertProgramExercises' `i`, not a
+// client-echoed value) — a client resending a stale/duplicate order_index can't
+// scramble the cycle order.
+func insertProgramDay(tx *sql.Tx, programID int64, orderIndex int, day models.CreateProgramDayReq) error {
+ dayRes, err := tx.Exec(
+ `INSERT INTO program_days (program_id, order_index, is_rest_day, name) VALUES (?, ?, ?, ?)`,
+ programID, orderIndex, day.IsRestDay, day.Name,
+ )
+ if err != nil {
+ return err
+ }
+ dayID, err := dayRes.LastInsertId()
+ if err != nil {
+ return err
+ }
+ if day.IsRestDay {
+ return nil // rest days never carry exercises, even if the client sent some
+ }
+ return insertProgramExercises(tx, programID, dayID, day.Exercises)
+}
+
+func insertProgramExercises(tx *sql.Tx, programID, dayID int64, exercises []models.CreateProgramExerciseReq) error {
for i, ex := range exercises {
exRes, err := tx.Exec(
- `INSERT INTO program_exercises (program_id, exercise_id, order_index, notes, rest_seconds) VALUES (?, ?, ?, ?, ?)`,
- pid, ex.ExerciseID, i, ex.Notes, ex.RestSeconds,
+ `INSERT INTO program_exercises (program_id, program_day_id, exercise_id, order_index, notes, rest_seconds) VALUES (?, ?, ?, ?, ?, ?)`,
+ programID, dayID, ex.ExerciseID, i, ex.Notes, ex.RestSeconds,
)
if err != nil {
return err
@@ -327,25 +653,66 @@ func insertProgramExercises(tx *sql.Tx, pid int64, exercises []models.CreateProg
return nil
}
+// loadDays scans + closes the parent cursor BEFORE loading each day's exercises
+// (#36 — same close-then-load discipline as loadExercises/loadSets below).
+func (s *ProgramStore) loadDays(programID int64) ([]models.ProgramDay, error) {
+ rows, err := s.db.Query(
+ `SELECT id, program_id, order_index, is_rest_day, name FROM program_days WHERE program_id = ? ORDER BY order_index`,
+ programID,
+ )
+ if err != nil {
+ return nil, err
+ }
+ days := []models.ProgramDay{}
+ for rows.Next() {
+ var d models.ProgramDay
+ var isRest int
+ if err := rows.Scan(&d.ID, &d.ProgramID, &d.OrderIndex, &isRest, &d.Name); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ d.IsRestDay = isRest != 0
+ days = append(days, d)
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ rows.Close()
+
+ for i := range days {
+ if days[i].IsRestDay {
+ days[i].Exercises = []models.ProgramExercise{}
+ continue
+ }
+ ex, err := s.loadExercises(days[i].ID)
+ if err != nil {
+ return nil, err
+ }
+ days[i].Exercises = ex
+ }
+ return days, nil
+}
+
// loadExercises scans + closes the parent cursor BEFORE loading each exercise's
// sets (#36), and surfaces scan errors.
-func (s *ProgramStore) loadExercises(programID int64) ([]models.ProgramExercise, error) {
+func (s *ProgramStore) loadExercises(dayID int64) ([]models.ProgramExercise, error) {
rows, err := s.db.Query(
- `SELECT pe.id, pe.program_id, pe.exercise_id, pe.order_index, pe.notes, pe.rest_seconds,
+ `SELECT pe.id, pe.program_day_id, pe.exercise_id, pe.order_index, pe.notes, pe.rest_seconds,
e.name, e.muscle_group, e.category, e.equipment, e.image_url
FROM program_exercises pe
JOIN exercises e ON e.id = pe.exercise_id
- WHERE pe.program_id = ? ORDER BY pe.order_index`,
- programID,
+ WHERE pe.program_day_id = ? ORDER BY pe.order_index`,
+ dayID,
)
if err != nil {
return nil, err
}
- var exercises []models.ProgramExercise
+ exercises := []models.ProgramExercise{}
for rows.Next() {
var pe models.ProgramExercise
if err := rows.Scan(
- &pe.ID, &pe.ProgramID, &pe.ExerciseID, &pe.OrderIndex, &pe.Notes, &pe.RestSeconds,
+ &pe.ID, &pe.ProgramDayID, &pe.ExerciseID, &pe.OrderIndex, &pe.Notes, &pe.RestSeconds,
&pe.Exercise.Name, &pe.Exercise.MuscleGroup, &pe.Exercise.Category,
&pe.Exercise.Equipment, &pe.Exercise.ImageURL,
); err != nil {
@@ -382,7 +749,7 @@ func (s *ProgramStore) loadSets(programExerciseID int64) ([]models.ProgramSet, e
return nil, err
}
defer rows.Close()
- var sets []models.ProgramSet
+ sets := []models.ProgramSet{}
for rows.Next() {
var st models.ProgramSet
var sw sql.NullFloat64
diff --git a/backend/stores/workout.go b/backend/stores/workout.go
index 6eafd4f..bc02c73 100644
--- a/backend/stores/workout.go
+++ b/backend/stores/workout.go
@@ -113,9 +113,44 @@ func (s *WorkoutStore) Create(uid int64, req models.CreateWorkoutRequest) (model
// transaction (see CreateWithProgression) — SQLite then serializes concurrent
// submissions instead of letting them read the same stale prior-best (#40).
func createWorkoutTx(tx *sql.Tx, uid int64, req models.CreateWorkoutRequest) (int64, error) {
+ // ProgramID (nil for freestyle workouts) is persisted so ProgramStore can compute
+ // a routine's cycle position — see ProgramStore.currentDayIndex. No FK: deleting
+ // a program must never take workout history down with it. ProgramDayID pins WHICH
+ // day of the cycle this workout was for (day-accurate due-day tracking); its FK is
+ // ON DELETE SET NULL so deleting/editing a day only drops the linkage, never the
+ // workout.
+ //
+ // A live session can outlive its routine's day rows (an edit mid-workout can
+ // remove days, a delete takes the whole program), so a stale/foreign day id must
+ // degrade to "day unknown" (NULL) here — never fail the user's save on the FK. The same check
+ // re-scopes the id to THIS request's program AND the calling user (via the
+ // programs join), so a client can't link a workout to another program's day or
+ // probe/persist references into some other user's routine. A REST day's id
+ // degrades to NULL the same way (is_rest_day = 0 below): rest days are excluded
+ // from the due-day tracker's anchor lookup, so persisting such a link would
+ // strand the workout — neither anchoring nor advancing the tracker — where a
+ // day-less row still advances it count-based.
+ dayID := req.ProgramDayID
+ if dayID != nil {
+ if req.ProgramID == nil {
+ dayID = nil // a day without its program is meaningless
+ } else {
+ var ok int64
+ err := tx.QueryRow(
+ `SELECT pd.id FROM program_days pd
+ JOIN programs p ON p.id = pd.program_id AND p.user_id = ?
+ WHERE pd.id = ? AND pd.program_id = ? AND pd.is_rest_day = 0`, uid, *dayID, *req.ProgramID,
+ ).Scan(&ok)
+ if err == sql.ErrNoRows {
+ dayID = nil
+ } else if err != nil {
+ return 0, err
+ }
+ }
+ }
res, err := tx.Exec(
- `INSERT INTO workouts (user_id, name, notes, duration, started_at) VALUES (?, ?, ?, ?, ?)`,
- uid, req.Name, req.Notes, req.Duration, req.StartedAt,
+ `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,
)
if err != nil {
return 0, err
@@ -139,7 +174,18 @@ func (s *WorkoutStore) Update(uid, id int64, req models.CreateWorkoutRequest) (m
if err := tx.QueryRow(`SELECT id FROM workouts WHERE id = ? AND user_id = ?`, id, uid).Scan(&ownedID); err != nil {
return err // ErrNoRows = not theirs
}
- if _, err := tx.Exec(
+ // started_at is only rewritten when the request carries one: a PUT omitting
+ // it (a name/notes-only patch) must not zero the stored timestamp — it's the
+ // due-day tracker's ordering key (ProgramStore.currentDayIndex), and a
+ // 0001-01-01 rewrite would silently drop this workout to oldest.
+ if req.StartedAt.IsZero() {
+ if _, err := tx.Exec(
+ `UPDATE workouts SET name = ?, notes = ?, duration = ? WHERE id = ?`,
+ req.Name, req.Notes, req.Duration, id,
+ ); err != nil {
+ return err
+ }
+ } else if _, err := tx.Exec(
`UPDATE workouts SET name = ?, notes = ?, duration = ?, started_at = ? WHERE id = ?`,
req.Name, req.Notes, req.Duration, req.StartedAt, id,
); err != nil {
diff --git a/backend/stores/workout_progression.go b/backend/stores/workout_progression.go
index b533c9f..7c97d10 100644
--- a/backend/stores/workout_progression.go
+++ b/backend/stores/workout_progression.go
@@ -27,7 +27,10 @@ import (
// dropped so the already-inserted workout still commits — never fail a save the
// user is waiting on because routine bookkeeping hiccuped. Its (possibly partial)
// writes are rolled back via a SAVEPOINT rather than left committed, so "dropped"
-// stays true even now that staging shares a transaction with the insert.
+// stays true even now that staging shares a transaction with the insert. The one
+// exception: failures of the savepoint machinery itself (creating or rolling back
+// to it) fail the whole transaction — without a working savepoint, "best-effort"
+// can't be delivered safely or observably.
//
// This does widen the critical section: with db.DB.SetMaxOpenConns(1), the whole
// PR-snapshot + insert + suggestion-staging sequence now holds the process's one
@@ -54,9 +57,14 @@ func (s *Stores) CreateWorkoutWithProgression(uid int64, req models.CreateWorkou
// Run suggestion-staging under its own SAVEPOINT: a mid-loop error must only
// undo staging's own (possibly partial) UPDATEs, never the workout insert above.
+ // Failing to CREATE the savepoint is not a staging error — it's savepoint
+ // machinery breaking (the tx itself is almost certainly already dead), so fail
+ // the whole transaction like the ROLLBACK-failure path below does, rather than
+ // silently committing the workout with progression dropped and the caller
+ // unable to tell that apart from "nothing to stage".
if _, spErr := tx.Exec("SAVEPOINT suggest_targets"); spErr != nil {
log.Printf("[workouts/progress] uid=%d: savepoint: %v", uid, spErr)
- return nil
+ return spErr
}
p, pErr := progressRoutineTx(tx, uid, req, priors)
if pErr != nil {
diff --git a/mobile/app/(tabs)/index.tsx b/mobile/app/(tabs)/index.tsx
index b0227eb..caa77e4 100644
--- a/mobile/app/(tabs)/index.tsx
+++ b/mobile/app/(tabs)/index.tsx
@@ -7,13 +7,13 @@ import {
eachDayOfInterval, endOfWeek, format, isSameDay, startOfWeek, subWeeks,
} from 'date-fns'
import {
- Activity, AlertCircle, ArrowRight, Dumbbell, Play, Plus, Scale, Timer, TrendingUp,
+ Activity, AlertCircle, ArrowRight, BookOpen, ChevronRight, Dumbbell, Play, Plus, Scale, Timer, TrendingUp,
} from 'lucide-react-native'
import {
- displayVolume, displayWeight, weightShort,
- type DailyStats, type WeightLog, type WeightStats, type Workout,
+ activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, isDayStartable, sessionNameForDay,
+ todaysDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout,
} from '@lyftr/shared'
-import { AppText, Card, Label, Screen, SectionHeader, SegmentedControl } from '../../src/components/ui'
+import { AppText, Card, IconButton, Label, Screen, SectionHeader, SegmentedControl } from '../../src/components/ui'
import { ExerciseImage } from '../../src/components/workouts/ExerciseImage'
import {
MuscleDonut, MuscleSparkline, VolumeBarChart, WeightSparkline,
@@ -114,6 +114,7 @@ function LinkRow({ label, onPress }: { label: string; onPress: () => void }) {
export default function Dashboard() {
const now = useMemo(() => new Date(), [])
const session = useWorkoutSession((s) => s.session)
+ const startSession = useWorkoutSession((s) => s.startSession)
const user = useAuthStore((s) => s.user)
const settings = useSettingsStore((s) => s.settings)
const fetchSettings = useSettingsStore((s) => s.fetch)
@@ -133,6 +134,7 @@ export default function Dashboard() {
}
const [workouts, setWorkouts] = useState<Workout[]>([])
+ const [programs, setPrograms] = useState<Program[]>([])
const [food, setFood] = useState<DailyStats>(DEFAULT_FOOD)
const [weightLogs, setWeightLogs] = useState<WeightLog[]>([])
const [weightStats, setWeightStats] = useState<WeightStats | null>(null)
@@ -145,13 +147,15 @@ export default function Dashboard() {
const [heatSel, setHeatSel] = useState<{ day: Date; count: number } | null>(null)
const load = useCallback(async () => {
- const [ws, fs, wl, wst] = await Promise.all([
+ const [ws, ps, fs, wl, wst] = await Promise.all([
client.workoutAPI.list({ limit: 84 }).catch(() => [] as Workout[]),
+ client.programAPI.list({ limit: 100 }).catch(() => [] as Program[]), // backend's max — Up Next must see every program
client.foodAPI.stats(format(new Date(), 'yyyy-MM-dd')).catch(() => DEFAULT_FOOD),
client.weightAPI.list({ limit: 14 }).catch(() => [] as WeightLog[]),
client.weightAPI.stats().catch(() => null),
])
setWorkouts(ws || [])
+ setPrograms(ps || [])
setFood(fs || DEFAULT_FOOD)
setWeightLogs(wl || [])
setWeightStats(wst)
@@ -200,6 +204,25 @@ export default function Dashboard() {
const weekWorkouts = workouts.filter((w) => new Date(w.started_at) >= weekStart)
const lastWorkout = workouts[0] ?? null
+ // "Up next": the first (most recently created) program whose due day is a
+ // startable workout day. Surfaces today's routine workout without opening the
+ // Programs tab — a routine that never shows on the dashboard never gets started.
+ const upNext = (() => {
+ for (const p of programs) {
+ const day = todaysDay(p)
+ if (isDayStartable(day)) return { program: p, day }
+ }
+ return null
+ })()
+
+ const startUpNext = () => {
+ if (!upNext) return
+ hImpact()
+ const { program, day } = upNext
+ startSession(sessionNameForDay(program, day), activeSessionExercisesForDay(day), program.id, day.id)
+ router.navigate('/workouts/active')
+ }
+
const chartData = workouts.slice(0, Number(volumePeriod)).reverse().map((w) => ({
date: format(new Date(w.started_at), 'M/d'),
volume: displayVolume(calcVolume(w), unit),
@@ -324,6 +347,44 @@ export default function Dashboard() {
</Pressable>
) : null}
+ {/* ── Up next — today's due day on the current routine. Hidden while a
+ session is live: the banner above already owns that slot. Thumbnail is
+ the due day's own first exercise (ProgramCard/WorkoutCard convention),
+ not a generic program glyph — makes the card feel like "this is what
+ you're about to do," not a bookmark. Start is a compact icon button
+ (ProgramCard's Play IconButton), not a labeled pill — the header above
+ already has a text "Start"/"Resume" button, and two buttons both saying
+ "Start" stacked this close reads as noise, not choice. ── */}
+ {!session && upNext ? (
+ <Card className="flex-row items-center gap-3">
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`View ${upNext.program.name} routine`}
+ onPress={() => { hSelect(); router.navigate(`/programs/${upNext.program.id}`) }}
+ className="min-w-0 flex-1 flex-row items-center gap-3 active:opacity-70"
+ >
+ <ExerciseImage url={upNext.day.exercises?.[0]?.exercise?.image_url} fallbackIcon={BookOpen} />
+ <View className="min-w-0 flex-1">
+ <Label>Up next · {upNext.program.name}</Label>
+ <Text className="mt-0.5 font-sans-semibold text-sm text-tx-primary" numberOfLines={1}>
+ {dayLabel(upNext.day, upNext.day.order_index)}
+ </Text>
+ <AppText variant="caption" color="muted" className="mt-0.5">
+ {(upNext.day.exercises ?? []).length} exercise{(upNext.day.exercises ?? []).length === 1 ? '' : 's'}
+ </AppText>
+ </View>
+ <ChevronRight size={16} color={colors.txMuted} />
+ </Pressable>
+ <IconButton
+ icon={Play}
+ label={`Start ${dayLabel(upNext.day, upNext.day.order_index)}`}
+ variant="solid"
+ size="sm"
+ onPress={startUpNext}
+ />
+ </Card>
+ ) : null}
+
{/* ── This Week (sessions + current-week dots) ── */}
<Card>
<View className="flex-row items-start justify-between">
@@ -497,9 +558,15 @@ export default function Dashboard() {
<Card className="items-center justify-center gap-2" style={{ minHeight: 148 }}>
<Dumbbell size={30} color={colors.txMuted} style={{ opacity: 0.4 }} />
<AppText variant="body" color="muted">No workouts logged yet</AppText>
- <Pressable onPress={() => { hSelect(); router.navigate('/workouts/start') }} hitSlop={6} className="active:opacity-60">
- <AppText variant="caption" color="brand">Start your first workout →</AppText>
- </Pressable>
+ {/* Suppressed when the Up Next card is already showing above — that
+ card is its own "start something" CTA, and stacking a second
+ "start your first workout" link right under it is the exact
+ redundant-buttons clutter this card exists to avoid. */}
+ {!upNext ? (
+ <Pressable onPress={() => { hSelect(); router.navigate('/workouts/start') }} hitSlop={6} className="active:opacity-60">
+ <AppText variant="caption" color="brand">Start your first workout →</AppText>
+ </Pressable>
+ ) : null}
</Card>
)}
diff --git a/mobile/app/(tabs)/programs/[id].tsx b/mobile/app/(tabs)/programs/[id].tsx
index 297e51f..c076659 100644
--- a/mobile/app/(tabs)/programs/[id].tsx
+++ b/mobile/app/(tabs)/programs/[id].tsx
@@ -3,12 +3,12 @@ import { Pressable, ScrollView, View } from 'react-native'
import { router, useFocusEffect, useLocalSearchParams, type Href } from 'expo-router'
import { format } from 'date-fns'
import {
- AlertCircle, ArrowLeft, Award, BookOpen, Check, ChevronDown, ChevronRight, ChevronUp, Dumbbell, Edit2,
- Layers, Pause, Play, TimerOff, TrendingUp, Trash2, X,
+ AlertCircle, ArrowLeft, Award, BookOpen, CalendarDays, Check, ChevronDown, ChevronRight, ChevronUp, Dumbbell,
+ Edit2, Layers, Moon, Pause, Play, TimerOff, TrendingUp, Trash2, X,
} from 'lucide-react-native'
import {
- apiErrorMessage, displayWeight, weightShort,
- type ActiveSessionExercise, type Program, type ProgramSet,
+ activeSessionExercisesForDay, allExercises, apiErrorMessage, dayLabel, displayWeight, sessionNameForDay,
+ weightShort, type Program, type ProgramSet,
} from '@lyftr/shared'
import { AppText, ConfirmSheet, Loading, Screen, deleteConfirmProps } from '../../../src/components/ui'
import { ExerciseImage } from '../../../src/components/workouts/ExerciseImage'
@@ -80,6 +80,7 @@ export default function ProgramDetail() {
const [confirming, setConfirming] = useState(false)
const [resolving, setResolving] = useState(false)
const [showAllSuggestions, setShowAllSuggestions] = useState(false)
+ const [selectedDayIdx, setSelectedDayIdx] = useState(0)
useEffect(() => {
fetchSettings()
@@ -105,12 +106,14 @@ export default function ProgramDetail() {
try {
const updated = await client.programAPI.resolveSuggestions(program.id, { accept, dismiss })
setProgram(updated)
- // Invalidate any focus refetch still in flight from before this point — its
- // response can't be trusted to reflect this write, whichever order it lands in.
- ++requestSeq.current
} catch {
// leave the banner in place so the user can retry
} finally {
+ // Invalidate any focus refetch still in flight from before this point — its
+ // response can't be trusted to reflect this write, whichever order it lands in.
+ // Must run on failure too, not just success, or a refetch dispatched during a
+ // failed PATCH can still pass the seq check and apply stale data.
+ ++requestSeq.current
setResolving(false)
}
}
@@ -131,7 +134,15 @@ export default function ProgramDetail() {
const seq = ++requestSeq.current
try {
const data = await client.programAPI.get(Number(id))
- if (!cancelled && requestSeq.current === seq) { setProgram(data); setError(null); loadedRef.current = true }
+ if (!cancelled && requestSeq.current === seq) {
+ setProgram(data)
+ setError(null)
+ // Only seed the day selection from the server's "due today" on the FIRST
+ // load — later focus refetches must not yank the user off a day they
+ // deliberately picked to look at.
+ if (!loadedRef.current) setSelectedDayIdx(data.current_day_index || 0)
+ loadedRef.current = true
+ }
} catch (err) {
if (!cancelled && !loadedRef.current) setError(apiErrorMessage(err, 'Failed to load program'))
} finally {
@@ -145,27 +156,15 @@ export default function ProgramDetail() {
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/programs'))
+ const days = program?.days ?? []
+ const selectedDay = days[selectedDayIdx]
+
const handleStart = () => {
- if (!program) return
+ if (!program || !selectedDay || selectedDay.is_rest_day) return
// navigate (not push): programs → workouts is a cross-tab jump; push corrupts the
// native tab/back stack (the "can't get off the workout from a program" bug).
if (session) { router.navigate(startHref); return }
- const exercises: ActiveSessionExercise[] = (program.exercises || []).map((ex) => ({
- exercise_id: ex.exercise_id,
- exercise: ex.exercise,
- notes: ex.notes || '',
- rest_seconds: ex.rest_seconds,
- sets: (ex.sets || []).map((s) => ({
- set_number: s.set_number,
- target_reps: s.target_reps,
- target_weight: s.target_weight,
- actual_reps: s.target_reps,
- actual_weight: s.target_weight,
- completed: false,
- program_set_id: s.id,
- })),
- }))
- startSession(program.name, exercises, program.id)
+ startSession(sessionNameForDay(program, selectedDay), activeSessionExercisesForDay(selectedDay), program.id, selectedDay.id)
router.navigate(activeHref)
}
@@ -199,14 +198,14 @@ export default function ProgramDetail() {
)
}
- const exs = program.exercises ?? []
- const totalSets = exs.reduce((s, ex) => s + (ex.sets ?? []).length, 0)
+ const allExs = allExercises(program)
+ const totalSets = allExs.reduce((s, ex) => s + (ex.sets ?? []).length, 0)
// Pending auto-progression suggestions (#40). A suggestion exists when suggested_reps
// is set. Show the FULL reps×weight on both sides when both changed (a heavier set can
// also drop the rep target — the user must see that before approving), else the single
// changed dimension.
- const suggestions: Suggestion[] = exs.flatMap((ex) =>
+ const suggestions: Suggestion[] = allExs.flatMap((ex) =>
(ex.sets ?? [])
.filter((s) => s.id != null && s.suggested_reps != null)
.map((s) => {
@@ -256,8 +255,9 @@ export default function ProgramDetail() {
accessibilityRole="button"
accessibilityLabel="Start workout"
onPress={handleStart}
+ disabled={!selectedDay || selectedDay.is_rest_day}
hitSlop={6}
- className="h-9 flex-row items-center gap-1.5 rounded-lg bg-brand-500 px-3 active:scale-95"
+ className={`h-9 flex-row items-center gap-1.5 rounded-lg bg-brand-500 px-3 active:scale-95 ${!selectedDay || selectedDay.is_rest_day ? 'opacity-40' : ''}`}
>
<Play size={14} color="#ffffff" strokeWidth={2.2} />
<AppText variant="label" color="white">Start</AppText>
@@ -371,7 +371,7 @@ export default function ProgramDetail() {
{/* Header card */}
<View className="bg-surface-raised border border-surface-border rounded-2xl p-4">
<View className="flex-row items-start gap-3">
- <ExerciseImage url={exs[0]?.exercise?.image_url} size="hero" fallbackIcon={BookOpen} />
+ <ExerciseImage url={allExs[0]?.exercise?.image_url} size="hero" fallbackIcon={BookOpen} />
<View className="flex-1">
<AppText variant="heading">{program.name}</AppText>
<AppText variant="body" color="muted" className="mt-0.5">
@@ -380,14 +380,21 @@ export default function ProgramDetail() {
</View>
</View>
- {/* Stats strip: Exercises / Total Sets */}
+ {/* Stats strip: Cycle / Exercises / Total Sets */}
<View className="flex-row mt-4 pt-4 border-t border-surface-border">
<View className="flex-1 items-center">
+ <View className="flex-row items-center gap-1 mb-0.5">
+ <CalendarDays size={13} color={colors.txMuted} />
+ <AppText variant="caption" color="muted">Cycle</AppText>
+ </View>
+ <AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{days.length || '—'}</AppText>
+ </View>
+ <View className="flex-1 items-center border-l border-surface-border">
<View className="flex-row items-center gap-1 mb-0.5">
<Dumbbell size={13} color={colors.txMuted} />
<AppText variant="caption" color="muted">Exercises</AppText>
</View>
- <AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{exs.length}</AppText>
+ <AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{allExs.length}</AppText>
</View>
<View className="flex-1 items-center border-l border-surface-border">
<View className="flex-row items-center gap-1 mb-0.5">
@@ -405,15 +412,77 @@ export default function ProgramDetail() {
) : null}
</View>
- {/* Exercises */}
- {!restOn && (
- <View className="flex-row items-center gap-1.5 px-1">
- <TimerOff size={13} color={colors.txMuted} />
- <AppText variant="caption" color="muted">Rest timer is off — turn it on in Settings</AppText>
+ {/* Day strip — the program's repeating cycle, in order. Selecting a day
+ shows its exercises below; it does NOT change which day is "due"
+ (that's server-computed from logged workouts). */}
+ {days.length === 0 ? (
+ <View className="items-center rounded-2xl border border-surface-border bg-surface-raised py-6">
+ <CalendarDays size={28} color={colors.txMuted} style={{ opacity: 0.5 }} />
+ <AppText variant="body" color="muted" className="mt-2">No days yet</AppText>
+ <Pressable onPress={() => router.push(`/programs/${program.id}/edit`)} className="mt-2 active:opacity-60">
+ <AppText variant="caption" style={{ color: accent }}>Add a day →</AppText>
+ </Pressable>
</View>
+ ) : (
+ <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ gap: 8, paddingRight: 8 }}>
+ {days.map((day, i) => {
+ const isSelected = i === selectedDayIdx
+ const isToday = i === program.current_day_index
+ return (
+ <Pressable
+ key={day.id ?? i}
+ onPress={() => setSelectedDayIdx(i)}
+ className={`flex-row items-center gap-1.5 rounded-xl border px-3 py-2 active:scale-95 ${
+ isSelected
+ ? 'bg-brand-500 border-brand-500'
+ : day.is_rest_day
+ ? 'bg-surface-muted/40 border-surface-border'
+ : 'bg-surface-raised border-surface-border'
+ }`}
+ >
+ {day.is_rest_day
+ ? <Moon size={14} color={isSelected ? '#ffffff' : colors.txMuted} />
+ : <Dumbbell size={14} color={isSelected ? '#ffffff' : accent} />}
+ <AppText variant="label" style={{ color: isSelected ? '#ffffff' : (day.is_rest_day ? colors.txMuted : colors.txSecondary) }} numberOfLines={1}>
+ {dayLabel(day, day.order_index)}
+ </AppText>
+ {/* Textual chip, not a bare dot — a color-only marker isn't
+ distinguishable by shape/text (a11y) and reads as decoration. */}
+ {isToday ? (
+ <View className={`rounded-full px-1.5 py-0.5 ${isSelected ? 'bg-white/20' : 'bg-brand-500/15'}`}>
+ <AppText variant="caption" style={{ color: isSelected ? '#ffffff' : accent, letterSpacing: 0.5 }}>TODAY</AppText>
+ </View>
+ ) : null}
+ </Pressable>
+ )
+ })}
+ </ScrollView>
)}
- <View className="gap-3">
- {exs.map((ex) => {
+
+ {/* Selected day's exercises */}
+ {selectedDay?.is_rest_day ? (
+ <View className="items-center rounded-2xl border border-surface-border bg-surface-raised py-10">
+ <Moon size={28} color={colors.txMuted} style={{ opacity: 0.6 }} />
+ <AppText variant="bodySemibold" className="mt-2">Rest Day</AppText>
+ <AppText variant="caption" color="muted" className="mt-1 text-center px-6">
+ No exercises scheduled — recover and come back stronger.
+ </AppText>
+ </View>
+ ) : selectedDay ? (
+ <>
+ {!restOn && (
+ <View className="flex-row items-center gap-1.5 px-1">
+ <TimerOff size={13} color={colors.txMuted} />
+ <AppText variant="caption" color="muted">Rest timer is off — turn it on in Settings</AppText>
+ </View>
+ )}
+ <View className="gap-3">
+ {(selectedDay.exercises ?? []).length === 0 ? (
+ <View className="items-center rounded-2xl border border-surface-border bg-surface-raised py-8">
+ <Dumbbell size={28} color={colors.txMuted} style={{ opacity: 0.5 }} />
+ <AppText variant="body" color="muted" className="mt-2">No exercises on this day yet</AppText>
+ </View>
+ ) : (selectedDay.exercises ?? []).map((ex) => {
const sets = ex.sets ?? []
const maxTargetLbs = sets.length > 0 ? Math.max(...sets.map((s) => s.target_weight || 0)) : 0
const maxTarget = displayWeight(maxTargetLbs, wUnit)
@@ -432,7 +501,7 @@ export default function ProgramDetail() {
<View className="flex-row items-center gap-2 mt-0.5">
{ex.exercise?.muscle_group ? <MuscleBadge muscle={ex.exercise.muscle_group} /> : null}
<AppText variant="caption" color="muted" numberOfLines={1} className="flex-shrink">
- {sets.length} sets{maxTarget > 0 ? ` · target ${maxTarget} ${wUnit}` : ''}
+ {sets.length} set{sets.length === 1 ? '' : 's'}{maxTarget > 0 ? ` · target ${maxTarget} ${wUnit}` : ''}
</AppText>
</View>
</View>
@@ -460,8 +529,10 @@ export default function ProgramDetail() {
)}
</Pressable>
)
- })}
- </View>
+ })}
+ </View>
+ </>
+ ) : null}
</View>
</ScrollView>
</Screen>
diff --git a/mobile/app/(tabs)/programs/[id]/edit.tsx b/mobile/app/(tabs)/programs/[id]/edit.tsx
index a1dd90c..9156295 100644
--- a/mobile/app/(tabs)/programs/[id]/edit.tsx
+++ b/mobile/app/(tabs)/programs/[id]/edit.tsx
@@ -1,25 +1,20 @@
-import { useCallback, useEffect, useRef, useState } from 'react'
-import { Platform, Pressable, ScrollView, Text, View } from 'react-native'
+import { useEffect, useRef, useState } from 'react'
+import { Platform, ScrollView, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
-import { AlertCircle, ArrowLeft, BookOpen, Dumbbell, FileText, Plus, Zap } from 'lucide-react-native'
+import { AlertCircle, ArrowLeft, BookOpen, CalendarDays, FileText } from 'lucide-react-native'
import type { LucideIcon } from 'lucide-react-native'
-import { apiErrorMessage, displayToLbs, lbsToDisplay, weightShort, type Exercise } from '@lyftr/shared'
-import { AppText, Button, EmptyState, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'
-import { ExerciseFormCard } from '../../../../src/components/workouts/ExerciseFormCard'
-import { ExercisePicker } from '../../../../src/components/workouts/ExercisePicker'
+import { apiErrorMessage, displayToLbs, hasWorkoutExercises, lbsToDisplay, weightShort, type Exercise } from '@lyftr/shared'
+import { AppText, Button, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'
import { KeyboardDoneBar } from '../../../../src/components/workouts/KeyboardDoneBar'
+import { ProgramDaysEditor } from '../../../../src/components/programs/ProgramDaysEditor'
import { client, useSettingsStore } from '../../../../src/lib/lyftr'
import { useTheme } from '../../../../src/theme/useTheme'
+import type { DayDraft } from '../../../../src/components/programs/types'
interface ProgramFormData {
name: string
notes: string
- exercises: {
- exercise_id: number
- notes: string
- rest_seconds: number
- sets: { set_number: number; reps: number; weight: number }[]
- }[]
+ days: DayDraft[]
}
const KEYPAD_DONE_ID = 'program-edit-keypad-done'
@@ -39,14 +34,13 @@ export default function EditProgram() {
const settings = useSettingsStore((s) => s.settings)
const fetchSettings = useSettingsStore((s) => s.fetch)
const wUnit = weightShort(settings.weight_unit)
- const { accent, brand, isDark } = useTheme()
+ const { brand, isDark } = useTheme()
- const [showPicker, setShowPicker] = useState(false)
const [loading, setLoading] = useState(false)
const [initialLoading, setInitialLoading] = useState(true)
const [error, setError] = useState('')
const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})
- const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', exercises: [] })
+ const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })
const scrollRef = useRef<ScrollView>(null)
useEffect(() => {
@@ -65,20 +59,26 @@ export default function EditProgram() {
.then((p) => {
if (cancelled) return
const map: Record<number, Exercise> = {}
- ;(p.exercises || []).forEach((ex) => { map[ex.exercise_id] = ex.exercise })
+ ;(p.days || []).forEach((d) => (d.exercises || []).forEach((ex) => { map[ex.exercise_id] = ex.exercise }))
setPickerExercises(map)
setFormData({
name: p.name,
notes: p.notes || '',
- exercises: (p.exercises || []).map((ex) => ({
- exercise_id: ex.exercise_id,
- notes: ex.notes || '',
- rest_seconds: ex.rest_seconds ?? (settings.rest_seconds_default ?? 90),
- sets: (ex.sets || []).map((s) => ({
- set_number: s.set_number,
- reps: s.target_reps,
- // Web parity: unrounded prefill (kg users see long decimals).
- weight: lbsToDisplay(s.target_weight, settings.weight_unit),
+ days: (p.days || []).map((d, i) => ({
+ id: d.id,
+ order_index: d.order_index ?? i,
+ is_rest_day: d.is_rest_day,
+ name: d.name || '',
+ exercises: (d.exercises || []).map((ex) => ({
+ exercise_id: ex.exercise_id,
+ notes: ex.notes || '',
+ rest_seconds: ex.rest_seconds ?? (settings.rest_seconds_default ?? 90),
+ sets: (ex.sets || []).map((s) => ({
+ set_number: s.set_number,
+ reps: s.target_reps,
+ // Web parity: unrounded prefill (kg users see long decimals).
+ weight: lbsToDisplay(s.target_weight, settings.weight_unit),
+ })),
})),
})),
})
@@ -91,76 +91,37 @@ export default function EditProgram() {
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/programs'))
- const addExercise = (exercise: Exercise) => {
- setPickerExercises((prev) => ({ ...prev, [exercise.id]: exercise }))
- setFormData((prev) => ({
- ...prev,
- exercises: [
- ...prev.exercises,
- { exercise_id: exercise.id, notes: '', rest_seconds: settings.rest_seconds_default ?? 90, sets: [{ set_number: 1, reps: 0, weight: 0 }] },
- ],
- }))
- setShowPicker(false)
- setError('')
- }
-
- const removeExercise = useCallback((index: number) =>
- setFormData((prev) => ({ ...prev, exercises: prev.exercises.filter((_, i) => i !== index) })), [])
-
- const addSet = useCallback((exIdx: number) => {
- setFormData((prev) => ({
- ...prev,
- exercises: prev.exercises.map((ex, i) =>
- i !== exIdx ? ex : { ...ex, sets: [...ex.sets, { set_number: ex.sets.length + 1, reps: 0, weight: 0 }] }),
- }))
- }, [])
-
- const removeSet = useCallback((exIdx: number, setIdx: number) => {
- setFormData((prev) => ({
- ...prev,
- exercises: prev.exercises.map((ex, i) =>
- i !== exIdx ? ex : { ...ex, sets: ex.sets.filter((_, j) => j !== setIdx) }),
- }))
- }, [])
-
- const updateSet = useCallback((exIdx: number, setIdx: number, field: 'reps' | 'weight', value: string) => {
- setFormData((prev) => ({
- ...prev,
- exercises: prev.exercises.map((ex, i) =>
- i !== exIdx ? ex : { ...ex, sets: ex.sets.map((s, j) => (j !== setIdx ? s : { ...s, [field]: Number(value) || 0 })) }),
- }))
- }, [])
-
- const updateExNotes = useCallback((exIdx: number, text: string) => {
- setFormData((prev) => ({
- ...prev,
- exercises: prev.exercises.map((ex, i) => (i !== exIdx ? ex : { ...ex, notes: text })),
- }))
- }, [])
-
- const setExRest = useCallback((exIdx: number, secs: number) => {
- setFormData((prev) => ({
- ...prev,
- exercises: prev.exercises.map((ex, i) => (i !== exIdx ? ex : { ...ex, rest_seconds: secs })),
- }))
- }, [])
+ const cacheExercise = (ex: Exercise) => setPickerExercises((prev) => ({ ...prev, [ex.id]: ex }))
const handleSubmit = async () => {
if (!formData.name.trim()) { setError('Program name required'); return }
- if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }
+ if (formData.days.length === 0) { setError('Add at least one day'); return }
+ const hasAnyExercise = hasWorkoutExercises(formData.days)
+ if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }
setLoading(true)
try {
const payload = {
name: formData.name,
notes: formData.notes,
- exercises: formData.exercises.map((ex) => ({
- exercise_id: ex.exercise_id,
- notes: ex.notes,
- rest_seconds: ex.rest_seconds,
- sets: ex.sets.map((s) => ({
- set_number: s.set_number,
- target_reps: s.reps,
- target_weight: displayToLbs(s.weight, settings.weight_unit),
+ // Declares this client round-trips day ids: without it, deleting every
+ // existing day and adding only new (id-less) ones is indistinguishable
+ // from a legacy payload and the server would positionally re-attribute
+ // the deleted days' workout history to the new days.
+ day_ids_known: true,
+ days: formData.days.map((d) => ({
+ id: d.id,
+ order_index: d.order_index,
+ is_rest_day: d.is_rest_day,
+ name: d.name,
+ exercises: d.exercises.map((ex) => ({
+ exercise_id: ex.exercise_id,
+ notes: ex.notes,
+ rest_seconds: ex.rest_seconds,
+ sets: ex.sets.map((s) => ({
+ set_number: s.set_number,
+ target_reps: s.reps,
+ target_weight: displayToLbs(s.weight, settings.weight_unit),
+ })),
})),
})),
}
@@ -175,8 +136,8 @@ export default function EditProgram() {
if (initialLoading) return <Loading />
- const selectedIds = formData.exercises.map((e) => e.exercise_id)
- const totalSets = formData.exercises.reduce((sum, ex) => sum + ex.sets.length, 0)
+ const totalExercises = formData.days.reduce((s, d) => s + d.exercises.length, 0)
+ const totalSets = formData.days.reduce((s, d) => s + d.exercises.reduce((s2, ex) => s2 + ex.sets.length, 0), 0)
return (
<Screen>
@@ -194,7 +155,7 @@ export default function EditProgram() {
<View>
<AppText variant="title">Edit Program</AppText>
<AppText variant="caption" color="muted">
- {formData.exercises.length} exercises • {totalSets} sets
+ {formData.days.length} day{formData.days.length === 1 ? '' : 's'} • {totalExercises} exercise{totalExercises === 1 ? '' : 's'} • {totalSets} set{totalSets === 1 ? '' : 's'}
</AppText>
</View>
</View>
@@ -225,63 +186,20 @@ export default function EditProgram() {
</View>
<View>
- <View className="mb-3">
- <View className="mb-2.5 flex-row items-center gap-2">
- <Zap size={14} color={accent} strokeWidth={2.2} />
- <Label>Exercises</Label>
- </View>
- <Pressable
- accessibilityRole="button"
- onPress={() => setShowPicker(true)}
- className="flex-row items-center justify-center gap-1.5 rounded-lg bg-brand-500 px-3 py-2.5 active:scale-95"
- >
- <Plus size={13} color="#ffffff" />
- <Text className="font-sans-semibold text-xs text-white">Add Exercise</Text>
- </Pressable>
- </View>
-
- {formData.exercises.length === 0 && (
- <View className="rounded-2xl border border-dashed border-surface-border">
- <EmptyState
- compact
- icon={Dumbbell}
- title="No exercises yet"
- subtitle="Add an exercise to build your program"
- />
- </View>
- )}
-
- <View className="gap-4">
- {formData.exercises.map((programEx, exIdx) => (
- <ExerciseFormCard
- key={exIdx}
- index={exIdx}
- exercise={pickerExercises[programEx.exercise_id]}
- notes={programEx.notes}
- sets={programEx.sets}
- restSeconds={programEx.rest_seconds ?? 90}
- unit={wUnit}
- onRemove={removeExercise}
- onNotesChange={updateExNotes}
- onAddSet={addSet}
- onRemoveSet={removeSet}
- onUpdateSet={updateSet}
- onRestChange={setExRest}
- inputAccessoryViewID={KEYPAD_DONE_ID}
- />
- ))}
- {formData.exercises.length > 0 && (
- <Pressable
- accessibilityRole="button"
- accessibilityLabel="Add exercise"
- onPress={() => setShowPicker(true)}
- className="h-11 flex-row items-center justify-center gap-1.5 rounded-2xl border border-dashed border-surface-border active:opacity-60"
- >
- <Plus size={14} color={accent} />
- <Text className="font-sans-semibold text-xs" style={{ color: accent }}>Add Exercise</Text>
- </Pressable>
- )}
+ <View className="mb-3 flex-row items-center gap-2">
+ <CalendarDays size={14} color={brand.cyan} strokeWidth={2.2} />
+ <Label>Days</Label>
+ <AppText variant="caption" color="muted">(repeats in this order)</AppText>
</View>
+ <ProgramDaysEditor
+ days={formData.days}
+ onChange={(days) => setFormData((prev) => ({ ...prev, days }))}
+ pickerExercises={pickerExercises}
+ onCacheExercise={cacheExercise}
+ unit={wUnit}
+ restSecondsDefault={settings.rest_seconds_default ?? 90}
+ inputAccessoryViewID={KEYPAD_DONE_ID}
+ />
</View>
</View>
</ScrollView>
@@ -292,10 +210,6 @@ export default function EditProgram() {
</View>
<KeyboardDoneBar nativeID={KEYPAD_DONE_ID} />
-
- {showPicker && (
- <ExercisePicker selectedIds={selectedIds} onSelect={addExercise} onClose={() => setShowPicker(false)} />
- )}
</Screen>
)
}
diff --git a/mobile/app/(tabs)/programs/index.tsx b/mobile/app/(tabs)/programs/index.tsx
index ce32f89..8094b82 100644
--- a/mobile/app/(tabs)/programs/index.tsx
+++ b/mobile/app/(tabs)/programs/index.tsx
@@ -3,6 +3,7 @@ import { ActivityIndicator, FlatList, RefreshControl, View } from 'react-native'
import { router, useFocusEffect } from 'expo-router'
import { BookOpen, Plus } from 'lucide-react-native'
import type { Program } from '@lyftr/shared'
+import { programExerciseCount } from '@lyftr/shared'
import { AppText, Card, EmptyState, IconButton, Label, PageHeader, Screen, SearchField } from '../../../src/components/ui'
import { ProgramCard } from '../../../src/components/programs/ProgramCard'
import { ProgramsSkeleton } from '../../../src/components/programs/ProgramsSkeleton'
@@ -69,7 +70,7 @@ export default function Programs() {
label: 'Avg Exercises',
value:
programs.length > 0
- ? String(Math.round(programs.reduce((s, p) => s + (p.exercises?.length || 0), 0) / programs.length))
+ ? String(Math.round(programs.reduce((s, p) => s + programExerciseCount(p), 0) / programs.length))
: '0',
unit: 'per program',
},
diff --git a/mobile/app/(tabs)/programs/new.tsx b/mobile/app/(tabs)/programs/new.tsx
index 0f7ffe9..f3db9f5 100644
--- a/mobile/app/(tabs)/programs/new.tsx
+++ b/mobile/app/(tabs)/programs/new.tsx
@@ -1,15 +1,15 @@
-import { useCallback, useEffect, useRef, useState } from 'react'
-import { Platform, Pressable, ScrollView, Text, View } from 'react-native'
+import { useEffect, useRef, useState } from 'react'
+import { Platform, ScrollView, View } from 'react-native'
import { router } from 'expo-router'
-import { AlertCircle, ArrowLeft, BookOpen, Dumbbell, FileText, Plus, Zap } from 'lucide-react-native'
+import { AlertCircle, ArrowLeft, BookOpen, CalendarDays, FileText } from 'lucide-react-native'
import type { LucideIcon } from 'lucide-react-native'
-import { apiErrorMessage, displayToLbs, weightShort, type Exercise } from '@lyftr/shared'
-import { AppText, Button, EmptyState, Field, IconButton, Label, Screen } from '../../../src/components/ui'
-import { ExerciseFormCard } from '../../../src/components/workouts/ExerciseFormCard'
-import { ExercisePicker } from '../../../src/components/workouts/ExercisePicker'
+import { apiErrorMessage, displayToLbs, hasWorkoutExercises, weightShort, type Exercise } from '@lyftr/shared'
+import { AppText, Button, Field, IconButton, Label, Screen } from '../../../src/components/ui'
import { KeyboardDoneBar } from '../../../src/components/workouts/KeyboardDoneBar'
+import { ProgramDaysEditor } from '../../../src/components/programs/ProgramDaysEditor'
import { client, useSettingsStore } from '../../../src/lib/lyftr'
import { useTheme } from '../../../src/theme/useTheme'
+import type { DayDraft } from '../../../src/components/programs/types'
// Weights live in DISPLAY units in the form (reps/weight per set, same shape the shared
// ExerciseFormCard edits); converted to lbs + mapped to target_reps/target_weight only in
@@ -17,12 +17,7 @@ import { useTheme } from '../../../src/theme/useTheme'
interface ProgramFormData {
name: string
notes: string
- exercises: {
- exercise_id: number
- notes: string
- rest_seconds: number
- sets: { set_number: number; reps: number; weight: number }[]
- }[]
+ days: DayDraft[]
}
const KEYPAD_DONE_ID = 'program-new-keypad-done'
@@ -42,13 +37,12 @@ export default function AddProgram() {
const settings = useSettingsStore((s) => s.settings)
const fetchSettings = useSettingsStore((s) => s.fetch)
const wUnit = weightShort(settings.weight_unit)
- const { accent, brand, isDark } = useTheme()
+ const { brand, isDark } = useTheme()
- const [showPicker, setShowPicker] = useState(false)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})
- const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', exercises: [] })
+ const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })
const scrollRef = useRef<ScrollView>(null)
useEffect(() => {
@@ -61,84 +55,31 @@ export default function AddProgram() {
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/programs'))
- const addExercise = (exercise: Exercise) => {
- setPickerExercises((prev) => ({ ...prev, [exercise.id]: exercise }))
- setFormData((prev) => ({
- ...prev,
- exercises: [
- ...prev.exercises,
- {
- exercise_id: exercise.id,
- notes: '',
- rest_seconds: settings.rest_seconds_default ?? 90,
- sets: [{ set_number: 1, reps: 0, weight: 0 }],
- },
- ],
- }))
- setShowPicker(false)
- setError('')
- }
-
- // Stable + immutable handlers (see workouts/new.tsx) so the memoized ExerciseFormCard
- // only re-renders the edited card.
- const removeExercise = useCallback((index: number) =>
- setFormData((prev) => ({ ...prev, exercises: prev.exercises.filter((_, i) => i !== index) })), [])
-
- const addSet = useCallback((exIdx: number) => {
- setFormData((prev) => ({
- ...prev,
- exercises: prev.exercises.map((ex, i) =>
- i !== exIdx ? ex : { ...ex, sets: [...ex.sets, { set_number: ex.sets.length + 1, reps: 0, weight: 0 }] }),
- }))
- }, [])
-
- // Web parity: removing a middle set does NOT renumber the rest.
- const removeSet = useCallback((exIdx: number, setIdx: number) => {
- setFormData((prev) => ({
- ...prev,
- exercises: prev.exercises.map((ex, i) =>
- i !== exIdx ? ex : { ...ex, sets: ex.sets.filter((_, j) => j !== setIdx) }),
- }))
- }, [])
-
- const updateSet = useCallback((exIdx: number, setIdx: number, field: 'reps' | 'weight', value: string) => {
- setFormData((prev) => ({
- ...prev,
- exercises: prev.exercises.map((ex, i) =>
- i !== exIdx ? ex : { ...ex, sets: ex.sets.map((s, j) => (j !== setIdx ? s : { ...s, [field]: Number(value) || 0 })) }),
- }))
- }, [])
-
- const updateExNotes = useCallback((exIdx: number, text: string) => {
- setFormData((prev) => ({
- ...prev,
- exercises: prev.exercises.map((ex, i) => (i !== exIdx ? ex : { ...ex, notes: text })),
- }))
- }, [])
-
- const setExRest = useCallback((exIdx: number, secs: number) => {
- setFormData((prev) => ({
- ...prev,
- exercises: prev.exercises.map((ex, i) => (i !== exIdx ? ex : { ...ex, rest_seconds: secs })),
- }))
- }, [])
+ const cacheExercise = (ex: Exercise) => setPickerExercises((prev) => ({ ...prev, [ex.id]: ex }))
const handleSubmit = async () => {
if (!formData.name.trim()) { setError('Program name required'); return }
- if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }
+ if (formData.days.length === 0) { setError('Add at least one day'); return }
+ const hasAnyExercise = hasWorkoutExercises(formData.days)
+ if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }
setLoading(true)
try {
const payload = {
name: formData.name,
notes: formData.notes,
- exercises: formData.exercises.map((ex) => ({
- exercise_id: ex.exercise_id,
- notes: ex.notes,
- rest_seconds: ex.rest_seconds,
- sets: ex.sets.map((s) => ({
- set_number: s.set_number,
- target_reps: s.reps,
- target_weight: displayToLbs(s.weight, settings.weight_unit),
+ days: formData.days.map((d) => ({
+ order_index: d.order_index,
+ is_rest_day: d.is_rest_day,
+ name: d.name,
+ exercises: d.exercises.map((ex) => ({
+ exercise_id: ex.exercise_id,
+ notes: ex.notes,
+ rest_seconds: ex.rest_seconds,
+ sets: ex.sets.map((s) => ({
+ set_number: s.set_number,
+ target_reps: s.reps,
+ target_weight: displayToLbs(s.weight, settings.weight_unit),
+ })),
})),
})),
}
@@ -151,8 +92,8 @@ export default function AddProgram() {
}
}
- const selectedIds = formData.exercises.map((e) => e.exercise_id)
- const totalSets = formData.exercises.reduce((sum, ex) => sum + ex.sets.length, 0)
+ const totalExercises = formData.days.reduce((s, d) => s + d.exercises.length, 0)
+ const totalSets = formData.days.reduce((s, d) => s + d.exercises.reduce((s2, ex) => s2 + ex.sets.length, 0), 0)
return (
<Screen>
@@ -170,7 +111,7 @@ export default function AddProgram() {
<View>
<AppText variant="title">New Program</AppText>
<AppText variant="caption" color="muted">
- {formData.exercises.length} exercises • {totalSets} sets
+ {formData.days.length} day{formData.days.length === 1 ? '' : 's'} • {totalExercises} exercise{totalExercises === 1 ? '' : 's'} • {totalSets} set{totalSets === 1 ? '' : 's'}
</AppText>
</View>
</View>
@@ -202,64 +143,20 @@ export default function AddProgram() {
</View>
<View>
- <View className="mb-3">
- <View className="mb-2.5 flex-row items-center gap-2">
- <Zap size={14} color={accent} strokeWidth={2.2} />
- <Label>Exercises</Label>
- <AppText variant="caption" color="muted">(required)</AppText>
- </View>
- <Pressable
- accessibilityRole="button"
- onPress={() => setShowPicker(true)}
- className="flex-row items-center justify-center gap-1.5 rounded-lg bg-brand-500 px-3 py-2.5 active:scale-95"
- >
- <Plus size={13} color="#ffffff" />
- <Text className="font-sans-semibold text-xs text-white">Add Exercise</Text>
- </Pressable>
- </View>
-
- {formData.exercises.length === 0 && (
- <View className="rounded-2xl border border-dashed border-surface-border">
- <EmptyState
- compact
- icon={Dumbbell}
- title="No exercises yet"
- subtitle="Add an exercise to build your program"
- />
- </View>
- )}
-
- <View className="gap-4">
- {formData.exercises.map((programEx, exIdx) => (
- <ExerciseFormCard
- key={exIdx}
- index={exIdx}
- exercise={pickerExercises[programEx.exercise_id]}
- notes={programEx.notes}
- sets={programEx.sets}
- restSeconds={programEx.rest_seconds ?? 90}
- unit={wUnit}
- onRemove={removeExercise}
- onNotesChange={updateExNotes}
- onAddSet={addSet}
- onRemoveSet={removeSet}
- onUpdateSet={updateSet}
- onRestChange={setExRest}
- inputAccessoryViewID={KEYPAD_DONE_ID}
- />
- ))}
- {formData.exercises.length > 0 && (
- <Pressable
- accessibilityRole="button"
- accessibilityLabel="Add exercise"
- onPress={() => setShowPicker(true)}
- className="h-11 flex-row items-center justify-center gap-1.5 rounded-2xl border border-dashed border-surface-border active:opacity-60"
- >
- <Plus size={14} color={accent} />
- <Text className="font-sans-semibold text-xs" style={{ color: accent }}>Add Exercise</Text>
- </Pressable>
- )}
+ <View className="mb-3 flex-row items-center gap-2">
+ <CalendarDays size={14} color={brand.cyan} strokeWidth={2.2} />
+ <Label>Days</Label>
+ <AppText variant="caption" color="muted">(required — repeats in this order)</AppText>
</View>
+ <ProgramDaysEditor
+ days={formData.days}
+ onChange={(days) => setFormData((prev) => ({ ...prev, days }))}
+ pickerExercises={pickerExercises}
+ onCacheExercise={cacheExercise}
+ unit={wUnit}
+ restSecondsDefault={settings.rest_seconds_default ?? 90}
+ inputAccessoryViewID={KEYPAD_DONE_ID}
+ />
</View>
</View>
</ScrollView>
@@ -270,10 +167,6 @@ export default function AddProgram() {
</View>
<KeyboardDoneBar nativeID={KEYPAD_DONE_ID} />
-
- {showPicker && (
- <ExercisePicker selectedIds={selectedIds} onSelect={addExercise} onClose={() => setShowPicker(false)} />
- )}
</Screen>
)
}
diff --git a/mobile/app/(tabs)/workouts/new.tsx b/mobile/app/(tabs)/workouts/new.tsx
index d10f155..ea7667e 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, weightShort, type Exercise, type Program } from '@lyftr/shared'
+import { apiErrorMessage, displayToLbs, lbsToDisplay, weightShort, type Exercise, type Program, type ProgramDay } 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'
@@ -79,17 +79,15 @@ export default function AddWorkout() {
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/workouts'))
- const loadFromProgram = (program: Program) => {
+ const loadFromProgram = (_program: Program, day: ProgramDay) => {
const newMap: Record<number, Exercise> = { ...pickerExercises }
- const newExercises = (program.exercises || []).map((ex) => {
+ const newExercises = (day.exercises || []).map((ex) => {
newMap[ex.exercise_id] = ex.exercise
return {
exercise_id: ex.exercise_id,
notes: ex.notes || '',
rest_seconds: ex.rest_seconds ?? (settings.rest_seconds_default ?? 90),
- // Web parity (latent web quirk, do not fix): target_weight is server-lbs
- // copied straight into the display-unit form — identity for lbs users.
- sets: (ex.sets || []).map((s) => ({ set_number: s.set_number, reps: s.target_reps, weight: s.target_weight })),
+ sets: (ex.sets || []).map((s) => ({ set_number: s.set_number, reps: s.target_reps, weight: lbsToDisplay(s.target_weight, settings.weight_unit) })),
}
})
setPickerExercises(newMap)
diff --git a/mobile/app/(tabs)/workouts/start.tsx b/mobile/app/(tabs)/workouts/start.tsx
index 0bfe0e6..004cbf7 100644
--- a/mobile/app/(tabs)/workouts/start.tsx
+++ b/mobile/app/(tabs)/workouts/start.tsx
@@ -2,8 +2,10 @@ import { useEffect, useState } from 'react'
import { ActivityIndicator, Pressable, ScrollView, View } from 'react-native'
import { router } from 'expo-router'
import { ArrowLeft, BookOpen, ChevronRight, Play, Timer, Trash2, Zap } from 'lucide-react-native'
-import type { ActiveSessionExercise, Program } from '@lyftr/shared'
+import type { Program, ProgramDay } from '@lyftr/shared'
+import { activeSessionExercisesForDay, sessionNameForDay } from '@lyftr/shared'
import { AppText, IconButton, Screen } from '../../../src/components/ui'
+import { DayPickerSheet, pickProgramDay } from '../../../src/components/programs/DayPickerSheet'
import { client, useWorkoutSession } from '../../../src/lib/lyftr'
import { useTheme } from '../../../src/theme/useTheme'
@@ -19,6 +21,7 @@ export default function StartWorkout() {
const [programs, setPrograms] = useState<Program[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
+ const [dayPickFor, setDayPickFor] = useState<Program | null>(null)
useEffect(() => {
setLoading(true)
@@ -37,23 +40,9 @@ export default function StartWorkout() {
router.push('/workouts/active')
}
- const startFromProgram = (program: Program) => {
- const exercises: ActiveSessionExercise[] = (program.exercises || []).map((ex) => ({
- exercise_id: ex.exercise_id,
- exercise: ex.exercise,
- notes: ex.notes || '',
- rest_seconds: ex.rest_seconds,
- sets: (ex.sets || []).map((s) => ({
- set_number: s.set_number,
- target_reps: s.target_reps,
- target_weight: s.target_weight,
- actual_reps: s.target_reps,
- actual_weight: s.target_weight,
- completed: false,
- program_set_id: s.id,
- })),
- }))
- startSession(program.name, exercises, program.id)
+ const startFromProgram = (program: Program, day: ProgramDay) => {
+ startSession(sessionNameForDay(program, day), activeSessionExercisesForDay(day), program.id, day.id)
+ setDayPickFor(null)
router.push('/workouts/active')
}
@@ -140,27 +129,36 @@ export default function StartWorkout() {
</View>
) : (
<View className="gap-2">
- {programs.map((p) => (
- <Pressable
- key={p.id}
- onPress={() => startFromProgram(p)}
- className="flex-row items-center gap-3 rounded-2xl border border-surface-border bg-surface-raised p-4 active:bg-surface-muted"
- >
- <View className="h-10 w-10 items-center justify-center rounded-xl border border-brand-500/20 bg-brand-500/10">
- <BookOpen size={20} color={accent} />
- </View>
- <View className="flex-1">
- <AppText variant="bodySemibold" numberOfLines={1}>{p.name}</AppText>
- <AppText variant="caption" color="muted" className="mt-0.5">{p.exercises?.length || 0} exercises</AppText>
- </View>
- <Play size={16} color={accent} />
- </Pressable>
- ))}
+ {programs.map((p) => {
+ const dayCount = p.days?.length ?? 0
+ return (
+ <Pressable
+ key={p.id}
+ // onEmpty: a program with zero workout days has nothing to load —
+ // open its detail page (add a day there) instead of a dead tap.
+ onPress={() => pickProgramDay(p, startFromProgram, setDayPickFor, () => router.push(`/programs/${p.id}`))}
+ className="flex-row items-center gap-3 rounded-2xl border border-surface-border bg-surface-raised p-4 active:bg-surface-muted"
+ >
+ <View className="h-10 w-10 items-center justify-center rounded-xl border border-brand-500/20 bg-brand-500/10">
+ <BookOpen size={20} color={accent} />
+ </View>
+ <View className="flex-1">
+ <AppText variant="bodySemibold" numberOfLines={1}>{p.name}</AppText>
+ <AppText variant="caption" color="muted" className="mt-0.5">
+ {dayCount > 0 ? `${dayCount} day${dayCount === 1 ? '' : 's'}` : 'No days yet'}
+ </AppText>
+ </View>
+ <Play size={16} color={accent} />
+ </Pressable>
+ )
+ })}
</View>
)}
</View>
</View>
</ScrollView>
+
+ <DayPickerSheet program={dayPickFor} onSelect={startFromProgram} onClose={() => setDayPickFor(null)} />
</Screen>
)
}
diff --git a/mobile/src/components/programs/DayExercisesEditor.test.tsx b/mobile/src/components/programs/DayExercisesEditor.test.tsx
new file mode 100644
index 0000000..bc8c6bc
--- /dev/null
+++ b/mobile/src/components/programs/DayExercisesEditor.test.tsx
@@ -0,0 +1,91 @@
+import { fireEvent, render, screen } from '@testing-library/react-native'
+import type { Exercise } from '@lyftr/shared'
+
+// Same transitive-import stubs as DayPickerSheet.test.tsx (ui barrel → useTheme →
+// lib/lyftr → expo-router; storage adapter → AsyncStorage; sheets → safe-area).
+jest.mock('expo-router', () => ({
+ router: { push: jest.fn(), navigate: jest.fn(), replace: jest.fn() },
+}))
+jest.mock('@react-native-async-storage/async-storage', () =>
+ require('@react-native-async-storage/async-storage/jest/async-storage-mock')
+)
+jest.mock('react-native-safe-area-context', () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),
+}))
+
+import { DayExercisesEditor } from './DayExercisesEditor'
+import type { DayExerciseDraft } from './types'
+
+const bench: Exercise = {
+ id: 1, name: 'Bench Press', muscle_group: 'chest', secondary_muscles: [],
+ category: 'strength', equipment: 'barbell', description: '',
+}
+
+const draft = (overrides: Partial<DayExerciseDraft> = {}): DayExerciseDraft => ({
+ exercise_id: 1,
+ notes: '',
+ rest_seconds: 90,
+ sets: [{ set_number: 1, reps: 5, weight: 135 }],
+ ...overrides,
+})
+
+const renderEditor = (exercises: DayExerciseDraft[], onChange = jest.fn()) => {
+ render(
+ <DayExercisesEditor
+ exercises={exercises}
+ onChange={onChange}
+ pickerExercises={{ 1: bench }}
+ onCacheExercise={() => {}}
+ unit="lbs"
+ restSecondsDefault={90}
+ />
+ )
+ return onChange
+}
+
+describe('DayExercisesEditor', () => {
+ it('renders the empty state when the day has no exercises', () => {
+ renderEditor([])
+ expect(screen.getByText('No exercises yet')).toBeTruthy()
+ })
+
+ it('shows the cached exercise', () => {
+ renderEditor([draft()])
+ expect(screen.getByText('Bench Press')).toBeTruthy()
+ })
+
+ it('Add Set appends a set with the next set_number', () => {
+ const onChange = renderEditor([draft()])
+ fireEvent.press(screen.getByText('Add Set'))
+ const next: DayExerciseDraft[] = onChange.mock.calls[0][0]
+ expect(next[0].sets).toHaveLength(2)
+ expect(next[0].sets[1]).toEqual({ set_number: 2, reps: 0, weight: 0 })
+ })
+
+ it('editing reps coerces to a number (garbage → 0)', () => {
+ const onChange = renderEditor([draft()])
+ fireEvent.changeText(screen.getByLabelText('Set reps'), '8')
+ expect(onChange.mock.calls[0][0][0].sets[0].reps).toBe(8)
+ fireEvent.changeText(screen.getByLabelText('Set reps'), 'abc')
+ expect(onChange.mock.calls[1][0][0].sets[0].reps).toBe(0)
+ })
+
+ it('removing the exercise emits an empty list', () => {
+ const onChange = renderEditor([draft()])
+ fireEvent.press(screen.getByLabelText('Remove Bench Press'))
+ expect(onChange.mock.calls[0][0]).toEqual([])
+ })
+
+ it('removing a set only touches that set', () => {
+ const onChange = renderEditor([draft({
+ sets: [
+ { set_number: 1, reps: 5, weight: 135 },
+ { set_number: 2, reps: 5, weight: 145 },
+ ],
+ })])
+ fireEvent.press(screen.getAllByLabelText('Remove set')[0])
+ const next: DayExerciseDraft[] = onChange.mock.calls[0][0]
+ expect(next[0].sets).toHaveLength(1)
+ expect(next[0].sets[0].weight).toBe(145)
+ })
+})
diff --git a/mobile/src/components/programs/DayExercisesEditor.tsx b/mobile/src/components/programs/DayExercisesEditor.tsx
new file mode 100644
index 0000000..efce2b4
--- /dev/null
+++ b/mobile/src/components/programs/DayExercisesEditor.tsx
@@ -0,0 +1,120 @@
+import { useCallback, useState } from 'react'
+import { Pressable, Text, View } from 'react-native'
+import { Dumbbell, Plus } from 'lucide-react-native'
+import type { Exercise } from '@lyftr/shared'
+import { EmptyState } from '../ui'
+import { ExerciseFormCard } from '../workouts/ExerciseFormCard'
+import { ExercisePicker } from '../workouts/ExercisePicker'
+import { useTheme } from '../../theme/useTheme'
+import type { DayExerciseDraft } from './types'
+
+interface Props {
+ exercises: DayExerciseDraft[]
+ onChange: (exercises: DayExerciseDraft[]) => void
+ pickerExercises: Record<number, Exercise>
+ onCacheExercise: (ex: Exercise) => void
+ unit: string
+ restSecondsDefault: number
+ inputAccessoryViewID?: string
+}
+
+// The per-exercise editing UI (name/notes/rest/target sets), unchanged from the
+// pre-multi-day flat editor (ExerciseFormCard) — just parameterized so each Day in
+// ProgramDaysEditor owns its own instance instead of the screen owning one flat
+// exercises array. Port of web/components/programs/DayExercisesEditor.tsx.
+export function DayExercisesEditor({
+ exercises, onChange, pickerExercises, onCacheExercise, unit, restSecondsDefault, inputAccessoryViewID,
+}: Props) {
+ const { accent } = useTheme()
+ const [showPicker, setShowPicker] = useState(false)
+
+ const addExercise = (exercise: Exercise) => {
+ onCacheExercise(exercise)
+ onChange([...exercises, {
+ exercise_id: exercise.id,
+ notes: '',
+ rest_seconds: restSecondsDefault,
+ sets: [{ set_number: 1, reps: 0, weight: 0 }],
+ }])
+ setShowPicker(false)
+ }
+
+ // Stable + immutable handlers so the memoized ExerciseFormCard only re-renders the
+ // edited card (same rationale as the pre-multi-day screens).
+ const removeExercise = useCallback((index: number) => onChange(exercises.filter((_, i) => i !== index)), [exercises, onChange])
+
+ const addSet = useCallback((exIdx: number) => {
+ onChange(exercises.map((ex, i) => (i !== exIdx ? ex : { ...ex, sets: [...ex.sets, { set_number: ex.sets.length + 1, reps: 0, weight: 0 }] })))
+ }, [exercises, onChange])
+
+ const removeSet = useCallback((exIdx: number, setIdx: number) => {
+ onChange(exercises.map((ex, i) => (i !== exIdx ? ex : { ...ex, sets: ex.sets.filter((_, j) => j !== setIdx) })))
+ }, [exercises, onChange])
+
+ const updateSet = useCallback((exIdx: number, setIdx: number, field: 'reps' | 'weight', value: string) => {
+ onChange(exercises.map((ex, i) => (i !== exIdx ? ex : { ...ex, sets: ex.sets.map((s, j) => (j !== setIdx ? s : { ...s, [field]: Number(value) || 0 })) })))
+ }, [exercises, onChange])
+
+ const updateExNotes = useCallback((exIdx: number, text: string) => {
+ onChange(exercises.map((ex, i) => (i !== exIdx ? ex : { ...ex, notes: text })))
+ }, [exercises, onChange])
+
+ const setExRest = useCallback((exIdx: number, secs: number) => {
+ onChange(exercises.map((ex, i) => (i !== exIdx ? ex : { ...ex, rest_seconds: secs })))
+ }, [exercises, onChange])
+
+ const selectedIds = exercises.map((e) => e.exercise_id)
+
+ return (
+ <View>
+ <Pressable
+ accessibilityRole="button"
+ onPress={() => setShowPicker(true)}
+ className="mb-3 flex-row items-center justify-center gap-1.5 rounded-lg bg-brand-500 px-3 py-2.5 active:scale-95"
+ >
+ <Plus size={13} color="#ffffff" />
+ <Text className="font-sans-semibold text-xs text-white">Add Exercise</Text>
+ </Pressable>
+
+ {exercises.length === 0 ? (
+ <View className="rounded-2xl border border-dashed border-surface-border">
+ <EmptyState compact icon={Dumbbell} title="No exercises yet" subtitle="Add an exercise to this day" />
+ </View>
+ ) : (
+ <View className="gap-4">
+ {exercises.map((dayEx, exIdx) => (
+ <ExerciseFormCard
+ key={exIdx}
+ index={exIdx}
+ exercise={pickerExercises[dayEx.exercise_id]}
+ notes={dayEx.notes}
+ sets={dayEx.sets}
+ restSeconds={dayEx.rest_seconds ?? 90}
+ unit={unit}
+ onRemove={removeExercise}
+ onNotesChange={updateExNotes}
+ onAddSet={addSet}
+ onRemoveSet={removeSet}
+ onUpdateSet={updateSet}
+ onRestChange={setExRest}
+ inputAccessoryViewID={inputAccessoryViewID}
+ />
+ ))}
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel="Add exercise"
+ onPress={() => setShowPicker(true)}
+ className="h-11 flex-row items-center justify-center gap-1.5 rounded-2xl border border-dashed border-surface-border active:opacity-60"
+ >
+ <Plus size={14} color={accent} />
+ <Text className="font-sans-semibold text-xs" style={{ color: accent }}>Add Exercise</Text>
+ </Pressable>
+ </View>
+ )}
+
+ {showPicker && (
+ <ExercisePicker selectedIds={selectedIds} onSelect={addExercise} onClose={() => setShowPicker(false)} />
+ )}
+ </View>
+ )
+}
diff --git a/mobile/src/components/programs/DayPickerSheet.test.tsx b/mobile/src/components/programs/DayPickerSheet.test.tsx
new file mode 100644
index 0000000..465cab1
--- /dev/null
+++ b/mobile/src/components/programs/DayPickerSheet.test.tsx
@@ -0,0 +1,101 @@
+import { fireEvent, render, screen } from '@testing-library/react-native'
+import type { Program, ProgramDay } from '@lyftr/shared'
+
+// expo-router can't load under bare jest (see jest.config.js note — route files are
+// never collected for the same reason); the sheet's import chain reaches it via the
+// ui barrel → useTheme → lib/lyftr, so stub just the router surface lib/lyftr touches.
+jest.mock('expo-router', () => ({
+ router: { push: jest.fn(), navigate: jest.fn(), replace: jest.fn() },
+}))
+jest.mock('@react-native-async-storage/async-storage', () =>
+ require('@react-native-async-storage/async-storage/jest/async-storage-mock')
+)
+// Sheet reads useSafeAreaInsets; there's no provider under test — zeroed insets.
+jest.mock('react-native-safe-area-context', () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),
+}))
+
+import { DayPickerSheet, pickProgramDay } from './DayPickerSheet'
+
+const day = (overrides: Partial<ProgramDay> = {}): ProgramDay => ({
+ id: 1,
+ order_index: 0,
+ is_rest_day: false,
+ name: '',
+ exercises: [],
+ ...overrides,
+})
+
+const program = (days: ProgramDay[], currentDayIndex = 0): Program => ({
+ id: 1,
+ name: 'PPL',
+ created_at: '2026-01-01T00:00:00Z',
+ days,
+ current_day_index: currentDayIndex,
+})
+
+describe('pickProgramDay', () => {
+ it('zero workout days → onEmpty, never the sheet or a selection', () => {
+ const onSelect = jest.fn()
+ const openSheet = jest.fn()
+ const onEmpty = jest.fn()
+ pickProgramDay(program([day({ is_rest_day: true })]), onSelect, openSheet, onEmpty)
+ expect(onEmpty).toHaveBeenCalled()
+ expect(onSelect).not.toHaveBeenCalled()
+ expect(openSheet).not.toHaveBeenCalled()
+ })
+
+ it('exactly one workout day resolves immediately (one-tap flow preserved)', () => {
+ const onSelect = jest.fn()
+ const openSheet = jest.fn()
+ const only = day({ id: 5, order_index: 1 })
+ const p = program([day({ id: 4, order_index: 0, is_rest_day: true }), only])
+ pickProgramDay(p, onSelect, openSheet)
+ expect(onSelect).toHaveBeenCalledWith(p, only)
+ expect(openSheet).not.toHaveBeenCalled()
+ })
+
+ it('multiple workout days defer to the sheet', () => {
+ const onSelect = jest.fn()
+ const openSheet = jest.fn()
+ const p = program([day({ id: 1 }), day({ id: 2, order_index: 1 })])
+ pickProgramDay(p, onSelect, openSheet)
+ expect(openSheet).toHaveBeenCalledWith(p)
+ expect(onSelect).not.toHaveBeenCalled()
+ })
+})
+
+describe('DayPickerSheet', () => {
+ const days = [
+ day({ id: 1, order_index: 0, name: 'Push' }),
+ day({ id: 2, order_index: 1, is_rest_day: true }),
+ day({ id: 3, order_index: 2 }), // unnamed → label from its cycle position
+ ]
+
+ it('renders nothing when program is null', () => {
+ render(<DayPickerSheet program={null} onSelect={() => {}} onClose={() => {}} />)
+ expect(screen.queryByText('Pick a Day')).toBeNull()
+ })
+
+ it('lists only workout days, labeled by cycle position (not filtered index)', () => {
+ render(<DayPickerSheet program={program(days)} onSelect={() => {}} onClose={() => {}} />)
+ expect(screen.getByText('Push')).toBeTruthy()
+ // The unnamed day sits at cycle position 2 → "Day 3", NOT "Day 2" (the
+ // rest-filtered loop index) — regression guard for the dayLabel(day, i) bug.
+ expect(screen.getByText('Day 3')).toBeTruthy()
+ expect(screen.queryByText('Rest Day')).toBeNull()
+ })
+
+ it('marks the due day with a TODAY chip', () => {
+ render(<DayPickerSheet program={program(days, 2)} onSelect={() => {}} onClose={() => {}} />)
+ expect(screen.getByText('TODAY')).toBeTruthy()
+ })
+
+ it('selecting a day fires onSelect with the program and that day', () => {
+ const onSelect = jest.fn()
+ const p = program(days)
+ render(<DayPickerSheet program={p} onSelect={onSelect} onClose={() => {}} />)
+ fireEvent.press(screen.getByText('Push'))
+ expect(onSelect).toHaveBeenCalledWith(p, days[0])
+ })
+})
diff --git a/mobile/src/components/programs/DayPickerSheet.tsx b/mobile/src/components/programs/DayPickerSheet.tsx
new file mode 100644
index 0000000..3209128
--- /dev/null
+++ b/mobile/src/components/programs/DayPickerSheet.tsx
@@ -0,0 +1,73 @@
+import { ScrollView, View } from 'react-native'
+import { Dumbbell } from 'lucide-react-native'
+import type { Program, ProgramDay } from '@lyftr/shared'
+import { workoutDays, dayLabel, todaysDay } from '@lyftr/shared'
+import { AppText, ListRow, Sheet } from '../ui'
+import { useTheme } from '../../theme/useTheme'
+
+interface Props {
+ /** The program to pick a day from; sheet is closed when null. */
+ program: Program | null
+ onSelect: (program: Program, day: ProgramDay) => void
+ onClose: () => void
+}
+
+// Given a program the user just tapped, either resolve straight to its one workout
+// day (skip the sheet entirely — keeps the single-day-program flow a one-tap action,
+// same as before the multi-day rework) or hand it to `openSheet` so DayPickerSheet
+// can ask which day. For a program with zero workout days (nothing to load), defers
+// to `onEmpty` if given — web parity: navigate somewhere rather than a dead tap.
+export function pickProgramDay(
+ program: Program,
+ onSelect: (program: Program, day: ProgramDay) => void,
+ openSheet: (program: Program) => void,
+ onEmpty?: () => void
+) {
+ const days = workoutDays(program)
+ if (days.length === 0) { onEmpty?.(); return }
+ if (days.length === 1) { onSelect(program, days[0]); return }
+ openSheet(program)
+}
+
+// Bottom sheet listing a program's workout days (rest days excluded — nothing to
+// load from them) so the caller can pick which one to start/load. Only ever shown
+// when pickProgramDay() determined the program has more than one workout day.
+export function DayPickerSheet({ program, onSelect, onClose }: Props) {
+ const { accent } = useTheme()
+ if (!program) return null
+ const days = workoutDays(program)
+ const todayId = todaysDay(program)?.id
+
+ return (
+ <Sheet open onClose={onClose} haptic="selection">
+ <View className="px-6">
+ <View className="items-center pb-4">
+ <AppText variant="label" color="muted" className="uppercase" style={{ letterSpacing: 1.5 }}>
+ {program.name}
+ </AppText>
+ <AppText variant="heading" className="mt-0.5">Pick a Day</AppText>
+ </View>
+ <ScrollView style={{ maxHeight: 360 }} showsVerticalScrollIndicator={false}>
+ {days.map((day, i) => (
+ <ListRow
+ key={day.id ?? i}
+ primary={
+ <View className="flex-row items-center gap-2">
+ <AppText variant="bodySemibold">{dayLabel(day, day.order_index)}</AppText>
+ {day.id === todayId ? (
+ <View className="rounded-full bg-brand-500/15 px-1.5 py-0.5">
+ <AppText variant="caption" style={{ color: accent }}>TODAY</AppText>
+ </View>
+ ) : null}
+ </View>
+ }
+ secondary={`${(day.exercises ?? []).length} exercise${(day.exercises ?? []).length === 1 ? '' : 's'}`}
+ right={<Dumbbell size={16} color={accent} />}
+ onPress={() => onSelect(program, day)}
+ />
+ ))}
+ </ScrollView>
+ </View>
+ </Sheet>
+ )
+}
diff --git a/mobile/src/components/programs/ProgramCard.tsx b/mobile/src/components/programs/ProgramCard.tsx
index e142a1d..63972bd 100644
--- a/mobile/src/components/programs/ProgramCard.tsx
+++ b/mobile/src/components/programs/ProgramCard.tsx
@@ -2,12 +2,17 @@ import { useState } from 'react'
import { Pressable, View } from 'react-native'
import { router, type Href } from 'expo-router'
import { format } from 'date-fns'
-import { BookOpen, ChevronRight, Dumbbell, Layers, MoreVertical, Play } from 'lucide-react-native'
-import type { ActiveSessionExercise, Program } from '@lyftr/shared'
+import { BookOpen, ChevronRight, Dumbbell, Layers, Moon, MoreVertical, Play, Sun } from 'lucide-react-native'
+import type { Program, ProgramDay } from '@lyftr/shared'
+import {
+ activeSessionExercisesForDay, allExercises, dayLabel, isDayStartable, programExerciseCount, programSetCount,
+ sessionNameForDay, todaysDay,
+} from '@lyftr/shared'
import { ActionSheet, AppText, Card, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'
import { useTheme } from '../../theme/useTheme'
import { client, useWorkoutSession } from '../../lib/lyftr'
import { ExerciseImage } from '../workouts/ExerciseImage'
+import { DayPickerSheet, pickProgramDay } from './DayPickerSheet'
interface Props {
program: Program
@@ -25,38 +30,40 @@ const activeHref = '/workouts/active' as unknown as Href
// (the primary Start action), a kebab (⋮) ActionSheet (Edit / Delete — same as
// WorkoutCard), and a chevron. Delete routes through the shared ConfirmSheet.
export function ProgramCard({ program, onPress, onDeleted }: Props) {
- const { colors } = useTheme()
+ const { colors, accent } = useTheme()
const { session, startSession } = useWorkoutSession()
const [deleting, setDeleting] = useState(false)
const [confirming, setConfirming] = useState(false)
const [menuOpen, setMenuOpen] = useState(false)
+ const [dayPickFor, setDayPickFor] = useState<Program | null>(null)
- const exCount = program.exercises?.length || 0
- const totalSets = program.exercises?.reduce((s, e) => s + (e.sets?.length || 0), 0) || 0
+ const exCount = programExerciseCount(program)
+ const totalSets = programSetCount(program)
+ const dayCount = program.days?.length ?? 0
+ const today = todaysDay(program)
+ const thumbnailUrl = allExercises(program)[0]?.exercise?.image_url
+
+ const beginSession = (day: ProgramDay) => {
+ startSession(sessionNameForDay(program, day), activeSessionExercisesForDay(day), program.id, day.id)
+ setDayPickFor(null)
+ router.navigate(activeHref)
+ }
// 1:1 with web: an existing session takes priority (resume/discard on the start
- // screen); otherwise seed a session from the program's targets and open it.
+ // screen); otherwise seed a session from today's due day (or ask which day, for a
+ // multi-workout-day program) and open it.
const handleStart = () => {
// navigate (not push): programs → workouts is a cross-tab jump; push corrupts the
// native tab/back stack (the "can't get off the workout from a program" bug).
if (session) { router.navigate(startHref); return }
- const exercises: ActiveSessionExercise[] = (program.exercises || []).map((ex) => ({
- exercise_id: ex.exercise_id,
- exercise: ex.exercise,
- notes: ex.notes || '',
- rest_seconds: ex.rest_seconds,
- sets: (ex.sets || []).map((s) => ({
- set_number: s.set_number,
- target_reps: s.target_reps,
- target_weight: s.target_weight,
- actual_reps: s.target_reps,
- actual_weight: s.target_weight,
- completed: false,
- program_set_id: s.id,
- })),
- }))
- startSession(program.name, exercises, program.id)
- router.navigate(activeHref)
+ if (isDayStartable(today)) {
+ beginSession(today)
+ return
+ }
+ // Today's slot is a rest day (or unknown) — let them pick a day explicitly
+ // instead of silently starting nothing. A program with zero workout days has
+ // nothing to pick either, so fall back to the program detail page (web parity).
+ pickProgramDay(program, (_p, day) => beginSession(day), setDayPickFor, () => router.push(`/programs/${program.id}`))
}
const handleDelete = async () => {
@@ -74,7 +81,7 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {
return (
<Pressable accessibilityRole="button" onPress={onPress} className="active:scale-[0.99]">
<Card className="flex-row items-center gap-3 rounded-2xl">
- <ExerciseImage url={program.exercises?.[0]?.exercise?.image_url} fallbackIcon={BookOpen} />
+ <ExerciseImage url={thumbnailUrl} fallbackIcon={BookOpen} />
<View className="flex-1">
<AppText variant="subheading" numberOfLines={1}>{program.name}</AppText>
<AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">
@@ -82,16 +89,37 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {
</AppText>
{/* Metric chips with leading icons — shared taxonomy with WorkoutCard:
Dumbbell = exercises, Layers = sets. */}
- <View className="mt-0.5 flex-row items-center gap-x-2">
+ <View className="mt-0.5 flex-row items-center gap-x-2 flex-wrap">
<View className="flex-row items-center gap-1">
<Dumbbell size={12} color={colors.txMuted} />
- <AppText variant="caption" color="muted" numberOfLines={1}>{exCount} exercises</AppText>
+ <AppText variant="caption" color="muted" numberOfLines={1}>{exCount} exercise{exCount === 1 ? '' : 's'}</AppText>
</View>
<AppText variant="caption" color="muted">·</AppText>
<View className="flex-row items-center gap-1">
<Layers size={12} color={colors.txMuted} />
- <AppText variant="caption" color="muted" numberOfLines={1}>{totalSets} sets</AppText>
+ <AppText variant="caption" color="muted" numberOfLines={1}>{totalSets} set{totalSets === 1 ? '' : 's'}</AppText>
</View>
+ {dayCount > 1 && today ? (
+ <>
+ <AppText variant="caption" color="muted">·</AppText>
+ {today.is_rest_day ? (
+ <View className="flex-row items-center gap-1">
+ <Moon size={12} color={colors.txMuted} />
+ <AppText variant="caption" color="muted" numberOfLines={1}>Rest today</AppText>
+ </View>
+ ) : (
+ <View className="flex-row items-center gap-1">
+ {/* Sun, not Dumbbell — Dumbbell is already the "exercises" count icon
+ earlier on this same row; reusing it here would mean two different
+ things next to each other. Sun/Moon reads as a natural due/rest pair. */}
+ <Sun size={12} color={accent} />
+ <AppText variant="caption" numberOfLines={1} style={{ color: accent }}>
+ Today: {dayLabel(today, today.order_index)}
+ </AppText>
+ </View>
+ )}
+ </>
+ ) : null}
</View>
</View>
{/* Start is the card's primary action → a filled Play button on the row
@@ -121,11 +149,11 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {
onClose={() => setMenuOpen(false)}
header={
<View className="flex-row items-center gap-3">
- <ExerciseImage url={program.exercises?.[0]?.exercise?.image_url} size="hero" fallbackIcon={BookOpen} />
+ <ExerciseImage url={thumbnailUrl} size="hero" fallbackIcon={BookOpen} />
<View className="flex-1">
<AppText variant="subheading" numberOfLines={1}>{program.name}</AppText>
<AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">
- {exCount} exercises · {totalSets} sets
+ {exCount} exercise{exCount === 1 ? '' : 's'} · {totalSets} set{totalSets === 1 ? '' : 's'}
</AppText>
</View>
</View>
@@ -143,6 +171,8 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {
onConfirm={handleDelete}
onCancel={() => setConfirming(false)}
/>
+
+ <DayPickerSheet program={dayPickFor} onSelect={(_p, day) => beginSession(day)} onClose={() => setDayPickFor(null)} />
</Pressable>
)
}
diff --git a/mobile/src/components/programs/ProgramDaysEditor.test.tsx b/mobile/src/components/programs/ProgramDaysEditor.test.tsx
new file mode 100644
index 0000000..2361f5b
--- /dev/null
+++ b/mobile/src/components/programs/ProgramDaysEditor.test.tsx
@@ -0,0 +1,105 @@
+import { fireEvent, render, screen } from '@testing-library/react-native'
+
+// Same transitive-import stubs as DayPickerSheet.test.tsx (ui barrel → useTheme →
+// lib/lyftr → expo-router; storage adapter → AsyncStorage; Sheet → safe-area).
+jest.mock('expo-router', () => ({
+ router: { push: jest.fn(), navigate: jest.fn(), replace: jest.fn() },
+}))
+jest.mock('@react-native-async-storage/async-storage', () =>
+ require('@react-native-async-storage/async-storage/jest/async-storage-mock')
+)
+jest.mock('react-native-safe-area-context', () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),
+}))
+
+import { ProgramDaysEditor } from './ProgramDaysEditor'
+import type { DayDraft } from './types'
+
+const dayDraft = (overrides: Partial<DayDraft> = {}): DayDraft => ({
+ order_index: 0,
+ is_rest_day: false,
+ name: '',
+ exercises: [],
+ ...overrides,
+})
+
+const renderEditor = (days: DayDraft[], onChange = jest.fn()) => {
+ render(
+ <ProgramDaysEditor
+ days={days}
+ onChange={onChange}
+ pickerExercises={{}}
+ onCacheExercise={() => {}}
+ unit="lbs"
+ restSecondsDefault={90}
+ />
+ )
+ return onChange
+}
+
+describe('ProgramDaysEditor', () => {
+ it('renders the empty state when there are no days', () => {
+ renderEditor([])
+ expect(screen.getByText(/No days yet/)).toBeTruthy()
+ })
+
+ it('Add Workout Day appends a workout day with a reindexed order_index', () => {
+ const onChange = renderEditor([dayDraft({ name: 'Push' })])
+ fireEvent.press(screen.getByText('Add Workout Day'))
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next).toHaveLength(2)
+ expect(next[1]).toMatchObject({ order_index: 1, is_rest_day: false, exercises: [] })
+ })
+
+ it('Add Rest Day appends a rest day', () => {
+ const onChange = renderEditor([])
+ fireEvent.press(screen.getByText('Add Rest Day'))
+ expect(onChange.mock.calls[0][0]).toEqual([dayDraft({ is_rest_day: true })])
+ })
+
+ it('removing a day reindexes the survivors', () => {
+ const onChange = renderEditor([
+ dayDraft({ order_index: 0, name: 'A' }),
+ dayDraft({ order_index: 1, name: 'B' }),
+ dayDraft({ order_index: 2, name: 'C' }),
+ ])
+ fireEvent.press(screen.getAllByLabelText('Remove day')[1])
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next.map((d) => d.name)).toEqual(['A', 'C'])
+ expect(next.map((d) => d.order_index)).toEqual([0, 1])
+ })
+
+ it('move-down swaps a day with its neighbor and rewrites order_index', () => {
+ const onChange = renderEditor([
+ dayDraft({ order_index: 0, name: 'A' }),
+ dayDraft({ order_index: 1, name: 'B' }),
+ ])
+ fireEvent.press(screen.getByLabelText('Move day 1 down'))
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next.map((d) => d.name)).toEqual(['B', 'A'])
+ expect(next.map((d) => d.order_index)).toEqual([0, 1])
+ })
+
+ it('move-up on the first day is a no-op (disabled)', () => {
+ const onChange = renderEditor([dayDraft({ name: 'A' }), dayDraft({ order_index: 1, name: 'B' })])
+ fireEvent.press(screen.getByLabelText('Move day 1 up'))
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ it('toggling a workout day to rest CLEARS its exercises (a rest day never carries any)', () => {
+ const exercises = [{ exercise_id: 1, notes: '', rest_seconds: 90, sets: [] }]
+ const onChange = renderEditor([dayDraft({ exercises })])
+ fireEvent.press(screen.getByText('Rest'))
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next[0].is_rest_day).toBe(true)
+ expect(next[0].exercises).toEqual([])
+ })
+
+ it('renaming a day emits the patch without touching siblings', () => {
+ const onChange = renderEditor([dayDraft({ name: 'A' }), dayDraft({ order_index: 1, name: 'B' })])
+ fireEvent.changeText(screen.getAllByPlaceholderText(/^Day \d$/)[0], 'Push')
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next[0].name).toBe('Push')
+ expect(next[1].name).toBe('B')
+ })
+})
diff --git a/mobile/src/components/programs/ProgramDaysEditor.tsx b/mobile/src/components/programs/ProgramDaysEditor.tsx
new file mode 100644
index 0000000..577575e
--- /dev/null
+++ b/mobile/src/components/programs/ProgramDaysEditor.tsx
@@ -0,0 +1,164 @@
+import { useState } from 'react'
+import { Pressable, View } from 'react-native'
+import { ChevronDown, ChevronRight, ChevronUp, Dumbbell, Moon, Plus, Trash2 } from 'lucide-react-native'
+import type { Exercise } from '@lyftr/shared'
+import { AppText, Field, IconButton, SegmentedControl } from '../ui'
+import { useTheme } from '../../theme/useTheme'
+import { DayExercisesEditor } from './DayExercisesEditor'
+import type { DayDraft } from './types'
+
+interface Props {
+ days: DayDraft[]
+ onChange: (days: DayDraft[]) => void
+ pickerExercises: Record<number, Exercise>
+ onCacheExercise: (ex: Exercise) => void
+ unit: string
+ restSecondsDefault: number
+ inputAccessoryViewID?: string
+}
+
+const reindex = (days: DayDraft[]): DayDraft[] => days.map((d, i) => ({ ...d, order_index: i }))
+
+// The program's day/rest-day cycle, in order. Add/remove/reorder days here; each
+// workout day expands to the (unchanged) per-day exercise editor. Port of
+// web/components/programs/ProgramDaysEditor.tsx.
+export function ProgramDaysEditor({
+ days, onChange, pickerExercises, onCacheExercise, unit, restSecondsDefault, inputAccessoryViewID,
+}: Props) {
+ const { colors, accent } = useTheme()
+ const [expanded, setExpanded] = useState<number | null>(() => days.findIndex((d) => !d.is_rest_day))
+
+ const addDay = (isRest: boolean) => {
+ const next = reindex([...days, { order_index: days.length, is_rest_day: isRest, name: '', exercises: [] }])
+ onChange(next)
+ setExpanded(next.length - 1)
+ }
+
+ const removeDay = (idx: number) => {
+ onChange(reindex(days.filter((_, i) => i !== idx)))
+ setExpanded(null)
+ }
+
+ const moveDay = (idx: number, dir: -1 | 1) => {
+ const target = idx + dir
+ if (target < 0 || target >= days.length) return
+ const next = [...days]
+ ;[next[idx], next[target]] = [next[target], next[idx]]
+ onChange(reindex(next))
+ if (expanded === idx) setExpanded(target)
+ else if (expanded === target) setExpanded(idx)
+ }
+
+ const updateDay = (idx: number, patch: Partial<DayDraft>) => {
+ const next = [...days]
+ next[idx] = { ...next[idx], ...patch }
+ onChange(next)
+ }
+
+ const setDayType = (idx: number, isRest: boolean) => {
+ const day = days[idx]
+ if (day.is_rest_day === isRest) return
+ // Switching to rest clears its exercises — a rest day never carries any.
+ updateDay(idx, { is_rest_day: isRest, exercises: isRest ? [] : day.exercises })
+ }
+
+ return (
+ <View className="gap-3">
+ {days.length === 0 ? (
+ <AppText variant="caption" color="muted" className="py-4 text-center">
+ No days yet — add a workout or rest day below.
+ </AppText>
+ ) : null}
+
+ {days.map((day, idx) => {
+ const isOpen = expanded === idx
+ return (
+ <View
+ key={idx}
+ className={`overflow-hidden rounded-2xl border ${day.is_rest_day ? 'border-surface-border bg-surface-muted/20' : 'border-surface-border bg-surface-raised'}`}
+ >
+ <View className="flex-row items-center gap-2 p-3">
+ <View className="flex-shrink-0">
+ <Pressable accessibilityRole="button" accessibilityLabel={`Move day ${idx + 1} up`} onPress={() => moveDay(idx, -1)} disabled={idx === 0} hitSlop={4} className={idx === 0 ? 'opacity-20' : 'active:opacity-60'}>
+ <ChevronUp size={16} color={colors.txMuted} />
+ </Pressable>
+ <Pressable accessibilityRole="button" accessibilityLabel={`Move day ${idx + 1} down`} onPress={() => moveDay(idx, 1)} disabled={idx === days.length - 1} hitSlop={4} className={idx === days.length - 1 ? 'opacity-20' : 'active:opacity-60'}>
+ <ChevronDown size={16} color={colors.txMuted} />
+ </Pressable>
+ </View>
+
+ <View className={`h-8 w-8 items-center justify-center rounded-lg ${day.is_rest_day ? 'bg-surface-muted' : 'bg-brand-500/15'}`}>
+ {day.is_rest_day ? <Moon size={16} color={colors.txMuted} /> : <Dumbbell size={16} color={accent} />}
+ </View>
+
+ <View className="flex-1">
+ <Field
+ value={day.name}
+ onChangeText={(t) => updateDay(idx, { name: t })}
+ placeholder={day.is_rest_day ? `Rest Day ${idx + 1}` : `Day ${idx + 1}`}
+ />
+ </View>
+
+ <IconButton icon={Trash2} label="Remove day" variant="ghost" size="sm" onPress={() => removeDay(idx)} />
+ </View>
+
+ <View className="px-3 pb-3">
+ <SegmentedControl
+ size="sm"
+ options={[{ value: 'workout', label: 'Workout' }, { value: 'rest', label: 'Rest' }] as const}
+ value={day.is_rest_day ? 'rest' : 'workout'}
+ onChange={(v) => setDayType(idx, v === 'rest')}
+ />
+ </View>
+
+ {!day.is_rest_day && (
+ <Pressable
+ accessibilityRole="button"
+ onPress={() => setExpanded(isOpen ? null : idx)}
+ className="flex-row items-center justify-between border-t border-surface-border/60 px-3 py-2.5 active:bg-surface-muted/40"
+ >
+ <AppText variant="caption" color="muted">
+ {day.exercises.length} exercise{day.exercises.length === 1 ? '' : 's'}
+ </AppText>
+ {isOpen ? <ChevronDown size={14} color={colors.txMuted} /> : <ChevronRight size={14} color={colors.txMuted} />}
+ </Pressable>
+ )}
+
+ {!day.is_rest_day && isOpen && (
+ <View className="border-t border-surface-border/60 p-3">
+ <DayExercisesEditor
+ exercises={day.exercises}
+ onChange={(exercises) => updateDay(idx, { exercises })}
+ pickerExercises={pickerExercises}
+ onCacheExercise={onCacheExercise}
+ unit={unit}
+ restSecondsDefault={restSecondsDefault}
+ inputAccessoryViewID={inputAccessoryViewID}
+ />
+ </View>
+ )}
+ </View>
+ )
+ })}
+
+ <View className="flex-row gap-2">
+ <Pressable
+ accessibilityRole="button"
+ onPress={() => addDay(false)}
+ className="flex-1 flex-row items-center justify-center gap-1.5 rounded-lg border border-brand-500/20 bg-brand-500/10 py-2.5 active:scale-95"
+ >
+ <Plus size={14} color={accent} />
+ <AppText variant="label" style={{ color: accent }}>Add Workout Day</AppText>
+ </Pressable>
+ <Pressable
+ accessibilityRole="button"
+ onPress={() => addDay(true)}
+ className="flex-1 flex-row items-center justify-center gap-1.5 rounded-lg border border-surface-border bg-surface-muted py-2.5 active:scale-95"
+ >
+ <Moon size={14} color={colors.txMuted} />
+ <AppText variant="label" color="secondary">Add Rest Day</AppText>
+ </Pressable>
+ </View>
+ </View>
+ )
+}
diff --git a/mobile/src/components/programs/types.ts b/mobile/src/components/programs/types.ts
new file mode 100644
index 0000000..f803117
--- /dev/null
+++ b/mobile/src/components/programs/types.ts
@@ -0,0 +1,28 @@
+// Local draft shapes for the program day/exercise editors — mirror
+// CreateProgramDayReq/CreateProgramExerciseReq (backend/models/models.go) but keep
+// weights in the user's display unit until submit (displayToLbs at save time), same
+// convention as the pre-existing flat ProgramFormData. Port of
+// web/src/components/programs/types.ts — keep in sync.
+export interface DaySetDraft {
+ set_number: number
+ reps: number
+ weight: number
+}
+
+export interface DayExerciseDraft {
+ exercise_id: number
+ notes: string
+ rest_seconds: number
+ sets: DaySetDraft[]
+}
+
+export interface DayDraft {
+ // Existing program_days row id, round-tripped through updates so the server can
+ // match edited days by identity instead of position — reordering/removing days
+ // must not re-attribute logged workouts to the wrong day. Absent for new days.
+ id?: number
+ order_index: number
+ is_rest_day: boolean
+ name: string
+ exercises: DayExerciseDraft[]
+}
diff --git a/mobile/src/components/workouts/ProgramPicker.tsx b/mobile/src/components/workouts/ProgramPicker.tsx
index c663b74..bfc627b 100644
--- a/mobile/src/components/workouts/ProgramPicker.tsx
+++ b/mobile/src/components/workouts/ProgramPicker.tsx
@@ -1,25 +1,29 @@
import { useEffect, useMemo, useState } from 'react'
import { ActivityIndicator, FlatList, Modal, Pressable, View } from 'react-native'
-import { AlertCircle, BookOpen, ChevronRight, Dumbbell, X } from 'lucide-react-native'
-import type { Program } from '@lyftr/shared'
+import { AlertCircle, BookOpen, ChevronRight, Dumbbell, Moon, X } from 'lucide-react-native'
+import type { Program, ProgramDay } from '@lyftr/shared'
+import { workoutDays, dayLabel, todaysDay } from '@lyftr/shared'
import { AppText, EmptyState, Field, IconButton } from '../ui'
import { client } from '../../lib/lyftr'
import { useTheme } from '../../theme/useTheme'
+import { pickProgramDay } from '../programs/DayPickerSheet'
interface Props {
- onSelect: (program: Program) => void
+ onSelect: (program: Program, day: ProgramDay) => void
onClose: () => void
}
-// Port of web/components/ProgramPicker.tsx: dimmed overlay + centered card. One
-// directed addition over web: a search field — client-side name filter, since the
-// program list is a single un-paginated fetch.
+// Port of web/components/ProgramPicker.tsx: dimmed overlay + centered card, with the
+// same two-step pick-a-program-then-pick-a-day flow (a single-workout-day program
+// skips the day step, same as web). One directed addition over web: a search field —
+// client-side name filter, since the program list is a single un-paginated fetch.
export function ProgramPicker({ onSelect, onClose }: Props) {
const { colors, brand, accent, isDark } = useTheme()
const [programs, setPrograms] = useState<Program[]>([])
const [query, setQuery] = useState('')
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
+ const [dayPickFor, setDayPickFor] = useState<Program | null>(null)
useEffect(() => {
client.programAPI.list()
@@ -33,75 +37,132 @@ export function ProgramPicker({ onSelect, onClose }: Props) {
return q ? programs.filter((p) => p.name.toLowerCase().includes(q)) : programs
}, [programs, query])
+ // Decision logic (auto-select the lone day vs. open the day list) lives once in
+ // DayPickerSheet.tsx's pickProgramDay — reused here instead of re-branching it.
+ const pickProgram = (p: Program) => pickProgramDay(p, onSelect, setDayPickFor)
+
+ const title = dayPickFor ? dayPickFor.name : 'Load from Program'
+ const subtitle = dayPickFor ? 'Pick a day to pre-fill exercises' : 'Pick a program to pre-fill exercises'
+
return (
- <Modal visible transparent animationType="fade" onRequestClose={onClose}>
+ <Modal visible transparent animationType="fade" onRequestClose={dayPickFor ? () => setDayPickFor(null) : onClose}>
<View className="flex-1 items-center justify-center bg-black/60 px-4">
{/* maxHeight is layout math NativeWind percentages don't cover reliably — inline. */}
<View className="w-full rounded-2xl border border-surface-border bg-surface-base" style={{ maxHeight: '80%' }}>
<View className="flex-row items-center justify-between border-b border-surface-border px-4 py-3">
- <View>
- <AppText variant="heading">Load from Program</AppText>
- <AppText variant="caption" color="muted" className="mt-0.5">Pick a program to pre-fill exercises</AppText>
+ <View className="flex-1 pr-2">
+ <AppText variant="heading" numberOfLines={1}>{title}</AppText>
+ <AppText variant="caption" color="muted" className="mt-0.5">{subtitle}</AppText>
</View>
- <IconButton icon={X} label="Close program picker" variant="ghost" size="md" onPress={onClose} />
- </View>
-
- <View className="border-b border-surface-border px-4 py-3">
- <Field
- value={query}
- onChangeText={setQuery}
- placeholder="Search programs…"
- autoCapitalize="none"
- autoCorrect={false}
- returnKeyType="search"
+ <IconButton
+ icon={X}
+ label="Close program picker"
+ variant="ghost"
+ size="md"
+ onPress={dayPickFor ? () => setDayPickFor(null) : onClose}
/>
</View>
- {loading ? (
- <View className="flex-row items-center justify-center gap-2 p-8">
- <ActivityIndicator color={accent} />
- <AppText variant="body" color="muted">Loading programs…</AppText>
- </View>
- ) : error ? (
- <View className="flex-row items-center gap-2 p-4">
- <AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />
- <AppText variant="body" color="error">{error}</AppText>
- </View>
- ) : shown.length === 0 ? (
- <EmptyState
- compact
- icon={BookOpen}
- title={query ? 'No matching programs' : 'No programs yet'}
- subtitle={query ? 'Try a different search' : 'Create a program first'}
- />
- ) : (
+ {dayPickFor ? (
<FlatList
- data={shown}
- keyExtractor={(p) => String(p.id)}
+ data={workoutDays(dayPickFor)}
+ keyExtractor={(d, i) => String(d.id ?? i)}
keyboardShouldPersistTaps="handled"
- renderItem={({ item }) => (
- <Pressable
- accessibilityRole="button"
- onPress={() => onSelect(item)}
- className="flex-row items-center gap-3 border-b border-surface-border px-4 py-3 active:bg-surface-muted"
- >
- <View className="h-9 w-9 items-center justify-center rounded-lg border border-brand-500/20 bg-brand-500/10">
- <BookOpen size={16} color={accent} />
- </View>
- <View className="flex-1">
- <AppText variant="subheading" numberOfLines={1}>{item.name}</AppText>
- <View className="mt-0.5 flex-row items-center gap-1.5">
- <Dumbbell size={12} color={colors.txMuted} />
- <AppText variant="caption" color="muted" numberOfLines={1}>
- {item.exercises?.length || 0} exercises{item.notes ? ` • ${item.notes}` : ''}
+ renderItem={({ item: day }) => {
+ const isToday = todaysDay(dayPickFor)?.id === day.id
+ return (
+ <Pressable
+ accessibilityRole="button"
+ onPress={() => onSelect(dayPickFor, day)}
+ className="flex-row items-center gap-3 border-b border-surface-border px-4 py-3 active:bg-surface-muted"
+ >
+ <View className="h-9 w-9 items-center justify-center rounded-lg border border-brand-500/20 bg-brand-500/10">
+ <Dumbbell size={16} color={accent} />
+ </View>
+ <View className="flex-1">
+ <View className="flex-row items-center gap-1.5">
+ <AppText variant="subheading" numberOfLines={1}>{dayLabel(day, day.order_index)}</AppText>
+ {isToday ? (
+ <View className="rounded-full bg-brand-500/15 px-1.5 py-0.5">
+ <AppText variant="caption" style={{ color: accent }}>TODAY</AppText>
+ </View>
+ ) : null}
+ </View>
+ <AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">
+ {(day.exercises ?? []).length} exercise{(day.exercises ?? []).length === 1 ? '' : 's'}
</AppText>
</View>
- </View>
- {/* Web reveals the chevron on hover; no hover on touch → always shown. */}
- <ChevronRight size={16} color={colors.txMuted} />
- </Pressable>
- )}
+ <ChevronRight size={16} color={colors.txMuted} />
+ </Pressable>
+ )
+ }}
/>
+ ) : (
+ <>
+ <View className="border-b border-surface-border px-4 py-3">
+ <Field
+ value={query}
+ onChangeText={setQuery}
+ placeholder="Search programs…"
+ autoCapitalize="none"
+ autoCorrect={false}
+ returnKeyType="search"
+ />
+ </View>
+
+ {loading ? (
+ <View className="flex-row items-center justify-center gap-2 p-8">
+ <ActivityIndicator color={accent} />
+ <AppText variant="body" color="muted">Loading programs…</AppText>
+ </View>
+ ) : error ? (
+ <View className="flex-row items-center gap-2 p-4">
+ <AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />
+ <AppText variant="body" color="error">{error}</AppText>
+ </View>
+ ) : shown.length === 0 ? (
+ <EmptyState
+ compact
+ icon={BookOpen}
+ title={query ? 'No matching programs' : 'No programs yet'}
+ subtitle={query ? 'Try a different search' : 'Create a program first'}
+ />
+ ) : (
+ <FlatList
+ data={shown}
+ keyExtractor={(p) => String(p.id)}
+ keyboardShouldPersistTaps="handled"
+ renderItem={({ item }) => {
+ const days = workoutDays(item)
+ return (
+ <Pressable
+ accessibilityRole="button"
+ disabled={days.length === 0}
+ onPress={() => pickProgram(item)}
+ className={`flex-row items-center gap-3 border-b border-surface-border px-4 py-3 active:bg-surface-muted ${days.length === 0 ? 'opacity-40' : ''}`}
+ >
+ <View className="h-9 w-9 items-center justify-center rounded-lg border border-brand-500/20 bg-brand-500/10">
+ <BookOpen size={16} color={accent} />
+ </View>
+ <View className="flex-1">
+ <AppText variant="subheading" numberOfLines={1}>{item.name}</AppText>
+ <View className="mt-0.5 flex-row items-center gap-1.5">
+ <Dumbbell size={12} color={colors.txMuted} />
+ <AppText variant="caption" color="muted" numberOfLines={1}>
+ {days.length === 0 ? 'No exercises yet' : `${days.length} workout day${days.length === 1 ? '' : 's'}`}
+ </AppText>
+ {(item.days ?? []).some((d) => d.is_rest_day) ? (
+ <Moon size={12} color={colors.txMuted} />
+ ) : null}
+ </View>
+ </View>
+ <ChevronRight size={16} color={colors.txMuted} />
+ </Pressable>
+ )
+ }}
+ />
+ )}
+ </>
)}
</View>
</View>
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 1e927f3..06a5765 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -8,6 +8,7 @@ export * from './client'
export * from './utils/serverUrl'
export * from './utils/weight'
export * from './utils/dateUtils'
+export * from './utils/programUtils'
export * from './stores/auth'
export * from './stores/server'
export * from './stores/settings'
diff --git a/packages/shared/src/stores/workoutSession.test.ts b/packages/shared/src/stores/workoutSession.test.ts
index 3e6d93b..875027a 100644
--- a/packages/shared/src/stores/workoutSession.test.ts
+++ b/packages/shared/src/stores/workoutSession.test.ts
@@ -136,9 +136,11 @@ describe('workoutSession buildPayload — auto-progression (#40)', () => {
{ set_number: 2, target_reps: 5, target_weight: 100, actual_reps: 6, actual_weight: 100, completed: true, program_set_id: 12 },
],
},
- ] as any, 7)
+ ] as any, 7, 3)
const payload = store().buildPayload()
expect(payload.program_id).toBe(7)
+ // WHICH cycle day this session was — the server's due-day tracker keys off it.
+ expect(payload.program_day_id).toBe(3)
expect(payload.exercises[0].sets[0].program_set_id).toBe(11)
expect(payload.exercises[0].sets[1].program_set_id).toBe(12)
// logged actuals are what the backend compares against the target
@@ -154,6 +156,7 @@ describe('workoutSession buildPayload — auto-progression (#40)', () => {
] as any)
const payload = store().buildPayload()
expect(payload.program_id).toBeNull()
+ expect(payload.program_day_id).toBeNull()
expect(payload.exercises[0].sets[0].program_set_id).toBeNull()
})
diff --git a/packages/shared/src/stores/workoutSession.ts b/packages/shared/src/stores/workoutSession.ts
index 715d483..d3f3ab0 100644
--- a/packages/shared/src/stores/workoutSession.ts
+++ b/packages/shared/src/stores/workoutSession.ts
@@ -25,7 +25,7 @@ export interface WorkoutSessionStore {
// hydrated: they are ephemeral by design.
isHydrated: boolean
hydrate: () => Promise<void>
- startSession: (name: string, exercises: types.ActiveSessionExercise[], programId?: number) => void
+ startSession: (name: string, exercises: types.ActiveSessionExercise[], programId?: number, programDayId?: number) => void
restoreSession: (session: types.ActiveSession) => void
updateSet: (exIdx: number, setIdx: number, field: 'actual_reps' | 'actual_weight', val: number) => void
completeSet: (exIdx: number, setIdx: number) => void
@@ -146,12 +146,13 @@ export function createWorkoutSession(storage: StorageAdapter) {
set({ gymPhase, gymExIdx, gymSetIdx })
},
- startSession: (name, exercises, programId) => {
+ startSession: (name, exercises, programId, programDayId) => {
const session: types.ActiveSession = {
name,
started_at: new Date().toISOString(),
exercises,
program_id: programId,
+ program_day_id: programDayId,
}
saveLocal(session)
set({ session })
@@ -278,6 +279,7 @@ export function createWorkoutSession(storage: StorageAdapter) {
duration: durationSec,
started_at: session.started_at,
program_id: session.program_id ?? null, // lets the backend auto-progress the routine (#40)
+ program_day_id: session.program_day_id ?? null, // which cycle day this was — drives the due-day tracker
exercises: session.exercises.map(ex => ({
exercise_id: ex.exercise_id,
notes: ex.notes,
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index bb81f7e..f4aeeff 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -170,6 +170,7 @@ export interface ProgramSet {
export interface ProgramExercise {
id?: number
+ program_day_id?: number
exercise_id: number
order_index?: number
notes?: string
@@ -178,12 +179,29 @@ export interface ProgramExercise {
sets: ProgramSet[]
}
+// One slot in a program's repeating cycle: a workout day (its own ordered
+// exercises/sets) or a rest day (exercises always empty). Days repeat in
+// order_index order once the sequence is exhausted — NOT locked to a calendar week
+// (a 6-day cycle repeats every 6 days regardless of which weekday it lands on).
+export interface ProgramDay {
+ id?: number
+ program_id?: number
+ order_index: number
+ is_rest_day: boolean
+ name?: string
+ exercises: ProgramExercise[]
+}
+
export interface Program {
id: number
name: string
notes?: string
created_at: string
- exercises: ProgramExercise[]
+ days: ProgramDay[]
+ // Which entry of `days` is due today — computed server-side from WHICH day the
+ // most recent program workout was logged against: the next workout day after it
+ // in cycle order (rest days are never due; wraps to the first workout day).
+ current_day_index: number
}
export interface ActiveSessionSet {
@@ -208,6 +226,10 @@ export interface ActiveSessionExercise {
export interface ActiveSession {
program_id?: number
+ // WHICH day of the program's cycle this session was started under — persisted on
+ // the created workout so the server's due-day tracker follows what was actually
+ // logged (not a blind count). Absent for freestyle sessions.
+ program_day_id?: number
name: string
started_at: string
exercises: ActiveSessionExercise[]
diff --git a/packages/shared/src/utils/programUtils.test.ts b/packages/shared/src/utils/programUtils.test.ts
new file mode 100644
index 0000000..34c8a4d
--- /dev/null
+++ b/packages/shared/src/utils/programUtils.test.ts
@@ -0,0 +1,172 @@
+import {
+ activeSessionExercisesForDay, allExercises, dayLabel, hasWorkoutExercises, isDayStartable, programExerciseCount,
+ programSetCount, sessionNameForDay, todaysDay, workoutDays,
+} from './programUtils'
+import type { Program, ProgramDay } from '../types'
+
+const day = (overrides: Partial<ProgramDay> = {}): ProgramDay => ({
+ id: 1,
+ order_index: 0,
+ is_rest_day: false,
+ name: '',
+ exercises: [],
+ ...overrides,
+})
+
+const program = (days: ProgramDay[], currentDayIndex = 0): Program => ({
+ id: 1,
+ name: 'PPL',
+ created_at: '2026-01-01T00:00:00Z',
+ days,
+ current_day_index: currentDayIndex,
+})
+
+describe('workoutDays', () => {
+ it('filters rest days out and preserves order', () => {
+ const p = program([
+ day({ id: 1, order_index: 0 }),
+ day({ id: 2, order_index: 1, is_rest_day: true }),
+ day({ id: 3, order_index: 2 }),
+ ])
+ expect(workoutDays(p).map((d) => d.id)).toEqual([1, 3])
+ })
+
+ it('tolerates a program with undefined days', () => {
+ expect(workoutDays({ ...program([]), days: undefined as any })).toEqual([])
+ })
+})
+
+describe('todaysDay', () => {
+ it('returns the entry at current_day_index', () => {
+ const p = program([day({ id: 1, order_index: 0 }), day({ id: 2, order_index: 1 })], 1)
+ expect(todaysDay(p)?.id).toBe(2)
+ })
+
+ it('is undefined for a program with no days', () => {
+ expect(todaysDay(program([]))).toBeUndefined()
+ })
+})
+
+describe('dayLabel', () => {
+ it('prefers the trimmed custom name', () => {
+ expect(dayLabel(day({ name: ' Push Day ' }), 0)).toBe('Push Day')
+ })
+
+ it('falls back to Rest Day / Day N+1 — idx must be order_index, not a filtered loop index', () => {
+ expect(dayLabel(day({ is_rest_day: true }), 3)).toBe('Rest Day')
+ // A workout day at cycle position 2 must label "Day 3" even when it's e.g. the
+ // second entry of a rest-filtered list (the classic loop-index bug).
+ expect(dayLabel(day({ order_index: 2 }), 2)).toBe('Day 3')
+ })
+
+ it('whitespace-only names fall back too', () => {
+ expect(dayLabel(day({ name: ' ' }), 0)).toBe('Day 1')
+ })
+})
+
+describe('counts + flattening', () => {
+ const ex = (id: number, sets: number) => ({
+ exercise_id: id,
+ exercise: { id, name: `E${id}` } as any,
+ sets: Array.from({ length: sets }, (_, i) => ({ set_number: i + 1, target_reps: 5, target_weight: 100 })),
+ })
+ const p = program([
+ day({ id: 1, order_index: 0, exercises: [ex(1, 2), ex(2, 3)] as any }),
+ day({ id: 2, order_index: 1, is_rest_day: true }),
+ day({ id: 3, order_index: 2, exercises: [ex(3, 1)] as any }),
+ ])
+
+ it('programExerciseCount sums across all days', () => {
+ expect(programExerciseCount(p)).toBe(3)
+ })
+
+ it('programSetCount sums sets across all days', () => {
+ expect(programSetCount(p)).toBe(6)
+ })
+
+ it('allExercises flattens in day order (so a suggestion is visible whatever day is selected)', () => {
+ expect(allExercises(p).map((e) => e.exercise_id)).toEqual([1, 2, 3])
+ })
+})
+
+describe('activeSessionExercisesForDay', () => {
+ it('seeds actuals from targets and links each set to its program_set_id (#40)', () => {
+ const d = day({
+ exercises: [{
+ exercise_id: 9,
+ exercise: { id: 9, name: 'Bench' } as any,
+ notes: 'slow eccentric',
+ rest_seconds: 120,
+ sets: [{ id: 41, set_number: 1, target_reps: 5, target_weight: 135 }],
+ }] as any,
+ })
+ const [ex] = activeSessionExercisesForDay(d)
+ expect(ex.exercise_id).toBe(9)
+ expect(ex.notes).toBe('slow eccentric')
+ expect(ex.rest_seconds).toBe(120)
+ expect(ex.sets[0]).toEqual({
+ set_number: 1,
+ target_reps: 5,
+ target_weight: 135,
+ actual_reps: 5,
+ actual_weight: 135,
+ completed: false,
+ program_set_id: 41,
+ })
+ })
+
+ it('a rest/empty day yields no exercises', () => {
+ expect(activeSessionExercisesForDay(day({ is_rest_day: true }))).toEqual([])
+ expect(activeSessionExercisesForDay({ ...day(), exercises: undefined as any })).toEqual([])
+ })
+})
+
+describe('isDayStartable', () => {
+ const withExercise = day({ exercises: [{ exercise_id: 1 }] as any })
+
+ it('true only for a workout day with at least one exercise', () => {
+ expect(isDayStartable(withExercise)).toBe(true)
+ })
+
+ it('false for a rest day, even with exercises somehow present', () => {
+ expect(isDayStartable({ ...withExercise, is_rest_day: true })).toBe(false)
+ })
+
+ it('false for a workout day with no exercises', () => {
+ expect(isDayStartable(day({ exercises: [] }))).toBe(false)
+ })
+
+ it('false for undefined (as todaysDay() returns for a dayless program)', () => {
+ expect(isDayStartable(undefined)).toBe(false)
+ })
+})
+
+describe('sessionNameForDay', () => {
+ it('is just the program name for a single-day program', () => {
+ const p = program([day({ order_index: 0 })])
+ expect(sessionNameForDay(p, p.days![0])).toBe('PPL')
+ })
+
+ it('appends the day label once a program has more than one day', () => {
+ const d = day({ order_index: 1, name: 'Pull A' })
+ const p = program([day({ order_index: 0 }), d])
+ expect(sessionNameForDay(p, d)).toBe('PPL — Pull A')
+ })
+})
+
+describe('hasWorkoutExercises', () => {
+ it('true when some workout day has an exercise', () => {
+ expect(hasWorkoutExercises([
+ day({ exercises: [] }),
+ day({ exercises: [{ exercise_id: 1 }] as any }),
+ ])).toBe(true)
+ })
+
+ it('false when every day is empty or a rest day', () => {
+ expect(hasWorkoutExercises([day({ exercises: [] }), day({ is_rest_day: true, exercises: [{ exercise_id: 1 }] as any })])).toBe(false)
+ })
+
+ it('false for an empty list', () => {
+ expect(hasWorkoutExercises([])).toBe(false)
+ })
+})
diff --git a/packages/shared/src/utils/programUtils.ts b/packages/shared/src/utils/programUtils.ts
new file mode 100644
index 0000000..11582f5
--- /dev/null
+++ b/packages/shared/src/utils/programUtils.ts
@@ -0,0 +1,69 @@
+// Program day/cycle helpers. Ported verbatim from web/src/utils/programUtils.ts so
+// web and mobile share one implementation of the multi-day-program logic.
+import type { ActiveSessionExercise, Program, ProgramDay, ProgramExercise } from '../types'
+
+// Workout days only — rest days carry no exercises and can't be "started" or
+// "loaded". Used everywhere a picker needs to offer a day to load/start from.
+export const workoutDays = (program: Program): ProgramDay[] =>
+ (program.days ?? []).filter((d) => !d.is_rest_day)
+
+// The Day due today per the cycle, computed server-side as
+// Program.current_day_index: the next workout day after the most recently logged
+// one (rest days are never due). Undefined for a program with no days yet.
+export const todaysDay = (program: Program): ProgramDay | undefined =>
+ (program.days ?? [])[program.current_day_index]
+
+export const dayLabel = (day: ProgramDay, idx: number): string =>
+ day.name?.trim() || (day.is_rest_day ? 'Rest Day' : `Day ${idx + 1}`)
+
+// A day is startable/loadable only if it's a workout day that actually has
+// exercises — a rest day or an empty day is never "due" and can't seed a session.
+// Takes `undefined` directly (as `todaysDay()` returns) so callers don't need a
+// separate null-guard before calling this.
+export const isDayStartable = (day: ProgramDay | undefined): day is ProgramDay =>
+ !!day && !day.is_rest_day && (day.exercises ?? []).length > 0
+
+// Display name for a session started from a specific program day: the plain
+// program name for a single-day program (nothing to disambiguate), or
+// "Program — Day Label" once there's more than one day to distinguish between.
+export const sessionNameForDay = (program: Program, day: ProgramDay): string =>
+ (program.days?.length ?? 0) > 1 ? `${program.name} — ${dayLabel(day, day.order_index)}` : program.name
+
+// Flattened, so the auto-progression review banner surfaces a suggestion no matter
+// which day it landed on (the user may not have that day selected/expanded when it
+// lands).
+export const allExercises = (program: Program): ProgramExercise[] =>
+ (program.days ?? []).flatMap((d) => d.exercises ?? [])
+
+// Whether any day in a list has at least one exercise on a workout (non-rest)
+// day — the "is there anything to actually run" check the create/edit-program
+// forms use before letting the user submit. Structural rather than typed to
+// ProgramDay so it also accepts the day/exercise editors' local draft shape.
+export const hasWorkoutExercises = (days: { is_rest_day: boolean; exercises: unknown[] }[]): boolean =>
+ days.some((d) => !d.is_rest_day && d.exercises.length > 0)
+
+export const programExerciseCount = (program: Program): number => allExercises(program).length
+
+export const programSetCount = (program: Program): number =>
+ allExercises(program).reduce((s, e) => s + (e.sets ?? []).length, 0)
+
+// Builds a live ActiveSession's exercises from one program Day, linking each set
+// back to its ProgramSet id so finishing the workout can auto-progress that
+// specific target (#40).
+export function activeSessionExercisesForDay(day: ProgramDay): ActiveSessionExercise[] {
+ return (day.exercises ?? []).map((ex) => ({
+ exercise_id: ex.exercise_id,
+ exercise: ex.exercise,
+ notes: ex.notes || '',
+ rest_seconds: ex.rest_seconds,
+ sets: (ex.sets ?? []).map((s) => ({
+ set_number: s.set_number,
+ target_reps: s.target_reps,
+ target_weight: s.target_weight,
+ actual_reps: s.target_reps,
+ actual_weight: s.target_weight,
+ completed: false,
+ program_set_id: s.id,
+ })),
+ }))
+}
diff --git a/web/e2e/programs.spec.ts b/web/e2e/programs.spec.ts
index 5d8fa7b..c852bec 100644
--- a/web/e2e/programs.spec.ts
+++ b/web/e2e/programs.spec.ts
@@ -21,7 +21,7 @@ test.describe('Programs', () => {
p => p.name === SEED_PROGRAM_NAME || p.name === SEED_SEARCH_PROGRAM_NAME)
const createProgram = async (name: string, notes: string): Promise<number> => {
- const r = await request.post(`${API}/programs`, { headers, data: { name, notes, exercises: [] } })
+ const r = await request.post(`${API}/programs`, { headers, data: { name, notes, days: [] } })
const rb = await r.json()
if (!rb.data?.id) throw new Error(`Failed to create seed program "${name}": ${JSON.stringify(rb)}`)
return rb.data.id
@@ -69,7 +69,8 @@ test.describe('Programs', () => {
await page.getByPlaceholder(/push pull legs, upper lower/i).fill(E2E_PROGRAM_NAME)
await page.getByPlaceholder(/description or goals/i).fill('Test description')
- // Add exercise
+ // Programs are day-nested now — add a workout day before its exercise editor appears.
+ await page.getByRole('button', { name: /add workout day/i }).click()
await page.getByRole('button', { name: /add exercise/i }).click()
await expect(page.getByPlaceholder(/search name/i)).toBeVisible()
await page.getByPlaceholder(/search name/i).fill('squat')
@@ -128,6 +129,7 @@ test.describe('Programs', () => {
test('target weight unit shown correctly in program add form', async ({ page }) => {
await page.goto('/programs/new')
+ await page.getByRole('button', { name: /add workout day/i }).click()
await page.getByRole('button', { name: /add exercise/i }).click()
await page.getByPlaceholder(/search name/i).fill('deadlift')
await page.getByText(/deadlift/i).first().click()
diff --git a/web/e2e/workouts.spec.ts b/web/e2e/workouts.spec.ts
index 248c3aa..7d4c4e3 100644
--- a/web/e2e/workouts.spec.ts
+++ b/web/e2e/workouts.spec.ts
@@ -188,10 +188,13 @@ test.describe('Workouts', () => {
// Routine with one working set targeting 5 × 100.
const created = await request.post(`${API}/programs`, {
headers,
- data: { name: PROG_PROGRESSION_NAME, notes: '', exercises: [{ exercise_id: exId, notes: '', rest_seconds: 90, sets: [{ set_number: 1, target_reps: 5, target_weight: 100 }] }] },
+ data: {
+ name: PROG_PROGRESSION_NAME, notes: '',
+ days: [{ order_index: 0, is_rest_day: false, name: '', exercises: [{ exercise_id: exId, notes: '', rest_seconds: 90, sets: [{ set_number: 1, target_reps: 5, target_weight: 100 }] }] }],
+ },
})
const progId = (await created.json()).data.id
- const psid = (await (await request.get(`${API}/programs/${progId}`, { headers })).json()).data.exercises[0].sets[0].id
+ const psid = (await (await request.get(`${API}/programs/${progId}`, { headers })).json()).data.days[0].exercises[0].sets[0].id
// Seed a list-mode session where the logged set beat the target (105 > 100).
const session = {
@@ -220,8 +223,8 @@ test.describe('Workouts', () => {
// Staged, NOT applied — the routine target is still 100 until approved.
const staged = await (await request.get(`${API}/programs/${progId}`, { headers })).json()
- expect(staged.data.exercises[0].sets[0].target_weight).toBe(100)
- expect(staged.data.exercises[0].sets[0].suggested_weight).toBe(105)
+ expect(staged.data.days[0].exercises[0].sets[0].target_weight).toBe(100)
+ expect(staged.data.days[0].exercises[0].sets[0].suggested_weight).toBe(105)
// Approve on the routine → target becomes 105, suggestion cleared.
await page.goto(`/programs/${progId}`)
@@ -230,8 +233,8 @@ test.describe('Workouts', () => {
await expect(page.getByText('New targets from your last workout')).toHaveCount(0, { timeout: 5000 })
const after = await (await request.get(`${API}/programs/${progId}`, { headers })).json()
- expect(after.data.exercises[0].sets[0].target_weight).toBe(105)
- expect(after.data.exercises[0].sets[0].suggested_weight ?? null).toBeNull()
+ expect(after.data.days[0].exercises[0].sets[0].target_weight).toBe(105)
+ expect(after.data.days[0].exercises[0].sets[0].suggested_weight ?? null).toBeNull()
// Cleanup: the workout we just logged + the routine.
const wl = await (await request.get(`${API}/workouts?limit=20`, { headers })).json()
diff --git a/web/src/components/AddProgramModal.tsx b/web/src/components/AddProgramModal.tsx
deleted file mode 100644
index 694f75b..0000000
--- a/web/src/components/AddProgramModal.tsx
+++ /dev/null
@@ -1,317 +0,0 @@
-import { useState } from 'react'
-import { createPortal } from 'react-dom'
-import { Plus, X, Trash2, AlertCircle, BookOpen, FileText, Zap, Target } from 'lucide-react'
-import { programAPI } from '../services/api'
-import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'
-import WeightInput from './WeightInput'
-import ExercisePicker from './ExercisePicker'
-import * as types from '../types'
-
-interface ProgramFormData {
- name: string
- notes: string
- exercises: {
- exercise_id: number
- notes: string
- sets: { set_number: number; target_reps: number; target_weight: number }[]
- }[]
-}
-
-interface Props {
- isOpen: boolean
- onClose: () => void
- onSuccess: () => void
-}
-
-export default function AddProgramModal({ isOpen, onClose, onSuccess }: Props) {
- const { settings } = useSettingsStore()
- const wUnit = weightShort(settings.weight_unit)
- const handleClose = () => { setError(''); onClose() }
- const [showPicker, setShowPicker] = useState(false)
- const [loading, setLoading] = useState(false)
- const [error, setError] = useState('')
- const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})
- const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', exercises: [] })
-
- const addExercise = (exercise: types.Exercise) => {
- setPickerExercises(prev => ({ ...prev, [exercise.id]: exercise }))
- setFormData(prev => ({
- ...prev,
- exercises: [...prev.exercises, {
- exercise_id: exercise.id,
- notes: '',
- sets: [{ set_number: 1, target_reps: 0, target_weight: 0 }],
- }],
- }))
- setShowPicker(false)
- setError('')
- }
-
- const removeExercise = (index: number) => {
- setFormData(prev => ({ ...prev, exercises: prev.exercises.filter((_, i) => i !== index) }))
- }
-
- const addSet = (exIdx: number) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- const count = exercises[exIdx].sets.length + 1
- exercises[exIdx].sets.push({ set_number: count, target_reps: 0, target_weight: 0 })
- return { ...prev, exercises }
- })
- }
-
- const removeSet = (exIdx: number, setIdx: number) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- exercises[exIdx].sets = exercises[exIdx].sets.filter((_, i) => i !== setIdx)
- return { ...prev, exercises }
- })
- }
-
- const updateSet = (exIdx: number, setIdx: number, field: string, value: any) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- ;(exercises[exIdx].sets[setIdx] as any)[field] = Number(value) || 0
- return { ...prev, exercises }
- })
- }
-
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault()
- if (!formData.name.trim()) { setError('Program name required'); return }
- if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }
-
- setLoading(true)
- try {
- const payload = {
- ...formData,
- exercises: formData.exercises.map(ex => ({
- ...ex,
- sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),
- })),
- }
- await programAPI.create(payload)
- setFormData({ name: '', notes: '', exercises: [] })
- setPickerExercises({})
- onSuccess()
- onClose()
- } catch (err: any) {
- setError(err.response?.data?.error || 'Failed to create program')
- } finally {
- setLoading(false)
- }
- }
-
- if (!isOpen) return null
-
- const selectedIds = formData.exercises.map(e => e.exercise_id)
- const totalSets = formData.exercises.reduce((sum, ex) => sum + ex.sets.length, 0)
-
- return createPortal((
- <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
- <div className="bg-surface-base border border-surface-border rounded-2xl w-full max-h-[90vh] sm:max-w-2xl overflow-y-auto">
- <div className="sticky top-0 border-b border-surface-border bg-surface-base px-5 py-4 flex items-center justify-between">
- <div>
- <h2 className="font-display font-bold text-xl text-tx-primary">New Program</h2>
- <p className="text-xs text-tx-muted mt-1">{formData.exercises.length} exercises • {totalSets} sets</p>
- </div>
- <button onClick={handleClose} className="p-1 hover:bg-surface-muted rounded-lg transition-colors">
- <X className="w-5 h-5 text-tx-muted" />
- </button>
- </div>
-
- <form onSubmit={handleSubmit} className="p-5 space-y-6">
- {error && (
- <div className="alert-error">
- <AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{error}</span>
- </div>
- )}
-
- <div>
- <div className="flex items-center gap-2 mb-2">
- <BookOpen className="w-4 h-4 text-brand-500" />
- <label className="label">Program Name</label>
- <span className="text-xs text-tx-muted">(required)</span>
- </div>
- <input
- type="text"
- value={formData.name}
- onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))}
- placeholder="e.g., Push Pull Legs, Upper Lower"
- className="input mt-1"
- />
- </div>
-
- <div>
- <div className="flex items-center gap-2 mb-2">
- <FileText className="w-4 h-4 text-brand-500" />
- <label className="label">Notes</label>
- </div>
- <textarea
- value={formData.notes}
- onChange={e => setFormData(prev => ({ ...prev, notes: e.target.value }))}
- placeholder="Program description or goals…"
- className="input mt-1 min-h-16 resize-none"
- />
- </div>
-
- {formData.exercises.length > 0 && (
- <div className="grid grid-cols-2 gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg">
- <div className="text-center">
- <div className="flex items-center justify-center gap-1 mb-1">
- <Zap className="w-3.5 h-3.5 text-brand-500" />
- </div>
- <div className="text-sm font-bold text-brand-500">{formData.exercises.length}</div>
- <div className="text-xs text-tx-muted">Exercises</div>
- </div>
- <div className="text-center">
- <div className="flex items-center justify-center gap-1 mb-1">
- <Target className="w-3.5 h-3.5 text-brand-500" />
- </div>
- <div className="text-sm font-bold text-brand-500">{totalSets}</div>
- <div className="text-xs text-tx-muted">Target Sets</div>
- </div>
- </div>
- )}
-
- <div>
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-2">
- <Zap className="w-4 h-4 text-brand-500" />
- <label className="label">Exercises</label>
- <span className="text-xs text-tx-muted">(required)</span>
- </div>
- <button
- type="button"
- onClick={() => setShowPicker(true)}
- className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 text-white rounded-lg transition-colors font-medium"
- >
- <Plus className="w-3.5 h-3.5" />
- Add Exercise
- </button>
- </div>
-
- {showPicker && (
- <ExercisePicker
- selectedIds={selectedIds}
- onSelect={addExercise}
- onClose={() => setShowPicker(false)}
- />
- )}
-
- <div className="space-y-4">
- {formData.exercises.map((workoutEx, exIdx) => {
- const exercise = pickerExercises[workoutEx.exercise_id]
- return (
- <div key={exIdx} className="p-4 bg-surface-muted/30 border border-surface-border rounded-lg">
- <div className="flex items-start justify-between mb-4">
- <div className="flex-1">
- <div className="flex items-center gap-2 mb-1">
- <div className="w-6 h-6 rounded bg-brand-500/20 flex items-center justify-center flex-shrink-0">
- <span className="text-xs font-bold text-brand-500">{exIdx + 1}</span>
- </div>
- <p className="font-semibold text-tx-primary">{exercise?.name}</p>
- </div>
- <p className="text-xs text-tx-muted ml-8">{exercise?.muscle_group} • {exercise?.equipment}</p>
- </div>
- <button
- type="button"
- onClick={() => removeExercise(exIdx)}
- className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0"
- >
- <Trash2 className="w-4 h-4 text-error-400" />
- </button>
- </div>
-
- <div className="mb-4">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Notes</label>
- <input
- type="text"
- value={workoutEx.notes}
- onChange={e => {
- const exercises = [...formData.exercises]
- exercises[exIdx].notes = e.target.value
- setFormData(prev => ({ ...prev, exercises }))
- }}
- placeholder="e.g., Focus on controlled eccentric"
- className="input text-sm"
- />
- </div>
-
- <div className="space-y-2 mb-3">
- <div className="flex items-center justify-between">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Target Sets</label>
- <span className="text-xs text-tx-muted">{workoutEx.sets.length} sets</span>
- </div>
- {workoutEx.sets.map((set, setIdx) => (
- <div key={setIdx} className="flex gap-2 items-end bg-surface-raised/40 p-3 rounded-lg border border-surface-border/50">
- <div className="flex-shrink-0 w-12">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">Set</label>
- <div className="text-sm font-bold text-tx-primary bg-surface-muted px-2 py-1 rounded text-center">
- {set.set_number}
- </div>
- </div>
- <div className="flex-1 min-w-0">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Reps</label>
- <input
- type="number"
- inputMode="numeric"
- value={set.target_reps || ''}
- onChange={e => updateSet(exIdx, setIdx, 'target_reps', e.target.value)}
- placeholder="10"
- className="input text-sm w-full"
- min="0"
- />
- </div>
- <div className="flex-1 min-w-0">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Weight</label>
- <WeightInput stepper={false} size="sm" value={set.target_weight ? String(set.target_weight) : ''} onChange={v => updateSet(exIdx, setIdx, 'target_weight', v)} unit={wUnit} placeholder="135" />
- </div>
- <button
- type="button"
- onClick={() => removeSet(exIdx, setIdx)}
- className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0"
- >
- <Trash2 className="w-4 h-4 text-error-400" />
- </button>
- </div>
- ))}
- </div>
-
- <button
- type="button"
- onClick={() => addSet(exIdx)}
- className="flex items-center gap-1 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors"
- >
- <Plus className="w-3.5 h-3.5" />
- Add Set
- </button>
- </div>
- )
- })}
- </div>
- </div>
-
- <div className="flex gap-3 sticky bottom-0 bg-surface-base pt-4 border-t border-surface-border -mx-5 px-5 pb-5">
- <button
- type="button"
- onClick={handleClose}
- className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium"
- >
- Cancel
- </button>
- <button
- type="submit"
- disabled={loading}
- className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
- >
- <BookOpen className="w-4 h-4" />
- {loading ? 'Saving…' : 'Save Program'}
- </button>
- </div>
- </form>
- </div>
- </div>
- ), document.body)
-}
diff --git a/web/src/components/AddWorkoutModal.tsx b/web/src/components/AddWorkoutModal.tsx
index 49fb509..f28abe6 100644
--- a/web/src/components/AddWorkoutModal.tsx
+++ b/web/src/components/AddWorkoutModal.tsx
@@ -50,9 +50,9 @@ export default function AddWorkoutModal({ isOpen, onClose, onSuccess }: Props) {
exercises: [],
})
- const loadFromProgram = (program: types.Program) => {
+ const loadFromProgram = (_program: types.Program, day: types.ProgramDay) => {
const newMap: Record<number, types.Exercise> = { ...pickerExercises }
- const newExercises = (program.exercises || []).map(ex => {
+ const newExercises = (day.exercises || []).map(ex => {
newMap[ex.exercise_id] = ex.exercise
return {
exercise_id: ex.exercise_id,
diff --git a/web/src/components/EditProgramModal.tsx b/web/src/components/EditProgramModal.tsx
deleted file mode 100644
index c15fcb3..0000000
--- a/web/src/components/EditProgramModal.tsx
+++ /dev/null
@@ -1,313 +0,0 @@
-import { useState, useEffect } from 'react'
-import { createPortal } from 'react-dom'
-import { Plus, X, Trash2, AlertCircle, BookOpen, FileText, Zap, Target } from 'lucide-react'
-import { programAPI } from '../services/api'
-import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'
-import WeightInput from './WeightInput'
-import ExercisePicker from './ExercisePicker'
-import * as types from '../types'
-
-interface ProgramFormData {
- name: string
- notes: string
- exercises: {
- exercise_id: number
- notes: string
- sets: { set_number: number; target_reps: number; target_weight: number }[]
- }[]
-}
-
-interface Props {
- isOpen: boolean
- onClose: () => void
- onSuccess: () => void
- programId: number
-}
-
-export default function EditProgramModal({ isOpen, onClose, onSuccess, programId }: Props) {
- const { settings } = useSettingsStore()
- const wUnit = weightShort(settings.weight_unit)
- const handleClose = () => { setError(''); onClose() }
- const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})
- const [showPicker, setShowPicker] = useState(false)
- const [loading, setLoading] = useState(false)
- const [initialLoading, setInitialLoading] = useState(false)
- const [error, setError] = useState('')
- const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', exercises: [] })
-
- useEffect(() => {
- if (!isOpen) return
- setInitialLoading(true)
- programAPI.get(programId)
- .then(p => {
- const map: Record<number, types.Exercise> = {}
- ;(p.exercises || []).forEach(ex => { map[ex.exercise_id] = ex.exercise })
- setPickerExercises(map)
- setFormData({
- name: p.name,
- notes: p.notes || '',
- exercises: (p.exercises || []).map(ex => ({
- exercise_id: ex.exercise_id,
- notes: ex.notes || '',
- sets: (ex.sets || []).map(s => ({
- set_number: s.set_number,
- target_reps: s.target_reps,
- target_weight: lbsToDisplay(s.target_weight, settings.weight_unit),
- })),
- })),
- })
- })
- .catch(() => setError('Failed to load program'))
- .finally(() => setInitialLoading(false))
- }, [isOpen, programId])
-
- const addExercise = (exercise: types.Exercise) => {
- setPickerExercises(prev => ({ ...prev, [exercise.id]: exercise }))
- setFormData(prev => ({
- ...prev,
- exercises: [...prev.exercises, { exercise_id: exercise.id, notes: '', sets: [{ set_number: 1, target_reps: 0, target_weight: 0 }] }],
- }))
- setShowPicker(false)
- setError('')
- }
-
- const removeExercise = (index: number) => {
- setFormData(prev => ({ ...prev, exercises: prev.exercises.filter((_, i) => i !== index) }))
- }
-
- const addSet = (exIdx: number) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- exercises[exIdx].sets.push({ set_number: exercises[exIdx].sets.length + 1, target_reps: 0, target_weight: 0 })
- return { ...prev, exercises }
- })
- }
-
- const removeSet = (exIdx: number, setIdx: number) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- exercises[exIdx].sets = exercises[exIdx].sets.filter((_, i) => i !== setIdx)
- return { ...prev, exercises }
- })
- }
-
- const updateSet = (exIdx: number, setIdx: number, field: string, value: any) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- ;(exercises[exIdx].sets[setIdx] as any)[field] = Number(value) || 0
- return { ...prev, exercises }
- })
- }
-
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault()
- if (!formData.name.trim()) { setError('Program name required'); return }
- if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }
-
- setLoading(true)
- try {
- const payload = {
- ...formData,
- exercises: formData.exercises.map(ex => ({
- ...ex,
- sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),
- })),
- }
- await programAPI.update(programId, payload)
- onSuccess()
- onClose()
- } catch (err: any) {
- setError(err.response?.data?.error || 'Failed to update program')
- } finally {
- setLoading(false)
- }
- }
-
- if (!isOpen) return null
-
- if (initialLoading) {
- return createPortal(
- <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
- <div className="bg-surface-base border border-surface-border rounded-2xl w-full max-h-[90vh] sm:max-w-2xl overflow-y-auto">
- <div className="sticky top-0 border-b border-surface-border bg-surface-base px-5 py-4 flex items-center justify-between">
- <h2 className="font-display font-bold text-xl text-tx-primary">Edit Program</h2>
- <button onClick={handleClose} className="p-1 hover:bg-surface-muted rounded-lg transition-colors">
- <X className="w-5 h-5 text-tx-muted" />
- </button>
- </div>
- <div className="p-5 flex items-center justify-center h-32">
- <BookOpen className="w-6 h-6 text-brand-500 animate-pulse" />
- </div>
- </div>
- </div>
- , document.body)
- }
-
- const selectedIds = formData.exercises.map(e => e.exercise_id)
- const totalSets = formData.exercises.reduce((sum, ex) => sum + ex.sets.length, 0)
-
- return createPortal(
- <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
- <div className="bg-surface-base border border-surface-border rounded-2xl w-full max-h-[90vh] sm:max-w-2xl overflow-y-auto">
- <div className="sticky top-0 border-b border-surface-border bg-surface-base px-5 py-4 flex items-center justify-between">
- <div>
- <h2 className="font-display font-bold text-xl text-tx-primary">Edit Program</h2>
- <p className="text-xs text-tx-muted mt-1">{formData.exercises.length} exercises • {totalSets} sets</p>
- </div>
- <button onClick={handleClose} className="p-1 hover:bg-surface-muted rounded-lg transition-colors">
- <X className="w-5 h-5 text-tx-muted" />
- </button>
- </div>
-
- <form onSubmit={handleSubmit} className="p-5 space-y-6">
- {error && (
- <div className="alert-error">
- <AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{error}</span>
- </div>
- )}
-
- <div>
- <div className="flex items-center gap-2 mb-2">
- <BookOpen className="w-4 h-4 text-brand-500" />
- <label className="label">Program Name</label>
- </div>
- <input
- type="text"
- value={formData.name}
- onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))}
- className="input mt-1"
- />
- </div>
-
- <div>
- <div className="flex items-center gap-2 mb-2">
- <FileText className="w-4 h-4 text-brand-500" />
- <label className="label">Notes</label>
- </div>
- <textarea
- value={formData.notes}
- onChange={e => setFormData(prev => ({ ...prev, notes: e.target.value }))}
- className="input mt-1 min-h-16 resize-none"
- />
- </div>
-
- {formData.exercises.length > 0 && (
- <div className="grid grid-cols-2 gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg">
- <div className="text-center">
- <Zap className="w-3.5 h-3.5 text-brand-500 mx-auto mb-1" />
- <div className="text-sm font-bold text-brand-500">{formData.exercises.length}</div>
- <div className="text-xs text-tx-muted">Exercises</div>
- </div>
- <div className="text-center">
- <Target className="w-3.5 h-3.5 text-brand-500 mx-auto mb-1" />
- <div className="text-sm font-bold text-brand-500">{totalSets}</div>
- <div className="text-xs text-tx-muted">Target Sets</div>
- </div>
- </div>
- )}
-
- <div>
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-2">
- <Zap className="w-4 h-4 text-brand-500" />
- <label className="label">Exercises</label>
- </div>
- <button
- type="button"
- onClick={() => setShowPicker(true)}
- className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 text-white rounded-lg transition-colors font-medium"
- >
- <Plus className="w-3.5 h-3.5" />
- Add Exercise
- </button>
- </div>
-
- {showPicker && (
- <ExercisePicker selectedIds={selectedIds} onSelect={addExercise} onClose={() => setShowPicker(false)} />
- )}
-
- <div className="space-y-4">
- {formData.exercises.map((workoutEx, exIdx) => {
- const exercise = pickerExercises[workoutEx.exercise_id]
- return (
- <div key={exIdx} className="p-4 bg-surface-muted/30 border border-surface-border rounded-lg">
- <div className="flex items-start justify-between mb-4">
- <div className="flex-1">
- <div className="flex items-center gap-2 mb-1">
- <div className="w-6 h-6 rounded bg-brand-500/20 flex items-center justify-center flex-shrink-0">
- <span className="text-xs font-bold text-brand-500">{exIdx + 1}</span>
- </div>
- <p className="font-semibold text-tx-primary">{exercise?.name}</p>
- </div>
- <p className="text-xs text-tx-muted ml-8">{exercise?.muscle_group} • {exercise?.equipment}</p>
- </div>
- <button type="button" onClick={() => removeExercise(exIdx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
- <Trash2 className="w-4 h-4 text-error-400" />
- </button>
- </div>
-
- <div className="mb-4">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Notes</label>
- <input
- type="text"
- value={workoutEx.notes}
- onChange={e => {
- const exercises = [...formData.exercises]
- exercises[exIdx].notes = e.target.value
- setFormData(prev => ({ ...prev, exercises }))
- }}
- className="input text-sm"
- />
- </div>
-
- <div className="space-y-2 mb-3">
- <div className="flex items-center justify-between">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Target Sets</label>
- <span className="text-xs text-tx-muted">{workoutEx.sets.length} sets</span>
- </div>
- {workoutEx.sets.map((set, setIdx) => (
- <div key={setIdx} className="flex gap-2 items-end bg-surface-raised/40 p-3 rounded-lg border border-surface-border/50">
- <div className="flex-shrink-0 w-12">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">Set</label>
- <div className="text-sm font-bold text-tx-primary bg-surface-muted px-2 py-1 rounded text-center">{set.set_number}</div>
- </div>
- <div className="flex-1 min-w-0">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Reps</label>
- <input type="number" inputMode="numeric" value={set.target_reps || ''} onChange={e => updateSet(exIdx, setIdx, 'target_reps', e.target.value)} placeholder="10" className="input text-sm w-full" min="0" />
- </div>
- <div className="flex-1 min-w-0">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Weight</label>
- <WeightInput stepper={false} size="sm" value={set.target_weight ? String(set.target_weight) : ''} onChange={v => updateSet(exIdx, setIdx, 'target_weight', v)} unit={wUnit} placeholder="135" />
- </div>
- <button type="button" onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
- <Trash2 className="w-4 h-4 text-error-400" />
- </button>
- </div>
- ))}
- </div>
-
- <button type="button" onClick={() => addSet(exIdx)} className="flex items-center gap-1 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors">
- <Plus className="w-3.5 h-3.5" />
- Add Set
- </button>
- </div>
- )
- })}
- </div>
- </div>
-
- <div className="flex gap-3 sticky bottom-0 bg-surface-base pt-4 border-t border-surface-border -mx-5 px-5 pb-5">
- <button type="button" onClick={handleClose} className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">
- Cancel
- </button>
- <button type="submit" disabled={loading} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2">
- <BookOpen className="w-4 h-4" />
- {loading ? 'Saving…' : 'Save Changes'}
- </button>
- </div>
- </form>
- </div>
- </div>
- , document.body)
-}
diff --git a/web/src/components/ProgramPicker.test.tsx b/web/src/components/ProgramPicker.test.tsx
new file mode 100644
index 0000000..15f3e69
--- /dev/null
+++ b/web/src/components/ProgramPicker.test.tsx
@@ -0,0 +1,100 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import ProgramPicker from './ProgramPicker'
+import * as types from '../types'
+
+const listMock = vi.fn()
+vi.mock('../services/api', () => ({
+ programAPI: { list: () => listMock() },
+}))
+
+const day = (overrides: Partial<types.ProgramDay> = {}): types.ProgramDay => ({
+ id: 1,
+ order_index: 0,
+ is_rest_day: false,
+ name: '',
+ exercises: [],
+ ...overrides,
+})
+
+const program = (days: types.ProgramDay[], overrides: Partial<types.Program> = {}): types.Program => ({
+ id: 1,
+ name: 'PPL',
+ created_at: '2026-01-01T00:00:00Z',
+ days,
+ current_day_index: 0,
+ ...overrides,
+})
+
+// [Push, Rest, unnamed] — current_day_index 2 points at the unnamed day.
+const multiDay = () =>
+ program(
+ [
+ day({ id: 1, order_index: 0, name: 'Push' }),
+ day({ id: 2, order_index: 1, is_rest_day: true }),
+ day({ id: 3, order_index: 2 }),
+ ],
+ { current_day_index: 2 }
+ )
+
+describe('ProgramPicker', () => {
+ beforeEach(() => listMock.mockReset())
+
+ it('a program with zero workout days renders disabled (nothing to load)', async () => {
+ listMock.mockResolvedValue([program([day({ is_rest_day: true })])])
+ render(<ProgramPicker onSelect={() => {}} onClose={() => {}} />)
+ const btn = (await screen.findByText('PPL')).closest('button')!
+ expect(btn.disabled).toBe(true)
+ expect(screen.getByText('No exercises yet')).toBeTruthy()
+ })
+
+ it('a single-workout-day program selects immediately (one-tap flow preserved)', async () => {
+ const only = day({ id: 5, order_index: 1 })
+ const p = program([day({ id: 4, order_index: 0, is_rest_day: true }), only])
+ listMock.mockResolvedValue([p])
+ const onSelect = vi.fn()
+ render(<ProgramPicker onSelect={onSelect} onClose={() => {}} />)
+ fireEvent.click(await screen.findByText('PPL'))
+ expect(onSelect).toHaveBeenCalledWith(p, only)
+ })
+
+ it('a multi-workout-day program opens the day step listing only workout days, labeled by cycle position', async () => {
+ listMock.mockResolvedValue([multiDay()])
+ render(<ProgramPicker onSelect={() => {}} onClose={() => {}} />)
+ fireEvent.click(await screen.findByText('PPL'))
+ expect(screen.getByText('Pick a day to pre-fill exercises')).toBeTruthy()
+ expect(screen.getByText('Push')).toBeTruthy()
+ // The unnamed day sits at cycle position 2 → "Day 3", NOT "Day 2" (the
+ // rest-filtered loop index) — regression guard for the dayLabel(day, i) bug.
+ expect(screen.getByText('Day 3')).toBeTruthy()
+ expect(screen.queryByText('Rest Day')).toBeNull()
+ })
+
+ it('marks the due day with a TODAY chip in the day step', async () => {
+ listMock.mockResolvedValue([multiDay()])
+ render(<ProgramPicker onSelect={() => {}} onClose={() => {}} />)
+ fireEvent.click(await screen.findByText('PPL'))
+ const today = screen.getByText('TODAY')
+ // The chip sits inside the due day's row (the unnamed "Day 3"), not Push's.
+ expect(today.closest('button')!.textContent).toContain('Day 3')
+ })
+
+ it('picking a day fires onSelect with the program and that day', async () => {
+ const p = multiDay()
+ listMock.mockResolvedValue([p])
+ const onSelect = vi.fn()
+ render(<ProgramPicker onSelect={onSelect} onClose={() => {}} />)
+ fireEvent.click(await screen.findByText('PPL'))
+ fireEvent.click(screen.getByText('Push'))
+ expect(onSelect).toHaveBeenCalledWith(p, p.days[0])
+ })
+
+ it('back returns from the day step to the program list', async () => {
+ listMock.mockResolvedValue([multiDay()])
+ render(<ProgramPicker onSelect={() => {}} onClose={() => {}} />)
+ fireEvent.click(await screen.findByText('PPL'))
+ fireEvent.click(screen.getByText('← Back to programs'))
+ expect(screen.getByText('Load from Program')).toBeTruthy()
+ expect(screen.queryByText('Pick a day to pre-fill exercises')).toBeNull()
+ })
+})
diff --git a/web/src/components/ProgramPicker.tsx b/web/src/components/ProgramPicker.tsx
index 89575be..34a8c99 100644
--- a/web/src/components/ProgramPicker.tsx
+++ b/web/src/components/ProgramPicker.tsx
@@ -1,17 +1,22 @@
import { useState, useEffect } from 'react'
-import { X, BookOpen, ChevronRight, Dumbbell, AlertCircle } from 'lucide-react'
+import { X, BookOpen, ChevronRight, Dumbbell, AlertCircle, Moon } from 'lucide-react'
import { programAPI } from '../services/api'
+import { workoutDays, dayLabel, todaysDay } from '../utils/programUtils'
import * as types from '../types'
interface Props {
- onSelect: (program: types.Program) => void
+ onSelect: (program: types.Program, day: types.ProgramDay) => void
onClose: () => void
}
+// Two-step: pick a Program, then (if it has more than one workout day) pick which
+// Day to load — a single-workout-day program skips straight through, so the common
+// case stays a one-tap flow exactly like before the multi-day rework.
export default function ProgramPicker({ onSelect, onClose }: Props) {
const [programs, setPrograms] = useState<types.Program[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
+ const [dayPickFor, setDayPickFor] = useState<types.Program | null>(null)
useEffect(() => {
programAPI.list()
@@ -20,13 +25,23 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {
.finally(() => setLoading(false))
}, [])
+ const pickProgram = (p: types.Program) => {
+ const days = workoutDays(p)
+ if (days.length === 0) return // nothing to load — no exercises anywhere in this program
+ if (days.length === 1) { onSelect(p, days[0]); return }
+ setDayPickFor(p)
+ }
+
+ const title = dayPickFor ? dayPickFor.name : 'Load from Program'
+ const subtitle = dayPickFor ? 'Pick a day to pre-fill exercises' : 'Pick a program to pre-fill exercises'
+
return (
<div className="fixed inset-0 bg-black/60 z-[60] flex items-center justify-center p-4">
<div className="bg-surface-base border border-surface-border rounded-2xl w-full sm:max-w-lg flex flex-col max-h-[80vh]">
<div className="flex items-center justify-between px-4 py-3 border-b border-surface-border flex-shrink-0">
<div>
- <h3 className="font-semibold text-tx-primary">Load from Program</h3>
- <p className="text-xs text-tx-muted mt-0.5">Pick a program to pre-fill exercises</p>
+ <h3 className="font-semibold text-tx-primary">{title}</h3>
+ <p className="text-xs text-tx-muted mt-0.5">{subtitle}</p>
</div>
<button onClick={onClose} className="p-1.5 hover:bg-surface-muted rounded-lg transition-colors">
<X className="w-4 h-4 text-tx-muted" />
@@ -44,6 +59,43 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {
<AlertCircle className="w-4 h-4 flex-shrink-0" />
{error}
</div>
+ ) : dayPickFor ? (
+ <div>
+ <button
+ type="button"
+ onClick={() => setDayPickFor(null)}
+ className="w-full text-left px-4 py-2 text-xs text-tx-muted hover:text-tx-secondary transition-colors"
+ >
+ ← Back to programs
+ </button>
+ <div className="divide-y divide-surface-border">
+ {workoutDays(dayPickFor).map((day, i) => {
+ const isToday = todaysDay(dayPickFor)?.id === day.id
+ return (
+ <button
+ key={day.id ?? i}
+ type="button"
+ onClick={() => onSelect(dayPickFor, day)}
+ className="w-full flex items-center gap-3 px-4 py-3 hover:bg-surface-muted transition-colors text-left group"
+ >
+ <div className="w-9 h-9 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
+ <Dumbbell className="w-4 h-4 text-brand-500" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium text-tx-primary truncate flex items-center gap-1.5">
+ {dayLabel(day, day.order_index)}
+ {isToday && <span className="text-[10px] font-bold text-brand-400 bg-brand-500/15 px-1.5 py-0.5 rounded-full">TODAY</span>}
+ </p>
+ <span className="text-xs text-tx-muted">
+ {(day.exercises ?? []).length} exercise{(day.exercises ?? []).length === 1 ? '' : 's'}
+ </span>
+ </div>
+ <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity" />
+ </button>
+ )
+ })}
+ </div>
+ </div>
) : programs.length === 0 ? (
<div className="flex flex-col items-center justify-center p-8 text-center">
<BookOpen className="w-8 h-8 text-tx-muted mb-2 opacity-50" />
@@ -52,31 +104,35 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {
</div>
) : (
<div className="divide-y divide-surface-border">
- {programs.map(p => (
- <button
- key={p.id}
- type="button"
- onClick={() => onSelect(p)}
- className="w-full flex items-center gap-3 px-4 py-3 hover:bg-surface-muted transition-colors text-left group"
- >
- <div className="w-9 h-9 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
- <BookOpen className="w-4 h-4 text-brand-500" />
- </div>
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium text-tx-primary truncate">{p.name}</p>
- <div className="flex items-center gap-2 mt-0.5">
- <span className="text-xs text-tx-muted">
- <Dumbbell className="w-3 h-3 inline mr-1" />
- {p.exercises?.length || 0} exercises
- </span>
- {p.notes && (
- <span className="text-xs text-tx-muted truncate">• {p.notes}</span>
- )}
+ {programs.map(p => {
+ const days = workoutDays(p)
+ return (
+ <button
+ key={p.id}
+ type="button"
+ disabled={days.length === 0}
+ onClick={() => pickProgram(p)}
+ className="w-full flex items-center gap-3 px-4 py-3 hover:bg-surface-muted disabled:opacity-40 disabled:hover:bg-transparent transition-colors text-left group"
+ >
+ <div className="w-9 h-9 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
+ <BookOpen className="w-4 h-4 text-brand-500" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium text-tx-primary truncate">{p.name}</p>
+ <div className="flex items-center gap-2 mt-0.5">
+ <span className="text-xs text-tx-muted">
+ <Dumbbell className="w-3 h-3 inline mr-1" />
+ {days.length === 0 ? 'No exercises yet' : `${days.length} workout day${days.length === 1 ? '' : 's'}`}
+ </span>
+ {(p.days ?? []).some(d => d.is_rest_day) && (
+ <span className="text-xs text-tx-muted"><Moon className="w-3 h-3 inline mr-0.5" />rest days</span>
+ )}
+ </div>
</div>
- </div>
- <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity" />
- </button>
- ))}
+ <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity" />
+ </button>
+ )
+ })}
</div>
)}
</div>
diff --git a/web/src/components/StartWorkoutModal.tsx b/web/src/components/StartWorkoutModal.tsx
index 49f410e..470fba4 100644
--- a/web/src/components/StartWorkoutModal.tsx
+++ b/web/src/components/StartWorkoutModal.tsx
@@ -1,9 +1,10 @@
import { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
-import { X, Play, BookOpen, Zap, ChevronRight, Dumbbell, AlertCircle } from 'lucide-react'
+import { X, Play, BookOpen, Zap, ChevronRight } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
-import { programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
+import ProgramPicker from './ProgramPicker'
+import { activeSessionExercisesForDay, sessionNameForDay } from '../utils/programUtils'
import * as types from '../types'
type Mode = 'pick' | 'from-program'
@@ -17,24 +18,11 @@ export default function StartWorkoutModal({ isOpen, onClose }: Props) {
const navigate = useNavigate()
const { startSession } = useWorkoutSession()
const [mode, setMode] = useState<Mode>('pick')
- const [programs, setPrograms] = useState<types.Program[]>([])
- const [programsLoading, setProgramsLoading] = useState(false)
- const [programsError, setProgramsError] = useState('')
useEffect(() => {
if (!isOpen) setMode('pick')
}, [isOpen])
- useEffect(() => {
- if (mode === 'from-program' && programs.length === 0) {
- setProgramsLoading(true)
- programAPI.list()
- .then(data => setPrograms(data || []))
- .catch(() => setProgramsError('Failed to load programs'))
- .finally(() => setProgramsLoading(false))
- }
- }, [mode])
-
const startQuick = () => {
const name = `Workout — ${new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`
startSession(name, [])
@@ -42,23 +30,8 @@ export default function StartWorkoutModal({ isOpen, onClose }: Props) {
navigate('/workout/active')
}
- const startFromProgram = (program: types.Program) => {
- const exercises: types.ActiveSessionExercise[] = (program.exercises || []).map(ex => ({
- exercise_id: ex.exercise_id,
- exercise: ex.exercise,
- notes: ex.notes || '',
- rest_seconds: ex.rest_seconds,
- sets: (ex.sets || []).map(s => ({
- set_number: s.set_number,
- target_reps: s.target_reps,
- target_weight: s.target_weight,
- actual_reps: s.target_reps,
- actual_weight: s.target_weight,
- completed: false,
- program_set_id: s.id, // link for routine target auto-progression (#40)
- })),
- }))
- startSession(program.name, exercises, program.id)
+ const startFromProgram = (program: types.Program, day: types.ProgramDay) => {
+ startSession(sessionNameForDay(program, day), activeSessionExercisesForDay(day), program.id, day.id)
onClose()
navigate('/workout/active')
}
@@ -102,58 +75,17 @@ export default function StartWorkoutModal({ isOpen, onClose }: Props) {
</div>
<div className="text-left flex-1">
<p className="font-semibold text-tx-primary">From Program</p>
- <p className="text-xs text-tx-muted mt-0.5">Load a saved program template</p>
+ <p className="text-xs text-tx-muted mt-0.5">Load a saved program's day</p>
</div>
<ChevronRight className="w-4 h-4 text-tx-muted opacity-0 group-hover:opacity-100 transition-opacity" />
</button>
</div>
)}
-
- {mode === 'from-program' && (
- <div className="space-y-3">
- <button onClick={() => setMode('pick')} className="text-xs text-tx-muted hover:text-tx-secondary transition-colors">← Back</button>
- {programsLoading ? (
- <div className="flex items-center justify-center py-8 text-tx-muted text-sm">
- <BookOpen className="w-5 h-5 mr-2 animate-pulse text-brand-500" />
- Loading programs…
- </div>
- ) : programsError ? (
- <div className="flex items-center gap-2 text-error-400 text-sm py-4">
- <AlertCircle className="w-4 h-4" />
- {programsError}
- </div>
- ) : programs.length === 0 ? (
- <div className="text-center py-8">
- <BookOpen className="w-8 h-8 text-tx-muted mx-auto mb-2 opacity-50" />
- <p className="text-sm text-tx-muted">No programs yet</p>
- <p className="text-xs text-tx-muted mt-1">Create a program first</p>
- </div>
- ) : (
- <div className="space-y-2 max-h-64 overflow-y-auto">
- {programs.map(p => (
- <button
- key={p.id}
- onClick={() => startFromProgram(p)}
- className="w-full flex items-center gap-3 p-3 bg-surface-muted/50 border border-surface-border hover:bg-surface-muted rounded-xl transition-colors text-left group"
- >
- <div className="w-9 h-9 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
- <BookOpen className="w-4 h-4 text-brand-500" />
- </div>
- <div className="flex-1 min-w-0">
- <p className="text-sm font-semibold text-tx-primary truncate">{p.name}</p>
- <p className="text-xs text-tx-muted">
- <Dumbbell className="w-3 h-3 inline mr-1" />
- {p.exercises?.length || 0} exercises
- </p>
- </div>
- <Play className="w-4 h-4 text-brand-500 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
- </button>
- ))}
- </div>
- )}
- </div>
- )}
</div>
+
+ {mode === 'from-program' && (
+ <ProgramPicker onSelect={startFromProgram} onClose={() => setMode('pick')} />
+ )}
</div>
</div>
), document.body)
diff --git a/web/src/components/programs/DayExercisesEditor.test.tsx b/web/src/components/programs/DayExercisesEditor.test.tsx
new file mode 100644
index 0000000..5e6dcc0
--- /dev/null
+++ b/web/src/components/programs/DayExercisesEditor.test.tsx
@@ -0,0 +1,87 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import DayExercisesEditor from './DayExercisesEditor'
+import * as types from '../../types'
+import type { DayExerciseDraft } from './types'
+
+const bench: types.Exercise = {
+ id: 1, name: 'Bench Press', muscle_group: 'chest', secondary_muscles: [],
+ category: 'strength', equipment: 'barbell', description: '',
+}
+
+const draft = (overrides: Partial<DayExerciseDraft> = {}): DayExerciseDraft => ({
+ exercise_id: 1,
+ notes: '',
+ rest_seconds: 90,
+ sets: [{ set_number: 1, target_reps: 5, target_weight: 135 }],
+ ...overrides,
+})
+
+const renderEditor = (exercises: DayExerciseDraft[], onChange = vi.fn()) => {
+ render(
+ <DayExercisesEditor
+ exercises={exercises}
+ onChange={onChange}
+ pickerExercises={{ 1: bench }}
+ onCacheExercise={() => {}}
+ wUnit="lbs"
+ restSecondsDefault={90}
+ />
+ )
+ return onChange
+}
+
+describe('DayExercisesEditor', () => {
+ it('renders the empty state when the day has no exercises', () => {
+ renderEditor([])
+ expect(screen.getByText(/No exercises yet/)).toBeTruthy()
+ })
+
+ it('shows the cached exercise name and its set count', () => {
+ renderEditor([draft()])
+ expect(screen.getByText('Bench Press')).toBeTruthy()
+ expect(screen.getByText('1 sets')).toBeTruthy()
+ })
+
+ it('Add Set appends a set with the next set_number', () => {
+ const onChange = renderEditor([draft()])
+ fireEvent.click(screen.getByText('Add Set'))
+ const next: DayExerciseDraft[] = onChange.mock.calls[0][0]
+ expect(next[0].sets).toHaveLength(2)
+ expect(next[0].sets[1]).toEqual({ set_number: 2, target_reps: 0, target_weight: 0 })
+ })
+
+ it('editing target reps coerces to a number (garbage → 0)', () => {
+ const onChange = renderEditor([draft()])
+ fireEvent.change(screen.getByPlaceholderText('10'), { target: { value: '8' } })
+ expect(onChange.mock.calls[0][0][0].sets[0].target_reps).toBe(8)
+ })
+
+ it('removing the exercise emits an empty list', () => {
+ const onChange = renderEditor([draft()])
+ // First trash button is the exercise's remove; the set rows' trash follow it.
+ const trash = document.querySelectorAll('button svg.lucide-trash-2')
+ fireEvent.click(trash[0].closest('button')!)
+ expect(onChange.mock.calls[0][0]).toEqual([])
+ })
+
+ it('removing a set only touches that set', () => {
+ const onChange = renderEditor([draft({
+ sets: [
+ { set_number: 1, target_reps: 5, target_weight: 135 },
+ { set_number: 2, target_reps: 5, target_weight: 145 },
+ ],
+ })])
+ const trash = document.querySelectorAll('button svg.lucide-trash-2')
+ fireEvent.click(trash[1].closest('button')!) // first SET row (index 0 is the exercise remove)
+ const next: DayExerciseDraft[] = onChange.mock.calls[0][0]
+ expect(next[0].sets).toHaveLength(1)
+ expect(next[0].sets[0].target_weight).toBe(145)
+ })
+
+ it('notes edits patch only the exercise notes', () => {
+ const onChange = renderEditor([draft()])
+ fireEvent.change(screen.getByPlaceholderText(/Focus on controlled/), { target: { value: 'pause reps' } })
+ expect(onChange.mock.calls[0][0][0].notes).toBe('pause reps')
+ })
+})
diff --git a/web/src/components/programs/DayExercisesEditor.tsx b/web/src/components/programs/DayExercisesEditor.tsx
new file mode 100644
index 0000000..d716f26
--- /dev/null
+++ b/web/src/components/programs/DayExercisesEditor.tsx
@@ -0,0 +1,176 @@
+import { useState } from 'react'
+import { Plus, Trash2, Zap, Timer } from 'lucide-react'
+import WeightInput from '../WeightInput'
+import ExercisePicker from '../ExercisePicker'
+import RestPicker from '../RestPicker'
+import * as types from '../../types'
+import type { DayExerciseDraft } from './types'
+
+interface Props {
+ exercises: DayExerciseDraft[]
+ onChange: (exercises: DayExerciseDraft[]) => void
+ pickerExercises: Record<number, types.Exercise>
+ onCacheExercise: (ex: types.Exercise) => void
+ wUnit: string
+ restSecondsDefault: number
+}
+
+// The per-exercise editing UI (name/notes/rest/target sets) — unchanged from the
+// pre-multi-day flat editor, just parameterized so each Day in ProgramDaysEditor
+// gets its own instance instead of the page owning one flat exercises array.
+export default function DayExercisesEditor({ exercises, onChange, pickerExercises, onCacheExercise, wUnit, restSecondsDefault }: Props) {
+ const [showPicker, setShowPicker] = useState(false)
+
+ const addExercise = (exercise: types.Exercise) => {
+ onCacheExercise(exercise)
+ onChange([...exercises, {
+ exercise_id: exercise.id,
+ notes: '',
+ rest_seconds: restSecondsDefault,
+ sets: [{ set_number: 1, target_reps: 0, target_weight: 0 }],
+ }])
+ setShowPicker(false)
+ }
+
+ const removeExercise = (exIdx: number) => onChange(exercises.filter((_, i) => i !== exIdx))
+
+ const addSet = (exIdx: number) => {
+ const next = [...exercises]
+ const count = next[exIdx].sets.length + 1
+ next[exIdx] = { ...next[exIdx], sets: [...next[exIdx].sets, { set_number: count, target_reps: 0, target_weight: 0 }] }
+ onChange(next)
+ }
+
+ const removeSet = (exIdx: number, setIdx: number) => {
+ const next = [...exercises]
+ next[exIdx] = { ...next[exIdx], sets: next[exIdx].sets.filter((_, i) => i !== setIdx) }
+ onChange(next)
+ }
+
+ const updateSet = (exIdx: number, setIdx: number, field: 'target_reps' | 'target_weight', value: any) => {
+ const next = [...exercises]
+ const sets = [...next[exIdx].sets]
+ sets[setIdx] = { ...sets[setIdx], [field]: Number(value) || 0 }
+ next[exIdx] = { ...next[exIdx], sets }
+ onChange(next)
+ }
+
+ const updateNotes = (exIdx: number, notes: string) => {
+ const next = [...exercises]
+ next[exIdx] = { ...next[exIdx], notes }
+ onChange(next)
+ }
+
+ const setExRest = (exIdx: number, secs: number) => {
+ const next = [...exercises]
+ next[exIdx] = { ...next[exIdx], rest_seconds: secs }
+ onChange(next)
+ }
+
+ const selectedIds = exercises.map(e => e.exercise_id)
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center gap-2">
+ <Zap className="w-4 h-4 text-brand-500" />
+ <label className="label">Exercises</label>
+ </div>
+ <button
+ type="button"
+ onClick={() => setShowPicker(true)}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 text-white rounded-lg transition-colors font-medium"
+ >
+ <Plus className="w-3.5 h-3.5" />
+ Add Exercise
+ </button>
+ </div>
+
+ {showPicker && (
+ <ExercisePicker
+ selectedIds={selectedIds}
+ onSelect={addExercise}
+ onClose={() => setShowPicker(false)}
+ />
+ )}
+
+ {exercises.length === 0 ? (
+ <p className="text-xs text-tx-muted text-center py-4">No exercises yet — add one above.</p>
+ ) : (
+ <div className="space-y-4">
+ {exercises.map((workoutEx, exIdx) => {
+ const exercise = pickerExercises[workoutEx.exercise_id]
+ return (
+ <div key={exIdx} className="p-4 bg-surface-muted/30 border border-surface-border rounded-lg">
+ <div className="flex items-start justify-between mb-4">
+ <div className="flex-1">
+ <div className="flex items-center gap-2 mb-1">
+ <div className="w-6 h-6 rounded bg-brand-500/20 flex items-center justify-center flex-shrink-0">
+ <span className="text-xs font-bold text-brand-500">{exIdx + 1}</span>
+ </div>
+ <p className="font-semibold text-tx-primary">{exercise?.name}</p>
+ </div>
+ <p className="text-xs text-tx-muted ml-8">{exercise?.muscle_group} • {exercise?.equipment}</p>
+ </div>
+ <button type="button" onClick={() => removeExercise(exIdx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
+ <Trash2 className="w-4 h-4 text-error-400" />
+ </button>
+ </div>
+
+ <div className="mb-4">
+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Notes</label>
+ <input
+ type="text"
+ value={workoutEx.notes}
+ onChange={e => updateNotes(exIdx, e.target.value)}
+ placeholder="e.g., Focus on controlled eccentric"
+ className="input text-sm"
+ />
+ </div>
+
+ <div className="mb-4">
+ <div className="flex items-center gap-1.5 mb-1">
+ <Timer className="w-3.5 h-3.5 text-brand-500" />
+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Rest between sets</label>
+ </div>
+ <RestPicker value={workoutEx.rest_seconds ?? 90} onChange={secs => setExRest(exIdx, secs)} />
+ </div>
+
+ <div className="space-y-2 mb-3">
+ <div className="flex items-center justify-between">
+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Target Sets</label>
+ <span className="text-xs text-tx-muted">{workoutEx.sets.length} sets</span>
+ </div>
+ {workoutEx.sets.map((set, setIdx) => (
+ <div key={setIdx} className="flex gap-2 items-end bg-surface-raised/40 p-3 rounded-lg border border-surface-border/50">
+ <div className="flex-shrink-0 w-12">
+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">Set</label>
+ <div className="text-sm font-bold text-tx-primary bg-surface-muted px-2 py-1 rounded text-center">{set.set_number}</div>
+ </div>
+ <div className="flex-1 min-w-0">
+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Reps</label>
+ <input type="number" inputMode="numeric" value={set.target_reps || ''} onChange={e => updateSet(exIdx, setIdx, 'target_reps', e.target.value)} placeholder="10" className="input text-sm w-full" min="0" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Weight</label>
+ <WeightInput stepper={false} size="sm" value={set.target_weight ? String(set.target_weight) : ''} onChange={v => updateSet(exIdx, setIdx, 'target_weight', v)} unit={wUnit} placeholder="135" />
+ </div>
+ <button type="button" onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
+ <Trash2 className="w-4 h-4 text-error-400" />
+ </button>
+ </div>
+ ))}
+ </div>
+
+ <button type="button" onClick={() => addSet(exIdx)} className="flex items-center gap-1 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors">
+ <Plus className="w-3.5 h-3.5" />
+ Add Set
+ </button>
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/web/src/components/programs/ProgramDaysEditor.test.tsx b/web/src/components/programs/ProgramDaysEditor.test.tsx
new file mode 100644
index 0000000..db8179a
--- /dev/null
+++ b/web/src/components/programs/ProgramDaysEditor.test.tsx
@@ -0,0 +1,99 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import ProgramDaysEditor from './ProgramDaysEditor'
+import type { DayDraft } from './types'
+
+const dayDraft = (overrides: Partial<DayDraft> = {}): DayDraft => ({
+ order_index: 0,
+ is_rest_day: false,
+ name: '',
+ exercises: [],
+ ...overrides,
+})
+
+const renderEditor = (days: DayDraft[], onChange = vi.fn()) => {
+ render(
+ <ProgramDaysEditor
+ days={days}
+ onChange={onChange}
+ pickerExercises={{}}
+ onCacheExercise={() => {}}
+ wUnit="lbs"
+ restSecondsDefault={90}
+ />
+ )
+ return onChange
+}
+
+describe('ProgramDaysEditor', () => {
+ it('renders the empty state when there are no days', () => {
+ renderEditor([])
+ expect(screen.getByText(/No days yet/)).toBeTruthy()
+ })
+
+ it('Add Workout Day appends a workout day with a reindexed order_index', () => {
+ const onChange = renderEditor([dayDraft({ name: 'Push' })])
+ fireEvent.click(screen.getByText('Add Workout Day'))
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next).toHaveLength(2)
+ expect(next[1]).toMatchObject({ order_index: 1, is_rest_day: false, exercises: [] })
+ })
+
+ it('Add Rest Day appends a rest day', () => {
+ const onChange = renderEditor([])
+ fireEvent.click(screen.getByText('Add Rest Day'))
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next).toEqual([dayDraft({ is_rest_day: true })])
+ })
+
+ it('removing a day reindexes the survivors', () => {
+ const onChange = renderEditor([
+ dayDraft({ order_index: 0, name: 'A' }),
+ dayDraft({ order_index: 1, name: 'B' }),
+ dayDraft({ order_index: 2, name: 'C' }),
+ ])
+ // One trash button per day row (set rows would add more, but days are empty).
+ const trash = document.querySelectorAll('button svg.lucide-trash-2')
+ fireEvent.click(trash[1].closest('button')!)
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next.map(d => d.name)).toEqual(['A', 'C'])
+ expect(next.map(d => d.order_index)).toEqual([0, 1])
+ })
+
+ it('move-down swaps a day with its neighbor and rewrites order_index', () => {
+ const onChange = renderEditor([
+ dayDraft({ order_index: 0, name: 'A' }),
+ dayDraft({ order_index: 1, name: 'B' }),
+ ])
+ const downs = document.querySelectorAll('button svg.lucide-chevron-down')
+ fireEvent.click(downs[0].closest('button')!)
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next.map(d => d.name)).toEqual(['B', 'A'])
+ expect(next.map(d => d.order_index)).toEqual([0, 1])
+ })
+
+ it('toggling a workout day to rest CLEARS its exercises (a rest day never carries any)', () => {
+ const exercises = [{ exercise_id: 1, notes: '', rest_seconds: 90, sets: [] }]
+ const onChange = renderEditor([dayDraft({ exercises })])
+ fireEvent.click(screen.getByText('Rest'))
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next[0].is_rest_day).toBe(true)
+ expect(next[0].exercises).toEqual([])
+ })
+
+ it('toggling rest → workout keeps the (empty) exercise list and flips the flag', () => {
+ const onChange = renderEditor([dayDraft({ is_rest_day: true })])
+ fireEvent.click(screen.getByText('Workout'))
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next[0].is_rest_day).toBe(false)
+ })
+
+ it('renaming a day emits the patch without touching siblings', () => {
+ const onChange = renderEditor([dayDraft({ name: 'A' }), dayDraft({ order_index: 1, name: 'B' })])
+ const inputs = screen.getAllByPlaceholderText(/^Day \d$/)
+ fireEvent.change(inputs[0], { target: { value: 'Push' } })
+ const next: DayDraft[] = onChange.mock.calls[0][0]
+ expect(next[0].name).toBe('Push')
+ expect(next[1].name).toBe('B')
+ })
+})
diff --git a/web/src/components/programs/ProgramDaysEditor.tsx b/web/src/components/programs/ProgramDaysEditor.tsx
new file mode 100644
index 0000000..7d8065f
--- /dev/null
+++ b/web/src/components/programs/ProgramDaysEditor.tsx
@@ -0,0 +1,158 @@
+import { useState } from 'react'
+import { Plus, Trash2, ChevronUp, ChevronDown, Dumbbell, Moon, ChevronRight, ChevronLeft as ChevronCollapse } from 'lucide-react'
+import DayExercisesEditor from './DayExercisesEditor'
+import * as types from '../../types'
+import type { DayDraft } from './types'
+
+interface Props {
+ days: DayDraft[]
+ onChange: (days: DayDraft[]) => void
+ pickerExercises: Record<number, types.Exercise>
+ onCacheExercise: (ex: types.Exercise) => void
+ wUnit: string
+ restSecondsDefault: number
+}
+
+const reindex = (days: DayDraft[]): DayDraft[] => days.map((d, i) => ({ ...d, order_index: i }))
+
+// The program's day/rest-day cycle, in order. Add/remove/reorder days here; each
+// workout day expands to the (unchanged) per-day exercise editor.
+export default function ProgramDaysEditor({ days, onChange, pickerExercises, onCacheExercise, wUnit, restSecondsDefault }: Props) {
+ const [expanded, setExpanded] = useState<number | null>(days.findIndex(d => !d.is_rest_day))
+
+ const addDay = (isRest: boolean) => {
+ const next = reindex([...days, { order_index: days.length, is_rest_day: isRest, name: '', exercises: [] }])
+ onChange(next)
+ setExpanded(next.length - 1)
+ }
+
+ const removeDay = (idx: number) => {
+ onChange(reindex(days.filter((_, i) => i !== idx)))
+ setExpanded(null)
+ }
+
+ const moveDay = (idx: number, dir: -1 | 1) => {
+ const target = idx + dir
+ if (target < 0 || target >= days.length) return
+ const next = [...days]
+ ;[next[idx], next[target]] = [next[target], next[idx]]
+ onChange(reindex(next))
+ if (expanded === idx) setExpanded(target)
+ else if (expanded === target) setExpanded(idx)
+ }
+
+ const updateDay = (idx: number, patch: Partial<DayDraft>) => {
+ const next = [...days]
+ next[idx] = { ...next[idx], ...patch }
+ onChange(next)
+ }
+
+ const toggleRest = (idx: number) => {
+ const day = days[idx]
+ // Switching to rest clears its exercises — a rest day never carries any.
+ updateDay(idx, { is_rest_day: !day.is_rest_day, exercises: day.is_rest_day ? day.exercises : [] })
+ }
+
+ return (
+ <div className="space-y-3">
+ {days.length === 0 && (
+ <p className="text-xs text-tx-muted text-center py-4">No days yet — add a workout or rest day below.</p>
+ )}
+
+ {days.map((day, idx) => {
+ const isOpen = expanded === idx
+ return (
+ <div key={idx} className={`border rounded-lg overflow-hidden ${day.is_rest_day ? 'border-surface-border bg-surface-muted/20' : 'border-surface-border bg-surface-muted/30'}`}>
+ <div className="flex items-center gap-2 p-3">
+ <div className="flex flex-col flex-shrink-0">
+ <button type="button" onClick={() => moveDay(idx, -1)} disabled={idx === 0} className="p-0.5 text-tx-muted hover:text-tx-primary disabled:opacity-20 transition-colors">
+ <ChevronUp className="w-3.5 h-3.5" />
+ </button>
+ <button type="button" onClick={() => moveDay(idx, 1)} disabled={idx === days.length - 1} className="p-0.5 text-tx-muted hover:text-tx-primary disabled:opacity-20 transition-colors">
+ <ChevronDown className="w-3.5 h-3.5" />
+ </button>
+ </div>
+
+ <div className={`w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 ${day.is_rest_day ? 'bg-surface-muted' : 'bg-brand-500/15'}`}>
+ {day.is_rest_day ? <Moon className="w-4 h-4 text-tx-muted" /> : <Dumbbell className="w-4 h-4 text-brand-500" />}
+ </div>
+
+ <input
+ type="text"
+ value={day.name}
+ onChange={e => updateDay(idx, { name: e.target.value })}
+ placeholder={day.is_rest_day ? `Rest Day ${idx + 1}` : `Day ${idx + 1}`}
+ className="input text-sm flex-1 min-w-0"
+ />
+
+ <div className="flex items-center rounded-lg border border-surface-border overflow-hidden flex-shrink-0">
+ <button
+ type="button"
+ onClick={() => day.is_rest_day && toggleRest(idx)}
+ className={`px-2.5 py-1.5 text-xs font-semibold transition-colors ${!day.is_rest_day ? 'bg-brand-500 text-white' : 'bg-transparent text-tx-muted hover:text-tx-secondary'}`}
+ >
+ Workout
+ </button>
+ <button
+ type="button"
+ onClick={() => !day.is_rest_day && toggleRest(idx)}
+ className={`px-2.5 py-1.5 text-xs font-semibold transition-colors ${day.is_rest_day ? 'bg-surface-muted text-tx-primary' : 'bg-transparent text-tx-muted hover:text-tx-secondary'}`}
+ >
+ Rest
+ </button>
+ </div>
+
+ {!day.is_rest_day && (
+ <button type="button" onClick={() => setExpanded(isOpen ? null : idx)} className="p-1.5 hover:bg-surface-muted rounded-lg transition-colors flex-shrink-0">
+ {isOpen ? <ChevronCollapse className="w-4 h-4 text-tx-muted rotate-90" /> : <ChevronRight className="w-4 h-4 text-tx-muted" />}
+ </button>
+ )}
+
+ <button type="button" onClick={() => removeDay(idx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
+ <Trash2 className="w-4 h-4 text-error-400" />
+ </button>
+ </div>
+
+ {!day.is_rest_day && (
+ <div className="px-3 pb-3 flex items-center gap-2 -mt-1">
+ <span className="text-[11px] text-tx-muted">{day.exercises.length} exercise{day.exercises.length === 1 ? '' : 's'}</span>
+ </div>
+ )}
+
+ {!day.is_rest_day && isOpen && (
+ <div className="px-3 pb-4 pt-1 border-t border-surface-border/60">
+ <DayExercisesEditor
+ exercises={day.exercises}
+ onChange={exercises => updateDay(idx, { exercises })}
+ pickerExercises={pickerExercises}
+ onCacheExercise={onCacheExercise}
+ wUnit={wUnit}
+ restSecondsDefault={restSecondsDefault}
+ />
+ </div>
+ )}
+ </div>
+ )
+ })}
+
+ <div className="flex gap-2">
+ <button
+ type="button"
+ onClick={() => addDay(false)}
+ className="flex-1 flex items-center justify-center gap-1.5 py-2.5 text-xs bg-brand-500/10 hover:bg-brand-500/15 text-brand-400 border border-brand-500/20 rounded-lg transition-colors font-medium"
+ >
+ <Plus className="w-3.5 h-3.5" />
+ Add Workout Day
+ </button>
+ <button
+ type="button"
+ onClick={() => addDay(true)}
+ className="flex-1 flex items-center justify-center gap-1.5 py-2.5 text-xs bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary border border-surface-border rounded-lg transition-colors font-medium"
+ >
+ <Moon className="w-3.5 h-3.5" />
+ Add Rest Day
+ </button>
+ </div>
+ </div>
+ )
+}
diff --git a/web/src/components/programs/types.ts b/web/src/components/programs/types.ts
new file mode 100644
index 0000000..1067bde
--- /dev/null
+++ b/web/src/components/programs/types.ts
@@ -0,0 +1,27 @@
+// Local draft shapes for the program day/exercise editors — mirror
+// CreateProgramDayReq/CreateProgramExerciseReq (backend/models/models.go) but keep
+// weights in the user's display unit until submit (see displayToLbs conversion at
+// save time in AddProgram/EditProgram).
+export interface DaySetDraft {
+ set_number: number
+ target_reps: number
+ target_weight: number
+}
+
+export interface DayExerciseDraft {
+ exercise_id: number
+ notes: string
+ rest_seconds: number
+ sets: DaySetDraft[]
+}
+
+export interface DayDraft {
+ // Existing program_days row id, round-tripped through updates so the server can
+ // match edited days by identity instead of position — reordering/removing days
+ // must not re-attribute logged workouts to the wrong day. Absent for new days.
+ id?: number
+ order_index: number
+ is_rest_day: boolean
+ name: string
+ exercises: DayExerciseDraft[]
+}
diff --git a/web/src/pages/AddProgram.tsx b/web/src/pages/AddProgram.tsx
index ea7de82..85c4e9e 100644
--- a/web/src/pages/AddProgram.tsx
+++ b/web/src/pages/AddProgram.tsx
@@ -1,99 +1,49 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
-import { Plus, ArrowLeft, Trash2, AlertCircle, BookOpen, FileText, Zap, Target, Timer } from 'lucide-react'
+import { ArrowLeft, AlertCircle, BookOpen, FileText, CalendarDays } from 'lucide-react'
import { programAPI } from '../services/api'
import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'
-import WeightInput from '../components/WeightInput'
-import ExercisePicker from '../components/ExercisePicker'
-import RestPicker from '../components/RestPicker'
+import { hasWorkoutExercises } from '../utils/programUtils'
+import ProgramDaysEditor from '../components/programs/ProgramDaysEditor'
import * as types from '../types'
+import type { DayDraft } from '../components/programs/types'
interface ProgramFormData {
name: string
notes: string
- exercises: {
- exercise_id: number
- notes: string
- rest_seconds: number
- sets: { set_number: number; target_reps: number; target_weight: number }[]
- }[]
+ days: DayDraft[]
}
export default function AddProgram() {
const navigate = useNavigate()
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
- const [showPicker, setShowPicker] = useState(false)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})
- const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', exercises: [] })
+ const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })
useEffect(() => { if (error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error])
- const addExercise = (exercise: types.Exercise) => {
- setPickerExercises(prev => ({ ...prev, [exercise.id]: exercise }))
- setFormData(prev => ({
- ...prev,
- exercises: [...prev.exercises, {
- exercise_id: exercise.id,
- notes: '',
- rest_seconds: settings.rest_seconds_default ?? 90,
- sets: [{ set_number: 1, target_reps: 0, target_weight: 0 }],
- }],
- }))
- setShowPicker(false)
- setError('')
- }
-
- const removeExercise = (index: number) => {
- setFormData(prev => ({ ...prev, exercises: prev.exercises.filter((_, i) => i !== index) }))
- }
-
- const addSet = (exIdx: number) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- const count = exercises[exIdx].sets.length + 1
- exercises[exIdx].sets.push({ set_number: count, target_reps: 0, target_weight: 0 })
- return { ...prev, exercises }
- })
- }
-
- const removeSet = (exIdx: number, setIdx: number) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- exercises[exIdx].sets = exercises[exIdx].sets.filter((_, i) => i !== setIdx)
- return { ...prev, exercises }
- })
- }
-
- const updateSet = (exIdx: number, setIdx: number, field: string, value: any) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- ;(exercises[exIdx].sets[setIdx] as any)[field] = Number(value) || 0
- return { ...prev, exercises }
- })
- }
-
- const setExRest = (exIdx: number, secs: number) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- exercises[exIdx] = { ...exercises[exIdx], rest_seconds: secs }
- return { ...prev, exercises }
- })
- }
+ const cacheExercise = (ex: types.Exercise) => setPickerExercises(prev => ({ ...prev, [ex.id]: ex }))
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name.trim()) { setError('Program name required'); return }
- if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }
+ if (formData.days.length === 0) { setError('Add at least one day'); return }
+ const hasAnyExercise = hasWorkoutExercises(formData.days)
+ if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }
setLoading(true)
try {
const payload = {
- ...formData,
- exercises: formData.exercises.map(ex => ({
- ...ex,
- sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),
+ name: formData.name,
+ notes: formData.notes,
+ days: formData.days.map(d => ({
+ ...d,
+ exercises: d.exercises.map(ex => ({
+ ...ex,
+ sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),
+ })),
})),
}
await programAPI.create(payload)
@@ -105,8 +55,8 @@ export default function AddProgram() {
}
}
- const selectedIds = formData.exercises.map(e => e.exercise_id)
- const totalSets = formData.exercises.reduce((sum, ex) => sum + ex.sets.length, 0)
+ const totalExercises = formData.days.reduce((s, d) => s + d.exercises.length, 0)
+ const totalSets = formData.days.reduce((s, d) => s + d.exercises.reduce((s2, ex) => s2 + ex.sets.length, 0), 0)
return (
<div className="space-y-6 animate-slide-up pb-10">
@@ -116,7 +66,9 @@ export default function AddProgram() {
</button>
<div>
<h1 className="font-display font-bold text-2xl text-tx-primary">New Program</h1>
- <p className="text-xs text-tx-muted">{formData.exercises.length} exercises • {totalSets} sets</p>
+ <p className="text-xs text-tx-muted">
+ {formData.days.length} day{formData.days.length === 1 ? '' : 's'} • {totalExercises} exercise{totalExercises === 1 ? '' : 's'} • {totalSets} set{totalSets === 1 ? '' : 's'}
+ </p>
</div>
</div>
@@ -156,10 +108,14 @@ export default function AddProgram() {
/>
</div>
- {formData.exercises.length > 0 && (
- <div className="grid grid-cols-2 gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg">
+ {formData.days.length > 0 && (
+ <div className="grid grid-cols-3 gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg">
<div className="text-center">
- <div className="text-sm font-bold text-brand-500">{formData.exercises.length}</div>
+ <div className="text-sm font-bold text-brand-500">{formData.days.length}</div>
+ <div className="text-xs text-tx-muted">Days</div>
+ </div>
+ <div className="text-center">
+ <div className="text-sm font-bold text-brand-500">{totalExercises}</div>
<div className="text-xs text-tx-muted">Exercises</div>
</div>
<div className="text-center">
@@ -170,107 +126,19 @@ export default function AddProgram() {
)}
<div>
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-2">
- <Zap className="w-4 h-4 text-brand-500" />
- <label className="label">Exercises</label>
- <span className="text-xs text-tx-muted">(required)</span>
- </div>
- <button
- type="button"
- onClick={() => setShowPicker(true)}
- className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 text-white rounded-lg transition-colors font-medium"
- >
- <Plus className="w-3.5 h-3.5" />
- Add Exercise
- </button>
- </div>
-
- {showPicker && (
- <ExercisePicker
- selectedIds={selectedIds}
- onSelect={addExercise}
- onClose={() => setShowPicker(false)}
- />
- )}
-
- <div className="space-y-4">
- {formData.exercises.map((workoutEx, exIdx) => {
- const exercise = pickerExercises[workoutEx.exercise_id]
- return (
- <div key={exIdx} className="p-4 bg-surface-muted/30 border border-surface-border rounded-lg">
- <div className="flex items-start justify-between mb-4">
- <div className="flex-1">
- <div className="flex items-center gap-2 mb-1">
- <div className="w-6 h-6 rounded bg-brand-500/20 flex items-center justify-center flex-shrink-0">
- <span className="text-xs font-bold text-brand-500">{exIdx + 1}</span>
- </div>
- <p className="font-semibold text-tx-primary">{exercise?.name}</p>
- </div>
- <p className="text-xs text-tx-muted ml-8">{exercise?.muscle_group} • {exercise?.equipment}</p>
- </div>
- <button type="button" onClick={() => removeExercise(exIdx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
- <Trash2 className="w-4 h-4 text-error-400" />
- </button>
- </div>
-
- <div className="mb-4">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Notes</label>
- <input
- type="text"
- value={workoutEx.notes}
- onChange={e => {
- const exercises = [...formData.exercises]
- exercises[exIdx].notes = e.target.value
- setFormData(prev => ({ ...prev, exercises }))
- }}
- placeholder="e.g., Focus on controlled eccentric"
- className="input text-sm"
- />
- </div>
-
- <div className="mb-4">
- <div className="flex items-center gap-1.5 mb-1">
- <Timer className="w-3.5 h-3.5 text-brand-500" />
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Rest between sets</label>
- </div>
- <RestPicker value={workoutEx.rest_seconds ?? 90} onChange={secs => setExRest(exIdx, secs)} />
- </div>
-
- <div className="space-y-2 mb-3">
- <div className="flex items-center justify-between">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Target Sets</label>
- <span className="text-xs text-tx-muted">{workoutEx.sets.length} sets</span>
- </div>
- {workoutEx.sets.map((set, setIdx) => (
- <div key={setIdx} className="flex gap-2 items-end bg-surface-raised/40 p-3 rounded-lg border border-surface-border/50">
- <div className="flex-shrink-0 w-12">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">Set</label>
- <div className="text-sm font-bold text-tx-primary bg-surface-muted px-2 py-1 rounded text-center">{set.set_number}</div>
- </div>
- <div className="flex-1 min-w-0">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Reps</label>
- <input type="number" inputMode="numeric" value={set.target_reps || ''} onChange={e => updateSet(exIdx, setIdx, 'target_reps', e.target.value)} placeholder="10" className="input text-sm w-full" min="0" />
- </div>
- <div className="flex-1 min-w-0">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Weight</label>
- <WeightInput stepper={false} size="sm" value={set.target_weight ? String(set.target_weight) : ''} onChange={v => updateSet(exIdx, setIdx, 'target_weight', v)} unit={wUnit} placeholder="135" />
- </div>
- <button type="button" onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
- <Trash2 className="w-4 h-4 text-error-400" />
- </button>
- </div>
- ))}
- </div>
-
- <button type="button" onClick={() => addSet(exIdx)} className="flex items-center gap-1 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors">
- <Plus className="w-3.5 h-3.5" />
- Add Set
- </button>
- </div>
- )
- })}
+ <div className="flex items-center gap-2 mb-3">
+ <CalendarDays className="w-4 h-4 text-brand-500" />
+ <label className="label">Days</label>
+ <span className="text-xs text-tx-muted">(required — repeats in this order)</span>
</div>
+ <ProgramDaysEditor
+ days={formData.days}
+ onChange={days => setFormData(prev => ({ ...prev, days }))}
+ pickerExercises={pickerExercises}
+ onCacheExercise={cacheExercise}
+ wUnit={wUnit}
+ restSecondsDefault={settings.rest_seconds_default ?? 90}
+ />
</div>
<div className="flex gap-3 pt-2">
diff --git a/web/src/pages/AddWorkout.tsx b/web/src/pages/AddWorkout.tsx
index ecbb8b6..74c63db 100644
--- a/web/src/pages/AddWorkout.tsx
+++ b/web/src/pages/AddWorkout.tsx
@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Plus, ArrowLeft, Trash2, AlertCircle, Dumbbell, Clock, FileText, Zap, Target, Gauge, BookOpen, CalendarDays, Timer } from 'lucide-react'
import { workoutAPI } from '../services/api'
-import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'
+import { useSettingsStore, weightShort, displayToLbs, lbsToDisplay } from '../stores/settings'
import WeightInput from '../components/WeightInput'
import ExercisePicker from '../components/ExercisePicker'
import ProgramPicker from '../components/ProgramPicker'
@@ -30,11 +30,11 @@ export default function AddWorkout() {
useEffect(() => { if (error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error])
- const loadFromProgram = (program: types.Program) => {
+ const loadFromProgram = (_program: types.Program, day: types.ProgramDay) => {
const newMap: Record<number, types.Exercise> = { ...pickerExercises }
- const newExercises = (program.exercises || []).map(ex => {
+ const newExercises = (day.exercises || []).map(ex => {
newMap[ex.exercise_id] = ex.exercise
- return { exercise_id: ex.exercise_id, notes: ex.notes || '', rest_seconds: ex.rest_seconds ?? (settings.rest_seconds_default ?? 90), sets: (ex.sets || []).map(s => ({ set_number: s.set_number, reps: s.target_reps, weight: s.target_weight })) }
+ return { exercise_id: ex.exercise_id, notes: ex.notes || '', rest_seconds: ex.rest_seconds ?? (settings.rest_seconds_default ?? 90), sets: (ex.sets || []).map(s => ({ set_number: s.set_number, reps: s.target_reps, weight: lbsToDisplay(s.target_weight, settings.weight_unit) })) }
})
setPickerExercises(newMap)
setFormData(prev => ({ ...prev, exercises: newExercises }))
diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx
index a673e40..5d1c6b4 100644
--- a/web/src/pages/Dashboard.tsx
+++ b/web/src/pages/Dashboard.tsx
@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react'
import { format, startOfWeek, isSameDay, eachDayOfInterval, endOfWeek, subWeeks } from 'date-fns'
import {
- Dumbbell, Flame, ArrowRight, Beef,
+ Dumbbell, Flame, ArrowRight, Beef, BookOpen,
AlertCircle, Play, Timer, TrendingUp, Scale, Activity, Plus,
} from 'lucide-react'
import {
@@ -12,13 +12,14 @@ import Loading from '../components/Loading'
import SectionHeader from '../components/ui/SectionHeader'
import PeriodSelector from '../components/PeriodSelector'
import QuickWeighInSheet from '../components/QuickWeighInSheet'
-import { workoutAPI, foodAPI, weightAPI, userAPI } from '../services/api'
+import { workoutAPI, foodAPI, weightAPI, userAPI, programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import { useAuthStore } from '../stores/auth'
import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'
import { useNavigate, Link } from 'react-router-dom'
import * as types from '../types'
import { muscleColor } from '../utils/exerciseUtils'
+import { activeSessionExercisesForDay, dayLabel, isDayStartable, sessionNameForDay, todaysDay } from '../utils/programUtils'
const TODAY = new Date()
@@ -126,11 +127,12 @@ const TOOLTIP_STYLE = {
export default function Dashboard() {
const navigate = useNavigate()
- const { session } = useWorkoutSession()
+ const { session, startSession } = useWorkoutSession()
const { user } = useAuthStore()
const { settings: storedSettings } = useSettingsStore()
const [workouts, setWorkouts] = useState<types.Workout[]>([])
+ const [programs, setPrograms] = useState<types.Program[]>([])
const [food, setFood] = useState<types.DailyStats>(DEFAULT_FOOD)
const [weightLogs, setWeightLogs] = useState<types.WeightLog[]>([])
const [weightStats, setWeightStats] = useState<types.WeightStats | null>(null)
@@ -144,13 +146,15 @@ export default function Dashboard() {
useEffect(() => {
Promise.all([
workoutAPI.list({ limit: 84 }), // 12 weeks × 7 days max
+ programAPI.list({ limit: 100 }).catch(() => []), // backend's max — Up Next must see every program
foodAPI.stats(format(TODAY, 'yyyy-MM-dd')).catch(() => DEFAULT_FOOD),
weightAPI.list({ limit: 14 }).catch(() => []),
weightAPI.stats().catch(() => null),
userAPI.getSettings().catch(() => DEFAULT_SETTINGS),
])
- .then(([ws, fs, wl, wst, s]) => {
+ .then(([ws, ps, fs, wl, wst, s]) => {
setWorkouts(ws || [])
+ setPrograms(ps || [])
setFood(fs || DEFAULT_FOOD)
setWeightLogs(wl || [])
setWeightStats(wst)
@@ -176,6 +180,24 @@ export default function Dashboard() {
const weekWorkouts = workouts.filter(w => new Date(w.started_at) >= weekStart)
const lastWorkout = workouts[0] ?? null
+ // "Up next": the first (most recently created) program whose due day is a
+ // startable workout day. Surfaces today's routine workout without opening the
+ // Programs page — a routine that never shows on the dashboard never gets started.
+ const upNext = (() => {
+ for (const p of programs) {
+ const day = todaysDay(p)
+ if (isDayStartable(day)) return { program: p, day }
+ }
+ return null
+ })()
+
+ const startUpNext = () => {
+ if (!upNext) return
+ const { program, day } = upNext
+ startSession(sessionNameForDay(program, day), activeSessionExercisesForDay(day), program.id, day.id)
+ navigate('/workout/active')
+ }
+
// Volume chart: slice by selected period, oldest→newest
const chartData = workouts.slice(0, Number(volumePeriod)).reverse().map(w => ({
date: format(new Date(w.started_at), 'M/d'),
@@ -290,6 +312,51 @@ export default function Dashboard() {
</Link>
)}
+ {/* ── Up next — today's due day on the current routine. Hidden while a
+ session is live: the banner above already owns that slot. Thumbnail is
+ the due day's own first exercise (same pattern as Programs.tsx's card
+ and the Last-workout list below), not a generic program glyph — makes
+ the card read as "this is what you're about to do." Start is icon-only,
+ not a labeled pill: the header above already has a text "Start"/"Resume"
+ button, and two buttons both saying "Start" stacked this close reads as
+ noise, not choice. The Start button stays a SIBLING of the link, not a
+ child: an <a> may not contain interactive descendants (invalid HTML, and
+ screen readers fold the button into the link's accessible name). ── */}
+ {!session && upNext && (
+ <div className="flex items-center gap-3 card p-3 hover:bg-surface-muted/40 transition-colors">
+ <Link
+ to={`/programs/${upNext.program.id}`}
+ aria-label={`View ${upNext.program.name} routine`}
+ className="flex items-center gap-3 flex-1 min-w-0"
+ >
+ {upNext.day.exercises?.[0]?.exercise?.image_url ? (
+ <img
+ src={upNext.day.exercises[0].exercise.image_url}
+ alt=""
+ className="w-10 h-10 rounded-xl object-cover flex-shrink-0 bg-surface-muted"
+ onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
+ />
+ ) : (
+ <div className="w-10 h-10 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
+ <BookOpen className="w-5 h-5 text-brand-500" />
+ </div>
+ )}
+ <div className="flex-1 min-w-0">
+ <p className="text-[10px] text-tx-muted uppercase tracking-wide font-medium truncate">Up next · {upNext.program.name}</p>
+ <p className="text-sm font-semibold text-tx-primary truncate mt-0.5">{dayLabel(upNext.day, upNext.day.order_index)}</p>
+ <p className="text-xs text-tx-muted mt-0.5">{(upNext.day.exercises ?? []).length} exercise{(upNext.day.exercises ?? []).length === 1 ? '' : 's'}</p>
+ </div>
+ </Link>
+ <button
+ onClick={startUpNext}
+ aria-label={`Start ${dayLabel(upNext.day, upNext.day.order_index)}`}
+ className="flex items-center justify-center w-9 h-9 bg-brand-500 hover:bg-brand-600 text-white rounded-xl transition-colors flex-shrink-0"
+ >
+ <Play className="w-4 h-4" />
+ </button>
+ </div>
+ )}
+
{/* ── KPI strip ──────────────────────────────── */}
<div className="grid grid-cols-3 gap-2">
<div className="card p-3 flex flex-col gap-1.5">
@@ -536,12 +603,18 @@ export default function Dashboard() {
<div className="card p-4 flex flex-col items-center justify-center min-h-36 gap-2">
<Dumbbell className="w-7 h-7 text-tx-muted opacity-40" />
<p className="text-sm text-tx-muted">No workouts logged yet</p>
- <button
- onClick={() => navigate('/workout/start')}
- className="text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors mt-1"
- >
- Start your first workout →
- </button>
+ {/* Suppressed when the Up Next card is already showing above — that
+ card is its own "start something" CTA; a second "start your first
+ workout" link right under it is the redundant-buttons clutter this
+ card exists to avoid. */}
+ {!upNext && (
+ <button
+ onClick={() => navigate('/workout/start')}
+ className="text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors mt-1"
+ >
+ Start your first workout →
+ </button>
+ )}
</div>
)}
diff --git a/web/src/pages/EditProgram.tsx b/web/src/pages/EditProgram.tsx
index 469c456..b64a79d 100644
--- a/web/src/pages/EditProgram.tsx
+++ b/web/src/pages/EditProgram.tsx
@@ -1,22 +1,17 @@
import { useState, useEffect } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
-import { Plus, ArrowLeft, Trash2, AlertCircle, BookOpen, FileText, Zap, Target, Dumbbell, Timer } from 'lucide-react'
+import { ArrowLeft, AlertCircle, BookOpen, FileText, Dumbbell, CalendarDays } from 'lucide-react'
import { programAPI } from '../services/api'
import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'
-import WeightInput from '../components/WeightInput'
-import ExercisePicker from '../components/ExercisePicker'
-import RestPicker from '../components/RestPicker'
+import { hasWorkoutExercises } from '../utils/programUtils'
+import ProgramDaysEditor from '../components/programs/ProgramDaysEditor'
import * as types from '../types'
+import type { DayDraft } from '../components/programs/types'
interface ProgramFormData {
name: string
notes: string
- exercises: {
- exercise_id: number
- notes: string
- rest_seconds: number
- sets: { set_number: number; target_reps: number; target_weight: number }[]
- }[]
+ days: DayDraft[]
}
export default function EditProgram() {
@@ -24,12 +19,11 @@ export default function EditProgram() {
const navigate = useNavigate()
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
- const [showPicker, setShowPicker] = useState(false)
const [loading, setLoading] = useState(false)
const [initialLoading, setInitialLoading] = useState(true)
const [error, setError] = useState('')
const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})
- const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', exercises: [] })
+ const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })
useEffect(() => { if (error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error])
@@ -39,19 +33,25 @@ export default function EditProgram() {
programAPI.get(programId)
.then(p => {
const map: Record<number, types.Exercise> = {}
- ;(p.exercises || []).forEach(ex => { map[ex.exercise_id] = ex.exercise })
+ ;(p.days || []).forEach(d => (d.exercises || []).forEach(ex => { map[ex.exercise_id] = ex.exercise }))
setPickerExercises(map)
setFormData({
name: p.name,
notes: p.notes || '',
- exercises: (p.exercises || []).map(ex => ({
- exercise_id: ex.exercise_id,
- notes: ex.notes || '',
- rest_seconds: ex.rest_seconds ?? (settings.rest_seconds_default ?? 90),
- sets: (ex.sets || []).map(s => ({
- set_number: s.set_number,
- target_reps: s.target_reps,
- target_weight: lbsToDisplay(s.target_weight, settings.weight_unit),
+ days: (p.days || []).map((d, i) => ({
+ id: d.id,
+ order_index: d.order_index ?? i,
+ is_rest_day: d.is_rest_day,
+ name: d.name || '',
+ exercises: (d.exercises || []).map(ex => ({
+ exercise_id: ex.exercise_id,
+ notes: ex.notes || '',
+ rest_seconds: ex.rest_seconds ?? (settings.rest_seconds_default ?? 90),
+ sets: (ex.sets || []).map(s => ({
+ set_number: s.set_number,
+ target_reps: s.target_reps,
+ target_weight: lbsToDisplay(s.target_weight, settings.weight_unit),
+ })),
})),
})),
})
@@ -60,63 +60,30 @@ export default function EditProgram() {
.finally(() => setInitialLoading(false))
}, [id])
- const addExercise = (exercise: types.Exercise) => {
- setPickerExercises(prev => ({ ...prev, [exercise.id]: exercise }))
- setFormData(prev => ({
- ...prev,
- exercises: [...prev.exercises, { exercise_id: exercise.id, notes: '', rest_seconds: settings.rest_seconds_default ?? 90, sets: [{ set_number: 1, target_reps: 0, target_weight: 0 }] }],
- }))
- setShowPicker(false)
- setError('')
- }
-
- const removeExercise = (index: number) => {
- setFormData(prev => ({ ...prev, exercises: prev.exercises.filter((_, i) => i !== index) }))
- }
-
- const addSet = (exIdx: number) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- exercises[exIdx].sets.push({ set_number: exercises[exIdx].sets.length + 1, target_reps: 0, target_weight: 0 })
- return { ...prev, exercises }
- })
- }
-
- const removeSet = (exIdx: number, setIdx: number) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- exercises[exIdx].sets = exercises[exIdx].sets.filter((_, i) => i !== setIdx)
- return { ...prev, exercises }
- })
- }
-
- const updateSet = (exIdx: number, setIdx: number, field: string, value: any) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- ;(exercises[exIdx].sets[setIdx] as any)[field] = Number(value) || 0
- return { ...prev, exercises }
- })
- }
-
- const setExRest = (exIdx: number, secs: number) => {
- setFormData(prev => {
- const exercises = [...prev.exercises]
- exercises[exIdx] = { ...exercises[exIdx], rest_seconds: secs }
- return { ...prev, exercises }
- })
- }
+ const cacheExercise = (ex: types.Exercise) => setPickerExercises(prev => ({ ...prev, [ex.id]: ex }))
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name.trim()) { setError('Program name required'); return }
- if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }
+ if (formData.days.length === 0) { setError('Add at least one day'); return }
+ const hasAnyExercise = hasWorkoutExercises(formData.days)
+ if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }
setLoading(true)
try {
const payload = {
- ...formData,
- exercises: formData.exercises.map(ex => ({
- ...ex,
- sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),
+ name: formData.name,
+ notes: formData.notes,
+ // Declares this client round-trips day ids: without it, deleting every
+ // existing day and adding only new (id-less) ones is indistinguishable
+ // from a legacy payload and the server would positionally re-attribute
+ // the deleted days' workout history to the new days.
+ day_ids_known: true,
+ days: formData.days.map(d => ({
+ ...d,
+ exercises: d.exercises.map(ex => ({
+ ...ex,
+ sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),
+ })),
})),
}
await programAPI.update(Number(id), payload)
@@ -136,8 +103,8 @@ export default function EditProgram() {
)
}
- const selectedIds = formData.exercises.map(e => e.exercise_id)
- const totalSets = formData.exercises.reduce((sum, ex) => sum + ex.sets.length, 0)
+ const totalExercises = formData.days.reduce((s, d) => s + d.exercises.length, 0)
+ const totalSets = formData.days.reduce((s, d) => s + d.exercises.reduce((s2, ex) => s2 + ex.sets.length, 0), 0)
return (
<div className="space-y-6 animate-slide-up pb-10">
@@ -147,7 +114,9 @@ export default function EditProgram() {
</button>
<div>
<h1 className="font-display font-bold text-2xl text-tx-primary">Edit Program</h1>
- <p className="text-xs text-tx-muted">{formData.exercises.length} exercises • {totalSets} sets</p>
+ <p className="text-xs text-tx-muted">
+ {formData.days.length} day{formData.days.length === 1 ? '' : 's'} • {totalExercises} exercise{totalExercises === 1 ? '' : 's'} • {totalSets} set{totalSets === 1 ? '' : 's'}
+ </p>
</div>
</div>
@@ -175,10 +144,14 @@ export default function EditProgram() {
<textarea value={formData.notes} onChange={e => setFormData(prev => ({ ...prev, notes: e.target.value }))} className="input mt-1 min-h-16 resize-none" />
</div>
- {formData.exercises.length > 0 && (
- <div className="grid grid-cols-2 gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg">
+ {formData.days.length > 0 && (
+ <div className="grid grid-cols-3 gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg">
+ <div className="text-center">
+ <div className="text-sm font-bold text-brand-500">{formData.days.length}</div>
+ <div className="text-xs text-tx-muted">Days</div>
+ </div>
<div className="text-center">
- <div className="text-sm font-bold text-brand-500">{formData.exercises.length}</div>
+ <div className="text-sm font-bold text-brand-500">{totalExercises}</div>
<div className="text-xs text-tx-muted">Exercises</div>
</div>
<div className="text-center">
@@ -189,88 +162,19 @@ export default function EditProgram() {
)}
<div>
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-2">
- <Zap className="w-4 h-4 text-brand-500" />
- <label className="label">Exercises</label>
- </div>
- <button type="button" onClick={() => setShowPicker(true)} className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 text-white rounded-lg transition-colors font-medium">
- <Plus className="w-3.5 h-3.5" />
- Add Exercise
- </button>
- </div>
-
- {showPicker && (
- <ExercisePicker selectedIds={selectedIds} onSelect={addExercise} onClose={() => setShowPicker(false)} />
- )}
-
- <div className="space-y-4">
- {formData.exercises.map((workoutEx, exIdx) => {
- const exercise = pickerExercises[workoutEx.exercise_id]
- return (
- <div key={exIdx} className="p-4 bg-surface-muted/30 border border-surface-border rounded-lg">
- <div className="flex items-start justify-between mb-4">
- <div className="flex-1">
- <div className="flex items-center gap-2 mb-1">
- <div className="w-6 h-6 rounded bg-brand-500/20 flex items-center justify-center flex-shrink-0">
- <span className="text-xs font-bold text-brand-500">{exIdx + 1}</span>
- </div>
- <p className="font-semibold text-tx-primary">{exercise?.name}</p>
- </div>
- <p className="text-xs text-tx-muted ml-8">{exercise?.muscle_group} • {exercise?.equipment}</p>
- </div>
- <button type="button" onClick={() => removeExercise(exIdx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
- <Trash2 className="w-4 h-4 text-error-400" />
- </button>
- </div>
-
- <div className="mb-4">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Notes</label>
- <input type="text" value={workoutEx.notes} onChange={e => { const ex = [...formData.exercises]; ex[exIdx].notes = e.target.value; setFormData(p => ({ ...p, exercises: ex })) }} placeholder="e.g., Focus on controlled eccentric" className="input text-sm" />
- </div>
-
- <div className="mb-4">
- <div className="flex items-center gap-1.5 mb-1">
- <Timer className="w-3.5 h-3.5 text-brand-500" />
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Rest between sets</label>
- </div>
- <RestPicker value={workoutEx.rest_seconds ?? 90} onChange={secs => setExRest(exIdx, secs)} />
- </div>
-
- <div className="space-y-2 mb-3">
- <div className="flex items-center justify-between">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Target Sets</label>
- <span className="text-xs text-tx-muted">{workoutEx.sets.length} sets</span>
- </div>
- {workoutEx.sets.map((set, setIdx) => (
- <div key={setIdx} className="flex gap-2 items-end bg-surface-raised/40 p-3 rounded-lg border border-surface-border/50">
- <div className="flex-shrink-0 w-12">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">Set</label>
- <div className="text-sm font-bold text-tx-primary bg-surface-muted px-2 py-1 rounded text-center">{set.set_number}</div>
- </div>
- <div className="flex-1 min-w-0">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Reps</label>
- <input type="number" inputMode="numeric" value={set.target_reps || ''} onChange={e => updateSet(exIdx, setIdx, 'target_reps', e.target.value)} placeholder="10" className="input text-sm w-full" min="0" />
- </div>
- <div className="flex-1 min-w-0">
- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Weight</label>
- <WeightInput stepper={false} size="sm" value={set.target_weight ? String(set.target_weight) : ''} onChange={v => updateSet(exIdx, setIdx, 'target_weight', v)} unit={wUnit} placeholder="135" />
- </div>
- <button type="button" onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
- <Trash2 className="w-4 h-4 text-error-400" />
- </button>
- </div>
- ))}
- </div>
-
- <button type="button" onClick={() => addSet(exIdx)} className="flex items-center gap-1 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors">
- <Plus className="w-3.5 h-3.5" />
- Add Set
- </button>
- </div>
- )
- })}
+ <div className="flex items-center gap-2 mb-3">
+ <CalendarDays className="w-4 h-4 text-brand-500" />
+ <label className="label">Days</label>
+ <span className="text-xs text-tx-muted">(repeats in this order)</span>
</div>
+ <ProgramDaysEditor
+ days={formData.days}
+ onChange={days => setFormData(prev => ({ ...prev, days }))}
+ pickerExercises={pickerExercises}
+ onCacheExercise={cacheExercise}
+ wUnit={wUnit}
+ restSecondsDefault={settings.rest_seconds_default ?? 90}
+ />
</div>
<div className="flex gap-3 pt-2">
diff --git a/web/src/pages/ProgramDetail.tsx b/web/src/pages/ProgramDetail.tsx
index 19ae13f..44364fa 100644
--- a/web/src/pages/ProgramDetail.tsx
+++ b/web/src/pages/ProgramDetail.tsx
@@ -4,13 +4,14 @@ import { useParams, useNavigate, Link } from 'react-router-dom'
import { format } from 'date-fns'
import {
ArrowLeft, BookOpen, Dumbbell, Edit2, Trash2, Play, AlertCircle, Loader, ChevronRight, Pause, TimerOff,
- Award, TrendingUp, Check, X, ChevronDown, ChevronUp,
+ Award, TrendingUp, Check, X, ChevronDown, ChevronUp, Moon, CalendarDays,
} from 'lucide-react'
import { programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import { useSettingsStore, weightShort, displayWeight } from '../stores/settings'
import * as types from '../types'
import { muscleColor } from '../utils/exerciseUtils'
+import { allExercises, activeSessionExercisesForDay, dayLabel, sessionNameForDay } from '../utils/programUtils'
// Rows shown before the review banner collapses behind a "Show all" toggle (#40).
const SUGGESTION_CAP = 3
@@ -30,6 +31,7 @@ export default function ProgramDetail() {
const [deleting, setDeleting] = useState(false)
const [resolving, setResolving] = useState(false)
const [showAllSuggestions, setShowAllSuggestions] = useState(false)
+ const [selectedDayIdx, setSelectedDayIdx] = useState(0)
// Accept (apply → target) or dismiss staged auto-progression suggestions (#40),
// then refresh from the returned program.
@@ -51,6 +53,7 @@ export default function ProgramDetail() {
try {
const data = await programAPI.get(Number(id))
setProgram(data)
+ setSelectedDayIdx(data.current_day_index || 0)
} catch (err: any) {
setError(err.message || 'Failed to load program')
} finally {
@@ -60,25 +63,14 @@ export default function ProgramDetail() {
load()
}, [id])
+ const days = program?.days ?? []
+ const selectedDay = days[selectedDayIdx]
+
const handleStart = () => {
- if (!program) return
+ if (!program || !selectedDay || selectedDay.is_rest_day) return
if (session) { navigate('/workout/start'); return }
- const exercises: types.ActiveSessionExercise[] = (program.exercises || []).map(ex => ({
- exercise_id: ex.exercise_id,
- exercise: ex.exercise,
- notes: ex.notes || '',
- rest_seconds: ex.rest_seconds,
- sets: (ex.sets || []).map(s => ({
- set_number: s.set_number,
- target_reps: s.target_reps,
- target_weight: s.target_weight,
- actual_reps: s.target_reps,
- actual_weight: s.target_weight,
- completed: false,
- program_set_id: s.id, // link for routine target auto-progression (#40)
- })),
- }))
- startSession(program.name, exercises, program.id)
+ const exercises = activeSessionExercisesForDay(selectedDay)
+ startSession(sessionNameForDay(program, selectedDay), exercises, program.id, selectedDay.id)
navigate('/workout/active')
}
@@ -116,14 +108,15 @@ export default function ProgramDetail() {
)
}
- const exs = program.exercises ?? []
- const totalSets = exs.reduce((s, ex) => s + (ex.sets ?? []).length, 0)
+ const allExs = allExercises(program)
+ const totalSets = allExs.reduce((s, ex) => s + (ex.sets ?? []).length, 0)
- // Pending auto-progression suggestions (#40), flattened for the review banner. A
+ // Pending auto-progression suggestions (#40), flattened across every day so a
+ // suggestion is never hidden behind whichever day tab happens to be selected. A
// suggestion exists when suggested_reps is set. Show the FULL reps×weight on both
// sides when both changed (a heavier set can also drop the rep target — the user
// must see that before approving), else the single changed dimension.
- const suggestions = exs.flatMap(ex =>
+ const suggestions = allExs.flatMap(ex =>
(ex.sets ?? [])
.filter(s => s.id != null && s.suggested_reps != null)
.map(s => {
@@ -165,7 +158,9 @@ export default function ProgramDetail() {
<div className="flex items-center gap-1">
<button
onClick={handleStart}
- className="flex items-center gap-1.5 px-3 py-2 bg-brand-500 hover:bg-brand-600 text-white text-xs font-semibold rounded-xl transition-colors"
+ disabled={!selectedDay || selectedDay.is_rest_day}
+ title={selectedDay?.is_rest_day ? 'Rest day — nothing to start' : undefined}
+ className="flex items-center gap-1.5 px-3 py-2 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 disabled:hover:bg-brand-500 text-white text-xs font-semibold rounded-xl transition-colors"
>
<Play className="w-3.5 h-3.5" /> Start Workout
</button>
@@ -278,9 +273,9 @@ export default function ProgramDetail() {
{/* Header */}
<div className="card p-4">
<div className="flex items-start gap-3">
- {exs[0]?.exercise?.image_url ? (
+ {allExs[0]?.exercise?.image_url ? (
<img
- src={exs[0].exercise.image_url}
+ src={allExs[0].exercise.image_url}
alt=""
className="w-14 h-14 rounded-xl object-cover flex-shrink-0 bg-surface-muted"
onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
@@ -293,18 +288,25 @@ export default function ProgramDetail() {
<div className="min-w-0 flex-1">
<h1 className="font-display font-bold text-xl text-tx-primary leading-tight">{program.name}</h1>
<p className="text-sm text-tx-muted mt-0.5">
- Created {format(new Date(program.created_at), 'MMMM d, yyyy')}
+ Created {format(new Date(program.created_at), 'MMM d, yyyy')}
</p>
</div>
</div>
- <div className="grid grid-cols-2 gap-3 mt-4 pt-4 border-t border-surface-border">
+ <div className="grid grid-cols-3 gap-3 mt-4 pt-4 border-t border-surface-border">
<div className="text-center">
+ <div className="flex items-center justify-center gap-1 mb-0.5">
+ <CalendarDays className="w-3.5 h-3.5 text-tx-muted" />
+ <p className="text-xs text-tx-muted">Cycle</p>
+ </div>
+ <p className="text-lg font-bold text-tx-primary tabular-nums">{days.length || '—'}</p>
+ </div>
+ <div className="text-center border-l border-surface-border">
<div className="flex items-center justify-center gap-1 mb-0.5">
<Dumbbell className="w-3.5 h-3.5 text-tx-muted" />
<p className="text-xs text-tx-muted">Exercises</p>
</div>
- <p className="text-lg font-bold text-tx-primary tabular-nums">{exs.length}</p>
+ <p className="text-lg font-bold text-tx-primary tabular-nums">{allExs.length}</p>
</div>
<div className="text-center border-l border-surface-border">
<div className="flex items-center justify-center gap-1 mb-0.5">
@@ -320,77 +322,136 @@ export default function ProgramDetail() {
)}
</div>
- {/* Exercises */}
- {!restOn && (
- <div className="flex items-center gap-1.5 text-[11px] text-tx-muted px-1">
- <TimerOff className="w-3.5 h-3.5" /> Rest timer is off — turn it on in Settings
+ {/* Day strip — the program's repeating cycle, in order. Selecting a day shows
+ its exercises below; it does NOT change which day is "due" (that's server-
+ computed from logged workouts). */}
+ {days.length === 0 ? (
+ <div className="card p-6 text-center">
+ <CalendarDays className="w-8 h-8 text-tx-muted mx-auto mb-2 opacity-50" />
+ <p className="text-sm text-tx-muted">No days yet</p>
+ <button
+ onClick={() => navigate(`/programs/${program.id}/edit`)}
+ className="mt-2 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors"
+ >
+ Add a day →
+ </button>
+ </div>
+ ) : (
+ <div className="flex gap-2 overflow-x-auto pb-1 -mx-1 px-1">
+ {days.map((day, i) => {
+ const isSelected = i === selectedDayIdx
+ const isToday = i === program.current_day_index
+ return (
+ <button
+ key={day.id ?? i}
+ onClick={() => setSelectedDayIdx(i)}
+ className={`flex-shrink-0 flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border transition-colors whitespace-nowrap ${
+ isSelected
+ ? 'bg-brand-500 border-brand-500 text-white'
+ : day.is_rest_day
+ ? 'bg-surface-muted/40 border-surface-border text-tx-muted'
+ : 'bg-surface-raised border-surface-border text-tx-secondary hover:bg-surface-muted'
+ }`}
+ >
+ {day.is_rest_day ? <Moon className="w-3.5 h-3.5" /> : <Dumbbell className="w-3.5 h-3.5" />}
+ {dayLabel(day, day.order_index)}
+ {/* Textual chip, not a bare dot — a color-only marker isn't
+ distinguishable by shape/text (a11y) and reads as decoration. */}
+ {isToday && (
+ <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded-full ${isSelected ? 'bg-white/20 text-white' : 'bg-brand-500/15 text-brand-400'}`}>TODAY</span>
+ )}
+ </button>
+ )
+ })}
</div>
)}
- <div className="space-y-2">
- {exs.map((ex) => {
- const sets = ex.sets ?? []
- const maxTargetLbs = sets.length > 0 ? Math.max(...sets.map(s => s.target_weight || 0)) : 0
- const maxTarget = displayWeight(maxTargetLbs, wUnit)
- return (
- <button
- key={ex.id}
- onClick={() => navigate(`/exercises/${ex.exercise_id}`)}
- className="card w-full overflow-hidden text-left active:scale-[0.99] transition-transform"
- >
- <div className="flex items-center gap-3 p-4">
- {ex.exercise?.image_url ? (
- <img
- src={ex.exercise.image_url}
- alt=""
- className="w-11 h-11 rounded-xl object-cover flex-shrink-0 bg-surface-muted"
- onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
- />
- ) : (
- <div className="w-11 h-11 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
- <Dumbbell className="w-5 h-5 text-brand-500" strokeWidth={2} />
- </div>
- )}
- <div className="flex-1 min-w-0">
- <p className="text-sm font-semibold text-tx-primary truncate">{ex.exercise?.name}</p>
- <div className="flex items-center gap-2 mt-0.5">
- {ex.exercise?.muscle_group && (
- <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0 ${muscleColor(ex.exercise.muscle_group)}`}>
- {ex.exercise.muscle_group}
- </span>
- )}
- <span className="text-xs text-tx-muted truncate">{sets.length} sets{maxTarget > 0 ? ` · target ${maxTarget} ${wUnit}` : ''}</span>
- </div>
- </div>
- <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />
+ {/* Selected day's exercises */}
+ {selectedDay?.is_rest_day ? (
+ <div className="card p-8 text-center">
+ <Moon className="w-8 h-8 text-tx-muted mx-auto mb-2 opacity-60" />
+ <p className="text-sm font-medium text-tx-primary">Rest Day</p>
+ <p className="text-xs text-tx-muted mt-1">No exercises scheduled — recover and come back stronger.</p>
+ </div>
+ ) : selectedDay ? (
+ <>
+ {!restOn && (
+ <div className="flex items-center gap-1.5 text-[11px] text-tx-muted px-1">
+ <TimerOff className="w-3.5 h-3.5" /> Rest timer is off — turn it on in Settings
+ </div>
+ )}
+ <div className="space-y-2">
+ {(selectedDay.exercises ?? []).length === 0 ? (
+ <div className="card p-6 text-center">
+ <Dumbbell className="w-8 h-8 text-tx-muted mx-auto mb-2 opacity-50" />
+ <p className="text-sm text-tx-muted">No exercises on this day yet</p>
</div>
+ ) : (selectedDay.exercises ?? []).map((ex) => {
+ const sets = ex.sets ?? []
+ const maxTargetLbs = sets.length > 0 ? Math.max(...sets.map(s => s.target_weight || 0)) : 0
+ const maxTarget = displayWeight(maxTargetLbs, wUnit)
- {sets.length > 0 && (
- <div className="flex items-center gap-2 px-4 pb-4 border-t border-surface-border/50 pt-3">
- <div className="flex flex-wrap gap-1.5 flex-1 min-w-0">
- {sets.map((set, i) => {
- const isBest = set.target_weight === maxTargetLbs && maxTargetLbs > 0
- const hasSuggestion = set.suggested_reps != null
- return (
- <div key={i} className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold tabular-nums leading-none ${
- hasSuggestion ? 'bg-warning-500/10 text-tx-secondary ring-1 ring-warning-500/40'
- : isBest ? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25' : 'bg-surface-raised text-tx-secondary'
- }`}>
- {set.target_reps > 0 ? set.target_reps : '—'} × {set.target_weight > 0 ? `${displayWeight(set.target_weight, wUnit)} ${wUnit}` : 'BW'}
- </div>
- )
- })}
+ return (
+ <button
+ key={ex.id}
+ onClick={() => navigate(`/exercises/${ex.exercise_id}`)}
+ className="card w-full overflow-hidden text-left active:scale-[0.99] transition-transform"
+ >
+ <div className="flex items-center gap-3 p-4">
+ {ex.exercise?.image_url ? (
+ <img
+ src={ex.exercise.image_url}
+ alt=""
+ className="w-11 h-11 rounded-xl object-cover flex-shrink-0 bg-surface-muted"
+ onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
+ />
+ ) : (
+ <div className="w-11 h-11 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
+ <Dumbbell className="w-5 h-5 text-brand-500" strokeWidth={2} />
+ </div>
+ )}
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-semibold text-tx-primary truncate">{ex.exercise?.name}</p>
+ <div className="flex items-center gap-2 mt-0.5">
+ {ex.exercise?.muscle_group && (
+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0 ${muscleColor(ex.exercise.muscle_group)}`}>
+ {ex.exercise.muscle_group}
+ </span>
+ )}
+ <span className="text-xs text-tx-muted truncate">{sets.length} set{sets.length === 1 ? '' : 's'}{maxTarget > 0 ? ` · target ${maxTarget} ${wUnit}` : ''}</span>
+ </div>
+ </div>
+ <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />
</div>
- {restOn && (ex.rest_seconds === 0
- ? <span className="text-xs text-tx-muted flex-shrink-0">No rest</span>
- : <span className="flex items-center gap-1 text-xs text-tx-muted flex-shrink-0"><Pause className="w-3.5 h-3.5" />{restLabel(ex.rest_seconds ?? 90)}</span>
+
+ {sets.length > 0 && (
+ <div className="flex items-center gap-2 px-4 pb-4 border-t border-surface-border/50 pt-3">
+ <div className="flex flex-wrap gap-1.5 flex-1 min-w-0">
+ {sets.map((set, i) => {
+ const isBest = set.target_weight === maxTargetLbs && maxTargetLbs > 0
+ const hasSuggestion = set.suggested_reps != null
+ return (
+ <div key={i} className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold tabular-nums leading-none ${
+ hasSuggestion ? 'bg-warning-500/10 text-tx-secondary ring-1 ring-warning-500/40'
+ : isBest ? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25' : 'bg-surface-raised text-tx-secondary'
+ }`}>
+ {set.target_reps > 0 ? set.target_reps : '—'} × {set.target_weight > 0 ? `${displayWeight(set.target_weight, wUnit)} ${wUnit}` : 'BW'}
+ </div>
+ )
+ })}
+ </div>
+ {restOn && (ex.rest_seconds === 0
+ ? <span className="text-xs text-tx-muted flex-shrink-0">No rest</span>
+ : <span className="flex items-center gap-1 text-xs text-tx-muted flex-shrink-0"><Pause className="w-3.5 h-3.5" />{restLabel(ex.rest_seconds ?? 90)}</span>
+ )}
+ </div>
)}
- </div>
- )}
- </button>
- )
- })}
- </div>
+ </button>
+ )
+ })}
+ </div>
+ </>
+ ) : null}
</div>
)
}
diff --git a/web/src/pages/Programs.tsx b/web/src/pages/Programs.tsx
index 14c0b3a..5766e0e 100644
--- a/web/src/pages/Programs.tsx
+++ b/web/src/pages/Programs.tsx
@@ -1,7 +1,7 @@
import { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { format } from 'date-fns'
-import { BookOpen, Plus, Dumbbell, Edit2, Trash2, Search, Play, ChevronRight, MoreVertical } from 'lucide-react'
+import { BookOpen, Plus, Dumbbell, Edit2, Trash2, Search, Play, ChevronRight, MoreVertical, Moon, Sun } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import Loading from '../components/Loading'
import PageHeader from '../components/ui/PageHeader'
@@ -10,7 +10,10 @@ import { programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import * as types from '../types'
-import { muscleColor } from '../utils/exerciseUtils'
+import {
+ todaysDay, dayLabel, isDayStartable, programExerciseCount, programSetCount, sessionNameForDay,
+ activeSessionExercisesForDay, allExercises,
+} from '../utils/programUtils'
function ProgramCard({
program,
@@ -37,25 +40,19 @@ function ProgramCard({
return () => document.removeEventListener('mousedown', handler)
}, [])
+ const today = todaysDay(program)
+ const canQuickStart = isDayStartable(today)
+
const handleStart = (e: React.MouseEvent) => {
e.stopPropagation()
if (session) { navigate('/workout/start'); return }
- const exercises: types.ActiveSessionExercise[] = (program.exercises || []).map(ex => ({
- exercise_id: ex.exercise_id,
- exercise: ex.exercise,
- notes: ex.notes || '',
- rest_seconds: ex.rest_seconds,
- sets: (ex.sets || []).map(s => ({
- set_number: s.set_number,
- target_reps: s.target_reps,
- target_weight: s.target_weight,
- actual_reps: s.target_reps,
- actual_weight: s.target_weight,
- completed: false,
- program_set_id: s.id, // link for routine target auto-progression (#40)
- })),
- }))
- startSession(program.name, exercises, program.id)
+ if (!canQuickStart) {
+ // Today's slot is a rest day (or the program has no days yet) — nothing to
+ // quick-start; send them to the program to pick a day manually.
+ navigate(`/programs/${program.id}`)
+ return
+ }
+ startSession(sessionNameForDay(program, today), activeSessionExercisesForDay(today), program.id, today.id)
navigate('/workout/active')
}
const [confirming, setConfirming] = useState(false)
@@ -106,7 +103,10 @@ function ProgramCard({
)
}
- const totalSets = program.exercises?.reduce((s, e) => s + (e.sets?.length || 0), 0) || 0
+ const totalSets = programSetCount(program)
+ const totalExercises = programExerciseCount(program)
+ const thumbnail = allExercises(program)[0]?.exercise?.image_url
+ const dayCount = program.days?.length ?? 0
return (
<div className="card group active:scale-[0.99] transition-transform">
@@ -115,9 +115,9 @@ function ProgramCard({
className="flex-1 flex items-center gap-3 min-w-0 text-left"
onClick={() => navigate(`/programs/${program.id}`)}
>
- {program.exercises?.[0]?.exercise?.image_url ? (
+ {thumbnail ? (
<img
- src={program.exercises[0].exercise.image_url}
+ src={thumbnail}
alt=""
className="w-11 h-11 rounded-xl object-cover flex-shrink-0 bg-surface-muted"
onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
@@ -131,9 +131,21 @@ function ProgramCard({
<p className="text-sm font-semibold text-tx-primary truncate">{program.name}</p>
<p className="text-xs text-tx-muted mt-0.5 whitespace-nowrap">{format(new Date(program.created_at), 'MMM d, yyyy')}</p>
<div className="flex items-center gap-x-2 mt-0.5 min-w-0 overflow-hidden">
- <span className="text-xs text-tx-muted whitespace-nowrap">{program.exercises?.length || 0} exercises</span>
+ <span className="text-xs text-tx-muted whitespace-nowrap">{totalExercises} exercise{totalExercises === 1 ? '' : 's'}</span>
<span className="text-tx-muted/40 text-xs">·</span>
- <span className="text-xs text-tx-muted whitespace-nowrap">{totalSets} sets</span>
+ <span className="text-xs text-tx-muted whitespace-nowrap">{totalSets} set{totalSets === 1 ? '' : 's'}</span>
+ {dayCount > 1 && today && (
+ <>
+ <span className="text-tx-muted/40 text-xs">·</span>
+ {today.is_rest_day ? (
+ <span className="text-xs text-tx-muted whitespace-nowrap flex items-center gap-1"><Moon className="w-3 h-3" />Rest today</span>
+ ) : (
+ // Sun, not Dumbbell — Dumbbell already means "exercises" earlier on
+ // this same row; Sun/Moon reads as a natural due/rest pair instead.
+ <span className="text-xs text-brand-400 font-medium whitespace-nowrap flex items-center gap-1"><Sun className="w-3 h-3" />Today: {dayLabel(today, today.order_index)}</span>
+ )}
+ </>
+ )}
</div>
</div>
<ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />
@@ -170,7 +182,7 @@ function ProgramCard({
<div className="w-8 h-8 rounded-xl bg-brand-500/10 flex items-center justify-center flex-shrink-0">
<Play className="w-4 h-4 text-brand-500" />
</div>
- Start Workout
+ {canQuickStart ? 'Start Workout' : 'View Program'}
</button>
<div className="mx-4 border-t border-surface-border/30" />
<button
@@ -209,7 +221,7 @@ function ProgramCard({
{/* Desktop hover icons */}
<div className="hidden sm:flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
<button onClick={handleStart}
- className="p-2 hover:bg-brand-500/10 rounded-lg transition-colors" title="Start workout">
+ className="p-2 hover:bg-brand-500/10 rounded-lg transition-colors" title={canQuickStart ? 'Start workout' : 'Rest day today — open program'}>
<Play className="w-4 h-4 text-brand-500" />
</button>
<button onClick={e => { e.stopPropagation(); onEdit(program.id) }}
@@ -259,7 +271,7 @@ export default function Programs() {
<div className="grid grid-cols-2 gap-3">
{[
{ label: 'Total', value: programs.length.toString(), unit: 'programs', icon: BookOpen },
- { label: 'Avg Exercises', value: programs.length > 0 ? Math.round(programs.reduce((s, p) => s + (p.exercises?.length || 0), 0) / programs.length).toString() : '0', unit: 'per program', icon: Dumbbell },
+ { label: 'Avg Exercises', value: programs.length > 0 ? Math.round(programs.reduce((s, p) => s + programExerciseCount(p), 0) / programs.length).toString() : '0', unit: 'per program', icon: Dumbbell },
].map(s => (
<div key={s.label} className="card p-4">
<div className="flex items-center gap-1.5 mb-2">
diff --git a/web/src/pages/StartWorkout.tsx b/web/src/pages/StartWorkout.tsx
index 3f105fb..0501623 100644
--- a/web/src/pages/StartWorkout.tsx
+++ b/web/src/pages/StartWorkout.tsx
@@ -1,24 +1,15 @@
-import { useState, useEffect } from 'react'
+import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
-import { ArrowLeft, Zap, BookOpen, ChevronRight, Dumbbell, AlertCircle, Play, Timer, Trash2 } from 'lucide-react'
-import { programAPI } from '../services/api'
+import { ArrowLeft, Zap, BookOpen, ChevronRight, Play, Timer, Trash2 } from 'lucide-react'
import { useWorkoutSession } from '../stores/workoutSession'
+import ProgramPicker from '../components/ProgramPicker'
+import { activeSessionExercisesForDay, sessionNameForDay } from '../utils/programUtils'
import * as types from '../types'
export default function StartWorkout() {
const navigate = useNavigate()
const { session, startSession, cancelSession } = useWorkoutSession()
- const [programs, setPrograms] = useState<types.Program[]>([])
- const [loading, setLoading] = useState(false)
- const [error, setError] = useState('')
-
- useEffect(() => {
- setLoading(true)
- programAPI.list()
- .then(data => setPrograms(data || []))
- .catch(() => setError('Failed to load programs'))
- .finally(() => setLoading(false))
- }, [])
+ const [showProgramPicker, setShowProgramPicker] = useState(false)
const startQuick = () => {
const name = `Workout — ${new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`
@@ -26,23 +17,9 @@ export default function StartWorkout() {
navigate('/workout/active')
}
- const startFromProgram = (program: types.Program) => {
- const exercises: types.ActiveSessionExercise[] = (program.exercises || []).map(ex => ({
- exercise_id: ex.exercise_id,
- exercise: ex.exercise,
- notes: ex.notes || '',
- rest_seconds: ex.rest_seconds,
- sets: (ex.sets || []).map(s => ({
- set_number: s.set_number,
- target_reps: s.target_reps,
- target_weight: s.target_weight,
- actual_reps: s.target_reps,
- actual_weight: s.target_weight,
- completed: false,
- program_set_id: s.id, // link for routine target auto-progression (#40)
- })),
- }))
- startSession(program.name, exercises, program.id)
+ const startFromProgram = (program: types.Program, day: types.ProgramDay) => {
+ startSession(sessionNameForDay(program, day), activeSessionExercisesForDay(day), program.id, day.id)
+ setShowProgramPicker(false)
navigate('/workout/active')
}
@@ -103,58 +80,23 @@ export default function StartWorkout() {
</button>
{/* Programs section */}
- <div>
- <div className="flex items-center gap-2 mb-3">
- <BookOpen className="w-4 h-4 text-brand-500" />
- <h2 className="font-semibold text-tx-primary">Start from Program</h2>
+ <button
+ onClick={() => setShowProgramPicker(true)}
+ className="w-full flex items-center gap-4 p-5 bg-surface-muted/50 border border-surface-border hover:bg-surface-muted rounded-2xl transition-colors group"
+ >
+ <div className="w-12 h-12 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center flex-shrink-0">
+ <BookOpen className="w-6 h-6 text-brand-500" />
</div>
+ <div className="text-left flex-1">
+ <p className="font-semibold text-tx-primary text-lg">Start from Program</p>
+ <p className="text-sm text-tx-muted mt-0.5">Load a saved routine's day</p>
+ </div>
+ <ChevronRight className="w-5 h-5 text-tx-muted opacity-0 group-hover:opacity-100 transition-opacity" />
+ </button>
- {error && (
- <div className="alert-error mb-3">
- <AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{error}</span>
- </div>
- )}
-
- {loading ? (
- <div className="flex items-center justify-center py-12 text-tx-muted text-sm">
- <Dumbbell className="w-5 h-5 mr-2 animate-pulse text-brand-500" />
- Loading programs…
- </div>
- ) : programs.length === 0 ? (
- <div className="text-center py-10 card">
- <BookOpen className="w-8 h-8 text-tx-muted mx-auto mb-2 opacity-50" />
- <p className="text-sm text-tx-muted">No programs yet</p>
- <button
- onClick={() => navigate('/programs/new')}
- className="mt-3 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors"
- >
- Create your first program →
- </button>
- </div>
- ) : (
- <div className="space-y-2">
- {programs.map(p => (
- <button
- key={p.id}
- onClick={() => startFromProgram(p)}
- className="w-full flex items-center gap-3 p-4 card hover:bg-surface-muted transition-colors text-left group"
- >
- <div className="w-10 h-10 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">
- <BookOpen className="w-5 h-5 text-brand-500" />
- </div>
- <div className="flex-1 min-w-0">
- <p className="font-semibold text-tx-primary truncate">{p.name}</p>
- <p className="text-xs text-tx-muted mt-0.5">
- {p.exercises?.length || 0} exercises
- </p>
- </div>
- <Play className="w-4 h-4 text-brand-500 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
- </button>
- ))}
- </div>
- )}
- </div>
+ {showProgramPicker && (
+ <ProgramPicker onSelect={startFromProgram} onClose={() => setShowProgramPicker(false)} />
+ )}
</div>
)
}
diff --git a/web/src/stores/workoutSession.test.ts b/web/src/stores/workoutSession.test.ts
index 437dff0..ba1b595 100644
--- a/web/src/stores/workoutSession.test.ts
+++ b/web/src/stores/workoutSession.test.ts
@@ -128,9 +128,11 @@ describe('workoutSession buildPayload — auto-progression (#40)', () => {
{ set_number: 2, target_reps: 5, target_weight: 100, actual_reps: 6, actual_weight: 100, completed: true, program_set_id: 12 },
],
},
- ] as any, 7)
+ ] as any, 7, 3)
const payload = store().buildPayload()
expect(payload.program_id).toBe(7)
+ // WHICH cycle day this session was — the server's due-day tracker keys off it.
+ expect(payload.program_day_id).toBe(3)
expect(payload.exercises[0].sets[0].program_set_id).toBe(11)
expect(payload.exercises[0].sets[1].program_set_id).toBe(12)
// logged actuals are what the backend compares against the target
@@ -145,6 +147,7 @@ describe('workoutSession buildPayload — auto-progression (#40)', () => {
] as any)
const payload = store().buildPayload()
expect(payload.program_id).toBeNull()
+ expect(payload.program_day_id).toBeNull()
expect(payload.exercises[0].sets[0].program_set_id).toBeNull()
})
diff --git a/web/src/stores/workoutSession.ts b/web/src/stores/workoutSession.ts
index 6be7e6e..9f8fee5 100644
--- a/web/src/stores/workoutSession.ts
+++ b/web/src/stores/workoutSession.ts
@@ -44,7 +44,7 @@ interface WorkoutSessionStore {
gymPhase: GymPhase
gymExIdx: number
gymSetIdx: number
- startSession: (name: string, exercises: types.ActiveSessionExercise[], programId?: number) => void
+ startSession: (name: string, exercises: types.ActiveSessionExercise[], programId?: number, programDayId?: number) => void
updateSet: (exIdx: number, setIdx: number, field: 'actual_reps' | 'actual_weight', val: number) => void
completeSet: (exIdx: number, setIdx: number) => void
updateExerciseNotes: (exIdx: number, notes: string) => void
@@ -130,12 +130,13 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
set({ gymPhase, gymExIdx, gymSetIdx })
},
- startSession: (name, exercises, programId) => {
+ startSession: (name, exercises, programId, programDayId) => {
const session: types.ActiveSession = {
name,
started_at: new Date().toISOString(),
exercises,
program_id: programId,
+ program_day_id: programDayId,
}
saveLocal(session)
set({ session })
@@ -255,6 +256,7 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
duration: durationSec,
started_at: session.started_at,
program_id: session.program_id ?? null, // lets the backend auto-progress the routine (#40)
+ program_day_id: session.program_day_id ?? null, // which cycle day this was — drives the due-day tracker
exercises: session.exercises.map(ex => ({
exercise_id: ex.exercise_id,
notes: ex.notes,
diff --git a/web/src/types.ts b/web/src/types.ts
index 422930f..c48184a 100644
--- a/web/src/types.ts
+++ b/web/src/types.ts
@@ -169,6 +169,7 @@ export interface ProgramSet {
export interface ProgramExercise {
id?: number
+ program_day_id?: number
exercise_id: number
order_index?: number
notes?: string
@@ -177,12 +178,29 @@ export interface ProgramExercise {
sets: ProgramSet[]
}
+// One slot in a program's repeating cycle: a workout day (its own ordered
+// exercises/sets) or a rest day (exercises always empty). Days repeat in
+// order_index order once the sequence is exhausted — NOT locked to a calendar week
+// (a 6-day cycle repeats every 6 days regardless of which weekday it lands on).
+export interface ProgramDay {
+ id?: number
+ program_id?: number
+ order_index: number
+ is_rest_day: boolean
+ name?: string
+ exercises: ProgramExercise[]
+}
+
export interface Program {
id: number
name: string
notes?: string
created_at: string
- exercises: ProgramExercise[]
+ days: ProgramDay[]
+ // Which entry of `days` is due today — computed server-side from WHICH day the
+ // most recent program workout was logged against: the next workout day after it
+ // in cycle order (rest days are never due; wraps to the first workout day).
+ current_day_index: number
}
export interface ActiveSessionSet {
@@ -207,6 +225,10 @@ export interface ActiveSessionExercise {
export interface ActiveSession {
program_id?: number
+ // WHICH day of the program's cycle this session was started under — persisted on
+ // the created workout so the server's due-day tracker follows what was actually
+ // logged (not a blind count). Absent for freestyle sessions.
+ program_day_id?: number
name: string
started_at: string
exercises: ActiveSessionExercise[]
diff --git a/web/src/utils/programUtils.test.ts b/web/src/utils/programUtils.test.ts
new file mode 100644
index 0000000..68e1116
--- /dev/null
+++ b/web/src/utils/programUtils.test.ts
@@ -0,0 +1,175 @@
+// Mirrors packages/shared/src/utils/programUtils.test.ts — the web keeps its own
+// copy of programUtils until it migrates to @lyftr/shared, so it keeps its own test.
+import { describe, it, expect } from 'vitest'
+import {
+ activeSessionExercisesForDay, allExercises, dayLabel, hasWorkoutExercises, isDayStartable, programExerciseCount,
+ programSetCount, sessionNameForDay, todaysDay, workoutDays,
+} from './programUtils'
+import * as types from '../types'
+
+const day = (overrides: Partial<types.ProgramDay> = {}): types.ProgramDay => ({
+ id: 1,
+ order_index: 0,
+ is_rest_day: false,
+ name: '',
+ exercises: [],
+ ...overrides,
+})
+
+const program = (days: types.ProgramDay[], currentDayIndex = 0): types.Program => ({
+ id: 1,
+ name: 'PPL',
+ created_at: '2026-01-01T00:00:00Z',
+ days,
+ current_day_index: currentDayIndex,
+})
+
+describe('workoutDays', () => {
+ it('filters rest days out and preserves order', () => {
+ const p = program([
+ day({ id: 1, order_index: 0 }),
+ day({ id: 2, order_index: 1, is_rest_day: true }),
+ day({ id: 3, order_index: 2 }),
+ ])
+ expect(workoutDays(p).map(d => d.id)).toEqual([1, 3])
+ })
+
+ it('tolerates a program with undefined days', () => {
+ expect(workoutDays({ ...program([]), days: undefined as any })).toEqual([])
+ })
+})
+
+describe('todaysDay', () => {
+ it('returns the entry at current_day_index', () => {
+ const p = program([day({ id: 1, order_index: 0 }), day({ id: 2, order_index: 1 })], 1)
+ expect(todaysDay(p)?.id).toBe(2)
+ })
+
+ it('is undefined for a program with no days', () => {
+ expect(todaysDay(program([]))).toBeUndefined()
+ })
+})
+
+describe('dayLabel', () => {
+ it('prefers the trimmed custom name', () => {
+ expect(dayLabel(day({ name: ' Push Day ' }), 0)).toBe('Push Day')
+ })
+
+ it('falls back to Rest Day / Day N+1 — idx must be order_index, not a filtered loop index', () => {
+ expect(dayLabel(day({ is_rest_day: true }), 3)).toBe('Rest Day')
+ // A workout day at cycle position 2 must label "Day 3" even when it's e.g. the
+ // second entry of a rest-filtered list (the classic loop-index bug).
+ expect(dayLabel(day({ order_index: 2 }), 2)).toBe('Day 3')
+ })
+
+ it('whitespace-only names fall back too', () => {
+ expect(dayLabel(day({ name: ' ' }), 0)).toBe('Day 1')
+ })
+})
+
+describe('counts + flattening', () => {
+ const ex = (id: number, sets: number) => ({
+ exercise_id: id,
+ exercise: { id, name: `E${id}` } as any,
+ sets: Array.from({ length: sets }, (_, i) => ({ set_number: i + 1, target_reps: 5, target_weight: 100 })),
+ })
+ const p = program([
+ day({ id: 1, order_index: 0, exercises: [ex(1, 2), ex(2, 3)] as any }),
+ day({ id: 2, order_index: 1, is_rest_day: true }),
+ day({ id: 3, order_index: 2, exercises: [ex(3, 1)] as any }),
+ ])
+
+ it('programExerciseCount sums across all days', () => {
+ expect(programExerciseCount(p)).toBe(3)
+ })
+
+ it('programSetCount sums sets across all days', () => {
+ expect(programSetCount(p)).toBe(6)
+ })
+
+ it('allExercises flattens in day order (so a suggestion is visible whatever day is selected)', () => {
+ expect(allExercises(p).map(e => e.exercise_id)).toEqual([1, 2, 3])
+ })
+})
+
+describe('activeSessionExercisesForDay', () => {
+ it('seeds actuals from targets and links each set to its program_set_id (#40)', () => {
+ const d = day({
+ exercises: [{
+ exercise_id: 9,
+ exercise: { id: 9, name: 'Bench' } as any,
+ notes: 'slow eccentric',
+ rest_seconds: 120,
+ sets: [{ id: 41, set_number: 1, target_reps: 5, target_weight: 135 }],
+ }] as any,
+ })
+ const [ex] = activeSessionExercisesForDay(d)
+ expect(ex.exercise_id).toBe(9)
+ expect(ex.notes).toBe('slow eccentric')
+ expect(ex.rest_seconds).toBe(120)
+ expect(ex.sets[0]).toEqual({
+ set_number: 1,
+ target_reps: 5,
+ target_weight: 135,
+ actual_reps: 5,
+ actual_weight: 135,
+ completed: false,
+ program_set_id: 41,
+ })
+ })
+
+ it('a rest/empty day yields no exercises', () => {
+ expect(activeSessionExercisesForDay(day({ is_rest_day: true }))).toEqual([])
+ expect(activeSessionExercisesForDay({ ...day(), exercises: undefined as any })).toEqual([])
+ })
+})
+
+describe('isDayStartable', () => {
+ const withExercise = day({ exercises: [{ exercise_id: 1 }] as any })
+
+ it('true only for a workout day with at least one exercise', () => {
+ expect(isDayStartable(withExercise)).toBe(true)
+ })
+
+ it('false for a rest day, even with exercises somehow present', () => {
+ expect(isDayStartable({ ...withExercise, is_rest_day: true })).toBe(false)
+ })
+
+ it('false for a workout day with no exercises', () => {
+ expect(isDayStartable(day({ exercises: [] }))).toBe(false)
+ })
+
+ it('false for undefined (as todaysDay() returns for a dayless program)', () => {
+ expect(isDayStartable(undefined)).toBe(false)
+ })
+})
+
+describe('sessionNameForDay', () => {
+ it('is just the program name for a single-day program', () => {
+ const p = program([day({ order_index: 0 })])
+ expect(sessionNameForDay(p, p.days![0])).toBe('PPL')
+ })
+
+ it('appends the day label once a program has more than one day', () => {
+ const d = day({ order_index: 1, name: 'Pull A' })
+ const p = program([day({ order_index: 0 }), d])
+ expect(sessionNameForDay(p, d)).toBe('PPL — Pull A')
+ })
+})
+
+describe('hasWorkoutExercises', () => {
+ it('true when some workout day has an exercise', () => {
+ expect(hasWorkoutExercises([
+ day({ exercises: [] }),
+ day({ exercises: [{ exercise_id: 1 }] as any }),
+ ])).toBe(true)
+ })
+
+ it('false when every day is empty or a rest day', () => {
+ expect(hasWorkoutExercises([day({ exercises: [] }), day({ is_rest_day: true, exercises: [{ exercise_id: 1 }] as any })])).toBe(false)
+ })
+
+ it('false for an empty list', () => {
+ expect(hasWorkoutExercises([])).toBe(false)
+ })
+})
diff --git a/web/src/utils/programUtils.ts b/web/src/utils/programUtils.ts
new file mode 100644
index 0000000..71df654
--- /dev/null
+++ b/web/src/utils/programUtils.ts
@@ -0,0 +1,67 @@
+import * as types from '../types'
+
+// Workout days only — rest days carry no exercises and can't be "started" or
+// "loaded". Used everywhere a picker needs to offer a day to load/start from.
+export const workoutDays = (program: types.Program): types.ProgramDay[] =>
+ (program.days ?? []).filter(d => !d.is_rest_day)
+
+// The Day due today per the cycle, computed server-side as
+// Program.current_day_index: the next workout day after the most recently logged
+// one (rest days are never due). Undefined for a program with no days yet.
+export const todaysDay = (program: types.Program): types.ProgramDay | undefined =>
+ (program.days ?? [])[program.current_day_index]
+
+export const dayLabel = (day: types.ProgramDay, idx: number): string =>
+ day.name?.trim() || (day.is_rest_day ? 'Rest Day' : `Day ${idx + 1}`)
+
+// A day is startable/loadable only if it's a workout day that actually has
+// exercises — a rest day or an empty day is never "due" and can't seed a session.
+// Takes `undefined` directly (as `todaysDay()` returns) so callers don't need a
+// separate null-guard before calling this.
+export const isDayStartable = (day: types.ProgramDay | undefined): day is types.ProgramDay =>
+ !!day && !day.is_rest_day && (day.exercises ?? []).length > 0
+
+// Display name for a session started from a specific program day: the plain
+// program name for a single-day program (nothing to disambiguate), or
+// "Program — Day Label" once there's more than one day to distinguish between.
+export const sessionNameForDay = (program: types.Program, day: types.ProgramDay): string =>
+ (program.days?.length ?? 0) > 1 ? `${program.name} — ${dayLabel(day, day.order_index)}` : program.name
+
+// Flattened, so the auto-progression review banner on ProgramDetail surfaces a
+// suggestion no matter which day it landed on (the user may not have that day
+// selected/expanded when it lands).
+export const allExercises = (program: types.Program): types.ProgramExercise[] =>
+ (program.days ?? []).flatMap(d => d.exercises ?? [])
+
+// Whether any day in a list has at least one exercise on a workout (non-rest)
+// day — the "is there anything to actually run" check the create/edit-program
+// forms use before letting the user submit. Structural rather than typed to
+// ProgramDay so it also accepts the day/exercise editors' local draft shape.
+export const hasWorkoutExercises = (days: { is_rest_day: boolean; exercises: unknown[] }[]): boolean =>
+ days.some(d => !d.is_rest_day && d.exercises.length > 0)
+
+export const programExerciseCount = (program: types.Program): number => allExercises(program).length
+
+export const programSetCount = (program: types.Program): number =>
+ allExercises(program).reduce((s, e) => s + (e.sets ?? []).length, 0)
+
+// Builds a live ActiveSession's exercises from one program Day, linking each set
+// back to its ProgramSet id so finishing the workout can auto-progress that
+// specific target (#40).
+export function activeSessionExercisesForDay(day: types.ProgramDay): types.ActiveSessionExercise[] {
+ return (day.exercises ?? []).map(ex => ({
+ exercise_id: ex.exercise_id,
+ exercise: ex.exercise,
+ notes: ex.notes || '',
+ rest_seconds: ex.rest_seconds,
+ sets: (ex.sets ?? []).map(s => ({
+ set_number: s.set_number,
+ target_reps: s.target_reps,
+ target_weight: s.target_weight,
+ actual_reps: s.target_reps,
+ actual_weight: s.target_weight,
+ completed: false,
+ program_set_id: s.id,
+ })),
+ }))
+}
diff --git a/web/vite.config.ts b/web/vite.config.ts
index c32c02e..38d20a0 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -14,7 +14,7 @@ export default defineConfig(({ command }) => ({
host: true, // expose to LAN for mobile testing
proxy: {
'/api': {
- target: 'http://localhost:3000',
+ target: process.env.VITE_PROXY_TARGET || 'http://localhost:3000',
changeOrigin: true,
},
},