Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
refactor(stores): introduce DI store layer scaffolding + thread handlers
Cawlumme63e0bdada1f
diff --git a/backend/controllers/active_session.go b/backend/controllers/active_session.goindex 5ad4fc1..ee70073 100644--- a/backend/controllers/active_session.go+++ b/backend/controllers/active_session.go@@ -10,7 +10,7 @@ import ("github.com/gin-gonic/gin")-func GetActiveSession(c *gin.Context) {+func (h *Handler) GetActiveSession(c *gin.Context) {uid := middleware.UserID(c)var data stringvar updatedAt time.Time@@ -28,7 +28,7 @@ func GetActiveSession(c *gin.Context) {c.JSON(200, gin.H{"data": gin.H{"data": data, "updated_at": updatedAt}})}-func UpsertActiveSession(c *gin.Context) {+func (h *Handler) UpsertActiveSession(c *gin.Context) {uid := middleware.UserID(c)var body struct {Data string `json:"data" binding:"required"`@@ -50,7 +50,7 @@ func UpsertActiveSession(c *gin.Context) {utils.OK(c, gin.H{"saved": true})}-func DeleteActiveSession(c *gin.Context) {+func (h *Handler) DeleteActiveSession(c *gin.Context) {uid := middleware.UserID(c)db.DB.Exec(`DELETE FROM active_sessions WHERE user_id = ?`, uid)utils.OK(c, gin.H{"deleted": true})diff --git a/backend/controllers/auth.go b/backend/controllers/auth.goindex 492d3c5..399438e 100644--- a/backend/controllers/auth.go+++ b/backend/controllers/auth.go@@ -12,7 +12,7 @@ import (var validate = validator.New()-func Register(c *gin.Context) {+func (h *Handler) Register(c *gin.Context) {var req models.RegisterRequestif err := c.ShouldBindJSON(&req); err != nil {utils.BadRequest(c, err.Error())@@ -53,7 +53,7 @@ func Register(c *gin.Context) {utils.Created(c, models.AuthResponse{Token: access, RefreshToken: refresh, User: user})}-func Login(c *gin.Context) {+func (h *Handler) Login(c *gin.Context) {var req models.LoginRequestif err := c.ShouldBindJSON(&req); err != nil {utils.BadRequest(c, err.Error())@@ -89,7 +89,7 @@ func Login(c *gin.Context) {utils.OK(c, models.AuthResponse{Token: access, RefreshToken: refresh, User: user})}-func RefreshToken(c *gin.Context) {+func (h *Handler) RefreshToken(c *gin.Context) {var req models.RefreshRequestif err := c.ShouldBindJSON(&req); err != nil {utils.BadRequest(c, err.Error())diff --git a/backend/controllers/exercises.go b/backend/controllers/exercises.goindex c826c66..4bba013 100644--- a/backend/controllers/exercises.go+++ b/backend/controllers/exercises.go@@ -11,7 +11,7 @@ import ("github.com/gin-gonic/gin")-func ListExercises(c *gin.Context) {+func (h *Handler) ListExercises(c *gin.Context) {query := `SELECT id, name, muscle_group, secondary_muscles, category, equipment, description, image_urlFROM exercises WHERE 1=1`args := []any{}@@ -55,7 +55,7 @@ func ListExercises(c *gin.Context) {utils.OK(c, exercises)}-func GetExercise(c *gin.Context) {+func (h *Handler) GetExercise(c *gin.Context) {id, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {utils.BadRequest(c, "invalid exercise id")@@ -74,7 +74,7 @@ func GetExercise(c *gin.Context) {utils.OK(c, e)}-func GetExercisePRs(c *gin.Context) {+func (h *Handler) GetExercisePRs(c *gin.Context) {userID := c.GetInt64("user_id")exerciseID, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -111,7 +111,7 @@ func GetExercisePRs(c *gin.Context) {})}-func GetExerciseHistory(c *gin.Context) {+func (h *Handler) GetExerciseHistory(c *gin.Context) {userID := c.GetInt64("user_id")exerciseID, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -156,7 +156,7 @@ func GetExerciseHistory(c *gin.Context) {}// SyncExercises is an admin-only endpoint to re-pull from ExerciseDB.-func SyncExercises(c *gin.Context) {+func (h *Handler) SyncExercises(c *gin.Context) {if err := seed.SyncExercises(db.DB); err != nil {utils.BadRequest(c, err.Error())return@@ -167,12 +167,12 @@ func SyncExercises(c *gin.Context) {}// ExerciseSeedStatus returns exercise count and whether seeding is running.-func ExerciseSeedStatus(c *gin.Context) {+func (h *Handler) ExerciseSeedStatus(c *gin.Context) {utils.OK(c, seed.GetSeedStatus(db.DB))}// ResetExercises wipes the exercises table and triggers a fresh seed in background.-func ResetExercises(c *gin.Context) {+func (h *Handler) ResetExercises(c *gin.Context) {if err := seed.WipeAndReseed(db.DB); err != nil {utils.BadRequest(c, err.Error())returndiff --git a/backend/controllers/exercises_test.go b/backend/controllers/exercises_test.goindex 3adc178..7a611e5 100644--- a/backend/controllers/exercises_test.go+++ b/backend/controllers/exercises_test.go@@ -43,7 +43,7 @@ func TestGetExercisePRs_noHistory(t *testing.T) {c, w := newContext(uid, http.MethodGet, fmt.Sprintf("/api/v1/exercises/%d/prs", exID), nil)setParam(c, "id", fmt.Sprintf("%d", exID))- GetExercisePRs(c)+ th.GetExercisePRs(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -65,7 +65,7 @@ func TestGetExercisePRs_returnsBestSet(t *testing.T) {c, w := newContext(uid, http.MethodGet, fmt.Sprintf("/api/v1/exercises/%d/prs", exID), nil)setParam(c, "id", fmt.Sprintf("%d", exID))- GetExercisePRs(c)+ th.GetExercisePRs(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -96,7 +96,7 @@ func TestGetExercisePRs_ignoresWarmup(t *testing.T) {c, w := newContext(uid, http.MethodGet, fmt.Sprintf("/api/v1/exercises/%d/prs", exID), nil)setParam(c, "id", fmt.Sprintf("%d", exID))- GetExercisePRs(c)+ th.GetExercisePRs(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -123,7 +123,7 @@ func TestGetExercisePRs_isolatesUser(t *testing.T) {c, w := newContext(uid1, http.MethodGet, fmt.Sprintf("/api/v1/exercises/%d/prs", exID), nil)setParam(c, "id", fmt.Sprintf("%d", exID))- GetExercisePRs(c)+ th.GetExercisePRs(c)resp := decodeResponse(t, w)data := resp["data"].(map[string]any)@@ -138,7 +138,7 @@ func TestGetExercisePRs_invalidID(t *testing.T) {c, w := newContext(uid, http.MethodGet, "/api/v1/exercises/bad/prs", nil)setParam(c, "id", "bad")- GetExercisePRs(c)+ th.GetExercisePRs(c)if w.Code != http.StatusBadRequest {t.Fatalf("expected 400, got %d", w.Code)@@ -152,7 +152,7 @@ func TestGetExerciseHistory_empty(t *testing.T) {c, w := newContext(uid, http.MethodGet, fmt.Sprintf("/api/v1/exercises/%d/history", exID), nil)setParam(c, "id", fmt.Sprintf("%d", exID))- GetExerciseHistory(c)+ th.GetExerciseHistory(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -178,7 +178,7 @@ func TestGetExerciseHistory_returnsSessionsGrouped(t *testing.T) {c, w := newContext(uid, http.MethodGet, fmt.Sprintf("/api/v1/exercises/%d/history", exID), nil)setParam(c, "id", fmt.Sprintf("%d", exID))- GetExerciseHistory(c)+ th.GetExerciseHistory(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())diff --git a/backend/controllers/food.go b/backend/controllers/food.goindex c8a7fd8..1effd9d 100644--- a/backend/controllers/food.go+++ b/backend/controllers/food.go@@ -36,7 +36,7 @@ func scanFoodLog(row interface{ Scan(...any) error }, f *models.FoodLog) error {const foodLogSelect = `SELECT id, user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, created_at FROM food_logs`-func ListFoodLogs(c *gin.Context) {+func (h *Handler) ListFoodLogs(c *gin.Context) {uid := middleware.UserID(c)date := c.Query("date")@@ -66,7 +66,7 @@ func ListFoodLogs(c *gin.Context) {utils.OK(c, logs)}-func GetFoodLog(c *gin.Context) {+func (h *Handler) GetFoodLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -83,7 +83,7 @@ func GetFoodLog(c *gin.Context) {utils.OK(c, f)}-func LogFood(c *gin.Context) {+func (h *Handler) LogFood(c *gin.Context) {uid := middleware.UserID(c)var req models.LogFoodRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -141,7 +141,7 @@ func LogFood(c *gin.Context) {utils.Created(c, f)}-func UpdateFoodLog(c *gin.Context) {+func (h *Handler) UpdateFoodLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -203,7 +203,7 @@ func UpdateFoodLog(c *gin.Context) {utils.OK(c, f)}-func DeleteFoodLog(c *gin.Context) {+func (h *Handler) DeleteFoodLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -225,7 +225,7 @@ func DeleteFoodLog(c *gin.Context) {utils.OK(c, gin.H{"deleted": true})}-func GetDailyStats(c *gin.Context) {+func (h *Handler) GetDailyStats(c *gin.Context) {uid := middleware.UserID(c)date := c.Query("date")if date == "" {@@ -258,7 +258,7 @@ func GetDailyStats(c *gin.Context) {utils.OK(c, stats)}-func GetFoodHistory(c *gin.Context) {+func (h *Handler) GetFoodHistory(c *gin.Context) {uid := middleware.UserID(c)days := 30@@ -408,7 +408,7 @@ func doOFFRequest(ctx context.Context, rawURL string) ([]byte, int, error) {return body, resp.StatusCode, err}-func SearchFood(c *gin.Context) {+func (h *Handler) SearchFood(c *gin.Context) {q := c.Query("q")if q == "" {utils.BadRequest(c, "q is required")@@ -488,7 +488,7 @@ type offBarcodeResponse struct {Product offProduct `json:"product"`}-func LookupBarcode(c *gin.Context) {+func (h *Handler) LookupBarcode(c *gin.Context) {code := c.Param("code")if code == "" {utils.BadRequest(c, "barcode is required")@@ -552,7 +552,7 @@ func LookupBarcode(c *gin.Context) {// ─── Saved Foods ──────────────────────────────────────────────────────────────-func ListSavedFoods(c *gin.Context) {+func (h *Handler) ListSavedFoods(c *gin.Context) {uid := middleware.UserID(c)rows, err := db.DB.Query(@@ -580,7 +580,7 @@ func ListSavedFoods(c *gin.Context) {utils.OK(c, foods)}-func CreateSavedFood(c *gin.Context) {+func (h *Handler) CreateSavedFood(c *gin.Context) {uid := middleware.UserID(c)var req models.SaveFoodRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -634,7 +634,7 @@ func CreateSavedFood(c *gin.Context) {utils.Created(c, f)}-func DeleteSavedFood(c *gin.Context) {+func (h *Handler) DeleteSavedFood(c *gin.Context) {uid := middleware.UserID(c)fid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.goindex 4c0adb7..6fd714b 100644--- a/backend/controllers/food_test.go+++ b/backend/controllers/food_test.go@@ -82,7 +82,7 @@ func TestListFoodLogs_empty(t *testing.T) {uid := createTestUser(t)c, w := newContext(uid, http.MethodGet, "/api/v1/food", nil)- ListFoodLogs(c)+ th.ListFoodLogs(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -108,7 +108,7 @@ func TestListFoodLogs_scopedByDateAndUser(t *testing.T) {date := today.Format("2006-01-02")c, w := newContext(uid, http.MethodGet, "/api/v1/food?date="+date, nil)- ListFoodLogs(c)+ th.ListFoodLogs(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)@@ -133,7 +133,7 @@ func TestGetFoodLog_success(t *testing.T) {c, w := newContext(uid, http.MethodGet, "/api/v1/food/"+fmt.Sprint(id), nil)setParam(c, "id", fmt.Sprint(id))- GetFoodLog(c)+ th.GetFoodLog(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -153,7 +153,7 @@ func TestGetFoodLog_ownershipEnforced(t *testing.T) {c, w := newContext(uid, http.MethodGet, "/api/v1/food/"+fmt.Sprint(id), nil)setParam(c, "id", fmt.Sprint(id))- GetFoodLog(c)+ th.GetFoodLog(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for cross-user get, got %d", w.Code)@@ -166,7 +166,7 @@ func TestGetFoodLog_invalidID(t *testing.T) {c, w := newContext(uid, http.MethodGet, "/api/v1/food/abc", nil)setParam(c, "id", "abc")- GetFoodLog(c)+ th.GetFoodLog(c)if w.Code != http.StatusBadRequest {t.Fatalf("expected 400 for invalid id, got %d", w.Code)@@ -185,7 +185,7 @@ func TestLogFood_success(t *testing.T) {"fiber": 5.0, "servings": 1.0, "serving_size": "1 cup",}c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)- LogFood(c)+ th.LogFood(c)if w.Code != http.StatusCreated {t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())@@ -215,7 +215,7 @@ func TestLogFood_defaultsServingsToOne(t *testing.T) {"calories": 95.0, "protein": 0.5, "carbs": 25.0, "fat": 0.3,}c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)- LogFood(c)+ th.LogFood(c)if w.Code != http.StatusCreated {t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())@@ -233,7 +233,7 @@ func TestLogFood_missingName(t *testing.T) {body := map[string]any{"meal": "breakfast", "calories": 300.0}c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)- LogFood(c)+ th.LogFood(c)if w.Code == http.StatusCreated {t.Fatal("expected error for missing name, got 201")@@ -249,7 +249,7 @@ func TestLogFood_nameTooLong(t *testing.T) {"calories": 100.0, "protein": 5.0, "carbs": 10.0, "fat": 3.0,}c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)- LogFood(c)+ th.LogFood(c)if w.Code != http.StatusBadRequest {t.Fatalf("expected 400 for name > 200 chars, got %d", w.Code)@@ -266,7 +266,7 @@ func TestLogFood_imageURLTooLong(t *testing.T) {"image_url": "https://" + strings.Repeat("a", 494),}c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)- LogFood(c)+ th.LogFood(c)if w.Code != http.StatusBadRequest {t.Fatalf("expected 400 for image_url > 500 chars, got %d", w.Code)@@ -283,7 +283,7 @@ func TestLogFood_barcodeTooLong(t *testing.T) {"barcode": strings.Repeat("1", 51),}c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)- LogFood(c)+ th.LogFood(c)if w.Code != http.StatusBadRequest {t.Fatalf("expected 400 for barcode > 50 chars, got %d", w.Code)@@ -303,7 +303,7 @@ func TestUpdateFoodLog_success(t *testing.T) {}c, w := newContext(uid, http.MethodPatch, "/api/v1/food/"+fmt.Sprint(id), body)setParam(c, "id", fmt.Sprint(id))- UpdateFoodLog(c)+ th.UpdateFoodLog(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -333,7 +333,7 @@ func TestUpdateFoodLog_ownershipEnforced(t *testing.T) {}c, w := newContext(uid, http.MethodPatch, "/api/v1/food/"+fmt.Sprint(id), body)setParam(c, "id", fmt.Sprint(id))- UpdateFoodLog(c)+ th.UpdateFoodLog(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for cross-user update, got %d", w.Code)@@ -355,7 +355,7 @@ func TestUpdateFoodLog_notFound(t *testing.T) {}c, w := newContext(uid, http.MethodPatch, "/api/v1/food/9999", body)setParam(c, "id", "9999")- UpdateFoodLog(c)+ th.UpdateFoodLog(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for missing entry, got %d", w.Code)@@ -371,7 +371,7 @@ func TestDeleteFoodLog_success(t *testing.T) {c, w := newContext(uid, http.MethodDelete, "/api/v1/food/"+fmt.Sprint(id), nil)setParam(c, "id", fmt.Sprint(id))- DeleteFoodLog(c)+ th.DeleteFoodLog(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -391,7 +391,7 @@ func TestDeleteFoodLog_ownershipEnforced(t *testing.T) {c, w := newContext(uid, http.MethodDelete, "/api/v1/food/"+fmt.Sprint(id), nil)setParam(c, "id", fmt.Sprint(id))- DeleteFoodLog(c)+ th.DeleteFoodLog(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for cross-user delete, got %d", w.Code)@@ -411,7 +411,7 @@ func TestGetDailyStats_empty(t *testing.T) {date := time.Now().Format("2006-01-02")c, w := newContext(uid, http.MethodGet, "/api/v1/food/stats?date="+date, nil)- GetDailyStats(c)+ th.GetDailyStats(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -435,7 +435,7 @@ func TestGetDailyStats_sumsMacrosCorrectly(t *testing.T) {date := today.Format("2006-01-02")c, w := newContext(uid, http.MethodGet, "/api/v1/food/stats?date="+date, nil)- GetDailyStats(c)+ th.GetDailyStats(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)@@ -467,7 +467,7 @@ func TestGetDailyStats_scopedByUser(t *testing.T) {date := today.Format("2006-01-02")c, w := newContext(uid, http.MethodGet, "/api/v1/food/stats?date="+date, nil)- GetDailyStats(c)+ th.GetDailyStats(c)resp := decodeResponse(t, w)data := resp["data"].(map[string]any)@@ -483,7 +483,7 @@ func TestGetFoodHistory_empty(t *testing.T) {uid := createTestUser(t)c, w := newContext(uid, http.MethodGet, "/api/v1/food/history?days=7", nil)- GetFoodHistory(c)+ th.GetFoodHistory(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -507,7 +507,7 @@ func TestGetFoodHistory_groupsByDay(t *testing.T) {insertFoodLog(t, uid, "Old", "dinner", 500, 30, 60, 12, now.AddDate(0, 0, -10))c, w := newContext(uid, http.MethodGet, "/api/v1/food/history?days=7", nil)- GetFoodHistory(c)+ th.GetFoodHistory(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)@@ -533,7 +533,7 @@ func TestGetFoodHistory_defaultsDaysTo30(t *testing.T) {insertFoodLog(t, uid, "Included", "lunch", 500, 30, 60, 15, time.Now().AddDate(0, 0, -20))c, w := newContext(uid, http.MethodGet, "/api/v1/food/history", nil)- GetFoodHistory(c)+ th.GetFoodHistory(c)resp := decodeResponse(t, w)data := resp["data"].([]any)@@ -658,7 +658,7 @@ func TestLookupBarcode_invalidFormat(t *testing.T) {for _, code := range []string{"abc", "123", "12345678901234567", "../etc"} {c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/"+code, nil)setParam(c, "code", code)- LookupBarcode(c)+ th.LookupBarcode(c)if w.Code != http.StatusBadRequest {t.Errorf("code %q: expected 400, got %d", code, w.Code)}@@ -677,7 +677,7 @@ func TestLookupBarcode_success(t *testing.T) {c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/051500255186", nil)setParam(c, "code", "051500255186")- LookupBarcode(c)+ th.LookupBarcode(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -703,7 +703,7 @@ func TestLookupBarcode_productNotFound(t *testing.T) {c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/012345678901", nil)setParam(c, "code", "012345678901")- LookupBarcode(c)+ th.LookupBarcode(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for unknown barcode, got %d", w.Code)@@ -720,7 +720,7 @@ func TestLookupBarcode_rateLimited(t *testing.T) {c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/012345678901", nil)setParam(c, "code", "012345678901")- LookupBarcode(c)+ th.LookupBarcode(c)if w.Code != http.StatusTooManyRequests {t.Fatalf("expected 429 forwarded, got %d", w.Code)@@ -734,7 +734,7 @@ func TestSearchFood_missingQuery(t *testing.T) {uid := createTestUser(t)c, w := newContext(uid, http.MethodGet, "/api/v1/food/search", nil)- SearchFood(c)+ th.SearchFood(c)if w.Code != http.StatusBadRequest {t.Fatalf("expected 400 for missing q, got %d", w.Code)@@ -752,7 +752,7 @@ func TestSearchFood_success(t *testing.T) {})c, w := newContext(uid, http.MethodGet, "/api/v1/food/search?q=milk", nil)- SearchFood(c)+ th.SearchFood(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -778,7 +778,7 @@ func TestSearchFood_rateLimited(t *testing.T) {})c, w := newContext(uid, http.MethodGet, "/api/v1/food/search?q=pizza", nil)- SearchFood(c)+ th.SearchFood(c)if w.Code != http.StatusTooManyRequests {t.Fatalf("expected 429 forwarded, got %d", w.Code)@@ -794,7 +794,7 @@ func TestSearchFood_upstreamError(t *testing.T) {})c, w := newContext(uid, http.MethodGet, "/api/v1/food/search?q=pizza", nil)- SearchFood(c)+ th.SearchFood(c)if w.Code != http.StatusServiceUnavailable {t.Fatalf("expected 503 for OFF 5xx, got %d", w.Code)@@ -808,7 +808,7 @@ func TestListSavedFoods_empty(t *testing.T) {uid := createTestUser(t)c, w := newContext(uid, http.MethodGet, "/api/v1/food/saved", nil)- ListSavedFoods(c)+ th.ListSavedFoods(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)@@ -831,7 +831,7 @@ func TestListSavedFoods_alphabeticalAndScopedByUser(t *testing.T) {insertSavedFood(t, other, "Should not appear")c, w := newContext(uid, http.MethodGet, "/api/v1/food/saved", nil)- ListSavedFoods(c)+ th.ListSavedFoods(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)@@ -863,7 +863,7 @@ func TestCreateSavedFood_success(t *testing.T) {"fiber": 0.0, "serving_size": "1 container (170g)",}c, w := newContext(uid, http.MethodPost, "/api/v1/food/saved", body)- CreateSavedFood(c)+ th.CreateSavedFood(c)if w.Code != http.StatusCreated {t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())@@ -884,7 +884,7 @@ func TestCreateSavedFood_missingName(t *testing.T) {body := map[string]any{"calories": 100.0, "protein": 5.0, "carbs": 10.0, "fat": 3.0}c, w := newContext(uid, http.MethodPost, "/api/v1/food/saved", body)- CreateSavedFood(c)+ th.CreateSavedFood(c)if w.Code == http.StatusCreated {t.Fatal("expected error for missing name, got 201")@@ -900,7 +900,7 @@ func TestDeleteSavedFood_success(t *testing.T) {c, w := newContext(uid, http.MethodDelete, "/api/v1/food/saved/"+fmt.Sprint(id), nil)setParam(c, "id", fmt.Sprint(id))- DeleteSavedFood(c)+ th.DeleteSavedFood(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -920,7 +920,7 @@ func TestDeleteSavedFood_ownershipEnforced(t *testing.T) {c, w := newContext(uid, http.MethodDelete, "/api/v1/food/saved/"+fmt.Sprint(id), nil)setParam(c, "id", fmt.Sprint(id))- DeleteSavedFood(c)+ th.DeleteSavedFood(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for cross-user delete, got %d", w.Code)diff --git a/backend/controllers/handler.go b/backend/controllers/handler.gonew file mode 100644index 0000000..f219f95--- /dev/null+++ b/backend/controllers/handler.go@@ -0,0 +1,11 @@+package controllers++import "github.com/Cawlumm/lyftr-backend/stores"++// Handler carries the injected stores. Every HTTP handler is a method on Handler+// so it reaches the database only through h.s.<Entity>, never the global db.DB.+type Handler struct {+ s *stores.Stores+}++func NewHandler(s *stores.Stores) *Handler { return &Handler{s: s} }diff --git a/backend/controllers/programs.go b/backend/controllers/programs.goindex 958271f..8d2069f 100644--- a/backend/controllers/programs.go+++ b/backend/controllers/programs.go@@ -12,7 +12,7 @@ import ("github.com/gin-gonic/gin")-func ListPrograms(c *gin.Context) {+func (h *Handler) ListPrograms(c *gin.Context) {uid := middleware.UserID(c)limit := 20@@ -54,7 +54,7 @@ func ListPrograms(c *gin.Context) {utils.OK(c, programs)}-func GetProgram(c *gin.Context) {+func (h *Handler) GetProgram(c *gin.Context) {uid := middleware.UserID(c)pid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -79,7 +79,7 @@ func GetProgram(c *gin.Context) {utils.OK(c, p)}-func CreateProgram(c *gin.Context) {+func (h *Handler) CreateProgram(c *gin.Context) {uid := middleware.UserID(c)var req models.CreateProgramRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -155,7 +155,7 @@ func CreateProgram(c *gin.Context) {utils.Created(c, p)}-func UpdateProgram(c *gin.Context) {+func (h *Handler) UpdateProgram(c *gin.Context) {uid := middleware.UserID(c)pid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -248,7 +248,7 @@ func UpdateProgram(c *gin.Context) {utils.OK(c, p)}-func DeleteProgram(c *gin.Context) {+func (h *Handler) DeleteProgram(c *gin.Context) {uid := middleware.UserID(c)pid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {diff --git a/backend/controllers/programs_test.go b/backend/controllers/programs_test.goindex cf41675..5be3239 100644--- a/backend/controllers/programs_test.go+++ b/backend/controllers/programs_test.go@@ -13,7 +13,7 @@ func TestListPrograms_empty(t *testing.T) {uid := createTestUser(t)c, w := newContext(uid, http.MethodGet, "/api/v1/programs", nil)- ListPrograms(c)+ th.ListPrograms(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -50,7 +50,7 @@ func TestCreateProgram_success(t *testing.T) {}c, w := newContext(uid, http.MethodPost, "/api/v1/programs", body)- CreateProgram(c)+ th.CreateProgram(c)if w.Code != http.StatusCreated {t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())@@ -86,7 +86,7 @@ func TestCreateProgram_missingName(t *testing.T) {"exercises": []map[string]any{},}c, w := newContext(uid, http.MethodPost, "/api/v1/programs", body)- CreateProgram(c)+ th.CreateProgram(c)if w.Code == http.StatusCreated {t.Fatal("expected error for empty name, got 201")@@ -104,7 +104,7 @@ func TestGetProgram_ownershipEnforced(t *testing.T) {c, w := newContext(uid, http.MethodGet, "/api/v1/programs/"+fmt.Sprint(pid), nil)setParam(c, "id", fmt.Sprint(pid))- GetProgram(c)+ th.GetProgram(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for cross-user access, got %d", w.Code)@@ -122,7 +122,7 @@ func TestDeleteProgram_ownershipEnforced(t *testing.T) {c, w := newContext(uid, http.MethodDelete, "/api/v1/programs/"+fmt.Sprint(pid), nil)setParam(c, "id", fmt.Sprint(pid))- DeleteProgram(c)+ th.DeleteProgram(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for cross-user delete, got %d", w.Code)@@ -166,7 +166,7 @@ func TestUpdateProgram_replacesExercises(t *testing.T) {c, w := newContext(uid, http.MethodPut, "/api/v1/programs/"+fmt.Sprint(pid), body)setParam(c, "id", fmt.Sprint(pid))- UpdateProgram(c)+ th.UpdateProgram(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -203,7 +203,7 @@ func TestCreateProgram_setNumberNormalized(t *testing.T) {}c, w := newContext(uid, http.MethodPost, "/api/v1/programs", body)- CreateProgram(c)+ th.CreateProgram(c)if w.Code != http.StatusCreated {t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())@@ -231,7 +231,7 @@ func TestListPrograms_filtersBySearchQuery(t *testing.T) {c, w := newContext(uid, http.MethodGet, "/api/v1/programs?q=push", nil)c.Request.URL.RawQuery = "q=push" // case-insensitive LIKE on name, scoped by user- ListPrograms(c)+ th.ListPrograms(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())diff --git a/backend/controllers/server.go b/backend/controllers/server.goindex c88f249..6e87a32 100644--- a/backend/controllers/server.go+++ b/backend/controllers/server.go@@ -11,7 +11,7 @@ import (// "test connection" behind the in-app server selector. It runs under the same// CORS policy as the rest of the API, so a successful probe honestly predicts// that authenticated requests from the same origin will be allowed too.-func ServerInfo(c *gin.Context) {+func (h *Handler) ServerInfo(c *gin.Context) {utils.OK(c, gin.H{"name": "lyftr","version": config.C.Version,diff --git a/backend/controllers/server_test.go b/backend/controllers/server_test.goindex 3a6d89b..c965ce0 100644--- a/backend/controllers/server_test.go+++ b/backend/controllers/server_test.go@@ -11,7 +11,7 @@ func TestServerInfo(t *testing.T) {config.C = &config.Config{Version: "9.9.9"}c, w := newContext(0, "GET", "/api/v1/info", nil)- ServerInfo(c)+ th.ServerInfo(c)if w.Code != http.StatusOK {t.Fatalf("status = %d, want 200", w.Code)diff --git a/backend/controllers/testhelper_test.go b/backend/controllers/testhelper_test.goindex 97ae6ce..b9ae492 100644--- a/backend/controllers/testhelper_test.go+++ b/backend/controllers/testhelper_test.go@@ -11,10 +11,15 @@ import ("testing""github.com/Cawlumm/lyftr-backend/db"+ "github.com/Cawlumm/lyftr-backend/stores""github.com/gin-gonic/gin"_ "modernc.org/sqlite")+// th is the DI handler under test, rebuilt per test in setupTestDB so it binds+// the fresh per-test db.DB.+var th *Handler+func setupTestDB(t *testing.T) {t.Helper()var err error@@ -29,6 +34,7 @@ func setupTestDB(t *testing.T) {if err = applySchema(); err != nil {t.Fatalf("apply schema: %v", err)}+ th = NewHandler(stores.New(db.DB))t.Cleanup(func() { db.DB.Close() })}@@ -41,6 +47,14 @@ CREATE TABLE IF NOT EXISTS users (created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP);+CREATE TABLE IF NOT EXISTS user_settings (+ user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,+ weight_unit TEXT NOT NULL DEFAULT 'lbs',+ calorie_target INTEGER NOT NULL DEFAULT 2000,+ protein_target INTEGER NOT NULL DEFAULT 150,+ carb_target INTEGER NOT NULL DEFAULT 250,+ fat_target INTEGER NOT NULL DEFAULT 65+);CREATE TABLE IF NOT EXISTS exercises (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL,diff --git a/backend/controllers/user.go b/backend/controllers/user.goindex a7be823..4a91c6a 100644--- a/backend/controllers/user.go+++ b/backend/controllers/user.go@@ -8,7 +8,7 @@ import ("github.com/gin-gonic/gin")-func GetMe(c *gin.Context) {+func (h *Handler) GetMe(c *gin.Context) {uid := middleware.UserID(c)var u models.Usererr := db.DB.QueryRow(@@ -21,7 +21,7 @@ func GetMe(c *gin.Context) {utils.OK(c, u)}-func GetSettings(c *gin.Context) {+func (h *Handler) GetSettings(c *gin.Context) {uid := middleware.UserID(c)var s models.UserSettingserr := db.DB.QueryRow(@@ -39,7 +39,7 @@ func GetSettings(c *gin.Context) {utils.OK(c, s)}-func UpdateSettings(c *gin.Context) {+func (h *Handler) UpdateSettings(c *gin.Context) {uid := middleware.UserID(c)var req models.UpdateSettingsRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -59,10 +59,10 @@ func UpdateSettings(c *gin.Context) {uid, req.WeightUnit, req.CalorieTarget, req.ProteinTarget, req.CarbTarget, req.FatTarget,)- GetSettings(c)+ h.GetSettings(c)}-func DeleteAccount(c *gin.Context) {+func (h *Handler) DeleteAccount(c *gin.Context) {uid := middleware.UserID(c)_, err := db.DB.Exec(`DELETE FROM users WHERE id = ?`, uid)if err != nil {diff --git a/backend/controllers/weight.go b/backend/controllers/weight.goindex 704999a..be89c17 100644--- a/backend/controllers/weight.go+++ b/backend/controllers/weight.go@@ -12,7 +12,7 @@ import ("github.com/gin-gonic/gin")-func ListWeightLogs(c *gin.Context) {+func (h *Handler) ListWeightLogs(c *gin.Context) {uid := middleware.UserID(c)limit := 90if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 1000 {@@ -71,7 +71,7 @@ func ListWeightLogs(c *gin.Context) {utils.OK(c, logs)}-func LogWeight(c *gin.Context) {+func (h *Handler) LogWeight(c *gin.Context) {uid := middleware.UserID(c)var req models.LogWeightRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -135,7 +135,7 @@ func LogWeight(c *gin.Context) {utils.Created(c, log)}-func GetWeightLog(c *gin.Context) {+func (h *Handler) GetWeightLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -154,7 +154,7 @@ func GetWeightLog(c *gin.Context) {utils.OK(c, log)}-func UpdateWeightLog(c *gin.Context) {+func (h *Handler) UpdateWeightLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -218,7 +218,7 @@ func UpdateWeightLog(c *gin.Context) {utils.OK(c, log)}-func DeleteWeightLog(c *gin.Context) {+func (h *Handler) DeleteWeightLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -239,7 +239,7 @@ func DeleteWeightLog(c *gin.Context) {utils.OK(c, gin.H{"deleted": true})}-func GetWeightStats(c *gin.Context) {+func (h *Handler) GetWeightStats(c *gin.Context) {uid := middleware.UserID(c)var (diff --git a/backend/controllers/weight_test.go b/backend/controllers/weight_test.goindex 254a089..8b7d03f 100644--- a/backend/controllers/weight_test.go+++ b/backend/controllers/weight_test.go@@ -27,7 +27,7 @@ func TestListWeightLogs_empty(t *testing.T) {uid := createTestUser(t)c, w := newContext(uid, http.MethodGet, "/api/v1/weight", nil)- ListWeightLogs(c)+ th.ListWeightLogs(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -52,7 +52,7 @@ func TestListWeightLogs_orderedDescAndScopedByUser(t *testing.T) {insertWeightLog(t, otherUID, 999.0, now)c, w := newContext(uid, http.MethodGet, "/api/v1/weight", nil)- ListWeightLogs(c)+ th.ListWeightLogs(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)@@ -82,7 +82,7 @@ func TestListWeightLogs_sameDayNewestFirst(t *testing.T) {insertWeightLog(t, uid, 186.0, day) // newer, identical timestampc, w := newContext(uid, http.MethodGet, "/api/v1/weight", nil)- ListWeightLogs(c)+ th.ListWeightLogs(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())}@@ -105,7 +105,7 @@ func TestGetWeightStats_latestPrefersNewestSameDay(t *testing.T) {insertWeightLog(t, uid, 186.0, day)c, w := newContext(uid, http.MethodGet, "/api/v1/weight/stats", nil)- GetWeightStats(c)+ th.GetWeightStats(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)}@@ -127,7 +127,7 @@ func TestListWeightLogs_dateRange(t *testing.T) {from := now.AddDate(0, 0, -7).Format("2006-01-02")to := now.Format("2006-01-02")c, w := newContext(uid, http.MethodGet, fmt.Sprintf("/api/v1/weight?from=%s&to=%s", from, to), nil)- ListWeightLogs(c)+ th.ListWeightLogs(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)@@ -154,7 +154,7 @@ func TestListWeightLogs_dateRangeWestTimezone(t *testing.T) {insertWeightLog(t, uid, 175.0, loggedAt)c, w := newContext(uid, http.MethodGet, "/api/v1/weight?from=2026-04-25&to=2026-04-25", nil)- ListWeightLogs(c)+ th.ListWeightLogs(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)@@ -176,7 +176,7 @@ func TestListWeightLogs_dateRangeExactRFC3339(t *testing.T) {c, w := newContext(uid, http.MethodGet,"/api/v1/weight?from=2026-04-25T12:00:00Z&to=2026-04-25T15:00:00Z", nil)- ListWeightLogs(c)+ th.ListWeightLogs(c)resp := decodeResponse(t, w)data := resp["data"].([]any)@@ -195,7 +195,7 @@ func TestLogWeight_success(t *testing.T) {body := map[string]any{"weight": 185.5, "notes": "morning"}c, w := newContext(uid, http.MethodPost, "/api/v1/weight", body)- LogWeight(c)+ th.LogWeight(c)if w.Code != http.StatusCreated {t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())@@ -219,14 +219,14 @@ func TestLogWeight_sameDayUpdatesInPlace(t *testing.T) {day := "2026-06-29T12:00:00Z"c1, w1 := newContext(uid, http.MethodPost, "/api/v1/weight",map[string]any{"weight": 181.0, "notes": "am", "logged_at": day})- LogWeight(c1)+ th.LogWeight(c1)if w1.Code != http.StatusCreated {t.Fatalf("first log: expected 201, got %d: %s", w1.Code, w1.Body.String())}c2, w2 := newContext(uid, http.MethodPost, "/api/v1/weight",map[string]any{"weight": 186.0, "notes": "pm", "logged_at": day})- LogWeight(c2)+ th.LogWeight(c2)if w2.Code != http.StatusCreated {t.Fatalf("second log: expected 201, got %d: %s", w2.Code, w2.Body.String())}@@ -259,7 +259,7 @@ func TestLogWeight_differentDaysCoexist(t *testing.T) {for _, d := range []string{"2026-06-27T12:00:00Z", "2026-06-28T12:00:00Z"} {c, w := newContext(uid, http.MethodPost, "/api/v1/weight",map[string]any{"weight": 180.0, "logged_at": d})- LogWeight(c)+ th.LogWeight(c)if w.Code != http.StatusCreated {t.Fatalf("log %s: expected 201, got %d", d, w.Code)}@@ -279,7 +279,7 @@ func TestLogWeight_normalizesOffsetToUTC(t *testing.T) {c, w := newContext(uid, http.MethodPost, "/api/v1/weight",map[string]any{"weight": 190.0, "logged_at": "2026-07-16T20:00:00-05:00"})- LogWeight(c)+ th.LogWeight(c)if w.Code != http.StatusCreated {t.Fatalf("offset ts: expected 201, got %d: %s", w.Code, w.Body.String())}@@ -296,7 +296,7 @@ func TestLogWeight_rejectsNonPositive(t *testing.T) {body := map[string]any{"weight": 0}c, w := newContext(uid, http.MethodPost, "/api/v1/weight", body)- LogWeight(c)+ th.LogWeight(c)if w.Code == http.StatusCreated {t.Fatal("expected validation error for weight=0, got 201")@@ -309,7 +309,7 @@ func TestLogWeight_rejectsImplausiblyLarge(t *testing.T) {body := map[string]any{"weight": 9999}c, w := newContext(uid, http.MethodPost, "/api/v1/weight", body)- LogWeight(c)+ th.LogWeight(c)if w.Code == http.StatusCreated {t.Fatal("expected validation error for weight=9999, got 201")@@ -324,7 +324,7 @@ func TestUpdateWeightLog_success(t *testing.T) {body := map[string]any{"weight": 178.0, "notes": "after run"}c, w := newContext(uid, http.MethodPatch, "/api/v1/weight/"+fmt.Sprint(id), body)setParam(c, "id", fmt.Sprint(id))- UpdateWeightLog(c)+ th.UpdateWeightLog(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -351,7 +351,7 @@ func TestUpdateWeightLog_dedupsOnTargetDay(t *testing.T) {body := map[string]any{"weight": 186.0, "logged_at": "2026-07-20T12:00:00Z"}c, w := newContext(uid, http.MethodPatch, "/api/v1/weight/"+fmt.Sprint(b), body)setParam(c, "id", fmt.Sprint(b))- UpdateWeightLog(c)+ th.UpdateWeightLog(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())}@@ -380,7 +380,7 @@ func TestUpdateWeightLog_ownershipEnforced(t *testing.T) {body := map[string]any{"weight": 100.0}c, w := newContext(uid, http.MethodPatch, "/api/v1/weight/"+fmt.Sprint(id), body)setParam(c, "id", fmt.Sprint(id))- UpdateWeightLog(c)+ th.UpdateWeightLog(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for cross-user update, got %d", w.Code)@@ -401,7 +401,7 @@ func TestDeleteWeightLog_ownershipEnforced(t *testing.T) {c, w := newContext(uid, http.MethodDelete, "/api/v1/weight/"+fmt.Sprint(id), nil)setParam(c, "id", fmt.Sprint(id))- DeleteWeightLog(c)+ th.DeleteWeightLog(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for cross-user delete, got %d", w.Code)@@ -423,7 +423,7 @@ func TestGetWeightStats_richFields(t *testing.T) {insertWeightLog(t, uid, 175.0, now.AddDate(0, 0, -1))c, w := newContext(uid, http.MethodGet, "/api/v1/weight/stats", nil)- GetWeightStats(c)+ th.GetWeightStats(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)@@ -461,7 +461,7 @@ func TestGetWeightStats_noData(t *testing.T) {uid := createTestUser(t)c, w := newContext(uid, http.MethodGet, "/api/v1/weight/stats", nil)- GetWeightStats(c)+ th.GetWeightStats(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.goindex 4e17009..81b8470 100644--- a/backend/controllers/workouts.go+++ b/backend/controllers/workouts.go@@ -13,7 +13,7 @@ import ("github.com/gin-gonic/gin")-func ListWorkouts(c *gin.Context) {+func (h *Handler) ListWorkouts(c *gin.Context) {uid := middleware.UserID(c)limit := 20offset := 0@@ -56,7 +56,7 @@ func ListWorkouts(c *gin.Context) {utils.OK(c, workouts)}-func GetWorkout(c *gin.Context) {+func (h *Handler) GetWorkout(c *gin.Context) {uid := middleware.UserID(c)wid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -82,7 +82,7 @@ func GetWorkout(c *gin.Context) {utils.OK(c, w)}-func CreateWorkout(c *gin.Context) {+func (h *Handler) CreateWorkout(c *gin.Context) {uid := middleware.UserID(c)var req models.CreateWorkoutRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -159,7 +159,7 @@ func CreateWorkout(c *gin.Context) {utils.Created(c, w)}-func UpdateWorkout(c *gin.Context) {+func (h *Handler) UpdateWorkout(c *gin.Context) {uid := middleware.UserID(c)wid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {@@ -252,7 +252,7 @@ func UpdateWorkout(c *gin.Context) {utils.OK(c, w)}-func DeleteWorkout(c *gin.Context) {+func (h *Handler) DeleteWorkout(c *gin.Context) {uid := middleware.UserID(c)wid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {diff --git a/backend/controllers/workouts_test.go b/backend/controllers/workouts_test.goindex cc773d9..90a954b 100644--- a/backend/controllers/workouts_test.go+++ b/backend/controllers/workouts_test.go@@ -13,7 +13,7 @@ func TestListWorkouts_empty(t *testing.T) {uid := createTestUser(t)c, w := newContext(uid, http.MethodGet, "/api/v1/workouts", nil)- ListWorkouts(c)+ th.ListWorkouts(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -50,7 +50,7 @@ func TestCreateWorkout_success(t *testing.T) {}c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)- CreateWorkout(c)+ th.CreateWorkout(c)if w.Code != http.StatusCreated {t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())@@ -75,7 +75,7 @@ func TestCreateWorkout_missingName(t *testing.T) {"exercises": []map[string]any{},}c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)- CreateWorkout(c)+ th.CreateWorkout(c)if w.Code == http.StatusCreated {t.Fatal("expected error for empty name, got 201")@@ -101,7 +101,7 @@ func TestCreateWorkout_preservesStartedAt(t *testing.T) {}c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)- CreateWorkout(c)+ th.CreateWorkout(c)if w.Code != http.StatusCreated {t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())@@ -130,7 +130,7 @@ func TestGetWorkout_ownershipEnforced(t *testing.T) {// 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)+ th.GetWorkout(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for cross-user access, got %d", w.Code)@@ -151,7 +151,7 @@ func TestDeleteWorkout_ownershipEnforced(t *testing.T) {c, w := newContext(uid, http.MethodDelete, "/api/v1/workouts/"+fmt.Sprint(wid), nil)setParam(c, "id", fmt.Sprint(wid))- DeleteWorkout(c)+ th.DeleteWorkout(c)if w.Code != http.StatusNotFound {t.Fatalf("expected 404 for cross-user delete, got %d", w.Code)@@ -191,7 +191,7 @@ func TestUpdateWorkout_preservesStartedAt(t *testing.T) {c, w := newContext(uid, http.MethodPut, "/api/v1/workouts/"+fmt.Sprint(wid), body)setParam(c, "id", fmt.Sprint(wid))- UpdateWorkout(c)+ th.UpdateWorkout(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())@@ -218,7 +218,7 @@ func TestListWorkouts_limitCap(t *testing.T) {// 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)+ th.ListWorkouts(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d", w.Code)@@ -243,7 +243,7 @@ func TestListWorkouts_filtersBySearchQuery(t *testing.T) {c, w := newContext(uid, http.MethodGet, "/api/v1/workouts?q=push", nil)c.Request.URL.RawQuery = "q=push" // case-insensitive LIKE on name, scoped by user- ListWorkouts(c)+ th.ListWorkouts(c)if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())diff --git a/backend/main.go b/backend/main.goindex 5bbf6c9..1b2f391 100644--- a/backend/main.go+++ b/backend/main.go@@ -7,9 +7,11 @@ import ("os""github.com/Cawlumm/lyftr-backend/config"+ "github.com/Cawlumm/lyftr-backend/controllers""github.com/Cawlumm/lyftr-backend/db""github.com/Cawlumm/lyftr-backend/routes""github.com/Cawlumm/lyftr-backend/seed"+ "github.com/Cawlumm/lyftr-backend/stores""github.com/gin-gonic/gin")@@ -32,7 +34,9 @@ func main() {}r := gin.Default()- routes.Setup(r)+ s := stores.New(db.DB)+ h := controllers.NewHandler(s)+ routes.Setup(r, h)addr := ":" + config.C.Portlog.Printf("lyftr API listening on %s (env=%s)", addr, config.C.Env)diff --git a/backend/models/models.go b/backend/models/models.goindex 45a5e4e..b001036 100644--- a/backend/models/models.go+++ b/backend/models/models.go@@ -24,7 +24,7 @@ type Exercise struct {Name string `json:"name" db:"name"`MuscleGroup string `json:"muscle_group" db:"muscle_group"`SecondaryMuscles []string `json:"secondary_muscles" db:"-"` // decoded from JSON column- Category string `json:"category" db:"category"` // "strength", "cardio", "flexibility"+ Category string `json:"category" db:"category"` // "strength", "cardio", "flexibility"Equipment string `json:"equipment" db:"equipment"`Description string `json:"description" db:"description"`ImageURL string `json:"image_url,omitempty" db:"image_url"`@@ -57,7 +57,7 @@ type Set struct {WorkoutExerciseID int64 `json:"workout_exercise_id" db:"workout_exercise_id"`SetNumber int `json:"set_number" db:"set_number"`Reps int `json:"reps,omitempty" db:"reps"`- Weight float64 `json:"weight,omitempty" db:"weight"` // raw value in user's preferred unit (lbs or kg)+ Weight float64 `json:"weight,omitempty" db:"weight"` // raw value in user's preferred unit (lbs or kg)Duration int `json:"duration,omitempty" db:"duration"` // seconds, for timed setsDistance float64 `json:"distance,omitempty" db:"distance"` // metersRPE float64 `json:"rpe,omitempty" db:"rpe"`@@ -150,17 +150,17 @@ type RefreshRequest struct {}type CreateWorkoutRequest struct {- Name string `json:"name" validate:"required"`- Notes string `json:"notes"`- Duration int `json:"duration"`- StartedAt time.Time `json:"started_at"`+ Name string `json:"name" validate:"required"`+ Notes string `json:"notes"`+ Duration int `json:"duration"`+ StartedAt time.Time `json:"started_at"`Exercises []CreateWorkoutExerciseReq `json:"exercises"`}type CreateWorkoutExerciseReq struct {- ExerciseID int64 `json:"exercise_id" validate:"required"`- OrderIndex int `json:"order_index"`- Notes string `json:"notes"`+ ExerciseID int64 `json:"exercise_id" validate:"required"`+ OrderIndex int `json:"order_index"`+ Notes string `json:"notes"`Sets []CreateSetReq `json:"sets"`}@@ -243,14 +243,14 @@ type ProgramSet struct {}type CreateProgramRequest struct {- Name string `json:"name" validate:"required"`- Notes string `json:"notes"`+ Name string `json:"name" validate:"required"`+ Notes string `json:"notes"`Exercises []CreateProgramExerciseReq `json:"exercises"`}type CreateProgramExerciseReq struct {- ExerciseID int64 `json:"exercise_id" validate:"required"`- Notes string `json:"notes"`+ ExerciseID int64 `json:"exercise_id" validate:"required"`+ Notes string `json:"notes"`Sets []CreateProgramSetReq `json:"sets"`}diff --git a/backend/routes/routes.go b/backend/routes/routes.goindex 85ecc6d..2113465 100644--- a/backend/routes/routes.go+++ b/backend/routes/routes.go@@ -11,7 +11,7 @@ import ("github.com/gin-gonic/gin")-func Setup(r *gin.Engine) {+func Setup(r *gin.Engine, h *controllers.Handler) {r.Use(cors.New(corsConfig()))r.GET("/health", func(c *gin.Context) {@@ -21,14 +21,14 @@ func Setup(r *gin.Engine) {api := r.Group("/api/v1")// Public: "test connection" probe for the in-app server selector.- api.GET("/info", controllers.ServerInfo)+ api.GET("/info", h.ServerInfo)// Auth (public)auth := api.Group("/auth"){- auth.POST("/register", controllers.Register)- auth.POST("/login", controllers.Login)- auth.POST("/refresh", controllers.RefreshToken)+ auth.POST("/register", h.Register)+ auth.POST("/login", h.Login)+ auth.POST("/refresh", h.RefreshToken)}// Protected routes@@ -36,62 +36,62 @@ func Setup(r *gin.Engine) {protected.Use(middleware.Auth()){// User- protected.GET("me", controllers.GetMe)- protected.GET("settings", controllers.GetSettings)- protected.PUT("settings", controllers.UpdateSettings)- protected.DELETE("me", controllers.DeleteAccount)+ protected.GET("me", h.GetMe)+ protected.GET("settings", h.GetSettings)+ protected.PUT("settings", h.UpdateSettings)+ protected.DELETE("me", h.DeleteAccount)// Workouts- protected.GET("workouts", controllers.ListWorkouts)- protected.POST("workouts", controllers.CreateWorkout)- protected.GET("workouts/:id", controllers.GetWorkout)- protected.PUT("workouts/:id", controllers.UpdateWorkout)- protected.DELETE("workouts/:id", controllers.DeleteWorkout)+ protected.GET("workouts", h.ListWorkouts)+ protected.POST("workouts", h.CreateWorkout)+ protected.GET("workouts/:id", h.GetWorkout)+ protected.PUT("workouts/:id", h.UpdateWorkout)+ protected.DELETE("workouts/:id", h.DeleteWorkout)// Weight- protected.GET("weight", controllers.ListWeightLogs)- protected.POST("weight", controllers.LogWeight)- protected.GET("weight/stats", controllers.GetWeightStats)- protected.GET("weight/:id", controllers.GetWeightLog)- protected.PATCH("weight/:id", controllers.UpdateWeightLog)- protected.DELETE("weight/:id", controllers.DeleteWeightLog)+ protected.GET("weight", h.ListWeightLogs)+ protected.POST("weight", h.LogWeight)+ protected.GET("weight/stats", h.GetWeightStats)+ protected.GET("weight/:id", h.GetWeightLog)+ protected.PATCH("weight/:id", h.UpdateWeightLog)+ protected.DELETE("weight/:id", h.DeleteWeightLog)// Food — named sub-paths must be registered before food/:id- protected.GET("food", controllers.ListFoodLogs)- protected.POST("food", controllers.LogFood)- protected.GET("food/stats", controllers.GetDailyStats)- protected.GET("food/history", controllers.GetFoodHistory)- protected.GET("food/search", controllers.SearchFood)- protected.GET("food/barcode/:code", controllers.LookupBarcode)- protected.GET("food/saved", controllers.ListSavedFoods)- protected.POST("food/saved", controllers.CreateSavedFood)- protected.DELETE("food/saved/:id", controllers.DeleteSavedFood)- protected.GET("food/:id", controllers.GetFoodLog)- protected.PATCH("food/:id", controllers.UpdateFoodLog)- protected.DELETE("food/:id", controllers.DeleteFoodLog)+ protected.GET("food", h.ListFoodLogs)+ protected.POST("food", h.LogFood)+ protected.GET("food/stats", h.GetDailyStats)+ protected.GET("food/history", h.GetFoodHistory)+ protected.GET("food/search", h.SearchFood)+ protected.GET("food/barcode/:code", h.LookupBarcode)+ protected.GET("food/saved", h.ListSavedFoods)+ protected.POST("food/saved", h.CreateSavedFood)+ protected.DELETE("food/saved/:id", h.DeleteSavedFood)+ protected.GET("food/:id", h.GetFoodLog)+ protected.PATCH("food/:id", h.UpdateFoodLog)+ protected.DELETE("food/:id", h.DeleteFoodLog)// Exercises (read-only for users)- protected.GET("exercises", controllers.ListExercises)- protected.GET("exercises/:id", controllers.GetExercise)- protected.GET("exercises/:id/prs", controllers.GetExercisePRs)- protected.GET("exercises/:id/history", controllers.GetExerciseHistory)+ protected.GET("exercises", h.ListExercises)+ protected.GET("exercises/:id", h.GetExercise)+ protected.GET("exercises/:id/prs", h.GetExercisePRs)+ protected.GET("exercises/:id/history", h.GetExerciseHistory)// Active session- protected.GET("active-session", controllers.GetActiveSession)- protected.PUT("active-session", controllers.UpsertActiveSession)- protected.DELETE("active-session", controllers.DeleteActiveSession)+ protected.GET("active-session", h.GetActiveSession)+ protected.PUT("active-session", h.UpsertActiveSession)+ protected.DELETE("active-session", h.DeleteActiveSession)// Programs- protected.GET("programs", controllers.ListPrograms)- protected.POST("programs", controllers.CreateProgram)- protected.GET("programs/:id", controllers.GetProgram)- protected.PUT("programs/:id", controllers.UpdateProgram)- protected.DELETE("programs/:id", controllers.DeleteProgram)+ protected.GET("programs", h.ListPrograms)+ protected.POST("programs", h.CreateProgram)+ protected.GET("programs/:id", h.GetProgram)+ protected.PUT("programs/:id", h.UpdateProgram)+ protected.DELETE("programs/:id", h.DeleteProgram)// Admin- protected.POST("admin/sync-exercises", controllers.SyncExercises)- protected.GET("admin/seed-status", controllers.ExerciseSeedStatus)- protected.POST("admin/reset-exercises", controllers.ResetExercises)+ protected.POST("admin/sync-exercises", h.SyncExercises)+ protected.GET("admin/seed-status", h.ExerciseSeedStatus)+ protected.POST("admin/reset-exercises", h.ResetExercises)}}diff --git a/backend/seed/exercises.go b/backend/seed/exercises.goindex fa5e301..361b1eb 100644--- a/backend/seed/exercises.go+++ b/backend/seed/exercises.go@@ -35,7 +35,7 @@ type freeExerciseItem struct {// SeedStatus returns current exercise count and whether a seed is running.type SeedStatus struct {- Count int `json:"count"`+ Count int `json:"count"`InProgress bool `json:"in_progress"`}diff --git a/backend/stores/active_session.go b/backend/stores/active_session.gonew file mode 100644index 0000000..52353cc--- /dev/null+++ b/backend/stores/active_session.go@@ -0,0 +1,8 @@+package stores++import "database/sql"++// ActiveSessionStore owns all SQL for the active_session entity.+type ActiveSessionStore struct{ db *sql.DB }++func NewActiveSessionStore(db *sql.DB) *ActiveSessionStore { return &ActiveSessionStore{db: db} }diff --git a/backend/stores/exercise.go b/backend/stores/exercise.gonew file mode 100644index 0000000..1480138--- /dev/null+++ b/backend/stores/exercise.go@@ -0,0 +1,8 @@+package stores++import "database/sql"++// ExerciseStore owns all SQL for the exercise entity.+type ExerciseStore struct{ db *sql.DB }++func NewExerciseStore(db *sql.DB) *ExerciseStore { return &ExerciseStore{db: db} }diff --git a/backend/stores/food.go b/backend/stores/food.gonew file mode 100644index 0000000..6b54d2f--- /dev/null+++ b/backend/stores/food.go@@ -0,0 +1,8 @@+package stores++import "database/sql"++// FoodStore owns all SQL for the food entity.+type FoodStore struct{ db *sql.DB }++func NewFoodStore(db *sql.DB) *FoodStore { return &FoodStore{db: db} }diff --git a/backend/stores/program.go b/backend/stores/program.gonew file mode 100644index 0000000..05822a1--- /dev/null+++ b/backend/stores/program.go@@ -0,0 +1,8 @@+package stores++import "database/sql"++// ProgramStore owns all SQL for the program entity.+type ProgramStore struct{ db *sql.DB }++func NewProgramStore(db *sql.DB) *ProgramStore { return &ProgramStore{db: db} }diff --git a/backend/stores/stores.go b/backend/stores/stores.gonew file mode 100644index 0000000..e77719e--- /dev/null+++ b/backend/stores/stores.go@@ -0,0 +1,31 @@+// Package stores holds the repository layer: each entity has a store that owns+// ALL of its SQL. Controllers depend on these via *Stores (constructor-injected)+// and never touch the database directly. Stores are transport-agnostic — they+// return models + raw errors and import neither gin nor the utils HTTP helpers.+package stores++import "database/sql"++// Stores aggregates every per-entity store, constructed once from the DB handle+// and injected into the HTTP handlers.+type Stores struct {+ ActiveSession *ActiveSessionStore+ Weight *WeightStore+ Food *FoodStore+ User *UserStore+ Exercise *ExerciseStore+ Workout *WorkoutStore+ Program *ProgramStore+}++func New(db *sql.DB) *Stores {+ return &Stores{+ ActiveSession: NewActiveSessionStore(db),+ Weight: NewWeightStore(db),+ Food: NewFoodStore(db),+ User: NewUserStore(db),+ Exercise: NewExerciseStore(db),+ Workout: NewWorkoutStore(db),+ Program: NewProgramStore(db),+ }+}diff --git a/backend/stores/user.go b/backend/stores/user.gonew file mode 100644index 0000000..741c94d--- /dev/null+++ b/backend/stores/user.go@@ -0,0 +1,8 @@+package stores++import "database/sql"++// UserStore owns all SQL for the user entity.+type UserStore struct{ db *sql.DB }++func NewUserStore(db *sql.DB) *UserStore { return &UserStore{db: db} }diff --git a/backend/stores/weight.go b/backend/stores/weight.gonew file mode 100644index 0000000..fcdceb8--- /dev/null+++ b/backend/stores/weight.go@@ -0,0 +1,8 @@+package stores++import "database/sql"++// WeightStore owns all SQL for the weight entity.+type WeightStore struct{ db *sql.DB }++func NewWeightStore(db *sql.DB) *WeightStore { return &WeightStore{db: db} }diff --git a/backend/stores/workout.go b/backend/stores/workout.gonew file mode 100644index 0000000..e5fbb43--- /dev/null+++ b/backend/stores/workout.go@@ -0,0 +1,8 @@+package stores++import "database/sql"++// WorkoutStore owns all SQL for the workout entity.+type WorkoutStore struct{ db *sql.DB }++func NewWorkoutStore(db *sql.DB) *WorkoutStore { return &WorkoutStore{db: db} }