Compare commits

...

12 Commits

Author SHA1 Message Date
f2606fe0ca deps: flutter 3.47.7, crdt-sync 0.9.2, freedays 0.3.1, pydantic 2.14.0, ruff 0.17.0
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled
ruff 0.17 stabilised CPY001 (ignored: no per-file copyright headers here),
ISC004 and ICN001 (autofixed).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:27:52 +02:00
a118120047 Merge branch 'worktree-agent-a92471b85d4d17556' into minute-slots 2026-10-10 20:13:41 +02:00
2d468bf5f8 gate: HH:MM spinboxes instead of comboboxes for the meal schedule
An inert dropdown arrow looked broken. ttk.Spinbox posts nothing; every
spin path (arrow press, Up/Down, wheel) generates <<Increment>>/
<<Decrement>>, bound here to step_time from the typed value (07:23 -> up
07:30, down 07:15) with "break" so ttk's values/wrap logic never runs.
First clamps to 00:00-23:45, last to 00:15-23:45. Popdown-blocking code
removed; FakeSpinbox replaces FakeCombobox.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:13:03 +02:00
cb8028bd22 app settings: exact-time clock button replaces the "Custom…" item
The dropdown menu opens centred on the current value, so a "Custom…" item
at either end of ~95 entries was always a long scroll away. Each meal-time
field now has a clock IconButton ("Type or pick an exact time") opening the
same 24h showTimePicker with the same clamping. The off-grid current value
is still offered as an item.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:10:55 +02:00
6dd52a11ae slots: never post the schedule combobox list; kuchnia dedup on raw minute
- The popdown maps beneath the gatelock surface yet holds ttk's grab
  (verified on Xvfb: invisible, swallows the next click, steals keys), so
  arrow clicks are intercepted as Down already was. Typing and Up/Down stay.
- Catering dedup compares the entry's recorded minute (parity with the
  app); occupancy (fill_plan) still snaps.
- Test: a corrupt peer slot (slot 24, slot_min 5000) re-signs and reads
  without raising.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:06:16 +02:00
b2176f8b69 app settings: "Custom…" first in the meal-time dropdowns
At the end of the list it sat ~95 grid items down; now it is the first
item, above 00:00. Test pins the order.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:04:19 +02:00
a9aa379a13 app tests: off-hour schedule round trips + real settings wiring
Pins that fm/lm survive both the sync wire and a disk reload, and that a
quarter-hour pick in SettingsScreen goes through the real _applySchedule.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 20:00:45 +02:00
4e5c6b453e docs: the schedule combobox popdown maps beneath the lock surface
Observed on Xvfb with the demo gate: the ComboboxPopdown is viewable but
stacked under the gatelock surface, so typing and Up/Down are the paths.

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

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 19:55:26 +02:00
c310861855 slots: minute-of-day consumers (phase 2 of 3: Python side)
Every Python consumer now speaks slot minutes:

- satisfaction is nearest-slot snapping (_slot_wire.satisfied_by_entries)
  at every "is this slot logged?" site: gate, CLI status, MCP, catering
  occupancy and dedup. Nothing on disk is rewritten; 07:00/10:00 entries
  keep covering 07:15/10:15 after a schedule move.
- log_meal writes slot_fields(minute) before signing (slot + slot_min).
- schedule store and sync encode via schedule_to_wire/from_wire; a
  whole-hour schedule stays byte-identical (f/l/n only).
- CLI ate --hour takes HH or HH:MM; MCP log_meal takes "HH:MM" or a
  legacy int hour, validated against today's slots; get_slots returns
  {minute, label}.
- gate History tab: first/last are HH:MM ttk.Comboboxes (quarter-hour
  list, typed times, Up/Down step without posting the popdown), locked
  as disabled; validation mirrors normalized().
- gate timer fires every 15 min; docs rewritten for minutes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 19:53:39 +02:00
a6fcd3266e deps: idb_shim 2.9.11, shared_preferences 2.5.6
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 19:26:08 +02:00
8bc1812147 slots: minute-of-day contract (phase 1 of 3: pure model + shared fixture)
Meal-slot checkpoints move from whole hours to minute-of-day ints
(0..1439) in the pure model and slot arithmetic of both languages:
MealSchedule(first_minute, last_minute, count) / (firstMinute:,
lastMinute:, count:), interior slots snapped to the 15-minute grid,
endpoints exact, integer-only. New: nearest_slot, satisfied_slots,
slot_fields / entry_slot_minute (additive "slot_min" wire field) and
schedule_to_wire / schedule_from_wire ("fm"/"lm" only when off the hour,
so whole-hour data stays byte-identical), parse_hhmm.

tests/fixtures/meal_schedule_vectors.json (scripts/
build_meal_schedule_fixture.py) is read by both suites; kuchnia_day.json
slot values regenerated as minutes.

Consumers (CLI, gate, storage, sync, app screens, kuchnia, notifications)
are intentionally broken until phase 2. patch-targets skipped: it fails
only because diet_guard._gatelock no longer imports.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015npsYVB2PdtWkG7MPAi4tn
2026-10-10 19:22:43 +02:00
126 changed files with 8856 additions and 1604 deletions

2
.fvmrc
View File

@ -1,3 +1,3 @@
{
"flutter": "3.47.6"
"flutter": "3.47.7"
}

View File

@ -60,7 +60,7 @@ jobs:
- uses: subosito/flutter-action@v2
with:
flutter-version: 3.47.6
flutter-version: 3.47.7
channel: stable
cache: true

View File

@ -1,6 +1,6 @@
# CLAUDE.md — diet_guard
A log-to-unlock gate. Every ~30 min `diet-guard-gate.timer` checks whether a
A log-to-unlock gate. Every ~15 min `diet-guard-gate.timer` checks whether a
meal slot (08:00, 12:00, 16:00, 20:00 by default — the schedule is
user-configurable, see below) elapsed unlogged; if so it opens a
fullscreen Tk window that blocks the desktop until the user logs what they
@ -29,7 +29,7 @@ catch-up rule).
## Scheduling
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/30:00`,
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/15:00`,
`Persistent=true`), not boot-relative — a boot-relative timer collided with
fullscreen games grabbing input. `diet-guard-gate.service` is `Type=oneshot`
and exits 0 immediately when no lock is due. It needs `DISPLAY`/`XAUTHORITY`;
@ -178,13 +178,14 @@ changing either hides the entire local food log).
## The meal schedule
The slot hours are user-configurable: a first meal, a last meal, and how
many meals fall between them, evenly divided. Default `(8, 20, 4)` is the
old hardcoded 08/12/16/20. Four load-bearing rules (integer-only
arithmetic, whole-hour slots, the count clamp, the `last + 2h` cutoff), the
forward-only history, and the two edit surfaces are documented in
[docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) — read it before touching
`_slots.py` / `slot.dart`.
Slots are **minutes of day**: a first meal and a last meal (any `HH:MM`) and
how many meals fall between them; interior slots round to the 15-min grid.
Default `(480, 1200, 4)` is the old hardcoded 08/12/16/20. The load-bearing
rules (integer-only arithmetic, the additive `slot`+`slot_min` /
`f`/`l`/`n`+`fm`/`lm` wire, the count clamp, the `last + 120 min` cutoff,
nearest-slot satisfaction), the forward-only history, and the two edit
surfaces are in [docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) —
read it before touching `_slots.py` / `_slot_wire.py` / `slot.dart`.
## Averages (`_averages.py` / `average_service.dart`)

View File

@ -46,7 +46,7 @@ The band boundaries are the calendar's own (at or under budget / up to 20%
over / more than 20% over), so a period and its day cells can never disagree
about what "over" means.
The timer runs the gate automatically every ~30 minutes; no manual
The timer runs the gate automatically every ~15 minutes; no manual
invocation is needed once installed.
## MCP server

View File

@ -2,6 +2,8 @@
library;
import 'package:diet_guard_app/models/meal_component.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
/// One logged meal, as stored in `food_log.json` under its date key.
///
@ -20,7 +22,7 @@ class FoodEntry {
required this.fatG,
required this.source,
this.id,
this.slot,
this.slotMinute,
this.hmac,
this.components,
this.deleted = false,
@ -40,7 +42,7 @@ class FoodEntry {
carbsG: (json['carbs_g'] as num?)?.toDouble() ?? 0,
fatG: (json['fat_g'] as num?)?.toDouble() ?? 0,
source: json['source'] as String? ?? 'manual',
slot: json['slot'] as int?,
slotMinute: entrySlotMinute(json),
hmac: json['hmac'] as String?,
components: (json['components'] as List?)
?.cast<Map<String, dynamic>>()
@ -79,16 +81,26 @@ class FoodEntry {
/// Provenance label (e.g. `"manual"`, `"food bank"`, `"meal"`).
final String source;
/// The meal-slot hour this entry satisfies (8/12/16/20), or null for a
/// snack that counts toward calories but satisfies no slot.
/// The meal-slot minute of day this entry was logged against (480 for
/// 08:00, 435 for 07:15), or null for a snack that satisfies no slot.
///
/// A *recorded* minute, not a live checkpoint: which slot it satisfies is
/// decided at read time by `satisfiedSlots`, so an entry written under an
/// older schedule still counts after the schedule moves.
///
/// Read through `entrySlotMinute` (`slot_min` wins, else `slot` x 60) and
/// written back through `slotFields`, so a PC entry carrying `slot_min`
/// survives a round trip through this device. Keeping only the hour would
/// make every edit or tombstone republish a stripped copy, and the merge
/// would spread that lossy copy back to the PC.
///
/// Nothing writes null any more -- the "Snack" chip was removed on
/// 2026-08-14 and every remaining writer resolves a concrete hour through
/// 2026-08-14 and every remaining writer resolves a concrete slot through
/// `slotForLog`/`slot_for_log` -- but entries already on disk and arriving
/// over sync still carry no `slot` key, so the null case and every
/// `slot != null` filter built on it are load-bearing. Dropping them would
/// make those historical entries retroactively satisfy meal slots.
final int? slot;
final int? slotMinute;
/// HMAC signature, present on entries that have passed through the PC's
/// signing step. Never computed on the phone -- it never holds the key.
@ -122,7 +134,7 @@ class FoodEntry {
'carbs_g': carbsG,
'fat_g': fatG,
'source': source,
if (slot != null) 'slot': slot,
..._slotJson(slotMinute),
if (components != null)
'components': components!.map((c) => c.toJson()).toList(),
if (deleted) 'deleted': true,
@ -139,9 +151,26 @@ class FoodEntry {
carbsG: carbsG,
fatG: fatG,
source: source,
slot: slot,
slotMinute: slotMinute,
hmac: hmac,
components: components,
deleted: true,
);
}
/// Returns the wire fields for [minute], total over every value it can hold.
///
/// [slotFields] throws outside the day, but [entrySlotMinute] does not
/// range-check what a peer sent. A single `slot: 24` arriving over sync would
/// otherwise make every later `writeLog` throw -- one bad entry blocking all
/// logging. Such a value is echoed back unrepaired, by the same whole-hour
/// rule (so a legacy `slot: 24` stays byte-identical), with `~/` only on a
/// non-negative operand -- a negative value travels as `slot_min` alone.
Map<String, int> _slotJson(int? minute) {
if (minute == null) return const {};
if (minute >= 0 && minute < kMinutesPerDay) return slotFields(minute);
return {
if (minute >= 0) 'slot': minute ~/ 60,
if (minute < 0 || minute % 60 != 0) 'slot_min': minute,
};
}

View File

@ -1,9 +1,15 @@
/// The user's eating window and meal count, and the slot hours they imply.
/// The user's eating window and meal count, and the slot minutes they imply.
///
/// A schedule is three numbers -- the first meal hour, the last meal hour, and
/// how many meals fall between them inclusive -- from which the intermediate
/// checkpoints are derived by even division. `MealSchedule(8, 20, 5)` yields
/// `[8, 11, 14, 17, 20]`.
/// A schedule is three numbers -- the first meal's minute of day, the last
/// meal's minute of day, and how many meals fall between them inclusive --
/// from which the intermediate checkpoints are derived by even division and
/// rounded to the 15-minute grid. `MealSchedule(firstMinute: 480,
/// lastMinute: 1200, count: 5)` yields `[480, 660, 840, 1020, 1200]`.
///
/// Every time here is a *minute of day*, an int in `0..1439`. The fields are
/// deliberately named `firstMinute`/`lastMinute` rather than reusing the old
/// hour-valued `first`/`last`, so `flutter analyze` enumerates every call site
/// that still thinks in hours.
///
/// This file is pure: no clock, no storage, no settings lookup. Persistence
/// lives in `services/meal_schedule_service.dart`, and the slot arithmetic
@ -12,13 +18,17 @@
/// KEEP IN SYNC WITH `diet_guard/_meal_schedule.py`. The two must agree on
/// every input, because a device that derives different slots than its peer
/// nags for checkpoints the other never offers -- and a slot that can never be
/// satisfied is a permanent lock. Two rules make that agreement checkable:
/// satisfied is a permanent lock. `tests/fixtures/meal_schedule_vectors.json`
/// is read by both test suites; three rules make that agreement checkable:
///
/// * **Integer arithmetic only.** No doubles and no `round()` anywhere in the
/// derivation. Dart's `round()` is half-away-from-zero (`2.5.round() == 3`)
/// while Python's is banker's rounding (`round(2.5) == 2`), so any
/// floating-point path is a latent cross-language split brain. `~/` here,
/// `//` there.
/// * **Non-negative operands to every division.** `~/` truncates while
/// Python's `//` floors (`-7 ~/ 15 == 0`, `-7 // 15 == -1`). Every division
/// below runs on a value [MealSchedule.normalized] has pulled into the day.
/// * **Clamp, don't reject.** Every out-of-range input is normalised to the
/// nearest legal schedule rather than throwing, so the two languages cannot
/// disagree about which inputs are errors.
@ -36,11 +46,16 @@ const int kMinMealCount = 2;
/// `test/widgets/slot_selector_row_test.dart`.
const int kMaxMealCount = 6;
/// Earliest hour a meal may be scheduled at.
const int kFirstHour = 0;
/// Minutes in a day; a minute of day is `0..kMinutesPerDay - 1`.
const int kMinutesPerDay = 1440;
/// Latest hour a meal may be scheduled at.
const int kLastHour = 23;
/// Minimum spacing between two checkpoints, and the grid interior checkpoints
/// are rounded onto.
///
/// One constant for both is what makes the strict-ascent proof in
/// [MealSchedule.slots] work: points at least one grid step apart cannot round
/// onto the same grid mark.
const int kSlotGridMinutes = 15;
/// Grace period after the final checkpoint, before the gate stops firing.
///
@ -48,9 +63,9 @@ const int kLastHour = 23;
/// have to log a late dinner, which has nothing to do with how many meals you
/// eat. Tying it to the spacing would stretch the lockout window to midnight
/// at four meals, contradicting the "don't trap me overnight" intent.
const int kEnforcementTailHours = 2;
const int kEnforcementTailMinutes = 120;
const int _hoursPerDay = 24;
const int _lastMinute = kMinutesPerDay - 1;
int _clamp(int value, int low, int high) =>
value < low ? low : (value > high ? high : value);
@ -60,95 +75,142 @@ int _clamp(int value, int low, int high) =>
class MealSchedule {
/// Creates a [MealSchedule].
const MealSchedule({
required this.first,
required this.last,
required this.firstMinute,
required this.lastMinute,
required this.count,
});
/// Hour of the first meal, 0-23.
final int first;
/// Minute of day of the first meal, 0-1424.
final int firstMinute;
/// Hour of the last meal, strictly after [first].
final int last;
/// Minute of day of the last meal, at least one grid step (15 minutes) after
/// [firstMinute] and at most 1439.
final int lastMinute;
/// Total meals including both endpoints.
final int count;
/// Returns an equivalent schedule guaranteed to satisfy the invariants.
///
/// Ordering matters: [first] is clamped into the day, then [last] is clamped
/// to leave at least one hour of window, then [count] is clamped to the
/// window's width. That last clamp is the load-bearing one -- see [slots].
/// Ordering matters: [firstMinute] is clamped into the day leaving room for
/// one grid step, then [lastMinute] is clamped to at least one grid step
/// after it, then [count] is clamped to how many grid-spaced checkpoints the
/// window holds. That last clamp is the load-bearing one -- see [slots].
MealSchedule normalized() {
final normFirst = _clamp(first, kFirstHour, kLastHour - 1);
final normLast = _clamp(last, normFirst + 1, kLastHour);
// A window of N hours holds at most N+1 whole-hour checkpoints; asking for
// more would repeat an hour (see slots()).
final first = _clamp(firstMinute, 0, _lastMinute - kSlotGridMinutes);
final last = _clamp(lastMinute, first + kSlotGridMinutes, _lastMinute);
// A window of W minutes holds at most W ~/ 15 + 1 checkpoints spaced a
// grid step apart; asking for more would round two onto one mark.
final capacity = (last - first) ~/ kSlotGridMinutes + 1;
final normCount = _clamp(
count,
kMinMealCount,
kMaxMealCount < normLast - normFirst + 1
? kMaxMealCount
: normLast - normFirst + 1,
kMaxMealCount < capacity ? kMaxMealCount : capacity,
);
return MealSchedule(first: normFirst, last: normLast, count: normCount);
return MealSchedule(firstMinute: first, lastMinute: last, count: normCount);
}
/// Returns the meal-slot hours, ascending, with both endpoints exact.
/// Returns the meal-slot minutes, ascending, with both endpoints exact.
///
/// Meals are spread evenly across the window and rounded to whole hours by
/// integer arithmetic: slot *i* is `first + (i*span + d ~/ 2) ~/ d` where
/// `span = last - first` and `d = count - 1`. The `d ~/ 2` term is a
/// round-half-up bias applied before the division, which is what keeps this
/// free of floating point.
/// With `span = last - first` and `d = count - 1`, interior slot *i* is
/// `raw = first + (i*span + d ~/ 2) ~/ d` (even division, the `d ~/ 2` term
/// a round-half-up bias that keeps it free of floating point), then snapped
/// to the nearest absolute quarter hour by `(raw + 7) ~/ 15 * 15`. The
/// endpoints are [firstMinute] and [lastMinute] exactly -- never snapped.
///
/// Both endpoints land exactly on [first] and [last] by construction, so the
/// eating window is always honoured even when interior spacing must round.
///
/// The result is strictly ascending because [normalized] caps [count] at
/// `last - first + 1`. Without that cap a narrow window repeats an hour
/// (`08-12` with 6 meals would give `8, 9, 10, 10, 11, 12`), and since slot
/// hours are used as set members, map keys *and* notification ids, a repeat
/// silently drops a checkpoint.
/// Strictly ascending, provably: [normalized] caps [count] so that
/// `span / d >= 15`, hence consecutive `raw` values differ by at least 15,
/// and two integers at least 15 apart never snap onto the same grid mark.
/// Snapping moves a value by at most 7, so no interior slot can reach an
/// endpoint. That matters because slot minutes are set members, map keys
/// *and* notification ids: a repeat silently drops a checkpoint.
List<int> slots() {
final schedule = normalized();
final span = schedule.last - schedule.first;
final first = schedule.firstMinute;
final last = schedule.lastMinute;
final span = last - first;
final divisions = schedule.count - 1;
return [
for (var index = 0; index < schedule.count; index++)
schedule.first + (index * span + divisions ~/ 2) ~/ divisions,
first,
for (var index = 1; index < divisions; index++)
(first + (index * span + divisions ~/ 2) ~/ divisions + 7) ~/
kSlotGridMinutes *
kSlotGridMinutes,
last,
];
}
/// The hour at which slot enforcement stops for the day.
/// The minute at which slot enforcement stops for the day.
///
/// Clamped to the end of the day: a 23:00 last meal would otherwise put the
/// cutoff at 25, making `hour < cutoff` vacuously true so the enforcement
/// window never closes and the reminder can never stop firing.
int get enforcementEndHour {
final end = last + kEnforcementTailHours;
return end < _hoursPerDay ? end : _hoursPerDay;
/// Derived from the *normalised* last meal, so it always agrees with the
/// last entry of [slots]. Clamped to the end of the day: a 23:00 last meal
/// would otherwise put the cutoff at 1500, making `minute < cutoff`
/// vacuously true so the enforcement window never closes.
int get enforcementEndMinute {
final end = normalized().lastMinute + kEnforcementTailMinutes;
return end < kMinutesPerDay ? end : kMinutesPerDay;
}
@override
bool operator ==(Object other) =>
other is MealSchedule &&
other.first == first &&
other.last == last &&
other.firstMinute == firstMinute &&
other.lastMinute == lastMinute &&
other.count == count;
@override
int get hashCode => Object.hash(first, last, count);
int get hashCode => Object.hash(firstMinute, lastMinute, count);
@override
String toString() => 'MealSchedule($first-$last x$count)';
String toString() => 'MealSchedule($firstMinute-$lastMinute x$count)';
}
/// The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, enforcement
/// closing at 22:00. Still what a device uses before the user has chosen
/// anything, so upgrading changes no behaviour.
const MealSchedule kDefaultSchedule = MealSchedule(
first: 8,
last: 20,
firstMinute: 8 * 60,
lastMinute: 20 * 60,
count: 4,
);
/// Returns the synced `sched:<date>` value for [schedule].
///
/// Mirrors `_meal_schedule.schedule_to_wire`. Backward compatible by
/// construction: `f`/`l` carry whole hours exactly as before the move to
/// minutes, and `fm`/`lm` appear only when an endpoint is off the hour, so a
/// whole-hour schedule encodes byte-identically to the old `{f, l, n}` form.
/// Normalised first, so every `~/` runs on a non-negative value.
Map<String, int> scheduleToWire(MealSchedule schedule) {
final norm = schedule.normalized();
final first = norm.firstMinute;
final last = norm.lastMinute;
return {
'f': first ~/ 60,
'l': last ~/ 60,
'n': norm.count,
if (first % 60 != 0) 'fm': first,
if (last % 60 != 0) 'lm': last,
};
}
/// Returns the normalised schedule a `sched:<date>` value describes, or null.
///
/// Mirrors `_meal_schedule.schedule_from_wire`. `fm`/`lm` win when they are
/// ints; otherwise `f`/`l` are hours. Never throws: anything without int `f`,
/// `l` and `n` yields null, so one bad field from a peer cannot take out the
/// whole history.
MealSchedule? scheduleFromWire(Object? raw) {
if (raw is! Map) return null;
final first = raw['f'];
final last = raw['l'];
final count = raw['n'];
if (first is! int || last is! int || count is! int) return null;
final firstMinute = raw['fm'];
final lastMinute = raw['lm'];
return MealSchedule(
firstMinute: firstMinute is int ? firstMinute : first * 60,
lastMinute: lastMinute is int ? lastMinute : last * 60,
count: count,
).normalized();
}

View File

@ -1,4 +1,5 @@
/// Pure meal-slot arithmetic, mirroring diet_guard's `_slots.py`.
/// Pure meal-slot arithmetic, mirroring diet_guard's `_slots.py` and
/// `_slot_wire.py`.
///
/// Deliberately I/O-free and clock-free: every function is a total function of
/// its `now` and `schedule` arguments, so the time-of-day edges are
@ -7,6 +8,11 @@
/// the Python original is shared between the gate dashboard and the lock
/// decision.
///
/// A slot is a *minute of day* (`0..1439`): 480, 720, 960, 1200 by default.
/// A logged meal satisfies the slot nearest its recorded slot minute
/// ([satisfiedSlots]), so an entry written under an older schedule still
/// counts after the schedule moves -- nothing stored is ever rewritten.
///
/// `schedule` is a required argument on every function here, deliberately: it
/// used to be read from module constants, and a default would let a call site
/// that was missed during a refactor keep deriving the old fixed hours on one
@ -14,11 +20,24 @@
/// slot one device offers and the other does not is a checkpoint that can
/// never be satisfied. Callers resolve the value at the impure edge, through
/// `MealScheduleService.current`.
///
/// **Entry wire rule** (mirrors `_slot_wire.py`): writers always write
/// `slot = minute ~/ 60` and add `slot_min = minute` only when the minute is
/// off the hour, so whole-hour entries stay byte-identical to the pre-minute
/// format and an older peer still reads an hour. Readers prefer an int
/// `slot_min`, then `slot * 60`, else no slot. See [slotFields] and
/// [entrySlotMinute]; `tests/fixtures/meal_schedule_vectors.json` gates both
/// languages.
library;
import 'package:diet_guard_app/models/meal_schedule.dart';
/// Returns the meal-slot hours for a day, e.g. `[8, 12, 16, 20]`.
/// Returns [now]'s minute of day, `0..1439` (seconds are ignored).
///
/// Mirrors `_slots.minute_of_day`.
int minuteOfDay(DateTime now) => now.hour * 60 + now.minute;
/// Returns the meal-slot minutes for a day, e.g. `[480, 720, 960, 1200]`.
///
/// Mirrors `_slots.day_slots`.
List<int> daySlots(MealSchedule schedule) => schedule.slots();
@ -26,29 +45,30 @@ List<int> daySlots(MealSchedule schedule) => schedule.slots();
/// Returns true if [now] is inside the daily slot-enforcement window.
///
/// Mirrors `_slots.within_enforcement_window`.
bool withinEnforcementWindow(DateTime now, MealSchedule schedule) =>
now.hour >= schedule.slots().first &&
now.hour < schedule.enforcementEndHour;
bool withinEnforcementWindow(DateTime now, MealSchedule schedule) {
final minute = minuteOfDay(now);
return schedule.slots().first <= minute &&
minute < schedule.enforcementEndMinute;
}
/// Returns today's slots whose hour has arrived as of [now].
/// Returns today's slots whose minute has arrived as of [now].
///
/// Empty outside the enforcement window. Mirrors `_slots.elapsed_slots`.
List<int> elapsedSlots(DateTime now, MealSchedule schedule) {
if (!withinEnforcementWindow(now, schedule)) return const [];
return daySlots(schedule).where((slot) => slot <= now.hour).toList();
final minute = minuteOfDay(now);
return daySlots(schedule).where((slot) => slot <= minute).toList();
}
/// Returns elapsed slots not yet covered by [logged].
/// Returns elapsed slots not yet covered by [logged] (normally
/// [satisfiedSlots] of the entries' slot minutes).
///
/// Mirrors `_slots.missing_slots`.
List<int> missingSlots(
DateTime now,
Set<int> logged,
MealSchedule schedule,
) => elapsedSlots(
now,
schedule,
).where((slot) => !logged.contains(slot)).toList();
List<int> missingSlots(DateTime now, Set<int> logged, MealSchedule schedule) =>
elapsedSlots(
now,
schedule,
).where((slot) => !logged.contains(slot)).toList();
/// Returns the most recent elapsed slot as of [now], or null.
///
@ -64,8 +84,7 @@ int? currentSlot(DateTime now, MealSchedule schedule) {
/// first slot, clamp to the first slot; after the enforcement window ends,
/// clamp to the last slot; behaviour inside a window is unchanged. The two
/// languages must reach each answer by the *same* branch, not merely agree on
/// the value -- `test/models/slot_test.dart` sweeps every hour of the day
/// against several schedules for exactly that reason.
/// the value -- the shared fixture pins every minute edge for that reason.
///
/// Unlike [currentSlot] this never returns null, which is the point: an
/// off-hours meal used to satisfy no slot at all, so eating at 07:30 or 22:30
@ -74,11 +93,65 @@ int? currentSlot(DateTime now, MealSchedule schedule) {
/// *those* would instead make every slot fall due at the end of the day.
int slotForLog(DateTime now, MealSchedule schedule) {
final slots = daySlots(schedule);
if (now.hour < slots.first) return slots.first;
if (minuteOfDay(now) < slots.first) return slots.first;
return currentSlot(now, schedule) ?? slots.last;
}
/// Returns a human `HH:00` label for [slot], e.g. `"08:00"`.
/// Returns the slot closest to [minute]; an exact tie goes to the earlier.
///
/// Mirrors `_slots.nearest_slot`, whose `min` keeps the first minimal element
/// of the ascending slots -- hence replacing the best only on a strictly
/// smaller distance here.
int nearestSlot(int minute, MealSchedule schedule) {
final slots = daySlots(schedule);
var best = slots.first;
for (final slot in slots) {
if ((slot - minute).abs() < (best - minute).abs()) best = slot;
}
return best;
}
/// Returns the slots covered by meals recorded at [entryMinutes].
///
/// Mirrors `_slots.satisfied_slots`. Many-to-one is intended: two meals
/// snapping onto one slot satisfy only that slot.
Set<int> satisfiedSlots(Iterable<int> entryMinutes, MealSchedule schedule) => {
for (final minute in entryMinutes) nearestSlot(minute, schedule),
};
/// Returns the entry fields that record [minute] as its slot.
///
/// Mirrors `_slot_wire.slot_fields`; throws [ArgumentError] for a minute
/// outside the day, as Python raises `ValueError`.
Map<String, int> slotFields(int minute) {
if (minute < 0 || minute >= kMinutesPerDay) {
throw ArgumentError.value(
minute,
'minute',
'slot minute is outside 0..${kMinutesPerDay - 1}',
);
}
return {'slot': minute ~/ 60, if (minute % 60 != 0) 'slot_min': minute};
}
/// Returns the slot minute a raw log entry records, or null when it has none.
///
/// Mirrors `_slot_wire.entry_slot_minute`: an int `slot_min` wins, else an int
/// `slot` is an hour, else null. Values are not range-checked.
int? entrySlotMinute(Map<String, Object?> entry) {
final slotMin = entry['slot_min'];
if (slotMin is int) return slotMin;
final slot = entry['slot'];
if (slot is int) return slot * 60;
return null;
}
/// Returns a human `HH:MM` label for a slot minute, e.g. `"07:15"`.
///
/// Mirrors `_slots.slot_label`.
String slotLabel(int slot) => '${(slot % 24).toString().padLeft(2, '0')}:00';
String slotLabel(int minute) {
final wrapped = minute % kMinutesPerDay;
final hours = (wrapped ~/ 60).toString().padLeft(2, '0');
final minutes = (wrapped % 60).toString().padLeft(2, '0');
return '$hours:$minutes';
}

View File

@ -15,7 +15,7 @@ import 'package:uuid/uuid.dart';
/// Edit screen for an existing [FoodEntry].
///
/// Preserves [FoodEntry.id], [FoodEntry.time], [FoodEntry.slot],
/// Preserves [FoodEntry.id], [FoodEntry.time], [FoodEntry.slotMinute],
/// and [FoodEntry.deleted]. All nutritional fields and
/// the description are editable.
class EditEntryScreen extends StatefulWidget {
@ -130,7 +130,7 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
carbsG: nutrition.carbsG,
fatG: nutrition.fatG,
source: _source,
slot: e.slot,
slotMinute: e.slotMinute,
);
await LogStorageService.instance.updateEntry(e, updated);
final log = await LogStorageService.instance.readLog();

View File

@ -9,8 +9,12 @@
/// a day that hasn't started.
library;
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.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/theme.dart';
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
import 'package:flutter/material.dart';
@ -20,6 +24,7 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
DateTime? _futureDate;
int? _futureSlot;
Set<int> _futureLoggedSlots = {};
MealSchedule? _futureSchedule;
/// The date currently chosen for a future log, or null when logging for
/// today through the screen's normal flow.
@ -34,6 +39,7 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
_futureDate = null;
_futureSlot = null;
_futureLoggedSlots = {};
_futureSchedule = null;
});
}
@ -49,12 +55,18 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
if (picked == null || !mounted) return;
final log = await LogStorageService.instance.readLog();
if (!mounted) return;
final logged = (log[localDateKey(picked)] ?? const [])
.where((entry) => !entry.deleted && entry.slot != null)
.map((entry) => entry.slot!)
.toSet();
final day = localDateKey(picked);
final schedule = MealScheduleService.history.forDay(day);
// Snapped against the schedule for *that* day, the same rule as
// `loggedSlotsToday`: an exact match would show a pre-logged meal's slot
// as open again after a schedule edit, inviting a duplicate.
final logged = satisfiedSlots([
for (final entry in log[day] ?? const <FoodEntry>[])
if (!entry.deleted) ?entry.slotMinute,
], schedule);
setState(() {
_futureDate = picked;
_futureSchedule = schedule;
_futureLoggedSlots = logged;
_futureSlot = null;
});
@ -107,6 +119,7 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
}
return SlotSelectorRow(
now: DateTime(date.year, date.month, date.day),
schedule: _futureSchedule,
loggedSlots: _futureLoggedSlots,
selectedSlot: _futureSlot,
onSlotSelected: (slot) => setState(() => _futureSlot = slot),
@ -132,7 +145,9 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
return (
error: null,
slot: slot,
when: DateTime(date.year, date.month, date.day, slot),
// The slot is a minute of day, not an hour: passing it as the hour
// argument would roll 720 (12:00) forward a whole month.
when: DateTime(date.year, date.month, date.day, slot ~/ 60, slot % 60),
);
}
}

View File

@ -149,7 +149,7 @@ class _LogMealScreenState extends State<LogMealScreen>
await LogStorageService.instance.logMeal(
desc,
nutritionFromControllers(_macros, _source),
slot: target.slot,
slotMinute: target.slot,
when: target.when,
);
resetFutureLog();

View File

@ -179,7 +179,7 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
/// The meal-schedule editor lives in settings, and [SlotSelectorRow] reads
/// `MealScheduleService.current` at build time, so refreshing is enough to
/// re-derive the row -- but the selected slot also has to be recomputed,
/// since the hour it referred to may no longer be a checkpoint at all.
/// since the minute it referred to may no longer be a checkpoint at all.
///
/// Found on the phone: without this the settings preview and the overdue
/// reminder both updated while the row behind them kept the old four

View File

@ -1,5 +1,5 @@
// The meal-schedule editor: first meal, last meal, how many meals, and a
// live preview of the checkpoint times they derive.
// The meal-schedule section: owns the schedule state and its persistence;
// the widgets themselves live in `widgets/meal_schedule_editor.dart`.
//
// Split out of `settings_screen.dart` for the repo's 250-line cap. A `part`
// mixin for the same reason as `_SettingsKcalGoal`: it drives the screen's
@ -14,134 +14,22 @@ mixin _SettingsMealSchedule on State<SettingsScreen> {
_schedule = MealScheduleService.current;
}
/// The meal counts selectable for the current window.
///
/// Capped at the number of whole hours the window holds, so the count
/// dropdown can never offer a value that would round two meals onto the
/// same hour. Invalid states are made unrepresentable here rather than
/// validated after the fact -- `MealSchedule.normalized` still clamps, but
/// that is the defence against corrupt synced data, not the input contract.
List<int> get _selectableCounts {
final span = _schedule.last - _schedule.first;
final maxCount = span + 1 < kMaxMealCount ? span + 1 : kMaxMealCount;
return [for (var n = kMinMealCount; n <= maxCount; n++) n];
}
Future<void> _applySchedule(MealSchedule next) async {
final normalized = next.normalized();
setState(() => _schedule = normalized);
if (!MealScheduleService.isInitialized) return;
await MealScheduleService.instance.recordChange(normalized);
// The reminder ids are slot hours, so a schedule change orphans the ones
// it no longer contains. Re-running the check cancels them immediately
// rather than leaving a stale nag until the next background tick.
// The reminder ids are slot minutes, so a schedule change leaves posted
// reminders for checkpoints that no longer exist. Re-running the check
// cancels them immediately rather than leaving a stale nag until the
// next background tick.
await checkAndNotify(pullWhenDue: false);
}
/// Dropdowns rather than a time picker: `showTimePicker` returns minutes,
/// and slots are whole hours on both devices by design.
Widget _hourDropdown({
required String label,
required int value,
required List<int> hours,
required ValueChanged<int> onChanged,
}) => ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: InputDecorator(
decoration: InputDecoration(labelText: label),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
value: value,
isDense: true,
isExpanded: true,
items: [
for (final hour in hours)
DropdownMenuItem(value: hour, child: Text(slotLabel(hour))),
],
onChanged: (hour) => hour == null ? null : onChanged(hour),
),
),
List<Widget> _mealScheduleSection(BuildContext context) => [
MealScheduleEditor(
schedule: _schedule,
onChanged: (next) => unawaited(_applySchedule(next)),
),
);
List<Widget> _mealScheduleSection(BuildContext context) {
final theme = Theme.of(context);
final counts = _selectableCounts;
return [
Text('Meal times', style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text(
'Checkpoints are spread evenly between your first and last meal.',
style: theme.textTheme.bodySmall,
),
const SizedBox(height: 12),
_hourDropdown(
label: 'First meal',
value: _schedule.first,
// Leaves at least one hour of window, so `last` always has a value
// strictly after `first` to offer.
hours: [for (var h = kFirstHour; h < kLastHour; h++) h],
onChanged: (hour) => unawaited(
_applySchedule(
MealSchedule(
first: hour,
last: _schedule.last,
count: _schedule.count,
),
),
),
),
const SizedBox(height: 12),
_hourDropdown(
label: 'Last meal',
value: _schedule.last,
hours: [for (var h = _schedule.first + 1; h <= kLastHour; h++) h],
onChanged: (hour) => unawaited(
_applySchedule(
MealSchedule(
first: _schedule.first,
last: hour,
count: _schedule.count,
),
),
),
),
const SizedBox(height: 12),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: InputDecorator(
decoration: const InputDecoration(labelText: 'Meals per day'),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
value: counts.contains(_schedule.count)
? _schedule.count
: counts.last,
isDense: true,
isExpanded: true,
items: [
for (final count in counts)
DropdownMenuItem(value: count, child: Text('$count')),
],
onChanged: (count) => count == null
? null
: unawaited(
_applySchedule(
MealSchedule(
first: _schedule.first,
last: _schedule.last,
count: count,
),
),
),
),
),
),
),
const SizedBox(height: 12),
Text(
_schedule.slots().map(slotLabel).join(' · '),
style: theme.textTheme.bodyMedium,
),
];
}
];
}

