mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-27 08:49:12 +01:00
Due-mode log screen, Claude button, photos
Action row 1A, due mode, catering auto-log rows with undo, relay interface, photo input. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
This commit is contained in:
parent
e6322f7f3e
commit
26d6a68ac0
20
AGENTS.md
20
AGENTS.md
@ -15,7 +15,7 @@ show adherence, streaks, a YTD tally and weekly/monthly averages, all derived fr
|
|||||||
- One sync tick: `python -m diet_guard sync`
|
- One sync tick: `python -m diet_guard sync`
|
||||||
- Averages: `python -m diet_guard averages`; Body: `body`, `weight KG`, `profile`, `plan-week`
|
- Averages: `python -m diet_guard averages`; Body: `body`, `weight KG`, `profile`, `plan-week`
|
||||||
- Prune dead sync peers (dry run): `python -m diet_guard prune-peers`
|
- Prune dead sync peers (dry run): `python -m diet_guard prune-peers`
|
||||||
- Phone's "send to Claude" worker: `python -m diet_guard claude-worker`, [docs/DOCS-claude-relay.md](docs/DOCS-claude-relay.md)
|
- "Send to Claude" worker: `python -m diet_guard claude-worker` ([relay](docs/DOCS-claude-relay.md), [screen](docs/DOCS-log-screen.md))
|
||||||
- Install: `bash install.sh` (production); app: `cd app && bash install_arch.sh`; run app: `bash run.sh`; phone: `flutter build apk --release`
|
- Install: `bash install.sh` (production); app: `cd app && bash install_arch.sh`; run app: `bash run.sh`; phone: `flutter build apk --release`
|
||||||
- run: `python -m diet_guard gate --demo`
|
- run: `python -m diet_guard gate --demo`
|
||||||
- test: `python -m pytest -n auto -p no:sugar -q` (python, 100% branch bar from pyproject) then `cd app && flutter test --reporter=compact`
|
- test: `python -m pytest -n auto -p no:sugar -q` (python, 100% branch bar from pyproject) then `cd app && flutter test --reporter=compact`
|
||||||
@ -216,18 +216,18 @@ only); the CLI, gate and phone show both.
|
|||||||
(`2.5.round() == 3`), so a float path silently desyncs the two devices —
|
(`2.5.round() == 3`), so a float path silently desyncs the two devices —
|
||||||
and a slot one device offers while the other does not is a checkpoint that
|
and a slot one device offers while the other does not is a checkpoint that
|
||||||
can never be satisfied, i.e. a permanent lock. Integer `//` and `~/` only.
|
can never be satisfied, i.e. a permanent lock. Integer `//` and `~/` only.
|
||||||
- Don't re-add the meal builder, "repeat last meal", the reward prompt, or
|
- Don't re-add the meal builder, "repeat last meal" or the reward prompt
|
||||||
**meal photos** — all removed deliberately, enforced by
|
(removed deliberately, `app/test/repo_invariants_test.dart`). A meal photo is
|
||||||
`app/test/repo_invariants_test.dart`. Photos also took `image_picker`, the
|
transient input to Claude only (2026-11-17): never stored, on a `FoodEntry`
|
||||||
blob stores, the `/blobs/` route and the `CAMERA` permission; re-adding them
|
or synced; the invariants test asserts no image bytes reach a record.
|
||||||
means syncing image blobs too.
|
|
||||||
- Don't strip the `components` field: nothing writes it, but historical
|
- Don't strip the `components` field: nothing writes it, but historical
|
||||||
composite entries and the food bank read it, and it is part of the sync wire
|
composite entries and the food bank read it, and it is part of the sync wire
|
||||||
format.
|
format.
|
||||||
- Don't let the catering import log unattended (delivered ≠ eaten), don't let
|
- Catering logs itself since 2026-11-17 (kuhy overrode "delivered ≠ eaten":
|
||||||
its Python and Dart halves drift (one shared fixture gates them), and don't
|
"LOG EVEN WITHOUT TAP"): v5 ids `kuchnia:<date>:<dishId>`, undo tombstones.
|
||||||
make the synced password machine-local — the phone could not then fetch.
|
Don't let its Python and Dart halves drift (shared fixtures) or make the
|
||||||
[docs](docs/DOCS-kuchnia-wikinga.md), [phone](docs/DOCS-kuchnia-wikinga-phone.md).
|
synced password machine-local. [docs](docs/DOCS-kuchnia-wikinga.md),
|
||||||
|
[phone](docs/DOCS-kuchnia-wikinga-phone.md).
|
||||||
- Don't add a dependency without the production install-path check above.
|
- Don't add a dependency without the production install-path check above.
|
||||||
- Don't reintroduce a seal/`chattr +i` on the budget file.
|
- Don't reintroduce a seal/`chattr +i` on the budget file.
|
||||||
- Don't re-add a Linux embedder target, and don't change the wrapper's port or
|
- Don't re-add a Linux embedder target, and don't change the wrapper's port or
|
||||||
|
|||||||
@ -19,6 +19,12 @@
|
|||||||
only, foreground only: no READ_HEALTH_DATA_IN_BACKGROUND, so the
|
only, foreground only: no READ_HEALTH_DATA_IN_BACKGROUND, so the
|
||||||
WorkManager isolate never reads Health Connect. -->
|
WorkManager isolate never reads Health Connect. -->
|
||||||
<uses-permission android:name="android.permission.health.READ_STEPS"/>
|
<uses-permission android:name="android.permission.health.READ_STEPS"/>
|
||||||
|
<!-- Camera for the meal photo sent to Claude (meal_photo_source.dart); the
|
||||||
|
runtime permission is requested before the camera opens. A photo is
|
||||||
|
transient input: it is never stored or synced. Not every device has a
|
||||||
|
camera, and the gallery path works without one. -->
|
||||||
|
<uses-permission android:name="android.permission.CAMERA"/>
|
||||||
|
<uses-feature android:name="android.hardware.camera" android:required="false"/>
|
||||||
<!-- Deliberately NOT requesting SCHEDULE_EXACT_ALARM: the background
|
<!-- Deliberately NOT requesting SCHEDULE_EXACT_ALARM: the background
|
||||||
check is a 15-minute WorkManager periodic task, not exact alarms
|
check is a 15-minute WorkManager periodic task, not exact alarms
|
||||||
(more robust against OEM background-kill; +/-15 min is accepted, see
|
(more robust against OEM background-kill; +/-15 min is accepted, see
|
||||||
|
|||||||
@ -20,6 +20,7 @@ class KuchniaDish {
|
|||||||
required this.grams,
|
required this.grams,
|
||||||
required this.priority,
|
required this.priority,
|
||||||
required this.slotLabel,
|
required this.slotLabel,
|
||||||
|
this.dishId = '',
|
||||||
});
|
});
|
||||||
|
|
||||||
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
|
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
|
||||||
@ -52,6 +53,17 @@ class KuchniaDish {
|
|||||||
/// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only.
|
/// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only.
|
||||||
final String slotLabel;
|
final String slotLabel;
|
||||||
|
|
||||||
|
/// The panel's own id for this meal (`deliveryMealId`), as a string, or ''
|
||||||
|
/// when the payload carried none.
|
||||||
|
///
|
||||||
|
/// Never written to the bank record or the log: it only feeds [autologKey].
|
||||||
|
final String dishId;
|
||||||
|
|
||||||
|
/// The dish half of the auto-log entry id: [dishId], else [bankKey].
|
||||||
|
///
|
||||||
|
/// Mirrors the fixture `tests/fixtures/kuchnia_autolog_ids.json`.
|
||||||
|
String get autologKey => dishId.isNotEmpty ? dishId : bankKey;
|
||||||
|
|
||||||
/// The curated-bank record for this dish.
|
/// The curated-bank record for this dish.
|
||||||
///
|
///
|
||||||
/// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count
|
/// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count
|
||||||
|
|||||||
@ -6,8 +6,7 @@ import 'package:material_ui/material_ui.dart';
|
|||||||
|
|
||||||
/// Writes [suggestion]'s name and macros into the log form's controllers.
|
/// Writes [suggestion]'s name and macros into the log form's controllers.
|
||||||
///
|
///
|
||||||
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap, mirroring
|
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap.
|
||||||
/// `log_meal_kuchnia_mixin.dart`'s `fillControllersFromDish`.
|
|
||||||
void fillControllersFromSuggestion(
|
void fillControllersFromSuggestion(
|
||||||
FoodSuggestion suggestion,
|
FoodSuggestion suggestion,
|
||||||
TextEditingController desc,
|
TextEditingController desc,
|
||||||
|
|||||||
112
app/lib/screens/log_meal_claude_mixin.dart
Normal file
112
app/lib/screens/log_meal_claude_mixin.dart
Normal file
@ -0,0 +1,112 @@
|
|||||||
|
/// The sparkle button: send the typed text and/or photo to Claude.
|
||||||
|
///
|
||||||
|
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line
|
||||||
|
/// ceiling. The transport is behind [ClaudeRelayClient]; this only drives the
|
||||||
|
/// button's states and shows the meal Claude logged.
|
||||||
|
///
|
||||||
|
/// The photo lives in [photo] for one send and nowhere else.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_photo_source.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/meal_action_row.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
/// Photo attach and the Claude send, for the log screen's state.
|
||||||
|
mixin LogMealClaudeMixin<T extends StatefulWidget>
|
||||||
|
on
|
||||||
|
LogMealSyncMixin<T>,
|
||||||
|
LogMealDueMixin<T>,
|
||||||
|
LogMealLoggedMixin<T>,
|
||||||
|
LogMealFutureMixin<T> {
|
||||||
|
/// The relay this screen sends through. Supplied by the screen.
|
||||||
|
ClaudeRelayClient get relay;
|
||||||
|
|
||||||
|
/// Where photos come from. Supplied by the screen.
|
||||||
|
MealPhotoSource get photoSource;
|
||||||
|
|
||||||
|
/// The food field. Supplied by the screen.
|
||||||
|
TextEditingController get claudeDesc;
|
||||||
|
|
||||||
|
/// The macro fields. Supplied by the screen.
|
||||||
|
MacroControllers get claudeMacros;
|
||||||
|
|
||||||
|
/// The sparkle button's state.
|
||||||
|
ClaudeButtonState claudeState = ClaudeButtonState.idle;
|
||||||
|
|
||||||
|
/// The attached photo's JPEG bytes, or null. Never stored or synced.
|
||||||
|
Uint8List? photo;
|
||||||
|
|
||||||
|
StreamSubscription<ClaudeRelayEvent>? _relaySub;
|
||||||
|
|
||||||
|
/// Whether there is something to send (a description or a photo).
|
||||||
|
bool get canSend =>
|
||||||
|
futureDate == null &&
|
||||||
|
(claudeDesc.text.trim().isNotEmpty || photo != null);
|
||||||
|
|
||||||
|
/// Attaches a photo from [origin]; backing out keeps the current one.
|
||||||
|
Future<void> attachPhoto(PhotoOrigin origin) async {
|
||||||
|
final bytes = await photoSource.pick(origin);
|
||||||
|
if (!mounted || bytes == null) return;
|
||||||
|
setState(() => photo = bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the attached photo.
|
||||||
|
void removePhoto() => setState(() => photo = null);
|
||||||
|
|
||||||
|
/// Sends the form to Claude and follows the request's events.
|
||||||
|
void sendToClaude() {
|
||||||
|
if (!canSend) return;
|
||||||
|
final request = ClaudeRelayRequest(
|
||||||
|
requestId: const Uuid().v4(),
|
||||||
|
slotMinute: targetSlot,
|
||||||
|
text: claudeDesc.text.trim(),
|
||||||
|
photoJpeg: photo,
|
||||||
|
);
|
||||||
|
unawaited(_relaySub?.cancel());
|
||||||
|
setState(() => claudeState = ClaudeButtonState.sending);
|
||||||
|
_relaySub = relay.send(request).listen((e) => unawaited(_onEvent(e)));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _onEvent(ClaudeRelayEvent event) async {
|
||||||
|
if (!mounted) return;
|
||||||
|
switch (event) {
|
||||||
|
case ClaudeRelayQueued():
|
||||||
|
setState(() => claudeState = ClaudeButtonState.queued);
|
||||||
|
case ClaudeRelayLocked():
|
||||||
|
setState(() => claudeState = ClaudeButtonState.locked);
|
||||||
|
case ClaudeRelayFailed():
|
||||||
|
setState(() => claudeState = ClaudeButtonState.error);
|
||||||
|
case ClaudeRelayLogged(:final entry):
|
||||||
|
// The worker logged it under the request id; the sync would deliver
|
||||||
|
// the same record, so this only shows it now and never doubles it.
|
||||||
|
final stored = await LogStorageService.instance.addIfAbsent(entry);
|
||||||
|
if (!mounted) return;
|
||||||
|
claudeDesc.clear();
|
||||||
|
claudeMacros.clear();
|
||||||
|
setState(() {
|
||||||
|
claudeState = ClaudeButtonState.idle;
|
||||||
|
photo = null;
|
||||||
|
});
|
||||||
|
showLogged([LoggedMeal(stored, LoggedOrigin.claude)]);
|
||||||
|
await publishAfterLog();
|
||||||
|
await refreshSlots();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancels the event subscription; call from `dispose`. A request still
|
||||||
|
/// queued on the PC reaches this phone through sync instead.
|
||||||
|
void disposeClaude() => unawaited(_relaySub?.cancel());
|
||||||
|
}
|
||||||
89
app/lib/screens/log_meal_due_mixin.dart
Normal file
89
app/lib/screens/log_meal_due_mixin.dart
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
/// Due mode: some slot has elapsed with nothing logged.
|
||||||
|
///
|
||||||
|
/// The log screen then strips everything that is not "log this meal now" (the
|
||||||
|
/// app bar, sync banner, date row), hides the Android status bar, and targets
|
||||||
|
/// the oldest due slot with both the check and the sparkle. Its own file
|
||||||
|
/// because `log_meal_screen.dart` is at the repo's 250-line ceiling.
|
||||||
|
///
|
||||||
|
/// Slot arithmetic is not touched here: due slots come from `missingSlots`
|
||||||
|
/// and the nearest-slot rule from `slotForLog`, both in `models/slot.dart`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// The clock the log screen reads for "which slots are due".
|
||||||
|
///
|
||||||
|
/// A hook rather than a constructor argument so the whole screen suite can pin
|
||||||
|
/// it once (`flutter_test_config.dart` pins 07:00, before the first slot);
|
||||||
|
/// otherwise every nav and slot test would pass at night and fail by day, once
|
||||||
|
/// due mode hides the app bar.
|
||||||
|
@visibleForTesting
|
||||||
|
DateTime Function() logMealClock = DateTime.now;
|
||||||
|
|
||||||
|
/// Shows or hides the Android status bar.
|
||||||
|
///
|
||||||
|
/// `main.dart` sets no system-UI mode, so "visible" is the platform default:
|
||||||
|
/// both bars shown. [hidden] true is sticky-immersive; false puts both back.
|
||||||
|
@visibleForTesting
|
||||||
|
Future<void> Function({required bool hidden}) setStatusBarHidden = _setBars;
|
||||||
|
|
||||||
|
Future<void> _setBars({required bool hidden}) => hidden
|
||||||
|
? SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky)
|
||||||
|
: SystemChrome.setEnabledSystemUIMode(
|
||||||
|
SystemUiMode.manual,
|
||||||
|
overlays: SystemUiOverlay.values,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Due-mode state and slot targeting for the log screen's state.
|
||||||
|
mixin LogMealDueMixin<T extends StatefulWidget> on LogMealSyncMixin<T> {
|
||||||
|
/// Whether the first read of today's log has finished. Until then the
|
||||||
|
/// screen draws neither mode, so it never flashes the app bar and drops it.
|
||||||
|
bool slotsLoaded = false;
|
||||||
|
|
||||||
|
bool _statusBarHidden = false;
|
||||||
|
|
||||||
|
/// What the screen reads as "now" (see [logMealClock]).
|
||||||
|
DateTime get screenNow => logMealClock();
|
||||||
|
|
||||||
|
/// Elapsed slots with nothing logged, oldest first.
|
||||||
|
List<int> get dueSlots =>
|
||||||
|
missingSlots(screenNow, loggedSlots, MealScheduleService.current);
|
||||||
|
|
||||||
|
/// Whether the screen is in due mode.
|
||||||
|
bool get dueMode => slotsLoaded && dueSlots.isNotEmpty;
|
||||||
|
|
||||||
|
/// The slot a log or a send lands in: the oldest due slot, else the slot
|
||||||
|
/// nearest [screenNow] (`slotForLog`).
|
||||||
|
int get targetSlot => dueSlots.isNotEmpty
|
||||||
|
? dueSlots.first
|
||||||
|
: slotForLog(screenNow, MealScheduleService.current);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> refreshSlots() async {
|
||||||
|
await super.refreshSlots();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => slotsLoaded = true);
|
||||||
|
await syncStatusBar();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hides the status bar while in due mode and restores it on exit.
|
||||||
|
Future<void> syncStatusBar() async {
|
||||||
|
final hide = dueMode;
|
||||||
|
if (hide == _statusBarHidden) return;
|
||||||
|
_statusBarHidden = hide;
|
||||||
|
await setStatusBarHidden(hidden: hide);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts the status bar back; call from `dispose`.
|
||||||
|
void restoreStatusBar() {
|
||||||
|
if (!_statusBarHidden) return;
|
||||||
|
_statusBarHidden = false;
|
||||||
|
unawaited(setStatusBarHidden(hidden: false));
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,131 +0,0 @@
|
|||||||
/// Wires "Fill all with catering" into the log form.
|
|
||||||
///
|
|
||||||
/// Its own file because `log_meal_screen.dart` and
|
|
||||||
/// `log_meal_kuchnia_mixin.dart` are both at the repo's 250-line ceiling. The
|
|
||||||
/// rule lives in `kuchnia_fill.dart` and the two-tap state in
|
|
||||||
/// `kuchnia_fill_flow.dart`; this only connects them to the screen.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
|
||||||
import 'package:diet_guard_app/ui/cues.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
|
|
||||||
/// One fill tap's status (see [CountCue]).
|
|
||||||
typedef FillCue = CountCue;
|
|
||||||
|
|
||||||
/// The cue for a tap's [outcome]: dishes logged (ok + N), a proposal of
|
|
||||||
/// [armed] dishes (info + N), or nothing done (warn + 0: no delivery, every
|
|
||||||
/// slot taken, or the fetch failed).
|
|
||||||
FillCue fillCue(FillOutcome outcome, {required int armed}) {
|
|
||||||
final written = outcome.written.length;
|
|
||||||
final label = outcome.message;
|
|
||||||
if (written > 0) return (label: label, kind: CueKind.ok, count: written);
|
|
||||||
if (armed > 0) return (label: label, kind: CueKind.info, count: armed);
|
|
||||||
return (label: label, kind: CueKind.warn, count: 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drives the screen's [FillAllFlow] and tidies the screen after a fill.
|
|
||||||
mixin LogMealFillMixin<T extends StatefulWidget>
|
|
||||||
on LogMealSyncMixin<T>, LogMealKuchniaMixin<T>, LogMealFutureMixin<T> {
|
|
||||||
/// The flow behind the button. Per-screen, so leaving the screen drops an
|
|
||||||
/// armed proposal along with it.
|
|
||||||
FillAllFlow fillFlow = FillAllFlow();
|
|
||||||
|
|
||||||
/// Shows [cue] as a status cue (its label is only spoken). Supplied by the
|
|
||||||
/// screen.
|
|
||||||
void showFillStatus(FillCue cue);
|
|
||||||
|
|
||||||
/// A proposal belongs to the date it was fetched for; picking another (or
|
|
||||||
/// going back to today) must not leave "Confirm (N)" offering it.
|
|
||||||
@override
|
|
||||||
void onLogDateChanged() {
|
|
||||||
super.onLogDateChanged();
|
|
||||||
fillFlow.cancel();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs one tap: the first proposes, a second on the same day confirms.
|
|
||||||
/// Fills the "Log for later" date when one is picked, else today.
|
|
||||||
Future<void> onFillAll() async {
|
|
||||||
final day = futureDate;
|
|
||||||
final pending = fillFlow.tap(day: day);
|
|
||||||
setState(() {}); // show the busy label while the fetch/writes run
|
|
||||||
final FillOutcome? outcome;
|
|
||||||
try {
|
|
||||||
outcome = await pending;
|
|
||||||
} on Exception catch (error) {
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {});
|
|
||||||
// A confirm can fail partway through its writes. Whatever did land is
|
|
||||||
// a real meal, so it is published like any other rather than waiting
|
|
||||||
// for the next tick, and the user is told the batch did not finish.
|
|
||||||
await publishAfterLog();
|
|
||||||
await refreshSlots();
|
|
||||||
if (mounted) {
|
|
||||||
showFillStatus((
|
|
||||||
label: 'Fill all failed: $error',
|
|
||||||
kind: CueKind.error,
|
|
||||||
count: null,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {});
|
|
||||||
if (outcome == null) return;
|
|
||||||
if (outcome.written.isNotEmpty) {
|
|
||||||
await _afterFill(outcome.written, later: day != null);
|
|
||||||
}
|
|
||||||
if (!mounted) return;
|
|
||||||
showFillStatus(fillCue(outcome, armed: fillFlow.armedCount));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Disarms a proposal without writing anything.
|
|
||||||
void onFillCancel() {
|
|
||||||
fillFlow.cancel();
|
|
||||||
showFillStatus((
|
|
||||||
label: 'Fill all cancelled — nothing logged.',
|
|
||||||
kind: CueKind.info,
|
|
||||||
count: null,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Publishes the batch once and drops the filled dishes from the delivery
|
|
||||||
/// queue, so "Today's delivery (N more to go)" and the prefilled form do
|
|
||||||
/// not keep offering meals that were just logged.
|
|
||||||
///
|
|
||||||
/// A [later] fill logged another day's delivery: today's queue and form are
|
|
||||||
/// left alone, and the screen goes back to today, as after a manual
|
|
||||||
/// "Log for later" -- the picked day's slot row would otherwise be stale.
|
|
||||||
Future<void> _afterFill(
|
|
||||||
List<SlottedDish> written, {
|
|
||||||
required bool later,
|
|
||||||
}) async {
|
|
||||||
if (later) {
|
|
||||||
resetFutureLog();
|
|
||||||
await publishAfterLog();
|
|
||||||
await refreshSlots();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (KuchniaQueueService.isInitialized) {
|
|
||||||
for (final item in written) {
|
|
||||||
KuchniaQueueService.instance.markLogged(item.dish);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
final offered = offeredDish;
|
|
||||||
if (offered != null &&
|
|
||||||
written.any((item) => item.dish.bankKey == offered.bankKey)) {
|
|
||||||
// The prefilled dish was just logged by the fill; leaving it in the
|
|
||||||
// form would invite a second, duplicate submit.
|
|
||||||
descController.clear();
|
|
||||||
macroControllers.clear();
|
|
||||||
}
|
|
||||||
prefillNextDish();
|
|
||||||
await publishAfterLog();
|
|
||||||
await refreshSlots();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -3,10 +3,7 @@
|
|||||||
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line cap.
|
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line cap.
|
||||||
///
|
///
|
||||||
/// Scoped to dates strictly after today: the date picker's `firstDate` is
|
/// Scoped to dates strictly after today: the date picker's `firstDate` is
|
||||||
/// tomorrow. Today's own not-yet-due slots keep using the screen's existing
|
/// tomorrow.
|
||||||
/// [SlotSelectorRow] (driven by the real `DateTime.now()`), so this mixin
|
|
||||||
/// never has to reproduce its "due" (red) coloring, which is meaningless for
|
|
||||||
/// a day that hasn't started.
|
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
@ -126,23 +123,14 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The slot row to show: [futureDate]'s own (driven by that date's logged
|
/// The slot row for a picked future date, else nothing.
|
||||||
/// slots) when a future date is picked, otherwise today's, built from the
|
///
|
||||||
/// screen's own state and [onTodaySlotSelected].
|
/// Today has no slot row any more: the screen derives today's slot (the
|
||||||
Widget buildSlotRow({
|
/// oldest due one, else the nearest). A *future* date has no due slots to
|
||||||
required Set<int> loggedSlots,
|
/// derive from, so the row survives for exactly that case.
|
||||||
required int? selectedSlot,
|
Widget buildSlotRow() {
|
||||||
required ValueChanged<int?> onTodaySlotSelected,
|
|
||||||
}) {
|
|
||||||
final date = _futureDate;
|
final date = _futureDate;
|
||||||
if (date == null) {
|
if (date == null) return const SizedBox.shrink();
|
||||||
return SlotSelectorRow(
|
|
||||||
now: DateTime.now(),
|
|
||||||
loggedSlots: loggedSlots,
|
|
||||||
selectedSlot: selectedSlot,
|
|
||||||
onSlotSelected: onTodaySlotSelected,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return SlotSelectorRow(
|
return SlotSelectorRow(
|
||||||
now: DateTime(date.year, date.month, date.day),
|
now: DateTime(date.year, date.month, date.day),
|
||||||
schedule: _futureSchedule,
|
schedule: _futureSchedule,
|
||||||
|
|||||||
@ -1,248 +0,0 @@
|
|||||||
/// Offers the day's delivered catering dishes to the log form.
|
|
||||||
///
|
|
||||||
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line
|
|
||||||
/// ceiling.
|
|
||||||
///
|
|
||||||
/// **A delivered meal is not an eaten meal.** This only ever *prefills* the
|
|
||||||
/// form -- the user still taps "Log" for each dish. Nothing here writes a log
|
|
||||||
/// entry, and nothing here may start doing so: the gate would then satisfy its
|
|
||||||
/// own checkpoint from a delivery note, and the log would record what the
|
|
||||||
/// courier dropped off rather than what was eaten.
|
|
||||||
///
|
|
||||||
/// [prefillNextDish] is called from **two** places: once when the delivery
|
|
||||||
/// first arrives, and again after every successful submit. That second caller
|
|
||||||
/// is the load-bearing one. On the PC it briefly did not exist, which made the
|
|
||||||
/// "(N more to go)" promise a dead letter -- every dish after the first stayed
|
|
||||||
/// queued behind another click. `kuchnia_queue_test.dart` asserts the state
|
|
||||||
/// transition rather than "a dish was offered", because the latter passes
|
|
||||||
/// while this misbehaves.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
|
||||||
import 'package:diet_guard_app/ui/cues.dart';
|
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
|
|
||||||
CountCue _cue(String l, CueKind k, [int? n]) => (label: l, kind: k, count: n);
|
|
||||||
|
|
||||||
/// Writes [dish]'s name and macros into the log form's controllers.
|
|
||||||
///
|
|
||||||
/// Free function rather than a mixin method so the numeric formatting is
|
|
||||||
/// testable without pumping a widget.
|
|
||||||
///
|
|
||||||
/// Clears every macro field first, mirroring `_gatelock_delivery.py`'s
|
|
||||||
/// `self._clear_inputs()`. Dropping that step is what corrupted a real log
|
|
||||||
/// entry on 2026-08-23: a dish carries *per-portion* macros and leaves
|
|
||||||
/// [MacroControllers.perGrams] untouched, so a `100` left behind by an
|
|
||||||
/// earlier food-bank pick made `nutritionForPortion` read them as *per-100g*
|
|
||||||
/// and scale them by `grams / 100` -- 472 kcal logged as 1217.8.
|
|
||||||
///
|
|
||||||
/// The clear is a single call covering all six controllers rather than a
|
|
||||||
/// `perGrams.clear()` line here, so a seventh field added later cannot be
|
|
||||||
/// forgotten at this call site; `MacroControllers.clear()` is enumerated by
|
|
||||||
/// its own test.
|
|
||||||
void fillControllersFromDish(
|
|
||||||
KuchniaDish dish,
|
|
||||||
TextEditingController desc,
|
|
||||||
MacroControllers macros,
|
|
||||||
) {
|
|
||||||
macros.clear();
|
|
||||||
desc.text = dish.name;
|
|
||||||
final (grams, values) = dishFieldValues(dish);
|
|
||||||
macros.kcal.text = values.$1;
|
|
||||||
macros.protein.text = values.$2;
|
|
||||||
macros.carbs.text = values.$3;
|
|
||||||
macros.fat.text = values.$4;
|
|
||||||
macros.grams.text = grams;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wires the catering queue into a log form.
|
|
||||||
mixin LogMealKuchniaMixin<T extends StatefulWidget> on State<T> {
|
|
||||||
/// The dish currently prefilled from the delivery, if any.
|
|
||||||
KuchniaDish? offeredDish;
|
|
||||||
|
|
||||||
/// How many delivered dishes still need logging, including the offered one.
|
|
||||||
///
|
|
||||||
/// The offered dish counts: it is prefilled, not logged, and the user has
|
|
||||||
/// still to tap for it. Excluding it made the line read "0 more" while a
|
|
||||||
/// real dish sat in the form.
|
|
||||||
int get dishesStillQueued => KuchniaQueueService.remaining;
|
|
||||||
|
|
||||||
/// The form's description field. Supplied by the screen.
|
|
||||||
TextEditingController get descController;
|
|
||||||
|
|
||||||
/// The form's macro fields. Supplied by the screen.
|
|
||||||
MacroControllers get macroControllers;
|
|
||||||
|
|
||||||
/// Called after the form is filled, so the screen can mark the source.
|
|
||||||
void onDishPrefilled() {}
|
|
||||||
|
|
||||||
/// Fills the form's fields from [dish].
|
|
||||||
///
|
|
||||||
/// Concrete here rather than an abstract hook: every implementation would be
|
|
||||||
/// the same three lines, and the screen file has no budget to spare.
|
|
||||||
void fillFormFromDish(KuchniaDish dish) {
|
|
||||||
fillControllersFromDish(dish, descController, macroControllers);
|
|
||||||
onDishPrefilled();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads today's delivery, guarded so it costs at most one walk per day.
|
|
||||||
///
|
|
||||||
/// Goes through [KuchniaQueueService.refreshOnce] rather than
|
|
||||||
/// `refreshDelivery`: this is an *automatic* trigger and can fire after
|
|
||||||
/// every meal, and each unguarded refresh is a login plus three requests
|
|
||||||
/// against a third party. The settings button is the explicit ask that
|
|
||||||
/// always goes and looks.
|
|
||||||
Future<void> loadDeliveryOnce({Set<String> alreadyLogged = const {}}) async {
|
|
||||||
if (!KuchniaQueueService.isInitialized) return;
|
|
||||||
final result = await KuchniaQueueService.refreshOnce(DateTime.now());
|
|
||||||
if (!mounted || result.dishes.isEmpty) return;
|
|
||||||
// Ordered by the caterer's own meal priority, against the *user's*
|
|
||||||
// schedule -- not a hardcoded four slots. A dish offered for a slot the
|
|
||||||
// user's schedule does not have is a checkpoint that can never be met.
|
|
||||||
final ordered = dishesInSlotOrder(
|
|
||||||
result.dishes,
|
|
||||||
daySlots(MealScheduleService.current),
|
|
||||||
);
|
|
||||||
KuchniaQueueService.instance.offer(ordered, alreadyLogged: alreadyLogged);
|
|
||||||
prefillNextDish();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads today's delivery, skipping dishes already logged today.
|
|
||||||
///
|
|
||||||
/// The skip matters across devices: a dish logged on the PC must not be
|
|
||||||
/// offered again here, and the food log is the only record of that.
|
|
||||||
Future<void> loadTodaysDelivery() async {
|
|
||||||
final logged = await LogStorageService.instance.todayEntries();
|
|
||||||
if (!mounted) return;
|
|
||||||
await loadDeliveryOnce(
|
|
||||||
alreadyLogged: {
|
|
||||||
for (final entry in logged) entry.desc.trim().toLowerCase(),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads today's delivery on an **explicit** user tap, unguarded.
|
|
||||||
///
|
|
||||||
/// Deliberately [refreshDelivery], not [KuchniaQueueService.refreshOnce]:
|
|
||||||
/// per `docs/kuchnia-wikinga.md`'s Triggers table, a user who asks gets a
|
|
||||||
/// look, the same as the CLI and the settings button. The guard exists to
|
|
||||||
/// rate-limit *automatic* triggers, and applying it here would make the
|
|
||||||
/// button silently do nothing for the rest of the day after the startup
|
|
||||||
/// load — the failure that has nothing to tap in the kitchen.
|
|
||||||
///
|
|
||||||
/// Still skips dishes already logged today (a dish logged on the PC must
|
|
||||||
/// not be re-offered) and still records the fetch, so a successful tap
|
|
||||||
/// also spares the automatic path a second walk.
|
|
||||||
///
|
|
||||||
/// Returns the cue to show (a spoken line, a glyph kind and a dish count),
|
|
||||||
/// or null when a dish was prefilled and the form speaks for itself.
|
|
||||||
Future<CountCue?> loadDeliveryOnTap() async {
|
|
||||||
if (!KuchniaQueueService.isInitialized) {
|
|
||||||
return _cue('Catering is not ready yet.', CueKind.warn);
|
|
||||||
}
|
|
||||||
final logged = await LogStorageService.instance.todayEntries();
|
|
||||||
if (!mounted) return null;
|
|
||||||
final result = await refreshDelivery(DateTime.now());
|
|
||||||
if (!mounted) return null;
|
|
||||||
if (!result.ok) return _cue(result.reason!, CueKind.error);
|
|
||||||
if (result.dishes.isEmpty) {
|
|
||||||
return _cue('No delivery today.', CueKind.warn, 0);
|
|
||||||
}
|
|
||||||
await KuchniaQueueService.instance.recordFetched(DateTime.now());
|
|
||||||
if (!mounted) return null;
|
|
||||||
final ordered = dishesInSlotOrder(
|
|
||||||
result.dishes,
|
|
||||||
daySlots(MealScheduleService.current),
|
|
||||||
);
|
|
||||||
KuchniaQueueService.instance.offer(
|
|
||||||
ordered,
|
|
||||||
alreadyLogged: {
|
|
||||||
for (final entry in logged) entry.desc.trim().toLowerCase(),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (KuchniaQueueService.next == null) {
|
|
||||||
return _cue('All delivered dishes are already logged.', CueKind.ok, 0);
|
|
||||||
}
|
|
||||||
prefillNextDish();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether an explicit delivery fetch is in flight.
|
|
||||||
///
|
|
||||||
/// Only guards against a double tap opening two logins at once -- it is not
|
|
||||||
/// the daily guard, which an explicit tap deliberately bypasses.
|
|
||||||
bool deliveryBusy = false;
|
|
||||||
|
|
||||||
/// Runs [loadDeliveryOnTap] and shows its outcome as a SnackBar.
|
|
||||||
///
|
|
||||||
/// Lives here rather than on the screen because `log_meal_screen.dart` is at
|
|
||||||
/// the 250-line cap, and this is the mixin's own behaviour anyway.
|
|
||||||
Future<void> loadDeliveryAndReport() async {
|
|
||||||
setState(() => deliveryBusy = true);
|
|
||||||
CountCue? cue;
|
|
||||||
try {
|
|
||||||
cue = await loadDeliveryOnTap();
|
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => deliveryBusy = false);
|
|
||||||
}
|
|
||||||
if (!mounted || cue == null) return;
|
|
||||||
// The outcome sentence stays as the spoken label; the snackbar paints
|
|
||||||
// the dish glyph in the kind's tint plus the count (0 = none to log).
|
|
||||||
showCueSnack(
|
|
||||||
context,
|
|
||||||
kind: cue.kind,
|
|
||||||
semanticLabel: cue.label,
|
|
||||||
icon: Icons.restaurant,
|
|
||||||
count: cue.count,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Prefills the form with the next queued dish, if there is one.
|
|
||||||
///
|
|
||||||
/// Safe to call when the queue is empty: it simply clears the offer.
|
|
||||||
void prefillNextDish() {
|
|
||||||
final dish = KuchniaQueueService.next;
|
|
||||||
if (dish == null) {
|
|
||||||
if (offeredDish != null) setState(() => offeredDish = null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setState(() => offeredDish = dish);
|
|
||||||
fillFormFromDish(dish);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drops the just-logged dish and immediately offers the next one.
|
|
||||||
///
|
|
||||||
/// Call this from the submit handler *after* the entry is written. This is
|
|
||||||
/// the second caller that keeps the queue alive across a submit.
|
|
||||||
void advanceQueueAfterLog(String loggedDesc) {
|
|
||||||
final dish = offeredDish;
|
|
||||||
if (dish == null) return;
|
|
||||||
if (dish.name.trim().toLowerCase() != loggedDesc.trim().toLowerCase()) {
|
|
||||||
// The user edited the description into something else, so the offered
|
|
||||||
// dish was not what they logged. Leave it queued rather than silently
|
|
||||||
// marking a dish eaten that never was.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
KuchniaQueueService.instance.markLogged(dish);
|
|
||||||
offeredDish = null;
|
|
||||||
prefillNextDish();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A short line naming what is still queued, or null when nothing is.
|
|
||||||
///
|
|
||||||
/// The leftover matters: the caterer's five meals against four default slots
|
|
||||||
/// means at least one dish is still queued when the last slot is logged. It
|
|
||||||
/// is already banked, so it is named rather than dropped silently.
|
|
||||||
String? get queueStatusLine {
|
|
||||||
final left = dishesStillQueued;
|
|
||||||
if (left <= 0) return null;
|
|
||||||
return '$left more delivered ${left == 1 ? 'dish' : 'dishes'} to log.';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
74
app/lib/screens/log_meal_logged_mixin.dart
Normal file
74
app/lib/screens/log_meal_logged_mixin.dart
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
/// The meals the screen logged for the user, shown below the action row with
|
||||||
|
/// an undo, plus the catering auto-log that fills the first of them.
|
||||||
|
///
|
||||||
|
/// The rows stay until the next meal is logged. Undo tombstones that one entry
|
||||||
|
/// by id (`deleteEntry`, never `undoLastToday`: several rows can be on screen,
|
||||||
|
/// and an auto-logged dish is not necessarily the newest entry), so the
|
||||||
|
/// deterministic catering id keeps blocking a re-log on the next open.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Logged-meal rows, undo and the catering auto-log.
|
||||||
|
mixin LogMealLoggedMixin<T extends StatefulWidget>
|
||||||
|
on LogMealSyncMixin<T>, LogMealDueMixin<T> {
|
||||||
|
/// The rows under the action row, oldest first.
|
||||||
|
List<LoggedMeal> loggedRows = const [];
|
||||||
|
|
||||||
|
/// Replaces the rows with [meals]: a new log retires the previous ones.
|
||||||
|
void showLogged(List<LoggedMeal> meals) {
|
||||||
|
if (mounted) setState(() => loggedRows = meals);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tombstones [meal]'s entry, drops its row and republishes.
|
||||||
|
Future<void> undoLogged(LoggedMeal meal) async {
|
||||||
|
final id = meal.entry.id;
|
||||||
|
if (id == null) return;
|
||||||
|
setState(() => loggedRows = [...loggedRows]..remove(meal));
|
||||||
|
await LogStorageService.instance.deleteEntry(id);
|
||||||
|
await publishAfterLog();
|
||||||
|
await refreshSlots();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs the delivered dishes of the due slots, no tap needed.
|
||||||
|
///
|
||||||
|
/// The old rule "a delivered meal is not an eaten meal" was overridden by
|
||||||
|
/// kuhy on 2026-11-17 ("LOG EVEN WITHOUT TAP"). Safe to call repeatedly: the
|
||||||
|
/// ids are deterministic (see `kuchnia_autolog.dart`).
|
||||||
|
Future<void> autoLogCatering() async {
|
||||||
|
if (!dueMode) return;
|
||||||
|
final entries = await KuchniaAutoLog.instance.logDue(dueSlots);
|
||||||
|
if (!mounted || entries.isEmpty) return;
|
||||||
|
showLogged([for (final e in entries) LoggedMeal(e, LoggedOrigin.catering)]);
|
||||||
|
await publishAfterLog();
|
||||||
|
await refreshSlots();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||||
|
// A resume does what an open does, with one sync (autoSync is
|
||||||
|
// single-flight, so calling super too would let the auto-log run before
|
||||||
|
// the pull finished). Pause still pushes through the sync mixin.
|
||||||
|
if (state == AppLifecycleState.resumed) {
|
||||||
|
unawaited(onOpenedOrResumed());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super.didChangeAppLifecycleState(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a fresh open or a resume does: show the screen from the local log,
|
||||||
|
/// pull what other devices logged, then auto-log what is still due.
|
||||||
|
Future<void> onOpenedOrResumed() async {
|
||||||
|
unawaited(refreshSlots());
|
||||||
|
await autoSync();
|
||||||
|
await refreshSlots();
|
||||||
|
await autoLogCatering();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,44 +1,54 @@
|
|||||||
/// Single-food meal logging screen -- the app's primary, done-criterion
|
/// Single-food meal logging screen -- the app's primary, done-criterion
|
||||||
/// screen: "I can open the diet app on my phone and fill meal I ate."
|
/// screen: "I can open the diet app on my phone and fill meal I ate."
|
||||||
|
///
|
||||||
|
/// Two modes. **Due mode** (a slot elapsed with nothing logged) shows only
|
||||||
|
/// what logging needs: the food field, suggestions, macros and the action row,
|
||||||
|
/// with the status bar hidden. **Normal mode** adds the app bar, the sync
|
||||||
|
/// banner and the date row. Either way the action row is photo / Claude /
|
||||||
|
/// log, and the field never moves between states.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:diet_guard_app/models/food_suggestion.dart';
|
import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_actions.dart';
|
import 'package:diet_guard_app/screens/log_meal_actions.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_fill_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_claude_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/services/log_feedback.dart';
|
import 'package:diet_guard_app/services/log_feedback.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_photo_source.dart';
|
||||||
import 'package:diet_guard_app/ui/cues.dart';
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
||||||
import 'package:diet_guard_app/widgets/fill_all_row.dart';
|
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||||
import 'package:diet_guard_app/widgets/log_meal_actions_row.dart';
|
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/meal_action_row.dart';
|
||||||
import 'package:diet_guard_app/widgets/sync_health_banner.dart';
|
import 'package:diet_guard_app/widgets/sync_health_banner.dart';
|
||||||
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Lets the user log one food item, with food-bank autocomplete and
|
/// Lets the user log one food item, with food-bank autocomplete.
|
||||||
/// today's slot status.
|
|
||||||
class LogMealScreen extends StatefulWidget {
|
class LogMealScreen extends StatefulWidget {
|
||||||
/// Creates a [LogMealScreen].
|
/// Creates a [LogMealScreen].
|
||||||
const LogMealScreen({super.key, this.httpClient});
|
const LogMealScreen({super.key, this.httpClient, this.relay, this.photos});
|
||||||
|
|
||||||
/// Injectable HTTP client for auto-sync; tests pass a [MockClient].
|
/// Injectable HTTP client for auto-sync; tests pass a [MockClient].
|
||||||
/// Production leaves this null so [GitHubClient] builds a real one.
|
|
||||||
final http.Client? httpClient;
|
final http.Client? httpClient;
|
||||||
|
|
||||||
|
/// Where the sparkle button sends; the app-wide [claudeRelay] when null.
|
||||||
|
final ClaudeRelayClient? relay;
|
||||||
|
|
||||||
|
/// Where photos come from; the camera/gallery picker when null.
|
||||||
|
final MealPhotoSource? photos;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<LogMealScreen> createState() => _LogMealScreenState();
|
State<LogMealScreen> createState() => _LogMealScreenState();
|
||||||
}
|
}
|
||||||
@ -47,66 +57,59 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
with
|
with
|
||||||
WidgetsBindingObserver,
|
WidgetsBindingObserver,
|
||||||
LogMealSyncMixin<LogMealScreen>,
|
LogMealSyncMixin<LogMealScreen>,
|
||||||
|
LogMealDueMixin<LogMealScreen>,
|
||||||
|
LogMealLoggedMixin<LogMealScreen>,
|
||||||
LogMealNavMixin<LogMealScreen>,
|
LogMealNavMixin<LogMealScreen>,
|
||||||
LogMealKuchniaMixin<LogMealScreen>,
|
|
||||||
LogMealFutureMixin<LogMealScreen>,
|
LogMealFutureMixin<LogMealScreen>,
|
||||||
LogMealFillMixin<LogMealScreen> {
|
LogMealClaudeMixin<LogMealScreen> {
|
||||||
@override
|
@override
|
||||||
http.Client? get syncHttpClient => widget.httpClient;
|
http.Client? get syncHttpClient => widget.httpClient;
|
||||||
|
@override
|
||||||
|
ClaudeRelayClient get relay => widget.relay ?? claudeRelay;
|
||||||
|
@override
|
||||||
|
late final MealPhotoSource photoSource =
|
||||||
|
widget.photos ?? ImagePickerPhotoSource();
|
||||||
|
|
||||||
final TextEditingController _descController = TextEditingController();
|
final TextEditingController _descController = TextEditingController();
|
||||||
final MacroControllers _macros = MacroControllers();
|
final MacroControllers _macros = MacroControllers();
|
||||||
List<FoodSuggestion> _suggestions = const [];
|
|
||||||
@override
|
@override
|
||||||
int? selectedSlot;
|
TextEditingController get claudeDesc => _descController;
|
||||||
|
@override
|
||||||
|
MacroControllers get claudeMacros => _macros;
|
||||||
|
List<FoodSuggestion> _suggestions = const [];
|
||||||
String _source = 'manual';
|
String _source = 'manual';
|
||||||
CueState? _cue; // painted as a tinted icon, never as text
|
CueState? _cue; // painted as a tinted icon, never as text
|
||||||
TodayProgress? _progress;
|
TodayProgress? _progress;
|
||||||
|
|
||||||
void _setCue(CueKind kind, String? label, [int? count]) {
|
|
||||||
_cue = label == null ? null : CueState.next(_cue, kind, label, count);
|
|
||||||
_progress = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
_descController.addListener(_onDescChanged);
|
_descController.addListener(_onDescChanged);
|
||||||
_macros.addListenerToAll(_onMacroEdited);
|
_macros.addListenerToAll(_onMacroEdited);
|
||||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
|
||||||
unawaited(refreshSlots());
|
|
||||||
unawaited(_onDescChanged());
|
unawaited(_onDescChanged());
|
||||||
// Read health before the first sync finishes, so a device that stalled in
|
// Health first, so a device that stalled earlier says so before a tick.
|
||||||
// a previous session says so immediately rather than only after a tick.
|
|
||||||
unawaited(refreshSyncHealth());
|
unawaited(refreshSyncHealth());
|
||||||
unawaited(autoSync());
|
unawaited(onOpenedOrResumed());
|
||||||
// After autoSync so a dish already logged on the PC is known before the
|
|
||||||
// queue is built, and guarded so this costs at most one walk per day.
|
|
||||||
unawaited(loadTodaysDelivery());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
WidgetsBinding.instance.removeObserver(this);
|
WidgetsBinding.instance.removeObserver(this);
|
||||||
|
disposeClaude();
|
||||||
|
restoreStatusBar();
|
||||||
_descController.dispose();
|
_descController.dispose();
|
||||||
_macros.dispose();
|
_macros.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _onMacroEdited() {
|
void _onMacroEdited() {
|
||||||
if (_source == 'food bank') {
|
if (_source == 'food bank') setState(() => _source = 'manual');
|
||||||
setState(() => _source = 'manual');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-runs the food-bank search and dismisses the previous progress card.
|
/// Re-runs the food-bank search and dismisses the previous progress card,
|
||||||
///
|
/// only while the field is non-empty: [_onLogMeal]'s own `clear()` fires
|
||||||
/// The card is cleared only when the field is non-empty because
|
/// this listener too, and would otherwise race it and null the new card.
|
||||||
/// [_onLogMeal]'s own `clear()` fires this listener too: without the guard
|
|
||||||
/// the two async chains race and the clear can null the card right after
|
|
||||||
/// [_onLogMeal] set it, so it never appears on device (in-memory test
|
|
||||||
/// stores resolve fast enough to hide this).
|
|
||||||
Future<void> _onDescChanged() async {
|
Future<void> _onDescChanged() async {
|
||||||
final matches = await FoodBankService.instance.search(_descController.text);
|
final matches = await FoodBankService.instance.search(_descController.text);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
@ -116,16 +119,6 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
|
||||||
TextEditingController get descController => _descController;
|
|
||||||
@override
|
|
||||||
MacroControllers get macroControllers => _macros;
|
|
||||||
@override
|
|
||||||
void onDishPrefilled() => setState(() => _source = 'catering');
|
|
||||||
@override
|
|
||||||
void showFillStatus(FillCue cue) =>
|
|
||||||
setState(() => _setCue(cue.kind, cue.label, cue.count));
|
|
||||||
|
|
||||||
void _onSuggestionSelected(FoodSuggestion suggestion) {
|
void _onSuggestionSelected(FoodSuggestion suggestion) {
|
||||||
fillControllersFromSuggestion(suggestion, _descController, _macros);
|
fillControllersFromSuggestion(suggestion, _descController, _macros);
|
||||||
setState(() {
|
setState(() {
|
||||||
@ -136,17 +129,13 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
|
|
||||||
Future<void> _onLogMeal() async {
|
Future<void> _onLogMeal() async {
|
||||||
final desc = _descController.text.trim();
|
final desc = _descController.text.trim();
|
||||||
if (desc.isEmpty) {
|
if (desc.isEmpty) return;
|
||||||
setState(() => _setCue(CueKind.error, 'Type what you ate first.'));
|
final target = resolveLogTarget(targetSlot);
|
||||||
return;
|
|
||||||
}
|
|
||||||
final target = resolveLogTarget(selectedSlot);
|
|
||||||
if (target.error != null) {
|
if (target.error != null) {
|
||||||
setState(() => _setCue(CueKind.error, target.error));
|
setState(() => _cue = CueState.next(_cue, CueKind.error, target.error!));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// On the tap, before the write/sync: waiting for them is just latency.
|
LogFeedback.mealLogged(); // on the tap, before the write
|
||||||
LogFeedback.mealLogged();
|
|
||||||
final entry = await LogStorageService.instance.logMeal(
|
final entry = await LogStorageService.instance.logMeal(
|
||||||
desc,
|
desc,
|
||||||
nutritionFromControllers(_macros, _source),
|
nutritionFromControllers(_macros, _source),
|
||||||
@ -160,89 +149,99 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
_macros.clear();
|
_macros.clear();
|
||||||
setState(() {
|
setState(() {
|
||||||
_source = 'manual';
|
_source = 'manual';
|
||||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
photo = null; // else a stale photo keeps the sparkle lit
|
||||||
|
claudeState = ClaudeButtonState.idle;
|
||||||
});
|
});
|
||||||
await refreshSlots();
|
await refreshSlots();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
// The second `prefillNextDish` caller. Without it every dish after the
|
showLogged([LoggedMeal(entry, LoggedOrigin.local)]);
|
||||||
// first stays queued behind another tap and the "N more to log" line
|
|
||||||
// becomes a dead letter -- the exact regression the PC gate once shipped.
|
|
||||||
advanceQueueAfterLog(desc);
|
|
||||||
setState(() {
|
setState(() {
|
||||||
_setCue(CueKind.info, queueStatusLine);
|
_cue = null;
|
||||||
_progress = buildTodayProgress(log, logged: entry);
|
_progress = buildTodayProgress(log, logged: entry);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
if (!slotsLoaded) return const Scaffold();
|
||||||
|
final due = dueMode;
|
||||||
|
// Dimmed while Claude works, but never moved: nothing is added around it.
|
||||||
|
final busy = claudeState == ClaudeButtonState.sending;
|
||||||
|
final dim = busy || claudeState == ClaudeButtonState.queued;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: due
|
||||||
// No title: the app's identity is the launcher icon, and the five
|
? null
|
||||||
// destination glyphs fill the bar.
|
: AppBar(
|
||||||
actions: [
|
actions: logMealAppBarActions(
|
||||||
...logMealAppBarActions(
|
onFoodBank: onOpenFoodBank,
|
||||||
onFoodBank: onOpenFoodBank,
|
onHistory: onOpenHistory,
|
||||||
onHistory: onOpenHistory,
|
onCalendar: onOpenCalendar,
|
||||||
onCalendar: onOpenCalendar,
|
onSettings: onOpenSettings,
|
||||||
onSettings: onOpenSettings,
|
onBody: onOpenBody,
|
||||||
onBody: onOpenBody,
|
),
|
||||||
|
),
|
||||||
|
body: SafeArea(
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
padding: const EdgeInsets.all(AppSpacing.md),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
if (!due) ...[
|
||||||
|
SyncHealthBanner(status: syncHealth),
|
||||||
|
buildWhenRow(context),
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
],
|
||||||
|
buildSlotRow(),
|
||||||
|
Opacity(
|
||||||
|
opacity: dim ? 0.5 : 1,
|
||||||
|
child: IgnorePointer(
|
||||||
|
ignoring: busy,
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
IconField(
|
||||||
|
controller: _descController,
|
||||||
|
icon: Icons.fastfood,
|
||||||
|
semanticLabel: 'What did you eat?',
|
||||||
|
onChanged: (_) => setState(() {}),
|
||||||
|
),
|
||||||
|
AutocompleteSuggestionList(
|
||||||
|
suggestions: _suggestions,
|
||||||
|
onSelected: _onSuggestionSelected,
|
||||||
|
compact: true,
|
||||||
|
compactLimit: due ? 2 : 3,
|
||||||
|
reserveHeight: due,
|
||||||
|
),
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
MacroInputRow(controllers: _macros, compact: true),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
MealActionRow(
|
||||||
|
claude: claudeState,
|
||||||
|
photoAttached: photo != null,
|
||||||
|
canSend: canSend,
|
||||||
|
canLog: _descController.text.trim().isNotEmpty,
|
||||||
|
onPhoto: () => unawaited(attachPhoto(PhotoOrigin.camera)),
|
||||||
|
onGallery: () => unawaited(attachPhoto(PhotoOrigin.gallery)),
|
||||||
|
onRemovePhoto: removePhoto,
|
||||||
|
onSend: sendToClaude,
|
||||||
|
onLog: _onLogMeal,
|
||||||
|
),
|
||||||
|
for (final meal in loggedRows)
|
||||||
|
LoggedMealRow(meal: meal, onUndo: () => undoLogged(meal)),
|
||||||
|
if (_cue != null) ...[
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
_cue!.widget,
|
||||||
|
],
|
||||||
|
if (_progress != null && !due) ...[
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
TodayProgressCard(progress: _progress!),
|
||||||
|
],
|
||||||
|
],
|
||||||
),
|
),
|
||||||
],
|
|
||||||
),
|
|
||||||
body: SingleChildScrollView(
|
|
||||||
padding: const EdgeInsets.all(AppSpacing.md),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
SyncHealthBanner(status: syncHealth),
|
|
||||||
buildWhenRow(context),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
buildSlotRow(
|
|
||||||
loggedSlots: loggedSlots,
|
|
||||||
selectedSlot: selectedSlot,
|
|
||||||
onTodaySlotSelected: (slot) =>
|
|
||||||
setState(() => selectedSlot = slot),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
IconField(
|
|
||||||
controller: _descController,
|
|
||||||
icon: Icons.fastfood,
|
|
||||||
semanticLabel: 'What did you eat?',
|
|
||||||
),
|
|
||||||
AutocompleteSuggestionList(
|
|
||||||
suggestions: _suggestions,
|
|
||||||
onSelected: _onSuggestionSelected,
|
|
||||||
compact: true,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
MacroInputRow(controllers: _macros, compact: true),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
LogMealActionsRow(
|
|
||||||
onLoadDelivery: loadDeliveryAndReport,
|
|
||||||
onLog: _onLogMeal,
|
|
||||||
deliveryBusy: deliveryBusy,
|
|
||||||
dishesQueued: dishesStillQueued,
|
|
||||||
),
|
|
||||||
const SizedBox(height: AppSpacing.sm),
|
|
||||||
FillAllRow(
|
|
||||||
onFill: onFillAll,
|
|
||||||
onCancel: onFillCancel,
|
|
||||||
busy: fillFlow.busy || deliveryBusy,
|
|
||||||
armedCount: fillFlow.armedCount,
|
|
||||||
),
|
|
||||||
// Mutually exclusive: _cue carries a validation complaint or
|
|
||||||
// queue note, _progress the post-log summary; the two may stack
|
|
||||||
// only after a log that leaves dishes queued.
|
|
||||||
if (_cue != null) ...[
|
|
||||||
const SizedBox(height: AppSpacing.sm),
|
|
||||||
_cue!.widget,
|
|
||||||
],
|
|
||||||
if (_progress != null) ...[
|
|
||||||
const SizedBox(height: AppSpacing.sm),
|
|
||||||
TodayProgressCard(progress: _progress!),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
|
||||||
import 'package:diet_guard_app/services/background_tasks.dart';
|
import 'package:diet_guard_app/services/background_tasks.dart';
|
||||||
import 'package:diet_guard_app/services/due_slot_check.dart';
|
import 'package:diet_guard_app/services/due_slot_check.dart';
|
||||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
@ -9,7 +8,6 @@ import 'package:diet_guard_app/services/foodbank_service.dart';
|
|||||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||||
import 'package:diet_guard_app/services/health_steps.dart';
|
import 'package:diet_guard_app/services/health_steps.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
|
||||||
import 'package:diet_guard_app/services/sync_health.dart';
|
import 'package:diet_guard_app/services/sync_health.dart';
|
||||||
import 'package:diet_guard_app/services/sync_service.dart';
|
import 'package:diet_guard_app/services/sync_service.dart';
|
||||||
import 'package:diet_guard_app/services/sync_settings.dart';
|
import 'package:diet_guard_app/services/sync_settings.dart';
|
||||||
@ -35,12 +33,6 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
/// The slots that already carry a logged meal today.
|
/// The slots that already carry a logged meal today.
|
||||||
Set<int> loggedSlots = {};
|
Set<int> loggedSlots = {};
|
||||||
|
|
||||||
/// The slot the screen is currently logging for.
|
|
||||||
///
|
|
||||||
/// Owned by the screen's own state; declared here so
|
|
||||||
/// [onScheduleMayHaveChanged] can re-derive it when the schedule changes.
|
|
||||||
abstract int? selectedSlot;
|
|
||||||
|
|
||||||
/// The screen's injected HTTP client, or null to use the default.
|
/// The screen's injected HTTP client, or null to use the default.
|
||||||
///
|
///
|
||||||
/// Declared abstract so the mixin stays independent of the widget's own
|
/// Declared abstract so the mixin stays independent of the widget's own
|
||||||
@ -174,21 +166,12 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
setState(() => loggedSlots = logged);
|
setState(() => loggedSlots = logged);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rebuilds the slot row after the settings screen pops.
|
/// Re-derives the due slots after the settings screen pops.
|
||||||
///
|
///
|
||||||
/// The meal-schedule editor lives in settings, and [SlotSelectorRow] reads
|
/// The meal-schedule editor lives in settings, and which slots are due (and
|
||||||
/// `MealScheduleService.current` at build time, so refreshing is enough to
|
/// so whether the screen is in due mode) reads `MealScheduleService.current`
|
||||||
/// re-derive the row -- but the selected slot also has to be recomputed,
|
/// at refresh time. Found on the phone: without this the settings preview
|
||||||
/// since the minute it referred to may no longer be a checkpoint at all.
|
/// and the overdue reminder both updated while the screen behind them kept
|
||||||
///
|
/// the old checkpoints until the app was restarted.
|
||||||
/// Found on the phone: without this the settings preview and the overdue
|
Future<void> onScheduleMayHaveChanged() => refreshSlots();
|
||||||
/// reminder both updated while the row behind them kept the old four
|
|
||||||
/// checkpoints until the app was restarted.
|
|
||||||
Future<void> onScheduleMayHaveChanged() async {
|
|
||||||
await refreshSlots();
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -40,9 +40,9 @@ class FetchOutcome {
|
|||||||
|
|
||||||
/// Fetches today's delivery and reports what was banked.
|
/// Fetches today's delivery and reports what was banked.
|
||||||
///
|
///
|
||||||
/// Deliberately "banked", not "logged": a delivered meal is not an eaten
|
/// Deliberately "banked", not "logged": the explicit fetch only fills the
|
||||||
/// meal, so the dishes land in the food bank and the user still taps to log
|
/// food bank; logging is the log screen's auto-log (`kuchnia_autolog.dart`).
|
||||||
/// each one. Top-level so the settings screen can pass it without growing.
|
/// Top-level so the settings screen can pass it without growing.
|
||||||
Future<FetchOutcome> fetchTodaysDelivery() async {
|
Future<FetchOutcome> fetchTodaysDelivery() async {
|
||||||
final result = await refreshDelivery(DateTime.now());
|
final result = await refreshDelivery(DateTime.now());
|
||||||
if (!result.ok) return FetchOutcome(CueKind.error, result.reason!);
|
if (!result.ok) return FetchOutcome(CueKind.error, result.reason!);
|
||||||
|
|||||||
105
app/lib/services/claude_relay_client.dart
Normal file
105
app/lib/services/claude_relay_client.dart
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
/// The phone's side of the Claude relay: what the check-mark-gold button
|
||||||
|
/// sends and what comes back.
|
||||||
|
///
|
||||||
|
/// The transport (a request record synced to the PC, a worker that asks Claude
|
||||||
|
/// and logs the meal, the reply) is not here; the screen only talks to this
|
||||||
|
/// interface. See `docs/DOCS-claude-relay.md` for the wire.
|
||||||
|
///
|
||||||
|
/// A `Stream`, not a `Future`: the PC may be off, so a request can sit
|
||||||
|
/// [ClaudeRelayQueued] for hours before the same stream delivers
|
||||||
|
/// [ClaudeRelayLogged]. Terminal events end the stream; [ClaudeRelayQueued]
|
||||||
|
/// does not.
|
||||||
|
///
|
||||||
|
/// **The request id is the future entry id.** The worker logs the meal under
|
||||||
|
/// `ClaudeRelayRequest.requestId`, so the phone's copy (written from
|
||||||
|
/// [ClaudeRelayLogged]) and the PC's copy merge to one entry, and undo is a
|
||||||
|
/// tombstone on that id.
|
||||||
|
///
|
||||||
|
/// **Photos are transient input.** `photoJpeg` lives in memory for one send:
|
||||||
|
/// it is never stored on the phone, never put on a `FoodEntry`, and never part
|
||||||
|
/// of a synced meal record (`repo_invariants_test.dart` enforces it).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
|
||||||
|
/// One send: the text and/or photo, and the slot the meal belongs to.
|
||||||
|
class ClaudeRelayRequest {
|
||||||
|
/// Creates a request; at least one of [text] and [photoJpeg] is non-empty.
|
||||||
|
const ClaudeRelayRequest({
|
||||||
|
required this.requestId,
|
||||||
|
required this.slotMinute,
|
||||||
|
this.text = '',
|
||||||
|
this.photoJpeg,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// A fresh uuid; becomes the logged entry's id.
|
||||||
|
final String requestId;
|
||||||
|
|
||||||
|
/// The slot minute the meal is logged against (the oldest due slot in due
|
||||||
|
/// mode, else `slotForLog`).
|
||||||
|
final int slotMinute;
|
||||||
|
|
||||||
|
/// What the user typed, trimmed; may be empty when a photo is attached.
|
||||||
|
final String text;
|
||||||
|
|
||||||
|
/// The photo as a JPEG of at most 1024 px, or null.
|
||||||
|
final Uint8List? photoJpeg;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the relay reports about one [ClaudeRelayRequest].
|
||||||
|
sealed class ClaudeRelayEvent {
|
||||||
|
const ClaudeRelayEvent();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The PC is offline; the request is stored and will run later (not terminal).
|
||||||
|
final class ClaudeRelayQueued extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event.
|
||||||
|
const ClaudeRelayQueued();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claude logged the meal (terminal). `entry.id == request.requestId`.
|
||||||
|
final class ClaudeRelayLogged extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event for [entry].
|
||||||
|
const ClaudeRelayLogged(this.entry);
|
||||||
|
|
||||||
|
/// The entry the worker wrote.
|
||||||
|
final FoodEntry entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sync is locked (no passphrase), so nothing can be sent (terminal).
|
||||||
|
final class ClaudeRelayLocked extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event.
|
||||||
|
const ClaudeRelayLocked();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The send failed (terminal); [reason] is for logs, never painted.
|
||||||
|
final class ClaudeRelayFailed extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event.
|
||||||
|
const ClaudeRelayFailed(this.reason);
|
||||||
|
|
||||||
|
/// Why it failed.
|
||||||
|
final String reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends a meal to Claude through the relay.
|
||||||
|
abstract interface class ClaudeRelayClient {
|
||||||
|
/// Sends [request]; the stream carries zero or more [ClaudeRelayQueued]
|
||||||
|
/// then one terminal event, and never throws (failures are events).
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stand-in until a transport is wired: every send fails closed.
|
||||||
|
class UnconfiguredClaudeRelayClient implements ClaudeRelayClient {
|
||||||
|
/// Creates the stand-in.
|
||||||
|
const UnconfiguredClaudeRelayClient();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) =>
|
||||||
|
Stream.value(const ClaudeRelayFailed('relay not configured'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client the screen uses unless it is handed one; `main.dart` assigns the
|
||||||
|
/// real transport.
|
||||||
|
ClaudeRelayClient claudeRelay = const UnconfiguredClaudeRelayClient();
|
||||||
37
app/lib/services/claude_relay_fake.dart
Normal file
37
app/lib/services/claude_relay_fake.dart
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
/// A controllable [ClaudeRelayClient] for tests and the unwired app.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
|
||||||
|
/// Records every request and lets the test emit the events by hand.
|
||||||
|
///
|
||||||
|
/// [emit] pushes to the most recent send's stream; a terminal event closes it,
|
||||||
|
/// as a real client's would.
|
||||||
|
class FakeClaudeRelayClient implements ClaudeRelayClient {
|
||||||
|
/// Every request sent, oldest first.
|
||||||
|
final List<ClaudeRelayRequest> sent = [];
|
||||||
|
|
||||||
|
/// Events replayed on each send before the stream waits for [emit].
|
||||||
|
final List<ClaudeRelayEvent> script = [];
|
||||||
|
|
||||||
|
StreamController<ClaudeRelayEvent>? _open;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) {
|
||||||
|
sent.add(request);
|
||||||
|
final controller = StreamController<ClaudeRelayEvent>();
|
||||||
|
_open = controller;
|
||||||
|
script.forEach(emit);
|
||||||
|
return controller.stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delivers [event] to the open stream; a terminal one closes it.
|
||||||
|
void emit(ClaudeRelayEvent event) {
|
||||||
|
final controller = _open;
|
||||||
|
if (controller == null || controller.isClosed) return;
|
||||||
|
controller.add(event);
|
||||||
|
if (event is! ClaudeRelayQueued) unawaited(controller.close());
|
||||||
|
}
|
||||||
|
}
|
||||||
107
app/lib/services/kuchnia_autolog.dart
Normal file
107
app/lib/services/kuchnia_autolog.dart
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
/// Logs the delivered catering dishes of the due slots, without a tap.
|
||||||
|
///
|
||||||
|
/// kuhy overrode the old "delivered is not eaten, so never log unattended"
|
||||||
|
/// rule on 2026-11-17 ("LOG EVEN WITHOUT TAP"). The screen calls [logDue] when
|
||||||
|
/// it opens or resumes with a slot due; the plan is the fill-all plan
|
||||||
|
/// (`assignSlots` by the caterer's `mealPriority`, `fillPlan` over occupied
|
||||||
|
/// slots) minus the confirm tap, restricted to the due slots.
|
||||||
|
///
|
||||||
|
/// **Ids are deterministic** so a repeat open and every other device collapse
|
||||||
|
/// to one entry on merge: UUID v5 over the RFC 4122 URL namespace of
|
||||||
|
/// `kuchnia:<delivery date YYYY-MM-DD>:<dish key>`. The shared fixture
|
||||||
|
/// `tests/fixtures/kuchnia_autolog_ids.json` pins them for both languages.
|
||||||
|
/// An undone dish keeps its tombstone, so it is never logged a second time.
|
||||||
|
///
|
||||||
|
/// The fetch is a third-party login, so the day's dishes are cached in memory
|
||||||
|
/// and a failed or empty fetch is retried at most every [retryAfter].
|
||||||
|
/// `KuchniaQueueService.refreshOnce` cannot serve here: after the first clean
|
||||||
|
/// fetch of the day it returns nothing, and slots that fall due later would
|
||||||
|
/// never see their dish.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
||||||
|
import 'package:diet_guard_app/models/local_time.dart';
|
||||||
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_fill.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:flutter/foundation.dart' show visibleForTesting;
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
/// The id of the entry that logs [dish] for [deliveryDate] (`YYYY-MM-DD`).
|
||||||
|
String kuchniaAutologId(String deliveryDate, KuchniaDish dish) => const Uuid()
|
||||||
|
.v5(Namespace.url.value, 'kuchnia:$deliveryDate:${dish.autologKey}');
|
||||||
|
|
||||||
|
/// Logs delivered dishes for due slots. One per process is plenty.
|
||||||
|
class KuchniaAutoLog {
|
||||||
|
/// Creates the service; every dependency is injectable for tests.
|
||||||
|
KuchniaAutoLog({
|
||||||
|
DeliveryFetch? fetch,
|
||||||
|
DateTime Function()? now,
|
||||||
|
this.retryAfter = const Duration(minutes: 10),
|
||||||
|
}) : _fetch = fetch ?? refreshDelivery,
|
||||||
|
_now = now ?? DateTime.now;
|
||||||
|
|
||||||
|
/// The process-wide instance the screen uses.
|
||||||
|
static KuchniaAutoLog instance = KuchniaAutoLog();
|
||||||
|
|
||||||
|
/// Minimum gap between fetches that found nothing or failed.
|
||||||
|
final Duration retryAfter;
|
||||||
|
|
||||||
|
final DeliveryFetch _fetch;
|
||||||
|
final DateTime Function() _now;
|
||||||
|
String? _cachedDay;
|
||||||
|
List<KuchniaDish> _cachedDishes = const [];
|
||||||
|
DateTime? _lastEmptyFetch;
|
||||||
|
Future<List<FoodEntry>>? _inFlight;
|
||||||
|
|
||||||
|
/// Forgets the cache, so the next call fetches again (tests, day change).
|
||||||
|
@visibleForTesting
|
||||||
|
void reset() {
|
||||||
|
_cachedDay = null;
|
||||||
|
_cachedDishes = const [];
|
||||||
|
_lastEmptyFetch = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs the dishes assigned to [dueSlots]; returns the entries it wrote.
|
||||||
|
///
|
||||||
|
/// Single-flight: a second call while one runs joins it, so an open and a
|
||||||
|
/// resume racing each other cannot interleave two read-modify-writes.
|
||||||
|
Future<List<FoodEntry>> logDue(List<int> dueSlots) =>
|
||||||
|
_inFlight ??= _run(dueSlots).whenComplete(() => _inFlight = null);
|
||||||
|
|
||||||
|
Future<List<FoodEntry>> _run(List<int> dueSlots) async {
|
||||||
|
if (dueSlots.isEmpty) return const [];
|
||||||
|
final today = _now();
|
||||||
|
final dayKey = localDateKey(today);
|
||||||
|
final dishes = await _dishesFor(today, dayKey);
|
||||||
|
if (dishes.isEmpty) return const [];
|
||||||
|
final store = LogStorageService.instance;
|
||||||
|
final slots = daySlots(MealScheduleService.history.forDay(dayKey));
|
||||||
|
final plan = fillPlan(
|
||||||
|
assignSlots(dishes, slots),
|
||||||
|
await loggedSlotsOn(store, today),
|
||||||
|
).where((item) => dueSlots.contains(item.slot)).toList();
|
||||||
|
String idFor(SlottedDish item) => kuchniaAutologId(dayKey, item.dish);
|
||||||
|
final written = await logDishes(plan, storage: store, idFor: idFor);
|
||||||
|
return [for (final item in written) ?await store.findEntry(idFor(item))];
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<List<KuchniaDish>> _dishesFor(DateTime today, String dayKey) async {
|
||||||
|
if (_cachedDay == dayKey) return _cachedDishes;
|
||||||
|
final last = _lastEmptyFetch;
|
||||||
|
if (last != null && _now().difference(last) < retryAfter) return const [];
|
||||||
|
final result = await _fetch(today);
|
||||||
|
if (result.ok && result.dishes.isNotEmpty) {
|
||||||
|
_cachedDay = dayKey;
|
||||||
|
return _cachedDishes = result.dishes;
|
||||||
|
}
|
||||||
|
_lastEmptyFetch = _now();
|
||||||
|
return const [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -3,10 +3,12 @@
|
|||||||
/// The Dart mirror of `diet_guard/_kuchnia_log.py`'s `fill_plan` and
|
/// The Dart mirror of `diet_guard/_kuchnia_log.py`'s `fill_plan` and
|
||||||
/// `log_dishes`. KEEP IN SYNC, gated by the shared parity fixture.
|
/// `log_dishes`. KEEP IN SYNC, gated by the shared parity fixture.
|
||||||
///
|
///
|
||||||
/// **Nothing here runs without an explicit confirm tap.** A delivered meal is
|
/// **Delivered counts as eaten (override, 2026-11-17).** The old rule was "a
|
||||||
/// not an eaten meal: logging unattended would let the delivery note satisfy
|
/// delivered meal is not an eaten meal, so nothing logs without a confirm
|
||||||
/// the very checkpoints the gate exists to enforce. [logDishes] is only ever
|
/// tap". kuhy overrode it ("LOG EVEN WITHOUT TAP"): [logDishes] is now also
|
||||||
/// reached from the second tap of `FillAllFlow`.
|
/// reached unattended from `kuchnia_autolog.dart`, which logs the dishes of the
|
||||||
|
/// slots that are due when the app opens. Every such entry has a deterministic
|
||||||
|
/// id and shows an undo row, so a skipped or binned meal is one tap to remove.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
@ -15,6 +17,7 @@ import 'package:diet_guard_app/models/local_time.dart';
|
|||||||
import 'package:diet_guard_app/models/nutrition.dart';
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
|
||||||
@ -98,25 +101,34 @@ Future<Set<int>> loggedSlotsOn(LogStorageService store, DateTime day) async {
|
|||||||
/// (a "Log for later" date, strictly after today) each dish is stamped at its
|
/// (a "Log for later" date, strictly after today) each dish is stamped at its
|
||||||
/// slot's time on that day; without it, now -- as a manual log is.
|
/// slot's time on that day; without it, now -- as a manual log is.
|
||||||
///
|
///
|
||||||
|
/// [idFor] gives each dish a deterministic entry id (see
|
||||||
|
/// `kuchniaAutologId`); a dish whose id is already in the log is skipped.
|
||||||
|
///
|
||||||
/// Returns the dishes actually written, in order.
|
/// Returns the dishes actually written, in order.
|
||||||
Future<List<SlottedDish>> logDishes(
|
Future<List<SlottedDish>> logDishes(
|
||||||
List<SlottedDish> chosen, {
|
List<SlottedDish> chosen, {
|
||||||
LogStorageService? storage,
|
LogStorageService? storage,
|
||||||
DateTime? day,
|
DateTime? day,
|
||||||
|
String Function(SlottedDish item)? idFor,
|
||||||
}) async {
|
}) async {
|
||||||
final store = storage ?? LogStorageService.instance;
|
final store = storage ?? LogStorageService.instance;
|
||||||
final seen = {
|
final seen = {
|
||||||
for (final entry in await dayEntries(store, day))
|
for (final entry in await dayEntries(store, day))
|
||||||
_dedupKey(entry.desc, entry.slotMinute),
|
_dedupKey(entry.desc, entry.slotMinute),
|
||||||
};
|
};
|
||||||
|
// Tombstones included: an undone auto-logged dish must stay undone.
|
||||||
|
final knownIds = idFor == null ? const <String>{} : await store.allEntryIds();
|
||||||
final written = <SlottedDish>[];
|
final written = <SlottedDish>[];
|
||||||
for (final item in chosen) {
|
for (final item in chosen) {
|
||||||
|
final id = idFor?.call(item);
|
||||||
|
if (id != null && knownIds.contains(id)) continue;
|
||||||
final key = _dedupKey(item.dish.name, item.slot);
|
final key = _dedupKey(item.dish.name, item.slot);
|
||||||
if (!seen.add(key)) continue;
|
if (!seen.add(key)) continue;
|
||||||
await store.logMeal(
|
await store.logMeal(
|
||||||
item.dish.name,
|
item.dish.name,
|
||||||
dishNutrition(item.dish),
|
dishNutrition(item.dish),
|
||||||
slotMinute: item.slot,
|
slotMinute: item.slot,
|
||||||
|
id: id,
|
||||||
when: day == null
|
when: day == null
|
||||||
? null
|
? null
|
||||||
: DateTime(
|
: DateTime(
|
||||||
|
|||||||
@ -4,12 +4,10 @@
|
|||||||
/// fail-closed boundary: every [KuchniaError] is turned into a reason string
|
/// fail-closed boundary: every [KuchniaError] is turned into a reason string
|
||||||
/// here, so no caller can be broken by a catering outage.
|
/// here, so no caller can be broken by a catering outage.
|
||||||
///
|
///
|
||||||
/// **Nothing is ever logged from here.** A delivered meal is not an eaten
|
/// **Nothing is logged from here: this only banks.** Dishes land in the
|
||||||
/// meal: dishes land in the *curated* bank and the user still taps to log
|
/// *curated* bank. Logging them is `kuchnia_autolog.dart`'s job, which kuhy
|
||||||
/// each one. If the import logged automatically, the gate would satisfy its
|
/// allowed without a tap on 2026-11-17 ("LOG EVEN WITHOUT TAP"; it was
|
||||||
/// own checkpoint from a delivery note, and the log would record what the
|
/// "delivered is not eaten" before), under deterministic ids with an undo.
|
||||||
/// courier dropped off rather than what was eaten -- skipped, shared and
|
|
||||||
/// binned meals included.
|
|
||||||
///
|
///
|
||||||
/// Imports go **only** to the curated bank. The derived bank is rebuilt from
|
/// Imports go **only** to the curated bank. The derived bank is rebuilt from
|
||||||
/// the log on every meal, so anything written there would vanish at the next
|
/// the log on every meal, so anything written there would vanish at the next
|
||||||
|
|||||||
@ -74,6 +74,15 @@ bool energyIsConsistent(double kcal, double protein, double carbs, double fat) {
|
|||||||
return (derived - kcal).abs() <= kuchniaEnergyTolerance * kcal;
|
return (derived - kcal).abs() <= kuchniaEnergyTolerance * kcal;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The panel's meal id as a string, or '' when absent or not a string/int.
|
||||||
|
///
|
||||||
|
/// A bool is not an id; Dart's `is int` already excludes it, matching Python.
|
||||||
|
String _mealId(Object? raw) {
|
||||||
|
if (raw is int) return raw.toString();
|
||||||
|
if (raw is String) return raw.trim();
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
/// Builds one dish, or null when the entry is unusable.
|
/// Builds one dish, or null when the entry is unusable.
|
||||||
///
|
///
|
||||||
/// [fallbackPriority] is the 1-based payload position, used when
|
/// [fallbackPriority] is the 1-based payload position, used when
|
||||||
@ -113,6 +122,7 @@ KuchniaDish? parseMeal(Object? meal, int fallbackPriority) {
|
|||||||
grams: grams,
|
grams: grams,
|
||||||
priority: priority,
|
priority: priority,
|
||||||
slotLabel: rawLabel is String ? rawLabel.trim() : '',
|
slotLabel: rawLabel is String ? rawLabel.trim() : '',
|
||||||
|
dishId: _mealId(meal['deliveryMealId']),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
/// The day's delivered dishes, offered to the log form one at a time.
|
/// The day's delivered dishes, offered to the log form one at a time.
|
||||||
///
|
///
|
||||||
/// **A delivered meal is not an eaten meal.** This queue only ever *prefills*
|
/// **Since 2026-11-17 the log screen no longer prefills from this queue**: a
|
||||||
/// the form; the user still taps to log each dish. Nothing here writes a log
|
/// delivered dish logs itself when its slot is due (`kuchnia_autolog.dart`;
|
||||||
/// entry, and nothing here may start doing so -- the gate would then satisfy
|
/// kuhy overrode "delivered is not eaten", "LOG EVEN WITHOUT TAP"). What
|
||||||
/// its own checkpoint from a delivery note, and the log would record what the
|
/// remains here is the offer/mark bookkeeping and the fetched-today marker.
|
||||||
/// courier dropped off rather than what was eaten.
|
/// The queue itself still writes no log entry.
|
||||||
///
|
///
|
||||||
/// Two things are load-bearing:
|
/// Two things are load-bearing:
|
||||||
///
|
///
|
||||||
|
|||||||
55
app/lib/services/log_entry_lookup.dart
Normal file
55
app/lib/services/log_entry_lookup.dart
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
/// Id lookups over the food log, tombstones included.
|
||||||
|
///
|
||||||
|
/// Split out of `log_storage_service.dart` for the repo's 250-line cap.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/models/local_time.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
|
||||||
|
/// Returns the entry with [id] anywhere in [log], deleted or not, else null.
|
||||||
|
///
|
||||||
|
/// Tombstones count on purpose: an entry the user undid must keep blocking
|
||||||
|
/// its own id, or a repeat open would log it again.
|
||||||
|
FoodEntry? findEntryById(DayLog log, String id) {
|
||||||
|
for (final entries in log.values) {
|
||||||
|
for (final entry in entries) {
|
||||||
|
if (entry.id == id) return entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Id-keyed writes and reads on [LogStorageService].
|
||||||
|
extension LogEntryLookup on LogStorageService {
|
||||||
|
/// The entry with [id], deleted or not, else null.
|
||||||
|
Future<FoodEntry?> findEntry(String id) async =>
|
||||||
|
findEntryById(await readLog(), id);
|
||||||
|
|
||||||
|
/// Every id in the log, tombstones included.
|
||||||
|
Future<Set<String>> allEntryIds() async => {
|
||||||
|
for (final entries in (await readLog()).values)
|
||||||
|
for (final entry in entries) ?entry.id,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Adds [entry] unless one with its id exists (live or tombstoned), and
|
||||||
|
/// returns whichever copy the log holds.
|
||||||
|
///
|
||||||
|
/// For an entry another device wrote under an id chosen here, such as a
|
||||||
|
/// Claude-logged meal: the sync merge delivers the same record, so this only
|
||||||
|
/// shows it a tick earlier and can never double it.
|
||||||
|
Future<FoodEntry> addIfAbsent(FoodEntry entry) async {
|
||||||
|
final log = await readLog();
|
||||||
|
final id = entry.id;
|
||||||
|
if (id != null) {
|
||||||
|
final existing = findEntryById(log, id);
|
||||||
|
if (existing != null) return existing;
|
||||||
|
}
|
||||||
|
final dayKey = entry.time.length >= 10
|
||||||
|
? entry.time.substring(0, 10)
|
||||||
|
: localDateKey(DateTime.now());
|
||||||
|
log.putIfAbsent(dayKey, () => []).add(entry);
|
||||||
|
await writeLog(log);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -10,6 +10,7 @@ import 'package:diet_guard_app/models/nutrition.dart';
|
|||||||
import 'package:diet_guard_app/models/slot.dart';
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
import 'package:diet_guard_app/services/document_store.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/document_store_factory.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:uuid/uuid.dart';
|
import 'package:uuid/uuid.dart';
|
||||||
@ -39,10 +40,8 @@ class LogStorageService {
|
|||||||
|
|
||||||
final DocumentStore _store;
|
final DocumentStore _store;
|
||||||
|
|
||||||
/// Initializes the singleton against the platform document store: files in
|
/// Initializes the singleton against the platform document store (files on
|
||||||
/// the app's documents directory on Android (phone-sandboxed; no
|
/// Android, IndexedDB in the browser-hosted desktop app).
|
||||||
/// external-storage permission needed), IndexedDB in the browser-hosted
|
|
||||||
/// desktop app.
|
|
||||||
static Future<LogStorageService> init() async {
|
static Future<LogStorageService> init() async {
|
||||||
if (_instance != null) return _instance!;
|
if (_instance != null) return _instance!;
|
||||||
final svc = LogStorageService._(await openDocumentStore());
|
final svc = LogStorageService._(await openDocumentStore());
|
||||||
@ -88,8 +87,7 @@ class LogStorageService {
|
|||||||
|
|
||||||
/// Persists the full log to the store, mirroring `_state._write_log`.
|
/// Persists the full log to the store, mirroring `_state._write_log`.
|
||||||
///
|
///
|
||||||
/// Atomicity against a concurrent reader is the store's job (see
|
/// Atomicity against a concurrent reader is the store's job.
|
||||||
/// `FileDocumentStore.write`'s temp-file-and-rename), not this method's.
|
|
||||||
Future<void> writeLog(DayLog log) async {
|
Future<void> writeLog(DayLog log) async {
|
||||||
final encoded = <String, Object?>{
|
final encoded = <String, Object?>{
|
||||||
for (final mapEntry in log.entries)
|
for (final mapEntry in log.entries)
|
||||||
@ -98,27 +96,34 @@ class LogStorageService {
|
|||||||
await _store.write(documentName, jsonEncode(encoded));
|
await _store.write(documentName, jsonEncode(encoded));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Appends a signed-on-PC-eventually entry for [desc] to [when]'s day (or
|
/// Appends an entry for [desc] to [when]'s day (today's when null).
|
||||||
/// today's, when [when] is null).
|
|
||||||
///
|
///
|
||||||
/// Mirrors `_state.log_meal`: always assigns a fresh `id`, never computes
|
/// Mirrors `_state.log_meal`: never computes an `hmac` (the phone never
|
||||||
/// an `hmac` (the phone never holds the shared key -- the PC re-signs on
|
/// holds the key; the PC re-signs on merge). [when] pre-logs a future
|
||||||
/// merge, see Milestone 3). [when] lets a caller pre-log a meal against a
|
/// date/slot and must not be in the past. [slotMinute] is a minute of day
|
||||||
/// future date/slot; must not be in the past. [slotMinute] is the slot's
|
/// (`slotForLog`'s result), never an hour.
|
||||||
/// minute of day (`slotForLog`'s result), never an hour.
|
///
|
||||||
|
/// A caller-chosen [id] makes the write idempotent: an entry already
|
||||||
|
/// carrying it (live or tombstoned) is returned and nothing is written.
|
||||||
Future<FoodEntry> logMeal(
|
Future<FoodEntry> logMeal(
|
||||||
String desc,
|
String desc,
|
||||||
Nutrition nutrition, {
|
Nutrition nutrition, {
|
||||||
int? slotMinute,
|
int? slotMinute,
|
||||||
List<MealComponent>? components,
|
List<MealComponent>? components,
|
||||||
DateTime? when,
|
DateTime? when,
|
||||||
|
String? id,
|
||||||
}) async {
|
}) async {
|
||||||
if (when != null && when.isBefore(DateTime.now())) {
|
if (when != null && when.isBefore(DateTime.now())) {
|
||||||
throw ArgumentError.value(when, 'when', 'cannot log a meal in the past');
|
throw ArgumentError.value(when, 'when', 'cannot log a meal in the past');
|
||||||
}
|
}
|
||||||
final now = when ?? DateTime.now();
|
final now = when ?? DateTime.now();
|
||||||
|
final log = await readLog();
|
||||||
|
if (id != null) {
|
||||||
|
final existing = findEntryById(log, id);
|
||||||
|
if (existing != null) return existing;
|
||||||
|
}
|
||||||
final entry = FoodEntry(
|
final entry = FoodEntry(
|
||||||
id: const Uuid().v4(),
|
id: id ?? const Uuid().v4(),
|
||||||
time: isoLocalSeconds(now),
|
time: isoLocalSeconds(now),
|
||||||
desc: desc,
|
desc: desc,
|
||||||
grams: nutrition.grams,
|
grams: nutrition.grams,
|
||||||
@ -130,7 +135,6 @@ class LogStorageService {
|
|||||||
slotMinute: slotMinute,
|
slotMinute: slotMinute,
|
||||||
components: components,
|
components: components,
|
||||||
);
|
);
|
||||||
final log = await readLog();
|
|
||||||
log.putIfAbsent(localDateKey(now), () => []).add(entry);
|
log.putIfAbsent(localDateKey(now), () => []).add(entry);
|
||||||
await writeLog(log);
|
await writeLog(log);
|
||||||
return entry;
|
return entry;
|
||||||
@ -165,9 +169,6 @@ class LogStorageService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns every non-tombstoned entry across all days, newest first.
|
/// Returns every non-tombstoned entry across all days, newest first.
|
||||||
///
|
|
||||||
/// Backs the history screen -- the only place that needs to see more than
|
|
||||||
/// "today".
|
|
||||||
Future<List<FoodEntry>> allEntriesNewestFirst() async {
|
Future<List<FoodEntry>> allEntriesNewestFirst() async {
|
||||||
final log = await readLog();
|
final log = await readLog();
|
||||||
final entries =
|
final entries =
|
||||||
@ -183,7 +184,7 @@ class LogStorageService {
|
|||||||
return entries;
|
return entries;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns today's total calories, mirrors `_state.today_total_kcal`.
|
/// Today's total calories, mirrors `_state.today_total_kcal`.
|
||||||
Future<double> todayTotalKcal() async {
|
Future<double> todayTotalKcal() async {
|
||||||
final entries = await todayEntries();
|
final entries = await todayEntries();
|
||||||
var total = 0.0;
|
var total = 0.0;
|
||||||
|
|||||||
8
app/lib/services/meal_photo_cleanup.dart
Normal file
8
app/lib/services/meal_photo_cleanup.dart
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
/// Deletes the cache file `image_picker` leaves behind.
|
||||||
|
///
|
||||||
|
/// `dart:io` stays behind the platform seam (see `repo_invariants_test.dart`):
|
||||||
|
/// the io half deletes, the web half has no file to delete.
|
||||||
|
library;
|
||||||
|
|
||||||
|
export 'meal_photo_cleanup_io.dart'
|
||||||
|
if (dart.library.js_interop) 'meal_photo_cleanup_web.dart';
|
||||||
11
app/lib/services/meal_photo_cleanup_io.dart
Normal file
11
app/lib/services/meal_photo_cleanup_io.dart
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
/// Deletes the picked file at [path]; a failure is not worth a crash.
|
||||||
|
Future<void> discardPickedFile(String path) async {
|
||||||
|
try {
|
||||||
|
await File(path).delete();
|
||||||
|
} on FileSystemException {
|
||||||
|
// Already gone, or not ours to delete: the bytes were read, which is all
|
||||||
|
// that mattered.
|
||||||
|
}
|
||||||
|
}
|
||||||
2
app/lib/services/meal_photo_cleanup_web.dart
Normal file
2
app/lib/services/meal_photo_cleanup_web.dart
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
/// Web has no cache file: the picker returns an in-memory blob.
|
||||||
|
Future<void> discardPickedFile(String path) async {}
|
||||||
76
app/lib/services/meal_photo_source.dart
Normal file
76
app/lib/services/meal_photo_source.dart
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
/// Where a meal photo comes from. A photo is transient input to Claude: the
|
||||||
|
/// bytes live in memory for one send and are never stored, put on a
|
||||||
|
/// `FoodEntry` or synced.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/meal_photo_cleanup.dart';
|
||||||
|
import 'package:flutter/foundation.dart' show kIsWeb, visibleForTesting;
|
||||||
|
import 'package:image_picker/image_picker.dart';
|
||||||
|
import 'package:permission_handler/permission_handler.dart';
|
||||||
|
|
||||||
|
/// Which picker the user asked for.
|
||||||
|
enum PhotoOrigin {
|
||||||
|
/// Take a new photo (a tap on the photo button).
|
||||||
|
camera,
|
||||||
|
|
||||||
|
/// Choose an existing one (a long press).
|
||||||
|
gallery,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands back a photo as JPEG bytes, or null when the user backed out.
|
||||||
|
abstract interface class MealPhotoSource {
|
||||||
|
/// Picks one photo from [origin].
|
||||||
|
Future<Uint8List?> pick(PhotoOrigin origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The longest edge the photo is scaled to before it leaves the phone.
|
||||||
|
const mealPhotoMaxEdge = 1024.0;
|
||||||
|
|
||||||
|
/// [MealPhotoSource] on `image_picker`.
|
||||||
|
class ImagePickerPhotoSource implements MealPhotoSource {
|
||||||
|
/// Creates the source; the three seams default to the real plugins.
|
||||||
|
ImagePickerPhotoSource({
|
||||||
|
@visibleForTesting Future<XFile?> Function(ImageSource source)? pickFile,
|
||||||
|
@visibleForTesting Future<bool> Function()? requestCamera,
|
||||||
|
@visibleForTesting Future<void> Function(String path)? discard,
|
||||||
|
}) : _pickFile = pickFile ?? _pickWithPlugin,
|
||||||
|
_requestCamera = requestCamera ?? _requestCameraPermission,
|
||||||
|
_discard = discard ?? discardPickedFile;
|
||||||
|
|
||||||
|
final Future<XFile?> Function(ImageSource source) _pickFile;
|
||||||
|
final Future<bool> Function() _requestCamera;
|
||||||
|
final Future<void> Function(String path) _discard;
|
||||||
|
|
||||||
|
static Future<XFile?> _pickWithPlugin(ImageSource source) =>
|
||||||
|
ImagePicker().pickImage(
|
||||||
|
source: source,
|
||||||
|
maxWidth: mealPhotoMaxEdge,
|
||||||
|
maxHeight: mealPhotoMaxEdge,
|
||||||
|
imageQuality: 85,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// `permission_handler` has no web implementation; the browser asks for
|
||||||
|
/// the camera itself when the picker opens.
|
||||||
|
static Future<bool> _requestCameraPermission() async {
|
||||||
|
if (kIsWeb) return true;
|
||||||
|
return (await Permission.camera.request()).isGranted;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Uint8List?> pick(PhotoOrigin origin) async {
|
||||||
|
// The runtime permission comes first: launching the camera intent without
|
||||||
|
// it fails on Android, and the failure names nothing.
|
||||||
|
if (origin == PhotoOrigin.camera && !await _requestCamera()) return null;
|
||||||
|
final file = await _pickFile(
|
||||||
|
origin == PhotoOrigin.camera ? ImageSource.camera : ImageSource.gallery,
|
||||||
|
);
|
||||||
|
if (file == null) return null;
|
||||||
|
final bytes = await file.readAsBytes();
|
||||||
|
// The plugin leaves the scaled JPEG in the app cache; the bytes are all
|
||||||
|
// that is needed, so the file goes the moment they are read.
|
||||||
|
await _discard(file.path);
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -26,6 +26,7 @@ class IconField extends StatelessWidget {
|
|||||||
this.onSubmitted,
|
this.onSubmitted,
|
||||||
this.autofocus = false,
|
this.autofocus = false,
|
||||||
this.autocorrect = true,
|
this.autocorrect = true,
|
||||||
|
this.fontSize,
|
||||||
super.key,
|
super.key,
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -41,6 +42,9 @@ class IconField extends StatelessWidget {
|
|||||||
/// Whether the keyboard may autocorrect (false for e-mails and secrets).
|
/// Whether the keyboard may autocorrect (false for e-mails and secrets).
|
||||||
final bool autocorrect;
|
final bool autocorrect;
|
||||||
|
|
||||||
|
/// Text size of the typed value; the theme's when null.
|
||||||
|
final double? fontSize;
|
||||||
|
|
||||||
/// Painted caption.
|
/// Painted caption.
|
||||||
final IconData icon;
|
final IconData icon;
|
||||||
|
|
||||||
@ -89,6 +93,7 @@ class IconField extends StatelessWidget {
|
|||||||
inputFormatters: inputFormatters,
|
inputFormatters: inputFormatters,
|
||||||
autofocus: autofocus,
|
autofocus: autofocus,
|
||||||
autocorrect: autocorrect,
|
autocorrect: autocorrect,
|
||||||
|
style: fontSize == null ? null : TextStyle(fontSize: fontSize),
|
||||||
enableSuggestions: autocorrect,
|
enableSuggestions: autocorrect,
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
prefixIcon: ExcludeSemantics(child: Icon(icon, color: iconColor)),
|
prefixIcon: ExcludeSemantics(child: Icon(icon, color: iconColor)),
|
||||||
|
|||||||
@ -7,8 +7,8 @@ import 'package:material_ui/material_ui.dart';
|
|||||||
|
|
||||||
/// A tappable list of [FoodSuggestion]s, each filling the form on tap.
|
/// A tappable list of [FoodSuggestion]s, each filling the form on tap.
|
||||||
///
|
///
|
||||||
/// When [compact] is true, only the top 3 suggestions render as compact
|
/// When [compact] is true, only the top [compactLimit] suggestions render as
|
||||||
/// single-line rows, with a "N more" button opening the full list in a
|
/// compact single-line rows, with a "N more" button opening the full list in a
|
||||||
/// bottom sheet so nothing becomes unreachable.
|
/// bottom sheet so nothing becomes unreachable.
|
||||||
class AutocompleteSuggestionList extends StatelessWidget {
|
class AutocompleteSuggestionList extends StatelessWidget {
|
||||||
/// Creates an [AutocompleteSuggestionList] for [suggestions].
|
/// Creates an [AutocompleteSuggestionList] for [suggestions].
|
||||||
@ -16,6 +16,8 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
|||||||
required this.suggestions,
|
required this.suggestions,
|
||||||
required this.onSelected,
|
required this.onSelected,
|
||||||
this.compact = false,
|
this.compact = false,
|
||||||
|
this.compactLimit = 3,
|
||||||
|
this.reserveHeight = false,
|
||||||
super.key,
|
super.key,
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -29,7 +31,16 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
|||||||
/// of the full unbounded list.
|
/// of the full unbounded list.
|
||||||
final bool compact;
|
final bool compact;
|
||||||
|
|
||||||
static const int _compactLimit = 3;
|
/// How many rows a compact list shows before its "more" button.
|
||||||
|
final int compactLimit;
|
||||||
|
|
||||||
|
/// Whether a compact list always occupies [dueBlockHeight], empty or full,
|
||||||
|
/// so nothing below it shifts as suggestions come and go (due mode).
|
||||||
|
final bool reserveHeight;
|
||||||
|
|
||||||
|
/// Height of the block that holds a compact list of two rows plus the
|
||||||
|
/// "more" button; due mode reserves it so nothing below shifts.
|
||||||
|
static const double dueBlockHeight = 120;
|
||||||
|
|
||||||
Future<void> _showMore(BuildContext context) async {
|
Future<void> _showMore(BuildContext context) async {
|
||||||
await showModalBottomSheet<void>(
|
await showModalBottomSheet<void>(
|
||||||
@ -48,6 +59,15 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final list = _list(context);
|
||||||
|
if (!reserveHeight) return list;
|
||||||
|
return SizedBox(
|
||||||
|
height: dueBlockHeight,
|
||||||
|
child: Align(alignment: Alignment.topLeft, child: list),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _list(BuildContext context) {
|
||||||
if (suggestions.isEmpty) return const SizedBox.shrink();
|
if (suggestions.isEmpty) return const SizedBox.shrink();
|
||||||
if (!compact) {
|
if (!compact) {
|
||||||
return ListView.builder(
|
return ListView.builder(
|
||||||
@ -70,7 +90,7 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
final shown = suggestions.take(_compactLimit).toList();
|
final shown = suggestions.take(compactLimit).toList();
|
||||||
final remaining = suggestions.length - shown.length;
|
final remaining = suggestions.length - shown.length;
|
||||||
return Column(
|
return Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
|||||||
@ -1,93 +0,0 @@
|
|||||||
/// The log form's "Fill all with catering" row: one button, plus Cancel while
|
|
||||||
/// a proposal is armed.
|
|
||||||
///
|
|
||||||
/// Its own row rather than a third control in [LogMealActionsRow]: that row is
|
|
||||||
/// already full on a narrow phone, and "✓ Confirm (N)" must stay legible.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_client.dart';
|
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
|
|
||||||
/// Spoken name of the resting button (never painted).
|
|
||||||
const fillAllLabel = 'Fill all with catering';
|
|
||||||
|
|
||||||
/// Fill-all button; relabels to "✓ Confirm (N)" once a proposal is armed.
|
|
||||||
class FillAllRow extends StatelessWidget {
|
|
||||||
/// Creates the row.
|
|
||||||
const FillAllRow({
|
|
||||||
required this.onFill,
|
|
||||||
required this.onCancel,
|
|
||||||
this.busy = false,
|
|
||||||
this.armedCount = 0,
|
|
||||||
this.canFetchDelivery,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// First tap proposes, second tap confirms.
|
|
||||||
final Future<void> Function() onFill;
|
|
||||||
|
|
||||||
/// Disarms a proposal without writing anything.
|
|
||||||
final VoidCallback onCancel;
|
|
||||||
|
|
||||||
/// Disables both controls while a fetch or the confirm's writes run.
|
|
||||||
final bool busy;
|
|
||||||
|
|
||||||
/// How many dishes the armed proposal would log; 0 when none is armed.
|
|
||||||
final int armedCount;
|
|
||||||
|
|
||||||
/// Whether the platform can fetch at all. Defaults to
|
|
||||||
/// [kuchniaFetchSupported] -- false on web, where the caterer's panel blocks
|
|
||||||
/// browser requests -- so the row is hidden there, like the delivery button.
|
|
||||||
final bool? canFetchDelivery;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
if (!(canFetchDelivery ?? kuchniaFetchSupported)) {
|
|
||||||
return const SizedBox.shrink();
|
|
||||||
}
|
|
||||||
final armed = armedCount > 0;
|
|
||||||
return Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: OutlinedButton(
|
|
||||||
onPressed: busy ? null : onFill,
|
|
||||||
child: _face(context, armed),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (armed) ...[
|
|
||||||
const SizedBox(width: AppSpacing.sm),
|
|
||||||
IconButton(
|
|
||||||
onPressed: busy ? null : onCancel,
|
|
||||||
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resting glyph; spinner while busy; double check + count once armed.
|
|
||||||
Widget _face(BuildContext context, bool armed) {
|
|
||||||
if (busy) {
|
|
||||||
return const SizedBox(
|
|
||||||
width: 18,
|
|
||||||
height: 18,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!armed) {
|
|
||||||
return const Icon(Icons.playlist_add_check, semanticLabel: fillAllLabel);
|
|
||||||
}
|
|
||||||
final success =
|
|
||||||
(Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark)
|
|
||||||
.success;
|
|
||||||
return Row(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
|
||||||
children: [
|
|
||||||
Icon(Icons.done_all, color: success, semanticLabel: 'Confirm'),
|
|
||||||
const SizedBox(width: AppSpacing.xs),
|
|
||||||
Text('$armedCount'),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,95 +0,0 @@
|
|||||||
/// The log form's action row: load today's delivery, then log the meal.
|
|
||||||
///
|
|
||||||
/// Its own file because `log_meal_screen.dart` sits at the repo's 250-line
|
|
||||||
/// ceiling; lifting the whole row rather than just the delivery button keeps
|
|
||||||
/// both controls' layout in one place and returns budget to the screen.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_client.dart';
|
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
|
|
||||||
/// A delivery button beside the log button.
|
|
||||||
///
|
|
||||||
/// The delivery control mirrors the PC lock screen's "🍱 Today's delivery":
|
|
||||||
/// standing in the kitchen, there must be something to tap. It stays visible
|
|
||||||
/// and enabled even when there is nothing to load — the outcome arrives as a
|
|
||||||
/// message rather than as a disabled button, because a disabled control gives
|
|
||||||
/// no way to retry after a late delivery and a hidden one reads as broken.
|
|
||||||
class LogMealActionsRow extends StatelessWidget {
|
|
||||||
/// Creates the action row.
|
|
||||||
const LogMealActionsRow({
|
|
||||||
required this.onLoadDelivery,
|
|
||||||
required this.onLog,
|
|
||||||
this.deliveryBusy = false,
|
|
||||||
this.dishesQueued = 0,
|
|
||||||
this.canFetchDelivery,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Loads today's delivery and prefills the first/next dish.
|
|
||||||
final Future<void> Function() onLoadDelivery;
|
|
||||||
|
|
||||||
/// Writes the current form as a log entry.
|
|
||||||
final VoidCallback onLog;
|
|
||||||
|
|
||||||
/// Whether a delivery fetch is in flight; disables the button meanwhile so
|
|
||||||
/// a second tap cannot start a concurrent login against the caterer.
|
|
||||||
final bool deliveryBusy;
|
|
||||||
|
|
||||||
/// How many delivered dishes are still queued, shown as the PC's
|
|
||||||
/// "(N more to go)" so the user knows the walk is not finished.
|
|
||||||
final int dishesQueued;
|
|
||||||
|
|
||||||
/// Whether the platform can fetch at all. Defaults to
|
|
||||||
/// [kuchniaFetchSupported] — false on web, where the desktop build runs and
|
|
||||||
/// the caterer's panel blocks browser requests, so the control is hidden
|
|
||||||
/// rather than shipped dead.
|
|
||||||
final bool? canFetchDelivery;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final canFetch = canFetchDelivery ?? kuchniaFetchSupported;
|
|
||||||
return Row(
|
|
||||||
children: [
|
|
||||||
// Expanded so the delivery button takes the slack and pushes the log
|
|
||||||
// button right; the queue is a numeral next to the icon, so there is
|
|
||||||
// no wide label to clip. While fetching the icon becomes a spinner.
|
|
||||||
if (canFetch)
|
|
||||||
Expanded(
|
|
||||||
child: OutlinedButton(
|
|
||||||
onPressed: deliveryBusy ? null : onLoadDelivery,
|
|
||||||
child: Row(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
|
||||||
children: [
|
|
||||||
if (deliveryBusy)
|
|
||||||
const SizedBox(
|
|
||||||
width: 18,
|
|
||||||
height: 18,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
)
|
|
||||||
else
|
|
||||||
const Icon(
|
|
||||||
Icons.restaurant,
|
|
||||||
semanticLabel: "Load today's catering delivery",
|
|
||||||
),
|
|
||||||
if (dishesQueued > 0) ...[
|
|
||||||
const SizedBox(width: AppSpacing.xs),
|
|
||||||
Text('$dishesQueued'),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// No Spacer when the delivery button is present: it is a flex child
|
|
||||||
// too and would split the free space with the Expanded above.
|
|
||||||
if (!canFetch) const Spacer(),
|
|
||||||
const SizedBox(width: AppSpacing.sm),
|
|
||||||
FilledButton(
|
|
||||||
onPressed: onLog,
|
|
||||||
child: const Icon(Icons.check_circle, semanticLabel: 'Log meal'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
101
app/lib/widgets/logged_meal_row.dart
Normal file
101
app/lib/widgets/logged_meal_row.dart
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
/// One meal the screen logged for the user: where it came from, what it is,
|
||||||
|
/// and a plain round undo.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// How the entry got logged; picks the leading glyph.
|
||||||
|
enum LoggedOrigin {
|
||||||
|
/// Claude read the text and/or photo (sparkle).
|
||||||
|
claude,
|
||||||
|
|
||||||
|
/// The delivered catering dish logged itself (restaurant).
|
||||||
|
catering,
|
||||||
|
|
||||||
|
/// The check button (check).
|
||||||
|
local,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A logged meal and the way it got logged.
|
||||||
|
@immutable
|
||||||
|
class LoggedMeal {
|
||||||
|
/// Creates the pair.
|
||||||
|
const LoggedMeal(this.entry, this.origin);
|
||||||
|
|
||||||
|
/// The entry that was written.
|
||||||
|
final FoodEntry entry;
|
||||||
|
|
||||||
|
/// How it got logged.
|
||||||
|
final LoggedOrigin origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Name, kcal and macro figures, and an undo button (no countdown).
|
||||||
|
class LoggedMealRow extends StatelessWidget {
|
||||||
|
/// Creates the row.
|
||||||
|
const LoggedMealRow({required this.meal, required this.onUndo, super.key});
|
||||||
|
|
||||||
|
/// The meal shown.
|
||||||
|
final LoggedMeal meal;
|
||||||
|
|
||||||
|
/// Tombstones the entry.
|
||||||
|
final VoidCallback onUndo;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final entry = meal.entry;
|
||||||
|
final (icon, color) = switch (meal.origin) {
|
||||||
|
LoggedOrigin.claude => (Icons.auto_awesome, theme.colorScheme.primary),
|
||||||
|
LoggedOrigin.catering => (
|
||||||
|
Icons.restaurant,
|
||||||
|
theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
LoggedOrigin.local => (
|
||||||
|
Icons.check_circle,
|
||||||
|
(theme.extension<AppStatusColors>() ?? AppStatusColors.dark).success,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
String n(double v) => v.round().toString();
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(top: AppSpacing.sm),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(icon, color: color),
|
||||||
|
const SizedBox(width: AppSpacing.sm),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(entry.desc, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
|
Wrap(
|
||||||
|
spacing: AppSpacing.sm,
|
||||||
|
children: [
|
||||||
|
MacroFigure(
|
||||||
|
kind: MacroKind.kcal,
|
||||||
|
value: n(entry.kcal),
|
||||||
|
size: 16,
|
||||||
|
),
|
||||||
|
MacroFigure(
|
||||||
|
kind: MacroKind.protein,
|
||||||
|
value: n(entry.proteinG),
|
||||||
|
),
|
||||||
|
MacroFigure(kind: MacroKind.carbs, value: n(entry.carbsG)),
|
||||||
|
MacroFigure(kind: MacroKind.fat, value: n(entry.fatG)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
IconButton.filledTonal(
|
||||||
|
constraints: const BoxConstraints.tightFor(width: 48, height: 48),
|
||||||
|
onPressed: onUndo,
|
||||||
|
icon: const Icon(Icons.undo, semanticLabel: 'Undo'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -5,7 +5,9 @@ library;
|
|||||||
|
|
||||||
import 'package:diet_guard_app/models/nutrition.dart';
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
import 'package:diet_guard_app/ui/cues.dart';
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/icon_field.dart';
|
||||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Text controllers for one macro-entry row, owned by the calling screen so
|
/// Text controllers for one macro-entry row, owned by the calling screen so
|
||||||
@ -128,12 +130,14 @@ class MacroInputRow extends StatelessWidget {
|
|||||||
_macroField(MacroKind.eaten, controllers.grams),
|
_macroField(MacroKind.eaten, controllers.grams),
|
||||||
];
|
];
|
||||||
if (compact) {
|
if (compact) {
|
||||||
return Row(
|
// Two rows of three, never six in one: a Row of Expanded fields clips a
|
||||||
|
// four-digit value silently (1250 g, 2400 kcal), and the digits must stay
|
||||||
|
// whole at body size. A field is 1/3 of the width, not 1/6.
|
||||||
|
return Column(
|
||||||
children: [
|
children: [
|
||||||
for (final (i, field) in fields.indexed) ...[
|
_threeAcross(fields.sublist(0, 3)),
|
||||||
if (i > 0) const SizedBox(width: 4),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
Expanded(child: field),
|
_threeAcross(fields.sublist(3)),
|
||||||
],
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -164,6 +168,15 @@ class MacroInputRow extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Widget _threeAcross(List<Widget> three) => Row(
|
||||||
|
children: [
|
||||||
|
for (final (i, field) in three.indexed) ...[
|
||||||
|
if (i > 0) const SizedBox(width: AppSpacing.sm),
|
||||||
|
Expanded(child: field),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
Widget _macroField(MacroKind kind, TextEditingController controller) {
|
Widget _macroField(MacroKind kind, TextEditingController controller) {
|
||||||
return IconField(
|
return IconField(
|
||||||
icon: kind.icon,
|
icon: kind.icon,
|
||||||
@ -172,6 +185,7 @@ class MacroInputRow extends StatelessWidget {
|
|||||||
controller: controller,
|
controller: controller,
|
||||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||||
dense: true,
|
dense: true,
|
||||||
|
fontSize: AppTextSize.body,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
216
app/lib/widgets/meal_action_row.dart
Normal file
216
app/lib/widgets/meal_action_row.dart
Normal file
@ -0,0 +1,216 @@
|
|||||||
|
/// The log form's action row (variant 1A): photo, send to Claude, log here.
|
||||||
|
///
|
||||||
|
/// Three solid icon buttons and no words. The photo button is blue (tap =
|
||||||
|
/// camera, long press = gallery); an attached photo turns it into a tinted
|
||||||
|
/// button with a check badge and a small remove badge, and never shows the
|
||||||
|
/// picture. The gold sparkle sends the text and/or photo to Claude; the green
|
||||||
|
/// check logs what is typed. Both are greyed until there is something to
|
||||||
|
/// send or log.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// What the sparkle button shows.
|
||||||
|
enum ClaudeButtonState {
|
||||||
|
/// Ready (sparkle), or greyed when [MealActionRow.canSend] is false.
|
||||||
|
idle,
|
||||||
|
|
||||||
|
/// A request is in flight (spinner).
|
||||||
|
sending,
|
||||||
|
|
||||||
|
/// The PC is offline; the request waits (hourglass).
|
||||||
|
queued,
|
||||||
|
|
||||||
|
/// Sync is locked, nothing can be sent (lock).
|
||||||
|
locked,
|
||||||
|
|
||||||
|
/// The last send failed (error glyph); a tap retries.
|
||||||
|
error,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The photo button's blue, the same hue as the fat figure.
|
||||||
|
const photoButtonColor = Color(0xFF6C9BD1);
|
||||||
|
|
||||||
|
/// Photo, Claude and log buttons side by side.
|
||||||
|
class MealActionRow extends StatelessWidget {
|
||||||
|
/// Creates the row.
|
||||||
|
const MealActionRow({
|
||||||
|
required this.claude,
|
||||||
|
required this.photoAttached,
|
||||||
|
required this.canSend,
|
||||||
|
required this.canLog,
|
||||||
|
required this.onPhoto,
|
||||||
|
required this.onGallery,
|
||||||
|
required this.onRemovePhoto,
|
||||||
|
required this.onSend,
|
||||||
|
required this.onLog,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// State of the sparkle button.
|
||||||
|
final ClaudeButtonState claude;
|
||||||
|
|
||||||
|
/// Whether a photo is attached.
|
||||||
|
final bool photoAttached;
|
||||||
|
|
||||||
|
/// Whether there is text or a photo to send.
|
||||||
|
final bool canSend;
|
||||||
|
|
||||||
|
/// Whether there is a description to log.
|
||||||
|
final bool canLog;
|
||||||
|
|
||||||
|
/// Tap on the photo button: the camera.
|
||||||
|
final VoidCallback onPhoto;
|
||||||
|
|
||||||
|
/// Long press on the photo button: the gallery.
|
||||||
|
final VoidCallback onGallery;
|
||||||
|
|
||||||
|
/// The remove badge.
|
||||||
|
final VoidCallback onRemovePhoto;
|
||||||
|
|
||||||
|
/// The sparkle button.
|
||||||
|
final VoidCallback onSend;
|
||||||
|
|
||||||
|
/// The check button.
|
||||||
|
final VoidCallback onLog;
|
||||||
|
|
||||||
|
static const double _height = 56;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final status =
|
||||||
|
Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark;
|
||||||
|
final gold = Theme.of(context).colorScheme.primary;
|
||||||
|
final sendable =
|
||||||
|
canSend &&
|
||||||
|
claude != ClaudeButtonState.sending &&
|
||||||
|
claude != ClaudeButtonState.queued;
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
Expanded(child: _photo(status.success)),
|
||||||
|
const SizedBox(width: AppSpacing.sm),
|
||||||
|
Expanded(
|
||||||
|
child: _solid(
|
||||||
|
color: gold,
|
||||||
|
onPressed: sendable ? onSend : null,
|
||||||
|
child: _claudeFace(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: AppSpacing.sm),
|
||||||
|
Expanded(
|
||||||
|
child: _solid(
|
||||||
|
color: status.success,
|
||||||
|
onPressed: canLog ? onLog : null,
|
||||||
|
child: const Icon(Icons.check_circle, semanticLabel: 'Log meal'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _solid({
|
||||||
|
required Color color,
|
||||||
|
required VoidCallback? onPressed,
|
||||||
|
required Widget child,
|
||||||
|
VoidCallback? onLongPress,
|
||||||
|
Color? foreground,
|
||||||
|
}) => FilledButton(
|
||||||
|
onPressed: onPressed,
|
||||||
|
onLongPress: onLongPress,
|
||||||
|
style: FilledButton.styleFrom(
|
||||||
|
backgroundColor: color,
|
||||||
|
foregroundColor: foreground ?? const Color(0xFF211D1B),
|
||||||
|
minimumSize: const Size.fromHeight(_height),
|
||||||
|
),
|
||||||
|
child: child,
|
||||||
|
);
|
||||||
|
|
||||||
|
Widget _claudeFace() => switch (claude) {
|
||||||
|
ClaudeButtonState.sending => const SizedBox(
|
||||||
|
width: 24,
|
||||||
|
height: 24,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 3),
|
||||||
|
),
|
||||||
|
ClaudeButtonState.queued => const Icon(
|
||||||
|
Icons.hourglass_top,
|
||||||
|
semanticLabel: 'Waiting for the PC',
|
||||||
|
),
|
||||||
|
ClaudeButtonState.locked => const Icon(
|
||||||
|
Icons.lock,
|
||||||
|
semanticLabel: 'Sync is locked',
|
||||||
|
),
|
||||||
|
ClaudeButtonState.error => const Icon(
|
||||||
|
Icons.error_outline,
|
||||||
|
semanticLabel: 'Claude failed',
|
||||||
|
),
|
||||||
|
ClaudeButtonState.idle => const Icon(
|
||||||
|
Icons.auto_awesome,
|
||||||
|
semanticLabel: 'Ask Claude',
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
Widget _photo(Color success) {
|
||||||
|
final button = _solid(
|
||||||
|
color: photoAttached
|
||||||
|
? photoButtonColor.withValues(alpha: 0.25)
|
||||||
|
: photoButtonColor,
|
||||||
|
foreground: photoAttached ? photoButtonColor : null,
|
||||||
|
onPressed: onPhoto,
|
||||||
|
onLongPress: onGallery,
|
||||||
|
child: const Icon(Icons.add_a_photo, semanticLabel: 'Photo'),
|
||||||
|
);
|
||||||
|
if (!photoAttached) return button;
|
||||||
|
return Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
|
children: [
|
||||||
|
button,
|
||||||
|
Positioned(
|
||||||
|
top: -6,
|
||||||
|
left: -6,
|
||||||
|
child: _badge(Icons.check, success, null, 'Photo attached'),
|
||||||
|
),
|
||||||
|
Positioned(
|
||||||
|
top: -6,
|
||||||
|
right: -6,
|
||||||
|
child: _badge(
|
||||||
|
Icons.close,
|
||||||
|
photoButtonColor,
|
||||||
|
onRemovePhoto,
|
||||||
|
'Remove photo',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A 24 dp badge inside a 32 dp hit area, so the remove target is usable.
|
||||||
|
Widget _badge(
|
||||||
|
IconData icon,
|
||||||
|
Color color,
|
||||||
|
VoidCallback? onTap,
|
||||||
|
String label,
|
||||||
|
) => GestureDetector(
|
||||||
|
behavior: HitTestBehavior.opaque,
|
||||||
|
onTap: onTap,
|
||||||
|
child: SizedBox(
|
||||||
|
width: 32,
|
||||||
|
height: 32,
|
||||||
|
child: Center(
|
||||||
|
child: DecoratedBox(
|
||||||
|
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: Icon(
|
||||||
|
icon,
|
||||||
|
size: 16,
|
||||||
|
color: const Color(0xFF211D1B),
|
||||||
|
semanticLabel: label,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -454,6 +454,14 @@ packages:
|
|||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
|
flutter_plugin_android_lifecycle:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_plugin_android_lifecycle
|
||||||
|
sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.0.35"
|
||||||
flutter_secure_storage:
|
flutter_secure_storage:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@ -578,6 +586,70 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "4.9.1"
|
version: "4.9.1"
|
||||||
|
image_picker:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: image_picker
|
||||||
|
sha256: e71b1bd9e40124041128d60fc3034c7b1598e1bba4e570bba0c70301c817013a
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.2.4"
|
||||||
|
image_picker_android:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_android
|
||||||
|
sha256: "8a7823d5d3e884f7780829d85d92110d072bdcd9ed48e2be158d2abe91a912d4"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.8.13+25"
|
||||||
|
image_picker_for_web:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_for_web
|
||||||
|
sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.1.1"
|
||||||
|
image_picker_ios:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_ios
|
||||||
|
sha256: f4e5650a81b268af3886bc789216ff6d56bdfa79934f93f1a5a8a303b8f60f77
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.8.13+15"
|
||||||
|
image_picker_linux:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_linux
|
||||||
|
sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.2.2"
|
||||||
|
image_picker_macos:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_macos
|
||||||
|
sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.2.2+1"
|
||||||
|
image_picker_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_platform_interface
|
||||||
|
sha256: "2dee4b4e3be429db71472c9c559c981498070a61af1ba82e0e4986fc5dadc042"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.11.2"
|
||||||
|
image_picker_windows:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_windows
|
||||||
|
sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.2.2"
|
||||||
intl:
|
intl:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -634,14 +706,6 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.0.2"
|
version: "3.0.2"
|
||||||
listen:
|
|
||||||
dependency: transitive
|
|
||||||
description:
|
|
||||||
name: listen
|
|
||||||
sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2"
|
|
||||||
url: "https://pub.dev"
|
|
||||||
source: hosted
|
|
||||||
version: "1.0.1"
|
|
||||||
logging:
|
logging:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -1004,10 +1068,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: test_api
|
name: test_api
|
||||||
sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f"
|
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.7.14"
|
version: "0.7.12"
|
||||||
timezone:
|
timezone:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@ -2,7 +2,7 @@ name: diet_guard_app
|
|||||||
description: "Companion phone app for diet_guard: log meals on the go."
|
description: "Companion phone app for diet_guard: log meals on the go."
|
||||||
publish_to: 'none'
|
publish_to: 'none'
|
||||||
|
|
||||||
version: 1.0.169+1
|
version: 1.0.170+1
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.12.2
|
sdk: ^3.12.2
|
||||||
@ -51,6 +51,8 @@ dependencies:
|
|||||||
health: 13.3.2
|
health: 13.3.2
|
||||||
http: 1.6.0
|
http: 1.6.0
|
||||||
idb_shim: 2.11.3
|
idb_shim: 2.11.3
|
||||||
|
# Camera/gallery photo as transient input to Claude (never stored or synced).
|
||||||
|
image_picker: 1.2.4
|
||||||
material_ui: 1.11.0
|
material_ui: 1.11.0
|
||||||
path: 1.9.1
|
path: 1.9.1
|
||||||
path_provider: 2.1.6
|
path_provider: 2.1.6
|
||||||
|
|||||||
@ -1,97 +0,0 @@
|
|||||||
/// The "Fill all with catering" row: glyph per state, Cancel only when armed.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/widgets/fill_all_row.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
|
|
||||||
import 'label_finders.dart';
|
|
||||||
|
|
||||||
Future<void> _pump(
|
|
||||||
WidgetTester tester, {
|
|
||||||
bool canFetch = true,
|
|
||||||
bool busy = false,
|
|
||||||
int armed = 0,
|
|
||||||
Future<void> Function()? onFill,
|
|
||||||
VoidCallback? onCancel,
|
|
||||||
}) => tester.pumpWidget(
|
|
||||||
MaterialApp(
|
|
||||||
home: Scaffold(
|
|
||||||
body: FillAllRow(
|
|
||||||
onFill: onFill ?? () async {},
|
|
||||||
onCancel: onCancel ?? () {},
|
|
||||||
busy: busy,
|
|
||||||
armedCount: armed,
|
|
||||||
canFetchDelivery: canFetch,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
testWidgets('is hidden where delivery cannot be fetched (web)', (t) async {
|
|
||||||
await _pump(t, canFetch: false, armed: 3);
|
|
||||||
|
|
||||||
expect(find.byType(OutlinedButton), findsNothing);
|
|
||||||
expect(byIconLabel(fillAllLabel), findsNothing);
|
|
||||||
expect(byIconLabel('Cancel'), findsNothing);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('resting: the fill glyph and no Cancel', (t) async {
|
|
||||||
await _pump(t);
|
|
||||||
|
|
||||||
expect(byIconLabel(fillAllLabel), findsOneWidget);
|
|
||||||
expect(find.byIcon(Icons.playlist_add_check), findsOneWidget);
|
|
||||||
expect(byIconLabel('Cancel'), findsNothing);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('armed: double check with the count, and a Cancel button', (
|
|
||||||
t,
|
|
||||||
) async {
|
|
||||||
await _pump(t, armed: 3);
|
|
||||||
|
|
||||||
expect(byIconLabel('Confirm'), findsOneWidget);
|
|
||||||
expect(find.text('3'), findsOneWidget);
|
|
||||||
expect(byIconLabel(fillAllLabel), findsNothing);
|
|
||||||
expect(byIconLabel('Cancel'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('busy: spinner and both controls disabled', (t) async {
|
|
||||||
var fills = 0;
|
|
||||||
var cancels = 0;
|
|
||||||
await _pump(
|
|
||||||
t,
|
|
||||||
busy: true,
|
|
||||||
armed: 3,
|
|
||||||
onFill: () async => fills++,
|
|
||||||
onCancel: () => cancels++,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(find.byType(CircularProgressIndicator), findsOneWidget);
|
|
||||||
expect(byIconLabel('Confirm'), findsNothing);
|
|
||||||
expect(
|
|
||||||
t.widget<OutlinedButton>(find.byType(OutlinedButton)).onPressed,
|
|
||||||
isNull,
|
|
||||||
);
|
|
||||||
expect(t.widget<IconButton>(find.byType(IconButton)).onPressed, isNull);
|
|
||||||
await t.tap(find.byType(OutlinedButton), warnIfMissed: false);
|
|
||||||
await t.tap(find.byType(IconButton), warnIfMissed: false);
|
|
||||||
expect(fills + cancels, 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('taps reach the callbacks when idle', (t) async {
|
|
||||||
var fills = 0;
|
|
||||||
var cancels = 0;
|
|
||||||
await _pump(
|
|
||||||
t,
|
|
||||||
armed: 2,
|
|
||||||
onFill: () async => fills++,
|
|
||||||
onCancel: () => cancels++,
|
|
||||||
);
|
|
||||||
|
|
||||||
await t.tap(byIconLabel('Confirm'));
|
|
||||||
await t.tap(byIconLabel('Cancel'));
|
|
||||||
|
|
||||||
expect([fills, cancels], [1, 1]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -1,10 +1,24 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
import 'package:diet_guard_app/services/log_feedback.dart';
|
import 'package:diet_guard_app/services/log_feedback.dart';
|
||||||
|
|
||||||
/// Mutes the log cue suite-wide: audioplayers has no platform side under
|
/// Suite-wide test defaults.
|
||||||
/// `flutter test`, so a real play would fail any test that logs a meal.
|
///
|
||||||
|
/// * The log cue is muted: audioplayers has no platform side under
|
||||||
|
/// `flutter test`, so a real play would fail any test that logs a meal.
|
||||||
|
/// * The log screen's clock is pinned to 07:00 today, before the first slot,
|
||||||
|
/// so no slot is due and the screen is in normal mode whatever the wall
|
||||||
|
/// clock says. Without the pin every nav and slot test would pass at night
|
||||||
|
/// and fail by day, once due mode hides the app bar. A test that needs due
|
||||||
|
/// mode sets [logMealClock] itself.
|
||||||
|
/// * The status bar call goes nowhere; a test that checks it replaces the hook.
|
||||||
Future<void> testExecutable(FutureOr<void> Function() testMain) async {
|
Future<void> testExecutable(FutureOr<void> Function() testMain) async {
|
||||||
LogFeedback.playConfirmCue = () async {};
|
LogFeedback.playConfirmCue = () async {};
|
||||||
|
logMealClock = () {
|
||||||
|
final now = DateTime.now();
|
||||||
|
return DateTime(now.year, now.month, now.day, 7);
|
||||||
|
};
|
||||||
|
setStatusBarHidden = ({required hidden}) async {};
|
||||||
await testMain();
|
await testMain();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,6 @@
|
|||||||
// Guard: a catering fetch / fill reports with a glyph and a dish count; its
|
// Guard: a catering fetch reports with a glyph and a dish count; its
|
||||||
// sentence is only the spoken label.
|
// sentence is only the spoken label.
|
||||||
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_fill_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
|
||||||
import 'package:diet_guard_app/ui/cues.dart';
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
@ -11,26 +9,6 @@ import 'label_finders.dart';
|
|||||||
import 'no_words_support.dart';
|
import 'no_words_support.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
group('fillCue', () {
|
|
||||||
test('nothing to fill paints a warning and 0', () {
|
|
||||||
final cue = fillCue((
|
|
||||||
message: 'No catering delivery today.',
|
|
||||||
written: const <SlottedDish>[],
|
|
||||||
), armed: 0);
|
|
||||||
expect(cue.kind, CueKind.warn);
|
|
||||||
expect(cue.count, 0);
|
|
||||||
expect(cue.label, 'No catering delivery today.');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a proposal paints its armed count', () {
|
|
||||||
final cue = fillCue((
|
|
||||||
message: 'Will log 3',
|
|
||||||
written: const <SlottedDish>[],
|
|
||||||
), armed: 3);
|
|
||||||
expect((cue.kind, cue.count), (CueKind.info, 3));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('a counted cue paints only the glyph and the number', (
|
testWidgets('a counted cue paints only the glyph and the number', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
|
|||||||
@ -9,6 +9,7 @@ import 'dart:io';
|
|||||||
import 'package:diet_guard_app/models/nutrition.dart';
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
import 'package:diet_guard_app/screens/calendar_screen.dart';
|
import 'package:diet_guard_app/screens/calendar_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/settings_screen.dart';
|
import 'package:diet_guard_app/screens/settings_screen.dart';
|
||||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||||
@ -24,6 +25,7 @@ import 'package:shared_preferences/shared_preferences.dart';
|
|||||||
import 'fake_secure_storage.dart';
|
import 'fake_secure_storage.dart';
|
||||||
import 'label_finders.dart';
|
import 'label_finders.dart';
|
||||||
import 'no_words_support.dart';
|
import 'no_words_support.dart';
|
||||||
|
import 'screens/log_meal_test_support.dart' show pinLogMealClock;
|
||||||
|
|
||||||
/// The one meal logged in setUp: user content, allowed.
|
/// The one meal logged in setUp: user content, allowed.
|
||||||
const _food = 'porridge';
|
const _food = 'porridge';
|
||||||
@ -88,16 +90,41 @@ void main() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
testWidgets('a rejected log paints a cue, not a sentence', (tester) async {
|
testWidgets('a future date with no slot paints a cue, not a sentence', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
await tester.runAsync(() async {
|
await tester.runAsync(() async {
|
||||||
await show(tester, const LogMealScreen());
|
await show(tester, const LogMealScreen());
|
||||||
|
final state = tester.state<State<LogMealScreen>>(
|
||||||
|
find.byType(LogMealScreen),
|
||||||
|
);
|
||||||
|
final tomorrow = DateTime.now().add(const Duration(days: 1));
|
||||||
|
await (state as LogMealFutureMixin<LogMealScreen>).selectLogDate(
|
||||||
|
tomorrow,
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.enterText(find.byType(TextField).first, _food);
|
||||||
|
await tester.pump();
|
||||||
final log = controlByLabel('Log meal');
|
final log = controlByLabel('Log meal');
|
||||||
await tester.ensureVisible(log);
|
await tester.ensureVisible(log);
|
||||||
await tester.tap(log);
|
await tester.tap(log);
|
||||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||||
await tester.pump(const Duration(seconds: 1));
|
await tester.pump(const Duration(seconds: 1));
|
||||||
expect(cueLabelled('Type what you ate first.'), findsOneWidget);
|
expect(cueLabelled('Pick a slot for that date first.'), findsOneWidget);
|
||||||
expectNoWords(tester, minStrings: 3, where: 'rejected log');
|
expectNoWords(tester, content: {_food}, minStrings: 3, where: 'cue');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('due mode and a logged row paint no words', (tester) async {
|
||||||
|
pinLogMealClock(13);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await show(tester, const LogMealScreen());
|
||||||
|
await tester.enterText(find.byType(TextField).first, _food);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(controlByLabel('Log meal'));
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||||
|
await tester.pump(const Duration(seconds: 1));
|
||||||
|
expectNoWords(tester, content: {_food}, minStrings: 5, where: 'due');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
145
app/test/repo_invariants_photo_test.dart
Normal file
145
app/test/repo_invariants_photo_test.dart
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
/// A meal photo is transient input to Claude, never data.
|
||||||
|
///
|
||||||
|
/// Photos came back on 2026-11-17 as input to the Claude relay only (the
|
||||||
|
/// earlier removal still stands for blob stores and the `/blobs/` route). A
|
||||||
|
/// device-local attachment would break the one-source-of-truth rule, so these
|
||||||
|
/// assertions are structural: a new field or file cannot slip an image into an
|
||||||
|
/// entry, a store or the sync wire unnoticed.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/models/meal_component.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
|
Directory get _appDir {
|
||||||
|
var dir = Directory.current;
|
||||||
|
while (!File('${dir.path}/pubspec.yaml').existsSync()) {
|
||||||
|
final parent = dir.parent;
|
||||||
|
if (parent.path == dir.path) fail('could not locate app/');
|
||||||
|
dir = parent;
|
||||||
|
}
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<File> _dartFilesIn(String relative) =>
|
||||||
|
Directory('${_appDir.path}/$relative')
|
||||||
|
.listSync(recursive: true)
|
||||||
|
.whereType<File>()
|
||||||
|
.where((f) => f.path.endsWith('.dart'))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('a meal photo is transient input to Claude, never data', () {
|
||||||
|
const pickerHome = 'services/meal_photo_source.dart';
|
||||||
|
const photoFiles = {
|
||||||
|
'services/meal_photo_source.dart',
|
||||||
|
'services/meal_photo_cleanup.dart',
|
||||||
|
'services/meal_photo_cleanup_io.dart',
|
||||||
|
'services/meal_photo_cleanup_web.dart',
|
||||||
|
'services/claude_relay_client.dart',
|
||||||
|
'services/claude_relay_fake.dart',
|
||||||
|
};
|
||||||
|
String relative(File f) => f.path.split('/app/lib/').last;
|
||||||
|
|
||||||
|
test('image_picker is imported by the photo source alone', () {
|
||||||
|
final offenders = [
|
||||||
|
for (final file in _dartFilesIn('lib'))
|
||||||
|
if (relative(file) != pickerHome &&
|
||||||
|
file.readAsStringSync().contains('package:image_picker/'))
|
||||||
|
relative(file),
|
||||||
|
];
|
||||||
|
expect(offenders, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('image bytes stay out of entries, storage and sync', () {
|
||||||
|
final banned = RegExp(
|
||||||
|
r'Uint8List|photo|jpeg|jpg|base64',
|
||||||
|
caseSensitive: false,
|
||||||
|
);
|
||||||
|
final offenders = [
|
||||||
|
for (final file in _dartFilesIn('lib'))
|
||||||
|
if (!photoFiles.contains(relative(file)) &&
|
||||||
|
(relative(file).startsWith('models/') ||
|
||||||
|
relative(file).contains('sync_') ||
|
||||||
|
relative(file).contains('document_store') ||
|
||||||
|
relative(file).contains('log_storage') ||
|
||||||
|
relative(file).contains('log_entry') ||
|
||||||
|
relative(file).contains('foodbank')) &&
|
||||||
|
banned.hasMatch(file.readAsStringSync()))
|
||||||
|
relative(file),
|
||||||
|
];
|
||||||
|
expect(
|
||||||
|
offenders,
|
||||||
|
isEmpty,
|
||||||
|
reason:
|
||||||
|
'A photo (or its bytes) reached a model, a store or the sync '
|
||||||
|
'wire. Photos are transient input to the Claude relay only.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a FoodEntry syncs a fixed set of keys, none of them an image', () {
|
||||||
|
const entry = FoodEntry(
|
||||||
|
id: 'a',
|
||||||
|
time: '2026-11-17T08:00:00',
|
||||||
|
desc: 'x',
|
||||||
|
grams: 1,
|
||||||
|
kcal: 1,
|
||||||
|
proteinG: 1,
|
||||||
|
carbsG: 1,
|
||||||
|
fatG: 1,
|
||||||
|
source: 'claude',
|
||||||
|
slotMinute: 435,
|
||||||
|
components: [
|
||||||
|
MealComponent(
|
||||||
|
name: 'c',
|
||||||
|
kcal: 1,
|
||||||
|
proteinG: 1,
|
||||||
|
carbsG: 1,
|
||||||
|
fatG: 1,
|
||||||
|
grams: 1,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
deleted: true,
|
||||||
|
);
|
||||||
|
expect(entry.toSyncJson().keys.toSet(), {
|
||||||
|
'id',
|
||||||
|
'time',
|
||||||
|
'desc',
|
||||||
|
'grams',
|
||||||
|
'kcal',
|
||||||
|
'protein_g',
|
||||||
|
'carbs_g',
|
||||||
|
'fat_g',
|
||||||
|
'source',
|
||||||
|
'slot',
|
||||||
|
'slot_min',
|
||||||
|
'components',
|
||||||
|
'deleted',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the photo is only ever picked into memory', () {
|
||||||
|
final source = File('${_appDir.path}/lib/$pickerHome').readAsStringSync();
|
||||||
|
expect(source.contains('readAsBytes'), isTrue);
|
||||||
|
for (final banned in [
|
||||||
|
'path_provider',
|
||||||
|
'writeAsBytes',
|
||||||
|
'getApplication',
|
||||||
|
]) {
|
||||||
|
expect(source.contains(banned), isFalse, reason: banned);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the camera permission is declared for the picker', () {
|
||||||
|
final manifest = File(
|
||||||
|
'${_appDir.path}/android/app/src/main/AndroidManifest.xml',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
manifest.readAsStringSync().contains('android.permission.CAMERA'),
|
||||||
|
isTrue,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -44,7 +44,8 @@ void main() {
|
|||||||
expect(
|
expect(
|
||||||
Directory('${_appDir.path}/linux').existsSync(),
|
Directory('${_appDir.path}/linux').existsSync(),
|
||||||
isFalse,
|
isFalse,
|
||||||
reason: 'A Linux embedder target was re-added. The desktop app is the '
|
reason:
|
||||||
|
'A Linux embedder target was re-added. The desktop app is the '
|
||||||
'web build served by bin/diet_guard_desktop.dart; see CLAUDE.md.',
|
'web build served by bin/diet_guard_desktop.dart; see CLAUDE.md.',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@ -68,7 +69,8 @@ void main() {
|
|||||||
expect(
|
expect(
|
||||||
offenders,
|
offenders,
|
||||||
isEmpty,
|
isEmpty,
|
||||||
reason: 'These files import dart:io outside the conditional-export '
|
reason:
|
||||||
|
'These files import dart:io outside the conditional-export '
|
||||||
'seam, which compiles for web and throws at runtime (blank white '
|
'seam, which compiles for web and throws at runtime (blank white '
|
||||||
'window). Move the platform edge into a *_io.dart / *_web.dart '
|
'window). Move the platform edge into a *_io.dart / *_web.dart '
|
||||||
'pair, and branch on kIsWeb before any Platform.is… check.',
|
'pair, and branch on kIsWeb before any Platform.is… check.',
|
||||||
@ -93,36 +95,11 @@ void main() {
|
|||||||
expect(
|
expect(
|
||||||
offenders,
|
offenders,
|
||||||
isEmpty,
|
isEmpty,
|
||||||
reason: 'A removed feature came back. See the "Do NOT" section of '
|
reason:
|
||||||
|
'A removed feature came back. See the "Do NOT" section of '
|
||||||
'CLAUDE.md before re-adding any of these.',
|
'CLAUDE.md before re-adding any of these.',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Photos took image_picker, the blob stores, the wrapper's /blobs/ route
|
|
||||||
// and the CAMERA permission with them. Re-adding photos means re-adding
|
|
||||||
// all of that *plus* syncing image blobs, since a device-local attachment
|
|
||||||
// would violate the one-source-of-truth rule.
|
|
||||||
test('no image_picker dependency', () {
|
|
||||||
final pubspec = File('${_appDir.path}/pubspec.yaml').readAsStringSync();
|
|
||||||
expect(
|
|
||||||
pubspec.contains('image_picker'),
|
|
||||||
isFalse,
|
|
||||||
reason: 'Meal photos were removed deliberately. A device-local image '
|
|
||||||
'attachment also breaks the shared-source-of-truth rule.',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('no CAMERA permission in the Android manifest', () {
|
|
||||||
final manifest = File(
|
|
||||||
'${_appDir.path}/android/app/src/main/AndroidManifest.xml',
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
manifest.readAsStringSync().contains('android.permission.CAMERA'),
|
|
||||||
isFalse,
|
|
||||||
reason: 'The CAMERA permission came back with no photo feature to '
|
|
||||||
'justify it.',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
group('pickers paint no words', () {
|
group('pickers paint no words', () {
|
||||||
@ -138,7 +115,8 @@ void main() {
|
|||||||
expect(
|
expect(
|
||||||
offenders,
|
offenders,
|
||||||
isEmpty,
|
isEmpty,
|
||||||
reason: 'A framework picker came back. Use pickDate, pickDateRange '
|
reason:
|
||||||
|
'A framework picker came back. Use pickDate, pickDateRange '
|
||||||
'or pickTime from widgets/pickers/pickers.dart.',
|
'or pickTime from widgets/pickers/pickers.dart.',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@ -159,7 +137,8 @@ void main() {
|
|||||||
expect(
|
expect(
|
||||||
source.contains(call),
|
source.contains(call),
|
||||||
isTrue,
|
isTrue,
|
||||||
reason: '$call is missing from main(). The feature will silently do '
|
reason:
|
||||||
|
'$call is missing from main(). The feature will silently do '
|
||||||
'nothing on a real device while every test still passes.',
|
'nothing on a real device while every test still passes.',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -177,7 +156,8 @@ void main() {
|
|||||||
expect(
|
expect(
|
||||||
source.contains('desktopWrapperPort = 8732'),
|
source.contains('desktopWrapperPort = 8732'),
|
||||||
isTrue,
|
isTrue,
|
||||||
reason: 'The wrapper port changed. IndexedDB is keyed by origin, so a '
|
reason:
|
||||||
|
'The wrapper port changed. IndexedDB is keyed by origin, so a '
|
||||||
'new port looks like a different app with no history at all. '
|
'new port looks like a different app with no history at all. '
|
||||||
'8730 is ~/src/todo and 8731 is ~/src/habit_stack; do not collide.',
|
'8730 is ~/src/todo and 8731 is ~/src/habit_stack; do not collide.',
|
||||||
);
|
);
|
||||||
@ -190,7 +170,8 @@ void main() {
|
|||||||
expect(
|
expect(
|
||||||
source.contains("'diet-guard-desktop', 'profile'"),
|
source.contains("'diet-guard-desktop', 'profile'"),
|
||||||
isTrue,
|
isTrue,
|
||||||
reason: 'The Chrome --user-data-dir moved. IndexedDB lives in that '
|
reason:
|
||||||
|
'The Chrome --user-data-dir moved. IndexedDB lives in that '
|
||||||
'profile, so relocating it hides the entire local food log.',
|
'profile, so relocating it hides the entire local food log.',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -76,6 +76,7 @@ void main() {
|
|||||||
) async {
|
) async {
|
||||||
await _pump(tester, const LogMealScreen());
|
await _pump(tester, const LogMealScreen());
|
||||||
await tester.enterText(find.byType(TextField).first, 'Oats');
|
await tester.enterText(find.byType(TextField).first, 'Oats');
|
||||||
|
await tester.pump(); // the log button greys until text is typed
|
||||||
await tester.runAsync(() async {
|
await tester.runAsync(() async {
|
||||||
await tester.tap(controlByLabel('Log meal'));
|
await tester.tap(controlByLabel('Log meal'));
|
||||||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||||
|
|||||||
140
app/test/screens/log_meal_autolog_test.dart
Normal file
140
app/test/screens/log_meal_autolog_test.dart
Normal file
@ -0,0 +1,140 @@
|
|||||||
|
/// Catering auto-log on the log screen: opening it with slots due logs the
|
||||||
|
/// delivered dishes without a tap (kuhy's override of 2026-11-17).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_fill.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
import '../label_finders.dart';
|
||||||
|
import 'log_meal_test_support.dart';
|
||||||
|
|
||||||
|
KuchniaDish _dish(int n) => KuchniaDish(
|
||||||
|
name: 'Danie $n',
|
||||||
|
kcal: 100.0 * n,
|
||||||
|
proteinG: 10,
|
||||||
|
carbsG: 20,
|
||||||
|
fatG: 5,
|
||||||
|
grams: 300,
|
||||||
|
priority: n,
|
||||||
|
slotLabel: '',
|
||||||
|
dishId: '${2000 + n}',
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
late Future<void> Function() restore;
|
||||||
|
late int fetches;
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
restore = await isolateLogScreenState();
|
||||||
|
fetches = 0;
|
||||||
|
pinLogMealClock(13); // 08:00 and 12:00 due
|
||||||
|
KuchniaAutoLog.instance = KuchniaAutoLog(
|
||||||
|
fetch: (day) async {
|
||||||
|
fetches++;
|
||||||
|
return KuchniaRefresh(dishes: [for (var i = 1; i <= 4; i++) _dish(i)]);
|
||||||
|
},
|
||||||
|
now: () => logMealClock(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
tearDown(() => restore());
|
||||||
|
|
||||||
|
Future<void> open(WidgetTester tester) async {
|
||||||
|
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||||
|
await settle(tester);
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('opening in due mode logs the due dishes with no tap', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
final entries = await LogStorageService.instance.todayEntries();
|
||||||
|
expect(entries.map((e) => e.desc), ['Danie 1', 'Danie 2']);
|
||||||
|
expect(entries.map((e) => e.slotMinute), [480, 720]);
|
||||||
|
expect(entries.every((e) => e.source == kuchniaSource), isTrue);
|
||||||
|
// A restaurant glyph and an undo per row; nothing is due any more.
|
||||||
|
expect(find.byIcon(Icons.restaurant), findsNWidgets(2));
|
||||||
|
expect(byIconLabel('Undo'), findsNWidgets(2));
|
||||||
|
expect(find.byType(AppBar), findsOneWidget);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('undo removes one dish and a reopen does not log it again', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
await tester.tap(byIconLabel('Undo').first);
|
||||||
|
await settle(tester);
|
||||||
|
expect(find.byIcon(Icons.restaurant), findsOneWidget);
|
||||||
|
var live = await LogStorageService.instance.todayEntries();
|
||||||
|
expect(live.map((e) => e.desc), ['Danie 2']);
|
||||||
|
|
||||||
|
// Reopen: 08:00 is due again, but its tombstoned id blocks the dish.
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
await open(tester);
|
||||||
|
live = await LogStorageService.instance.todayEntries();
|
||||||
|
expect(live.map((e) => e.desc), ['Danie 2']);
|
||||||
|
expect(find.byIcon(Icons.restaurant), findsNothing);
|
||||||
|
expect(find.byType(AppBar), findsNothing, reason: 'still due');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('opening twice fetches once and leaves one entry per dish', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
await open(tester);
|
||||||
|
final entries = await LogStorageService.instance.todayEntries();
|
||||||
|
expect(entries, hasLength(2));
|
||||||
|
expect(fetches, 1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('normal mode logs nothing and never fetches', (tester) async {
|
||||||
|
pinLogMealClock(7);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
expect(await LogStorageService.instance.todayEntries(), isEmpty);
|
||||||
|
expect(fetches, 0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('resuming into a due slot logs the dishes with no tap', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
// Opened before the first slot: normal mode, nothing logged.
|
||||||
|
logMealClock = () {
|
||||||
|
final t = DateTime.now();
|
||||||
|
return DateTime(t.year, t.month, t.day, 7);
|
||||||
|
};
|
||||||
|
await open(tester);
|
||||||
|
expect(await LogStorageService.instance.todayEntries(), isEmpty);
|
||||||
|
expect(fetches, 0);
|
||||||
|
|
||||||
|
// Time passes (08:00 and 12:00 elapse); the app comes back to front.
|
||||||
|
pinLogMealClock(13);
|
||||||
|
final state = tester.state<State<LogMealScreen>>(
|
||||||
|
find.byType(LogMealScreen),
|
||||||
|
);
|
||||||
|
(state as WidgetsBindingObserver).didChangeAppLifecycleState(
|
||||||
|
AppLifecycleState.resumed,
|
||||||
|
);
|
||||||
|
await settle(tester);
|
||||||
|
|
||||||
|
final entries = await LogStorageService.instance.todayEntries();
|
||||||
|
expect(entries.map((e) => e.desc), ['Danie 1', 'Danie 2']);
|
||||||
|
expect(find.byIcon(Icons.restaurant), findsNWidgets(2));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
202
app/test/screens/log_meal_claude_test.dart
Normal file
202
app/test/screens/log_meal_claude_test.dart
Normal file
@ -0,0 +1,202 @@
|
|||||||
|
/// The sparkle button and the photo button on the log screen.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_fake.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_photo_source.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
import '../label_finders.dart';
|
||||||
|
import 'log_meal_test_support.dart';
|
||||||
|
|
||||||
|
class _Photos implements MealPhotoSource {
|
||||||
|
final List<PhotoOrigin> asked = [];
|
||||||
|
final Uint8List bytes = Uint8List.fromList([1, 2, 3]);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Uint8List?> pick(PhotoOrigin origin) async {
|
||||||
|
asked.add(origin);
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
FoodEntry _claudeEntry(String id) => FoodEntry(
|
||||||
|
id: id,
|
||||||
|
time: DateTime.now().toIso8601String().substring(0, 19),
|
||||||
|
desc: 'kurczak z ryzem',
|
||||||
|
grams: 300,
|
||||||
|
kcal: 540,
|
||||||
|
proteinG: 42,
|
||||||
|
carbsG: 61,
|
||||||
|
fatG: 9,
|
||||||
|
source: 'claude',
|
||||||
|
slotMinute: 480,
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
late Future<void> Function() restore;
|
||||||
|
late FakeClaudeRelayClient relay;
|
||||||
|
late _Photos photos;
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
restore = await isolateLogScreenState();
|
||||||
|
relay = FakeClaudeRelayClient();
|
||||||
|
photos = _Photos();
|
||||||
|
});
|
||||||
|
tearDown(() => restore());
|
||||||
|
|
||||||
|
Future<void> open(WidgetTester tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: LogMealScreen(relay: relay, photos: photos),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await settle(tester);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool sparkleEnabled(WidgetTester tester) =>
|
||||||
|
tester
|
||||||
|
.widget<FilledButton>(
|
||||||
|
find.ancestor(
|
||||||
|
of: find.byWidgetPredicate(
|
||||||
|
(w) =>
|
||||||
|
w is Icon &&
|
||||||
|
(w.semanticLabel == 'Ask Claude' ||
|
||||||
|
w.icon == Icons.hourglass_top ||
|
||||||
|
w.icon == Icons.lock ||
|
||||||
|
w.icon == Icons.error_outline),
|
||||||
|
),
|
||||||
|
matching: find.byType(FilledButton),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.onPressed !=
|
||||||
|
null;
|
||||||
|
|
||||||
|
testWidgets('the sparkle is greyed until there is text or a photo', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
pinLogMealClock(13);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
expect(sparkleEnabled(tester), isFalse);
|
||||||
|
await tester.enterText(find.byType(TextField).at(0), 'kurczak');
|
||||||
|
await settle(tester);
|
||||||
|
expect(sparkleEnabled(tester), isTrue);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a photo alone enables the sparkle; tap camera, hold gallery', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
pinLogMealClock(13);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
// Inside runAsync the recognizer's timer is real, so wait in real time.
|
||||||
|
final press = await tester.startGesture(
|
||||||
|
tester.getCenter(controlByLabel('Photo')),
|
||||||
|
);
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 700));
|
||||||
|
await press.up();
|
||||||
|
await settle(tester);
|
||||||
|
expect(photos.asked, [PhotoOrigin.gallery]);
|
||||||
|
await tester.tap(byIconLabel('Remove photo'));
|
||||||
|
await settle(tester);
|
||||||
|
await tester.tap(controlByLabel('Photo'));
|
||||||
|
await settle(tester);
|
||||||
|
expect(photos.asked, [PhotoOrigin.gallery, PhotoOrigin.camera]);
|
||||||
|
expect(sparkleEnabled(tester), isTrue);
|
||||||
|
expect(byIconLabel('Photo attached'), findsOneWidget);
|
||||||
|
expect(find.byType(Image), findsNothing);
|
||||||
|
|
||||||
|
await tester.tap(byIconLabel('Remove photo'));
|
||||||
|
await settle(tester);
|
||||||
|
expect(sparkleEnabled(tester), isFalse);
|
||||||
|
|
||||||
|
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a send carries the text, photo and the oldest due slot', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
pinLogMealClock(13); // 08:00 and 12:00 are due
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
await tester.tap(controlByLabel('Photo'));
|
||||||
|
await settle(tester);
|
||||||
|
await tester.enterText(find.byType(TextField).at(0), ' kurczak ');
|
||||||
|
await settle(tester);
|
||||||
|
await tester.tap(controlByLabel('Ask Claude'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
final sent = relay.sent.single;
|
||||||
|
expect(sent.text, 'kurczak');
|
||||||
|
expect(sent.photoJpeg, photos.bytes);
|
||||||
|
expect(sent.slotMinute, 480);
|
||||||
|
expect(find.byType(CircularProgressIndicator), findsOneWidget);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('queued, then logged: the row shows and undo tombstones it', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
pinLogMealClock(13);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
await tester.enterText(find.byType(TextField).at(0), 'kurczak');
|
||||||
|
await settle(tester);
|
||||||
|
await tester.tap(controlByLabel('Ask Claude'));
|
||||||
|
await tester.pump();
|
||||||
|
relay.emit(const ClaudeRelayQueued());
|
||||||
|
await settle(tester);
|
||||||
|
expect(byIconLabel('Waiting for the PC'), findsOneWidget);
|
||||||
|
|
||||||
|
final id = relay.sent.single.requestId;
|
||||||
|
relay.emit(ClaudeRelayLogged(_claudeEntry(id)));
|
||||||
|
await settle(tester);
|
||||||
|
|
||||||
|
expect(find.text('kurczak z ryzem'), findsOneWidget);
|
||||||
|
expect(find.byIcon(Icons.auto_awesome), findsWidgets);
|
||||||
|
expect((await LogStorageService.instance.todayEntries()).single.id, id);
|
||||||
|
// The form reset, and the photo is gone with the send.
|
||||||
|
expect(
|
||||||
|
tester.widget<TextField>(find.byType(TextField).at(0)).controller!.text,
|
||||||
|
'',
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(byIconLabel('Undo'));
|
||||||
|
await settle(tester);
|
||||||
|
expect(await LogStorageService.instance.todayEntries(), isEmpty);
|
||||||
|
expect((await LogStorageService.instance.findEntry(id))!.deleted, isTrue);
|
||||||
|
expect(find.text('kurczak z ryzem'), findsNothing);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
for (final (event, glyph) in [
|
||||||
|
(const ClaudeRelayLocked(), Icons.lock),
|
||||||
|
(const ClaudeRelayFailed('boom'), Icons.error_outline),
|
||||||
|
]) {
|
||||||
|
testWidgets('$event paints its glyph and keeps the text', (tester) async {
|
||||||
|
pinLogMealClock(13);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
await tester.enterText(find.byType(TextField).at(0), 'kurczak');
|
||||||
|
await settle(tester);
|
||||||
|
await tester.tap(controlByLabel('Ask Claude'));
|
||||||
|
await tester.pump();
|
||||||
|
relay.emit(event);
|
||||||
|
await settle(tester);
|
||||||
|
expect(find.byIcon(glyph), findsOneWidget);
|
||||||
|
expect(find.text('kurczak'), findsOneWidget);
|
||||||
|
expect(sparkleEnabled(tester), isTrue); // a tap retries
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
146
app/test/screens/log_meal_due_mode_test.dart
Normal file
146
app/test/screens/log_meal_due_mode_test.dart
Normal file
@ -0,0 +1,146 @@
|
|||||||
|
/// Due mode versus normal mode on the log screen: what shows, which slot a
|
||||||
|
/// log lands in, and when the status bar is hidden.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/sync_health_banner.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
import '../label_finders.dart';
|
||||||
|
import 'log_meal_test_support.dart';
|
||||||
|
|
||||||
|
final _plain = nutritionForPortion(
|
||||||
|
kcal: 100,
|
||||||
|
proteinG: 1,
|
||||||
|
carbsG: 1,
|
||||||
|
fatG: 1,
|
||||||
|
perGrams: 0,
|
||||||
|
ateGrams: 100,
|
||||||
|
source: 'manual',
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
late Future<void> Function() restore;
|
||||||
|
late List<bool> statusBar;
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
restore = await isolateLogScreenState();
|
||||||
|
statusBar = [];
|
||||||
|
setStatusBarHidden = ({required hidden}) async => statusBar.add(hidden);
|
||||||
|
});
|
||||||
|
tearDown(() => restore());
|
||||||
|
|
||||||
|
Future<void> open(WidgetTester tester) async {
|
||||||
|
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||||
|
await settle(tester);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> logTyped(WidgetTester tester, String text) async {
|
||||||
|
await tester.enterText(find.byType(TextField).at(0), text);
|
||||||
|
await settle(tester);
|
||||||
|
await tester.tap(controlByLabel('Log meal'));
|
||||||
|
await settle(tester);
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('due mode strips the bar, banner, date row and chips', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
pinLogMealClock(13);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
expect(find.byType(AppBar), findsNothing);
|
||||||
|
expect(find.byType(SyncHealthBanner), findsNothing);
|
||||||
|
expect(find.byIcon(Icons.date_range), findsNothing);
|
||||||
|
expect(find.byType(ChoiceChip), findsNothing);
|
||||||
|
expect(find.byIcon(Icons.playlist_add_check), findsNothing);
|
||||||
|
// What stays: field, six macro fields, the three buttons.
|
||||||
|
expect(find.byType(TextField), findsNWidgets(7));
|
||||||
|
expect(byIconLabel('Photo'), findsOneWidget);
|
||||||
|
expect(byIconLabel('Ask Claude'), findsOneWidget);
|
||||||
|
expect(byIconLabel('Log meal'), findsOneWidget);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('normal mode keeps the bar and date row, drops chips and fill', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
expect(find.byType(AppBar), findsOneWidget);
|
||||||
|
expect(find.byIcon(Icons.date_range), findsOneWidget);
|
||||||
|
expect(find.byType(ChoiceChip), findsNothing);
|
||||||
|
expect(find.byIcon(Icons.playlist_add_check), findsNothing);
|
||||||
|
expect(byIconLabel('Photo'), findsOneWidget);
|
||||||
|
expect(byIconLabel('Ask Claude'), findsOneWidget);
|
||||||
|
expect(statusBar, isEmpty, reason: 'normal mode never touches the bar');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('both buttons target the oldest due slot, one after another', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
pinLogMealClock(13); // 08:00 and 12:00 due
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
await logTyped(tester, 'first');
|
||||||
|
await logTyped(tester, 'second');
|
||||||
|
final slots = (await LogStorageService.instance.todayEntries()).map(
|
||||||
|
(e) => e.slotMinute,
|
||||||
|
);
|
||||||
|
expect(slots, [480, 720]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('with nothing due the nearest slot is used', (tester) async {
|
||||||
|
pinLogMealClock(18); // 16:00 is the latest elapsed slot
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
for (final minute in [480, 720, 960]) {
|
||||||
|
await LogStorageService.instance.logMeal(
|
||||||
|
'seed$minute',
|
||||||
|
_plain,
|
||||||
|
slotMinute: minute,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await open(tester);
|
||||||
|
expect(find.byType(AppBar), findsOneWidget);
|
||||||
|
await logTyped(tester, 'late snack');
|
||||||
|
final last = (await LogStorageService.instance.todayEntries()).last;
|
||||||
|
expect(last.slotMinute, 960);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the status bar hides in due mode and returns afterwards', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
pinLogMealClock(13);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
expect(statusBar, [true]);
|
||||||
|
await logTyped(tester, 'first');
|
||||||
|
expect(statusBar, [true], reason: '12:00 is still due');
|
||||||
|
await logTyped(tester, 'second');
|
||||||
|
expect(statusBar, [true, false]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('leaving the screen in due mode restores the status bar', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
pinLogMealClock(13);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
expect(statusBar, [true]);
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
expect(statusBar, [true, false]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the suite default clock is before the first slot', () {
|
||||||
|
final now = logMealClock();
|
||||||
|
expect(now.hour, 7);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -1,245 +0,0 @@
|
|||||||
/// "Fill all with catering" as the log form drives it.
|
|
||||||
///
|
|
||||||
/// `kuchnia_fill_flow_test.dart` proves the flow writes nothing until the
|
|
||||||
/// second tap. This covers what the *screen* must do around it: publish once
|
|
||||||
/// for the whole batch (and never after the first tap), drop the filled
|
|
||||||
/// dishes from the delivery queue, and not leave a just-logged dish
|
|
||||||
/// prefilled in the form where a second submit would duplicate it.
|
|
||||||
///
|
|
||||||
/// Driven through a minimal host, like `log_meal_kuchnia_mixin_test.dart`:
|
|
||||||
/// the real `LogMealScreen` fans out into sync and notifications and does not
|
|
||||||
/// pump to quiescence in a widget test.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
|
||||||
import 'package:diet_guard_app/models/local_time.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_fill_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_fill.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
|
||||||
import 'package:diet_guard_app/ui/cues.dart';
|
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
|
|
||||||
import '../kuchnia_fill_support.dart';
|
|
||||||
|
|
||||||
class _Host extends StatefulWidget {
|
|
||||||
const _Host(this.storage, this.delivery);
|
|
||||||
|
|
||||||
final LogStorageService storage;
|
|
||||||
final List<KuchniaDish> delivery;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_Host> createState() => _HostState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _HostState extends State<_Host>
|
|
||||||
with
|
|
||||||
WidgetsBindingObserver,
|
|
||||||
LogMealSyncMixin<_Host>,
|
|
||||||
LogMealKuchniaMixin<_Host>,
|
|
||||||
LogMealFutureMixin<_Host>,
|
|
||||||
LogMealFillMixin<_Host> {
|
|
||||||
final TextEditingController desc = TextEditingController();
|
|
||||||
final MacroControllers macros = MacroControllers();
|
|
||||||
int publishes = 0;
|
|
||||||
String status = '';
|
|
||||||
CueKind statusKind = CueKind.info;
|
|
||||||
|
|
||||||
@override
|
|
||||||
int? selectedSlot;
|
|
||||||
|
|
||||||
@override
|
|
||||||
http.Client? get syncHttpClient => null;
|
|
||||||
|
|
||||||
@override
|
|
||||||
TextEditingController get descController => desc;
|
|
||||||
|
|
||||||
@override
|
|
||||||
MacroControllers get macroControllers => macros;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
fillFlow = FillAllFlow(
|
|
||||||
fetch: (_) async => KuchniaRefresh(dishes: widget.delivery),
|
|
||||||
slots: (_) => defaultSlots,
|
|
||||||
storage: widget.storage,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
int? statusCount;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void showFillStatus(FillCue cue) => setState(() {
|
|
||||||
status = cue.label;
|
|
||||||
statusKind = cue.kind;
|
|
||||||
statusCount = cue.count;
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Counted instead of run: the real one starts a network sync.
|
|
||||||
@override
|
|
||||||
Future<DayLog> publishAfterLog() {
|
|
||||||
publishes++;
|
|
||||||
return widget.storage.readLog();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) =>
|
|
||||||
Text(status, textDirection: TextDirection.ltr);
|
|
||||||
}
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
late LogStorageService storage;
|
|
||||||
late _HostState host;
|
|
||||||
final delivery = dishes(4);
|
|
||||||
|
|
||||||
Future<void> pumpHost(WidgetTester tester) async {
|
|
||||||
await tester.pumpWidget(MaterialApp(home: _Host(storage, delivery)));
|
|
||||||
host = tester.state(find.byType(_Host));
|
|
||||||
// Mirrors the screen: the delivery is queued and the first dish prefilled.
|
|
||||||
KuchniaQueueService.instance.offer(delivery);
|
|
||||||
host.prefillNextDish();
|
|
||||||
}
|
|
||||||
|
|
||||||
setUp(() async {
|
|
||||||
storage = freshStorage();
|
|
||||||
await KuchniaQueueService.initForTesting(MemoryStore());
|
|
||||||
});
|
|
||||||
|
|
||||||
tearDown(() {
|
|
||||||
KuchniaQueueService.resetForTesting();
|
|
||||||
LogStorageService.resetForTesting();
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('the first tap only proposes: no write, no publish', (t) async {
|
|
||||||
await pumpHost(t);
|
|
||||||
|
|
||||||
await t.runAsync(host.onFillAll);
|
|
||||||
|
|
||||||
expect(host.status, startsWith('Will log 4'));
|
|
||||||
// Painted: a glyph + the number of dishes the confirm would log.
|
|
||||||
expect(host.statusCount, 4);
|
|
||||||
expect(await t.runAsync(storage.todayEntries), isEmpty);
|
|
||||||
expect(host.publishes, 0);
|
|
||||||
expect(KuchniaQueueService.remaining, 4);
|
|
||||||
expect(host.desc.text, 'D1');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('confirm logs the batch, publishes once, empties the queue', (
|
|
||||||
t,
|
|
||||||
) async {
|
|
||||||
await pumpHost(t);
|
|
||||||
|
|
||||||
await t.runAsync(() async {
|
|
||||||
await host.onFillAll();
|
|
||||||
await host.onFillAll();
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(host.status, 'Logged 4 catering dishes.');
|
|
||||||
expect(host.statusKind, CueKind.ok);
|
|
||||||
expect(host.statusCount, 4);
|
|
||||||
expect(await t.runAsync(() => loggedToday(storage)), hasLength(4));
|
|
||||||
expect(host.publishes, 1, reason: 'one publish per batch, not per dish');
|
|
||||||
expect(KuchniaQueueService.remaining, 0);
|
|
||||||
expect(host.loggedSlots, {480, 720, 960, 1200});
|
|
||||||
expect(host.desc.text, isEmpty, reason: 'D1 was logged by the fill');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('a dish the fill skipped stays queued and prefilled', (t) async {
|
|
||||||
await pumpHost(t);
|
|
||||||
await t.runAsync(() async {
|
|
||||||
await storage.logMeal(
|
|
||||||
'own breakfast',
|
|
||||||
dishNutrition(dish('own', 1)),
|
|
||||||
slotMinute: 480,
|
|
||||||
);
|
|
||||||
await host.onFillAll();
|
|
||||||
await host.onFillAll();
|
|
||||||
});
|
|
||||||
|
|
||||||
// D1's slot was taken, so only D2..D4 landed and D1 is still on offer.
|
|
||||||
expect(host.status, 'Logged 3 catering dishes.');
|
|
||||||
expect(host.statusCount, 3);
|
|
||||||
expect(KuchniaQueueService.remaining, 1);
|
|
||||||
expect(host.desc.text, 'D1');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('cancel says so and writes nothing', (t) async {
|
|
||||||
await pumpHost(t);
|
|
||||||
await t.runAsync(host.onFillAll);
|
|
||||||
|
|
||||||
host.onFillCancel();
|
|
||||||
await t.pump();
|
|
||||||
|
|
||||||
expect(host.status, contains('cancelled'));
|
|
||||||
expect(host.fillFlow.armedCount, 0);
|
|
||||||
expect(await t.runAsync(storage.todayEntries), isEmpty);
|
|
||||||
expect(host.publishes, 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('a failure mid-fill publishes what landed and says so', (
|
|
||||||
t,
|
|
||||||
) async {
|
|
||||||
await pumpHost(t);
|
|
||||||
host.fillFlow = FillAllFlow(
|
|
||||||
fetch: (_) async => KuchniaRefresh(dishes: delivery),
|
|
||||||
slots: (_) => defaultSlots,
|
|
||||||
occupiedSlots: (_) async => throw Exception('storage unavailable'),
|
|
||||||
storage: storage,
|
|
||||||
);
|
|
||||||
|
|
||||||
await t.runAsync(host.onFillAll);
|
|
||||||
|
|
||||||
expect(host.status, startsWith('Fill all failed'));
|
|
||||||
expect(host.statusKind, CueKind.error);
|
|
||||||
expect(host.publishes, 1, reason: 'a partial batch must still sync');
|
|
||||||
expect(host.fillFlow.busy, isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('a later-day fill leaves today alone and returns to it', (
|
|
||||||
t,
|
|
||||||
) async {
|
|
||||||
final now = DateTime.now();
|
|
||||||
final tomorrow = DateTime(now.year, now.month, now.day + 1);
|
|
||||||
await pumpHost(t);
|
|
||||||
await t.runAsync(() async {
|
|
||||||
await host.selectLogDate(tomorrow);
|
|
||||||
await host.onFillAll();
|
|
||||||
await host.onFillAll();
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(
|
|
||||||
host.status,
|
|
||||||
'Logged 4 catering dishes for ${localDateKey(tomorrow)}.',
|
|
||||||
);
|
|
||||||
final log = await t.runAsync(storage.readLog);
|
|
||||||
expect(log![localDateKey(tomorrow)], hasLength(4));
|
|
||||||
expect(await t.runAsync(storage.todayEntries), isEmpty);
|
|
||||||
expect(host.publishes, 1);
|
|
||||||
expect(KuchniaQueueService.remaining, 4, reason: "today's queue untouched");
|
|
||||||
expect(host.desc.text, 'D1');
|
|
||||||
expect(host.futureDate, isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('changing the date disarms a proposal', (t) async {
|
|
||||||
final now = DateTime.now();
|
|
||||||
await pumpHost(t);
|
|
||||||
await t.runAsync(() async {
|
|
||||||
await host.selectLogDate(DateTime(now.year, now.month, now.day + 1));
|
|
||||||
await host.onFillAll();
|
|
||||||
});
|
|
||||||
expect(host.fillFlow.armedCount, 4);
|
|
||||||
|
|
||||||
host.resetFutureLog();
|
|
||||||
|
|
||||||
expect(host.fillFlow.armedCount, 0);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
177
app/test/screens/log_meal_geometry_test.dart
Normal file
177
app/test/screens/log_meal_geometry_test.dart
Normal file
@ -0,0 +1,177 @@
|
|||||||
|
/// Due mode on a real phone's geometry: Pixel-class 1080x2400 at 2.625, with
|
||||||
|
/// the status-bar and gesture insets and the keyboard open.
|
||||||
|
///
|
||||||
|
/// Two promises (kuhy, 2026-11-17): the food field never moves between states,
|
||||||
|
/// and nothing scrolls with the keyboard up -- the whole form is reachable at
|
||||||
|
/// once. Heights are asserted, not eyeballed: a form that merely "looks fine"
|
||||||
|
/// in an unconstrained test viewport is the failure this guards against.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_fake.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
import '../label_finders.dart';
|
||||||
|
import 'log_meal_test_support.dart';
|
||||||
|
|
||||||
|
void _phone(WidgetTester tester, {required bool keyboard}) {
|
||||||
|
tester.view
|
||||||
|
..physicalSize = const Size(1080, 2400)
|
||||||
|
..devicePixelRatio = 2.625
|
||||||
|
..padding = const FakeViewPadding(top: 132, bottom: 63)
|
||||||
|
..viewPadding = const FakeViewPadding(top: 132, bottom: 63)
|
||||||
|
..viewInsets = FakeViewPadding(bottom: keyboard ? 840 : 0);
|
||||||
|
addTearDown(tester.view.reset);
|
||||||
|
}
|
||||||
|
|
||||||
|
double _fieldTop(WidgetTester tester) =>
|
||||||
|
tester.getTopLeft(find.byType(TextField).at(0)).dy;
|
||||||
|
|
||||||
|
double _maxScroll(WidgetTester tester) => tester
|
||||||
|
.state<ScrollableState>(
|
||||||
|
find
|
||||||
|
.descendant(
|
||||||
|
of: find.byType(SingleChildScrollView),
|
||||||
|
matching: find.byType(Scrollable),
|
||||||
|
)
|
||||||
|
.first,
|
||||||
|
)
|
||||||
|
.position
|
||||||
|
.maxScrollExtent;
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
late Future<void> Function() restore;
|
||||||
|
late FakeClaudeRelayClient relay;
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
restore = await isolateLogScreenState();
|
||||||
|
relay = FakeClaudeRelayClient();
|
||||||
|
});
|
||||||
|
tearDown(() => restore());
|
||||||
|
|
||||||
|
Future<void> open(WidgetTester tester) async {
|
||||||
|
pinLogMealClock(13); // 08:00 and 12:00 are due, so logging one stays due
|
||||||
|
await tester.pumpWidget(MaterialApp(home: LogMealScreen(relay: relay)));
|
||||||
|
await settle(tester);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> fillWorstCase(WidgetTester tester) async {
|
||||||
|
await tester.enterText(find.byType(TextField).at(0), 'kurczak z ryzem');
|
||||||
|
final worst = ['1250', '2400', '1234', '1234', '1234', '1234'];
|
||||||
|
for (var i = 0; i < worst.length; i++) {
|
||||||
|
await tester.enterText(find.byType(TextField).at(i + 1), worst[i]);
|
||||||
|
}
|
||||||
|
await settle(tester);
|
||||||
|
}
|
||||||
|
|
||||||
|
FoodEntry claudeEntry(String id) => FoodEntry(
|
||||||
|
id: id,
|
||||||
|
time: DateTime.now().toIso8601String().substring(0, 19),
|
||||||
|
desc: 'kurczak z ryzem',
|
||||||
|
grams: 300,
|
||||||
|
kcal: 540,
|
||||||
|
proteinG: 42,
|
||||||
|
carbsG: 61,
|
||||||
|
fatG: 9,
|
||||||
|
source: 'claude',
|
||||||
|
slotMinute: 480,
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('keyboard open: no scroll, field fixed across every state', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
_phone(tester, keyboard: true);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
await fillWorstCase(tester);
|
||||||
|
final top = _fieldTop(tester);
|
||||||
|
expect(_maxScroll(tester), 0, reason: 'idle, worst-case values');
|
||||||
|
|
||||||
|
Future<void> expectSteady(String state) async {
|
||||||
|
// A spinner never settles, so pump a few frames instead.
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||||
|
await tester.pump(const Duration(milliseconds: 100));
|
||||||
|
expect(_fieldTop(tester), top, reason: '$state moved the field');
|
||||||
|
expect(_maxScroll(tester), 0, reason: '$state made the form scroll');
|
||||||
|
}
|
||||||
|
|
||||||
|
await tester.tap(controlByLabel('Ask Claude'));
|
||||||
|
await tester.pump();
|
||||||
|
await expectSteady('sending');
|
||||||
|
|
||||||
|
relay.emit(const ClaudeRelayQueued());
|
||||||
|
await expectSteady('queued');
|
||||||
|
|
||||||
|
relay.emit(const ClaudeRelayLocked());
|
||||||
|
await expectSteady('locked');
|
||||||
|
|
||||||
|
await tester.tap(controlByLabel('Sync is locked'));
|
||||||
|
await tester.pump();
|
||||||
|
relay.emit(const ClaudeRelayFailed('x'));
|
||||||
|
await expectSteady('error');
|
||||||
|
|
||||||
|
await tester.tap(controlByLabel('Claude failed'));
|
||||||
|
await tester.pump();
|
||||||
|
relay.emit(ClaudeRelayLogged(claudeEntry(relay.sent.last.requestId)));
|
||||||
|
await settle(tester);
|
||||||
|
expect(find.byIcon(Icons.undo), findsOneWidget);
|
||||||
|
// Still due (12:00 is open): the screen stays in due mode.
|
||||||
|
expect(find.byType(AppBar), findsNothing);
|
||||||
|
await fillWorstCase(tester);
|
||||||
|
await expectSteady('logged row');
|
||||||
|
|
||||||
|
await tester.tap(controlByLabel('Log meal'));
|
||||||
|
await settle(tester);
|
||||||
|
// Both due slots are logged now: due mode ends, so this is the one
|
||||||
|
// transition where the field is allowed to move.
|
||||||
|
expect(find.byType(AppBar), findsOneWidget);
|
||||||
|
expect(
|
||||||
|
(await LogStorageService.instance.todayEntries()).map(
|
||||||
|
(e) => e.slotMinute,
|
||||||
|
),
|
||||||
|
[480, 720],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('keyboard closed: the form fits too', (tester) async {
|
||||||
|
_phone(tester, keyboard: false);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
await fillWorstCase(tester);
|
||||||
|
expect(_maxScroll(tester), 0);
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the suggestion block is a fixed height, empty or full', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
_phone(tester, keyboard: true);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
final empty = tester.getTopLeft(controlByLabel('Ask Claude')).dy;
|
||||||
|
await tester.enterText(find.byType(TextField).at(0), 'a');
|
||||||
|
await settle(tester);
|
||||||
|
expect(tester.getTopLeft(controlByLabel('Ask Claude')).dy, empty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the scroll probe sees a squeezed form scroll', (tester) async {
|
||||||
|
// Proves the maxScrollExtent == 0 assertions above can fail: a keyboard
|
||||||
|
// far taller than a phone's must leave the form scrollable.
|
||||||
|
tester.view
|
||||||
|
..physicalSize = const Size(1080, 2400)
|
||||||
|
..devicePixelRatio = 2.625
|
||||||
|
..viewInsets = const FakeViewPadding(bottom: 1800);
|
||||||
|
addTearDown(tester.view.reset);
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await open(tester);
|
||||||
|
expect(_maxScroll(tester), greaterThan(0));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -89,17 +89,16 @@ void main() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('a rejected log (empty description) gives only the error tick', (
|
testWidgets('a greyed log button (empty description) gives no feedback', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
await tester.runAsync(() async {
|
await tester.runAsync(() async {
|
||||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||||
await settle(tester);
|
await settle(tester);
|
||||||
await tester.tap(controlByLabel('Log meal'));
|
await tester.tap(controlByLabel('Log meal'), warnIfMissed: false);
|
||||||
await settle(tester);
|
await settle(tester);
|
||||||
expect(cueLabelled('Type what you ate first.'), findsOneWidget);
|
// Nothing to log, so neither the success buzz nor the sound.
|
||||||
// Only the error cue's own heavy tick: no success buzz.
|
expect(haptics, isEmpty);
|
||||||
expect(haptics, ['HapticFeedbackType.heavyImpact']);
|
|
||||||
expect(cues, 0);
|
expect(cues, 0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,211 +0,0 @@
|
|||||||
/// The delivered-dish queue as the log form actually drives it.
|
|
||||||
///
|
|
||||||
/// `kuchnia_queue_test.dart` covers the queue's own state machine. This file
|
|
||||||
/// covers the part that state machine exists for and that a queue-only test
|
|
||||||
/// cannot see: after a submit, are the **form controllers** already holding
|
|
||||||
/// the next dish?
|
|
||||||
///
|
|
||||||
/// That distinction is the whole point. On the PC this regressed once --
|
|
||||||
/// `_prefill_next_dish` briefly had exactly one caller, so the queue was
|
|
||||||
/// correct and the form was not. Every dish after the first stayed behind
|
|
||||||
/// another tap and the "(N more to go)" line became a dead letter. A test
|
|
||||||
/// asserting "the dish was offered" passes throughout that bug; one asserting
|
|
||||||
/// the controller contents after a submit does not.
|
|
||||||
///
|
|
||||||
/// Driven through a minimal host rather than the real `LogMealScreen`: that
|
|
||||||
/// screen's `initState` fans out into sync, notifications and the food bank,
|
|
||||||
/// and pumping it to quiescence in a widget test does not terminate. The
|
|
||||||
/// mixin is the unit that owns this behaviour, so it is the unit under test.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/services/document_store.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
|
|
||||||
/// In-memory store, so these tests need no plugin channel.
|
|
||||||
class _MemoryStore implements DocumentStore {
|
|
||||||
final Map<String, String> documents = {};
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<String?> read(String name) async => documents[name];
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> write(String name, String contents) async {
|
|
||||||
documents[name] = contents;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The smallest widget that uses the mixin the way the log screen does.
|
|
||||||
class _Host extends StatefulWidget {
|
|
||||||
const _Host();
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_Host> createState() => _HostState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _HostState extends State<_Host> with LogMealKuchniaMixin<_Host> {
|
|
||||||
final TextEditingController desc = TextEditingController();
|
|
||||||
final MacroControllers macros = MacroControllers();
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
for (final c in [
|
|
||||||
macros.kcal,
|
|
||||||
macros.protein,
|
|
||||||
macros.carbs,
|
|
||||||
macros.fat,
|
|
||||||
macros.perGrams,
|
|
||||||
macros.grams,
|
|
||||||
]) {
|
|
||||||
c.addListener(() {
|
|
||||||
if (source == 'food bank') source = 'manual';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
TextEditingController get descController => desc;
|
|
||||||
|
|
||||||
@override
|
|
||||||
MacroControllers get macroControllers => macros;
|
|
||||||
|
|
||||||
/// Mirrors the screen: a macro edit demotes a food-bank pick to manual,
|
|
||||||
/// and a prefilled dish stamps catering.
|
|
||||||
String source = 'manual';
|
|
||||||
|
|
||||||
@override
|
|
||||||
void onDishPrefilled() => source = 'catering';
|
|
||||||
|
|
||||||
/// Stands in for the screen's submit: the entry write is irrelevant here,
|
|
||||||
/// the queue advance is what is under test.
|
|
||||||
void submit() {
|
|
||||||
final logged = desc.text;
|
|
||||||
desc.clear();
|
|
||||||
macros.clear();
|
|
||||||
advanceQueueAfterLog(logged);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) =>
|
|
||||||
Text(queueStatusLine ?? '', textDirection: TextDirection.ltr);
|
|
||||||
}
|
|
||||||
|
|
||||||
KuchniaDish _dish(String name, int priority) => KuchniaDish(
|
|
||||||
name: name,
|
|
||||||
kcal: 400,
|
|
||||||
proteinG: 25,
|
|
||||||
carbsG: 45.5,
|
|
||||||
fatG: 12,
|
|
||||||
grams: 300,
|
|
||||||
priority: priority,
|
|
||||||
slotLabel: 'Obiad',
|
|
||||||
);
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
late _HostState host;
|
|
||||||
|
|
||||||
Future<void> pumpHost(WidgetTester tester) async {
|
|
||||||
await tester.pumpWidget(const MaterialApp(home: _Host()));
|
|
||||||
host = tester.state(find.byType(_Host));
|
|
||||||
}
|
|
||||||
|
|
||||||
setUp(() async {
|
|
||||||
await KuchniaQueueService.initForTesting(_MemoryStore());
|
|
||||||
});
|
|
||||||
|
|
||||||
tearDown(KuchniaQueueService.resetForTesting);
|
|
||||||
|
|
||||||
testWidgets('after a submit the form already holds the next dish', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpHost(tester);
|
|
||||||
KuchniaQueueService.instance.offer([
|
|
||||||
_dish('Pancakes', 1),
|
|
||||||
_dish('Kaszotto', 2),
|
|
||||||
]);
|
|
||||||
host.prefillNextDish();
|
|
||||||
await tester.pump();
|
|
||||||
expect(host.desc.text, 'Pancakes');
|
|
||||||
|
|
||||||
host.submit();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(
|
|
||||||
host.desc.text,
|
|
||||||
'Kaszotto',
|
|
||||||
reason: 'the form must already hold dish 2. Empty here means the queue '
|
|
||||||
'is right and the form is not -- the dead-letter regression where '
|
|
||||||
'every dish after the first waits behind another tap.',
|
|
||||||
);
|
|
||||||
expect(KuchniaQueueService.remaining, 1);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('the macros come with the dish, not just the name', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpHost(tester);
|
|
||||||
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
|
|
||||||
host.prefillNextDish();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// Whole numbers print without a trailing `.0`, matching Python's `:g`.
|
|
||||||
expect(host.macros.kcal.text, '400');
|
|
||||||
expect(host.macros.protein.text, '25');
|
|
||||||
expect(host.macros.carbs.text, '45.5');
|
|
||||||
expect(host.macros.fat.text, '12');
|
|
||||||
expect(host.macros.grams.text, '300');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('the leftover dish is named rather than dropped', (tester) async {
|
|
||||||
// Five delivered meals against four default slots leaves one queued when
|
|
||||||
// the last slot is logged. It is already banked, so say so.
|
|
||||||
await pumpHost(tester);
|
|
||||||
KuchniaQueueService.instance.offer([_dish('A', 1), _dish('B', 2)]);
|
|
||||||
host.prefillNextDish();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
host.submit();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.text('1 more delivered dish to log.'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('editing the description does not consume the offer', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// What the user logged was not the delivered dish, so marking it eaten
|
|
||||||
// would lose a real delivered meal silently.
|
|
||||||
await pumpHost(tester);
|
|
||||||
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
|
|
||||||
host.prefillNextDish();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
host.desc.text = 'Something else';
|
|
||||||
host.submit();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(KuchniaQueueService.remaining, 1);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('an empty queue clears the offer instead of throwing', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpHost(tester);
|
|
||||||
host.prefillNextDish();
|
|
||||||
await tester.pump();
|
|
||||||
expect(host.offeredDish, isNull);
|
|
||||||
expect(host.queueStatusLine, isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('submitting with nothing offered is a no-op', (tester) async {
|
|
||||||
await pumpHost(tester);
|
|
||||||
host.submit();
|
|
||||||
await tester.pump();
|
|
||||||
expect(KuchniaQueueService.remaining, 0);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -1,183 +0,0 @@
|
|||||||
/// What a prefilled dish actually *logs*, as distinct from what it displays.
|
|
||||||
///
|
|
||||||
/// Split from `log_meal_kuchnia_mixin_test.dart` (250-line cap) along the
|
|
||||||
/// seam the 2026-08-23 corruption exposed: that file asserts the queue's
|
|
||||||
/// mechanics and the controllers' text, and every one of its tests passed
|
|
||||||
/// while a delivered dish logged 2.58x its real calories. The bug lived in
|
|
||||||
/// the *computed* `Nutrition`, which nothing there looked at.
|
|
||||||
///
|
|
||||||
/// So these tests assert the computed value, never the field text.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_actions.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/services/document_store.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
|
|
||||||
/// In-memory store, so these tests need no plugin channel.
|
|
||||||
class _MemoryStore implements DocumentStore {
|
|
||||||
final Map<String, String> documents = {};
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<String?> read(String name) async => documents[name];
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> write(String name, String contents) async {
|
|
||||||
documents[name] = contents;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The smallest widget that uses the mixin the way the log screen does.
|
|
||||||
class _Host extends StatefulWidget {
|
|
||||||
const _Host();
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_Host> createState() => _HostState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _HostState extends State<_Host> with LogMealKuchniaMixin<_Host> {
|
|
||||||
final TextEditingController desc = TextEditingController();
|
|
||||||
final MacroControllers macros = MacroControllers();
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
for (final c in [
|
|
||||||
macros.kcal,
|
|
||||||
macros.protein,
|
|
||||||
macros.carbs,
|
|
||||||
macros.fat,
|
|
||||||
macros.perGrams,
|
|
||||||
macros.grams,
|
|
||||||
]) {
|
|
||||||
c.addListener(() {
|
|
||||||
if (source == 'food bank') source = 'manual';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
TextEditingController get descController => desc;
|
|
||||||
|
|
||||||
@override
|
|
||||||
MacroControllers get macroControllers => macros;
|
|
||||||
|
|
||||||
/// Mirrors the screen: a macro edit demotes a food-bank pick to manual,
|
|
||||||
/// and a prefilled dish stamps catering.
|
|
||||||
String source = 'manual';
|
|
||||||
|
|
||||||
@override
|
|
||||||
void onDishPrefilled() => source = 'catering';
|
|
||||||
|
|
||||||
/// Stands in for the screen's submit: the entry write is irrelevant here,
|
|
||||||
/// the queue advance is what is under test.
|
|
||||||
void submit() {
|
|
||||||
final logged = desc.text;
|
|
||||||
desc.clear();
|
|
||||||
macros.clear();
|
|
||||||
advanceQueueAfterLog(logged);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) =>
|
|
||||||
Text(queueStatusLine ?? '', textDirection: TextDirection.ltr);
|
|
||||||
}
|
|
||||||
|
|
||||||
KuchniaDish _dish(String name, int priority) => KuchniaDish(
|
|
||||||
name: name,
|
|
||||||
kcal: 400,
|
|
||||||
proteinG: 25,
|
|
||||||
carbsG: 45.5,
|
|
||||||
fatG: 12,
|
|
||||||
grams: 300,
|
|
||||||
priority: priority,
|
|
||||||
slotLabel: 'Obiad',
|
|
||||||
);
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
late _HostState host;
|
|
||||||
|
|
||||||
Future<void> pumpHost(WidgetTester tester) async {
|
|
||||||
await tester.pumpWidget(const MaterialApp(home: _Host()));
|
|
||||||
host = tester.state(find.byType(_Host));
|
|
||||||
}
|
|
||||||
|
|
||||||
setUp(() async {
|
|
||||||
await KuchniaQueueService.initForTesting(_MemoryStore());
|
|
||||||
});
|
|
||||||
|
|
||||||
tearDown(KuchniaQueueService.resetForTesting);
|
|
||||||
|
|
||||||
testWidgets('a stale per-grams does not rescale the prefilled dish', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// The 2026-08-23 corruption: a food-bank pick leaves `perGrams` at 100,
|
|
||||||
// the dish prefills over it without clearing, and `nutritionForPortion`
|
|
||||||
// reads the dish's *per-portion* macros as *per-100g* and multiplies them
|
|
||||||
// by 300/100. Asserting controller text passes throughout that bug --
|
|
||||||
// only the computed Nutrition sees it.
|
|
||||||
await pumpHost(tester);
|
|
||||||
host.macros.perGrams.text = '100';
|
|
||||||
|
|
||||||
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
|
|
||||||
host.prefillNextDish();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
final nutrition = nutritionFromControllers(host.macros, 'kuchnia wikinga');
|
|
||||||
expect(
|
|
||||||
nutrition.kcal,
|
|
||||||
400,
|
|
||||||
reason: 'the dish must log its own calories. 1200 here is the stale '
|
|
||||||
'per-grams rescaling a per-portion dish by 300/100.',
|
|
||||||
);
|
|
||||||
expect(nutrition.proteinG, 25);
|
|
||||||
expect(nutrition.carbsG, 45.5);
|
|
||||||
expect(nutrition.fatG, 12);
|
|
||||||
expect(nutrition.grams, 300);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('clear() empties every macro controller', (tester) async {
|
|
||||||
// Enumerated deliberately: the bug was a *forgotten* field, so a new
|
|
||||||
// seventh controller must fail this until it is cleared too.
|
|
||||||
await pumpHost(tester);
|
|
||||||
final controllers = <String, TextEditingController>{
|
|
||||||
'kcal': host.macros.kcal,
|
|
||||||
'protein': host.macros.protein,
|
|
||||||
'carbs': host.macros.carbs,
|
|
||||||
'fat': host.macros.fat,
|
|
||||||
'perGrams': host.macros.perGrams,
|
|
||||||
'grams': host.macros.grams,
|
|
||||||
};
|
|
||||||
for (final c in controllers.values) {
|
|
||||||
c.text = '99';
|
|
||||||
}
|
|
||||||
|
|
||||||
host.macros.clear();
|
|
||||||
|
|
||||||
controllers.forEach((name, c) {
|
|
||||||
expect(c.text, isEmpty, reason: '$name survived clear()');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('the prefill stamps catering even though clearing demotes it', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// Ordering is load-bearing and invisible: `clear()` fires the macro
|
|
||||||
// listener, which demotes a food-bank pick to 'manual'. `onDishPrefilled`
|
|
||||||
// runs after and must have the last word, or a delivered dish logs as a
|
|
||||||
// manual entry and the queue never advances.
|
|
||||||
await pumpHost(tester);
|
|
||||||
host.source = 'food bank';
|
|
||||||
host.macros.perGrams.text = '100';
|
|
||||||
|
|
||||||
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
|
|
||||||
host.prefillNextDish();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(host.source, 'catering');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -1,4 +1,4 @@
|
|||||||
/// The log screen's slot row versus a meal-schedule change.
|
/// The log screen's due slots versus a meal-schedule change.
|
||||||
///
|
///
|
||||||
/// Split from `log_meal_screen_test.dart` for the repo's 250-line cap.
|
/// Split from `log_meal_screen_test.dart` for the repo's 250-line cap.
|
||||||
library;
|
library;
|
||||||
@ -6,6 +6,7 @@ library;
|
|||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/meal_schedule.dart';
|
import 'package:diet_guard_app/models/meal_schedule.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||||
@ -17,6 +18,8 @@ import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
|||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
|
import 'log_meal_test_support.dart' show pinLogMealClock;
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
late Directory tempDir;
|
late Directory tempDir;
|
||||||
|
|
||||||
@ -43,31 +46,32 @@ void main() {
|
|||||||
await tester.pumpAndSettle();
|
await tester.pumpAndSettle();
|
||||||
}
|
}
|
||||||
|
|
||||||
testWidgets('the slot row follows a schedule change made in settings', (
|
testWidgets('the due slots follow a schedule change made in settings', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
// Found on the phone: the settings preview and the overdue reminder both
|
// Found on the phone: the settings preview and the overdue reminder both
|
||||||
// picked up a four -> five meal change while the row behind them kept
|
// picked up a schedule change while the screen behind them kept the old
|
||||||
// rendering the old four checkpoints until the app was restarted, because
|
// checkpoints until the app was restarted, because onOpenSettings pushed
|
||||||
// onOpenSettings pushed without awaiting the pop.
|
// without awaiting the pop.
|
||||||
|
pinLogMealClock(13);
|
||||||
await tester.runAsync(() async {
|
await tester.runAsync(() async {
|
||||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||||
await settle(tester);
|
await settle(tester);
|
||||||
expect(find.text('12:00'), findsOneWidget);
|
|
||||||
|
|
||||||
await MealScheduleService.instance.recordChange(
|
|
||||||
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
|
|
||||||
);
|
|
||||||
final state = tester.state<State<LogMealScreen>>(
|
final state = tester.state<State<LogMealScreen>>(
|
||||||
find.byType(LogMealScreen),
|
find.byType(LogMealScreen),
|
||||||
);
|
);
|
||||||
|
final due = state as LogMealDueMixin<LogMealScreen>;
|
||||||
|
expect(due.dueSlots, [480, 720]);
|
||||||
|
|
||||||
|
await MealScheduleService.instance.recordChange(
|
||||||
|
const MealSchedule(firstMinute: 9 * 60, lastMinute: 21 * 60, count: 4),
|
||||||
|
);
|
||||||
await (state as LogMealNavMixin<LogMealScreen>)
|
await (state as LogMealNavMixin<LogMealScreen>)
|
||||||
.onScheduleMayHaveChanged();
|
.onScheduleMayHaveChanged();
|
||||||
await settle(tester);
|
await settle(tester);
|
||||||
|
|
||||||
expect(find.text('11:00'), findsOneWidget);
|
expect(due.dueSlots, [540, 780]);
|
||||||
expect(find.text('17:00'), findsOneWidget);
|
expect(due.targetSlot, 540);
|
||||||
expect(find.text('12:00'), findsNothing);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -144,55 +144,14 @@ void main() {
|
|||||||
expect(find.byType(FoodBankScreen), findsOneWidget);
|
expect(find.byType(FoodBankScreen), findsOneWidget);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
testWidgets('logged slot chip renders check-icon avatar', (tester) async {
|
testWidgets('normal mode has no slot chips', (tester) async {
|
||||||
await tester.runAsync(() async {
|
|
||||||
final now = DateTime.now();
|
|
||||||
final dateKey =
|
|
||||||
'${now.year.toString().padLeft(4, '0')}-'
|
|
||||||
'${now.month.toString().padLeft(2, '0')}-'
|
|
||||||
'${now.day.toString().padLeft(2, '0')}';
|
|
||||||
final at8 = DateTime(now.year, now.month, now.day, 8);
|
|
||||||
|
|
||||||
await LogStorageService.instance.writeLog({
|
|
||||||
dateKey: [
|
|
||||||
FoodEntry(
|
|
||||||
id: 'slot-seed',
|
|
||||||
time: at8.toIso8601String(),
|
|
||||||
desc: 'breakfast',
|
|
||||||
grams: 100,
|
|
||||||
kcal: 300,
|
|
||||||
proteinG: 10,
|
|
||||||
carbsG: 40,
|
|
||||||
fatG: 5,
|
|
||||||
source: 'manual',
|
|
||||||
slotMinute: 480,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
|
||||||
await settle(tester);
|
|
||||||
|
|
||||||
// The 08:00 slot is logged — its ChoiceChip has a check-icon avatar.
|
|
||||||
expect(find.byIcon(Icons.check), findsWidgets);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
testWidgets('tapping a slot chip selects it', (tester) async {
|
|
||||||
await tester.runAsync(() async {
|
await tester.runAsync(() async {
|
||||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||||
await settle(tester);
|
await settle(tester);
|
||||||
|
|
||||||
// Tap the 08:00 chip to force _selectedSlot = 8.
|
// The slot is derived (oldest due, else nearest), never picked.
|
||||||
await tester.tap(find.text('08:00'));
|
expect(find.byType(ChoiceChip), findsNothing);
|
||||||
await settle(tester);
|
expect(find.text('08:00'), findsNothing);
|
||||||
|
|
||||||
final chip = tester.widget<ChoiceChip>(
|
|
||||||
find.ancestor(
|
|
||||||
of: find.text('08:00'),
|
|
||||||
matching: find.byType(ChoiceChip),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(chip.selected, isTrue);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -39,11 +39,6 @@ class _FakeUrlLauncher extends UrlLauncherPlatform
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a fixed [XFile] without touching any real platform channel.
|
|
||||||
|
|
||||||
/// A minimal valid 1x1 transparent PNG, so the thumbnail preview can decode
|
|
||||||
/// it as a real image instead of throwing on bogus bytes.
|
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
late Directory tempDir;
|
late Directory tempDir;
|
||||||
|
|
||||||
@ -152,17 +147,27 @@ void main() {
|
|||||||
expect(find.byType(TodayProgressCard), findsNothing);
|
expect(find.byType(TodayProgressCard), findsNothing);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
testWidgets('refuses to log with an empty description', (tester) async {
|
testWidgets('the log button is greyed until a description is typed', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
await tester.runAsync(() async {
|
await tester.runAsync(() async {
|
||||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||||
await settle(tester);
|
await settle(tester);
|
||||||
|
|
||||||
await tester.ensureVisible(logMealButton);
|
FilledButton log() => tester.widget<FilledButton>(
|
||||||
await tester.tap(logMealButton);
|
find.ancestor(
|
||||||
|
of: byIconLabel('Log meal'),
|
||||||
|
matching: find.byType(FilledButton),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(log().onPressed, isNull);
|
||||||
|
await tester.tap(logMealButton, warnIfMissed: false);
|
||||||
await settle(tester);
|
await settle(tester);
|
||||||
|
|
||||||
expect(cueLabelled('Type what you ate first.'), findsOneWidget);
|
|
||||||
expect(await LogStorageService.instance.todayEntries(), isEmpty);
|
expect(await LogStorageService.instance.todayEntries(), isEmpty);
|
||||||
|
|
||||||
|
await tester.enterText(find.byType(TextField).at(0), 'toast');
|
||||||
|
await settle(tester);
|
||||||
|
expect(log().onPressed, isNotNull);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
testWidgets(
|
testWidgets(
|
||||||
@ -217,7 +222,7 @@ void main() {
|
|||||||
await settle(tester);
|
await settle(tester);
|
||||||
|
|
||||||
// The empty-query suggestion list shows the only banked food.
|
// The empty-query suggestion list shows the only banked food.
|
||||||
await tester.tap(find.text('seeded food'));
|
await tester.tap(find.text('seeded food').first);
|
||||||
await settle(tester);
|
await settle(tester);
|
||||||
await tester.ensureVisible(logMealButton);
|
await tester.ensureVisible(logMealButton);
|
||||||
await tester.tap(logMealButton);
|
await tester.tap(logMealButton);
|
||||||
@ -228,7 +233,7 @@ void main() {
|
|||||||
expect(firstEntry.source, 'food bank');
|
expect(firstEntry.source, 'food bank');
|
||||||
expect(firstEntry.kcal, 250);
|
expect(firstEntry.kcal, 250);
|
||||||
|
|
||||||
await tester.tap(find.text('seeded food'));
|
await tester.tap(find.text('seeded food').first);
|
||||||
await settle(tester);
|
await settle(tester);
|
||||||
await tester.enterText(find.byType(TextField).at(2), '999');
|
await tester.enterText(find.byType(TextField).at(2), '999');
|
||||||
await settle(tester);
|
await settle(tester);
|
||||||
|
|||||||
53
app/test/screens/log_meal_test_support.dart
Normal file
53
app/test/screens/log_meal_test_support.dart
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
/// Shared setup for the log screen's due-mode tests.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||||
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
|
/// Pins the screen's clock to [hour]:[minute] today for this test only; the
|
||||||
|
/// suite default (07:00, before the first slot) comes back afterwards.
|
||||||
|
void pinLogMealClock(int hour, [int minute = 0]) {
|
||||||
|
final previous = logMealClock;
|
||||||
|
final today = DateTime.now();
|
||||||
|
logMealClock = () =>
|
||||||
|
DateTime(today.year, today.month, today.day, hour, minute);
|
||||||
|
addTearDown(() => logMealClock = previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Points every singleton the screen touches at a fresh temp directory.
|
||||||
|
///
|
||||||
|
/// Call from `setUp`; the returned function undoes it, for `tearDown`.
|
||||||
|
Future<Future<void> Function()> isolateLogScreenState() async {
|
||||||
|
final dir = await Directory.systemTemp.createTemp('diet_guard_due_');
|
||||||
|
LogStorageService.resetForTesting(store: FileDocumentStore(dir));
|
||||||
|
FoodBankService.resetForTesting(store: FileDocumentStore(dir));
|
||||||
|
AppSettingsService.resetForTesting(store: FileDocumentStore(dir));
|
||||||
|
BudgetHistoryService.resetForTesting(store: FileDocumentStore(dir));
|
||||||
|
await MealScheduleService.initForTesting(FileDocumentStore(dir));
|
||||||
|
KuchniaAutoLog.instance = KuchniaAutoLog();
|
||||||
|
return () async {
|
||||||
|
LogStorageService.resetForTesting();
|
||||||
|
FoodBankService.resetForTesting();
|
||||||
|
AppSettingsService.resetForTesting();
|
||||||
|
BudgetHistoryService.resetForTesting();
|
||||||
|
MealScheduleService.resetForTesting();
|
||||||
|
KuchniaAutoLog.instance = KuchniaAutoLog();
|
||||||
|
await dir.delete(recursive: true);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lets real file I/O finish, then settles the frame (the screens' file
|
||||||
|
/// stores run outside the fake-async zone).
|
||||||
|
Future<void> settle(WidgetTester tester) async {
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
}
|
||||||
77
app/test/services/claude_relay_client_test.dart
Normal file
77
app/test/services/claude_relay_client_test.dart
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
/// The relay interface and its fake: the contract the screen depends on.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_fake.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
|
const _request = ClaudeRelayRequest(
|
||||||
|
requestId: 'r1',
|
||||||
|
slotMinute: 480,
|
||||||
|
text: 'x',
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test(
|
||||||
|
'queued is not terminal: the same stream later delivers the meal',
|
||||||
|
() async {
|
||||||
|
final relay = FakeClaudeRelayClient();
|
||||||
|
final events = <ClaudeRelayEvent>[];
|
||||||
|
final done = Completer<void>();
|
||||||
|
relay.send(_request).listen(events.add, onDone: done.complete);
|
||||||
|
|
||||||
|
relay.emit(const ClaudeRelayQueued());
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(done.isCompleted, isFalse);
|
||||||
|
|
||||||
|
const entry = FoodEntry(
|
||||||
|
id: 'r1',
|
||||||
|
time: 't',
|
||||||
|
desc: 'x',
|
||||||
|
grams: 1,
|
||||||
|
kcal: 1,
|
||||||
|
proteinG: 1,
|
||||||
|
carbsG: 1,
|
||||||
|
fatG: 1,
|
||||||
|
source: 'claude',
|
||||||
|
);
|
||||||
|
relay.emit(const ClaudeRelayLogged(entry));
|
||||||
|
await done.future;
|
||||||
|
expect(events.map((e) => e.runtimeType), [
|
||||||
|
ClaudeRelayQueued,
|
||||||
|
ClaudeRelayLogged,
|
||||||
|
]);
|
||||||
|
expect((events.last as ClaudeRelayLogged).entry.id, _request.requestId);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
for (final event in [
|
||||||
|
const ClaudeRelayLocked(),
|
||||||
|
const ClaudeRelayFailed('boom'),
|
||||||
|
]) {
|
||||||
|
test('${event.runtimeType} ends the stream', () async {
|
||||||
|
final relay = FakeClaudeRelayClient();
|
||||||
|
final done = Completer<void>();
|
||||||
|
relay.send(_request).listen((_) {}, onDone: done.complete);
|
||||||
|
relay.emit(event);
|
||||||
|
await done.future;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('the fake records every request', () {
|
||||||
|
final relay = FakeClaudeRelayClient()
|
||||||
|
..send(_request).listen((_) {})
|
||||||
|
..send(_request).listen((_) {});
|
||||||
|
expect(relay.sent, hasLength(2));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the unwired client fails closed', () async {
|
||||||
|
final events = await const UnconfiguredClaudeRelayClient()
|
||||||
|
.send(_request)
|
||||||
|
.toList();
|
||||||
|
expect(events.single, isA<ClaudeRelayFailed>());
|
||||||
|
});
|
||||||
|
}
|
||||||
84
app/test/services/kuchnia_autolog_ids_test.dart
Normal file
84
app/test/services/kuchnia_autolog_ids_test.dart
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
/// The catering auto-log entry ids against the shared fixture.
|
||||||
|
///
|
||||||
|
/// `tests/fixtures/kuchnia_autolog_ids.json` is generated by Python's stdlib
|
||||||
|
/// `uuid.uuid5` (scripts/build_kuchnia_autolog_fixture.py), so this test
|
||||||
|
/// checks a value Dart did not compute itself.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_parse.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
|
Map<String, dynamic> _fixture() {
|
||||||
|
var dir = Directory.current;
|
||||||
|
while (!File(
|
||||||
|
'${dir.path}/tests/fixtures/kuchnia_autolog_ids.json',
|
||||||
|
).existsSync()) {
|
||||||
|
dir = dir.parent;
|
||||||
|
}
|
||||||
|
return jsonDecode(
|
||||||
|
File(
|
||||||
|
'${dir.path}/tests/fixtures/kuchnia_autolog_ids.json',
|
||||||
|
).readAsStringSync(),
|
||||||
|
)
|
||||||
|
as Map<String, dynamic>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The payload meal the fixture case describes, as the panel sends it.
|
||||||
|
Map<String, Object?> _payloadMeal(Map<String, dynamic> c) => {
|
||||||
|
if (c['delivery_meal_id'] != null) 'deliveryMealId': c['delivery_meal_id'],
|
||||||
|
'mealName': 'Obiad',
|
||||||
|
'mealPriority': 3,
|
||||||
|
'menuMealName': c['name'],
|
||||||
|
'nutrition': {
|
||||||
|
'weight': 300.0,
|
||||||
|
'calories': 400.0,
|
||||||
|
'protein': 25.0,
|
||||||
|
'carbohydrate': 45.0,
|
||||||
|
'fat': 12.0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final fixture = _fixture();
|
||||||
|
final cases = (fixture['cases'] as List).cast<Map<String, dynamic>>();
|
||||||
|
|
||||||
|
test('the fixture uses the RFC URL namespace', () {
|
||||||
|
expect(fixture['namespace'], '6ba7b811-9dad-11d1-80b4-00c04fd430c8');
|
||||||
|
expect(cases, isNotEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (final c in cases) {
|
||||||
|
test('${c['name_string']} -> ${c['expected_id']}', () {
|
||||||
|
final dish = parseMeal(_payloadMeal(c), 1)!;
|
||||||
|
expect(
|
||||||
|
kuchniaAutologId(c['delivery_date'] as String, dish),
|
||||||
|
c['expected_id'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('the panel id never leaks into the bank record', () {
|
||||||
|
final dish = parseMeal(_payloadMeal(cases.first), 1)!;
|
||||||
|
expect(dish.toBankRecord().containsKey('dishId'), isFalse);
|
||||||
|
expect(dish.dishId, '1001');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a dish with no id keys on its bank key', () {
|
||||||
|
const dish = KuchniaDish(
|
||||||
|
name: ' Zupa ',
|
||||||
|
kcal: 1,
|
||||||
|
proteinG: 0,
|
||||||
|
carbsG: 0,
|
||||||
|
fatG: 0,
|
||||||
|
grams: 1,
|
||||||
|
priority: 1,
|
||||||
|
slotLabel: '',
|
||||||
|
);
|
||||||
|
expect(dish.autologKey, 'zupa');
|
||||||
|
});
|
||||||
|
}
|
||||||
143
app/test/services/kuchnia_autolog_test.dart
Normal file
143
app/test/services/kuchnia_autolog_test.dart
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
/// Catering auto-log: due slots log their dish without a tap, exactly once.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_fill.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
|
import '../kuchnia_fill_support.dart';
|
||||||
|
|
||||||
|
KuchniaDish _dish(int n) => KuchniaDish(
|
||||||
|
name: 'D$n',
|
||||||
|
kcal: 100.0 * n,
|
||||||
|
proteinG: 10,
|
||||||
|
carbsG: 20,
|
||||||
|
fatG: 5,
|
||||||
|
grams: 300,
|
||||||
|
priority: n,
|
||||||
|
slotLabel: '',
|
||||||
|
dishId: '${1000 + n}',
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
late LogStorageService storage;
|
||||||
|
late int fetches;
|
||||||
|
late KuchniaRefresh result;
|
||||||
|
late DateTime clock;
|
||||||
|
late KuchniaAutoLog autoLog;
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
storage = freshStorage();
|
||||||
|
fetches = 0;
|
||||||
|
result = KuchniaRefresh(dishes: [for (var i = 1; i <= 4; i++) _dish(i)]);
|
||||||
|
final today = DateTime.now();
|
||||||
|
clock = DateTime(today.year, today.month, today.day, 13);
|
||||||
|
autoLog = KuchniaAutoLog(
|
||||||
|
fetch: (day) async {
|
||||||
|
fetches++;
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
now: () => clock,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('logs only the dishes of the due slots, source catering', () async {
|
||||||
|
final written = await autoLog.logDue([480, 720]);
|
||||||
|
expect(written.map((e) => e.desc), ['D1', 'D2']);
|
||||||
|
expect(written.map((e) => e.slotMinute), [480, 720]);
|
||||||
|
expect(written.every((e) => e.source == kuchniaSource), isTrue);
|
||||||
|
expect(await loggedToday(storage), ['D1@480', 'D2@720']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ids are the deterministic v5 ids', () async {
|
||||||
|
final written = await autoLog.logDue([480]);
|
||||||
|
final day = written.single.time.substring(0, 10);
|
||||||
|
expect(written.single.id, kuchniaAutologId(day, _dish(1)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('opening twice leaves one entry per dish', () async {
|
||||||
|
await autoLog.logDue([480, 720]);
|
||||||
|
final second = await KuchniaAutoLog(
|
||||||
|
fetch: (day) async => result,
|
||||||
|
now: () => clock,
|
||||||
|
).logDue([480, 720]);
|
||||||
|
expect(second, isEmpty);
|
||||||
|
expect(await loggedToday(storage), ['D1@480', 'D2@720']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an undone dish is not logged again on the next open', () async {
|
||||||
|
final first = await autoLog.logDue([480]);
|
||||||
|
await storage.deleteEntry(first.single.id!);
|
||||||
|
final again = await KuchniaAutoLog(
|
||||||
|
fetch: (day) async => result,
|
||||||
|
now: () => clock,
|
||||||
|
).logDue([480]);
|
||||||
|
expect(again, isEmpty);
|
||||||
|
expect(await storage.todayEntries(), isEmpty);
|
||||||
|
expect((await storage.findEntry(first.single.id!))!.deleted, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a copy logged on another device merges to one entry', () async {
|
||||||
|
final mine = (await autoLog.logDue([480])).single;
|
||||||
|
final theirs = FoodEntry(
|
||||||
|
id: mine.id,
|
||||||
|
time: mine.time.replaceRange(17, 19, '59'),
|
||||||
|
desc: mine.desc,
|
||||||
|
grams: mine.grams,
|
||||||
|
kcal: mine.kcal,
|
||||||
|
proteinG: mine.proteinG,
|
||||||
|
carbsG: mine.carbsG,
|
||||||
|
fatG: mine.fatG,
|
||||||
|
source: mine.source,
|
||||||
|
slotMinute: mine.slotMinute,
|
||||||
|
);
|
||||||
|
final merged = logToDayLog(
|
||||||
|
mergeLogs(
|
||||||
|
dayLogToLog(await storage.readLog()),
|
||||||
|
dayLogToLog({
|
||||||
|
mine.time.substring(0, 10): [theirs],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(merged.values.expand((e) => e), hasLength(1));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('later slots find their dish without a second fetch', () async {
|
||||||
|
await autoLog.logDue([480]);
|
||||||
|
final later = await autoLog.logDue([720]);
|
||||||
|
expect(later.map((e) => e.desc), ['D2']);
|
||||||
|
expect(fetches, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an empty or failed fetch is retried only after the gap', () async {
|
||||||
|
result = const KuchniaRefresh(reason: 'offline');
|
||||||
|
expect(await autoLog.logDue([480]), isEmpty);
|
||||||
|
expect(await autoLog.logDue([480]), isEmpty);
|
||||||
|
expect(fetches, 1);
|
||||||
|
clock = clock.add(const Duration(minutes: 11));
|
||||||
|
result = KuchniaRefresh(dishes: [_dish(1)]);
|
||||||
|
expect((await autoLog.logDue([480])).single.desc, 'D1');
|
||||||
|
expect(fetches, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('nothing due fetches nothing', () async {
|
||||||
|
expect(await autoLog.logDue(const []), isEmpty);
|
||||||
|
expect(fetches, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a slot that already holds a meal is left alone', () async {
|
||||||
|
await storage.logMeal(
|
||||||
|
'manual toast',
|
||||||
|
dishNutrition(_dish(1)),
|
||||||
|
slotMinute: 480,
|
||||||
|
);
|
||||||
|
expect(await autoLog.logDue([480]), isEmpty);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -2,9 +2,8 @@
|
|||||||
///
|
///
|
||||||
/// Three behaviours here are load-bearing, and each fails silently if broken:
|
/// Three behaviours here are load-bearing, and each fails silently if broken:
|
||||||
///
|
///
|
||||||
/// * **Nothing is ever logged.** A delivered meal is not an eaten meal; if the
|
/// * **The fetch only banks.** Logging is `kuchnia_autolog.dart`'s job (see
|
||||||
/// import logged, the gate would satisfy its own checkpoint from a delivery
|
/// `kuchnia_autolog_test.dart`); `refreshDelivery` itself writes no entry.
|
||||||
/// note.
|
|
||||||
/// * **Unchanged dishes are not re-banked.** `addManualEntry` restamps
|
/// * **Unchanged dishes are not re-banked.** `addManualEntry` restamps
|
||||||
/// `editedAt` unconditionally and the merge derives each record's clock from
|
/// `editedAt` unconditionally and the merge derives each record's clock from
|
||||||
/// it, so re-banking republishes the whole curated bank to every peer. The
|
/// it, so re-banking republishes the whole curated bank to every peer. The
|
||||||
@ -130,7 +129,7 @@ void main() {
|
|||||||
expect(result.dishes.single.name, 'Kaszotto');
|
expect(result.dishes.single.name, 'Kaszotto');
|
||||||
final bank = await FoodBankService.instance.readManualBank();
|
final bank = await FoodBankService.instance.readManualBank();
|
||||||
expect(bank.keys, contains('kaszotto'));
|
expect(bank.keys, contains('kaszotto'));
|
||||||
// The whole point: a delivered meal is not an eaten meal.
|
// The fetch banks; it never logs.
|
||||||
expect(await LogStorageService.instance.todayEntries(), isEmpty);
|
expect(await LogStorageService.instance.todayEntries(), isEmpty);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
66
app/test/services/meal_photo_source_test.dart
Normal file
66
app/test/services/meal_photo_source_test.dart
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
/// The photo source: permission before camera, bytes only, cache file dropped.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/meal_photo_source.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:image_picker/image_picker.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final jpeg = Uint8List.fromList([0xFF, 0xD8, 0xFF, 0xD9]);
|
||||||
|
late List<ImageSource> picked;
|
||||||
|
late List<String> discarded;
|
||||||
|
late int permissionAsks;
|
||||||
|
late bool granted;
|
||||||
|
late XFile? next;
|
||||||
|
|
||||||
|
ImagePickerPhotoSource source() => ImagePickerPhotoSource(
|
||||||
|
pickFile: (s) async {
|
||||||
|
picked.add(s);
|
||||||
|
return next;
|
||||||
|
},
|
||||||
|
requestCamera: () async {
|
||||||
|
permissionAsks++;
|
||||||
|
return granted;
|
||||||
|
},
|
||||||
|
discard: (path) async => discarded.add(path),
|
||||||
|
);
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
picked = [];
|
||||||
|
discarded = [];
|
||||||
|
permissionAsks = 0;
|
||||||
|
granted = true;
|
||||||
|
next = XFile.fromData(jpeg, path: '/cache/pick.jpg');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the camera is not opened until permission is granted', () async {
|
||||||
|
granted = false;
|
||||||
|
expect(await source().pick(PhotoOrigin.camera), isNull);
|
||||||
|
expect(permissionAsks, 1);
|
||||||
|
expect(picked, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a granted camera pick returns the bytes and drops the file', () async {
|
||||||
|
expect(await source().pick(PhotoOrigin.camera), jpeg);
|
||||||
|
expect(picked, [ImageSource.camera]);
|
||||||
|
expect(discarded, ['/cache/pick.jpg']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the gallery needs no camera permission', () async {
|
||||||
|
expect(await source().pick(PhotoOrigin.gallery), jpeg);
|
||||||
|
expect(permissionAsks, 0);
|
||||||
|
expect(picked, [ImageSource.gallery]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('backing out of the picker returns nothing', () async {
|
||||||
|
next = null;
|
||||||
|
expect(await source().pick(PhotoOrigin.gallery), isNull);
|
||||||
|
expect(discarded, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('photos are scaled to 1024 px', () {
|
||||||
|
expect(mealPhotoMaxEdge, 1024);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -1,108 +0,0 @@
|
|||||||
/// The log form's action row, and the delivery button the phone lacked.
|
|
||||||
///
|
|
||||||
/// The PC lock screen has had a "🍱 Today's delivery" button since the import
|
|
||||||
/// shipped; the phone had the queue but no visible control, so standing in
|
|
||||||
/// the kitchen there was nothing to tap. These tests pin the affordance and
|
|
||||||
/// the two ways it silently fails: a clipped label, and a dead control on the
|
|
||||||
/// web build.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/widgets/log_meal_actions_row.dart';
|
|
||||||
import 'package:material_ui/material_ui.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
|
|
||||||
import '../label_finders.dart';
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
Future<void> pump(
|
|
||||||
WidgetTester tester, {
|
|
||||||
int queued = 0,
|
|
||||||
bool busy = false,
|
|
||||||
bool canFetch = true,
|
|
||||||
Future<void> Function()? onLoad,
|
|
||||||
VoidCallback? onLog,
|
|
||||||
double width = 360,
|
|
||||||
}) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(
|
|
||||||
home: Scaffold(
|
|
||||||
body: SizedBox(
|
|
||||||
width: width,
|
|
||||||
child: LogMealActionsRow(
|
|
||||||
onLoadDelivery: onLoad ?? () async {},
|
|
||||||
onLog: onLog ?? () {},
|
|
||||||
deliveryBusy: busy,
|
|
||||||
dishesQueued: queued,
|
|
||||||
canFetchDelivery: canFetch,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
testWidgets('the delivery button is there to tap', (tester) async {
|
|
||||||
var taps = 0;
|
|
||||||
await pump(tester, onLoad: () async => taps++);
|
|
||||||
|
|
||||||
await tester.tap(find.byIcon(Icons.restaurant));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(taps, 1);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('the queue count is a numeral beside the icon', (tester) async {
|
|
||||||
await pump(tester, queued: 4);
|
|
||||||
expect(find.text('4'), findsOneWidget);
|
|
||||||
expect(byIconLabel("Load today's catering delivery"), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('nothing queued shows no numeral and never overflows', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pump(tester, width: 300);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.text('0'), findsNothing);
|
|
||||||
expect(tester.takeException(), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('a fetch in flight disables the button and spins', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pump(tester, busy: true);
|
|
||||||
|
|
||||||
final button = tester.widget<OutlinedButton>(find.byType(OutlinedButton));
|
|
||||||
expect(button.onPressed, isNull);
|
|
||||||
expect(find.byType(CircularProgressIndicator), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('the button stays visible with nothing queued', (tester) async {
|
|
||||||
// Never hidden or disabled on an empty queue: the outcome arrives as a
|
|
||||||
// cue so a late delivery can still be retried.
|
|
||||||
await pump(tester);
|
|
||||||
|
|
||||||
expect(byIconLabel("Load today's catering delivery"), findsOneWidget);
|
|
||||||
final button = tester.widget<OutlinedButton>(find.byType(OutlinedButton));
|
|
||||||
expect(button.onPressed, isNotNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('web gets no delivery button at all', (tester) async {
|
|
||||||
// The desktop target *is* the web build, and the caterer's panel blocks
|
|
||||||
// browser requests -- an unguarded button would ship a dead control.
|
|
||||||
await pump(tester, canFetch: false);
|
|
||||||
|
|
||||||
expect(find.byIcon(Icons.restaurant), findsNothing);
|
|
||||||
expect(find.byIcon(Icons.check_circle), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('the log button still logs', (tester) async {
|
|
||||||
var logged = 0;
|
|
||||||
await pump(tester, onLog: () => logged++);
|
|
||||||
|
|
||||||
await tester.tap(find.byIcon(Icons.check_circle));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(logged, 1);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
95
app/test/widgets/macro_input_row_test.dart
Normal file
95
app/test/widgets/macro_input_row_test.dart
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
/// The macro fields at the worst case: every value four digits wide.
|
||||||
|
///
|
||||||
|
/// "No overflow exception" proves nothing here -- a Row of Expanded fields
|
||||||
|
/// clips its text silently (see the row-expanded-clips-chips memory) -- so each
|
||||||
|
/// test measures the painted digits against the width the field really has.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
|
import 'package:flutter/rendering.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// `flutter test` paints with Ahem, whose every glyph is one em wide. Roboto's
|
||||||
|
/// digits (the phone's font) are 0.5615 em, so measured widths are scaled down
|
||||||
|
/// to what the phone paints; without this the check would demand room no real
|
||||||
|
/// font needs.
|
||||||
|
const _ahemToRoboto = 0.5615;
|
||||||
|
|
||||||
|
const _worst = ['1250', '2400', '1234', '1234', '1234', '1234'];
|
||||||
|
|
||||||
|
Future<MacroControllers> _pump(WidgetTester tester, double width) async {
|
||||||
|
tester.view
|
||||||
|
..physicalSize = Size(width * 2, 1600)
|
||||||
|
..devicePixelRatio = 2;
|
||||||
|
addTearDown(tester.view.reset);
|
||||||
|
final macros = MacroControllers();
|
||||||
|
addTearDown(macros.dispose);
|
||||||
|
final all = [
|
||||||
|
macros.perGrams,
|
||||||
|
macros.kcal,
|
||||||
|
macros.protein,
|
||||||
|
macros.carbs,
|
||||||
|
macros.fat,
|
||||||
|
macros.grams,
|
||||||
|
];
|
||||||
|
for (var i = 0; i < all.length; i++) {
|
||||||
|
all[i].text = _worst[i];
|
||||||
|
}
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
theme: buildAppTheme(),
|
||||||
|
home: Scaffold(
|
||||||
|
body: Padding(
|
||||||
|
padding: const EdgeInsets.all(AppSpacing.md),
|
||||||
|
child: MacroInputRow(controllers: macros, compact: true),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return macros;
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
for (final width in [411.0, 360.0]) {
|
||||||
|
group('at $width dp', () {
|
||||||
|
testWidgets('four digits fit the field at 16 sp or more', (tester) async {
|
||||||
|
await _pump(tester, width);
|
||||||
|
final editables = tester.widgetList<EditableText>(
|
||||||
|
find.byType(EditableText),
|
||||||
|
);
|
||||||
|
expect(editables, hasLength(6));
|
||||||
|
for (final (i, editable) in editables.indexed) {
|
||||||
|
expect(editable.style.fontSize, greaterThanOrEqualTo(16));
|
||||||
|
final painter = TextPainter(
|
||||||
|
text: TextSpan(text: _worst[i], style: editable.style),
|
||||||
|
textDirection: TextDirection.ltr,
|
||||||
|
)..layout();
|
||||||
|
final room = tester.getSize(find.byType(EditableText).at(i)).width;
|
||||||
|
final painted = painter.width * _ahemToRoboto;
|
||||||
|
expect(
|
||||||
|
painted,
|
||||||
|
lessThanOrEqualTo(room),
|
||||||
|
reason: '${_worst[i]} is clipped: $painted > $room',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('six fields sit in two rows of three', (tester) async {
|
||||||
|
await _pump(tester, width);
|
||||||
|
final tops = [
|
||||||
|
for (var i = 0; i < 6; i++)
|
||||||
|
tester.getTopLeft(find.byType(TextField).at(i)),
|
||||||
|
];
|
||||||
|
expect(tops[0].dy, tops[1].dy);
|
||||||
|
expect(tops[1].dy, tops[2].dy);
|
||||||
|
expect(tops[3].dy, tops[4].dy);
|
||||||
|
expect(tops[4].dy, tops[5].dy);
|
||||||
|
expect(tops[3].dy, greaterThan(tops[0].dy));
|
||||||
|
expect(tops[0].dx, lessThan(tops[1].dx));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
179
app/test/widgets/meal_action_row_test.dart
Normal file
179
app/test/widgets/meal_action_row_test.dart
Normal file
@ -0,0 +1,179 @@
|
|||||||
|
/// The 1A action row: photo, Claude, log; greyed until there is something.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/meal_action_row.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
import '../label_finders.dart';
|
||||||
|
|
||||||
|
Widget _row({
|
||||||
|
ClaudeButtonState claude = ClaudeButtonState.idle,
|
||||||
|
bool photo = false,
|
||||||
|
bool canSend = true,
|
||||||
|
bool canLog = true,
|
||||||
|
List<String>? taps,
|
||||||
|
}) => MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: MealActionRow(
|
||||||
|
claude: claude,
|
||||||
|
photoAttached: photo,
|
||||||
|
canSend: canSend,
|
||||||
|
canLog: canLog,
|
||||||
|
onPhoto: () => taps?.add('photo'),
|
||||||
|
onGallery: () => taps?.add('gallery'),
|
||||||
|
onRemovePhoto: () => taps?.add('remove'),
|
||||||
|
onSend: () => taps?.add('send'),
|
||||||
|
onLog: () => taps?.add('log'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
bool _enabled(WidgetTester tester, String label) {
|
||||||
|
final button = tester.widget<FilledButton>(
|
||||||
|
find.ancestor(of: byIconLabel(label), matching: find.byType(FilledButton)),
|
||||||
|
);
|
||||||
|
return button.onPressed != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('tap is the camera, long press is the gallery', (tester) async {
|
||||||
|
final taps = <String>[];
|
||||||
|
await tester.pumpWidget(_row(taps: taps));
|
||||||
|
await tester.tap(controlByLabel('Photo'));
|
||||||
|
await tester.longPress(controlByLabel('Photo'));
|
||||||
|
expect(taps, ['photo', 'gallery']);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('send and log are greyed with nothing to send or log', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.pumpWidget(_row(canSend: false, canLog: false));
|
||||||
|
expect(_enabled(tester, 'Ask Claude'), isFalse);
|
||||||
|
expect(_enabled(tester, 'Log meal'), isFalse);
|
||||||
|
expect(_enabled(tester, 'Photo'), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('an attached photo shows both badges and removes on the x', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final taps = <String>[];
|
||||||
|
await tester.pumpWidget(_row(photo: true, taps: taps));
|
||||||
|
expect(byIconLabel('Photo attached'), findsOneWidget);
|
||||||
|
await tester.tap(byIconLabel('Remove photo'));
|
||||||
|
expect(taps, ['remove']);
|
||||||
|
expect(find.byType(Image), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('no badges without a photo', (tester) async {
|
||||||
|
await tester.pumpWidget(_row());
|
||||||
|
expect(byIconLabel('Photo attached'), findsNothing);
|
||||||
|
expect(byIconLabel('Remove photo'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (final (state, label) in [
|
||||||
|
(ClaudeButtonState.queued, 'Waiting for the PC'),
|
||||||
|
(ClaudeButtonState.locked, 'Sync is locked'),
|
||||||
|
(ClaudeButtonState.error, 'Claude failed'),
|
||||||
|
]) {
|
||||||
|
testWidgets('$state paints its own glyph', (tester) async {
|
||||||
|
await tester.pumpWidget(_row(claude: state));
|
||||||
|
expect(byIconLabel(label), findsOneWidget);
|
||||||
|
expect(byIconLabel('Ask Claude'), findsNothing);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('sending shows a spinner and blocks a second send', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.pumpWidget(_row(claude: ClaudeButtonState.sending));
|
||||||
|
expect(find.byType(CircularProgressIndicator), findsOneWidget);
|
||||||
|
final send = tester.widget<FilledButton>(find.byType(FilledButton).at(1));
|
||||||
|
expect(send.onPressed, isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a locked or failed button can be tapped to retry', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final taps = <String>[];
|
||||||
|
await tester.pumpWidget(_row(claude: ClaudeButtonState.error, taps: taps));
|
||||||
|
await tester.tap(find.byType(FilledButton).at(1));
|
||||||
|
expect(taps, ['send']);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a logged row names the meal and undoes on a 48 dp button', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
var undone = 0;
|
||||||
|
const entry = FoodEntry(
|
||||||
|
id: 'a',
|
||||||
|
time: '2026-11-17T12:00:00',
|
||||||
|
desc: 'kurczak z ryzem',
|
||||||
|
grams: 300,
|
||||||
|
kcal: 540,
|
||||||
|
proteinG: 42,
|
||||||
|
carbsG: 61,
|
||||||
|
fatG: 9,
|
||||||
|
source: 'claude',
|
||||||
|
);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: LoggedMealRow(
|
||||||
|
meal: const LoggedMeal(entry, LoggedOrigin.claude),
|
||||||
|
onUndo: () => undone++,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(find.text('kurczak z ryzem'), findsOneWidget);
|
||||||
|
expect(find.text('540'), findsOneWidget);
|
||||||
|
expect(byIconLabel('Undo'), findsOneWidget);
|
||||||
|
final size = tester.getSize(find.byType(IconButton));
|
||||||
|
expect(size.width, 48);
|
||||||
|
expect(size.height, 48);
|
||||||
|
expect(find.byType(CircularProgressIndicator), findsNothing);
|
||||||
|
await tester.tap(byIconLabel('Undo'));
|
||||||
|
expect(undone, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the glyph tells where a logged meal came from', (tester) async {
|
||||||
|
const entry = FoodEntry(
|
||||||
|
id: 'a',
|
||||||
|
time: 't',
|
||||||
|
desc: 'x',
|
||||||
|
grams: 1,
|
||||||
|
kcal: 1,
|
||||||
|
proteinG: 1,
|
||||||
|
carbsG: 1,
|
||||||
|
fatG: 1,
|
||||||
|
source: 's',
|
||||||
|
);
|
||||||
|
for (final (origin, icon) in [
|
||||||
|
(LoggedOrigin.claude, Icons.auto_awesome),
|
||||||
|
(LoggedOrigin.catering, Icons.restaurant),
|
||||||
|
(LoggedOrigin.local, Icons.check_circle),
|
||||||
|
]) {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: LoggedMealRow(
|
||||||
|
meal: const LoggedMeal(entry, LoggedOrigin.claude),
|
||||||
|
onUndo: () {},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: LoggedMealRow(meal: LoggedMeal(entry, origin), onUndo: () {}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(find.byIcon(icon), findsOneWidget);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -14,31 +14,38 @@ PC switched off. The files map one-to-one:
|
|||||||
| `_kuchnia_parse.py` | `services/kuchnia_parse.dart` |
|
| `_kuchnia_parse.py` | `services/kuchnia_parse.dart` |
|
||||||
| `_kuchnia_spread.py` | `services/kuchnia_spread.dart` |
|
| `_kuchnia_spread.py` | `services/kuchnia_spread.dart` |
|
||||||
| `_kuchnia_import.py` | `services/kuchnia_import.dart` |
|
| `_kuchnia_import.py` | `services/kuchnia_import.dart` |
|
||||||
| `_gatelock_kuchnia.py` | `screens/log_meal_kuchnia_mixin.dart` + `services/kuchnia_queue.dart` |
|
| `_gatelock_kuchnia.py` | `services/kuchnia_queue.dart` (fetched-today marker; the form prefill is gone) |
|
||||||
| `_kuchnia_log.py` (`fill_plan`, `log_dishes`) | `services/kuchnia_fill.dart` |
|
| `_kuchnia_log.py` (`fill_plan`, `log_dishes`) | `services/kuchnia_fill.dart` |
|
||||||
| `_gatelock_fillall.py` | `services/kuchnia_fill_flow.dart` + `screens/log_meal_fill_mixin.dart` + `widgets/fill_all_row.dart` |
|
| `_gatelock_fillall.py` | `services/kuchnia_fill_flow.dart` (plan, no UI) + `services/kuchnia_autolog.dart` |
|
||||||
|
|
||||||
### "🍱 Fill all with catering"
|
### Auto-log (replaces "Fill all" on the phone)
|
||||||
|
|
||||||
The PC gate's Fill all, on the log screen under "Today's delivery". Two taps,
|
kuhy overrode "delivered is not eaten" on 2026-11-17 ("LOG EVEN WITHOUT TAP").
|
||||||
never one: the first fetches (unguarded, like the delivery button) and shows
|
When the log screen opens or resumes with a slot due, `KuchniaAutoLog.logDue`
|
||||||
"Will log N (X kcal): HH:00 dish, …" while the button reads "✓ Confirm (N)";
|
fetches today's delivery and logs the dishes assigned to the **due** slots, no
|
||||||
only the second writes. Cancel disarms. No modal.
|
tap. The Fill all button, its confirm tap and the delivery prefill are gone
|
||||||
|
from the phone; `FillAllFlow` stays as the tested plan logic.
|
||||||
|
|
||||||
- **Every slot today, later ones included, skipping occupied slots.** `fillPlan`
|
- **Plan = Fill all's plan minus the tap:** `assignSlots` by the caterer's
|
||||||
takes occupancy as an argument (Python reads `today_entries()` itself), read
|
`mealPriority` against the user's schedule, `fillPlan` over occupied slots,
|
||||||
once per batch so two dishes spread into one empty slot both land. Confirm
|
then only the due slots. Written by `logDishes`, source `kuchnia wikinga`.
|
||||||
re-reads it: a meal logged between the taps keeps its slot.
|
- **Deterministic ids.** UUID v5, namespace `6ba7b811-9dad-11d1-80b4-00c04fd430c8`
|
||||||
- **The plan is pinned to the day of the first tap.** A tap after midnight
|
(RFC URL), over `kuchnia:<delivery date YYYY-MM-DD>:<dishKey>`; `dishKey` is
|
||||||
refetches instead of confirming yesterday's menu into today.
|
the panel's `deliveryMealId` as a string, else the dish's bank key. A repeat
|
||||||
- **Entries match a submitted prefill** (`nutritionForPortion` with no "per"
|
open and every other device derive the same id, so the merge keeps one entry.
|
||||||
basis, so the same 0.1 rounding) except for the source, `kuchnia wikinga`,
|
`tests/fixtures/kuchnia_autolog_ids.json` (made by Python's `uuid.uuid5`,
|
||||||
the PC's tag. The prefill still tags its entries `catering`.
|
`scripts/build_kuchnia_autolog_fixture.py`) pins it for both languages.
|
||||||
- **One publish per batch** (`publishAfterLog`, shared with the manual submit):
|
- **Undo is a tombstone and it sticks.** `logMeal(id:)` and `logDishes(idFor:)`
|
||||||
`autoSync` is single-flight, so publishing per dish would drop the later
|
skip an id that exists in the full log, deleted entries included; otherwise
|
||||||
pushes.
|
undo plus the next resume would log the dish again.
|
||||||
- Filled dishes leave the delivery queue, and a prefilled form holding one of
|
- **The fetch is cached.** `KuchniaQueueService.refreshOnce` returns nothing
|
||||||
them is cleared, so it cannot be submitted a second time.
|
after the day's first clean fetch, so a slot falling due at 12:00 would never
|
||||||
|
see its dish. `KuchniaAutoLog` keeps the day's dishes in memory and retries a
|
||||||
|
failed or empty fetch at most every 10 minutes (a login per try).
|
||||||
|
- Each logged dish shows as a row: restaurant glyph, name, kcal and macro
|
||||||
|
dots, a 48 dp undo. One publish per batch (`publishAfterLog`).
|
||||||
|
- Unverified: whether `deliveryMealId` is stable across fetches on the live
|
||||||
|
panel (the fixtures carry scrubbed synthetic ids).
|
||||||
|
|
||||||
**Android only.** The panel sends no CORS headers, so a browser cannot call it;
|
**Android only.** The panel sends no CORS headers, so a browser cannot call it;
|
||||||
`refreshDelivery` checks `kIsWeb` first and returns a reason. The settings
|
`refreshDelivery` checks `kIsWeb` first and returns a reason. The settings
|
||||||
|
|||||||
@ -6,11 +6,11 @@ keypress instead of five retyped numbers.
|
|||||||
|
|
||||||
## What it does, and deliberately does not
|
## What it does, and deliberately does not
|
||||||
|
|
||||||
**A delivered meal is not an eaten meal.** Dishes land in the *curated* food
|
**Override 2026-11-17: delivered counts as eaten.** kuhy ("LOG EVEN WITHOUT
|
||||||
bank; entries are only ever written after an explicit confirmation. If the
|
TAP") dropped the confirm-tap rule: the phone logs the due slots' dishes on
|
||||||
importer logged automatically, the gate would satisfy its own checkpoint from a
|
open ([phone doc](DOCS-kuchnia-wikinga-phone.md)), under deterministic ids with
|
||||||
delivery note, and the log would record what the courier dropped off rather than
|
an undo row. The bullets below describe the PC gate as it still is until the
|
||||||
what was eaten — skipped, shared and binned meals included.
|
Python side follows; the import itself still only banks dishes.
|
||||||
|
|
||||||
So:
|
So:
|
||||||
|
|
||||||
|
|||||||
62
docs/DOCS-log-screen.md
Normal file
62
docs/DOCS-log-screen.md
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
# The phone's log screen
|
||||||
|
|
||||||
|
`app/lib/screens/log_meal_screen.dart` and its mixins. Approved design: kuhy,
|
||||||
|
2026-11-17, mockup variant 1A. **No painted words**: every control is an icon.
|
||||||
|
|
||||||
|
## Two modes
|
||||||
|
|
||||||
|
- **Due mode** (`missingSlots` is non-empty): no app bar, sync banner, date row,
|
||||||
|
slot chips or Fill all; the Android status bar is hidden (immersive) and put
|
||||||
|
back on exit and on `dispose`. `main.dart` sets no system-UI mode, so "back"
|
||||||
|
means both bars visible. Only the food field, a fixed-height suggestion block,
|
||||||
|
the macro fields (2 rows of 3) and the action row remain.
|
||||||
|
- **Normal mode** (nothing due): the old screen minus the slot chips and Fill
|
||||||
|
all, plus the same action row. Notifications are unchanged.
|
||||||
|
|
||||||
|
Until the first read of today's log the screen draws neither (no app-bar flash).
|
||||||
|
`logMealClock` (`log_meal_due_mixin.dart`) is the clock; the suite pins it to
|
||||||
|
07:00 in `flutter_test_config.dart`, and a test needing due mode calls
|
||||||
|
`pinLogMealClock`.
|
||||||
|
|
||||||
|
## Slot targeting
|
||||||
|
|
||||||
|
No slot picker. Due mode: both the check and the sparkle target the **oldest
|
||||||
|
due slot** (`dueSlots.first`). Normal mode: `slotForLog` (nearest). The integer
|
||||||
|
slot maths in `models/slot.dart` is untouched. A *future* date (the date row,
|
||||||
|
normal mode only) keeps its own slot row, because it has no due slots to derive
|
||||||
|
from.
|
||||||
|
|
||||||
|
## The action row (1A)
|
||||||
|
|
||||||
|
Photo (blue; tap = camera, long press = gallery; attached = tinted with a check
|
||||||
|
badge and a remove badge, **never a thumbnail**), Claude (gold sparkle), log
|
||||||
|
(green check). Sparkle and check are greyed until there is text (or, for the
|
||||||
|
sparkle, a photo). The sparkle shows a spinner while sending, an hourglass when
|
||||||
|
queued (PC offline), a lock when sync is locked, an error glyph on failure
|
||||||
|
(a tap retries).
|
||||||
|
|
||||||
|
**The food field never moves.** Spinners, logged rows and cues go *below* the
|
||||||
|
action row. `log_meal_geometry_test.dart` asserts, on 1080x2400 at 2.625 with
|
||||||
|
the Pixel insets and a 320 dp keyboard, that the field's top is identical in
|
||||||
|
every state and `maxScrollExtent == 0`. Macro values of four digits must paint
|
||||||
|
whole at 16 sp or more (`macro_input_row_test.dart` measures the digits; a
|
||||||
|
`Row` of `Expanded` fields clips them without any exception).
|
||||||
|
|
||||||
|
## Logged rows and undo
|
||||||
|
|
||||||
|
After a Claude, check or catering log, a row (origin glyph, name, kcal and macro
|
||||||
|
dots, a 48 dp round undo, no countdown) shows under the action row until the
|
||||||
|
next meal is logged. Undo is `deleteEntry(id)` plus `publishAfterLog`, a
|
||||||
|
tombstone by id (several rows can be on screen, so not `undoLastToday`).
|
||||||
|
|
||||||
|
## Claude and photos
|
||||||
|
|
||||||
|
The sparkle talks to `ClaudeRelayClient` (`services/claude_relay_client.dart`),
|
||||||
|
injectable; `FakeClaudeRelayClient` drives the tests. The request id becomes the
|
||||||
|
logged entry's id. A photo is **transient input**: `image_picker` scales it to
|
||||||
|
1024 px JPEG, the bytes are read into memory and the plugin's cache file is
|
||||||
|
deleted at once (`meal_photo_cleanup_io.dart`). It is never stored, put on a
|
||||||
|
`FoodEntry`, or synced; `repo_invariants_test.dart` asserts it structurally. The
|
||||||
|
camera runtime permission is requested before the camera opens.
|
||||||
|
|
||||||
|
Catering auto-log: [DOCS-kuchnia-wikinga-phone.md](DOCS-kuchnia-wikinga-phone.md).
|
||||||
@ -28,7 +28,6 @@ notification shows only the slot clock time and has no body.
|
|||||||
|
|
||||||
| Where | Text | Evidence |
|
| Where | Text | Evidence |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `app/lib/screens/log_meal_fill_mixin.dart` | fill failed / cancelled sentences | handed to `StatusCue` as the semantic label; the cue paints a glyph and a count |
|
|
||||||
| `app/lib/services/kuchnia_fill_flow.dart` | delivery and logged sentences | `FillOutcome.message`, same route; `no_words_kuchnia_test.dart` proves the snackbar paints a glyph and a number |
|
| `app/lib/services/kuchnia_fill_flow.dart` | delivery and logged sentences | `FillOutcome.message`, same route; `no_words_kuchnia_test.dart` proves the snackbar paints a glyph and a number |
|
||||||
|
|
||||||
## Read by Claude, not by kuhy
|
## Read by Claude, not by kuhy
|
||||||
|
|||||||
105
scripts/build_kuchnia_autolog_fixture.py
Executable file
105
scripts/build_kuchnia_autolog_fixture.py
Executable file
@ -0,0 +1,105 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regenerate the shared catering auto-log id fixture.
|
||||||
|
|
||||||
|
The fixture (``tests/fixtures/kuchnia_autolog_ids.json``) pins the entry id the
|
||||||
|
phone gives a catering dish it logs by itself. Each id is a UUID v5 over the
|
||||||
|
RFC 4122 URL namespace (``6ba7b811-9dad-11d1-80b4-00c04fd430c8``) of the string
|
||||||
|
``kuchnia:<deliveryDate YYYY-MM-DD>:<dishKey>``, so a repeat open and every
|
||||||
|
other device derive the same id and the merge collapses them to one entry.
|
||||||
|
|
||||||
|
``dishKey`` is the panel's ``deliveryMealId`` as a string (an int, or a
|
||||||
|
stripped string). Anything else, or a blank one, falls back to the dish's bank
|
||||||
|
key (name, stripped, lower-cased). The fallback cases use ASCII names only,
|
||||||
|
because ``str.casefold`` and Dart's ``toLowerCase`` agree there and diverge on
|
||||||
|
a few exotic characters.
|
||||||
|
|
||||||
|
The expected ids come from Python's stdlib ``uuid.uuid5`` on purpose: the Dart
|
||||||
|
test must reproduce a value it did not compute itself.
|
||||||
|
|
||||||
|
Run from the repo root:
|
||||||
|
|
||||||
|
python3 scripts/build_kuchnia_autolog_fixture.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
FIXTURE = (
|
||||||
|
Path(__file__).resolve().parent.parent / "tests/fixtures/kuchnia_autolog_ids.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
#: (delivery date, raw ``deliveryMealId`` or None, dish name)
|
||||||
|
_CASES: list[tuple[str, object, str]] = [
|
||||||
|
("2026-11-17", 1001, "Marchewkowe pancakes"),
|
||||||
|
("2026-11-17", 1002, "Hummus paprykowy"),
|
||||||
|
("2026-11-18", 1001, "Marchewkowe pancakes"),
|
||||||
|
("2026-11-17", "A-77", "String id dish"),
|
||||||
|
("2026-11-17", " A-77 ", "Padded id dish"),
|
||||||
|
("2026-11-17", True, "Bool id dish"),
|
||||||
|
("2026-11-17", 1001.0, "Float id dish"),
|
||||||
|
("2026-11-17", "", "Empty id dish"),
|
||||||
|
("2026-11-17", None, " No Id Dish "),
|
||||||
|
("2026-01-02", 9, "Zupa"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _dish_key(meal_id: object, name: str) -> str:
|
||||||
|
"""The dish half of the id string, by the same rule as the Dart port.
|
||||||
|
|
||||||
|
An ``int`` becomes its decimal string; a ``str`` is stripped. Everything
|
||||||
|
else (``bool``, a float such as ``1001.0``, an empty or blank string, a
|
||||||
|
missing id) falls back to the bank key. ``bool`` is tested first because
|
||||||
|
``isinstance(True, int)`` is true in Python and not in Dart.
|
||||||
|
"""
|
||||||
|
key = ""
|
||||||
|
if isinstance(meal_id, bool):
|
||||||
|
key = ""
|
||||||
|
elif isinstance(meal_id, int):
|
||||||
|
key = str(meal_id)
|
||||||
|
elif isinstance(meal_id, str):
|
||||||
|
key = meal_id.strip()
|
||||||
|
return key or name.strip().lower()
|
||||||
|
|
||||||
|
|
||||||
|
def build() -> dict[str, object]:
|
||||||
|
"""Return the fixture document."""
|
||||||
|
cases = []
|
||||||
|
for date, meal_id, name in _CASES:
|
||||||
|
key = _dish_key(meal_id, name)
|
||||||
|
cases.append(
|
||||||
|
{
|
||||||
|
"delivery_date": date,
|
||||||
|
"delivery_meal_id": meal_id,
|
||||||
|
"name": name,
|
||||||
|
"dish_key": key,
|
||||||
|
"name_string": f"kuchnia:{date}:{key}",
|
||||||
|
"expected_id": str(
|
||||||
|
uuid.uuid5(uuid.NAMESPACE_URL, f"kuchnia:{date}:{key}")
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"_comment": (
|
||||||
|
"Shared catering auto-log id fixture. Read by "
|
||||||
|
"app/test/services/kuchnia_autolog_ids_test.dart (and the Python "
|
||||||
|
"side later). Regenerate with "
|
||||||
|
"scripts/build_kuchnia_autolog_fixture.py."
|
||||||
|
),
|
||||||
|
"namespace": str(uuid.NAMESPACE_URL),
|
||||||
|
"cases": cases,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""Write the fixture."""
|
||||||
|
FIXTURE.write_text(
|
||||||
|
json.dumps(build(), indent=2, ensure_ascii=False) + "\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
86
tests/fixtures/kuchnia_autolog_ids.json
vendored
Normal file
86
tests/fixtures/kuchnia_autolog_ids.json
vendored
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
{
|
||||||
|
"_comment": "Shared catering auto-log id fixture. Read by app/test/services/kuchnia_autolog_ids_test.dart (and the Python side later). Regenerate with scripts/build_kuchnia_autolog_fixture.py.",
|
||||||
|
"namespace": "6ba7b811-9dad-11d1-80b4-00c04fd430c8",
|
||||||
|
"cases": [
|
||||||
|
{
|
||||||
|
"delivery_date": "2026-11-17",
|
||||||
|
"delivery_meal_id": 1001,
|
||||||
|
"name": "Marchewkowe pancakes",
|
||||||
|
"dish_key": "1001",
|
||||||
|
"name_string": "kuchnia:2026-11-17:1001",
|
||||||
|
"expected_id": "643aabb5-0953-5dba-89a4-87edffc92061"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"delivery_date": "2026-11-17",
|
||||||
|
"delivery_meal_id": 1002,
|
||||||
|
"name": "Hummus paprykowy",
|
||||||
|
"dish_key": "1002",
|
||||||
|
"name_string": "kuchnia:2026-11-17:1002",
|
||||||
|
"expected_id": "e6c75895-3050-54bf-9f2e-72b476925820"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"delivery_date": "2026-11-18",
|
||||||
|
"delivery_meal_id": 1001,
|
||||||
|
"name": "Marchewkowe pancakes",
|
||||||
|
"dish_key": "1001",
|
||||||
|
"name_string": "kuchnia:2026-11-18:1001",
|
||||||
|
"expected_id": "11ba0c49-7c5e-5d85-9cf8-b32ab0cf9d41"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"delivery_date": "2026-11-17",
|
||||||
|
"delivery_meal_id": "A-77",
|
||||||
|
"name": "String id dish",
|
||||||
|
"dish_key": "A-77",
|
||||||
|
"name_string": "kuchnia:2026-11-17:A-77",
|
||||||
|
"expected_id": "66f586bf-0da6-5f05-b14c-ec56e9165f72"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"delivery_date": "2026-11-17",
|
||||||
|
"delivery_meal_id": " A-77 ",
|
||||||
|
"name": "Padded id dish",
|
||||||
|
"dish_key": "A-77",
|
||||||
|
"name_string": "kuchnia:2026-11-17:A-77",
|
||||||
|
"expected_id": "66f586bf-0da6-5f05-b14c-ec56e9165f72"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"delivery_date": "2026-11-17",
|
||||||
|
"delivery_meal_id": true,
|
||||||
|
"name": "Bool id dish",
|
||||||
|
"dish_key": "bool id dish",
|
||||||
|
"name_string": "kuchnia:2026-11-17:bool id dish",
|
||||||
|
"expected_id": "a893963c-99ad-5aa5-83fb-3f03a654568f"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"delivery_date": "2026-11-17",
|
||||||
|
"delivery_meal_id": 1001.0,
|
||||||
|
"name": "Float id dish",
|
||||||
|
"dish_key": "float id dish",
|
||||||
|
"name_string": "kuchnia:2026-11-17:float id dish",
|
||||||
|
"expected_id": "45f4f56d-5a5f-59ba-9afc-fac44442db09"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"delivery_date": "2026-11-17",
|
||||||
|
"delivery_meal_id": "",
|
||||||
|
"name": "Empty id dish",
|
||||||
|
"dish_key": "empty id dish",
|
||||||
|
"name_string": "kuchnia:2026-11-17:empty id dish",
|
||||||
|
"expected_id": "2434643a-112f-509a-a8b3-eb5bb5cbbcf9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"delivery_date": "2026-11-17",
|
||||||
|
"delivery_meal_id": null,
|
||||||
|
"name": " No Id Dish ",
|
||||||
|
"dish_key": "no id dish",
|
||||||
|
"name_string": "kuchnia:2026-11-17:no id dish",
|
||||||
|
"expected_id": "1eba71d4-1786-584a-b60c-8d2a4576c04b"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"delivery_date": "2026-01-02",
|
||||||
|
"delivery_meal_id": 9,
|
||||||
|
"name": "Zupa",
|
||||||
|
"dish_key": "9",
|
||||||
|
"name_string": "kuchnia:2026-01-02:9",
|
||||||
|
"expected_id": "dd51fed4-1260-5129-bda1-91e0ff8e9ac1"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user