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.

Serve exercise names and descriptions in the reader's language (#204)

Carter5a0336caacc3
diff --git a/backend/controllers/exercises.go b/backend/controllers/exercises.go
index 9037c7d..ddb0363 100644
--- a/backend/controllers/exercises.go
+++ b/backend/controllers/exercises.go
@@ -11,12 +11,21 @@ import (
"github.com/gin-gonic/gin"
)
+// requestLocale is the language the reader asked for. It is a query parameter, not a
+// header, so a URL names the whole response. Absent or malformed means English.
+func requestLocale(c *gin.Context) string { return stores.NormalizeLocale(c.Query("locale")) }
+
+// requestLanguage is its primary language ("pt-BR" -> "pt"), for upstreams such as
+// Open Food Facts that key their names by language alone.
+func requestLanguage(c *gin.Context) string { return stores.BaseLanguage(requestLocale(c)) }
+
func (h *Handler) ListExercises(c *gin.Context) {
f := stores.ExerciseFilter{
Query: c.Query("q"),
MuscleGroup: c.Query("muscle_group"),
Category: c.Query("category"),
Equipment: c.Query("equipment"),
+ Locale: requestLocale(c),
Limit: 100,
}
if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 2000 {
@@ -38,7 +47,7 @@ func (h *Handler) GetExercise(c *gin.Context) {
utils.Fail(c, utils.CodeInvalidExerciseID, nil)
return
}
- e, err := h.s.Exercise.Get(id)
+ e, err := h.s.Exercise.Get(id, requestLocale(c))
if err == sql.ErrNoRows {
utils.Fail(c, utils.CodeExerciseNotFound, nil)
return
diff --git a/backend/controllers/exercises_test.go b/backend/controllers/exercises_test.go
index 7a611e5..a21e5da 100644
--- a/backend/controllers/exercises_test.go
+++ b/backend/controllers/exercises_test.go
@@ -196,3 +196,82 @@ func TestGetExerciseHistory_returnsSessionsGrouped(t *testing.T) {
t.Fatalf("missing fields in history point: %v", first)
}
}
+
+// seedSpanishSquat is an English base row with a Spanish translation, a workout
+// that logged it, and returns the workout id and the exercise id.
+func seedSpanishSquat(t *testing.T, uid int64) (workoutID, exerciseID int64) {
+ t.Helper()
+ res, err := db.DB.Exec(`INSERT INTO exercises (name, muscle_group, category) VALUES ('Squat', 'legs', 'strength')`)
+ if err != nil {
+ t.Fatalf("insert exercise: %v", err)
+ }
+ exerciseID, _ = res.LastInsertId()
+ if _, err := db.DB.Exec(
+ `INSERT INTO exercise_translations (exercise_id, locale, name) VALUES (?, 'es', 'Sentadilla')`, exerciseID,
+ ); err != nil {
+ t.Fatalf("insert translation: %v", err)
+ }
+ seedWorkoutWithSet(t, uid, exerciseID, 100, 5, 0)
+ if err := db.DB.QueryRow(`SELECT id FROM workouts WHERE user_id = ?`, uid).Scan(&workoutID); err != nil {
+ t.Fatalf("find workout: %v", err)
+ }
+ return workoutID, exerciseID
+}
+
+func TestLocaleQueryParam(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ wid, exID := seedSpanishSquat(t, uid)
+
+ workoutExerciseName := func(query string) (int, string) {
+ c, w := newContext(uid, http.MethodGet, fmt.Sprintf("/api/v1/workouts/%d%s", wid, query), nil)
+ setParam(c, "id", fmt.Sprintf("%d", wid))
+ th.GetWorkout(c)
+ if w.Code != http.StatusOK {
+ return w.Code, ""
+ }
+ data := decodeResponse(t, w)["data"].(map[string]any)
+ ex := data["exercises"].([]any)[0].(map[string]any)["exercise"].(map[string]any)
+ return w.Code, ex["name"].(string)
+ }
+
+ for query, want := range map[string]string{
+ "?locale=es": "Sentadilla",
+ "?locale=es-MX": "Sentadilla",
+ "": "Squat",
+ "?locale=fr": "Squat",
+ "?locale=!!": "Squat",
+ "?locale=": "Squat",
+ } {
+ code, got := workoutExerciseName(query)
+ if code != http.StatusOK || got != want {
+ t.Errorf("GET workout%s = %d %q, want 200 %q", query, code, got, want)
+ }
+ }
+
+ c, w := newContext(uid, http.MethodGet, "/api/v1/exercises?q=sentadilla&locale=es", nil)
+ th.ListExercises(c)
+ list := decodeResponse(t, w)["data"].([]any)
+ if len(list) != 1 || list[0].(map[string]any)["name"] != "Sentadilla" {
+ t.Errorf("localized search = %v, want the one Spanish row", list)
+ }
+
+ c, w = newContext(uid, http.MethodGet, "/api/v1/exercises?q=sentadilla", nil)
+ th.ListExercises(c)
+ if list := decodeResponse(t, w)["data"].([]any); len(list) != 0 {
+ t.Errorf("English search for a Spanish name = %v, want nothing", list)
+ }
+
+ c, w = newContext(uid, http.MethodGet, fmt.Sprintf("/api/v1/exercises/%d?locale=es", exID), nil)
+ setParam(c, "id", fmt.Sprintf("%d", exID))
+ th.GetExercise(c)
+ if got := decodeResponse(t, w)["data"].(map[string]any)["name"]; got != "Sentadilla" {
+ t.Errorf("GetExercise?locale=es name = %v", got)
+ }
+ c, w = newContext(uid, http.MethodGet, fmt.Sprintf("/api/v1/exercises/%d?locale=xx!!", exID), nil)
+ setParam(c, "id", fmt.Sprintf("%d", exID))
+ th.GetExercise(c)
+ if w.Code != http.StatusOK || decodeResponse(t, w)["data"].(map[string]any)["name"] != "Squat" {
+ t.Errorf("GetExercise?locale=xx!! = %d %s, want 200 English", w.Code, w.Body.String())
+ }
+}
diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.go
index 0b51d2f..8b603f4 100644
--- a/backend/controllers/food_test.go
+++ b/backend/controllers/food_test.go
@@ -1873,9 +1873,9 @@ func TestUpdateFoodLog_trimsNameAndBrand(t *testing.T) {
func TestRequestLanguage(t *testing.T) {
cases := map[string]string{
- "es": "es", "ES": "es", "en": "en", "pt-BR": "pt", "pt_BR": "pt",
+ "es": "es", "ES": "es", "en": "en", "pt-BR": "pt", "pt_BR": "en",
"zh-Hant-TW": "zh", "": "en", "../x": "en", "e": "en", "español": "en",
- "12": "en", "abcdefgh": "en",
+ "12": "en",
}
for in, want := range cases {
c, _ := newContext(0, http.MethodGet, "/x?locale="+url.QueryEscape(in), nil)
diff --git a/backend/controllers/locale.go b/backend/controllers/locale.go
deleted file mode 100644
index 04c37d0..0000000
--- a/backend/controllers/locale.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package controllers
-
-import (
- "regexp"
- "strings"
-
- "github.com/gin-gonic/gin"
-)
-
-// BCP 47 primary language subtags are 2-3 letters, and OpenFoodFacts keys its
-// languages by ISO 639-1 (es, fr, pt). The value is pasted into upstream URLs, so
-// it has to be letters only.
-var languageSubtagRe = regexp.MustCompile(`^[a-z]{2,3}$`)
-
-// requestLanguage reads the optional `locale` query param and reduces it to a
-// primary language subtag ("pt-BR" -> "pt"). Absent or malformed means "en".
-// Generic on purpose: other localised content reads its language here too.
-func requestLanguage(c *gin.Context) string {
- raw := strings.TrimSpace(c.Query("locale"))
- if i := strings.IndexAny(raw, "-_"); i >= 0 {
- raw = raw[:i]
- }
- raw = strings.ToLower(raw)
- if languageSubtagRe.MatchString(raw) {
- return raw
- }
- return "en"
-}
diff --git a/backend/controllers/programs.go b/backend/controllers/programs.go
index af68505..f0f38fe 100644
--- a/backend/controllers/programs.go
+++ b/backend/controllers/programs.go
@@ -45,7 +45,7 @@ func (h *Handler) ListPrograms(c *gin.Context) {
if o, err := strconv.Atoi(c.Query("offset")); err == nil && o >= 0 {
f.Offset = o
}
- programs, err := h.s.Program.List(uid, f)
+ programs, err := h.s.Program.List(uid, f, requestLocale(c))
if utils.DBError(c, err) {
return
}
@@ -59,7 +59,7 @@ func (h *Handler) GetProgram(c *gin.Context) {
utils.Fail(c, utils.CodeInvalidProgramID, nil)
return
}
- p, err := h.s.Program.Get(uid, pid)
+ p, err := h.s.Program.Get(uid, pid, requestLocale(c))
if err == sql.ErrNoRows {
utils.Fail(c, utils.CodeProgramNotFound, nil)
return
@@ -81,7 +81,7 @@ func (h *Handler) CreateProgram(c *gin.Context) {
utils.ValidationError(c, err)
return
}
- p, err := h.s.Program.Create(uid, req)
+ p, err := h.s.Program.Create(uid, req, requestLocale(c))
if utils.IsForeignKeyViolation(err) {
utils.Fail(c, utils.CodeUnknownExercises, nil)
return
@@ -108,7 +108,7 @@ func (h *Handler) UpdateProgram(c *gin.Context) {
utils.ValidationError(c, err)
return
}
- p, err := h.s.Program.Update(uid, pid, req)
+ p, err := h.s.Program.Update(uid, pid, req, requestLocale(c))
if err == sql.ErrNoRows {
utils.Fail(c, utils.CodeProgramNotFound, nil)
return
@@ -159,7 +159,7 @@ func (h *Handler) ResolveSuggestions(c *gin.Context) {
utils.ValidationError(c, err)
return
}
- p, err := h.s.Program.ResolveSuggestions(uid, pid, req.Accept, req.Dismiss)
+ p, err := h.s.Program.ResolveSuggestions(uid, pid, req.Accept, req.Dismiss, requestLocale(c))
if err == sql.ErrNoRows {
utils.Fail(c, utils.CodeProgramNotFound, nil)
return
diff --git a/backend/controllers/progression_test.go b/backend/controllers/progression_test.go
index 49a52c1..db92d3b 100644
--- a/backend/controllers/progression_test.go
+++ b/backend/controllers/progression_test.go
@@ -214,7 +214,7 @@ func TestResolveSuggestions_AcceptAndDismiss(t *testing.T) {
}
// Accept set0, dismiss set1.
- prog, err := ps.ResolveSuggestions(uid, pid, []int64{ids[0]}, []int64{ids[1]})
+ prog, err := ps.ResolveSuggestions(uid, pid, []int64{ids[0]}, []int64{ids[1]}, "")
if err != nil {
t.Fatalf("ResolveSuggestions: %v", err)
}
@@ -251,7 +251,7 @@ func TestResolveSuggestions_OwnershipGuard(t *testing.T) {
// attacker's own program, tries to accept the owner's staged set id → join fails → no-op.
p2, _ := seedProgram(t, attacker, exID, []ptTarget{{5, 50}})
- if _, err := ps.ResolveSuggestions(attacker, p2, []int64{ids[0]}, nil); err != nil {
+ if _, err := ps.ResolveSuggestions(attacker, p2, []int64{ids[0]}, nil, ""); err != nil {
t.Fatalf("ResolveSuggestions(attacker): %v", err)
}
if r, w := getTarget(t, ids[0]); r != 5 || w != 100 {
diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.go
index 186dd0b..1bbe363 100644
--- a/backend/controllers/workouts.go
+++ b/backend/controllers/workouts.go
@@ -40,7 +40,7 @@ func (h *Handler) ListWorkouts(c *gin.Context) {
if o, err := strconv.Atoi(c.Query("offset")); err == nil && o >= 0 {
f.Offset = o
}
- workouts, err := h.s.Workout.List(uid, f)
+ workouts, err := h.s.Workout.List(uid, f, requestLocale(c))
if utils.DBError(c, err) {
return
}
@@ -54,7 +54,7 @@ func (h *Handler) GetWorkout(c *gin.Context) {
utils.Fail(c, utils.CodeInvalidWorkoutID, nil)
return
}
- w, err := h.s.Workout.Get(uid, wid)
+ w, err := h.s.Workout.Get(uid, wid, requestLocale(c))
if err == sql.ErrNoRows {
utils.Fail(c, utils.CodeWorkoutNotFound, nil)
return
@@ -94,7 +94,7 @@ func (h *Handler) CreateWorkout(c *gin.Context) {
// #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
// never fails the already-saved workout.
- w, progression, err := h.s.CreateWorkoutWithProgression(uid, req)
+ w, progression, err := h.s.CreateWorkoutWithProgression(uid, req, requestLocale(c))
if utils.IsForeignKeyViolation(err) {
utils.Fail(c, utils.CodeUnknownExercises, nil)
return
@@ -136,7 +136,7 @@ func (h *Handler) UpdateWorkout(c *gin.Context) {
off := h.tzOffsetMinutes(uid, req.StartedAt)
req.TZOffsetMinutes = &off
}
- w, err := h.s.Workout.Update(uid, wid, req)
+ w, err := h.s.Workout.Update(uid, wid, req, requestLocale(c))
if err == sql.ErrNoRows {
utils.Fail(c, utils.CodeWorkoutNotFound, nil)
return
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index 602ccbb..ff67437 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -182,6 +182,25 @@ func alterMigrations() {
ensureIndex("idx_users_email_nocase",
`CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_nocase ON users(email COLLATE NOCASE)`)
}
+
+ // exercises.name and .description are English: only Materialize writes them, and only
+ // from text oedb served in English, so there is nothing to backfill. Every other
+ // language lives here, one row per (exercise, locale), and a reader falls through to
+ // the base row field by field (stores.translationJoin). The cascade is required, not
+ // tidy: ClearUnreferenced deletes exercises with foreign keys on, and a single
+ // translation row without it would make that delete fail.
+ if _, err := DB.Exec(`
+ CREATE TABLE IF NOT EXISTS exercise_translations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ exercise_id INTEGER NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
+ locale TEXT NOT NULL,
+ name TEXT NOT NULL DEFAULT '',
+ description TEXT NOT NULL DEFAULT '',
+ origin TEXT NOT NULL DEFAULT 'human' CHECK (origin IN ('human', 'machine')),
+ UNIQUE (exercise_id, locale)
+ )`); err != nil {
+ log.Fatalf("create exercise_translations: %v", err)
+ }
}
// emailsFoldUnique reports whether no two addresses differ only in letter case, i.e.
diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.go
index 4144cb0..0a89963 100644
--- a/backend/db/migrations_test.go
+++ b/backend/db/migrations_test.go
@@ -900,3 +900,83 @@ func TestEmailNocaseIndex_isIdempotentAcrossBoots(t *testing.T) {
t.Error("index not created after the collision was resolved")
}
}
+
+// TestUpgrade_ExerciseTranslationsOnExistingData upgrades an install that already
+// holds exercises, workouts and programs. The new table must arrive empty and leave
+// every exercise id, name and foreign key as it was: exercises.name stays the English
+// base, so there is nothing to backfill and nothing that may be rewritten.
+func TestUpgrade_ExerciseTranslationsOnExistingData(t *testing.T) {
+ setupMigrationTestDB(t)
+ // An install that has the oedb link already (the column predates this table).
+ ensureColumn("exercises", "oedb_id", `ALTER TABLE exercises ADD COLUMN oedb_id TEXT`)
+
+ 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, description, oedb_id) VALUES ('Bench Press', '1. Press.', 'uuid-1')`); err != nil {
+ t.Fatalf("seed exercise: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO exercises (name, description) VALUES ('My Own Lift', 'mine')`); err != nil {
+ t.Fatalf("seed legacy exercise: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO workouts (user_id, name) VALUES (1, 'W')`); err != nil {
+ t.Fatalf("seed workout: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO workout_exercises (workout_id, exercise_id) VALUES (1, 1), (1, 2)`); err != nil {
+ t.Fatalf("seed workout exercises: %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)
+ }
+ if _, err := DB.Exec(`INSERT INTO programs (user_id, name) VALUES (1, 'P')`); 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), (1, 2, 1)`); err != nil {
+ t.Fatalf("seed program exercises: %v", err)
+ }
+
+ verify := func(boot string) {
+ t.Helper()
+ if n := countRow(t, `SELECT COUNT(*) FROM exercise_translations`); n != 0 {
+ t.Fatalf("%s: exercise_translations holds %d rows, want it empty", boot, n)
+ }
+ for id, want := range map[int]string{1: "Bench Press", 2: "My Own Lift"} {
+ var name string
+ if err := DB.QueryRow(`SELECT name FROM exercises WHERE id = ?`, id).Scan(&name); err != nil || name != want {
+ t.Fatalf("%s: exercise %d = %q (%v), want %q", boot, id, name, err, want)
+ }
+ }
+ if n := countRow(t, `SELECT COUNT(*) FROM exercises WHERE description IN ('1. Press.', 'mine')`); n != 2 {
+ t.Fatalf("%s: exercise descriptions changed", boot)
+ }
+ if n := countRow(t, `SELECT COUNT(*) FROM workout_exercises we JOIN exercises e ON e.id = we.exercise_id`); n != 2 {
+ t.Fatalf("%s: a workout_exercises row lost its exercise (%d resolve)", boot, n)
+ }
+ if n := countRow(t, `SELECT COUNT(*) FROM program_exercises pe JOIN exercises e ON e.id = pe.exercise_id`); n != 2 {
+ t.Fatalf("%s: a program_exercises row lost its exercise (%d resolve)", boot, n)
+ }
+ }
+
+ alterMigrations()
+ verify("first boot")
+ alterMigrations()
+ verify("second boot")
+
+ // The cascade is load-bearing: deleting an exercise must take its translations
+ // with it rather than fail on the foreign key.
+ if _, err := DB.Exec(`INSERT INTO exercises (name) VALUES ('Spare')`); err != nil {
+ t.Fatalf("seed spare: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO exercise_translations (exercise_id, locale, name) VALUES (3, 'es', 'Repuesto')`); err != nil {
+ t.Fatalf("seed translation: %v", err)
+ }
+ if _, err := DB.Exec(`DELETE FROM exercises WHERE id = 3`); err != nil {
+ t.Fatalf("deleting an exercise with a translation: %v", err)
+ }
+ if n := countRow(t, `SELECT COUNT(*) FROM exercise_translations`); n != 0 {
+ t.Fatalf("translation survived its exercise: %d rows", n)
+ }
+ if _, err := DB.Exec(`INSERT INTO exercise_translations (exercise_id, locale, name, origin) VALUES (1, 'es', 'x', 'robot')`); err == nil {
+ t.Fatal("an unknown origin was accepted")
+ }
+}
diff --git a/backend/oedb/client.go b/backend/oedb/client.go
index 93ba61b..539553b 100644
--- a/backend/oedb/client.go
+++ b/backend/oedb/client.go
@@ -87,8 +87,12 @@ type ListParams struct {
MuscleGroup string
Category string
Equipment string
- Page int
- PerPage int
+ // Locale asks for translated text. It is part of the URL, never a header,
+ // because the response cache is keyed by path.
+ Locale string
+ IDs []string
+ Page int
+ PerPage int
}
func (p ListParams) query() url.Values {
@@ -102,6 +106,10 @@ func (p ListParams) query() url.Values {
set("muscle_group", p.MuscleGroup)
set("category", p.Category)
set("equipment", p.Equipment)
+ set("locale", p.Locale)
+ if len(p.IDs) > 0 {
+ v.Set("ids", strings.Join(p.IDs, ","))
+ }
if p.Page > 1 {
v.Set("page", strconv.Itoa(p.Page))
}
@@ -130,11 +138,17 @@ type Image struct {
// Translation is the locale-resolved text for an exercise. oedb keeps name and
// instructions here rather than on the exercise because they vary by locale
// while the taxonomy does not.
+//
+// Each field reports the locale it was actually served in, because a locale that
+// was asked for may be answered per field in English.
type Translation struct {
- Name string `json:"name"`
- Aliases []string `json:"aliases"`
- Instructions []string `json:"instructions"`
- Locale string `json:"name_locale"`
+ Name string `json:"name"`
+ Aliases []string `json:"aliases"`
+ Instructions []string `json:"instructions"`
+ NameLocale string `json:"name_locale"`
+ NameMachineOrigin bool `json:"name_machine_origin"`
+ InstructionsLocale string `json:"instructions_locale"`
+ InstructionsMachineOrigin bool `json:"instructions_machine_origin"`
}
// Exercise is one oedb catalog row, trimmed to the fields Lyftr reads.
diff --git a/backend/oedb/client_test.go b/backend/oedb/client_test.go
index eaef536..6cf6891 100644
--- a/backend/oedb/client_test.go
+++ b/backend/oedb/client_test.go
@@ -3,6 +3,7 @@ package oedb
import (
"compress/gzip"
"context"
+ "encoding/json"
"errors"
"fmt"
"net/http"
@@ -345,3 +346,61 @@ func TestRetryAfter(t *testing.T) {
t.Errorf("retryAfter(\"2\") = %v, %v", d, ok)
}
}
+
+func TestListParams_LocaleAndIDsInURL(t *testing.T) {
+ q := ListParams{Locale: "es", IDs: []string{"a", "b"}}.query()
+ if q.Get("locale") != "es" {
+ t.Errorf("locale = %q, want es", q.Get("locale"))
+ }
+ if q.Get("ids") != "a,b" {
+ t.Errorf("ids = %q, want a,b", q.Get("ids"))
+ }
+
+ q = ListParams{}.query()
+ if q.Has("locale") || q.Has("ids") {
+ t.Errorf("zero params leaked a locale or ids: %v", q)
+ }
+}
+
+// The cache is one process-wide map keyed by path, so the locale has to be in the
+// path. A header would let a Spanish answer be served to an English reader.
+func TestGet_LocaleIsPartOfTheCacheKey(t *testing.T) {
+ var hits int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ atomic.AddInt32(&hits, 1)
+ w.Header().Set("Cache-Control", "public, max-age=300")
+ name := "Squat"
+ if r.URL.Query().Get("locale") == "es" {
+ name = "Sentadilla"
+ }
+ fmt.Fprint(w, listBody(name))
+ }))
+ defer srv.Close()
+
+ c := New(srv.URL, "test")
+ for _, tc := range []struct{ locale, want string }{{"es", "Sentadilla"}, {"", "Squat"}, {"es", "Sentadilla"}, {"", "Squat"}} {
+ res, err := c.List(context.Background(), ListParams{Locale: tc.locale})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := res.Exercises[0].Name(); got != tc.want {
+ t.Errorf("locale %q served %q, want %q", tc.locale, got, tc.want)
+ }
+ }
+ if got := atomic.LoadInt32(&hits); got != 2 {
+ t.Errorf("upstream hits = %d, want 2 (one per locale, then both cached)", got)
+ }
+}
+
+func TestTranslation_DecodesServedLocalesAndMachineFlags(t *testing.T) {
+ var out ListResult
+ body := `{"exercises":[{"id":"u","translation":{"name":"Sentadilla","name_locale":"es","name_machine_origin":true,
+ "instructions":["x"],"instructions_locale":"en","instructions_machine_origin":false}}]}`
+ if err := json.Unmarshal([]byte(body), &out); err != nil {
+ t.Fatal(err)
+ }
+ tr := out.Exercises[0].Translation
+ if tr.NameLocale != "es" || !tr.NameMachineOrigin || tr.InstructionsLocale != "en" || tr.InstructionsMachineOrigin {
+ t.Errorf("decoded %+v", tr)
+ }
+}
diff --git a/backend/stores/exercise.go b/backend/stores/exercise.go
index 0a0458e..19a4fc5 100644
--- a/backend/stores/exercise.go
+++ b/backend/stores/exercise.go
@@ -5,7 +5,9 @@ import (
"database/sql"
"encoding/json"
"errors"
+ "fmt"
"log"
+ "strings"
"time"
"github.com/Cawlumm/lyftr-backend/models"
@@ -24,7 +26,9 @@ func NewExerciseStore(db *sql.DB) *ExerciseStore { return &ExerciseStore{db: db}
// ExerciseFilter holds the optional list filters (empty string = no filter).
type ExerciseFilter struct {
Query, MuscleGroup, Category, Equipment string
- Limit int
+ // Locale is the reader's language. Empty and malformed values mean English.
+ Locale string
+ Limit int
// Page is 1-based; zero and one both mean the first page. Paging is what lets
// the pickers stop downloading the catalog to filter it in the browser.
Page int
@@ -38,7 +42,75 @@ func (f ExerciseFilter) offset() int {
return (f.Page - 1) * f.Limit
}
-const exerciseSelect = `SELECT id, name, muscle_group, secondary_muscles, category, equipment, description, image_url FROM exercises`
+const defaultLocale = "en"
+
+// NormalizeLocale is the one spelling of a locale: language lowercase, everything
+// after the first '-' uppercase, as oedb's normalizeLocale writes it, because the
+// rows stored here carry oedb's spelling. Empty or malformed input is English, the
+// documented meaning of "no usable locale" rather than an error.
+func NormalizeLocale(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if len(raw) > 35 {
+ return defaultLocale
+ }
+ subtags := strings.Split(raw, "-")
+ for i, tag := range subtags {
+ if tag == "" {
+ return defaultLocale
+ }
+ for j := 0; j < len(tag); j++ {
+ c := tag[j]
+ isLetter := c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
+ if !isLetter && (i == 0 || c < '0' || c > '9') {
+ return defaultLocale
+ }
+ }
+ }
+ if n := len(subtags[0]); n < 2 || n > 8 {
+ return defaultLocale
+ }
+ subtags[0] = strings.ToLower(subtags[0])
+ for i := 1; i < len(subtags); i++ {
+ subtags[i] = strings.ToUpper(subtags[i])
+ }
+ return strings.Join(subtags, "-")
+}
+
+// BaseLanguage is the language subtag of a normalized locale: es for es-MX.
+func BaseLanguage(locale string) string {
+ if i := strings.IndexByte(locale, '-'); i > 0 {
+ return locale[:i]
+ }
+ return locale
+}
+
+// Which text an exercise shows is decided here and nowhere else: the reader's
+// locale, then its base language, then the English base row, field by field. Every
+// read that returns exercise text joins through translationJoin and selects
+// localizedName / localizedDescription.
+const (
+ localizedName = `COALESCE(NULLIF(tr.name, ''), e.name)`
+ localizedDescription = `COALESCE(NULLIF(tr.description, ''), e.description)`
+)
+
+// translationJoin returns a LEFT JOIN, aliased tr, onto the single best translation
+// row for each exercise e. English reads join nothing: the base row is English.
+func translationJoin(locale string) (string, []any) {
+ l := NormalizeLocale(locale)
+ if l == defaultLocale {
+ return ` LEFT JOIN exercise_translations tr ON 1 = 0`, nil
+ }
+ return ` LEFT JOIN exercise_translations tr ON tr.id = (
+ SELECT t.id FROM exercise_translations t
+ WHERE t.exercise_id = e.id AND t.locale IN (?, ?)
+ ORDER BY t.locale = ? DESC LIMIT 1)`, []any{l, BaseLanguage(l), l}
+}
+
+func exerciseSelect(locale string) (string, []any) {
+ join, args := translationJoin(locale)
+ return `SELECT e.id, ` + localizedName + `, e.muscle_group, e.secondary_muscles, e.category, e.equipment, ` +
+ localizedDescription + `, e.image_url FROM exercises e` + join, args
+}
type scanner interface{ Scan(dest ...any) error }
@@ -55,25 +127,27 @@ func scanExercise(row scanner, e *models.Exercise) error {
}
func (s *ExerciseStore) List(f ExerciseFilter) ([]models.Exercise, error) {
- q := exerciseSelect + ` WHERE 1=1`
- args := []any{}
+ locale := NormalizeLocale(f.Locale)
+ sel, args := exerciseSelect(locale)
+ q := sel + ` WHERE 1=1`
if f.Query != "" {
- q += " AND name LIKE ?"
- args = append(args, "%"+f.Query+"%")
+ like := "%" + f.Query + "%"
+ q += " AND (e.name LIKE ? OR EXISTS (SELECT 1 FROM exercise_translations t WHERE t.exercise_id = e.id AND t.locale IN (?, ?) AND t.name LIKE ?))"
+ args = append(args, like, locale, BaseLanguage(locale), like)
}
if f.MuscleGroup != "" {
- q += " AND muscle_group = ?"
+ q += " AND e.muscle_group = ?"
args = append(args, f.MuscleGroup)
}
if f.Category != "" {
- q += " AND category = ?"
+ q += " AND e.category = ?"
args = append(args, f.Category)
}
if f.Equipment != "" {
- q += " AND equipment = ?"
+ q += " AND e.equipment = ?"
args = append(args, f.Equipment)
}
- q += " ORDER BY name LIMIT ? OFFSET ?"
+ q += " ORDER BY " + localizedName + " LIMIT ? OFFSET ?"
args = append(args, f.Limit, f.offset())
rows, err := s.db.Query(q, args...)
@@ -93,9 +167,10 @@ func (s *ExerciseStore) List(f ExerciseFilter) ([]models.Exercise, error) {
}
// Get returns one exercise, or sql.ErrNoRows if not found.
-func (s *ExerciseStore) Get(id int64) (models.Exercise, error) {
+func (s *ExerciseStore) Get(id int64, locale string) (models.Exercise, error) {
var e models.Exercise
- if err := scanExercise(s.db.QueryRow(exerciseSelect+` WHERE id = ?`, id), &e); err != nil {
+ sel, args := exerciseSelect(locale)
+ if err := scanExercise(s.db.QueryRow(sel+` WHERE e.id = ?`, append(args, id)...), &e); err != nil {
return models.Exercise{}, err
}
return e, nil
@@ -122,7 +197,13 @@ func (s *ExerciseStore) Count() (int, error) {
// free-exercise-db), while oedb_id is the only key that survives an upstream
// rename. Trying oedb_id first means a renamed exercise updates the row it
// already owns instead of inserting a duplicate under the new name.
-func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase string) ([]models.Exercise, error) {
+//
+// The base row is English and stays English. Each field oedb served in English
+// goes into it; each field served in another language goes into that locale's
+// exercise_translations row instead, so one user's Spanish search never rewrites
+// what an English reader sees. locale is the language that was asked for, and the
+// language the returned rows are shown in.
+func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase, locale string) ([]models.Exercise, error) {
if len(items) == 0 {
return []models.Exercise{}, nil
}
@@ -133,10 +214,13 @@ func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase string) ([]
}
defer tx.Rollback()
+ locale = NormalizeLocale(locale)
+ sel, selArgs := exerciseSelect(locale)
+
byOedbID, err := tx.Prepare(`
UPDATE exercises SET
- name = ?, muscle_group = ?, secondary_muscles = ?, category = ?,
- equipment = ?, description = ?, image_url = ?, slug = ?
+ name = COALESCE(?, name), muscle_group = ?, secondary_muscles = ?, category = ?,
+ equipment = ?, description = COALESCE(?, description), image_url = ?, slug = ?
WHERE oedb_id = ?`)
if err != nil {
return nil, err
@@ -151,7 +235,7 @@ func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase string) ([]
secondary_muscles = excluded.secondary_muscles,
category = excluded.category,
equipment = excluded.equipment,
- description = excluded.description,
+ description = COALESCE(?, description),
image_url = excluded.image_url,
oedb_id = excluded.oedb_id,
slug = excluded.slug`)
@@ -171,13 +255,23 @@ func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase string) ([]
return nil, err
}
- name := it.Name()
- args := []any{
- name, it.MuscleGroup, string(secondaryJSON), it.Category,
- it.Equipment, it.Description(), it.ImageURL(imageBase), it.Slug,
+ name, desc := it.Name(), it.Description()
+ nameEN := servedInEnglish(it.Translation.NameLocale)
+ descEN := servedInEnglish(it.Translation.InstructionsLocale)
+ // nil leaves the base column alone: a field served in another language is
+ // not the English text this column holds.
+ var nameEnglish, descEnglish any
+ if nameEN {
+ nameEnglish = name
+ }
+ if descEN {
+ descEnglish = desc
}
- res, err := byOedbID.Exec(append(append([]any{}, args...), it.ID)...)
+ res, err := byOedbID.Exec(
+ nameEnglish, it.MuscleGroup, string(secondaryJSON), it.Category,
+ it.Equipment, descEnglish, it.ImageURL(imageBase), it.Slug, it.ID,
+ )
if err != nil {
return nil, err
}
@@ -186,17 +280,30 @@ func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase string) ([]
return nil, err
}
if n == 0 {
- insertArgs := []any{
+ if !nameEN {
+ return nil, fmt.Errorf("%w: %s", errNoEnglishBase, it.ID)
+ }
+ baseDesc := ""
+ if descEN {
+ baseDesc = desc
+ }
+ if _, err := byName.Exec(
name, it.MuscleGroup, string(secondaryJSON), it.Category,
- it.Equipment, it.Description(), it.ImageURL(imageBase), it.ID, it.Slug,
+ it.Equipment, baseDesc, it.ImageURL(imageBase), it.ID, it.Slug,
+ descEnglish,
+ ); err != nil {
+ return nil, err
}
- if _, err := byName.Exec(insertArgs...); err != nil {
+ }
+
+ if locale != defaultLocale {
+ if err := replaceTranslation(tx, it, locale, nameEN, descEN); err != nil {
return nil, err
}
}
var e models.Exercise
- row := tx.QueryRow(exerciseSelect+` WHERE oedb_id = ?`, it.ID)
+ row := tx.QueryRow(sel+` WHERE e.oedb_id = ?`, append(append([]any{}, selArgs...), it.ID)...)
if err := scanExercise(row, &e); err != nil {
return nil, err
}
@@ -209,6 +316,61 @@ func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase string) ([]
return out, nil
}
+// errNoEnglishBase is returned when oedb served an exercise's name only in another
+// language and no local row exists to hold the English one. Inserting the translated
+// name as the base would show it to every English reader, so the whole batch rolls
+// back and the caller falls back to the local snapshot.
+var errNoEnglishBase = errors.New("exercises: no English base row for a translated exercise")
+
+// servedInEnglish reports whether a field oedb served is the English text. An empty
+// locale is an oedb that predates name_locale, which only ever served English.
+func servedInEnglish(served string) bool { return NormalizeLocale(served) == defaultLocale }
+
+// replaceTranslation records what oedb served for the requested locale. It drops
+// the rows for the requested locale and its base language first, so a translation
+// upstream has since dropped (a new revision does that) stops being shown, then
+// writes one row if any field really was served in another language. A field that
+// fell back to English is stored empty so the read falls through to the base row.
+func replaceTranslation(tx *sql.Tx, it oedb.Exercise, locale string, nameEN, descEN bool) error {
+ var exerciseID int64
+ if err := tx.QueryRow(`SELECT id FROM exercises WHERE oedb_id = ?`, it.ID).Scan(&exerciseID); err != nil {
+ return err
+ }
+ if _, err := tx.Exec(
+ `DELETE FROM exercise_translations WHERE exercise_id = ? AND locale IN (?, ?)`,
+ exerciseID, locale, BaseLanguage(locale),
+ ); err != nil {
+ return err
+ }
+ if nameEN && descEN {
+ return nil
+ }
+
+ served, name, desc, origin := NormalizeLocale(it.Translation.NameLocale), "", "", "human"
+ if nameEN {
+ served = NormalizeLocale(it.Translation.InstructionsLocale)
+ } else {
+ name = it.Name()
+ if it.Translation.NameMachineOrigin {
+ origin = "machine"
+ }
+ }
+ if !descEN {
+ desc = it.Description()
+ if it.Translation.InstructionsMachineOrigin {
+ origin = "machine"
+ }
+ }
+ _, err := tx.Exec(
+ `INSERT INTO exercise_translations (exercise_id, locale, name, description, origin)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(exercise_id, locale) DO UPDATE SET
+ name = excluded.name, description = excluded.description, origin = excluded.origin`,
+ exerciseID, served, name, desc, origin,
+ )
+ return err
+}
+
// UseCatalog points this store at an upstream open-exercise-db instance.
//
// Optional by design: with no catalog the store answers from the local table
@@ -235,7 +397,12 @@ func (s *ExerciseStore) Search(ctx context.Context, f ExerciseFilter) ([]models.
return s.List(f)
}
- out, err := s.Materialize(items, s.catalog.BaseURL())
+ if err := s.ensureEnglishBase(ctx, items); err != nil {
+ log.Printf("exercises: could not fetch English base rows, serving local snapshot: %v", err)
+ return s.List(f)
+ }
+
+ out, err := s.Materialize(items, s.catalog.BaseURL(), f.Locale)
if err != nil {
log.Printf("exercises: could not record catalog results, serving local snapshot: %v", err)
return s.List(f)
@@ -243,6 +410,55 @@ func (s *ExerciseStore) Search(ctx context.Context, f ExerciseFilter) ([]models.
return out, nil
}
+// ensureEnglishBase records the English row of any exercise that arrived with a
+// translated name and is not held locally yet. Materialize refuses to invent an
+// English base from translated text, so this has to happen first: the exercises are
+// re-read by id with no locale, which is the only way to learn their English name.
+func (s *ExerciseStore) ensureEnglishBase(ctx context.Context, items []oedb.Exercise) error {
+ var missing []string
+ for _, it := range items {
+ if servedInEnglish(it.Translation.NameLocale) {
+ continue
+ }
+ var held int
+ err := s.db.QueryRow(`SELECT COUNT(*) FROM exercises WHERE oedb_id = ?`, it.ID).Scan(&held)
+ if err != nil {
+ return err
+ }
+ if held == 0 {
+ missing = append(missing, it.ID)
+ }
+ }
+ if len(missing) == 0 {
+ return nil
+ }
+
+ ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
+ defer cancel()
+ for len(missing) > 0 {
+ batch := missing[:min(len(missing), 100)]
+ missing = missing[len(batch):]
+ res, err := s.catalog.List(ctx, oedb.ListParams{IDs: batch, PerPage: len(batch)})
+ if err != nil {
+ return err
+ }
+ wanted := make(map[string]bool, len(batch))
+ for _, id := range batch {
+ wanted[id] = true
+ }
+ english := res.Exercises[:0]
+ for _, it := range res.Exercises {
+ if wanted[it.ID] {
+ english = append(english, it)
+ }
+ }
+ if _, err := s.Materialize(english, s.catalog.BaseURL(), defaultLocale); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
// fetchCatalog picks between the paged endpoint and the bulk export.
//
// The picker asks for the whole catalog (limit=1000) to build its client-side
@@ -252,7 +468,13 @@ func (s *ExerciseStore) Search(ctx context.Context, f ExerciseFilter) ([]models.
// filtered stays on List, where the filter is what keeps the response small.
func (s *ExerciseStore) fetchCatalog(ctx context.Context, f ExerciseFilter) ([]oedb.Exercise, error) {
filtered := f.Query != "" || f.MuscleGroup != "" || f.Category != "" || f.Equipment != ""
- if !filtered && f.Limit > 100 && f.Page < 2 {
+ // The export takes no locale, so only an English read may use it. English is
+ // sent as "" so its upstream URLs, and cache entries, are the same as before.
+ locale := NormalizeLocale(f.Locale)
+ if locale == defaultLocale {
+ locale = ""
+ }
+ if !filtered && f.Limit > 100 && f.Page < 2 && locale == "" {
// The export is ~300 KB and measured around 14s against the hosted
// instance, so it gets a deadline sized for that. It is also cached
// upstream-style for 900s, so only the first caller after a cold start
@@ -282,6 +504,7 @@ func (s *ExerciseStore) fetchCatalog(ctx context.Context, f ExerciseFilter) ([]o
MuscleGroup: f.MuscleGroup,
Category: f.Category,
Equipment: f.Equipment,
+ Locale: locale,
Page: page,
PerPage: f.Limit - len(out),
})
@@ -349,7 +572,7 @@ func (s *ExerciseStore) RefreshCached(ctx context.Context) (int, error) {
}
}
- out, err := s.Materialize(keep, s.catalog.BaseURL())
+ out, err := s.Materialize(keep, s.catalog.BaseURL(), defaultLocale)
if err != nil {
return 0, err
}
diff --git a/backend/stores/exercise_locale_test.go b/backend/stores/exercise_locale_test.go
new file mode 100644
index 0000000..e454598
--- /dev/null
+++ b/backend/stores/exercise_locale_test.go
@@ -0,0 +1,633 @@
+package stores
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/Cawlumm/lyftr-backend/models"
+ "github.com/Cawlumm/lyftr-backend/oedb"
+)
+
+const imageBase = "https://oedb.test"
+
+// served builds an oedb row whose name and instructions came back in the given
+// locales, which is what a localized read of the real catalog returns.
+func served(id, name, nameLocale string, steps []string, stepsLocale string) oedb.Exercise {
+ ex := catalogExercise(id, name)
+ ex.Translation.NameLocale = nameLocale
+ ex.Translation.Instructions = steps
+ ex.Translation.InstructionsLocale = stepsLocale
+ return ex
+}
+
+func englishSquat() oedb.Exercise {
+ return served("uuid-1", "Squat", "en", []string{"Stand tall.", "Sit down."}, "en")
+}
+
+func spanishSquat() oedb.Exercise {
+ return served("uuid-1", "Sentadilla", "es", []string{"Ponte recto.", "Siéntate."}, "es")
+}
+
+func materialize(t *testing.T, s *ExerciseStore, locale string, items ...oedb.Exercise) []models.Exercise {
+ t.Helper()
+ out, err := s.Materialize(items, imageBase, locale)
+ if err != nil {
+ t.Fatalf("Materialize(%q): %v", locale, err)
+ }
+ return out
+}
+
+func mustGet(t *testing.T, s *ExerciseStore, id int64, locale string) models.Exercise {
+ t.Helper()
+ e, err := s.Get(id, locale)
+ if err != nil {
+ t.Fatalf("Get(%d, %q): %v", id, locale, err)
+ }
+ return e
+}
+
+func countRows(t *testing.T, conn *sql.DB, query string, args ...any) int {
+ t.Helper()
+ var n int
+ if err := conn.QueryRow(query, args...).Scan(&n); err != nil {
+ t.Fatalf("%s: %v", query, err)
+ }
+ return n
+}
+
+func TestNormalizeLocale(t *testing.T) {
+ cases := map[string]string{
+ "es": "es",
+ "ES": "es",
+ "es-mx": "es-MX",
+ " pt-br ": "pt-BR",
+ "zh-hant": "zh-HANT",
+ "en-gb": "en-GB",
+ "": "en",
+ " ": "en",
+ "!!": "en",
+ "e": "en",
+ "es_ES": "en",
+ "es-": "en",
+ "-es": "en",
+ "es--MX": "en",
+ "1s": "en",
+ strings.Repeat("a", 36): "en",
+ strings.Repeat("a", 200): "en",
+ "es-" + strings.Repeat("x", 40): "en",
+ }
+ for in, want := range cases {
+ if got := NormalizeLocale(in); got != want {
+ t.Errorf("NormalizeLocale(%q) = %q, want %q", in, got, want)
+ }
+ if again := NormalizeLocale(want); again != want {
+ t.Errorf("NormalizeLocale is not idempotent: %q -> %q", want, again)
+ }
+ }
+}
+
+func TestMaterialize_LocalizedFetchKeepsEnglishBase(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+
+ base := materialize(t, s, "en", englishSquat())
+ out := materialize(t, s, "es", spanishSquat())
+
+ if out[0].Name != "Sentadilla" {
+ t.Errorf("returned name = %q, want the Spanish one", out[0].Name)
+ }
+ if out[0].ID != base[0].ID {
+ t.Errorf("localized fetch changed the row id: %d != %d", out[0].ID, base[0].ID)
+ }
+
+ var name, desc string
+ conn.QueryRow(`SELECT name, description FROM exercises WHERE id = ?`, base[0].ID).Scan(&name, &desc)
+ if name != "Squat" || desc != "1. Stand tall.\n2. Sit down." {
+ t.Errorf("base row = (%q, %q), want it still English", name, desc)
+ }
+
+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations`); n != 1 {
+ t.Fatalf("translation rows = %d, want 1", n)
+ }
+ var tl, tn, td, origin string
+ conn.QueryRow(`SELECT locale, name, description, origin FROM exercise_translations`).Scan(&tl, &tn, &td, &origin)
+ if tl != "es" || tn != "Sentadilla" || td != "1. Ponte recto.\n2. Siéntate." || origin != "human" {
+ t.Errorf("translation = (%q, %q, %q, %q)", tl, tn, td, origin)
+ }
+
+ reads := map[string]string{"en": "Squat", "": "Squat", "fr": "Squat", "es": "Sentadilla", "es-MX": "Sentadilla", "ES-mx": "Sentadilla", "!!": "Squat"}
+ for locale, want := range reads {
+ if got := mustGet(t, s, base[0].ID, locale).Name; got != want {
+ t.Errorf("Get(%q).Name = %q, want %q", locale, got, want)
+ }
+ }
+}
+
+func TestMaterialize_RegionalRequestStoresServedLocale(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ base := materialize(t, s, "en", englishSquat())
+
+ // es-MX was asked for, oedb answered with its es text.
+ materialize(t, s, "es-MX", spanishSquat())
+
+ var tl string
+ conn.QueryRow(`SELECT locale FROM exercise_translations`).Scan(&tl)
+ if tl != "es" {
+ t.Errorf("stored locale = %q, want the served es", tl)
+ }
+ if got := mustGet(t, s, base[0].ID, "es-MX").Name; got != "Sentadilla" {
+ t.Errorf("es-MX read = %q, want the es fallback", got)
+ }
+}
+
+func TestMaterialize_PerFieldFallback(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ base := materialize(t, s, "en", englishSquat())
+
+ // Name translated, instructions fell back to English (and were edited upstream).
+ materialize(t, s, "es", served("uuid-1", "Sentadilla", "es", []string{"Stand tall.", "Sit lower."}, "en"))
+
+ var tn, td string
+ conn.QueryRow(`SELECT name, description FROM exercise_translations`).Scan(&tn, &td)
+ if tn != "Sentadilla" || td != "" {
+ t.Errorf("translation = (%q, %q), want the name only", tn, td)
+ }
+ got := mustGet(t, s, base[0].ID, "es")
+ if got.Name != "Sentadilla" || got.Description != "1. Stand tall.\n2. Sit lower." {
+ t.Errorf("es read = (%q, %q), want Spanish name and refreshed English description", got.Name, got.Description)
+ }
+ if en := mustGet(t, s, base[0].ID, "en"); en.Name != "Squat" {
+ t.Errorf("en name = %q", en.Name)
+ }
+
+ // The opposite case: name fell back, instructions translated.
+ materialize(t, s, "es", served("uuid-1", "Squat", "en", []string{"Ponte recto."}, "es"))
+ got = mustGet(t, s, base[0].ID, "es")
+ if got.Name != "Squat" || got.Description != "1. Ponte recto." {
+ t.Errorf("es read = (%q, %q), want English name and Spanish description", got.Name, got.Description)
+ }
+ if en := mustGet(t, s, base[0].ID, "en"); en.Description != "1. Stand tall.\n2. Sit lower." {
+ t.Errorf("en description = %q, want the base left alone", en.Description)
+ }
+}
+
+func TestMaterialize_UntranslatedLocalizedFetchDeletesStaleRow(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ base := materialize(t, s, "en", englishSquat())
+ materialize(t, s, "es", spanishSquat())
+
+ edited := served("uuid-1", "Squat", "en", []string{"Stand tall.", "Sit lower."}, "en")
+ out := materialize(t, s, "es", edited)
+
+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations`); n != 0 {
+ t.Errorf("translation rows = %d, want the stale one removed", n)
+ }
+ if out[0].Name != "Squat" || out[0].Description != "1. Stand tall.\n2. Sit lower." {
+ t.Errorf("returned = (%q, %q)", out[0].Name, out[0].Description)
+ }
+ if got := mustGet(t, s, base[0].ID, "es"); got.Name != "Squat" {
+ t.Errorf("es read = %q, want English once the translation is gone", got.Name)
+ }
+}
+
+func TestMaterialize_OnlyReplacesItsOwnLocales(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ base := materialize(t, s, "en", englishSquat())
+ materialize(t, s, "es", spanishSquat())
+ materialize(t, s, "fr", served("uuid-1", "Squat (fr)", "fr", []string{"Debout."}, "fr"))
+
+ materialize(t, s, "es", englishSquat())
+
+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations WHERE locale = 'fr'`); n != 1 {
+ t.Errorf("fr rows = %d, want the es fetch to leave them alone", n)
+ }
+ if got := mustGet(t, s, base[0].ID, "fr").Name; got != "Squat (fr)" {
+ t.Errorf("fr read = %q", got)
+ }
+}
+
+func TestMaterialize_RefusesNonEnglishBaseInsert(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+
+ _, err := s.Materialize([]oedb.Exercise{spanishSquat()}, imageBase, "es")
+ if err == nil {
+ t.Fatal("a translated item with no English base row was accepted")
+ }
+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises`); n != 0 {
+ t.Errorf("exercises = %d, want nothing written", n)
+ }
+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations`); n != 0 {
+ t.Errorf("translations = %d, want nothing written", n)
+ }
+}
+
+func TestMaterialize_RefusalRollsBackTheWholeBatch(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+
+ other := served("uuid-2", "Deadlift", "en", []string{"Lift."}, "en")
+ if _, err := s.Materialize([]oedb.Exercise{other, spanishSquat()}, imageBase, "es"); err == nil {
+ t.Fatal("expected the batch to fail")
+ }
+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises`); n != 0 {
+ t.Errorf("exercises = %d, want the English item rolled back with the batch", n)
+ }
+}
+
+func TestMaterialize_MachineOrigin(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ materialize(t, s, "en", englishSquat())
+
+ machine := spanishSquat()
+ machine.Translation.NameMachineOrigin = true
+ materialize(t, s, "es", machine)
+
+ var origin string
+ conn.QueryRow(`SELECT origin FROM exercise_translations`).Scan(&origin)
+ if origin != "machine" {
+ t.Errorf("origin = %q, want machine", origin)
+ }
+
+ // A machine flag on a field that fell back to English does not count.
+ fellBack := served("uuid-1", "Sentadilla", "es", []string{"Stand tall."}, "en")
+ fellBack.Translation.InstructionsMachineOrigin = true
+ materialize(t, s, "es", fellBack)
+ conn.QueryRow(`SELECT origin FROM exercise_translations`).Scan(&origin)
+ if origin != "human" {
+ t.Errorf("origin = %q, want human", origin)
+ }
+}
+
+func TestMaterialize_OlderOedbWithoutLocaleFieldsIsEnglish(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+
+ out := materialize(t, s, "es", catalogExercise("uuid-1", "Squat"))
+ if out[0].Name != "Squat" {
+ t.Errorf("name = %q", out[0].Name)
+ }
+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations`); n != 0 {
+ t.Errorf("translations = %d, want none", n)
+ }
+}
+
+func TestUserCreatedRowNeverLocalized(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ res, err := conn.Exec(`INSERT INTO exercises (name, muscle_group, category) VALUES ('My Thing', 'chest', 'strength')`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ id, _ := res.LastInsertId()
+
+ materialize(t, s, "en", englishSquat())
+ materialize(t, s, "es", spanishSquat())
+ for _, locale := range []string{"es", "fr", "en", ""} {
+ if got := mustGet(t, s, id, locale).Name; got != "My Thing" {
+ t.Errorf("Get(%q).Name = %q, want the name as typed", locale, got)
+ }
+ }
+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations WHERE exercise_id = ?`, id); n != 0 {
+ t.Errorf("translations = %d, want none for a row with no oedb_id", n)
+ }
+}
+
+func TestList_LocalSearchCoversTranslationAndEnglish(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ materialize(t, s, "en", englishSquat(), served("uuid-2", "Bench Press", "en", []string{"Press."}, "en"), served("uuid-3", "Curl", "en", []string{"Curl."}, "en"))
+ materialize(t, s, "es", spanishSquat())
+ materialize(t, s, "es", served("uuid-3", "Flexión de bíceps", "es", []string{"Flexiona."}, "es"))
+
+ names := func(q, locale string) []string {
+ t.Helper()
+ list, err := s.List(ExerciseFilter{Query: q, Locale: locale, Limit: 50})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for _, e := range list {
+ out = append(out, e.Name)
+ }
+ return out
+ }
+ eq := func(got []string, want ...string) {
+ t.Helper()
+ if strings.Join(got, "|") != strings.Join(want, "|") {
+ t.Errorf("got %v, want %v", got, want)
+ }
+ }
+
+ eq(names("sentadilla", "es"), "Sentadilla")
+ eq(names("sentadilla", "es-MX"), "Sentadilla")
+ eq(names("sentadilla", "en"))
+ eq(names("sentadilla", "fr"))
+ eq(names("squat", "es"), "Sentadilla")
+ eq(names("squat", "en"), "Squat")
+ // Ordered by the name the reader sees: Bench Press, Flexión..., Sentadilla.
+ eq(names("", "es"), "Bench Press", "Flexión de bíceps", "Sentadilla")
+ eq(names("", "en"), "Bench Press", "Curl", "Squat")
+}
+
+func TestClearUnreferenced_CascadesTranslations(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ materialize(t, s, "en", englishSquat(), served("uuid-2", "Deadlift", "en", []string{"Lift."}, "en"))
+ materialize(t, s, "es", spanishSquat())
+ materialize(t, s, "es", served("uuid-2", "Peso muerto", "es", []string{"Levanta."}, "es"))
+
+ uid := seedUser(t, conn)
+ var keep int64
+ conn.QueryRow(`SELECT id FROM exercises WHERE oedb_id = 'uuid-2'`).Scan(&keep)
+ pid := seedProgram(t, conn, uid, keep)
+ _ = pid
+
+ n, err := s.ClearUnreferenced()
+ if err != nil {
+ t.Fatalf("ClearUnreferenced: %v", err)
+ }
+ if n != 1 {
+ t.Errorf("deleted %d, want the one unreferenced exercise", n)
+ }
+ if c := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations`); c != 1 {
+ t.Errorf("translation rows = %d, want only the referenced exercise's", c)
+ }
+ if c := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations WHERE exercise_id = ?`, keep); c != 1 {
+ t.Errorf("the referenced exercise lost its translation")
+ }
+}
+
+func seedUser(t *testing.T, conn *sql.DB) int64 {
+ t.Helper()
+ res, err := conn.Exec(`INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'x')`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ id, _ := res.LastInsertId()
+ return id
+}
+
+// seedProgram stores a one-exercise routine directly, bypassing the stores under test.
+func seedProgram(t *testing.T, conn *sql.DB, uid, exerciseID int64) int64 {
+ t.Helper()
+ res, err := conn.Exec(`INSERT INTO programs (user_id, name) VALUES (?, 'P')`, uid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pid, _ := res.LastInsertId()
+ res, err = conn.Exec(`INSERT INTO program_days (program_id, order_index, name) VALUES (?, 0, 'D')`, pid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ did, _ := res.LastInsertId()
+ if _, err := conn.Exec(`INSERT INTO program_exercises (program_id, program_day_id, exercise_id, order_index) VALUES (?, ?, ?, 0)`, pid, did, exerciseID); err != nil {
+ t.Fatal(err)
+ }
+ return pid
+}
+
+func TestWorkoutAndProgramReadsResolveLocale(t *testing.T) {
+ conn := testDB(t)
+ st := New(conn)
+ base := materialize(t, st.Exercise, "en", englishSquat())
+ materialize(t, st.Exercise, "es", spanishSquat())
+ exID := base[0].ID
+ uid := seedUser(t, conn)
+
+ workoutName := func(w models.Workout) string { return w.Exercises[0].Exercise.Name }
+ programName := func(p models.Program) string { return p.Days[0].Exercises[0].Exercise.Name }
+ check := func(what, locale, got, want string) {
+ t.Helper()
+ if got != want {
+ t.Errorf("%s (%q) = %q, want %q", what, locale, got, want)
+ }
+ }
+
+ wreq := models.CreateWorkoutRequest{
+ Name: "W",
+ StartedAt: time.Now(),
+ Exercises: []models.CreateWorkoutExerciseReq{{ExerciseID: exID, Sets: []models.CreateSetReq{{SetNumber: 1, Reps: 5, Weight: 100}}}},
+ }
+ preq := models.CreateProgramRequest{
+ Name: "P",
+ Days: []models.CreateProgramDayReq{{Name: "D", Exercises: []models.CreateProgramExerciseReq{
+ {ExerciseID: exID, Sets: []models.CreateProgramSetReq{{SetNumber: 1, TargetReps: 5, TargetWeight: 100}}},
+ }}},
+ }
+
+ for locale, want := range map[string]string{"es": "Sentadilla", "es-MX": "Sentadilla", "en": "Squat", "": "Squat"} {
+ w, _, err := st.CreateWorkoutWithProgression(uid, wreq, locale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ check("CreateWorkoutWithProgression", locale, workoutName(w), want)
+
+ got, err := st.Workout.Get(uid, w.ID, locale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ check("Workout.Get", locale, workoutName(got), want)
+
+ list, err := st.Workout.List(uid, WorkoutFilter{Limit: 50}, locale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, lw := range list {
+ check("Workout.List", locale, workoutName(lw), want)
+ }
+
+ upd, err := st.Workout.Update(uid, w.ID, wreq, locale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ check("Workout.Update", locale, workoutName(upd), want)
+
+ p, err := st.Program.Create(uid, preq, locale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ check("Program.Create", locale, programName(p), want)
+
+ gp, err := st.Program.Get(uid, p.ID, locale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ check("Program.Get", locale, programName(gp), want)
+
+ plist, err := st.Program.List(uid, ProgramFilter{Limit: 50}, locale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, lp := range plist {
+ check("Program.List", locale, programName(lp), want)
+ }
+
+ preq.DayIDsKnown = true
+ preq.Days[0].ID = gp.Days[0].ID
+ up, err := st.Program.Update(uid, p.ID, preq, locale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ check("Program.Update", locale, programName(up), want)
+
+ rp, err := st.Program.ResolveSuggestions(uid, p.ID, nil, nil, locale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ check("Program.ResolveSuggestions", locale, programName(rp), want)
+ preq.DayIDsKnown, preq.Days[0].ID = false, 0
+ }
+}
+
+// fakeOEDB serves the catalog the way the real one does for this test's single
+// exercise, and records every request URL.
+type fakeOEDB struct {
+ mu sync.Mutex
+ urls []string
+ srv *httptest.Server
+}
+
+func newFakeOEDB(t *testing.T, handle func(w http.ResponseWriter, r *http.Request)) *fakeOEDB {
+ t.Helper()
+ f := &fakeOEDB{}
+ f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ f.urls = append(f.urls, r.URL.RequestURI())
+ f.mu.Unlock()
+ handle(w, r)
+ }))
+ t.Cleanup(f.srv.Close)
+ return f
+}
+
+func (f *fakeOEDB) requests() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]string(nil), f.urls...)
+}
+
+func TestSearch_LocalizedCatalogQuery(t *testing.T) {
+ f := newFakeOEDB(t, func(w http.ResponseWriter, r *http.Request) {
+ q := r.URL.Query()
+ switch {
+ case q.Get("locale") == "es":
+ fmt.Fprint(w, `{"exercises":[{"id":"uuid-1","slug":"squat","muscle_group":"legs",
+ "translation":{"name":"Sentadilla","instructions":["Ponte recto."],"name_locale":"es","instructions_locale":"es"}}],"total":1}`)
+ case q.Get("ids") == "uuid-1":
+ fmt.Fprint(w, `{"exercises":[{"id":"uuid-1","slug":"squat","muscle_group":"legs",
+ "translation":{"name":"Squat","instructions":["Stand tall."],"name_locale":"en","instructions_locale":"en"}}],"total":1}`)
+ default:
+ fmt.Fprint(w, `{"exercises":[{"id":"uuid-1","slug":"squat","muscle_group":"legs",
+ "translation":{"name":"Squat","instructions":["Stand tall."],"name_locale":"en","instructions_locale":"en"}}],"total":1}`)
+ }
+ })
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ s.UseCatalog(oedb.New(f.srv.URL, "test"))
+
+ es, err := s.Search(context.Background(), ExerciseFilter{Query: "sentadilla", Locale: "es", Limit: 10})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(es) != 1 || es[0].Name != "Sentadilla" {
+ t.Fatalf("es results = %+v, want the Spanish name", es)
+ }
+
+ var sawList, sawIDs bool
+ for _, u := range f.requests() {
+ if strings.Contains(u, "locale=es") && strings.Contains(u, "q=sentadilla") {
+ sawList = true
+ }
+ if strings.Contains(u, "ids=uuid-1") {
+ sawIDs = true
+ if strings.Contains(u, "locale=") {
+ t.Errorf("the base-row fetch carried a locale: %s", u)
+ }
+ }
+ }
+ if !sawList || !sawIDs {
+ t.Errorf("requests = %v, want a localized list and an ids fetch for the unseen exercise", f.requests())
+ }
+
+ en, err := s.Search(context.Background(), ExerciseFilter{Query: "squat", Limit: 10})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(en) != 1 || en[0].Name != "Squat" || en[0].ID != es[0].ID {
+ t.Fatalf("en results = %+v, want the same row in English: the shared row was never overwritten", en)
+ }
+ for _, u := range f.requests()[len(f.requests())-1:] {
+ if strings.Contains(u, "locale=") {
+ t.Errorf("an English search sent a locale: %s", u)
+ }
+ }
+}
+
+func TestSearch_FallsBackWhenEnglishBaseCannotBeFetched(t *testing.T) {
+ f := newFakeOEDB(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Query().Get("ids") != "" {
+ http.Error(w, `{"error":"unknown filter"}`, http.StatusUnprocessableEntity)
+ return
+ }
+ fmt.Fprint(w, `{"exercises":[{"id":"uuid-1","slug":"squat",
+ "translation":{"name":"Sentadilla","instructions":[],"name_locale":"es","instructions_locale":"es"}}],"total":1}`)
+ })
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ s.UseCatalog(oedb.New(f.srv.URL, "test"))
+
+ out, err := s.Search(context.Background(), ExerciseFilter{Query: "sentadilla", Locale: "es", Limit: 10})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(out) != 0 {
+ t.Errorf("results = %+v, want the (empty) local snapshot", out)
+ }
+ if n := countRows(t, conn, `SELECT COUNT(*) FROM exercises`); n != 0 {
+ t.Errorf("exercises = %d, a translated name was inserted as a base", n)
+ }
+}
+
+func TestSearch_NonEnglishBulkSkipsExport(t *testing.T) {
+ f := newFakeOEDB(t, func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, `{"exercises":[],"total":0}`)
+ })
+ s := NewExerciseStore(testDB(t))
+ s.UseCatalog(oedb.New(f.srv.URL, "test"))
+
+ if _, err := s.Search(context.Background(), ExerciseFilter{Limit: 500, Locale: "es"}); err != nil {
+ t.Fatal(err)
+ }
+ for _, u := range f.requests() {
+ if strings.Contains(u, "/exercises/export") {
+ t.Errorf("a Spanish bulk read used the export: %s", u)
+ }
+ if !strings.Contains(u, "locale=es") {
+ t.Errorf("list request without the locale: %s", u)
+ }
+ }
+ if len(f.requests()) == 0 {
+ t.Fatal("no request made")
+ }
+
+ if _, err := s.Search(context.Background(), ExerciseFilter{Limit: 500, Locale: "EN"}); err != nil {
+ t.Fatal(err)
+ }
+ last := f.requests()[len(f.requests())-1]
+ if !strings.Contains(last, "/exercises/export") {
+ t.Errorf("an English bulk read left the export: %s", last)
+ }
+}
diff --git a/backend/stores/exercise_test.go b/backend/stores/exercise_test.go
index 88af658..feab29d 100644
--- a/backend/stores/exercise_test.go
+++ b/backend/stores/exercise_test.go
@@ -73,7 +73,7 @@ func TestMaterialize_AdoptsLegacyRowByNameAndKeepsID(t *testing.T) {
}
legacyID, _ := res.LastInsertId()
- out, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Bench Press")}, "https://oedb.test")
+ out, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Bench Press")}, "https://oedb.test", "en")
if err != nil {
t.Fatalf("materialize: %v", err)
}
@@ -112,12 +112,12 @@ func TestMaterialize_UpstreamRenameUpdatesSameRow(t *testing.T) {
conn := testDB(t)
s := NewExerciseStore(conn)
- first, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Barbell Bench Press")}, "https://oedb.test")
+ first, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Barbell Bench Press")}, "https://oedb.test", "en")
if err != nil {
t.Fatalf("first materialize: %v", err)
}
- second, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Bench Press (Barbell)")}, "https://oedb.test")
+ second, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Bench Press (Barbell)")}, "https://oedb.test", "en")
if err != nil {
t.Fatalf("second materialize: %v", err)
}
@@ -139,7 +139,7 @@ func TestMaterialize_DecodesSecondaryMuscles(t *testing.T) {
conn := testDB(t)
s := NewExerciseStore(conn)
- out, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Bench Press")}, "https://oedb.test")
+ out, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Bench Press")}, "https://oedb.test", "en")
if err != nil {
t.Fatalf("materialize: %v", err)
}
@@ -261,7 +261,7 @@ func TestRefreshCached_UpdatesHeldRowsWithoutImporting(t *testing.T) {
s := NewExerciseStore(conn)
s.UseCatalog(oedb.New(srv.URL, "test"))
- if _, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Held Original")}, srv.URL); err != nil {
+ if _, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Held Original")}, srv.URL, "en"); err != nil {
t.Fatalf("seed held row: %v", err)
}
diff --git a/backend/stores/program.go b/backend/stores/program.go
index 53dd2d6..2da4239 100644
--- a/backend/stores/program.go
+++ b/backend/stores/program.go
@@ -25,7 +25,7 @@ func scanProgram(row interface{ Scan(...any) error }, p *models.Program) error {
return row.Scan(&p.ID, &p.UserID, &p.Name, &p.Notes, &p.CreatedAt)
}
-func (s *ProgramStore) List(uid int64, f ProgramFilter) ([]models.Program, error) {
+func (s *ProgramStore) List(uid int64, f ProgramFilter, locale string) ([]models.Program, error) {
var rows *sql.Rows
var err error
if f.Query != "" {
@@ -63,7 +63,7 @@ func (s *ProgramStore) List(uid int64, f ProgramFilter) ([]models.Program, error
// of that, and SetMaxOpenConns(1) serializes every one of them on the process's
// single connection.
for i := range programs {
- days, err := s.loadDays(programs[i].ID)
+ days, err := s.loadDays(programs[i].ID, locale)
if err != nil {
return nil, err
}
@@ -80,25 +80,25 @@ func (s *ProgramStore) List(uid int64, f ProgramFilter) ([]models.Program, error
}
// Get returns a user-owned program with its days/exercises/sets, or sql.ErrNoRows.
-func (s *ProgramStore) Get(uid, id int64) (models.Program, error) {
+func (s *ProgramStore) Get(uid, id int64, locale string) (models.Program, error) {
var p models.Program
if err := scanProgram(
s.db.QueryRow(`SELECT `+programCols+` FROM programs WHERE id = ? AND user_id = ?`, id, uid), &p,
); err != nil {
return models.Program{}, err
}
- if err := s.hydrate(&p); err != nil {
+ if err := s.hydrate(&p, locale); err != nil {
return models.Program{}, err
}
return p, nil
}
-func (s *ProgramStore) get(id int64) (models.Program, error) {
+func (s *ProgramStore) get(id int64, locale string) (models.Program, error) {
var p models.Program
if err := scanProgram(s.db.QueryRow(`SELECT `+programCols+` FROM programs WHERE id = ?`, id), &p); err != nil {
return models.Program{}, err
}
- if err := s.hydrate(&p); err != nil {
+ if err := s.hydrate(&p, locale); err != nil {
return models.Program{}, err
}
return p, nil
@@ -106,8 +106,8 @@ func (s *ProgramStore) get(id int64) (models.Program, error) {
// 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)
+func (s *ProgramStore) hydrate(p *models.Program, locale string) error {
+ days, err := s.loadDays(p.ID, locale)
if err != nil {
return err
}
@@ -255,7 +255,7 @@ func (s *ProgramStore) currentDayIndex(uid int64, programs []models.Program) (ma
return result, rows.Err()
}
-func (s *ProgramStore) Create(uid int64, req models.CreateProgramRequest) (models.Program, error) {
+func (s *ProgramStore) Create(uid int64, req models.CreateProgramRequest, locale string) (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)
if err != nil {
@@ -273,7 +273,7 @@ func (s *ProgramStore) Create(uid int64, req models.CreateProgramRequest) (model
if err != nil {
return models.Program{}, err
}
- return s.get(pid)
+ return s.get(pid, locale)
}
// Update replaces a user-owned program and its days/exercises/sets in one tx.
@@ -306,7 +306,7 @@ func (s *ProgramStore) Create(uid int64, req models.CreateProgramRequest) (model
// (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) {
+func (s *ProgramStore) Update(uid, id int64, req models.CreateProgramRequest, locale string) (models.Program, error) {
if err := inTxDo(s.db, func(tx *sql.Tx) error {
var ownedID int64
if err := tx.QueryRow(`SELECT id FROM programs WHERE id = ? AND user_id = ?`, id, uid).Scan(&ownedID); err != nil {
@@ -396,7 +396,7 @@ func (s *ProgramStore) Update(uid, id int64, req models.CreateProgramRequest) (m
}); err != nil {
return models.Program{}, err
}
- return s.get(id)
+ return s.get(id, locale)
}
// dropDayLinkage severs workouts.program_day_id for a day that's being deleted or
@@ -526,7 +526,7 @@ func suggestTargetsTx(tx *sql.Tx, uid, programID int64, sets []ProgressInput) (s
// target_*; both paths clear the suggestion. Ownership-gated, and every id is re-scoped
// to this program via the pe.program_id sub-select — the same IDOR guard as SuggestTargets,
// so a client can't touch another user's routine by guessing ids.
-func (s *ProgramStore) ResolveSuggestions(uid, programID int64, accept, dismiss []int64) (models.Program, error) {
+func (s *ProgramStore) ResolveSuggestions(uid, programID int64, accept, dismiss []int64, locale string) (models.Program, error) {
err := inTxDo(s.db, func(tx *sql.Tx) error {
var ownedID int64
if err := tx.QueryRow(`SELECT id FROM programs WHERE id = ? AND user_id = ?`, programID, uid).Scan(&ownedID); err != nil {
@@ -560,7 +560,7 @@ func (s *ProgramStore) ResolveSuggestions(uid, programID int64, accept, dismiss
if err != nil {
return models.Program{}, err
}
- return s.get(programID)
+ return s.get(programID, locale)
}
// progressedTarget applies the upward-only progression rule for a single set and
@@ -655,7 +655,7 @@ func insertProgramExercises(tx *sql.Tx, programID, dayID int64, exercises []mode
// 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) {
+func (s *ProgramStore) loadDays(programID int64, locale string) ([]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,
@@ -685,7 +685,7 @@ func (s *ProgramStore) loadDays(programID int64) ([]models.ProgramDay, error) {
days[i].Exercises = []models.ProgramExercise{}
continue
}
- ex, err := s.loadExercises(days[i].ID)
+ ex, err := s.loadExercises(days[i].ID, locale)
if err != nil {
return nil, err
}
@@ -696,14 +696,15 @@ func (s *ProgramStore) loadDays(programID int64) ([]models.ProgramDay, error) {
// loadExercises scans + closes the parent cursor BEFORE loading each exercise's
// sets (#36), and surfaces scan errors.
-func (s *ProgramStore) loadExercises(dayID int64) ([]models.ProgramExercise, error) {
+func (s *ProgramStore) loadExercises(dayID int64, locale string) ([]models.ProgramExercise, error) {
+ join, joinArgs := translationJoin(locale)
rows, err := s.db.Query(
`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
+ `+localizedName+`, e.muscle_group, e.category, e.equipment, e.image_url
FROM program_exercises pe
- JOIN exercises e ON e.id = pe.exercise_id
+ JOIN exercises e ON e.id = pe.exercise_id`+join+`
WHERE pe.program_day_id = ? ORDER BY pe.order_index`,
- dayID,
+ append(joinArgs, dayID)...,
)
if err != nil {
return nil, err
diff --git a/backend/stores/workout.go b/backend/stores/workout.go
index 320eeb8..b8bbfd3 100644
--- a/backend/stores/workout.go
+++ b/backend/stores/workout.go
@@ -25,7 +25,7 @@ func scanWorkout(row interface{ Scan(...any) error }, w *models.Workout) error {
return row.Scan(&w.ID, &w.UserID, &w.Name, &w.Notes, &w.Duration, &w.StartedAt, &w.TZOffsetMinutes, &w.CreatedAt)
}
-func (s *WorkoutStore) List(uid int64, f WorkoutFilter) ([]models.Workout, error) {
+func (s *WorkoutStore) List(uid int64, f WorkoutFilter, locale string) ([]models.Workout, error) {
var rows *sql.Rows
var err error
if f.Query != "" {
@@ -58,7 +58,7 @@ func (s *WorkoutStore) List(uid int64, f WorkoutFilter) ([]models.Workout, error
rows.Close() // close the parent cursor BEFORE loading children (#36: avoid holding 2 pool connections per request)
for i := range workouts {
- ex, err := s.loadExercises(workouts[i].ID)
+ ex, err := s.loadExercises(workouts[i].ID, locale)
if err != nil {
return nil, err
}
@@ -68,14 +68,14 @@ func (s *WorkoutStore) List(uid int64, f WorkoutFilter) ([]models.Workout, error
}
// Get returns a user-owned workout with its exercises/sets, or sql.ErrNoRows.
-func (s *WorkoutStore) Get(uid, id int64) (models.Workout, error) {
+func (s *WorkoutStore) Get(uid, id int64, locale string) (models.Workout, error) {
var w models.Workout
if err := scanWorkout(
s.db.QueryRow(`SELECT `+workoutCols+` FROM workouts WHERE id = ? AND user_id = ?`, id, uid), &w,
); err != nil {
return models.Workout{}, err
}
- ex, err := s.loadExercises(id)
+ ex, err := s.loadExercises(id, locale)
if err != nil {
return models.Workout{}, err
}
@@ -84,12 +84,12 @@ func (s *WorkoutStore) Get(uid, id int64) (models.Workout, error) {
}
// get re-reads by id (no user scope) — used after a user-scoped write.
-func (s *WorkoutStore) get(id int64) (models.Workout, error) {
+func (s *WorkoutStore) get(id int64, locale string) (models.Workout, error) {
var w models.Workout
if err := scanWorkout(s.db.QueryRow(`SELECT `+workoutCols+` FROM workouts WHERE id = ?`, id), &w); err != nil {
return models.Workout{}, err
}
- ex, err := s.loadExercises(id)
+ ex, err := s.loadExercises(id, locale)
if err != nil {
return models.Workout{}, err
}
@@ -157,7 +157,7 @@ func createWorkoutTx(tx *sql.Tx, uid int64, req models.CreateWorkoutRequest) (in
// Update replaces a user-owned workout and its children in one tx. sql.ErrNoRows
// if the workout isn't theirs (nothing is mutated).
-func (s *WorkoutStore) Update(uid, id int64, req models.CreateWorkoutRequest) (models.Workout, error) {
+func (s *WorkoutStore) Update(uid, id int64, req models.CreateWorkoutRequest, locale string) (models.Workout, error) {
// Ownership check + replace-children, all in one transaction (no TOCTOU).
if err := inTxDo(s.db, func(tx *sql.Tx) error {
var ownedID int64
@@ -194,7 +194,7 @@ func (s *WorkoutStore) Update(uid, id int64, req models.CreateWorkoutRequest) (m
}); err != nil {
return models.Workout{}, err
}
- return s.get(id)
+ return s.get(id, locale)
}
func (s *WorkoutStore) Delete(uid, id int64) (int64, error) {
@@ -236,14 +236,15 @@ func insertWorkoutExercises(tx *sql.Tx, wid int64, exercises []models.CreateWork
// loadExercises loads a workout's exercises (JOIN exercises for display) then
// their sets. Scans + closes the parent cursor fully BEFORE the per-exercise set
// queries (#36) so a request never holds two pool connections at once.
-func (s *WorkoutStore) loadExercises(workoutID int64) ([]models.WorkoutExercise, error) {
+func (s *WorkoutStore) loadExercises(workoutID int64, locale string) ([]models.WorkoutExercise, error) {
+ join, joinArgs := translationJoin(locale)
rows, err := s.db.Query(
`SELECT we.id, we.workout_id, we.exercise_id, we.order_index, we.notes, we.rest_seconds,
- e.name, e.muscle_group, e.category, e.equipment, e.image_url
+ `+localizedName+`, e.muscle_group, e.category, e.equipment, e.image_url
FROM workout_exercises we
- JOIN exercises e ON e.id = we.exercise_id
+ JOIN exercises e ON e.id = we.exercise_id`+join+`
WHERE we.workout_id = ? ORDER BY we.order_index`,
- workoutID,
+ append(joinArgs, workoutID)...,
)
if err != nil {
return nil, err
diff --git a/backend/stores/workout_progression.go b/backend/stores/workout_progression.go
index 7c97d10..5e6c3f5 100644
--- a/backend/stores/workout_progression.go
+++ b/backend/stores/workout_progression.go
@@ -43,7 +43,7 @@ import (
// struct-level validation (models.MaxWorkoutSets, enforced in
// controllers/workouts.go's init()), which caps sum(len(Exercises[i].Sets)) across
// the whole request.
-func (s *Stores) CreateWorkoutWithProgression(uid int64, req models.CreateWorkoutRequest) (models.Workout, *models.ProgressionResult, error) {
+func (s *Stores) CreateWorkoutWithProgression(uid int64, req models.CreateWorkoutRequest, locale string) (models.Workout, *models.ProgressionResult, error) {
var wid int64
var progression *models.ProgressionResult
err := inTxDo(s.db, func(tx *sql.Tx) error {
@@ -89,7 +89,7 @@ func (s *Stores) CreateWorkoutWithProgression(uid int64, req models.CreateWorkou
if err != nil {
return models.Workout{}, nil, err
}
- w, err := s.Workout.get(wid)
+ w, err := s.Workout.get(wid, locale)
if err != nil {
return models.Workout{}, nil, err
}
diff --git a/docs/API_CHANGES.md b/docs/API_CHANGES.md
index ad3a593..cb4e837 100644
--- a/docs/API_CHANGES.md
+++ b/docs/API_CHANGES.md
@@ -291,3 +291,10 @@ somebody will see the change.
- **`DEMO_MODE` no longer defaults on in development.** A deployment default rather than an
HTTP contract, and the published config docs already said `false`, but a dev instance
that relied on signing in as `[email protected]` must now set `DEMO_MODE=true`.
+- **`locale` on exercise text.** `GET /exercises`, `GET /exercises/:id`, the workout reads
+ and writes and the program reads and writes accept an optional `locale` query parameter
+ (a BCP-47 tag such as `es` or `es-MX`). Exercise `name` and `description` come back in
+ that locale where this instance holds a translation, falling back field by field to the
+ base language and then to English. With no `locale`, or a malformed one, responses are
+ unchanged: English, status `200`. Local search also matches translated names in that
+ locale.
diff --git a/mobile/src/lib/lyftr.ts b/mobile/src/lib/lyftr.ts
index 345392b..72099b5 100644
--- a/mobile/src/lib/lyftr.ts
+++ b/mobile/src/lib/lyftr.ts
@@ -11,6 +11,7 @@ import {
createThemeStore,
createLanguageStore,
createWorkoutSession,
+ i18n,
testServerConnection,
useServerInfoFor,
} from '@lyftr/shared'
@@ -30,6 +31,7 @@ export const client = createClient(storage, {
onAuthFailure: () => {
void useAuthStore.getState().logout()
},
+ getLocale: () => i18n.resolvedLanguage,
})
export const useAuthStore = createAuthStore(client, storage)
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index 889eb4c..32656c2 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -50,22 +50,6 @@ describe('foodAPI day windowing', () => {
})
})
-// Open Food Facts names a product in the language it was entered in. The server asks for
-// the reader's, so the client has to say which that is.
-describe('foodAPI search and barcode send the UI language', () => {
- afterEach(() => i18n.changeLanguage('en'))
-
- it.each(['en', 'es'])('sends locale=%s', async (lang) => {
- await i18n.changeLanguage(lang)
- const { client, calls } = captureClient()
- await client.foodAPI.search('nutella', 5)
- await client.foodAPI.barcode('3017620406003')
- expect(calls[0].params).toEqual({ q: 'nutella', limit: 5, locale: lang })
- expect(calls[1].url).toBe('/food/barcode/3017620406003')
- expect(calls[1].params).toEqual({ locale: lang })
- })
-})
-
// The offset must describe the instant being sent. A screen that re-picks the date
// derives a new instant in this zone and wants this zone's offset; a screen that
// resends the timestamp it loaded must keep the offset that instant was recorded with,
@@ -824,3 +808,69 @@ describe('apiErrorMessage — server codes', () => {
})
})
})
+
+// The language exercise names come back in is one parameter added in one place: the
+// request interceptor. No API method names it, so a screen cannot forget it.
+describe('getLocale adds locale to the endpoints that answer in the reader language', () => {
+ const localizedClient = (getLocale?: () => string | null | undefined | Promise<string | null | undefined>) => {
+ const seen: Array<{ url?: string; params?: any }> = []
+ const client = createClient(memStorage(), { getLocale })
+ client.api.defaults.adapter = async (config: any) => {
+ seen.push({ url: config.url, params: config.params })
+ return { data: { data: [] }, status: 200, statusText: 'OK', headers: {}, config }
+ }
+ return { client, seen }
+ }
+
+ it('sends locale on a list call, merged with its own params, and on a get', async () => {
+ const { client, seen } = localizedClient(() => 'es')
+ await client.exerciseAPI.list({ q: 'sent', page: 2 })
+ await client.workoutAPI.get(7)
+ expect(seen[0].params).toMatchObject({ q: 'sent', page: 2, limit: 50, locale: 'es' })
+ expect(seen[1].url).toBe('/workouts/7')
+ expect(seen[1].params).toEqual({ locale: 'es' })
+ })
+
+ // Open Food Facts names a product in the language it was entered in; the server asks
+ // for the reader's, so food search and barcode lookups carry it too.
+ it('sends locale on food search and barcode lookup', async () => {
+ const { client, seen } = localizedClient(() => 'es')
+ await client.foodAPI.search('nutella', 5)
+ await client.foodAPI.barcode('3017620406003')
+ expect(seen[0].params).toEqual({ q: 'nutella', limit: 5, locale: 'es' })
+ expect(seen[1].url).toBe('/food/barcode/3017620406003')
+ expect(seen[1].params).toEqual({ locale: 'es' })
+ })
+
+ // A request nothing localizes keeps its URL: a proxy, a cache key or an e2e route that
+ // matches on it must not start missing because a language was chosen.
+ it('leaves every other endpoint alone', async () => {
+ const { client, seen } = localizedClient(() => 'es')
+ await client.weightAPI.delete(3)
+ await client.foodAPI.list('2026-06-15')
+ expect(seen[0].url).toBe('/weight/3')
+ expect(seen[0].params).toBeUndefined()
+ expect(seen[1].params).toEqual({ date: '2026-06-15' })
+ })
+
+ it.each([[''], [null], [undefined]])('adds nothing when the getter returns %p', async (value) => {
+ const { client, seen } = localizedClient(() => value)
+ await client.workoutAPI.get(7)
+ expect(seen[0].params).toBeUndefined()
+ })
+
+ it('reads the getter on every request, awaiting an async one', async () => {
+ let current = 'es'
+ const { client, seen } = localizedClient(async () => current)
+ await client.workoutAPI.get(1)
+ current = 'fr'
+ await client.workoutAPI.get(1)
+ expect(seen.map((s) => s.params.locale)).toEqual(['es', 'fr'])
+ })
+
+ it('sends no locale when the client was created without a getter', async () => {
+ const { client, seen } = localizedClient()
+ await client.workoutAPI.get(1)
+ expect(seen[0].params).toBeUndefined()
+ })
+})
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index ce9e01f..32a911f 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -193,6 +193,12 @@ const sessionWasRevoked = (err: any): boolean => {
// Build a fully-wired API client bound to a platform storage adapter. All token
// reads/writes and the base-URL resolution go through `storage`, so the same code
// runs on web (localStorage) and mobile (SecureStore/AsyncStorage).
+// The endpoints whose answers hold text in the reader's language: exercise names, the
+// names inside workouts and programs, and Open Food Facts product names. Listing them
+// here keeps `locale` off every other request, so a URL a test or proxy matches on is
+// the one the API method wrote.
+const LOCALIZED_PATH = /^\/(exercises|workouts|programs|food\/(search|barcode))(\/|$)/
+
export function createClient(
storage: StorageAdapter,
opts: {
@@ -202,6 +208,12 @@ export function createClient(
// Optional hard override of the base URL (web passes import.meta.env.VITE_API_URL).
// When set, the stored server_url is ignored.
baseUrlOverride?: string
+ // The language exercise names should come back in. Resolved per request, like the
+ // server URL, so a language switch applies to the next call. Nothing is sent when it
+ // yields nothing, and the backend answers in English then.
+ // Only the calls that answer with localized text carry it (LOCALIZED_PATH); every
+ // other URL stays exactly as its API method wrote it.
+ getLocale?: () => string | null | undefined | Promise<string | null | undefined>
} = {},
) {
// Resolved per-request so a "Server settings" change takes effect immediately.
@@ -230,6 +242,8 @@ export function createClient(
config.baseURL = await resolveAPIBase()
const token = await storage.get(STORAGE_KEYS.access)
if (token) config.headers.Authorization = `Bearer ${token}`
+ const locale = await opts.getLocale?.()
+ if (locale && LOCALIZED_PATH.test(config.url ?? '')) config.params = { ...config.params, locale }
return config
})
@@ -478,8 +492,8 @@ export function createClient(
delete: (id: number) => api.delete(`/food/${id}`),
stats: (date?: string) => api.get<{ data: types.DailyStats }>('/food/stats', { params: { date } }).then(unwrap),
history: (days = 30) => api.get<{ data: types.FoodHistoryPoint[] }>('/food/history', { params: { days } }).then(unwrap),
- search: (q: string, limit = 20) => api.get<{ data: types.FoodSearchResult[] }>('/food/search', { params: { q, limit, locale: i18n.resolvedLanguage } }).then(unwrap),
- barcode: (code: string) => api.get<{ data: types.FoodSearchResult }>(`/food/barcode/${code}`, { params: { locale: i18n.resolvedLanguage } }).then(unwrap),
+ search: (q: string, limit = 20) => api.get<{ data: types.FoodSearchResult[] }>('/food/search', { params: { q, limit } }).then(unwrap),
+ barcode: (code: string) => api.get<{ data: types.FoodSearchResult }>(`/food/barcode/${code}`).then(unwrap),
}
const savedFoodsAPI = {
diff --git a/web/src/lib/lyftr.ts b/web/src/lib/lyftr.ts
index d83b7d9..adb4995 100644
--- a/web/src/lib/lyftr.ts
+++ b/web/src/lib/lyftr.ts
@@ -27,6 +27,7 @@ export const client = createClient(storage, {
// Same escape hatch as before: an explicit build-time API URL wins over the
// user-configured server, for deployments that pin the backend.
baseUrlOverride: import.meta.env.VITE_API_URL as string | undefined,
+ getLocale: () => i18n.resolvedLanguage,
})
export const useAuthStore = createAuthStore(client, storage)