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.

Add workout/program detail pages, E2E test infra, settings store, and nav improvements

Cawlumma0a12d7e3649
diff --git a/.gitignore b/.gitignore
index fdfe3bb..78a4919 100644
--- a/.gitignore
+++ b/.gitignore
@@ -50,3 +50,6 @@ temp/
# design docs (keep screenshots for README)
docs/*.md
docs/*.txt
+
+# Local Claude context
+CLAUDE.md
diff --git a/backend/controllers/programs.go b/backend/controllers/programs.go
index e3a5253..5ce69c9 100644
--- a/backend/controllers/programs.go
+++ b/backend/controllers/programs.go
@@ -86,7 +86,11 @@ func CreateProgram(c *gin.Context) {
utils.InternalError(c)
return
}
- pid, _ := res.LastInsertId()
+ pid, err := res.LastInsertId()
+ if err != nil {
+ utils.InternalError(c)
+ return
+ }
for i, ex := range req.Exercises {
exRes, err := tx.Exec(
@@ -97,7 +101,11 @@ func CreateProgram(c *gin.Context) {
utils.InternalError(c)
return
}
- peid, _ := exRes.LastInsertId()
+ peid, err := exRes.LastInsertId()
+ if err != nil {
+ utils.InternalError(c)
+ return
+ }
for j, s := range ex.Sets {
sn := s.SetNumber
if sn == 0 {
@@ -186,7 +194,11 @@ func UpdateProgram(c *gin.Context) {
utils.InternalError(c)
return
}
- peid, _ := exRes.LastInsertId()
+ peid, err := exRes.LastInsertId()
+ if err != nil {
+ utils.InternalError(c)
+ return
+ }
for j, s := range ex.Sets {
sn := s.SetNumber
if sn == 0 {
diff --git a/backend/controllers/programs_test.go b/backend/controllers/programs_test.go
new file mode 100644
index 0000000..fc406e9
--- /dev/null
+++ b/backend/controllers/programs_test.go
@@ -0,0 +1,220 @@
+package controllers
+
+import (
+ "fmt"
+ "net/http"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/db"
+)
+
+func TestListPrograms_empty(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ c, w := newContext(uid, http.MethodGet, "/api/v1/programs", nil)
+ ListPrograms(c)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ resp := decodeResponse(t, w)
+ data, ok := resp["data"].([]any)
+ if !ok {
+ t.Fatalf("expected data array, got %T", resp["data"])
+ }
+ if len(data) != 0 {
+ t.Fatalf("expected empty list, got %d items", len(data))
+ }
+}
+
+func TestCreateProgram_success(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ body := map[string]any{
+ "name": "PPL Program",
+ "notes": "Push Pull Legs 6 days",
+ "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},
+ },
+ },
+ },
+ }
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/programs", body)
+ CreateProgram(c)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ resp := decodeResponse(t, w)
+ data := resp["data"].(map[string]any)
+ if data["name"] != "PPL Program" {
+ t.Errorf("expected name 'PPL Program', got %v", data["name"])
+ }
+ exercises, ok := data["exercises"].([]any)
+ if !ok {
+ t.Fatalf("exercises field missing or wrong type: %T = %v", data["exercises"], data["exercises"])
+ }
+ if len(exercises) != 1 {
+ t.Fatalf("expected 1 exercise, got %d", len(exercises))
+ }
+ ex0 := exercises[0].(map[string]any)
+ sets, ok := ex0["sets"].([]any)
+ if !ok {
+ t.Fatalf("sets field missing or wrong type: %T = %v", ex0["sets"], ex0["sets"])
+ }
+ if len(sets) != 3 {
+ t.Errorf("expected 3 sets, got %d", len(sets))
+ }
+}
+
+func TestCreateProgram_missingName(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ body := map[string]any{
+ "name": "",
+ "exercises": []map[string]any{},
+ }
+ c, w := newContext(uid, http.MethodPost, "/api/v1/programs", body)
+ CreateProgram(c)
+
+ if w.Code == http.StatusCreated {
+ t.Fatal("expected error for empty name, got 201")
+ }
+}
+
+func TestGetProgram_ownershipEnforced(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ res, _ := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, "[email protected]", "x")
+ otherUID, _ := res.LastInsertId()
+
+ res2, _ := db.DB.Exec(`INSERT INTO programs (user_id, name) VALUES (?, ?)`, otherUID, "Private Program")
+ pid, _ := res2.LastInsertId()
+
+ c, w := newContext(uid, http.MethodGet, "/api/v1/programs/"+fmt.Sprint(pid), nil)
+ setParam(c, "id", fmt.Sprint(pid))
+ GetProgram(c)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 for cross-user access, got %d", w.Code)
+ }
+}
+
+func TestDeleteProgram_ownershipEnforced(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ res, _ := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, "[email protected]", "x")
+ otherUID, _ := res.LastInsertId()
+
+ res2, _ := db.DB.Exec(`INSERT INTO programs (user_id, name) VALUES (?, ?)`, otherUID, "Protected Program")
+ pid, _ := res2.LastInsertId()
+
+ c, w := newContext(uid, http.MethodDelete, "/api/v1/programs/"+fmt.Sprint(pid), nil)
+ setParam(c, "id", fmt.Sprint(pid))
+ DeleteProgram(c)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 for cross-user delete, got %d", w.Code)
+ }
+
+ var count int
+ db.DB.QueryRow(`SELECT COUNT(*) FROM programs WHERE id = ?`, pid).Scan(&count)
+ if count != 1 {
+ t.Fatal("program was deleted by wrong user")
+ }
+}
+
+func TestUpdateProgram_replacesExercises(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ // Create second exercise
+ 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
+ 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)
+ peid, _ := exRes.LastInsertId()
+ db.DB.Exec(`INSERT INTO program_sets (program_exercise_id, set_number, target_reps) VALUES (?, 1, 5)`, peid)
+
+ // Update with different exercise
+ body := map[string]any{
+ "name": "Updated Program",
+ "notes": "",
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID2,
+ "notes": "",
+ "sets": []map[string]any{{"set_number": 1, "target_reps": 8, "target_weight": 60.0}},
+ },
+ },
+ }
+
+ c, w := newContext(uid, http.MethodPut, "/api/v1/programs/"+fmt.Sprint(pid), body)
+ setParam(c, "id", fmt.Sprint(pid))
+ UpdateProgram(c)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Old exercise should be gone
+ var count int
+ db.DB.QueryRow(`SELECT COUNT(*) FROM program_exercises WHERE program_id = ? AND exercise_id = ?`, pid, exID).Scan(&count)
+ if count != 0 {
+ t.Error("old exercise not removed after update")
+ }
+
+ // New exercise should exist
+ db.DB.QueryRow(`SELECT COUNT(*) FROM program_exercises WHERE program_id = ? AND exercise_id = ?`, pid, exID2).Scan(&count)
+ if count != 1 {
+ t.Error("new exercise not found after update")
+ }
+}
+
+func TestCreateProgram_setNumberNormalized(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ // Send set_number: 0 — backend should normalize to 1
+ body := map[string]any{
+ "name": "Norm Test",
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID,
+ "sets": []map[string]any{{"set_number": 0, "target_reps": 10, "target_weight": 50.0}},
+ },
+ },
+ }
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/programs", body)
+ CreateProgram(c)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ resp := decodeResponse(t, w)
+ data := resp["data"].(map[string]any)
+ exercises := data["exercises"].([]any)
+ sets := exercises[0].(map[string]any)["sets"].([]any)
+ setNum := sets[0].(map[string]any)["set_number"].(float64)
+ if setNum != 1 {
+ t.Errorf("expected set_number 1 after normalization, got %v", setNum)
+ }
+}
diff --git a/backend/controllers/testhelper_test.go b/backend/controllers/testhelper_test.go
new file mode 100644
index 0000000..70d7a22
--- /dev/null
+++ b/backend/controllers/testhelper_test.go
@@ -0,0 +1,160 @@
+package controllers
+
+import (
+ "bytes"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "math/rand"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/db"
+ "github.com/gin-gonic/gin"
+ _ "modernc.org/sqlite"
+)
+
+func setupTestDB(t *testing.T) {
+ t.Helper()
+ var err error
+ dbName := fmt.Sprintf("file:testdb_%d?mode=memory&cache=shared&_foreign_keys=on", rand.Int63())
+ db.DB, err = sql.Open("sqlite", dbName)
+ if err != nil {
+ t.Fatalf("open test db: %v", err)
+ }
+ if err = db.DB.Ping(); err != nil {
+ t.Fatalf("ping test db: %v", err)
+ }
+ if err = applySchema(); err != nil {
+ t.Fatalf("apply schema: %v", err)
+ }
+ t.Cleanup(func() { db.DB.Close() })
+}
+
+func applySchema() error {
+ schema := `
+CREATE TABLE IF NOT EXISTS users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ email TEXT NOT NULL UNIQUE,
+ password_hash TEXT NOT NULL,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+CREATE TABLE IF NOT EXISTS exercises (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ muscle_group TEXT NOT NULL DEFAULT '',
+ secondary_muscles TEXT NOT NULL DEFAULT '[]',
+ category TEXT NOT NULL DEFAULT 'strength',
+ equipment TEXT NOT NULL DEFAULT '',
+ description TEXT NOT NULL DEFAULT '',
+ image_url TEXT NOT NULL DEFAULT '',
+ video_url TEXT NOT NULL DEFAULT ''
+);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_exercises_name ON exercises(name);
+CREATE TABLE IF NOT EXISTS workouts (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ notes TEXT NOT NULL DEFAULT '',
+ duration INTEGER NOT NULL DEFAULT 0,
+ started_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+CREATE TABLE IF NOT EXISTS workout_exercises (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ workout_id INTEGER NOT NULL REFERENCES workouts(id) ON DELETE CASCADE,
+ exercise_id INTEGER NOT NULL REFERENCES exercises(id),
+ order_index INTEGER NOT NULL DEFAULT 0,
+ notes TEXT NOT NULL DEFAULT ''
+);
+CREATE TABLE IF NOT EXISTS sets (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ workout_exercise_id INTEGER NOT NULL REFERENCES workout_exercises(id) ON DELETE CASCADE,
+ set_number INTEGER NOT NULL DEFAULT 1,
+ reps INTEGER NOT NULL DEFAULT 0,
+ weight REAL NOT NULL DEFAULT 0,
+ duration INTEGER NOT NULL DEFAULT 0,
+ distance REAL NOT NULL DEFAULT 0,
+ rpe REAL NOT NULL DEFAULT 0,
+ is_warmup INTEGER NOT NULL DEFAULT 0
+);
+CREATE TABLE IF NOT EXISTS programs (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ notes TEXT NOT NULL DEFAULT '',
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+CREATE TABLE IF NOT EXISTS program_exercises (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ program_id INTEGER NOT NULL REFERENCES programs(id) ON DELETE CASCADE,
+ exercise_id INTEGER NOT NULL REFERENCES exercises(id),
+ order_index INTEGER NOT NULL DEFAULT 0,
+ notes TEXT NOT NULL DEFAULT ''
+);
+CREATE TABLE IF NOT EXISTS program_sets (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ program_exercise_id INTEGER NOT NULL REFERENCES program_exercises(id) ON DELETE CASCADE,
+ set_number INTEGER NOT NULL DEFAULT 1,
+ target_reps INTEGER NOT NULL DEFAULT 0,
+ target_weight REAL NOT NULL DEFAULT 0
+);`
+ _, err := db.DB.Exec(schema)
+ return err
+}
+
+func createTestUser(t *testing.T) int64 {
+ t.Helper()
+ res, err := db.DB.Exec(
+ `INSERT INTO users (email, password_hash) VALUES (?, ?)`,
+ "[email protected]", "hashed",
+ )
+ if err != nil {
+ t.Fatalf("create test user: %v", err)
+ }
+ id, _ := res.LastInsertId()
+ return id
+}
+
+func createTestExercise(t *testing.T) int64 {
+ t.Helper()
+ res, err := db.DB.Exec(
+ `INSERT INTO exercises (name, muscle_group, category) VALUES (?, ?, ?)`,
+ "Test Exercise", "chest", "strength",
+ )
+ if err != nil {
+ t.Fatalf("create test exercise: %v", err)
+ }
+ id, _ := res.LastInsertId()
+ return id
+}
+
+func newContext(userID int64, method, path string, body any) (*gin.Context, *httptest.ResponseRecorder) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+
+ var bodyBytes []byte
+ if body != nil {
+ bodyBytes, _ = json.Marshal(body)
+ }
+ c.Request, _ = http.NewRequest(method, path, bytes.NewBuffer(bodyBytes))
+ c.Request.Header.Set("Content-Type", "application/json")
+ c.Set("user_id", userID)
+ return c, w
+}
+
+func setParam(c *gin.Context, key, val string) {
+ c.Params = gin.Params{{Key: key, Value: val}}
+}
+
+func decodeResponse(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
+ t.Helper()
+ var result map[string]any
+ if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ return result
+}
diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.go
index fc5eee6..ff77867 100644
--- a/backend/controllers/workouts.go
+++ b/backend/controllers/workouts.go
@@ -16,7 +16,7 @@ func ListWorkouts(c *gin.Context) {
uid := middleware.UserID(c)
limit := 20
offset := 0
- if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 {
+ if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 100 {
limit = l
}
if o, err := strconv.Atoi(c.Query("offset")); err == nil && o >= 0 {
@@ -101,7 +101,11 @@ func CreateWorkout(c *gin.Context) {
utils.InternalError(c)
return
}
- wid, _ := res.LastInsertId()
+ wid, err := res.LastInsertId()
+ if err != nil {
+ utils.InternalError(c)
+ return
+ }
for i, ex := range req.Exercises {
exRes, err := tx.Exec(
@@ -109,11 +113,14 @@ func CreateWorkout(c *gin.Context) {
wid, ex.ExerciseID, i, ex.Notes,
)
if err != nil {
- tx.Rollback()
utils.InternalError(c)
return
}
- weid, _ := exRes.LastInsertId()
+ weid, err := exRes.LastInsertId()
+ if err != nil {
+ utils.InternalError(c)
+ return
+ }
for j, s := range ex.Sets {
_, err := tx.Exec(
`INSERT INTO sets (workout_exercise_id, set_number, reps, weight, duration, distance, rpe, is_warmup)
@@ -121,7 +128,6 @@ func CreateWorkout(c *gin.Context) {
weid, j+1, s.Reps, s.Weight, s.Duration, s.Distance, s.RPE, s.IsWarmup,
)
if err != nil {
- tx.Rollback()
utils.InternalError(c)
return
}
@@ -200,11 +206,14 @@ func UpdateWorkout(c *gin.Context) {
wid, ex.ExerciseID, i, ex.Notes,
)
if err != nil {
- tx.Rollback()
utils.InternalError(c)
return
}
- weid, _ := exRes.LastInsertId()
+ weid, err := exRes.LastInsertId()
+ if err != nil {
+ utils.InternalError(c)
+ return
+ }
for j, s := range ex.Sets {
_, err := tx.Exec(
`INSERT INTO sets (workout_exercise_id, set_number, reps, weight, duration, distance, rpe, is_warmup)
@@ -212,7 +221,6 @@ func UpdateWorkout(c *gin.Context) {
weid, j+1, s.Reps, s.Weight, s.Duration, s.Distance, s.RPE, s.IsWarmup,
)
if err != nil {
- tx.Rollback()
utils.InternalError(c)
return
}
diff --git a/backend/controllers/workouts_test.go b/backend/controllers/workouts_test.go
new file mode 100644
index 0000000..9b8a8c9
--- /dev/null
+++ b/backend/controllers/workouts_test.go
@@ -0,0 +1,232 @@
+package controllers
+
+import (
+ "fmt"
+ "net/http"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/db"
+)
+
+func TestListWorkouts_empty(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ c, w := newContext(uid, http.MethodGet, "/api/v1/workouts", nil)
+ ListWorkouts(c)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ resp := decodeResponse(t, w)
+ data, ok := resp["data"].([]any)
+ if !ok {
+ t.Fatalf("expected data array, got %T", resp["data"])
+ }
+ if len(data) != 0 {
+ t.Fatalf("expected empty list, got %d items", len(data))
+ }
+}
+
+func TestCreateWorkout_success(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ body := map[string]any{
+ "name": "Push Day",
+ "notes": "felt strong",
+ "duration": 3600,
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID,
+ "notes": "",
+ "sets": []map[string]any{
+ {"set_number": 1, "reps": 8, "weight": 100.0},
+ {"set_number": 2, "reps": 8, "weight": 100.0},
+ },
+ },
+ },
+ }
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)
+ CreateWorkout(c)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ resp := decodeResponse(t, w)
+ data := resp["data"].(map[string]any)
+ if data["name"] != "Push Day" {
+ t.Errorf("expected name 'Push Day', got %v", data["name"])
+ }
+ exercises, ok := data["exercises"].([]any)
+ if !ok || len(exercises) != 1 {
+ t.Errorf("expected 1 exercise, got %v", data["exercises"])
+ }
+}
+
+func TestCreateWorkout_missingName(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ body := map[string]any{
+ "name": "",
+ "exercises": []map[string]any{},
+ }
+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)
+ CreateWorkout(c)
+
+ if w.Code == http.StatusCreated {
+ t.Fatal("expected error for empty name, got 201")
+ }
+}
+
+func TestCreateWorkout_preservesStartedAt(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ startedAt := "2024-01-15T09:30:00Z"
+ body := map[string]any{
+ "name": "Morning Lift",
+ "duration": 60,
+ "started_at": startedAt,
+ "exercises": []map[string]any{
+ {
+ "exercise_id": exID,
+ "sets": []map[string]any{{"set_number": 1, "reps": 5, "weight": 80.0}},
+ },
+ },
+ }
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)
+ CreateWorkout(c)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ resp := decodeResponse(t, w)
+ data := resp["data"].(map[string]any)
+ if sa, ok := data["started_at"].(string); !ok || sa == "" {
+ t.Errorf("started_at missing in response: %v", data["started_at"])
+ }
+}
+
+func TestGetWorkout_ownershipEnforced(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ // Create second user
+ res, _ := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, "[email protected]", "x")
+ otherUID, _ := res.LastInsertId()
+
+ // Create workout as otherUID
+ res2, _ := db.DB.Exec(
+ `INSERT INTO workouts (user_id, name, started_at) VALUES (?, ?, CURRENT_TIMESTAMP)`,
+ otherUID, "Other's Workout",
+ )
+ wid, _ := res2.LastInsertId()
+
+ // Try to GET as uid (different user)
+ c, w := newContext(uid, http.MethodGet, "/api/v1/workouts/"+fmt.Sprint(wid), nil)
+ setParam(c, "id", fmt.Sprint(wid))
+ GetWorkout(c)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 for cross-user access, got %d", w.Code)
+ }
+}
+
+func TestDeleteWorkout_ownershipEnforced(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ res, _ := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, "[email protected]", "x")
+ otherUID, _ := res.LastInsertId()
+
+ res2, _ := db.DB.Exec(
+ `INSERT INTO workouts (user_id, name, started_at) VALUES (?, ?, CURRENT_TIMESTAMP)`,
+ otherUID, "Protected Workout",
+ )
+ wid, _ := res2.LastInsertId()
+
+ c, w := newContext(uid, http.MethodDelete, "/api/v1/workouts/"+fmt.Sprint(wid), nil)
+ setParam(c, "id", fmt.Sprint(wid))
+ DeleteWorkout(c)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 for cross-user delete, got %d", w.Code)
+ }
+
+ // Verify workout still exists
+ var count int
+ db.DB.QueryRow(`SELECT COUNT(*) FROM workouts WHERE id = ?`, wid).Scan(&count)
+ if count != 1 {
+ t.Fatal("workout was deleted by wrong user")
+ }
+}
+
+func TestUpdateWorkout_preservesStartedAt(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{
+ "name": "Updated Name",
+ "duration": 1800,
+ "started_at": originalTime,
+ "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))
+ UpdateWorkout(c)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ resp := decodeResponse(t, w)
+ data := resp["data"].(map[string]any)
+ if data["name"] != "Updated Name" {
+ t.Errorf("name not updated: %v", data["name"])
+ }
+}
+
+func TestListWorkouts_limitCap(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ // Insert 5 workouts
+ for i := 0; i < 5; i++ {
+ db.DB.Exec(
+ `INSERT INTO workouts (user_id, name, started_at) VALUES (?, ?, CURRENT_TIMESTAMP)`,
+ uid, fmt.Sprintf("Workout %d", i),
+ )
+ }
+
+ // Request with limit=200 (above cap of 100)
+ c, w := newContext(uid, http.MethodGet, "/api/v1/workouts?limit=200", nil)
+ c.Request.URL.RawQuery = "limit=200"
+ ListWorkouts(c)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+ // Should still return results (capped at 100, but we only have 5)
+ resp := decodeResponse(t, w)
+ data := resp["data"].([]any)
+ if len(data) != 5 {
+ t.Errorf("expected 5 workouts, got %d", len(data))
+ }
+}
diff --git a/web/e2e/auth.setup.ts b/web/e2e/auth.setup.ts
new file mode 100644
index 0000000..be472fa
--- /dev/null
+++ b/web/e2e/auth.setup.ts
@@ -0,0 +1,16 @@
+import { test as setup, expect } from '@playwright/test'
+import path from 'path'
+import { fileURLToPath } from 'url'
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
+const authFile = path.join(__dirname, '.auth/user.json')
+
+setup('authenticate', async ({ page }) => {
+ await page.goto('/login')
+ await page.getByPlaceholder('[email protected]').fill('[email protected]')
+ await page.locator('input[type="password"]').fill('password123')
+ await page.getByRole('button', { name: /sign in|log in/i }).click()
+ await page.waitForURL('/')
+ await expect(page.locator('h1, h2').first()).toBeVisible()
+ await page.context().storageState({ path: authFile })
+})
diff --git a/web/package.json b/web/package.json
index d129a4c..e92e443 100644
--- a/web/package.json
+++ b/web/package.json
@@ -8,7 +8,9 @@
"build": "tsc && vite build",
"preview": "vite preview",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
- "type-check": "tsc --noEmit"
+ "type-check": "tsc --noEmit",
+ "test:e2e": "playwright test",
+ "test:e2e:ui": "playwright test --ui"
},
"dependencies": {
"@tanstack/react-query": "^5.28.0",
diff --git a/web/playwright.config.ts b/web/playwright.config.ts
new file mode 100644
index 0000000..02d342d
--- /dev/null
+++ b/web/playwright.config.ts
@@ -0,0 +1,34 @@
+import { defineConfig, devices } from '@playwright/test'
+
+export default defineConfig({
+ testDir: './e2e',
+ fullyParallel: false,
+ forbidOnly: !!process.env.CI,
+ retries: process.env.CI ? 1 : 0,
+ workers: 1,
+ reporter: 'list',
+ use: {
+ baseURL: 'http://localhost:5173',
+ trace: 'on-first-retry',
+ screenshot: 'only-on-failure',
+ },
+ projects: [
+ { name: 'setup', testMatch: '**/auth.setup.ts' },
+ {
+ name: 'chromium',
+ use: {
+ ...devices['Desktop Chrome'],
+ storageState: 'e2e/.auth/user.json',
+ },
+ dependencies: ['setup'],
+ },
+ {
+ name: 'mobile',
+ use: {
+ ...devices['iPhone 14'],
+ storageState: 'e2e/.auth/user.json',
+ },
+ dependencies: ['setup'],
+ },
+ ],
+})
diff --git a/web/src/App.tsx b/web/src/App.tsx
index e5287a0..e213923 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -2,6 +2,7 @@ import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { useEffect } from 'react'
import { useAuthStore } from './stores/auth'
import { useWorkoutSession } from './stores/workoutSession'
+import { useSettingsStore } from './stores/settings'
import Layout from './components/Layout'
import Dashboard from './pages/Dashboard'
import Workouts from './pages/Workouts'
@@ -25,9 +26,15 @@ import Register from './pages/Register'
function App() {
const { isAuthenticated } = useAuthStore()
const { restoreFromServer } = useWorkoutSession()
+ const { fetch: fetchSettings, reset: resetSettings } = useSettingsStore()
useEffect(() => {
- if (isAuthenticated) restoreFromServer()
+ if (isAuthenticated) {
+ restoreFromServer()
+ fetchSettings()
+ } else {
+ resetSettings()
+ }
}, [isAuthenticated])
return (
diff --git a/web/src/components/AddProgramModal.tsx b/web/src/components/AddProgramModal.tsx
index b05859c..d49934c 100644
--- a/web/src/components/AddProgramModal.tsx
+++ b/web/src/components/AddProgramModal.tsx
@@ -2,6 +2,7 @@ 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 } from '../stores/settings'
import ExercisePicker from './ExercisePicker'
import * as types from '../types'
@@ -22,6 +23,9 @@ interface Props {
}
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('')
@@ -103,7 +107,7 @@ export default function AddProgramModal({ isOpen, onClose, onSuccess }: Props) {
<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={onClose} className="p-1 hover:bg-surface-muted rounded-lg transition-colors">
+ <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>
@@ -265,7 +269,7 @@ export default function AddProgramModal({ isOpen, onClose, onSuccess }: Props) {
min="0"
step="0.5"
/>
- <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted font-medium pointer-events-none">lbs</span>
+ <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted font-medium pointer-events-none">{wUnit}</span>
</div>
</div>
<button
@@ -296,7 +300,7 @@ export default function AddProgramModal({ isOpen, onClose, onSuccess }: Props) {
<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={onClose}
+ 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
diff --git a/web/src/components/AddWorkoutModal.tsx b/web/src/components/AddWorkoutModal.tsx
index 25cf602..be7af5f 100644
--- a/web/src/components/AddWorkoutModal.tsx
+++ b/web/src/components/AddWorkoutModal.tsx
@@ -2,6 +2,7 @@ import { useState } from 'react'
import { createPortal } from 'react-dom'
import { Plus, X, Trash2, AlertCircle, Dumbbell, Clock, FileText, Zap, Target, Gauge, BookOpen } from 'lucide-react'
import { workoutAPI } from '../services/api'
+import { useSettingsStore, weightShort } from '../stores/settings'
import ExercisePicker from './ExercisePicker'
import ProgramPicker from './ProgramPicker'
import * as types from '../types'
@@ -28,6 +29,9 @@ interface Props {
}
export default function AddWorkoutModal({ isOpen, onClose, onSuccess }: Props) {
+ const { settings } = useSettingsStore()
+ const wUnit = weightShort(settings.weight_unit)
+ const handleClose = () => { setError(''); onClose() }
const [showPicker, setShowPicker] = useState(false)
const [showProgramPicker, setShowProgramPicker] = useState(false)
const [loading, setLoading] = useState(false)
@@ -157,7 +161,7 @@ export default function AddWorkoutModal({ isOpen, onClose, onSuccess }: Props) {
<h2 className="font-display font-bold text-xl text-tx-primary">Log Workout</h2>
<p className="text-xs text-tx-muted mt-1">{formData.exercises.length} exercises • {totalSets} sets</p>
</div>
- <button onClick={onClose} className="p-1 hover:bg-surface-muted rounded-lg transition-colors">
+ <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>
@@ -249,7 +253,7 @@ export default function AddWorkoutModal({ isOpen, onClose, onSuccess }: Props) {
<Gauge className="w-3.5 h-3.5 text-brand-500" />
</div>
<div className="text-sm font-bold text-brand-500">{Math.round(totalWeight)}</div>
- <div className="text-xs text-tx-muted">Total lbs</div>
+ <div className="text-xs text-tx-muted">Total {wUnit}</div>
</div>
</div>
)}
@@ -385,7 +389,7 @@ export default function AddWorkoutModal({ isOpen, onClose, onSuccess }: Props) {
step="0.5"
/>
<span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted font-medium pointer-events-none">
- lbs
+ {wUnit}
</span>
</div>
</div>
@@ -422,7 +426,7 @@ export default function AddWorkoutModal({ isOpen, onClose, onSuccess }: Props) {
<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={onClose}
+ 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
diff --git a/web/src/components/EditProgramModal.tsx b/web/src/components/EditProgramModal.tsx
index 278ea69..3ef8b6d 100644
--- a/web/src/components/EditProgramModal.tsx
+++ b/web/src/components/EditProgramModal.tsx
@@ -2,6 +2,7 @@ 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 } from '../stores/settings'
import ExercisePicker from './ExercisePicker'
import * as types from '../types'
@@ -23,6 +24,9 @@ interface Props {
}
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)
@@ -119,7 +123,7 @@ export default function EditProgramModal({ isOpen, onClose, onSuccess, programId
<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={onClose} className="p-1 hover:bg-surface-muted rounded-lg transition-colors">
+ <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>
@@ -142,7 +146,7 @@ export default function EditProgramModal({ isOpen, onClose, onSuccess, programId
<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={onClose} className="p-1 hover:bg-surface-muted rounded-lg transition-colors">
+ <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>
@@ -268,7 +272,7 @@ export default function EditProgramModal({ isOpen, onClose, onSuccess, programId
<label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Weight</label>
<div className="relative">
<input type="number" inputMode="decimal" value={set.target_weight || ''} onChange={e => updateSet(exIdx, setIdx, 'target_weight', e.target.value)} placeholder="135" className="input text-sm w-full pr-7" min="0" step="0.5" />
- <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted font-medium pointer-events-none">lbs</span>
+ <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted font-medium pointer-events-none">{wUnit}</span>
</div>
</div>
<button type="button" onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
@@ -289,7 +293,7 @@ export default function EditProgramModal({ isOpen, onClose, onSuccess, programId
</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={onClose} className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">
+ <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">
diff --git a/web/src/components/EditWorkoutModal.tsx b/web/src/components/EditWorkoutModal.tsx
index 0b079be..befdcfb 100644
--- a/web/src/components/EditWorkoutModal.tsx
+++ b/web/src/components/EditWorkoutModal.tsx
@@ -2,6 +2,7 @@ import { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { Plus, X, Trash2, AlertCircle, Dumbbell, Clock, FileText, Zap, Target, Gauge } from 'lucide-react'
import { workoutAPI, exerciseAPI } from '../services/api'
+import { useSettingsStore, weightShort } from '../stores/settings'
import ExercisePicker from './ExercisePicker'
import * as types from '../types'
@@ -28,11 +29,16 @@ interface Props {
}
export default function EditWorkoutModal({ isOpen, onClose, onSuccess, workoutId }: Props) {
+ const { settings } = useSettingsStore()
+ const wUnit = weightShort(settings.weight_unit)
const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})
const [showPicker, setShowPicker] = useState(false)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [initialLoading, setInitialLoading] = useState(false)
+ const [originalStartedAt, setOriginalStartedAt] = useState('')
+
+ const handleClose = () => { setError(''); onClose() }
const [formData, setFormData] = useState<WorkoutFormData>({
name: '',
@@ -56,6 +62,7 @@ export default function EditWorkoutModal({ isOpen, onClose, onSuccess, workoutId
})
setPickerExercises(exerciseMap)
+ setOriginalStartedAt(workout.started_at || new Date().toISOString())
setFormData({
name: workout.name,
notes: workout.notes || '',
@@ -143,7 +150,7 @@ export default function EditWorkoutModal({ isOpen, onClose, onSuccess, workoutId
notes: formData.notes,
duration: formData.duration,
exercises: formData.exercises,
- started_at: new Date().toISOString(),
+ started_at: originalStartedAt || new Date().toISOString(),
})
onSuccess()
onClose()
@@ -166,7 +173,7 @@ export default function EditWorkoutModal({ isOpen, onClose, onSuccess, workoutId
<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 Workout</h2>
- <button onClick={onClose} className="p-1 hover:bg-surface-muted rounded-lg transition-colors">
+ <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>
@@ -189,7 +196,7 @@ export default function EditWorkoutModal({ isOpen, onClose, onSuccess, workoutId
<h2 className="font-display font-bold text-xl text-tx-primary">Edit Workout</h2>
<p className="text-xs text-tx-muted mt-1">{formData.exercises.length} exercises • {totalSets} sets</p>
</div>
- <button onClick={onClose} className="p-1 hover:bg-surface-muted rounded-lg transition-colors">
+ <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>
@@ -281,7 +288,7 @@ export default function EditWorkoutModal({ isOpen, onClose, onSuccess, workoutId
<Gauge className="w-3.5 h-3.5 text-brand-500" />
</div>
<div className="text-sm font-bold text-brand-500">{Math.round(totalWeight)}</div>
- <div className="text-xs text-tx-muted">Total lbs</div>
+ <div className="text-xs text-tx-muted">Total {wUnit}</div>
</div>
</div>
)}
@@ -400,7 +407,7 @@ export default function EditWorkoutModal({ isOpen, onClose, onSuccess, workoutId
step="0.5"
/>
<span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted font-medium pointer-events-none">
- lbs
+ {wUnit}
</span>
</div>
</div>
@@ -437,7 +444,7 @@ export default function EditWorkoutModal({ isOpen, onClose, onSuccess, workoutId
<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={onClose}
+ 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
diff --git a/web/src/pages/ActiveWorkout.tsx b/web/src/pages/ActiveWorkout.tsx
index 0190737..f7eed59 100644
--- a/web/src/pages/ActiveWorkout.tsx
+++ b/web/src/pages/ActiveWorkout.tsx
@@ -6,6 +6,7 @@ import {
AlertCircle, ChevronRight, ChevronLeft, Info,
} from 'lucide-react'
import { useWorkoutSession } from '../stores/workoutSession'
+import { useSettingsStore, weightShort } from '../stores/settings'
import { workoutAPI } from '../services/api'
import * as types from '../types'
import { muscleColor } from '../utils/exerciseUtils'
@@ -22,6 +23,8 @@ export default function ActiveWorkout() {
const navigate = useNavigate()
const { session, updateSet, completeSet, addSet, removeSet, removeExercise, buildPayload, cancelSession } =
useWorkoutSession()
+ const { settings } = useSettingsStore()
+ const wUnit = weightShort(settings.weight_unit)
const [elapsed, setElapsed] = useState(0)
const [confirmCancel, setConfirmCancel] = useState(false)
@@ -310,7 +313,7 @@ export default function ActiveWorkout() {
disabled={set.completed}
step="0.5"
/>
- <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted pointer-events-none">lb</span>
+ <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted pointer-events-none">{wUnit}</span>
</div>
{/* Complete toggle */}
diff --git a/web/src/pages/AddProgram.tsx b/web/src/pages/AddProgram.tsx
index d70289e..5df7e85 100644
--- a/web/src/pages/AddProgram.tsx
+++ b/web/src/pages/AddProgram.tsx
@@ -2,6 +2,7 @@ import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Plus, ArrowLeft, Trash2, AlertCircle, BookOpen, FileText, Zap, Target } from 'lucide-react'
import { programAPI } from '../services/api'
+import { useSettingsStore, weightShort } from '../stores/settings'
import ExercisePicker from '../components/ExercisePicker'
import * as types from '../types'
@@ -17,6 +18,8 @@ interface ProgramFormData {
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('')
@@ -224,7 +227,7 @@ export default function AddProgram() {
<label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Weight</label>
<div className="relative">
<input type="number" inputMode="decimal" value={set.target_weight || ''} onChange={e => updateSet(exIdx, setIdx, 'target_weight', e.target.value)} placeholder="135" className="input text-sm w-full pr-7" min="0" step="0.5" />
- <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted font-medium pointer-events-none">lbs</span>
+ <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted font-medium pointer-events-none">{wUnit}</span>
</div>
</div>
<button type="button" onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
diff --git a/web/src/pages/EditProgram.tsx b/web/src/pages/EditProgram.tsx
index 1f1c558..6b2232c 100644
--- a/web/src/pages/EditProgram.tsx
+++ b/web/src/pages/EditProgram.tsx
@@ -2,6 +2,7 @@ import { useState, useEffect } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { Plus, ArrowLeft, Trash2, AlertCircle, BookOpen, FileText, Zap, Target, Dumbbell } from 'lucide-react'
import { programAPI } from '../services/api'
+import { useSettingsStore, weightShort } from '../stores/settings'
import ExercisePicker from '../components/ExercisePicker'
import * as types from '../types'
@@ -18,6 +19,8 @@ interface ProgramFormData {
export default function EditProgram() {
const { id } = useParams<{ id: string }>()
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)
@@ -224,7 +227,7 @@ export default function EditProgram() {
<label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Weight</label>
<div className="relative">
<input type="number" inputMode="decimal" value={set.target_weight || ''} onChange={e => updateSet(exIdx, setIdx, 'target_weight', e.target.value)} placeholder="135" className="input text-sm w-full pr-7" min="0" step="0.5" />
- <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted font-medium pointer-events-none">lbs</span>
+ <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-tx-muted font-medium pointer-events-none">{wUnit}</span>
</div>
</div>
<button type="button" onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">
diff --git a/web/src/pages/ProgramDetail.tsx b/web/src/pages/ProgramDetail.tsx
index 886e532..8a210c5 100644
--- a/web/src/pages/ProgramDetail.tsx
+++ b/web/src/pages/ProgramDetail.tsx
@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react'
+import { createPortal } from 'react-dom'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { format } from 'date-fns'
import {
@@ -6,6 +7,7 @@ import {
} from 'lucide-react'
import { programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
+import { useSettingsStore, weightShort } from '../stores/settings'
import * as types from '../types'
import { muscleColor } from '../utils/exerciseUtils'
@@ -13,6 +15,8 @@ export default function ProgramDetail() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const { session, startSession } = useWorkoutSession()
+ const { settings } = useSettingsStore()
+ const wUnit = weightShort(settings.weight_unit)
const [program, setProgram] = useState<types.Program | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@@ -119,18 +123,25 @@ export default function ProgramDetail() {
</div>
</div>
- {/* Delete confirm */}
- {confirming && (
- <div className="card p-4 border-error-500/30 bg-error-500/5">
- <p className="text-sm font-semibold text-tx-primary mb-1">Delete "{program.name}"?</p>
- <p className="text-xs text-tx-muted mb-3">This cannot be undone.</p>
- <div className="flex gap-2">
- <button onClick={handleDelete} disabled={deleting} className="btn-danger btn-sm flex-1">
- {deleting ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Deleting…</> : 'Yes, delete'}
- </button>
- <button onClick={() => setConfirming(false)} className="btn-secondary btn-sm flex-1">Cancel</button>
+ {/* Delete confirm — bottom sheet */}
+ {confirming && createPortal(
+ <div className="fixed inset-0 bg-black/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">
+ <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
+ <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
+ <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Delete Program?</h3>
+ <p className="text-sm text-tx-muted mb-5">"{program.name}" will be permanently deleted.</p>
+ <div className="flex gap-3">
+ <button onClick={() => setConfirming(false)} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm">
+ Cancel
+ </button>
+ <button onClick={handleDelete} disabled={deleting} className="flex-1 py-3 bg-error-500 hover:bg-error-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
+ <Trash2 className="w-3.5 h-3.5" />
+ {deleting ? 'Deleting…' : 'Delete'}
+ </button>
+ </div>
</div>
- </div>
+ </div>,
+ document.body
)}
{/* Header */}
@@ -212,7 +223,7 @@ export default function ProgramDetail() {
</span>
)}
<span className="text-xs text-tx-muted">{sets.length} sets</span>
- {maxTarget > 0 && <span className="text-xs text-tx-muted">target {maxTarget} lb</span>}
+ {maxTarget > 0 && <span className="text-xs text-tx-muted">target {maxTarget} {wUnit}</span>}
</div>
</div>
<ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />
@@ -226,7 +237,7 @@ export default function ProgramDetail() {
<div key={i} className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold tabular-nums leading-none ${
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 ? `${set.target_weight} lb` : 'BW'}
+ {set.target_reps > 0 ? set.target_reps : '—'} × {set.target_weight > 0 ? `${set.target_weight} ${wUnit}` : 'BW'}
</div>
)
})}
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 00800e6..32d6088 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -1,7 +1,8 @@
import { useState, useEffect, useCallback } from 'react'
import { useAuthStore } from '../stores/auth'
+import { useSettingsStore } from '../stores/settings'
import { useTheme } from '../hooks/useTheme'
-import { userAPI, exerciseAPI } from '../services/api'
+import { exerciseAPI } from '../services/api'
import * as types from '../types'
import { HelpTip } from '../components/Tooltip'
import {
@@ -37,8 +38,8 @@ function Section({ title, children }: { title: string; children: React.ReactNode
export default function Settings() {
const { user, logout } = useAuthStore()
const { theme, toggleTheme } = useTheme()
- const [settings, setSettings] = useState<types.UserSettings | null>(null)
- const [loading, setLoading] = useState(true)
+ const { settings: storedSettings, update: updateSettings, fetch: fetchSettings } = useSettingsStore()
+ const [loading, setLoading] = useState(!useSettingsStore.getState().loaded)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState(false)
@@ -48,11 +49,11 @@ export default function Settings() {
const [seedMsg, setSeedMsg] = useState<string | null>(null)
const [formData, setFormData] = useState({
- weight_unit: 'lbs' as 'lbs' | 'kg',
- calorie_target: 2000,
- protein_target: 150,
- carb_target: 250,
- fat_target: 65,
+ weight_unit: storedSettings.weight_unit,
+ calorie_target: storedSettings.calorie_target,
+ protein_target: storedSettings.protein_target,
+ carb_target: storedSettings.carb_target,
+ fat_target: storedSettings.fat_target,
})
const loadSeedStatus = useCallback(async () => {
@@ -66,14 +67,14 @@ export default function Settings() {
useEffect(() => {
const load = async () => {
try {
- const data = await userAPI.getSettings()
- setSettings(data)
+ await fetchSettings()
+ const s = useSettingsStore.getState().settings
setFormData({
- weight_unit: data.weight_unit,
- calorie_target: data.calorie_target,
- protein_target: data.protein_target,
- carb_target: data.carb_target,
- fat_target: data.fat_target,
+ weight_unit: s.weight_unit,
+ calorie_target: s.calorie_target,
+ protein_target: s.protein_target,
+ carb_target: s.carb_target,
+ fat_target: s.fat_target,
})
} catch (err: any) {
setError(err.message || 'Failed to load settings')
@@ -110,12 +111,19 @@ export default function Settings() {
}
+ const handleUnitChange = async (unit: 'lbs' | 'kg') => {
+ setFormData(prev => ({ ...prev, weight_unit: unit }))
+ try {
+ await updateSettings({ ...formData, weight_unit: unit })
+ } catch {}
+ }
+
const handleSave = async () => {
setSaving(true)
setError(null)
setSuccess(false)
try {
- await userAPI.updateSettings(formData)
+ await updateSettings(formData)
setSuccess(true)
setTimeout(() => setSuccess(false), 3000)
} catch (err: any) {
@@ -181,15 +189,15 @@ export default function Settings() {
{/* Goals & Units */}
<Section title="Goals & Units">
- <SettingRow label="Weight unit" description="Displayed across the entire app">
+ <SettingRow label="Weight unit" description="Changes apply immediately across the app">
<div className="flex gap-1 bg-surface-overlay rounded-lg p-1 border border-surface-border">
{(['lbs', 'kg'] as const).map(unit => (
<button
key={unit}
- onClick={() => setFormData({ ...formData, weight_unit: unit })}
+ onClick={() => handleUnitChange(unit)}
className={`px-3 py-1 rounded-md text-xs font-medium transition-all ${
formData.weight_unit === unit
- ? 'bg-surface-raised border border-surface-border text-tx-primary'
+ ? 'bg-surface-raised border border-surface-border text-tx-primary shadow-sm'
: 'text-tx-muted hover:text-tx-primary'
}`}
>
@@ -249,13 +257,14 @@ export default function Settings() {
</div>
</SettingRow>
- <div className="py-3 flex justify-end">
+ <div className="py-3 flex items-center justify-between">
+ <p className="text-xs text-tx-muted">Save calorie and macro targets</p>
<button
onClick={handleSave}
disabled={saving}
className="btn-primary btn-sm"
>
- <Check className="w-3.5 h-3.5" /> {saving ? 'Saving...' : 'Save'}
+ <Check className="w-3.5 h-3.5" /> {saving ? 'Saving...' : 'Save targets'}
</button>
</div>
</Section>
diff --git a/web/src/pages/WorkoutDetail.tsx b/web/src/pages/WorkoutDetail.tsx
index 51dc684..635d5e4 100644
--- a/web/src/pages/WorkoutDetail.tsx
+++ b/web/src/pages/WorkoutDetail.tsx
@@ -1,21 +1,23 @@
import { useState, useEffect } from 'react'
+import { createPortal } from 'react-dom'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { format } from 'date-fns'
import {
ArrowLeft, Clock, Dumbbell, TrendingUp, Edit2, Trash2, ChevronRight, AlertCircle, Loader,
} from 'lucide-react'
import { workoutAPI } from '../services/api'
+import { useSettingsStore, weightShort } from '../stores/settings'
import * as types from '../types'
import { muscleColor } from '../utils/exerciseUtils'
-function SetChip({ set, isBest }: { set: types.Set; isBest: boolean }) {
+function SetChip({ set, isBest, unit }: { set: types.Set; isBest: boolean; unit: string }) {
return (
<div className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold tabular-nums leading-none ${
isBest
? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25'
: 'bg-surface-raised text-tx-secondary'
}`}>
- {set.reps > 0 ? set.reps : '—'} × {set.weight > 0 ? `${set.weight} lb` : 'BW'}
+ {set.reps > 0 ? set.reps : '—'} × {set.weight > 0 ? `${set.weight} ${unit}` : 'BW'}
</div>
)
}
@@ -23,6 +25,8 @@ function SetChip({ set, isBest }: { set: types.Set; isBest: boolean }) {
export default function WorkoutDetail() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
+ const { settings } = useSettingsStore()
+ const wUnit = weightShort(settings.weight_unit)
const [workout, setWorkout] = useState<types.Workout | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@@ -107,21 +111,25 @@ export default function WorkoutDetail() {
</div>
</div>
- {/* Delete confirm */}
- {confirming && (
- <div className="card p-4 border-error-500/30 bg-error-500/5">
- <p className="text-sm font-semibold text-tx-primary mb-1">Delete "{workout.name}"?</p>
- <p className="text-xs text-tx-muted mb-3">This cannot be undone.</p>
- <div className="flex gap-2">
- <button onClick={handleDelete} disabled={deleting}
- className="btn-danger btn-sm flex-1">
- {deleting ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Deleting…</> : 'Yes, delete'}
- </button>
- <button onClick={() => setConfirming(false)} className="btn-secondary btn-sm flex-1">
- Cancel
- </button>
+ {/* Delete confirm — bottom sheet */}
+ {confirming && createPortal(
+ <div className="fixed inset-0 bg-black/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">
+ <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
+ <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
+ <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Delete Workout?</h3>
+ <p className="text-sm text-tx-muted mb-5">"{workout.name}" will be permanently deleted.</p>
+ <div className="flex gap-3">
+ <button onClick={() => setConfirming(false)} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm">
+ Cancel
+ </button>
+ <button onClick={handleDelete} disabled={deleting} className="flex-1 py-3 bg-error-500 hover:bg-error-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
+ <Trash2 className="w-3.5 h-3.5" />
+ {deleting ? 'Deleting…' : 'Delete'}
+ </button>
+ </div>
</div>
- </div>
+ </div>,
+ document.body
)}
{/* Header */}
@@ -170,7 +178,7 @@ export default function WorkoutDetail() {
</div>
<p className="text-lg font-bold text-tx-primary tabular-nums">
{totalVolume > 0 ? `${totalVolume.toLocaleString()}` : '—'}
- {totalVolume > 0 && <span className="text-xs font-normal text-tx-muted ml-0.5">lb</span>}
+ {totalVolume > 0 && <span className="text-xs font-normal text-tx-muted ml-0.5">{wUnit}</span>}
</p>
</div>
</div>
@@ -215,13 +223,13 @@ export default function WorkoutDetail() {
</span>
)}
<span className="text-xs text-tx-muted">{sets.length} sets</span>
- {exVol > 0 && <span className="text-xs text-tx-muted">{exVol.toLocaleString()} lb</span>}
+ {exVol > 0 && <span className="text-xs text-tx-muted">{exVol.toLocaleString()} {wUnit}</span>}
</div>
</div>
{maxWeight > 0 && (
<div className="text-right flex-shrink-0 mr-1">
<p className="text-[10px] text-tx-muted uppercase tracking-wide">best</p>
- <p className="text-sm font-bold text-brand-400 tabular-nums">{maxWeight} lb</p>
+ <p className="text-sm font-bold text-brand-400 tabular-nums">{maxWeight} {wUnit}</p>
</div>
)}
<ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />
@@ -231,7 +239,7 @@ export default function WorkoutDetail() {
<div className="flex flex-wrap gap-1.5 px-4 pb-4 pt-0 border-t border-surface-border/50">
<div className="w-full pt-3" />
{sets.map((set, i) => (
- <SetChip key={i} set={set} isBest={set.weight === maxWeight && maxWeight > 0} />
+ <SetChip key={i} set={set} isBest={set.weight === maxWeight && maxWeight > 0} unit={wUnit} />
))}
</div>
)}
diff --git a/web/src/stores/settings.ts b/web/src/stores/settings.ts
new file mode 100644
index 0000000..4116dca
--- /dev/null
+++ b/web/src/stores/settings.ts
@@ -0,0 +1,46 @@
+import { create } from 'zustand'
+import * as types from '../types'
+import { userAPI } from '../services/api'
+
+interface SettingsStore {
+ settings: types.UserSettings
+ loaded: boolean
+ fetch: () => Promise<void>
+ update: (patch: Partial<types.UserSettings>) => Promise<void>
+ reset: () => void
+}
+
+const DEFAULTS: types.UserSettings = {
+ user_id: 0,
+ weight_unit: 'lbs',
+ calorie_target: 2000,
+ protein_target: 150,
+ carb_target: 250,
+ fat_target: 65,
+}
+
+export const useSettingsStore = create<SettingsStore>((set, get) => ({
+ settings: DEFAULTS,
+ loaded: false,
+
+ fetch: async () => {
+ if (get().loaded) return
+ try {
+ const s = await userAPI.getSettings()
+ set({ settings: s, loaded: true })
+ } catch {
+ set({ loaded: true })
+ }
+ },
+
+ update: async (patch) => {
+ set(state => ({ settings: { ...state.settings, ...patch } }))
+ const updated = await userAPI.updateSettings(patch)
+ set({ settings: updated })
+ },
+
+ reset: () => set({ settings: DEFAULTS, loaded: false }),
+}))
+
+export const weightLabel = (unit: string) => unit === 'kg' ? 'kg' : 'lbs'
+export const weightShort = (unit: string) => unit === 'kg' ? 'kg' : 'lb'
diff --git a/web/src/stores/workoutSession.ts b/web/src/stores/workoutSession.ts
index 7ef1a5f..0936d7c 100644
--- a/web/src/stores/workoutSession.ts
+++ b/web/src/stores/workoutSession.ts
@@ -201,8 +201,12 @@ export const useWorkoutSession = create<WorkoutSessionStore>((set, get) => ({
if (local) return
// User explicitly cancelled — don't restore, retry the server clear
if (localStorage.getItem(CANCEL_KEY)) {
- localStorage.removeItem(CANCEL_KEY)
- activeSessionAPI.clear().catch(() => {})
+ try {
+ await activeSessionAPI.clear()
+ localStorage.removeItem(CANCEL_KEY)
+ } catch {
+ // Keep CANCEL_KEY so next restore retries the clear
+ }
return
}
try {