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:
parent
fb3c01cdd7
commit
ad4b6aa22f
12 changed files with 238 additions and 30 deletions
|
|
@ -208,6 +208,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 +239,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) {
|
||||
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) {
|
||||
final r = store.row('food.food', uid);
|
||||
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.
|
||||
/// 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 +533,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,6 +550,12 @@ 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();
|
||||
|
|
@ -547,11 +565,31 @@ const foodFields = {
|
|||
...?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) _follow(store, u);
|
||||
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.
|
||||
void deleteMyFood(SyncStore store, String uid) {
|
||||
final r = store.row('food.food', uid);
|
||||
|
|
|
|||
|
|
@ -2,8 +2,9 @@
|
|||
// keyboard). Modes:
|
||||
// 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
|
||||
// (+ ones kept from the archive); a barcode (typed or scanned — the camera button) = that
|
||||
// product; "Search all products…" = the archive on the sync server (food_archive.dart)
|
||||
// (+ ones kept from the archive); a barcode (typed or scanned — the camera button) = My foods
|
||||
// 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
|
||||
// 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.
|
||||
|
|
@ -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))]));
|
||||
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: that product, here or kept
|
||||
final found = widget.fdb?.byBarcode(text) ?? keptByBarcode(store, text);
|
||||
} else if (RegExp(r'^\d{8,14}$').hasMatch(text)) { // a barcode: My foods with it, that product here or kept
|
||||
final found = _byBarcode(text);
|
||||
sections.add(('Barcode $text', [
|
||||
for (final f in found) _foodTile(f),
|
||||
if (found.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
|
||||
|
|
@ -194,12 +195,13 @@ class _FoodSheetState extends State<FoodSheet> {
|
|||
if (text.isNotEmpty)
|
||||
TextButton.icon(
|
||||
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);
|
||||
if (f != null && mounted) _pick(f);
|
||||
},
|
||||
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)
|
||||
TextButton.icon(
|
||||
|
|
@ -225,11 +227,16 @@ class _FoodSheetState extends State<FoodSheet> {
|
|||
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 {
|
||||
final code = await scanBarcode(context);
|
||||
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);
|
||||
setState(() => q.text = code);
|
||||
if (here.isEmpty) await _archive(code);
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import 'package:flutter/material.dart';
|
|||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import 'food_archive.dart' show scanBarcode;
|
||||
import 'food_model.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).
|
||||
Future<String?> openFoodEditor(BuildContext context, SyncService sync, {Map<String, dynamic>? row, String name = ''}) =>
|
||||
/// The editor as a bottom sheet; → the saved food's id (null = cancelled / deleted). [barcode]: a new food's,
|
||||
/// 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>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: card,
|
||||
builder: (_) => FoodEditor(sync: sync, row: row, name: name),
|
||||
builder: (_) => FoodEditor(sync: sync, row: row, name: name, barcode: barcode),
|
||||
);
|
||||
|
||||
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 Map<String, dynamic>? row;
|
||||
final String name;
|
||||
final String name, barcode;
|
||||
@override
|
||||
State<FoodEditor> createState() => _FoodEditorState();
|
||||
}
|
||||
|
|
@ -103,6 +105,7 @@ class FoodEditor extends StatefulWidget {
|
|||
class _FoodEditorState extends State<FoodEditor> {
|
||||
late final name = TextEditingController(text: widget.row?['name'] as String? ?? widget.name);
|
||||
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 final values = {
|
||||
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,
|
||||
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);
|
||||
widget.sync.changed();
|
||||
Navigator.pop(context, uid);
|
||||
|
|
@ -142,6 +145,23 @@ class _FoodEditorState extends State<FoodEditor> {
|
|||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||||
TextField(controller: name, autofocus: widget.row == null && widget.name.isEmpty,
|
||||
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),
|
||||
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)),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue