Skip to content

armgit / lyftr

Public Imported from GitHub
0

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

Normalise saved-food identity on read and on write (#142)

Carter96cfae249b1c
diff --git a/backend/controllers/food.go b/backend/controllers/food.go
index 968c82b..fed7f1e 100644
--- a/backend/controllers/food.go
+++ b/backend/controllers/food.go
@@ -70,6 +70,13 @@ func (h *Handler) LogFood(c *gin.Context) {
utils.BadRequest(c, err.Error())
return
}
+ // Same normalisation the favourites path applies, and for a reason that only exists
+ // since food_logs gained `brand`: the Recent tab matches logged entries against
+ // Favorites by name and brand, so an untrimmed entry misses the favourite it is —
+ // the star reads empty next to a food already starred. Before validation, so a
+ // whitespace-only name collapses to "" and the existing `required` rule rejects it.
+ req.Name = strings.TrimSpace(req.Name)
+ req.Brand = strings.TrimSpace(req.Brand)
if err := validate.Struct(req); err != nil {
utils.ValidationError(c, err)
return
@@ -126,6 +133,13 @@ func (h *Handler) UpdateFoodLog(c *gin.Context) {
utils.BadRequest(c, err.Error())
return
}
+ // Same normalisation the favourites path applies, and for a reason that only exists
+ // since food_logs gained `brand`: the Recent tab matches logged entries against
+ // Favorites by name and brand, so an untrimmed entry misses the favourite it is —
+ // the star reads empty next to a food already starred. Before validation, so a
+ // whitespace-only name collapses to "" and the existing `required` rule rejects it.
+ req.Name = strings.TrimSpace(req.Name)
+ req.Brand = strings.TrimSpace(req.Brand)
if err := validate.Struct(req); err != nil {
utils.ValidationError(c, err)
return
diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.go
index d9dae0a..2e3531d 100644
--- a/backend/controllers/food_test.go
+++ b/backend/controllers/food_test.go
@@ -1576,3 +1576,69 @@ func TestLogFood_roundTripsBrand(t *testing.T) {
t.Errorf("listed entry has brand %v, want Tesco", got)
}
}
+
+// The Recent tab matches logged entries against Favorites by name and brand, so a log
+// written with stray whitespace misses the favourite it came from — the star reads empty
+// next to a food already starred. Same normalisation as the favourites path.
+func TestLogFood_trimsNameAndBrand(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ body := map[string]any{
+ "name": " Oats ", "brand": " Quaker ", "meal": "breakfast",
+ "calories": 100.0, "servings": 1.0,
+ }
+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)
+ th.LogFood(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ d := decodeResponse(t, w)["data"].(map[string]any)
+ if d["name"].(string) != "Oats" {
+ t.Errorf("logged name = %q, want %q", d["name"], "Oats")
+ }
+ if d["brand"].(string) != "Quaker" {
+ t.Errorf("logged brand = %q, want %q", d["brand"], "Quaker")
+ }
+}
+
+// A whitespace-only name is not a name; `required` only rejects the empty string, so the
+// trim has to happen before validation for it to be caught.
+func TestLogFood_rejectsWhitespaceOnlyName(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ body := map[string]any{"name": " ", "meal": "breakfast", "calories": 100.0, "servings": 1.0}
+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)
+ th.LogFood(c)
+
+ if w.Code == http.StatusCreated {
+ t.Fatalf("a whitespace-only name was logged: %s", w.Body.String())
+ }
+ var count int
+ db.DB.QueryRow(`SELECT COUNT(*) FROM food_logs WHERE user_id = ?`, uid).Scan(&count)
+ if count != 0 {
+ t.Errorf("%d row(s) written for a rejected name", count)
+ }
+}
+
+func TestUpdateFoodLog_trimsNameAndBrand(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ id := insertFoodLog(t, uid, "Oats", "breakfast", 100, 5, 20, 2, time.Now())
+
+ body := map[string]any{
+ "name": " Rolled Oats ", "brand": " Quaker ", "meal": "breakfast",
+ "calories": 120.0, "servings": 1.0,
+ }
+ c, w := newContext(uid, http.MethodPut, "/api/v1/food/"+fmt.Sprint(id), body)
+ setParam(c, "id", fmt.Sprint(id))
+ th.UpdateFoodLog(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ d := decodeResponse(t, w)["data"].(map[string]any)
+ if d["name"].(string) != "Rolled Oats" || d["brand"].(string) != "Quaker" {
+ t.Errorf("updated entry is %q/%q, want trimmed", d["name"], d["brand"])
+ }
+}
diff --git a/packages/shared/src/utils/food.test.ts b/packages/shared/src/utils/food.test.ts
index 8740ad4..681e449 100644
--- a/packages/shared/src/utils/food.test.ts
+++ b/packages/shared/src/utils/food.test.ts
@@ -1,4 +1,4 @@
-import { entryToResult, findSavedFood, savedToResult, scaleServing } from './food'
+import { entryToResult, findSavedFood, normaliseFoodKey, savedToResult, scaleServing } from './food'
import type { FoodLog, SavedFood } from '../types'
const log = (over: Partial<FoodLog> = {}): FoodLog => ({
@@ -129,3 +129,43 @@ describe('findSavedFood', () => {
expect(findSavedFood([], { name: 'Chicken Breast', brand: 'Tesco' })).toBeUndefined()
})
})
+
+// The server trims before storing, so the client has to compare on the same terms —
+// otherwise a search result carrying "Oats " reads as different from the stored "Oats",
+// the star shows unfilled next to a food that is already favourited, and tapping it asks
+// the server to create a row it will refuse as a duplicate.
+describe('findSavedFood normalisation', () => {
+ const list = [saved({ id: 9, name: 'Oats', brand: 'Quaker' })]
+
+ it.each([
+ ['trailing space', 'Oats ', 'Quaker'],
+ ['leading space', ' Oats', 'Quaker'],
+ ['both ends', ' Oats ', 'Quaker'],
+ ['tab and newline', '\tOats\n', 'Quaker'],
+ ['padded brand', 'Oats', ' Quaker '],
+ ])('matches across %s', (_label, name, brand) => {
+ expect(findSavedFood(list, { name, brand })?.id).toBe(9)
+ })
+
+ // Case stays significant, matching the UNIQUE(user_id, name, brand) index. Folding it
+ // here would hide a favourite the server would happily create.
+ it('does not fold case', () => {
+ expect(findSavedFood(list, { name: 'oats', brand: 'Quaker' })).toBeUndefined()
+ })
+
+ it('still separates genuinely different brands', () => {
+ expect(findSavedFood(list, { name: 'Oats ', brand: 'Lidl' })).toBeUndefined()
+ })
+
+ it('treats a whitespace-only brand as unbranded', () => {
+ const unbranded = [saved({ id: 4, name: 'Water', brand: '' })]
+ expect(findSavedFood(unbranded, { name: 'Water', brand: ' ' })?.id).toBe(4)
+ })
+})
+
+describe('normaliseFoodKey', () => {
+ it('trims and tolerates undefined', () => {
+ expect(normaliseFoodKey(' Oats ')).toBe('Oats')
+ expect(normaliseFoodKey(undefined)).toBe('')
+ })
+})
diff --git a/packages/shared/src/utils/food.ts b/packages/shared/src/utils/food.ts
index f2bf7a6..b53d092 100644
--- a/packages/shared/src/utils/food.ts
+++ b/packages/shared/src/utils/food.ts
@@ -70,5 +70,19 @@ export function findSavedFood(
saved: SavedFood[],
item: Pick<FoodSearchResult, 'name' | 'brand'>,
): SavedFood | undefined {
- return saved.find(s => s.name === item.name && (s.brand ?? '') === (item.brand ?? ''))
+ const name = normaliseFoodKey(item.name)
+ const brand = normaliseFoodKey(item.brand)
+ return saved.find(s => normaliseFoodKey(s.name) === name && normaliseFoodKey(s.brand) === brand)
+}
+
+// The single definition of "the same food", client-side. It has to agree with the
+// server, which trims before storing — otherwise a search result carrying "Oats " reads
+// as different from the stored "Oats", the star shows unfilled next to a food that is
+// already favourited, and tapping it asks the server to create something it will refuse
+// as a duplicate.
+//
+// Trim only. Case is deliberately significant, matching the UNIQUE(user_id, name, brand)
+// index: folding it here would hide a favourite the server would happily create.
+export function normaliseFoodKey(value: string | undefined): string {
+ return (value ?? '').trim()
}