mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-11 17:33:55 +01:00
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>
182 lines
5.7 KiB
Dart
182 lines
5.7 KiB
Dart
/// Screen for editing an existing meal-history entry in-place.
|
|
library;
|
|
|
|
import 'dart:async';
|
|
|
|
import 'package:diet_guard_app/models/food_entry.dart';
|
|
import 'package:diet_guard_app/models/food_suggestion.dart';
|
|
import 'package:diet_guard_app/models/nutrition.dart';
|
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
|
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:uuid/uuid.dart';
|
|
|
|
/// Edit screen for an existing [FoodEntry].
|
|
///
|
|
/// Preserves [FoodEntry.id], [FoodEntry.time], [FoodEntry.slot],
|
|
/// and [FoodEntry.deleted]. All nutritional fields and
|
|
/// the description are editable.
|
|
class EditEntryScreen extends StatefulWidget {
|
|
/// Creates an [EditEntryScreen] pre-filled with [entry].
|
|
const EditEntryScreen({required this.entry, super.key});
|
|
|
|
/// The entry to edit.
|
|
final FoodEntry entry;
|
|
|
|
@override
|
|
State<EditEntryScreen> createState() => _EditEntryScreenState();
|
|
}
|
|
|
|
class _EditEntryScreenState extends State<EditEntryScreen> {
|
|
late final TextEditingController _descController;
|
|
final MacroControllers _macros = MacroControllers();
|
|
List<FoodSuggestion> _suggestions = const [];
|
|
String _source = 'manual';
|
|
String? _status;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
final e = widget.entry;
|
|
_descController = TextEditingController(text: e.desc);
|
|
_macros.kcal.text = e.kcal.toStringAsFixed(0);
|
|
_macros.protein.text = e.proteinG.toStringAsFixed(0);
|
|
_macros.carbs.text = e.carbsG.toStringAsFixed(0);
|
|
_macros.fat.text = e.fatG.toStringAsFixed(0);
|
|
_macros.grams.text = e.grams > 0 ? e.grams.toStringAsFixed(0) : '';
|
|
_source = e.source;
|
|
|
|
_descController.addListener(_onDescChanged);
|
|
for (final c in [
|
|
_macros.kcal,
|
|
_macros.protein,
|
|
_macros.carbs,
|
|
_macros.fat,
|
|
_macros.perGrams,
|
|
_macros.grams,
|
|
]) {
|
|
c.addListener(_onMacroEdited);
|
|
}
|
|
unawaited(_onDescChanged());
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_descController.dispose();
|
|
_macros.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
void _onMacroEdited() {
|
|
if (_source == 'food bank') {
|
|
setState(() => _source = 'manual');
|
|
}
|
|
}
|
|
|
|
Future<void> _onDescChanged() async {
|
|
final matches = await FoodBankService.instance.search(
|
|
_descController.text,
|
|
);
|
|
if (!mounted) return;
|
|
setState(() => _suggestions = matches);
|
|
}
|
|
|
|
void _onSuggestionSelected(FoodSuggestion suggestion) {
|
|
_descController.text = suggestion.name;
|
|
_macros.kcal.text = suggestion.nutrition.kcal.toStringAsFixed(0);
|
|
_macros.protein.text = suggestion.nutrition.proteinG.toStringAsFixed(0);
|
|
_macros.carbs.text = suggestion.nutrition.carbsG.toStringAsFixed(0);
|
|
_macros.fat.text = suggestion.nutrition.fatG.toStringAsFixed(0);
|
|
_macros.perGrams.text = suggestion.nutrition.grams.toStringAsFixed(0);
|
|
_macros.grams.text = suggestion.nutrition.grams.toStringAsFixed(0);
|
|
setState(() {
|
|
_source = 'food bank';
|
|
_suggestions = const [];
|
|
});
|
|
}
|
|
|
|
double _parse(TextEditingController c) => double.tryParse(c.text.trim()) ?? 0;
|
|
|
|
Future<void> _onSave() async {
|
|
final desc = _descController.text.trim();
|
|
if (desc.isEmpty) {
|
|
setState(() => _status = 'Description cannot be empty.');
|
|
return;
|
|
}
|
|
final nutrition = nutritionForPortion(
|
|
kcal: _parse(_macros.kcal),
|
|
proteinG: _parse(_macros.protein),
|
|
carbsG: _parse(_macros.carbs),
|
|
fatG: _parse(_macros.fat),
|
|
perGrams: _parse(_macros.perGrams),
|
|
ateGrams: _parse(_macros.grams),
|
|
source: _source,
|
|
);
|
|
final e = widget.entry;
|
|
final updated = FoodEntry(
|
|
// Assign a UUID when editing a legacy entry that never had one.
|
|
// This upgrades it to a first-class sync entry without creating a
|
|
// duplicate: the Python sync deduplicates null-id entries by time+desc.
|
|
id: e.id ?? const Uuid().v4(),
|
|
time: e.time,
|
|
desc: desc,
|
|
grams: nutrition.grams,
|
|
kcal: nutrition.kcal,
|
|
proteinG: nutrition.proteinG,
|
|
carbsG: nutrition.carbsG,
|
|
fatG: nutrition.fatG,
|
|
source: _source,
|
|
slot: e.slot,
|
|
);
|
|
await LogStorageService.instance.updateEntry(e, updated);
|
|
final log = await LogStorageService.instance.readLog();
|
|
await FoodBankService.instance.rebuildAndPersist(log);
|
|
if (!mounted) return;
|
|
Navigator.of(context).pop();
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: AppBar(title: const Text('Edit meal')),
|
|
body: SingleChildScrollView(
|
|
padding: const EdgeInsets.all(16),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
TextField(
|
|
controller: _descController,
|
|
decoration: const InputDecoration(
|
|
labelText: 'What did you eat?',
|
|
),
|
|
),
|
|
ConstrainedBox(
|
|
constraints: const BoxConstraints(maxHeight: 240),
|
|
child: AutocompleteSuggestionList(
|
|
suggestions: _suggestions,
|
|
onSelected: _onSuggestionSelected,
|
|
),
|
|
),
|
|
const SizedBox(height: 12),
|
|
MacroInputRow(controllers: _macros),
|
|
const SizedBox(height: 16),
|
|
SizedBox(
|
|
width: double.infinity,
|
|
child: ElevatedButton(
|
|
onPressed: _onSave,
|
|
child: const Text('Save'),
|
|
),
|
|
),
|
|
if (_status != null) ...[
|
|
const SizedBox(height: 12),
|
|
Text(_status!),
|
|
],
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|