Food, sync and warmer updates from 2026-10-26
- Food: "All products" lists what's here first (My foods, the food database, kept products), then Open Food Facts; the start of a barcode (4+ digits) finds the products starting with it (dashboard, app, server search). - Food: My foods barcodes; entries follow edits of their food or meal, and meals made with a changed food are worked out again (nested meals too); a save that changes nothing isn't written. - Food: the week strip shows protein / carbs / fat per day, over-target calories in red; the header's arrows go by week, days swap in place with prefetch on hover; the app's arrows go by week, a sideways swipe by day. - Food search: stomach / žalúdok / pipotă find gizzards, kurací / pui chicken, morčací / curcan turkey. - Sync: tables a plugin makes after start-up are prepared at the next sync and their file read from the start once. - Warmers build pages as each admin account and wait while someone is using the dashboard; slow page builds are logged. - Stations: impossible sensor readings are dropped; chart ticks never fail. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
fb3c01cdd7
commit
4193de4262
26 changed files with 704 additions and 111 deletions
|
|
@ -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];
|
||||
|
|
@ -208,6 +224,7 @@ Food myFood(Map<String, dynamic> r) {
|
|||
final ps = (jsonDecode((r['portions'] as String?) ?? '[]') as List).cast<Map<String, dynamic>>();
|
||||
return Food(
|
||||
ref: 'my:${r['_u']}', kind: 'my', name: r['name'] as String, category: 'My foods', myUid: r['_u'] as String,
|
||||
barcode: r['barcode'] as String?,
|
||||
per100: {for (final c in foodCols) c: (r[c] as num?)?.toDouble()},
|
||||
portions: [for (final p in ps) Portion(p['label'] as String, (p['grams'] as num).toDouble())],
|
||||
isMeal: r['recipe'] != null,
|
||||
|
|
@ -238,6 +255,18 @@ 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);
|
||||
/// [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+'), '');
|
||||
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 && 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) {
|
||||
final r = store.row('food.food', uid);
|
||||
return r == null ? null : myFood(r);
|
||||
|
|
@ -339,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}) {
|
||||
|
|
@ -388,7 +419,7 @@ Food? foodOf(SyncStore store, FoodDb? fdb, Entry e) {
|
|||
}
|
||||
|
||||
/// Save an entry made from [food] (amount × unit → grams → its nutrients) — new (u null) or changed.
|
||||
/// The numbers are the entry's own, worked out now (later changes to the food don't touch it).
|
||||
/// The numbers are the entry's own, worked out now; edits to one of My foods re-work them (_follow).
|
||||
String? saveFromFood(SyncStore store, {String? u, required String day, required String meal, required Food food,
|
||||
required double amount, required String unit, String note = ''}) {
|
||||
final g = food.grams(amount, unit);
|
||||
|
|
@ -522,8 +553,9 @@ const foodFields = {
|
|||
/// New (uid null) or changed food: name unique among the live ones, energy required, portions need a
|
||||
/// name + grams. The nutrients the editor doesn't show stay as they were. → (uid, error).
|
||||
/// [sugarKind]: "Sugar counts as" (added / dairy / natural; '' = estimated; null = left as it is).
|
||||
/// [barcode]: the pack's, 8–14 digits ('' = none; null = left as it is).
|
||||
(String?, String?) saveMyFood(SyncStore store, {String? uid, required String name, required Map<String, double?> per100,
|
||||
required List<Portion> portions, String note = '', String? sugarKind}) {
|
||||
required List<Portion> portions, String note = '', String? sugarKind, String? barcode}) {
|
||||
final n = name.trim().split(RegExp(r'\s+')).join(' ');
|
||||
if (n.isEmpty) return (null, 'Name the food.');
|
||||
if (per100['kcal'] == null) return (null, 'Energy per 100 g — from the label.');
|
||||
|
|
@ -538,20 +570,84 @@ const foodFields = {
|
|||
final clash = store.rows('food.food').any((r) =>
|
||||
(r['gone'] ?? 0) == 0 && r['_u'] != uid && (r['name'] as String).toLowerCase() == n.toLowerCase());
|
||||
if (clash) return (null, 'You already have a food with that name in My foods — pick it, or name this one differently.');
|
||||
final code = barcode?.replaceAll(RegExp(r'\s'), '');
|
||||
if (code != null && code.isNotEmpty) {
|
||||
if (!RegExp(r'^\d{8,14}$').hasMatch(code)) return (null, 'A barcode is 8–14 digits.');
|
||||
final other = myFoodsByBarcode(store, code).where((f) => f.myUid != uid);
|
||||
if (other.isNotEmpty) return (null, '“${other.first.name}” in My foods has that barcode already.');
|
||||
}
|
||||
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,
|
||||
'name': n, ...per100, 'note': note.trim(), 'updated': now,
|
||||
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 && 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) {
|
||||
final f = store.row('food.food', uid);
|
||||
if (f == null) return;
|
||||
for (final e in store.rows('food.entry', where: "json_extract(data, '\$.my_food_id') = ?", args: [uid])) {
|
||||
final g = (e['grams'] as num?)?.toDouble();
|
||||
if (g == null || g <= 0) continue;
|
||||
final next = <String, dynamic>{
|
||||
for (final c in foodCols) c: f[c] == null ? null : ((f[c] as num) * g / 100 * 100).round() / 100,
|
||||
'name': f['name'],
|
||||
};
|
||||
if (next.entries.any((x) => e[x.key] != x.value)) {
|
||||
store.put('food.entry', e['_u'] as String, {...e, ...next});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deleted foods are only hidden (gone): entries made from them keep pointing at them.
|
||||
void deleteMyFood(SyncStore store, String uid) {
|
||||
final r = store.row('food.food', uid);
|
||||
|
|
@ -708,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);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue