From eeca189b7faffea7a9ec6d2036130d08765fe661 Mon Sep 17 00:00:00 2001 From: bashynx Date: Mon, 26 Oct 2026 15:41:23 +0200 Subject: [PATCH] Food: all products, barcode prefixes, meals that follow their ingredients MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - "All products" lists what's here first (My foods, kept products, the food database), then Open Food Facts; if the archive can't be reached, what's here is still shown. A My food picked there is used as it is. - The start of a barcode (4+ digits) finds the products whose barcode starts with it: in the search box, in all products and in the server's search (an index range, so it stays fast). - A meal made with a changed food is worked out again, and so are meals made with that meal and their logged entries (db.follow_meals, app _followMeals). - Saving a food that didn't change writes nothing, so nothing is synced again. - Food search knows a few words in other languages: stomach / žalúdok / pipotă find gizzards, kurací / pui chicken, morčací / curcan turkey. - App 1.1.5 changelog entry. Co-Authored-By: Claude Opus 5.5 --- app/CHANGELOG.md | 10 +++ app/lib/health/food_archive.dart | 58 +++++++++++++--- app/lib/health/food_model.dart | 96 +++++++++++++++++++++------ app/lib/health/food_sheet.dart | 12 ++-- app/pubspec.yaml | 2 +- app/test/food_follow_test.dart | 18 +++++ dashboard/plugins/food/__init__.py | 57 ++++++++++++---- dashboard/plugins/food/db.py | 41 ++++++++++-- dashboard/plugins/food/fooddb.py | 32 +++++++-- dashboard/plugins/food/static/food.js | 15 +++-- server/src/food.php | 17 ++++- 11 files changed, 287 insertions(+), 71 deletions(-) diff --git a/app/CHANGELOG.md b/app/CHANGELOG.md index aaaa789..912a6e5 100644 --- a/app/CHANGELOG.md +++ b/app/CHANGELOG.md @@ -13,6 +13,16 @@ What changed in each published build of the app. `tool/publish.sh` shows the ent - The band's data goes with the phone's time zone, so the dashboard reads its times right without a setting. +## 1.1.5 — 2026-10-26 + +- Food: "All products" lists everything — My foods, the food database and products you kept first, then + Open Food Facts. The dashboard does the same. +- Food: the start of a barcode (4+ digits) finds the products whose barcode starts with it, in the search box + and in all products. +- Food: a meal made with a food you change is worked out again (and the meals made with that meal), its + logged entries too. +- Food: "stomach", "žalúdky" or "pipote" find gizzards; kurací / pui find chicken, morčací / curcan turkey. + ## 1.1.4 — 2026-10-26 - Food: My foods can have a barcode (the food editor, with a scan button). Scanning it, or typing it in the diff --git a/app/lib/health/food_archive.dart b/app/lib/health/food_archive.dart index 5bf8702..f8b34b3 100644 --- a/app/lib/health/food_archive.dart +++ b/app/lib/health/food_archive.dart @@ -1,6 +1,7 @@ -// Every Open Food Facts product (2 million+, every country), searched on the sync server's archive -// (GET /v1/food/search — sync-server/src/food.php), with filters: country, brand, Nutri-Score; a -// barcode finds that product. A pick is kept ("food.product", food_model.dart keepProduct) and synced, +// All products: what's here first (My foods, the food database, kept products), then every Open Food Facts +// product (2 million+, every country), searched on the sync server's archive (GET /v1/food/search — +// sync-server/src/food.php), with filters: country, brand, Nutri-Score; a barcode (or its first 4+ digits) +// finds those products. A pick is kept ("food.product", food_model.dart keepProduct) and synced, // so entries made from it work on every device. Also the camera barcode scanner (ZXing, no Google services). import 'dart:async'; import 'dart:convert'; @@ -14,6 +15,7 @@ import '../app/scanner.dart'; import '../app/sync_service.dart'; import '../app/theme.dart'; import 'food_model.dart'; +import 'sugar.dart' show fold; const _countries = [('', 'Any country'), ('ro', 'Romania'), ('sk', 'Slovakia'), ('cz', 'Czechia'), ('hu', 'Hungary'), ('at', 'Austria'), ('de', 'Germany'), ('pl', 'Poland'), ('it', 'Italy'), ('fr', 'France'), ('es', 'Spain'), ('uk', 'UK'), ('us', 'USA')]; @@ -57,6 +59,7 @@ class _ArchiveSheetState extends State { late final q = TextEditingController(text: widget.q); final brand = TextEditingController(); String country = '', score = ''; + List here = []; // My foods, the food database, kept products (no filters on) List> items = []; String? status; Timer? timer; @@ -81,30 +84,48 @@ class _ArchiveSheetState extends State { Future _run() async { final text = q.text.trim(), n = ++seq; - final code = RegExp(r'^\d{8,14}$').hasMatch(text); + final code = RegExp(r'^\d{4,14}$').hasMatch(text); if (!code && text.length < 3 && brand.text.trim().isEmpty && country.isEmpty) { setState(() { + here = []; items = []; status = 'Type at least 3 letters, or pick a filter.'; }); return; } - setState(() => status = 'Searching…'); + final store = widget.sync.store; + final filtered = brand.text.trim().isNotEmpty || country.isNotEmpty || score.isNotEmpty; // the archive's facts + final found = filtered + ? [] + : code + ? [...myFoodsByBarcode(store, text, prefix: true).take(8), ...(widget.fdb?.byBarcode(text, prefix: true) ?? keptByBarcode(store, text, prefix: true)).take(8)] + : text.length >= 3 + ? () { + final kept = keptProducts(store, text, fold: fold); + return [...myFoods(store, text, limit: 6), ...kept, + ...(widget.fdb?.search(text, limit: 12) ?? []).where((f) => !kept.any((k) => k.foodId == f.foodId)).take(8)]; + }() + : []; + setState(() { + here = found; + status = 'Searching…'; + }); try { final got = await archiveSearch(widget.sync, { if (code) 'barcode': text else 'q': text, 'country': country, 'brand': brand.text.trim(), 'nutriscore': score, }); if (!mounted || n != seq) return; + final ids = {for (final f in here) if (f.foodId != null) f.foodId}; setState(() { - items = got; - status = got.isEmpty ? 'Nothing found.' : null; + items = [for (final it in got) if (!ids.contains((it['id'] as num).toInt())) it]; + status = items.isEmpty && here.isEmpty ? 'Nothing found.' : null; }); } catch (e) { if (mounted && n == seq) { setState(() { items = []; - status = '$e'; + status = here.isEmpty ? '$e' : 'Only what\'s here — $e'; }); } } @@ -149,7 +170,8 @@ class _ArchiveSheetState extends State { padding: const EdgeInsets.fromLTRB(16, 14, 16, 12), child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Text('All products', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), - const Text('Open Food Facts — every country, through the sync server', style: TextStyle(color: muted, fontSize: 12.5)), + const Text('Yours and the food database first, then Open Food Facts — every country, through the sync server', + style: TextStyle(color: muted, fontSize: 12.5)), const SizedBox(height: 6), TextField( controller: q, @@ -188,6 +210,24 @@ class _ArchiveSheetState extends State { if (status != null) Padding(padding: const EdgeInsets.only(top: 10), child: Text(status!, style: const TextStyle(color: muted))), Flexible( child: ListView(shrinkWrap: true, children: [ + for (final f in here) + ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + title: Text(f.name, maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: Text( + [ + f.kind == 'my' ? (f.isMeal ? 'meal' : 'My foods') : (f.brand ?? '').isNotEmpty ? f.brand! : 'food database', + if (f.kind != 'my') '✓ you have it', + if (RegExp(r'^\d+$').hasMatch(q.text.trim()) && f.barcode != null) f.barcode!, + ].join(' · '), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(color: muted), + ), + trailing: Text('${(f.per100['kcal'] ?? 0).round()} kcal', style: const TextStyle(fontSize: 13.5)), + onTap: () => Navigator.of(context).pop(f), + ), for (final it in items) ListTile( dense: true, diff --git a/app/lib/health/food_model.dart b/app/lib/health/food_model.dart index a11a584..08d6d3f 100644 --- a/app/lib/health/food_model.dart +++ b/app/lib/health/food_model.dart @@ -21,6 +21,7 @@ import 'package:sqlite3/sqlite3.dart'; import '../sync/store.dart'; import 'body_model.dart' show BodyView, bmrMifflin, female, profileOf; import 'cycle_model.dart' show iso; +import 'sugar.dart' show fold; import 'summaries.dart'; const mealKeys = ['breakfast', 'lunch', 'dinner', 'snack']; @@ -157,10 +158,25 @@ class FoodDb { return r != null ? _food(r) : store == null ? null : keptProduct(store!, id); } - /// The products with that barcode (foods.db keeps it as on the pack), else kept ones. - List byBarcode(String code) { - final rs = db.select("SELECT * FROM food WHERE barcode = ? OR barcode = ?", [code, code.replaceFirst(RegExp(r'^0+'), '')]); - return rs.isNotEmpty ? [for (final r in rs) _food(r)] : store == null ? [] : keptByBarcode(store!, code); + /// The products with that barcode (foods.db keeps it as on the pack), else kept ones; [prefix]: the ones whose + /// barcode starts with [code] (a part typed), an exact one first (fooddb.by_barcode). + List byBarcode(String code, {bool prefix = false}) { + final bare = code.replaceFirst(RegExp(r'^0+'), ''); + final rs = prefix // a range, so the barcode index does it (digits; ':' follows '9') + ? db.select("SELECT * FROM food WHERE (barcode >= ? AND barcode < ?) OR (barcode >= ? AND barcode < ?) " + "ORDER BY barcode IN (?, ?) DESC, barcode LIMIT 20", [code, '$code:', bare, '$bare:', code, bare]) + : db.select("SELECT * FROM food WHERE barcode = ? OR barcode = ?", [code, bare]); + return rs.isNotEmpty ? [for (final r in rs) _food(r)] : store == null ? [] : keptByBarcode(store!, code, prefix: prefix); + } + + /// A word's start → the database's words for it too (fooddb.SAME: Slovak žalúdok / kurací / morčací, + /// Romanian pipotă / pui / curcan). + static const _same = {'stomach': ['gizzard'], 'zalud': ['gizzard', 'stomach'], 'pipot': ['gizzard'], + 'kurac': ['chicken'], 'pui': ['chicken'], 'morc': ['turkey'], 'curcan': ['turkey']}; + + static List _alts(String w) { + final f = fold(w); + return [w, for (final e in _same.entries) if (f.startsWith(e.key)) ...e.value]; } /// fooddb.search: every word a prefix in name / brand / category; all in the name first, the name starting @@ -168,7 +184,7 @@ class FoodDb { List search(String q, {int limit = 10}) { final ws = words(q); if (ws.isEmpty) return []; - final terms = ws.map((w) => '"$w"*').join(' '); + final terms = ws.map((w) => '(${_alts(w).map((x) => '"$x"*').join(' OR ')})').join(' AND '); final rs = db.select( 'SELECT f.*, bm25(food_fts, 10, 1) AS rank FROM food_fts JOIN food f ON f.id = food_fts.rowid ' 'WHERE food_fts MATCH ? ORDER BY rank LIMIT 200', [terms]); @@ -179,7 +195,7 @@ class FoodDb { final lead = nameWords.isEmpty ? '' : nameWords.first; final exact = (lead == first || lead == '${first}s' || lead == '${first}es' || first == '${lead}s' || first == '${lead}es') ? 0 : lead.startsWith(first) ? 1 : 2; - final inName = ws.every((w) => nameWords.any((x) => x.startsWith(w))) ? 0 : 1; + final inName = ws.every((w) => nameWords.any((x) => _alts(w).any(x.startsWith))) ? 0 : 1; final plain = nameWords.any(_plain.contains) ? 0 : 1; return [inName, exact, plain, nameWords.length, ((r['rank'] as num) * 10).round() / 10, name.length, _rank[r['source']] ?? 3]; @@ -239,14 +255,16 @@ List myFoods(SyncStore store, String q, {int limit = 8}) { return all.take(limit).map(myFood).toList(); } -/// My foods (not deleted) with that barcode — as typed, or without its leading zeros (db.my_foods_by_barcode). -List myFoodsByBarcode(SyncStore store, String code) { +/// My foods (not deleted) with that barcode — as typed, or without its leading zeros (db.my_foods_by_barcode); +/// [prefix]: the ones whose barcode starts with [code] (a part typed), an exact one first. +List myFoodsByBarcode(SyncStore store, String code, {bool prefix = false}) { String bare(String c) => c.replaceFirst(RegExp(r'^0+'), ''); - return [ + bool hit(String b) => prefix ? b.startsWith(code) || bare(b).startsWith(bare(code)) : b == code || bare(b) == bare(code); + final rs = [ for (final r in store.rows('food.food')) - if ((r['gone'] ?? 0) == 0 && r['barcode'] is String && (r['barcode'] == code || bare(r['barcode'] as String) == bare(code))) - myFood(r) - ]; + if ((r['gone'] ?? 0) == 0 && r['barcode'] is String && hit(r['barcode'] as String)) r + ]..sort((a, b) => (a['barcode'] == code ? 0 : 1).compareTo(b['barcode'] == code ? 0 : 1)); + return rs.map(myFood).toList(); } Food? myFoodByUid(SyncStore store, String uid) { @@ -350,8 +368,10 @@ Food? _kept(Map? row) { Food? keptProduct(SyncStore store, int id) => _kept(store.row(tProduct, 'p:$id')); -List keptByBarcode(SyncStore store, String code) => - [for (final r in store.rows(tProduct, where: "json_extract(data, '\$.barcode') = ?", args: [code])) ?_kept(r)]; +List keptByBarcode(SyncStore store, String code, {bool prefix = false}) => [ + for (final r in store.rows(tProduct, where: "json_extract(data, '\$.barcode') ${prefix ? 'LIKE' : '='} ?", args: [prefix ? '$code%' : code])) + ?_kept(r) +]; /// Kept products whose name / brand has every word of [q] (folded: no diacritics). List keptProducts(SyncStore store, String q, {required String Function(String) fold, int limit = 4}) { @@ -559,7 +579,7 @@ const foodFields = { final now = DateTime.now().toIso8601String().substring(0, 19); final old = uid == null ? null : store.row('food.food', uid); final u = uid ?? SyncStore.randomId(); - store.put('food.food', u, { + final next = { 'based_on': null, 'based_on_name': null, 'recipe': null, 'gone': 0, 'created': now, for (final c in foodCols) c: null, ...?old, @@ -567,11 +587,49 @@ const foodFields = { if (sugarKind != null) 'sugar_kind': const ['added', 'dairy', 'natural'].contains(sugarKind) ? sugarKind : null, if (code != null) 'barcode': code.isEmpty ? null : code, 'portions': jsonEncode([for (final p in portions) {'label': p.label.trim().split(RegExp(r'\s+')).join(' '), 'grams': p.grams}]), - }); - if (old != null) _follow(store, u); + }; + if (old != null && next.entries.every((e) => e.key == 'updated' || old[e.key] == e.value)) return (u, null); // nothing changed + store.put('food.food', u, next); + if (old != null) { + _follow(store, u); + _followMeals(store, u); + } return (u, null); } +int _mealDepth = 0; // _followMeals inside _followMeals (a meal in a meal …) + +/// The meals made with one of My foods follow its edits too: worked out again from their recipes (saveMeal, the +/// ingredients as they are now — their entries follow), then the meals made with those (saveMyFood calls this +/// again). One that can't be — an ingredient gone, or the food database not open yet — stays as it was +/// (db.follow_meals). +void _followMeals(SyncStore store, String uid) { + if (_mealDepth >= 5) return; + _mealDepth++; + try { + for (final m in store.rows('food.food')) { + if ((m['gone'] ?? 0) != 0 || m['recipe'] is! String || m['_u'] == uid) continue; + final refs = [ + for (final i in ((jsonDecode(m['recipe'] as String) as Map)['ingredients'] as List? ?? [])) + if ((i as Map)['food'] is String) i['food'] as String + ]; + if (!refs.any((r) => r.replaceFirst('~', '') == 'my:$uid')) continue; + final fdb = FoodDb._one; + final ok = refs.every((r) => r.startsWith('usda:') ? fdb?.food(int.tryParse(r.substring(5)) ?? -1) != null + : r.startsWith('my:') ? myFoodByUid(store, r.substring(3).replaceFirst('~', '')) != null : false); + if (!ok) continue; + saveMeal(store, uid: m['_u'] as String, name: m['name'] as String, ings: recipeOf(store, fdb, m), doneGrams: doneGramsOf(m), + portions: [ + for (final p in (jsonDecode((m['portions'] as String?) ?? '[]') as List).cast()) + Portion(p['label'] as String, (p['grams'] as num).toDouble()) + ], + note: (m['note'] as String?) ?? ''); + } + } finally { + _mealDepth--; + } +} + /// The entries logged from one of My foods follow its edits (a meal's recipe, a food's values or name): /// worked out again for their grams — only the ones that change, so the rest aren't re-sent (db._follow). void _follow(SyncStore store, String uid) { @@ -746,8 +804,8 @@ Set mealIds(SyncStore store, String uid, [int depth = 0]) { portions: [...portions.where((p) => p.label.trim().toLowerCase() != 'whole meal'), Portion('whole meal', (weight * 10).round() / 10)], note: note); if (err != null) return (null, err); - final row = store.row('food.food', u!)!; - store.put('food.food', u, {...row, 'recipe': jsonEncode({'ingredients': recipe, 'done_grams': doneGrams})}); + final row = store.row('food.food', u!)!, r = jsonEncode({'ingredients': recipe, 'done_grams': doneGrams}); + if (row['recipe'] != r) store.put('food.food', u, {...row, 'recipe': r}); return (u, null); } diff --git a/app/lib/health/food_sheet.dart b/app/lib/health/food_sheet.dart index 9e0f292..8bbd1dc 100644 --- a/app/lib/health/food_sheet.dart +++ b/app/lib/health/food_sheet.dart @@ -144,8 +144,8 @@ class _FoodSheetState extends State { if (rest.isNotEmpty) sections.add(('Yesterday · other meals', [for (final e in rest) _yday(e, already(e))])); final recent = recentFoods(store, '', limit: 8); if (recent.isNotEmpty) sections.add(('Eaten often', [for (final (e, n) in recent) _recent(e, n)])); - } else if (RegExp(r'^\d{8,14}$').hasMatch(text)) { // a barcode: My foods with it, that product here or kept - final found = _byBarcode(text); + } else if (RegExp(r'^\d{4,14}$').hasMatch(text)) { // a barcode or its start: My foods, products here or kept + final found = _byBarcode(text, prefix: true); sections.add(('Barcode $text', [ for (final f in found) _foodTile(f), if (found.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6), @@ -227,9 +227,11 @@ class _FoodSheetState extends State { if (f != null && mounted) _pick(f); } - /// My foods with that barcode first, then the food database's product (or a kept one). - List _byBarcode(String code) => - [...myFoodsByBarcode(widget.sync.store, code), ...widget.fdb?.byBarcode(code) ?? keptByBarcode(widget.sync.store, code)]; + /// My foods with that barcode first, then the food database's product (or a kept one); [prefix]: starting with it. + List _byBarcode(String code, {bool prefix = false}) => [ + ...myFoodsByBarcode(widget.sync.store, code, prefix: prefix), + ...widget.fdb?.byBarcode(code, prefix: prefix) ?? keptByBarcode(widget.sync.store, code, prefix: prefix), + ]; /// The camera → a barcode: My foods / its product here, else straight to the archive (nothing there either: /// the box keeps the barcode, with "New food with barcode …"). diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 50c1707..a9e61ec 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.1.4+7 +version: 1.1.5+8 environment: sdk: ^3.12.2 diff --git a/app/test/food_follow_test.dart b/app/test/food_follow_test.dart index fb2ec5e..359e904 100644 --- a/app/test/food_follow_test.dart +++ b/app/test/food_follow_test.dart @@ -47,4 +47,22 @@ void main() { saveMeal(store, uid: soup, name: 'Soup', ings: [ing(oil, 10), ing(veg, 970)], portions: []); expect(store.row('food.entry', 's1')!['kcal'], closeTo(400 * (9000 + 29100) / 98000, 0.01)); }); + + test('a meal made with a changed food is worked out again, its entries too', () { + final (curd, _) = saveMyFood(store, name: 'Curd', per100: {'kcal': 100, 'protein': 12}, portions: []); + final (flour, _) = saveMyFood(store, name: 'Flour', per100: {'kcal': 350}, portions: []); + Ingredient ing(String uid, double g) => Ingredient.food(myFoodByUid(store, uid)!, g, 'g'); + final (strudel, _) = saveMeal(store, name: 'Strudel', ings: [ing(curd!, 300), ing(flour!, 200)], portions: []); + final (plate, _) = saveMeal(store, name: 'Plate', ings: [ing(strudel!, 250), ing(flour, 50)], portions: []); + saveFromFood(store, u: 'p1', day: '2026-10-27', meal: 'dinner', food: myFoodByUid(store, plate!)!, amount: 150, unit: 'g'); + expect(store.row('food.food', strudel)!['kcal'], closeTo((300 + 700) / 5, 0.001)); + final hFlour = store.row('food.food', flour)!['_h']; + + saveMyFood(store, uid: curd, name: 'Curd', per100: {'kcal': 200, 'protein': 12}, portions: []); + expect(store.row('food.food', strudel)!['kcal'], closeTo((600 + 700) / 5, 0.001)); + final plateKcal = (250 * 260 / 100 + 175) * 100 / 300; + expect(store.row('food.food', plate)!['kcal'], closeTo(plateKcal, 0.001)); + expect(store.row('food.entry', 'p1')!['kcal'], closeTo(plateKcal * 1.5, 0.01)); + expect(store.row('food.food', flour)!['_h'], hFlour); // not an ingredient's meal: untouched + }); } diff --git a/dashboard/plugins/food/__init__.py b/dashboard/plugins/food/__init__.py index fe2a9c7..62a9281 100644 --- a/dashboard/plugins/food/__init__.py +++ b/dashboard/plugins/food/__init__.py @@ -8,7 +8,7 @@ (made of other foods: the meal builder) — add, edit, delete /food/export.csv every entry /food/api/… JSON writes + the food suggestions (same-origin only, like the core's); - api/archive = every Open Food Facts product, searched on the sync server + api/archive = every product: what's here, then every Open Food Facts one (searched on the sync server) (its /v1/food/search, with this dashboard's sync token); api/product keeps a picked one (food.db `product`, synced) @@ -259,14 +259,22 @@ def register(ctx): def ref_of(e): return f"my:{e['my_food_id']}" if e.get("my_food_id") else f"usda:{e['food_id']}" if e.get("food_id") else None + def by_code(c, code): + """A barcode or the start of one (4–14 digits) → (My foods, products: the database's, else kept ones).""" + return (db.my_foods_by_barcode(c, code, prefix=True), + fooddb.by_barcode(foods_db, code, prefix=True) or db.products(c, barcode=code, prefix=True, limit=20)) + + def code_of(q): + return q.strip() if re.fullmatch(r"\s*\d{4,14}\s*", q) else None + @bp.route("/api/foods") - def api_foods(): # ?q= → {recent, mine, db, products} — the form's suggestions (a barcode: My foods / its product) + def api_foods(): # ?q= → {recent, mine, db, products} — the form's suggestions (a barcode or a part: My foods / products) q = request.args.get("q", "")[:60] - code = q.strip() if re.fullmatch(r"\s*\d{8,14}\s*", q) else None + code = code_of(q) with con() as c: if code: # scanned / typed off the pack - return jsonify(recent=[], mine=db.my_foods_by_barcode(c, code), db=[], - products=fooddb.by_barcode(foods_db, code) or db.products(c, barcode=code)) + mine, products = by_code(c, code) + return jsonify(recent=[], mine=mine, db=[], products=products[:8]) rows = db.foods(c, q, limit=5) mine = db.my_foods(c, q, limit=8) kept = db.products(c, q, limit=4, fold=sugar.fold) # picked from the archive before @@ -278,16 +286,33 @@ def register(ctx): products=(kept + [f for f in found if f["kind"] == "off" and f["id"] not in ids])[:8]) @bp.route("/api/archive") - def api_archive(): # ?q, country, brand, nutriscore, barcode → {items} from the archive (sync server) + def api_archive(): # ?q, country, brand, nutriscore, barcode → {items[, error]}: what's here (My foods, the food + # database, kept products) first, then the archive's (sync server); unreachable → what's here + the error p = {k: request.args.get(k, "")[:60] for k in ("q", "country", "brand", "category", "nutriscore", "barcode")} - try: - items = archive(dict(p, limit=25)) - except RuntimeError as e: - return jsonify(error=str(e)), 502 - with con() as c: # ones you have here already say so - for f in items: + code = code_of(p["barcode"] or p["q"]) + if code: + p.update(barcode=code, q="") + with con() as c: + here = [] + if not any(p[k] for k in ("country", "brand", "category", "nutriscore")): # filters: the archive's facts + if code: + mine, products = by_code(c, code) + here = mine[:8] + products[:8] + elif len(p["q"].strip()) >= 3: + kept = db.products(c, p["q"], limit=4, fold=sugar.fold) + found = [f for f in fooddb.search(foods_db, p["q"], limit=12) if f["id"] not in {k["id"] for k in kept}] + here = db.my_foods(c, p["q"], limit=6) + kept + found[:8] + for f in here: + f["saved"] = True + error = None + try: + items = archive(dict(p, limit=25)) + except RuntimeError as e: + items, error = [], str(e) + ids = {f["id"] for f in here if f["kind"] != "my"} + for f in items: # ones you have here already say so f["saved"] = bool(fooddb.food(foods_db, f["id"]) or db.product(c, f["id"])) - return jsonify(items=items) + return jsonify(items=here + [f for f in items if f["id"] not in ids], **({"error": error} if error else {})) @bp.route("/api/product", methods=["POST"]) def api_product(): # {id, barcode} — keep a product picked from the archive → {food} @@ -362,6 +387,7 @@ def register(ctx): edit, food = write mine = food if food and food["kind"] == "my" else None e["my_food_id"] = db.save_food(c, edit, base=food, fid=mine["id"] if mine else None) + db.follow_meals(c, e["my_food_id"], lambda ref: resolve(c, ref)) return db.save(c, e, source=source, extra=extra) @bp.route("/api/entry", methods=["POST"]) @@ -404,7 +430,9 @@ def register(ctx): raise db.Invalid("name", "That food is gone.") if base and base.get("recipe"): raise db.Invalid("name", "That's a meal — change it with Edit meal.") - return jsonify(ok=True, id=db.save_food(c, d, base=base, fid=fid)) + fid = db.save_food(c, d, base=base, fid=fid) + db.follow_meals(c, fid, lambda ref: resolve(c, ref)) + return jsonify(ok=True, id=fid) except db.Invalid as e: return jsonify(error=str(e), field="food." + e.field), 400 @@ -425,6 +453,7 @@ def register(ctx): log = d.get("log") or {} db.clean(dict(log, name="-", kcal=0)) # day / meal / time valid before anything is written fid = db.save_meal(c, d, lambda ref: resolve(c, ref), fid) + db.follow_meals(c, fid, lambda ref: resolve(c, ref)) eid = None if ids: eid = commit(c, prepare(c, {**{k: log.get(k) for k in ("day", "meal", "time")}, "food": f"my:{fid}", diff --git a/dashboard/plugins/food/db.py b/dashboard/plugins/food/db.py index ad8fba8..a40a775 100644 --- a/dashboard/plugins/food/db.py +++ b/dashboard/plugins/food/db.py @@ -339,10 +339,12 @@ def product(con, food_id): return _product(json.loads(r[0])) if r else None -def products(con, q="", barcode=None, limit=6, fold=str.lower): - """Kept products whose name / brand has every word of q (fold: sugar.fold — no diacritics), or with that barcode.""" +def products(con, q="", barcode=None, limit=6, fold=str.lower, prefix=False): + """Kept products whose name / brand has every word of q (fold: sugar.fold — no diacritics), or with that barcode + (prefix: starting with it).""" if barcode: - rows = con.execute("SELECT data FROM product WHERE barcode = ?", (barcode,)).fetchall() + rows = con.execute(f"SELECT data FROM product WHERE barcode {'LIKE' if prefix else '='} ? ORDER BY barcode = ? DESC", + (barcode + "%" if prefix else barcode, barcode)).fetchall() else: words = fold(q).split() rows = [r for r in con.execute("SELECT data, name, brand FROM product ORDER BY name") @@ -366,11 +368,14 @@ def my_foods(con, q="", limit=None): return [_food(r, r["uses"]) for r in rows] -def my_foods_by_barcode(con, code): - """My foods (not deleted) with that barcode — as typed, or without its leading zeros.""" +def my_foods_by_barcode(con, code, prefix=False): + """My foods (not deleted) with that barcode — as typed, or without its leading zeros; prefix: the ones + whose barcode starts with code (a part typed), an exact one first.""" + bare = code.lstrip("0") or code + match = "(f.barcode LIKE ? OR ltrim(f.barcode, '0') LIKE ?)" if prefix else "(f.barcode = ? OR ltrim(f.barcode, '0') = ?)" rows = con.execute("SELECT f.*, (SELECT COUNT(*) FROM entry e WHERE e.my_food_id = f.id) AS uses FROM food f " - "WHERE f.gone = 0 AND (f.barcode = ? OR ltrim(f.barcode, '0') = ?)", - (code, code.lstrip("0") or code)).fetchall() + f"WHERE f.gone = 0 AND {match} ORDER BY f.barcode IN (?, ?) DESC, f.name", + ((code + "%", bare + "%") if prefix else (code, bare)) + (code, bare)).fetchall() return [_food(r, r["uses"]) for r in rows] @@ -434,6 +439,9 @@ def _write_food(con, v, base=None, fid=None): raise Invalid("barcode", f"“{other[0]['name']}” in My foods has that barcode already.") now = datetime.now().isoformat(timespec="seconds") if fid: + old = con.execute("SELECT * FROM food WHERE id = ?", (fid,)).fetchone() + if old and all(old[k] == x for k, x in v.items()): + return fid # nothing changed: not stamped, not synced again con.execute(f"UPDATE food SET {', '.join(f'{k} = ?' for k in v)}, updated = ? WHERE id = ?", (*v.values(), now, fid)) _follow(con, fid) else: @@ -457,6 +465,25 @@ def _follow(con, fid): con.execute(f"UPDATE entry SET {', '.join(f'{k} = ?' for k in new)} WHERE id = ?", (*new.values(), e["id"])) +def follow_meals(con, fid, resolve, _seen=None): + """The meals made with one of My foods follow its edits too: worked out again from their recipes (save_meal, + the ingredients as they are now — their entries follow), then the meals made with those. One that can't be + (an ingredient gone since) stays as it was. Same in the app (food_model.dart _followMeals).""" + seen = _seen if _seen is not None else {fid} + ref = f"my:{fid}" + for r in con.execute("SELECT * FROM food WHERE gone = 0 AND recipe LIKE ?", (f'%"{ref}"%',)).fetchall(): + m = _food(r) + if m["id"] in seen or not any(i.get("food") == ref for i in m["recipe"]["ingredients"]): + continue + seen.add(m["id"]) + try: + save_meal(con, {"name": m["name"], "ingredients": m["recipe"]["ingredients"], "done_grams": m["recipe"]["done_grams"], + "portions": m["portions"], "note": m["note"], "sugar_kind": m["sugar_kind"]}, resolve, m["id"]) + except Invalid: + continue + follow_meals(con, m["id"], resolve, seen) + + MEAL_MAX = 40 # ingredients diff --git a/dashboard/plugins/food/fooddb.py b/dashboard/plugins/food/fooddb.py index 7e1dfc6..b6a182f 100644 --- a/dashboard/plugins/food/fooddb.py +++ b/dashboard/plugins/food/fooddb.py @@ -4,7 +4,7 @@ read-only lookups for the entry form and the describe box. Nutrients are per 100 search(path, q) → foods for the form's suggestions, best first, with their portions food(path, id) → one food + portions - by_barcode(path, c) → the products with that barcode + by_barcode(path, c) → the products with that barcode (prefix=True: starting with c) best(path, name) → the likeliest food for a name (the describe box) portion(f, amount, unit) → (grams, unit label) for "2 pcs" / "1 slice" / "150 g" of it, or (None, None) nutrients(f, grams) → its columns for that many grams @@ -17,6 +17,7 @@ USDA's generic foods (fdc.py; kind "usda") and Open Food Facts' shop products (o import os import re import sqlite3 +import unicodedata from .fdc import COLS @@ -47,6 +48,17 @@ STOP = {"with", "and", "of", "a", "an", "the", "in", "on", "some", "my"} PLAIN = ("nfs", "raw", "whole", "plain", "regular", "fresh", "cooked", "boiled") # the generic version of a food +SAME = {"stomach": ("gizzard",), "zalud": ("gizzard", "stomach"), "pipot": ("gizzard",), # a word's start → the + "kurac": ("chicken",), "pui": ("chicken",), "morc": ("turkey",), "curcan": ("turkey",)} # database's words +# for it too (Slovak žalúdok / kurací / morčací, Romanian pipotă / pui / curcan) — food_model.dart has the same + + +def _alts(w): + """A query word → it and the database's words for the same thing (SAME).""" + f = "".join(c for c in unicodedata.normalize("NFKD", w) if not unicodedata.combining(c)) + return (w,) + next((v for k, v in SAME.items() if f.startswith(k)), ()) + + def _words(q): return [w for w in re.findall(r"\w+", q.lower()) if (len(w) > 1 or w.isdigit()) and w not in STOP] @@ -62,7 +74,7 @@ def search(path, q, limit=10): if not words or not con: return [] with con: - terms = " ".join(f'"{w}"*' for w in words) + terms = " AND ".join("(" + " OR ".join(f'"{x}"*' for x in _alts(w)) + ")" for w in words) rs = con.execute("SELECT f.*, bm25(food_fts, 10, 1) AS rank FROM food_fts JOIN food f ON f.id = food_fts.rowid " "WHERE food_fts MATCH ? ORDER BY rank LIMIT 200", (terms,)).fetchall() first = words[0] @@ -73,7 +85,7 @@ def search(path, q, limit=10): exact = 0 if lead in (first, first + "s", first + "es") or first in (lead + "s", lead + "es") \ else 1 if lead.startswith(first) else 2 ws = re.findall(r"\w+", name) - in_name = 0 if all(any(x.startswith(w) for x in ws) for w in words) else 1 # else only via brand / category + in_name = 0 if all(any(x.startswith(a) for x in ws for a in _alts(w)) for w in words) else 1 # else only via brand / category plain = 0 if any(w in PLAIN for w in ws) else 1 return (in_name, exact, plain, len(ws), round(r["rank"], 1), len(name), SOURCE_RANK.get(r["source"], 3)) seen, out = set(), [] @@ -96,16 +108,22 @@ def food(path, fid): return _food(con, r) if r else None -def by_barcode(path, code): - """The products with that barcode (foods.db keeps it as on the pack, leading zeros too).""" +def by_barcode(path, code, prefix=False, limit=20): + """The products with that barcode (foods.db keeps it as on the pack, leading zeros too); prefix: the ones + whose barcode starts with code (a part typed) — an exact one first.""" con = _con(path) if not con or not code: return [] with con: if "barcode" not in {r[1] for r in con.execute("PRAGMA table_info(food)")}: return [] - return [_food(con, r) for r in con.execute("SELECT * FROM food WHERE barcode = ? OR barcode = ?", - (code, code.lstrip("0") or code))] + bare = code.lstrip("0") or code + if not prefix: + rows = con.execute("SELECT * FROM food WHERE barcode = ? OR barcode = ?", (code, bare)) + else: # a range: the barcode index does it (digits; ':' follows '9') + rows = con.execute("SELECT * FROM food WHERE (barcode >= ? AND barcode < ?) OR (barcode >= ? AND barcode < ?) " + "ORDER BY barcode IN (?, ?) DESC, barcode LIMIT ?", (code, code + ":", bare, bare + ":", code, bare, limit)) + return [_food(con, r) for r in rows] def best(path, name): diff --git a/dashboard/plugins/food/static/food.js b/dashboard/plugins/food/static/food.js index 0bcd569..2a7b368 100644 --- a/dashboard/plugins/food/static/food.js +++ b/dashboard/plugins/food/static/food.js @@ -210,8 +210,9 @@ pick: (f) => pick(f), open: () => ie === st, }); - // the archive: every Open Food Facts product (/food/api/archive → the sync server), with filters; the search box - // keeps searching it while open, a barcode (8–14 digits) finds that product. A pick is kept (/food/api/product). + // all products: what's here (My foods, the food database, kept products), then every Open Food Facts product + // (/food/api/archive → the sync server), with filters; the search box keeps searching it while open, a barcode + // (or its first 4+ digits) finds those products. A pick from the archive is kept (/food/api/product). const arch = q(".fd-arch"); let archTimer = null, archSeq = 0; const archHome = (c) => c.split(" ").filter(Boolean).slice(0, 3).map((x) => x[0].toUpperCase() + x.slice(1).replace(/-/g, " ")) @@ -225,17 +226,18 @@ const text = q(".fd-ie-in").value.trim(), n = ++archSeq, s = q(".fd-arch-s"), ul = q(".fd-arch-l"); const p = new URLSearchParams({ q: text, country: q(".fd-arch-c").value, brand: q(".fd-arch-b").value.trim(), nutriscore: q(".fd-arch-n").value }); - if (/^\d{8,14}$/.test(text)) { p.set("barcode", text); p.delete("q"); } + if (/^\d{4,14}$/.test(text)) { p.set("barcode", text); p.delete("q"); } s.textContent = "Searching…"; try { const r = await fetch(`/food/api/archive?${p}`), j = await r.json().catch(() => ({})); if (n !== archSeq) return; if (!r.ok) throw new Error(j.error || `Error ${r.status}`); st.archItems = j.items; - s.textContent = j.items.length ? "" : text.length < 3 && !p.get("brand") && !p.get("country") ? "Type at least 3 letters, or pick a filter." : "Nothing found."; + s.textContent = j.items.length ? (j.error ? `Only what's here — ${j.error}` : "") : j.error ? j.error : text.length < 3 && !p.get("brand") && !p.get("country") ? "Type at least 3 letters, or pick a filter." : "Nothing found."; ul.innerHTML = j.items.map((f, i) => `
  • ${esc(f.name)}` + `${Math.round(f.per100.kcal ?? 0)} kcal / 100 g` + - `${esc([f.brand, archHome(f.countries || "")].filter(Boolean).join(" · "))}${f.saved ? " · ✓ you have it" : ""}` + + `${esc(f.kind === "my" ? (f.recipe ? "meal" : "My foods") : [f.brand, archHome(f.countries || "")].filter(Boolean).join(" · ") || "food database")}` + + `${f.kind !== "my" && f.saved ? " · ✓ you have it" : ""}${f.barcode && /^\d+$/.test(text) ? ` · ${esc(f.barcode)}` : ""}` + `${nsBadge(f.nutriscore)}
  • `).join(""); } catch (x) { if (n === archSeq) { s.textContent = x.message; ul.innerHTML = ""; } } } @@ -248,6 +250,7 @@ const li = e.target.closest("li[data-i]"); if (!li) return; const f = st.archItems[Number(li.dataset.i)]; + if (f.kind === "my") { archClose(); return useFood(f); } // one of My foods: as it is q(".fd-arch-s").textContent = "Keeping it…"; try { const j = await post("/food/api/product", { id: f.id, barcode: f.barcode }); @@ -319,7 +322,7 @@ q(".fd-ie-edit").textContent = m === "edit" ? "Undo changes" : f?.recipe ? "Edit meal" : "Edit item"; q(".fd-ie-edit").hidden = !(m === "food" || m === "edit"); q(".fd-copy").textContent = m !== "edit" ? "" : f.kind === "my" - ? `Saving changes “${f.name}” in My foods (past entries keep their numbers).` + ? `Saving changes “${f.name}” in My foods — the entries logged with it change too.` : `Saving adds a copy to My foods — rename it if you like; “${f.name}” stays as it is.`; const info = q(".fd-pinfo"); info.innerHTML = m === "food" || m === "edit" ? productInfo(f) : ""; diff --git a/server/src/food.php b/server/src/food.php index 1758a05..c93b99d 100644 --- a/server/src/food.php +++ b/server/src/food.php @@ -70,7 +70,7 @@ function food_row(array $r): array { /** * GET /v1/food/search: q (every word a prefix of the name / brand / category), brand, country (a name or - * ro / sk / de …), category, nutriscore ("a" or "ab"), barcode (exact, the merged duplicates' too), limit (≤ 50). + * ro / sk / de …), category, nutriscore ("a" or "ab"), barcode (exact, the merged duplicates' too; then, 4+ digits, the ones starting with it), limit (≤ 50). * Ranked as the dashboard's fooddb.search: all of q in the name first, home-country products, the name * starting with the first word, fewer words, FTS relevance (name ≫ brand), shorter names. */ @@ -78,10 +78,21 @@ function food_search(PDO $db, array $p, array $home = []): array { // $home: c $home = array_map(fn($c) => food_fold((string)$c), $home); $limit = min(50, max(1, (int)($p['limit'] ?? 20))); $code = preg_replace('/\D/', '', (string)($p['barcode'] ?? '')); - if ($code !== '') { + if ($code !== '') { // that barcode, then (4+ digits) the ones starting with it $st = $db->prepare('SELECT * FROM food WHERE barcode = ? UNION SELECT f.* FROM alias a JOIN food f ON f.id = a.food_id WHERE a.barcode = ?'); $st->execute([$code, $code]); - return array_map('food_row', $st->fetchAll()); + $rows = $st->fetchAll(); + if (strlen($code) >= 4 && count($rows) < $limit) { // a range, so the barcode index does it (':' follows '9') + $st = $db->prepare('SELECT * FROM food WHERE barcode > ? AND barcode < ? ORDER BY barcode LIMIT ?'); + $st->execute([$code, $code . ':', $limit]); + $ids = array_column($rows, 'id'); + foreach ($st->fetchAll() as $r) { + if (count($rows) < $limit && !in_array($r['id'], $ids)) { + $rows[] = $r; + } + } + } + return array_map('food_row', $rows); } $words = food_words((string)($p['q'] ?? '')); $terms = array_map(fn($w) => food_term($w), $words);