Food: all products, barcode prefixes, meals that follow their ingredients

- "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 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-10-26 15:41:23 +02:00
parent d9460a2293
commit eeca189b7f
11 changed files with 287 additions and 71 deletions

View file

@ -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<ArchiveSheet> {
late final q = TextEditingController(text: widget.q);
final brand = TextEditingController();
String country = '', score = '';
List<Food> here = []; // My foods, the food database, kept products (no filters on)
List<Map<String, dynamic>> items = [];
String? status;
Timer? timer;
@ -81,30 +84,48 @@ class _ArchiveSheetState extends State<ArchiveSheet> {
Future<void> _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
? <Food>[]
: 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)];
}()
: <Food>[];
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<ArchiveSheet> {
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<ArchiveSheet> {
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,

View file

@ -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<Food> 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<Food> 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<String> _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<Food> 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<Food> 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<Food> 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<Food> 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<String, dynamic>? row) {
Food? keptProduct(SyncStore store, int id) => _kept(store.row(tProduct, 'p:$id'));
List<Food> keptByBarcode(SyncStore store, String code) =>
[for (final r in store.rows(tProduct, where: "json_extract(data, '\$.barcode') = ?", args: [code])) ?_kept(r)];
List<Food> 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<Food> 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 = <String, dynamic>{
'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<Map>())
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<String> 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);
}

View file

@ -144,8 +144,8 @@ class _FoodSheetState extends State<FoodSheet> {
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<FoodSheet> {
if (f != null && mounted) _pick(f);
}
/// My foods with that barcode first, then the food database's product (or a kept one).
List<Food> _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<Food> _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 …").