Compare commits

..

No commits in common. "f2606fe0ca6a472f1c0362d1666bbbfe4869882f" and "5cd89a4e99de79b46a1d3e8748f1da65dfcc3973" have entirely different histories.

126 changed files with 1611 additions and 8863 deletions

2
.fvmrc
View File

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

View File

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

View File

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

View File

@ -2,8 +2,6 @@
library; library;
import 'package:diet_guard_app/models/meal_component.dart'; 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. /// One logged meal, as stored in `food_log.json` under its date key.
/// ///
@ -22,7 +20,7 @@ class FoodEntry {
required this.fatG, required this.fatG,
required this.source, required this.source,
this.id, this.id,
this.slotMinute, this.slot,
this.hmac, this.hmac,
this.components, this.components,
this.deleted = false, this.deleted = false,
@ -42,7 +40,7 @@ class FoodEntry {
carbsG: (json['carbs_g'] as num?)?.toDouble() ?? 0, carbsG: (json['carbs_g'] as num?)?.toDouble() ?? 0,
fatG: (json['fat_g'] as num?)?.toDouble() ?? 0, fatG: (json['fat_g'] as num?)?.toDouble() ?? 0,
source: json['source'] as String? ?? 'manual', source: json['source'] as String? ?? 'manual',
slotMinute: entrySlotMinute(json), slot: json['slot'] as int?,
hmac: json['hmac'] as String?, hmac: json['hmac'] as String?,
components: (json['components'] as List?) components: (json['components'] as List?)
?.cast<Map<String, dynamic>>() ?.cast<Map<String, dynamic>>()
@ -81,26 +79,16 @@ class FoodEntry {
/// Provenance label (e.g. `"manual"`, `"food bank"`, `"meal"`). /// Provenance label (e.g. `"manual"`, `"food bank"`, `"meal"`).
final String source; final String source;
/// The meal-slot minute of day this entry was logged against (480 for /// The meal-slot hour this entry satisfies (8/12/16/20), or null for a
/// 08:00, 435 for 07:15), or null for a snack that satisfies no slot. /// snack that counts toward calories but 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 /// Nothing writes null any more -- the "Snack" chip was removed on
/// 2026-08-14 and every remaining writer resolves a concrete slot through /// 2026-08-14 and every remaining writer resolves a concrete hour through
/// `slotForLog`/`slot_for_log` -- but entries already on disk and arriving /// `slotForLog`/`slot_for_log` -- but entries already on disk and arriving
/// over sync still carry no `slot` key, so the null case and every /// 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 /// `slot != null` filter built on it are load-bearing. Dropping them would
/// make those historical entries retroactively satisfy meal slots. /// make those historical entries retroactively satisfy meal slots.
final int? slotMinute; final int? slot;
/// HMAC signature, present on entries that have passed through the PC's /// HMAC signature, present on entries that have passed through the PC's
/// signing step. Never computed on the phone -- it never holds the key. /// signing step. Never computed on the phone -- it never holds the key.
@ -134,7 +122,7 @@ class FoodEntry {
'carbs_g': carbsG, 'carbs_g': carbsG,
'fat_g': fatG, 'fat_g': fatG,
'source': source, 'source': source,
..._slotJson(slotMinute), if (slot != null) 'slot': slot,
if (components != null) if (components != null)
'components': components!.map((c) => c.toJson()).toList(), 'components': components!.map((c) => c.toJson()).toList(),
if (deleted) 'deleted': true, if (deleted) 'deleted': true,
@ -151,26 +139,9 @@ class FoodEntry {
carbsG: carbsG, carbsG: carbsG,
fatG: fatG, fatG: fatG,
source: source, source: source,
slotMinute: slotMinute, slot: slot,
hmac: hmac, hmac: hmac,
components: components, components: components,
deleted: true, 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,15 +1,9 @@
/// The user's eating window and meal count, and the slot minutes they imply. /// The user's eating window and meal count, and the slot hours they imply.
/// ///
/// A schedule is three numbers -- the first meal's minute of day, the last /// A schedule is three numbers -- the first meal hour, the last meal hour, and
/// meal's minute of day, and how many meals fall between them inclusive -- /// how many meals fall between them inclusive -- from which the intermediate
/// from which the intermediate checkpoints are derived by even division and /// checkpoints are derived by even division. `MealSchedule(8, 20, 5)` yields
/// rounded to the 15-minute grid. `MealSchedule(firstMinute: 480, /// `[8, 11, 14, 17, 20]`.
/// 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 /// This file is pure: no clock, no storage, no settings lookup. Persistence
/// lives in `services/meal_schedule_service.dart`, and the slot arithmetic /// lives in `services/meal_schedule_service.dart`, and the slot arithmetic
@ -18,17 +12,13 @@
/// KEEP IN SYNC WITH `diet_guard/_meal_schedule.py`. The two must agree on /// 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 /// 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 /// nags for checkpoints the other never offers -- and a slot that can never be
/// satisfied is a permanent lock. `tests/fixtures/meal_schedule_vectors.json` /// satisfied is a permanent lock. Two rules make that agreement checkable:
/// is read by both test suites; three rules make that agreement checkable:
/// ///
/// * **Integer arithmetic only.** No doubles and no `round()` anywhere in the /// * **Integer arithmetic only.** No doubles and no `round()` anywhere in the
/// derivation. Dart's `round()` is half-away-from-zero (`2.5.round() == 3`) /// 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 /// while Python's is banker's rounding (`round(2.5) == 2`), so any
/// floating-point path is a latent cross-language split brain. `~/` here, /// floating-point path is a latent cross-language split brain. `~/` here,
/// `//` there. /// `//` 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 /// * **Clamp, don't reject.** Every out-of-range input is normalised to the
/// nearest legal schedule rather than throwing, so the two languages cannot /// nearest legal schedule rather than throwing, so the two languages cannot
/// disagree about which inputs are errors. /// disagree about which inputs are errors.
@ -46,16 +36,11 @@ const int kMinMealCount = 2;
/// `test/widgets/slot_selector_row_test.dart`. /// `test/widgets/slot_selector_row_test.dart`.
const int kMaxMealCount = 6; const int kMaxMealCount = 6;
/// Minutes in a day; a minute of day is `0..kMinutesPerDay - 1`. /// Earliest hour a meal may be scheduled at.
const int kMinutesPerDay = 1440; const int kFirstHour = 0;
/// Minimum spacing between two checkpoints, and the grid interior checkpoints /// Latest hour a meal may be scheduled at.
/// are rounded onto. const int kLastHour = 23;
///
/// 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. /// Grace period after the final checkpoint, before the gate stops firing.
/// ///
@ -63,9 +48,9 @@ const int kSlotGridMinutes = 15;
/// have to log a late dinner, which has nothing to do with how many meals you /// 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 /// eat. Tying it to the spacing would stretch the lockout window to midnight
/// at four meals, contradicting the "don't trap me overnight" intent. /// at four meals, contradicting the "don't trap me overnight" intent.
const int kEnforcementTailMinutes = 120; const int kEnforcementTailHours = 2;
const int _lastMinute = kMinutesPerDay - 1; const int _hoursPerDay = 24;
int _clamp(int value, int low, int high) => int _clamp(int value, int low, int high) =>
value < low ? low : (value > high ? high : value); value < low ? low : (value > high ? high : value);
@ -75,142 +60,95 @@ int _clamp(int value, int low, int high) =>
class MealSchedule { class MealSchedule {
/// Creates a [MealSchedule]. /// Creates a [MealSchedule].
const MealSchedule({ const MealSchedule({
required this.firstMinute, required this.first,
required this.lastMinute, required this.last,
required this.count, required this.count,
}); });
/// Minute of day of the first meal, 0-1424. /// Hour of the first meal, 0-23.
final int firstMinute; final int first;
/// Minute of day of the last meal, at least one grid step (15 minutes) after /// Hour of the last meal, strictly after [first].
/// [firstMinute] and at most 1439. final int last;
final int lastMinute;
/// Total meals including both endpoints. /// Total meals including both endpoints.
final int count; final int count;
/// Returns an equivalent schedule guaranteed to satisfy the invariants. /// Returns an equivalent schedule guaranteed to satisfy the invariants.
/// ///
/// Ordering matters: [firstMinute] is clamped into the day leaving room for /// Ordering matters: [first] is clamped into the day, then [last] is clamped
/// one grid step, then [lastMinute] is clamped to at least one grid step /// to leave at least one hour of window, then [count] is clamped to the
/// after it, then [count] is clamped to how many grid-spaced checkpoints the /// window's width. That last clamp is the load-bearing one -- see [slots].
/// window holds. That last clamp is the load-bearing one -- see [slots].
MealSchedule normalized() { MealSchedule normalized() {
final first = _clamp(firstMinute, 0, _lastMinute - kSlotGridMinutes); final normFirst = _clamp(first, kFirstHour, kLastHour - 1);
final last = _clamp(lastMinute, first + kSlotGridMinutes, _lastMinute); final normLast = _clamp(last, normFirst + 1, kLastHour);
// A window of W minutes holds at most W ~/ 15 + 1 checkpoints spaced a // A window of N hours holds at most N+1 whole-hour checkpoints; asking for
// grid step apart; asking for more would round two onto one mark. // more would repeat an hour (see slots()).
final capacity = (last - first) ~/ kSlotGridMinutes + 1;
final normCount = _clamp( final normCount = _clamp(
count, count,
kMinMealCount, kMinMealCount,
kMaxMealCount < capacity ? kMaxMealCount : capacity, kMaxMealCount < normLast - normFirst + 1
? kMaxMealCount
: normLast - normFirst + 1,
); );
return MealSchedule(firstMinute: first, lastMinute: last, count: normCount); return MealSchedule(first: normFirst, last: normLast, count: normCount);
} }
/// Returns the meal-slot minutes, ascending, with both endpoints exact. /// Returns the meal-slot hours, ascending, with both endpoints exact.
/// ///
/// With `span = last - first` and `d = count - 1`, interior slot *i* is /// Meals are spread evenly across the window and rounded to whole hours by
/// `raw = first + (i*span + d ~/ 2) ~/ d` (even division, the `d ~/ 2` term /// integer arithmetic: slot *i* is `first + (i*span + d ~/ 2) ~/ d` where
/// a round-half-up bias that keeps it free of floating point), then snapped /// `span = last - first` and `d = count - 1`. The `d ~/ 2` term is a
/// to the nearest absolute quarter hour by `(raw + 7) ~/ 15 * 15`. The /// round-half-up bias applied before the division, which is what keeps this
/// endpoints are [firstMinute] and [lastMinute] exactly -- never snapped. /// free of floating point.
/// ///
/// Strictly ascending, provably: [normalized] caps [count] so that /// Both endpoints land exactly on [first] and [last] by construction, so the
/// `span / d >= 15`, hence consecutive `raw` values differ by at least 15, /// eating window is always honoured even when interior spacing must round.
/// 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 /// The result is strictly ascending because [normalized] caps [count] at
/// endpoint. That matters because slot minutes are set members, map keys /// `last - first + 1`. Without that cap a narrow window repeats an hour
/// *and* notification ids: a repeat silently drops a checkpoint. /// (`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.
List<int> slots() { List<int> slots() {
final schedule = normalized(); final schedule = normalized();
final first = schedule.firstMinute; final span = schedule.last - schedule.first;
final last = schedule.lastMinute;
final span = last - first;
final divisions = schedule.count - 1; final divisions = schedule.count - 1;
return [ return [
first, for (var index = 0; index < schedule.count; index++)
for (var index = 1; index < divisions; index++) schedule.first + (index * span + divisions ~/ 2) ~/ divisions,
(first + (index * span + divisions ~/ 2) ~/ divisions + 7) ~/
kSlotGridMinutes *
kSlotGridMinutes,
last,
]; ];
} }
/// The minute at which slot enforcement stops for the day. /// The hour at which slot enforcement stops for the day.
/// ///
/// Derived from the *normalised* last meal, so it always agrees with the /// Clamped to the end of the day: a 23:00 last meal would otherwise put the
/// last entry of [slots]. Clamped to the end of the day: a 23:00 last meal /// cutoff at 25, making `hour < cutoff` vacuously true so the enforcement
/// would otherwise put the cutoff at 1500, making `minute < cutoff` /// window never closes and the reminder can never stop firing.
/// vacuously true so the enforcement window never closes. int get enforcementEndHour {
int get enforcementEndMinute { final end = last + kEnforcementTailHours;
final end = normalized().lastMinute + kEnforcementTailMinutes; return end < _hoursPerDay ? end : _hoursPerDay;
return end < kMinutesPerDay ? end : kMinutesPerDay;
} }
@override @override
bool operator ==(Object other) => bool operator ==(Object other) =>
other is MealSchedule && other is MealSchedule &&
other.firstMinute == firstMinute && other.first == first &&
other.lastMinute == lastMinute && other.last == last &&
other.count == count; other.count == count;
@override @override
int get hashCode => Object.hash(firstMinute, lastMinute, count); int get hashCode => Object.hash(first, last, count);
@override @override
String toString() => 'MealSchedule($firstMinute-$lastMinute x$count)'; String toString() => 'MealSchedule($first-$last x$count)';
} }
/// The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, enforcement /// 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 /// closing at 22:00. Still what a device uses before the user has chosen
/// anything, so upgrading changes no behaviour. /// anything, so upgrading changes no behaviour.
const MealSchedule kDefaultSchedule = MealSchedule( const MealSchedule kDefaultSchedule = MealSchedule(
firstMinute: 8 * 60, first: 8,
lastMinute: 20 * 60, last: 20,
count: 4, 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,5 +1,4 @@
/// Pure meal-slot arithmetic, mirroring diet_guard's `_slots.py` and /// Pure meal-slot arithmetic, mirroring diet_guard's `_slots.py`.
/// `_slot_wire.py`.
/// ///
/// Deliberately I/O-free and clock-free: every function is a total function of /// 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 /// its `now` and `schedule` arguments, so the time-of-day edges are
@ -8,11 +7,6 @@
/// the Python original is shared between the gate dashboard and the lock /// the Python original is shared between the gate dashboard and the lock
/// decision. /// 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 /// `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 /// 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 /// that was missed during a refactor keep deriving the old fixed hours on one
@ -20,24 +14,11 @@
/// slot one device offers and the other does not is a checkpoint that can /// 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 /// never be satisfied. Callers resolve the value at the impure edge, through
/// `MealScheduleService.current`. /// `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; library;
import 'package:diet_guard_app/models/meal_schedule.dart'; import 'package:diet_guard_app/models/meal_schedule.dart';
/// Returns [now]'s minute of day, `0..1439` (seconds are ignored). /// Returns the meal-slot hours for a day, e.g. `[8, 12, 16, 20]`.
///
/// 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`. /// Mirrors `_slots.day_slots`.
List<int> daySlots(MealSchedule schedule) => schedule.slots(); List<int> daySlots(MealSchedule schedule) => schedule.slots();
@ -45,30 +26,29 @@ List<int> daySlots(MealSchedule schedule) => schedule.slots();
/// Returns true if [now] is inside the daily slot-enforcement window. /// Returns true if [now] is inside the daily slot-enforcement window.
/// ///
/// Mirrors `_slots.within_enforcement_window`. /// Mirrors `_slots.within_enforcement_window`.
bool withinEnforcementWindow(DateTime now, MealSchedule schedule) { bool withinEnforcementWindow(DateTime now, MealSchedule schedule) =>
final minute = minuteOfDay(now); now.hour >= schedule.slots().first &&
return schedule.slots().first <= minute && now.hour < schedule.enforcementEndHour;
minute < schedule.enforcementEndMinute;
}
/// Returns today's slots whose minute has arrived as of [now]. /// Returns today's slots whose hour has arrived as of [now].
/// ///
/// Empty outside the enforcement window. Mirrors `_slots.elapsed_slots`. /// Empty outside the enforcement window. Mirrors `_slots.elapsed_slots`.
List<int> elapsedSlots(DateTime now, MealSchedule schedule) { List<int> elapsedSlots(DateTime now, MealSchedule schedule) {
if (!withinEnforcementWindow(now, schedule)) return const []; if (!withinEnforcementWindow(now, schedule)) return const [];
final minute = minuteOfDay(now); return daySlots(schedule).where((slot) => slot <= now.hour).toList();
return daySlots(schedule).where((slot) => slot <= minute).toList();
} }
/// Returns elapsed slots not yet covered by [logged] (normally /// Returns elapsed slots not yet covered by [logged].
/// [satisfiedSlots] of the entries' slot minutes).
/// ///
/// Mirrors `_slots.missing_slots`. /// Mirrors `_slots.missing_slots`.
List<int> missingSlots(DateTime now, Set<int> logged, MealSchedule schedule) => List<int> missingSlots(
elapsedSlots( DateTime now,
Set<int> logged,
MealSchedule schedule,
) => elapsedSlots(
now, now,
schedule, schedule,
).where((slot) => !logged.contains(slot)).toList(); ).where((slot) => !logged.contains(slot)).toList();
/// Returns the most recent elapsed slot as of [now], or null. /// Returns the most recent elapsed slot as of [now], or null.
/// ///
@ -84,7 +64,8 @@ int? currentSlot(DateTime now, MealSchedule schedule) {
/// first slot, clamp to the first slot; after the enforcement window ends, /// 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 /// 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 /// languages must reach each answer by the *same* branch, not merely agree on
/// the value -- the shared fixture pins every minute edge for that reason. /// the value -- `test/models/slot_test.dart` sweeps every hour of the day
/// against several schedules for exactly that reason.
/// ///
/// Unlike [currentSlot] this never returns null, which is the point: an /// 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 /// off-hours meal used to satisfy no slot at all, so eating at 07:30 or 22:30
@ -93,65 +74,11 @@ int? currentSlot(DateTime now, MealSchedule schedule) {
/// *those* would instead make every slot fall due at the end of the day. /// *those* would instead make every slot fall due at the end of the day.
int slotForLog(DateTime now, MealSchedule schedule) { int slotForLog(DateTime now, MealSchedule schedule) {
final slots = daySlots(schedule); final slots = daySlots(schedule);
if (minuteOfDay(now) < slots.first) return slots.first; if (now.hour < slots.first) return slots.first;
return currentSlot(now, schedule) ?? slots.last; return currentSlot(now, schedule) ?? slots.last;
} }
/// Returns the slot closest to [minute]; an exact tie goes to the earlier. /// Returns a human `HH:00` label for [slot], e.g. `"08:00"`.
///
/// 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`. /// Mirrors `_slots.slot_label`.
String slotLabel(int minute) { String slotLabel(int slot) => '${(slot % 24).toString().padLeft(2, '0')}:00';
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]. /// Edit screen for an existing [FoodEntry].
/// ///
/// Preserves [FoodEntry.id], [FoodEntry.time], [FoodEntry.slotMinute], /// Preserves [FoodEntry.id], [FoodEntry.time], [FoodEntry.slot],
/// and [FoodEntry.deleted]. All nutritional fields and /// and [FoodEntry.deleted]. All nutritional fields and
/// the description are editable. /// the description are editable.
class EditEntryScreen extends StatefulWidget { class EditEntryScreen extends StatefulWidget {
@ -130,7 +130,7 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
carbsG: nutrition.carbsG, carbsG: nutrition.carbsG,
fatG: nutrition.fatG, fatG: nutrition.fatG,
source: _source, source: _source,
slotMinute: e.slotMinute, slot: e.slot,
); );
await LogStorageService.instance.updateEntry(e, updated); await LogStorageService.instance.updateEntry(e, updated);
final log = await LogStorageService.instance.readLog(); final log = await LogStorageService.instance.readLog();

View File

@ -9,12 +9,8 @@
/// a day that hasn't started. /// a day that hasn't started.
library; 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/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/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/ui/theme.dart';
import 'package:diet_guard_app/widgets/slot_selector_row.dart'; import 'package:diet_guard_app/widgets/slot_selector_row.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -24,7 +20,6 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
DateTime? _futureDate; DateTime? _futureDate;
int? _futureSlot; int? _futureSlot;
Set<int> _futureLoggedSlots = {}; Set<int> _futureLoggedSlots = {};
MealSchedule? _futureSchedule;
/// The date currently chosen for a future log, or null when logging for /// The date currently chosen for a future log, or null when logging for
/// today through the screen's normal flow. /// today through the screen's normal flow.
@ -39,7 +34,6 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
_futureDate = null; _futureDate = null;
_futureSlot = null; _futureSlot = null;
_futureLoggedSlots = {}; _futureLoggedSlots = {};
_futureSchedule = null;
}); });
} }
@ -55,18 +49,12 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
if (picked == null || !mounted) return; if (picked == null || !mounted) return;
final log = await LogStorageService.instance.readLog(); final log = await LogStorageService.instance.readLog();
if (!mounted) return; if (!mounted) return;
final day = localDateKey(picked); final logged = (log[localDateKey(picked)] ?? const [])
final schedule = MealScheduleService.history.forDay(day); .where((entry) => !entry.deleted && entry.slot != null)
// Snapped against the schedule for *that* day, the same rule as .map((entry) => entry.slot!)
// `loggedSlotsToday`: an exact match would show a pre-logged meal's slot .toSet();
// 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(() { setState(() {
_futureDate = picked; _futureDate = picked;
_futureSchedule = schedule;
_futureLoggedSlots = logged; _futureLoggedSlots = logged;
_futureSlot = null; _futureSlot = null;
}); });
@ -119,7 +107,6 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
} }
return SlotSelectorRow( return SlotSelectorRow(
now: DateTime(date.year, date.month, date.day), now: DateTime(date.year, date.month, date.day),
schedule: _futureSchedule,
loggedSlots: _futureLoggedSlots, loggedSlots: _futureLoggedSlots,
selectedSlot: _futureSlot, selectedSlot: _futureSlot,
onSlotSelected: (slot) => setState(() => _futureSlot = slot), onSlotSelected: (slot) => setState(() => _futureSlot = slot),
@ -145,9 +132,7 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
return ( return (
error: null, error: null,
slot: slot, slot: slot,
// The slot is a minute of day, not an hour: passing it as the hour when: DateTime(date.year, date.month, date.day, slot),
// 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( await LogStorageService.instance.logMeal(
desc, desc,
nutritionFromControllers(_macros, _source), nutritionFromControllers(_macros, _source),
slotMinute: target.slot, slot: target.slot,
when: target.when, when: target.when,
); );
resetFutureLog(); 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 /// The meal-schedule editor lives in settings, and [SlotSelectorRow] reads
/// `MealScheduleService.current` at build time, so refreshing is enough to /// `MealScheduleService.current` at build time, so refreshing is enough to
/// re-derive the row -- but the selected slot also has to be recomputed, /// re-derive the row -- but the selected slot also has to be recomputed,
/// since the minute it referred to may no longer be a checkpoint at all. /// since the hour it referred to may no longer be a checkpoint at all.
/// ///
/// Found on the phone: without this the settings preview and the overdue /// Found on the phone: without this the settings preview and the overdue
/// reminder both updated while the row behind them kept the old four /// reminder both updated while the row behind them kept the old four

View File

@ -1,5 +1,5 @@
// The meal-schedule section: owns the schedule state and its persistence; // The meal-schedule editor: first meal, last meal, how many meals, and a
// the widgets themselves live in `widgets/meal_schedule_editor.dart`. // live preview of the checkpoint times they derive.
// //
// Split out of `settings_screen.dart` for the repo's 250-line cap. A `part` // 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 // mixin for the same reason as `_SettingsKcalGoal`: it drives the screen's
@ -14,22 +14,134 @@ mixin _SettingsMealSchedule on State<SettingsScreen> {
_schedule = MealScheduleService.current; _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 { Future<void> _applySchedule(MealSchedule next) async {
final normalized = next.normalized(); final normalized = next.normalized();
setState(() => _schedule = normalized); setState(() => _schedule = normalized);
if (!MealScheduleService.isInitialized) return; if (!MealScheduleService.isInitialized) return;
await MealScheduleService.instance.recordChange(normalized); await MealScheduleService.instance.recordChange(normalized);
// The reminder ids are slot minutes, so a schedule change leaves posted // The reminder ids are slot hours, so a schedule change orphans the ones
// reminders for checkpoints that no longer exist. Re-running the check // it no longer contains. Re-running the check cancels them immediately
// cancels them immediately rather than leaving a stale nag until the // rather than leaving a stale nag until the next background tick.
// next background tick.
await checkAndNotify(pullWhenDue: false); await checkAndNotify(pullWhenDue: false);
} }
List<Widget> _mealScheduleSection(BuildContext context) => [ /// Dropdowns rather than a time picker: `showTimePicker` returns minutes,
MealScheduleEditor( /// and slots are whole hours on both devices by design.
schedule: _schedule, Widget _hourDropdown({
onChanged: (next) => unawaited(_applySchedule(next)), 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) {
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,6 +12,7 @@ import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart'; import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/meal_schedule.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/github_mirror_screen.dart';
import 'package:diet_guard_app/screens/settings_kuchnia.dart'; import 'package:diet_guard_app/screens/settings_kuchnia.dart';
import 'package:diet_guard_app/services/app_settings_service.dart'; import 'package:diet_guard_app/services/app_settings_service.dart';
@ -21,7 +22,6 @@ 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/google_sign_in_backend.dart';
import 'package:diet_guard_app/services/meal_schedule_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/ui/theme.dart';
import 'package:diet_guard_app/widgets/meal_schedule_editor.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';

View File

@ -11,7 +11,6 @@ library;
import 'package:diet_guard_app/models/kuchnia_dish.dart'; import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/models/nutrition.dart'; import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart'; import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
@ -21,11 +20,6 @@ const kuchniaSource = 'kuchnia wikinga';
/// Keeps only the dishes whose slot has nothing logged in it today. /// 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 /// 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 /// 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 /// the batch, so two dishes the spread put in the same empty slot (5 dishes on
@ -54,12 +48,8 @@ Nutrition dishNutrition(KuchniaDish dish) => nutritionForPortion(
source: kuchniaSource, source: kuchniaSource,
); );
/// Keyed by the entry's *recorded* slot minute, unsnapped, mirroring Python's String _dedupKey(String desc, int? slot) =>
/// `_already_logged` exact comparison. Deliberately not snapped: occupancy '${desc.trim().toLowerCase()}\u0000$slot';
/// ([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. /// Logs each chosen dish, skipping any already logged today in that slot.
/// ///
@ -78,7 +68,7 @@ Future<List<SlottedDish>> logDishes(
final store = storage ?? LogStorageService.instance; final store = storage ?? LogStorageService.instance;
final seen = { final seen = {
for (final entry in await store.todayEntries()) for (final entry in await store.todayEntries())
_dedupKey(entry.desc, entry.slotMinute), _dedupKey(entry.desc, entry.slot),
}; };
final written = <SlottedDish>[]; final written = <SlottedDish>[];
for (final item in chosen) { for (final item in chosen) {
@ -87,7 +77,7 @@ Future<List<SlottedDish>> logDishes(
await store.logMeal( await store.logMeal(
item.dish.name, item.dish.name,
dishNutrition(item.dish), dishNutrition(item.dish),
slotMinute: item.slot, slot: item.slot,
); );
written.add(item); written.add(item);
} }
@ -105,7 +95,11 @@ String _g(double value) {
String planSummary(List<SlottedDish> plan) { String planSummary(List<SlottedDish> plan) {
final total = plan.fold<double>(0, (sum, item) => sum + item.dish.kcal); final total = plan.fold<double>(0, (sum, item) => sum + item.dish.kcal);
final listing = plan final listing = plan
.map((item) => '${slotLabel(item.slot)} ${item.dish.name}') .map(
(item) =>
'${item.slot.toString().padLeft(2, '0')}:00 '
'${item.dish.name}',
)
.join(', '); .join(', ');
return 'Will log ${plan.length} (${_g(total)} kcal): $listing' return 'Will log ${plan.length} (${_g(total)} kcal): $listing'
' — tap Confirm.'; ' — tap Confirm.';

View File

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

View File

@ -7,10 +7,8 @@ import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/local_time.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/meal_component.dart';
import 'package:diet_guard_app/models/nutrition.dart'; import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/document_store.dart'; import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart'; import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
@ -104,12 +102,11 @@ class LogStorageService {
/// Mirrors `_state.log_meal`: always assigns a fresh `id`, never computes /// 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 /// 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 /// merge, see Milestone 3). [when] lets a caller pre-log a meal against a
/// future date/slot; must not be in the past. [slotMinute] is the slot's /// future date/slot; must not be in the past.
/// minute of day (`slotForLog`'s result), never an hour.
Future<FoodEntry> logMeal( Future<FoodEntry> logMeal(
String desc, String desc,
Nutrition nutrition, { Nutrition nutrition, {
int? slotMinute, int? slot,
List<MealComponent>? components, List<MealComponent>? components,
DateTime? when, DateTime? when,
}) async { }) async {
@ -127,7 +124,7 @@ class LogStorageService {
carbsG: nutrition.carbsG, carbsG: nutrition.carbsG,
fatG: nutrition.fatG, fatG: nutrition.fatG,
source: nutrition.source, source: nutrition.source,
slotMinute: slotMinute, slot: slot,
components: components, components: components,
); );
final log = await readLog(); final log = await readLog();
@ -232,17 +229,10 @@ class LogStorageService {
} }
} }
/// Returns today's slot minutes already satisfied, mirrors /// Returns the slot hours already satisfied today, mirrors
/// `_state.logged_slots_today`. /// `_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 { Future<Set<int>> loggedSlotsToday() async {
final entries = await todayEntries(); final entries = await todayEntries();
return satisfiedSlots([ return entries.where((e) => e.slot != null).map((e) => e.slot!).toSet();
for (final entry in entries) ?entry.slotMinute,
], MealScheduleService.current);
} }
} }

View File

@ -50,28 +50,33 @@ class ScheduleEntry {
} }
/// Returns the wire/disk form of one entry's value. /// 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) => { Map<String, Object?> scheduleEntryToJson(ScheduleEntry entry) => {
...scheduleToWire(entry.schedule), 'f': entry.schedule.first,
'l': entry.schedule.last,
'n': entry.schedule.count,
't': entry.editedAt, 't': entry.editedAt,
}; };
/// Returns an entry parsed from its stored value, or null if unusable. /// 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 /// Never throws: a malformed entry is skipped so one bad field from a peer
/// cannot take out the whole history. [scheduleFromWire] normalises on the /// cannot take out the whole history.
/// 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) { ScheduleEntry? scheduleEntryFromJson(String effectiveFrom, Object? raw) {
final schedule = scheduleFromWire(raw); if (raw is! Map) return null;
if (schedule == null || 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 editedAt = raw['t']; final editedAt = raw['t'];
return ScheduleEntry( return ScheduleEntry(
effectiveFrom: effectiveFrom, effectiveFrom: effectiveFrom,
schedule: schedule, // 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(),
editedAt: editedAt is String ? editedAt : _epochIso, editedAt: editedAt is String ? editedAt : _epochIso,
); );
} }

View File

@ -25,12 +25,4 @@ abstract class NotificationBackend {
/// Removes the notification for [slot], if one is showing. /// Removes the notification for [slot], if one is showing.
Future<void> cancel(int slot); 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,17 +66,6 @@ class LocalNotificationsBackend implements NotificationBackend {
@override @override
Future<void> cancel(int slot) => plugin.cancel(id: slot); 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. /// Opens the platform notification backend.

View File

@ -50,13 +50,6 @@ class WebNotificationBackend implements NotificationBackend {
Future<void> cancel(int slot) async { Future<void> cancel(int slot) async {
_shown.remove(slot)?.close(); _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. /// Opens the platform notification backend.

View File

@ -4,12 +4,13 @@
/// rather than fired once. /// rather than fired once.
library; library;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.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.dart';
import 'package:diet_guard_app/services/notification_backend_factory.dart'; import 'package:diet_guard_app/services/notification_backend_factory.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
const int _hoursPerDay = 24;
/// Owns the due-slot notification logic ([syncToSlots]) independently of the /// Owns the due-slot notification logic ([syncToSlots]) independently of the
/// platform surface that actually posts them: `flutter_local_notifications` /// platform surface that actually posts them: `flutter_local_notifications`
/// on Android, the browser's Notifications API in the desktop web build (see /// on Android, the browser's Notifications API in the desktop web build (see
@ -52,45 +53,30 @@ class NotificationService {
/// false the same way. /// false the same way.
Future<bool?> requestPermission() => _backend.requestPermission(); Future<bool?> requestPermission() => _backend.requestPermission();
/// Shows a notification for every slot minute in [dueSlots] and cancels /// Shows a notification for every slot in [dueSlots] and cancels one for
/// every other reminder this app has showing. /// every other known slot.
/// ///
/// Idempotent and re-evaluated every tick: a slot logged after its /// Idempotent and re-evaluated every tick: a slot logged after its
/// notification fired gets that notification cancelled on the very next /// notification fired gets that notification cancelled on the very next
/// call, mirroring `_gate.gate_is_due()`'s re-evaluate-every-tick /// call, mirroring `_gate.gate_is_due()`'s re-evaluate-every-tick
/// behavior rather than firing once and forgetting. /// 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 { Future<void> syncToSlots(List<int> dueSlots) async {
final due = dueSlots.toSet(); final due = dueSlots.toSet();
Iterable<int> stale; // Sweeps every hour of the day, not just the *current* schedule's slots.
try { // The slot hour doubles as the notification id, so a schedule change
stale = (await _backend.activeIds()).difference(due); // orphans the ids it no longer contains: going 08/12/16/20 -> 08/11/14/17
} on Object { // used to leave 12 and 16 posted with nothing left to ever cancel them,
stale = [ // nagging forever about checkpoints that no longer exist.
for (var id = 0; id < kMinutesPerDay; id++) for (var slot = 0; slot < _hoursPerDay; slot++) {
if (!due.contains(id)) id, if (due.contains(slot)) {
];
}
for (final id in stale) {
await _backend.cancel(id);
}
for (final slot in due) {
await _backend.show( await _backend.show(
slot, slot,
'Meal not logged', 'Meal not logged',
"You haven't logged your ${slotLabel(slot)} meal yet.", "You haven't logged your ${slotLabel(slot)} meal yet.",
); );
} else {
await _backend.cancel(slot);
}
} }
} }
} }

View File

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

View File

@ -1,119 +0,0 @@
/// 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

@ -1,134 +0,0 @@
/// 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,16 +3,15 @@
/// used to be three separate stacked elements. /// used to be three separate stacked elements.
library; library;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart'; import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/meal_schedule_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/ui/theme.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// One row of [ChoiceChip]s, one per today's slot (labelled `HH:MM`). Each /// One row of [ChoiceChip]s, one per today's slot hour. Each chip is
/// chip is simultaneously selectable (tap to log for that slot) and /// simultaneously selectable (tap to log for that slot) and status-colored
/// status-colored (green+check = logged, red = due, grey = upcoming), so no /// (green+check = logged, red = due, grey = upcoming), so no separate status
/// separate status bar or caption text is needed. /// bar or caption text is needed.
/// ///
/// There used to be a fifth "Snack" chip that selected no slot at all, /// 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 /// removed 2026-08-14. Entries with a null slot still exist in storage and
@ -25,27 +24,20 @@ class SlotSelectorRow extends StatelessWidget {
required this.loggedSlots, required this.loggedSlots,
required this.selectedSlot, required this.selectedSlot,
required this.onSlotSelected, required this.onSlotSelected,
this.schedule,
super.key, super.key,
}); });
/// Reference time used to decide which slots are due. /// Reference time used to decide which slots are due.
final DateTime now; final DateTime now;
/// The schedule whose slots to show; defaults to the one in force today. /// Slot hours already satisfied by today's log.
///
/// 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; final Set<int> loggedSlots;
/// The slot currently chosen to log for. Nullable for historical reasons /// The slot currently chosen to log for. Nullable for historical reasons
/// (see the class doc); no chip in this row selects null any more. /// (see the class doc); no chip in this row selects null any more.
final int? selectedSlot; final int? selectedSlot;
/// Called with the tapped slot's minute. Never called with null. /// Called with the tapped slot's hour. Never called with null.
final ValueChanged<int?> onSlotSelected; final ValueChanged<int?> onSlotSelected;
@override @override
@ -57,7 +49,7 @@ class SlotSelectorRow extends StatelessWidget {
// matches production exactly when the extension is genuinely absent. // matches production exactly when the extension is genuinely absent.
final statusColors = final statusColors =
Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark; Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark;
final schedule = this.schedule ?? MealScheduleService.current; final schedule = MealScheduleService.current;
final elapsed = elapsedSlots(now, schedule).toSet(); final elapsed = elapsedSlots(now, schedule).toSet();
// One row, always. A Wrap dropped the later pills onto a second line as // 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 // 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" dependency: "direct main"
description: description:
name: idb_shim name: idb_shim
sha256: "110fe0514a52dc8da5414df42405a8f9e880dfac3e84852fdab8e5559ee6ad07" sha256: "1495b1bca25088ab05be682ba32532e62f1559b7cd781141c96130b7654ac9f7"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.9.11" version: "2.9.10"
image: image:
dependency: transitive dependency: transitive
description: description:
@ -670,10 +670,10 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: shared_preferences name: shared_preferences
sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f" sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.5.6" version: "2.5.5"
shared_preferences_android: shared_preferences_android:
dependency: transitive dependency: transitive
description: description:

View File

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

View File

@ -3,57 +3,28 @@ import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.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 /// Mocks the raw `dexterous.com/flutter/local_notifications` MethodChannel
/// the way the package's own test suite does /// the way the package's own test suite does
/// (`android_flutter_local_notifications_test.dart`), so /// (`android_flutter_local_notifications_test.dart`), so
/// [NotificationService] can be exercised end-to-end (init/show/cancel) /// [NotificationService] can be exercised end-to-end (init/show/cancel)
/// without a real Android plugin. /// 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. /// Returns the call log so a test can assert which slots were shown vs.
/// cancelled. /// cancelled.
List<MethodCall> installFakeAndroidNotifications({ List<MethodCall> installFakeAndroidNotifications() {
Map<int, String>? active,
}) {
AndroidFlutterLocalNotificationsPlugin.registerWith(); AndroidFlutterLocalNotificationsPlugin.registerWith();
debugDefaultTargetPlatformOverride = TargetPlatform.android; debugDefaultTargetPlatformOverride = TargetPlatform.android;
const channel = MethodChannel('dexterous.com/flutter/local_notifications'); const channel = MethodChannel('dexterous.com/flutter/local_notifications');
final log = <MethodCall>[]; final log = <MethodCall>[];
final shade = active ?? <int, String>{};
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async { .setMockMethodCallHandler(channel, (call) async {
log.add(call); log.add(call);
final args = call.arguments;
switch (call.method) { switch (call.method) {
case 'initialize': case 'initialize':
return true; return true;
case 'requestNotificationsPermission': case 'requestNotificationsPermission':
return true; 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: default:
return null; return null;
} }

View File

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

View File

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

View File

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

View File

@ -23,40 +23,40 @@ void main() {
test('an empty day keeps every dish', () { test('an empty day keeps every dish', () {
final slotted = assignSlots(dishes(4), defaultSlots); final slotted = assignSlots(dishes(4), defaultSlots);
expect(_names(fillPlan(slotted, {})), [ expect(_names(fillPlan(slotted, {})), [
'D1@480', 'D1@8',
'D2@720', 'D2@12',
'D3@960', 'D3@16',
'D4@1200', 'D4@20',
]); ]);
}); });
test('an occupied slot is skipped, the others stay', () { test('an occupied slot is skipped, the others stay', () {
final slotted = assignSlots(dishes(4), defaultSlots); final slotted = assignSlots(dishes(4), defaultSlots);
expect(_names(fillPlan(slotted, {720})), ['D1@480', 'D3@960', 'D4@1200']); expect(_names(fillPlan(slotted, {12})), ['D1@8', 'D3@16', 'D4@20']);
}); });
test('5 dishes on 4 slots: both dishes of one empty slot stay', () { test('5 dishes on 4 slots: both dishes of one empty slot stay', () {
final slotted = assignSlots(dishes(5), defaultSlots); final slotted = assignSlots(dishes(5), defaultSlots);
// The spread doubles the first slot; occupancy is read once, so the // The spread doubles the first slot; occupancy is read once, so the
// first dish must not shadow the second. // first dish must not shadow the second.
expect(_names(slotted).take(2), ['D1@480', 'D2@480']); expect(_names(slotted).take(2), ['D1@8', 'D2@8']);
expect(_names(fillPlan(slotted, {})), hasLength(5)); expect(_names(fillPlan(slotted, {})), hasLength(5));
expect(_names(fillPlan(slotted, {960})), [ expect(_names(fillPlan(slotted, {16})), [
'D1@480', 'D1@8',
'D2@480', 'D2@8',
'D3@720', 'D3@12',
'D5@1200', 'D5@20',
]); ]);
}); });
test('an occupied doubled slot drops both of its dishes', () { test('an occupied doubled slot drops both of its dishes', () {
final slotted = assignSlots(dishes(5), defaultSlots); final slotted = assignSlots(dishes(5), defaultSlots);
expect(_names(fillPlan(slotted, {480})), ['D3@720', 'D4@960', 'D5@1200']); expect(_names(fillPlan(slotted, {8})), ['D3@12', 'D4@16', 'D5@20']);
}); });
test('a full day yields an empty plan', () { test('a full day yields an empty plan', () {
final slotted = assignSlots(dishes(4), defaultSlots); final slotted = assignSlots(dishes(4), defaultSlots);
expect(fillPlan(slotted, {480, 720, 960, 1200}), isEmpty); expect(fillPlan(slotted, {8, 12, 16, 20}), isEmpty);
}); });
}); });
@ -79,16 +79,16 @@ void main() {
() async { () async {
final storage = freshStorage(); final storage = freshStorage();
final chosen = [ final chosen = [
at(dish('D1', 1, grams: 250), 480), at(dish('D1', 1, grams: 250), 8),
at(dish('D3', 3), 960), at(dish('D3', 3), 16),
]; ];
final written = await logDishes(chosen, storage: storage); final written = await logDishes(chosen, storage: storage);
expect(_names(written), ['D1@480', 'D3@960']); expect(_names(written), ['D1@8', 'D3@16']);
final entries = await storage.todayEntries(); final entries = await storage.todayEntries();
expect(entries.map((e) => e.desc), ['D1', 'D3']); expect(entries.map((e) => e.desc), ['D1', 'D3']);
expect(entries.map((e) => e.slotMinute), [480, 960]); expect(entries.map((e) => e.slot), [8, 16]);
expect(entries.map((e) => e.source), everyElement('kuchnia wikinga')); expect(entries.map((e) => e.source), everyElement('kuchnia wikinga'));
expect(entries.map((e) => e.grams), [250, 300]); expect(entries.map((e) => e.grams), [250, 300]);
expect(entries.map((e) => e.kcal), [100, 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 { test('skips a dish already logged in that slot', () async {
final storage = freshStorage(); final storage = freshStorage();
await storage.logMeal(' d1 ', dishNutrition(dish('D1', 1)), slotMinute: 480); await storage.logMeal(' d1 ', dishNutrition(dish('D1', 1)), slot: 8);
final written = await logDishes([ final written = await logDishes([
at(dish('D1', 1), 480), at(dish('D1', 1), 8),
at(dish('D2', 2), 720), at(dish('D2', 2), 12),
], storage: storage); ], storage: storage);
// Case and surrounding whitespace do not make it a different meal. // Case and surrounding whitespace do not make it a different meal.
expect(_names(written), ['D2@720']); expect(_names(written), ['D2@12']);
expect(await storage.todayEntries(), hasLength(2)); expect(await storage.todayEntries(), hasLength(2));
}); });
@ -114,30 +114,30 @@ void main() {
final twin = dish('Twin', 1); final twin = dish('Twin', 1);
final written = await logDishes([ final written = await logDishes([
at(twin, 480), at(twin, 8),
at(twin, 480), at(twin, 8),
], storage: storage); ], storage: storage);
expect(_names(written), ['Twin@480']); expect(_names(written), ['Twin@8']);
expect(await loggedToday(storage), ['Twin@480']); expect(await loggedToday(storage), ['Twin@8']);
}); });
test('the same dish in a different slot is not a duplicate', () async { test('the same dish in a different slot is not a duplicate', () async {
final storage = freshStorage(); final storage = freshStorage();
await storage.logMeal('D1', dishNutrition(dish('D1', 1)), slotMinute: 480); await storage.logMeal('D1', dishNutrition(dish('D1', 1)), slot: 8);
final written = await logDishes([ final written = await logDishes([
at(dish('D1', 1), 720), at(dish('D1', 1), 12),
], storage: storage); ], storage: storage);
expect(_names(written), ['D1@720']); expect(_names(written), ['D1@12']);
expect(await loggedToday(storage), ['D1@480', 'D1@720']); expect(await loggedToday(storage), ['D1@8', 'D1@12']);
}); });
}); });
group('planSummary', () { group('planSummary', () {
test('lists slot, dish and the kcal total', () { test('lists slot, dish and the kcal total', () {
final plan = [at(dish('D1', 1), 480), at(dish('D2', 2), 720)]; final plan = [at(dish('D1', 1), 8), at(dish('D2', 2), 12)];
expect( expect(
planSummary(plan), planSummary(plan),
'Will log 2 (300 kcal): 08:00 D1, 12:00 D2 — tap Confirm.', '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(); subject = dishes.take(3).toList();
key = key.substring('first_three_'.length); key = key.substring('first_three_'.length);
} }
final minutes = [for (final part in key.split(',')) int.parse(part)]; final hours = [for (final part in key.split(',')) int.parse(part)];
final actual = [ final actual = [
for (final item in assignSlots(subject, minutes)) item.slot, for (final item in assignSlots(subject, hours)) item.slot,
]; ];
expect( expect(
actual, actual,
@ -124,10 +124,10 @@ void main() {
// total. Run repeatedly: an unstable sort need not misbehave every time. // total. Run repeatedly: an unstable sort need not misbehave every time.
for (var attempt = 0; attempt < 5; attempt++) { for (var attempt = 0; attempt < 5; attempt++) {
final ordered = assignSlots(parseMenu(fixture['payload']), const [ final ordered = assignSlots(parseMenu(fixture['payload']), const [
480, 8,
720, 12,
960, 16,
1200, 20,
]); ]);
expect( expect(
[for (final item in ordered) item.dish.name], [for (final item in ordered) item.dish.name],

View File

@ -32,7 +32,7 @@ void main() {
expect(entry.id, 'abc-123'); expect(entry.id, 'abc-123');
expect(entry.desc, 'label_food'); expect(entry.desc, 'label_food');
expect(entry.kcal, 300.0); expect(entry.kcal, 300.0);
expect(entry.slotMinute, 960); expect(entry.slot, 16);
expect(entry.hmac, 'deadbeef'); expect(entry.hmac, 'deadbeef');
expect(entry.components, hasLength(1)); expect(entry.components, hasLength(1));
expect(entry.components!.first.name, 'rice'); expect(entry.components!.first.name, 'rice');
@ -45,7 +45,7 @@ void main() {
expect(entry.kcal, 0); expect(entry.kcal, 0);
expect(entry.proteinG, 0); expect(entry.proteinG, 0);
expect(entry.source, 'manual'); expect(entry.source, 'manual');
expect(entry.slotMinute, isNull); expect(entry.slot, isNull);
expect(entry.deleted, isFalse); expect(entry.deleted, isFalse);
expect(entry.components, isNull); expect(entry.components, isNull);
}); });
@ -67,7 +67,6 @@ void main() {
); );
final local = entry.toLocalJson(); final local = entry.toLocalJson();
final sync = entry.toSyncJson(); final sync = entry.toSyncJson();
expect(local, sync);
expect(sync.containsKey('hmac'), isFalse); expect(sync.containsKey('hmac'), isFalse);
expect(sync['desc'], 'toast'); expect(sync['desc'], 'toast');
}); });
@ -137,50 +136,4 @@ void main() {
expect(tombstoned.components, base.components); 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,87 +1,94 @@
/// Tests for the pure meal-schedule derivation. /// Tests for the pure meal-schedule derivation.
/// ///
/// The cross-language exact values live in the shared fixture /// The vector table below is duplicated verbatim from
/// `tests/fixtures/meal_schedule_vectors.json`, asserted by /// `diet_guard/tests/test_meal_schedule.py`. KEEP THE TWO IN SYNC: it is the
/// `meal_schedule_vectors_test.dart` (and by its Python mirror). This file /// only thing that catches a Python/Dart divergence before it reaches a
/// holds the properties: the grid sweep, the hour-formula regression and the /// device, and a divergence there means one device nags for a checkpoint the
/// clamps a human should read without opening the fixture. The sweeps are /// other never offers -- a slot that can never be satisfied, i.e. a permanent
/// duplicated loop-for-loop in `diet_guard/tests/test_meal_schedule.py`. /// lock.
library; library;
import 'package:diet_guard_app/models/meal_schedule.dart'; import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
const int _h = 60; /// (first, last, count, expected slots). Shared with the Python mirror.
const List<(int, int, int, List<int>)> scheduleVectors = [
/// The pre-minute whole-hour derivation, converted to minutes. // The eating window the user described, at every supported meal count.
List<int> _oldHourSlots(int first, int last, int count) { (8, 20, 2, [8, 20]),
final span = last - first; (8, 20, 3, [8, 14, 20]),
final divisions = count - 1; (8, 20, 4, [8, 12, 16, 20]), // today's hardcoded schedule
return [ (8, 20, 5, [8, 11, 14, 17, 20]), // the user's stated example
for (var index = 0; index < count; index++) (8, 20, 6, [8, 10, 13, 15, 18, 20]),
(first + (index * span + divisions ~/ 2) ~/ divisions) * _h, // 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]),
bool _strictlyAscending(List<int> slots) { // Narrow windows: count is capped at the number of whole hours available,
for (var i = 1; i < slots.length; i++) { // so the slots stay distinct instead of repeating an hour.
if (slots[i - 1] >= slots[i]) return false; (8, 12, 6, [8, 9, 10, 11, 12]),
} (8, 10, 5, [8, 9, 10]),
return true; (8, 9, 4, [8, 9]),
} // Whole-day extremes.
(0, 23, 6, [0, 5, 9, 14, 18, 23]),
MealSchedule _s(int first, int last, int count) => (0, 1, 2, [0, 1]),
MealSchedule(firstMinute: first, lastMinute: last, count: count); ];
void main() { void main() {
group('slots', () { group('slots', () {
test('the default is the historical schedule', () { for (final (first, last, count, expected) in scheduleVectors) {
expect(kDefaultSchedule.slots(), [480, 720, 960, 1200]); test('$first-$last x$count derives $expected', () {
});
// 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( expect(
_s(first * _h, last * _h, count).slots(), MealSchedule(first: first, last: last, count: count).slots(),
_oldHourSlots(first, last, count), expected,
); );
}); });
} }
test('off-grid endpoints are exact; only the interior snaps', () { test('the default is the historical schedule', () {
final slots = _s(443, 1181, 5).slots(); expect(kDefaultSchedule.slots(), [8, 12, 16, 20]);
expect(slots.first, 443);
expect(slots.last, 1181);
for (final slot in slots.sublist(1, slots.length - 1)) {
expect(slot % kSlotGridMinutes, 0);
}
}); });
test("the user's quarter-hour schedule", () { test('endpoints stay exact when the spacing rounds', () {
expect(_s(435, 1140, 5).slots(), [435, 615, 795, 960, 1140]); final slots = const MealSchedule(first: 8, last: 20, count: 6).slots();
expect(slots.first, 8);
expect(slots.last, 20);
}); });
}); });
group('normalized', () { group('normalized', () {
final cases = <(MealSchedule, MealSchedule)>[ const cases = <(MealSchedule, MealSchedule)>[
(_s(480, 1200, 99), _s(480, 1200, kMaxMealCount)), (
(_s(480, 1200, 0), _s(480, 1200, kMinMealCount)), MealSchedule(first: 8, last: 20, count: 99),
(_s(-5, 1200, 4), _s(0, 1200, 4)), MealSchedule(first: 8, last: 20, count: kMaxMealCount),
(_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)), MealSchedule(first: 8, last: 20, count: 0),
(_s(720, 3, 4), _s(720, 735, 2)), MealSchedule(first: 8, last: 20, count: kMinMealCount),
// 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. MealSchedule(first: -5, last: 20, count: 4),
(_s(480, 540, 6), _s(480, 540, 5)), 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),
),
]; ];
for (final (input, expected) in cases) { for (final (input, expected) in cases) {
test('$input clamps to $expected', () { test('$input clamps to $expected', () {
expect(input.normalized(), expected); expect(input.normalized(), expected);
@ -89,82 +96,56 @@ void main() {
} }
test('garbage still yields usable slots', () { test('garbage still yields usable slots', () {
expect(_s(9999, -5, 999).slots(), [1424, 1439]); expect(
const MealSchedule(first: 99, last: -5, count: 999).slots(),
[22, 23],
);
}); });
}); });
group('enforcementEndMinute', () { group('enforcementEndHour', () {
test('the default keeps the historical 22:00 cutoff', () { test('the default keeps the historical 22:00 cutoff', () {
expect(kDefaultSchedule.enforcementEndMinute, 22 * _h); expect(kDefaultSchedule.enforcementEndHour, 22);
}); });
test('the tail follows the last meal, to the minute', () { test('the tail follows the last meal', () {
expect(_s(480, 1095, 4).enforcementEndMinute, 1215); expect(
const MealSchedule(first: 8, last: 18, count: 4).enforcementEndHour,
20,
);
}); });
test('is clamped to the end of the day', () { test('is clamped to the end of the day', () {
// An unclamped 1380 + 120 = 1500 would make `minute < cutoff` // An unclamped 23 + 2 = 25 would make `hour < cutoff` vacuously true,
// vacuously true, so the enforcement window would never close. // so the enforcement window would never close.
expect(_s(480, 1380, 4).enforcementEndMinute, kMinutesPerDay); expect(
}); const MealSchedule(first: 8, last: 23, count: 4).enforcementEndHour,
24,
test('follows the normalised last meal', () { );
final schedule = _s(720, 3, 4);
expect(schedule.enforcementEndMinute, schedule.slots().last + 120);
}); });
}); });
group('wire', () { test('every input yields ascending slots with exact endpoints', () {
test('a whole-hour schedule encodes exactly as before', () { // The Dart half of the cross-language parity guarantee; the Python mirror
expect(scheduleToWire(kDefaultSchedule), {'f': 8, 'l': 20, 'n': 4}); // runs the identical sweep.
}); for (var first = -2; first < 26; first++) {
for (var last = -2; last < 26; last++) {
test('off-hour endpoints add minute fields', () { for (var count = -2; count < 10; count++) {
expect(scheduleToWire(_s(435, 1181, 5)), { final schedule = MealSchedule(
'f': 7, first: first,
'l': 19, last: last,
'n': 5, count: count,
'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 normalized = schedule.normalized();
final slots = schedule.slots(); 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');
}
}
}
});
test('off-grid sweep stays strictly ascending', () { expect(slots.first, normalized.first);
for (var first = 0; first < 120; first += 7) { expect(slots.last, normalized.last);
for (var width = 15; width < 200; width += 11) { expect(slots.length, normalized.count);
for (var count = kMinMealCount; count <= kMaxMealCount; count++) { expect(slots.toSet().length, slots.length);
final slots = _s(first, first + width, count).slots(); expect(slots, orderedEquals(List<int>.of(slots)..sort()));
if (!_strictlyAscending(slots)) fail('$first+$width x$count: $slots'); expect(slots.length, greaterThanOrEqualTo(kMinMealCount));
expect(slots.length, lessThanOrEqualTo(kMaxMealCount));
} }
} }
} }

View File

@ -1,177 +0,0 @@
/// 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,172 +1,229 @@
/// 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/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart'; import 'package:diet_guard_app/models/slot.dart';
import 'package:flutter_test/flutter_test.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() { void main() {
test('minuteOfDay counts minutes and ignores seconds', () { group('daySlots', () {
expect(minuteOfDay(DateTime(2026, 6, 22, 7, 15, 59)), 435); test('returns the four fixed hourly slots', () {
expect(minuteOfDay(_at(23, 59)), 1439); expect(daySlots(kDefaultSchedule), [8, 12, 16, 20]);
}); });
test('daySlots returns the four default slots', () {
expect(daySlots(kDefaultSchedule), [480, 720, 960, 1200]);
}); });
group('withinEnforcementWindow', () { group('withinEnforcementWindow', () {
test('false at 07:59, true at 08:00', () { test('false before the day start hour', () {
expect(withinEnforcementWindow(_at(7, 59), kDefaultSchedule), isFalse); expect(
expect(withinEnforcementWindow(_at(8), kDefaultSchedule), isTrue); withinEnforcementWindow(DateTime(2026, 6, 22, 7, 59), kDefaultSchedule),
isFalse,
);
}); });
test('true at 21:59, false at the 22:00 cutoff', () { test('true at the day start hour', () {
expect(withinEnforcementWindow(_at(21, 59), kDefaultSchedule), isTrue); expect(
expect(withinEnforcementWindow(_at(22), kDefaultSchedule), isFalse); withinEnforcementWindow(DateTime(2026, 6, 22, 8, 0), kDefaultSchedule),
isTrue,
);
}); });
test('a 07:15 breakfast opens the window at 07:15', () { test('true just before the eating end hour', () {
final schedule = _s(435, 1140, 5); expect(
expect(withinEnforcementWindow(_at(7, 14), schedule), isFalse); withinEnforcementWindow(
expect(withinEnforcementWindow(_at(7, 15), schedule), isTrue); 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,
);
}); });
}); });
group('elapsedSlots', () { group('elapsedSlots', () {
test('empty outside the enforcement window', () { test('empty outside the enforcement window', () {
expect(elapsedSlots(_at(23), kDefaultSchedule), isEmpty); expect(
expect(elapsedSlots(_at(7, 59), kDefaultSchedule), isEmpty); elapsedSlots(DateTime(2026, 6, 22, 23, 0), kDefaultSchedule),
isEmpty,
);
}); });
test('grows through the day', () { test('only the 8 slot right at day start', () {
expect(elapsedSlots(_at(8), kDefaultSchedule), [480]); expect(elapsedSlots(DateTime(2026, 6, 22, 8, 0), kDefaultSchedule), [8]);
expect(elapsedSlots(_at(15, 59), kDefaultSchedule), [480, 720]);
expect(elapsedSlots(_at(21), kDefaultSchedule), [480, 720, 960, 1200]);
}); });
test('a slot opens on its minute', () { test('8 and 12 mid-afternoon before 16', () {
final schedule = _s(435, 1140, 5); expect(elapsedSlots(DateTime(2026, 6, 22, 15, 59), kDefaultSchedule), [
expect(elapsedSlots(_at(10, 14), schedule), [435]); 8,
expect(elapsedSlots(_at(10, 15), schedule), [435, 615]); 12,
]);
});
test('all four slots once 20:00 has passed', () {
expect(elapsedSlots(DateTime(2026, 6, 22, 21, 0), kDefaultSchedule), [
8,
12,
16,
20,
]);
}); });
}); });
test('missingSlots excludes logged slots', () { group('missingSlots', () {
expect(missingSlots(_at(17), {480}, kDefaultSchedule), [720, 960]); test('excludes already-logged elapsed slots', () {
expect(missingSlots(_at(17), {480, 720, 960}, kDefaultSchedule), isEmpty); expect(
missingSlots(DateTime(2026, 6, 22, 17, 0), {8}, kDefaultSchedule),
[12, 16],
);
}); });
test('currentSlot is the latest elapsed slot, or null', () { test('empty once every elapsed slot is logged', () {
expect(currentSlot(_at(6), kDefaultSchedule), isNull); expect(
expect(currentSlot(_at(17, 41), kDefaultSchedule), 960); missingSlots(DateTime(2026, 6, 22, 17, 0), {
8,
12,
16,
}, 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);
});
}); });
group('slotForLog', () { group('slotForLog', () {
// Keep in lockstep with `diet_guard/tests/test_slots.py`'s // Keep in lockstep with `diet_guard/tests/test_slots.py`'s
// TestSlotForLog: a divergence means the PC and the phone disagree about // TestSlotForLog: a divergence means the PC and the phone disagree about
// which checkpoint a meal satisfied. // which checkpoint a meal satisfied.
test('clamps before the window and after it', () { DateTime at(int hour) => DateTime(2026, 6, 22, hour, 0);
expect(slotForLog(_at(0), kDefaultSchedule), 480);
expect(slotForLog(_at(7, 59), kDefaultSchedule), 480); test('clamps to the first slot before the window opens', () {
expect(slotForLog(_at(13), kDefaultSchedule), 720); expect(slotForLog(at(7), kDefaultSchedule), 8);
expect(slotForLog(_at(21, 59), kDefaultSchedule), 1200);
expect(slotForLog(_at(22), kDefaultSchedule), 1200);
}); });
test('clamps the same way at every minute across schedules', () { test('clamps to the first slot in the small hours', () {
// `test_slots.py` runs the identical sweep. expect(slotForLog(at(0), kDefaultSchedule), 8);
final schedules = [ });
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 = [
kDefaultSchedule, kDefaultSchedule,
_s(480, 1200, 5), MealSchedule(first: 8, last: 20, count: 5),
_s(435, 1140, 5), MealSchedule(first: 6, last: 22, count: 6),
_s(443, 1181, 4), MealSchedule(first: 0, last: 23, count: 2),
_s(0, 1439, 2), MealSchedule(first: 10, last: 14, count: 3),
_s(600, 840, 3),
]; ];
for (final schedule in schedules) { for (final schedule in schedules) {
final slots = daySlots(schedule); final slots = daySlots(schedule);
for (var minute = 0; minute < 1440; minute++) { for (var hour = 0; hour < 24; hour++) {
final attributed = slotForLog( final attributed = slotForLog(at(hour), schedule);
_at(minute ~/ 60, minute % 60), expect(slots, contains(attributed));
schedule, if (hour < slots.first) {
); expect(attributed, slots.first);
final int expected; } else if (hour >= schedule.enforcementEndHour) {
if (minute < slots.first) { expect(attributed, slots.last);
expected = slots.first;
} else if (minute >= schedule.enforcementEndMinute) {
expected = slots.last;
} else { } else {
expected = slots.where((s) => s <= minute).last; // Inside the window: the most recent slot that has opened.
} expect(attributed, slots.where((s) => s <= hour).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', () { test('midnight is a real slot, not a falsy absence', () {
final schedule = _s(0, 720, 3); const schedule = MealSchedule(first: 0, last: 12, count: 3);
expect(daySlots(schedule), [0, 360, 720]); expect(daySlots(schedule), [0, 6, 12]);
expect(currentSlot(_at(0), schedule), 0); expect(currentSlot(DateTime(2026, 6, 22), schedule), 0);
expect(slotForLog(_at(0), schedule), 0); expect(slotForLog(DateTime(2026, 6, 22), schedule), 0);
}); });
}); });
group('nearestSlot / satisfiedSlots', () { group('slotLabel', () {
test('an exact halfway goes to the earlier slot', () { test('pads single-digit hours', () {
expect(nearestSlot(600, kDefaultSchedule), 480); expect(slotLabel(8), '08:00');
expect(nearestSlot(601, kDefaultSchedule), 720);
}); });
test('outside the window clamps to the ends', () { test('formats double-digit hours', () {
expect(nearestSlot(-60, kDefaultSchedule), 480); expect(slotLabel(20), '20:00');
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(await t.runAsync(() => loggedToday(storage)), hasLength(4));
expect(host.publishes, 1, reason: 'one publish per batch, not per dish'); expect(host.publishes, 1, reason: 'one publish per batch, not per dish');
expect(KuchniaQueueService.remaining, 0); expect(KuchniaQueueService.remaining, 0);
expect(host.loggedSlots, {480, 720, 960, 1200}); expect(host.loggedSlots, {8, 12, 16, 20});
expect(host.desc.text, isEmpty, reason: 'D1 was logged by the fill'); expect(host.desc.text, isEmpty, reason: 'D1 was logged by the fill');
}); });
@ -144,7 +144,7 @@ void main() {
await storage.logMeal( await storage.logMeal(
'own breakfast', 'own breakfast',
dishNutrition(dish('own', 1)), dishNutrition(dish('own', 1)),
slotMinute: 480, slot: 8,
); );
await host.onFillAll(); await host.onFillAll();
await host.onFillAll(); await host.onFillAll();

View File

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

View File

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

View File

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

View File

@ -85,35 +85,12 @@ void main() {
expect(find.text('Meals per day'), findsOneWidget); 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', ( testWidgets('reflects a five-meal schedule as the user\'s example', (
tester, tester,
) async { ) async {
await tester.runAsync(() async { await tester.runAsync(() async {
await MealScheduleService.instance.recordChange( await MealScheduleService.instance.recordChange(
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
); );
await tester.pumpWidget(const MaterialApp(home: SettingsScreen())); await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester); await settle(tester);

View File

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

View File

@ -59,11 +59,11 @@ void main() {
final entry = await LogStorageService.instance.logMeal( final entry = await LogStorageService.instance.logMeal(
'toast', 'toast',
_manual, _manual,
slotMinute: 480, slot: 8,
); );
expect(entry.id, isNotEmpty); expect(entry.id, isNotEmpty);
expect(entry.hmac, isNull); expect(entry.hmac, isNull);
expect(entry.slotMinute, 480); expect(entry.slot, 8);
expect(entry.desc, 'toast'); expect(entry.desc, 'toast');
}); });
@ -100,7 +100,7 @@ void main() {
final entry = await LogStorageService.instance.logMeal( final entry = await LogStorageService.instance.logMeal(
'future meal', 'future meal',
_manual, _manual,
slotMinute: 720, slot: 12,
when: future, when: future,
); );
final log = await LogStorageService.instance.readLog(); final log = await LogStorageService.instance.readLog();
@ -195,17 +195,9 @@ void main() {
}); });
group('loggedSlotsToday', () { group('loggedSlotsToday', () {
test('returns only the slots with a logged entry', () async { test('returns only the slots with a logged entry', () async {
await LogStorageService.instance.logMeal('a', _manual, slotMinute: 480); await LogStorageService.instance.logMeal('a', _manual, slot: 8);
await LogStorageService.instance.logMeal('b', _manual); await LogStorageService.instance.logMeal('b', _manual);
expect(await LogStorageService.instance.loggedSlotsToday(), {480}); expect(await LogStorageService.instance.loggedSlotsToday(), {8});
});
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', () { test('round trips', () {
const entry = ScheduleEntry( const entry = ScheduleEntry(
effectiveFrom: '2026-08-16', effectiveFrom: '2026-08-16',
schedule: MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), schedule: MealSchedule(first: 8, last: 20, count: 5),
editedAt: '2026-08-16T12:00:00.000', editedAt: '2026-08-16T12:00:00.000',
); );
expect( expect(
@ -32,7 +32,7 @@ void main() {
'l': 20, 'l': 20,
'n': 99, 'n': 99,
}); });
expect(entry!.schedule, const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 6)); expect(entry!.schedule, const MealSchedule(first: 8, last: 20, count: 6));
}); });
test('falls back to the epoch when the stamp is missing', () { test('falls back to the epoch when the stamp is missing', () {
@ -86,7 +86,7 @@ void main() {
final history = MealScheduleHistory(const [ final history = MealScheduleHistory(const [
ScheduleEntry( ScheduleEntry(
effectiveFrom: '2026-08-16', effectiveFrom: '2026-08-16',
schedule: MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), schedule: MealSchedule(first: 8, last: 20, count: 5),
editedAt: 't', editedAt: 't',
), ),
]); ]);
@ -97,7 +97,7 @@ void main() {
final history = MealScheduleHistory(const [ final history = MealScheduleHistory(const [
ScheduleEntry( ScheduleEntry(
effectiveFrom: '2026-08-16', effectiveFrom: '2026-08-16',
schedule: MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), schedule: MealSchedule(first: 8, last: 20, count: 5),
editedAt: 't1', editedAt: 't1',
), ),
ScheduleEntry( ScheduleEntry(
@ -108,30 +108,30 @@ void main() {
]); ]);
expect( expect(
history.forDay('2026-08-16'), history.forDay('2026-08-16'),
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
); );
expect(history.forDay('2026-05-01'), kDefaultSchedule); expect(history.forDay('2026-05-01'), kDefaultSchedule);
}); });
test('upsert replaces a same-day re-edit', () { test('upsert replaces a same-day re-edit', () {
final once = MealScheduleHistory.empty.upsert( final once = MealScheduleHistory.empty.upsert(
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
when: _at('2026-08-16'), when: _at('2026-08-16'),
); );
final twice = once.upsert( final twice = once.upsert(
const MealSchedule(firstMinute: 9 * 60, lastMinute: 21 * 60, count: 3), const MealSchedule(first: 9, last: 21, count: 3),
when: _at('2026-08-16'), when: _at('2026-08-16'),
); );
expect(twice.entries, hasLength(1)); expect(twice.entries, hasLength(1));
expect( expect(
twice.entries.single.schedule, twice.entries.single.schedule,
const MealSchedule(firstMinute: 9 * 60, lastMinute: 21 * 60, count: 3), const MealSchedule(first: 9, last: 21, count: 3),
); );
}); });
test('upsert defaults to now', () { test('upsert defaults to now', () {
final history = MealScheduleHistory.empty.upsert( final history = MealScheduleHistory.empty.upsert(
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
); );
expect(history.entries, hasLength(1)); expect(history.entries, hasLength(1));
}); });

View File

@ -56,13 +56,13 @@ void main() {
() async { () async {
await MealScheduleService.initForTesting(store); await MealScheduleService.initForTesting(store);
await MealScheduleService.instance.recordChange( await MealScheduleService.instance.recordChange(
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
); );
await MealScheduleService.initForTesting(store); await MealScheduleService.initForTesting(store);
expect( expect(
MealScheduleService.current, MealScheduleService.current,
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
); );
// The whole point of the history: a day before the edit keeps the // The whole point of the history: a day before the edit keeps the
// four-meal schedule it was actually judged against. // four-meal schedule it was actually judged against.
@ -103,7 +103,7 @@ void main() {
() async { () async {
await MealScheduleService.initForTesting(store); await MealScheduleService.initForTesting(store);
await MealScheduleService.instance.recordChange( await MealScheduleService.instance.recordChange(
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
); );
// A pre-feature peer contributes no `sched:` fields; writing that back // A pre-feature peer contributes no `sched:` fields; writing that back
@ -111,20 +111,20 @@ void main() {
await MealScheduleService.instance.applyMerged(const []); await MealScheduleService.instance.applyMerged(const []);
expect( expect(
MealScheduleService.current, MealScheduleService.current,
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
); );
final stamp = DateTime.parse('2026-08-16T09:00:00.000'); final stamp = DateTime.parse('2026-08-16T09:00:00.000');
await MealScheduleService.instance.applyMerged([ await MealScheduleService.instance.applyMerged([
ScheduleEntry( ScheduleEntry(
effectiveFrom: kScheduleEpochDay, effectiveFrom: kScheduleEpochDay,
schedule: const MealSchedule(firstMinute: 7 * 60, lastMinute: 19 * 60, count: 3), schedule: const MealSchedule(first: 7, last: 19, count: 3),
editedAt: stamp.toIso8601String(), editedAt: stamp.toIso8601String(),
), ),
], updatedAt: stamp); ], updatedAt: stamp);
expect( expect(
MealScheduleService.current, MealScheduleService.current,
const MealSchedule(firstMinute: 7 * 60, lastMinute: 19 * 60, count: 3), const MealSchedule(first: 7, last: 19, count: 3),
); );
// The winner's stamp is kept verbatim, so re-syncing is idempotent. // The winner's stamp is kept verbatim, so re-syncing is idempotent.
expect(MealScheduleService.updatedAt, stamp); expect(MealScheduleService.updatedAt, stamp);
@ -134,7 +134,7 @@ void main() {
test('the stored document is plain readable JSON', () async { test('the stored document is plain readable JSON', () async {
await MealScheduleService.initForTesting(store); await MealScheduleService.initForTesting(store);
await MealScheduleService.instance.recordChange( await MealScheduleService.instance.recordChange(
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
when: _at('2026-08-16'), when: _at('2026-08-16'),
); );
final decoded = final decoded =
@ -143,22 +143,5 @@ void main() {
expect(decoded['v'], 1); expect(decoded['v'], 1);
expect((decoded['e']! as Map).keys, contains('2026-08-16')); 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,8 +1,5 @@
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_backend_io.dart';
import 'package:diet_guard_app/services/notification_service.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_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
@ -44,134 +41,98 @@ void main() {
expect(await NotificationService.instance.requestPermission(), isTrue); expect(await NotificationService.instance.requestPermission(), isTrue);
}); });
Future<List<MethodCall>> ready({Map<int, String>? active}) async { test('syncToSlots shows due slots and cancels the rest', () async {
final log = installFakeAndroidNotifications(active: active); final log = installFakeAndroidNotifications();
NotificationService.resetForTesting( NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()), backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
); );
await NotificationService.init(); await NotificationService.init();
log.clear(); log.clear();
return log;
}
Set<Object?> ids(List<MethodCall> log, String method) => { await NotificationService.instance.syncToSlots([12, 20]);
for (final call in log)
if (call.method == method) (call.arguments as Map)['id'],
};
test('syncToSlots shows due slots and cancels other reminders', () async { final shown = log
final log = await ready( .where((c) => c.method == 'show')
active: {480: reminderChannelId, 720: reminderChannelId}, .map((c) => (c.arguments as Map)['id'])
); .toSet();
final cancelled = log
await NotificationService.instance.syncToSlots([720, 1200]); .where((c) => c.method == 'cancel')
.map((c) => (c.arguments as Map)['id'])
expect(ids(log, 'show'), {720, 1200}); .toSet();
expect(ids(log, 'cancel'), {480}); 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('a quiet tick costs one lookup and no cancels', () async { test('syncToSlots with no due slots cancels every id in the day', () async {
// The cost bound: the old design swept every id each tick, which at final log = installFakeAndroidNotifications();
// minute resolution would be 1440 platform calls per background run. NotificationService.resetForTesting(
final log = await ready(); backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await NotificationService.init();
log.clear();
await NotificationService.instance.syncToSlots(const []); await NotificationService.instance.syncToSlots(const []);
expect(log.map((c) => c.method), ['getActiveNotifications']); 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.
test('the upgrade cancels reminders keyed by the old slot hours', () async { expect(log.where((c) => c.method == 'cancel'), hasLength(24));
// 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 { test('syncToSlots cancels ids orphaned by a schedule change', () async {
// The regression this guards: the slot minute *is* the notification // The regression this guards: the slot hour *is* the notification id,
// id, so iterating only the current schedule's slots would leave the // and syncToSlots used to iterate only the current schedule's slots.
// old schedule's reminders posted forever. // Switching 08/12/16/20 -> 08/11/14/17/20 therefore left ids 12 and 16
final log = await ready(); // posted with nothing that would ever cancel them, so the phone nagged
await NotificationService.instance.syncToSlots([720, 960]); // 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]);
log.clear(); log.clear();
// Now due under a five-meal schedule, which has neither 12 nor 16.
await NotificationService.instance.syncToSlots([11]);
// Now due under a schedule that has neither 720 nor 960. final cancelled = log
await NotificationService.instance.syncToSlots([660]); .where((c) => c.method == 'cancel')
.map((c) => (c.arguments as Map)['id'])
expect(ids(log, 'cancel'), {720, 960}); .toSet();
}); expect(cancelled, containsAll(<int>{12, 16}));
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( test(
'syncToSlots cancels a slot whose meal was logged after it fired', 'syncToSlots cancels a slot whose meal was logged after it fired',
() async { () async {
final log = await ready(); final log = installFakeAndroidNotifications();
await NotificationService.instance.syncToSlots([720]); NotificationService.resetForTesting(
backend: LocalNotificationsBackend(
FlutterLocalNotificationsPlugin(),
),
);
await NotificationService.init();
await NotificationService.instance.syncToSlots([12]);
log.clear(); log.clear();
await NotificationService.instance.syncToSlots(const []); // logged await NotificationService.instance.syncToSlots(const []); // logged
expect(ids(log, 'cancel'), {720}); expect(
log
.where((c) => c.method == 'cancel')
.map((c) => (c.arguments as Map)['id']),
contains(12),
);
}, },
); );
}); });
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', () { test('instance throws before init has ever been called', () {
expect(() => NotificationService.instance, throwsA(anything)); 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

@ -1,78 +0,0 @@
// 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([ final fields = scheduleFields([
_entry( _entry(
'2026-08-16', '2026-08-16',
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
'2026-08-16T10:00:00+02:00', '2026-08-16T10:00:00+02:00',
), ),
]); ]);
@ -51,7 +51,7 @@ void main() {
test('the Hlc is deterministic', () { test('the Hlc is deterministic', () {
final entry = _entry( final entry = _entry(
'2026-08-16', '2026-08-16',
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
'2026-08-16T10:00:00+02:00', '2026-08-16T10:00:00+02:00',
); );
expect( expect(
@ -63,7 +63,7 @@ void main() {
test('an unparsable timestamp falls back to the epoch', () { test('an unparsable timestamp falls back to the epoch', () {
final entry = _entry( final entry = _entry(
'2026-08-16', '2026-08-16',
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
'not-a-timestamp', 'not-a-timestamp',
); );
expect(scheduleHlc(entry).wallTimeMs, 0); expect(scheduleHlc(entry).wallTimeMs, 0);
@ -80,7 +80,7 @@ void main() {
budgetToLog(_record, const [], [ budgetToLog(_record, const [], [
_entry( _entry(
'2026-08-16', '2026-08-16',
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
'2026-08-16T10:00:00+02:00', '2026-08-16T10:00:00+02:00',
), ),
]), ]),
@ -89,24 +89,10 @@ void main() {
expect(back.single.effectiveFrom, '2026-08-16'); expect(back.single.effectiveFrom, '2026-08-16');
expect( expect(
back.single.schedule, back.single.schedule,
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, 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", () { test("normalizes a peer's out-of-range schedule", () {
final log = budgetToLog(_record); final log = budgetToLog(_record);
final record = log[budgetRecordId]!; final record = log[budgetRecordId]!;
@ -117,7 +103,7 @@ void main() {
); );
expect( expect(
logToScheduleHistory(log).single.schedule, logToScheduleHistory(log).single.schedule,
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 6), const MealSchedule(first: 8, last: 20, count: 6),
); );
}); });
@ -141,7 +127,7 @@ void main() {
_entry('1970-01-01', kDefaultSchedule, '1970-01-01T00:00:00.000Z'), _entry('1970-01-01', kDefaultSchedule, '1970-01-01T00:00:00.000Z'),
_entry( _entry(
'2026-08-16', '2026-08-16',
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
'2026-08-16T10:00:00+02:00', '2026-08-16T10:00:00+02:00',
), ),
]); ]);
@ -155,7 +141,7 @@ void main() {
expect(logToScheduleHistory(merged).map((e) => e.schedule), [ expect(logToScheduleHistory(merged).map((e) => e.schedule), [
kDefaultSchedule, kDefaultSchedule,
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
]); ]);
}); });
@ -163,14 +149,14 @@ void main() {
final older = budgetToLog(_record, const [], [ final older = budgetToLog(_record, const [], [
_entry( _entry(
'2026-08-16', '2026-08-16',
const MealSchedule(firstMinute: 8 * 60, lastMinute: 20 * 60, count: 5), const MealSchedule(first: 8, last: 20, count: 5),
'2026-08-16T10:00:00+02:00', '2026-08-16T10:00:00+02:00',
), ),
]); ]);
final newer = budgetToLog(_record, const [], [ final newer = budgetToLog(_record, const [], [
_entry( _entry(
'2026-08-16', '2026-08-16',
const MealSchedule(firstMinute: 7 * 60, lastMinute: 21 * 60, count: 3), const MealSchedule(first: 7, last: 21, count: 3),
'2026-08-16T18:00:00+02:00', '2026-08-16T18:00:00+02:00',
), ),
]); ]);
@ -178,7 +164,7 @@ void main() {
final merged = mergeLogs(parseRemoteBudget(_wire(older)), newer); final merged = mergeLogs(parseRemoteBudget(_wire(older)), newer);
expect( expect(
logToScheduleHistory(merged).single.schedule, logToScheduleHistory(merged).single.schedule,
const MealSchedule(firstMinute: 7 * 60, lastMinute: 21 * 60, count: 3), const MealSchedule(first: 7, last: 21, count: 3),
); );
}); });
}); });

View File

@ -1,191 +0,0 @@
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 # 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 # 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() # $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 ~15 min is cheap. # and exits 0 when no lock is needed, so running it every ~30 min is cheap.
# No PYTHONPATH needed: diet_guard is pip-installed (see install.sh / README), # No PYTHONPATH needed: diet_guard is pip-installed (see install.sh / README),
# so /usr/bin/python finds it via user site-packages. # so /usr/bin/python finds it via user site-packages.
# #

View File

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

View File

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

View File

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

View File

@ -87,10 +87,9 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
) )
ate.add_argument( ate.add_argument(
"--hour", "--hour",
type=str, type=int,
default=None, default=None,
help="Meal slot on --date this meal satisfies, as HH:MM or HH (e.g." help="Slot hour on --date this meal satisfies (e.g. 20); requires --date.",
" 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.") 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._kuchnia_spread import assign_slots
from diet_guard._meal_schedule_store import current_schedule from diet_guard._meal_schedule_store import current_schedule
from diet_guard._slots import day_slots, slot_label from diet_guard._slots import day_slots
from diet_guard._state import now_local from diet_guard._state import now_local
if TYPE_CHECKING: # pragma: no cover - typing only if TYPE_CHECKING: # pragma: no cover - typing only
@ -99,7 +99,7 @@ def cmd_kuchnia(
emit(f"{len(dishes)} dish(es) delivered today, banked:") emit(f"{len(dishes)} dish(es) delivered today, banked:")
for item in slotted: for item in slotted:
emit( emit(
f" {slot_label(item.slot)} {item.dish.name} " f" {item.slot:02d}:00 {item.dish.name} "
f"({item.dish.kcal:g} kcal, {item.dish.grams:g} g)", f"({item.dish.kcal:g} kcal, {item.dish.grams:g} g)",
) )
total = sum(dish.kcal for dish in dishes) total = sum(dish.kcal for dish in dishes)

View File

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

View File

@ -76,11 +76,18 @@ OFF_USER_AGENT: str = "diet_guard/1.0 (personal diet tracker)"
DEFAULT_PORTION_GRAMS: float = 100.0 DEFAULT_PORTION_GRAMS: float = 100.0
# --- Gate (log-to-unlock) --------------------------------------------------- # --- Gate (log-to-unlock) ---------------------------------------------------
# The gate is driven by MEAL SLOTS, not by a gap timer: once a slot's minute has # The gate is driven by FIXED MEAL SLOTS, not by a gap timer. Starting at the
# passed, that slot must carry a logged meal or the screen locks until it does. # day-start hour, a slot opens every interval; once a slot's hour has passed,
# Coming home late naturally produces several unlogged elapsed slots at once -> # that slot must carry a logged meal or the screen locks until it does. This
# one lock that backfills the whole day. The slot minutes and the overnight # makes tracking fully automatic (you are prompted on a schedule rather than
# cutoff come from the user's schedule (``_meal_schedule``), not constants here. # 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)
# flock single-instance guard: stops a timer from stacking lock windows. # flock single-instance guard: stops a timer from stacking lock windows.
GATE_LOCK_FILE: Path = DATA_DIR / ".gate.lock" 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. now: Reference time (defaults to the current local time); injectable.
Returns: Returns:
The slot minutes that still need a meal logged (empty == nothing due). The slot hours that still need a meal logged (empty == nothing due).
Empty on a shared free day, whatever the schedule says. The pool is read 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 from a single local file and never the network, so this cannot hang the
@ -49,11 +49,7 @@ def due_slots(now: datetime | None = None) -> tuple[int, ...]:
reference = now if now is not None else now_local() reference = now if now is not None else now_local()
if freedays.is_free_day(reference.date()): if freedays.is_free_day(reference.date()):
return () return ()
# One schedule for both halves: snapping the log onto a different schedule return missing_slots(reference, logged_slots_today(), current_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: 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. demo_mode: Whether the window is a safe sandbox.
Returns: Returns:
The slot minutes to collect, ascending. The slot hours to collect, ascending.
""" """
pending = list(due_slots()) pending = list(due_slots())
if pending: if pending:

View File

@ -4,27 +4,11 @@ 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 250-line cap) rather than added to it. The behaviour behind these widgets
lives in :mod:`._gatelock_scheduleedit`, mirroring how the budget row's lives in :mod:`._gatelock_scheduleedit`, mirroring how the budget row's
widgets and its edit/save logic are split. 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 from __future__ import annotations
import tkinter as tk import tkinter as tk
from tkinter import ttk
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from gatelock import make_button from gatelock import make_button
@ -33,98 +17,19 @@ from diet_guard._gatelock_calendar_types import _COLORS, _FIELD_BG
from diet_guard._gatelock_spacing import SM, XS from diet_guard._gatelock_spacing import SM, XS
from diet_guard._gatelock_typography import BODY, LABEL from diet_guard._gatelock_typography import BODY, LABEL
from diet_guard._gatelock_ui import BG, FG 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: if TYPE_CHECKING:
from collections.abc import Callable from collections.abc import Callable
from diet_guard._gatelock_calendar_types import CalendarVars from diet_guard._gatelock_calendar_types import CalendarVars
__all__ = ["FIRST_RANGE", "LAST_RANGE", "build_schedule_row", "step_time"] __all__ = ["build_schedule_row"]
_ENTRY_WIDTH = 4 _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: def _spin_entry(row: tk.Frame, variable: tk.StringVar) -> tk.Entry:
"""Return the read-only-by-default meal-count entry in the schedule row.""" """Return one read-only-by-default numeric entry in the schedule row."""
entry = tk.Entry( entry = tk.Entry(
row, row,
textvariable=variable, textvariable=variable,
@ -141,38 +46,45 @@ def _spin_entry(row: tk.Frame, variable: tk.StringVar) -> tk.Entry:
return 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( def build_schedule_row(
parent: tk.Frame, parent: tk.Frame,
vars_: CalendarVars, vars_: CalendarVars,
on_edit_or_save_schedule: Callable[[], None], on_edit_or_save_schedule: Callable[[], None],
) -> tuple[ttk.Spinbox, ttk.Spinbox, tk.Entry, tk.Button, tk.Label]: ) -> tuple[tk.Entry, tk.Entry, tk.Entry, tk.Button, tk.Label]:
"""Build the meal-schedule row. """Build the meal-schedule row.
Returns the two time spinboxes, the count entry, the edit button, and the Returns the three hour/count entries, the edit button, and the status
status label, in that order. Like the budget row the fields start locked: label, in that order. Like the budget row the entries start read-only:
the schedule is displayed but not directly editable until "Edit". the schedule is displayed but not directly typeable until "Edit".
Returns: Returns:
``(first_spin, last_spin, count_entry, edit_button, status_label)``. ``(first_entry, last_entry, count_entry, edit_button, status_label)``.
""" """
row = tk.Frame(parent, bg=BG) row = tk.Frame(parent, bg=BG)
row.pack(pady=(SM, XS)) row.pack(pady=(SM, XS))
_caption(row, "Meals:") tk.Label(
first_spin = _time_spin(row, vars_.schedule.first, FIRST_RANGE) row,
_caption(row, "to") text="Meals:",
last_spin = _time_spin(row, vars_.schedule.last, LAST_RANGE) font=(_COLORS.typography.font_family, LABEL),
_caption(row, "x") 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")
count_entry = _spin_entry(row, vars_.schedule.count) count_entry = _spin_entry(row, vars_.schedule.count)
edit_button = make_button(row, _COLORS, "Edit", on_edit_or_save_schedule) edit_button = make_button(row, _COLORS, "Edit", on_edit_or_save_schedule)
edit_button.pack(side="left") edit_button.pack(side="left")
@ -194,4 +106,4 @@ def build_schedule_row(
fg=FG, fg=FG,
) )
status_label.pack(pady=(0, XS)) status_label.pack(pady=(0, XS))
return first_spin, last_spin, count_entry, edit_button, status_label return first_entry, last_entry, count_entry, edit_button, status_label

View File

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

View File

@ -52,10 +52,7 @@ __all__ = [
def _style_notebook(root: tk.Misc) -> None: def _style_notebook(root: tk.Misc) -> None:
"""Theme the History tab's ttk widgets to match the gate's dark palette. """Theme the ``ttk.Notebook`` tab strip 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 ``ttk`` widgets ignore plain ``bg=``/``fg=`` -- unlike every other widget
here, they only take color from a named ``ttk.Style``. Without this the here, they only take color from a named ``ttk.Style``. Without this the
@ -80,21 +77,3 @@ def _style_notebook(root: tk.Misc) -> None:
background=[("selected", _ACCENT)], background=[("selected", _ACCENT)],
foreground=[("selected", _COLORS.palette.on_fill)], 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_log import fill_plan, log_dishes
from diet_guard._kuchnia_spread import assign_slots from diet_guard._kuchnia_spread import assign_slots
from diet_guard._meal_schedule_store import current_schedule from diet_guard._meal_schedule_store import current_schedule
from diet_guard._slots import day_slots, slot_label from diet_guard._slots import day_slots
from diet_guard._state import now_local from diet_guard._state import now_local
if TYPE_CHECKING: # pragma: no cover - typing only if TYPE_CHECKING: # pragma: no cover - typing only
@ -144,9 +144,7 @@ class FillAllFlow:
self._plan = plan self._plan = plan
self._label.set(f"✓ Confirm ({len(plan)})") self._label.set(f"✓ Confirm ({len(plan)})")
total = sum(item.dish.kcal for item in plan) total = sum(item.dish.kcal for item in plan)
listing = ", ".join( listing = ", ".join(f"{item.slot:02d}:00 {item.dish.name}" for item in plan)
f"{slot_label(item.slot)} {item.dish.name}" for item in plan
)
self._set_status( self._set_status(
f"Will log {len(plan)} ({total:g} kcal): {listing} — click Confirm." f"Will log {len(plan)} ({total:g} kcal): {listing} — click Confirm."
) )

View File

@ -11,10 +11,6 @@ before it is written rather than relying on
:meth:`~diet_guard._meal_schedule.MealSchedule.normalized` to clamp it. The :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 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. 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 from __future__ import annotations
@ -26,20 +22,16 @@ import tkinter as tk
from diet_guard._gatelock_budgetedit import _GateBudgetEdit from diet_guard._gatelock_budgetedit import _GateBudgetEdit
from diet_guard._gatelock_ui import ERR, FG from diet_guard._gatelock_ui import ERR, FG
from diet_guard._meal_schedule import ( from diet_guard._meal_schedule import (
FIRST_HOUR,
LAST_HOUR,
MAX_MEAL_COUNT, MAX_MEAL_COUNT,
MIN_MEAL_COUNT, MIN_MEAL_COUNT,
SLOT_GRID_MINUTES,
MealSchedule, MealSchedule,
) )
from diet_guard._meal_schedule_store import current_schedule, record_schedule_change 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 from diet_guard._slots import day_slots, slot_label
__all__ = ["_GateScheduleEdit", "schedule_problem", "schedule_summary"] __all__ = ["_GateScheduleEdit", "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: def schedule_summary(schedule: MealSchedule) -> str:
@ -47,27 +39,6 @@ def schedule_summary(schedule: MealSchedule) -> str:
return " ".join(slot_label(slot) for slot in day_slots(schedule)) 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): class _GateScheduleEdit(_GateBudgetEdit):
"""The History tab's meal-schedule row: display, edit, validate, persist. """The History tab's meal-schedule row: display, edit, validate, persist.
@ -84,16 +55,11 @@ class _GateScheduleEdit(_GateBudgetEdit):
"""Repaint the History tab; implemented by ``_GateCalendar``.""" """Repaint the History tab; implemented by ``_GateCalendar``."""
def _set_schedule_entry_state(self, state: str) -> None: def _set_schedule_entry_state(self, state: str) -> None:
"""Lock (``"readonly"``) or unlock (``"normal"``) the row's fields. """Lock or unlock the three schedule entries on every monitor."""
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 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): 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) surface.schedule_count_entry.config(state=state)
def _set_schedule_button_text(self, text: str) -> None: def _set_schedule_button_text(self, text: str) -> None:
@ -112,8 +78,8 @@ class _GateScheduleEdit(_GateBudgetEdit):
def _show_schedule(self, schedule: MealSchedule) -> None: def _show_schedule(self, schedule: MealSchedule) -> None:
"""Populate the row's fields and derived-times label.""" """Populate the row's fields and derived-times label."""
self._cal_vars.schedule.first.set(slot_label(schedule.first_minute)) self._cal_vars.schedule.first.set(str(schedule.first))
self._cal_vars.schedule.last.set(slot_label(schedule.last_minute)) self._cal_vars.schedule.last.set(str(schedule.last))
self._cal_vars.schedule.count.set(str(schedule.count)) self._cal_vars.schedule.count.set(str(schedule.count))
self._cal_vars.schedule.times.set(schedule_summary(schedule)) self._cal_vars.schedule.times.set(schedule_summary(schedule))
@ -138,19 +104,16 @@ class _GateScheduleEdit(_GateBudgetEdit):
self._refresh_calendar() self._refresh_calendar()
def _read_schedule_fields(self) -> MealSchedule | None: def _read_schedule_fields(self) -> MealSchedule | None:
"""Parse the three fields, or None (with a status set) if unusable.""" """Parse the three entries, or None (with a status set) if unusable."""
try: raw = (
first = parse_hhmm(self._cal_vars.schedule.first.get()) self._cal_vars.schedule.first.get().strip(),
last = parse_hhmm(self._cal_vars.schedule.last.get()) self._cal_vars.schedule.last.get().strip(),
except ValueError: self._cal_vars.schedule.count.get().strip(),
self._set_schedule_status(
"Enter meal times as HH:MM, e.g. 07:15.", error=True
) )
return None
try: try:
count = int(self._cal_vars.schedule.count.get().strip()) first, last, count = (int(value) for value in raw)
except ValueError: except ValueError:
self._set_schedule_status("Enter meals per day as a number.", error=True) self._set_schedule_status("Enter whole hours, e.g. 8 20 5.", error=True)
return None return None
return MealSchedule(first, last, count) return MealSchedule(first, last, count)
@ -163,9 +126,25 @@ class _GateScheduleEdit(_GateBudgetEdit):
schedule = self._read_schedule_fields() schedule = self._read_schedule_fields()
if schedule is None: if schedule is None:
return False return False
problem = schedule_problem(schedule) if not FIRST_HOUR <= schedule.first < schedule.last <= LAST_HOUR:
if problem is not None: self._set_schedule_status(
self._set_schedule_status(problem, error=True) 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,
)
return False return False
record_schedule_change(schedule) record_schedule_change(schedule)
self._show_schedule(current_schedule()) self._show_schedule(current_schedule())

View File

@ -18,8 +18,6 @@ from __future__ import annotations
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from diet_guard._estimator import Nutrition 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 import log_meal
from diet_guard._state_today import today_entries from diet_guard._state_today import today_entries
@ -35,18 +33,11 @@ SOURCE = "kuchnia wikinga"
def _already_logged(entries: Sequence[dict[str, object]], name: str, slot: int) -> bool: def _already_logged(entries: Sequence[dict[str, object]], name: str, slot: int) -> bool:
"""Return True when today's log already holds this dish at this slot minute. """Return True when today's log already holds this dish in this slot."""
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() wanted = name.strip().casefold()
return any( return any(
str(entry.get("desc", "")).strip().casefold() == wanted str(entry.get("desc", "")).strip().casefold() == wanted
and entry_slot_minute(entry) == slot and entry.get("slot") == slot
for entry in entries for entry in entries
) )
@ -65,7 +56,7 @@ def fill_plan(slotted: Sequence[SlottedDish]) -> list[SlottedDish]:
Returns: Returns:
The dishes to log, in the order given. The dishes to log, in the order given.
""" """
taken = satisfied_by_entries(today_entries(), current_schedule()) taken = {entry.get("slot") for entry in today_entries()}
return [item for item in slotted if item.slot not in taken] return [item for item in slotted if item.slot not in taken]
@ -104,6 +95,6 @@ def log_dishes(chosen: Sequence[SlottedDish]) -> list[str]:
log_meal(dish.name, dish_nutrition(dish), item.slot) log_meal(dish.name, dish_nutrition(dish), item.slot)
# Reflect the write locally so two identical dishes in one batch do not # Reflect the write locally so two identical dishes in one batch do not
# both land: today_entries() was read once, before the loop. # both land: today_entries() was read once, before the loop.
entries = [*entries, {"desc": dish.name, **slot_fields(item.slot)}] entries = [*entries, {"desc": dish.name, "slot": item.slot}]
written.append(dish.name) written.append(dish.name)
return written 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. last, and doubles up the earliest slots rather than dropping anything.
Integer ``//`` only, never ``round()``. That is repo convention for slot Integer ``//`` only, never ``round()``. That is repo convention for slot
arithmetic (``docs/DOCS-meal-schedule.md``): Python's banker's rounding and Dart's arithmetic (``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 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. other does not is a checkpoint that can never be satisfied.
@ -44,19 +44,18 @@ if TYPE_CHECKING:
class SlottedDish(NamedTuple): class SlottedDish(NamedTuple):
"""A dish paired with the meal-slot minute it was assigned to.""" """A dish paired with the meal-slot hour it was assigned to."""
dish: Dish dish: Dish
slot: int slot: int
def assign_slots(dishes: Sequence[Dish], slots: Sequence[int]) -> list[SlottedDish]: def assign_slots(dishes: Sequence[Dish], slots: Sequence[int]) -> list[SlottedDish]:
"""Pair each dish with a slot minute, following the provider's meal order. """Pair each dish with a slot hour, following the provider's meal order.
Args: Args:
dishes: The day's dishes, in any order (sorted here by ``priority``). dishes: The day's dishes, in any order (sorted here by ``priority``).
slots: The configured slot minutes, ascending, e.g. slots: The configured slot hours, ascending, e.g. ``(8, 12, 16, 20)``.
``(480, 720, 960, 1200)``.
Returns: Returns:
One :class:`SlottedDish` per dish, ordered by the provider's priority. One :class:`SlottedDish` per dish, ordered by the provider's priority.

View File

@ -44,19 +44,15 @@ from pydantic import BaseModel
# the names are genuinely used -- drop this and the server starts write-only. # 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_read import get_averages, get_slots, get_status, list_today
from diet_guard._mcp_server import APPENDS, logger, mcp 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._meal_schedule_store import current_schedule
from diet_guard._resolve import ManualMacros, resolve_nutrition from diet_guard._resolve import ManualMacros, resolve_nutrition
from diet_guard._slot_wire import parse_hhmm from diet_guard._slots import slot_for_log
from diet_guard._slots import day_slots, slot_for_log, slot_label
from diet_guard._state import ( from diet_guard._state import (
log_meal as record_meal, log_meal as record_meal,
) )
from diet_guard._state import now_local from diet_guard._state import now_local
from diet_guard._sync_events import publish_after_log from diet_guard._sync_events import publish_after_log
_HOURS_PER_DAY = 24
# ────────────────────────────────────────────────────────────── # ──────────────────────────────────────────────────────────────
# Gated write tool (preview unless confirm=True; NEVER allowlist this) # Gated write tool (preview unless confirm=True; NEVER allowlist this)
# ────────────────────────────────────────────────────────────── # ──────────────────────────────────────────────────────────────
@ -78,43 +74,12 @@ class Macros(BaseModel):
fat: float = 0.0 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) @mcp.tool(title="Log a meal (gated write)", annotations=APPENDS)
def log_meal( def log_meal(
description: str, description: str,
grams: float | None = None, grams: float | None = None,
macros: Macros | None = None, macros: Macros | None = None,
slot: int | str | None = None, slot: int | None = None,
*, *,
confirm: bool = False, confirm: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
@ -139,22 +104,15 @@ def log_meal(
macros: Manually-entered nutrition (``kcal`` plus optional macros: Manually-entered nutrition (``kcal`` plus optional
protein/carbs/fat). When given, lookups are skipped and the meal is protein/carbs/fat). When given, lookups are skipped and the meal is
logged exactly as specified. logged exactly as specified.
slot: The meal slot to satisfy, as ``"HH:MM"`` (e.g. ``"07:15"``) or slot: The meal-slot hour to satisfy; when omitted (or None) it falls
a legacy int hour (e.g. ``12`` for 12:00); it must be one of back to ``slot_for_log``, which clamps to a real hour rather than
today's slots (see ``get_slots``). When omitted (or None) it returning None, so the entry always satisfies some slot.
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. confirm: Set ``True`` to actually append the entry; otherwise preview.
Returns: Returns:
A preview or applied result dict; ``{"ok": false, "reason": ...}`` when A preview or applied result dict; ``{"ok": false, "reason": ...}`` when
the food cannot be resolved or the log cannot be written. 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 = ( manual_macros = (
ManualMacros( ManualMacros(
kcal=macros.kcal, kcal=macros.kcal,
@ -174,6 +132,9 @@ def log_meal(
"or Open Food Facts. Pass kcal=<number> to log it manually." "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 = { resolved = {
"kcal": nutrition.kcal, "kcal": nutrition.kcal,
"protein_g": nutrition.protein_g, "protein_g": nutrition.protein_g,

View File

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

View File

@ -1,38 +1,23 @@
"""The user's eating window and meal count, and the slot minutes they imply. """The user's eating window and meal count, and the slot hours they imply.
A schedule is three numbers -- the first meal's minute of day, the last meal's A schedule is three numbers -- the first meal hour, the last meal hour, and how
minute of day, and how many meals fall between them inclusive -- from which the many meals fall between them inclusive -- from which the intermediate
intermediate checkpoints are derived by even division and rounded to the checkpoints are derived by even division. ``MealSchedule(8, 20, 5)`` yields
15-minute grid. ``MealSchedule(480, 1200, 5)`` (08:00-20:00, five meals) ``(8, 11, 14, 17, 20)``.
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 This module is pure: no clock, no filesystem, no configuration lookup. Storage
lives in :mod:`diet_guard._meal_schedule_store`, the slot arithmetic that lives in :mod:`diet_guard._meal_schedule_store`, and the slot arithmetic that
consumes a schedule in :mod:`diet_guard._slots`, and a log entry's slot consumes a schedule lives in :mod:`diet_guard._slots`.
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 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 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 for checkpoints the other never offers -- and a slot that can never be
satisfied is a permanent lock. ``tests/fixtures/meal_schedule_vectors.json`` satisfied is a permanent lock. Two rules make that agreement checkable:
(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 * **Integer arithmetic only.** No floats and no ``round()`` anywhere in the
derivation. Python's ``round`` is banker's rounding (``round(2.5) == 2``) 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 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. 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 * **Clamp, don't reject.** Every out-of-range input is normalised to the
nearest legal schedule rather than raising, so the two languages cannot nearest legal schedule rather than raising, so the two languages cannot
disagree about which inputs are errors. disagree about which inputs are errors.
@ -41,7 +26,6 @@ test suites; three rules make that agreement checkable:
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass 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 # 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 # stay legible on a phone at the widest (all-logged) size -- see
@ -49,13 +33,8 @@ from typing import TypeGuard
MIN_MEAL_COUNT = 2 MIN_MEAL_COUNT = 2
MAX_MEAL_COUNT = 6 MAX_MEAL_COUNT = 6
MINUTES_PER_DAY = 1440 FIRST_HOUR = 0
LAST_HOUR = 23
# 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 # 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 # the day. Deliberately a constant rather than the slot spacing: it is how
@ -63,9 +42,9 @@ SLOT_GRID_MINUTES = 15
# meals you eat. Tying it to the spacing would stretch the lockout window to # 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 # midnight at four meals, contradicting the "don't trap me overnight" intent
# this cutoff exists to serve. # this cutoff exists to serve.
ENFORCEMENT_TAIL_MINUTES = 120 ENFORCEMENT_TAIL_HOURS = 2
_LAST_MINUTE = MINUTES_PER_DAY - 1 _HOURS_PER_DAY = 24
def _clamp(value: int, low: int, high: int) -> int: def _clamp(value: int, low: int, high: int) -> int:
@ -78,141 +57,78 @@ class MealSchedule:
"""An eating window and the number of meals inside it. """An eating window and the number of meals inside it.
Attributes: Attributes:
first_minute: Minute of day of the first meal, 0-1424. first: Hour of the first meal, 0-23.
last_minute: Minute of day of the last meal, at least one grid step last: Hour of the last meal, strictly after ``first``.
(15 minutes) after ``first_minute`` and at most 1439.
count: Total meals including both endpoints. count: Total meals including both endpoints.
""" """
first_minute: int first: int
last_minute: int last: int
count: int count: int
def normalized(self) -> MealSchedule: def normalized(self) -> MealSchedule:
"""Return an equivalent schedule guaranteed to satisfy the invariants. """Return an equivalent schedule guaranteed to satisfy the invariants.
Ordering matters: ``first_minute`` is clamped into the day leaving room Ordering matters: ``first`` is clamped into the day, then ``last`` is
for one grid step, then ``last_minute`` is clamped to at least one grid clamped to leave at least one hour of window, then ``count`` is clamped
step after it, then ``count`` is clamped to how many grid-spaced to the window's width. That last clamp is the load-bearing one -- see
checkpoints the window holds. That last clamp is the load-bearing one :meth:`slots`.
-- see :meth:`slots`.
Returns: Returns:
A schedule whose ``slots()`` is strictly ascending. A schedule whose ``slots()`` is strictly ascending.
""" """
first = _clamp(self.first_minute, 0, _LAST_MINUTE - SLOT_GRID_MINUTES) first = _clamp(self.first, FIRST_HOUR, LAST_HOUR - 1)
last = _clamp(self.last_minute, first + SLOT_GRID_MINUTES, _LAST_MINUTE) last = _clamp(self.last, first + 1, LAST_HOUR)
# A window of W minutes holds at most W//15 + 1 checkpoints spaced a # A window of N hours holds at most N+1 whole-hour checkpoints; asking
# grid step apart; asking for more would round two onto one mark. # for more would repeat an hour (see slots()).
capacity = (last - first) // SLOT_GRID_MINUTES + 1 count = _clamp(
count = _clamp(self.count, MIN_MEAL_COUNT, min(MAX_MEAL_COUNT, capacity)) self.count, MIN_MEAL_COUNT, min(MAX_MEAL_COUNT, last - first + 1)
)
return MealSchedule(first, last, count) return MealSchedule(first, last, count)
def slots(self) -> tuple[int, ...]: def slots(self) -> tuple[int, ...]:
"""Return the meal-slot minutes, ascending, endpoints exact. """Return the meal-slot hours, ascending, endpoints exact.
With ``span = last - first`` and ``d = count - 1``, interior slot *i* Meals are spread evenly across the window and rounded to whole hours by
is ``raw = first + (i*span + d//2) // d`` (even division, the ``d//2`` integer arithmetic: slot *i* is ``first + (i*span + d//2) // d`` where
term a round-half-up bias that keeps it float-free), then snapped to ``span = last - first`` and ``d = count - 1``. The ``d//2`` term is a
the nearest absolute quarter hour by ``(raw + 7) // 15 * 15``. The round-half-up bias applied before the division, which is what keeps
endpoints are ``first`` and ``last`` exactly -- never snapped -- so the this float-free.
eating window the user typed is always honoured, even at 07:23.
Strictly ascending, provably: :meth:`normalized` caps ``count`` so that Both endpoints land exactly on ``first`` and ``last`` by construction,
``span / d >= 15``, hence consecutive ``raw`` values differ by at least so the eating window is always honoured even when the interior spacing
15, and two integers at least 15 apart never snap onto the same grid has to round.
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``. The result is strictly ascending because :meth:`normalized` caps
That matters because slot minutes are set members, dict keys *and* ``count`` at ``last - first + 1``. Without that cap a narrow window
notification ids: a repeat silently drops a checkpoint. 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.
Returns: Returns:
The slot minutes, ascending, of length ``normalized().count``. The slot hours, ascending, of length ``normalized().count``.
""" """
schedule = self.normalized() schedule = self.normalized()
first, last = schedule.first_minute, schedule.last_minute span = schedule.last - schedule.first
span = last - first
divisions = schedule.count - 1 divisions = schedule.count - 1
interior = ( return tuple(
(first + (index * span + divisions // 2) // divisions + 7) schedule.first + (index * span + divisions // 2) // divisions
// SLOT_GRID_MINUTES for index in range(schedule.count)
* SLOT_GRID_MINUTES
for index in range(1, divisions)
) )
return (first, *interior, last)
@property @property
def enforcement_end_minute(self) -> int: def enforcement_end_hour(self) -> int:
"""Return the minute at which slot enforcement stops for the day. """Return the hour at which slot enforcement stops for the day.
Derived from the *normalised* last meal, so it always agrees with the Clamped to the end of the day: a 23:00 last meal would otherwise put
last entry of :meth:`slots`. Clamped to the end of the day: a 23:00 the cutoff at 25, making ``hour < cutoff`` vacuously true so the
last meal would otherwise put the cutoff at 1500, making enforcement window never closes and the gate can never stop firing.
``minute < cutoff`` vacuously true so the enforcement window never
closes and the gate can never stop firing.
""" """
last = self.normalized().last_minute return min(self.last + ENFORCEMENT_TAIL_HOURS, _HOURS_PER_DAY)
return min(last + ENFORCEMENT_TAIL_MINUTES, MINUTES_PER_DAY)
# The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, with the # 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 # enforcement window closing at 22:00. Still what a device uses before the
# user has ever chosen anything, so upgrading changes no behaviour. # user has ever chosen anything, so upgrading changes no behaviour.
DEFAULT_SCHEDULE = MealSchedule(first_minute=8 * 60, last_minute=20 * 60, count=4) DEFAULT_SCHEDULE = MealSchedule(first=8, last=20, 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,12 +34,7 @@ import json
import logging import logging
from diet_guard._constants import MEAL_SCHEDULE_FILE from diet_guard._constants import MEAL_SCHEDULE_FILE
from diet_guard._meal_schedule import ( from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule
DEFAULT_SCHEDULE,
MealSchedule,
schedule_from_wire,
schedule_to_wire,
)
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -70,27 +65,33 @@ class ScheduleEntry:
def entry_to_json(entry: ScheduleEntry) -> dict[str, object]: def entry_to_json(entry: ScheduleEntry) -> dict[str, object]:
"""Return the wire/disk form of one entry's value.""" """Return the wire/disk form of one entry's value."""
# ``schedule_to_wire`` keeps a whole-hour schedule byte-identical to the return {
# pre-minute ``{"f", "l", "n"}`` form, so an older build reading this file "f": entry.schedule.first,
# still sees the hours it understands. "l": entry.schedule.last,
return {**schedule_to_wire(entry.schedule), "t": entry.edited_at} "n": entry.schedule.count,
"t": entry.edited_at,
}
def entry_from_json(effective_from: str, raw: object) -> ScheduleEntry | None: def entry_from_json(effective_from: str, raw: object) -> ScheduleEntry | None:
"""Return an entry parsed from its stored value, or None if unusable. """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 Never raises: a malformed entry is skipped so one bad field from a peer
cannot take out the whole history. ``schedule_from_wire`` normalises on cannot take out the whole history.
the way in, so a peer running a future version with a wider range cannot
hand us a schedule we would derive differently.
""" """
schedule = schedule_from_wire(raw) if not isinstance(raw, dict):
if schedule is None or 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)
):
return None return None
edited_at = raw.get("t") edited_at = raw.get("t")
return ScheduleEntry( return ScheduleEntry(
effective_from=effective_from, effective_from=effective_from,
schedule=schedule, # 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(),
edited_at=edited_at if isinstance(edited_at, str) else _EPOCH_ISO, edited_at=edited_at if isinstance(edited_at, str) else _EPOCH_ISO,
) )

View File

@ -1,136 +0,0 @@
"""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,17 +7,10 @@ exhaustively unit-testable without mocking the filesystem or the wall clock.
The stateful "which slots have I actually logged?" question lives in The stateful "which slots have I actually logged?" question lives in
:mod:`diet_guard._state`; the two are composed in :mod:`diet_guard._gate`. :mod:`diet_guard._state`; the two are composed in :mod:`diet_guard._gate`.
A "slot" is the *minute of day* (``0..1439``) at which a meal checkpoint opens A "slot" is simply the integer hour at which a meal checkpoint opens (08, 12,
(480, 720, 960, 1200 -- 08:00, 12:00, 16:00, 20:00 -- by default). A slot is 16, 20 by default). A slot is *elapsed* once its hour has arrived and we are
*elapsed* once its minute has arrived and we are still inside the daily still inside the daily enforcement window; an elapsed slot with no logged meal
enforcement window; an elapsed slot with no logged meal is what makes the gate is what makes the gate fire.
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 ``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 used to be read from module constants, and a default would let a call site that
@ -27,9 +20,6 @@ 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. satisfied. Making it required lets mypy enumerate the call sites instead.
Callers resolve the value at the impure edge, mirroring how Callers resolve the value at the impure edge, mirroring how
:mod:`diet_guard._daystatus` takes an explicit budget schedule. :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 from __future__ import annotations
@ -37,27 +27,20 @@ from __future__ import annotations
from datetime import date, datetime, time from datetime import date, datetime, time
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from diet_guard._meal_schedule import MINUTES_PER_DAY
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterable
from diet_guard._meal_schedule import MealSchedule 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, ...]: def day_slots(schedule: MealSchedule) -> tuple[int, ...]:
"""Return the meal-slot minutes for a day, e.g. ``(480, 720, 960, 1200)``. """Return the meal-slot hours for a day, e.g. ``(8, 12, 16, 20)``.
Args: Args:
schedule: The eating window and meal count to derive slots from. schedule: The eating window and meal count to derive slots from.
Returns: Returns:
The slot minutes in ascending order. The slot hours in ascending order.
""" """
return schedule.slots() return schedule.slots()
@ -75,12 +58,11 @@ def within_enforcement_window(now: datetime, schedule: MealSchedule) -> bool:
Returns: Returns:
True if slot enforcement is active at ``now``. True if slot enforcement is active at ``now``.
""" """
minute = minute_of_day(now) return schedule.slots()[0] <= now.hour < schedule.enforcement_end_hour
return schedule.slots()[0] <= minute < schedule.enforcement_end_minute
def elapsed_slots(now: datetime, schedule: MealSchedule) -> tuple[int, ...]: def elapsed_slots(now: datetime, schedule: MealSchedule) -> tuple[int, ...]:
"""Return today's slots whose minute has arrived as of ``now``. """Return today's slots whose hour has arrived as of ``now``.
Empty outside the enforcement window (before the first slot, or after the Empty outside the enforcement window (before the first slot, or after the
overnight cutoff), so the caller never has to special-case the night. overnight cutoff), so the caller never has to special-case the night.
@ -90,12 +72,11 @@ def elapsed_slots(now: datetime, schedule: MealSchedule) -> tuple[int, ...]:
schedule: The schedule in force for that day. schedule: The schedule in force for that day.
Returns: Returns:
The elapsed slot minutes, ascending (possibly empty). The elapsed slot hours, ascending (possibly empty).
""" """
if not within_enforcement_window(now, schedule): if not within_enforcement_window(now, schedule):
return () return ()
minute = minute_of_day(now) return tuple(slot for slot in day_slots(schedule) if slot <= now.hour)
return tuple(slot for slot in day_slots(schedule) if slot <= minute)
def missing_slots( def missing_slots(
@ -105,12 +86,11 @@ def missing_slots(
Args: Args:
now: Reference local time. now: Reference local time.
logged: The slot minutes already covered by today's log -- normally logged: The set of slot hours already covered by today's log.
:func:`satisfied_slots` of the entries' slot minutes.
schedule: The schedule in force for that day. schedule: The schedule in force for that day.
Returns: Returns:
The unsatisfied elapsed slot minutes, ascending (empty == nothing due). The unsatisfied elapsed slot hours, ascending (empty == nothing due).
""" """
return tuple(slot for slot in elapsed_slots(now, schedule) if slot not in logged) return tuple(slot for slot in elapsed_slots(now, schedule) if slot not in logged)
@ -127,7 +107,7 @@ def current_slot(now: datetime, schedule: MealSchedule) -> int | None:
schedule: The schedule in force for that day. schedule: The schedule in force for that day.
Returns: Returns:
The latest elapsed slot minute, or None when none have elapsed yet. The latest elapsed slot hour, or None when none have elapsed yet.
""" """
elapsed = elapsed_slots(now, schedule) elapsed = elapsed_slots(now, schedule)
return elapsed[-1] if elapsed else None return elapsed[-1] if elapsed else None
@ -140,8 +120,8 @@ def slot_for_log(now: datetime, schedule: MealSchedule) -> int:
the first slot, clamp to the first slot; after the enforcement window ends, 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 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 languages must reach each answer by the *same* branch, not merely agree on
the value -- the shared fixture pins every minute edge for exactly that the value -- ``test_slots.py`` sweeps every hour of the day against several
reason. schedules for exactly that reason.
Unlike :func:`current_slot` this never returns None, which is the point: an 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 off-hours meal used to satisfy no slot at all, so eating at 07:30 or 22:30
@ -154,61 +134,39 @@ def slot_for_log(now: datetime, schedule: MealSchedule) -> int:
schedule: The schedule in force for that day. schedule: The schedule in force for that day.
Returns: Returns:
The slot minute to tag the log with. The slot hour to tag the log with.
""" """
slots = day_slots(schedule) slots = day_slots(schedule)
if minute_of_day(now) < slots[0]: if now.hour < slots[0]:
return slots[0] return slots[0]
current = current_slot(now, schedule) current = current_slot(now, schedule)
return current if current is not None else slots[-1] 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( def resolve_future_when(
date_str: str, slot_minute: int, schedule: MealSchedule, now: datetime date_str: str, hour: int, schedule: MealSchedule, now: datetime
) -> datetime: ) -> datetime:
"""Build a tz-aware datetime for a meal pre-logged against a future slot. """Build a tz-aware datetime for a meal pre-logged against a future slot.
Lets a caller (the CLI's ``--date`` flag, or the app's future-date picker) Lets a caller (the CLI's ``--date``/``--hour`` flags, or the app's future-
turn a user-picked date+slot into the ``when`` that date picker) turn a user-picked date+hour into the ``when`` that
:func:`diet_guard._state.log_meal` expects, with the same validation on :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 both platforms. Still clock-free per the module's own rule: ``now`` is
supplied by the caller rather than read here. supplied by the caller rather than read here.
Args: Args:
date_str: The chosen date as ``YYYY-MM-DD``. date_str: The chosen date as ``YYYY-MM-DD``.
slot_minute: The chosen slot; must be one of ``schedule``'s slots. hour: The chosen slot hour; must be one of ``schedule``'s slot hours.
schedule: The schedule in force, used to validate ``slot_minute``. schedule: The schedule in force, used to validate ``hour``.
now: Reference local time, used to reject a non-future date. now: Reference local time, used to reject a non-future date.
Returns: Returns:
A tz-aware datetime combining ``date_str`` and ``slot_minute``, in A tz-aware datetime combining ``date_str`` and ``hour``, in ``now``'s
``now``'s timezone. timezone.
Raises: Raises:
ValueError: ``date_str`` doesn't parse, ``slot_minute`` isn't a slot, ValueError: ``date_str`` doesn't parse, ``hour`` isn't a slot hour, or
or the resulting date isn't strictly after ``now``'s date. the resulting date isn't strictly after ``now``'s date.
""" """
try: try:
parsed_date = date.fromisoformat(date_str) parsed_date = date.fromisoformat(date_str)
@ -216,18 +174,15 @@ def resolve_future_when(
msg = f"invalid date {date_str!r}, expected YYYY-MM-DD" msg = f"invalid date {date_str!r}, expected YYYY-MM-DD"
raise ValueError(msg) from exc raise ValueError(msg) from exc
slots = day_slots(schedule) slots = day_slots(schedule)
if slot_minute not in slots: if hour not in slots:
labels = ", ".join(slot_label(slot) for slot in slots) msg = f"hour {hour} is not a meal slot; choose one of {slots}"
msg = f"{slot_label(slot_minute)} is not a meal slot; choose one of {labels}"
raise ValueError(msg) raise ValueError(msg)
if parsed_date <= now.date(): if parsed_date <= now.date():
msg = f"{date_str} is not a future date" msg = f"{date_str} is not a future date"
raise ValueError(msg) raise ValueError(msg)
clock = time(hour=slot_minute // 60, minute=slot_minute % 60) return datetime.combine(parsed_date, time(hour=hour), tzinfo=now.tzinfo)
return datetime.combine(parsed_date, clock, tzinfo=now.tzinfo)
def slot_label(minute: int) -> str: def slot_label(slot: int) -> str:
"""Return a human ``HH:MM`` label for a slot minute, e.g. ``"07:15"``.""" """Return a human ``HH:00`` label for a slot hour, e.g. ``"08:00"``."""
wrapped = minute % MINUTES_PER_DAY return f"{slot % _HOURS_PER_DAY:02d}:00"
return f"{wrapped // 60:02d}:{wrapped % 60:02d}"

View File

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

View File

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

View File

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

View File

@ -199,9 +199,6 @@ def fake_tk() -> Iterator[None]:
stack.enter_context(patch.object(module, "tk", _FAKE_TK)) 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, "ttk", _FAKE_TTK))
stack.enter_context(patch.object(_gatelock_calendar_ui, "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 yield

View File

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

View File

@ -23,7 +23,6 @@ from __future__ import annotations
__all__ = [ __all__ = [
"FakeNotebook", "FakeNotebook",
"FakeRadiobutton", "FakeRadiobutton",
"FakeSpinbox",
"FakeStyle", "FakeStyle",
"FakeWidget", "FakeWidget",
] ]
@ -182,28 +181,3 @@ class FakeStyle:
def map(self, style_name: str, **kwargs: object) -> None: def map(self, style_name: str, **kwargs: object) -> None:
self.configured.setdefault(style_name, {}).update(kwargs) 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: def test_slot_status_all_marks(self, capsys: pytest.CaptureFixture[str]) -> None:
"""The slot line shows logged / DUE / upcoming together.""" """The slot line shows logged / DUE / upcoming together."""
with ( with (
patch.object(_cli, "logged_slots_today", return_value={480}), patch.object(_cli, "logged_slots_today", return_value={8}),
patch.object(_cli, "due_slots", return_value=[720]), patch.object(_cli, "due_slots", return_value=[12]),
): ):
_cli._print_slot_status() _cli._print_slot_status()
out = capsys.readouterr().out out = capsys.readouterr().out

View File

@ -13,8 +13,6 @@ from diet_guard import _cli_log
from diet_guard._budget import write_budget from diet_guard._budget import write_budget
from diet_guard._cli import main from diet_guard._cli import main
from diet_guard._estimator import Nutrition 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 from diet_guard._state import load_log, now_local
if TYPE_CHECKING: if TYPE_CHECKING:
@ -59,32 +57,3 @@ class TestAteFutureDate:
yesterday = (now_local() - timedelta(days=1)).date().isoformat() yesterday = (now_local() - timedelta(days=1)).date().isoformat()
assert main(["ate", "x", "--date", yesterday, "--hour", "12"]) == 1 assert main(["ate", "x", "--date", yesterday, "--hour", "12"]) == 1
assert "not a future date" in capsys.readouterr().out 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.""" """At 09:00 only the 08:00 slot is due; logging it flips the decision."""
now = datetime(2026, 1, 1, 9, 0, tzinfo=UTC) now = datetime(2026, 1, 1, 9, 0, tzinfo=UTC)
assert gate_is_due(now) is True assert gate_is_due(now) is True
log_meal("oatmeal", self._nutrition(), slot=480) log_meal("oatmeal", self._nutrition(), slot=8)
assert gate_is_due(now) is False assert gate_is_due(now) is False

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -24,7 +24,6 @@ from diet_guard._gatelock_fillall import FILL_LABEL, FillAllFlow, FillHooks
from diet_guard._gatelock_kuchnia import DeliveryResult from diet_guard._gatelock_kuchnia import DeliveryResult
from diet_guard._kuchnia_parse import Dish from diet_guard._kuchnia_parse import Dish
from diet_guard._meal_schedule_store import current_schedule 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._slots import day_slots
from diet_guard._state import log_meal, now_local from diet_guard._state import log_meal, now_local
from diet_guard._state_today import today_entries from diet_guard._state_today import today_entries
@ -90,11 +89,10 @@ def delivered(*dishes: Dish) -> DeliveryResult:
def logged() -> dict[int, list[str]]: def logged() -> dict[int, list[str]]:
"""Today's on-disk log as recorded slot minute -> descriptions.""" """Today's on-disk log as slot -> descriptions."""
by_slot: dict[int, list[str]] = {} by_slot: dict[int, list[str]] = {}
for entry in today_entries(): for entry in today_entries():
slot = entry_slot_minute(entry) or 0 by_slot.setdefault(int(entry["slot"]), []).append(str(entry["desc"]))
by_slot.setdefault(slot, []).append(str(entry["desc"]))
return by_slot return by_slot
@ -106,7 +104,7 @@ def propose(h: Harness) -> None:
def test_default_schedule_precondition() -> None: def test_default_schedule_precondition() -> None:
# Every expectation below assumes the redirected (default) schedule. # Every expectation below assumes the redirected (default) schedule.
assert day_slots(current_schedule()) == (480, 720, 960, 1200) assert day_slots(current_schedule()) == (8, 12, 16, 20)
class TestFirstClick: class TestFirstClick:
@ -162,7 +160,7 @@ class TestFirstClick:
assert h.label.get() == FILL_LABEL assert h.label.get() == FILL_LABEL
def test_every_slot_already_logged(self) -> None: def test_every_slot_already_logged(self) -> None:
for slot in (480, 720, 960, 1200): for slot in (8, 12, 16, 20):
log_meal(f"mine {slot}", _nutrition(), slot) log_meal(f"mine {slot}", _nutrition(), slot)
h = Harness() h = Harness()
with fetching(delivered(*FOUR)): with fetching(delivered(*FOUR)):
@ -171,7 +169,7 @@ class TestFirstClick:
assert h.label.get() == FILL_LABEL assert h.label.get() == FILL_LABEL
def test_the_proposal_writes_nothing(self) -> None: def test_the_proposal_writes_nothing(self) -> None:
log_meal("my sandwich", _nutrition(), 720) log_meal("my sandwich", _nutrition(), 12)
h = Harness() h = Harness()
with fetching(delivered(*FOUR)): with fetching(delivered(*FOUR)):
propose(h) propose(h)
@ -180,23 +178,23 @@ class TestFirstClick:
"Will log 3 (1144 kcal): 08:00 Owsianka, 16:00 Obiad, " "Will log 3 (1144 kcal): 08:00 Owsianka, 16:00 Obiad, "
"20:00 Kolacja — click Confirm." "20:00 Kolacja — click Confirm."
) )
assert logged() == {720: ["my sandwich"]} assert logged() == {12: ["my sandwich"]}
h.on_logged.assert_not_called() h.on_logged.assert_not_called()
class TestConfirm: class TestConfirm:
def test_confirm_fills_only_the_empty_slots(self) -> None: def test_confirm_fills_only_the_empty_slots(self) -> None:
log_meal("my sandwich", _nutrition(), 720) log_meal("my sandwich", _nutrition(), 12)
h = Harness() h = Harness()
with fetching(delivered(*FOUR)) as start: with fetching(delivered(*FOUR)) as start:
propose(h) propose(h)
h.flow.click() h.flow.click()
assert start.call_count == 1 # the confirm did not refetch assert start.call_count == 1 # the confirm did not refetch
assert logged() == { assert logged() == {
480: ["Owsianka"], 8: ["Owsianka"],
720: ["my sandwich"], 12: ["my sandwich"],
960: ["Obiad"], 16: ["Obiad"],
1200: ["Kolacja"], 20: ["Kolacja"],
} }
assert h.status == "Logged 3 catering dish(es)." assert h.status == "Logged 3 catering dish(es)."
h.on_logged.assert_called_once_with() h.on_logged.assert_called_once_with()
@ -209,7 +207,7 @@ class TestConfirm:
with fetching(delivered(*five)): with fetching(delivered(*five)):
propose(h) propose(h)
h.flow.click() h.flow.click()
assert logged()[480] == ["Owsianka", "Wrap"] assert logged()[8] == ["Owsianka", "Wrap"]
assert h.status == "Logged 5 catering dish(es)." assert h.status == "Logged 5 catering dish(es)."
def test_a_meal_typed_between_the_clicks_keeps_its_slot(self) -> None: def test_a_meal_typed_between_the_clicks_keeps_its_slot(self) -> None:
@ -217,16 +215,16 @@ class TestConfirm:
with fetching(delivered(*FOUR)): with fetching(delivered(*FOUR)):
propose(h) propose(h)
assert h.label.get() == "✓ Confirm (4)" assert h.label.get() == "✓ Confirm (4)"
log_meal("toast", _nutrition(), 480) log_meal("toast", _nutrition(), 8)
h.flow.click() h.flow.click()
assert logged()[480] == ["toast"] assert logged()[8] == ["toast"]
assert h.status == "Logged 3 catering dish(es)." assert h.status == "Logged 3 catering dish(es)."
def test_every_slot_taken_between_the_clicks(self) -> None: def test_every_slot_taken_between_the_clicks(self) -> None:
h = Harness() h = Harness()
with fetching(delivered(*FOUR)): with fetching(delivered(*FOUR)):
propose(h) propose(h)
for slot in (480, 720, 960, 1200): for slot in (8, 12, 16, 20):
log_meal(f"mine {slot}", _nutrition(), slot) log_meal(f"mine {slot}", _nutrition(), slot)
h.flow.click() h.flow.click()
assert h.status == "Every slot already has a meal — nothing to fill." assert h.status == "Every slot already has a meal — nothing to fill."
@ -242,8 +240,10 @@ class TestConfirm:
with patch.object(_gatelock_fillall, "now_local", return_value=tomorrow): with patch.object(_gatelock_fillall, "now_local", return_value=tomorrow):
h.flow.click() h.flow.click()
assert start.call_count == 2 assert start.call_count == 2
refetch = (_gatelock_fillall._refresh_delivery, tomorrow.date()) assert start.call_args.args == (
assert start.call_args.args == refetch _gatelock_fillall._refresh_delivery,
tomorrow.date(),
)
assert logged() == {} assert logged() == {}
h.on_logged.assert_not_called() h.on_logged.assert_not_called()
assert h.label.get() == FILL_LABEL 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_mealflow import _UNLOCK_DELAY_MS
from diet_guard._gatelock_ui import GateCallbacks, make_vars from diet_guard._gatelock_ui import GateCallbacks, make_vars
from diet_guard._state import log_meal, now_local from diet_guard._state import log_meal, now_local
from diet_guard._state_today import logged_slots_today from diet_guard._state_today import today_entries
from diet_guard.tests._gate_fixtures import fake_tk from diet_guard.tests._gate_fixtures import fake_tk
from diet_guard.tests.conftest import _nutrition from diet_guard.tests.conftest import _nutrition
from diet_guard.tests.test_gatelock_fillall import ( 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.""" """``due_slots`` as the log on disk says, so an unlock needs a real write."""
def due() -> tuple[int, ...]: def due() -> tuple[int, ...]:
taken = logged_slots_today() taken = {entry.get("slot") for entry in today_entries()}
return tuple(slot for slot in pending if slot not in taken) return tuple(slot for slot in pending if slot not in taken)
return due return due
@ -86,29 +86,29 @@ class TestTheGateDrivesTheFlow:
def test_fill_and_confirm_unlocks_from_catering(self, gate: MealGate) -> None: 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.demo_mode = False # read once, when the flow is first built
gate._pending = [480, 720] gate._pending = [8, 12]
# Fill all also banks the dishes for one-at-a-time offering; the # Fill all also banks the dishes for one-at-a-time offering; the
# unlock line must not then call them "still delivered". # unlock line must not then call them "still delivered".
gate._delivery_pending = FOUR gate._delivery_pending = FOUR
due = _due_from_log([480, 720]) due = _due_from_log([8, 12])
with patch.object(_gatelock_delivery, "due_slots", side_effect=due): with patch.object(_gatelock_delivery, "due_slots", side_effect=due):
_fill(gate, delivered(*FOUR)) _fill(gate, delivered(*FOUR))
status = gate._vars.status.get() status = gate._vars.status.get()
assert status == "Filled from catering — all meals logged, unlocking…" assert status == "Filled from catering — all meals logged, unlocking…"
assert gate._pending == [] assert gate._pending == []
gate.root.after.assert_called_with(_UNLOCK_DELAY_MS, gate.close) gate.root.after.assert_called_with(_UNLOCK_DELAY_MS, gate.close)
assert sorted(logged()) == [480, 720, 960, 1200] assert sorted(logged()) == [8, 12, 16, 20]
assert gate._vars.fill_label.get() == FILL_LABEL assert gate._vars.fill_label.get() == FILL_LABEL
def test_a_partial_fill_advances_instead_of_unlocking(self, gate: MealGate) -> None: def test_a_partial_fill_advances_instead_of_unlocking(self, gate: MealGate) -> None:
gate.demo_mode = False gate.demo_mode = False
gate._pending = [480, 720] gate._pending = [8, 12]
due = _due_from_log([480, 720]) due = _due_from_log([8, 12])
# Two dishes spread onto 08:00 and 16:00: 12:00 is still owed. # Two dishes spread onto 08:00 and 16:00: 12:00 is still owed.
two = (dish("Owsianka", 1), dish("Obiad", 2)) two = (dish("Owsianka", 1), dish("Obiad", 2))
with patch.object(_gatelock_delivery, "due_slots", side_effect=due): with patch.object(_gatelock_delivery, "due_slots", side_effect=due):
_fill(gate, delivered(*two)) _fill(gate, delivered(*two))
assert gate._pending == [720] assert gate._pending == [12]
assert "Pulled 1 meal " in gate._vars.status.get() assert "Pulled 1 meal " in gate._vars.status.get()
assert "unlocking" not 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: def test_demo_logs_without_slot(self, gate: MealGate) -> None:
"""A demo record banks the food but tags no real slot.""" """A demo record banks the food but tags no real slot."""
gate._pending = [480] gate._pending = [8]
with patch.object(_gatelock_mealflow, "log_meal") as log: with patch.object(_gatelock_mealflow, "log_meal") as log:
gate._record("apple", _nutrition(95, 100)) gate._record("apple", _nutrition(95, 100))
assert log.call_args.args[2] is None assert log.call_args.args[2] is None
def test_last_slot_unlocks(self, gate: MealGate) -> None: def test_last_slot_unlocks(self, gate: MealGate) -> None:
"""Recording the final pending slot triggers the unlock.""" """Recording the final pending slot triggers the unlock."""
gate._pending = [480] gate._pending = [8]
with ( with (
patch.object(_gatelock_mealflow, "log_meal"), patch.object(_gatelock_mealflow, "log_meal"),
patch.object(_gatelock_mealflow, "remember_food"), patch.object(_gatelock_mealflow, "remember_food"),
@ -212,13 +212,13 @@ class TestRecord:
def test_more_slots_continue(self, gate: MealGate) -> None: def test_more_slots_continue(self, gate: MealGate) -> None:
"""With slots remaining, the form clears and prompts the next.""" """With slots remaining, the form clears and prompts the next."""
gate._pending = [480, 720] gate._pending = [8, 12]
with ( with (
patch.object(_gatelock_mealflow, "log_meal"), patch.object(_gatelock_mealflow, "log_meal"),
patch.object(_gatelock_mealflow, "remember_food"), patch.object(_gatelock_mealflow, "remember_food"),
): ):
gate._record("apple", _nutrition(95, 100)) gate._record("apple", _nutrition(95, 100))
assert gate._pending == [720] assert gate._pending == [12]
assert "next meal" in gate._vars.status.get() assert "next meal" in gate._vars.status.get()
def test_unlock_schedules_close(self, gate: MealGate) -> None: def test_unlock_schedules_close(self, gate: MealGate) -> None:

View File

@ -1,18 +1,15 @@
"""Tests for the gate History tab's meal-schedule row. """Tests for the gate History tab's meal-schedule row.
Covers :mod:`._gatelock_scheduleedit` and the row's widgets in Covers :mod:`._gatelock_scheduleedit`. The functional fake ``tk`` widgets and
:mod:`._gatelock_calendar_schedule`. The functional fake ``tk``/``ttk`` the ``gate`` fixture live in ``conftest.py``, shared with the other gate
widgets and the ``gate`` fixture live in ``conftest.py``, shared with the tests.
other gate tests.
""" """
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
import pytest from diet_guard._gatelock_scheduleedit import schedule_summary
from diet_guard._gatelock_scheduleedit import schedule_problem, schedule_summary
from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule
from diet_guard._meal_schedule_store import current_schedule, record_schedule_change from diet_guard._meal_schedule_store import current_schedule, record_schedule_change
@ -21,30 +18,21 @@ if TYPE_CHECKING:
def _type(gate: MealGate, first: str, last: str, count: str) -> None: def _type(gate: MealGate, first: str, last: str, count: str) -> None:
"""Fill the three schedule fields as the user would.""" """Fill the three schedule entries as the user would."""
gate._cal_vars.schedule.first.set(first) gate._cal_vars.schedule.first.set(first)
gate._cal_vars.schedule.last.set(last) gate._cal_vars.schedule.last.set(last)
gate._cal_vars.schedule.count.set(count) gate._cal_vars.schedule.count.set(count)
def _status(gate: MealGate) -> str:
return gate._cal_vars.schedule.status.get()
class TestScheduleSummary: class TestScheduleSummary:
"""The derived-times label.""" """The derived-times label."""
def test_lists_every_checkpoint(self) -> None: def test_lists_every_checkpoint(self) -> None:
"""The label spells out the times the schedule derives.""" """The label spells out the hours the schedule derives."""
assert schedule_summary(MealSchedule(480, 1200, 5)) == ( assert schedule_summary(MealSchedule(8, 20, 5)) == (
"08:00 11:00 14:00 17:00 20:00" "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: class TestEditToggle:
"""The Edit/Save button's two states.""" """The Edit/Save button's two states."""
@ -59,95 +47,71 @@ class TestEditToggle:
def test_second_click_persists_and_relocks(self, gate: MealGate) -> None: def test_second_click_persists_and_relocks(self, gate: MealGate) -> None:
"""Clicking Save validates, writes, and returns to read-only.""" """Clicking Save validates, writes, and returns to read-only."""
gate._on_edit_or_save_schedule() gate._on_edit_or_save_schedule()
_type(gate, "07:15", "19:00", "5") _type(gate, "8", "20", "5")
gate._on_edit_or_save_schedule() gate._on_edit_or_save_schedule()
assert not gate._cal_editing_schedule assert not gate._cal_editing_schedule
assert current_schedule() == MealSchedule(435, 1140, 5) assert current_schedule() == MealSchedule(8, 20, 5)
assert _status(gate) == "Saved." assert gate._cal_vars.schedule.status.get() == "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: def test_a_failed_save_leaves_editing_open(self, gate: MealGate) -> None:
"""A bad value can be corrected rather than silently discarded.""" """A bad value can be corrected rather than silently discarded."""
gate._on_edit_or_save_schedule() gate._on_edit_or_save_schedule()
_type(gate, "20:00", "08:00", "4") _type(gate, "20", "8", "4")
gate._on_edit_or_save_schedule() gate._on_edit_or_save_schedule()
assert gate._cal_editing_schedule assert gate._cal_editing_schedule
assert current_schedule() == DEFAULT_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: class TestValidation:
"""Rejected input, with the reason shown rather than silently clamped.""" """Rejected input, with the reason shown rather than silently clamped."""
@pytest.mark.parametrize("first", ["eight", "7:5", "24:00", "07:60", ""]) def test_rejects_non_numeric(self, gate: MealGate) -> None:
def test_rejects_a_time_that_is_not_hhmm(self, gate: MealGate, first: str) -> None: """Letters in an hour field are refused, not coerced."""
_type(gate, first, "20:00", "4") _type(gate, "eight", "20", "4")
assert not gate._save_schedule_entry() assert not gate._save_schedule_entry()
assert "HH:MM" in _status(gate) assert "whole hours" in gate._cal_vars.schedule.status.get()
def test_rejects_a_non_numeric_count(self, gate: MealGate) -> None: def test_rejects_a_backwards_window(self, gate: MealGate) -> None:
_type(gate, "08:00", "20:00", "five") """The last meal must come after the first."""
_type(gate, "20", "8", "4")
assert not gate._save_schedule_entry() assert not gate._save_schedule_entry()
assert "meals per day as a number" in _status(gate) assert "before the last" in gate._cal_vars.schedule.status.get()
@pytest.mark.parametrize( def test_rejects_an_out_of_range_hour(self, gate: MealGate) -> None:
("first", "last", "count", "reason"), """Hours outside 0-23 are refused."""
[ _type(gate, "8", "25", "4")
("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 not gate._save_schedule_entry()
assert reason in _status(gate) assert "0-23" in gate._cal_vars.schedule.status.get()
assert current_schedule() == DEFAULT_SCHEDULE
def test_the_narrowest_legal_window_is_accepted(self, gate: MealGate) -> None: def test_rejects_too_few_meals(self, gate: MealGate) -> None:
"""15 min holds two meals; 45 min holds four (one per quarter hour).""" """One meal a day is below the supported range."""
_type(gate, "08:00", "08:45", "4") _type(gate, "8", "20", "1")
assert gate._save_schedule_entry() assert not gate._save_schedule_entry()
assert current_schedule().slots() == (480, 495, 510, 525) assert "Meals per day" in gate._cal_vars.schedule.status.get()
def test_an_accepted_schedule_is_stored_unchanged(self) -> None: def test_rejects_too_many_meals(self, gate: MealGate) -> None:
"""No rule here is looser than ``normalized()``: what passes is kept.""" """More than the cap is refused."""
for first in range(0, 1440, 37): _type(gate, "8", "20", "9")
for last in range(first + 15, 1440, 53):
for count in range(2, 7): assert not gate._save_schedule_entry()
schedule = MealSchedule(first, last, count) assert "Meals per day" in gate._cal_vars.schedule.status.get()
if schedule_problem(schedule) is None:
assert schedule.normalized() == schedule 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()
class TestDisplay: class TestDisplay:
@ -155,27 +119,27 @@ class TestDisplay:
def test_shows_the_stored_schedule(self, gate: MealGate) -> None: def test_shows_the_stored_schedule(self, gate: MealGate) -> None:
"""The fields and the derived-times label reflect what is stored.""" """The fields and the derived-times label reflect what is stored."""
gate._show_schedule(MealSchedule(435, 1260, 3)) gate._show_schedule(MealSchedule(7, 21, 3))
assert gate._cal_vars.schedule.first.get() == "07:15" assert gate._cal_vars.schedule.first.get() == "7"
assert gate._cal_vars.schedule.last.get() == "21:00" assert gate._cal_vars.schedule.last.get() == "21"
assert gate._cal_vars.schedule.count.get() == "3" assert gate._cal_vars.schedule.count.get() == "3"
assert gate._cal_vars.schedule.times.get() == "07:15 14:15 21:00" assert gate._cal_vars.schedule.times.get() == "07:00 14:00 21:00"
def test_a_refresh_does_not_clobber_an_open_edit(self, gate: MealGate) -> None: def test_a_refresh_does_not_clobber_an_open_edit(self, gate: MealGate) -> None:
"""Typing survives a calendar refresh landing mid-edit.""" """Typing survives a calendar refresh landing mid-edit."""
gate._on_edit_or_save_schedule() gate._on_edit_or_save_schedule()
_type(gate, "06:00", "22:00", "6") _type(gate, "6", "22", "6")
gate._refresh_calendar() gate._refresh_calendar()
assert gate._cal_vars.schedule.first.get() == "06:00" assert gate._cal_vars.schedule.first.get() == "6"
def test_a_refresh_shows_the_stored_schedule_when_idle( def test_a_refresh_shows_the_stored_schedule_when_idle(
self, gate: MealGate self, gate: MealGate
) -> None: ) -> None:
"""Outside an edit the row tracks whatever is stored.""" """Outside an edit the row tracks whatever is stored."""
record_schedule_change(MealSchedule(540, 1140, 3)) record_schedule_change(MealSchedule(9, 19, 3))
gate._refresh_calendar() gate._refresh_calendar()
assert gate._cal_vars.schedule.first.get() == "09:00" assert gate._cal_vars.schedule.first.get() == "9"
assert gate._cal_vars.schedule.times.get() == "09:00 14:00 19: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 from __future__ import annotations
import datetime as dt import datetime
import json import json
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from unittest.mock import patch from unittest.mock import patch
@ -28,7 +28,7 @@ from diet_guard.tests._kuchnia_fakes import (
if TYPE_CHECKING: if TYPE_CHECKING:
from pathlib import Path from pathlib import Path
DAY = dt.date(2026, 8, 22) DAY = datetime.date(2026, 8, 22)
@pytest.fixture @pytest.fixture

View File

@ -40,40 +40,33 @@ def _eat(desc: str, slot: int) -> None:
class TestFillPlan: class TestFillPlan:
def test_an_empty_day_fills_every_slot(self) -> None: def test_an_empty_day_fills_every_slot(self) -> None:
plan = [_slotted("A", 480), _slotted("B", 720), _slotted("C", 1200)] plan = [_slotted("A", 8), _slotted("B", 12), _slotted("C", 20)]
assert fill_plan(plan) == plan assert fill_plan(plan) == plan
def test_a_slot_with_a_meal_keeps_it(self) -> None: def test_a_slot_with_a_meal_keeps_it(self) -> None:
_eat("apple", 720) _eat("apple", 12)
plan = fill_plan([_slotted("A", 480), _slotted("B", 720), _slotted("C", 1200)]) plan = fill_plan([_slotted("A", 8), _slotted("B", 12), _slotted("C", 20)])
assert [item.slot for item in plan] == [480, 1200] assert [item.slot for item in plan] == [8, 20]
def test_two_dishes_sharing_an_empty_slot_both_land(self) -> None: 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, # 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. # before the batch, so the second dish is not refused by the first.
plan = fill_plan([_slotted("A", 480), _slotted("B", 480)]) plan = fill_plan([_slotted("A", 8), _slotted("B", 8)])
assert log_dishes(plan) == ["A", "B"] assert log_dishes(plan) == ["A", "B"]
def test_a_full_day_fills_nothing(self) -> None: def test_a_full_day_fills_nothing(self) -> None:
for slot in (480, 720): for slot in (8, 12):
_eat("apple", slot) _eat("apple", slot)
assert fill_plan([_slotted("A", 480), _slotted("B", 720)]) == [] assert fill_plan([_slotted("A", 8), _slotted("B", 12)]) == []
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: class TestCliFill:
def test_log_skips_a_taken_slot(self) -> None: def test_log_skips_a_taken_slot(self) -> None:
# Two dishes on the default four slots spread to 08:00 and 16:00. # Two dishes on the default four slots spread to 08:00 and 16:00.
_eat("apple", 480) _eat("apple", 8)
dishes = [ dishes = [
replace(_slotted("Owsianka", 480).dish, priority=1), replace(_slotted("Owsianka", 8).dish, priority=1),
replace(_slotted("Kaszotto", 960).dish, priority=2), replace(_slotted("Kaszotto", 16).dish, priority=2),
] ]
lines: list[str] = [] lines: list[str] = []
with patch.object( with patch.object(

View File

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

View File

@ -9,7 +9,7 @@ that happens, so these assert on **call count** instead.
from __future__ import annotations from __future__ import annotations
import datetime as dt import datetime
from unittest.mock import patch from unittest.mock import patch
from diet_guard import _kuchnia_config, _kuchnia_import 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._kuchnia_spread import SlottedDish
from diet_guard._state_today import today_entries, today_total_kcal from diet_guard._state_today import today_entries, today_total_kcal
DAY = dt.date(2026, 8, 22) DAY = datetime.date(2026, 8, 22)
def _dish(name: str = "Kaszotto", kcal: float = 391.0, priority: int = 1) -> Dish: def _dish(name: str = "Kaszotto", kcal: float = 391.0, priority: int = 1) -> Dish:
@ -150,7 +150,7 @@ class TestRefreshOnce:
return_value=([_dish()], None), return_value=([_dish()], None),
) as refresh: ) as refresh:
_kuchnia_import.refresh_delivery_once(DAY) _kuchnia_import.refresh_delivery_once(DAY)
_kuchnia_import.refresh_delivery_once(DAY + dt.timedelta(days=1)) _kuchnia_import.refresh_delivery_once(DAY + datetime.timedelta(days=1))
assert refresh.call_count == 2 assert refresh.call_count == 2
def test_an_outage_does_not_suppress_the_retry(self) -> None: def test_an_outage_does_not_suppress_the_retry(self) -> None:
@ -194,8 +194,8 @@ class TestRefreshOnce:
class TestLogDishes: class TestLogDishes:
def test_logs_each_dish_into_its_slot(self) -> None: def test_logs_each_dish_into_its_slot(self) -> None:
chosen = [ chosen = [
SlottedDish(dish=_dish("A", kcal=100.0), slot=480), SlottedDish(dish=_dish("A", kcal=100.0), slot=8),
SlottedDish(dish=_dish("B", kcal=200.0), slot=720), SlottedDish(dish=_dish("B", kcal=200.0), slot=12),
] ]
assert log_dishes(chosen) == ["A", "B"] assert log_dishes(chosen) == ["A", "B"]
entries = today_entries() entries = today_entries()
@ -203,41 +203,33 @@ class TestLogDishes:
assert today_total_kcal() == 300.0 assert today_total_kcal() == 300.0
def test_records_the_provenance(self) -> None: def test_records_the_provenance(self) -> None:
log_dishes([SlottedDish(dish=_dish("A"), slot=480)]) log_dishes([SlottedDish(dish=_dish("A"), slot=8)])
(entry,) = today_entries() (entry,) = today_entries()
assert entry["source"] == "kuchnia wikinga" assert entry["source"] == "kuchnia wikinga"
def test_a_second_run_logs_nothing(self) -> None: def test_a_second_run_logs_nothing(self) -> None:
chosen = [SlottedDish(dish=_dish("A"), slot=480)] chosen = [SlottedDish(dish=_dish("A"), slot=8)]
log_dishes(chosen) log_dishes(chosen)
assert log_dishes(chosen) == [] assert log_dishes(chosen) == []
assert len(today_entries()) == 1 assert len(today_entries()) == 1
def test_the_same_dish_in_a_different_slot_is_a_separate_meal(self) -> None: def test_the_same_dish_in_a_different_slot_is_a_separate_meal(self) -> None:
log_dishes([SlottedDish(dish=_dish("A"), slot=480)]) log_dishes([SlottedDish(dish=_dish("A"), slot=8)])
assert log_dishes([SlottedDish(dish=_dish("A"), slot=720)]) == ["A"] assert log_dishes([SlottedDish(dish=_dish("A"), slot=12)]) == ["A"]
assert len(today_entries()) == 2 assert len(today_entries()) == 2
def test_duplicates_within_one_batch_land_once(self) -> None: def test_duplicates_within_one_batch_land_once(self) -> None:
# today_entries() is read once, before the loop; without reflecting the # today_entries() is read once, before the loop; without reflecting the
# writes locally both copies would be logged. # writes locally both copies would be logged.
chosen = [ chosen = [
SlottedDish(dish=_dish("A"), slot=480), SlottedDish(dish=_dish("A"), slot=8),
SlottedDish(dish=_dish("A"), slot=480), SlottedDish(dish=_dish("A"), slot=8),
] ]
assert log_dishes(chosen) == ["A"] assert log_dishes(chosen) == ["A"]
def test_matching_ignores_case_and_padding(self) -> None: def test_matching_ignores_case_and_padding(self) -> None:
log_dishes([SlottedDish(dish=_dish("Kaszotto"), slot=480)]) log_dishes([SlottedDish(dish=_dish("Kaszotto"), slot=8)])
assert log_dishes([SlottedDish(dish=_dish(" kaszotto "), slot=480)]) == [] assert log_dishes([SlottedDish(dish=_dish(" kaszotto "), slot=8)]) == []
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: def test_logging_nothing_is_not_an_error(self) -> None:
assert log_dishes([]) == [] 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 from __future__ import annotations
import datetime as dt import datetime
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -28,7 +28,7 @@ from diet_guard.tests._kuchnia_fakes import (
write_credentials, write_credentials,
) )
DAY = dt.date(2026, 8, 22) DAY = datetime.date(2026, 8, 22)
@pytest.fixture @pytest.fixture

View File

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

View File

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

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