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.

Name Open Food Facts products in the reader's language (#203)

Carter00fb9433e260
diff --git a/backend/controllers/food.go b/backend/controllers/food.go
index 0ba8099..53af4e1 100644
--- a/backend/controllers/food.go
+++ b/backend/controllers/food.go
@@ -287,6 +287,46 @@ type offProduct struct {
ServingQuantity offFloat `json:"serving_quantity"`
ProductQuantityUnit string `json:"product_quantity_unit"`
ImageURL string `json:"image_url"`
+
+ // Names holds every product_name_<lc> OFF sent, keyed by <lc>.
+ Names map[string]string `json:"-"`
+}
+
+func (p *offProduct) UnmarshalJSON(data []byte) error {
+ type plain offProduct
+ if err := json.Unmarshal(data, (*plain)(p)); err != nil {
+ return err
+ }
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return err
+ }
+ for k, v := range raw {
+ lc, ok := strings.CutPrefix(k, "product_name_")
+ if !ok {
+ continue
+ }
+ var s string
+ if json.Unmarshal(v, &s) != nil {
+ continue
+ }
+ if p.Names == nil {
+ p.Names = map[string]string{}
+ }
+ p.Names[lc] = s
+ }
+ return nil
+}
+
+// name is the user's language, then English, then product_name, which is the main
+// language: whatever the packaging was entered in, hence last.
+func (p offProduct) name(lang string) string {
+ for _, s := range []string{p.Names[lang], p.Names["en"], p.ProductName} {
+ if s = strings.TrimSpace(s); s != "" {
+ return s
+ }
+ }
+ return ""
}
// A serving spelled in any volume unit means the product's figures are per 100 ml, not
@@ -323,7 +363,7 @@ type offNutrients struct {
FiberServing float64 `json:"fiber_serving"`
}
-func offProductToResult(p offProduct) models.FoodSearchResult {
+func offProductToResult(p offProduct, lang string) models.FoodSearchResult {
brand := strings.Join(p.Brands, ", ")
imageURL := p.ImageURL
if !strings.HasPrefix(imageURL, "https://") {
@@ -362,7 +402,7 @@ func offProductToResult(p offProduct) models.FoodSearchResult {
}
return models.FoodSearchResult{
- Name: p.ProductName,
+ Name: p.name(lang),
Brand: brand,
Calories: cal,
Protein: pro,
@@ -381,6 +421,9 @@ func offProductToResult(p offProduct) models.FoodSearchResult {
}
}
+// No cache sits in front of OFF. A future one must key on rawURL, which already decides
+// the response: a search URL carries the language (langs=, fields=), and a barcode URL
+// fetches every language and the name is picked afterwards.
func doOFFRequest(ctx context.Context, rawURL string) ([]byte, int, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
@@ -410,12 +453,20 @@ func (h *Handler) SearchFood(c *gin.Context) {
limit = l
}
+ lang := requestLanguage(c)
+ langs := lang
+ nameFields := "product_name,product_name_en"
+ if lang != "en" {
+ langs = lang + ",en"
+ nameFields += ",product_name_" + lang
+ }
+
start := time.Now()
searchURL := fmt.Sprintf(
- "https://search.openfoodfacts.org/search?q=%s&lang=en&cc=world&page_size=%d&page=1&fields=code,product_name,brands,nutriments,serving_size,image_url",
- url.QueryEscape(q), limit,
+ "https://search.openfoodfacts.org/search?q=%s&langs=%s&cc=world&page_size=%d&page=1&fields=code,%s,brands,nutriments,serving_size,image_url",
+ url.QueryEscape(q), langs, limit, nameFields,
)
- log.Printf("[food/search] OFF request: q=%q limit=%d", q, limit)
+ log.Printf("[food/search] OFF request: q=%q limit=%d lang=%q", q, limit, lang)
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
@@ -464,10 +515,11 @@ func (h *Handler) SearchFood(c *gin.Context) {
}
results := make([]models.FoodSearchResult, 0, len(products))
for _, p := range products {
- if p.ProductName == "" {
+ r := offProductToResult(p, lang)
+ if r.Name == "" {
continue
}
- results = append(results, offProductToResult(p))
+ results = append(results, r)
}
utils.OK(c, results)
}
@@ -487,9 +539,10 @@ func (h *Handler) LookupBarcode(c *gin.Context) {
return
}
+ lang := requestLanguage(c)
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)
+ log.Printf("[food/barcode] OFF request: code=%q lang=%q", code, lang)
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
@@ -528,12 +581,13 @@ func (h *Handler) LookupBarcode(c *gin.Context) {
return
}
- if !strings.HasPrefix(parsed.Status, "success") || parsed.Product.ProductName == "" {
+ r := offProductToResult(parsed.Product, lang)
+ if !strings.HasPrefix(parsed.Status, "success") || r.Name == "" {
utils.Fail(c, utils.CodeProductNotFound, nil)
return
}
- utils.OK(c, offProductToResult(parsed.Product))
+ utils.OK(c, r)
}
// ─── Saved Foods ──────────────────────────────────────────────────────────────
diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.go
index 417efce..0b51d2f 100644
--- a/backend/controllers/food_test.go
+++ b/backend/controllers/food_test.go
@@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
+ "net/url"
"strings"
"testing"
"time"
@@ -745,7 +746,7 @@ func TestOffProductToResult_usesServingWhenAvailable(t *testing.T) {
},
ImageURL: "https://images.openfoodfacts.org/jif.jpg",
}
- r := offProductToResult(p)
+ r := offProductToResult(p, "en")
if r.Calories != 190 {
t.Errorf("expected per-serving calories 190, got %v", r.Calories)
@@ -764,7 +765,7 @@ func TestOffProductToResult_fallsBackTo100g(t *testing.T) {
Nutriments: offNutrients{EnergyKcal100g: 265, Proteins100g: 9, Carbohydrates100g: 49, Fat100g: 3},
// No serving_size, no _serving nutriments
}
- r := offProductToResult(p)
+ r := offProductToResult(p, "en")
if r.Calories != 265 {
t.Errorf("expected per-100g calories 265, got %v", r.Calories)
@@ -789,7 +790,7 @@ func TestOffProductToResult_liquidFallbackIsPer100ml(t *testing.T) {
// openfoodfacts-server#7768 tracks, and the one the reporter hit.
Nutriments: offNutrients{EnergyKcal100g: 800, Fat100g: 93.33},
}
- r := offProductToResult(p)
+ r := offProductToResult(p, "en")
if r.Calories != 800 {
t.Errorf("expected per-100 calories 800, got %v", r.Calories)
@@ -813,7 +814,7 @@ func TestOffProductToResult_carriesServingQuantityAndBarcode(t *testing.T) {
EnergyKcalServing: 120, FatServing: 14,
},
}
- r := offProductToResult(p)
+ r := offProductToResult(p, "en")
if r.Calories != 120 || r.Fat != 14 {
t.Errorf("expected the per-serving figures, got %v kcal %v fat", r.Calories, r.Fat)
@@ -836,7 +837,7 @@ func TestOffProductToResult_servingWithoutAQuantityStaysUnknown(t *testing.T) {
ServingSize: "12 fl oz",
Nutriments: offNutrients{EnergyKcal100g: 41, EnergyKcalServing: 145},
}
- r := offProductToResult(p)
+ r := offProductToResult(p, "en")
if r.ServingQuantity != 0 {
t.Errorf("expected an unknown quantity to stay 0, got %v", r.ServingQuantity)
@@ -908,7 +909,7 @@ func TestOffProductToResult_rejectsNonHTTPSImageURL(t *testing.T) {
ProductName: "Test",
ImageURL: "http://example.com/img.jpg", // http, not https
}
- r := offProductToResult(p)
+ r := offProductToResult(p, "en")
if r.ImageURL != "" {
t.Errorf("expected empty image_url for non-https, got %q", r.ImageURL)
}
@@ -919,7 +920,7 @@ func TestOffProductToResult_rejectsJavascriptImageURL(t *testing.T) {
ProductName: "Test",
ImageURL: "javascript:alert(1)",
}
- r := offProductToResult(p)
+ r := offProductToResult(p, "en")
if r.ImageURL != "" {
t.Errorf("expected empty image_url for javascript: URL, got %q", r.ImageURL)
}
@@ -930,7 +931,7 @@ func TestOffProductToResult_joinsMultipleBrands(t *testing.T) {
ProductName: "Cola",
Brands: offBrands{"Coca-Cola", "TCCC"},
}
- r := offProductToResult(p)
+ r := offProductToResult(p, "en")
if r.Brand != "Coca-Cola, TCCC" {
t.Errorf("expected joined brands, got %q", r.Brand)
}
@@ -1867,3 +1868,162 @@ func TestUpdateFoodLog_trimsNameAndBrand(t *testing.T) {
t.Errorf("updated entry is %q/%q, want trimmed", d["name"], d["brand"])
}
}
+
+// ─── Localised names ──────────────────────────────────────────────────────────
+
+func TestRequestLanguage(t *testing.T) {
+ cases := map[string]string{
+ "es": "es", "ES": "es", "en": "en", "pt-BR": "pt", "pt_BR": "pt",
+ "zh-Hant-TW": "zh", "": "en", "../x": "en", "e": "en", "español": "en",
+ "12": "en", "abcdefgh": "en",
+ }
+ for in, want := range cases {
+ c, _ := newContext(0, http.MethodGet, "/x?locale="+url.QueryEscape(in), nil)
+ if got := requestLanguage(c); got != want {
+ t.Errorf("locale %q: got %q, want %q", in, got, want)
+ }
+ }
+ c, _ := newContext(0, http.MethodGet, "/x", nil)
+ if got := requestLanguage(c); got != "en" {
+ t.Errorf("absent locale: got %q, want en", got)
+ }
+}
+
+func TestSearchFood_offURLCarriesLanguage(t *testing.T) {
+ const tail = "&cc=world&page_size=20&page=1&fields=code,product_name,product_name_en,"
+ const rest = "brands,nutriments,serving_size,image_url"
+ cases := []struct{ path, want string }{
+ {"/api/v1/food/search?q=leche&locale=es", "q=leche&langs=es,en" + tail + "product_name_es," + rest},
+ {"/api/v1/food/search?q=milk&locale=en", "q=milk&langs=en" + tail + rest},
+ {"/api/v1/food/search?q=milk", "q=milk&langs=en" + tail + rest},
+ {"/api/v1/food/search?q=milk&locale=" + url.QueryEscape("../x"), "q=milk&langs=en" + tail + rest},
+ {"/api/v1/food/search?q=pao&locale=pt-BR", "q=pao&langs=pt,en" + tail + "product_name_pt," + rest},
+ }
+ for _, tc := range cases {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ var gotPath, gotQuery string
+ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) {
+ gotPath, gotQuery = r.URL.Path, r.URL.RawQuery
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(`{"hits":[]}`))
+ })
+ c, w := newContext(uid, http.MethodGet, tc.path, nil)
+ th.SearchFood(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("%s: got %d", tc.path, w.Code)
+ }
+ if gotPath != "/search" || gotQuery != tc.want {
+ t.Errorf("%s:\n got %s?%s\nwant /search?%s", tc.path, gotPath, gotQuery, tc.want)
+ }
+ }
+}
+
+func TestOffProductName(t *testing.T) {
+ cases := []struct{ name, js, lang, want string }{
+ {"user language", `{"product_name":"Nutella pate","product_name_en":"Nutella","product_name_es":"Nutella crema"}`, "es", "Nutella crema"},
+ {"falls to en", `{"product_name":"Nutella pate","product_name_en":"Nutella"}`, "es", "Nutella"},
+ {"en over main", `{"product_name":"ผลิตภัณฑ์นม","product_name_en":"Homogenized Milk"}`, "en", "Homogenized Milk"},
+ {"main only", `{"product_name":"Leche"}`, "en", "Leche"},
+ {"blank lang falls through", `{"product_name":"Leche","product_name_es":" "}`, "es", "Leche"},
+ {"suffixed key is not a language", `{"product_name_fr_imported":"x","product_name":"y"}`, "fr", "y"},
+ {"null ignored", `{"product_name_de":null,"product_name":"z"}`, "de", "z"},
+ {"all empty", `{"product_name":"","product_name_en":""}`, "en", ""},
+ }
+ for _, tc := range cases {
+ var p offProduct
+ if err := json.Unmarshal([]byte(tc.js), &p); err != nil {
+ t.Fatalf("%s: decode: %v", tc.name, err)
+ }
+ if got := p.name(tc.lang); got != tc.want {
+ t.Errorf("%s: got %q, want %q", tc.name, got, tc.want)
+ }
+ }
+}
+
+func TestSearchFood_namesInRequestedLanguage(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(`{"hits":[
+ {"product_name":"Main1","product_name_en":"En1","product_name_es":"Es1"},
+ {"product_name":"Main2","product_name_en":"En2"},
+ {"product_name":"Main3"},
+ {"product_name":"","product_name_es":"Es4"},
+ {"product_name":"","product_name_en":""}
+ ]}`))
+ })
+
+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/search?q=x&locale=es", nil)
+ th.SearchFood(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("got %d", w.Code)
+ }
+ data := decodeResponse(t, w)["data"].([]any)
+ want := []string{"Es1", "En2", "Main3", "Es4"}
+ if len(data) != len(want) {
+ t.Fatalf("expected %d results, got %d", len(want), len(data))
+ }
+ for i, wn := range want {
+ if got := data[i].(map[string]any)["name"]; got != wn {
+ t.Errorf("hit %d: got %v, want %s", i, got, wn)
+ }
+ }
+}
+
+func TestLookupBarcode_localisedNameFromFullProduct(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ var gotPath, gotQuery string
+ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) {
+ gotPath, gotQuery = r.URL.Path, r.URL.RawQuery
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(`{"status":"success","product":{"code":"3017620406003","product_name":"Nutella pate","product_name_en":"Nutella","product_name_es":"Nutella crema","serving_size":"15 g","serving_quantity":15,"nutriments":{"energy-kcal_serving":80,"energy-kcal_100g":539}}}`))
+ })
+
+ for locale, want := range map[string]string{"es": "Nutella crema", "fr": "Nutella"} {
+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/3017620406003?locale="+locale, nil)
+ setParam(c, "code", "3017620406003")
+ th.LookupBarcode(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("%s: got %d", locale, w.Code)
+ }
+ if gotPath != "/api/v3/product/3017620406003.json" || gotQuery != "" {
+ t.Errorf("%s: OFF saw %s?%s, want the full product with no fields filter", locale, gotPath, gotQuery)
+ }
+ data := decodeResponse(t, w)["data"].(map[string]any)
+ if data["name"] != want {
+ t.Errorf("%s: name %v, want %s", locale, data["name"], want)
+ }
+ if data["calories"].(float64) != 80 {
+ t.Errorf("%s: calories %v, want per-serving 80", locale, data["calories"])
+ }
+ }
+}
+
+func TestLookupBarcode_nameOnlyInUserLanguage(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":"success","product":{"product_name":"","product_name_es":"Solo es"}}`))
+ })
+
+ for q, want := range map[string]int{"?locale=es": http.StatusOK, "": http.StatusNotFound} {
+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/012345678901"+q, nil)
+ setParam(c, "code", "012345678901")
+ th.LookupBarcode(c)
+ if w.Code != want {
+ t.Fatalf("%q: got %d, want %d", q, w.Code, want)
+ }
+ if want == http.StatusOK {
+ if n := decodeResponse(t, w)["data"].(map[string]any)["name"]; n != "Solo es" {
+ t.Errorf("%q: name %v", q, n)
+ }
+ }
+ }
+}
diff --git a/backend/controllers/locale.go b/backend/controllers/locale.go
new file mode 100644
index 0000000..04c37d0
--- /dev/null
+++ b/backend/controllers/locale.go
@@ -0,0 +1,28 @@
+package controllers
+
+import (
+ "regexp"
+ "strings"
+
+ "github.com/gin-gonic/gin"
+)
+
+// BCP 47 primary language subtags are 2-3 letters, and OpenFoodFacts keys its
+// languages by ISO 639-1 (es, fr, pt). The value is pasted into upstream URLs, so
+// it has to be letters only.
+var languageSubtagRe = regexp.MustCompile(`^[a-z]{2,3}$`)
+
+// requestLanguage reads the optional `locale` query param and reduces it to a
+// primary language subtag ("pt-BR" -> "pt"). Absent or malformed means "en".
+// Generic on purpose: other localised content reads its language here too.
+func requestLanguage(c *gin.Context) string {
+ raw := strings.TrimSpace(c.Query("locale"))
+ if i := strings.IndexAny(raw, "-_"); i >= 0 {
+ raw = raw[:i]
+ }
+ raw = strings.ToLower(raw)
+ if languageSubtagRe.MatchString(raw) {
+ return raw
+ }
+ return "en"
+}
diff --git a/docs/API_CHANGES.md b/docs/API_CHANGES.md
index 46c35b6..ad3a593 100644
--- a/docs/API_CHANGES.md
+++ b/docs/API_CHANGES.md
@@ -76,6 +76,19 @@ previously `BAD_REQUEST`, which no release shipped.
New codes may appear in later releases: treat an unknown `code` as "show `error`".
+## `GET /api/v1/food/search`, `GET /api/v1/food/barcode/:code` — optional `locale` names the product in the reader's language
+
+Both accept `?locale=<tag>` (`es`, `pt-BR`; only the primary language is used). Open Food Facts
+holds a name per language, and the server now asks for the reader's, then English, then the
+product's main name. A missing or malformed `locale` means `en`. The response shape is unchanged,
+but a caller that never sends `locale` can see a different name: English is now preferred over the
+product's main-language name, so a product whose `product_name` is Thai and whose English name is
+"Homogenized Milk" is now named the latter.
+
+Saving a favourite still matches on name and brand on the server, so a product saved without a
+`barcode` from a Spanish and an English search is two favourites. The shared client now sends the
+`barcode` when starring and matches on it first, which keeps barcoded products to one.
+
## `POST /api/v1/auth/register` — an address differing only in letter case is a duplicate
An address that differs from an existing account only in letter case (`[email protected]`
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index b4d5448..889eb4c 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -50,6 +50,22 @@ describe('foodAPI day windowing', () => {
})
})
+// Open Food Facts names a product in the language it was entered in. The server asks for
+// the reader's, so the client has to say which that is.
+describe('foodAPI search and barcode send the UI language', () => {
+ afterEach(() => i18n.changeLanguage('en'))
+
+ it.each(['en', 'es'])('sends locale=%s', async (lang) => {
+ await i18n.changeLanguage(lang)
+ const { client, calls } = captureClient()
+ await client.foodAPI.search('nutella', 5)
+ await client.foodAPI.barcode('3017620406003')
+ expect(calls[0].params).toEqual({ q: 'nutella', limit: 5, locale: lang })
+ expect(calls[1].url).toBe('/food/barcode/3017620406003')
+ expect(calls[1].params).toEqual({ locale: lang })
+ })
+})
+
// The offset must describe the instant being sent. A screen that re-picks the date
// derives a new instant in this zone and wants this zone's offset; a screen that
// resends the timestamp it loaded must keep the offset that instant was recorded with,
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index 6d808c9..ce9e01f 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -478,8 +478,8 @@ export function createClient(
delete: (id: number) => api.delete(`/food/${id}`),
stats: (date?: string) => api.get<{ data: types.DailyStats }>('/food/stats', { params: { date } }).then(unwrap),
history: (days = 30) => api.get<{ data: types.FoodHistoryPoint[] }>('/food/history', { params: { days } }).then(unwrap),
- search: (q: string, limit = 20) => api.get<{ data: types.FoodSearchResult[] }>('/food/search', { params: { q, limit } }).then(unwrap),
- barcode: (code: string) => api.get<{ data: types.FoodSearchResult }>(`/food/barcode/${code}`).then(unwrap),
+ search: (q: string, limit = 20) => api.get<{ data: types.FoodSearchResult[] }>('/food/search', { params: { q, limit, locale: i18n.resolvedLanguage } }).then(unwrap),
+ barcode: (code: string) => api.get<{ data: types.FoodSearchResult }>(`/food/barcode/${code}`, { params: { locale: i18n.resolvedLanguage } }).then(unwrap),
}
const savedFoodsAPI = {
diff --git a/packages/shared/src/hooks/useFavorites.ts b/packages/shared/src/hooks/useFavorites.ts
index 9bdcae4..d7508f2 100644
--- a/packages/shared/src/hooks/useFavorites.ts
+++ b/packages/shared/src/hooks/useFavorites.ts
@@ -86,6 +86,7 @@ export function useFavorites(api: SavedFoodsApi): Favorites {
calories: item.calories, protein: item.protein,
carbs: item.carbs, fat: item.fat, fiber: item.fiber ?? 0,
serving_size: item.serving_size ?? '',
+ barcode: item.barcode ?? '',
}
// Answer the tap at once and put it back if the server refuses: on gym wifi the round
// trip is seconds of a dead-looking star. `pending` stands in until the real id arrives.
diff --git a/packages/shared/src/utils/food.test.ts b/packages/shared/src/utils/food.test.ts
index 6ad3a88..c6d588a 100644
--- a/packages/shared/src/utils/food.test.ts
+++ b/packages/shared/src/utils/food.test.ts
@@ -100,6 +100,17 @@ describe('brand survives the log round-trip', () => {
})
describe('findSavedFood', () => {
+ // Same product saved under its Spanish name, searched under its English one.
+ it('matches on barcode even when the name is spelled differently', () => {
+ const list = [saved({ id: 9, name: 'Crema de cacahuete', barcode: '3017620406003' })]
+ expect(findSavedFood(list, { name: 'Peanut butter', brand: 'Tesco', barcode: '3017620406003' })?.id).toBe(9)
+ })
+
+ it('falls back to name and brand when the barcode matches nothing', () => {
+ const list = [saved({ id: 7, barcode: '111' })]
+ expect(findSavedFood(list, { name: 'Chicken Breast', brand: 'Tesco', barcode: '222' })?.id).toBe(7)
+ })
+
it('matches on name and brand', () => {
const list = [saved({ id: 7 })]
expect(findSavedFood(list, { name: 'Chicken Breast', brand: 'Tesco' })?.id).toBe(7)
diff --git a/packages/shared/src/utils/food.ts b/packages/shared/src/utils/food.ts
index f024da4..032b8bb 100644
--- a/packages/shared/src/utils/food.ts
+++ b/packages/shared/src/utils/food.ts
@@ -148,8 +148,14 @@ export function savedToResult(s: SavedFood): FoodSearchResult {
// brand, while a search result can carry undefined.
export function findSavedFood(
saved: SavedFood[],
- item: Pick<FoodSearchResult, 'name' | 'brand'>,
+ item: Pick<FoodSearchResult, 'name' | 'brand'> & { barcode?: string | null },
): SavedFood | undefined {
+ // A barcode names one product in every language; name+brand only matches while the
+ // name is spelled the way it was saved.
+ if (item.barcode) {
+ const byCode = saved.find(s => s.barcode === item.barcode)
+ if (byCode) return byCode
+ }
const name = normaliseFoodKey(item.name)
const brand = normaliseFoodKey(item.brand)
return saved.find(s => normaliseFoodKey(s.name) === name && normaliseFoodKey(s.brand) === brand)
diff --git a/web/src/hooks/useFavorites.test.ts b/web/src/hooks/useFavorites.test.ts
index 15e06fa..b57b400 100644
--- a/web/src/hooks/useFavorites.test.ts
+++ b/web/src/hooks/useFavorites.test.ts
@@ -35,6 +35,22 @@ describe('useFavorites epoch', () => {
})
})
+// The barcode is how the same product is recognised when a search names it in another
+// language, so the star has to save it.
+describe('useFavorites barcode', () => {
+ it('sends the barcode when starring, and finds the favourite by it under a different name', async () => {
+ const sent: Array<Record<string, unknown>> = []
+ const spanish: SavedFood = { ...OATS, id: 9, name: 'Copos de avena', barcode: '3560071006587' }
+ const api = { create: (d: Record<string, unknown>) => { sent.push(d); return Promise.resolve(spanish) }, delete: () => Promise.resolve() }
+ const { result } = renderHook(() => useFavorites(api))
+
+ await act(async () => { await result.current.toggle({ ...oats, name: 'Copos de avena', barcode: '3560071006587' }) })
+
+ expect(sent[0].barcode).toBe('3560071006587')
+ expect(result.current.favoriteOf({ ...oats, name: 'Oat flakes', barcode: '3560071006587' })?.id).toBe(9)
+ })
+})
+
// The star answers the tap at once; a refusal puts it back and says why.
describe('useFavorites optimistic toggle', () => {
const granola = { ...oats, name: 'Granola', brand: '' }