diet-guard/app/lib/services/foodbank_service.dart
Krzysztof kuhy Rudnicki f7f06aee53
Some checks failed
pre-commit / pre-commit (push) Has been cancelled
Tests / test (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
Remove unused features; fix reminder false alarms; share all state
Four asks, plus the fixes two review passes turned up.

Removals (all unused):
- "Repeat last meal" button, and the reward/temptation-bundling prompt it
  was the sole trigger for. Replaced with a post-log progress card showing
  kcal against budget, macros, and the adherence streak.
- The multi-item meal builder, on both the gate and the phone. The stored
  `components` field stays: nothing writes it now, but historical composite
  entries and the food bank still read it and it is part of the wire format.
- Meal photos entirely: 13 files, `imagePath`, the photo filter, the
  wrapper's /blobs/ route, image_picker, and the CAMERA permission.

Reminder false alarms had three real causes, all fixed:
- Logging never reconciled notifications, so a reminder sat on screen up to
  15 minutes after the meal was logged -- on the phone itself.
- The background check never pulled, so a PC-logged meal nagged forever
  until the app was opened. Now mirrors _cli_gate._should_lock: cheap local
  check, network only when a slot looks due, then re-check.
- Meals before 08:00 / after 22:00 were attributed to no slot at all. New
  slot_for_log/slotForLog clamps them to the first/last slot, byte-identical
  across Python and Dart. Deliberately separate from elapsed_slots, which
  would otherwise make every slot fall due at 23:00.

Budget history, so lowering the budget stops rewriting the past:
- Forward-only (effective_from, kcal) entries; each day is judged against
  the budget in force then. Verified live: setting 2000 left a 36-day
  adherence streak and the whole calendar pixel-identical.
- Rides as hist:<date> fields on the existing budget record. crdt_sync
  merges per-field over the union of field names and both devices push the
  merged log, so a device that predates the feature relays them untouched --
  no coordinated rollout, no second document.
- The seed guard tests emptiness, not file presence: _sync can write an
  empty history after merging with a pre-feature peer, and a presence check
  would then never seed again, silently reclassifying every past day.

One shared source of truth for every piece of data:
- Body weight now travels as its own `weight` CRDT field. Inside `value` it
  was collateral damage of whole-map LWW -- any phone budget edit deleted it,
  and the protein target with it.
- Both halves of the food bank sync. The curated half (foods added without
  eating them) was the last device-local state. The derived half merges with
  count as the clock, so LWW means max-count-wins; the log stays
  authoritative for membership, because a CRDT union never shrinks and a
  peer's stale copy would otherwise resurrect a deleted food permanently.
- Bank adapters honour tombstones, and Dart parses bank records defensively:
  a cast failure there is an Error, not an Exception, so one malformed
  remote record would have broken phone sync permanently.

_test_guard.py blocks any pathlib write to real user state while pytest is
in the process, whatever conftest is loaded. A throwaway test run outside
the package conftest destroyed a real GitHub token during this work; this
makes that class of accident impossible rather than merely discouraged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 16:39:52 +02:00

315 lines
10 KiB
Dart

/// Local food-bank (autocomplete index), mirroring diet_guard's
/// `_foodbank.py` -- but *derived*, not synced (see Milestone 3's decision
/// to avoid counter-merge logic entirely: every device rebuilds its own
/// bank by replaying its own post-merge log).
library;
import 'dart:convert';
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/food_suggestion.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:diet_guard_app/services/fuzzy.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/foundation.dart';
/// Below this similarity ratio a non-substring candidate is dropped.
/// Mirrors `_foodbank._FUZZY_THRESHOLD`.
const double fuzzyThreshold = 0.6;
/// Default number of autocomplete suggestions to surface. Mirrors
/// `_foodbank.DEFAULT_SUGGESTIONS`.
const int defaultSuggestions = 8;
String _normalize(String description) => description.trim().toLowerCase();
Nutrition _recordToNutrition(FoodBankRecord record) => Nutrition(
kcal: record.kcal,
proteinG: record.proteinG,
carbsG: record.carbsG,
fatG: record.fatG,
grams: record.grams,
source: 'food bank',
);
String _displayName(FoodBankRecord record, String key) =>
record.desc.trim().isEmpty ? key : record.desc;
/// Singleton service for the locally-rebuilt food bank.
class FoodBankService {
FoodBankService._(this._store);
/// Document holding the log-derived bank. Unchanged from the pre-web
/// on-disk filename so an installed phone keeps its existing bank.
static const documentName = 'food_bank.json';
/// Document holding the manually-curated bank.
static const manualDocumentName = 'food_bank_manual.json';
static FoodBankService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static FoodBankService get instance => _instance!;
final DocumentStore _store;
/// Initializes the singleton, pointing at the app's documents directory.
static Future<FoodBankService> init() async {
if (_instance != null) return _instance!;
final svc = FoodBankService._(await openDocumentStore());
_instance = svc;
return svc;
}
/// Resets the singleton so [init] can be called again in tests.
@visibleForTesting
static void resetForTesting({DocumentStore? store}) {
_instance = store == null ? null : FoodBankService._(store);
}
/// Reads the persisted bank (empty map on a missing/unparsable document).
Future<Map<String, FoodBankRecord>> readBank() => _readBank(documentName);
/// Persists [bank].
Future<void> writeBank(Map<String, FoodBankRecord> bank) =>
_writeBank(documentName, bank);
Future<Map<String, FoodBankRecord>> _readBank(String name) async {
final raw = await _store.read(name);
if (raw == null) return {};
Object? data;
try {
data = jsonDecode(raw);
} on FormatException {
return {};
}
if (data is! Map) return {};
final result = <String, FoodBankRecord>{};
for (final mapEntry in data.entries) {
final key = mapEntry.key;
final value = mapEntry.value;
if (key is String && value is Map) {
result[key] = FoodBankRecord.fromJson(value.cast<String, dynamic>());
}
}
return result;
}
Future<void> _writeBank(
String name,
Map<String, FoodBankRecord> bank,
) async {
final encoded = <String, Object?>{
for (final mapEntry in bank.entries)
mapEntry.key: mapEntry.value.toJson(),
};
await _store.write(name, jsonEncode(encoded));
}
/// Rebuilds the bank by replaying [log]'s entries in a fixed, device-
/// independent order (by `time` then `id`), so any two devices that
/// converge on the same merged log also converge on the same bank.
///
/// Pure -- no I/O -- so it is independently unit-testable, mirroring
/// `_foodbank.remember_food`/`remember_meal`'s upsert semantics: latest
/// macros win per normalized name, `count` increments per occurrence.
static Map<String, FoodBankRecord> rebuild(DayLog log) {
final entries =
log.values
.expand((entries) => entries)
.where((entry) => !entry.deleted)
.toList()
..sort((a, b) {
final byTime = a.time.compareTo(b.time);
return byTime != 0 ? byTime : (a.id ?? '').compareTo(b.id ?? '');
});
final bank = <String, FoodBankRecord>{};
for (final entry in entries) {
final components = entry.components;
if (components != null) {
for (final component in components) {
_upsert(
bank,
component.name,
Nutrition(
kcal: component.kcal,
proteinG: component.proteinG,
carbsG: component.carbsG,
fatG: component.fatG,
grams: component.grams,
source: 'food bank',
),
null,
);
}
_upsert(
bank,
entry.desc,
Nutrition(
kcal: entry.kcal,
proteinG: entry.proteinG,
carbsG: entry.carbsG,
fatG: entry.fatG,
grams: entry.grams,
source: entry.source,
),
components.map((c) => c.name).toList(),
);
} else {
_upsert(
bank,
entry.desc,
Nutrition(
kcal: entry.kcal,
proteinG: entry.proteinG,
carbsG: entry.carbsG,
fatG: entry.fatG,
grams: entry.grams,
source: entry.source,
),
null,
);
}
}
return bank;
}
static void _upsert(
Map<String, FoodBankRecord> bank,
String description,
Nutrition nutrition,
List<String>? components,
) {
final key = _normalize(description);
if (key.isEmpty) return;
final previous = bank[key];
final count = (previous?.count ?? 0) + 1;
bank[key] = FoodBankRecord(
desc: description.trim(),
kcal: nutrition.kcal,
proteinG: nutrition.proteinG,
carbsG: nutrition.carbsG,
fatG: nutrition.fatG,
grams: nutrition.grams,
count: count,
components: components,
);
}
/// Rebuilds the bank from [log] and persists it, returning the result.
Future<Map<String, FoodBankRecord>> rebuildAndPersist(DayLog log) async {
final bank = rebuild(log);
await writeBank(bank);
return bank;
}
// ---------------------------------------------------------------------------
// Manual bank (food items added directly without logging them as eaten)
// ---------------------------------------------------------------------------
Future<Map<String, FoodBankRecord>> _readManualBank() =>
_readBank(manualDocumentName);
Future<void> _writeManualBank(Map<String, FoodBankRecord> bank) =>
_writeBank(manualDocumentName, bank);
/// Adds or updates [record] in the manually-curated bank without logging it
/// as eaten. A repeated call with the same normalized name overwrites the
/// previous entry.
Future<void> addManualEntry(FoodBankRecord record) async {
final bank = await _readManualBank();
bank[_normalize(record.desc)] = FoodBankRecord(
desc: record.desc,
kcal: record.kcal,
proteinG: record.proteinG,
carbsG: record.carbsG,
fatG: record.fatG,
grams: record.grams,
count: record.count,
components: record.components,
// Stamped here, not by callers: this is what the cross-device merge
// orders by, so it must be set on every write without exception.
editedAt: DateTime.now().toIso8601String(),
);
await _writeManualBank(bank);
}
/// Returns the hand-curated bank, for the sync layer.
Future<Map<String, FoodBankRecord>> readManualBank() => _readManualBank();
/// Replaces the hand-curated bank with a merge result from the sync layer.
Future<void> applyMergedManualBank(Map<String, FoodBankRecord> bank) =>
_writeManualBank(bank);
/// All known food records: log-derived entries merged with manually-added
/// ones, sorted by count descending.
///
/// Log-derived records (from [readBank]) take precedence over manual records
/// with the same normalized name.
Future<List<FoodBankRecord>> mergedEntries() async {
final logBank = await readBank();
final manualBank = await _readManualBank();
final merged = <String, FoodBankRecord>{...manualBank, ...logBank};
return merged.values.toList()..sort((a, b) => b.count.compareTo(a.count));
}
// ---------------------------------------------------------------------------
// Search
// ---------------------------------------------------------------------------
/// Returns banked foods matching [query], best match first.
///
/// An empty query returns the most-logged foods. Mirrors
/// `_foodbank.search_foods`. Searches both log-derived and manually-added
/// entries; log-derived entries win on name collision.
Future<List<FoodSuggestion>> search(
String query, {
int limit = defaultSuggestions,
}) async {
final logBank = await readBank();
final manualBank = await _readManualBank();
final bank = <String, FoodBankRecord>{...manualBank, ...logBank};
final normalized = _normalize(query);
if (normalized.isEmpty) return _rankedAll(bank, limit);
final scored = <(double score, double count, FoodSuggestion suggestion)>[];
for (final mapEntry in bank.entries) {
final score = matchScore(normalized, mapEntry.key);
if (score < fuzzyThreshold) continue;
final record = mapEntry.value;
scored.add((
score,
record.count,
FoodSuggestion(
name: _displayName(record, mapEntry.key),
nutrition: _recordToNutrition(record),
),
));
}
scored.sort((a, b) {
final byScore = b.$1.compareTo(a.$1);
return byScore != 0 ? byScore : b.$2.compareTo(a.$2);
});
return scored.take(limit).map((s) => s.$3).toList();
}
List<FoodSuggestion> _rankedAll(
Map<String, FoodBankRecord> bank,
int limit,
) {
final ranked = bank.entries.toList()
..sort((a, b) => b.value.count.compareTo(a.value.count));
return ranked
.take(limit)
.map(
(mapEntry) => FoodSuggestion(
name: _displayName(mapEntry.value, mapEntry.key),
nutrition: _recordToNutrition(mapEntry.value),
),
)
.toList();
}
}