diet-guard/app/lib/services/day_status_service.dart
Krzysztof kuhy Rudnicki f7f06aee53
Some checks failed
pre-commit / pre-commit (push) Has been cancelled
Tests / test (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
Remove unused features; fix reminder false alarms; share all state
Four asks, plus the fixes two review passes turned up.

Removals (all unused):
- "Repeat last meal" button, and the reward/temptation-bundling prompt it
  was the sole trigger for. Replaced with a post-log progress card showing
  kcal against budget, macros, and the adherence streak.
- The multi-item meal builder, on both the gate and the phone. The stored
  `components` field stays: nothing writes it now, but historical composite
  entries and the food bank still read it and it is part of the wire format.
- Meal photos entirely: 13 files, `imagePath`, the photo filter, the
  wrapper's /blobs/ route, image_picker, and the CAMERA permission.

Reminder false alarms had three real causes, all fixed:
- Logging never reconciled notifications, so a reminder sat on screen up to
  15 minutes after the meal was logged -- on the phone itself.
- The background check never pulled, so a PC-logged meal nagged forever
  until the app was opened. Now mirrors _cli_gate._should_lock: cheap local
  check, network only when a slot looks due, then re-check.
- Meals before 08:00 / after 22:00 were attributed to no slot at all. New
  slot_for_log/slotForLog clamps them to the first/last slot, byte-identical
  across Python and Dart. Deliberately separate from elapsed_slots, which
  would otherwise make every slot fall due at 23:00.

Budget history, so lowering the budget stops rewriting the past:
- Forward-only (effective_from, kcal) entries; each day is judged against
  the budget in force then. Verified live: setting 2000 left a 36-day
  adherence streak and the whole calendar pixel-identical.
- Rides as hist:<date> fields on the existing budget record. crdt_sync
  merges per-field over the union of field names and both devices push the
  merged log, so a device that predates the feature relays them untouched --
  no coordinated rollout, no second document.
- The seed guard tests emptiness, not file presence: _sync can write an
  empty history after merging with a pre-feature peer, and a presence check
  would then never seed again, silently reclassifying every past day.

One shared source of truth for every piece of data:
- Body weight now travels as its own `weight` CRDT field. Inside `value` it
  was collateral damage of whole-map LWW -- any phone budget edit deleted it,
  and the protein target with it.
- Both halves of the food bank sync. The curated half (foods added without
  eating them) was the last device-local state. The derived half merges with
  count as the clock, so LWW means max-count-wins; the log stays
  authoritative for membership, because a CRDT union never shrinks and a
  peer's stale copy would otherwise resurrect a deleted food permanently.
- Bank adapters honour tombstones, and Dart parses bank records defensively:
  a cast failure there is an Error, not an Exception, so one malformed
  remote record would have broken phone sync permanently.

_test_guard.py blocks any pathlib write to real user state while pytest is
in the process, whatever conftest is loaded. A throwaway test run outside
the package conftest destroyed a real GitHub token during this work; this
makes that class of accident impossible rather than merely discouraged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 16:39:52 +02:00

183 lines
6.6 KiB
Dart

/// Per-day budget-adherence status, streaks, and year-to-date tallies.
///
/// DAY STATUS SPEC (keep in sync with `diet_guard/_daystatus.py`):
///
/// * green: `total_kcal <= budget`
/// * yellow: `budget < total_kcal <= budget * kOverBudgetYellowCeiling`
/// * red: `total_kcal > budget * kOverBudgetYellowCeiling`
/// * notLogged: the day is absent from the log entirely (no valid,
/// non-tombstoned entries).
/// * ordering, worst to best: notLogged > red > yellow > green.
/// * the logging streak breaks on a not-logged day.
/// * the adherence streak breaks on a red or a not-logged day; yellow and
/// green both keep it alive.
///
/// Every function here is a pure function of an explicit `log`/`statusMap`
/// argument (never reaching into on-disk state itself), so the boundary
/// matrix above is trivially testable with synthetic data.
library;
import 'package:diet_guard_app/models/day_status.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/services/budget_schedule.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
/// The multiplier defining the top of the "yellow" band above budget: a 20%
/// margin, mirroring `diet_guard._constants.BUDGET_WARN_FRACTION` (0.80)'s
/// 20% margin below 100% on the "approaching limit" side, so the two bands
/// are symmetric around the budget line.
const double kOverBudgetYellowCeiling = 1.20;
const Set<DayStatus> _loggedStatuses = {
DayStatus.green,
DayStatus.yellow,
DayStatus.red,
};
const Set<DayStatus> _adherentStatuses = {DayStatus.green, DayStatus.yellow};
/// Returns the summed kcal across [entries].
///
/// Shared by [dayTotalKcal] and `history_screen.dart`'s day-header total, so
/// the "sum a day's entries" logic exists in exactly one place regardless of
/// whether the caller already has a day's entries grouped or is looking one
/// up by date key.
double sumKcal(Iterable<FoodEntry> entries) {
var total = 0.0;
for (final entry in entries) {
total += entry.kcal;
}
return total;
}
/// Returns the summed protein/carbs/fat across [entries].
///
/// The macro counterpart to [sumKcal], so the three folds live in one place
/// rather than being re-inlined per caller.
({double proteinG, double carbsG, double fatG}) sumMacros(
Iterable<FoodEntry> entries,
) {
var proteinG = 0.0;
var carbsG = 0.0;
var fatG = 0.0;
for (final entry in entries) {
proteinG += entry.proteinG;
carbsG += entry.carbsG;
fatG += entry.fatG;
}
return (proteinG: proteinG, carbsG: carbsG, fatG: fatG);
}
/// Returns [log]'s entries for [day] with tombstoned (deleted) ones
/// removed -- `readLog()` returns the raw log including tombstones, so
/// every consumer that classifies a day (rather than just displaying an
/// already-filtered list) must drop them here first.
Iterable<FoodEntry> _validEntriesForDay(DayLog log, String day) =>
(log[day] ?? const []).where((entry) => !entry.deleted);
/// Returns the summed kcal for one `YYYY-MM-DD` key in [log], excluding
/// tombstoned entries.
double dayTotalKcal(DayLog log, String day) =>
sumKcal(_validEntriesForDay(log, day));
/// Classifies one day's budget adherence.
///
/// A day with no valid, non-tombstoned entries is [DayStatus.notLogged] --
/// a day whose only entries were later deleted must not read as green at
/// zero kcal.
DayStatus dayStatus(DayLog log, String day, int budget) {
final entries = _validEntriesForDay(log, day).toList();
if (entries.isEmpty) return DayStatus.notLogged;
final total = sumKcal(entries);
if (total <= budget) return DayStatus.green;
if (total <= budget * kOverBudgetYellowCeiling) return DayStatus.yellow;
return DayStatus.red;
}
/// Returns a [DayStatus] for every date key present in [log].
///
/// Each day is judged against the budget that applied *on that day*, so a
/// later budget change leaves earlier days classified exactly as before.
///
/// Days with no log entries are simply absent from the result; a caller
/// rendering a full calendar treats a missing key as [DayStatus.notLogged].
Map<String, DayStatus> statusMap(
DayLog log, {
required BudgetSchedule schedule,
}) {
return {
for (final day in log.keys) day: dayStatus(log, day, schedule.forDay(day)),
};
}
DateTime _dateOnly(DateTime d) => DateTime(d.year, d.month, d.day);
String _dateKey(DateTime d) {
final y = d.year.toString().padLeft(4, '0');
final m = d.month.toString().padLeft(2, '0');
final day = d.day.toString().padLeft(2, '0');
return '$y-$m-$day';
}
int _streak(
Map<String, DayStatus> statusMap,
Set<DayStatus> keeps, {
DateTime? today,
}) {
var day = _dateOnly(today ?? DateTime.now());
if (statusMap[_dateKey(day)] == null) {
day = day.subtract(const Duration(days: 1));
}
var count = 0;
while (keeps.contains(statusMap[_dateKey(day)])) {
count++;
day = day.subtract(const Duration(days: 1));
}
return count;
}
/// Returns the consecutive-day logging streak ending at [today].
///
/// A [today] absent from [statusMap] (not yet logged) is skipped rather
/// than treated as a break, so the streak does not appear broken every
/// morning before the user has eaten; counting resumes from yesterday in
/// that case. Any other day missing from [statusMap] ends the streak.
int loggingStreak(Map<String, DayStatus> statusMap, {DateTime? today}) =>
_streak(statusMap, _loggedStatuses, today: today);
/// Returns the consecutive-day budget-adherence streak ending at [today].
///
/// Breaks on a red or not-logged day; green and yellow days both keep it
/// alive ("not too aggressively crossed").
int adherenceStreak(Map<String, DayStatus> statusMap, {DateTime? today}) =>
_streak(statusMap, _adherentStatuses, today: today);
int _dayOfYear(DateTime d) {
final start = DateTime.utc(d.year);
final day = DateTime.utc(d.year, d.month, d.day);
return day.difference(start).inDays + 1;
}
/// Returns this year's logged/elapsed/adherent day counts.
///
/// [today] is the reference date; defaults to the real current date.
/// [elapsedDays] is inclusive of [today].
YtdTally yearToDateTally(Map<String, DayStatus> statusMap, {DateTime? today}) {
final ref = _dateOnly(today ?? DateTime.now());
final elapsedDays = _dayOfYear(ref);
var loggedDays = 0;
var adherentDays = 0;
for (final mapEntry in statusMap.entries) {
if (mapEntry.value == DayStatus.notLogged) continue;
final day = DateTime.parse(mapEntry.key);
if (day.year != ref.year || day.isAfter(ref)) continue;
loggedDays++;
if (_adherentStatuses.contains(mapEntry.value)) adherentDays++;
}
return YtdTally(
loggedDays: loggedDays,
elapsedDays: elapsedDays,
adherentDays: adherentDays,
);
}