diet-guard/app/lib/screens/calendar_screen.dart
Krzysztof kuhy Rudnicki e07284d3e1 Show weekly and monthly average intake on both devices
The calendar already said which individual days went over budget, but not
whether the week as a whole did. A run of small overages reads as four
harmless yellow squares; averaged, it is the thing that actually moves the
needle.

Three rules are load-bearing, and are documented in CLAUDE.md because getting
any of them wrong silently changes what "under budget" means:

- The denominator is logged days, not elapsed days. An unlogged day is not a
  zero-kcal day, and averaging gaps in as zeros would make a badly-tracked
  week look like the best week of the year.
- The yardstick is the mean of the per-day budgets over those same days,
  resolved through BudgetSchedule -- never today's budget, which would
  retroactively reclassify past weeks on every budget edit.
- Today is excluded. A half-logged today drags the mean far enough to flip
  the band, so every period ends at yesterday.

Band boundaries reuse the calendar's own OVER_BUDGET_YELLOW_CEILING by
import rather than by copy, so a period and its days can never disagree
about what "over" means; that constant loses its underscore to say so.

The MCP get_averages tool returns the average and the band but drops the
average budget, keeping the module's existing invariant that the budget
number never leaves this machine. The CLI, the gate and the phone all show
both, since it is hidden from the network, not from the user.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DjJqpcEsaV5WRhPXyxCThd
2026-08-09 14:59:40 +02:00

241 lines
7.4 KiB
Dart

/// Budget-adherence calendar, streaks, year-to-date tally, budget editing.
///
/// Mirrors the diet_guard gate's calendar tab (`_gatelock_calendar.py`): the
/// budget field starts read-only, defaulting to
/// [AppSettingsService.dailyKcalGoal]'s built-in 2200 kcal fallback when
/// nothing has ever been saved, and an "Edit"/"Save" toggle button unlocks
/// it for editing on the first click and validates+persists on the second.
library;
import 'dart:async';
import 'package:diet_guard_app/models/day_status.dart';
import 'package:diet_guard_app/models/period_average.dart';
import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/average_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/day_status_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/widgets/average_summary_row.dart';
import 'package:diet_guard_app/widgets/day_status_calendar.dart';
import 'package:diet_guard_app/widgets/streak_summary_row.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Screen showing the budget-adherence calendar, streaks, and budget entry.
class CalendarScreen extends StatefulWidget {
/// Creates a [CalendarScreen].
const CalendarScreen({super.key});
@override
State<CalendarScreen> createState() => _CalendarScreenState();
}
class _CalendarScreenState extends State<CalendarScreen> {
final _budgetController = TextEditingController();
DateTime _month = DateTime.now();
Map<String, DayStatus> _statusByDate = {};
int _loggingStreak = 0;
int _adherenceStreak = 0;
YtdTally _tally = const YtdTally(
loggedDays: 0,
elapsedDays: 0,
adherentDays: 0,
);
PeriodAverage _weekAverage = PeriodAverage.empty;
PeriodAverage _monthAverage = PeriodAverage.empty;
bool _loading = true;
bool _editingBudget = false;
String? _budgetStatus;
bool _budgetError = false;
@override
void initState() {
super.initState();
unawaited(_load());
}
@override
void dispose() {
_budgetController.dispose();
super.dispose();
}
/// Loads the log, recomputes status/streaks/tally, and refreshes the
/// (read-only) budget field -- unless the user is mid-edit, in which case
/// their unsaved text is left untouched.
///
/// Each past day is judged against the budget that applied *then*, so
/// changing the budget today leaves the grid, the streaks, the tally, and
/// the averages for earlier days alone.
Future<void> _load() async {
final log = await LogStorageService.instance.readLog();
if (!mounted) return;
final budget = AppSettingsService.dailyKcalGoal;
final schedule = BudgetHistoryService.schedule;
final statusByDate = statusMap(log, schedule: schedule);
final week = weeklyAverage(log, schedule: schedule);
final month = monthlyAverage(log, schedule: schedule);
setState(() {
_statusByDate = statusByDate;
_loggingStreak = loggingStreak(statusByDate);
_adherenceStreak = adherenceStreak(statusByDate);
_tally = yearToDateTally(statusByDate);
_weekAverage = week;
_monthAverage = month;
_loading = false;
if (!_editingBudget) {
_budgetController.text = budget.toString();
}
});
}
void _onPrevMonth() {
setState(() => _month = DateTime(_month.year, _month.month - 1));
}
void _onNextMonth() {
setState(() => _month = DateTime(_month.year, _month.month + 1));
}
/// Opens [HistoryScreen] pre-filtered to the tapped day.
void _onDaySelected(DateTime day) {
unawaited(
Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => HistoryScreen(
initialDateRange: DateTimeRange(start: day, end: day),
),
),
),
);
}
/// First click: unlocks the entry for typing, relabels the button "Save".
/// Second click: validates and persists; a validation failure leaves
/// editing open so the user can correct the value instead of silently
/// discarding it.
Future<void> _onEditOrSaveBudget() async {
if (!_editingBudget) {
setState(() {
_editingBudget = true;
_budgetStatus = null;
_budgetError = false;
});
return;
}
final value = int.tryParse(_budgetController.text.trim());
if (value == null) {
setState(() {
_budgetStatus = 'Enter a whole number of kcal.';
_budgetError = true;
});
return;
}
if (value <= 0) {
setState(() {
_budgetStatus = 'Budget must be a positive number.';
_budgetError = true;
});
return;
}
await AppSettingsService.instance.saveDailyKcalGoal(value);
if (!mounted) return;
setState(() {
_editingBudget = false;
_budgetStatus = 'Saved.';
_budgetError = false;
});
await _load();
}
@override
Widget build(BuildContext context) {
if (_loading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: const Text('Calendar')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_BudgetRow(
controller: _budgetController,
editing: _editingBudget,
onEditOrSave: _onEditOrSaveBudget,
),
if (_budgetStatus != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
_budgetStatus!,
style: TextStyle(
color: _budgetError ? theme.colorScheme.error : null,
),
),
),
const SizedBox(height: 12),
DayStatusCalendar(
statusByDate: _statusByDate,
month: _month,
today: DateTime.now(),
onPrevMonth: _onPrevMonth,
onNextMonth: _onNextMonth,
onDaySelected: _onDaySelected,
),
const SizedBox(height: 16),
StreakSummaryRow(
loggingStreak: _loggingStreak,
adherenceStreak: _adherenceStreak,
tally: _tally,
),
const SizedBox(height: 4),
AverageSummaryRow(week: _weekAverage, month: _monthAverage),
],
),
),
);
}
}
class _BudgetRow extends StatelessWidget {
const _BudgetRow({
required this.controller,
required this.editing,
required this.onEditOrSave,
});
final TextEditingController controller;
final bool editing;
final VoidCallback onEditOrSave;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Daily budget (kcal):'),
const SizedBox(width: 8),
SizedBox(
width: 90,
child: TextField(
controller: controller,
enabled: editing,
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
),
),
const SizedBox(width: 8),
FilledButton(
onPressed: onEditOrSave,
child: Text(editing ? 'Save' : 'Edit'),
),
],
);
}
}