diet-guard/app/lib/screens/edit_entry_screen.dart
Krzysztof kuhy Rudnicki f83938bfe3 app: minute-of-day slots (phase 2 of 3: every app consumer)
- FoodEntry.slot -> slotMinute: read via entrySlotMinute, written via
  slotFields (whole-hour stays byte-identical, else slot_min), kept by
  copyWithDeleted and the edit screen, so the phone never republishes a
  stripped copy of a PC entry. Out-of-range peer values echo, never throw.
- Satisfaction is nearest-slot snapping (satisfiedSlots) everywhere:
  loggedSlotsToday, due check, kuchnia occupancy, future-day logged set
  (that day's schedule), slot selector. Schedule edits no longer un-log.
- Future pre-log builds DateTime from slot ~/ 60, slot % 60.
- Schedule history + sync go through scheduleToWire/scheduleFromWire.
- Notifications: ids are slot minutes; syncToSlots cancels whatever the
  platform reports active (getActiveNotifications, reminder channel) that
  is not due, covering legacy hour ids; full 0..1439 sweep only if the
  lookup throws.
- Settings: 15-minute dropdowns + "Custom..." (24h showTimePicker), off-grid
  values always selectable, counts capped by grid capacity; editor moved
  to widgets/meal_schedule_editor.dart + meal_time_dropdown.dart.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 19:55:26 +02:00

184 lines
5.8 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.slotMinute],
/// 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);
// Same clear-before-fill discipline as `fillControllersFromDish`: the
// entry's macros describe the whole eaten portion, so any reference
// weight left in `perGrams` would rescale them on save.
_macros.clear();
_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;
// Routed through `fillFrom` rather than six hand-written assignments, so
// this path and the log screen's cannot drift and neither can forget a
// field. It clears first, so nothing survives from the previous pick.
_macros.fillFrom(suggestion.nutrition);
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,
slotMinute: e.slotMinute,
);
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!),
],
],
),
),
);
}
}