dashboard/app/lib/health/food_archive.dart
bashynx eeca189b7f Food: all products, barcode prefixes, meals that follow their ingredients
- "All products" lists what's here first (My foods, kept products, the food
  database), then Open Food Facts; if the archive can't be reached, what's
  here is still shown. A My food picked there is used as it is.
- The start of a barcode (4+ digits) finds the products whose barcode starts
  with it: in the search box, in all products and in the server's search
  (an index range, so it stays fast).
- A meal made with a changed food is worked out again, and so are meals made
  with that meal and their logged entries (db.follow_meals, app _followMeals).
- Saving a food that didn't change writes nothing, so nothing is synced again.
- Food search knows a few words in other languages: stomach / žalúdok /
  pipotă find gizzards, kurací / pui chicken, morčací / curcan turkey.
- App 1.1.5 changelog entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:41:23 +02:00

266 lines
11 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// All products: what's here first (My foods, the food database, kept products), then every Open Food Facts
// product (2 million+, every country), searched on the sync server's archive (GET /v1/food/search —
// sync-server/src/food.php), with filters: country, brand, Nutri-Score; a barcode (or its first 4+ digits)
// finds those products. A pick is kept ("food.product", food_model.dart keepProduct) and synced,
// so entries made from it work on every device. Also the camera barcode scanner (ZXing, no Google services).
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_zxing/flutter_zxing.dart' show Format;
import '../app/scanner.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'food_model.dart';
import 'sugar.dart' show fold;
const _countries = [('', 'Any country'), ('ro', 'Romania'), ('sk', 'Slovakia'), ('cz', 'Czechia'), ('hu', 'Hungary'), ('at', 'Austria'),
('de', 'Germany'), ('pl', 'Poland'), ('it', 'Italy'), ('fr', 'France'), ('es', 'Spain'), ('uk', 'UK'), ('us', 'USA')];
const _scores = [('', 'Any Nutri-Score'), ('a', 'A'), ('ab', 'A–B'), ('abc', 'A–C')];
/// The archive's search: [q] (or a barcode), filters → its products (as it sends them), or throws a message.
Future<List<Map<String, dynamic>>> archiveSearch(SyncService sync, Map<String, String> p) async {
final s = sync.settings;
final query = {for (final e in p.entries) if (e.value.isNotEmpty) e.key: e.value, 'limit': '25'};
final uri = Uri.parse('${s.server.replaceAll(RegExp(r'/+$'), '')}/v1/food/search').replace(queryParameters: query);
final http.Response r;
try {
r = await http.get(uri, headers: {'Authorization': 'Bearer ${s.token}', 'Accept': 'application/json'})
.timeout(const Duration(seconds: 20));
} catch (_) {
throw 'The sync server can\'t be reached — no connection?';
}
final j = jsonDecode(r.body);
if (r.statusCode != 200) throw (j is Map ? j['error'] : null) ?? 'Error ${r.statusCode}';
return ((j as Map)['items'] as List).cast<Map<String, dynamic>>();
}
/// The archive's search sheet → the product picked (kept already), or null.
Future<Food?> openArchive(BuildContext context, SyncService sync, FoodDb? fdb, String q) => showModalBottomSheet<Food>(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => ArchiveSheet(sync: sync, fdb: fdb, q: q),
);
class ArchiveSheet extends StatefulWidget {
const ArchiveSheet({super.key, required this.sync, required this.fdb, required this.q});
final SyncService sync;
final FoodDb? fdb;
final String q;
@override
State<ArchiveSheet> createState() => _ArchiveSheetState();
}
class _ArchiveSheetState extends State<ArchiveSheet> {
late final q = TextEditingController(text: widget.q);
final brand = TextEditingController();
String country = '', score = '';
List<Food> here = []; // My foods, the food database, kept products (no filters on)
List<Map<String, dynamic>> items = [];
String? status;
Timer? timer;
int seq = 0;
@override
void initState() {
super.initState();
_run();
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
void _soon() {
timer?.cancel();
timer = Timer(const Duration(milliseconds: 350), _run);
}
Future<void> _run() async {
final text = q.text.trim(), n = ++seq;
final code = RegExp(r'^\d{4,14}$').hasMatch(text);
if (!code && text.length < 3 && brand.text.trim().isEmpty && country.isEmpty) {
setState(() {
here = [];
items = [];
status = 'Type at least 3 letters, or pick a filter.';
});
return;
}
final store = widget.sync.store;
final filtered = brand.text.trim().isNotEmpty || country.isNotEmpty || score.isNotEmpty; // the archive's facts
final found = filtered
? <Food>[]
: code
? [...myFoodsByBarcode(store, text, prefix: true).take(8), ...(widget.fdb?.byBarcode(text, prefix: true) ?? keptByBarcode(store, text, prefix: true)).take(8)]
: text.length >= 3
? () {
final kept = keptProducts(store, text, fold: fold);
return [...myFoods(store, text, limit: 6), ...kept,
...(widget.fdb?.search(text, limit: 12) ?? []).where((f) => !kept.any((k) => k.foodId == f.foodId)).take(8)];
}()
: <Food>[];
setState(() {
here = found;
status = 'Searching…';
});
try {
final got = await archiveSearch(widget.sync, {
if (code) 'barcode': text else 'q': text,
'country': country, 'brand': brand.text.trim(), 'nutriscore': score,
});
if (!mounted || n != seq) return;
final ids = {for (final f in here) if (f.foodId != null) f.foodId};
setState(() {
items = [for (final it in got) if (!ids.contains((it['id'] as num).toInt())) it];
status = items.isEmpty && here.isEmpty ? 'Nothing found.' : null;
});
} catch (e) {
if (mounted && n == seq) {
setState(() {
items = [];
status = here.isEmpty ? '$e' : 'Only what\'s here — $e';
});
}
}
}
String _home(String c) {
final cs = c.split(' ').where((x) => x.isNotEmpty).toList();
return cs.take(3).map((x) => x[0].toUpperCase() + x.substring(1).replaceAll('-', ' ')).join(', ') + (cs.length > 3 ? ' …' : '');
}
void _pick(Map<String, dynamic> it) {
final id = (it['id'] as num).toInt();
final f = widget.fdb?.food(id) ?? keepProduct(widget.sync.store, it); // one you have already: that one
if (f == null) {
setState(() => status = 'That product came back garbled.');
return;
}
widget.sync.changed();
Navigator.of(context).pop(f);
}
Widget _drop(List<(String, String)> opts, String value, void Function(String) set) => DropdownButton<String>(
value: value,
isDense: true,
underline: const SizedBox(),
dropdownColor: card2,
items: [for (final (k, l) in opts) DropdownMenuItem(value: k, child: Text(l, style: const TextStyle(fontSize: 13.5)))],
onChanged: (v) {
set(v ?? '');
_run();
},
);
@override
Widget build(BuildContext context) {
final h = MediaQuery.of(context).size.height;
return Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: h * 0.85),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
const Text('All products', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
const Text('Yours and the food database first, then Open Food Facts — every country, through the sync server',
style: TextStyle(color: muted, fontSize: 12.5)),
const SizedBox(height: 6),
TextField(
controller: q,
autofocus: widget.q.isEmpty,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
hintText: 'Name, brand or barcode…',
suffixIcon: IconButton(
tooltip: 'Scan a barcode',
icon: const Icon(Icons.qr_code_scanner),
onPressed: () async {
final code = await scanBarcode(context);
if (code != null) {
q.text = code;
_run();
}
},
),
),
onChanged: (_) => _soon(),
onSubmitted: (_) => _run(),
),
Wrap(spacing: 12, crossAxisAlignment: WrapCrossAlignment.center, children: [
_drop(_countries, country, (v) => country = v),
_drop(_scores, score, (v) => score = v),
SizedBox(
width: 120,
child: TextField(
controller: brand,
style: const TextStyle(fontSize: 13.5),
decoration: const InputDecoration(isDense: true, hintText: 'Brand'),
onChanged: (_) => _soon(),
),
),
]),
if (status != null) Padding(padding: const EdgeInsets.only(top: 10), child: Text(status!, style: const TextStyle(color: muted))),
Flexible(
child: ListView(shrinkWrap: true, children: [
for (final f in here)
ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
title: Text(f.name, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(
[
f.kind == 'my' ? (f.isMeal ? 'meal' : 'My foods') : (f.brand ?? '').isNotEmpty ? f.brand! : 'food database',
if (f.kind != 'my') '✓ you have it',
if (RegExp(r'^\d+$').hasMatch(q.text.trim()) && f.barcode != null) f.barcode!,
].join(' · '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(color: muted),
),
trailing: Text('${(f.per100['kcal'] ?? 0).round()} kcal', style: const TextStyle(fontSize: 13.5)),
onTap: () => Navigator.of(context).pop(f),
),
for (final it in items)
ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
title: Text('${it['name']}', maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(
[
if ('${it['brand'] ?? ''}'.isNotEmpty) '${it['brand']}',
_home('${it['countries'] ?? ''}'),
if (widget.fdb?.food((it['id'] as num).toInt()) != null) '✓ you have it',
].where((x) => x.isNotEmpty).join(' · '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(color: muted),
),
trailing: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [
Text('${((it['per100'] as Map?)?['kcal'] as num? ?? 0).round()} kcal', style: const TextStyle(fontSize: 13.5)),
if (it['nutriscore'] != null)
Text('Nutri-Score ${'${it['nutriscore']}'.toUpperCase()}', style: const TextStyle(color: muted, fontSize: 11.5)),
]),
onTap: () => _pick(it),
),
]),
),
]),
),
),
);
}
}
/// The camera, until a product barcode (EAN / UPC) is read → its digits, or null (closed) — app/scanner.dart.
Future<String?> scanBarcode(BuildContext context) => scanCode(context,
title: 'Scan a barcode',
format: Format.ean13 | Format.ean8 | Format.upca | Format.upce,
accept: (v) => RegExp(r'^\d{8,14}$').hasMatch(v));