View File

@ -12,7 +12,6 @@ import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
@ -22,6 +21,7 @@ import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/meal_schedule_editor.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

View File

@ -11,6 +11,7 @@ library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
@ -20,6 +21,11 @@ const kuchniaSource = 'kuchnia wikinga';
/// Keeps only the dishes whose slot has nothing logged in it today.
///
/// [occupied] holds slot minutes *satisfied* today (see
/// `LogStorageService.loggedSlotsToday`), i.e. entries already snapped to
/// the nearest current slot -- not raw recorded minutes, or a meal logged
/// under yesterday's schedule would leave its slot looking empty.
///
/// Fills *empty* slots: a slot the user already logged something into keeps
/// that meal rather than gaining a second one. [occupied] is read once, before
/// the batch, so two dishes the spread put in the same empty slot (5 dishes on
@ -48,8 +54,12 @@ Nutrition dishNutrition(KuchniaDish dish) => nutritionForPortion(
source: kuchniaSource,
);
String _dedupKey(String desc, int? slot) =>
'${desc.trim().toLowerCase()}\u0000$slot';
/// Keyed by the entry's *recorded* slot minute, unsnapped, mirroring Python's
/// `_already_logged` exact comparison. Deliberately not snapped: occupancy
/// ([fillPlan]) already snaps, so this only has to catch the exact dish this
/// batch or an earlier fill wrote into the same slot.
String _dedupKey(String desc, int? slotMinute) =>
'${desc.trim().toLowerCase()}\u0000$slotMinute';
/// Logs each chosen dish, skipping any already logged today in that slot.
///
@ -68,7 +78,7 @@ Future<List<SlottedDish>> logDishes(
final store = storage ?? LogStorageService.instance;
final seen = {
for (final entry in await store.todayEntries())
_dedupKey(entry.desc, entry.slot),
_dedupKey(entry.desc, entry.slotMinute),
};
final written = <SlottedDish>[];
for (final item in chosen) {
@ -77,7 +87,7 @@ Future<List<SlottedDish>> logDishes(
await store.logMeal(
item.dish.name,
dishNutrition(item.dish),
slot: item.slot,
slotMinute: item.slot,
);
written.add(item);
}
@ -95,11 +105,7 @@ String _g(double value) {
String planSummary(List<SlottedDish> plan) {
final total = plan.fold<double>(0, (sum, item) => sum + item.dish.kcal);
final listing = plan
.map(
(item) =>
'${item.slot.toString().padLeft(2, '0')}:00 '
'${item.dish.name}',
)
.map((item) => '${slotLabel(item.slot)} ${item.dish.name}')
.join(', ');
return 'Will log ${plan.length} (${_g(total)} kcal): $listing'
' — tap Confirm.';

View File

@ -27,19 +27,19 @@ library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
/// A dish paired with the meal-slot hour it was assigned to.
/// A dish paired with the meal-slot minute it was assigned to.
class SlottedDish {
/// Pairs [dish] with the [slot] hour it should be logged against.
/// Pairs [dish] with the [slot] minute it should be logged against.
const SlottedDish({required this.dish, required this.slot});
/// The dish itself.
final KuchniaDish dish;
/// The slot hour, e.g. `12` for the 12:00 checkpoint.
/// The slot's minute of day, e.g. `720` for the 12:00 checkpoint.
final int slot;
}
/// Pairs each dish with a slot hour, following the provider's meal order.
/// Pairs each dish with a slot minute, following the provider's meal order.
///
/// Returns an empty list when either input is empty -- a day with no delivery
/// and a schedule with no slots are both "nothing to assign", not errors.

View File

@ -7,8 +7,10 @@ import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/meal_component.dart';
import 'package:diet_guard_app/models/nutrition.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_factory.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter/foundation.dart';
import 'package:uuid/uuid.dart';
@ -102,11 +104,12 @@ class LogStorageService {
/// Mirrors `_state.log_meal`: always assigns a fresh `id`, never computes
/// an `hmac` (the phone never holds the shared key -- the PC re-signs on
/// merge, see Milestone 3). [when] lets a caller pre-log a meal against a
/// future date/slot; must not be in the past.
/// future date/slot; must not be in the past. [slotMinute] is the slot's
/// minute of day (`slotForLog`'s result), never an hour.
Future<FoodEntry> logMeal(
String desc,
Nutrition nutrition, {
int? slot,
int? slotMinute,
List<MealComponent>? components,
DateTime? when,
}) async {
@ -124,7 +127,7 @@ class LogStorageService {
carbsG: nutrition.carbsG,
fatG: nutrition.fatG,
source: nutrition.source,
slot: slot,
slotMinute: slotMinute,
components: components,
);
final log = await readLog();
@ -229,10 +232,17 @@ class LogStorageService {
}
}
/// Returns the slot hours already satisfied today, mirrors
/// Returns today's slot minutes already satisfied, mirrors
/// `_state.logged_slots_today`.
///
/// Each entry satisfies the slot *nearest* its recorded minute under the
/// schedule in force now. Stored minutes are never rewritten, so an exact
/// match would let a schedule edit (07:00 -> 07:15) un-log a meal already
/// eaten and re-nag for it -- and disagree with the PC, which snaps too.
Future<Set<int>> loggedSlotsToday() async {
final entries = await todayEntries();
return entries.where((e) => e.slot != null).map((e) => e.slot!).toSet();
return satisfiedSlots([
for (final entry in entries) ?entry.slotMinute,
], MealScheduleService.current);
}
}

View File

@ -50,33 +50,28 @@ class ScheduleEntry {
}
/// Returns the wire/disk form of one entry's value.
///
/// Goes through [scheduleToWire], so a whole-hour schedule is stored exactly
/// as before minutes existed (`{f, l, n, t}`) and an older build still reads
/// it; `fm`/`lm` appear only for an off-the-hour endpoint.
Map<String, Object?> scheduleEntryToJson(ScheduleEntry entry) => {
'f': entry.schedule.first,
'l': entry.schedule.last,
'n': entry.schedule.count,
...scheduleToWire(entry.schedule),
't': entry.editedAt,
};
/// Returns an entry parsed from its stored value, or null if unusable.
///
/// Never throws: a malformed entry is skipped so one bad field from a peer
/// cannot take out the whole history.
/// cannot take out the whole history. [scheduleFromWire] normalises on the
/// way in, so a peer running a future version with a wider range cannot hand
/// us a schedule we would derive differently.
ScheduleEntry? scheduleEntryFromJson(String effectiveFrom, Object? raw) {
if (raw is! Map) return null;
final first = raw['f'];
final last = raw['l'];
final count = raw['n'];
if (first is! int || last is! int || count is! int) return null;
final schedule = scheduleFromWire(raw);
if (schedule == null || raw is! Map) return null;
final editedAt = raw['t'];
return ScheduleEntry(
effectiveFrom: effectiveFrom,
// Normalising on the way in means a peer running a future version with a
// wider range cannot hand us a schedule we would derive differently.
schedule: MealSchedule(
first: first,
last: last,
count: count,
).normalized(),
schedule: schedule,
editedAt: editedAt is String ? editedAt : _epochIso,
);
}

View File

@ -25,4 +25,12 @@ abstract class NotificationBackend {
/// Removes the notification for [slot], if one is showing.
Future<void> cancel(int slot);
/// Returns the ids of the meal reminders currently showing.
///
/// Must include reminders posted by *earlier* builds and runs (on Android
/// the hour-keyed ids an older version left behind), because this is what
/// lets `NotificationService.syncToSlots` cancel orphans without sweeping
/// every possible id. May throw; the caller then falls back to a sweep.
Future<Set<int>> activeIds();
}

View File

@ -66,6 +66,17 @@ class LocalNotificationsBackend implements NotificationBackend {
@override
Future<void> cancel(int slot) => plugin.cancel(id: slot);
/// Asks Android which notifications this app has in the shade (API 23+;
/// minSdk is 26), restricted to the reminder channel so nothing else the
/// app might ever post is swept up. Older builds posted on this same
/// channel id, so their hour-keyed reminders are included -- which is what
/// makes the upgrade orphan-free.
@override
Future<Set<int>> activeIds() async => {
for (final active in await plugin.getActiveNotifications())
if (active.channelId == _channelId && active.id != null) active.id!,
};
}
/// Opens the platform notification backend.

View File

@ -50,6 +50,13 @@ class WebNotificationBackend implements NotificationBackend {
Future<void> cancel(int slot) async {
_shown.remove(slot)?.close();
}
/// The page's own live notifications. Complete for this surface: a browser
/// notification cannot outlive the page that raised it in any way this
/// page could still close, so nothing posted by an earlier load (or an
/// older, hour-keyed build) is reachable to orphan.
@override
Future<Set<int>> activeIds() async => _shown.keys.toSet();
}
/// Opens the platform notification backend.

View File

@ -4,13 +4,12 @@
/// rather than fired once.
library;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/notification_backend.dart';
import 'package:diet_guard_app/services/notification_backend_factory.dart';
import 'package:flutter/foundation.dart';
const int _hoursPerDay = 24;
/// Owns the due-slot notification logic ([syncToSlots]) independently of the
/// platform surface that actually posts them: `flutter_local_notifications`
/// on Android, the browser's Notifications API in the desktop web build (see
@ -53,30 +52,45 @@ class NotificationService {
/// false the same way.
Future<bool?> requestPermission() => _backend.requestPermission();
/// Shows a notification for every slot in [dueSlots] and cancels one for
/// every other known slot.
/// Shows a notification for every slot minute in [dueSlots] and cancels
/// every other reminder this app has showing.
///
/// Idempotent and re-evaluated every tick: a slot logged after its
/// notification fired gets that notification cancelled on the very next
/// call, mirroring `_gate.gate_is_due()`'s re-evaluate-every-tick
/// behavior rather than firing once and forgetting.
///
/// The slot minute doubles as the notification id, so a schedule change
/// leaves ids no current slot names -- and so does the upgrade itself,
/// because older builds used the slot *hour* (0..23) as the id. Iterating
/// only today's slots would leave those posted forever, nagging about
/// checkpoints that no longer exist. Rather than sweeping all 1440 possible
/// ids (a platform call each, every ~15 min from a background isolate),
/// this asks the platform which reminders are actually showing and cancels
/// those not due: one lookup plus one call per real notification, and
/// complete by construction, since an orphan is by definition something
/// showing. Only when that lookup fails does it fall back to the full
/// sweep, paying the cost on that one tick to keep the guarantee.
Future<void> syncToSlots(List<int> dueSlots) async {
final due = dueSlots.toSet();
// Sweeps every hour of the day, not just the *current* schedule's slots.
// The slot hour doubles as the notification id, so a schedule change
// orphans the ids it no longer contains: going 08/12/16/20 -> 08/11/14/17
// used to leave 12 and 16 posted with nothing left to ever cancel them,
// nagging forever about checkpoints that no longer exist.
for (var slot = 0; slot < _hoursPerDay; slot++) {
if (due.contains(slot)) {
await _backend.show(
slot,
'Meal not logged',
"You haven't logged your ${slotLabel(slot)} meal yet.",
);
} else {
await _backend.cancel(slot);
}
Iterable<int> stale;
try {
stale = (await _backend.activeIds()).difference(due);
} on Object {
stale = [
for (var id = 0; id < kMinutesPerDay; id++)
if (!due.contains(id)) id,
];
}
for (final id in stale) {
await _backend.cancel(id);
}
for (final slot in due) {
await _backend.show(
slot,
'Meal not logged',
"You haven't logged your ${slotLabel(slot)} meal yet.",
);
}
}
}

View File

@ -47,12 +47,10 @@ Hlc scheduleHlc(ScheduleEntry entry) {
/// default over a peer's real value.
Map<String, (dynamic, Hlc)> scheduleFields(List<ScheduleEntry> entries) => {
for (final entry in entries)
// scheduleToWire keeps a whole-hour schedule byte-identical to the
// pre-minute `{f, l, n}`, so a peer that predates minutes still reads it.
'$scheduleFieldPrefix${entry.effectiveFrom}': (
{
'f': entry.schedule.first,
'l': entry.schedule.last,
'n': entry.schedule.count,
},
scheduleToWire(entry.schedule),
scheduleHlc(entry),
),
};
@ -69,23 +67,15 @@ List<ScheduleEntry> logToScheduleHistory(Log log) {
final entries = <ScheduleEntry>[];
for (final field in record.fields.entries) {
if (!field.key.startsWith(scheduleFieldPrefix)) continue;
final value = field.value.$1;
if (value is! Map) continue;
final first = value['f'];
final last = value['l'];
final count = value['n'];
if (first is! int || last is! int || count is! int) continue;
// Normalised on the way in (scheduleFromWire), so a peer running a future
// version with a wider range cannot hand us a schedule we would derive
// slots differently from.
final schedule = scheduleFromWire(field.value.$1);
if (schedule == null) continue;
entries.add(
ScheduleEntry(
effectiveFrom: field.key.substring(scheduleFieldPrefix.length),
// Normalised on the way in, so a peer running a future version with a
// wider range cannot hand us a schedule we would derive slots
// differently from.
schedule: MealSchedule(
first: first,
last: last,
count: count,
).normalized(),
schedule: schedule,
editedAt: DateTime.fromMillisecondsSinceEpoch(
field.value.$2.wallTimeMs,
isUtc: true,

View File

@ -0,0 +1,119 @@
/// The meal-schedule editor: first meal, last meal, how many meals, and a
/// live preview of the checkpoint times they derive.
library;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/meal_time_dropdown.dart';
import 'package:flutter/material.dart';
/// Latest minute the *grid* offers for the first meal: 23:30, leaving one
/// grid step for a grid-aligned last meal. The clock button can go later, up
/// to the 23:44 that [MealSchedule.normalized] allows.
const int _firstGridMax = kMinutesPerDay - 2 * kSlotGridMinutes;
/// Latest first-meal minute [MealSchedule.normalized] keeps: one grid step
/// before the end of the day.
const int _firstMax = kMinutesPerDay - 1 - kSlotGridMinutes;
/// Edits a [MealSchedule], reporting every change through [onChanged].
///
/// Stateless: the owner holds the schedule and persists it. Every offered
/// value is already legal, so `normalized()` in the owner is the defence
/// against corrupt synced data rather than the input contract.
class MealScheduleEditor extends StatelessWidget {
/// Creates a [MealScheduleEditor].
const MealScheduleEditor({
required this.schedule,
required this.onChanged,
super.key,
});
/// The schedule being shown.
final MealSchedule schedule;
/// Called with the edited (not yet normalised) schedule.
final ValueChanged<MealSchedule> onChanged;
/// The meal counts selectable for the current window.
///
/// Capped at the number of grid-spaced checkpoints the window holds, so the
/// dropdown can never offer a count that would round two meals onto the
/// same quarter hour -- the same capacity rule `normalized` enforces.
List<int> get selectableCounts {
final span = schedule.lastMinute - schedule.firstMinute;
final capacity = span ~/ kSlotGridMinutes + 1;
final maxCount = capacity < kMaxMealCount ? capacity : kMaxMealCount;
return [for (var n = kMinMealCount; n <= maxCount; n++) n];
}
MealSchedule _with({int? first, int? last, int? count}) => MealSchedule(
firstMinute: first ?? schedule.firstMinute,
lastMinute: last ?? schedule.lastMinute,
count: count ?? schedule.count,
);
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final counts = selectableCounts;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Meal times', style: theme.textTheme.titleMedium),
const SizedBox(height: AppSpacing.xs),
Text(
'Checkpoints are spread evenly between your first and last meal.',
style: theme.textTheme.bodySmall,
),
const SizedBox(height: 12),
MealTimeDropdown(
label: 'First meal',
value: schedule.firstMinute,
minMinute: 0,
maxMinute: _firstMax,
gridMaxMinute: _firstGridMax,
onChanged: (minute) => onChanged(_with(first: minute)),
),
const SizedBox(height: 12),
MealTimeDropdown(
label: 'Last meal',
value: schedule.lastMinute,
// At least one grid step after the first meal: the shortest window
// that still holds two distinct checkpoints.
minMinute: schedule.firstMinute + kSlotGridMinutes,
maxMinute: kMinutesPerDay - 1,
onChanged: (minute) => onChanged(_with(last: minute)),
),
const SizedBox(height: 12),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: InputDecorator(
decoration: const InputDecoration(labelText: 'Meals per day'),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
value: counts.contains(schedule.count)
? schedule.count
: counts.last,
isDense: true,
isExpanded: true,
items: [
for (final count in counts)
DropdownMenuItem(value: count, child: Text('$count')),
],
onChanged: (count) =>
count == null ? null : onChanged(_with(count: count)),
),
),
),
),
const SizedBox(height: 12),
Text(
schedule.slots().map(slotLabel).join(' · '),
style: theme.textTheme.bodyMedium,
),
],
);
}
}

View File

@ -0,0 +1,134 @@
/// A minute-of-day picker: a 15-minute dropdown plus an exact-time button.
library;
import 'dart:async';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart';
/// Picks a minute of day, offering the 15-minute grid within
/// [minMinute]..[maxMinute], with a clock button beside it that opens a time
/// picker for any minute in that range.
///
/// A separate button rather than a "Custom…" menu item: the menu opens
/// centred on the current value, so an item at either end of ~95 entries was
/// always a long scroll away.
///
/// The grid is what most people want and keeps the list short; the button
/// exists because an endpoint may legitimately sit off the grid (07:23 to
/// match a train), and because the PC can set such a value and sync it here.
/// That second case is why the current [value] is always offered as an item
/// even when it is off-grid or outside the range: a [DropdownButton] whose
/// value matches no item asserts, which would take the settings screen down
/// over a value another device wrote.
class MealTimeDropdown extends StatelessWidget {
/// Creates a [MealTimeDropdown].
const MealTimeDropdown({
required this.label,
required this.value,
required this.minMinute,
required this.maxMinute,
required this.onChanged,
this.gridMaxMinute,
super.key,
});
/// The field label, e.g. "First meal".
final String label;
/// The current minute of day.
final int value;
/// Earliest minute offered (inclusive).
final int minMinute;
/// Latest minute offered (inclusive), via the clock button if not the grid.
final int maxMinute;
/// Latest grid mark listed, when it must stop short of [maxMinute] (the
/// first meal's grid ends at 23:30 so a grid-aligned last meal still fits,
/// while the clock button may go to 23:44). Defaults to [maxMinute].
final int? gridMaxMinute;
/// Called with the chosen minute, already clamped into
/// [minMinute]..[maxMinute]. Not called when the picker is dismissed.
final ValueChanged<int> onChanged;
/// The minutes listed, ascending: the grid marks in range plus [value].
List<int> get options {
final first =
(minMinute + kSlotGridMinutes - 1) ~/
kSlotGridMinutes *
kSlotGridMinutes;
return {
for (
var m = first;
m <= (gridMaxMinute ?? maxMinute);
m += kSlotGridMinutes
)
m,
value,
}.toList()..sort();
}
int _clampToRange(int minute) => minute < minMinute
? minMinute
: (minute > maxMinute ? maxMinute : minute);
Future<void> _pickExact(BuildContext context) async {
final picked = await showTimePicker(
context: context,
initialTime: TimeOfDay(hour: value ~/ 60, minute: value % 60),
helpText: label,
// The rest of the app writes times as HH:MM; an AM/PM dial here would
// be the one place that reads differently.
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child!,
),
);
if (picked == null) return;
// Clamped rather than rejected: the picker cannot be told the range, and
// the nearest legal minute is what `MealSchedule.normalized` would
// produce anyway -- doing it here keeps the dropdown's own contract.
onChanged(_clampToRange(picked.hour * 60 + picked.minute));
}
@override
Widget build(BuildContext context) => ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: Row(
spacing: AppSpacing.xs,
children: [
Expanded(
child: InputDecorator(
decoration: InputDecoration(labelText: label),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
value: value,
isDense: true,
isExpanded: true,
items: [
for (final minute in options)
DropdownMenuItem(
value: minute,
child: Text(slotLabel(minute)),
),
],
onChanged: (minute) =>
minute == null ? null : onChanged(minute),
),
),
),
),
IconButton(
icon: const Icon(Icons.schedule),
tooltip: 'Type or pick an exact time',
onPressed: () => unawaited(_pickExact(context)),
),
],
),
);
}

View File

@ -3,15 +3,16 @@
/// used to be three separate stacked elements.
library;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart';
/// One row of [ChoiceChip]s, one per today's slot hour. Each chip is
/// simultaneously selectable (tap to log for that slot) and status-colored
/// (green+check = logged, red = due, grey = upcoming), so no separate status
/// bar or caption text is needed.
/// One row of [ChoiceChip]s, one per today's slot (labelled `HH:MM`). Each
/// chip is simultaneously selectable (tap to log for that slot) and
/// status-colored (green+check = logged, red = due, grey = upcoming), so no
/// separate status bar or caption text is needed.
///
/// There used to be a fifth "Snack" chip that selected no slot at all,
/// removed 2026-08-14. Entries with a null slot still exist in storage and
@ -24,20 +25,27 @@ class SlotSelectorRow extends StatelessWidget {
required this.loggedSlots,
required this.selectedSlot,
required this.onSlotSelected,
this.schedule,
super.key,
});
/// Reference time used to decide which slots are due.
final DateTime now;
/// Slot hours already satisfied by today's log.
/// The schedule whose slots to show; defaults to the one in force today.
///
/// Passed explicitly for a future day so the chips and [loggedSlots] (which
/// the caller snapped against that day's schedule) can never disagree.
final MealSchedule? schedule;
/// Slot minutes already satisfied by the day's log (`satisfiedSlots`).
final Set<int> loggedSlots;
/// The slot currently chosen to log for. Nullable for historical reasons
/// (see the class doc); no chip in this row selects null any more.
final int? selectedSlot;
/// Called with the tapped slot's hour. Never called with null.
/// Called with the tapped slot's minute. Never called with null.
final ValueChanged<int?> onSlotSelected;
@override
@ -49,7 +57,7 @@ class SlotSelectorRow extends StatelessWidget {
// matches production exactly when the extension is genuinely absent.
final statusColors =
Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark;
final schedule = MealScheduleService.current;
final schedule = this.schedule ?? MealScheduleService.current;
final elapsed = elapsedSlots(now, schedule).toSet();
// One row, always. A Wrap dropped the later pills onto a second line as
// soon as the row outgrew the width, which it does even at four: a logged

View File

@ -390,10 +390,10 @@ packages:
dependency: "direct main"
description:
name: idb_shim
sha256: "1495b1bca25088ab05be682ba32532e62f1559b7cd781141c96130b7654ac9f7"
sha256: "110fe0514a52dc8da5414df42405a8f9e880dfac3e84852fdab8e5559ee6ad07"
url: "https://pub.dev"
source: hosted
version: "2.9.10"
version: "2.9.11"
image:
dependency: transitive
description:
@ -670,10 +670,10 @@ packages:
dependency: "direct main"
description:
name: shared_preferences
sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf
sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f"
url: "https://pub.dev"
source: hosted
version: "2.5.5"
version: "2.5.6"
shared_preferences_android:
dependency: transitive
description:

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none'
version: 1.0.104+1
version: 1.0.111+1
environment:
sdk: ^3.12.2
@ -30,11 +30,11 @@ dependencies:
google_sign_in: 7.2.0
health: 13.3.2
http: 1.6.0
idb_shim: 2.9.10
idb_shim: 2.9.11
path: 1.9.1
path_provider: 2.1.6
permission_handler: 13.0.2
shared_preferences: 2.5.5
shared_preferences: 2.5.6
# Shared "Sync settings" screen (Firebase + optional local backup), reused
# across every kuhy app that syncs. GitHub mirror stays app-local (see

View File

@ -3,28 +3,57 @@ import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
/// The channel id `LocalNotificationsBackend` posts reminders on -- and the
/// one older, hour-keyed builds used too.
const reminderChannelId = 'diet_guard_due_slot';
/// Mocks the raw `dexterous.com/flutter/local_notifications` MethodChannel
/// the way the package's own test suite does
/// (`android_flutter_local_notifications_test.dart`), so
/// [NotificationService] can be exercised end-to-end (init/show/cancel)
/// without a real Android plugin.
///
/// Stateful, like the real notification shade: `show` adds an id, `cancel`
/// removes it, and `getActiveNotifications` reports what is left. Without
/// that, the active-id lookup `syncToSlots` relies on would always see an
/// empty shade and every orphan test would pass vacuously. Seed [active]
/// (id -> channel id) to simulate reminders a previous run or an older build
/// left behind.
///
/// Returns the call log so a test can assert which slots were shown vs.
/// cancelled.
List<MethodCall> installFakeAndroidNotifications() {
List<MethodCall> installFakeAndroidNotifications({
Map<int, String>? active,
}) {
AndroidFlutterLocalNotificationsPlugin.registerWith();
debugDefaultTargetPlatformOverride = TargetPlatform.android;
const channel = MethodChannel('dexterous.com/flutter/local_notifications');
final log = <MethodCall>[];
final shade = active ?? <int, String>{};
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
log.add(call);
final args = call.arguments;
switch (call.method) {
case 'initialize':
return true;
case 'requestNotificationsPermission':
return true;
case 'show':
final map = args as Map;
final details = map['platformSpecifics'] as Map?;
shade[map['id'] as int] =
details?['channelId'] as String? ?? reminderChannelId;
return null;
case 'cancel':
shade.remove((args as Map)['id']);
return null;
case 'getActiveNotifications':
return [
for (final entry in shade.entries)
{'id': entry.key, 'channelId': entry.value},
];
default:
return null;
}

View File

@ -76,7 +76,7 @@ void main() {
final outcome = await flow.tap();
expect(outcome!.message, 'Logged 4 catering dishes.');
expect(await loggedToday(storage), ['D1@8', 'D2@12', 'D3@16', 'D4@20']);
expect(await loggedToday(storage), ['D1@480', 'D2@720', 'D3@960', 'D4@1200']);
expect(
(await storage.todayEntries()).map((e) => e.source),
everyElement(kuchniaSource),
@ -94,18 +94,18 @@ void main() {
await storage.logMeal(
'my own lunch',
dishNutrition(dish('x', 1)),
slot: 12,
slotMinute: 720,
);
occupied = {12};
occupied = {720};
final outcome = await flow.tap();
expect(outcome!.message, 'Logged 3 catering dishes.');
expect(await loggedToday(storage), [
'my own lunch@12',
'D1@8',
'D3@16',
'D4@20',
'my own lunch@720',
'D1@480',
'D3@960',
'D4@1200',
]);
expect(occupancyReads, 2, reason: 'once to propose, once to confirm');
},
@ -113,7 +113,7 @@ void main() {
test('a confirm into a now-full day writes nothing', () async {
await flow.tap();
occupied = {8, 12, 16, 20};
occupied = {480, 720, 960, 1200};
final outcome = await flow.tap();
@ -131,11 +131,11 @@ void main() {
await flow.tap();
expect(await loggedToday(storage), [
'D1@8',
'D2@8',
'D3@12',
'D4@16',
'D5@20',
'D1@480',
'D2@480',
'D3@720',
'D4@960',
'D5@1200',
]);
},
);
@ -193,7 +193,7 @@ void main() {
});
test('all slots full arms nothing', () async {
occupied = {8, 12, 16, 20};
occupied = {480, 720, 960, 1200};
final outcome = await flow.tap();
expect(outcome!.message, nothingToFillMessage);

View File

@ -97,13 +97,15 @@ void main() {
await storage.logMeal(
row['desc'] as String,
_seedNutrition,
slot: row['slot'] as int,
// Fixture slots are resolved minutes: seeded through logMeal, so
// storage writes them via slotFields, never as a raw hour.
slotMinute: row['slot'] as int,
);
}
final returned = await logDishes(spread(testCase), storage: storage);
final logged = [
for (final e in (await storage.todayEntries()).skip(seeded.length))
[e.desc, e.slot],
[e.desc, e.slotMinute],
];
final reason = 'logDishes diverged for ${entry.key}';
expect(logged, equals(testCase['expected']), reason: reason);
@ -116,7 +118,7 @@ void main() {
// silently stops testing the intra-batch dedup.
final testCase = cases('log_dishes')['twins_share_16'] as Map;
final input = _pairs(spread(testCase.cast<String, dynamic>()));
bool isTwin16(List<Object?> p) => p[0] == 'Twin dish' && p[1] == 16;
bool isTwin16(List<Object?> p) => p[0] == 'Twin dish' && p[1] == 960;
expect(input.where(isTwin16), hasLength(2));
expect(
(testCase['expected'] as List).cast<List<Object?>>().where(isTwin16),

View File

@ -21,7 +21,7 @@ class MemoryStore implements DocumentStore {
}
/// The default four-slot day.
const defaultSlots = [8, 12, 16, 20];
const defaultSlots = [480, 720, 960, 1200];
/// A dish with the given [priority]; macros are distinct per priority.
KuchniaDish dish(String name, int priority, {double grams = 300}) =>
@ -53,5 +53,5 @@ LogStorageService freshStorage() {
/// `desc@slot` for every live entry logged today, in write order.
Future<List<String>> loggedToday(LogStorageService storage) async => [
for (final e in await storage.todayEntries()) '${e.desc}@${e.slot}',
for (final e in await storage.todayEntries()) '${e.desc}@${e.slotMinute}',
];

View File

@ -23,40 +23,40 @@ void main() {
test('an empty day keeps every dish', () {
final slotted = assignSlots(dishes(4), defaultSlots);
expect(_names(fillPlan(slotted, {})), [
'D1@8',
'D2@12',
'D3@16',
'D4@20',
'D1@480',
'D2@720',
'D3@960',
'D4@1200',
]);
});
test('an occupied slot is skipped, the others stay', () {
final slotted = assignSlots(dishes(4), defaultSlots);
expect(_names(fillPlan(slotted, {12})), ['D1@8', 'D3@16', 'D4@20']);
expect(_names(fillPlan(slotted, {720})), ['D1@480', 'D3@960', 'D4@1200']);
});
test('5 dishes on 4 slots: both dishes of one empty slot stay', () {
final slotted = assignSlots(dishes(5), defaultSlots);
// The spread doubles the first slot; occupancy is read once, so the
// first dish must not shadow the second.
expect(_names(slotted).take(2), ['D1@8', 'D2@8']);
expect(_names(slotted).take(2), ['D1@480', 'D2@480']);
expect(_names(fillPlan(slotted, {})), hasLength(5));
expect(_names(fillPlan(slotted, {16})), [
'D1@8',
'D2@8',
'D3@12',
'D5@20',
expect(_names(fillPlan(slotted, {960})), [
'D1@480',
'D2@480',
'D3@720',
'D5@1200',
]);
});
test('an occupied doubled slot drops both of its dishes', () {
final slotted = assignSlots(dishes(5), defaultSlots);
expect(_names(fillPlan(slotted, {8})), ['D3@12', 'D4@16', 'D5@20']);
expect(_names(fillPlan(slotted, {480})), ['D3@720', 'D4@960', 'D5@1200']);
});
test('a full day yields an empty plan', () {
final slotted = assignSlots(dishes(4), defaultSlots);
expect(fillPlan(slotted, {8, 12, 16, 20}), isEmpty);
expect(fillPlan(slotted, {480, 720, 960, 1200}), isEmpty);
});
});
@ -79,16 +79,16 @@ void main() {
() async {
final storage = freshStorage();
final chosen = [
at(dish('D1', 1, grams: 250), 8),
at(dish('D3', 3), 16),
at(dish('D1', 1, grams: 250), 480),
at(dish('D3', 3), 960),
];
final written = await logDishes(chosen, storage: storage);
expect(_names(written), ['D1@8', 'D3@16']);
expect(_names(written), ['D1@480', 'D3@960']);
final entries = await storage.todayEntries();
expect(entries.map((e) => e.desc), ['D1', 'D3']);
expect(entries.map((e) => e.slot), [8, 16]);
expect(entries.map((e) => e.slotMinute), [480, 960]);
expect(entries.map((e) => e.source), everyElement('kuchnia wikinga'));
expect(entries.map((e) => e.grams), [250, 300]);
expect(entries.map((e) => e.kcal), [100, 300]);
@ -97,15 +97,15 @@ void main() {
test('skips a dish already logged in that slot', () async {
final storage = freshStorage();
await storage.logMeal(' d1 ', dishNutrition(dish('D1', 1)), slot: 8);
await storage.logMeal(' d1 ', dishNutrition(dish('D1', 1)), slotMinute: 480);
final written = await logDishes([
at(dish('D1', 1), 8),
at(dish('D2', 2), 12),
at(dish('D1', 1), 480),
at(dish('D2', 2), 720),
], storage: storage);
// Case and surrounding whitespace do not make it a different meal.
expect(_names(written), ['D2@12']);
expect(_names(written), ['D2@720']);
expect(await storage.todayEntries(), hasLength(2));
});
@ -114,30 +114,30 @@ void main() {
final twin = dish('Twin', 1);
final written = await logDishes([
at(twin, 8),
at(twin, 8),
at(twin, 480),
at(twin, 480),
], storage: storage);
expect(_names(written), ['Twin@8']);
expect(await loggedToday(storage), ['Twin@8']);
expect(_names(written), ['Twin@480']);
expect(await loggedToday(storage), ['Twin@480']);
});
test('the same dish in a different slot is not a duplicate', () async {
final storage = freshStorage();
await storage.logMeal('D1', dishNutrition(dish('D1', 1)), slot: 8);
await storage.logMeal('D1', dishNutrition(dish('D1', 1)), slotMinute: 480);
final written = await logDishes([
at(dish('D1', 1), 12),
at(dish('D1', 1), 720),
], storage: storage);
expect(_names(written), ['D1@12']);
expect(await loggedToday(storage), ['D1@8', 'D1@12']);
expect(_names(written), ['D1@720']);
expect(await loggedToday(storage), ['D1@480', 'D1@720']);
});
});
group('planSummary', () {
test('lists slot, dish and the kcal total', () {
final plan = [at(dish('D1', 1), 8), at(dish('D2', 2), 12)];
final plan = [at(dish('D1', 1), 480), at(dish('D2', 2), 720)];
expect(
planSummary(plan),
'Will log 2 (300 kcal): 08:00 D1, 12:00 D2 — tap Confirm.',

View File

@ -106,9 +106,9 @@ void main() {
subject = dishes.take(3).toList();
key = key.substring('first_three_'.length);
}
final hours = [for (final part in key.split(',')) int.parse(part)];
final minutes = [for (final part in key.split(',')) int.parse(part)];
final actual = [
for (final item in assignSlots(subject, hours)) item.slot,
for (final item in assignSlots(subject, minutes)) item.slot,
];
expect(
actual,
@ -124,10 +124,10 @@ void main() {
// total. Run repeatedly: an unstable sort need not misbehave every time.
for (var attempt = 0; attempt < 5; attempt++) {
final ordered = assignSlots(parseMenu(fixture['payload']), const [
8,
12,
16,
20,
480,
720,
960,
1200,
]);
expect(
[for (final item in ordered) item.dish.name],

View File

@ -32,7 +32,7 @@ void main() {
expect(entry.id, 'abc-123');
expect(entry.desc, 'label_food');
expect(entry.kcal, 300.0);
expect(entry.slot, 16);
expect(entry.slotMinute, 960);
expect(entry.hmac, 'deadbeef');
expect(entry.components, hasLength(1));
expect(entry.components!.first.name, 'rice');
@ -45,7 +45,7 @@ void main() {
expect(entry.kcal, 0);
expect(entry.proteinG, 0);
expect(entry.source, 'manual');
expect(entry.slot, isNull);
expect(entry.slotMinute, isNull);
expect(entry.deleted, isFalse);
expect(entry.components, isNull);
});
@ -67,6 +67,7 @@ void main() {
);
final local = entry.toLocalJson();
final sync = entry.toSyncJson();
expect(local, sync);
expect(sync.containsKey('hmac'), isFalse);
expect(sync['desc'], 'toast');
});
@ -136,4 +137,50 @@ void main() {
expect(tombstoned.components, base.components);
});
});
group('slot minute round trip', () {
Map<String, Object?> entry(Map<String, Object?> slot) => {
'id': 'id-1',
'time': '2026-06-22T07:15:00+02:00',
'desc': 'toast',
'grams': 50.0,
'kcal': 120.0,
'protein_g': 3.0,
'carbs_g': 20.0,
'fat_g': 2.0,
'source': 'manual',
...slot,
};
test('a PC entry with slot_min survives a phone round trip', () {
// The regression this guards: keeping only the hour made every phone
// edit or tombstone republish a stripped copy of the PC's entry.
final raw = entry({'slot': 7, 'slot_min': 435});
final parsed = FoodEntry.fromJson(raw);
expect(parsed.slotMinute, 435);
expect(parsed.toSyncJson(), raw);
expect(parsed.copyWithDeleted().slotMinute, 435);
expect(parsed.copyWithDeleted().toSyncJson()['slot_min'], 435);
});
test('a legacy whole-hour entry stays byte-identical', () {
final raw = entry({'slot': 8});
final parsed = FoodEntry.fromJson(raw);
expect(parsed.slotMinute, 480);
expect(parsed.toSyncJson(), raw);
expect(parsed.toSyncJson().containsKey('slot_min'), isFalse);
});
test('an out-of-range peer slot is echoed, never thrown on', () {
// slotFields throws outside the day; writeLog encodes every entry, so a
// throw here would block all logging behind one bad synced entry.
expect(FoodEntry.fromJson(entry({'slot': 24})).toSyncJson()['slot'], 24);
final late = FoodEntry.fromJson(entry({'slot_min': 1510})).toSyncJson();
expect(late['slot'], 25);
expect(late['slot_min'], 1510);
final negative = FoodEntry.fromJson(entry({'slot': -1})).toSyncJson();
expect(negative.containsKey('slot'), isFalse);
expect(negative['slot_min'], -60);
});
});
}

View File

@ -1,94 +1,87 @@
/// Tests for the pure meal-schedule derivation.
///
/// The vector table below is duplicated verbatim from
/// `diet_guard/tests/test_meal_schedule.py`. KEEP THE TWO IN SYNC: it is the
/// only thing that catches a Python/Dart divergence before it reaches a
/// device, and a divergence there means one device nags for a checkpoint the
/// other never offers -- a slot that can never be satisfied, i.e. a permanent
/// lock.
/// The cross-language exact values live in the shared fixture
/// `tests/fixtures/meal_schedule_vectors.json`, asserted by
/// `meal_schedule_vectors_test.dart` (and by its Python mirror). This file
/// holds the properties: the grid sweep, the hour-formula regression and the
/// clamps a human should read without opening the fixture. The sweeps are
/// duplicated loop-for-loop in `diet_guard/tests/test_meal_schedule.py`.
library;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:flutter_test/flutter_test.dart';
/// (first, last, count, expected slots). Shared with the Python mirror.
const List<(int, int, int, List<int>)> scheduleVectors = [
// The eating window the user described, at every supported meal count.
(8, 20, 2, [8, 20]),
(8, 20, 3, [8, 14, 20]),
(8, 20, 4, [8, 12, 16, 20]), // today's hardcoded schedule
(8, 20, 5, [8, 11, 14, 17, 20]), // the user's stated example
(8, 20, 6, [8, 10, 13, 15, 18, 20]),
// A window that does not divide evenly: 14 hours across 3 gaps.
(7, 21, 4, [7, 12, 16, 21]),
(7, 21, 5, [7, 11, 14, 18, 21]),
(9, 19, 4, [9, 12, 16, 19]),
// Narrow windows: count is capped at the number of whole hours available,
// so the slots stay distinct instead of repeating an hour.
(8, 12, 6, [8, 9, 10, 11, 12]),
(8, 10, 5, [8, 9, 10]),
(8, 9, 4, [8, 9]),
// Whole-day extremes.
(0, 23, 6, [0, 5, 9, 14, 18, 23]),
(0, 1, 2, [0, 1]),
];
const int _h = 60;
/// The pre-minute whole-hour derivation, converted to minutes.
List<int> _oldHourSlots(int first, int last, int count) {
final span = last - first;
final divisions = count - 1;
return [
for (var index = 0; index < count; index++)
(first + (index * span + divisions ~/ 2) ~/ divisions) * _h,
];
}
bool _strictlyAscending(List<int> slots) {
for (var i = 1; i < slots.length; i++) {
if (slots[i - 1] >= slots[i]) return false;
}
return true;
}
MealSchedule _s(int first, int last, int count) =>
MealSchedule(firstMinute: first, lastMinute: last, count: count);
void main() {
group('slots', () {
for (final (first, last, count, expected) in scheduleVectors) {
test('$first-$last x$count derives $expected', () {
test('the default is the historical schedule', () {
expect(kDefaultSchedule.slots(), [480, 720, 960, 1200]);
});
// Upgrading must not move a checkpoint for the schedules people actually
// have, or every existing hour-tagged entry would satisfy a neighbour.
for (final (first, last, count) in const [
(8, 20, 4),
(8, 20, 5),
(7, 19, 5),
]) {
test('$first-$last x$count matches the old hour formula', () {
expect(
MealSchedule(first: first, last: last, count: count).slots(),
expected,
_s(first * _h, last * _h, count).slots(),
_oldHourSlots(first, last, count),
);
});
}
test('the default is the historical schedule', () {
expect(kDefaultSchedule.slots(), [8, 12, 16, 20]);
test('off-grid endpoints are exact; only the interior snaps', () {
final slots = _s(443, 1181, 5).slots();
expect(slots.first, 443);
expect(slots.last, 1181);
for (final slot in slots.sublist(1, slots.length - 1)) {
expect(slot % kSlotGridMinutes, 0);
}
});
test('endpoints stay exact when the spacing rounds', () {
final slots = const MealSchedule(first: 8, last: 20, count: 6).slots();
expect(slots.first, 8);
expect(slots.last, 20);
test("the user's quarter-hour schedule", () {
expect(_s(435, 1140, 5).slots(), [435, 615, 795, 960, 1140]);
});
});
group('normalized', () {
const cases = <(MealSchedule, MealSchedule)>[
(
MealSchedule(first: 8, last: 20, count: 99),
MealSchedule(first: 8, last: 20, count: kMaxMealCount),
),
(
MealSchedule(first: 8, last: 20, count: 0),
MealSchedule(first: 8, last: 20, count: kMinMealCount),
),
(
MealSchedule(first: -5, last: 20, count: 4),
MealSchedule(first: 0, last: 20, count: 4),
),
(
MealSchedule(first: 8, last: 99, count: 4),
MealSchedule(first: 8, last: 23, count: 4),
),
// last <= first is pulled forward to leave a one-hour window.
(
MealSchedule(first: 12, last: 12, count: 4),
MealSchedule(first: 12, last: 13, count: 2),
),
(
MealSchedule(first: 12, last: 3, count: 4),
MealSchedule(first: 12, last: 13, count: 2),
),
// first cannot occupy the final hour, or no window would remain.
(
MealSchedule(first: 23, last: 23, count: 2),
MealSchedule(first: 22, last: 23, count: 2),
),
final cases = <(MealSchedule, MealSchedule)>[
(_s(480, 1200, 99), _s(480, 1200, kMaxMealCount)),
(_s(480, 1200, 0), _s(480, 1200, kMinMealCount)),
(_s(-5, 1200, 4), _s(0, 1200, 4)),
(_s(480, 9999, 4), _s(480, 1439, 4)),
// last <= first is pulled forward to leave one grid step of window.
(_s(720, 720, 4), _s(720, 735, 2)),
(_s(720, 3, 4), _s(720, 735, 2)),
// first cannot sit in the final grid step, or no window remains.
(_s(1439, 1439, 2), _s(1424, 1439, 2)),
// Count is capped by the grid: 60 minutes hold 5 quarter-hour marks.
(_s(480, 540, 6), _s(480, 540, 5)),
];
for (final (input, expected) in cases) {
test('$input clamps to $expected', () {
expect(input.normalized(), expected);
@ -96,56 +89,82 @@ void main() {
}
test('garbage still yields usable slots', () {
expect(
const MealSchedule(first: 99, last: -5, count: 999).slots(),
[22, 23],
);
expect(_s(9999, -5, 999).slots(), [1424, 1439]);
});
});
group('enforcementEndHour', () {
group('enforcementEndMinute', () {
test('the default keeps the historical 22:00 cutoff', () {
expect(kDefaultSchedule.enforcementEndHour, 22);
expect(kDefaultSchedule.enforcementEndMinute, 22 * _h);
});
test('the tail follows the last meal', () {
expect(
const MealSchedule(first: 8, last: 18, count: 4).enforcementEndHour,
20,
);
test('the tail follows the last meal, to the minute', () {
expect(_s(480, 1095, 4).enforcementEndMinute, 1215);
});
test('is clamped to the end of the day', () {
// An unclamped 23 + 2 = 25 would make `hour < cutoff` vacuously true,
// so the enforcement window would never close.
expect(
const MealSchedule(first: 8, last: 23, count: 4).enforcementEndHour,
24,
);
// An unclamped 1380 + 120 = 1500 would make `minute < cutoff`
// vacuously true, so the enforcement window would never close.
expect(_s(480, 1380, 4).enforcementEndMinute, kMinutesPerDay);
});
test('follows the normalised last meal', () {
final schedule = _s(720, 3, 4);
expect(schedule.enforcementEndMinute, schedule.slots().last + 120);
});
});
test('every input yields ascending slots with exact endpoints', () {
// The Dart half of the cross-language parity guarantee; the Python mirror
// runs the identical sweep.
for (var first = -2; first < 26; first++) {
for (var last = -2; last < 26; last++) {
for (var count = -2; count < 10; count++) {
final schedule = MealSchedule(
first: first,
last: last,
count: count,
);
group('wire', () {
test('a whole-hour schedule encodes exactly as before', () {
expect(scheduleToWire(kDefaultSchedule), {'f': 8, 'l': 20, 'n': 4});
});
test('off-hour endpoints add minute fields', () {
expect(scheduleToWire(_s(435, 1181, 5)), {
'f': 7,
'l': 19,
'n': 5,
'fm': 435,
'lm': 1181,
});
});
test('unusable values decode to null', () {
expect(scheduleFromWire({'f': true, 'l': 20, 'n': 4}), isNull);
expect(scheduleFromWire('not a map'), isNull);
});
});
test('grid sweep yields ascending slots with exact endpoints', () {
// The Python mirror runs the identical loop. A wire round trip rides
// along, because it is the same sweep's worth of schedules. Plain checks
// with `fail` rather than `expect` per cell keep 46k cells fast.
for (var first = 0; first < kMinutesPerDay; first += kSlotGridMinutes) {
for (var last = 0; last < kMinutesPerDay; last += kSlotGridMinutes) {
for (var count = kMinMealCount; count <= kMaxMealCount; count++) {
final schedule = _s(first, last, count);
final normalized = schedule.normalized();
final slots = schedule.slots();
final ok =
slots.first == normalized.firstMinute &&
slots.last == normalized.lastMinute &&
slots.length == normalized.count &&
_strictlyAscending(slots) &&
slots.first >= 0 &&
slots.last < kMinutesPerDay &&
scheduleFromWire(scheduleToWire(schedule)) == normalized;
if (!ok) fail('$schedule derived $slots');
}
}
}
});
expect(slots.first, normalized.first);
expect(slots.last, normalized.last);
expect(slots.length, normalized.count);
expect(slots.toSet().length, slots.length);
expect(slots, orderedEquals(List<int>.of(slots)..sort()));
expect(slots.length, greaterThanOrEqualTo(kMinMealCount));
expect(slots.length, lessThanOrEqualTo(kMaxMealCount));
test('off-grid sweep stays strictly ascending', () {
for (var first = 0; first < 120; first += 7) {
for (var width = 15; width < 200; width += 11) {
for (var count = kMinMealCount; count <= kMaxMealCount; count++) {
final slots = _s(first, first + width, count).slots();
if (!_strictlyAscending(slots)) fail('$first+$width x$count: $slots');
}
}
}

View File

@ -0,0 +1,177 @@
/// The Dart half of the cross-language meal-slot parity gate.
///
/// `diet_guard/tests/test_meal_schedule_vectors.py` asserts the *same*
/// expectations against the *same* `tests/fixtures/meal_schedule_vectors.json`.
/// Two independently written suites from the same prose is not a gate -- one
/// shared input with one shared expected result is: a device that derives a
/// slot its peer never offers has a checkpoint that can never be satisfied,
/// i.e. a permanent lock. Regenerate with
/// `scripts/build_meal_schedule_fixture.py`.
library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:flutter_test/flutter_test.dart';
/// The repo root, found by walking up from wherever `flutter test` runs.
Directory get _repoRoot {
var dir = Directory.current.absolute;
while (!File('${dir.path}/pubspec.yaml').existsSync()) {
final parent = dir.parent;
if (parent.path == dir.path) {
fail('could not locate app/ from ${Directory.current.path}');
}
dir = parent;
}
// `dir` is app/; the fixture is shared, so it lives at the repo root.
return dir.parent;
}
File get _fixtureFile =>
File('${_repoRoot.path}/tests/fixtures/meal_schedule_vectors.json');
MealSchedule _schedule(Object? row) {
final values = (row! as List).cast<int>();
return MealSchedule(
firstMinute: values[0],
lastMinute: values[1],
count: values[2],
);
}
DateTime _at(int minute) => DateTime(2026, 1, 1, minute ~/ 60, minute % 60);
List<int> _ints(Object? value) => (value! as List).cast<int>();
void main() {
late Map<String, dynamic> vectors;
setUpAll(() {
vectors =
jsonDecode(_fixtureFile.readAsStringSync()) as Map<String, dynamic>;
});
List<Map<String, dynamic>> rows(String key) =>
(vectors[key] as List).cast<Map<String, dynamic>>();
test('the shared fixture is present', () {
expect(
_fixtureFile.existsSync(),
isTrue,
reason: 'shared parity fixture missing at ${_fixtureFile.path}',
);
});
test('schedules: normalised form, slots, cutoff and wire', () {
expect(rows('schedules'), isNotEmpty);
for (final row in rows('schedules')) {
final schedule = _schedule(row['input']);
final reason = '${row['input']}';
expect(
schedule.normalized(),
_schedule(row['normalized']),
reason: reason,
);
expect(schedule.slots(), _ints(row['slots']), reason: reason);
expect(
schedule.enforcementEndMinute,
row['enforcement_end_minute'],
reason: reason,
);
expect(scheduleToWire(schedule), row['wire'], reason: reason);
expect(
scheduleFromWire(row['wire']),
schedule.normalized(),
reason: reason,
);
}
});
test('time edges: every clock-reading function', () {
expect(rows('time_edges'), isNotEmpty);
for (final row in rows('time_edges')) {
final schedule = _schedule(row['schedule']);
final now = _at(row['minute'] as int);
final reason = '${row['schedule']} @ ${row['minute']}';
expect(
withinEnforcementWindow(now, schedule),
row['within_window'],
reason: reason,
);
expect(
elapsedSlots(now, schedule),
_ints(row['elapsed']),
reason: reason,
);
expect(currentSlot(now, schedule), row['current_slot'], reason: reason);
expect(slotForLog(now, schedule), row['slot_for_log'], reason: reason);
}
});
test('missing slots', () {
for (final row in rows('missing')) {
final actual = missingSlots(
_at(row['minute'] as int),
_ints(row['logged']).toSet(),
_schedule(row['schedule']),
);
expect(actual, _ints(row['missing']), reason: '$row');
}
});
test('nearest slot', () {
for (final row in rows('nearest')) {
final actual = nearestSlot(
row['minute'] as int,
_schedule(row['schedule']),
);
expect(actual, row['nearest'], reason: '$row');
}
});
test('satisfied slots', () {
for (final row in rows('satisfied')) {
final actual = satisfiedSlots(
_ints(row['entry_minutes']),
_schedule(row['schedule']),
).toList()..sort();
expect(actual, _ints(row['satisfied']), reason: '${row['name']}');
}
});
test('labels', () {
for (final row in rows('labels')) {
expect(slotLabel(row['minute'] as int), row['label'], reason: '$row');
}
});
test('schedule wire decode', () {
for (final row in rows('schedule_wire_decode')) {
final expected = row['schedule'] == null
? null
: _schedule(row['schedule']);
expect(scheduleFromWire(row['raw']), expected, reason: '$row');
}
});
test('slot fields', () {
for (final row in rows('slot_fields')) {
final minute = row['minute'] as int;
if (row['error'] == true) {
expect(() => slotFields(minute), throwsArgumentError, reason: '$row');
} else {
expect(slotFields(minute), row['fields'], reason: '$row');
}
}
});
test('entry slot minute', () {
for (final row in rows('entry_slot_minute')) {
final entry = (row['entry'] as Map).cast<String, Object?>();
expect(entrySlotMinute(entry), row['minute'], reason: '$row');
}
});
}

View File

@ -1,229 +1,172 @@
/// Tests for `models/slot.dart`, in minutes of day.
///
/// Mirrors `diet_guard/tests/test_slots.py`, `test_slots_nearest.py` and
/// `test_slot_wire.py`; the exhaustive cross-language edges live in the shared
/// fixture (`meal_schedule_vectors_test.dart`).
library;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:flutter_test/flutter_test.dart';
DateTime _at(int hour, [int minute = 0]) => DateTime(2026, 6, 22, hour, minute);
MealSchedule _s(int first, int last, int count) =>
MealSchedule(firstMinute: first, lastMinute: last, count: count);
void main() {
group('daySlots', () {
test('returns the four fixed hourly slots', () {
expect(daySlots(kDefaultSchedule), [8, 12, 16, 20]);
});
test('minuteOfDay counts minutes and ignores seconds', () {
expect(minuteOfDay(DateTime(2026, 6, 22, 7, 15, 59)), 435);
expect(minuteOfDay(_at(23, 59)), 1439);
});
test('daySlots returns the four default slots', () {
expect(daySlots(kDefaultSchedule), [480, 720, 960, 1200]);
});
group('withinEnforcementWindow', () {
test('false before the day start hour', () {
expect(
withinEnforcementWindow(DateTime(2026, 6, 22, 7, 59), kDefaultSchedule),
isFalse,
);
test('false at 07:59, true at 08:00', () {
expect(withinEnforcementWindow(_at(7, 59), kDefaultSchedule), isFalse);
expect(withinEnforcementWindow(_at(8), kDefaultSchedule), isTrue);
});
test('true at the day start hour', () {
expect(
withinEnforcementWindow(DateTime(2026, 6, 22, 8, 0), kDefaultSchedule),
isTrue,
);
test('true at 21:59, false at the 22:00 cutoff', () {
expect(withinEnforcementWindow(_at(21, 59), kDefaultSchedule), isTrue);
expect(withinEnforcementWindow(_at(22), kDefaultSchedule), isFalse);
});
test('true just before the eating end hour', () {
expect(
withinEnforcementWindow(
DateTime(2026, 6, 22, 21, 59),
kDefaultSchedule,
),
isTrue,
);
});
test('false at the eating end hour (exclusive)', () {
expect(
withinEnforcementWindow(DateTime(2026, 6, 22, 22, 0), kDefaultSchedule),
isFalse,
);
test('a 07:15 breakfast opens the window at 07:15', () {
final schedule = _s(435, 1140, 5);
expect(withinEnforcementWindow(_at(7, 14), schedule), isFalse);
expect(withinEnforcementWindow(_at(7, 15), schedule), isTrue);
});
});
group('elapsedSlots', () {
test('empty outside the enforcement window', () {
expect(
elapsedSlots(DateTime(2026, 6, 22, 23, 0), kDefaultSchedule),
isEmpty,
);
expect(elapsedSlots(_at(23), kDefaultSchedule), isEmpty);
expect(elapsedSlots(_at(7, 59), kDefaultSchedule), isEmpty);
});
test('only the 8 slot right at day start', () {
expect(elapsedSlots(DateTime(2026, 6, 22, 8, 0), kDefaultSchedule), [8]);
test('grows through the day', () {
expect(elapsedSlots(_at(8), kDefaultSchedule), [480]);
expect(elapsedSlots(_at(15, 59), kDefaultSchedule), [480, 720]);
expect(elapsedSlots(_at(21), kDefaultSchedule), [480, 720, 960, 1200]);
});
test('8 and 12 mid-afternoon before 16', () {
expect(elapsedSlots(DateTime(2026, 6, 22, 15, 59), kDefaultSchedule), [
8,
12,
]);
});
test('all four slots once 20:00 has passed', () {
expect(elapsedSlots(DateTime(2026, 6, 22, 21, 0), kDefaultSchedule), [
8,
12,
16,
20,
]);
test('a slot opens on its minute', () {
final schedule = _s(435, 1140, 5);
expect(elapsedSlots(_at(10, 14), schedule), [435]);
expect(elapsedSlots(_at(10, 15), schedule), [435, 615]);
});
});
group('missingSlots', () {
test('excludes already-logged elapsed slots', () {
expect(
missingSlots(DateTime(2026, 6, 22, 17, 0), {8}, kDefaultSchedule),
[12, 16],
);
});
test('empty once every elapsed slot is logged', () {
expect(
missingSlots(DateTime(2026, 6, 22, 17, 0), {
8,
12,
16,
}, kDefaultSchedule),
isEmpty,
);
});
test('missingSlots excludes logged slots', () {
expect(missingSlots(_at(17), {480}, kDefaultSchedule), [720, 960]);
expect(missingSlots(_at(17), {480, 720, 960}, kDefaultSchedule), isEmpty);
});
group('currentSlot', () {
test('null outside the enforcement window', () {
expect(
currentSlot(DateTime(2026, 6, 22, 6, 0), kDefaultSchedule),
isNull,
);
});
test('returns the most recently elapsed slot', () {
expect(currentSlot(DateTime(2026, 6, 22, 17, 41), kDefaultSchedule), 16);
});
test('returns 8 right at day start', () {
expect(currentSlot(DateTime(2026, 6, 22, 8, 0), kDefaultSchedule), 8);
});
test('currentSlot is the latest elapsed slot, or null', () {
expect(currentSlot(_at(6), kDefaultSchedule), isNull);
expect(currentSlot(_at(17, 41), kDefaultSchedule), 960);
});
group('slotForLog', () {
// Keep in lockstep with `diet_guard/tests/test_slots.py`'s
// TestSlotForLog: a divergence means the PC and the phone disagree about
// which checkpoint a meal satisfied.
DateTime at(int hour) => DateTime(2026, 6, 22, hour, 0);
test('clamps to the first slot before the window opens', () {
expect(slotForLog(at(7), kDefaultSchedule), 8);
test('clamps before the window and after it', () {
expect(slotForLog(_at(0), kDefaultSchedule), 480);
expect(slotForLog(_at(7, 59), kDefaultSchedule), 480);
expect(slotForLog(_at(13), kDefaultSchedule), 720);
expect(slotForLog(_at(21, 59), kDefaultSchedule), 1200);
expect(slotForLog(_at(22), kDefaultSchedule), 1200);
});
test('clamps to the first slot in the small hours', () {
expect(slotForLog(at(0), kDefaultSchedule), 8);
});
test('is unchanged exactly at the first slot', () {
expect(slotForLog(at(8), kDefaultSchedule), 8);
});
test('matches currentSlot inside the window', () {
expect(
slotForLog(at(13), kDefaultSchedule),
currentSlot(at(13), kDefaultSchedule),
);
expect(slotForLog(at(13), kDefaultSchedule), 12);
});
test('is unchanged at the last in-window hour', () {
expect(slotForLog(at(21), kDefaultSchedule), 20);
});
test('clamps to the last slot once the window closes', () {
expect(slotForLog(at(22), kDefaultSchedule), 20);
});
test('clamps to the last slot late in the evening', () {
expect(slotForLog(at(23), kDefaultSchedule), 20);
});
test('never returns a slot outside the schedule', () {
for (var hour = 0; hour < 24; hour++) {
expect(
daySlots(kDefaultSchedule),
contains(slotForLog(at(hour), kDefaultSchedule)),
);
}
});
test('clamps the same way across configured schedules', () {
// Sweeps every hour against several windows. `test_slots.py` runs the
// identical sweep: the two must agree on every cell, because a device
// that attributes a meal to a different slot than its peer leaves the
// other device's checkpoint permanently unsatisfied.
const schedules = [
test('clamps the same way at every minute across schedules', () {
// `test_slots.py` runs the identical sweep.
final schedules = [
kDefaultSchedule,
MealSchedule(first: 8, last: 20, count: 5),
MealSchedule(first: 6, last: 22, count: 6),
MealSchedule(first: 0, last: 23, count: 2),
MealSchedule(first: 10, last: 14, count: 3),
_s(480, 1200, 5),
_s(435, 1140, 5),
_s(443, 1181, 4),
_s(0, 1439, 2),
_s(600, 840, 3),
];
for (final schedule in schedules) {
final slots = daySlots(schedule);
for (var hour = 0; hour < 24; hour++) {
final attributed = slotForLog(at(hour), schedule);
expect(slots, contains(attributed));
if (hour < slots.first) {
expect(attributed, slots.first);
} else if (hour >= schedule.enforcementEndHour) {
expect(attributed, slots.last);
for (var minute = 0; minute < 1440; minute++) {
final attributed = slotForLog(
_at(minute ~/ 60, minute % 60),
schedule,
);
final int expected;
if (minute < slots.first) {
expected = slots.first;
} else if (minute >= schedule.enforcementEndMinute) {
expected = slots.last;
} else {
// Inside the window: the most recent slot that has opened.
expect(attributed, slots.where((s) => s <= hour).last);
expected = slots.where((s) => s <= minute).last;
}
if (attributed != expected) fail('$schedule @ $minute: $attributed');
}
}
});
});
group('configured schedules', () {
test('five meals shifts the checkpoints', () {
const schedule = MealSchedule(first: 8, last: 20, count: 5);
expect(daySlots(schedule), [8, 11, 14, 17, 20]);
expect(elapsedSlots(DateTime(2026, 6, 22, 14), schedule), [8, 11, 14]);
expect(
missingSlots(DateTime(2026, 6, 22, 14), {8, 11}, schedule),
[14],
);
});
test('enforcement follows the last meal', () {
const schedule = MealSchedule(first: 8, last: 18, count: 3);
expect(
withinEnforcementWindow(DateTime(2026, 6, 22, 19), schedule),
isTrue,
);
expect(
withinEnforcementWindow(DateTime(2026, 6, 22, 20), schedule),
isFalse,
);
expect(elapsedSlots(DateTime(2026, 6, 22, 20), schedule), isEmpty);
});
test('midnight is a real slot, not a falsy absence', () {
const schedule = MealSchedule(first: 0, last: 12, count: 3);
expect(daySlots(schedule), [0, 6, 12]);
expect(currentSlot(DateTime(2026, 6, 22), schedule), 0);
expect(slotForLog(DateTime(2026, 6, 22), schedule), 0);
final schedule = _s(0, 720, 3);
expect(daySlots(schedule), [0, 360, 720]);
expect(currentSlot(_at(0), schedule), 0);
expect(slotForLog(_at(0), schedule), 0);
});
});
group('slotLabel', () {
test('pads single-digit hours', () {
expect(slotLabel(8), '08:00');
group('nearestSlot / satisfiedSlots', () {
test('an exact halfway goes to the earlier slot', () {
expect(nearestSlot(600, kDefaultSchedule), 480);
expect(nearestSlot(601, kDefaultSchedule), 720);
});
test('formats double-digit hours', () {
expect(slotLabel(20), '20:00');
test('outside the window clamps to the ends', () {
expect(nearestSlot(-60, kDefaultSchedule), 480);
expect(nearestSlot(1800, kDefaultSchedule), 1200);
});
test('meals logged at 07:00 and 10:00 survive a move to 07:15', () {
expect(satisfiedSlots([420, 600], _s(435, 1140, 5)), {435, 615});
});
test('two meals on one slot satisfy only that slot', () {
expect(satisfiedSlots([480, 540], kDefaultSchedule), {480});
expect(satisfiedSlots(const [], kDefaultSchedule), isEmpty);
});
});
group('slotFields / entrySlotMinute', () {
test('a whole hour is byte-identical to the old format', () {
expect(slotFields(480), {'slot': 8});
expect(slotFields(435), {'slot': 7, 'slot_min': 435});
});
test('a minute outside the day is refused', () {
expect(() => slotFields(-1), throwsArgumentError);
expect(() => slotFields(1440), throwsArgumentError);
});
test('slot_min wins; legacy slot is an hour; bools are not ints', () {
expect(entrySlotMinute({'slot': 8}), 480);
expect(entrySlotMinute({'slot': 5, 'slot_min': 0}), 0);
expect(entrySlotMinute({'slot': 8, 'slot_min': true}), 480);
expect(entrySlotMinute({'slot': true}), isNull);
expect(entrySlotMinute({}), isNull);
});
});
test('slotLabel zero-pads and wraps into the day', () {
expect(slotLabel(435), '07:15');
expect(slotLabel(5), '00:05');
expect(slotLabel(1200), '20:00');
expect(slotLabel(1440), '00:00');
expect(slotLabel(-15), '23:45');
});
}

View File

@ -134,7 +134,7 @@ void main() {
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, {8, 12, 16, 20});
expect(host.loggedSlots, {480, 720, 960, 1200});
expect(host.desc.text, isEmpty, reason: 'D1 was logged by the fill');
});
@ -144,7 +144,7 @@ void main() {
await storage.logMeal(
'own breakfast',
dishNutrition(dish('own', 1)),
slot: 8,
slotMinute: 480,
);
await host.onFillAll();
await host.onFillAll();

View File

@ -56,7 +56,7 @@ void main() {
expect(find.text('12:00'), findsOneWidget);
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
);
final state = tester.state<State<LogMealScreen>>(
find.byType(LogMealScreen),

View File

@ -85,7 +85,7 @@ void main() {
final log = await LogStorageService.instance.readLog();
final future = log[tomorrowKey]!.single;
expect(future.desc, 'future meal');
expect(future.slot, firstSlot);
expect(future.slotMinute, firstSlot);
expect(future.time.startsWith(tomorrowKey), isTrue);
// Back to logging for today.

View File

@ -163,7 +163,7 @@ void main() {
carbsG: 40,
fatG: 5,
source: 'manual',
slot: 8,
slotMinute: 480,
),
],
});

View File

@ -85,12 +85,35 @@ void main() {
expect(find.text('Meals per day'), findsOneWidget);
});
});
testWidgets('an exact 07:23 first meal saves the schedule', (tester) async {
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester);
await tester.tap(find.byTooltip('Type or pick an exact time').first);
await settle(tester);
await tester.tap(find.byIcon(Icons.keyboard_outlined));
await settle(tester);
final fields = find.descendant(
of: find.byType(TimePickerDialog),
matching: find.byType(TextField),
);
await tester.enterText(fields.at(0), '07');
await tester.enterText(fields.at(1), '23');
await tester.tap(find.text('OK'));
await settle(tester);
// Through the real _applySchedule: normalised, recorded, persisted.
expect(MealScheduleService.current.firstMinute, 443);
expect(find.text('07:23 · 11:30 · 15:45 · 20:00'), findsOneWidget);
});
});
testWidgets('reflects a five-meal schedule as the user\'s example', (
tester,
) async {
await tester.runAsync(() async {
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
);
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester);

View File

@ -75,37 +75,42 @@ void main() {
});
test(
'shows due-and-unlogged slots, cancels logged and upcoming ones',
'shows due-and-unlogged slots, cancels one once its meal is logged',
() async {
await LogStorageService.instance.logMeal('lunch', _manual, slot: 12);
await checkAndNotify(now: DateTime(2026, 1, 1, 16));
Set<Object?> ids(String method) => {
for (final call in notificationLog)
if (call.method == method) (call.arguments as Map)['id'],
};
// Ids are slot minutes: 08:00, 12:00 and 16:00 are due by 16:00.
expect(ids('show'), {480, 720, 960});
notificationLog.clear();
await LogStorageService.instance.logMeal(
'lunch',
_manual,
slotMinute: 720,
);
await checkAndNotify(now: DateTime(2026, 1, 1, 16));
final shown = notificationLog
.where((c) => c.method == 'show')
.map((c) => (c.arguments as Map)['id'])
.toSet();
final cancelled = notificationLog
.where((c) => c.method == 'cancel')
.map((c) => (c.arguments as Map)['id'])
.toSet();
expect(shown, {8, 16});
// Every other id in the 0..23 space is cancelled, not just the other
// slots of the current schedule -- see syncToSlots' comment.
expect(cancelled, containsAll(<int>{12, 20}));
expect(cancelled.intersection(shown), isEmpty);
expect(ids('show'), {480, 960});
expect(ids('cancel'), {720});
},
);
test('cancels everything when every due slot is logged', () async {
await LogStorageService.instance.logMeal('breakfast', _manual, slot: 8);
test('a tick with every due slot logged posts and cancels nothing', () async {
await LogStorageService.instance.logMeal(
'breakfast',
_manual,
slotMinute: 480,
);
await checkAndNotify(now: DateTime(2026, 1, 1, 8));
expect(notificationLog.where((c) => c.method == 'show'), isEmpty);
// 24, not 4: syncToSlots sweeps the whole id space so a schedule change
// cannot orphan the ids it no longer contains.
expect(notificationLog.where((c) => c.method == 'cancel'), hasLength(24));
// Nothing is showing, so nothing is cancelled: the active-id lookup
// replaced a sweep of the whole id space on every tick.
expect(notificationLog.where((c) => c.method == 'cancel'), isEmpty);
});
test('uses the real clock when now is omitted', () async {
@ -119,7 +124,11 @@ void main() {
});
test('still syncs when nothing is due', () async {
await LogStorageService.instance.logMeal('breakfast', _manual, slot: 8);
await LogStorageService.instance.logMeal(
'breakfast',
_manual,
slotMinute: 480,
);
SharedPreferences.setMockInitialValues({
'sync.owner': 'o',
'sync.repo': 'r',
@ -216,6 +225,6 @@ void main() {
.where((c) => c.method == 'show')
.map((c) => (c.arguments as Map)['id'])
.toSet();
expect(shown, isNot(contains(12)));
expect(shown, isNot(contains(720)));
});
}

View File

@ -59,11 +59,11 @@ void main() {
final entry = await LogStorageService.instance.logMeal(
'toast',
_manual,
slot: 8,
slotMinute: 480,
);
expect(entry.id, isNotEmpty);
expect(entry.hmac, isNull);
expect(entry.slot, 8);
expect(entry.slotMinute, 480);
expect(entry.desc, 'toast');
});
@ -100,7 +100,7 @@ void main() {
final entry = await LogStorageService.instance.logMeal(
'future meal',
_manual,
slot: 12,
slotMinute: 720,
when: future,
);
final log = await LogStorageService.instance.readLog();
@ -195,9 +195,17 @@ void main() {
});
group('loggedSlotsToday', () {
test('returns only the slots with a logged entry', () async {
await LogStorageService.instance.logMeal('a', _manual, slot: 8);
await LogStorageService.instance.logMeal('a', _manual, slotMinute: 480);
await LogStorageService.instance.logMeal('b', _manual);
expect(await LogStorageService.instance.loggedSlotsToday(), {8});
expect(await LogStorageService.instance.loggedSlotsToday(), {480});
});
test('snaps an off-slot minute to the nearest slot', () async {
// 07:30 under the default 08/12/16/20 schedule satisfies 08:00, and
// two meals snapping onto one slot satisfy only that slot.
await LogStorageService.instance.logMeal('a', _manual, slotMinute: 450);
await LogStorageService.instance.logMeal('b', _manual, slotMinute: 500);
expect(await LogStorageService.instance.loggedSlotsToday(), {480});
});
});
}

View File

@ -17,7 +17,7 @@ void main() {
test('round trips', () {
const entry = ScheduleEntry(
effectiveFrom: '2026-08-16',
schedule: MealSchedule(first: 8, last: 20, count: 5),
schedule: MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
editedAt: '2026-08-16T12:00:00.000',
);
expect(
@ -32,7 +32,7 @@ void main() {
'l': 20,
'n': 99,
});
expect(entry!.schedule, const MealSchedule(first: 8, last: 20, count: 6));
expect(entry!.schedule, const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 6));
});
test('falls back to the epoch when the stamp is missing', () {
@ -86,7 +86,7 @@ void main() {
final history = MealScheduleHistory(const [
ScheduleEntry(
effectiveFrom: '2026-08-16',
schedule: MealSchedule(first: 8, last: 20, count: 5),
schedule: MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
editedAt: 't',
),
]);
@ -97,7 +97,7 @@ void main() {
final history = MealScheduleHistory(const [
ScheduleEntry(
effectiveFrom: '2026-08-16',
schedule: MealSchedule(first: 8, last: 20, count: 5),
schedule: MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
editedAt: 't1',
),
ScheduleEntry(
@ -108,30 +108,30 @@ void main() {
]);
expect(
history.forDay('2026-08-16'),
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
);
expect(history.forDay('2026-05-01'), kDefaultSchedule);
});
test('upsert replaces a same-day re-edit', () {
final once = MealScheduleHistory.empty.upsert(
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
when: _at('2026-08-16'),
);
final twice = once.upsert(
const MealSchedule(first: 9, last: 21, count: 3),
const MealSchedule(firstMinute: 9 * 60, lastMinute: 21 * 60, count: 3),
when: _at('2026-08-16'),
);
expect(twice.entries, hasLength(1));
expect(
twice.entries.single.schedule,
const MealSchedule(first: 9, last: 21, count: 3),
const MealSchedule(firstMinute: 9 * 60, lastMinute: 21 * 60, count: 3),
);
});
test('upsert defaults to now', () {
final history = MealScheduleHistory.empty.upsert(
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
);
expect(history.entries, hasLength(1));
});

View File

@ -56,13 +56,13 @@ void main() {
() async {
await MealScheduleService.initForTesting(store);
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
);
await MealScheduleService.initForTesting(store);
expect(
MealScheduleService.current,
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
);
// The whole point of the history: a day before the edit keeps the
// four-meal schedule it was actually judged against.
@ -103,7 +103,7 @@ void main() {
() async {
await MealScheduleService.initForTesting(store);
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
);
// A pre-feature peer contributes no `sched:` fields; writing that back
@ -111,20 +111,20 @@ void main() {
await MealScheduleService.instance.applyMerged(const []);
expect(
MealScheduleService.current,
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
);
final stamp = DateTime.parse('2026-08-16T09:00:00.000');
await MealScheduleService.instance.applyMerged([
ScheduleEntry(
effectiveFrom: kScheduleEpochDay,
schedule: const MealSchedule(first: 7, last: 19, count: 3),
schedule: const MealSchedule(firstMinute: 7 * 60, lastMinute: 19 * 60, count: 3),
editedAt: stamp.toIso8601String(),
),
], updatedAt: stamp);
expect(
MealScheduleService.current,
const MealSchedule(first: 7, last: 19, count: 3),
const MealSchedule(firstMinute: 7 * 60, lastMinute: 19 * 60, count: 3),
);
// The winner's stamp is kept verbatim, so re-syncing is idempotent.
expect(MealScheduleService.updatedAt, stamp);
@ -134,7 +134,7 @@ void main() {
test('the stored document is plain readable JSON', () async {
await MealScheduleService.initForTesting(store);
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
when: _at('2026-08-16'),
);
final decoded =
@ -143,5 +143,22 @@ void main() {
expect(decoded['v'], 1);
expect((decoded['e']! as Map).keys, contains('2026-08-16'));
});
test('an off-the-hour schedule survives a reload', () async {
const offHour = MealSchedule(firstMinute: 443, lastMinute: 1155, count: 5);
await MealScheduleService.initForTesting(store);
await MealScheduleService.instance.recordChange(offHour);
MealScheduleService.resetForTesting();
await MealScheduleService.initForTesting(store);
expect(MealScheduleService.current, offHour);
final decoded =
jsonDecode(store.documents[MealScheduleService.documentName]!)
as Map<String, Object?>;
final today = (decoded['e']! as Map).values.last as Map;
expect(today['fm'], 443);
expect(today['lm'], 1155);
});
});
}

View File

@ -1,5 +1,8 @@
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/services/notification_backend.dart';
import 'package:diet_guard_app/services/notification_backend_io.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
@ -41,98 +44,134 @@ void main() {
expect(await NotificationService.instance.requestPermission(), isTrue);
});
test('syncToSlots shows due slots and cancels the rest', () async {
final log = installFakeAndroidNotifications();
Future<List<MethodCall>> ready({Map<int, String>? active}) async {
final log = installFakeAndroidNotifications(active: active);
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await NotificationService.init();
log.clear();
return log;
}
await NotificationService.instance.syncToSlots([12, 20]);
Set<Object?> ids(List<MethodCall> log, String method) => {
for (final call in log)
if (call.method == method) (call.arguments as Map)['id'],
};
final shown = log
.where((c) => c.method == 'show')
.map((c) => (c.arguments as Map)['id'])
.toSet();
final cancelled = log
.where((c) => c.method == 'cancel')
.map((c) => (c.arguments as Map)['id'])
.toSet();
expect(shown, {12, 20});
// Every other id in the 0..23 space is cancelled, not just the other
// slots of the current schedule -- see syncToSlots' comment.
expect(cancelled, containsAll(<int>{8, 16}));
expect(cancelled.intersection(shown), isEmpty);
test('syncToSlots shows due slots and cancels other reminders', () async {
final log = await ready(
active: {480: reminderChannelId, 720: reminderChannelId},
);
await NotificationService.instance.syncToSlots([720, 1200]);
expect(ids(log, 'show'), {720, 1200});
expect(ids(log, 'cancel'), {480});
});
test('syncToSlots with no due slots cancels every id in the day', () async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await NotificationService.init();
log.clear();
test('a quiet tick costs one lookup and no cancels', () async {
// The cost bound: the old design swept every id each tick, which at
// minute resolution would be 1440 platform calls per background run.
final log = await ready();
await NotificationService.instance.syncToSlots(const []);
expect(log.where((c) => c.method == 'show'), isEmpty);
// 24, not 4: the slot hour doubles as the notification id, so a
// schedule change would otherwise orphan the ids it no longer contains.
expect(log.where((c) => c.method == 'cancel'), hasLength(24));
expect(log.map((c) => c.method), ['getActiveNotifications']);
});
test('the upgrade cancels reminders keyed by the old slot hours', () async {
// Older builds used the slot *hour* as the id. Nothing in the minute
// schedule names 8/12/16, so only the active lookup can find them.
final log = await ready(
active: {
8: reminderChannelId,
12: reminderChannelId,
16: reminderChannelId,
},
);
await NotificationService.instance.syncToSlots([720]);
expect(ids(log, 'cancel'), {8, 12, 16});
expect(ids(log, 'show'), {720});
});
test('syncToSlots cancels ids orphaned by a schedule change', () async {
// The regression this guards: the slot hour *is* the notification id,
// and syncToSlots used to iterate only the current schedule's slots.
// Switching 08/12/16/20 -> 08/11/14/17/20 therefore left ids 12 and 16
// posted with nothing that would ever cancel them, so the phone nagged
// forever about checkpoints that no longer existed.
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await NotificationService.init();
// Due under the old four-meal schedule.
await NotificationService.instance.syncToSlots([12, 16]);
// The regression this guards: the slot minute *is* the notification
// id, so iterating only the current schedule's slots would leave the
// old schedule's reminders posted forever.
final log = await ready();
await NotificationService.instance.syncToSlots([720, 960]);
log.clear();
// Now due under a five-meal schedule, which has neither 12 nor 16.
await NotificationService.instance.syncToSlots([11]);
final cancelled = log
.where((c) => c.method == 'cancel')
.map((c) => (c.arguments as Map)['id'])
.toSet();
expect(cancelled, containsAll(<int>{12, 16}));
// Now due under a schedule that has neither 720 nor 960.
await NotificationService.instance.syncToSlots([660]);
expect(ids(log, 'cancel'), {720, 960});
});
test('leaves notifications on other channels alone', () async {
final log = await ready(active: {5: 'some_other_channel'});
await NotificationService.instance.syncToSlots(const []);
expect(ids(log, 'cancel'), isEmpty);
});
test(
'syncToSlots cancels a slot whose meal was logged after it fired',
() async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(
FlutterLocalNotificationsPlugin(),
),
);
await NotificationService.init();
await NotificationService.instance.syncToSlots([12]);
final log = await ready();
await NotificationService.instance.syncToSlots([720]);
log.clear();
await NotificationService.instance.syncToSlots(const []); // logged
expect(
log
.where((c) => c.method == 'cancel')
.map((c) => (c.arguments as Map)['id']),
contains(12),
);
expect(ids(log, 'cancel'), {720});
},
);
});
test('a failed active lookup falls back to sweeping every id', () async {
final backend = _FakeBackend()..failLookup = true;
NotificationService.resetForTesting(backend: backend);
await NotificationService.init();
await NotificationService.instance.syncToSlots([435]);
expect(backend.shown, [435]);
expect(backend.cancelled, hasLength(kMinutesPerDay - 1));
expect(backend.cancelled, isNot(contains(435)));
expect(backend.cancelled, containsAll(<int>[0, 8, 23, 720, 1439]));
});
test('instance throws before init has ever been called', () {
expect(() => NotificationService.instance, throwsA(anything));
});
}
/// A platform-free backend for the paths the channel fake cannot reach.
class _FakeBackend implements NotificationBackend {
bool failLookup = false;
final shown = <int>[];
final cancelled = <int>[];
@override
Future<void> initialize() async {}
@override
Future<bool?> requestPermission() async => null;
@override
Future<void> show(int slot, String title, String body) async =>
shown.add(slot);
@override
Future<void> cancel(int slot) async => cancelled.add(slot);
@override
Future<Set<int>> activeIds() async {
if (failLookup) throw StateError('no notification service');
return {};
}
}

View File

@ -0,0 +1,78 @@
// The user-approved acceptance scenario for minute slots: editing the
// schedule must never un-log a meal already eaten, on this device or in the
// reminders it posts.
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/due_slot_check.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/notification_backend_io.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
import '../fake_notifications.dart';
import 'body_test_support.dart';
const _manual = Nutrition(
kcal: 200,
proteinG: 10,
carbsG: 20,
fatG: 5,
grams: 100,
source: 'manual',
);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
LogStorageService.resetForTesting(store: MemoryDocStore());
await MealScheduleService.initForTesting(MemoryDocStore());
});
tearDown(() {
LogStorageService.resetForTesting();
MealScheduleService.resetForTesting();
NotificationService.resetForTesting();
});
test('moving the first meal 07:00 -> 07:15 keeps both meals logged', () async {
const before = MealSchedule(firstMinute: 420, lastMinute: 1140, count: 5);
const after = MealSchedule(firstMinute: 435, lastMinute: 1140, count: 5);
expect(before.slots(), [420, 600, 780, 960, 1140]);
expect(after.slots(), [435, 615, 795, 960, 1140]);
final schedule = MealScheduleService.instance;
await schedule.recordChange(before);
final today = DateTime.now();
DateTime at(int hour) => DateTime(today.year, today.month, today.day, hour);
// Logged at 07:00 and 10:00 under the old schedule, so recorded as the
// slots slotForLog attributed them to then.
final storage = LogStorageService.instance;
for (final hour in [7, 10]) {
await storage.logMeal(
'meal',
_manual,
slotMinute: slotForLog(at(hour), MealScheduleService.current),
);
}
expect(await storage.loggedSlotsToday(), {420, 600});
await schedule.recordChange(after);
// Nothing stored was rewritten; each entry now snaps to its nearest slot.
final logged = await storage.loggedSlotsToday();
expect(logged, {435, 615});
expect(missingSlots(at(11), logged, MealScheduleService.current), isEmpty);
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await checkAndNotify(now: at(11), pullWhenDue: false);
expect(log.where((c) => c.method == 'show'), isEmpty);
});
}

View File

@ -36,7 +36,7 @@ void main() {
final fields = scheduleFields([
_entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
'2026-08-16T10:00:00+02:00',
),
]);
@ -51,7 +51,7 @@ void main() {
test('the Hlc is deterministic', () {
final entry = _entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
'2026-08-16T10:00:00+02:00',
);
expect(
@ -63,7 +63,7 @@ void main() {
test('an unparsable timestamp falls back to the epoch', () {
final entry = _entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
'not-a-timestamp',
);
expect(scheduleHlc(entry).wallTimeMs, 0);
@ -80,7 +80,7 @@ void main() {
budgetToLog(_record, const [], [
_entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
'2026-08-16T10:00:00+02:00',
),
]),
@ -89,10 +89,24 @@ void main() {
expect(back.single.effectiveFrom, '2026-08-16');
expect(
back.single.schedule,
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
);
});
test('an off-the-hour schedule round trips through the wire', () {
// Dropping fm/lm on either side would silently snap 07:15 to 07:00.
const offHour = MealSchedule(firstMinute: 435, lastMinute: 1140, count: 5);
final entry = _entry('2026-08-16', offHour, '2026-08-16T10:00:00+02:00');
expect(scheduleFields([entry]).values.single.$1, {
'f': 7,
'l': 19,
'n': 5,
'fm': 435,
});
final back = logToScheduleHistory(budgetToLog(_record, const [], [entry]));
expect(back.single.schedule, offHour);
});
test("normalizes a peer's out-of-range schedule", () {
final log = budgetToLog(_record);
final record = log[budgetRecordId]!;
@ -103,7 +117,7 @@ void main() {
);
expect(
logToScheduleHistory(log).single.schedule,
const MealSchedule(first: 8, last: 20, count: 6),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 6),
);
});
@ -127,7 +141,7 @@ void main() {
_entry('1970-01-01', kDefaultSchedule, '1970-01-01T00:00:00.000Z'),
_entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
'2026-08-16T10:00:00+02:00',
),
]);
@ -141,7 +155,7 @@ void main() {
expect(logToScheduleHistory(merged).map((e) => e.schedule), [
kDefaultSchedule,
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
]);
});
@ -149,14 +163,14 @@ void main() {
final older = budgetToLog(_record, const [], [
_entry(
'2026-08-16',
const MealSchedule(first: 8, last: 20, count: 5),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5),
'2026-08-16T10:00:00+02:00',
),
]);
final newer = budgetToLog(_record, const [], [
_entry(
'2026-08-16',
const MealSchedule(first: 7, last: 21, count: 3),
const MealSchedule(firstMinute: 7 * 60, lastMinute: 21 * 60, count: 3),
'2026-08-16T18:00:00+02:00',
),
]);
@ -164,7 +178,7 @@ void main() {
final merged = mergeLogs(parseRemoteBudget(_wire(older)), newer);
expect(
logToScheduleHistory(merged).single.schedule,
const MealSchedule(first: 7, last: 21, count: 3),
const MealSchedule(firstMinute: 7 * 60, lastMinute: 21 * 60, count: 3),
);
});
});

View File

@ -0,0 +1,191 @@
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/widgets/meal_schedule_editor.dart';
import 'package:diet_guard_app/widgets/meal_time_dropdown.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
/// Holds the schedule the way `_SettingsMealSchedule` does: every edit is
/// normalised and fed back, so the preview reflects what would be saved.
class _Harness extends StatefulWidget {
const _Harness(this.initial, this.edits);
final MealSchedule initial;
final List<MealSchedule> edits;
@override
State<_Harness> createState() => _HarnessState();
}
class _HarnessState extends State<_Harness> {
late MealSchedule _schedule = widget.initial;
@override
Widget build(BuildContext context) => MaterialApp(
home: Scaffold(
body: ListView(
children: [
MealScheduleEditor(
schedule: _schedule,
onChanged: (next) {
widget.edits.add(next);
setState(() => _schedule = next.normalized());
},
),
],
),
),
);
}
const _fiveMeals = MealSchedule(firstMinute: 480, lastMinute: 1200, count: 5);
void main() {
late List<MealSchedule> edits;
setUp(() => edits = []);
Future<void> pump(WidgetTester tester, MealSchedule schedule) async {
await tester.binding.setSurfaceSize(const Size(500, 900));
addTearDown(() => tester.binding.setSurfaceSize(null));
await tester.pumpWidget(_Harness(schedule, edits));
}
Future<void> openDropdown(WidgetTester tester, String label) async {
await tester.tap(find.widgetWithText(InputDecorator, label));
await tester.pumpAndSettle();
}
/// Taps [label]'s clock button and types [hh]:[mm] in the time picker's
/// keyboard mode.
Future<void> pickExact(
WidgetTester tester,
String label,
String hh,
String mm,
) async {
await tester.tap(
find.descendant(
of: find.byWidgetPredicate(
(w) => w is MealTimeDropdown && w.label == label,
),
matching: find.byTooltip('Type or pick an exact time'),
),
);
await tester.pumpAndSettle();
expect(find.byType(TimePickerDialog), findsOneWidget);
await tester.tap(find.byIcon(Icons.keyboard_outlined));
await tester.pumpAndSettle();
final fields = find.descendant(
of: find.byType(TimePickerDialog),
matching: find.byType(TextField),
);
await tester.enterText(fields.at(0), hh);
await tester.enterText(fields.at(1), mm);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
}
testWidgets('an off-grid value from another device renders', (tester) async {
// A dropdown whose value matches no item asserts; a PC-set 07:23 must
// show as itself rather than take the settings screen down.
await pump(
tester,
const MealSchedule(firstMinute: 443, lastMinute: 1140, count: 5),
);
expect(find.text('07:23'), findsWidgets);
expect(tester.takeException(), isNull);
await openDropdown(tester, 'First meal');
expect(find.text('07:23'), findsWidgets);
expect(find.text('07:15'), findsWidgets);
});
testWidgets('choosing a 15-minute value updates the preview', (tester) async {
await pump(tester, _fiveMeals);
expect(find.text('08:00 · 11:00 · 14:00 · 17:00 · 20:00'), findsOne);
await openDropdown(tester, 'First meal');
await tester.tap(find.text('07:45').last);
await tester.pumpAndSettle();
expect(edits.last.firstMinute, 465);
expect(find.text('07:45 · 10:45 · 14:00 · 17:00 · 20:00'), findsOne);
});
testWidgets('the clock button opens the time picker and applies 07:23', (
tester,
) async {
await pump(tester, _fiveMeals);
await pickExact(tester, 'First meal', '07', '23');
expect(edits.last.firstMinute, 443);
expect(edits.last.lastMinute, 1200);
expect(find.text('07:23'), findsWidgets);
});
testWidgets('no "Custom…" item remains in either menu', (tester) async {
await pump(tester, _fiveMeals);
for (final dropdown in tester.widgetList<DropdownButton<int>>(
find.byType(DropdownButton<int>),
)) {
final values = [for (final item in dropdown.items!) item.value!];
expect(values.every((v) => v >= 0), isTrue, reason: 'no sentinel');
}
await openDropdown(tester, 'First meal');
await tester.scrollUntilVisible(
find.text('00:00'),
-300,
scrollable: find.byType(Scrollable).last,
);
expect(find.text('Custom…'), findsNothing);
});
testWidgets('an exact last meal before the first is clamped', (tester) async {
await pump(tester, _fiveMeals);
await pickExact(tester, 'Last meal', '06', '00');
// One grid step after 08:00: the shortest legal window, not a rejection.
expect(edits.last.lastMinute, 495);
});
testWidgets('Last meal only offers times after the first', (tester) async {
await pump(tester, _fiveMeals);
MealTimeDropdown field(String label) => tester.widget(
find.byWidgetPredicate((w) => w is MealTimeDropdown && w.label == label),
);
final last = field('Last meal').options;
expect(last.first, 495, reason: '08:15, one grid step after 08:00');
expect(last.last, 1425, reason: '23:45, the last grid mark');
final first = field('First meal').options;
expect(first.first, 0);
expect(first.last, 1410, reason: '23:30 leaves a grid-aligned last meal');
expect(first.every((m) => m % 15 == 0), isTrue);
});
testWidgets('meal counts shrink to what a narrow window holds', (
tester,
) async {
const narrow = MealSchedule(firstMinute: 480, lastMinute: 510, count: 2);
expect(
const MealScheduleEditor(schedule: narrow, onChanged: _ignore)
.selectableCounts,
[2, 3],
);
expect(
const MealScheduleEditor(schedule: _fiveMeals, onChanged: _ignore)
.selectableCounts,
[2, 3, 4, 5, 6],
);
await pump(tester, narrow);
await openDropdown(tester, 'Meals per day');
expect(find.text('3'), findsWidgets);
expect(find.text('4'), findsNothing);
});
}
void _ignore(MealSchedule _) {}

View File

@ -7,7 +7,7 @@ Type=oneshot
# DISPLAY mirrors wake-alarm.service: the gate opens a Tk window when a lock
# is due, so without DISPLAY it would crash with "no display name and no
# $DISPLAY" before it could even check. The command self-checks gate_is_due()
# and exits 0 when no lock is needed, so running it every ~30 min is cheap.
# and exits 0 when no lock is needed, so running it every ~15 min is cheap.
# No PYTHONPATH needed: diet_guard is pip-installed (see install.sh / README),
# so /usr/bin/python finds it via user site-packages.
#

View File

@ -2,10 +2,13 @@
Description=Periodically run the Diet Guard gate check
[Timer]
# Check on a WALL-CLOCK schedule (every 30 min, on the hour and half-hour).
# The 5-hour "log a meal" threshold and the 08:00-22:00 eating window are
# enforced inside gate_is_due(), so the timer only needs to fire often enough to
# notice the boundary; 30 min is plenty.
# Check on a WALL-CLOCK schedule (every 15 min: :00, :15, :30, :45).
# The meal slots and the enforcement window are enforced inside gate_is_due(),
# so the timer only needs to fire often enough to notice a slot opening. Slots
# can sit on any quarter hour (interior slots round to the 15-minute grid, and
# a 07:15 first meal is common), so a 30-min tick would let a slot go
# unenforced for up to half an hour; 15 min lands on every grid slot exactly.
# A first/last meal typed off the grid (07:23) is caught by the next tick.
#
# Why OnCalendar and not OnBootSec/OnUnitActiveSec: the gate is a *blocking*
# oneshot -- it stays up until a meal is logged -- and a monotonic schedule
@ -13,7 +16,7 @@ Description=Periodically run the Diet Guard gate check
# reboot), leaving the timer dormant (NextElapse=infinity). OnCalendar re-arms
# every period regardless of how long the gate stayed open, and Persistent
# catches a run missed while the machine was suspended.
OnCalendar=*-*-* *:00/30:00
OnCalendar=*-*-* *:00/15:00
Persistent=true
[Install]

View File

@ -72,8 +72,10 @@ def bodyfat_lines(view: BodyView) -> list[str]:
return ["Body fat: not logged (log one to use Katch-McArdle)."]
day = max(view.body_fats)
return [
f"Body fat: {_num(view.body_fats[day], 1)}% on {day} "
f"({len(view.body_fats)} readings) -- targets use Katch-McArdle."
(
f"Body fat: {_num(view.body_fats[day], 1)}% on {day} "
f"({len(view.body_fats)} readings) -- targets use Katch-McArdle."
)
]
@ -85,8 +87,10 @@ def bmi_lines(view: BodyView) -> list[str]:
low, high = view.numbers.healthy
return [
f"BMI {_num(bmi.bmi, 1)} ({bmi.category})",
f"Healthy weight for your height (BMI 18.5-24.9): "
f"{_num(low, 1)}-{_num(high, 1)} kg",
(
f"Healthy weight for your height (BMI 18.5-24.9): "
f"{_num(low, 1)}-{_num(high, 1)} kg"
),
f"BMI Prime {_num(bmi.prime, 2)} Trefethen {_num(bmi.trefethen, 1)}",
*_wrap(BMI_PRIME_NOTE, " "),
*_wrap(TREFETHEN_NOTE, " "),
@ -141,8 +145,10 @@ def target_lines(view: BodyView) -> list[str]:
target = view.numbers.target
if target.kcal is None or target.tdee is None:
return [
f"{goal_sentence(view.goal)}: no workouts published yet "
"(the PC publishes them on sync)."
(
f"{goal_sentence(view.goal)}: no workouts published yet "
"(the PC publishes them on sync)."
)
]
lines = [f"{goal_sentence(view.goal)} eat {target.kcal} kcal a day."]
if target.below_floor:

View File

@ -116,10 +116,11 @@ def _print_entry_line(entry: dict[str, object]) -> None:
def _print_slot_status() -> None:
"""Print each meal slot as logged / DUE / upcoming for today."""
logged = logged_slots_today()
schedule = current_schedule()
logged = logged_slots_today(schedule)
due = set(due_slots())
parts: list[str] = []
for slot in day_slots(current_schedule()):
for slot in day_slots(schedule):
if slot in logged:
mark = "logged"
elif slot in due:

View File

@ -87,9 +87,10 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
)
ate.add_argument(
"--hour",
type=int,
type=str,
default=None,
help="Slot hour on --date this meal satisfies (e.g. 20); requires --date.",
help="Meal slot on --date this meal satisfies, as HH:MM or HH (e.g."
" 07:15 or 20); must be one of that day's slots. Requires --date.",
)
sub.add_parser("status", help="Show today's calories and budget band.")

View File

@ -19,7 +19,7 @@ from typing import TYPE_CHECKING
from diet_guard._kuchnia_spread import assign_slots
from diet_guard._meal_schedule_store import current_schedule
from diet_guard._slots import day_slots
from diet_guard._slots import day_slots, slot_label
from diet_guard._state import now_local
if TYPE_CHECKING: # pragma: no cover - typing only
@ -99,7 +99,7 @@ def cmd_kuchnia(
emit(f"{len(dishes)} dish(es) delivered today, banked:")
for item in slotted:
emit(
f" {item.slot:02d}:00 {item.dish.name} "
f" {slot_label(item.slot)} {item.dish.name} "
f"({item.dish.kcal:g} kcal, {item.dish.grams:g} g)",
)
total = sum(dish.kcal for dish in dishes)

View File

@ -22,7 +22,8 @@ from diet_guard._kuchnia_import import refresh_delivery_once
from diet_guard._meal_schedule_store import current_schedule
from diet_guard._portions import DEFAULT_ITEM_GRAMS, estimate_unit_grams
from diet_guard._resolve import ManualMacros, resolve_nutrition
from diet_guard._slots import resolve_future_when, slot_for_log
from diet_guard._slot_wire import parse_hhmm
from diet_guard._slots import resolve_future_when, slot_for_log, slot_label
from diet_guard._state import log_meal, now_local
from diet_guard._sync_events import publish_after_log_detached
@ -66,15 +67,17 @@ class Portion:
for a per-100 g label), or None to treat the macros as totals.
date: Log against this future date (``YYYY-MM-DD``) instead of now.
Must be given together with ``hour``. None means "now".
hour: The slot hour on ``date`` this meal satisfies. Required
together with ``date``.
hour: The slot on ``date`` this meal satisfies, as the user typed it
(``HH:MM`` or ``HH``; parsed by
:func:`diet_guard._slot_wire.parse_hhmm`). Required together with
``date``.
"""
grams: float | None
count: float | None
per_grams: float | None
date: str | None = None
hour: int | None = None
hour: str | None = None
def eaten_grams(
@ -100,8 +103,10 @@ def eaten_grams(
if unit is None:
return (
portion.count * DEFAULT_ITEM_GRAMS,
f"(assumed {DEFAULT_ITEM_GRAMS:g} g per item; "
"pass --grams to be exact)",
(
f"(assumed {DEFAULT_ITEM_GRAMS:g} g per item; "
"pass --grams to be exact)"
),
)
return portion.count * unit, None
return portion.grams, None
@ -116,13 +121,15 @@ def _resolve_target(
limit.
Raises:
ValueError: ``portion.date``/``portion.hour`` are an invalid future
ValueError: ``portion.hour`` is not a clock time, or
``portion.date``/``portion.hour`` are an invalid future
combination -- see :func:`diet_guard._slots.resolve_future_when`.
"""
if portion.date is None or portion.hour is None:
return None, slot_for_log(now_local(), schedule)
when = resolve_future_when(portion.date, portion.hour, schedule, now_local())
return when, slot_for_log(when, schedule)
slot = parse_hhmm(portion.hour)
when = resolve_future_when(portion.date, slot, schedule, now_local())
return when, slot
def cmd_ate(
@ -195,7 +202,7 @@ def cmd_ate(
emit(
f"logged: {description} {nutrition.kcal:g} kcal "
f"({macro_str}) [{nutrition.source}, {portion_str}]"
f"{f' for {portion.date} {portion.hour:02d}:00' if when else ''}",
f"{f' for {portion.date} {slot_label(slot)}' if when else ''}",
)
# Publish straight away rather than waiting for a periodic tick: until this
# lands, the phone still believes this slot is unlogged and will nag for it.

View File

@ -76,18 +76,11 @@ OFF_USER_AGENT: str = "diet_guard/1.0 (personal diet tracker)"
DEFAULT_PORTION_GRAMS: float = 100.0
# --- Gate (log-to-unlock) ---------------------------------------------------
# The gate is driven by FIXED MEAL SLOTS, not by a gap timer. Starting at the
# day-start hour, a slot opens every interval; once a slot's hour has passed,
# that slot must carry a logged meal or the screen locks until it does. This
# makes tracking fully automatic (you are prompted on a schedule rather than
# trusted to log voluntarily) and nudges regular eating. Coming home late
# naturally produces several unlogged elapsed slots at once -> one lock that
# backfills the whole day, which is the "requirement to access the PC" behavior.
GATE_DAY_START_HOUR: int = 8 # first slot (08:00); also the "beginning of day"
GATE_SLOT_INTERVAL_HOURS: int = 4 # slots at 08:00, 12:00, 16:00, 20:00
# Past this hour the gate never fires, so an unlogged late slot lapses quietly
# instead of locking you out overnight. (A new day resets all slots at 00:00.)
GATE_EATING_END_HOUR: int = 22 # exclusive (22:00)
# The gate is driven by MEAL SLOTS, not by a gap timer: once a slot's minute has
# passed, that slot must carry a logged meal or the screen locks until it does.
# Coming home late naturally produces several unlogged elapsed slots at once ->
# one lock that backfills the whole day. The slot minutes and the overnight
# cutoff come from the user's schedule (``_meal_schedule``), not constants here.
# flock single-instance guard: stops a timer from stacking lock windows.
GATE_LOCK_FILE: Path = DATA_DIR / ".gate.lock"

View File

@ -39,7 +39,7 @@ def due_slots(now: datetime | None = None) -> tuple[int, ...]:
now: Reference time (defaults to the current local time); injectable.
Returns:
The slot hours that still need a meal logged (empty == nothing due).
The slot minutes that still need a meal logged (empty == nothing due).
Empty on a shared free day, whatever the schedule says. The pool is read
from a single local file and never the network, so this cannot hang the
@ -49,7 +49,11 @@ def due_slots(now: datetime | None = None) -> tuple[int, ...]:
reference = now if now is not None else now_local()
if freedays.is_free_day(reference.date()):
return ()
return missing_slots(reference, logged_slots_today(), current_schedule())
# One schedule for both halves: snapping the log onto a different schedule
# than the one deriving the due slots would leave a logged meal covering a
# checkpoint that is not on the list -- and the real one nagging.
schedule = current_schedule()
return missing_slots(reference, logged_slots_today(schedule), schedule)
def gate_is_due(now: datetime | None = None) -> bool:

View File

@ -97,7 +97,7 @@ def _pending_slots(*, demo_mode: bool) -> list[int]:
demo_mode: Whether the window is a safe sandbox.
Returns:
The slot hours to collect, ascending.
The slot minutes to collect, ascending.
"""
pending = list(due_slots())
if pending:

View File

@ -4,11 +4,27 @@ Split out of :mod:`._gatelock_calendar_widgets` (216 lines against the repo's
250-line cap) rather than added to it. The behaviour behind these widgets
lives in :mod:`._gatelock_scheduleedit`, mirroring how the budget row's
widgets and its edit/save logic are split.
The first and last meal are editable ``ttk.Spinbox`` fields: the user may type
any ``HH:MM``, and the arrow buttons, Up/Down and the mouse wheel step to the
neighbouring quarter hour (:func:`step_time`). The ``ttk`` import is
load-bearing for the tests, which patch this module's ``ttk`` with a fake --
keep binding it at module level.
**No popup of any kind.** These used to be ``ttk.Combobox`` fields, and on
Xvfb (2026-10-10, demo gate) a posted ``ComboboxPopdown`` mapped *beneath*
the lock surface, which gatelock keeps raised, while still holding ttk's grab:
invisible, it swallowed the next click and stole keystrokes. A spinbox posts
nothing. Every way ttk spins one -- arrow press, Up/Down, the wheel --
generates ``<<Increment>>``/``<<Decrement>>`` (``ttk/spinbox.tcl``), and those
are bound here and answered with ``"break"``, so ttk's own ``values``/``wrap``
logic never runs: stepping is always :func:`step_time` from the typed value.
"""
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from typing import TYPE_CHECKING
from gatelock import make_button
@ -17,19 +33,98 @@ from diet_guard._gatelock_calendar_types import _COLORS, _FIELD_BG
from diet_guard._gatelock_spacing import SM, XS
from diet_guard._gatelock_typography import BODY, LABEL
from diet_guard._gatelock_ui import BG, FG
from diet_guard._meal_schedule import MINUTES_PER_DAY, SLOT_GRID_MINUTES
from diet_guard._slot_wire import parse_hhmm
from diet_guard._slots import slot_label
if TYPE_CHECKING:
from collections.abc import Callable
from diet_guard._gatelock_calendar_types import CalendarVars
__all__ = ["build_schedule_row"]
__all__ = ["FIRST_RANGE", "LAST_RANGE", "build_schedule_row", "step_time"]
_ENTRY_WIDTH = 4
# "HH:MM" plus room for the caret, so a typed time is never clipped.
_TIME_WIDTH = 6
_LAST_MARK = MINUTES_PER_DAY - SLOT_GRID_MINUTES # 23:45, the day's last grid mark
#: Where stepping clamps each field, as ``(low, high)`` minutes. The last meal
#: must sit at least one grid step after the first, so it can never be 00:00.
FIRST_RANGE = (0, _LAST_MARK)
LAST_RANGE = (SLOT_GRID_MINUTES, _LAST_MARK)
def step_time(text: str, direction: int, bounds: tuple[int, int] = FIRST_RANGE) -> str:
"""Return ``text`` moved to the next quarter hour in ``direction``.
An off-grid time (07:23) steps to the neighbouring grid mark (07:30 up,
07:15 down) rather than by a flat 15, so stepping always lands on the
grid. Clamped to ``bounds``; unparsable text is returned unchanged so a
half-typed value is not clobbered.
Args:
text: The field's current value.
direction: ``+1`` for later, ``-1`` for earlier.
bounds: The ``(low, high)`` minutes the result is clamped to.
Returns:
The stepped ``HH:MM`` label, or ``text`` if it does not parse.
"""
try:
minute = parse_hhmm(text)
except ValueError:
return text
if direction > 0:
stepped = (minute // SLOT_GRID_MINUTES + 1) * SLOT_GRID_MINUTES
else:
stepped = (minute - 1) // SLOT_GRID_MINUTES * SLOT_GRID_MINUTES
low, high = bounds
return slot_label(max(low, min(high, stepped)))
def _bind_steps(
spin: ttk.Spinbox, variable: tk.StringVar, bounds: tuple[int, int]
) -> None:
"""Answer the spinbox's step events with :func:`step_time`."""
def _step(direction: int) -> str:
if str(spin.cget("state")) == "normal":
variable.set(step_time(variable.get(), direction, bounds))
# "break" keeps ttk's own Spin (values/from/to/wrap) from running.
return "break"
spin.bind("<<Increment>>", lambda _event: _step(1))
spin.bind("<<Decrement>>", lambda _event: _step(-1))
def _time_spin(
row: tk.Frame, variable: tk.StringVar, bounds: tuple[int, int]
) -> ttk.Spinbox:
"""Return one locked-by-default ``HH:MM`` spinbox in the schedule row.
Locked means ``disabled``, not ``readonly``: a read-only ttk spinbox still
spins, which would edit a "locked" row. Its colours come from the
``TSpinbox`` style (see
:func:`diet_guard._gatelock_calendar_ui._style_notebook`) -- ttk widgets
reject ``bg``/``fg``.
"""
spin = ttk.Spinbox(
row,
textvariable=variable,
font=(_COLORS.typography.font_family, BODY),
width=_TIME_WIDTH,
justify="center",
state="disabled",
)
_bind_steps(spin, variable, bounds)
spin.pack(side="left", padx=(XS, SM), ipady=XS)
return spin
def _spin_entry(row: tk.Frame, variable: tk.StringVar) -> tk.Entry:
"""Return one read-only-by-default numeric entry in the schedule row."""
"""Return the read-only-by-default meal-count entry in the schedule row."""
entry = tk.Entry(
row,
textvariable=variable,
@ -46,45 +141,38 @@ def _spin_entry(row: tk.Frame, variable: tk.StringVar) -> tk.Entry:
return entry
def _caption(row: tk.Frame, text: str) -> None:
"""Pack one static label between the row's fields."""
tk.Label(
row,
text=text,
font=(_COLORS.typography.font_family, LABEL),
bg=BG,
fg=FG,
).pack(side="left")
def build_schedule_row(
parent: tk.Frame,
vars_: CalendarVars,
on_edit_or_save_schedule: Callable[[], None],
) -> tuple[tk.Entry, tk.Entry, tk.Entry, tk.Button, tk.Label]:
) -> tuple[ttk.Spinbox, ttk.Spinbox, tk.Entry, tk.Button, tk.Label]:
"""Build the meal-schedule row.
Returns the three hour/count entries, the edit button, and the status
label, in that order. Like the budget row the entries start read-only:
the schedule is displayed but not directly typeable until "Edit".
Returns the two time spinboxes, the count entry, the edit button, and the
status label, in that order. Like the budget row the fields start locked:
the schedule is displayed but not directly editable until "Edit".
Returns:
``(first_entry, last_entry, count_entry, edit_button, status_label)``.
``(first_spin, last_spin, count_entry, edit_button, status_label)``.
"""
row = tk.Frame(parent, bg=BG)
row.pack(pady=(SM, XS))
tk.Label(
row,
text="Meals:",
font=(_COLORS.typography.font_family, LABEL),
bg=BG,
fg=FG,
).pack(side="left")
first_entry = _spin_entry(row, vars_.schedule.first)
tk.Label(
row,
text="to",
font=(_COLORS.typography.font_family, LABEL),
bg=BG,
fg=FG,
).pack(side="left")
last_entry = _spin_entry(row, vars_.schedule.last)
tk.Label(
row,
text="x",
font=(_COLORS.typography.font_family, LABEL),
bg=BG,
fg=FG,
).pack(side="left")
_caption(row, "Meals:")
first_spin = _time_spin(row, vars_.schedule.first, FIRST_RANGE)
_caption(row, "to")
last_spin = _time_spin(row, vars_.schedule.last, LAST_RANGE)
_caption(row, "x")
count_entry = _spin_entry(row, vars_.schedule.count)
edit_button = make_button(row, _COLORS, "Edit", on_edit_or_save_schedule)
edit_button.pack(side="left")
@ -106,4 +194,4 @@ def build_schedule_row(
fg=FG,
)
status_label.pack(pady=(0, XS))
return first_entry, last_entry, count_entry, edit_button, status_label
return first_spin, last_spin, count_entry, edit_button, status_label

View File

@ -19,6 +19,7 @@ from gatelock import LockConfig
if TYPE_CHECKING:
from collections.abc import Callable
from tkinter import ttk
# BG/FG/ERR come from _gatelock_ui's public exports (themselves sourced from
# LockConfig -- see DESIGN_AUDIT_TODO.md). The rest of the calendar's palette
@ -60,7 +61,9 @@ class ScheduleVars:
status: tk.StringVar
first: tk.StringVar
"""The first meal as ``HH:MM`` text, parsed only on save."""
last: tk.StringVar
"""The last meal as ``HH:MM`` text, parsed only on save."""
count: tk.StringVar
times: tk.StringVar
"""The derived checkpoint times, e.g. ``"08:00 11:00 14:00"``."""
@ -89,8 +92,8 @@ class CalendarWidgets:
budget_entry: tk.Entry
budget_edit_button: tk.Button
budget_status_label: tk.Label
schedule_first_entry: tk.Entry
schedule_last_entry: tk.Entry
schedule_first_entry: ttk.Spinbox
schedule_last_entry: ttk.Spinbox
schedule_count_entry: tk.Entry
schedule_edit_button: tk.Button
schedule_status_label: tk.Label

View File

@ -52,7 +52,10 @@ __all__ = [
def _style_notebook(root: tk.Misc) -> None:
"""Theme the ``ttk.Notebook`` tab strip to match the gate's dark palette.
"""Theme the History tab's ttk widgets to match the gate's dark palette.
Covers the ``ttk.Notebook`` tab strip and the schedule row's
``ttk.Spinbox`` fields.
``ttk`` widgets ignore plain ``bg=``/``fg=`` -- unlike every other widget
here, they only take color from a named ``ttk.Style``. Without this the
@ -77,3 +80,21 @@ def _style_notebook(root: tk.Misc) -> None:
background=[("selected", _ACCENT)],
foreground=[("selected", _COLORS.palette.on_fill)],
)
# The meal-schedule row's HH:MM spinboxes. Locked they are ``disabled``,
# which clam greys out; mapping the disabled state back to the field
# colours keeps the stored schedule legible, matching the read-only
# ``tk.Entry`` beside them.
style.configure(
"TSpinbox",
fieldbackground=_FIELD_BG,
background=_FIELD_BG,
foreground=FG,
arrowcolor=FG,
insertcolor=FG,
)
style.map(
"TSpinbox",
fieldbackground=[("disabled", _FIELD_BG), ("readonly", _FIELD_BG)],
foreground=[("disabled", FG)],
arrowcolor=[("disabled", _COLORS.palette.muted)],
)

View File

@ -28,7 +28,7 @@ from diet_guard._gatelock_kuchnia import start_delivery_fetch
from diet_guard._kuchnia_log import fill_plan, log_dishes
from diet_guard._kuchnia_spread import assign_slots
from diet_guard._meal_schedule_store import current_schedule
from diet_guard._slots import day_slots
from diet_guard._slots import day_slots, slot_label
from diet_guard._state import now_local
if TYPE_CHECKING: # pragma: no cover - typing only
@ -144,7 +144,9 @@ class FillAllFlow:
self._plan = plan
self._label.set(f"✓ Confirm ({len(plan)})")
total = sum(item.dish.kcal for item in plan)
listing = ", ".join(f"{item.slot:02d}:00 {item.dish.name}" for item in plan)
listing = ", ".join(
f"{slot_label(item.slot)} {item.dish.name}" for item in plan
)
self._set_status(
f"Will log {len(plan)} ({total:g} kcal): {listing} — click Confirm."
)

View File

@ -11,6 +11,10 @@ before it is written rather than relying on
:meth:`~diet_guard._meal_schedule.MealSchedule.normalized` to clamp it. The
clamp is the defence against a peer's corrupt sync data; a typo at the
keyboard should say so instead of silently becoming a different schedule.
The first and last meal are ``HH:MM`` times (any minute, not just the
quarter hours the dropdown offers); the rules mirror ``normalized()`` exactly
so that a schedule accepted here is stored unchanged.
"""
from __future__ import annotations
@ -22,16 +26,20 @@ import tkinter as tk
from diet_guard._gatelock_budgetedit import _GateBudgetEdit
from diet_guard._gatelock_ui import ERR, FG
from diet_guard._meal_schedule import (
FIRST_HOUR,
LAST_HOUR,
MAX_MEAL_COUNT,
MIN_MEAL_COUNT,
SLOT_GRID_MINUTES,
MealSchedule,
)
from diet_guard._meal_schedule_store import current_schedule, record_schedule_change
from diet_guard._slot_wire import parse_hhmm
from diet_guard._slots import day_slots, slot_label
__all__ = ["_GateScheduleEdit", "schedule_summary"]
__all__ = ["_GateScheduleEdit", "schedule_problem", "schedule_summary"]
# ttk.Spinbox and tk.Entry spell "locked" differently: a ``readonly`` ttk
# spinbox still spins, which would edit a locked row, so locked is ``disabled``.
_SPIN_STATE = {"normal": "normal", "readonly": "disabled"}
def schedule_summary(schedule: MealSchedule) -> str:
@ -39,6 +47,27 @@ def schedule_summary(schedule: MealSchedule) -> str:
return " ".join(slot_label(slot) for slot in day_slots(schedule))
def schedule_problem(schedule: MealSchedule) -> str | None:
"""Return why ``schedule`` cannot be saved as typed, or None if it can.
Each rule is one ``normalized()`` would otherwise apply silently: the
15-minute minimum window, the meal-count range, and the capacity of the
window -- one checkpoint per grid step, because two meals closer than that
would snap onto the same quarter hour and a duplicate slot silently drops
a checkpoint.
"""
first, last = schedule.first_minute, schedule.last_minute
if last < first + SLOT_GRID_MINUTES:
return (
f"The last meal must be at least {SLOT_GRID_MINUTES} min after the first."
)
if not MIN_MEAL_COUNT <= schedule.count <= MAX_MEAL_COUNT:
return f"Meals per day must be {MIN_MEAL_COUNT}-{MAX_MEAL_COUNT}."
if schedule.count > (last - first) // SLOT_GRID_MINUTES + 1:
return "Too many meals for that window -- widen it or eat less often."
return None
class _GateScheduleEdit(_GateBudgetEdit):
"""The History tab's meal-schedule row: display, edit, validate, persist.
@ -55,11 +84,16 @@ class _GateScheduleEdit(_GateBudgetEdit):
"""Repaint the History tab; implemented by ``_GateCalendar``."""
def _set_schedule_entry_state(self, state: str) -> None:
"""Lock or unlock the three schedule entries on every monitor."""
"""Lock (``"readonly"``) or unlock (``"normal"``) the row's fields.
One suppress per widget: a monitor that vanished mid-update must not
stop the remaining fields from changing state.
"""
for surface in self._cal_surfaces:
for spin in (surface.schedule_first_entry, surface.schedule_last_entry):
with contextlib.suppress(tk.TclError):
spin.configure(state=_SPIN_STATE[state])
with contextlib.suppress(tk.TclError):
surface.schedule_first_entry.config(state=state)
surface.schedule_last_entry.config(state=state)
surface.schedule_count_entry.config(state=state)
def _set_schedule_button_text(self, text: str) -> None:
@ -78,8 +112,8 @@ class _GateScheduleEdit(_GateBudgetEdit):
def _show_schedule(self, schedule: MealSchedule) -> None:
"""Populate the row's fields and derived-times label."""
self._cal_vars.schedule.first.set(str(schedule.first))
self._cal_vars.schedule.last.set(str(schedule.last))
self._cal_vars.schedule.first.set(slot_label(schedule.first_minute))
self._cal_vars.schedule.last.set(slot_label(schedule.last_minute))
self._cal_vars.schedule.count.set(str(schedule.count))
self._cal_vars.schedule.times.set(schedule_summary(schedule))
@ -104,16 +138,19 @@ class _GateScheduleEdit(_GateBudgetEdit):
self._refresh_calendar()
def _read_schedule_fields(self) -> MealSchedule | None:
"""Parse the three entries, or None (with a status set) if unusable."""
raw = (
self._cal_vars.schedule.first.get().strip(),
self._cal_vars.schedule.last.get().strip(),
self._cal_vars.schedule.count.get().strip(),
)
"""Parse the three fields, or None (with a status set) if unusable."""
try:
first, last, count = (int(value) for value in raw)
first = parse_hhmm(self._cal_vars.schedule.first.get())
last = parse_hhmm(self._cal_vars.schedule.last.get())
except ValueError:
self._set_schedule_status("Enter whole hours, e.g. 8 20 5.", error=True)
self._set_schedule_status(
"Enter meal times as HH:MM, e.g. 07:15.", error=True
)
return None
try:
count = int(self._cal_vars.schedule.count.get().strip())
except ValueError:
self._set_schedule_status("Enter meals per day as a number.", error=True)
return None
return MealSchedule(first, last, count)
@ -126,25 +163,9 @@ class _GateScheduleEdit(_GateBudgetEdit):
schedule = self._read_schedule_fields()
if schedule is None:
return False
if not FIRST_HOUR <= schedule.first < schedule.last <= LAST_HOUR:
self._set_schedule_status(
f"First meal must be before the last, both {FIRST_HOUR}-{LAST_HOUR}.",
error=True,
)
return False
if not MIN_MEAL_COUNT <= schedule.count <= MAX_MEAL_COUNT:
self._set_schedule_status(
f"Meals per day must be {MIN_MEAL_COUNT}-{MAX_MEAL_COUNT}.",
error=True,
)
return False
# A window of N hours holds at most N+1 whole-hour checkpoints; asking
# for more would round two meals onto the same hour.
if schedule.count > schedule.last - schedule.first + 1:
self._set_schedule_status(
"Too many meals for that window -- widen it or eat less often.",
error=True,
)
problem = schedule_problem(schedule)
if problem is not None:
self._set_schedule_status(problem, error=True)
return False
record_schedule_change(schedule)
self._show_schedule(current_schedule())

View File

@ -18,6 +18,8 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from diet_guard._estimator import Nutrition
from diet_guard._meal_schedule_store import current_schedule
from diet_guard._slot_wire import entry_slot_minute, satisfied_by_entries, slot_fields
from diet_guard._state import log_meal
from diet_guard._state_today import today_entries
@ -33,11 +35,18 @@ SOURCE = "kuchnia wikinga"
def _already_logged(entries: Sequence[dict[str, object]], name: str, slot: int) -> bool:
"""Return True when today's log already holds this dish in this slot."""
"""Return True when today's log already holds this dish at this slot minute.
Compares the entry's *recorded* minute (:func:`entry_slot_minute`), not its
snapped slot -- the app's catering fill uses the same rule, which is the
point: both devices must agree on which dishes are duplicates, or one
re-logs what the other skipped. Snapping still guards the fill flow,
because :func:`fill_plan` skips any slot an entry snaps to (occupancy).
"""
wanted = name.strip().casefold()
return any(
str(entry.get("desc", "")).strip().casefold() == wanted
and entry.get("slot") == slot
and entry_slot_minute(entry) == slot
for entry in entries
)
@ -56,7 +65,7 @@ def fill_plan(slotted: Sequence[SlottedDish]) -> list[SlottedDish]:
Returns:
The dishes to log, in the order given.
"""
taken = {entry.get("slot") for entry in today_entries()}
taken = satisfied_by_entries(today_entries(), current_schedule())
return [item for item in slotted if item.slot not in taken]
@ -95,6 +104,6 @@ def log_dishes(chosen: Sequence[SlottedDish]) -> list[str]:
log_meal(dish.name, dish_nutrition(dish), item.slot)
# Reflect the write locally so two identical dishes in one batch do not
# both land: today_entries() was read once, before the loop.
entries = [*entries, {"desc": dish.name, "slot": item.slot}]
entries = [*entries, {"desc": dish.name, **slot_fields(item.slot)}]
written.append(dish.name)
return written

View File

@ -12,7 +12,7 @@ non-decreasing, keeps the first dish on the first slot and the last on the
last, and doubles up the earliest slots rather than dropping anything.
Integer ``//`` only, never ``round()``. That is repo convention for slot
arithmetic (``docs/meal-schedule.md``): Python's banker's rounding and Dart's
arithmetic (``docs/DOCS-meal-schedule.md``): Python's banker's rounding and Dart's
half-away-from-zero disagree on ``.5``, and a slot one device offers while the
other does not is a checkpoint that can never be satisfied.
@ -44,18 +44,19 @@ if TYPE_CHECKING:
class SlottedDish(NamedTuple):
"""A dish paired with the meal-slot hour it was assigned to."""
"""A dish paired with the meal-slot minute it was assigned to."""
dish: Dish
slot: int
def assign_slots(dishes: Sequence[Dish], slots: Sequence[int]) -> list[SlottedDish]:
"""Pair each dish with a slot hour, following the provider's meal order.
"""Pair each dish with a slot minute, following the provider's meal order.
Args:
dishes: The day's dishes, in any order (sorted here by ``priority``).
slots: The configured slot hours, ascending, e.g. ``(8, 12, 16, 20)``.
slots: The configured slot minutes, ascending, e.g.
``(480, 720, 960, 1200)``.
Returns:
One :class:`SlottedDish` per dish, ordered by the provider's priority.

View File

@ -44,15 +44,19 @@ from pydantic import BaseModel
# the names are genuinely used -- drop this and the server starts write-only.
from diet_guard._mcp_read import get_averages, get_slots, get_status, list_today
from diet_guard._mcp_server import APPENDS, logger, mcp
from diet_guard._meal_schedule import is_wire_int
from diet_guard._meal_schedule_store import current_schedule
from diet_guard._resolve import ManualMacros, resolve_nutrition
from diet_guard._slots import slot_for_log
from diet_guard._slot_wire import parse_hhmm
from diet_guard._slots import day_slots, slot_for_log, slot_label
from diet_guard._state import (
log_meal as record_meal,
)
from diet_guard._state import now_local
from diet_guard._sync_events import publish_after_log
_HOURS_PER_DAY = 24
# ──────────────────────────────────────────────────────────────
# Gated write tool (preview unless confirm=True; NEVER allowlist this)
# ──────────────────────────────────────────────────────────────
@ -74,12 +78,43 @@ class Macros(BaseModel):
fat: float = 0.0
def _resolve_slot_arg(slot: int | str | None) -> int:
"""Return the slot minute ``log_meal``'s ``slot`` argument names.
An int is the legacy whole-hour form (``12`` -> 720), kept so an existing
caller's prompt does not silently start logging at 00:12; a string is
``"HH:MM"``. The result must be one of today's slots: an entry tagged
with a minute the schedule never offers would still snap to *some* slot,
but which one would be a surprise to the caller.
Raises:
ValueError: ``slot`` is not a clock time, or not one of today's slots.
"""
schedule = current_schedule()
if slot is None:
return slot_for_log(now_local(), schedule)
if isinstance(slot, str):
minute = parse_hhmm(slot)
elif is_wire_int(slot) and 0 <= slot < _HOURS_PER_DAY:
# ``is_wire_int`` rejects ``True``: as an int it is 1, i.e. 01:00.
minute = slot * 60
else:
msg = f"slot {slot} is not an hour 0-23; pass a time like '07:15'"
raise ValueError(msg)
slots = day_slots(schedule)
if minute not in slots:
labels = ", ".join(slot_label(each) for each in slots)
msg = f"{slot_label(minute)} is not a meal slot today; choose one of {labels}"
raise ValueError(msg)
return minute
@mcp.tool(title="Log a meal (gated write)", annotations=APPENDS)
def log_meal(
description: str,
grams: float | None = None,
macros: Macros | None = None,
slot: int | None = None,
slot: int | str | None = None,
*,
confirm: bool = False,
) -> dict[str, Any]:
@ -104,15 +139,22 @@ def log_meal(
macros: Manually-entered nutrition (``kcal`` plus optional
protein/carbs/fat). When given, lookups are skipped and the meal is
logged exactly as specified.
slot: The meal-slot hour to satisfy; when omitted (or None) it falls
back to ``slot_for_log``, which clamps to a real hour rather than
returning None, so the entry always satisfies some slot.
slot: The meal slot to satisfy, as ``"HH:MM"`` (e.g. ``"07:15"``) or
a legacy int hour (e.g. ``12`` for 12:00); it must be one of
today's slots (see ``get_slots``). When omitted (or None) it
falls back to ``slot_for_log``, which clamps to a real slot rather
than returning None, so the entry always satisfies some slot.
``target_slot`` in the result is the slot's minute of day.
confirm: Set ``True`` to actually append the entry; otherwise preview.
Returns:
A preview or applied result dict; ``{"ok": false, "reason": ...}`` when
the food cannot be resolved or the log cannot be written.
"""
try:
target_slot = _resolve_slot_arg(slot)
except ValueError as exc:
return {"ok": False, "reason": str(exc)}
manual_macros = (
ManualMacros(
kcal=macros.kcal,
@ -132,9 +174,6 @@ def log_meal(
"or Open Food Facts. Pass kcal=<number> to log it manually."
),
}
target_slot = (
slot if slot is not None else slot_for_log(now_local(), current_schedule())
)
resolved = {
"kcal": nutrition.kcal,
"protein_g": nutrition.protein_g,

View File

@ -21,6 +21,7 @@ from diet_guard._budget import BudgetError, current_schedule, daily_budget
from diet_guard._gate import due_slots
from diet_guard._mcp_server import READS_ONLY, mcp
from diet_guard._meal_schedule_store import current_schedule as current_meal_schedule
from diet_guard._slot_wire import entry_slot_minute
from diet_guard._slots import current_slot, day_slots, slot_label
from diet_guard._state import (
load_log,
@ -62,7 +63,9 @@ def _entry_view(entry: dict[str, object]) -> dict[str, Any]:
"fat_g": entry.get("fat_g"),
"grams": entry.get("grams"),
"source": entry.get("source"),
"slot": entry.get("slot"),
# The recorded slot minute (``slot_min``, else the legacy hour x 60),
# in the same unit as every other slot this server reports.
"slot": entry_slot_minute(entry),
}
@ -78,8 +81,9 @@ def get_status() -> dict[str, Any]:
Reports the calories and macros *consumed* so far, the qualitative
:func:`consumption_band` (``"on track"`` / ``"approaching limit"`` /
``"OVER BUDGET"``, or ``None`` when no budget has been set yet), and the
meal-slot picture (which slots are due, which are already logged, and the
current slot). The raw budget number is intentionally withheld -- only the
meal-slot picture (which slots are due, as ``HH:MM`` labels; which are
already logged and the current slot, as minutes of day -- e.g. 435 for
07:15). The raw budget number is intentionally withheld -- only the
band is exposed, mirroring how the CLI status shows a label to an automated
caller rather than the anchor number.
"""
@ -88,14 +92,15 @@ def get_status() -> dict[str, Any]:
except BudgetError:
# No budget set (or a corrupt file): surface the absence, not a number.
band = None
schedule = current_meal_schedule()
return {
"consumed_kcal": today_total_kcal(),
"consumed_macros_g": _macros_dict(today_total_macros()),
"consumption_band": band,
"budget_initialized": band is not None,
"due_slots": [slot_label(slot) for slot in due_slots()],
"logged_slots": sorted(logged_slots_today()),
"current_slot": current_slot(now_local(), current_meal_schedule()),
"logged_slots": sorted(logged_slots_today(schedule)),
"current_slot": current_slot(now_local(), schedule),
}
@ -104,8 +109,8 @@ def list_today() -> dict[str, Any]:
"""List today's logged meals (valid entries only), newest last.
Returns the per-entry description, calories, macros, portion, source, and
slot -- the same data the CLI ``status`` listing renders, minus the internal
HMAC signature.
recorded slot minute -- the same data the CLI ``status`` listing renders,
minus the internal HMAC signature.
"""
entries = today_entries()
return {
@ -172,15 +177,18 @@ def get_averages() -> dict[str, Any]:
@mcp.tool(title="Meal slots for the day", annotations=READS_ONLY)
def get_slots() -> dict[str, Any]:
"""Return the day's fixed meal slots and which one is current.
"""Return today's meal slots and which one is current.
Pure schedule information (08:00 / 12:00 / 16:00 / 20:00 by default) with no
budget or intake data attached.
budget or intake data attached. Each slot is ``{"minute": m, "label":
"HH:MM"}`` with ``m`` the minute of day (e.g. 435 for 07:15); the label is
what ``log_meal``'s ``slot`` argument accepts. ``current_slot`` is a
minute too, or None before the first slot.
"""
schedule = current_meal_schedule()
return {
"day_slots": [
{"hour": slot, "label": slot_label(slot)} for slot in day_slots(schedule)
{"minute": slot, "label": slot_label(slot)} for slot in day_slots(schedule)
],
"current_slot": current_slot(now_local(), schedule),
}

View File

@ -1,23 +1,38 @@
"""The user's eating window and meal count, and the slot hours they imply.
"""The user's eating window and meal count, and the slot minutes they imply.
A schedule is three numbers -- the first meal hour, the last meal hour, and how
many meals fall between them inclusive -- from which the intermediate
checkpoints are derived by even division. ``MealSchedule(8, 20, 5)`` yields
``(8, 11, 14, 17, 20)``.
A schedule is three numbers -- the first meal's minute of day, the last meal's
minute of day, and how many meals fall between them inclusive -- from which the
intermediate checkpoints are derived by even division and rounded to the
15-minute grid. ``MealSchedule(480, 1200, 5)`` (08:00-20:00, five meals)
yields ``(480, 660, 840, 1020, 1200)``: 08:00, 11:00, 14:00, 17:00, 20:00.
Every time here is a *minute of day*, an int in ``0..1439``. The fields are
deliberately named ``first_minute``/``last_minute`` rather than reusing the old
hour-valued ``first``/``last``: renaming them makes mypy enumerate every call
site that still thinks in hours, instead of one quietly passing ``8`` and
getting a 00:08 breakfast.
This module is pure: no clock, no filesystem, no configuration lookup. Storage
lives in :mod:`diet_guard._meal_schedule_store`, and the slot arithmetic that
consumes a schedule lives in :mod:`diet_guard._slots`.
lives in :mod:`diet_guard._meal_schedule_store`, the slot arithmetic that
consumes a schedule in :mod:`diet_guard._slots`, and a log entry's slot
encoding in :mod:`diet_guard._slot_wire`. The schedule's own wire encoding
(:func:`schedule_to_wire`/:func:`schedule_from_wire`) lives here.
KEEP IN SYNC WITH ``app/lib/models/meal_schedule.dart``. The two must agree on
every input, because a device that derives different slots than its peer nags
for checkpoints the other never offers -- and a slot that can never be
satisfied is a permanent lock. Two rules make that agreement checkable:
satisfied is a permanent lock. ``tests/fixtures/meal_schedule_vectors.json``
(regenerated by ``scripts/build_meal_schedule_fixture.py``) is read by both
test suites; three rules make that agreement checkable:
* **Integer arithmetic only.** No floats and no ``round()`` anywhere in the
derivation. Python's ``round`` is banker's rounding (``round(2.5) == 2``)
while Dart's is half-away-from-zero (``2.5.round() == 3``), so any float path
is a latent cross-language split brain. ``//`` here, ``~/`` there.
* **Non-negative operands to every division.** Python's ``//`` floors while
Dart's ``~/`` truncates, so ``-7 // 15 == -1`` but ``-7 ~/ 15 == 0``. Every
division below runs on a value :meth:`MealSchedule.normalized` has already
pulled into the day, which is what keeps the two operators equivalent.
* **Clamp, don't reject.** Every out-of-range input is normalised to the
nearest legal schedule rather than raising, so the two languages cannot
disagree about which inputs are errors.
@ -26,6 +41,7 @@ satisfied is a permanent lock. Two rules make that agreement checkable:
from __future__ import annotations
from dataclasses import dataclass
from typing import TypeGuard
# A day's meals must fit inside a day, and the pills that render them have to
# stay legible on a phone at the widest (all-logged) size -- see
@ -33,8 +49,13 @@ from dataclasses import dataclass
MIN_MEAL_COUNT = 2
MAX_MEAL_COUNT = 6
FIRST_HOUR = 0
LAST_HOUR = 23
MINUTES_PER_DAY = 1440
# Both the minimum spacing between two checkpoints and the grid the interior
# checkpoints are rounded onto. One constant for both is what makes the
# strict-ascent proof in ``slots()`` work: points at least one grid step apart
# cannot round onto the same grid mark.
SLOT_GRID_MINUTES = 15
# Grace period after the final checkpoint, before the gate stops firing for
# the day. Deliberately a constant rather than the slot spacing: it is how
@ -42,9 +63,9 @@ LAST_HOUR = 23
# meals you eat. Tying it to the spacing would stretch the lockout window to
# midnight at four meals, contradicting the "don't trap me overnight" intent
# this cutoff exists to serve.
ENFORCEMENT_TAIL_HOURS = 2
ENFORCEMENT_TAIL_MINUTES = 120
_HOURS_PER_DAY = 24
_LAST_MINUTE = MINUTES_PER_DAY - 1
def _clamp(value: int, low: int, high: int) -> int:
@ -57,78 +78,141 @@ class MealSchedule:
"""An eating window and the number of meals inside it.
Attributes:
first: Hour of the first meal, 0-23.
last: Hour of the last meal, strictly after ``first``.
first_minute: Minute of day of the first meal, 0-1424.
last_minute: Minute of day of the last meal, at least one grid step
(15 minutes) after ``first_minute`` and at most 1439.
count: Total meals including both endpoints.
"""
first: int
last: int
first_minute: int
last_minute: int
count: int
def normalized(self) -> MealSchedule:
"""Return an equivalent schedule guaranteed to satisfy the invariants.
Ordering matters: ``first`` is clamped into the day, then ``last`` is
clamped to leave at least one hour of window, then ``count`` is clamped
to the window's width. That last clamp is the load-bearing one -- see
:meth:`slots`.
Ordering matters: ``first_minute`` is clamped into the day leaving room
for one grid step, then ``last_minute`` is clamped to at least one grid
step after it, then ``count`` is clamped to how many grid-spaced
checkpoints the window holds. That last clamp is the load-bearing one
-- see :meth:`slots`.
Returns:
A schedule whose ``slots()`` is strictly ascending.
"""
first = _clamp(self.first, FIRST_HOUR, LAST_HOUR - 1)
last = _clamp(self.last, first + 1, LAST_HOUR)
# A window of N hours holds at most N+1 whole-hour checkpoints; asking
# for more would repeat an hour (see slots()).
count = _clamp(
self.count, MIN_MEAL_COUNT, min(MAX_MEAL_COUNT, last - first + 1)
)
first = _clamp(self.first_minute, 0, _LAST_MINUTE - SLOT_GRID_MINUTES)
last = _clamp(self.last_minute, first + SLOT_GRID_MINUTES, _LAST_MINUTE)
# A window of W minutes holds at most W//15 + 1 checkpoints spaced a
# grid step apart; asking for more would round two onto one mark.
capacity = (last - first) // SLOT_GRID_MINUTES + 1
count = _clamp(self.count, MIN_MEAL_COUNT, min(MAX_MEAL_COUNT, capacity))
return MealSchedule(first, last, count)
def slots(self) -> tuple[int, ...]:
"""Return the meal-slot hours, ascending, endpoints exact.
"""Return the meal-slot minutes, ascending, endpoints exact.
Meals are spread evenly across the window and rounded to whole hours by
integer arithmetic: slot *i* is ``first + (i*span + d//2) // d`` where
``span = last - first`` and ``d = count - 1``. The ``d//2`` term is a
round-half-up bias applied before the division, which is what keeps
this float-free.
With ``span = last - first`` and ``d = count - 1``, interior slot *i*
is ``raw = first + (i*span + d//2) // d`` (even division, the ``d//2``
term a round-half-up bias that keeps it float-free), then snapped to
the nearest absolute quarter hour by ``(raw + 7) // 15 * 15``. The
endpoints are ``first`` and ``last`` exactly -- never snapped -- so the
eating window the user typed is always honoured, even at 07:23.
Both endpoints land exactly on ``first`` and ``last`` by construction,
so the eating window is always honoured even when the interior spacing
has to round.
The result is strictly ascending because :meth:`normalized` caps
``count`` at ``last - first + 1``. Without that cap a narrow window
repeats an hour (``08-12`` with 6 meals would give
``8, 9, 10, 10, 11, 12``), and since slot hours are used as set
members, dict keys *and* notification ids, a repeat silently drops a
checkpoint.
Strictly ascending, provably: :meth:`normalized` caps ``count`` so that
``span / d >= 15``, hence consecutive ``raw`` values differ by at least
15, and two integers at least 15 apart never snap onto the same grid
mark. Snapping moves a value by at most 7, so the first interior slot
is at least 8 past ``first`` and the last at least 8 before ``last``.
That matters because slot minutes are set members, dict keys *and*
notification ids: a repeat silently drops a checkpoint.
Returns:
The slot hours, ascending, of length ``normalized().count``.
The slot minutes, ascending, of length ``normalized().count``.
"""
schedule = self.normalized()
span = schedule.last - schedule.first
first, last = schedule.first_minute, schedule.last_minute
span = last - first
divisions = schedule.count - 1
return tuple(
schedule.first + (index * span + divisions // 2) // divisions
for index in range(schedule.count)
interior = (
(first + (index * span + divisions // 2) // divisions + 7)
// SLOT_GRID_MINUTES
* SLOT_GRID_MINUTES
for index in range(1, divisions)
)
return (first, *interior, last)
@property
def enforcement_end_hour(self) -> int:
"""Return the hour at which slot enforcement stops for the day.
def enforcement_end_minute(self) -> int:
"""Return the minute at which slot enforcement stops for the day.
Clamped to the end of the day: a 23:00 last meal would otherwise put
the cutoff at 25, making ``hour < cutoff`` vacuously true so the
enforcement window never closes and the gate can never stop firing.
Derived from the *normalised* last meal, so it always agrees with the
last entry of :meth:`slots`. Clamped to the end of the day: a 23:00
last meal would otherwise put the cutoff at 1500, making
``minute < cutoff`` vacuously true so the enforcement window never
closes and the gate can never stop firing.
"""
return min(self.last + ENFORCEMENT_TAIL_HOURS, _HOURS_PER_DAY)
last = self.normalized().last_minute
return min(last + ENFORCEMENT_TAIL_MINUTES, MINUTES_PER_DAY)
# The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, with the
# enforcement window closing at 22:00. Still what a device uses before the
# user has ever chosen anything, so upgrading changes no behaviour.
DEFAULT_SCHEDULE = MealSchedule(first=8, last=20, count=4)
DEFAULT_SCHEDULE = MealSchedule(first_minute=8 * 60, last_minute=20 * 60, count=4)
def is_wire_int(value: object) -> TypeGuard[int]:
"""Return True for a real int; ``bool`` is excluded, as Dart's ``is int`` is.
Python's ``bool`` subclasses ``int``, so a bare ``isinstance`` would accept
``true`` from a peer's JSON that the Dart side rejects -- two devices
disagreeing about which values are usable.
"""
return isinstance(value, int) and not isinstance(value, bool)
def schedule_to_wire(schedule: MealSchedule) -> dict[str, int]:
"""Return the synced ``sched:<date>`` value for ``schedule``.
Backward compatible by construction: ``f``/``l`` carry whole hours exactly
as before the move to minutes, and ``fm``/``lm`` appear only when an
endpoint is off the hour. So a whole-hour schedule encodes byte-identically
to the old ``{"f", "l", "n"}`` form. The schedule is normalised first, so
every ``//`` runs on a non-negative value (see the module docstring).
Returns:
``{"f", "l", "n"}`` plus ``"fm"``/``"lm"`` for off-hour endpoints.
"""
norm = schedule.normalized()
first, last = norm.first_minute, norm.last_minute
wire = {"f": first // 60, "l": last // 60, "n": norm.count}
if first % 60:
wire["fm"] = first
if last % 60:
wire["lm"] = last
return wire
def schedule_from_wire(raw: object) -> MealSchedule | None:
"""Return the normalised schedule a ``sched:<date>`` value describes.
``fm``/``lm`` win when they are ints; otherwise ``f``/``l`` are hours.
Never raises: anything without int ``f``, ``l`` and ``n`` yields None, so
one bad field from a peer cannot take out the whole history. Normalising
on the way in means a peer running a future version with a wider range
cannot hand us a schedule we would derive differently.
Returns:
The decoded, normalised schedule, or None when ``raw`` is unusable.
"""
if not isinstance(raw, dict):
return None
first, last, count = raw.get("f"), raw.get("l"), raw.get("n")
if not (is_wire_int(first) and is_wire_int(last) and is_wire_int(count)):
return None
first_minute, last_minute = raw.get("fm"), raw.get("lm")
return MealSchedule(
first_minute if is_wire_int(first_minute) else first * 60,
last_minute if is_wire_int(last_minute) else last * 60,
count,
).normalized()

View File

@ -34,7 +34,12 @@ import json
import logging
from diet_guard._constants import MEAL_SCHEDULE_FILE
from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule
from diet_guard._meal_schedule import (
DEFAULT_SCHEDULE,
MealSchedule,
schedule_from_wire,
schedule_to_wire,
)
_logger = logging.getLogger(__name__)
@ -65,33 +70,27 @@ class ScheduleEntry:
def entry_to_json(entry: ScheduleEntry) -> dict[str, object]:
"""Return the wire/disk form of one entry's value."""
return {
"f": entry.schedule.first,
"l": entry.schedule.last,
"n": entry.schedule.count,
"t": entry.edited_at,
}
# ``schedule_to_wire`` keeps a whole-hour schedule byte-identical to the
# pre-minute ``{"f", "l", "n"}`` form, so an older build reading this file
# still sees the hours it understands.
return {**schedule_to_wire(entry.schedule), "t": entry.edited_at}
def entry_from_json(effective_from: str, raw: object) -> ScheduleEntry | None:
"""Return an entry parsed from its stored value, or None if unusable.
Never raises: a malformed entry is skipped so one bad field from a peer
cannot take out the whole history.
cannot take out the whole history. ``schedule_from_wire`` normalises on
the way in, so a peer running a future version with a wider range cannot
hand us a schedule we would derive differently.
"""
if not isinstance(raw, dict):
return None
first, last, count = raw.get("f"), raw.get("l"), raw.get("n")
if not (
isinstance(first, int) and isinstance(last, int) and isinstance(count, int)
):
schedule = schedule_from_wire(raw)
if schedule is None or not isinstance(raw, dict):
return None
edited_at = raw.get("t")
return ScheduleEntry(
effective_from=effective_from,
# Normalising on the way in means a peer running a future version with
# a wider range cannot hand us a schedule we would derive differently.
schedule=MealSchedule(first, last, count).normalized(),
schedule=schedule,
edited_at=edited_at if isinstance(edited_at, str) else _EPOCH_ISO,
)

136
diet_guard/_slot_wire.py Normal file
View File

@ -0,0 +1,136 @@
"""How a log entry records its meal slot on disk and on the sync wire.
Slots are minutes of day (see :mod:`diet_guard._slots`), but every entry ever
written before that change carries an hour in ``"slot"``, and a peer running an
older build reads only that field. So the wire rule is additive:
* **Writers** always write ``"slot" = minute // 60`` and add
``"slot_min" = minute`` *only* when ``minute % 60 != 0``. A whole-hour slot
therefore encodes byte-identically to the pre-minute format -- no re-signing
storm, no diff on every existing entry -- and an older peer reading an
off-hour entry sees the hour it starts in. :func:`slot_fields` is that rule.
* **Readers** prefer an int ``"slot_min"``, fall back to ``"slot" * 60``, and
otherwise report no slot. :func:`entry_slot_minute` is that rule.
``bool`` is rejected wherever an int is expected: Python's ``bool`` subclasses
``int`` but Dart's does not, and a value one device accepts while the other
ignores is the cross-device split brain the shared fixture exists to catch.
KEEP IN SYNC WITH ``app/lib/models/slot.dart`` (``slotFields``,
``entrySlotMinute``); ``tests/fixtures/meal_schedule_vectors.json`` gates both.
"""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
from diet_guard._meal_schedule import MINUTES_PER_DAY, is_wire_int
from diet_guard._slots import satisfied_slots
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
from diet_guard._meal_schedule import MealSchedule
# ASCII digits only: ``\d`` would also accept Arabic-Indic and other Unicode
# digits, which ``int()`` happily parses.
_HHMM = re.compile(r"([0-9]{1,2})(?::([0-9]{2}))?")
_HOURS_PER_DAY = 24
_MINUTES_PER_HOUR = 60
def slot_fields(minute: int) -> dict[str, int]:
"""Return the entry fields that record ``minute`` as its slot.
Args:
minute: The slot's minute of day, ``0..1439``.
Returns:
``{"slot": hour}``, plus ``"slot_min"`` when ``minute`` is off the hour.
Raises:
ValueError: ``minute`` is outside the day -- a writer bug, refused
rather than encoded, since ``//`` on a negative value would floor
here and truncate in Dart.
"""
if not 0 <= minute < MINUTES_PER_DAY:
msg = f"slot minute {minute} is outside 0..{MINUTES_PER_DAY - 1}"
raise ValueError(msg)
fields = {"slot": minute // 60}
if minute % 60:
fields["slot_min"] = minute
return fields
def entry_slot_minute(entry: Mapping[str, object]) -> int | None:
"""Return the slot minute an entry records, or None when it has none.
Args:
entry: One decoded log entry.
Returns:
``entry["slot_min"]`` if it is an int, else ``entry["slot"] * 60`` if
that is an int, else None. Values are not range-checked: an entry is
reported as written, and :func:`diet_guard._slots.nearest_slot` maps
anything onto a real slot.
"""
slot_min = entry.get("slot_min")
if is_wire_int(slot_min):
return slot_min
slot = entry.get("slot")
if is_wire_int(slot):
return slot * 60
return None
def satisfied_by_entries(
entries: Iterable[Mapping[str, object]], schedule: MealSchedule
) -> set[int]:
"""Return the slots of ``schedule`` that ``entries`` satisfy.
The one composition every "is this slot logged?" site goes through: read
each entry's recorded minute, then snap it to its nearest slot. Routing
every site through here is what keeps the gate, the CLI, MCP and the
catering import from disagreeing about one entry after a schedule edit --
an exact-match site would re-nag for a meal another site counts.
Args:
entries: Decoded log entries; ones recording no slot are ignored.
schedule: The schedule in force on the entries' day.
Returns:
The satisfied slot minutes (possibly empty).
"""
minutes = (entry_slot_minute(entry) for entry in entries)
return satisfied_slots(
(minute for minute in minutes if minute is not None), schedule
)
def parse_hhmm(text: str) -> int:
"""Parse a user-typed clock time into a minute of day.
Accepts ``H``, ``HH``, ``H:MM`` and ``HH:MM`` with surrounding whitespace,
e.g. ``"7"`` -> 420, ``"07:15"`` -> 435.
Args:
text: The time as typed.
Returns:
The minute of day, ``0..1439``.
Raises:
ValueError: ``text`` is not in one of those forms, or the hour is not
0-23 or the minutes not 0-59.
"""
match = _HHMM.fullmatch(text.strip())
if match is None:
msg = f"invalid time {text!r}, expected HH:MM (e.g. 07:15) or HH"
raise ValueError(msg)
hour = int(match.group(1))
minute = int(match.group(2) or 0)
if hour >= _HOURS_PER_DAY or minute >= _MINUTES_PER_HOUR:
msg = f"invalid time {text!r}: hour must be 0-23 and minutes 0-59"
raise ValueError(msg)
return hour * 60 + minute

View File

@ -7,10 +7,17 @@ exhaustively unit-testable without mocking the filesystem or the wall clock.
The stateful "which slots have I actually logged?" question lives in
:mod:`diet_guard._state`; the two are composed in :mod:`diet_guard._gate`.
A "slot" is simply the integer hour at which a meal checkpoint opens (08, 12,
16, 20 by default). A slot is *elapsed* once its hour has arrived and we are
still inside the daily enforcement window; an elapsed slot with no logged meal
is what makes the gate fire.
A "slot" is the *minute of day* (``0..1439``) at which a meal checkpoint opens
(480, 720, 960, 1200 -- 08:00, 12:00, 16:00, 20:00 -- by default). A slot is
*elapsed* once its minute has arrived and we are still inside the daily
enforcement window; an elapsed slot with no logged meal is what makes the gate
fire. How a log entry records its slot on the wire, and how the old
hour-valued ``slot`` field is read back, lives in :mod:`diet_guard._slot_wire`.
A logged meal satisfies the slot *nearest* its recorded slot minute
(:func:`satisfied_slots`), not only an exact match. That is how a meal logged
under an old schedule (or an old hour-valued entry) still counts after the
schedule moves by a few minutes -- nothing on disk is ever rewritten.
``schedule`` is a required argument on every function here, deliberately: it
used to be read from module constants, and a default would let a call site that
@ -20,6 +27,9 @@ device offers and the other does not is a checkpoint that can never be
satisfied. Making it required lets mypy enumerate the call sites instead.
Callers resolve the value at the impure edge, mirroring how
:mod:`diet_guard._daystatus` takes an explicit budget schedule.
KEEP IN SYNC WITH ``app/lib/models/slot.dart``; the shared vectors in
``tests/fixtures/meal_schedule_vectors.json`` gate the two.
"""
from __future__ import annotations
@ -27,20 +37,27 @@ from __future__ import annotations
from datetime import date, datetime, time
from typing import TYPE_CHECKING
from diet_guard._meal_schedule import MINUTES_PER_DAY
if TYPE_CHECKING:
from collections.abc import Iterable
from diet_guard._meal_schedule import MealSchedule
_HOURS_PER_DAY = 24
def minute_of_day(now: datetime) -> int:
"""Return ``now``'s minute of day, ``0..1439`` (seconds are ignored)."""
return now.hour * 60 + now.minute
def day_slots(schedule: MealSchedule) -> tuple[int, ...]:
"""Return the meal-slot hours for a day, e.g. ``(8, 12, 16, 20)``.
"""Return the meal-slot minutes for a day, e.g. ``(480, 720, 960, 1200)``.
Args:
schedule: The eating window and meal count to derive slots from.
Returns:
The slot hours in ascending order.
The slot minutes in ascending order.
"""
return schedule.slots()
@ -58,11 +75,12 @@ def within_enforcement_window(now: datetime, schedule: MealSchedule) -> bool:
Returns:
True if slot enforcement is active at ``now``.
"""
return schedule.slots()[0] <= now.hour < schedule.enforcement_end_hour
minute = minute_of_day(now)
return schedule.slots()[0] <= minute < schedule.enforcement_end_minute
def elapsed_slots(now: datetime, schedule: MealSchedule) -> tuple[int, ...]:
"""Return today's slots whose hour has arrived as of ``now``.
"""Return today's slots whose minute has arrived as of ``now``.
Empty outside the enforcement window (before the first slot, or after the
overnight cutoff), so the caller never has to special-case the night.
@ -72,11 +90,12 @@ def elapsed_slots(now: datetime, schedule: MealSchedule) -> tuple[int, ...]:
schedule: The schedule in force for that day.
Returns:
The elapsed slot hours, ascending (possibly empty).
The elapsed slot minutes, ascending (possibly empty).
"""
if not within_enforcement_window(now, schedule):
return ()
return tuple(slot for slot in day_slots(schedule) if slot <= now.hour)
minute = minute_of_day(now)
return tuple(slot for slot in day_slots(schedule) if slot <= minute)
def missing_slots(
@ -86,11 +105,12 @@ def missing_slots(
Args:
now: Reference local time.
logged: The set of slot hours already covered by today's log.
logged: The slot minutes already covered by today's log -- normally
:func:`satisfied_slots` of the entries' slot minutes.
schedule: The schedule in force for that day.
Returns:
The unsatisfied elapsed slot hours, ascending (empty == nothing due).
The unsatisfied elapsed slot minutes, ascending (empty == nothing due).
"""
return tuple(slot for slot in elapsed_slots(now, schedule) if slot not in logged)
@ -107,7 +127,7 @@ def current_slot(now: datetime, schedule: MealSchedule) -> int | None:
schedule: The schedule in force for that day.
Returns:
The latest elapsed slot hour, or None when none have elapsed yet.
The latest elapsed slot minute, or None when none have elapsed yet.
"""
elapsed = elapsed_slots(now, schedule)
return elapsed[-1] if elapsed else None
@ -120,8 +140,8 @@ def slot_for_log(now: datetime, schedule: MealSchedule) -> int:
the first slot, clamp to the first slot; after the enforcement window ends,
clamp to the last slot; behaviour inside a window is unchanged. Both
languages must reach each answer by the *same* branch, not merely agree on
the value -- ``test_slots.py`` sweeps every hour of the day against several
schedules for exactly that reason.
the value -- the shared fixture pins every minute edge for exactly that
reason.
Unlike :func:`current_slot` this never returns None, which is the point: an
off-hours meal used to satisfy no slot at all, so eating at 07:30 or 22:30
@ -134,39 +154,61 @@ def slot_for_log(now: datetime, schedule: MealSchedule) -> int:
schedule: The schedule in force for that day.
Returns:
The slot hour to tag the log with.
The slot minute to tag the log with.
"""
slots = day_slots(schedule)
if now.hour < slots[0]:
if minute_of_day(now) < slots[0]:
return slots[0]
current = current_slot(now, schedule)
return current if current is not None else slots[-1]
def nearest_slot(minute: int, schedule: MealSchedule) -> int:
"""Return the slot closest to ``minute``; an exact tie goes to the earlier.
The tie rule is part of the cross-language contract: ``min`` keeps the
first minimal element of the ascending slots, and the Dart loop replaces
its best only on a strictly smaller distance.
"""
return min(day_slots(schedule), key=lambda slot: abs(slot - minute))
def satisfied_slots(entry_minutes: Iterable[int], schedule: MealSchedule) -> set[int]:
"""Return the slots covered by meals recorded at ``entry_minutes``.
Each recorded slot minute satisfies its :func:`nearest_slot`. Many-to-one
is intended: two meals snapping onto one slot satisfy only that slot, so a
double breakfast does not also clear lunch. This is what lets an entry
written under an older schedule count toward today's nearest checkpoint
without rewriting it on disk.
"""
return {nearest_slot(minute, schedule) for minute in entry_minutes}
def resolve_future_when(
date_str: str, hour: int, schedule: MealSchedule, now: datetime
date_str: str, slot_minute: int, schedule: MealSchedule, now: datetime
) -> datetime:
"""Build a tz-aware datetime for a meal pre-logged against a future slot.
Lets a caller (the CLI's ``--date``/``--hour`` flags, or the app's future-
date picker) turn a user-picked date+hour into the ``when`` that
Lets a caller (the CLI's ``--date`` flag, or the app's future-date picker)
turn a user-picked date+slot into the ``when`` that
:func:`diet_guard._state.log_meal` expects, with the same validation on
both platforms. Still clock-free per the module's own rule: ``now`` is
supplied by the caller rather than read here.
Args:
date_str: The chosen date as ``YYYY-MM-DD``.
hour: The chosen slot hour; must be one of ``schedule``'s slot hours.
schedule: The schedule in force, used to validate ``hour``.
slot_minute: The chosen slot; must be one of ``schedule``'s slots.
schedule: The schedule in force, used to validate ``slot_minute``.
now: Reference local time, used to reject a non-future date.
Returns:
A tz-aware datetime combining ``date_str`` and ``hour``, in ``now``'s
timezone.
A tz-aware datetime combining ``date_str`` and ``slot_minute``, in
``now``'s timezone.
Raises:
ValueError: ``date_str`` doesn't parse, ``hour`` isn't a slot hour, or
the resulting date isn't strictly after ``now``'s date.
ValueError: ``date_str`` doesn't parse, ``slot_minute`` isn't a slot,
or the resulting date isn't strictly after ``now``'s date.
"""
try:
parsed_date = date.fromisoformat(date_str)
@ -174,15 +216,18 @@ def resolve_future_when(
msg = f"invalid date {date_str!r}, expected YYYY-MM-DD"
raise ValueError(msg) from exc
slots = day_slots(schedule)
if hour not in slots:
msg = f"hour {hour} is not a meal slot; choose one of {slots}"
if slot_minute not in slots:
labels = ", ".join(slot_label(slot) for slot in slots)
msg = f"{slot_label(slot_minute)} is not a meal slot; choose one of {labels}"
raise ValueError(msg)
if parsed_date <= now.date():
msg = f"{date_str} is not a future date"
raise ValueError(msg)
return datetime.combine(parsed_date, time(hour=hour), tzinfo=now.tzinfo)
clock = time(hour=slot_minute // 60, minute=slot_minute % 60)
return datetime.combine(parsed_date, clock, tzinfo=now.tzinfo)
def slot_label(slot: int) -> str:
"""Return a human ``HH:00`` label for a slot hour, e.g. ``"08:00"``."""
return f"{slot % _HOURS_PER_DAY:02d}:00"
def slot_label(minute: int) -> str:
"""Return a human ``HH:MM`` label for a slot minute, e.g. ``"07:15"``."""
wrapped = minute % MINUTES_PER_DAY
return f"{wrapped // 60:02d}:{wrapped % 60:02d}"

View File

@ -24,6 +24,7 @@ from gatelock.log_integrity import (
from diet_guard._coerce import as_float
from diet_guard._constants import FOOD_LOG_FILE
from diet_guard._slot_wire import slot_fields
if TYPE_CHECKING:
from diet_guard._estimator import Nutrition
@ -137,9 +138,12 @@ def log_meal(
Args:
description: The user's free-text meal description.
nutrition: Estimated nutrition for the portion eaten.
slot: The meal-slot hour this entry satisfies (e.g. ``12`` for the
12:00 checkpoint). When None the entry still counts toward the
day's calories but does not mark any slot as logged.
slot: The meal-slot *minute of day* this entry satisfies (e.g.
``720`` for the 12:00 checkpoint, ``435`` for 07:15). Encoded
through :func:`diet_guard._slot_wire.slot_fields`, so a whole-hour
slot is written exactly as before the move to minutes. When None
the entry still counts toward the day's calories but does not mark
any slot as logged.
components: For a composite (multi-item) meal, each component's own
name and macros. Carried on the log entry itself -- not just the
food bank -- so a bank rebuilt purely by replaying the log (the
@ -173,7 +177,9 @@ def log_meal(
"source": nutrition.source,
}
if slot is not None:
entry["slot"] = slot
# Before signing: the HMAC covers the whole dict, so a ``slot_min``
# added afterwards would make the entry fail verification and vanish.
entry.update(slot_fields(slot))
if components is not None:
entry["components"] = list(components)
signature = compute_entry_hmac(entry)

View File

@ -18,8 +18,12 @@ already import them from.
from __future__ import annotations
from typing import TYPE_CHECKING
from diet_guard._budget import daily_budget
from diet_guard._constants import BUDGET_WARN_FRACTION
from diet_guard._meal_schedule_store import current_schedule
from diet_guard._slot_wire import satisfied_by_entries
from diet_guard._state import (
_entry_float,
_today,
@ -27,6 +31,9 @@ from diet_guard._state import (
load_log,
)
if TYPE_CHECKING:
from diet_guard._meal_schedule import MealSchedule
__all__ = [
"consumption_band",
"logged_slots_today",
@ -65,8 +72,14 @@ def today_total_macros() -> tuple[float, float, float]:
return round(protein, 1), round(carbs, 1), round(fat, 1)
def logged_slots_today() -> set[int]:
"""Return the set of meal-slot hours already covered by today's log.
def logged_slots_today(schedule: MealSchedule | None = None) -> set[int]:
"""Return the set of today's slot minutes already covered by today's log.
Each entry satisfies the slot *nearest* its recorded minute
(:func:`diet_guard._slot_wire.satisfied_by_entries`), so a meal logged at
07:00 still covers a checkpoint the user has since moved to 07:15.
Without the snap, every schedule edit would re-open the slots already
eaten that day and lock the user out for meals they did log.
Only valid (HMAC-verified) entries count, so stripping entries to dodge a
checkpoint makes that slot reappear as unsatisfied -- the fail-closed
@ -74,23 +87,22 @@ def logged_slots_today() -> set[int]:
checkpoint) contributes calories but satisfies no slot.
Nothing produces a slot-less entry any more: the phone's "Snack" chip was
removed on 2026-08-14, and every remaining writer resolves a concrete hour
removed on 2026-08-14, and every remaining writer resolves a concrete slot
through ``slot_for_log`` -- the CLI (:mod:`_cli`), the gate
(:mod:`_gatelock_mealflow`) and the MCP tool (:mod:`_mcp`, which falls back
to it whenever its ``slot`` argument is omitted or None). The check below
is still load-bearing for entries already on disk and arriving over sync --
removing it would make every historical snack retroactively satisfy a meal
slot.
to it whenever its ``slot`` argument is omitted or None). Skipping
slot-less entries (in ``satisfied_by_entries``) is still load-bearing for
entries already on disk and arriving over sync -- removing it would make
every historical snack retroactively satisfy a meal slot.
Args:
schedule: The schedule to snap onto; defaults to today's.
Returns:
The distinct integer slot hours logged today (possibly empty).
The distinct slot minutes satisfied today (possibly empty).
"""
slots: set[int] = set()
for entry in today_entries():
value = entry.get("slot")
if isinstance(value, int) and not isinstance(value, bool):
slots.add(value)
return slots
resolved = schedule if schedule is not None else current_schedule()
return satisfied_by_entries(today_entries(), resolved)
def remaining_budget() -> float:

View File

@ -11,7 +11,9 @@ predates meal schedules neither clobbers those fields nor blocks them -- it
relays them untouched. That is what makes this shippable without a
coordinated release.
The value is a small map (``{"f": 8, "l": 20, "n": 5}``) rather than a scalar.
The value is a small map (``{"f": 8, "l": 20, "n": 5}``, plus ``fm``/``lm``
minutes only for an off-hour endpoint -- see
:func:`diet_guard._meal_schedule.schedule_to_wire`) rather than a scalar.
``Record.to_dict``/``from_dict`` round-trip nested values unchanged, and a
malformed one is skipped exactly as a non-int ``hist:`` value is.
"""
@ -24,7 +26,7 @@ from typing import TYPE_CHECKING
from crdt_sync import Hlc
from diet_guard._device import device_id
from diet_guard._meal_schedule import MealSchedule
from diet_guard._meal_schedule import schedule_from_wire, schedule_to_wire
from diet_guard._meal_schedule_store import ScheduleEntry
from diet_guard.sync_merge._clock import _EPOCH
@ -64,11 +66,7 @@ def schedule_fields(
"""
return {
f"{SCHEDULE_FIELD_PREFIX}{entry.effective_from}": (
{
"f": entry.schedule.first,
"l": entry.schedule.last,
"n": entry.schedule.count,
},
schedule_to_wire(entry.schedule),
schedule_hlc(entry),
)
for entry in entries
@ -90,21 +88,17 @@ def log_to_schedule_history(log: Log) -> tuple[ScheduleEntry, ...]:
for name, (value, hlc) in record.fields.items():
if not name.startswith(SCHEDULE_FIELD_PREFIX):
continue
if not isinstance(value, dict):
continue
first, last, count = value.get("f"), value.get("l"), value.get("n")
if not (
isinstance(first, int) and isinstance(last, int) and isinstance(count, int)
) or any(isinstance(part, bool) for part in (first, last, count)):
# Normalised on the way in, so a peer running a future version with a
# wider range cannot hand us a schedule we would derive slots
# differently from.
schedule = schedule_from_wire(value)
if schedule is None:
continue
edited = datetime.fromtimestamp(hlc.wall_time_ms / 1000, tz=UTC)
entries.append(
ScheduleEntry(
effective_from=name[len(SCHEDULE_FIELD_PREFIX) :],
# Normalised on the way in, so a peer running a future version
# with a wider range cannot hand us a schedule we would derive
# slots differently from.
schedule=MealSchedule(first, last, count).normalized(),
schedule=schedule,
edited_at=edited.astimezone().isoformat(timespec="seconds"),
),
)

View File

@ -199,6 +199,9 @@ def fake_tk() -> Iterator[None]:
stack.enter_context(patch.object(module, "tk", _FAKE_TK))
stack.enter_context(patch.object(_gatelock_calendar, "ttk", _FAKE_TTK))
stack.enter_context(patch.object(_gatelock_calendar_ui, "ttk", _FAKE_TTK))
# The schedule row's HH:MM spinboxes are ttk widgets; left real, they
# would be built against a fake parent.
stack.enter_context(patch.object(_gatelock_calendar_schedule, "ttk", _FAKE_TTK))
yield

View File

@ -27,6 +27,7 @@ from diet_guard.tests._tk_fakes_canvas import FakeCanvas, FakeScrollbar
from diet_guard.tests._tk_fakes_containers import (
FakeNotebook,
FakeRadiobutton,
FakeSpinbox,
FakeStyle,
FakeWidget,
)
@ -45,6 +46,7 @@ __all__ = [
"FakeNotebook",
"FakeRadiobutton",
"FakeScrollbar",
"FakeSpinbox",
"FakeStyle",
"FakeText",
"FakeVar",
@ -174,7 +176,7 @@ _FAKE_TK = SimpleNamespace(
Event=object,
)
_FAKE_TTK = SimpleNamespace(Notebook=FakeNotebook, Style=FakeStyle)
_FAKE_TTK = SimpleNamespace(Notebook=FakeNotebook, Style=FakeStyle, Spinbox=FakeSpinbox)
# Every mixin module the gate window is built from imports ``tkinter``
# independently; all of them must see the fake so ``tk.TclError`` etc. are the

View File

@ -23,6 +23,7 @@ from __future__ import annotations
__all__ = [
"FakeNotebook",
"FakeRadiobutton",
"FakeSpinbox",
"FakeStyle",
"FakeWidget",
]
@ -181,3 +182,28 @@ class FakeStyle:
def map(self, style_name: str, **kwargs: object) -> None:
self.configured.setdefault(style_name, {}).update(kwargs)
class FakeSpinbox(FakeWidget):
"""A functional stand-in for ``ttk.Spinbox``.
Reads and writes go through its ``textvariable`` (as the real widget's
do), ``state`` is readable via ``cget``, and ``bind`` keeps each handler
so a test can fire ``<<Increment>>``/``<<Decrement>>`` the way an arrow
press, Up/Down or the wheel would.
"""
def __init__(self, *args: object, **kwargs: object) -> None:
super().__init__(*args, **kwargs)
self.bindings: dict[str, object] = {}
def cget(self, key: str) -> object:
return self.configured.get(key, "")
def get(self) -> str:
variable = self.configured.get("textvariable")
return str(variable.get()) if hasattr(variable, "get") else ""
def bind(self, *args: object, **kwargs: object) -> None:
sequence, handler = args[0], args[1]
self.bindings[str(sequence)] = handler

View File

@ -195,8 +195,8 @@ class TestStatus:
def test_slot_status_all_marks(self, capsys: pytest.CaptureFixture[str]) -> None:
"""The slot line shows logged / DUE / upcoming together."""
with (
patch.object(_cli, "logged_slots_today", return_value={8}),
patch.object(_cli, "due_slots", return_value=[12]),
patch.object(_cli, "logged_slots_today", return_value={480}),
patch.object(_cli, "due_slots", return_value=[720]),
):
_cli._print_slot_status()
out = capsys.readouterr().out

View File

@ -13,6 +13,8 @@ from diet_guard import _cli_log
from diet_guard._budget import write_budget
from diet_guard._cli import main
from diet_guard._estimator import Nutrition
from diet_guard._meal_schedule import MealSchedule
from diet_guard._meal_schedule_store import record_schedule_change
from diet_guard._state import load_log, now_local
if TYPE_CHECKING:
@ -57,3 +59,32 @@ class TestAteFutureDate:
yesterday = (now_local() - timedelta(days=1)).date().isoformat()
assert main(["ate", "x", "--date", yesterday, "--hour", "12"]) == 1
assert "not a future date" in capsys.readouterr().out
def test_an_hhmm_hour_pre_logs_an_off_hour_slot(
self, capsys: pytest.CaptureFixture[str]
) -> None:
"""--hour 07:15 names a minute slot and is echoed as HH:MM."""
record_schedule_change(MealSchedule(435, 1140, 5))
tomorrow = (now_local() + timedelta(days=1)).date().isoformat()
with patch.object(_cli_log, "resolve_nutrition", return_value=_NUT):
assert main(["ate", "oats", "--date", tomorrow, "--hour", "07:15"]) == 0
assert f"for {tomorrow} 07:15" in capsys.readouterr().out
(entry,) = load_log()[tomorrow]
assert (entry["slot"], entry["slot_min"]) == (7, 435)
assert entry["time"].startswith(f"{tomorrow}T07:15")
def test_a_whole_hour_is_echoed_as_hhmm(
self, capsys: pytest.CaptureFixture[str]
) -> None:
tomorrow = (now_local() + timedelta(days=1)).date().isoformat()
with patch.object(_cli_log, "resolve_nutrition", return_value=_NUT):
assert main(["ate", "x", "--date", tomorrow, "--hour", "20:00"]) == 0
assert f"for {tomorrow} 20:00" in capsys.readouterr().out
assert "slot_min" not in load_log()[tomorrow][0]
def test_an_unparseable_hour_errors(
self, capsys: pytest.CaptureFixture[str]
) -> None:
tomorrow = (now_local() + timedelta(days=1)).date().isoformat()
assert main(["ate", "x", "--date", tomorrow, "--hour", "noon"]) == 1
assert "expected HH:MM" in capsys.readouterr().out

View File

@ -216,5 +216,5 @@ class TestGateReadsFreshState:
"""At 09:00 only the 08:00 slot is due; logging it flips the decision."""
now = datetime(2026, 1, 1, 9, 0, tzinfo=UTC)
assert gate_is_due(now) is True
log_meal("oatmeal", self._nutrition(), slot=8)
log_meal("oatmeal", self._nutrition(), slot=480)
assert gate_is_due(now) is False

View File

@ -36,8 +36,8 @@ class TestDueSlots:
def test_injected_now(self) -> None:
"""With 08:00 logged at 13:00, only 12:00 is due."""
with _logged({8}):
assert due_slots(_at(13)) == (12,)
with _logged({480}):
assert due_slots(_at(13)) == (720,)
def test_default_now_uses_clock(self) -> None:
"""Omitting ``now`` reads the real clock (mocked here for determinism)."""
@ -48,7 +48,7 @@ class TestDueSlots:
return_value=_at(9),
),
):
assert due_slots() == (8,)
assert due_slots() == (480,)
class TestGateIsDue:
@ -61,7 +61,7 @@ class TestGateIsDue:
def test_not_due_when_all_logged(self) -> None:
"""Everything elapsed is logged -> no lock."""
with _logged({8, 12}):
with _logged({480, 720}):
assert gate_is_due(_at(13)) is False
@ -70,12 +70,12 @@ class TestGateMessage:
def test_all_logged(self) -> None:
"""Nothing missing -> the up-to-date message."""
with _logged({8, 12}):
with _logged({480, 720}):
assert "up to date" in gate_message(_at(13))
def test_single_missing(self) -> None:
"""One missing slot -> singular phrasing."""
with _logged({8}):
with _logged({480}):
assert gate_message(_at(13)) == "Log your 12:00 meal to unlock."
def test_multiple_missing(self) -> None:

View File

@ -0,0 +1,65 @@
"""A schedule edit must not re-open meals already logged that day.
End-to-end through the real public path -- ``log_meal`` writes signed entries
to the (redirected) log, ``record_schedule_change`` stores the schedule, and
``gate_is_due`` / ``logged_slots_today`` read both back -- with nothing mocked
in between. This is the user-approved satisfaction rule: each logged meal
satisfies the slot *nearest* its recorded minute, and nothing on disk is ever
rewritten. An exact-match rule would lock the user out for two meals they did
log, the moment they nudged breakfast by fifteen minutes.
"""
from __future__ import annotations
from datetime import UTC, datetime
from diet_guard._estimator import Nutrition
from diet_guard._gate import due_slots, gate_is_due
from diet_guard._meal_schedule import MealSchedule
from diet_guard._meal_schedule_store import record_schedule_change
from diet_guard._state import log_meal
from diet_guard._state_today import logged_slots_today
def _today_at(hour: int, minute: int = 0) -> datetime:
"""Return today's local date at ``hour:minute`` (the log is keyed by today)."""
now = datetime.now(tz=UTC).astimezone()
return now.replace(hour=hour, minute=minute, second=0, microsecond=0)
def _log_breakfast_and_snack_then_move_the_schedule() -> None:
"""07:00 and 10:00 logged under 07:00-19:00 x5, then moved to 07:15."""
record_schedule_change(MealSchedule(420, 1140, 5))
meal = Nutrition(300, 10, 40, 8, 200, "manual")
log_meal("oats", meal, slot=420)
log_meal("apple", meal, slot=600)
record_schedule_change(MealSchedule(435, 1140, 5))
class TestScheduleMoveKeepsLoggedMeals:
"""07:00/10:00 entries keep covering 07:15/10:15 after the edit."""
def test_the_moved_slots_are_derived_as_expected(self) -> None:
"""Precondition: the new schedule really moved both checkpoints."""
assert MealSchedule(435, 1140, 5).slots() == (435, 615, 795, 960, 1140)
def test_old_entries_satisfy_the_nearest_new_slots(self) -> None:
"""Nearest-slot snapping: 420 -> 435 and 600 -> 615."""
_log_breakfast_and_snack_then_move_the_schedule()
assert logged_slots_today() == {435, 615}
def test_nothing_is_due_at_eleven(self) -> None:
"""Both elapsed checkpoints are covered, so the gate stays down."""
_log_breakfast_and_snack_then_move_the_schedule()
assert not gate_is_due(_today_at(11))
def test_the_next_unlogged_slot_still_falls_due(self) -> None:
"""Snapping is not a free pass: 13:15 is due once it arrives."""
_log_breakfast_and_snack_then_move_the_schedule()
assert due_slots(_today_at(13, 15)) == (795,)
def test_the_moved_first_slot_opens_on_its_minute(self) -> None:
"""With nothing logged, 07:15 is due at 07:15 and not at 07:14."""
record_schedule_change(MealSchedule(435, 1140, 5))
assert not gate_is_due(_today_at(7, 14))
assert due_slots(_today_at(7, 15)) == (435,)

View File

@ -22,6 +22,7 @@ from unittest.mock import MagicMock
from diet_guard import (
_gatelock_calendar,
_gatelock_calendar_schedule,
_gatelock_calendar_ui,
_gatelock_ui,
_gatelock_widgetgroups,
@ -149,6 +150,7 @@ def test_fake_tk_actually_replaces_real_tkinter() -> None:
assert not wrong, f"fake_tk() left real tkinter in place for: {wrong}"
assert _gatelock_calendar.ttk is _FAKE_TTK
assert _gatelock_calendar_ui.ttk is _FAKE_TTK
assert _gatelock_calendar_schedule.ttk is _FAKE_TTK
# ...and is restored afterwards, so the fake cannot leak into other tests.
assert _gatelock_ui.tk is tk

View File

@ -69,8 +69,8 @@ class TestModuleHelpers:
def test_pending_slots_due(self) -> None:
"""When slots are due, those are returned verbatim."""
with patch.object(_gatelock, "due_slots", return_value=[12, 16]):
assert _pending_slots(demo_mode=False) == [12, 16]
with patch.object(_gatelock, "due_slots", return_value=[720, 960]):
assert _pending_slots(demo_mode=False) == [720, 960]
def test_pending_slots_demo_fallback(self) -> None:
"""Demo mode invents a representative slot when nothing is due."""

View File

@ -0,0 +1,99 @@
"""Tests for the schedule row's ``HH:MM`` spinboxes.
Covers :mod:`._gatelock_calendar_schedule`: the quarter-hour step and its
clamps, the ``<<Increment>>``/``<<Decrement>>`` bindings that replace ttk's own
spin logic, and the per-widget state toggle in :mod:`._gatelock_scheduleedit`.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from unittest.mock import patch
import pytest
from diet_guard._gatelock_calendar_schedule import LAST_RANGE, step_time
from diet_guard.tests._tk_fakes import _FakeTclError
if TYPE_CHECKING:
from collections.abc import Callable
from diet_guard._gatelock import MealGate
from diet_guard.tests._tk_fakes import FakeSpinbox
class TestStepTime:
@pytest.mark.parametrize(
("text", "direction", "expected"),
[
("07:15", 1, "07:30"),
("07:15", -1, "07:00"),
# Off-grid steps to the neighbouring mark, not by a flat 15.
("07:23", 1, "07:30"),
("07:23", -1, "07:15"),
("7", 1, "07:15"),
# Clamped to the first meal's range: 00:00..23:45.
("00:00", -1, "00:00"),
("23:45", 1, "23:45"),
("23:50", 1, "23:45"),
],
)
def test_steps_onto_the_grid(
self, text: str, direction: int, expected: str
) -> None:
assert step_time(text, direction) == expected
def test_the_last_meal_never_steps_below_00_15(self) -> None:
"""It must sit one grid step after the earliest possible first meal."""
assert step_time("00:15", -1, LAST_RANGE) == "00:15"
assert step_time("00:20", -1, LAST_RANGE) == "00:15"
assert step_time("23:45", 1, LAST_RANGE) == "23:45"
def test_half_typed_text_is_left_alone(self) -> None:
assert step_time("07:", 1) == "07:"
def _spin(gate: MealGate, which: str, event: str) -> object:
"""Fire one of a spinbox's step events, as ttk would on press/key/wheel."""
widget = getattr(gate._cal_widgets, f"schedule_{which}_entry")
spin = cast("FakeSpinbox", widget)
handler = cast("Callable[[object], object]", spin.bindings[event])
return handler(None)
class TestSpinEvents:
def test_steps_only_while_editing(self, gate: MealGate) -> None:
gate._cal_vars.schedule.first.set("08:00")
# Locked: the event is swallowed and the value is unchanged.
assert _spin(gate, "first", "<<Increment>>") == "break"
assert gate._cal_vars.schedule.first.get() == "08:00"
gate._on_edit_or_save_schedule()
assert _spin(gate, "first", "<<Increment>>") == "break"
assert gate._cal_vars.schedule.first.get() == "08:15"
_spin(gate, "first", "<<Decrement>>")
_spin(gate, "first", "<<Decrement>>")
assert gate._cal_vars.schedule.first.get() == "07:45"
def test_an_off_grid_value_steps_to_its_neighbour(self, gate: MealGate) -> None:
gate._on_edit_or_save_schedule()
gate._cal_vars.schedule.last.set("19:23")
_spin(gate, "last", "<<Increment>>")
assert gate._cal_vars.schedule.last.get() == "19:30"
def test_the_last_field_uses_its_own_clamp(self, gate: MealGate) -> None:
gate._on_edit_or_save_schedule()
gate._cal_vars.schedule.last.set("00:15")
_spin(gate, "last", "<<Decrement>>")
assert gate._cal_vars.schedule.last.get() == "00:15"
class TestStateToggle:
def test_one_dead_widget_does_not_skip_the_rest(self, gate: MealGate) -> None:
"""A vanished monitor's spinbox must not leave the others locked."""
widgets = gate._cal_widgets
dead = _FakeTclError("dead")
with patch.object(widgets.schedule_first_entry, "configure", side_effect=dead):
gate._set_schedule_entry_state("normal")
assert widgets.schedule_last_entry.configured["state"] == "normal"
assert widgets.schedule_count_entry.configured["state"] == "normal"

View File

@ -54,10 +54,10 @@ class TestDashboard:
gate._pending = []
gate._refresh_slot_header()
assert "All meals logged" in gate._vars.slot_header.get()
gate._pending = [8]
gate._pending = [480]
gate._refresh_slot_header()
assert "Log your" in gate._vars.slot_header.get()
gate._pending = [8, 12]
gate._pending = [480, 720]
gate._refresh_slot_header()
assert "remaining" in gate._vars.slot_header.get()
@ -74,14 +74,14 @@ class TestSlotWalk:
def test_slot_for_log_demo_is_none(self, gate: MealGate) -> None:
"""A demo gate tags logs with no real slot."""
gate._pending = [8]
gate._pending = [480]
assert gate._slot_for_log() is None
def test_slot_for_log_production_is_slot(self, gate: MealGate) -> None:
"""A production gate tags logs with the current slot."""
gate.demo_mode = False
gate._pending = [12]
assert gate._slot_for_log() == 12
gate._pending = [720]
assert gate._slot_for_log() == 720
def test_clear_inputs_resets_the_form(self, gate: MealGate) -> None:
"""Clearing between slots empties the description and the macros."""
@ -93,7 +93,7 @@ class TestSlotWalk:
def test_finish_slot_unlocks_on_last(self, gate: MealGate) -> None:
"""Finishing the final slot triggers unlock."""
gate._pending = [20]
gate._pending = [1200]
with patch.object(gate, "_unlock") as unlock:
gate._finish_slot("done")
unlock.assert_called_once()
@ -126,7 +126,7 @@ class TestFetchFromSync:
def test_pull_failure_keeps_lock(self, gate: MealGate) -> None:
"""A failed pull shows the reason and leaves pending slots intact."""
gate.demo_mode = False
gate._pending = [8, 12]
gate._pending = [480, 720]
with patch.object(
_gatelock_delivery,
"pull_peer_logs",
@ -134,52 +134,52 @@ class TestFetchFromSync:
):
gate._on_fetch_sync()
_drive_fetch(gate)
assert gate._pending == [8, 12]
assert gate._pending == [480, 720]
assert "still locked" in gate._vars.status.get()
def test_no_new_meals_keeps_all_slots(self, gate: MealGate) -> None:
"""A clean pull that satisfies nothing reports so and keeps the slots."""
gate.demo_mode = False
gate._pending = [8, 12]
gate._pending = [480, 720]
with (
patch.object(_gatelock_delivery, "pull_peer_logs", return_value=None),
patch.object(_gatelock_delivery, "due_slots", return_value=(8, 12)),
patch.object(_gatelock_delivery, "due_slots", return_value=(480, 720)),
):
gate._on_fetch_sync()
_drive_fetch(gate)
assert gate._pending == [8, 12]
assert gate._pending == [480, 720]
assert "No new meals" in gate._vars.status.get()
def test_partial_advances_to_next_slot(self, gate: MealGate) -> None:
"""One slot pulled in leaves the rest; the window advances (singular)."""
gate.demo_mode = False
gate._pending = [8, 12]
gate._pending = [480, 720]
with (
patch.object(_gatelock_delivery, "pull_peer_logs", return_value=None),
patch.object(_gatelock_delivery, "due_slots", return_value=(12,)),
patch.object(_gatelock_delivery, "due_slots", return_value=(720,)),
):
gate._on_fetch_sync()
_drive_fetch(gate)
assert gate._pending == [12]
assert gate._pending == [720]
assert "Pulled 1 meal " in gate._vars.status.get()
def test_partial_plural_wording(self, gate: MealGate) -> None:
"""Two slots pulled in uses the plural 'meals'."""
gate.demo_mode = False
gate._pending = [8, 12, 16]
gate._pending = [480, 720, 960]
with (
patch.object(_gatelock_delivery, "pull_peer_logs", return_value=None),
patch.object(_gatelock_delivery, "due_slots", return_value=(16,)),
patch.object(_gatelock_delivery, "due_slots", return_value=(960,)),
):
gate._on_fetch_sync()
_drive_fetch(gate)
assert gate._pending == [16]
assert gate._pending == [960]
assert "Pulled 2 meals" in gate._vars.status.get()
def test_all_satisfied_unlocks(self, gate: MealGate) -> None:
"""When the pull satisfies every pending slot, the gate unlocks."""
gate.demo_mode = False
gate._pending = [8, 12]
gate._pending = [480, 720]
with (
patch.object(_gatelock_delivery, "pull_peer_logs", return_value=None),
patch.object(_gatelock_delivery, "due_slots", return_value=()),

View File

@ -8,21 +8,15 @@ touched the first surface fails here and nowhere else.
from __future__ import annotations
from contextlib import ExitStack
import tkinter as tk
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock
import pytest
from diet_guard import _gatelock_calendar
from diet_guard._gatelock import MealGate
from diet_guard.tests.conftest import (
_FAKE_TK,
_FAKE_TTK,
_GATE_TK_MODULES,
TWO_OUTPUTS,
)
from diet_guard.tests._gate_fixtures import fake_tk
from diet_guard.tests.conftest import TWO_OUTPUTS
if TYPE_CHECKING:
from collections.abc import Iterator
@ -32,10 +26,10 @@ if TYPE_CHECKING:
def dual_gate(dual_output: None) -> Iterator[MealGate]:
"""A demo gate built across two live outputs."""
del dual_output
with ExitStack() as stack:
for module in _GATE_TK_MODULES:
stack.enter_context(patch.object(module, "tk", _FAKE_TK))
stack.enter_context(patch.object(_gatelock_calendar, "ttk", _FAKE_TTK))
# The shared patch set, never a hand-picked copy: a copy silently misses
# the next module that starts building widgets (the schedule row's ttk
# time fields were exactly that).
with fake_tk():
yield MealGate(demo_mode=True)

View File

@ -24,6 +24,7 @@ from diet_guard._gatelock_fillall import FILL_LABEL, FillAllFlow, FillHooks
from diet_guard._gatelock_kuchnia import DeliveryResult
from diet_guard._kuchnia_parse import Dish
from diet_guard._meal_schedule_store import current_schedule
from diet_guard._slot_wire import entry_slot_minute
from diet_guard._slots import day_slots
from diet_guard._state import log_meal, now_local
from diet_guard._state_today import today_entries
@ -89,10 +90,11 @@ def delivered(*dishes: Dish) -> DeliveryResult:
def logged() -> dict[int, list[str]]:
"""Today's on-disk log as slot -> descriptions."""
"""Today's on-disk log as recorded slot minute -> descriptions."""
by_slot: dict[int, list[str]] = {}
for entry in today_entries():
by_slot.setdefault(int(entry["slot"]), []).append(str(entry["desc"]))
slot = entry_slot_minute(entry) or 0
by_slot.setdefault(slot, []).append(str(entry["desc"]))
return by_slot
@ -104,7 +106,7 @@ def propose(h: Harness) -> None:
def test_default_schedule_precondition() -> None:
# Every expectation below assumes the redirected (default) schedule.
assert day_slots(current_schedule()) == (8, 12, 16, 20)
assert day_slots(current_schedule()) == (480, 720, 960, 1200)
class TestFirstClick:
@ -160,7 +162,7 @@ class TestFirstClick:
assert h.label.get() == FILL_LABEL
def test_every_slot_already_logged(self) -> None:
for slot in (8, 12, 16, 20):
for slot in (480, 720, 960, 1200):
log_meal(f"mine {slot}", _nutrition(), slot)
h = Harness()
with fetching(delivered(*FOUR)):
@ -169,7 +171,7 @@ class TestFirstClick:
assert h.label.get() == FILL_LABEL
def test_the_proposal_writes_nothing(self) -> None:
log_meal("my sandwich", _nutrition(), 12)
log_meal("my sandwich", _nutrition(), 720)
h = Harness()
with fetching(delivered(*FOUR)):
propose(h)
@ -178,23 +180,23 @@ class TestFirstClick:
"Will log 3 (1144 kcal): 08:00 Owsianka, 16:00 Obiad, "
"20:00 Kolacja — click Confirm."
)
assert logged() == {12: ["my sandwich"]}
assert logged() == {720: ["my sandwich"]}
h.on_logged.assert_not_called()
class TestConfirm:
def test_confirm_fills_only_the_empty_slots(self) -> None:
log_meal("my sandwich", _nutrition(), 12)
log_meal("my sandwich", _nutrition(), 720)
h = Harness()
with fetching(delivered(*FOUR)) as start:
propose(h)
h.flow.click()
assert start.call_count == 1 # the confirm did not refetch
assert logged() == {
8: ["Owsianka"],
12: ["my sandwich"],
16: ["Obiad"],
20: ["Kolacja"],
480: ["Owsianka"],
720: ["my sandwich"],
960: ["Obiad"],
1200: ["Kolacja"],
}
assert h.status == "Logged 3 catering dish(es)."
h.on_logged.assert_called_once_with()
@ -207,7 +209,7 @@ class TestConfirm:
with fetching(delivered(*five)):
propose(h)
h.flow.click()
assert logged()[8] == ["Owsianka", "Wrap"]
assert logged()[480] == ["Owsianka", "Wrap"]
assert h.status == "Logged 5 catering dish(es)."
def test_a_meal_typed_between_the_clicks_keeps_its_slot(self) -> None:
@ -215,16 +217,16 @@ class TestConfirm:
with fetching(delivered(*FOUR)):
propose(h)
assert h.label.get() == "✓ Confirm (4)"
log_meal("toast", _nutrition(), 8)
log_meal("toast", _nutrition(), 480)
h.flow.click()
assert logged()[8] == ["toast"]
assert logged()[480] == ["toast"]
assert h.status == "Logged 3 catering dish(es)."
def test_every_slot_taken_between_the_clicks(self) -> None:
h = Harness()
with fetching(delivered(*FOUR)):
propose(h)
for slot in (8, 12, 16, 20):
for slot in (480, 720, 960, 1200):
log_meal(f"mine {slot}", _nutrition(), slot)
h.flow.click()
assert h.status == "Every slot already has a meal — nothing to fill."
@ -240,10 +242,8 @@ class TestConfirm:
with patch.object(_gatelock_fillall, "now_local", return_value=tomorrow):
h.flow.click()
assert start.call_count == 2
assert start.call_args.args == (
_gatelock_fillall._refresh_delivery,
tomorrow.date(),
)
refetch = (_gatelock_fillall._refresh_delivery, tomorrow.date())
assert start.call_args.args == refetch
assert logged() == {}
h.on_logged.assert_not_called()
assert h.label.get() == FILL_LABEL

View File

@ -25,7 +25,7 @@ from diet_guard._gatelock_layout import build_layout
from diet_guard._gatelock_mealflow import _UNLOCK_DELAY_MS
from diet_guard._gatelock_ui import GateCallbacks, make_vars
from diet_guard._state import log_meal, now_local
from diet_guard._state_today import today_entries
from diet_guard._state_today import logged_slots_today
from diet_guard.tests._gate_fixtures import fake_tk
from diet_guard.tests.conftest import _nutrition
from diet_guard.tests.test_gatelock_fillall import (
@ -50,7 +50,7 @@ def _due_from_log(pending: list[int]) -> Callable[[], tuple[int, ...]]:
"""``due_slots`` as the log on disk says, so an unlock needs a real write."""
def due() -> tuple[int, ...]:
taken = {entry.get("slot") for entry in today_entries()}
taken = logged_slots_today()
return tuple(slot for slot in pending if slot not in taken)
return due
@ -86,29 +86,29 @@ class TestTheGateDrivesTheFlow:
def test_fill_and_confirm_unlocks_from_catering(self, gate: MealGate) -> None:
gate.demo_mode = False # read once, when the flow is first built
gate._pending = [8, 12]
gate._pending = [480, 720]
# Fill all also banks the dishes for one-at-a-time offering; the
# unlock line must not then call them "still delivered".
gate._delivery_pending = FOUR
due = _due_from_log([8, 12])
due = _due_from_log([480, 720])
with patch.object(_gatelock_delivery, "due_slots", side_effect=due):
_fill(gate, delivered(*FOUR))
status = gate._vars.status.get()
assert status == "Filled from catering — all meals logged, unlocking…"
assert gate._pending == []
gate.root.after.assert_called_with(_UNLOCK_DELAY_MS, gate.close)
assert sorted(logged()) == [8, 12, 16, 20]
assert sorted(logged()) == [480, 720, 960, 1200]
assert gate._vars.fill_label.get() == FILL_LABEL
def test_a_partial_fill_advances_instead_of_unlocking(self, gate: MealGate) -> None:
gate.demo_mode = False
gate._pending = [8, 12]
due = _due_from_log([8, 12])
gate._pending = [480, 720]
due = _due_from_log([480, 720])
# Two dishes spread onto 08:00 and 16:00: 12:00 is still owed.
two = (dish("Owsianka", 1), dish("Obiad", 2))
with patch.object(_gatelock_delivery, "due_slots", side_effect=due):
_fill(gate, delivered(*two))
assert gate._pending == [12]
assert gate._pending == [720]
assert "Pulled 1 meal " in gate._vars.status.get()
assert "unlocking" not in gate._vars.status.get()

View File

@ -194,14 +194,14 @@ class TestRecord:
def test_demo_logs_without_slot(self, gate: MealGate) -> None:
"""A demo record banks the food but tags no real slot."""
gate._pending = [8]
gate._pending = [480]
with patch.object(_gatelock_mealflow, "log_meal") as log:
gate._record("apple", _nutrition(95, 100))
assert log.call_args.args[2] is None
def test_last_slot_unlocks(self, gate: MealGate) -> None:
"""Recording the final pending slot triggers the unlock."""
gate._pending = [8]
gate._pending = [480]
with (
patch.object(_gatelock_mealflow, "log_meal"),
patch.object(_gatelock_mealflow, "remember_food"),
@ -212,13 +212,13 @@ class TestRecord:
def test_more_slots_continue(self, gate: MealGate) -> None:
"""With slots remaining, the form clears and prompts the next."""
gate._pending = [8, 12]
gate._pending = [480, 720]
with (
patch.object(_gatelock_mealflow, "log_meal"),
patch.object(_gatelock_mealflow, "remember_food"),
):
gate._record("apple", _nutrition(95, 100))
assert gate._pending == [12]
assert gate._pending == [720]
assert "next meal" in gate._vars.status.get()
def test_unlock_schedules_close(self, gate: MealGate) -> None:

View File

@ -1,15 +1,18 @@
"""Tests for the gate History tab's meal-schedule row.
Covers :mod:`._gatelock_scheduleedit`. The functional fake ``tk`` widgets and
the ``gate`` fixture live in ``conftest.py``, shared with the other gate
tests.
Covers :mod:`._gatelock_scheduleedit` and the row's widgets in
:mod:`._gatelock_calendar_schedule`. The functional fake ``tk``/``ttk``
widgets and the ``gate`` fixture live in ``conftest.py``, shared with the
other gate tests.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from diet_guard._gatelock_scheduleedit import schedule_summary
import pytest
from diet_guard._gatelock_scheduleedit import schedule_problem, schedule_summary
from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule
from diet_guard._meal_schedule_store import current_schedule, record_schedule_change
@ -18,21 +21,30 @@ if TYPE_CHECKING:
def _type(gate: MealGate, first: str, last: str, count: str) -> None:
"""Fill the three schedule entries as the user would."""
"""Fill the three schedule fields as the user would."""
gate._cal_vars.schedule.first.set(first)
gate._cal_vars.schedule.last.set(last)
gate._cal_vars.schedule.count.set(count)
def _status(gate: MealGate) -> str:
return gate._cal_vars.schedule.status.get()
class TestScheduleSummary:
"""The derived-times label."""
def test_lists_every_checkpoint(self) -> None:
"""The label spells out the hours the schedule derives."""
assert schedule_summary(MealSchedule(8, 20, 5)) == (
"""The label spells out the times the schedule derives."""
assert schedule_summary(MealSchedule(480, 1200, 5)) == (
"08:00 11:00 14:00 17:00 20:00"
)
def test_an_off_hour_schedule_shows_its_minutes(self) -> None:
assert schedule_summary(MealSchedule(435, 1140, 5)) == (
"07:15 10:15 13:15 16:00 19:00"
)
class TestEditToggle:
"""The Edit/Save button's two states."""
@ -47,71 +59,95 @@ class TestEditToggle:
def test_second_click_persists_and_relocks(self, gate: MealGate) -> None:
"""Clicking Save validates, writes, and returns to read-only."""
gate._on_edit_or_save_schedule()
_type(gate, "8", "20", "5")
_type(gate, "07:15", "19:00", "5")
gate._on_edit_or_save_schedule()
assert not gate._cal_editing_schedule
assert current_schedule() == MealSchedule(8, 20, 5)
assert gate._cal_vars.schedule.status.get() == "Saved."
assert current_schedule() == MealSchedule(435, 1140, 5)
assert _status(gate) == "Saved."
assert gate._cal_vars.schedule.times.get().startswith("07:15 10:15")
def test_a_bare_hour_is_still_accepted(self, gate: MealGate) -> None:
"""Typing ``8`` means 08:00, as it did before minutes existed."""
_type(gate, "8", "20", "5")
assert gate._save_schedule_entry()
assert current_schedule() == MealSchedule(480, 1200, 5)
assert gate._cal_vars.schedule.first.get() == "08:00"
def test_a_failed_save_leaves_editing_open(self, gate: MealGate) -> None:
"""A bad value can be corrected rather than silently discarded."""
gate._on_edit_or_save_schedule()
_type(gate, "20", "8", "4")
_type(gate, "20:00", "08:00", "4")
gate._on_edit_or_save_schedule()
assert gate._cal_editing_schedule
assert current_schedule() == DEFAULT_SCHEDULE
def test_the_spinboxes_lock_as_disabled_not_readonly(self, gate: MealGate) -> None:
"""A ``readonly`` ttk spinbox still spins, editing a locked row."""
widgets = gate._cal_widgets
gate._on_edit_or_save_schedule()
assert widgets.schedule_first_entry.configured["state"] == "normal"
assert widgets.schedule_count_entry.configured["state"] == "normal"
_type(gate, "07:15", "19:00", "5")
gate._on_edit_or_save_schedule()
assert widgets.schedule_first_entry.configured["state"] == "disabled"
assert widgets.schedule_last_entry.configured["state"] == "disabled"
assert widgets.schedule_count_entry.configured["state"] == "readonly"
class TestValidation:
"""Rejected input, with the reason shown rather than silently clamped."""
def test_rejects_non_numeric(self, gate: MealGate) -> None:
"""Letters in an hour field are refused, not coerced."""
_type(gate, "eight", "20", "4")
@pytest.mark.parametrize("first", ["eight", "7:5", "24:00", "07:60", ""])
def test_rejects_a_time_that_is_not_hhmm(self, gate: MealGate, first: str) -> None:
_type(gate, first, "20:00", "4")
assert not gate._save_schedule_entry()
assert "whole hours" in gate._cal_vars.schedule.status.get()
assert "HH:MM" in _status(gate)
def test_rejects_a_backwards_window(self, gate: MealGate) -> None:
"""The last meal must come after the first."""
_type(gate, "20", "8", "4")
def test_rejects_a_non_numeric_count(self, gate: MealGate) -> None:
_type(gate, "08:00", "20:00", "five")
assert not gate._save_schedule_entry()
assert "before the last" in gate._cal_vars.schedule.status.get()
assert "meals per day as a number" in _status(gate)
def test_rejects_an_out_of_range_hour(self, gate: MealGate) -> None:
"""Hours outside 0-23 are refused."""
_type(gate, "8", "25", "4")
@pytest.mark.parametrize(
("first", "last", "count", "reason"),
[
("20:00", "08:00", "4", "at least 15 min after"),
("08:00", "08:14", "2", "at least 15 min after"),
("08:00", "20:00", "1", "Meals per day must be 2-6."),
("08:00", "20:00", "9", "Meals per day must be 2-6."),
("08:00", "08:45", "5", "Too many meals"),
],
)
def test_rejects_what_normalize_would_silently_change(
self, gate: MealGate, first: str, last: str, count: str, reason: str
) -> None:
_type(gate, first, last, count)
assert not gate._save_schedule_entry()
assert "0-23" in gate._cal_vars.schedule.status.get()
assert reason in _status(gate)
assert current_schedule() == DEFAULT_SCHEDULE
def test_rejects_too_few_meals(self, gate: MealGate) -> None:
"""One meal a day is below the supported range."""
_type(gate, "8", "20", "1")
def test_the_narrowest_legal_window_is_accepted(self, gate: MealGate) -> None:
"""15 min holds two meals; 45 min holds four (one per quarter hour)."""
_type(gate, "08:00", "08:45", "4")
assert not gate._save_schedule_entry()
assert "Meals per day" in gate._cal_vars.schedule.status.get()
assert gate._save_schedule_entry()
assert current_schedule().slots() == (480, 495, 510, 525)
def test_rejects_too_many_meals(self, gate: MealGate) -> None:
"""More than the cap is refused."""
_type(gate, "8", "20", "9")
assert not gate._save_schedule_entry()
assert "Meals per day" in gate._cal_vars.schedule.status.get()
def test_rejects_more_meals_than_the_window_holds(self, gate: MealGate) -> None:
"""A narrow window cannot hold six distinct whole-hour checkpoints.
Without this the derivation would round two meals onto the same hour,
and a duplicate slot silently drops a checkpoint.
"""
_type(gate, "8", "11", "6")
assert not gate._save_schedule_entry()
assert "Too many meals" in gate._cal_vars.schedule.status.get()
def test_an_accepted_schedule_is_stored_unchanged(self) -> None:
"""No rule here is looser than ``normalized()``: what passes is kept."""
for first in range(0, 1440, 37):
for last in range(first + 15, 1440, 53):
for count in range(2, 7):
schedule = MealSchedule(first, last, count)
if schedule_problem(schedule) is None:
assert schedule.normalized() == schedule
class TestDisplay:
@ -119,27 +155,27 @@ class TestDisplay:
def test_shows_the_stored_schedule(self, gate: MealGate) -> None:
"""The fields and the derived-times label reflect what is stored."""
gate._show_schedule(MealSchedule(7, 21, 3))
gate._show_schedule(MealSchedule(435, 1260, 3))
assert gate._cal_vars.schedule.first.get() == "7"
assert gate._cal_vars.schedule.last.get() == "21"
assert gate._cal_vars.schedule.first.get() == "07:15"
assert gate._cal_vars.schedule.last.get() == "21:00"
assert gate._cal_vars.schedule.count.get() == "3"
assert gate._cal_vars.schedule.times.get() == "07:00 14:00 21:00"
assert gate._cal_vars.schedule.times.get() == "07:15 14:15 21:00"
def test_a_refresh_does_not_clobber_an_open_edit(self, gate: MealGate) -> None:
"""Typing survives a calendar refresh landing mid-edit."""
gate._on_edit_or_save_schedule()
_type(gate, "6", "22", "6")
_type(gate, "06:00", "22:00", "6")
gate._refresh_calendar()
assert gate._cal_vars.schedule.first.get() == "6"
assert gate._cal_vars.schedule.first.get() == "06:00"
def test_a_refresh_shows_the_stored_schedule_when_idle(
self, gate: MealGate
) -> None:
"""Outside an edit the row tracks whatever is stored."""
record_schedule_change(MealSchedule(9, 19, 3))
record_schedule_change(MealSchedule(540, 1140, 3))
gate._refresh_calendar()
assert gate._cal_vars.schedule.first.get() == "9"
assert gate._cal_vars.schedule.first.get() == "09:00"
assert gate._cal_vars.schedule.times.get() == "09:00 14:00 19:00"

View File

@ -7,7 +7,7 @@ through ``sys.modules`` instead of binding it at import time.
from __future__ import annotations
import datetime
import datetime as dt
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
@ -28,7 +28,7 @@ from diet_guard.tests._kuchnia_fakes import (
if TYPE_CHECKING:
from pathlib import Path
DAY = datetime.date(2026, 8, 22)
DAY = dt.date(2026, 8, 22)
@pytest.fixture

View File

@ -40,33 +40,40 @@ def _eat(desc: str, slot: int) -> None:
class TestFillPlan:
def test_an_empty_day_fills_every_slot(self) -> None:
plan = [_slotted("A", 8), _slotted("B", 12), _slotted("C", 20)]
plan = [_slotted("A", 480), _slotted("B", 720), _slotted("C", 1200)]
assert fill_plan(plan) == plan
def test_a_slot_with_a_meal_keeps_it(self) -> None:
_eat("apple", 12)
plan = fill_plan([_slotted("A", 8), _slotted("B", 12), _slotted("C", 20)])
assert [item.slot for item in plan] == [8, 20]
_eat("apple", 720)
plan = fill_plan([_slotted("A", 480), _slotted("B", 720), _slotted("C", 1200)])
assert [item.slot for item in plan] == [480, 1200]
def test_two_dishes_sharing_an_empty_slot_both_land(self) -> None:
# 5 dishes on 4 slots double up the first; occupancy is read once,
# before the batch, so the second dish is not refused by the first.
plan = fill_plan([_slotted("A", 8), _slotted("B", 8)])
plan = fill_plan([_slotted("A", 480), _slotted("B", 480)])
assert log_dishes(plan) == ["A", "B"]
def test_a_full_day_fills_nothing(self) -> None:
for slot in (8, 12):
for slot in (480, 720):
_eat("apple", slot)
assert fill_plan([_slotted("A", 8), _slotted("B", 12)]) == []
assert fill_plan([_slotted("A", 480), _slotted("B", 720)]) == []
def test_a_meal_near_a_slot_occupies_it(self) -> None:
# Logged at 08:15 (say, under an older schedule): it snaps to 08:00,
# the same rule the gate uses, so catering must not double that slot.
_eat("apple", 495)
plan = fill_plan([_slotted("A", 480), _slotted("B", 720)])
assert [item.slot for item in plan] == [720]
class TestCliFill:
def test_log_skips_a_taken_slot(self) -> None:
# Two dishes on the default four slots spread to 08:00 and 16:00.
_eat("apple", 8)
_eat("apple", 480)
dishes = [
replace(_slotted("Owsianka", 8).dish, priority=1),
replace(_slotted("Kaszotto", 16).dish, priority=2),
replace(_slotted("Owsianka", 480).dish, priority=1),
replace(_slotted("Kaszotto", 960).dish, priority=2),
]
lines: list[str] = []
with patch.object(

View File

@ -15,7 +15,7 @@ is testable with no thread at all.
from __future__ import annotations
import datetime
import datetime as dt
import queue
from types import SimpleNamespace
from typing import TYPE_CHECKING
@ -38,7 +38,7 @@ if TYPE_CHECKING:
from diet_guard._estimator import Nutrition
DAY = datetime.date(2026, 8, 22)
DAY = dt.date(2026, 8, 22)
def _dish(name: str = "Kaszotto", priority: int = 1) -> Dish:
@ -68,7 +68,7 @@ class TestWorker:
def test_a_raising_call_still_feeds_the_queue(self) -> None:
# Without the finally, the poll waits forever with the button disabled
# and the user cannot get out from behind the lock.
def boom(_day: datetime.date) -> tuple[Sequence[Dish], str | None]:
def boom(_day: dt.date) -> tuple[Sequence[Dish], str | None]:
msg = "kaboom"
raise RuntimeError(msg)

View File

@ -9,7 +9,7 @@ that happens, so these assert on **call count** instead.
from __future__ import annotations
import datetime
import datetime as dt
from unittest.mock import patch
from diet_guard import _kuchnia_config, _kuchnia_import
@ -21,7 +21,7 @@ from diet_guard._kuchnia_parse import Dish
from diet_guard._kuchnia_spread import SlottedDish
from diet_guard._state_today import today_entries, today_total_kcal
DAY = datetime.date(2026, 8, 22)
DAY = dt.date(2026, 8, 22)
def _dish(name: str = "Kaszotto", kcal: float = 391.0, priority: int = 1) -> Dish:
@ -150,7 +150,7 @@ class TestRefreshOnce:
return_value=([_dish()], None),
) as refresh:
_kuchnia_import.refresh_delivery_once(DAY)
_kuchnia_import.refresh_delivery_once(DAY + datetime.timedelta(days=1))
_kuchnia_import.refresh_delivery_once(DAY + dt.timedelta(days=1))
assert refresh.call_count == 2
def test_an_outage_does_not_suppress_the_retry(self) -> None:
@ -194,8 +194,8 @@ class TestRefreshOnce:
class TestLogDishes:
def test_logs_each_dish_into_its_slot(self) -> None:
chosen = [
SlottedDish(dish=_dish("A", kcal=100.0), slot=8),
SlottedDish(dish=_dish("B", kcal=200.0), slot=12),
SlottedDish(dish=_dish("A", kcal=100.0), slot=480),
SlottedDish(dish=_dish("B", kcal=200.0), slot=720),
]
assert log_dishes(chosen) == ["A", "B"]
entries = today_entries()
@ -203,33 +203,41 @@ class TestLogDishes:
assert today_total_kcal() == 300.0
def test_records_the_provenance(self) -> None:
log_dishes([SlottedDish(dish=_dish("A"), slot=8)])
log_dishes([SlottedDish(dish=_dish("A"), slot=480)])
(entry,) = today_entries()
assert entry["source"] == "kuchnia wikinga"
def test_a_second_run_logs_nothing(self) -> None:
chosen = [SlottedDish(dish=_dish("A"), slot=8)]
chosen = [SlottedDish(dish=_dish("A"), slot=480)]
log_dishes(chosen)
assert log_dishes(chosen) == []
assert len(today_entries()) == 1
def test_the_same_dish_in_a_different_slot_is_a_separate_meal(self) -> None:
log_dishes([SlottedDish(dish=_dish("A"), slot=8)])
assert log_dishes([SlottedDish(dish=_dish("A"), slot=12)]) == ["A"]
log_dishes([SlottedDish(dish=_dish("A"), slot=480)])
assert log_dishes([SlottedDish(dish=_dish("A"), slot=720)]) == ["A"]
assert len(today_entries()) == 2
def test_duplicates_within_one_batch_land_once(self) -> None:
# today_entries() is read once, before the loop; without reflecting the
# writes locally both copies would be logged.
chosen = [
SlottedDish(dish=_dish("A"), slot=8),
SlottedDish(dish=_dish("A"), slot=8),
SlottedDish(dish=_dish("A"), slot=480),
SlottedDish(dish=_dish("A"), slot=480),
]
assert log_dishes(chosen) == ["A"]
def test_matching_ignores_case_and_padding(self) -> None:
log_dishes([SlottedDish(dish=_dish("Kaszotto"), slot=8)])
assert log_dishes([SlottedDish(dish=_dish(" kaszotto "), slot=8)]) == []
log_dishes([SlottedDish(dish=_dish("Kaszotto"), slot=480)])
assert log_dishes([SlottedDish(dish=_dish(" kaszotto "), slot=480)]) == []
def test_dedup_compares_the_recorded_minute_not_the_snapped_slot(self) -> None:
# Parity with the app: dedup is (name, recorded minute). An 08:15 copy
# is a different key from 08:00 even though both snap to 08:00 --
# the fill flow is kept from doubling it by fill_plan's occupancy.
log_dishes([SlottedDish(dish=_dish("A"), slot=495)])
assert log_dishes([SlottedDish(dish=_dish("A"), slot=495)]) == []
assert log_dishes([SlottedDish(dish=_dish("A"), slot=480)]) == ["A"]
def test_logging_nothing_is_not_an_error(self) -> None:
assert log_dishes([]) == []

View File

@ -10,7 +10,7 @@ The endpoint shape here is not the obvious one: ``.../deliveries/{id}/details``
from __future__ import annotations
import datetime
import datetime as dt
from unittest.mock import patch
import pytest
@ -28,7 +28,7 @@ from diet_guard.tests._kuchnia_fakes import (
write_credentials,
)
DAY = datetime.date(2026, 8, 22)
DAY = dt.date(2026, 8, 22)
@pytest.fixture

View File

@ -32,6 +32,7 @@ from diet_guard import _kuchnia_log
from diet_guard._kuchnia_import import dish_to_record
from diet_guard._kuchnia_parse import Dish, parse_menu
from diet_guard._kuchnia_spread import SlottedDish, assign_slots
from diet_guard._slot_wire import slot_fields
FIXTURE = Path(__file__).resolve().parents[2] / "tests/fixtures/kuchnia_day.json"
@ -57,7 +58,7 @@ def _dishes(fixture: dict[str, Any]) -> list[Dish]:
def _slots_for(key: str) -> tuple[int, ...]:
"""Turn a fixture slot key such as ``"8,12,16,20"`` into slot hours."""
"""Turn a fixture slot key such as ``"480,720,960,1200"`` into slot minutes."""
return tuple(int(part) for part in key.split(","))
@ -107,8 +108,8 @@ def test_slot_assignment_matches(fixture: dict[str, Any], dishes: list[Dish]) ->
"""``i * S // N`` lands each dish on the slot the Dart side also picks."""
for key, expected in fixture["expected"]["slots"].items():
subject = dishes[:3] if key.startswith("first_three_") else dishes
hours = _slots_for(key.removeprefix("first_three_"))
actual = [item.slot for item in assign_slots(subject, hours)]
minutes = _slots_for(key.removeprefix("first_three_"))
actual = [item.slot for item in assign_slots(subject, minutes)]
assert actual == expected, f"slot assignment diverged for {key}"
@ -119,7 +120,7 @@ def test_slot_order_matches(fixture: dict[str, Any], dishes: list[Dish]) -> None
dishes sharing both priority and name are the case that forces both
comparators to be total.
"""
ordered = assign_slots(dishes, (8, 12, 16, 20))
ordered = assign_slots(dishes, (480, 720, 960, 1200))
assert [item.dish.name for item in ordered] == fixture["expected"]["slot_order"]
@ -151,6 +152,12 @@ def test_bank_record_numbers_are_floats(dishes: list[Dish]) -> None:
assert not isinstance(record["count"], bool)
def _as_entry(row: dict[str, Any]) -> dict[str, Any]:
"""Turn a fixture row's resolved ``slot`` minute into on-disk entry fields."""
fields = {key: value for key, value in row.items() if key != "slot"}
return {**fields, **slot_fields(row["slot"])}
def _spread(
dishes: list[Dish], fill: dict[str, Any], case: dict[str, Any]
) -> list[SlottedDish]:
@ -168,7 +175,10 @@ def test_fill_plan_matches(
fill = fixture["expected"]["fill"]
assert fill["fill_plan"], "fixture carries no fill_plan cases"
for key, case in fill["fill_plan"].items():
today = [{"slot": slot} for slot in case["occupied"]]
# ``occupied`` holds RESOLVED slot minutes, not on-disk fields: seed
# them through the writer's encoding, never as a raw ``{"slot": m}``
# (which the reader would take for an hour, i.e. ``m * 60``).
today = [slot_fields(slot) for slot in case["occupied"]]
monkeypatch.setattr(_kuchnia_log, "today_entries", lambda t=today: t)
kept = _kuchnia_log.fill_plan(_spread(dishes, fill, case))
actual = [[item.dish.name, item.slot] for item in kept]
@ -185,7 +195,8 @@ def test_log_dishes_matches(
fill = fixture["expected"]["fill"]
for key, case in fill["log_dishes"].items():
recorder = MagicMock()
monkeypatch.setattr(_kuchnia_log, "today_entries", lambda c=case: c["today"])
today = [_as_entry(row) for row in case["today"]]
monkeypatch.setattr(_kuchnia_log, "today_entries", lambda t=today: t)
monkeypatch.setattr(_kuchnia_log, "log_meal", recorder)
_kuchnia_log.log_dishes(_spread(dishes, fill, case))
written = [[call.args[0], call.args[2]] for call in recorder.call_args_list]
@ -201,5 +212,5 @@ def test_twin_case_is_not_vacuous(fixture: dict[str, Any], dishes: list[Dish]) -
fill = fixture["expected"]["fill"]
case = fill["log_dishes"]["twins_share_16"]
spread = [(item.dish.name, item.slot) for item in _spread(dishes, fill, case)]
assert spread.count(("Twin dish", 16)) == 2
assert case["expected"].count(["Twin dish", 16]) == 1
assert spread.count(("Twin dish", 960)) == 2
assert case["expected"].count(["Twin dish", 960]) == 1

View File

@ -137,18 +137,20 @@ def _dish(priority: int, name: str = "d") -> Dish:
class TestAssignSlots:
def test_follows_the_providers_priority_not_payload_order(self) -> None:
dishes = [_dish(3), _dish(1), _dish(2)]
assigned = assign_slots(dishes, (8, 12, 16))
assigned = assign_slots(dishes, (480, 720, 960))
assert [item.dish.name for item in assigned] == ["d1", "d2", "d3"]
assert [item.slot for item in assigned] == [8, 12, 16]
assert [item.slot for item in assigned] == [480, 720, 960]
def test_five_dishes_over_four_slots_double_up_the_earliest(self) -> None:
assigned = assign_slots([_dish(i) for i in range(1, 6)], (8, 12, 16, 20))
assert [item.slot for item in assigned] == [8, 8, 12, 16, 20]
assigned = assign_slots([_dish(i) for i in range(1, 6)], (480, 720, 960, 1200))
assert [item.slot for item in assigned] == [480, 480, 720, 960, 1200]
def test_five_dishes_over_five_slots_map_one_to_one(self) -> None:
# kuhy's real schedule; the catering plan is also five meals.
assigned = assign_slots([_dish(i) for i in range(1, 6)], (8, 11, 14, 17, 20))
assert [item.slot for item in assigned] == [8, 11, 14, 17, 20]
assigned = assign_slots(
[_dish(i) for i in range(1, 6)], (480, 660, 840, 1020, 1200)
)
assert [item.slot for item in assigned] == [480, 660, 840, 1020, 1200]
@pytest.mark.parametrize("count", range(1, 9))
@pytest.mark.parametrize("span", range(2, 7))
@ -170,8 +172,8 @@ class TestAssignSlots:
# Two dishes sharing a priority must not reshuffle between runs: an
# unstable order looks like a change and re-stamps every bank record.
dishes = [_dish(1, "b"), _dish(1, "a")]
first = [item.dish.name for item in assign_slots(dishes, (8, 12))]
second = [item.dish.name for item in assign_slots(dishes[::-1], (8, 12))]
first = [item.dish.name for item in assign_slots(dishes, (480, 720))]
second = [item.dish.name for item in assign_slots(dishes[::-1], (480, 720))]
assert first == second
@pytest.mark.parametrize(

Some files were not shown because too many files have changed in this diff Show More