Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Feature/nutrient tracker (#11)
Cartere1ba12559cd8
diff --git a/.gitignore b/.gitignoreindex 33f1edb..858a024 100644--- a/.gitignore+++ b/.gitignore@@ -52,3 +52,8 @@ docs/*.txt# Local Claude contextCLAUDE.md+.claude/++# Playwright artifacts+web/e2e/.auth/+web/test-results/diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 1676469..a86d5f8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -4,6 +4,66 @@ Bug reports, feature requests, and pull requests are welcome. Open an issue befo---+## Local Development Setup++### Prerequisites++- [Go 1.22+](https://go.dev/dl/)+- [Node.js 20+](https://nodejs.org/)++### Backend++```bash+cd backend+go run .+# API listens on http://localhost:3000+```++On first run the backend seeds a demo account and exercise database automatically.++**Demo credentials**+```+Email: [email protected]+Password: password123+```++To seed additional food log history for the demo account:++```bash+python3 scripts/seed_food.py+```++### Frontend++```bash+cd web+npm install+npm run dev+# App at https://localhost:5173+```++The dev server uses a self-signed HTTPS certificate (via `@vitejs/plugin-basic-ssl`). Your browser will show a security warning on first visit — accept it to proceed. HTTPS is required so the barcode scanner can access the device camera on mobile.++**Testing on a mobile device**++1. Run `npm run dev` — Vite binds to all network interfaces (`host: true`)+2. Find your machine's LAN IP: `ipconfig` (Windows) / `ifconfig` (macOS/Linux)+3. Open `https://<your-lan-ip>:5173` on the phone+4. Accept the self-signed cert warning once+5. Barcode scanner and camera will work++### Production++Production HTTPS is handled by a reverse proxy (nginx, Caddy, etc.) with a real TLS certificate — no Vite or self-signed certs involved. The `basicSsl` plugin is dev-only and has no effect on `vite build` output.++```+Internet → nginx/Caddy (real TLS cert)+ ├── / → dist/ (vite build output)+ └── /api → localhost:3000+```++---+## Branch Naming| Prefix | Use for | Example |diff --git a/backend/controllers/food.go b/backend/controllers/food.goindex 0d4365d..c8a7fd8 100644--- a/backend/controllers/food.go+++ b/backend/controllers/food.go@@ -1,7 +1,16 @@package controllersimport (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "log"+ "net/http"+ "net/url"+ "regexp""strconv"+ "strings""time""github.com/Cawlumm/lyftr-backend/db"@@ -11,23 +20,36 @@ import ("github.com/gin-gonic/gin")+var offClient = &http.Client{Timeout: 5 * time.Second}++const offUserAgent = "Lyftr/1.0 (https://lyftr.app; nutrition-tracker)"++// scanFoodLog scans all food_log columns including fiber and image_url.+func scanFoodLog(row interface{ Scan(...any) error }, f *models.FoodLog) error {+ return row.Scan(+ &f.ID, &f.UserID, &f.Name, &f.Meal,+ &f.Calories, &f.Protein, &f.Carbs, &f.Fat, &f.Fiber,+ &f.Servings, &f.ServingSize, &f.Barcode, &f.ImageURL,+ &f.LoggedAt, &f.CreatedAt,+ )+}++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) {uid := middleware.UserID(c)- // default to todaydate := c.Query("date")if date == "" {date = time.Now().Format("2006-01-02")}rows, err := db.DB.Query(- `SELECT id, user_id, name, meal, calories, protein, carbs, fat, servings, serving_size, barcode, logged_at, created_at- FROM food_logs- WHERE user_id = ? AND date(logged_at) = ?- ORDER BY logged_at ASC`,+ foodLogSelect+` WHERE user_id = ? AND substr(logged_at, 1, 10) = ? ORDER BY logged_at ASC`,uid, date,)if err != nil {+ log.Printf("[food/list] db error: %v", err)utils.InternalError(c)return}@@ -36,13 +58,31 @@ func ListFoodLogs(c *gin.Context) {logs := []models.FoodLog{}for rows.Next() {var f models.FoodLog- rows.Scan(&f.ID, &f.UserID, &f.Name, &f.Meal, &f.Calories, &f.Protein, &f.Carbs, &f.Fat,- &f.Servings, &f.ServingSize, &f.Barcode, &f.LoggedAt, &f.CreatedAt)+ if err := scanFoodLog(rows, &f); err != nil {+ log.Printf("[food/list] scan error: %v", err)+ }logs = append(logs, f)}utils.OK(c, logs)}+func GetFoodLog(c *gin.Context) {+ uid := middleware.UserID(c)+ lid, err := strconv.ParseInt(c.Param("id"), 10, 64)+ if err != nil {+ utils.BadRequest(c, "invalid id")+ return+ }++ var f models.FoodLog+ row := db.DB.QueryRow(foodLogSelect+` WHERE id = ? AND user_id = ?`, lid, uid)+ if err := scanFoodLog(row, &f); err != nil {+ utils.NotFound(c, "log entry not found")+ return+ }+ utils.OK(c, f)+}+func LogFood(c *gin.Context) {uid := middleware.UserID(c)var req models.LogFoodRequest@@ -54,6 +94,22 @@ func LogFood(c *gin.Context) {utils.ValidationError(c, err)return}+ if len(req.Name) > 200 {+ utils.BadRequest(c, "name exceeds 200 characters")+ return+ }+ if len(req.ServingSize) > 100 {+ utils.BadRequest(c, "serving_size exceeds 100 characters")+ return+ }+ if len(req.Barcode) > 50 {+ utils.BadRequest(c, "barcode exceeds 50 characters")+ return+ }+ if len(req.ImageURL) > 500 {+ utils.BadRequest(c, "image_url exceeds 500 characters")+ return+ }if req.LoggedAt.IsZero() {req.LoggedAt = time.Now()@@ -63,27 +119,90 @@ func LogFood(c *gin.Context) {}res, err := db.DB.Exec(- `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, servings, serving_size, barcode, logged_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,- uid, req.Name, req.Meal, req.Calories, req.Protein, req.Carbs, req.Fat,- req.Servings, req.ServingSize, req.Barcode, req.LoggedAt,+ `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ uid, req.Name, req.Meal, req.Calories, req.Protein, req.Carbs, req.Fat, req.Fiber,+ req.Servings, req.ServingSize, req.Barcode, req.ImageURL, req.LoggedAt,)if err != nil {+ log.Printf("[food/log] db error: %v", err)utils.InternalError(c)return}id, _ := res.LastInsertId()var f models.FoodLog- db.DB.QueryRow(- `SELECT id, user_id, name, meal, calories, protein, carbs, fat, servings, serving_size, barcode, logged_at, created_at- FROM food_logs WHERE id = ?`, id,- ).Scan(&f.ID, &f.UserID, &f.Name, &f.Meal, &f.Calories, &f.Protein, &f.Carbs, &f.Fat,- &f.Servings, &f.ServingSize, &f.Barcode, &f.LoggedAt, &f.CreatedAt)-+ row := db.DB.QueryRow(foodLogSelect+` WHERE id = ? AND user_id = ?`, id, uid)+ if err := scanFoodLog(row, &f); err != nil {+ log.Printf("[food/log] scan error: %v", err)+ utils.InternalError(c)+ return+ }utils.Created(c, f)}+func UpdateFoodLog(c *gin.Context) {+ uid := middleware.UserID(c)+ lid, err := strconv.ParseInt(c.Param("id"), 10, 64)+ if err != nil {+ utils.BadRequest(c, "invalid id")+ return+ }++ var req models.LogFoodRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ utils.BadRequest(c, err.Error())+ return+ }+ if err := validate.Struct(req); err != nil {+ utils.ValidationError(c, err)+ return+ }+ if len(req.Name) > 200 {+ utils.BadRequest(c, "name exceeds 200 characters")+ return+ }+ if len(req.ServingSize) > 100 {+ utils.BadRequest(c, "serving_size exceeds 100 characters")+ return+ }+ if len(req.Barcode) > 50 {+ utils.BadRequest(c, "barcode exceeds 50 characters")+ return+ }+ if len(req.ImageURL) > 500 {+ utils.BadRequest(c, "image_url exceeds 500 characters")+ return+ }+ if req.Servings == 0 {+ req.Servings = 1+ }++ res, err := db.DB.Exec(+ `UPDATE food_logs SET name=?, meal=?, calories=?, protein=?, carbs=?, fat=?, fiber=?,+ servings=?, serving_size=?, barcode=?, image_url=?, logged_at=?+ WHERE id=? AND user_id=?`,+ req.Name, req.Meal, req.Calories, req.Protein, req.Carbs, req.Fat, req.Fiber,+ req.Servings, req.ServingSize, req.Barcode, req.ImageURL, req.LoggedAt,+ lid, uid,+ )+ if err != nil {+ log.Printf("[food/update] db error: %v", err)+ utils.InternalError(c)+ return+ }+ n, _ := res.RowsAffected()+ if n == 0 {+ utils.NotFound(c, "log entry not found")+ return+ }++ var f models.FoodLog+ row := db.DB.QueryRow(foodLogSelect+` WHERE id = ? AND user_id = ?`, lid, uid)+ scanFoodLog(row, &f)+ utils.OK(c, f)+}+func DeleteFoodLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)@@ -94,6 +213,7 @@ func DeleteFoodLog(c *gin.Context) {res, err := db.DB.Exec(`DELETE FROM food_logs WHERE id = ? AND user_id = ?`, lid, uid)if err != nil {+ log.Printf("[food/delete] db error: %v", err)utils.InternalError(c)return}@@ -115,17 +235,423 @@ func GetDailyStats(c *gin.Context) {var stats models.DailyStatsstats.Date = date- db.DB.QueryRow(+ if err := db.DB.QueryRow(`SELECT COALESCE(SUM(calories),0), COALESCE(SUM(protein),0),- COALESCE(SUM(carbs),0), COALESCE(SUM(fat),0)- FROM food_logs WHERE user_id = ? AND date(logged_at) = ?`,+ COALESCE(SUM(carbs),0), COALESCE(SUM(fat),0), COALESCE(SUM(fiber),0)+ FROM food_logs WHERE user_id = ? AND substr(logged_at, 1, 10) = ?`,uid, date,- ).Scan(&stats.TotalCalories, &stats.TotalProtein, &stats.TotalCarbs, &stats.TotalFat)+ ).Scan(&stats.TotalCalories, &stats.TotalProtein, &stats.TotalCarbs, &stats.TotalFat, &stats.TotalFiber); err != nil {+ log.Printf("[food/stats] scan error (macros): %v", err)+ utils.InternalError(c)+ return+ }- db.DB.QueryRow(- `SELECT COUNT(*) FROM workouts WHERE user_id = ? AND date(started_at) = ?`,+ if err := db.DB.QueryRow(+ `SELECT COUNT(*) FROM workouts WHERE user_id = ? AND substr(started_at, 1, 10) = ?`,uid, date,- ).Scan(&stats.WorkoutCount)+ ).Scan(&stats.WorkoutCount); err != nil {+ log.Printf("[food/stats] scan error (workouts): %v", err)+ utils.InternalError(c)+ return+ }utils.OK(c, stats)}++func GetFoodHistory(c *gin.Context) {+ uid := middleware.UserID(c)++ days := 30+ if d, err := strconv.Atoi(c.Query("days")); err == nil && d > 0 && d <= 365 {+ days = d+ }++ rows, err := db.DB.Query(+ `SELECT substr(logged_at, 1, 10) as d,+ COALESCE(SUM(calories),0), COALESCE(SUM(protein),0),+ COALESCE(SUM(carbs),0), COALESCE(SUM(fat),0)+ FROM food_logs+ WHERE user_id = ? AND logged_at >= date('now', ?)+ GROUP BY d ORDER BY d ASC`,+ uid, fmt.Sprintf("-%d days", days),+ )+ if err != nil {+ log.Printf("[food/history] db error: %v", err)+ utils.InternalError(c)+ return+ }+ defer rows.Close()++ points := []models.FoodHistoryPoint{}+ for rows.Next() {+ var p models.FoodHistoryPoint+ if err := rows.Scan(&p.Date, &p.Calories, &p.Protein, &p.Carbs, &p.Fat); err != nil {+ log.Printf("food/history scan: %v", err)+ continue+ }+ points = append(points, p)+ }+ utils.OK(c, points)+}++// ─── Open Food Facts proxy ────────────────────────────────────────────────────++// offSearchResponse is a partial decode of the OFF search API response.+type offSearchResponse struct {+ Products []offProduct `json:"products"` // CGI endpoint+ Hits []offProduct `json:"hits"` // new search endpoint+}++// offBrands accepts both a JSON string and a JSON array of strings.+type offBrands []string++func (b *offBrands) UnmarshalJSON(data []byte) error {+ if len(data) == 0 || string(data) == "null" {+ return nil+ }+ if data[0] == '[' {+ var arr []string+ if err := json.Unmarshal(data, &arr); err != nil {+ return err+ }+ *b = arr+ return nil+ }+ var s string+ if err := json.Unmarshal(data, &s); err != nil {+ return err+ }+ if s != "" {+ *b = []string{s}+ }+ return nil+}++type offProduct struct {+ ProductName string `json:"product_name"`+ Brands offBrands `json:"brands"`+ Nutriments offNutrients `json:"nutriments"`+ ServingSize string `json:"serving_size"`+ ImageURL string `json:"image_url"`+}++type offNutrients struct {+ EnergyKcal100g float64 `json:"energy-kcal_100g"`+ Proteins100g float64 `json:"proteins_100g"`+ Carbohydrates100g float64 `json:"carbohydrates_100g"`+ Fat100g float64 `json:"fat_100g"`+ Fiber100g float64 `json:"fiber_100g"`++ EnergyKcalServing float64 `json:"energy-kcal_serving"`+ ProteinsServing float64 `json:"proteins_serving"`+ CarbohydratesServing float64 `json:"carbohydrates_serving"`+ FatServing float64 `json:"fat_serving"`+ FiberServing float64 `json:"fiber_serving"`+}++func offProductToResult(p offProduct) models.FoodSearchResult {+ brand := strings.Join(p.Brands, ", ")+ imageURL := p.ImageURL+ if !strings.HasPrefix(imageURL, "https://") {+ imageURL = ""+ }++ // Prefer per-serving values when OFF provides them and a serving size label.+ // Fall back to per-100g so the label always matches the numbers.+ useServing := p.Nutriments.EnergyKcalServing > 0 && strings.TrimSpace(p.ServingSize) != ""+ var cal, pro, carb, fat, fiber float64+ var servingLabel string+ if useServing {+ cal = p.Nutriments.EnergyKcalServing+ pro = p.Nutriments.ProteinsServing+ carb = p.Nutriments.CarbohydratesServing+ fat = p.Nutriments.FatServing+ fiber = p.Nutriments.FiberServing+ servingLabel = p.ServingSize+ } else {+ cal = p.Nutriments.EnergyKcal100g+ pro = p.Nutriments.Proteins100g+ carb = p.Nutriments.Carbohydrates100g+ fat = p.Nutriments.Fat100g+ fiber = p.Nutriments.Fiber100g+ servingLabel = "per 100g"+ }++ return models.FoodSearchResult{+ Name: p.ProductName,+ Brand: brand,+ Calories: cal,+ Protein: pro,+ Carbs: carb,+ Fat: fat,+ Fiber: fiber,+ ServingSize: servingLabel,+ ImageURL: imageURL,+ Source: "off",+ }+}++func doOFFRequest(ctx context.Context, rawURL string) ([]byte, int, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)+ if err != nil {+ return nil, 0, err+ }+ req.Header.Set("User-Agent", offUserAgent)++ resp, err := offClient.Do(req)+ if err != nil {+ return nil, 0, err+ }+ defer resp.Body.Close()++ body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) // 4 MB limit+ return body, resp.StatusCode, err+}++func SearchFood(c *gin.Context) {+ q := c.Query("q")+ if q == "" {+ utils.BadRequest(c, "q is required")+ return+ }++ limit := 20+ if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 50 {+ limit = l+ }++ start := time.Now()+ searchURL := fmt.Sprintf(+ "https://search.openfoodfacts.org/search?q=%s&lang=en&cc=world&page_size=%d&page=1&fields=product_name,brands,nutriments,serving_size,image_url",+ url.QueryEscape(q), limit,+ )+ log.Printf("[food/search] OFF request: q=%q limit=%d", q, limit)++ ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)+ defer cancel()++ body, status, err := doOFFRequest(ctx, searchURL)+ elapsed := time.Since(start)+ log.Printf("[food/search] OFF response: status=%d duration=%dms", status, elapsed.Milliseconds())++ if err != nil {+ if ctx.Err() == context.DeadlineExceeded {+ log.Printf("[food/search] OFF timeout after %dms", elapsed.Milliseconds())+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "food search timed out — try again"})+ return+ }+ log.Printf("[food/search] OFF network error: %v", err)+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "could not reach food database"})+ return+ }++ switch {+ case status == 429:+ log.Printf("[food/search] OFF rate limit hit")+ c.Header("Retry-After", "60")+ c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many requests — wait a moment and try again"})+ return+ case status >= 500:+ log.Printf("[food/search] OFF upstream error: %d", status)+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "food search temporarily unavailable"})+ return+ case status != 200:+ log.Printf("[food/search] OFF unexpected status: %d", status)+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "food search temporarily unavailable"})+ return+ }++ var parsed offSearchResponse+ if err := json.Unmarshal(body, &parsed); err != nil {+ log.Printf("[food/search] OFF parse error: %v", err)+ utils.InternalError(c)+ return+ }++ products := parsed.Hits+ if len(products) == 0 {+ products = parsed.Products // fallback for CGI-style response+ }+ results := make([]models.FoodSearchResult, 0, len(products))+ for _, p := range products {+ if p.ProductName == "" {+ continue+ }+ results = append(results, offProductToResult(p))+ }+ utils.OK(c, results)+}++// offBarcodeResponse is a partial decode of the OFF v3 product endpoint.+type offBarcodeResponse struct {+ Status string `json:"status"` // v3 API returns "success" | "failure"+ Product offProduct `json:"product"`+}++func LookupBarcode(c *gin.Context) {+ code := c.Param("code")+ if code == "" {+ utils.BadRequest(c, "barcode is required")+ return+ }++ matched, err := regexp.MatchString(`^\d{6,14}$`, code)+ if err != nil || !matched {+ utils.BadRequest(c, "Invalid barcode format")+ return+ }++ start := time.Now()+ lookupURL := fmt.Sprintf("https://world.openfoodfacts.org/api/v3/product/%s.json", url.PathEscape(code))+ log.Printf("[food/barcode] OFF request: code=%q", code)++ ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)+ defer cancel()++ body, status, err := doOFFRequest(ctx, lookupURL)+ elapsed := time.Since(start)+ log.Printf("[food/barcode] OFF response: status=%d duration=%dms", status, elapsed.Milliseconds())++ if err != nil {+ if ctx.Err() == context.DeadlineExceeded {+ log.Printf("[food/barcode] OFF timeout after %dms", elapsed.Milliseconds())+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "barcode lookup timed out — try again"})+ return+ }+ log.Printf("[food/barcode] OFF network error: %v", err)+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "could not reach food database"})+ return+ }++ switch {+ case status == 429:+ log.Printf("[food/barcode] OFF rate limit hit")+ c.Header("Retry-After", "60")+ c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many requests — wait a moment and try again"})+ return+ case status >= 500:+ log.Printf("[food/barcode] OFF upstream error: %d", status)+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "barcode lookup temporarily unavailable"})+ return+ }++ var parsed offBarcodeResponse+ if err := json.Unmarshal(body, &parsed); err != nil {+ log.Printf("[food/barcode] OFF parse error: %v", err)+ utils.InternalError(c)+ return+ }++ if !strings.HasPrefix(parsed.Status, "success") || parsed.Product.ProductName == "" {+ utils.NotFound(c, "product not found")+ return+ }++ utils.OK(c, offProductToResult(parsed.Product))+}++// ─── Saved Foods ──────────────────────────────────────────────────────────────++func ListSavedFoods(c *gin.Context) {+ uid := middleware.UserID(c)++ rows, err := db.DB.Query(+ `SELECT id, user_id, name, brand, calories, protein, carbs, fat, fiber, serving_size, barcode, created_at+ FROM saved_foods WHERE user_id = ? ORDER BY name ASC`,+ uid,+ )+ if err != nil {+ log.Printf("[food/saved/list] db error: %v", err)+ utils.InternalError(c)+ return+ }+ defer rows.Close()++ foods := []models.SavedFood{}+ for rows.Next() {+ var f models.SavedFood+ if err := rows.Scan(&f.ID, &f.UserID, &f.Name, &f.Brand, &f.Calories, &f.Protein, &f.Carbs, &f.Fat,+ &f.Fiber, &f.ServingSize, &f.Barcode, &f.CreatedAt); err != nil {+ log.Printf("food/saved/list scan: %v", err)+ continue+ }+ foods = append(foods, f)+ }+ utils.OK(c, foods)+}++func CreateSavedFood(c *gin.Context) {+ uid := middleware.UserID(c)+ var req models.SaveFoodRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ utils.BadRequest(c, err.Error())+ return+ }+ if err := validate.Struct(req); err != nil {+ utils.ValidationError(c, err)+ return+ }+ if len(req.Name) > 200 {+ utils.BadRequest(c, "name exceeds 200 characters")+ return+ }+ if len(req.Brand) > 200 {+ utils.BadRequest(c, "brand exceeds 200 characters")+ return+ }+ if len(req.ServingSize) > 100 {+ utils.BadRequest(c, "serving_size exceeds 100 characters")+ return+ }+ if len(req.Barcode) > 50 {+ utils.BadRequest(c, "barcode exceeds 50 characters")+ return+ }++ res, err := db.DB.Exec(+ `INSERT INTO saved_foods (user_id, name, brand, calories, protein, carbs, fat, fiber, serving_size, barcode)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ uid, req.Name, req.Brand, req.Calories, req.Protein, req.Carbs, req.Fat, req.Fiber,+ req.ServingSize, req.Barcode,+ )+ if err != nil {+ log.Printf("[food/saved/create] db error: %v", err)+ utils.InternalError(c)+ return+ }++ id, _ := res.LastInsertId()+ var f models.SavedFood+ if err := db.DB.QueryRow(+ `SELECT id, user_id, name, brand, calories, protein, carbs, fat, fiber, serving_size, barcode, created_at+ FROM saved_foods WHERE id = ?`, id,+ ).Scan(&f.ID, &f.UserID, &f.Name, &f.Brand, &f.Calories, &f.Protein, &f.Carbs, &f.Fat,+ &f.Fiber, &f.ServingSize, &f.Barcode, &f.CreatedAt); err != nil {+ log.Printf("[food/saved/create] scan error: %v", err)+ utils.InternalError(c)+ return+ }+ utils.Created(c, f)+}++func DeleteSavedFood(c *gin.Context) {+ uid := middleware.UserID(c)+ fid, err := strconv.ParseInt(c.Param("id"), 10, 64)+ if err != nil {+ utils.BadRequest(c, "invalid id")+ return+ }++ res, err := db.DB.Exec(`DELETE FROM saved_foods WHERE id = ? AND user_id = ?`, fid, uid)+ if err != nil {+ log.Printf("[food/saved/delete] db error: %v", err)+ utils.InternalError(c)+ return+ }+ n, _ := res.RowsAffected()+ if n == 0 {+ utils.NotFound(c, "saved food not found")+ return+ }+ utils.OK(c, gin.H{"deleted": true})+}diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.gonew file mode 100644index 0000000..4c0adb7--- /dev/null+++ b/backend/controllers/food_test.go@@ -0,0 +1,933 @@+package controllers++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/Cawlumm/lyftr-backend/db"+)++// ─── helpers ──────────────────────────────────────────────────────────────────++func insertFoodLog(t *testing.T, uid int64, name, meal string, calories, protein, carbs, fat float64, loggedAt time.Time) int64 {+ t.Helper()+ res, err := db.DB.Exec(+ `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, 1, '', '', '', ?)`,+ uid, name, meal, calories, protein, carbs, fat,+ loggedAt.Format("2006-01-02T15:04:05Z"),+ )+ if err != nil {+ t.Fatalf("insertFoodLog: %v", err)+ }+ id, _ := res.LastInsertId()+ return id+}++func insertSavedFood(t *testing.T, uid int64, name string) int64 {+ t.Helper()+ res, err := db.DB.Exec(+ `INSERT INTO saved_foods (user_id, name, brand, calories, protein, carbs, fat, fiber, serving_size, barcode) VALUES (?, ?, '', 100, 10, 10, 5, 2, '1 serving', '')`,+ uid, name,+ )+ if err != nil {+ t.Fatalf("insertSavedFood: %v", err)+ }+ id, _ := res.LastInsertId()+ return id+}++func otherUser(t *testing.T) int64 {+ t.Helper()+ res, err := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, "[email protected]", "x")+ if err != nil {+ t.Fatalf("otherUser: %v", err)+ }+ id, _ := res.LastInsertId()+ return id+}++// offMockTransport rewrites all requests to the given httptest.Server, so+// SearchFood and LookupBarcode hit a local handler instead of real OFF.+type offMockTransport struct{ server *httptest.Server }++func (tr *offMockTransport) RoundTrip(r *http.Request) (*http.Response, error) {+ r2 := r.Clone(r.Context())+ r2.URL.Scheme = "http"+ r2.URL.Host = strings.TrimPrefix(tr.server.URL, "http://")+ return http.DefaultTransport.RoundTrip(r2)+}++func withOFFMock(t *testing.T, handler http.HandlerFunc) *httptest.Server {+ t.Helper()+ s := httptest.NewServer(handler)+ prev := offClient+ offClient = &http.Client{Transport: &offMockTransport{server: s}, Timeout: 5 * time.Second}+ t.Cleanup(func() {+ offClient = prev+ s.Close()+ })+ return s+}++// ─── ListFoodLogs ─────────────────────────────────────────────────────────────++func TestListFoodLogs_empty(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ c, w := newContext(uid, http.MethodGet, "/api/v1/food", nil)+ ListFoodLogs(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 0 {+ t.Fatalf("expected empty list, got %d items", len(data))+ }+}++func TestListFoodLogs_scopedByDateAndUser(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other := otherUser(t)++ today := time.Now()+ yesterday := today.AddDate(0, 0, -1)++ insertFoodLog(t, uid, "Breakfast today", "breakfast", 400, 30, 50, 10, today)+ insertFoodLog(t, uid, "Lunch yesterday", "lunch", 600, 40, 60, 15, yesterday)+ insertFoodLog(t, other, "Other user today", "dinner", 500, 25, 55, 12, today)++ date := today.Format("2006-01-02")+ c, w := newContext(uid, http.MethodGet, "/api/v1/food?date="+date, nil)+ ListFoodLogs(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 1 {+ t.Fatalf("expected 1 entry for today (own only), got %d", len(data))+ }+ entry := data[0].(map[string]any)+ if entry["name"].(string) != "Breakfast today" {+ t.Errorf("unexpected entry name: %v", entry["name"])+ }+}++// ─── GetFoodLog ───────────────────────────────────────────────────────────────++func TestGetFoodLog_success(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ id := insertFoodLog(t, uid, "Chicken breast", "lunch", 300, 50, 5, 8, time.Now())++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/"+fmt.Sprint(id), nil)+ setParam(c, "id", fmt.Sprint(id))+ GetFoodLog(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["name"].(string) != "Chicken breast" {+ t.Errorf("unexpected name: %v", data["name"])+ }+}++func TestGetFoodLog_ownershipEnforced(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other := otherUser(t)+ id := insertFoodLog(t, other, "Secret meal", "dinner", 800, 60, 80, 30, time.Now())++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/"+fmt.Sprint(id), nil)+ setParam(c, "id", fmt.Sprint(id))+ GetFoodLog(c)++ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404 for cross-user get, got %d", w.Code)+ }+}++func TestGetFoodLog_invalidID(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/abc", nil)+ setParam(c, "id", "abc")+ GetFoodLog(c)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for invalid id, got %d", w.Code)+ }+}++// ─── LogFood ──────────────────────────────────────────────────────────────────++func TestLogFood_success(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{+ "name": "Oatmeal", "meal": "breakfast",+ "calories": 350.0, "protein": 12.0, "carbs": 60.0, "fat": 6.0,+ "fiber": 5.0, "servings": 1.0, "serving_size": "1 cup",+ }+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)+ LogFood(c)++ if w.Code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["name"].(string) != "Oatmeal" {+ t.Errorf("expected name Oatmeal, got %v", data["name"])+ }+ if data["calories"].(float64) != 350.0 {+ t.Errorf("expected calories 350, got %v", data["calories"])+ }+ if data["fiber"].(float64) != 5.0 {+ t.Errorf("expected fiber 5, got %v", data["fiber"])+ }+ if data["servings"].(float64) != 1.0 {+ t.Errorf("expected servings 1, got %v", data["servings"])+ }+}++func TestLogFood_defaultsServingsToOne(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{+ "name": "Apple", "meal": "snacks",+ "calories": 95.0, "protein": 0.5, "carbs": 25.0, "fat": 0.3,+ }+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)+ LogFood(c)++ if w.Code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["servings"].(float64) != 1.0 {+ t.Errorf("expected default servings=1, got %v", data["servings"])+ }+}++func TestLogFood_missingName(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{"meal": "breakfast", "calories": 300.0}+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)+ LogFood(c)++ if w.Code == http.StatusCreated {+ t.Fatal("expected error for missing name, got 201")+ }+}++func TestLogFood_nameTooLong(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{+ "name": strings.Repeat("x", 201), "meal": "lunch",+ "calories": 100.0, "protein": 5.0, "carbs": 10.0, "fat": 3.0,+ }+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)+ LogFood(c)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for name > 200 chars, got %d", w.Code)+ }+}++func TestLogFood_imageURLTooLong(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{+ "name": "Test", "meal": "lunch",+ "calories": 100.0, "protein": 5.0, "carbs": 10.0, "fat": 3.0,+ "image_url": "https://" + strings.Repeat("a", 494),+ }+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)+ LogFood(c)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for image_url > 500 chars, got %d", w.Code)+ }+}++func TestLogFood_barcodeTooLong(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{+ "name": "Test", "meal": "dinner",+ "calories": 100.0, "protein": 5.0, "carbs": 10.0, "fat": 3.0,+ "barcode": strings.Repeat("1", 51),+ }+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)+ LogFood(c)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for barcode > 50 chars, got %d", w.Code)+ }+}++// ─── UpdateFoodLog ────────────────────────────────────────────────────────────++func TestUpdateFoodLog_success(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ id := insertFoodLog(t, uid, "Old name", "breakfast", 300, 20, 40, 10, time.Now())++ body := map[string]any{+ "name": "New name", "meal": "lunch",+ "calories": 450.0, "protein": 35.0, "carbs": 55.0, "fat": 12.0,+ }+ c, w := newContext(uid, http.MethodPatch, "/api/v1/food/"+fmt.Sprint(id), body)+ setParam(c, "id", fmt.Sprint(id))+ UpdateFoodLog(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["name"].(string) != "New name" {+ t.Errorf("expected updated name, got %v", data["name"])+ }+ if data["calories"].(float64) != 450.0 {+ t.Errorf("expected updated calories 450, got %v", data["calories"])+ }+ if data["meal"].(string) != "lunch" {+ t.Errorf("expected updated meal lunch, got %v", data["meal"])+ }+}++func TestUpdateFoodLog_ownershipEnforced(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other := otherUser(t)+ id := insertFoodLog(t, other, "Original", "dinner", 500, 30, 60, 15, time.Now())++ body := map[string]any{+ "name": "Hijacked", "meal": "snacks",+ "calories": 100.0, "protein": 5.0, "carbs": 10.0, "fat": 3.0,+ }+ c, w := newContext(uid, http.MethodPatch, "/api/v1/food/"+fmt.Sprint(id), body)+ setParam(c, "id", fmt.Sprint(id))+ UpdateFoodLog(c)++ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404 for cross-user update, got %d", w.Code)+ }+ var name string+ db.DB.QueryRow(`SELECT name FROM food_logs WHERE id = ?`, id).Scan(&name)+ if name != "Original" {+ t.Fatal("entry was modified by wrong user")+ }+}++func TestUpdateFoodLog_notFound(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{+ "name": "x", "meal": "lunch",+ "calories": 100.0, "protein": 5.0, "carbs": 10.0, "fat": 3.0,+ }+ c, w := newContext(uid, http.MethodPatch, "/api/v1/food/9999", body)+ setParam(c, "id", "9999")+ UpdateFoodLog(c)++ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404 for missing entry, got %d", w.Code)+ }+}++// ─── DeleteFoodLog ────────────────────────────────────────────────────────────++func TestDeleteFoodLog_success(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ id := insertFoodLog(t, uid, "To delete", "snacks", 100, 5, 15, 3, time.Now())++ c, w := newContext(uid, http.MethodDelete, "/api/v1/food/"+fmt.Sprint(id), nil)+ setParam(c, "id", fmt.Sprint(id))+ DeleteFoodLog(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var count int+ db.DB.QueryRow(`SELECT COUNT(*) FROM food_logs WHERE id = ?`, id).Scan(&count)+ if count != 0 {+ t.Fatal("entry was not deleted")+ }+}++func TestDeleteFoodLog_ownershipEnforced(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other := otherUser(t)+ id := insertFoodLog(t, other, "Protected", "breakfast", 400, 25, 50, 12, time.Now())++ c, w := newContext(uid, http.MethodDelete, "/api/v1/food/"+fmt.Sprint(id), nil)+ setParam(c, "id", fmt.Sprint(id))+ DeleteFoodLog(c)++ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404 for cross-user delete, got %d", w.Code)+ }+ var count int+ db.DB.QueryRow(`SELECT COUNT(*) FROM food_logs WHERE id = ?`, id).Scan(&count)+ if count != 1 {+ t.Fatal("entry was deleted by wrong user")+ }+}++// ─── GetDailyStats ────────────────────────────────────────────────────────────++func TestGetDailyStats_empty(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ date := time.Now().Format("2006-01-02")+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/stats?date="+date, nil)+ GetDailyStats(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["total_calories"].(float64) != 0 {+ t.Errorf("expected 0 calories, got %v", data["total_calories"])+ }+}++func TestGetDailyStats_sumsMacrosCorrectly(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ today := time.Now()+ insertFoodLog(t, uid, "Breakfast", "breakfast", 500, 30, 60, 15, today)+ insertFoodLog(t, uid, "Lunch", "lunch", 700, 50, 80, 20, today)+ // Different date — must be excluded+ insertFoodLog(t, uid, "Yesterday", "dinner", 600, 40, 70, 18, today.AddDate(0, 0, -1))++ date := today.Format("2006-01-02")+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/stats?date="+date, nil)+ GetDailyStats(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["total_calories"].(float64) != 1200 {+ t.Errorf("expected total_calories=1200, got %v", data["total_calories"])+ }+ if data["total_protein"].(float64) != 80 {+ t.Errorf("expected total_protein=80, got %v", data["total_protein"])+ }+ if data["total_carbs"].(float64) != 140 {+ t.Errorf("expected total_carbs=140, got %v", data["total_carbs"])+ }+ if data["total_fat"].(float64) != 35 {+ t.Errorf("expected total_fat=35, got %v", data["total_fat"])+ }+}++func TestGetDailyStats_scopedByUser(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other := otherUser(t)+ today := time.Now()++ insertFoodLog(t, uid, "Mine", "breakfast", 400, 25, 50, 10, today)+ insertFoodLog(t, other, "Theirs", "lunch", 9999, 999, 999, 999, today)++ date := today.Format("2006-01-02")+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/stats?date="+date, nil)+ GetDailyStats(c)++ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["total_calories"].(float64) != 400 {+ t.Errorf("expected 400 kcal (own only), got %v", data["total_calories"])+ }+}++// ─── GetFoodHistory ───────────────────────────────────────────────────────────++func TestGetFoodHistory_empty(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/history?days=7", nil)+ GetFoodHistory(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 0 {+ t.Fatalf("expected empty history, got %d points", len(data))+ }+}++func TestGetFoodHistory_groupsByDay(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ now := time.Now()++ // Two entries on same day → should be one aggregated point+ insertFoodLog(t, uid, "A", "breakfast", 400, 20, 50, 10, now.AddDate(0, 0, -1))+ insertFoodLog(t, uid, "B", "lunch", 600, 40, 70, 15, now.AddDate(0, 0, -1))+ // Entry outside window → excluded+ 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)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 1 {+ t.Fatalf("expected 1 day point, got %d", len(data))+ }+ pt := data[0].(map[string]any)+ if pt["calories"].(float64) != 1000 {+ t.Errorf("expected aggregated calories=1000, got %v", pt["calories"])+ }+ if pt["protein"].(float64) != 60 {+ t.Errorf("expected aggregated protein=60, got %v", pt["protein"])+ }+}++func TestGetFoodHistory_defaultsDaysTo30(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ // Entry 20 days ago — should appear with no ?days param (default 30)+ 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)++ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 1 {+ t.Fatalf("expected 1 point within default 30d window, got %d", len(data))+ }+}++// ─── offBrands.UnmarshalJSON ──────────────────────────────────────────────────++func TestOffBrands_stringInput(t *testing.T) {+ var b offBrands+ if err := json.Unmarshal([]byte(`"Kellogg's"`), &b); err != nil {+ t.Fatalf("unmarshal string brand: %v", err)+ }+ if len(b) != 1 || b[0] != "Kellogg's" {+ t.Errorf("expected [\"Kellogg's\"], got %v", b)+ }+}++func TestOffBrands_arrayInput(t *testing.T) {+ var b offBrands+ if err := json.Unmarshal([]byte(`["Jif","Smucker's"]`), &b); err != nil {+ t.Fatalf("unmarshal array brands: %v", err)+ }+ if len(b) != 2 {+ t.Errorf("expected 2 brands, got %v", b)+ }+}++func TestOffBrands_nullInput(t *testing.T) {+ var b offBrands+ if err := json.Unmarshal([]byte(`null`), &b); err != nil {+ t.Fatalf("unmarshal null: %v", err)+ }+ if len(b) != 0 {+ t.Errorf("expected empty brands for null, got %v", b)+ }+}++// ─── offProductToResult ───────────────────────────────────────────────────────++func TestOffProductToResult_usesServingWhenAvailable(t *testing.T) {+ p := offProduct{+ ProductName: "Jif Peanut Butter",+ Brands: offBrands{"Jif"},+ ServingSize: "2 tbsp (32g)",+ Nutriments: offNutrients{+ EnergyKcal100g: 593, Proteins100g: 19, Carbohydrates100g: 22, Fat100g: 50,+ EnergyKcalServing: 190, ProteinsServing: 7, CarbohydratesServing: 7, FatServing: 16,+ },+ ImageURL: "https://images.openfoodfacts.org/jif.jpg",+ }+ r := offProductToResult(p)++ if r.Calories != 190 {+ t.Errorf("expected per-serving calories 190, got %v", r.Calories)+ }+ if r.ServingSize != "2 tbsp (32g)" {+ t.Errorf("expected serving size label, got %q", r.ServingSize)+ }+ if r.ImageURL != "https://images.openfoodfacts.org/jif.jpg" {+ t.Errorf("unexpected image url: %v", r.ImageURL)+ }+}++func TestOffProductToResult_fallsBackTo100g(t *testing.T) {+ p := offProduct{+ ProductName: "Generic Bread",+ Nutriments: offNutrients{EnergyKcal100g: 265, Proteins100g: 9, Carbohydrates100g: 49, Fat100g: 3},+ // No serving_size, no _serving nutriments+ }+ r := offProductToResult(p)++ if r.Calories != 265 {+ t.Errorf("expected per-100g calories 265, got %v", r.Calories)+ }+ if r.ServingSize != "per 100g" {+ t.Errorf("expected 'per 100g' label, got %q", r.ServingSize)+ }+}++func TestOffProductToResult_rejectsNonHTTPSImageURL(t *testing.T) {+ p := offProduct{+ ProductName: "Test",+ ImageURL: "http://example.com/img.jpg", // http, not https+ }+ r := offProductToResult(p)+ if r.ImageURL != "" {+ t.Errorf("expected empty image_url for non-https, got %q", r.ImageURL)+ }+}++func TestOffProductToResult_rejectsJavascriptImageURL(t *testing.T) {+ p := offProduct{+ ProductName: "Test",+ ImageURL: "javascript:alert(1)",+ }+ r := offProductToResult(p)+ if r.ImageURL != "" {+ t.Errorf("expected empty image_url for javascript: URL, got %q", r.ImageURL)+ }+}++func TestOffProductToResult_joinsMultipleBrands(t *testing.T) {+ p := offProduct{+ ProductName: "Cola",+ Brands: offBrands{"Coca-Cola", "TCCC"},+ }+ r := offProductToResult(p)+ if r.Brand != "Coca-Cola, TCCC" {+ t.Errorf("expected joined brands, got %q", r.Brand)+ }+}++// ─── LookupBarcode ────────────────────────────────────────────────────────────++func TestLookupBarcode_invalidFormat(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(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)+ if w.Code != http.StatusBadRequest {+ t.Errorf("code %q: expected 400, got %d", code, w.Code)+ }+ }+}++func TestLookupBarcode_success(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ offResp := `{"status":"success","product":{"product_name":"Jif PB","brands":"Jif","serving_size":"2 tbsp","nutriments":{"energy-kcal_serving":190,"proteins_serving":7,"carbohydrates_serving":7,"fat_serving":16}}}`+ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(offResp))+ })++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/051500255186", nil)+ setParam(c, "code", "051500255186")+ LookupBarcode(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["name"].(string) != "Jif PB" {+ t.Errorf("expected name 'Jif PB', got %v", data["name"])+ }+ if data["calories"].(float64) != 190 {+ t.Errorf("expected per-serving calories 190, got %v", data["calories"])+ }+}++func TestLookupBarcode_productNotFound(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"status":"failure","product":{}}`))+ })++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/012345678901", nil)+ setParam(c, "code", "012345678901")+ LookupBarcode(c)++ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404 for unknown barcode, got %d", w.Code)+ }+}++func TestLookupBarcode_rateLimited(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusTooManyRequests)+ })++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/012345678901", nil)+ setParam(c, "code", "012345678901")+ LookupBarcode(c)++ if w.Code != http.StatusTooManyRequests {+ t.Fatalf("expected 429 forwarded, got %d", w.Code)+ }+}++// ─── SearchFood ───────────────────────────────────────────────────────────────++func TestSearchFood_missingQuery(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/search", nil)+ SearchFood(c)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for missing q, got %d", w.Code)+ }+}++func TestSearchFood_success(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ offResp := `{"hits":[{"product_name":"Whole Milk","brands":"Organic Valley","serving_size":"1 cup","nutriments":{"energy-kcal_serving":150,"proteins_serving":8,"carbohydrates_serving":12,"fat_serving":8}},{"product_name":"","brands":"","nutriments":{}}]}`+ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(offResp))+ })++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/search?q=milk", nil)+ SearchFood(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ // Product with empty name must be filtered out+ if len(data) != 1 {+ t.Fatalf("expected 1 result (empty product filtered), got %d", len(data))+ }+ item := data[0].(map[string]any)+ if item["name"].(string) != "Whole Milk" {+ t.Errorf("expected 'Whole Milk', got %v", item["name"])+ }+}++func TestSearchFood_rateLimited(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusTooManyRequests)+ })++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/search?q=pizza", nil)+ SearchFood(c)++ if w.Code != http.StatusTooManyRequests {+ t.Fatalf("expected 429 forwarded, got %d", w.Code)+ }+}++func TestSearchFood_upstreamError(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ })++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/search?q=pizza", nil)+ SearchFood(c)++ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503 for OFF 5xx, got %d", w.Code)+ }+}++// ─── ListSavedFoods ───────────────────────────────────────────────────────────++func TestListSavedFoods_empty(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/saved", nil)+ ListSavedFoods(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 0 {+ t.Fatalf("expected empty list, got %d items", len(data))+ }+}++func TestListSavedFoods_alphabeticalAndScopedByUser(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other := otherUser(t)++ insertSavedFood(t, uid, "Zucchini")+ insertSavedFood(t, uid, "Apple")+ insertSavedFood(t, uid, "Mango")+ insertSavedFood(t, other, "Should not appear")++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/saved", nil)+ ListSavedFoods(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ resp := decodeResponse(t, w)+ data := resp["data"].([]any)+ if len(data) != 3 {+ t.Fatalf("expected 3 items (own only), got %d", len(data))+ }+ names := []string{+ data[0].(map[string]any)["name"].(string),+ data[1].(map[string]any)["name"].(string),+ data[2].(map[string]any)["name"].(string),+ }+ if names[0] != "Apple" || names[1] != "Mango" || names[2] != "Zucchini" {+ t.Errorf("expected alphabetical order, got %v", names)+ }+}++// ─── CreateSavedFood ──────────────────────────────────────────────────────────++func TestCreateSavedFood_success(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ body := map[string]any{+ "name": "Greek Yogurt", "brand": "Chobani",+ "calories": 130.0, "protein": 17.0, "carbs": 9.0, "fat": 3.5,+ "fiber": 0.0, "serving_size": "1 container (170g)",+ }+ c, w := newContext(uid, http.MethodPost, "/api/v1/food/saved", body)+ CreateSavedFood(c)++ if w.Code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())+ }+ resp := decodeResponse(t, w)+ data := resp["data"].(map[string]any)+ if data["name"].(string) != "Greek Yogurt" {+ t.Errorf("expected name 'Greek Yogurt', got %v", data["name"])+ }+ if data["brand"].(string) != "Chobani" {+ t.Errorf("expected brand 'Chobani', got %v", data["brand"])+ }+}++func TestCreateSavedFood_missingName(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(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)++ if w.Code == http.StatusCreated {+ t.Fatal("expected error for missing name, got 201")+ }+}++// ─── DeleteSavedFood ──────────────────────────────────────────────────────────++func TestDeleteSavedFood_success(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ id := insertSavedFood(t, uid, "To delete")++ c, w := newContext(uid, http.MethodDelete, "/api/v1/food/saved/"+fmt.Sprint(id), nil)+ setParam(c, "id", fmt.Sprint(id))+ DeleteSavedFood(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var count int+ db.DB.QueryRow(`SELECT COUNT(*) FROM saved_foods WHERE id = ?`, id).Scan(&count)+ if count != 0 {+ t.Fatal("saved food was not deleted")+ }+}++func TestDeleteSavedFood_ownershipEnforced(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other := otherUser(t)+ id := insertSavedFood(t, other, "Protected food")++ c, w := newContext(uid, http.MethodDelete, "/api/v1/food/saved/"+fmt.Sprint(id), nil)+ setParam(c, "id", fmt.Sprint(id))+ DeleteSavedFood(c)++ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404 for cross-user delete, got %d", w.Code)+ }+ var count int+ db.DB.QueryRow(`SELECT COUNT(*) FROM saved_foods WHERE id = ?`, id).Scan(&count)+ if count != 1 {+ t.Fatal("saved food was deleted by wrong user")+ }+}diff --git a/backend/controllers/testhelper_test.go b/backend/controllers/testhelper_test.goindex 0966d04..97ae6ce 100644--- a/backend/controllers/testhelper_test.go+++ b/backend/controllers/testhelper_test.go@@ -108,6 +108,37 @@ CREATE TABLE IF NOT EXISTS weight_logs (notes TEXT NOT NULL DEFAULT '',logged_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP+);+CREATE TABLE IF NOT EXISTS food_logs (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ meal TEXT NOT NULL DEFAULT 'snacks',+ calories REAL NOT NULL DEFAULT 0,+ protein REAL NOT NULL DEFAULT 0,+ carbs REAL NOT NULL DEFAULT 0,+ fat REAL NOT NULL DEFAULT 0,+ fiber REAL NOT NULL DEFAULT 0,+ servings REAL NOT NULL DEFAULT 1,+ serving_size TEXT NOT NULL DEFAULT '',+ barcode TEXT NOT NULL DEFAULT '',+ image_url TEXT NOT NULL DEFAULT '',+ logged_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP+);+CREATE TABLE IF NOT EXISTS saved_foods (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ brand TEXT NOT NULL DEFAULT '',+ calories REAL NOT NULL DEFAULT 0,+ protein REAL NOT NULL DEFAULT 0,+ carbs REAL NOT NULL DEFAULT 0,+ fat REAL NOT NULL DEFAULT 0,+ fiber REAL NOT NULL DEFAULT 0,+ serving_size TEXT NOT NULL DEFAULT '',+ barcode TEXT NOT NULL DEFAULT '',+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP);`_, err := db.DB.Exec(schema)return errdiff --git a/backend/db/migrations.go b/backend/db/migrations.goindex ffebe2f..7cf0843 100644--- a/backend/db/migrations.go+++ b/backend/db/migrations.go@@ -1,10 +1,51 @@package db+import "log"+func migrate() error {_, err := DB.Exec(schema)return err}+// alterMigrations adds columns/tables that postdate the initial schema.+// Each operation is idempotent: it checks before altering.+func alterMigrations() {+ rows, err := DB.Query("PRAGMA table_info(food_logs)")+ if err == nil {+ hasFiber, hasImageURL := false, false+ for rows.Next() {+ var cid int+ var name, typ string+ var notnull int+ var dflt interface{}+ var pk int+ if err := rows.Scan(&cid, &name, &typ, ¬null, &dflt, &pk); err != nil {+ log.Printf("migrations: scan error: %v", err)+ continue+ }+ if name == "fiber" {+ hasFiber = true+ }+ if name == "image_url" {+ hasImageURL = true+ }+ }+ rows.Close()+ if !hasFiber {+ if _, err := DB.Exec(`ALTER TABLE food_logs ADD COLUMN fiber REAL NOT NULL DEFAULT 0`); err != nil {+ log.Fatalf("alter food_logs add fiber: %v", err)+ }+ log.Println("migration: added food_logs.fiber")+ }+ if !hasImageURL {+ if _, err := DB.Exec(`ALTER TABLE food_logs ADD COLUMN image_url TEXT NOT NULL DEFAULT ''`); err != nil {+ log.Fatalf("alter food_logs add image_url: %v", err)+ }+ log.Println("migration: added food_logs.image_url")+ }+ }+}+const schema = `CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -98,6 +139,23 @@ CREATE TABLE IF NOT EXISTS food_logs (CREATE INDEX IF NOT EXISTS idx_food_logs_user ON food_logs(user_id, logged_at DESC);+CREATE TABLE IF NOT EXISTS saved_foods (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ brand TEXT NOT NULL DEFAULT '',+ calories REAL NOT NULL DEFAULT 0,+ protein REAL NOT NULL DEFAULT 0,+ carbs REAL NOT NULL DEFAULT 0,+ fat REAL NOT NULL DEFAULT 0,+ fiber REAL NOT NULL DEFAULT 0,+ serving_size TEXT NOT NULL DEFAULT '',+ barcode TEXT NOT NULL DEFAULT '',+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP+);++CREATE INDEX IF NOT EXISTS idx_saved_foods_user ON saved_foods(user_id);+CREATE TABLE IF NOT EXISTS active_sessions (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,diff --git a/backend/db/sqlite.go b/backend/db/sqlite.goindex edfd05b..2c0a390 100644--- a/backend/db/sqlite.go+++ b/backend/db/sqlite.go@@ -37,5 +37,7 @@ func Connect() {log.Fatalf("migration failed: %v", err)}+ alterMigrations()+log.Printf("SQLite database ready at %s", dbPath)}diff --git a/backend/models/models.go b/backend/models/models.goindex 137956c..45a5e4e 100644--- a/backend/models/models.go+++ b/backend/models/models.go@@ -82,13 +82,51 @@ type FoodLog struct {Protein float64 `json:"protein" db:"protein"`Carbs float64 `json:"carbs" db:"carbs"`Fat float64 `json:"fat" db:"fat"`+ Fiber float64 `json:"fiber" db:"fiber"`Servings float64 `json:"servings" db:"servings"`ServingSize string `json:"serving_size" db:"serving_size"`Barcode string `json:"barcode,omitempty" db:"barcode"`+ ImageURL string `json:"image_url,omitempty" db:"image_url"`LoggedAt time.Time `json:"logged_at" db:"logged_at"`CreatedAt time.Time `json:"created_at" db:"created_at"`}+type SavedFood struct {+ ID int64 `json:"id" db:"id"`+ UserID int64 `json:"user_id,omitempty" db:"user_id"`+ Name string `json:"name" db:"name"`+ Brand string `json:"brand" db:"brand"`+ Calories float64 `json:"calories" db:"calories"`+ Protein float64 `json:"protein" db:"protein"`+ Carbs float64 `json:"carbs" db:"carbs"`+ Fat float64 `json:"fat" db:"fat"`+ Fiber float64 `json:"fiber" db:"fiber"`+ ServingSize string `json:"serving_size" db:"serving_size"`+ Barcode string `json:"barcode,omitempty" db:"barcode"`+ CreatedAt time.Time `json:"created_at" db:"created_at"`+}++type FoodSearchResult struct {+ Name string `json:"name"`+ Brand string `json:"brand,omitempty"`+ Calories float64 `json:"calories"`+ Protein float64 `json:"protein"`+ Carbs float64 `json:"carbs"`+ Fat float64 `json:"fat"`+ Fiber float64 `json:"fiber"`+ ServingSize string `json:"serving_size"`+ ImageURL string `json:"image_url,omitempty"`+ Source string `json:"source"` // "off" | "saved"+}++type FoodHistoryPoint struct {+ Date string `json:"date"`+ Calories float64 `json:"calories"`+ Protein float64 `json:"protein"`+ Carbs float64 `json:"carbs"`+ Fat float64 `json:"fat"`+}+// Request/Response typestype RegisterRequest struct {@@ -149,12 +187,26 @@ type LogFoodRequest struct {Protein float64 `json:"protein" validate:"gte=0"`Carbs float64 `json:"carbs" validate:"gte=0"`Fat float64 `json:"fat" validate:"gte=0"`- Servings float64 `json:"servings" validate:"gt=0"`+ Fiber float64 `json:"fiber" validate:"gte=0"`+ Servings float64 `json:"servings" validate:"gte=0"`ServingSize string `json:"serving_size"`Barcode string `json:"barcode"`+ ImageURL string `json:"image_url"`LoggedAt time.Time `json:"logged_at"`}+type SaveFoodRequest struct {+ Name string `json:"name" validate:"required"`+ Brand string `json:"brand"`+ Calories float64 `json:"calories" validate:"gte=0"`+ Protein float64 `json:"protein" validate:"gte=0"`+ Carbs float64 `json:"carbs" validate:"gte=0"`+ Fat float64 `json:"fat" validate:"gte=0"`+ Fiber float64 `json:"fiber" validate:"gte=0"`+ ServingSize string `json:"serving_size"`+ Barcode string `json:"barcode"`+}+type UpdateSettingsRequest struct {WeightUnit string `json:"weight_unit" validate:"omitempty,oneof=lbs kg"`CalorieTarget int `json:"calorie_target" validate:"omitempty,gte=0"`@@ -214,5 +266,6 @@ type DailyStats struct {TotalProtein float64 `json:"total_protein"`TotalCarbs float64 `json:"total_carbs"`TotalFat float64 `json:"total_fat"`+ TotalFiber float64 `json:"total_fiber"`WorkoutCount int `json:"workout_count"`}diff --git a/backend/routes/routes.go b/backend/routes/routes.goindex d488bff..36214b6 100644--- a/backend/routes/routes.go+++ b/backend/routes/routes.go@@ -59,11 +59,19 @@ func Setup(r *gin.Engine) {protected.PATCH("weight/:id", controllers.UpdateWeightLog)protected.DELETE("weight/:id", controllers.DeleteWeightLog)- // Food+ // Food — named sub-paths must be registered before food/:idprotected.GET("food", controllers.ListFoodLogs)protected.POST("food", controllers.LogFood)- protected.DELETE("food/:id", controllers.DeleteFoodLog)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)// Exercises (read-only for users)protected.GET("exercises", controllers.ListExercises)diff --git a/scripts/seed_food.py b/scripts/seed_food.pynew file mode 100644index 0000000..08ae70b--- /dev/null+++ b/scripts/seed_food.py@@ -0,0 +1,90 @@+#!/usr/bin/env python3+"""Seed food logs for demo account via API. Run with: python scripts/seed_food.py"""++import json+import urllib.request+import urllib.error+from datetime import date, timedelta++BASE = "http://localhost:3000/api/v1"+EMAIL = "[email protected]"+PASSWORD = "password123"++MEAL_ROTATION = [+ [+ {"meal": "breakfast", "name": "Eggs, oats and banana", "calories": 520, "protein": 38, "carbs": 62, "fat": 12, "fiber": 6},+ {"meal": "lunch", "name": "Chicken breast with rice and broccoli", "calories": 640, "protein": 55, "carbs": 70, "fat": 8, "fiber": 5},+ {"meal": "dinner", "name": "Salmon with sweet potato and asparagus", "calories": 590, "protein": 48, "carbs": 48, "fat": 16, "fiber": 7},+ {"meal": "snacks", "name": "Greek yogurt and protein shake", "calories": 370, "protein": 52, "carbs": 28, "fat": 6, "fiber": 2},+ ],+ [+ {"meal": "breakfast", "name": "Protein oats with blueberries", "calories": 490, "protein": 35, "carbs": 65, "fat": 9, "fiber": 8},+ {"meal": "lunch", "name": "Turkey and avocado wrap", "calories": 610, "protein": 46, "carbs": 58, "fat": 18, "fiber": 6},+ {"meal": "dinner", "name": "Lean ground beef with pasta and marinara", "calories": 680, "protein": 52, "carbs": 72, "fat": 14, "fiber": 5},+ {"meal": "snacks", "name": "Cottage cheese and almonds", "calories": 330, "protein": 38, "carbs": 14, "fat": 16, "fiber": 2},+ ],+ [+ {"meal": "breakfast", "name": "Scrambled eggs with whole-wheat toast", "calories": 480, "protein": 34, "carbs": 48, "fat": 15, "fiber": 4},+ {"meal": "lunch", "name": "Tuna salad with quinoa", "calories": 570, "protein": 50, "carbs": 52, "fat": 12, "fiber": 5},+ {"meal": "dinner", "name": "Grilled chicken thighs with roasted veg", "calories": 620, "protein": 54, "carbs": 38, "fat": 22, "fiber": 8},+ {"meal": "snacks", "name": "Protein shake with banana", "calories": 340, "protein": 40, "carbs": 40, "fat": 4, "fiber": 3},+ ],+ [+ {"meal": "breakfast", "name": "Overnight oats with chia and honey", "calories": 510, "protein": 30, "carbs": 70, "fat": 11, "fiber": 9},+ {"meal": "lunch", "name": "Greek salad with grilled chicken", "calories": 520, "protein": 48, "carbs": 22, "fat": 20, "fiber": 4},+ {"meal": "dinner", "name": "Beef stir-fry with brown rice", "calories": 660, "protein": 50, "carbs": 68, "fat": 16, "fiber": 6},+ {"meal": "snacks", "name": "Rice cakes with peanut butter", "calories": 290, "protein": 10, "carbs": 38, "fat": 12, "fiber": 3},+ ],+ [+ {"meal": "breakfast", "name": "Smoothie bowl with granola", "calories": 460, "protein": 22, "carbs": 72, "fat": 8, "fiber": 7},+ {"meal": "lunch", "name": "Shrimp tacos with slaw", "calories": 580, "protein": 44, "carbs": 60, "fat": 14, "fiber": 5},+ {"meal": "dinner", "name": "Baked cod with mashed sweet potato", "calories": 550, "protein": 46, "carbs": 52, "fat": 10, "fiber": 6},+ {"meal": "snacks", "name": "Hard boiled eggs and apple", "calories": 250, "protein": 18, "carbs": 26, "fat": 10, "fiber": 4},+ ],+]+++def post(path, data, token=None):+ body = json.dumps(data).encode()+ headers = {"Content-Type": "application/json"}+ if token:+ headers["Authorization"] = f"Bearer {token}"+ req = urllib.request.Request(f"{BASE}{path}", data=body, headers=headers, method="POST")+ with urllib.request.urlopen(req) as r:+ return json.loads(r.read())+++def main():+ print(f"Logging in as {EMAIL}…")+ resp = post("/auth/login", {"email": EMAIL, "password": PASSWORD})+ token = resp["data"]["token"]+ print("Login OK")++ today = date.today()+ days = 60 # fill 60 days back+ logged = 0+ skipped = 0++ for offset in range(days, 0, -1):+ day = today - timedelta(days=offset)+ pattern = MEAL_ROTATION[offset % len(MEAL_ROTATION)]+ for meal in pattern:+ payload = {+ **meal,+ "servings": 1,+ "serving_size": "1 serving",+ "logged_at": f"{day.isoformat()}T12:00:00Z",+ }+ try:+ post("/food", payload, token=token)+ logged += 1+ except urllib.error.HTTPError as e:+ body = e.read().decode()+ print(f" SKIP {day} {meal['meal']}: {e.code} {body[:80]}")+ skipped += 1++ print(f"\nDone — {logged} entries logged, {skipped} skipped")+++if __name__ == "__main__":+ main()diff --git a/web/e2e/config.ts b/web/e2e/config.tsindex 004e009..278bc13 100644--- a/web/e2e/config.ts+++ b/web/e2e/config.ts@@ -22,6 +22,11 @@ function getBase(): string {const base = getBase()-export const API_BASE = process.env.API_URL ?? `${base}/api/v1`+// API_BASE is used by the Playwright `request` fixture (not the browser).+// Direct calls to :3000 bypass the Vite proxy and avoid its HTTPS self-signed cert.+// Docker mode keeps routing through the reverse proxy.+export const API_BASE = process.env.API_URL ?? (+ process.env.E2E_DOCKER ? `${base}/api/v1` : 'http://localhost:3000/api/v1'+)export const TEST_EMAIL = process.env.TEST_EMAIL ?? '[email protected]'export const TEST_PASSWORD = process.env.TEST_PASSWORD ?? 'password123'diff --git a/web/e2e/food.spec.ts b/web/e2e/food.spec.tsnew file mode 100644index 0000000..50ef940--- /dev/null+++ b/web/e2e/food.spec.ts@@ -0,0 +1,493 @@+import { test, expect } from '@playwright/test'+import { API_BASE as API, TEST_EMAIL, TEST_PASSWORD } from './config'++const SEED_PREFIX = 'E2EFood'+// Use local calendar date to match what todayStr() returns in the frontend.+const _now = new Date()+const _pad = (n: number) => String(n).padStart(2, '0')+const today = `${_now.getFullYear()}-${_pad(_now.getMonth() + 1)}-${_pad(_now.getDate())}`+// Local noon → UTC ISO, same anchor as dayToIsoNoon() in the app.+const todayNoon = new Date(_now.getFullYear(), _now.getMonth(), _now.getDate(), 12, 0, 0, 0).toISOString()++let authToken: string+let seedFoodIds: number[] = []+let seedSavedIds: number[] = []++test.describe('Food', () => {+ test.beforeAll(async ({ request }) => {+ const res = await request.post(`${API}/auth/login`, {+ data: { email: TEST_EMAIL, password: TEST_PASSWORD },+ })+ authToken = (await res.json()).data.token+ const h = { Authorization: `Bearer ${authToken}` }++ // Pre-cleanup: wipe ALL E2E-prefixed food log entries from the last 3 days+ // (covers timezone edge cases and accumulated state from multiple test runs).+ // Deletes are serial — bulk Promise.all against SQLite single-writer can+ // drop requests under load and leave entries behind.+ for (let d = 0; d < 3; d++) {+ const checkDate = new Date(_now)+ checkDate.setDate(_now.getDate() - d)+ const dateStr = `${checkDate.getFullYear()}-${_pad(checkDate.getMonth() + 1)}-${_pad(checkDate.getDate())}`+ const existing = await request.get(`${API}/food?date=${dateStr}`, { headers: h })+ const body = await existing.json()+ const toDelete = (body.data ?? []).filter((e: any) =>+ e.name.startsWith(SEED_PREFIX) ||+ e.name.startsWith('E2ELog-') ||+ e.name.startsWith('E2ESave-') ||+ e.name.startsWith('E2EEdit-')+ )+ for (const e of toDelete) {+ await request.delete(`${API}/food/${e.id}`, { headers: h })+ }+ }+ const existingSaved = await request.get(`${API}/food/saved`, { headers: h })+ const es = await existingSaved.json()+ const savedToDelete = (es.data ?? []).filter((s: any) =>+ s.name.startsWith(SEED_PREFIX) || s.name.startsWith('E2ESave-')+ )+ for (const s of savedToDelete) {+ await request.delete(`${API}/food/saved/${s.id}`, { headers: h })+ }++ // Seed one entry per meal so meal sections have data+ for (const [name, meal] of [+ [`${SEED_PREFIX}-breakfast`, 'breakfast'],+ [`${SEED_PREFIX}-lunch`, 'lunch'],+ [`${SEED_PREFIX}-snacks`, 'snacks'],+ ]) {+ const r = await request.post(`${API}/food`, {+ headers: h,+ data: { name, meal, calories: 300, protein: 20, carbs: 40, fat: 10, logged_at: todayNoon },+ })+ const rb = await r.json()+ if (rb.data?.id) seedFoodIds.push(rb.data.id)+ }++ // Seed a saved food+ const sf = await request.post(`${API}/food/saved`, {+ headers: h,+ data: { name: `${SEED_PREFIX}-saved`, calories: 200, protein: 15, carbs: 25, fat: 8, serving_size: '100g' },+ })+ const sfb = await sf.json()+ if (sfb.data?.id) seedSavedIds.push(sfb.data.id)+ })++ test.afterAll(async ({ request }) => {+ const h = { Authorization: `Bearer ${authToken}` }++ for (const id of seedFoodIds) {+ await request.delete(`${API}/food/${id}`, { headers: h })+ }+ for (const id of seedSavedIds) {+ await request.delete(`${API}/food/saved/${id}`, { headers: h })+ }++ // Clean up any UI-created entries+ const list = await request.get(`${API}/food?date=${today}`, { headers: h })+ const lb = await list.json()+ const toDelete = (lb.data ?? []).filter((e: any) =>+ e.name.startsWith('E2ELog-') || e.name.startsWith('E2ESave-') || e.name.startsWith('E2EEdit-')+ )+ for (const e of toDelete) {+ await request.delete(`${API}/food/${e.id}`, { headers: h })+ }++ // Clean up saved foods created via UI+ const sfList = await request.get(`${API}/food/saved`, { headers: h })+ const sfb = await sfList.json()+ const sfToDelete = (sfb.data ?? []).filter((s: any) => s.name.startsWith('E2ESave-'))+ for (const s of sfToDelete) {+ await request.delete(`${API}/food/saved/${s.id}`, { headers: h })+ }+ })++ test.beforeEach(async ({ page }) => {+ await page.goto('/food')+ })++ // ─── Food page ────────────────────────────────────────────────────────────++ test('renders Nutrition heading and all four meal sections', async ({ page }) => {+ await expect(page.getByRole('heading', { name: 'Nutrition' })).toBeVisible()+ for (const meal of ['Breakfast', 'Lunch', 'Dinner', 'Snacks']) {+ await expect(page.getByText(meal).first()).toBeVisible()+ }+ })++ test('shows Today label and seeded entries', async ({ page }) => {+ await expect(page.getByText('Today')).toBeVisible()+ await expect(page.getByText(`${SEED_PREFIX}-breakfast`).first()).toBeVisible()+ await expect(page.getByText(`${SEED_PREFIX}-lunch`).first()).toBeVisible()+ })++ test('macro summary card shows calorie and macro labels', async ({ page }) => {+ await expect(page.getByText('Calories')).toBeVisible()+ await expect(page.getByText('Protein').first()).toBeVisible()+ await expect(page.getByText('Carbs').first()).toBeVisible()+ await expect(page.getByText('Fat').first()).toBeVisible()+ })++ test('previous day button shows Yesterday, next returns to Today', async ({ page }) => {+ await expect(page.getByText('Today')).toBeVisible()+ await page.getByRole('button', { name: 'Previous day' }).click()+ await expect(page.getByText('Yesterday')).toBeVisible()+ await page.getByRole('button', { name: 'Next day' }).click()+ await expect(page.getByText('Today')).toBeVisible()+ })++ test('Next day button is disabled on today', async ({ page }) => {+ await expect(page.getByRole('button', { name: 'Next day' })).toBeDisabled()+ })++ test('seeded entries are absent on a previous date', async ({ page }) => {+ // Wait for today's data to fully load before navigating, avoiding a race+ // where the in-flight today-fetch overwrites yesterday's data after the click+ await expect(page.getByText(`${SEED_PREFIX}-breakfast`).first()).toBeVisible({ timeout: 8000 })+ await page.getByRole('button', { name: 'Previous day' }).click()+ await expect(page.getByText('Yesterday')).toBeVisible()+ await expect(page.getByText(`${SEED_PREFIX}-breakfast`).first()).not.toBeVisible()+ })++ test('Macro History section renders with period selector', async ({ page }) => {+ await expect(page.getByText('Macro History')).toBeVisible()+ for (const period of ['7d', '30d', '90d']) {+ await page.getByRole('button', { name: period, exact: true }).click()+ await page.waitForTimeout(300)+ await expect(page.getByRole('heading', { name: 'Nutrition' })).toBeVisible()+ }+ })++ test('history chart SVG renders with demo seed data', async ({ page }) => {+ // Demo user has 60 days of seed data — chart should render, not the empty state+ await expect(page.locator('.recharts-surface').first()).toBeVisible({ timeout: 10_000 })+ await expect(page.getByText('No data yet')).not.toBeVisible()+ })++ test('Log Food header button navigates to /food/log', async ({ page }) => {+ await page.getByRole('button', { name: /log food/i }).first().click()+ await expect(page).toHaveURL(/\/food\/log/)+ })++ // ─── Log food flow ─────────────────────────────────────────────────────────++ test('manual entry: log food and verify it appears in meal section', async ({ page }) => {+ const name = `E2ELog-${Date.now()}`++ await page.route('**/api/v1/food/search**', route =>+ route.fulfill({ json: { data: [] } })+ )+ await page.goto(`/food/log?meal=breakfast&date=${today}`)+ await expect(page.locator('input[placeholder="Search food…"]')).toBeVisible()++ // Typing auto-switches to the Search tab+ await page.fill('input[placeholder="Search food…"]', name)+ await expect(page.getByText(`No results for "${name}"`)).toBeVisible({ timeout: 2000 })++ // Click "Enter X manually"+ await page.getByRole('button').filter({ hasText: /manually/ }).click()++ // Detail phase — sticky Log Food button+ await expect(page.getByRole('button', { name: 'Log Food' })).toBeVisible()+ await page.getByRole('button', { name: 'Log Food' }).click()++ await page.waitForURL('/food', { timeout: 5000 })+ await expect(page.getByText(name)).toBeVisible()+ })++ test('quick-add: typing a number shows quick-add shortcut row', async ({ page }) => {+ await page.route('**/api/v1/food/search**', route =>+ route.fulfill({ json: { data: [] } })+ )+ await page.goto('/food/log')+ await page.fill('input[placeholder="Search food…"]', '500')+ await expect(page.getByText('Quick add 500 kcal')).toBeVisible()++ await page.getByText('Quick add 500 kcal').click()+ // Detail phase with 500 kcal+ await expect(page.getByRole('button', { name: 'Log Food' })).toBeVisible()+ await expect(page.getByText('500').first()).toBeVisible()+ })++ test('servings stepper scales macros in detail phase', async ({ page }) => {+ await page.route('**/api/v1/food/search**', route =>+ route.fulfill({+ json: {+ data: [{ name: 'Test Rice', calories: 200, protein: 4, carbs: 45, fat: 1, fiber: 1, serving_size: '1 cup', source: 'off' }],+ },+ })+ )+ await page.goto('/food/log')+ await page.fill('input[placeholder="Search food…"]', 'rice')+ await page.getByText('Test Rice').click()++ // Default 1 serving = 200 kcal shown+ await expect(page.getByText('200').first()).toBeVisible()++ // Stepper increments by 0.5 — click twice to reach 2 servings → 400 kcal+ await page.getByRole('button', { name: 'Increase servings' }).click()+ await page.getByRole('button', { name: 'Increase servings' }).click()+ await expect(page.getByText('400').first()).toBeVisible()+ })++ test('meal selector in detail phase updates active meal', async ({ page }) => {+ await page.route('**/api/v1/food/search**', route =>+ route.fulfill({ json: { data: [] } })+ )+ await page.goto('/food/log?meal=breakfast')+ await page.fill('input[placeholder="Search food…"]', 'test')+ await page.getByRole('button').filter({ hasText: /manually/ }).click()++ // Should start on breakfast+ const dinnerBtn = page.getByRole('button', { name: 'Dinner' })+ await dinnerBtn.click()+ await expect(dinnerBtn).toHaveClass(/bg-brand/)+ })++ // ─── Search ───────────────────────────────────────────────────────────────++ test('search results display from mocked API', async ({ page }) => {+ await page.route('**/api/v1/food/search**', route =>+ route.fulfill({+ json: {+ data: [{ name: 'Mocked Banana', calories: 89, protein: 1, carbs: 23, fat: 0, fiber: 3, serving_size: '1 medium', source: 'off' }],+ },+ })+ )+ await page.goto('/food/log')+ await page.fill('input[placeholder="Search food…"]', 'banana')+ await expect(page.getByText('Mocked Banana')).toBeVisible({ timeout: 2000 })+ })++ test('selecting a search result goes to detail phase', async ({ page }) => {+ await page.route('**/api/v1/food/search**', route =>+ route.fulfill({+ json: {+ data: [{ name: 'Test Apple', calories: 95, protein: 0, carbs: 25, fat: 0, fiber: 4, serving_size: '1 medium', source: 'off' }],+ },+ })+ )+ await page.goto('/food/log')+ await page.fill('input[placeholder="Search food…"]', 'apple')+ await page.getByText('Test Apple').click()++ await expect(page.getByRole('button', { name: 'Log Food' })).toBeVisible()+ await expect(page.getByText('95').first()).toBeVisible()+ })++ test('429 rate limit response shows amber warning banner', async ({ page }) => {+ await page.route('**/api/v1/food/search**', route =>+ route.fulfill({ status: 429, body: 'Too Many Requests' })+ )+ await page.goto('/food/log')+ await page.fill('input[placeholder="Search food…"]', 'pizza')+ await expect(page.getByText(/too many requests/i)).toBeVisible({ timeout: 2000 })+ })++ // ─── Edit food log ─────────────────────────────────────────────────────────++ test('edit mode: URL with edit= pre-fills food name and shows Save Changes', async ({ page }) => {+ const [firstId] = seedFoodIds+ await page.goto(`/food/log?edit=${firstId}`)++ await expect(page.getByRole('button', { name: 'Save Changes' })).toBeVisible({ timeout: 5000 })+ await expect(page.getByText(`${SEED_PREFIX}-breakfast`)).toBeVisible()+ })++ test('edit mode: saving returns to food page', async ({ page }) => {+ const h = { Authorization: `Bearer ${authToken}` }+ const r = await page.request.post(`${API}/food`, {+ headers: h,+ data: { name: `E2EEdit-${Date.now()}`, meal: 'dinner', calories: 200, protein: 10, carbs: 30, fat: 5, logged_at: todayNoon },+ })+ const { data } = await r.json()+ seedFoodIds.push(data.id)++ await page.goto(`/food/log?edit=${data.id}`)+ await expect(page.getByRole('button', { name: 'Save Changes' })).toBeVisible({ timeout: 5000 })+ await page.getByRole('button', { name: 'Save Changes' }).click()+ await page.waitForURL('/food', { timeout: 5000 })+ await expect(page.getByRole('heading', { name: 'Nutrition' })).toBeVisible()+ })++ // ─── Delete food log ───────────────────────────────────────────────────────++ test('delete: trash shows confirm dialog, cancel keeps entry', async ({ page }) => {+ await expect(page.getByText(`${SEED_PREFIX}-snacks`).first()).toBeVisible()++ // Scope to the per-entry wrapper div (.divide-y > div) that contains this name+ const entryRow = page.locator('.divide-y > div').filter({+ has: page.getByText(`${SEED_PREFIX}-snacks`, { exact: true }),+ }).last()+ await entryRow.getByRole('button', { name: 'Delete' }).click()++ await expect(page.locator('button.btn-danger-solid')).toBeVisible()+ await expect(page.getByRole('button', { name: 'Cancel' })).toBeVisible()++ await page.getByRole('button', { name: 'Cancel' }).click()+ await expect(page.getByText(`${SEED_PREFIX}-snacks`).first()).toBeVisible()+ })++ test('delete: confirm removes entry from list', async ({ page }) => {+ const h = { Authorization: `Bearer ${authToken}` }+ const r = await page.request.post(`${API}/food`, {+ headers: h,+ data: { name: `E2ELog-del-${Date.now()}`, meal: 'snacks', calories: 100, protein: 5, carbs: 15, fat: 3, logged_at: todayNoon },+ })+ const { data } = await r.json()+ const deleteName = data.name+ // Don't push to seedFoodIds — UI deletion is the test++ await page.reload()+ await expect(page.getByText(deleteName)).toBeVisible({ timeout: 5000 })++ const entryRow = page.locator('.divide-y > div').filter({+ has: page.getByText(deleteName, { exact: true }),+ }).first()+ await entryRow.getByRole('button', { name: 'Delete' }).click()+ await page.locator('button.btn-danger-solid').click()++ await expect(page.getByText(deleteName)).not.toBeVisible({ timeout: 3000 })+ })++ // ─── My Foods ─────────────────────────────────────────────────────────────++ test('My Foods tab shows seeded saved food', async ({ page }) => {+ await page.goto('/food/log')+ await page.getByRole('button', { name: 'My Foods' }).click()+ await expect(page.getByText(`${SEED_PREFIX}-saved`).first()).toBeVisible({ timeout: 3000 })+ })++ test('Save to My Foods toggle saves food during logging', async ({ page }) => {+ const savedName = `E2ESave-${Date.now()}`++ await page.route('**/api/v1/food/search**', route =>+ route.fulfill({ json: { data: [] } })+ )+ await page.goto('/food/log')+ await page.fill('input[placeholder="Search food…"]', savedName)+ await expect(page.getByText(`No results for "${savedName}"`)).toBeVisible({ timeout: 2000 })+ await page.getByRole('button').filter({ hasText: /manually/ }).click()++ // Toggle "Save to My Foods"+ await page.getByText('Save to My Foods').click()++ await page.getByRole('button', { name: 'Log Food' }).click()+ await page.waitForURL('/food', { timeout: 5000 })++ // Verify in My Foods tab+ await page.goto('/food/log')+ await page.getByRole('button', { name: 'My Foods' }).click()+ await expect(page.getByText(savedName)).toBeVisible({ timeout: 8000 })+ })++ test('selecting from My Foods goes to detail phase', async ({ page }) => {+ await page.goto('/food/log')+ await page.getByRole('button', { name: 'My Foods' }).click()+ await expect(page.getByText(`${SEED_PREFIX}-saved`).first()).toBeVisible({ timeout: 3000 })+ await page.getByText(`${SEED_PREFIX}-saved`).first().click()++ await expect(page.getByRole('button', { name: 'Log Food' })).toBeVisible()+ })++ // ─── Barcode scanner ──────────────────────────────────────────────────────++ test('Scan button renders scan phase overlay with close button', async ({ page }) => {+ test.slow()+ await page.goto('/food/log')+ await page.getByRole('button', { name: /scan/i }).click()+ await expect(page.getByRole('button', { name: 'Close scanner' })).toBeVisible({ timeout: 3000 })+ })++ test('Close scanner button returns to search phase', async ({ page }) => {+ await page.goto('/food/log')+ await page.getByRole('button', { name: /scan/i }).click()+ await page.getByRole('button', { name: 'Close scanner' }).click()+ await expect(page.locator('input[placeholder="Search food…"]')).toBeVisible()+ })++ test('barcode API returns 404 for unknown barcode', async ({ page }) => {+ const h = { Authorization: `Bearer ${authToken}` }+ const r = await page.request.get(`${API}/food/barcode/000000000000`, { headers: h })+ expect([404, 429, 503]).toContain(r.status())+ })++ test('barcode API returns product data for known barcode', async ({ page }) => {+ // 051500255186 is Jif Creamy Peanut Butter — seeded via seed script+ const h = { Authorization: `Bearer ${authToken}` }+ const r = await page.request.get(`${API}/food/barcode/051500255186`, { headers: h })+ // May be 200 (product in OFF), 503 (OFF unreachable), 404 or 429 (rate-limited)+ expect([200, 503, 404, 429]).toContain(r.status())+ })++ // ─── Backend endpoints ─────────────────────────────────────────────────────++ test('GET /food/search returns results for a common query', async ({ page }) => {+ const h = { Authorization: `Bearer ${authToken}` }+ const r = await page.request.get(`${API}/food/search?q=apple`, { headers: h })+ // May be 200 (OFF reachable) or 503 (unreachable) — not 4xx+ expect([200, 503]).toContain(r.status())+ })++ test('GET /food/history returns array of date-grouped entries', async ({ page }) => {+ const h = { Authorization: `Bearer ${authToken}` }+ const r = await page.request.get(`${API}/food/history?days=7`, { headers: h })+ expect(r.status()).toBe(200)+ const body = await r.json()+ expect(Array.isArray(body.data)).toBe(true)+ if (body.data.length > 0) {+ expect(body.data[0]).toHaveProperty('date')+ expect(body.data[0]).toHaveProperty('calories')+ }+ })++ test('GET /food/saved returns user saved foods', async ({ page }) => {+ const h = { Authorization: `Bearer ${authToken}` }+ const r = await page.request.get(`${API}/food/saved`, { headers: h })+ expect(r.status()).toBe(200)+ const body = await r.json()+ expect(Array.isArray(body.data)).toBe(true)+ const found = body.data.find((s: any) => s.name === `${SEED_PREFIX}-saved`)+ expect(found).toBeTruthy()+ })++ test('PATCH /food/:id updates food log', async ({ page }) => {+ const h = { Authorization: `Bearer ${authToken}` }+ const [firstId] = seedFoodIds+ const r = await page.request.patch(`${API}/food/${firstId}`, {+ headers: h,+ data: { name: `${SEED_PREFIX}-breakfast`, meal: 'breakfast', calories: 350, protein: 22, carbs: 44, fat: 11, servings: 1, logged_at: todayNoon },+ })+ expect(r.status()).toBe(200)+ const body = await r.json()+ expect(body.data.calories).toBe(350)+ })++ test('GET /food/:id returns ownership-scoped entry', async ({ page }) => {+ const h = { Authorization: `Bearer ${authToken}` }+ const [firstId] = seedFoodIds+ const r = await page.request.get(`${API}/food/${firstId}`, { headers: h })+ expect(r.status()).toBe(200)+ const body = await r.json()+ expect(body.data.name).toBe(`${SEED_PREFIX}-breakfast`)+ })++ test('GET /food?date= returns entries for the specified date', async ({ page }) => {+ const h = { Authorization: `Bearer ${authToken}` }+ const r = await page.request.get(`${API}/food?date=${today}`, { headers: h })+ expect(r.status()).toBe(200)+ const body = await r.json()+ const seeded = body.data.filter((e: any) => e.name.startsWith(SEED_PREFIX))+ expect(seeded.length).toBeGreaterThanOrEqual(3)+ })++ test('GET /food/stats returns calorie and macro totals', async ({ page }) => {+ const h = { Authorization: `Bearer ${authToken}` }+ const r = await page.request.get(`${API}/food/stats?date=${today}`, { headers: h })+ expect(r.status()).toBe(200)+ const body = await r.json()+ expect(body.data).toHaveProperty('total_calories')+ expect(body.data).toHaveProperty('total_protein')+ expect(body.data.total_calories).toBeGreaterThan(0)+ })+})diff --git a/web/e2e/programs.spec.ts b/web/e2e/programs.spec.tsindex 2d17f74..0ff96e3 100644--- a/web/e2e/programs.spec.ts+++ b/web/e2e/programs.spec.ts@@ -15,28 +15,40 @@ test.describe('Programs', () => {})const body = await res.json()authToken = body.data.token+ const headers = { Authorization: `Bearer ${authToken}` }- const p = await request.post(`${API}/programs`, {- headers: { Authorization: `Bearer ${authToken}` },- data: {- name: SEED_PROGRAM_NAME,- notes: 'Created by E2E seed',- exercises: []- }- })- const pb = await p.json()- programId = pb.data.id-- const sp = await request.post(`${API}/programs`, {- headers: { Authorization: `Bearer ${authToken}` },- data: {- name: SEED_SEARCH_PROGRAM_NAME,- notes: 'Created by E2E seed for search',- exercises: []+ // Pre-clean any accumulated seed programs from prior runs so the search+ // and list assertions don't see duplicates. Serial deletes — bulk+ // Promise.all races against SQLite's single-writer.+ const existing = await request.get(`${API}/programs`, { headers })+ const eb = await existing.json()+ const stale = (eb.data ?? []).filter((p: any) =>+ p.name === SEED_PROGRAM_NAME ||+ p.name === SEED_SEARCH_PROGRAM_NAME ||+ p.name === E2E_PROGRAM_NAME+ )+ for (const p of stale) {+ await request.delete(`${API}/programs/${p.id}`, { headers })+ }++ // Retry create on transient backend failure (e.g. SQLite busy under+ // concurrent worker load). spb.data is undefined when backend returned+ // an error envelope instead of the created row.+ const createSeed = async (name: string, notes: string): Promise<number> => {+ for (let attempt = 0; attempt < 3; attempt++) {+ const r = await request.post(`${API}/programs`, {+ headers,+ data: { name, notes, exercises: [] },+ })+ const rb = await r.json()+ if (rb.data?.id) return rb.data.id+ await new Promise(res => setTimeout(res, 200 * (attempt + 1)))}- })- const spb = await sp.json()- searchProgramId = spb.data.id+ throw new Error(`Failed to create seed program "${name}" after 3 attempts`)+ }++ programId = await createSeed(SEED_PROGRAM_NAME, 'Created by E2E seed')+ searchProgramId = await createSeed(SEED_SEARCH_PROGRAM_NAME, 'Created by E2E seed for search')})test.afterAll(async ({ request }) => {@@ -50,13 +62,14 @@ test.describe('Programs', () => {await request.delete(`${API}/programs/${searchProgramId}`, { headers })}- // Delete any UI-created E2E programs+ // Delete any UI-created E2E programs (serial — bulk Promise.all races+ // against SQLite's single-writer and silently drops requests).const list = await request.get(`${API}/programs`, { headers })const lb = await list.json()const toDelete = (lb.data ?? []).filter((p: any) => p.name === E2E_PROGRAM_NAME)- await Promise.all(toDelete.map((p: any) =>- request.delete(`${API}/programs/${p.id}`, { headers })- ))+ for (const p of toDelete) {+ await request.delete(`${API}/programs/${p.id}`, { headers })+ }})test.beforeEach(async ({ page }) => {diff --git a/web/e2e/weight.spec.ts b/web/e2e/weight.spec.tsindex aa079fd..d9b2ac8 100644--- a/web/e2e/weight.spec.ts+++ b/web/e2e/weight.spec.ts@@ -36,13 +36,14 @@ test.describe('Weight', () => {await request.delete(`${API}/weight/${id}`, { headers })}- // Clean up any entries the form-submit test created+ // Clean up any entries the form-submit test created (serial — SQLite+ // single-writer drops bulk Promise.all requests under load).const list = await request.get(`${API}/weight?limit=100`, { headers })const lb = await list.json()const toDelete = (lb.data ?? []).filter((w: any) => w.notes === FORM_WEIGHT_NOTE)- await Promise.all(toDelete.map((w: any) =>- request.delete(`${API}/weight/${w.id}`, { headers })- ))+ for (const w of toDelete) {+ await request.delete(`${API}/weight/${w.id}`, { headers })+ }})test.beforeEach(async ({ page }) => {diff --git a/web/e2e/workouts.spec.ts b/web/e2e/workouts.spec.tsindex 9d75bf8..fc17b77 100644--- a/web/e2e/workouts.spec.ts+++ b/web/e2e/workouts.spec.ts@@ -54,13 +54,14 @@ test.describe('Workouts', () => {await request.delete(`${API}/workouts/${searchWorkoutId}`, { headers })}- // Delete any UI-created E2E workouts+ // Delete any UI-created E2E workouts (serial — SQLite single-writer+ // drops bulk Promise.all requests under load).const list = await request.get(`${API}/workouts?limit=100`, { headers })const lb = await list.json()const toDelete = (lb.data ?? []).filter((w: any) => w.name === E2E_WORKOUT_NAME)- await Promise.all(toDelete.map((w: any) =>- request.delete(`${API}/workouts/${w.id}`, { headers })- ))+ for (const w of toDelete) {+ await request.delete(`${API}/workouts/${w.id}`, { headers })+ }})test.beforeEach(async ({ page }) => {diff --git a/web/package-lock.json b/web/package-lock.jsonindex bddccfc..cee8075 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -17,6 +17,7 @@"react-body-highlighter": "^2.0.5","react-dom": "^18.2.0","react-router-dom": "^6.22.0",+ "react-zxing": "^2.1.0","recharts": "^2.10.3","zustand": "^4.4.6"},@@ -26,6 +27,7 @@"@types/react-dom": "^18.2.17","@typescript-eslint/eslint-plugin": "^6.14.0","@typescript-eslint/parser": "^6.14.0",+ "@vitejs/plugin-basic-ssl": "^1.2.0","@vitejs/plugin-react": "^4.2.1","autoprefixer": "^10.4.16","cross-env": "^10.1.0",@@ -1668,6 +1670,18 @@"integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==","dev": true},+ "node_modules/@vitejs/plugin-basic-ssl": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-basic-ssl/-/plugin-basic-ssl-1.2.0.tgz",+ "integrity": "sha512-mkQnxTkcldAzIsomk1UuLfAu9n+kpQ3JbHcpCp7d2Oo6ITtji8pHS3QToOWjhPFvNQSnhlkAjmGbhv2QvwO/7Q==",+ "dev": true,+ "engines": {+ "node": ">=14.21.3"+ },+ "peerDependencies": {+ "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0"+ }+ },"node_modules/@vitejs/plugin-react": {"version": "4.7.0","resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",@@ -1688,6 +1702,26 @@"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"}},+ "node_modules/@zxing/library": {+ "version": "0.20.0",+ "resolved": "https://registry.npmjs.org/@zxing/library/-/library-0.20.0.tgz",+ "integrity": "sha512-6Ev6rcqVjMakZFIDvbUf0dtpPGeZMTfyxYg4HkVWioWeN7cRcnUWT3bU6sdohc82O1nPXcjq6WiGfXX2Pnit6A==",+ "dependencies": {+ "ts-custom-error": "^3.2.1"+ },+ "engines": {+ "node": ">= 10.4.0"+ },+ "optionalDependencies": {+ "@zxing/text-encoding": "~0.9.0"+ }+ },+ "node_modules/@zxing/text-encoding": {+ "version": "0.9.0",+ "resolved": "https://registry.npmjs.org/@zxing/text-encoding/-/text-encoding-0.9.0.tgz",+ "integrity": "sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==",+ "optional": true+ },"node_modules/acorn": {"version": "8.16.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",@@ -3980,6 +4014,21 @@"react-dom": ">=16.6.0"}},+ "node_modules/react-zxing": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/react-zxing/-/react-zxing-2.1.0.tgz",+ "integrity": "sha512-iFZ8KPfZl+biiT5/bluuMGaSLQAwnE0ialQHbJioHFuwqhCo1WmjQmAtI4WN8BmiKYFVkHGgwHSl+pgwpwtQEg==",+ "dependencies": {+ "@zxing/library": "^0.20.0"+ },+ "engines": {+ "node": "^18 || ^20 || ^22",+ "yarn": "^1.22"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/read-cache": {"version": "1.0.0","resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",@@ -4421,6 +4470,14 @@"typescript": ">=4.2.0"}},+ "node_modules/ts-custom-error": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.3.1.tgz",+ "integrity": "sha512-5OX1tzOjxWEgsr/YEUWSuPrQ00deKLh6D7OTWcvNHm12/7QPyRh8SYpyWvA4IZv8H/+GQWQEh/kwo95Q9OVW1A==",+ "engines": {+ "node": ">=14.0.0"+ }+ },"node_modules/ts-interface-checker": {"version": "0.1.13","resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz",diff --git a/web/package.json b/web/package.jsonindex ef89c47..898ff45 100644--- a/web/package.json+++ b/web/package.json@@ -23,6 +23,7 @@"react-body-highlighter": "^2.0.5","react-dom": "^18.2.0","react-router-dom": "^6.22.0",+ "react-zxing": "^2.1.0","recharts": "^2.10.3","zustand": "^4.4.6"},@@ -32,6 +33,7 @@"@types/react-dom": "^18.2.17","@typescript-eslint/eslint-plugin": "^6.14.0","@typescript-eslint/parser": "^6.14.0",+ "@vitejs/plugin-basic-ssl": "^1.2.0","@vitejs/plugin-react": "^4.2.1","autoprefixer": "^10.4.16","cross-env": "^10.1.0",diff --git a/web/playwright.config.ts b/web/playwright.config.tsindex 4458202..dbbd406 100644--- a/web/playwright.config.ts+++ b/web/playwright.config.ts@@ -16,17 +16,23 @@ function dockerBaseURL(): string {}const baseURL = process.env.BASE_URL- ?? (process.env.E2E_DOCKER ? dockerBaseURL() : 'http://localhost:5173')+ ?? (process.env.E2E_DOCKER ? dockerBaseURL() : 'https://localhost:5173')export default defineConfig({testDir: './e2e',fullyParallel: false,forbidOnly: !!process.env.CI,retries: process.env.CI ? 1 : 0,+ // Single worker. Each spec file is run twice (chromium + mobile projects)+ // and shares one demo user, so two workers running the same spec across+ // projects race on cleanup — both `beforeAll` hooks run their pre-clean,+ // and the second worker wipes the first's seeded rows mid-test.+ // Per-worker namespacing would unblock workers > 1; deferred for now.workers: 1,reporter: 'list',use: {baseURL,+ ignoreHTTPSErrors: true,trace: 'on-first-retry',screenshot: 'only-on-failure',},diff --git a/web/src/App.tsx b/web/src/App.tsxindex 467a3e8..06af503 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -17,6 +17,7 @@ import EditWorkout from './pages/EditWorkout'import WorkoutDetail from './pages/WorkoutDetail'import ProgramDetail from './pages/ProgramDetail'import Food from './pages/Food'+import LogFood from './pages/LogFood'import Weight from './pages/Weight'import WeightDetail from './pages/WeightDetail'import Settings from './pages/Settings'@@ -60,6 +61,7 @@ function App() {<Route path="/workout/active/exercise/:exerciseId" element={<ExerciseDetail />} /><Route path="/exercises/:exerciseId" element={<ExerciseDetail />} /><Route path="/food" element={<Food />} />+ <Route path="/food/log" element={<LogFood />} /><Route path="/weight" element={<Weight />} /><Route path="/weight/:id" element={<WeightDetail />} /><Route path="/settings" element={<Settings />} />diff --git a/web/src/components/BarcodeScanner.tsx b/web/src/components/BarcodeScanner.tsxnew file mode 100644index 0000000..25654bd--- /dev/null+++ b/web/src/components/BarcodeScanner.tsx@@ -0,0 +1,105 @@+import React, { useEffect, useRef, useState } from 'react'+import { createPortal } from 'react-dom'+import { useZxing } from 'react-zxing'+import { X, AlertCircle } from 'lucide-react'++interface Props {+ onResult: (code: string) => void+ onClose: () => void+}++export default function BarcodeScanner({ onResult, onClose }: Props) {+ const resolvedRef = useRef(false)+ const [cameraError, setCameraError] = useState<string | null>(null)++ const { ref } = useZxing({+ constraints: {+ audio: false,+ video: { facingMode: 'environment' },+ },+ timeBetweenDecodingAttempts: 150,+ onDecodeResult(result) {+ if (resolvedRef.current) return+ resolvedRef.current = true+ navigator.vibrate?.(100)+ onResult(result.getText())+ },+ onError(err) {+ const msg = (err as any)?.message ?? String(err)+ // ZXing fires NotFoundException on every frame with no barcode — ignore those+ if (!msg.includes('NotFoundException') && !msg.includes('No MultiFormat')) {+ setCameraError(msg)+ }+ },+ })++ useEffect(() => {+ const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [onClose])++ return createPortal(+ <div className="fixed inset-0 z-50 bg-black/95 flex flex-col">+ <div className="flex items-center justify-between p-4">+ <p className="text-white text-sm font-medium">Scan barcode</p>+ <button+ onClick={onClose}+ className="p-2 rounded-lg hover:bg-white/10 transition-colors"+ aria-label="Close scanner"+ >+ <X className="w-5 h-5 text-white" />+ </button>+ </div>++ <div className="flex-1 flex items-center justify-center relative">+ {!cameraError && (+ <video+ // react-zxing ref type doesn't match HTMLVideoElement exactly; cast is safe as useZxing always returns a video ref+ ref={ref as React.RefObject<HTMLVideoElement>}+ className="w-full max-w-sm rounded-lg"+ style={{ maxHeight: '60vh', objectFit: 'cover' }}+ playsInline+ />+ )}++ {!cameraError && (+ <div className="absolute pointer-events-none" style={{ width: 260, height: 160 }}>+ <div className="absolute top-0 left-0 w-8 h-8 border-t-2 border-l-2 border-brand-400 rounded-tl" />+ <div className="absolute top-0 right-0 w-8 h-8 border-t-2 border-r-2 border-brand-400 rounded-tr" />+ <div className="absolute bottom-0 left-0 w-8 h-8 border-b-2 border-l-2 border-brand-400 rounded-bl" />+ <div className="absolute bottom-0 right-0 w-8 h-8 border-b-2 border-r-2 border-brand-400 rounded-br" />+ <div+ className="absolute inset-x-0 h-0.5 bg-brand-400/70"+ style={{ animation: 'barcode-scan 1.5s ease-in-out infinite' }}+ />+ </div>+ )}+ </div>++ {cameraError ? (+ <div className="flex flex-col items-center gap-3 px-6 pb-10 text-center">+ <AlertCircle className="w-8 h-8 text-error-400" />+ <p className="text-white text-sm font-medium">Camera unavailable</p>+ <p className="text-white/50 text-xs font-mono break-all">{cameraError}</p>+ <button onClick={onClose} className="btn-primary btn-sm mt-2">+ Search by name instead+ </button>+ </div>+ ) : (+ <p className="text-center text-white/60 text-xs pb-8 px-4">+ Point camera at barcode — it will scan automatically+ </p>+ )}++ <style>{`+ @keyframes barcode-scan {+ 0% { top: 10%; }+ 50% { top: 85%; }+ 100% { top: 10%; }+ }+ `}</style>+ </div>,+ document.body,+ )+}diff --git a/web/src/components/FoodLogModal.tsx b/web/src/components/FoodLogModal.tsxnew file mode 100644index 0000000..ed05484--- /dev/null+++ b/web/src/components/FoodLogModal.tsx@@ -0,0 +1,568 @@+import { useState, useEffect, useRef } from 'react'+import { createPortal } from 'react-dom'+import {+ X, Search, Scan, ChevronLeft, Minus, Plus,+ Bookmark, BookmarkCheck, AlertCircle, Utensils, Zap,+} from 'lucide-react'+import { foodAPI, savedFoodsAPI } from '../services/api'+import { useBodyScrollLock } from '../hooks/useBodyScrollLock'+import { useEscapeKey } from '../hooks/useEscapeKey'+import { todayStr, dayToIsoNoon, isoToDayInput } from '../utils/dateUtils'+import BarcodeScanner from './BarcodeScanner'+import * as types from '../types'++interface Props {+ open: boolean+ onClose: () => void+ onLogged: (entry: types.FoodLog) => void+ defaultMeal?: types.FoodLog['meal']+ editEntry?: types.FoodLog+ defaultDate?: string+}++type Phase = 'search' | 'detail' | 'scan'+type SearchTab = 'recent' | 'myfoods' | 'all'++const MEALS = ['breakfast', 'lunch', 'dinner', 'snacks'] as const+const MEAL_LABELS: Record<string, string> = {+ breakfast: 'Breakfast', lunch: 'Lunch', dinner: 'Dinner', snacks: 'Snacks',+}++function entryToResult(e: types.FoodLog): types.FoodSearchResult {+ const s = e.servings || 1+ return {+ name: e.name,+ calories: e.calories / s,+ protein: e.protein / s,+ carbs: e.carbs / s,+ fat: e.fat / s,+ fiber: (e.fiber ?? 0) / s,+ serving_size: e.serving_size ?? '',+ source: 'saved',+ }+}++function savedToResult(s: types.SavedFood): types.FoodSearchResult {+ return {+ name: s.name,+ brand: s.brand,+ calories: s.calories,+ protein: s.protein,+ carbs: s.carbs,+ fat: s.fat,+ fiber: s.fiber,+ serving_size: s.serving_size,+ source: 'saved',+ }+}++export default function FoodLogModal({+ open, onClose, onLogged, defaultMeal = 'breakfast', editEntry, defaultDate,+}: Props) {+ const [phase, setPhase] = useState<Phase>(editEntry ? 'detail' : 'search')+ const [tab, setTab] = useState<SearchTab>('recent')+ const [query, setQuery] = useState('')+ const [searchResults, setSearchResults] = useState<types.FoodSearchResult[]>([])+ const [recentItems, setRecentItems] = useState<types.FoodSearchResult[]>([])+ const [savedFoods, setSavedFoods] = useState<types.SavedFood[]>([])+ const [searching, setSearching] = useState(false)+ const [searchError, setSearchError] = useState<string | null>(null)+ const [rateLimited, setRateLimited] = useState(false)++ const [selected, setSelected] = useState<types.FoodSearchResult | null>(null)+ const [servings, setServings] = useState(1)+ const [meal, setMeal] = useState<types.FoodLog['meal']>(defaultMeal)+ const [date, setDate] = useState(defaultDate ?? todayStr())+ const [saveToMyFoods, setSaveToMyFoods] = useState(false)+ const [saving, setSaving] = useState(false)+ const [saveError, setSaveError] = useState<string | null>(null)++ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)++ useBodyScrollLock(open)+ useEscapeKey(open, onClose)++ useEffect(() => {+ if (!open) return+ if (editEntry) {+ setPhase('detail')+ setSelected(entryToResult(editEntry))+ setServings(editEntry.servings)+ setMeal(editEntry.meal)+ setDate(isoToDayInput(editEntry.logged_at))+ } else {+ setPhase('search')+ setQuery('')+ setSearchResults([])+ setSearchError(null)+ setRateLimited(false)+ setTab('recent')+ }+ setSaving(false)+ setSaveError(null)+ setSaveToMyFoods(false)+ }, [open, editEntry])++ useEffect(() => {+ if (!open || phase !== 'search') return+ foodAPI.list(todayStr()).then(logs => {+ const seen = new Set<string>()+ const items: types.FoodSearchResult[] = []+ for (const log of (logs || [])) {+ const key = log.name.toLowerCase()+ if (!seen.has(key)) {+ seen.add(key)+ items.push(entryToResult(log))+ if (items.length >= 10) break+ }+ }+ setRecentItems(items)+ }).catch(() => {})+ savedFoodsAPI.list().then(setSavedFoods).catch(() => {})+ }, [open, phase])++ useEffect(() => {+ if (tab !== 'all') return+ if (debounceRef.current) clearTimeout(debounceRef.current)+ if (!query.trim()) { setSearchResults([]); return }+ debounceRef.current = setTimeout(async () => {+ setSearching(true)+ setSearchError(null)+ setRateLimited(false)+ try {+ const results = await foodAPI.search(query.trim())+ setSearchResults(results ?? [])+ } catch (err: any) {+ if (err?.response?.status === 429) {+ setRateLimited(true)+ } else {+ setSearchError('Food search unavailable — enter details manually')+ }+ setSearchResults([])+ } finally {+ setSearching(false)+ }+ }, 300)+ return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }+ }, [query, tab])++ const selectResult = (result: types.FoodSearchResult) => {+ setSelected(result)+ setServings(1)+ setPhase('detail')+ }++ const handleBarcodeResult = async (code: string) => {+ setPhase('search')+ try {+ const result = await foodAPI.barcode(code)+ setSelected(result)+ setServings(1)+ setPhase('detail')+ } catch (err: any) {+ if (err?.response?.status === 404) {+ setSelected({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'off' })+ setServings(1)+ setPhase('detail')+ } else {+ setSearchError('Product not found — enter details manually')+ }+ }+ }++ const handleLog = async () => {+ if (!selected || saving) return+ setSaving(true)+ setSaveError(null)+ try {+ const payload = {+ name: selected.name || 'Custom entry',+ meal,+ calories: +(selected.calories * servings).toFixed(1),+ protein: +(selected.protein * servings).toFixed(1),+ carbs: +(selected.carbs * servings).toFixed(1),+ fat: +(selected.fat * servings).toFixed(1),+ fiber: +((selected.fiber ?? 0) * servings).toFixed(1),+ servings,+ serving_size: selected.serving_size ?? '',+ logged_at: dayToIsoNoon(date),+ }+ const entry = editEntry+ ? await foodAPI.update(editEntry.id, payload)+ : await foodAPI.log(payload)++ if (saveToMyFoods && !editEntry) {+ savedFoodsAPI.create({+ name: selected.name,+ brand: selected.brand ?? '',+ calories: selected.calories,+ protein: selected.protein,+ carbs: selected.carbs,+ fat: selected.fat,+ fiber: selected.fiber ?? 0,+ serving_size: selected.serving_size ?? '',+ }).catch(() => {})+ }++ onLogged(entry)+ onClose()+ } catch (err: any) {+ setSaveError(err?.response?.data?.error || 'Failed to save')+ setSaving(false)+ }+ }++ if (!open) return null++ const cal = selected ? Math.round(selected.calories * servings) : 0+ const pro = selected ? +(selected.protein * servings).toFixed(1) : 0+ const carb = selected ? +(selected.carbs * servings).toFixed(1) : 0+ const fat_ = selected ? +(selected.fat * servings).toFixed(1) : 0+ const fib = selected ? +((selected.fiber ?? 0) * servings).toFixed(1) : 0++ const quickAddCals = /^\d+(\.\d+)?$/.test(query.trim()) ? Number(query.trim()) : null++ return createPortal(+ <>+ {phase === 'scan' && (+ <BarcodeScanner+ onResult={handleBarcodeResult}+ onClose={() => setPhase('search')}+ />+ )}++ {phase !== 'scan' && (+ <div+ className="fixed inset-0 bg-black/60 z-[60] flex items-end sm:items-center justify-center"+ onClick={onClose}+ >+ <div+ role="dialog"+ aria-modal="true"+ className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-lg max-h-[90vh] flex flex-col overflow-hidden animate-slide-up"+ onClick={e => e.stopPropagation()}+ >+ <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mt-3 mb-1 sm:hidden flex-shrink-0" />++ {phase === 'search' && (+ <>+ <div className="flex items-center gap-2 px-4 pt-3 pb-3 border-b border-surface-border flex-shrink-0">+ <div className="flex-1 relative">+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-tx-muted pointer-events-none" />+ <input+ autoFocus+ type="text"+ value={query}+ onChange={e => {+ setQuery(e.target.value)+ if (e.target.value.trim()) setTab('all')+ }}+ placeholder="Search food…"+ className="input pl-9 pr-8 w-full"+ />+ {query && (+ <button+ onClick={() => setQuery('')}+ className="absolute right-2.5 top-1/2 -translate-y-1/2 text-tx-muted hover:text-tx-primary transition-colors"+ >+ <X className="w-4 h-4" />+ </button>+ )}+ </div>+ <button+ onClick={() => setPhase('scan')}+ className="p-2 rounded-lg bg-surface-muted hover:bg-surface-overlay border border-surface-border text-tx-secondary hover:text-tx-primary transition-colors flex-shrink-0"+ aria-label="Scan barcode"+ >+ <Scan className="w-5 h-5" />+ </button>+ <button+ onClick={onClose}+ className="p-2 rounded-lg hover:bg-surface-muted text-tx-muted transition-colors flex-shrink-0"+ >+ <X className="w-5 h-5" />+ </button>+ </div>++ <div className="flex gap-1 px-4 py-2 bg-surface-overlay border-b border-surface-border flex-shrink-0">+ {(['recent', 'myfoods', 'all'] as const).map(t => (+ <button+ key={t}+ onClick={() => setTab(t)}+ className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors duration-150 ${+ tab === t+ ? 'bg-surface-raised border border-surface-border text-tx-primary shadow-card'+ : 'text-tx-muted hover:text-tx-primary'+ }`}+ >+ {t === 'recent' ? 'Recent' : t === 'myfoods' ? 'My Foods' : 'Search'}+ </button>+ ))}+ </div>++ {rateLimited && (+ <div className="mx-4 mt-3 flex-shrink-0 flex items-center gap-2 rounded-lg border border-amber-500/20 bg-amber-500/10 px-3 py-2 text-xs text-amber-400">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ Too many requests — wait a moment and try again+ </div>+ )}+ {searchError && (+ <div className="mx-4 mt-3 flex-shrink-0 flex items-center gap-2 rounded-lg border border-error-500/20 bg-error-500/10 px-3 py-2 text-xs text-error-400">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ {searchError}+ </div>+ )}++ <div className="flex-1 overflow-y-auto">+ {tab === 'all' && quickAddCals !== null && (+ <button+ onClick={() => selectResult({+ name: `${quickAddCals} kcal`,+ calories: quickAddCals,+ protein: 0, carbs: 0, fat: 0, fiber: 0,+ serving_size: '1 serving', source: 'off',+ })}+ className="flex items-center gap-3 w-full px-4 py-3 hover:bg-surface-muted transition-colors border-b border-surface-border"+ >+ <div className="w-10 h-10 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">+ <Zap className="w-5 h-5 text-brand-500" />+ </div>+ <div className="flex-1 text-left min-w-0">+ <p className="text-sm font-medium text-tx-primary">Quick add {quickAddCals} kcal</p>+ <p className="text-xs text-tx-muted">No macro breakdown</p>+ </div>+ </button>+ )}++ {tab === 'recent' && (+ recentItems.length === 0+ ? <div className="px-4 py-12 text-center text-xs text-tx-muted">No recent items today</div>+ : recentItems.map((item, i) => (+ <FoodResultRow key={i} item={item} onClick={() => selectResult(item)} />+ ))+ )}++ {tab === 'myfoods' && (+ savedFoods.length === 0+ ? <div className="px-4 py-12 text-center text-xs text-tx-muted">No saved foods yet</div>+ : savedFoods.map(sf => (+ <FoodResultRow key={sf.id} item={savedToResult(sf)} onClick={() => selectResult(savedToResult(sf))} />+ ))+ )}++ {tab === 'all' && !query.trim() && (+ <div className="px-4 py-12 text-center text-xs text-tx-muted">Type to search millions of foods</div>+ )}++ {tab === 'all' && query.trim() && searching && (+ <div className="px-4 py-12 text-center text-xs text-tx-muted">Searching…</div>+ )}++ {tab === 'all' && query.trim() && !searching && searchResults.length === 0 && !searchError && !rateLimited && (+ <div className="px-4 py-12 text-center space-y-2">+ <p className="text-xs text-tx-muted">No results for "{query}"</p>+ <button+ onClick={() => selectResult({+ name: query.trim(), calories: 0, protein: 0, carbs: 0,+ fat: 0, fiber: 0, serving_size: '1 serving', source: 'off',+ })}+ className="text-xs text-brand-400 hover:text-brand-300 transition-colors"+ >+ + Enter "{query.trim()}" manually+ </button>+ </div>+ )}++ {tab === 'all' && !searching && searchResults.map((item, i) => (+ <FoodResultRow key={i} item={item} onClick={() => selectResult(item)} />+ ))}+ </div>+ </>+ )}++ {phase === 'detail' && selected && (+ <>+ <div className="flex items-center gap-2 px-4 pt-4 pb-3 border-b border-surface-border flex-shrink-0">+ {!editEntry && (+ <button+ onClick={() => setPhase('search')}+ className="p-1.5 hover:bg-surface-muted rounded-lg transition-colors text-tx-muted flex-shrink-0"+ >+ <ChevronLeft className="w-5 h-5" />+ </button>+ )}+ <div className="flex-1 min-w-0">+ <p className="font-semibold text-tx-primary text-sm truncate">{selected.name || 'New Entry'}</p>+ {selected.brand && <p className="text-xs text-tx-muted truncate">{selected.brand}</p>}+ </div>+ <button+ onClick={onClose}+ className="p-1.5 hover:bg-surface-muted rounded-lg transition-colors text-tx-muted flex-shrink-0"+ >+ <X className="w-5 h-5" />+ </button>+ </div>++ <div className="flex-1 overflow-y-auto p-4 space-y-5">+ {saveError && (+ <div className="alert-error">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ <span>{saveError}</span>+ </div>+ )}++ <div className="p-4 bg-surface-muted/30 border border-surface-border rounded-xl">+ <div className="text-center mb-3">+ <span className="stat-value text-3xl tabular-nums">{cal}</span>+ <span className="text-tx-muted text-sm ml-1">kcal</span>+ </div>+ <div className="grid grid-cols-4 gap-2 text-center">+ {[+ { label: 'Protein', value: pro, cls: 'text-emerald-400' },+ { label: 'Carbs', value: carb, cls: 'text-amber-400' },+ { label: 'Fat', value: fat_, cls: 'text-violet-400' },+ { label: 'Fiber', value: fib, cls: 'text-tx-secondary' },+ ].map(m => (+ <div key={m.label}>+ <p className={`stat-value text-sm tabular-nums ${m.cls}`}>{m.value}g</p>+ <p className="text-[10px] text-tx-muted">{m.label}</p>+ </div>+ ))}+ </div>+ </div>++ <div>+ <label className="label mb-2 block">+ Servings+ {selected.serving_size && (+ <span className="text-tx-muted font-normal normal-case tracking-normal ml-1">+ ({selected.serving_size})+ </span>+ )}+ </label>+ <div className="flex items-center gap-3">+ <button+ onClick={() => setServings(s => Math.max(0.5, +(s - 0.5).toFixed(1)))}+ className="w-10 h-10 rounded-lg bg-surface-muted border border-surface-border flex items-center justify-center hover:bg-surface-overlay transition-colors"+ >+ <Minus className="w-4 h-4 text-tx-primary" />+ </button>+ <input+ type="number"+ value={servings}+ onChange={e => setServings(Math.max(0.5, Number(e.target.value) || 1))}+ step="0.5"+ min="0.5"+ className="input text-center w-24 tabular-nums"+ />+ <button+ onClick={() => setServings(s => +(s + 0.5).toFixed(1))}+ className="w-10 h-10 rounded-lg bg-surface-muted border border-surface-border flex items-center justify-center hover:bg-surface-overlay transition-colors"+ >+ <Plus className="w-4 h-4 text-tx-primary" />+ </button>+ </div>+ </div>++ <div>+ <label className="label mb-2 block">Meal</label>+ <div className="flex flex-wrap gap-2">+ {MEALS.map(m => (+ <button+ key={m}+ onClick={() => setMeal(m)}+ className={`px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${+ meal === m+ ? 'bg-brand-500 border-brand-500 text-white'+ : 'bg-surface-muted border-surface-border text-tx-secondary hover:text-tx-primary'+ }`}+ >+ {MEAL_LABELS[m]}+ </button>+ ))}+ </div>+ </div>++ <div>+ <label className="label mb-1 block">Date</label>+ <input+ type="date"+ value={date}+ onChange={e => setDate(e.target.value)}+ max={todayStr()}+ className="input"+ />+ </div>++ {!editEntry && (+ <button+ type="button"+ onClick={() => setSaveToMyFoods(v => !v)}+ className="flex items-center gap-3 w-full"+ >+ <div className={`relative w-10 h-6 rounded-full border transition-colors flex-shrink-0 ${saveToMyFoods ? 'bg-brand-500 border-brand-500' : 'bg-surface-muted border-surface-border'}`}>+ <div className={`absolute top-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${saveToMyFoods ? 'translate-x-4' : 'translate-x-0.5'}`} />+ </div>+ <div className="flex items-center gap-1.5">+ {saveToMyFoods+ ? <BookmarkCheck className="w-4 h-4 text-brand-500" />+ : <Bookmark className="w-4 h-4 text-tx-muted" />+ }+ <span className="text-sm text-tx-secondary">Save to My Foods</span>+ </div>+ </button>+ )}+ </div>++ <div className="flex gap-3 px-4 pb-5 pt-3 border-t border-surface-border flex-shrink-0">+ <button+ onClick={() => editEntry ? onClose() : setPhase('search')}+ className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-overlay text-tx-secondary rounded-lg transition-colors font-medium text-sm"+ >+ Cancel+ </button>+ <button+ onClick={handleLog}+ disabled={saving}+ className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2 text-sm"+ >+ {saving ? 'Saving…' : editEntry ? 'Save Changes' : 'Log Food'}+ </button>+ </div>+ </>+ )}+ </div>+ </div>+ )}+ </>,+ document.body,+ )+}++function FoodResultRow({ item, onClick }: { item: types.FoodSearchResult; onClick: () => void }) {+ return (+ <button+ onClick={onClick}+ className="flex items-center gap-3 w-full px-4 py-3 hover:bg-surface-muted transition-colors border-b border-surface-border last:border-0 text-left"+ >+ {item.image_url ? (+ <img+ src={item.image_url}+ alt=""+ className="w-10 h-10 rounded-lg object-cover flex-shrink-0 border border-surface-border"+ />+ ) : (+ <div className="w-10 h-10 rounded-lg bg-surface-muted border border-surface-border flex items-center justify-center flex-shrink-0">+ <Utensils className="w-4 h-4 text-tx-muted" />+ </div>+ )}+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-tx-primary truncate">{item.name}</p>+ {item.brand && <p className="text-xs text-tx-muted truncate">{item.brand}</p>}+ <p className="text-xs text-tx-muted mt-0.5 tabular-nums">+ {Math.round(item.calories)} kcal · {item.protein.toFixed(0)}g P · {item.carbs.toFixed(0)}g C · {item.fat.toFixed(0)}g F+ </p>+ </div>+ </button>+ )+}diff --git a/web/src/components/ui/DateInput.tsx b/web/src/components/ui/DateInput.tsxnew file mode 100644index 0000000..92f9ad8--- /dev/null+++ b/web/src/components/ui/DateInput.tsx@@ -0,0 +1,23 @@+interface Props {+ label?: string+ value: string+ onChange: (value: string) => void+ max?: string+ min?: string+}++export default function DateInput({ label, value, onChange, max, min }: Props) {+ return (+ <div className="space-y-1.5 min-w-0 w-full">+ {label && <label className="label">{label}</label>}+ <input+ type="date"+ value={value}+ onChange={e => { if (e.target.value) onChange(e.target.value) }}+ max={max}+ min={min}+ className="input w-full max-w-full min-w-0 appearance-none"+ />+ </div>+ )+}diff --git a/web/src/components/ui/EmptyState.tsx b/web/src/components/ui/EmptyState.tsxnew file mode 100644index 0000000..f29b31d--- /dev/null+++ b/web/src/components/ui/EmptyState.tsx@@ -0,0 +1,25 @@+import type React from 'react'++interface Props {+ icon: React.ElementType+ title: string+ subtitle?: string+ action?: React.ReactNode+ compact?: boolean+}++export default function EmptyState({ icon: Icon, title, subtitle, action, compact = false }: Props) {+ return (+ <div className={compact+ ? 'flex flex-col items-center justify-center py-8 text-center px-4 gap-1'+ : 'empty-state'+ }>+ <div className="w-12 h-12 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center mb-2">+ <Icon className="w-6 h-6 text-tx-muted opacity-60" />+ </div>+ <p className="text-sm font-medium text-tx-primary">{title}</p>+ {subtitle && <p className="text-xs text-tx-muted mt-0.5">{subtitle}</p>}+ {action && <div className="mt-3">{action}</div>}+ </div>+ )+}diff --git a/web/src/components/ui/IconButton.tsx b/web/src/components/ui/IconButton.tsxnew file mode 100644index 0000000..c0d1c18--- /dev/null+++ b/web/src/components/ui/IconButton.tsx@@ -0,0 +1,47 @@+import type React from 'react'++interface Props {+ icon: React.ElementType+ label: string+ onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void+ variant?: 'brand' | 'danger' | 'ghost' | 'secondary' | 'solid'+ size?: 'sm' | 'md' | 'lg'+ disabled?: boolean+ className?: string+ type?: 'button' | 'submit'+}++const CONTAINER: Record<string, string> = {+ sm: 'w-8 h-8 rounded-lg',+ md: 'w-10 h-10 rounded-xl',+ lg: 'w-12 h-12 rounded-xl',+}+const ICON_SIZE: Record<string, string> = {+ sm: 'w-3.5 h-3.5',+ md: 'w-4 h-4',+ lg: 'w-5 h-5',+}+const VARIANT: Record<string, string> = {+ brand: 'bg-brand-500/10 border border-brand-500/20 text-brand-400 hover:bg-brand-500/20',+ danger: 'text-tx-muted hover:bg-error-500/10 hover:text-error-400',+ ghost: 'text-tx-muted hover:bg-surface-muted hover:text-tx-primary',+ secondary: 'bg-surface-muted border border-surface-border text-tx-primary hover:bg-surface-overlay',+ solid: 'bg-brand-500 text-white hover:bg-brand-600 shadow-sm',+}++export default function IconButton({+ icon: Icon, label, onClick, variant = 'ghost', size = 'sm',+ disabled, className = '', type = 'button',+}: Props) {+ return (+ <button+ type={type}+ aria-label={label}+ onClick={onClick}+ disabled={disabled}+ className={`flex items-center justify-center flex-shrink-0 active:scale-95 transition-all disabled:opacity-40 disabled:cursor-not-allowed ${CONTAINER[size]} ${VARIANT[variant]} ${className}`}+ >+ <Icon className={ICON_SIZE[size]} />+ </button>+ )+}diff --git a/web/src/components/ui/PageHeader.tsx b/web/src/components/ui/PageHeader.tsxnew file mode 100644index 0000000..28cd7a1--- /dev/null+++ b/web/src/components/ui/PageHeader.tsx@@ -0,0 +1,19 @@+import type React from 'react'++interface Props {+ title: string+ subtitle?: string+ action?: React.ReactNode+}++export default function PageHeader({ title, subtitle, action }: Props) {+ return (+ <div className="flex justify-between items-center gap-3">+ <div className="min-w-0">+ <h1 className="font-display font-bold text-2xl text-tx-primary">{title}</h1>+ {subtitle && <p className="text-tx-muted text-sm mt-0.5">{subtitle}</p>}+ </div>+ {action && <div className="flex-shrink-0">{action}</div>}+ </div>+ )+}diff --git a/web/src/components/ui/SectionHeader.tsx b/web/src/components/ui/SectionHeader.tsxnew file mode 100644index 0000000..9c4646e--- /dev/null+++ b/web/src/components/ui/SectionHeader.tsx@@ -0,0 +1,20 @@+import type React from 'react'++interface Props {+ icon?: React.ElementType+ title: string+ right?: React.ReactNode+ className?: string+}++export default function SectionHeader({ icon: Icon, title, right, className = '' }: Props) {+ return (+ <div className={`flex items-center justify-between ${className}`}>+ <div className="flex items-center gap-2">+ {Icon && <Icon className="w-4 h-4 text-brand-500 flex-shrink-0" />}+ <h2 className="section-title">{title}</h2>+ </div>+ {right && <div className="flex-shrink-0">{right}</div>}+ </div>+ )+}diff --git a/web/src/components/ui/SegmentedControl.tsx b/web/src/components/ui/SegmentedControl.tsxnew file mode 100644index 0000000..8c4e139--- /dev/null+++ b/web/src/components/ui/SegmentedControl.tsx@@ -0,0 +1,40 @@+interface Option<T extends string> {+ value: T+ label: string+}++interface Props<T extends string> {+ options: readonly Option<T>[] | Option<T>[]+ value: T+ onChange: (v: T) => void+ size?: 'sm' | 'md'+ className?: string+}++const ITEM: Record<string, string> = {+ sm: 'px-3 py-1.5 text-xs rounded-md',+ md: 'px-3 py-2.5 text-sm rounded-lg',+}++export default function SegmentedControl<T extends string>({+ options, value, onChange, size = 'md', className = '',+}: Props<T>) {+ return (+ <div className={`flex gap-1 bg-surface-overlay rounded-xl p-1 ${className}`}>+ {options.map(opt => (+ <button+ key={opt.value}+ type="button"+ onClick={() => onChange(opt.value)}+ className={`flex-1 font-medium transition-all duration-150 ${ITEM[size]} ${+ value === opt.value+ ? 'bg-surface-raised border border-surface-border text-tx-primary shadow-card'+ : 'text-tx-muted hover:text-tx-primary'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>+ )+}diff --git a/web/src/components/ui/index.ts b/web/src/components/ui/index.tsnew file mode 100644index 0000000..f8a895d--- /dev/null+++ b/web/src/components/ui/index.ts@@ -0,0 +1,6 @@+export { default as IconButton } from './IconButton'+export { default as DateInput } from './DateInput'+export { default as SegmentedControl } from './SegmentedControl'+export { default as EmptyState } from './EmptyState'+export { default as SectionHeader } from './SectionHeader'+export { default as PageHeader } from './PageHeader'diff --git a/web/src/index.css b/web/src/index.cssindex a253138..e156ac1 100644--- a/web/src/index.css+++ b/web/src/index.css@@ -69,14 +69,16 @@.btn-primary { @apply bg-brand-500 text-white hover:bg-brand-600 active:bg-brand-700 shadow-sm; }.btn-secondary { @apply bg-surface-muted border border-surface-border text-tx-secondary hover:text-tx-primary hover:border-tx-muted; }.btn-ghost { @apply text-tx-muted hover:text-tx-primary hover:bg-surface-muted; }- .btn-danger { @apply bg-error-500/10 border border-error-500/20 text-error-400 hover:bg-error-500/20; }+ .btn-danger { @apply bg-error-500/10 border border-error-500/20 text-error-400 hover:bg-error-500/20; }+ .btn-danger-solid { @apply bg-error-500 text-white hover:bg-error-600 active:bg-error-700 shadow-sm; }.btn-icon { @apply btn p-2.5 rounded-lg; }.btn-icon-sm { @apply btn p-2 rounded-md; }/* Inputs */.input {/* text-base (16px) is the minimum to prevent iOS Safari auto-zoom on focus. */- @apply w-full px-3.5 py-2.5 bg-surface-overlay border border-surface-border rounded-lg+ /* min-w-0 overrides browser-imposed intrinsic min-width on date/number inputs. */+ @apply w-full min-w-0 px-3.5 py-2.5 bg-surface-overlay border border-surface-border rounded-lgtext-tx-primary placeholder-tx-muted text-basefocus:outline-none focus:ring-1 focus:ring-brand-500 focus:border-brand-500transition-colors duration-150;diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsxindex 38b4cf3..bd9427a 100644--- a/web/src/pages/Dashboard.tsx+++ b/web/src/pages/Dashboard.tsx@@ -9,6 +9,7 @@ import {LineChart, Line, PieChart, Pie, Legend,} from 'recharts'import Loading from '../components/Loading'+import SectionHeader from '../components/ui/SectionHeader'import PeriodSelector from '../components/PeriodSelector'import QuickWeighInSheet from '../components/QuickWeighInSheet'import { workoutAPI, foodAPI, weightAPI, userAPI } from '../services/api'@@ -33,7 +34,7 @@ const calcVolume = (w: types.Workout) =>const DEFAULT_FOOD: types.DailyStats = {date: format(TODAY, 'yyyy-MM-dd'),- total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0, workout_count: 0,+ total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0, total_fiber: 0, workout_count: 0,}const DEFAULT_SETTINGS: types.UserSettings = {user_id: 0, weight_unit: 'lbs', calorie_target: 2000,@@ -329,17 +330,12 @@ export default function Dashboard() {{/* ── Volume trend chart ─────────────────────── */}<div className="card p-4">- <div className="flex items-center justify-between mb-3 gap-2">- <div className="flex items-center gap-2">- <TrendingUp className="w-4 h-4 text-brand-500" />- <h2 className="section-title">Volume Trend</h2>- </div>- <PeriodSelector- options={['7', '14', '30'] as const}- value={volumePeriod}- onChange={setVolumePeriod}- />- </div>+ <SectionHeader+ icon={TrendingUp}+ title="Volume Trend"+ right={<PeriodSelector options={['7', '14', '30'] as const} value={volumePeriod} onChange={setVolumePeriod} />}+ className="mb-3"+ />{chartData.length === 0 ? (<div className="flex flex-col items-center justify-center py-8 gap-2">@@ -400,13 +396,12 @@ export default function Dashboard() {{/* ── Frequency heatmap ──────────────────────── */}<div className="card p-4">- <div className="flex items-center justify-between mb-3">- <div className="flex items-center gap-2">- <Activity className="w-4 h-4 text-brand-500" />- <h2 className="section-title">Consistency</h2>- </div>- <span className="text-xs text-tx-muted">12 weeks</span>- </div>+ <SectionHeader+ icon={Activity}+ title="Consistency"+ right={<span className="text-xs text-tx-muted">12 weeks</span>}+ className="mb-3"+ />{workouts.length === 0 ? (<div className="flex flex-col items-center justify-center py-6 gap-2">@@ -598,13 +593,12 @@ export default function Dashboard() {{/* ── Muscle group balance ────────────────────── */}<div className="card p-4">- <div className="flex items-center justify-between mb-1">- <div className="flex items-center gap-2">- <Dumbbell className="w-4 h-4 text-brand-500" />- <h2 className="section-title">Muscle Balance</h2>- </div>- <span className="text-xs text-tx-muted">{workouts.length} workouts</span>- </div>+ <SectionHeader+ icon={Dumbbell}+ title="Muscle Balance"+ right={<span className="text-xs text-tx-muted">{workouts.length} workouts</span>}+ className="mb-1"+ />{topMuscle ? (<p className="text-xs text-tx-muted mb-3 italic">@@ -683,15 +677,16 @@ export default function Dashboard() {{/* ── Weight quick-log card ──────────────────── */}<div className="card p-4">- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <Scale className="w-4 h-4 text-brand-500" />- <h2 className="section-title">Weight</h2>- </div>- <Link to="/weight" className="text-xs text-brand-400 hover:text-brand-300 transition-colors flex items-center gap-0.5">- View <ArrowRight className="w-3 h-3" />- </Link>- </div>+ <SectionHeader+ icon={Scale}+ title="Weight"+ right={+ <Link to="/weight" className="text-xs text-brand-400 hover:text-brand-300 transition-colors flex items-center gap-0.5">+ View <ArrowRight className="w-3 h-3" />+ </Link>+ }+ className="mb-2"+ />{weightLogs.length === 0 ? (<button@@ -733,9 +728,9 @@ export default function Dashboard() {</span>)})()}- <span className="w-7 h-7 rounded-lg bg-brand-500 hover:bg-brand-600 flex items-center justify-center text-white shadow-sm">- <Plus className="w-4 h-4" />- </span>+ <div className="w-8 h-8 rounded-lg bg-brand-500 flex items-center justify-center text-white shadow-sm flex-shrink-0">+ <Plus className="w-3.5 h-3.5" />+ </div></div></div>{weightLogs.length >= 2 && (diff --git a/web/src/pages/Food.tsx b/web/src/pages/Food.tsxindex 6ed0eeb..6ef597d 100644--- a/web/src/pages/Food.tsx+++ b/web/src/pages/Food.tsx@@ -1,167 +1,474 @@-import { useState, useEffect } from 'react'-import { Plus, Flame, AlertCircle, Trash2 } from 'lucide-react'-import { format } from 'date-fns'-import { HelpTip } from '../components/Tooltip'+import { useState, useEffect, useCallback, useRef } from 'react'+import { useNavigate, useLocation } from 'react-router-dom'+import { format, subDays, addDays } from 'date-fns'+import {+ ChevronLeft, ChevronRight, Flame, Plus, Trash2,+ AlertCircle, Coffee, Sun, Moon, Cookie, CalendarDays, Utensils,+} from 'lucide-react'+import IconButton from '../components/ui/IconButton'+import SectionHeader from '../components/ui/SectionHeader'+import PageHeader from '../components/ui/PageHeader'+import {+ AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer,+} from 'recharts'import Loading from '../components/Loading'+import PeriodSelector from '../components/PeriodSelector'import { foodAPI, userAPI } from '../services/api'+import { todayStr } from '../utils/dateUtils'+import { MACRO_COLORS } from '../utils/macroColors'import * as types from '../types'const MEALS = ['breakfast', 'lunch', 'dinner', 'snacks'] as const-const MEAL_LABELS: Record<typeof MEALS[number], string> = {- breakfast: 'Breakfast', lunch: 'Lunch', dinner: 'Dinner', snacks: 'Snacks'+const MEAL_LABELS: Record<string, string> = {+ breakfast: 'Breakfast', lunch: 'Lunch', dinner: 'Dinner', snacks: 'Snacks',}+const MEAL_ICONS: Record<string, React.ElementType> = {+ breakfast: Coffee, lunch: Sun, dinner: Moon, snacks: Cookie,+}+const MEAL_COLORS: Record<string, string> = {+ breakfast: 'text-amber-400', lunch: 'text-yellow-400',+ dinner: 'text-indigo-400', snacks: 'text-pink-400',+}+const HISTORY_PERIODS = ['7d', '30d', '90d'] as const+type HistoryPeriod = typeof HISTORY_PERIODS[number]++// ─── MacroRing ────────────────────────────────────────────────────────────────++function MacroRing({+ value, target, color, label,+}: { value: number; target: number; color: string; label: string }) {+ const r = 30+ const circ = 2 * Math.PI * r+ const pct = Math.min(1, value / Math.max(target, 1))+ return (+ <div className="flex flex-col items-center gap-1.5">+ <div className="relative">+ <svg width="72" height="72" className="-rotate-90">+ <circle cx="36" cy="36" r={r} fill="none" stroke="currentColor" strokeWidth="5"+ className="text-surface-muted" />+ <circle cx="36" cy="36" r={r} fill="none" stroke={color} strokeWidth="5"+ strokeDasharray={circ}+ strokeDashoffset={circ * (1 - pct)}+ strokeLinecap="round"+ style={{ transition: 'stroke-dashoffset 0.6s ease' }} />+ </svg>+ <div className="absolute inset-0 flex items-center justify-center">+ <span className="text-xs font-bold tabular-nums" style={{ color }}>{Math.round(pct * 100)}%</span>+ </div>+ </div>+ <div className="text-center">+ <p className="text-sm font-semibold tabular-nums text-tx-primary">{Math.round(value)}g</p>+ <p className="text-[10px] text-tx-muted">{label} / {target}g</p>+ </div>+ </div>+ )+}++// ─── Food page ────────────────────────────────────────────────────────────────export default function Food() {+ const navigate = useNavigate()+ const location = useLocation()+ const [selectedDate, setSelectedDate] = useState(todayStr())const [logs, setLogs] = useState<types.FoodLog[]>([])const [stats, setStats] = useState<types.DailyStats | null>(null)const [settings, setSettings] = useState<types.UserSettings | null>(null)const [loading, setLoading] = useState(true)const [error, setError] = useState<string | null>(null)- useEffect(() => {- const load = async () => {- try {- const today = format(new Date(), 'yyyy-MM-dd')- const [logData, statsData, settingsData] = await Promise.all([- foodAPI.list(today),- foodAPI.stats(today).catch(() => ({- date: today,- total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0, workout_count: 0- })),- userAPI.getSettings().catch(() => ({- user_id: 0, weight_unit: 'lbs' as const, calorie_target: 2000,- protein_target: 150, carb_target: 250, fat_target: 65- })),- ])- setLogs(logData || [])- setStats(statsData)- setSettings(settingsData)- } catch (err: any) {- setError(err.message || 'Failed to load food data')- } finally {- setLoading(false)+ const [historyPeriod, setHistoryPeriod] = useState<HistoryPeriod>('30d')+ const [historyData, setHistoryData] = useState<types.FoodHistoryPoint[]>([])+ const [historyLoading, setHistoryLoading] = useState(false)++ const [deletingId, setDeletingId] = useState<number | null>(null)+ const dateInputRef = useRef<HTMLInputElement>(null)+ const [deleteConfirmId, setDeleteConfirmId] = useState<number | null>(null)+ const hasLoadedRef = useRef(false)++ const loadDay = useCallback(async (date: string) => {+ setLoading(true)+ setLogs([])+ setStats(null)+ setError(null)+ try {+ const defaultStats: types.DailyStats = {+ date, total_calories: 0, total_protein: 0, total_carbs: 0,+ total_fat: 0, total_fiber: 0, workout_count: 0,}+ const [logData, statsData, settingsData] = await Promise.all([+ foodAPI.list(date),+ foodAPI.stats(date).catch(() => defaultStats),+ settings+ ? Promise.resolve(settings)+ : userAPI.getSettings().catch(() => ({+ user_id: 0, weight_unit: 'lbs' as const,+ calorie_target: 2000, protein_target: 150, carb_target: 250, fat_target: 65,+ })),+ ])+ setLogs(logData || [])+ setStats(statsData)+ if (!settings) setSettings(settingsData as types.UserSettings)+ } catch (err: any) {+ setError(err.message || 'Failed to load food data')+ } finally {+ hasLoadedRef.current = true+ setLoading(false)}- load()- }, [])+ }, [settings])++ useEffect(() => { loadDay(selectedDate) }, [selectedDate, location.key, loadDay])++ useEffect(() => {+ setHistoryLoading(true)+ const days = historyPeriod === '7d' ? 7 : historyPeriod === '30d' ? 30 : 90+ foodAPI.history(days)+ .then(data => setHistoryData(data || []))+ .catch(() => {})+ .finally(() => setHistoryLoading(false))+ }, [historyPeriod])++ const openLog = (meal: types.FoodLog['meal']) => {+ navigate(`/food/log?meal=${meal}&date=${selectedDate}`)+ }const handleDelete = async (id: number) => {+ setDeletingId(id)try {await foodAPI.delete(id)- setLogs(logs.filter(l => l.id !== id))- } catch (err: any) {- setError(err.message || 'Failed to delete entry')+ setLogs(prev => prev.filter(l => l.id !== id))+ setDeleteConfirmId(null)+ foodAPI.stats(selectedDate).then(setStats).catch(() => {})+ } catch {+ setError('Failed to delete entry')+ } finally {+ setDeletingId(null)}}- if (loading) {- return <Loading />- }+ if (loading && !hasLoadedRef.current) return <Loading />- if (!settings) {- return (- <div className="alert-error">- <AlertCircle className="w-5 h-5 flex-shrink-0" />- <span>Failed to load settings</span>- </div>- )- }+ const s = stats+ const totalCals = s?.total_calories ?? 0+ const calTarget = settings?.calorie_target ?? 2000+ const remaining = calTarget - totalCals+ const isOver = remaining < 0+ const calPct = Math.min(100, (totalCals / calTarget) * 100)- const stats_ = stats!- const totalCals = stats_.total_calories- const remaining = settings.calorie_target - totalCals+ const isToday = selectedDate === todayStr()+ const selectedDateObj = new Date(selectedDate + 'T12:00:00')+ const prevDate = format(subDays(selectedDateObj, 1), 'yyyy-MM-dd')+ const nextDate = format(addDays(selectedDateObj, 1), 'yyyy-MM-dd')+ const canGoNext = selectedDate < todayStr()++ const dayLabel = isToday+ ? 'Today'+ : selectedDate === format(subDays(new Date(), 1), 'yyyy-MM-dd')+ ? 'Yesterday'+ : format(selectedDateObj, 'EEE, MMM d')return (- <div className="space-y-5 animate-slide-up">- {/* Header */}- <div className="flex justify-between items-center">- <div>- <h1 className="font-display font-bold text-2xl text-tx-primary">Nutrition</h1>- <p className="text-tx-muted text-sm mt-0.5">Log meals and track your macros</p>- </div>- <button className="btn-primary btn-sm">- <Plus className="w-3.5 h-3.5" /> Log- </button>- </div>+ <div className="space-y-4 animate-slide-up">+ <PageHeader+ title="Nutrition"+ subtitle="Macros & meals"+ action={+ <button onClick={() => openLog('breakfast')} className="btn-primary btn-sm">+ <Plus className="w-4 h-4" /> Log Food+ </button>+ }+ />- {/* Daily summary */}- <div className="card p-5">- <div className="flex items-center justify-between mb-5">- <h2 className="section-title">Today's Summary</h2>- <div className={`flex items-center gap-1 text-xs font-medium ${remaining > 0 ? 'text-tx-muted' : 'text-warning-400'}`}>- <Flame className="w-3.5 h-3.5" />- {remaining > 0 ? `${remaining.toFixed(0)} kcal left` : `${Math.abs(remaining).toFixed(0)} kcal over`}- </div>+ {error && (+ <div className="alert-error">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ <span>{error}</span></div>+ )}- <div className="space-y-3">- <div className="flex justify-between items-center">- <span className="text-sm text-tx-secondary">Calories</span>- <span className="stat-value text-2xl">{Math.round(totalCals)} / {settings.calorie_target}</span>- </div>- <div className="progress-track">- <div className="progress-bar" style={{ width: `${Math.min(100, (totalCals / settings.calorie_target) * 100)}%`, background: '#00b8d9' }} />+ {/* Date navigator */}+ <div className="flex items-center gap-2">+ <button+ aria-label="Previous day"+ onClick={() => setSelectedDate(prevDate)}+ className="p-3 rounded-xl hover:bg-surface-muted active:scale-95 transition-all text-tx-muted"+ >+ <ChevronLeft className="w-5 h-5" />+ </button>+ <div className="relative flex-1 cursor-pointer" onClick={() => dateInputRef.current?.showPicker?.()}>+ <div className="flex items-center justify-center gap-2 py-2 rounded-xl bg-surface-muted pointer-events-none">+ <CalendarDays className="w-4 h-4 text-tx-muted" />+ <span className="text-sm font-semibold text-tx-primary">{dayLabel}</span>+ {!isToday && (+ <span className="text-xs text-tx-muted">{format(selectedDateObj, 'yyyy')}</span>+ )}</div>+ <input+ ref={dateInputRef}+ type="date"+ value={selectedDate}+ onChange={e => e.target.value && setSelectedDate(e.target.value)}+ max={todayStr()}+ className="absolute inset-0 opacity-0 w-full h-full cursor-pointer"+ />+ </div>+ <button+ aria-label="Next day"+ onClick={() => setSelectedDate(nextDate)}+ disabled={!canGoNext}+ className="p-3 rounded-xl hover:bg-surface-muted active:scale-95 transition-all text-tx-muted disabled:opacity-30 disabled:cursor-not-allowed"+ >+ <ChevronRight className="w-5 h-5" />+ </button>+ </div>- <div className="grid grid-cols-3 gap-3 mt-5 pt-3 border-t border-surface-border">+ {/* Macro summary card */}+ {settings && (+ <div className="card p-5 space-y-5">+ {/* Calorie hero */}+ <div className="flex items-center justify-between"><div>- <p className="text-xs text-tx-muted">Protein</p>- <p className="stat-value text-lg">{Math.round(stats_.total_protein)}/{settings.protein_target}g</p>+ <p className="text-xs font-medium text-tx-muted uppercase tracking-wide mb-1">Calories</p>+ <div className="flex items-baseline gap-1.5">+ <span className="text-4xl font-bold tabular-nums text-tx-primary">{Math.round(totalCals)}</span>+ <span className="text-sm text-tx-muted">/ {calTarget}</span>+ </div></div>- <div>- <p className="text-xs text-tx-muted">Carbs</p>- <p className="stat-value text-lg">{Math.round(stats_.total_carbs)}/{settings.carb_target}g</p>+ <div className={`flex items-center gap-1.5 text-sm font-semibold px-3 py-2 rounded-xl border ${+ isOver+ ? 'bg-amber-500/10 border-amber-500/20 text-amber-400'+ : 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400'+ }`}>+ <Flame className="w-4 h-4" />+ {isOver+ ? `${Math.round(Math.abs(remaining))} over`+ : `${Math.round(remaining)} left`+ }</div>- <div>- <p className="text-xs text-tx-muted">Fat</p>- <p className="stat-value text-lg">{Math.round(stats_.total_fat)}/{settings.fat_target}g</p>+ </div>++ {/* Segmented progress bar */}+ <div className="space-y-1">+ <div className="h-2.5 rounded-full bg-surface-muted overflow-hidden">+ <div+ className="h-full rounded-full transition-all duration-500"+ style={{+ width: `${calPct}%`,+ background: isOver+ ? `linear-gradient(90deg, ${MACRO_COLORS.carbs}, #ef4444)`+ : `linear-gradient(90deg, #00b8d9, ${MACRO_COLORS.protein})`,+ }}+ />+ </div>+ <div className="flex justify-between text-[10px] text-tx-muted">+ <span>0</span>+ <span>{calTarget} kcal goal</span></div></div>++ {/* Macro rings */}+ <div className="grid grid-cols-3 gap-3">+ <MacroRing+ value={s?.total_protein ?? 0}+ target={settings.protein_target}+ color={MACRO_COLORS.protein}+ label="Protein"+ />+ <MacroRing+ value={s?.total_carbs ?? 0}+ target={settings.carb_target}+ color={MACRO_COLORS.carbs}+ label="Carbs"+ />+ <MacroRing+ value={s?.total_fat ?? 0}+ target={settings.fat_target}+ color={MACRO_COLORS.fat}+ label="Fat"+ />+ </div></div>- </div>+ )}- {/* Meal sections */}- {MEALS.map(meal => {- const entries = logs.filter(l => l.meal === meal)- const mealCals = entries.reduce((sum, e) => sum + e.calories, 0)-- return (- <div key={meal} className="card overflow-hidden">- <div className="px-4 py-3 border-b border-surface-border flex justify-between items-center">- <div className="flex items-center gap-2">- <span className="text-sm font-semibold text-tx-primary">{MEAL_LABELS[meal]}</span>- {mealCals > 0 && <span className="badge-dim">{Math.round(mealCals)} kcal</span>}- </div>- <button className="btn-ghost btn-icon-sm">- <Plus className="w-3.5 h-3.5" />- </button>- </div>+ {/* Meals */}+ <div className="space-y-3">+ {MEALS.map(meal => {+ const MealIcon = MEAL_ICONS[meal]+ const iconColor = MEAL_COLORS[meal]+ const entries = logs.filter(l => l.meal === meal)+ const mealCals = entries.reduce((sum, e) => sum + e.calories, 0)- {entries.length === 0 ? (- <div className="px-4 py-6 text-center">- <p className="text-xs text-tx-muted">No entries</p>- </div>- ) : (- <div className="divide-y divide-surface-border">- {entries.map(entry => (- <div key={entry.id} className="px-4 py-3 flex justify-between items-center hover:bg-surface-muted transition-colors group">- <div>- <p className="text-sm font-medium text-tx-primary">{entry.name}</p>- <p className="text-xs text-tx-muted">{Math.round(entry.calories)} kcal · {entry.servings} servings</p>- </div>- <button- onClick={() => handleDelete(entry.id)}- className="btn-ghost btn-icon-sm opacity-0 group-hover:opacity-100 transition-opacity"- >- <Trash2 className="w-3.5 h-3.5" />- </button>+ return (+ <div key={meal} className="card overflow-hidden">+ {/* Meal header */}+ <div className="px-4 py-3.5 flex items-center gap-3">+ <div className={`w-8 h-8 rounded-lg flex items-center justify-center bg-surface-muted flex-shrink-0`}>+ <MealIcon className={`w-4 h-4 ${iconColor}`} />+ </div>+ <div className="flex-1 min-w-0">+ <span className="text-sm font-semibold text-tx-primary">{MEAL_LABELS[meal]}</span>+ {mealCals > 0 && (+ <span className="ml-2 text-xs text-tx-muted tabular-nums">{Math.round(mealCals)} kcal</span>+ )}+ </div>+ <IconButton+ icon={Plus}+ variant="solid"+ label={`Add to ${MEAL_LABELS[meal]}`}+ onClick={() => openLog(meal)}+ />+ </div>++ {entries.length === 0 ? (+ <button+ onClick={() => openLog(meal)}+ className="w-full px-4 py-4 text-center border-t border-surface-border hover:bg-surface-muted/50 transition-colors group"+ >+ <p className="text-xs text-tx-muted group-hover:text-tx-secondary transition-colors">+ + Tap to add food+ </p>+ </button>+ ) : (+ <div className="divide-y divide-surface-border border-t border-surface-border">+ {entries.map(entry => (+ <div key={entry.id}>+ {deleteConfirmId === entry.id ? (+ <div className="px-4 py-3 flex items-center justify-between gap-3 bg-error-500/5 border-l-2 border-error-500">+ <p className="text-xs text-tx-secondary flex-1 min-w-0">+ Delete <span className="font-medium text-tx-primary">{entry.name}</span>?+ </p>+ <div className="flex gap-2 flex-shrink-0">+ <button onClick={() => setDeleteConfirmId(null)} className="btn-secondary btn-sm">+ Cancel+ </button>+ <button onClick={() => handleDelete(entry.id)} disabled={deletingId === entry.id} className="btn-danger-solid btn-sm disabled:opacity-50">+ {deletingId === entry.id ? '…' : 'Delete'}+ </button>+ </div>+ </div>+ ) : (+ <div className="flex items-center gap-2 px-4 py-3">+ <button+ onClick={() => navigate(`/food/log?edit=${entry.id}&date=${selectedDate}`)}+ className="flex items-center gap-3 flex-1 min-w-0 text-left"+ >+ {entry.image_url ? (+ <img src={entry.image_url} alt="" className="w-11 h-11 rounded-xl object-cover flex-shrink-0 border border-surface-border" />+ ) : (+ <div className="w-11 h-11 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center flex-shrink-0">+ <Utensils className="w-5 h-5 text-tx-muted opacity-40" />+ </div>+ )}+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-tx-primary truncate">{entry.name}</p>+ <div className="flex items-center gap-2 mt-0.5 flex-wrap">+ <span className="text-xs font-semibold text-tx-secondary tabular-nums">+ {Math.round(entry.calories)} kcal+ </span>+ <span className="text-[10px] text-tx-muted">·</span>+ <span className="text-xs text-emerald-400 tabular-nums">{entry.protein.toFixed(0)}g P</span>+ <span className="text-[10px] text-tx-muted">·</span>+ <span className="text-xs text-amber-400 tabular-nums">{entry.carbs.toFixed(0)}g C</span>+ <span className="text-[10px] text-tx-muted">·</span>+ <span className="text-xs text-violet-400 tabular-nums">{entry.fat.toFixed(0)}g F</span>+ {entry.servings !== 1 && (+ <span className="text-xs text-tx-muted">× {entry.servings}</span>+ )}+ </div>+ </div>+ <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />+ </button>+ <IconButton icon={Trash2} variant="danger" label="Delete" onClick={() => setDeleteConfirmId(entry.id)} />+ </div>+ )}+ </div>+ ))}</div>- ))}+ )}</div>- )}+ )+ })}+ </div>++ {/* Macro history */}+ <div className="card p-5">+ <SectionHeader+ title="Macro History"+ right={<PeriodSelector options={HISTORY_PERIODS} value={historyPeriod} onChange={setHistoryPeriod} />}+ className="mb-5"+ />++ {historyLoading ? (+ <div className="flex items-center justify-center h-48 text-xs text-tx-muted">Loading…</div>+ ) : historyData.length === 0 ? (+ <div className="flex flex-col items-center justify-center h-48 gap-2">+ <CalendarDays className="w-8 h-8 text-tx-muted opacity-40" />+ <p className="text-xs text-tx-muted">No data yet — start logging meals</p></div>- )- })}+ ) : (+ <ResponsiveContainer width="100%" height={220}>+ <AreaChart data={historyData} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>+ <defs>+ <linearGradient id="gProtein" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stopColor={MACRO_COLORS.protein} stopOpacity={0.5} />+ <stop offset="100%" stopColor={MACRO_COLORS.protein} stopOpacity={0.1} />+ </linearGradient>+ <linearGradient id="gCarbs" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stopColor={MACRO_COLORS.carbs} stopOpacity={0.5} />+ <stop offset="100%" stopColor={MACRO_COLORS.carbs} stopOpacity={0.1} />+ </linearGradient>+ <linearGradient id="gFat" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stopColor={MACRO_COLORS.fat} stopOpacity={0.5} />+ <stop offset="100%" stopColor={MACRO_COLORS.fat} stopOpacity={0.1} />+ </linearGradient>+ </defs>+ <XAxis+ dataKey="date"+ tickFormatter={d => format(new Date(d + 'T12:00:00'), 'M/d')}+ tick={{ fontSize: 10, fill: 'var(--color-tx-muted)' }}+ axisLine={false}+ tickLine={false}+ interval="preserveStartEnd"+ />+ <YAxis+ tick={{ fontSize: 10, fill: 'var(--color-tx-muted)' }}+ axisLine={false}+ tickLine={false}+ tickFormatter={v => `${v}g`}+ width={36}+ />+ <Tooltip+ contentStyle={{+ background: 'var(--color-surface-raised)',+ border: '1px solid var(--color-surface-border)',+ borderRadius: '12px',+ fontSize: '12px',+ color: 'var(--color-tx-primary)',+ }}+ labelFormatter={d => format(new Date(d + 'T12:00:00'), 'MMM d')}+ formatter={(val: number, name: string) => [`${Math.round(val)}g`, name]}+ cursor={{ stroke: 'rgba(99,102,241,0.15)', strokeWidth: 1 }}+ />+ <Area type="monotone" dataKey="fat" stackId="macros" stroke={MACRO_COLORS.fat} strokeWidth={1.5} fill="url(#gFat)" name="Fat" dot={false} />+ <Area type="monotone" dataKey="carbs" stackId="macros" stroke={MACRO_COLORS.carbs} strokeWidth={1.5} fill="url(#gCarbs)" name="Carbs" dot={false} />+ <Area type="monotone" dataKey="protein" stackId="macros" stroke={MACRO_COLORS.protein} strokeWidth={1.5} fill="url(#gProtein)" name="Protein" dot={false} />+ </AreaChart>+ </ResponsiveContainer>+ )}++ <div className="flex gap-4 justify-center mt-4">+ {[+ { color: MACRO_COLORS.protein, label: 'Protein' },+ { color: MACRO_COLORS.carbs, label: 'Carbs' },+ { color: MACRO_COLORS.fat, label: 'Fat' },+ ].map(m => (+ <div key={m.label} className="flex items-center gap-1.5">+ <div className="w-2.5 h-2.5 rounded-sm flex-shrink-0" style={{ background: m.color }} />+ <span className="text-xs text-tx-muted">{m.label}</span>+ </div>+ ))}+ </div>+ </div>+</div>)}diff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsxnew file mode 100644index 0000000..c4c0046--- /dev/null+++ b/web/src/pages/LogFood.tsx@@ -0,0 +1,570 @@+import { useState, useEffect, useRef } from 'react'+import { useNavigate, useSearchParams } from 'react-router-dom'+import {+ ArrowLeft, Search, Scan, Minus, Plus, X,+ Bookmark, BookmarkCheck, AlertCircle, Utensils, Zap,+ Coffee, Sun, Moon, Cookie, ChevronRight,+} from 'lucide-react'+import { foodAPI, savedFoodsAPI } from '../services/api'+import { todayStr, dayToIsoNoon } from '../utils/dateUtils'+import { MACRO_COLORS } from '../utils/macroColors'+import BarcodeScanner from '../components/BarcodeScanner'+import IconButton from '../components/ui/IconButton'+import SegmentedControl from '../components/ui/SegmentedControl'+import DateInput from '../components/ui/DateInput'+import * as types from '../types'++type Phase = 'search' | 'detail' | 'scan'+type SearchTab = 'recent' | 'myfoods' | 'all'++const MEALS = ['breakfast', 'lunch', 'dinner', 'snacks'] as const+const MEAL_LABELS: Record<string, string> = {+ breakfast: 'Breakfast', lunch: 'Lunch', dinner: 'Dinner', snacks: 'Snacks',+}+const MEAL_ICONS: Record<string, React.ElementType> = {+ breakfast: Coffee, lunch: Sun, dinner: Moon, snacks: Cookie,+}+const MEAL_COLORS: Record<string, string> = {+ breakfast: 'text-amber-400', lunch: 'text-yellow-400',+ dinner: 'text-indigo-400', snacks: 'text-pink-400',+}++function entryToResult(e: types.FoodLog): types.FoodSearchResult {+ const s = e.servings || 1+ return {+ name: e.name,+ calories: e.calories / s,+ protein: e.protein / s,+ carbs: e.carbs / s,+ fat: e.fat / s,+ fiber: (e.fiber ?? 0) / s,+ serving_size: e.serving_size ?? '',+ image_url: e.image_url,+ source: 'saved',+ }+}++function savedToResult(s: types.SavedFood): types.FoodSearchResult {+ return {+ name: s.name, brand: s.brand,+ calories: s.calories, protein: s.protein, carbs: s.carbs,+ fat: s.fat, fiber: s.fiber, serving_size: s.serving_size, source: 'saved',+ }+}++function FoodResultRow({ item, onClick }: { item: types.FoodSearchResult; onClick: () => void }) {+ return (+ <button+ onClick={onClick}+ className="flex items-center gap-3 w-full px-4 py-3.5 hover:bg-surface-muted active:bg-surface-muted/80 transition-colors border-b border-surface-border last:border-0 text-left"+ >+ {item.image_url ? (+ <img src={item.image_url} alt="" className="w-11 h-11 rounded-xl object-cover flex-shrink-0 border border-surface-border" />+ ) : (+ <div className="w-11 h-11 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center flex-shrink-0">+ <Utensils className="w-5 h-5 text-tx-muted" />+ </div>+ )}+ <div className="flex-1 min-w-0">+ <p className="text-sm font-semibold text-tx-primary truncate">{item.name}</p>+ {item.brand && <p className="text-xs text-tx-muted truncate mt-0.5">{item.brand}</p>}+ <div className="flex items-center gap-1.5 mt-1 flex-wrap">+ <span className="text-xs font-semibold text-tx-secondary tabular-nums">{Math.round(item.calories)} kcal</span>+ <span className="text-[10px] text-tx-muted">·</span>+ <span className="text-xs text-emerald-400 tabular-nums">{item.protein.toFixed(0)}g P</span>+ <span className="text-[10px] text-tx-muted">·</span>+ <span className="text-xs text-amber-400 tabular-nums">{item.carbs.toFixed(0)}g C</span>+ <span className="text-[10px] text-tx-muted">·</span>+ <span className="text-xs text-violet-400 tabular-nums">{item.fat.toFixed(0)}g F</span>+ {item.serving_size && (+ <>+ <span className="text-[10px] text-tx-muted">·</span>+ <span className="text-[10px] text-tx-muted">{item.serving_size}</span>+ </>+ )}+ </div>+ </div>+ <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />+ </button>+ )+}++export default function LogFood() {+ const navigate = useNavigate()+ const [searchParams] = useSearchParams()++ const editId = searchParams.get('edit') ? Number(searchParams.get('edit')) : null+ const initMeal = (searchParams.get('meal') ?? 'breakfast') as types.FoodLog['meal']+ const initDate = searchParams.get('date') ?? todayStr()++ const [phase, setPhase] = useState<Phase>('search')+ const [tab, setTab] = useState<SearchTab>('recent')+ const [query, setQuery] = useState('')+ const [searchResults, setSearchResults] = useState<types.FoodSearchResult[]>([])+ const [recentItems, setRecentItems] = useState<types.FoodSearchResult[]>([])+ const [savedFoods, setSavedFoods] = useState<types.SavedFood[]>([])+ const [searching, setSearching] = useState(false)+ const [searchError, setSearchError] = useState<string | null>(null)+ const [rateLimited, setRateLimited] = useState(false)++ const [selected, setSelected] = useState<types.FoodSearchResult | null>(null)+ const [servings, setServings] = useState(1)+ const [meal, setMeal] = useState<types.FoodLog['meal']>(initMeal)+ const [date, setDate] = useState(initDate)+ const [saveToMyFoods, setSaveToMyFoods] = useState(false)+ const [saving, setSaving] = useState(false)+ const [saveError, setSaveError] = useState<string | null>(null)++ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const searchInputRef = useRef<HTMLInputElement>(null)++ useEffect(() => {+ if (!editId) return+ foodAPI.get(editId).then(entry => {+ setSelected(entryToResult(entry))+ setServings(entry.servings || 1)+ setMeal(entry.meal)+ setDate(entry.logged_at.slice(0, 10))+ setPhase('detail')+ }).catch(() => navigate('/food', { replace: true }))+ }, [editId, navigate])++ useEffect(() => {+ foodAPI.list(todayStr()).then(logs => {+ const seen = new Set<string>()+ const items: types.FoodSearchResult[] = []+ for (const log of (logs || [])) {+ const key = log.name.toLowerCase()+ if (!seen.has(key)) {+ seen.add(key)+ items.push(entryToResult(log))+ if (items.length >= 10) break+ }+ }+ setRecentItems(items)+ }).catch(() => {})+ savedFoodsAPI.list().then(setSavedFoods).catch(() => {})+ }, [])++ useEffect(() => {+ if (tab !== 'all') return+ if (debounceRef.current) clearTimeout(debounceRef.current)+ if (!query.trim()) { setSearchResults([]); return }+ debounceRef.current = setTimeout(async () => {+ setSearching(true)+ setSearchError(null)+ setRateLimited(false)+ try {+ setSearchResults(await foodAPI.search(query.trim()) ?? [])+ } catch (err: any) {+ if (err?.response?.status === 429) setRateLimited(true)+ else setSearchError('Food search unavailable — enter details manually')+ setSearchResults([])+ } finally {+ setSearching(false)+ }+ }, 300)+ return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }+ }, [query, tab])++ const selectResult = (result: types.FoodSearchResult) => {+ setSelected(result)+ setServings(1)+ setPhase('detail')+ }++ const handleBarcodeResult = async (code: string) => {+ setPhase('search')+ try {+ selectResult(await foodAPI.barcode(code))+ } catch (err: any) {+ if (err?.response?.status === 404) {+ selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'manual' })+ } else {+ setSearchError('Product not found — enter details manually')+ }+ }+ }++ const handleLog = async () => {+ if (!selected || saving) return+ setSaving(true)+ setSaveError(null)+ try {+ const payload = {+ name: selected.name || 'Custom entry',+ meal,+ calories: +(selected.calories * servings).toFixed(1),+ protein: +(selected.protein * servings).toFixed(1),+ carbs: +(selected.carbs * servings).toFixed(1),+ fat: +(selected.fat * servings).toFixed(1),+ fiber: +((selected.fiber ?? 0) * servings).toFixed(1),+ servings,+ serving_size: selected.serving_size ?? '',+ image_url: selected.image_url ?? '',+ logged_at: dayToIsoNoon(date),+ }+ if (editId) {+ await foodAPI.update(editId, payload)+ } else {+ await foodAPI.log(payload)+ if (saveToMyFoods) {+ await savedFoodsAPI.create({+ name: selected.name, brand: selected.brand ?? '',+ calories: selected.calories, protein: selected.protein,+ carbs: selected.carbs, fat: selected.fat, fiber: selected.fiber ?? 0,+ serving_size: selected.serving_size ?? '',+ }).catch(() => {})+ }+ }+ navigate('/food', { replace: true })+ } catch (err: any) {+ setSaveError(err?.response?.data?.error || 'Failed to save')+ setSaving(false)+ }+ }++ if (phase === 'scan') {+ return (+ <BarcodeScanner+ onResult={handleBarcodeResult}+ onClose={() => setPhase('search')}+ />+ )+ }++ const cal = selected ? Math.round(selected.calories * servings) : 0+ const pro = selected ? +(selected.protein * servings).toFixed(1) : 0+ const carb = selected ? +(selected.carbs * servings).toFixed(1) : 0+ const fat_ = selected ? +(selected.fat * servings).toFixed(1) : 0+ const fib = selected ? +((selected.fiber ?? 0) * servings).toFixed(1) : 0+ const quickAddCals = /^\d+(\.\d+)?$/.test(query.trim()) ? Number(query.trim()) : null++ return (+ <div className="animate-slide-up flex flex-col min-h-0">+ {/* Header with breadcrumb */}+ <div className="flex items-center gap-3 mb-5">+ <button+ onClick={() => phase === 'detail' && !editId ? setPhase('search') : navigate(-1)}+ className="w-10 h-10 flex items-center justify-center rounded-xl hover:bg-surface-muted active:scale-95 transition-all flex-shrink-0"+ >+ <ArrowLeft className="w-5 h-5 text-tx-muted" />+ </button>+ <div className="flex-1 min-w-0">+ {phase === 'detail' && selected ? (+ <>+ <div className="flex items-center gap-1.5 text-xs text-tx-muted mb-0.5">+ <span>{editId ? 'Edit Food' : 'Log Food'}</span>+ <ChevronRight className="w-3 h-3" />+ <span className="text-tx-secondary">Details</span>+ </div>+ <h1 className="font-display font-bold text-xl text-tx-primary truncate">+ {selected.name || 'New Entry'}+ </h1>+ {selected.brand && <p className="text-xs text-tx-muted mt-0.5">{selected.brand}</p>}+ </>+ ) : (+ <h1 className="font-display font-bold text-2xl text-tx-primary">Log Food</h1>+ )}+ </div>+ </div>++ {/* Search phase */}+ {phase === 'search' && (+ <div className="space-y-4">+ {/* Search input + scan button */}+ <div className="flex items-center gap-2">+ <div className="flex-1 relative">+ <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4.5 h-4.5 text-tx-muted pointer-events-none" />+ <input+ ref={searchInputRef}+ autoFocus+ type="text"+ value={query}+ onChange={e => { setQuery(e.target.value); if (e.target.value.trim()) setTab('all') }}+ placeholder="Search food…"+ className="input pl-10 pr-10 w-full h-12 text-base"+ />+ {query && (+ <button+ onClick={() => { setQuery(''); searchInputRef.current?.focus() }}+ className="absolute right-3 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full bg-surface-muted flex items-center justify-center hover:bg-surface-overlay transition-colors"+ >+ <X className="w-3.5 h-3.5 text-tx-muted" />+ </button>+ )}+ </div>+ <button+ onClick={() => setPhase('scan')}+ className="flex items-center gap-1.5 px-3.5 h-12 rounded-xl bg-surface-muted hover:bg-surface-overlay border border-surface-border text-tx-secondary hover:text-tx-primary transition-colors flex-shrink-0"+ aria-label="Scan barcode"+ >+ <Scan className="w-5 h-5" />+ <span className="text-xs font-medium">Scan</span>+ </button>+ </div>++ {/* Tabs */}+ <SegmentedControl+ options={[+ { value: 'recent', label: 'Recent' },+ { value: 'myfoods', label: 'My Foods' },+ { value: 'all', label: 'Search' },+ ] as const}+ value={tab}+ onChange={setTab}+ />++ {rateLimited && (+ <div className="flex items-center gap-2 rounded-xl border border-amber-500/20 bg-amber-500/10 px-3.5 py-3 text-xs text-amber-400">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ Too many requests — wait a moment and try again+ </div>+ )}+ {searchError && (+ <div className="flex items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 px-3.5 py-3 text-xs text-error-400">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ {searchError}+ </div>+ )}++ {/* Results */}+ <div className="card overflow-hidden">+ {tab === 'all' && quickAddCals !== null && (+ <button+ onClick={() => selectResult({ name: `${quickAddCals} kcal`, calories: quickAddCals, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'off' })}+ className="flex items-center gap-3 w-full px-4 py-3.5 hover:bg-surface-muted transition-colors border-b border-surface-border"+ >+ <div className="w-11 h-11 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">+ <Zap className="w-5 h-5 text-brand-500" />+ </div>+ <div className="flex-1 text-left min-w-0">+ <p className="text-sm font-semibold text-tx-primary">Quick add {quickAddCals} kcal</p>+ <p className="text-xs text-tx-muted mt-0.5">No macro breakdown</p>+ </div>+ <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />+ </button>+ )}++ {tab === 'recent' && (+ recentItems.length === 0+ ? (+ <div className="px-4 py-14 text-center">+ <Utensils className="w-8 h-8 text-tx-muted opacity-30 mx-auto mb-2" />+ <p className="text-sm text-tx-muted">No recent items today</p>+ <p className="text-xs text-tx-muted mt-1 opacity-60">Search or scan to log food</p>+ </div>+ )+ : recentItems.map((item) => <FoodResultRow key={`${item.name}-${item.calories}`} item={item} onClick={() => selectResult(item)} />)+ )}++ {tab === 'myfoods' && (+ savedFoods.length === 0+ ? (+ <div className="px-4 py-14 text-center">+ <Bookmark className="w-8 h-8 text-tx-muted opacity-30 mx-auto mb-2" />+ <p className="text-sm text-tx-muted">No saved foods yet</p>+ <p className="text-xs text-tx-muted mt-1 opacity-60">Save foods while logging to find them here</p>+ </div>+ )+ : savedFoods.map(sf => <FoodResultRow key={sf.id} item={savedToResult(sf)} onClick={() => selectResult(savedToResult(sf))} />)+ )}++ {tab === 'all' && !query.trim() && (+ <div className="px-4 py-14 text-center">+ <Search className="w-8 h-8 text-tx-muted opacity-30 mx-auto mb-2" />+ <p className="text-sm text-tx-muted">Search millions of foods</p>+ <p className="text-xs text-tx-muted mt-1 opacity-60">Or scan a barcode</p>+ </div>+ )}+ {tab === 'all' && query.trim() && searching && (+ <div className="px-4 py-14 text-center text-sm text-tx-muted">Searching…</div>+ )}+ {tab === 'all' && query.trim() && !searching && searchResults.length === 0 && !searchError && !rateLimited && (+ <div className="px-4 py-14 text-center space-y-3">+ <p className="text-sm text-tx-muted">No results for "{query}"</p>+ <button+ onClick={() => selectResult({ name: query.trim(), calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'off' })}+ className="btn-secondary text-xs"+ >+ + Enter "{query.trim()}" manually+ </button>+ </div>+ )}+ {tab === 'all' && !searching && searchResults.map((item) => (+ <FoodResultRow key={`${item.name}-${item.calories}`} item={item} onClick={() => selectResult(item)} />+ ))}+ </div>+ </div>+ )}++ {/* Detail phase */}+ {phase === 'detail' && selected && (+ <div className="space-y-4 pb-32">+ {saveError && (+ <div className="alert-error">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ <span>{saveError}</span>+ </div>+ )}++ {/* Food hero + macros */}+ <div className="card overflow-hidden">+ {/* Image or placeholder */}+ {selected.image_url ? (+ <img+ src={selected.image_url}+ alt={selected.name}+ className="w-full h-52 object-cover"+ onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}+ />+ ) : (+ <div className="w-full h-32 bg-surface-muted border-b border-surface-border flex items-center justify-center">+ <Utensils className="w-10 h-10 text-tx-muted opacity-20" />+ </div>+ )}++ <div className="p-5">+ {/* Calorie hero */}+ <div className="flex items-end justify-between mb-5">+ <div>+ <div className="flex items-baseline gap-1.5">+ <span className="text-5xl font-bold tabular-nums text-tx-primary leading-none">{cal}</span>+ <span className="text-sm text-tx-muted">kcal</span>+ </div>+ {selected.serving_size && (+ <p className="text-xs text-tx-muted mt-1">+ per {servings === 1 ? '' : `${servings} × `}{selected.serving_size}+ </p>+ )}+ </div>+ {/* Macro composition mini-bars */}+ {(pro + carb + fat_) > 0 && (+ <div className="flex flex-col gap-1 items-end w-20 flex-shrink-0">+ {[+ { label: 'P', value: pro, color: MACRO_COLORS.protein },+ { label: 'C', value: carb, color: MACRO_COLORS.carbs },+ { label: 'F', value: fat_, color: MACRO_COLORS.fat },+ ].map(m => {+ const total = pro + carb + fat_+ const pct = total > 0 ? Math.round((m.value / total) * 100) : 0+ return (+ <div key={m.label} className="flex items-center gap-1.5 w-full">+ <span className="text-[10px] text-tx-muted w-3 text-right flex-shrink-0">{m.label}</span>+ <div className="flex-1 h-1.5 bg-surface-muted rounded-full overflow-hidden">+ <div className="h-full rounded-full transition-all duration-500" style={{ width: `${pct}%`, background: m.color }} />+ </div>+ <span className="text-[10px] tabular-nums w-6 text-right flex-shrink-0" style={{ color: m.color }}>{pct}%</span>+ </div>+ )+ })}+ </div>+ )}+ </div>++ {/* Macro grid */}+ <div className="grid grid-cols-4 gap-2">+ {[+ { label: 'Protein', value: pro, color: 'text-emerald-400', bg: 'bg-emerald-500/10 border-emerald-500/20' },+ { label: 'Carbs', value: carb, color: 'text-amber-400', bg: 'bg-amber-500/10 border-amber-500/20' },+ { label: 'Fat', value: fat_, color: 'text-violet-400', bg: 'bg-violet-500/10 border-violet-500/20' },+ { label: 'Fiber', value: fib, color: 'text-tx-secondary', bg: 'bg-surface-muted border-surface-border' },+ ].map(m => (+ <div key={m.label} className={`rounded-xl border p-2.5 text-center ${m.bg}`}>+ <p className={`text-sm font-bold tabular-nums ${m.color}`}>{m.value}g</p>+ <p className="text-[10px] text-tx-muted mt-0.5">{m.label}</p>+ </div>+ ))}+ </div>+ </div>+ </div>++ {/* Servings */}+ <div className="card p-4 space-y-3">+ <div className="flex items-baseline gap-2">+ <label className="label">Servings</label>+ {selected.serving_size && (+ <span className="text-xs text-tx-muted">({selected.serving_size} each)</span>+ )}+ </div>+ <div className="flex items-center gap-3">+ <IconButton icon={Minus} variant="secondary" size="lg" label="Decrease servings" onClick={() => setServings(s => Math.max(0.5, +(s - 0.5).toFixed(1)))} />+ <input+ type="number"+ value={servings}+ onChange={e => setServings(Math.max(0.5, Number(e.target.value) || 1))}+ step="0.5" min="0.5"+ className="input text-center flex-1 h-12 text-lg font-semibold tabular-nums"+ />+ <IconButton icon={Plus} variant="secondary" size="lg" label="Increase servings" onClick={() => setServings(s => +(s + 0.5).toFixed(1))} />+ </div>+ </div>++ {/* Log to: meal + when */}+ <div className="card p-4 space-y-5">+ {/* Meal */}+ <div className="space-y-3">+ <label className="label">Meal</label>+ <div className="grid grid-cols-2 gap-2">+ {MEALS.map(m => {+ const MealIcon = MEAL_ICONS[m]+ const iconColor = MEAL_COLORS[m]+ const active = meal === m+ return (+ <button+ key={m}+ onClick={() => setMeal(m)}+ className={`flex items-center gap-2.5 px-3.5 py-3 rounded-xl border font-medium text-sm transition-all ${+ active+ ? 'bg-brand-500/10 border-brand-500/40 text-tx-primary'+ : 'bg-surface-muted border-surface-border text-tx-secondary hover:text-tx-primary hover:bg-surface-overlay'+ }`}+ >+ <MealIcon className={`w-4 h-4 flex-shrink-0 ${active ? iconColor : 'text-tx-muted'}`} />+ {MEAL_LABELS[m]}+ </button>+ )+ })}+ </div>+ </div>++ <div className="border-t border-surface-border" />++ <DateInput label="When" value={date} onChange={setDate} max={todayStr()} />+ </div>++ {/* Save to My Foods toggle — hidden in edit mode */}+ {!editId && <button+ type="button"+ onClick={() => setSaveToMyFoods(v => !v)}+ className="flex items-center gap-3 w-full card p-4 hover:bg-surface-muted/50 transition-colors"+ >+ <div className={`relative w-11 h-6 rounded-full border transition-colors flex-shrink-0 ${saveToMyFoods ? 'bg-brand-500 border-brand-500' : 'bg-surface-muted border-surface-border'}`}>+ <div className={`absolute top-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${saveToMyFoods ? 'translate-x-5' : 'translate-x-0.5'}`} />+ </div>+ <div className="flex items-center gap-2 flex-1">+ {saveToMyFoods+ ? <BookmarkCheck className="w-4 h-4 text-brand-500" />+ : <Bookmark className="w-4 h-4 text-tx-muted" />+ }+ <span className="text-sm font-medium text-tx-secondary">Save to My Foods</span>+ </div>+ </button>}+ </div>+ )}++ {/* Sticky log button — detail phase only */}+ {phase === 'detail' && selected && (+ <div className="fixed bottom-0 inset-x-0 p-4 bg-surface-base/95 backdrop-blur-sm border-t border-surface-border safe-area-bottom">+ <button+ onClick={handleLog}+ disabled={saving}+ className="btn-primary btn-lg w-full"+ >+ {saving ? 'Saving…' : editId ? 'Save Changes' : 'Log Food'}+ </button>+ </div>+ )}+ </div>+ )+}diff --git a/web/src/pages/Programs.tsx b/web/src/pages/Programs.tsxindex 4af63d6..f8d5e2e 100644--- a/web/src/pages/Programs.tsx+++ b/web/src/pages/Programs.tsx@@ -4,6 +4,7 @@ import { format } from 'date-fns'import { BookOpen, Plus, Dumbbell, Edit2, Trash2, Search, Play, ChevronRight, MoreVertical } from 'lucide-react'import { useNavigate } from 'react-router-dom'import Loading from '../components/Loading'+import PageHeader from '../components/ui/PageHeader'import { useServerInfiniteList } from '../hooks/useServerInfiniteList'import { programAPI } from '../services/api'import { useWorkoutSession } from '../stores/workoutSession'@@ -243,15 +244,15 @@ export default function Programs() {return (<div className="space-y-5 animate-slide-up">- <div className="flex justify-between items-center">- <div>- <h1 className="font-display font-bold text-2xl text-tx-primary">Programs</h1>- <p className="text-tx-muted text-sm mt-0.5">Reusable workout templates</p>- </div>- <button onClick={() => navigate('/programs/new')} className="btn-primary btn-md">- <Plus className="w-4 h-4" /> New Program- </button>- </div>+ <PageHeader+ title="Programs"+ subtitle="Reusable workout templates"+ action={+ <button onClick={() => navigate('/programs/new')} className="btn-primary btn-sm">+ <Plus className="w-4 h-4" /> New Program+ </button>+ }+ /><div className="grid grid-cols-2 gap-3">{[diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsxindex 4b2574b..4d87d76 100644--- a/web/src/pages/Settings.tsx+++ b/web/src/pages/Settings.tsx@@ -5,6 +5,7 @@ import { useTheme } from '../hooks/useTheme'import { exerciseAPI } from '../services/api'import * as types from '../types'import { HelpTip } from '../components/Tooltip'+import PageHeader from '../components/ui/PageHeader'import {User, Shield, Target, Moon, Sun, Server, LogOut, Trash2, ChevronRight, Check, AlertCircle, Loader,Dumbbell, RefreshCw,@@ -143,11 +144,7 @@ export default function Settings() {return (<div className="space-y-5 animate-slide-up max-w-2xl">- {/* Header */}- <div>- <h1 className="font-display font-bold text-2xl text-tx-primary">Settings</h1>- <p className="text-tx-muted text-sm mt-0.5">Preferences and account configuration</p>- </div>+ <PageHeader title="Settings" subtitle="Preferences and account configuration" />{error && (<div className="alert-error">diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsxindex 1a81e35..37352ca 100644--- a/web/src/pages/Weight.tsx+++ b/web/src/pages/Weight.tsx@@ -4,6 +4,8 @@ import { format, subDays } from 'date-fns'import { Link } from 'react-router-dom'import { HelpTip } from '../components/Tooltip'import Loading from '../components/Loading'+import PageHeader from '../components/ui/PageHeader'+import DateInput from '../components/ui/DateInput'import PeriodSelector from '../components/PeriodSelector'import WeightInput from '../components/WeightInput'import { useServerInfiniteList } from '../hooks/useServerInfiniteList'@@ -350,16 +352,11 @@ export default function Weight() {return (<div className="space-y-5 animate-slide-up">- {/* Header */}- <div className="flex justify-between items-center">- <div>- <h1 className="font-display font-bold text-2xl text-tx-primary">Weight</h1>- <p className="text-tx-muted text-sm mt-0.5">Track your body weight over time</p>- </div>- <span className="badge-brand">- <Calendar className="w-3 h-3" /> {wUnit}- </span>- </div>+ <PageHeader+ title="Weight"+ subtitle="Track your body weight over time"+ action={<span className="badge-brand"><Calendar className="w-3 h-3" /> {wUnit}</span>}+ />{error && (<div className="alert-error" role="alert" aria-live="polite">@@ -400,13 +397,7 @@ export default function Weight() {<X className="w-3.5 h-3.5 text-tx-muted" /></button></div>- <input- type="date"- value={newDate}- onChange={e => setNewDate(e.target.value)}- max={todayStr()}- className="input"- />+ <DateInput value={newDate} onChange={setNewDate} max={todayStr()} /><inputtype="text"value={newNotes}diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsxindex 06c9b56..1bf82b8 100644--- a/web/src/pages/Workouts.tsx+++ b/web/src/pages/Workouts.tsx@@ -4,6 +4,8 @@ import { format } from 'date-fns'import { Dumbbell, Plus, Clock, Search, AlertCircle, Edit2, Trash2, TrendingUp, ChevronRight, MoreVertical } from 'lucide-react'import { useNavigate } from 'react-router-dom'import Loading from '../components/Loading'+import EmptyState from '../components/ui/EmptyState'+import PageHeader from '../components/ui/PageHeader'import { useServerInfiniteList } from '../hooks/useServerInfiniteList'import { workoutAPI } from '../services/api'import { useSettingsStore, weightShort, lbsToDisplay } from '../stores/settings'@@ -61,12 +63,10 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on</div></div><div className="flex items-center gap-2">- <button onClick={() => setConfirming(false)}- className="px-3 py-1.5 text-xs bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">+ <button onClick={() => setConfirming(false)} className="btn-secondary btn-sm">Cancel</button>- <button onClick={handleDelete} disabled={deleting}- className="px-3 py-1.5 text-xs bg-error-500 hover:bg-error-600 disabled:opacity-50 text-white rounded-lg transition-colors font-medium flex items-center gap-1">+ <button onClick={handleDelete} disabled={deleting} className="btn-danger-solid btn-sm disabled:opacity-50"><Trash2 className="w-3 h-3" />{deleting ? 'Deleting…' : 'Delete'}</button>@@ -229,16 +229,15 @@ export default function Workouts() {return (<div className="space-y-5 animate-slide-up">- {/* Header */}- <div className="flex justify-between items-center">- <div>- <h1 className="font-display font-bold text-2xl text-tx-primary">Workouts</h1>- <p className="text-tx-muted text-sm mt-0.5">Track and review your training sessions</p>- </div>- <button onClick={() => navigate('/workouts/new')} className="btn-primary btn-md">- <Plus className="w-4 h-4" /> Log Workout- </button>- </div>+ <PageHeader+ title="Workouts"+ subtitle="Track and review your training sessions"+ action={+ <button onClick={() => navigate('/workouts/new')} className="btn-primary btn-sm">+ <Plus className="w-4 h-4" /> Log Workout+ </button>+ }+ />{/* Summary */}<div className="grid grid-cols-3 gap-3">@@ -273,13 +272,11 @@ export default function Workouts() {{/* Workout list */}<div className="space-y-2">{workouts.length === 0 && !loading ? (- <div className="empty-state">- <div className="w-12 h-12 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center mb-4">- <Dumbbell className="w-6 h-6 text-tx-muted" />- </div>- <p className="text-sm font-medium text-tx-primary mb-1">No workouts found</p>- <p className="text-xs text-tx-muted">{search ? 'Try a different search' : 'Log a workout to get started'}</p>- </div>+ <EmptyState+ icon={Dumbbell}+ title="No workouts found"+ subtitle={search ? 'Try a different search' : 'Log a workout to get started'}+ />) : (<>{workouts.map(w => <WorkoutCard key={w.id} workout={w}diff --git a/web/src/services/api.ts b/web/src/services/api.tsindex 3e4f3b9..56ca091 100644--- a/web/src/services/api.ts+++ b/web/src/services/api.ts@@ -117,10 +117,21 @@ export const weightAPI = {}export const foodAPI = {- list: (date?: string) => api.get<{ data: types.FoodLog[] }>('/food', { params: { date } }).then(res => unwrap(res)),- log: (data: any) => api.post<{ data: types.FoodLog }>('/food', data).then(res => unwrap(res)),- delete: (id: number) => api.delete(`/food/${id}`),- stats: (date?: string) => api.get<{ data: types.DailyStats }>('/food/stats', { params: { date } }).then(res => unwrap(res)),+ list: (date?: string) => api.get<{ data: types.FoodLog[] }>('/food', { params: { date } }).then(res => unwrap(res)),+ log: (data: any) => api.post<{ data: types.FoodLog }>('/food', data).then(res => unwrap(res)),+ get: (id: number) => api.get<{ data: types.FoodLog }>(`/food/${id}`).then(res => unwrap(res)),+ update: (id: number, data: any) => api.patch<{ data: types.FoodLog }>(`/food/${id}`, data).then(res => unwrap(res)),+ delete: (id: number) => api.delete(`/food/${id}`),+ stats: (date?: string) => api.get<{ data: types.DailyStats }>('/food/stats', { params: { date } }).then(res => unwrap(res)),+ history: (days = 30) => api.get<{ data: types.FoodHistoryPoint[] }>('/food/history', { params: { days } }).then(res => unwrap(res)),+ search: (q: string, limit = 20) => api.get<{ data: types.FoodSearchResult[] }>('/food/search', { params: { q, limit } }).then(res => unwrap(res)),+ barcode: (code: string) => api.get<{ data: types.FoodSearchResult }>(`/food/barcode/${code}`).then(res => unwrap(res)),+}++export const savedFoodsAPI = {+ list: () => api.get<{ data: types.SavedFood[] }>('/food/saved').then(res => unwrap(res)),+ create: (data: any) => api.post<{ data: types.SavedFood }>('/food/saved', data).then(res => unwrap(res)),+ delete: (id: number) => api.delete(`/food/saved/${id}`),}export default apidiff --git a/web/src/types.ts b/web/src/types.tsindex fcdc75b..fee1002 100644--- a/web/src/types.ts+++ b/web/src/types.ts@@ -77,9 +77,11 @@ export interface FoodLog {protein: numbercarbs: numberfat: number+ fiber?: numberservings: numberserving_size?: stringbarcode?: string+ image_url?: stringlogged_at: stringcreated_at?: string}@@ -90,9 +92,44 @@ export interface DailyStats {total_protein: numbertotal_carbs: numbertotal_fat: number+ total_fiber: numberworkout_count: number}+export interface FoodSearchResult {+ name: string+ brand?: string+ calories: number+ protein: number+ carbs: number+ fat: number+ fiber: number+ serving_size: string+ image_url?: string+ source: 'off' | 'saved' | 'manual'+}++export interface SavedFood {+ id: number+ name: string+ brand?: string+ calories: number+ protein: number+ carbs: number+ fat: number+ fiber: number+ serving_size: string+ barcode?: string+}++export interface FoodHistoryPoint {+ date: string+ calories: number+ protein: number+ carbs: number+ fat: number+}+export interface WeightStats {latest: numberstarting: numberdiff --git a/web/src/utils/macroColors.ts b/web/src/utils/macroColors.tsnew file mode 100644index 0000000..6a37e6d--- /dev/null+++ b/web/src/utils/macroColors.ts@@ -0,0 +1 @@+export const MACRO_COLORS = { protein: '#10b981', carbs: '#f59e0b', fat: '#8b5cf6' } as constdiff --git a/web/tailwind.config.ts b/web/tailwind.config.tsindex 3d3dfcc..c2d248a 100644--- a/web/tailwind.config.ts+++ b/web/tailwind.config.ts@@ -47,7 +47,7 @@ export default {},success: { 400: '#4ade80', 500: '#22c55e', DEFAULT: '#22c55e' },warning: { 400: '#facc15', 500: '#eab308', DEFAULT: '#eab308' },- error: { 400: '#f87171', 500: '#ef4444', DEFAULT: '#ef4444' },+ error: { 400: '#f87171', 500: '#ef4444', 600: '#dc2626', 700: '#b91c1c', DEFAULT: '#ef4444' },},backgroundImage: {'gradient-brand': 'linear-gradient(135deg, #00b8d9 0%, #8b5cf6 100%)',diff --git a/web/vite.config.ts b/web/vite.config.tsindex 37ae4d9..c32c02e 100644--- a/web/vite.config.ts+++ b/web/vite.config.ts@@ -1,15 +1,22 @@import { defineConfig } from 'vite'import react from '@vitejs/plugin-react'+import basicSsl from '@vitejs/plugin-basic-ssl'-export default defineConfig({- plugins: [react()],+export default defineConfig(({ command }) => ({+ plugins: [+ react(),+ // Self-signed HTTPS so getUserMedia works on mobile LAN during dev.+ // Production HTTPS is handled by the reverse proxy (nginx/Caddy) — this never runs in builds.+ ...(command === 'serve' ? [basicSsl()] : []),+ ],server: {port: 5173,+ host: true, // expose to LAN for mobile testingproxy: {'/api': {target: 'http://localhost:3000',changeOrigin: true,- }- }- }-})+ },+ },+ },+}))