dashPi: a self-hosted home dashboard, its sync server and phone app

The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end
encrypted sync mailbox (PHP + SQLite) and the Android companion app
(Flutter), with docs, clean-install checks and screenshots made from
demo data.

Built mostly with an AI coding assistant; not yet reviewed line by line
by a human (see README and SECURITY.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-10-24 09:35:12 +02:00
commit fb3c01cdd7
333 changed files with 45151 additions and 0 deletions

View file

@ -0,0 +1,720 @@
// The food diary — a port of the dashboard's plugins/food: db.py (what an entry is, recent foods),
// fooddb.py (the food database: search, portions → grams → nutrients), views.py (totals, targets,
// the ring, the bars). Keep them in step with the web pages.
//
// Synced rows: "food.entry" {day, time, meal, name, kcal, protein, carbs, sugar, fiber, fat, sat_fat,
// mono_fat, poly_fat, trans_fat, sodium_mg, cholesterol_mg, potassium_mg, micros, source, src_id,
// amount, unit, note, food_id (foods.db id), grams, my_food_id (a "food.food" id)}; "food.food" =
// My foods + meals (per 100 g, portions JSON, recipe JSON, gone).
// foods.db (USDA + Open Food Facts, read-only) ships with the app — the same file as on the Pi, so
// food_id means the same food on both. "food.product" = shop products picked from the archive on the
// sync server (every Open Food Facts product; uid "p:<food_id>", {food_id, name, brand, barcode, data
// JSON = the product, added}) — FoodDb.food finds them too, so entries made from them work everywhere.
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
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 'summaries.dart';
const mealKeys = ['breakfast', 'lunch', 'dinner', 'snack'];
const mealLabels = {'breakfast': 'Breakfast', 'lunch': 'Lunch', 'dinner': 'Dinner', 'snack': 'Snacks', '': 'Other'};
const kcalPerG = {'protein': 4, 'carbs': 4, 'fat': 9};
const macros = ['protein', 'carbs', 'fat'];
const foodCols = ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'mono_fat', 'poly_fat', 'trans_fat',
'sodium_mg', 'cholesterol_mg', 'potassium_mg'];
const reuseSources = {'manual', 'parsed'}; // entries worth offering again (imports are too rough)
const generic = {'tbsp (15 ml)': 15.0, 'tsp (5 ml)': 5.0}; // spoons every food can be measured in (ml as g)
/// The dashboard's Settings ▸ Food, as its Health summary brings it (meta:food); its defaults until then.
class FoodSettings {
const FoodSettings({this.goalRate = 0, this.split = (20, 50, 30), this.kcalTarget = 0, this.fiberMin = 25,
this.sugarMax = 50, this.sodiumMax = 2000});
final double goalRate; // % of the weight a week (0 = keep it)
final (int, int, int) split; // protein / carbs / fat % of the energy
final int kcalTarget, fiberMin, sugarMax, sodiumMax;
static FoodSettings of(SyncStore store) {
final m = Summaries(store).meta('food');
if (m == null) return const FoodSettings();
final sp = (m['split'] as List?)?.map((v) => (v as num).toInt()).toList();
int n(String k, int d) => (m[k] as num?)?.toInt() ?? d;
return FoodSettings(
goalRate: (m['goal_rate'] as num?)?.toDouble() ?? 0,
split: sp != null && sp.length == 3 ? (sp[0], sp[1], sp[2]) : (20, 50, 30),
kcalTarget: n('kcal_target', 0), fiberMin: n('fiber_min', 25), sugarMax: n('sugar_max', 50),
sodiumMax: n('sodium_max', 2000));
}
}
// ---- a food (the database's or one of My foods) ---------------------------------------------
class Portion {
const Portion(this.label, this.grams);
final String label;
final double grams;
}
class Food {
Food({required this.ref, required this.kind, required this.name, this.category = '', this.brand, this.barcode, required this.per100,
required this.portions, this.nutriscore, this.nova, this.foodId, this.myUid, this.isMeal = false, this.source = '',
this.labels = '', this.sugarsIn, this.dairy, this.addedSugar});
final String ref, kind, name, category; // ref "usda:ID" / "my:UID"; kind usda / off / my
final String source, labels; // foods.db: foundation / sr_legacy / survey / off; OFF labels ("no added sugar" …)
final String? brand, barcode, nutriscore;
final int? nova, foodId;
// off.py's facts for the added-sugar estimate (sugar.dart): the sweet ingredients ("" = none; null = not known),
// filed as dairy (1 / 0), the label's added sugars g / 100 g
final String? sugarsIn;
final int? dairy;
final double? addedSugar;
final String? myUid;
final Map<String, double?> per100;
final List<Portion> portions;
final bool isMeal;
/// g, ml, its portions, and the generic spoons unless it has its own (food.js unitsOf).
List<String> get units {
final own = portions.map((p) => p.label).toList();
final hasSpoon = own.any((l) => RegExp(r'^(tablespoon|tbsp|teaspoon|tsp)', caseSensitive: false).hasMatch(l));
return ['g', 'ml', ...own, if (!hasSpoon) ...generic.keys];
}
/// Grams of [amount] [unit] (fooddb.portion for the units the form offers), or null.
double? grams(double amount, String unit) {
if (unit == 'g' || unit == 'ml') return amount;
if (generic.containsKey(unit)) return amount * generic[unit]!;
for (final p in portions) {
if (p.label == unit) return amount * p.grams;
}
return null;
}
/// The food's columns for that many grams (fooddb.nutrients).
Map<String, double?> nutrients(double grams) =>
{for (final c in foodCols) c: per100[c] == null ? null : (per100[c]! * grams / 100 * 100).round() / 100};
}
// ---- foods.db (the database) ---------------------------------------------------------------
class FoodDb {
FoodDb._(this.db);
final Database db;
static FoodDb? _one;
static SyncStore? store; // the synced data: products kept from the archive ("food.product") — set in main.dart
/// Copies the shipped foods.db out of the app (once per version of the file) and opens it read-only.
static Future<FoodDb> open() async {
if (_one != null) return _one!;
final data = await rootBundle.load('assets/foods.db');
final path = '${(await getApplicationSupportDirectory()).path}/foods.db';
final f = File(path);
if (!f.existsSync() || f.lengthSync() != data.lengthInBytes) {
await f.writeAsBytes(data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes), flush: true);
}
return _one = FoodDb._(sqlite3.open(path, mode: OpenMode.readOnly));
}
static const _stop = {'with', 'and', 'of', 'a', 'an', 'the', 'in', 'on', 'some', 'my'};
static const _plain = {'nfs', 'raw', 'whole', 'plain', 'regular', 'fresh', 'cooked', 'boiled'};
static const _rank = {'foundation': 0, 'sr_legacy': 1, 'survey': 2, 'off': 3};
static List<String> words(String q) => RegExp(r'\w+', unicode: true)
.allMatches(q.toLowerCase())
.map((m) => m.group(0)!)
.where((w) => (w.length > 1 || int.tryParse(w) != null) && !_stop.contains(w))
.toList();
Food _food(Row r) {
final off = r['source'] == 'off';
return Food(
ref: 'usda:${r['id']}', kind: off ? 'off' : 'usda', name: r['name'] as String, category: r['category'] as String? ?? '',
brand: r['brand'] as String?, barcode: r.containsKey('barcode') ? r['barcode'] as String? : null,
nutriscore: r['nutriscore'] as String?, nova: (r['nova'] as num?)?.toInt(),
foodId: r['id'] as int, source: r['source'] as String? ?? '', labels: r['labels'] as String? ?? '',
// a foods.db older than these columns: none of them (the old rule)
sugarsIn: r.containsKey('sugars_in') ? r['sugars_in'] as String? : null,
dairy: r.containsKey('dairy') ? (r['dairy'] as num?)?.toInt() : null,
addedSugar: r.containsKey('added_sugar') ? (r['added_sugar'] as num?)?.toDouble() : null,
per100: {for (final c in foodCols) c: (r[c] as num?)?.toDouble()},
portions: [
for (final p in db.select('SELECT label, grams FROM portion WHERE food_id = ? ORDER BY seq, grams', [r['id']]))
Portion(p['label'] as String, (p['grams'] as num).toDouble())
],
);
}
/// A food of the database by id: foods.db's, else a product kept from the archive.
Food? food(int id) {
final r = db.select('SELECT * FROM food WHERE id = ?', [id]).firstOrNull;
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);
}
/// fooddb.search: every word a prefix in name / brand / category; all in the name first, the name starting
/// with the first word, plain versions (raw, NFS …), fewer words, relevance, shorter names; one per name.
List<Food> search(String q, {int limit = 10}) {
final ws = words(q);
if (ws.isEmpty) return [];
final terms = ws.map((w) => '"$w"*').join(' ');
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]);
final first = ws.first;
List<num> key(Row r) {
final name = (r['name'] as String).toLowerCase();
final nameWords = RegExp(r'\w+', unicode: true).allMatches(name).map((m) => m.group(0)!).toList();
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 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];
}
final sorted = rs.toList()
..sort((a, b) {
final ka = key(a), kb = key(b);
for (var i = 0; i < ka.length; i++) {
final c = ka[i].compareTo(kb[i]);
if (c != 0) return c;
}
return 0;
});
final seen = <String>{}, out = <Food>[];
for (final r in sorted) {
if (seen.add((r['name'] as String).toLowerCase())) out.add(_food(r));
if (out.length >= limit) break;
}
return out;
}
}
// ---- My foods ------------------------------------------------------------------------------
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,
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,
);
}
/// My foods (not deleted) with every word of q in the name; exact / starting first, then the most used.
List<Food> myFoods(SyncStore store, String q, {int limit = 8}) {
final ws = q.toLowerCase().split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
final uses = <String, int>{};
for (final e in store.rows('food.entry')) {
final m = e['my_food_id'];
if (m is String) uses[m] = (uses[m] ?? 0) + 1;
}
final all = [
for (final r in store.rows('food.food'))
if ((r['gone'] ?? 0) == 0 && ws.every((w) => (r['name'] as String).toLowerCase().contains(w))) r
];
final ql = q.trim().toLowerCase();
all.sort((a, b) {
int k(Map<String, dynamic> r) {
final n = (r['name'] as String).toLowerCase();
return n == ql ? 0 : n.startsWith(ql) ? 1 : 2;
}
final c = k(a).compareTo(k(b));
return c != 0 ? c : (uses[b['_u']] ?? 0).compareTo(uses[a['_u']] ?? 0);
});
return all.take(limit).map(myFood).toList();
}
Food? myFoodByUid(SyncStore store, String uid) {
final r = store.row('food.food', uid);
return r == null ? null : myFood(r);
}
// ---- entries ------------------------------------------------------------------------------
class Entry {
Entry(this.row);
final Map<String, dynamic> row;
String get u => row['_u'] as String;
String get day => row['day'] as String;
String get meal => mealKeys.contains(row['meal']) ? row['meal'] as String : '';
String get name => (row['name'] as String?) ?? '';
double? n(String k) => (row[k] as num?)?.toDouble();
double get kcal => n('kcal') ?? 0;
double? get amount => n('amount');
String? get unit => row['unit'] as String?;
int? get foodId => (row['food_id'] as num?)?.toInt();
String? get myFoodId => row['my_food_id'] is String ? row['my_food_id'] as String : null;
String get source => (row['source'] as String?) ?? '';
String get portion => amount == null ? '' : '${_num(amount!)} ${unit ?? ''}'.trim();
int get stamp => (row['_h'] as num?)?.toInt() ?? 0;
}
String _num(double v) => v == v.roundToDouble() ? v.round().toString() : v.toStringAsFixed(v < 10 ? 2 : 1).replaceFirst(RegExp(r'0+$'), '');
List<Entry> entriesOn(SyncStore store, String day) {
final es = [for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') = ?", args: [day])) Entry(r)];
es.sort((a, b) {
final c = a.stamp.compareTo(b.stamp);
if (c != 0) return c;
return ((a.row['time'] as String?) ?? '').compareTo((b.row['time'] as String?) ?? '');
});
return es;
}
/// {day: kcal} for the days in [a, z] (the week strip).
Map<String, double> kcalByDay(SyncStore store, String a, String z) {
final out = <String, double>{};
for (final r in store.db.select(
"SELECT json_extract(data, '\$.day') AS dday, sum(json_extract(data, '\$.kcal')) AS k FROM rec "
"WHERE t = 'food.entry' AND json_extract(data, '\$.day') BETWEEN ? AND ? GROUP BY dday", [a, z])) { // not 'd': rec.d is the device
out[r['dday'] as String] = (r['k'] as num?)?.toDouble() ?? 0;
}
return out;
}
/// Foods eaten before (db.foods): one per name — its latest entry — most eaten first; q anywhere in the name.
List<(Entry, int)> recentFoods(SyncStore store, String q, {int limit = 8}) {
final groups = <String, (Entry, int)>{};
for (final r in store.rows('food.entry')) {
final e = Entry(r);
if (!reuseSources.contains(e.source) || e.name.trim().isEmpty) continue;
final k = e.name.trim().toLowerCase();
final g = groups[k];
final newer = g == null || e.day.compareTo(g.$1.day) > 0 || (e.day == g.$1.day && e.stamp > g.$1.stamp);
groups[k] = (newer ? e : g.$1, (g?.$2 ?? 0) + 1);
}
final ql = q.trim().toLowerCase();
final hits = groups.entries.where((e) => e.key.contains(ql)).map((e) => e.value).toList()
..sort((a, b) {
final sa = a.$1.name.toLowerCase().startsWith(ql) ? 0 : 1, sb = b.$1.name.toLowerCase().startsWith(ql) ? 0 : 1;
if (sa != sb) return sa.compareTo(sb);
if (a.$2 != b.$2) return b.$2.compareTo(a.$2);
return b.$1.day.compareTo(a.$1.day);
});
return hits.take(limit).toList();
}
// ---- products kept from the archive ("food.product", the dashboard's db.product) ---------------
const tProduct = 'food.product';
const offId = 20000000000000; // off.OFF_ID: + the barcode
/// A product from the archive (or as kept: the same keys) → a Food (kind "off").
Food productFood(Map<String, dynamic> d) {
final per = (d['per100'] as Map?)?.cast<String, dynamic>() ?? {};
return Food(
ref: 'usda:${d['id']}', kind: 'off', name: d['name'] as String? ?? '?', category: d['category'] as String? ?? '',
brand: d['brand'] as String?, barcode: d['barcode'] as String?, nutriscore: d['nutriscore'] as String?,
nova: (d['nova'] as num?)?.toInt(), foodId: (d['id'] as num).toInt(), source: 'off', labels: d['labels'] as String? ?? '',
sugarsIn: d['sugars_in'] as String?, dairy: (d['dairy'] as num?)?.toInt(), addedSugar: (d['added_sugar'] as num?)?.toDouble(),
per100: {for (final c in foodCols) c: (per[c] as num?)?.toDouble()},
portions: [
for (final p in ((d['portions'] as List?) ?? []).cast<Map>())
if ((p['grams'] as num?) != null) Portion('${p['label']}', (p['grams'] as num).toDouble())
],
);
}
Food? _kept(Map<String, dynamic>? row) {
try {
return row == null ? null : productFood(jsonDecode(row['data'] as String) as Map<String, dynamic>);
} catch (_) {
return null;
}
}
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)];
/// 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}) {
final ws = fold(q).split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
if (ws.isEmpty) return [];
return [
for (final r in store.rows(tProduct))
if (ws.every(fold('${r['name']} ${r['brand'] ?? ''}').contains)) ?_kept(r),
].take(limit).toList();
}
/// Keep a product picked from the archive (the dashboard's db.save_product: checked, then stored and synced).
Food? keepProduct(SyncStore store, Map<String, dynamic> d) {
final id = (d['id'] as num?)?.toInt();
final per = d['per100'];
if (id == null || id < offId || id >= offId * 1.5 || per is! Map || '${d['name'] ?? ''}'.trim().isEmpty) return null;
String? t(String k, int n) => d[k] == null ? null : '${d[k]}'.substring(0, min(n, '${d[k]}'.length));
final v = <String, dynamic>{
for (final (k, n) in [('name', 120), ('category', 120), ('brand', 60), ('barcode', 14), ('countries', 200), ('nutriscore', 1),
('allergens', 400), ('labels', 400), ('ingredients', 1600), ('sugars_in', 200)]) k: t(k, n),
'id': id,
'per100': {for (final c in foodCols) c: (per[c] as num?)?.toDouble()},
'portions': [
for (final p in ((d['portions'] as List?) ?? []).cast<Map>().take(6))
if ((p['grams'] as num? ?? 0) > 0 && (p['grams'] as num) <= 10000) {'label': '${p['label']}', 'grams': (p['grams'] as num).toDouble()}
],
'nova': [1, 2, 3, 4].contains(d['nova']) ? d['nova'] : null,
'dairy': [0, 1].contains(d['dairy']) ? d['dairy'] : null,
'added_sugar': (d['added_sugar'] as num?)?.toDouble(),
};
final old = store.row(tProduct, 'p:$id');
final data = jsonEncode(v);
if (old?['data'] != data) {
store.put(tProduct, 'p:$id', {'food_id': id, 'name': v['name'], 'brand': v['brand'] ?? '', 'barcode': v['barcode'], 'data': data,
'added': old?['added'] ?? DateTime.now().toUtc().toIso8601String().substring(0, 19).replaceFirst('T', ' ')});
}
return productFood(v);
}
/// The food an entry was made from, if it still exists (database or My foods).
Food? foodOf(SyncStore store, FoodDb? fdb, Entry e) {
if (e.myFoodId != null) return myFoodByUid(store, e.myFoodId!);
if (e.foodId != null) return fdb?.food(e.foodId!);
return null;
}
/// 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).
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);
if (g == null) return "Can't tell the grams of that portion.";
final old = u == null ? null : store.row('food.entry', u);
store.put('food.entry', u ?? SyncStore.randomId(), {
'micros': '{}', 'src_id': null, 'time': null,
...?old,
'day': day, 'meal': meal, 'name': food.name, ...food.nutrients(g),
'amount': amount, 'unit': unit, 'grams': g, 'note': note,
'food_id': food.foodId, 'my_food_id': food.myUid, 'source': old?['source'] ?? 'manual',
});
return null;
}
/// Save an entry without a food (its numbers typed, or copied from an older one and scaled by amount).
String? saveTotals(SyncStore store, {String? u, required String day, required String meal, required String name,
required Map<String, double?> values, double? amount, String? unit, Map<String, dynamic>? copyFrom, String note = ''}) {
if (name.trim().isEmpty) return 'What was it?';
if (values['kcal'] == null) return 'How much energy? A guess is fine.';
final old = u == null ? null : store.row('food.entry', u);
final extra = <String, dynamic>{};
if (old == null && copyFrom != null && (copyFrom['kcal'] as num?) != null && (copyFrom['kcal'] as num) > 0) {
final f = values['kcal']! / (copyFrom['kcal'] as num); // db.save `from`: the other nutrients, scaled
for (final k in foodCols) {
if (!values.containsKey(k) && copyFrom[k] != null) extra[k] = ((copyFrom[k] as num) * f * 1000).round() / 1000;
}
}
store.put('food.entry', u ?? SyncStore.randomId(), {
'micros': '{}', 'src_id': null, 'time': null, 'food_id': null, 'grams': null, 'my_food_id': null,
...?old, ...extra,
'day': day, 'meal': meal, 'name': name.trim(), ...values, 'amount': amount, 'unit': unit, 'note': note,
'source': old?['source'] ?? 'manual',
});
return null;
}
/// Add an older entry again as it was (yesterday's +): a food entry is worked out again, else copied.
void addAgain(SyncStore store, FoodDb? fdb, Entry e, String day, String meal) {
final f = foodOf(store, fdb, e);
if (f != null && e.amount != null && e.unit != null && f.grams(e.amount!, e.unit!) != null) {
saveFromFood(store, day: day, meal: meal, food: f, amount: e.amount!, unit: e.unit!);
return;
}
saveTotals(store, day: day, meal: meal, name: e.name, amount: e.amount, unit: e.unit,
values: {for (final k in ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'sodium_mg']) k: e.n(k)},
copyFrom: e.row);
}
// ---- totals, targets, ring (views.py) ----------------------------------------------------------
Map<String, double?> totals(Iterable<Entry> es) {
final out = <String, double?>{};
for (final k in ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'sodium_mg']) {
final vs = es.map((e) => e.n(k)).whereType<double>().toList();
out[k] = vs.isEmpty ? null : vs.reduce((a, b) => a + b);
}
out['kcal'] ??= 0;
return out;
}
class Plan {
Plan(this.kcal, this.maint, this.basis, this.deficit, this.capped);
final int kcal;
final int? maint;
final String basis;
final int deficit;
final bool capped;
}
/// views.plan: your usual day from Health (the Pi's energy summary: resting + walking + workouts,
/// averaged over 28 days with step data — at least 7) minus the weight goal; resting × 1.4 until then.
Plan plan(SyncStore store, FoodSettings s) {
final e = Summaries(store).meta('energy') ?? {};
final b = BodyView(store, profileOf(store));
final w = (e['weight'] as num?)?.toDouble() ?? b.weight;
final bmr = (e['bmr'] as num?)?.toDouble() ?? bmrMifflin(w, b.p.height, b.p.sex, b.age);
if (s.kcalTarget > 0) return Plan(s.kcalTarget, null, 'set by hand', 0, false);
final tdee = (e['tdee'] as num?)?.toInt(), days = (e['days'] as num?)?.toInt() ?? 0;
final int? maint;
final String basis;
if (tdee != null && days >= 7) {
maint = tdee;
basis = 'your average day in Health (resting + walking + workouts, $days days)';
} else if (bmr != null) {
maint = (bmr * 1.4).round();
basis = 'resting energy × 1.4 (not enough step data in Health yet)';
} else {
return Plan(2000, null, 'no weight yet — 2000 kcal', 0, false);
}
if (w == null) return Plan(2000, maint, basis, 0, false);
var deficit = w * s.goalRate / 100 * 7700 / 7;
var capped = deficit > 1000;
deficit = min(deficit, 1000);
var kcal = maint - deficit;
final floor = b.p.sex == female ? 1200 : 1500;
if (kcal < floor) {
kcal = floor.toDouble();
capped = true;
}
return Plan((kcal / 10).round() * 10, maint, basis, deficit.round(), capped);
}
/// {key: (target, kind)} — kind goal / min / max (views.targets).
Map<String, (double, String)> targets(SyncStore store, FoodSettings s) {
final kcal = plan(store, s).kcal.toDouble();
final pct = [s.split.$1, s.split.$2, s.split.$3];
return {
'kcal': (kcal, 'goal'),
for (var i = 0; i < 3; i++) macros[i]: ((kcal * pct[i] / 100 / kcalPerG[macros[i]]!).roundToDouble(), 'goal'),
'fiber': (s.fiberMin.toDouble(), 'min'),
'sugar': (0, 'info'), // total sugar: shown, no limit (natural sugar counts too)
'added_sugar': ((kcal * 0.10 / 4).roundToDouble(), 'max'), // WHO: added ("free") sugars under 10 % of the energy (sugar.dart)
'sat_fat': ((kcal * 0.10 / 9).roundToDouble(), 'max'),
'sodium_mg': (s.sodiumMax.toDouble(), 'max'),
};
}
String dayIso(DateTime d) => iso(d);
String num1(double v) => _num(v);
// ---- My foods: save / delete (db.clean_food, save_food, delete_food) ---------------------------
/// What the food editor edits per 100 g (db.FIELDS): key → (label, unit, max).
const foodFields = {
'kcal': ('Energy', 'kcal', 10000.0), 'protein': ('Protein', 'g', 1000.0), 'carbs': ('Carbs', 'g', 1000.0),
'sugar': ('of which sugar', 'g', 1000.0), 'fat': ('Fat', 'g', 1000.0), 'sat_fat': ('of which saturated', 'g', 1000.0),
'fiber': ('Fibre', 'g', 500.0), 'sodium_mg': ('Sodium', 'mg', 50000.0),
};
/// 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).
(String?, String?) saveMyFood(SyncStore store, {String? uid, required String name, required Map<String, double?> per100,
required List<Portion> portions, String note = '', String? sugarKind}) {
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.');
for (final e in per100.entries) {
final max = foodFields[e.key]?.$3;
if (e.value != null && max != null && (e.value! < 0 || e.value! > max)) return (null, '${foodFields[e.key]!.$1}: 0–${max.round()}.');
}
for (final p in portions) {
if (p.label.trim().isEmpty || p.grams <= 0) return (null, 'A portion needs a name and its grams.');
if (['g', 'ml'].contains(p.label.trim().toLowerCase())) return (null, 'g and ml are there already.');
}
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 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, {
'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,
'portions': jsonEncode([for (final p in portions) {'label': p.label.trim().split(RegExp(r'\s+')).join(' '), 'grams': p.grams}]),
});
return (u, null);
}
/// 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);
if (r == null) return;
store.put('food.food', uid, {...r, 'gone': 1, 'updated': DateTime.now().toIso8601String().substring(0, 19)});
}
/// All My foods (not deleted), by name, with how often each was used.
List<(Map<String, dynamic>, int)> allMyFoods(SyncStore store) {
final uses = <String, int>{};
for (final e in store.rows('food.entry')) {
if (e['my_food_id'] is String) uses[e['my_food_id'] as String] = (uses[e['my_food_id'] as String] ?? 0) + 1;
}
final rs = store.rows('food.food').where((r) => (r['gone'] ?? 0) == 0).toList()
..sort((a, b) => (a['name'] as String).toLowerCase().compareTo((b['name'] as String).toLowerCase()));
return [for (final r in rs) (r, uses[r['_u']] ?? 0)];
}
// ---- history (views.history) -------------------------------------------------------------------
/// {day: totals} for [a, z] (ISO days) — one pass over the entries.
Map<String, Map<String, double>> dayTotals(SyncStore store, String a, String z) {
final out = <String, Map<String, double>>{};
for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [a, z])) {
final t = out.putIfAbsent(r['day'] as String, () => {});
for (final k in ['kcal', 'protein', 'carbs', 'fat', 'fiber', 'sugar', 'sodium_mg', 'sat_fat']) {
t[k] = (t[k] ?? 0) + ((r[k] as num?)?.toDouble() ?? 0);
}
}
return out;
}
/// The foods eaten most in [a, z]: (name, times, average kcal).
List<(String, int, double)> topFoods(SyncStore store, String a, String z, {int limit = 12}) {
final g = <String, (String, int, double)>{};
for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [a, z])) {
final name = (r['name'] as String?)?.trim() ?? '';
if (name.isEmpty) continue;
final k = name.toLowerCase(), cur = g[k];
final kcal = (r['kcal'] as num?)?.toDouble() ?? 0;
g[k] = cur == null ? (name, 1, kcal) : (cur.$1, cur.$2 + 1, cur.$3 + kcal);
}
final out = [for (final v in g.values) (v.$1, v.$2, v.$3 / v.$2)]
..sort((x, y) => x.$2 != y.$2 ? y.$2.compareTo(x.$2) : (y.$3 * y.$2).compareTo(x.$3 * x.$2));
return out.take(limit).toList();
}
// ---- meals (db.save_meal) ------------------------------------------------------------------------
const mealMax = 40; // ingredients
/// One ingredient of a meal: a food + amount + unit, or (an entry logged without a food) its own numbers.
class Ingredient {
Ingredient.food(Food this.food, this.amount, this.unit) : fixed = null, name = food.name, grams = null;
Ingredient.fixed(Map<String, double?> this.fixed, this.name, this.amount, this.unit, this.grams) : food = null;
final Food? food;
final Map<String, double?>? fixed;
final String name;
double? amount, grams;
String? unit;
double? get g => food != null ? (amount == null ? null : food!.grams(amount!, unit ?? 'g')) : grams;
Map<String, double?> get values => food != null ? (g == null ? {} : food!.nutrients(g!)) : fixed!;
}
/// The meal's ingredients from its synced recipe (refs "usda:ID" / "my:~ID").
List<Ingredient> recipeOf(SyncStore store, FoodDb? fdb, Map<String, dynamic> row) {
final r = row['recipe'] is String ? jsonDecode(row['recipe'] as String) as Map<String, dynamic> : null;
final out = <Ingredient>[];
for (final i in ((r?['ingredients'] as List?) ?? []).cast<Map<String, dynamic>>()) {
final amount = (i['amount'] as num?)?.toDouble(), unit = i['unit'] as String?;
if (i['fixed'] is Map) {
out.add(Ingredient.fixed({for (final e in (i['fixed'] as Map).entries) e.key as String: (e.value as num?)?.toDouble()},
(i['name'] as String?) ?? '', amount, unit, (i['grams'] as num?)?.toDouble()));
continue;
}
final ref = (i['food'] as String?) ?? '';
final f = ref.startsWith('usda:') ? fdb?.food(int.parse(ref.substring(5)))
: ref.startsWith('my:') ? myFoodByUid(store, ref.substring(3).replaceFirst('~', '')) : null;
if (f != null) {
out.add(Ingredient.food(f, amount, unit));
} else {
// gone: keep it as its own numbers so the meal still adds up (the web says "remove it and pick it again")
out.add(Ingredient.fixed({}, '${(i['name'] as String?) ?? '?'} (gone)', amount, unit, (i['grams'] as num?)?.toDouble()));
}
}
return out;
}
double? doneGramsOf(Map<String, dynamic> row) {
final r = row['recipe'] is String ? jsonDecode(row['recipe'] as String) as Map<String, dynamic> : null;
return (r?['done_grams'] as num?)?.toDouble();
}
/// The meals inside a meal (by id) — a meal may hold another meal, not itself.
Set<String> mealIds(SyncStore store, String uid, [int depth = 0]) {
final row = store.row('food.food', uid);
final r = row?['recipe'] is String ? jsonDecode(row!['recipe'] as String) as Map<String, dynamic> : null;
final out = <String>{};
for (final i in ((r?['ingredients'] as List?) ?? []).cast<Map<String, dynamic>>()) {
final ref = (i['food'] as String?) ?? '';
if (ref.startsWith('my:')) {
final id = ref.substring(3).replaceFirst('~', '');
out.add(id);
if (depth < 4) out.addAll(mealIds(store, id, depth + 1));
}
}
return out;
}
/// Save a meal (new: uid null): its values per 100 g worked out from the ingredients as they are now;
/// portions get "whole meal" (its whole weight). → (uid, error).
(String?, String?) saveMeal(SyncStore store, {String? uid, required String name, required List<Ingredient> ings,
double? doneGrams, required List<Portion> portions, String note = ''}) {
if (name.trim().isEmpty) return (null, 'Name the meal.');
if (ings.isEmpty) return (null, 'Add what goes into it.');
if (ings.length > mealMax) return (null, 'At most $mealMax ingredients.');
final tot = <String, double?>{for (final c in foodCols) c: null};
var grams = 0.0;
final unweighed = <String>[], recipe = <Map<String, dynamic>>[];
for (final i in ings) {
if (i.food != null) {
if (uid != null && i.food!.myUid != null && (i.food!.myUid == uid || mealIds(store, i.food!.myUid!).contains(uid))) {
return (null, '${i.name}: a meal can’t contain itself.');
}
final g = i.g;
if (g == null || g <= 0) return (null, '${i.name}: how much of it — amount and unit?');
i.food!.nutrients(g).forEach((c, v) {
if (v != null) tot[c] = (tot[c] ?? 0) + v;
});
grams += g;
recipe.add({'food': i.food!.myUid != null ? 'my:~${i.food!.myUid}' : 'usda:${i.food!.foodId}', 'name': i.food!.name,
'amount': i.amount, 'unit': i.unit ?? 'g', 'grams': (g * 100).round() / 100});
} else {
if (i.fixed!['kcal'] == null) return (null, '${i.name}: no energy on that one.');
i.fixed!.forEach((c, v) {
if (v != null && tot.containsKey(c)) tot[c] = (tot[c] ?? 0) + v;
});
if (i.grams != null && i.grams! > 0) {
grams += i.grams!;
} else {
unweighed.add(i.name);
}
recipe.add({'fixed': i.fixed, 'name': i.name, 'amount': i.amount, 'unit': i.unit, 'grams': i.grams});
}
}
final weight = doneGrams ?? grams;
if (unweighed.isNotEmpty && doneGrams == null) {
return (null, 'No weight for ${unweighed.take(3).join(', ')}${unweighed.length > 3 ? ' …' : ''} — weigh the meal (or guess) and enter it as the weight when done.');
}
if (weight <= 0) return (null, 'How much does it weigh?');
final per100 = {for (final e in tot.entries) e.key: e.value == null ? null : (e.value! * 100 / weight * 1000).round() / 1000};
final (u, err) = saveMyFood(store, uid: uid, name: name, per100: per100,
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})});
return (u, null);
}
/// An entry dragged into another meal (db.move: only the meal changes).
void moveEntry(SyncStore store, String u, String meal) {
final r = store.row('food.entry', u);
if (r != null && r['meal'] != meal) store.put('food.entry', u, {...r, 'meal': meal});
}