Food: logged entries follow their food; barcodes for My foods

- Saving one of My foods or a meal works every entry logged from it out again
  for that entry's grams, on any day. Only the entries that change are
  written, so the rest aren't synced again (db._follow, app _follow).
- My foods can have a barcode (8-14 digits, one food per barcode). A scanned
  or typed barcode finds My foods first (leading zeros ignored), then the food
  database and kept products; when nothing matches, "New food with barcode"
  opens the food editor with it filled in.
- App 1.1.3 and 1.1.4 changelog entries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-10-26 14:08:32 +02:00
parent fb3c01cdd7
commit ad4b6aa22f
12 changed files with 238 additions and 30 deletions

View file

@ -13,6 +13,19 @@ 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 - The band's data goes with the phone's time zone, so the dashboard reads its times right without a
setting. setting.
## 1.1.4 — not published yet
- Food: My foods can have a barcode (the food editor, with a scan button). Scanning it, or typing it in the
search box, finds that food first.
- Food: a barcode nothing is found for offers "New food with barcode …", which opens the editor with the
barcode filled in. The dashboard does the same.
## 1.1.3 — 2026-10-26
- Food: editing a meal (its ingredients, weight when done) or one of My foods (its values or name) now
updates every entry logged with it, for that entry's grams — already-logged days included. The
dashboard does the same.
## 1.1.2 — 2026-10-23 ## 1.1.2 — 2026-10-23
- Work: grips at the top and bottom of a block — hold one and drag to start earlier / later or end - Work: grips at the top and bottom of a block — hold one and drag to start earlier / later or end

View file

@ -208,6 +208,7 @@ Food myFood(Map<String, dynamic> r) {
final ps = (jsonDecode((r['portions'] as String?) ?? '[]') as List).cast<Map<String, dynamic>>(); final ps = (jsonDecode((r['portions'] as String?) ?? '[]') as List).cast<Map<String, dynamic>>();
return Food( return Food(
ref: 'my:${r['_u']}', kind: 'my', name: r['name'] as String, category: 'My foods', myUid: r['_u'] as String, 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()}, 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())], portions: [for (final p in ps) Portion(p['label'] as String, (p['grams'] as num).toDouble())],
isMeal: r['recipe'] != null, isMeal: r['recipe'] != null,
@ -238,6 +239,16 @@ List<Food> myFoods(SyncStore store, String q, {int limit = 8}) {
return all.take(limit).map(myFood).toList(); 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) {
String bare(String c) => c.replaceFirst(RegExp(r'^0+'), '');
return [
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)
];
}
Food? myFoodByUid(SyncStore store, String uid) { Food? myFoodByUid(SyncStore store, String uid) {
final r = store.row('food.food', uid); final r = store.row('food.food', uid);
return r == null ? null : myFood(r); return r == null ? null : myFood(r);
@ -388,7 +399,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. /// 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, String? saveFromFood(SyncStore store, {String? u, required String day, required String meal, required Food food,
required double amount, required String unit, String note = ''}) { required double amount, required String unit, String note = ''}) {
final g = food.grams(amount, unit); final g = food.grams(amount, unit);
@ -522,8 +533,9 @@ const foodFields = {
/// New (uid null) or changed food: name unique among the live ones, energy required, portions need a /// 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). /// 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). /// [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, (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(' '); final n = name.trim().split(RegExp(r'\s+')).join(' ');
if (n.isEmpty) return (null, 'Name the food.'); if (n.isEmpty) return (null, 'Name the food.');
if (per100['kcal'] == null) return (null, 'Energy per 100 g — from the label.'); if (per100['kcal'] == null) return (null, 'Energy per 100 g — from the label.');
@ -538,6 +550,12 @@ const foodFields = {
final clash = store.rows('food.food').any((r) => final clash = store.rows('food.food').any((r) =>
(r['gone'] ?? 0) == 0 && r['_u'] != uid && (r['name'] as String).toLowerCase() == n.toLowerCase()); (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.'); 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 now = DateTime.now().toIso8601String().substring(0, 19);
final old = uid == null ? null : store.row('food.food', uid); final old = uid == null ? null : store.row('food.food', uid);
final u = uid ?? SyncStore.randomId(); final u = uid ?? SyncStore.randomId();
@ -547,11 +565,31 @@ const foodFields = {
...?old, ...?old,
'name': n, ...per100, 'note': note.trim(), 'updated': now, 'name': n, ...per100, 'note': note.trim(), 'updated': now,
if (sugarKind != null) 'sugar_kind': const ['added', 'dairy', 'natural'].contains(sugarKind) ? sugarKind : null, 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}]), '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);
return (u, null); return (u, null);
} }
/// 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. /// Deleted foods are only hidden (gone): entries made from them keep pointing at them.
void deleteMyFood(SyncStore store, String uid) { void deleteMyFood(SyncStore store, String uid) {
final r = store.row('food.food', uid); final r = store.row('food.food', uid);

View file

@ -2,8 +2,9 @@
// keyboard). Modes: // keyboard). Modes:
// search — the box: empty = yesterday's foods (this meal first; + adds one as it was, a tap picks // search — the box: empty = yesterday's foods (this meal first; + adds one as it was, a tap picks
// it to change the portion); typed = My foods · Eaten before · Food database · Products // it to change the portion); typed = My foods · Eaten before · Food database · Products
// (+ ones kept from the archive); a barcode (typed or scanned — the camera button) = that // (+ ones kept from the archive); a barcode (typed or scanned — the camera button) = My foods
// product; "Search all products…" = the archive on the sync server (food_archive.dart) // with it, else that product; nothing → "New food with barcode …" (it's kept with the food);
// "Search all products…" = the archive on the sync server (food_archive.dart)
// food — the picked food: amount + unit (g, ml, its portions, tbsp / tsp), the numbers live, meal // food — the picked food: amount + unit (g, ml, its portions, tbsp / tsp), the numbers live, meal
// totals — an entry without a food (Lifesum imports, estimates): name, kcal / P / C / F // totals — an entry without a food (Lifesum imports, estimates): name, kcal / P / C / F
// Editing an entry opens it in food or totals mode; Delete = tap twice. // Editing an entry opens it in food or totals mode; Delete = tap twice.
@ -143,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))])); if (rest.isNotEmpty) sections.add(('Yesterday · other meals', [for (final e in rest) _yday(e, already(e))]));
final recent = recentFoods(store, '', limit: 8); final recent = recentFoods(store, '', limit: 8);
if (recent.isNotEmpty) sections.add(('Eaten often', [for (final (e, n) in recent) _recent(e, n)])); 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: that product, here or kept } else if (RegExp(r'^\d{8,14}$').hasMatch(text)) { // a barcode: My foods with it, that product here or kept
final found = widget.fdb?.byBarcode(text) ?? keptByBarcode(store, text); final found = _byBarcode(text);
sections.add(('Barcode $text', [ sections.add(('Barcode $text', [
for (final f in found) _foodTile(f), for (final f in found) _foodTile(f),
if (found.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6), if (found.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
@ -194,12 +195,13 @@ class _FoodSheetState extends State<FoodSheet> {
if (text.isNotEmpty) if (text.isNotEmpty)
TextButton.icon( TextButton.icon(
onPressed: () async { onPressed: () async {
final uid = await openFoodEditor(context, widget.sync, name: text); final code = RegExp(r'^\d{8,14}$').hasMatch(text);
final uid = await openFoodEditor(context, widget.sync, name: code ? '' : text, barcode: code ? text : '');
final f = uid == null ? null : myFoodByUid(widget.sync.store, uid); final f = uid == null ? null : myFoodByUid(widget.sync.store, uid);
if (f != null && mounted) _pick(f); if (f != null && mounted) _pick(f);
}, },
icon: const Icon(Icons.add), icon: const Icon(Icons.add),
label: Text('New food “$text” (from its label)'), label: Text(RegExp(r'^\d{8,14}$').hasMatch(text) ? 'New food with barcode $text (from its label)' : 'New food “$text” (from its label)'),
), ),
if (text.isNotEmpty) if (text.isNotEmpty)
TextButton.icon( TextButton.icon(
@ -225,11 +227,16 @@ class _FoodSheetState extends State<FoodSheet> {
if (f != null && mounted) _pick(f); if (f != null && mounted) _pick(f);
} }
/// The camera → a barcode: its product here, else straight to the archive. /// 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)];
/// 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 …").
Future<void> _scan() async { Future<void> _scan() async {
final code = await scanBarcode(context); final code = await scanBarcode(context);
if (code == null || !mounted) return; if (code == null || !mounted) return;
final here = widget.fdb?.byBarcode(code) ?? keptByBarcode(widget.sync.store, code); final here = _byBarcode(code);
if (here.length == 1) return _pick(here.first); if (here.length == 1) return _pick(here.first);
setState(() => q.text = code); setState(() => q.text = code);
if (here.isEmpty) await _archive(code); if (here.isEmpty) await _archive(code);

View file

@ -8,6 +8,7 @@ import 'package:flutter/material.dart';
import '../app/sync_service.dart'; import '../app/sync_service.dart';
import '../app/theme.dart'; import '../app/theme.dart';
import 'food_archive.dart' show scanBarcode;
import 'food_model.dart'; import 'food_model.dart';
import 'meal_builder.dart'; import 'meal_builder.dart';
@ -82,20 +83,21 @@ class MyFoodsPage extends StatelessWidget {
); );
} }
/// The editor as a bottom sheet; → the saved food's id (null = cancelled / deleted). /// The editor as a bottom sheet; → the saved food's id (null = cancelled / deleted). [barcode]: a new food's,
Future<String?> openFoodEditor(BuildContext context, SyncService sync, {Map<String, dynamic>? row, String name = ''}) => /// from a scan / typed barcode nothing was found for.
Future<String?> openFoodEditor(BuildContext context, SyncService sync, {Map<String, dynamic>? row, String name = '', String barcode = ''}) =>
showModalBottomSheet<String>( showModalBottomSheet<String>(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
backgroundColor: card, backgroundColor: card,
builder: (_) => FoodEditor(sync: sync, row: row, name: name), builder: (_) => FoodEditor(sync: sync, row: row, name: name, barcode: barcode),
); );
class FoodEditor extends StatefulWidget { class FoodEditor extends StatefulWidget {
const FoodEditor({super.key, required this.sync, this.row, this.name = ''}); const FoodEditor({super.key, required this.sync, this.row, this.name = '', this.barcode = ''});
final SyncService sync; final SyncService sync;
final Map<String, dynamic>? row; final Map<String, dynamic>? row;
final String name; final String name, barcode;
@override @override
State<FoodEditor> createState() => _FoodEditorState(); State<FoodEditor> createState() => _FoodEditorState();
} }
@ -103,6 +105,7 @@ class FoodEditor extends StatefulWidget {
class _FoodEditorState extends State<FoodEditor> { class _FoodEditorState extends State<FoodEditor> {
late final name = TextEditingController(text: widget.row?['name'] as String? ?? widget.name); late final name = TextEditingController(text: widget.row?['name'] as String? ?? widget.name);
late final note = TextEditingController(text: widget.row?['note'] as String? ?? ''); late final note = TextEditingController(text: widget.row?['note'] as String? ?? '');
late final barcode = TextEditingController(text: widget.row?['barcode'] as String? ?? widget.barcode);
late String sugarKind = widget.row?['sugar_kind'] as String? ?? ''; // '' = estimated (sugar.dart) late String sugarKind = widget.row?['sugar_kind'] as String? ?? ''; // '' = estimated (sugar.dart)
late final values = { late final values = {
for (final k in foodFields.keys) for (final k in foodFields.keys)
@ -127,7 +130,7 @@ class _FoodEditorState extends State<FoodEditor> {
} }
final (uid, err) = saveMyFood(widget.sync.store, uid: widget.row?['_u'] as String?, name: name.text, final (uid, err) = saveMyFood(widget.sync.store, uid: widget.row?['_u'] as String?, name: name.text,
per100: isMeal ? {for (final k in foodFields.keys) k: (widget.row![k] as num?)?.toDouble()} : {for (final e in values.entries) e.key: _n(e.value)}, per100: isMeal ? {for (final k in foodFields.keys) k: (widget.row![k] as num?)?.toDouble()} : {for (final e in values.entries) e.key: _n(e.value)},
portions: ps, note: note.text, sugarKind: sugarKind); portions: ps, note: note.text, sugarKind: sugarKind, barcode: barcode.text);
if (err != null) return setState(() => error = err); if (err != null) return setState(() => error = err);
widget.sync.changed(); widget.sync.changed();
Navigator.pop(context, uid); Navigator.pop(context, uid);
@ -142,6 +145,23 @@ class _FoodEditorState extends State<FoodEditor> {
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
TextField(controller: name, autofocus: widget.row == null && widget.name.isEmpty, TextField(controller: name, autofocus: widget.row == null && widget.name.isEmpty,
decoration: const InputDecoration(labelText: 'Name')), decoration: const InputDecoration(labelText: 'Name')),
if (!isMeal)
TextField(
controller: barcode,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Barcode',
hintText: 'optional — scanning it finds this food',
suffixIcon: IconButton(
tooltip: 'Scan a barcode',
icon: const Icon(Icons.qr_code_scanner),
onPressed: () async {
final code = await scanBarcode(context);
if (code != null && mounted) setState(() => barcode.text = code);
},
),
),
),
const SizedBox(height: 10), const SizedBox(height: 10),
Text(isMeal ? 'Per 100 g — from its ingredients (change them with the meal builder)' : 'Per 100 g (from the label)', Text(isMeal ? 'Per 100 g — from its ingredients (change them with the meal builder)' : 'Per 100 g (from the label)',
style: const TextStyle(color: muted, fontSize: 13)), style: const TextStyle(color: muted, fontSize: 13)),

View file

@ -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 # 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 # 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. # of the product and file versions while build-number is used as the build suffix.
version: 1.1.2+5 version: 1.1.4+6
environment: environment:
sdk: ^3.12.2 sdk: ^3.12.2

View file

@ -0,0 +1,40 @@
// My foods with the pack's barcode (food_model.dart saveMyFood / myFoodsByBarcode = the dashboard's db.clean_food /
// my_foods_by_barcode): kept, found by it (leading zeros or not), checked, one food per barcode, left alone when not given.
import 'dart:io';
import 'package:dash_app/health/food_model.dart';
import 'package:dash_app/sync/store.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final store = SyncStore('${Directory.systemTemp.createTempSync('barcode').path}/d.db', 'test00000000');
test('kept and found by it', () {
final (u, err) = saveMyFood(store, name: 'Chicory syrup (4Slim)', per100: {'kcal': 161, 'fiber': 71}, portions: [],
barcode: '8595245311155');
expect(err, isNull);
expect(myFoodsByBarcode(store, '8595245311155').single.myUid, u);
expect(myFoodsByBarcode(store, '08595245311155').single.name, 'Chicory syrup (4Slim)');
expect(myFoodByUid(store, u!)!.barcode, '8595245311155');
expect(myFoodsByBarcode(store, '1234567890123'), isEmpty);
});
test('checked: digits only, 8–14, one food per barcode', () {
expect(saveMyFood(store, name: 'A', per100: {'kcal': 1}, portions: [], barcode: '12ab5678').$2, 'A barcode is 8–14 digits.');
expect(saveMyFood(store, name: 'B', per100: {'kcal': 1}, portions: [], barcode: '1234567').$2, 'A barcode is 8–14 digits.');
expect(saveMyFood(store, name: 'C', per100: {'kcal': 1}, portions: [], barcode: '8595245311155').$2, contains('has that barcode already'));
});
test('an edit without it keeps it; empty clears it; a deleted food is not found', () {
final u = myFoodsByBarcode(store, '8595245311155').single.myUid!;
saveMyFood(store, uid: u, name: 'Chicory syrup (4Slim)', per100: {'kcal': 160}, portions: []);
expect(store.row('food.food', u)!['barcode'], '8595245311155');
saveMyFood(store, uid: u, name: 'Chicory syrup (4Slim)', per100: {'kcal': 160}, portions: [], barcode: ' 8595245311155 ');
expect(store.row('food.food', u)!['barcode'], '8595245311155');
deleteMyFood(store, u);
expect(myFoodsByBarcode(store, '8595245311155'), isEmpty);
final (v, _) = saveMyFood(store, name: 'D', per100: {'kcal': 1}, portions: [], barcode: '8595245311155');
saveMyFood(store, uid: v, name: 'D', per100: {'kcal': 1}, portions: [], barcode: '');
expect(store.row('food.food', v!)!['barcode'], isNull);
});
}

View file

@ -0,0 +1,50 @@
// Entries logged from one of My foods follow its edits (food_model.dart _follow = the dashboard's db._follow):
// a meal's new recipe or a food's new values / name re-work them for their grams; others aren't touched.
import 'dart:io';
import 'package:dash_app/health/food_model.dart';
import 'package:dash_app/sync/store.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final store = SyncStore('${Directory.systemTemp.createTempSync('follow').path}/d.db', 'test00000000');
test('editing a food re-works its entries', () {
final (u, err) = saveMyFood(store, name: 'Tvaroh', per100: {'kcal': 200, 'protein': 14, 'fat': 15}, portions: []);
expect(err, isNull);
final f = myFoodByUid(store, u!)!;
saveFromFood(store, u: 'e1', day: '2026-10-26', meal: 'lunch', food: f, amount: 100, unit: 'g');
saveFromFood(store, u: 'e2', day: '2026-10-27', meal: 'lunch', food: f, amount: 150, unit: 'g');
saveTotals(store, u: 'e3', day: '2026-10-27', meal: 'lunch', name: 'Tvaroh', values: {'kcal': 300});
final h3 = store.rows('food.entry').firstWhere((r) => r['_u'] == 'e3')['_h'];
saveMyFood(store, uid: u, name: 'Tvaroh (homemade)', per100: {'kcal': 212, 'protein': 14, 'fat': 16}, portions: []);
expect(store.row('food.entry', 'e1')!['kcal'], 212);
expect(store.row('food.entry', 'e2')!['kcal'], 318);
expect(store.row('food.entry', 'e2')!['fat'], 24);
expect(store.row('food.entry', 'e2')!['name'], 'Tvaroh (homemade)');
expect(store.row('food.entry', 'e3')!['kcal'], 300); // typed numbers, no food: left alone
expect(store.rows('food.entry').firstWhere((r) => r['_u'] == 'e3')['_h'], h3);
});
test('unchanged entries are not re-sent', () {
final (u, _) = saveMyFood(store, name: 'Casein', per100: {'kcal': 390}, portions: []);
saveFromFood(store, u: 'c1', day: '2026-10-26', meal: 'breakfast', food: myFoodByUid(store, u!)!, amount: 30, unit: 'g');
final h = store.rows('food.entry').firstWhere((r) => r['_u'] == 'c1')['_h'];
saveMyFood(store, uid: u, name: 'Casein', per100: {'kcal': 390}, portions: [], note: 'a note');
expect(store.rows('food.entry').firstWhere((r) => r['_u'] == 'c1')['_h'], h);
});
test('a meal’s new recipe re-works its entries', () {
final (oil, _) = saveMyFood(store, name: 'Oil', per100: {'kcal': 900, 'fat': 100}, portions: []);
final (veg, _) = saveMyFood(store, name: 'Veg', per100: {'kcal': 30, 'fat': 0}, portions: []);
Ingredient ing(String uid, double g) => Ingredient.food(myFoodByUid(store, uid)!, g, 'g');
final (soup, err) = saveMeal(store, name: 'Soup', ings: [ing(oil!, 30), ing(veg!, 970)], portions: []);
expect(err, isNull);
saveFromFood(store, u: 's1', day: '2026-10-27', meal: 'lunch', food: myFoodByUid(store, soup!)!, amount: 400, unit: 'g');
expect(store.row('food.entry', 's1')!['kcal'], closeTo(400 * (27000 + 29100) / 100000, 0.01));
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));
});
}

View file

@ -260,12 +260,13 @@ def register(ctx):
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 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
@bp.route("/api/foods") @bp.route("/api/foods")
def api_foods(): # ?q= → {recent, mine, db, products} — the form's suggestions (a barcode: its product) def api_foods(): # ?q= → {recent, mine, db, products} — the form's suggestions (a barcode: My foods / its product)
q = request.args.get("q", "")[:60] q = request.args.get("q", "")[:60]
code = q.strip() if re.fullmatch(r"\s*\d{8,14}\s*", q) else None code = q.strip() if re.fullmatch(r"\s*\d{8,14}\s*", q) else None
with con() as c: with con() as c:
if code: # scanned / typed off the pack if code: # scanned / typed off the pack
return jsonify(recent=[], mine=[], db=[], products=fooddb.by_barcode(foods_db, code) or db.products(c, barcode=code)) 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))
rows = db.foods(c, q, limit=5) rows = db.foods(c, q, limit=5)
mine = db.my_foods(c, q, limit=8) mine = db.my_foods(c, q, limit=8)
kept = db.products(c, q, limit=4, fold=sugar.fold) # picked from the archive before kept = db.products(c, q, limit=4, fold=sugar.fold) # picked from the archive before
@ -393,7 +394,7 @@ def register(ctx):
return jsonify(ok=True, ids=ids) return jsonify(ok=True, ids=ids)
@bp.route("/api/myfood", methods=["POST"]) @bp.route("/api/myfood", methods=["POST"])
def api_myfood(): # {id?, name, per100, portions, note} — My foods page def api_myfood(): # {id?, name, per100, portions, note, sugar_kind, barcode} — My foods page
d = body() d = body()
with con() as c: with con() as c:
try: try:

View file

@ -28,6 +28,7 @@ health/hc.py imports Health Connect nutrition (Lifesum) through import_health_co
""" """
import json import json
import os import os
import re
import sqlite3 import sqlite3
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
@ -67,7 +68,8 @@ CREATE TABLE IF NOT EXISTS food (
updated TEXT NOT NULL, updated TEXT NOT NULL,
gone INTEGER NOT NULL DEFAULT 0, -- deleted: hidden, entries still point at it gone INTEGER NOT NULL DEFAULT 0, -- deleted: hidden, entries still point at it
recipe TEXT, -- a meal: {"ingredients": [{food, name, amount, unit, grams}], "done_grams"} recipe TEXT, -- a meal: {"ingredients": [{food, name, amount, unit, grams}], "done_grams"}
sugar_kind TEXT -- added / dairy / natural: how its sugar counts (NULL = estimated, sugar.py) sugar_kind TEXT, -- added / dairy / natural: how its sugar counts (NULL = estimated, sugar.py)
barcode TEXT -- the pack's (8–14 digits): a scan / typed barcode finds it
); );
CREATE TABLE IF NOT EXISTS product ( CREATE TABLE IF NOT EXISTS product (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
@ -81,7 +83,7 @@ CREATE TABLE IF NOT EXISTS product (
""" """
ADDED = {"amount": "REAL", "unit": "TEXT", "note": "TEXT NOT NULL DEFAULT ''", # columns newer than the first food.db ADDED = {"amount": "REAL", "unit": "TEXT", "note": "TEXT NOT NULL DEFAULT ''", # columns newer than the first food.db
"food_id": "INTEGER", "grams": "REAL", "my_food_id": "INTEGER"} "food_id": "INTEGER", "grams": "REAL", "my_food_id": "INTEGER"}
FOOD_ADDED = {"recipe": "TEXT", "sugar_kind": "TEXT"} # columns newer than the first `food` table FOOD_ADDED = {"recipe": "TEXT", "sugar_kind": "TEXT", "barcode": "TEXT"} # columns newer than the first `food` table
SUGAR_KINDS = ("added", "dairy", "natural") # My foods' sugar_kind (sugar.py) SUGAR_KINDS = ("added", "dairy", "natural") # My foods' sugar_kind (sugar.py)
MEAL_KEYS = ("breakfast", "lunch", "dinner", "snack") MEAL_KEYS = ("breakfast", "lunch", "dinner", "snack")
@ -285,7 +287,8 @@ def _food(r, uses=None):
"based_on": r["based_on"], "based_on_name": r["based_on_name"], "note": r["note"], "based_on": r["based_on"], "based_on_name": r["based_on_name"], "note": r["note"],
"updated": r["updated"], "gone": bool(r["gone"]), "uses": uses, "updated": r["updated"], "gone": bool(r["gone"]), "uses": uses,
"recipe": json.loads(r["recipe"]) if r["recipe"] else None, "recipe": json.loads(r["recipe"]) if r["recipe"] else None,
"sugar_kind": r["sugar_kind"] if "sugar_kind" in r.keys() else None} "sugar_kind": r["sugar_kind"] if "sugar_kind" in r.keys() else None,
"barcode": r["barcode"] if "barcode" in r.keys() else None}
# ---- products picked from the archive ------------------------------------------------------------ # ---- products picked from the archive ------------------------------------------------------------
@ -363,6 +366,14 @@ def my_foods(con, q="", limit=None):
return [_food(r, r["uses"]) for r in rows] 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."""
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()
return [_food(r, r["uses"]) for r in rows]
def my_food(con, fid): def my_food(con, fid):
r = con.execute("SELECT * FROM food WHERE id = ?", (fid,)).fetchone() r = con.execute("SELECT * FROM food WHERE id = ?", (fid,)).fetchone()
return _food(r) if r else None return _food(r) if r else None
@ -398,6 +409,11 @@ def clean_food(d, base=None):
out["portions"] = json.dumps(ps) out["portions"] = json.dumps(ps)
if "sugar_kind" in d: # the form's "Sugar counts as" (absent: left as it is) if "sugar_kind" in d: # the form's "Sugar counts as" (absent: left as it is)
out["sugar_kind"] = d["sugar_kind"] if d["sugar_kind"] in SUGAR_KINDS else None out["sugar_kind"] = d["sugar_kind"] if d["sugar_kind"] in SUGAR_KINDS else None
if "barcode" in d: # the pack's barcode (absent: left as it is)
code = re.sub(r"\s", "", str(d["barcode"] or ""))
if code and not re.fullmatch(r"\d{8,14}", code):
raise Invalid("barcode", "A barcode is 8–14 digits.")
out["barcode"] = code or None
return out return out
@ -412,9 +428,14 @@ def _write_food(con, v, base=None, fid=None):
(v["name"].lower(), fid or 0)).fetchone() (v["name"].lower(), fid or 0)).fetchone()
if clash: if clash:
raise Invalid("name", "You already have a food with that name in My foods — pick it, or name this one differently.") raise Invalid("name", "You already have a food with that name in My foods — pick it, or name this one differently.")
if v.get("barcode"):
other = [f for f in my_foods_by_barcode(con, v["barcode"]) if f["id"] != fid]
if other:
raise Invalid("barcode", f"“{other[0]['name']}” in My foods has that barcode already.")
now = datetime.now().isoformat(timespec="seconds") now = datetime.now().isoformat(timespec="seconds")
if fid: if fid:
con.execute(f"UPDATE food SET {', '.join(f'{k} = ?' for k in v)}, updated = ? WHERE id = ?", (*v.values(), now, fid)) con.execute(f"UPDATE food SET {', '.join(f'{k} = ?' for k in v)}, updated = ? WHERE id = ?", (*v.values(), now, fid))
_follow(con, fid)
else: else:
if base and base.get("kind") in ("usda", "off"): if base and base.get("kind") in ("usda", "off"):
v.update(based_on=base["id"], based_on_name=base["name"]) v.update(based_on=base["id"], based_on_name=base["name"])
@ -424,7 +445,19 @@ def _write_food(con, v, base=None, fid=None):
return fid return fid
MEAL_MAX = 40 # ingredients def _follow(con, fid):
"""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.
Same in the app (food_model.dart _follow)."""
f = con.execute("SELECT * FROM food WHERE id = ?", (fid,)).fetchone()
for e in con.execute("SELECT * FROM entry WHERE my_food_id = ? AND grams > 0", (fid,)).fetchall():
new = {c: (round(f[c] * e["grams"] / 100, 2) if f[c] is not None else None) for c in FOOD_COLS}
new["name"] = f["name"]
if any(e[k] != v for k, v in new.items()):
con.execute(f"UPDATE entry SET {', '.join(f'{k} = ?' for k in new)} WHERE id = ?", (*new.values(), e["id"]))
MEAL_MAX = 40 # ingredients
def save_meal(con, d, resolve, fid=None): def save_meal(con, d, resolve, fid=None):

View file

@ -480,3 +480,4 @@ body.fd-dragging, body.fd-dragging * { cursor: grabbing !important; user-select:
.fd-skind { display: flex; align-items: center; gap: 10px; margin-top: 8px; } .fd-skind { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
.fd-skind span { color: var(--muted); font-size: 13px; } .fd-skind span { color: var(--muted); font-size: 13px; }
.fd-skind select { background: #262d3b; color: inherit; border: 1px solid #39425a; border-radius: 7px; padding: 5px 8px; font: inherit; font-size: 13px; } .fd-skind select { background: #262d3b; color: inherit; border: 1px solid #39425a; border-radius: 7px; padding: 5px 8px; font: inherit; font-size: 13px; }
.fd-bc input { max-width: 16em; }

View file

@ -58,7 +58,8 @@
if (!items.length) return hide(); if (!items.length) return hide();
let head = ""; let head = "";
ul.innerHTML = items.map((f, i) => { ul.innerHTML = items.map((f, i) => {
if (f.new) return `<li role="option" data-i="${i}" class="fd-snew${i === on ? " on" : ""}"><b>+ New food “${esc(f.name)}”</b>` + if (f.new) return `<li role="option" data-i="${i}" class="fd-snew${i === on ? " on" : ""}"><b>${/^\d{8,14}$/.test(f.name)
? `+ New food with barcode ${esc(f.name)}` : `+ New food “${esc(f.name)}”`}</b>` +
`<span class="fd-sk"></span><small>enter its values per 100 g — saved to My foods</small><span class="fd-ss"></span></li>`; `<span class="fd-sk"></span><small>enter its values per 100 g — saved to My foods</small><span class="fd-ss"></span></li>`;
if (f.ext) return `<li role="option" data-i="${i}" class="fd-sext${i === on ? " on" : ""}"><b>${/^\d{8,14}$/.test(f.name) if (f.ext) return `<li role="option" data-i="${i}" class="fd-sext${i === on ? " on" : ""}"><b>${/^\d{8,14}$/.test(f.name)
? `Look up barcode ${esc(f.name)} in all products…` : `Search all products for “${esc(f.name)}”…`}</b>` + ? `Look up barcode ${esc(f.name)} in all products…` : `Search all products for “${esc(f.name)}”…`}</b>` +
@ -373,14 +374,15 @@
units(e.unit || ""); units(e.unit || "");
q(".fd-ie-a").focus(); q(".fd-ie-a").focus();
} }
function startNew(name) { // a food typed in: values per 100 g function startNew(name) { // a food typed in: values per 100 g (a barcode: kept with it)
st.food = null; st.base = null; st.food = null; st.base = null;
q(".fd-ie-nm").value = name; st.barcode = /^\d{8,14}$/.test(name) ? name : null;
q(".fd-ie-nm").value = st.barcode ? "" : name;
fillPer(null); fillPer(null);
portionRow({}, q(".fd-plist")); portionRow({}, q(".fd-plist"));
q(".fd-ie-a").value = "100"; q(".fd-ie-a").value = "100";
setMode("new"); setMode("new");
el.querySelector('[data-k="kcal"]').focus(); (st.barcode ? q(".fd-ie-nm") : el.querySelector('[data-k="kcal"]')).focus();
} }
async function pick(f) { async function pick(f) {
if (f.new) return startNew(f.name); if (f.new) return startNew(f.name);
@ -406,7 +408,8 @@
const foodData = () => { const foodData = () => {
const per100 = {}; const per100 = {};
el.querySelectorAll("[data-k]").forEach((i) => { per100[i.dataset.k] = i.value; }); el.querySelectorAll("[data-k]").forEach((i) => { per100[i.dataset.k] = i.value; });
return { name: q(".fd-ie-nm").value, per100, portions: portionsTyped(q(".fd-plist")), note: st.food?.note || "" }; return { name: q(".fd-ie-nm").value, per100, portions: portionsTyped(q(".fd-plist")), note: st.food?.note || "",
...(st.mode === "new" && st.barcode ? { barcode: st.barcode } : {}) };
}; };
if (st.mode === "search") return err("Pick a food first.", "name"); if (st.mode === "search") return err("Pick a food first.", "name");
if (st.mode === "food") d.food = st.food.ref; if (st.mode === "food") d.food = st.food.ref;
@ -488,6 +491,7 @@
(f ? f.portions : [{}]).forEach((p) => portionRow(p, plist)); (f ? f.portions : [{}]).forEach((p) => portionRow(p, plist));
F.note.value = f ? (f.note || "") : ""; F.note.value = f ? (f.note || "") : "";
F.sugar_kind.value = f ? (f.sugar_kind || "") : ""; F.sugar_kind.value = f ? (f.sugar_kind || "") : "";
F.barcode.value = f ? (f.barcode || "") : "";
box.querySelector(".fd-ftitle").textContent = f ? "Edit food" : "New food"; box.querySelector(".fd-ftitle").textContent = f ? "Edit food" : "New food";
const del = box.querySelector(".fd-del"); const del = box.querySelector(".fd-del");
del.hidden = !f; del.classList.remove("armed"); del.textContent = "Delete"; del.hidden = !f; del.classList.remove("armed"); del.textContent = "Delete";
@ -521,7 +525,7 @@
const per100 = {}; const per100 = {};
NUT.forEach((k) => { per100[k] = F[k].value; }); NUT.forEach((k) => { per100[k] = F[k].value; });
await post("/food/api/myfood", { id: F.id.value || null, name: F.name.value, per100, portions: portionsTyped(plist), note: F.note.value, await post("/food/api/myfood", { id: F.id.value || null, name: F.name.value, per100, portions: portionsTyped(plist), note: F.note.value,
sugar_kind: F.sugar_kind.value }); sugar_kind: F.sugar_kind.value, barcode: F.barcode.value });
close(); onSaved?.(); close(); onSaved?.();
} catch (x) { ferr(x.message, x.field); } } catch (x) { ferr(x.message, x.field); }
finally { s.disabled = false; } finally { s.disabled = false; }

View file

@ -125,6 +125,7 @@
<div class="fd-ftitle">New food</div> <div class="fd-ftitle">New food</div>
<input type="hidden" name="id"> <input type="hidden" name="id">
<label class="fd-name"><span>Food</span><input name="name" maxlength="120"></label> <label class="fd-name"><span>Food</span><input name="name" maxlength="120"></label>
<label class="fd-bc" title="The pack's barcode: scanning it or typing it in the add box finds this food"><span>Barcode</span><input name="barcode" inputmode="numeric" maxlength="14" placeholder="optional"></label>
<fieldset class="fd-per"> <fieldset class="fd-per">
<legend class="fd-perh">Per 100 g</legend> <legend class="fd-perh">Per 100 g</legend>
<div class="fd-nut"> <div class="fd-nut">