mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-27 09:49:11 +01:00
Compare commits
18 Commits
7a491d9d91
...
5125a98980
| Author | SHA1 | Date | |
|---|---|---|---|
| 5125a98980 | |||
| 499882b1de | |||
| c77e7d9acf | |||
| 3c67cf8c9c | |||
| c0ed6154ac | |||
| cc78dd383b | |||
| 3e51e614b1 | |||
| df5e1272f1 | |||
| af461d3157 | |||
| 8f2d1011c7 | |||
| e8f0ecaae1 | |||
| 7cb09a5b85 | |||
| 895a87cf86 | |||
| 38d66a8492 | |||
| 1e201acbdc | |||
| fef140d970 | |||
| 17a2c62f26 | |||
| c7538f691b |
33
.github/workflows/file-length.yml
vendored
Normal file
33
.github/workflows/file-length.yml
vendored
Normal file
@ -0,0 +1,33 @@
|
||||
name: file-length
|
||||
|
||||
# The 250-line cap, enforced on push as well as at commit time. The local
|
||||
# pre-commit hook can be skipped (a fresh clone that never ran `pre-commit
|
||||
# install` has no hooks at all), so the cap needs a second gate that no one
|
||||
# can forget to install.
|
||||
#
|
||||
# Deliberately a SEPARATE workflow from release-apk.yml: a file that grew too
|
||||
# long should fail lint, not block publishing an APK.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
file-length:
|
||||
name: file length <= 250 lines
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# The gate and its exemption list live in the shared utils repo so every
|
||||
# repo enforces the same cap. Checking it out beats vendoring a copy
|
||||
# here, which is exactly how a gate and a survey start disagreeing.
|
||||
- name: Check out the shared gate
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: kuhyx/utils
|
||||
path: .utils
|
||||
|
||||
- name: Enforce the cap
|
||||
run: bash .utils/scripts/check_file_length.sh --all
|
||||
14
.github/workflows/pre-commit.yml
vendored
14
.github/workflows/pre-commit.yml
vendored
@ -16,4 +16,18 @@ jobs:
|
||||
python-version: "3.12"
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt
|
||||
|
||||
# The file-length hook delegates to the shared gate in kuhyx/utils, which
|
||||
# a runner does not have at $HOME/utils. Check it out and point the shim
|
||||
# at it via UTILS_ROOT, or `pre-commit run --all-files` fails on a
|
||||
# missing checker rather than on anything in this repo. `.utils` is in
|
||||
# the gate's own EXCLUDED_DIRS, so it does not lint itself.
|
||||
- name: Check out the shared gate
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: kuhyx/utils
|
||||
path: .utils
|
||||
|
||||
- uses: pre-commit/action@v3.0.1
|
||||
env:
|
||||
UTILS_ROOT: ${{ github.workspace }}/.utils
|
||||
|
||||
@ -26,9 +26,9 @@ repos:
|
||||
- id: debug-statements
|
||||
- id: name-tests-test
|
||||
args: [--pytest-test-first]
|
||||
# Shared fake widgets, not a test module. Split out of conftest.py only
|
||||
# because that file passed the 500-line cap.
|
||||
exclude: ^diet_guard/tests/_(tk_fakes|gate_layout_probe|gate_keyboard_probe)\.py$
|
||||
# Shared fakes and fixtures, not test modules. Split out of conftest.py
|
||||
# and test_sync.py only because those files passed the 250-line cap.
|
||||
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes)\.py$
|
||||
- id: check-ast
|
||||
- id: mixed-line-ending
|
||||
args: [--fix=lf]
|
||||
@ -170,8 +170,28 @@ repos:
|
||||
# shebang (SC2148) and its variables are read by makepkg rather than by
|
||||
# the file itself (SC2034). namcap is what actually lints these.
|
||||
exclude: '^packaging/aur/PKGBUILD$'
|
||||
- id: max-file-length
|
||||
name: Max file length (500 lines)
|
||||
entry: python3 scripts/check_file_length.py
|
||||
# The shared 250-line cap. Checks only the files in the commit, so an
|
||||
# unrelated commit never breaks; exits 1 rather than warning. No
|
||||
# baseline and no allowlist -- those are suppressions. The exemption
|
||||
# list (generated/vendored/data files) lives with the checker in
|
||||
# ~/utils/file_length/config.py so the gate and the survey cannot
|
||||
# disagree.
|
||||
#
|
||||
# Deliberately unfiltered: no types_or and no files. The cap applies to
|
||||
# Dart and prose too, and a type filter here is what would silently
|
||||
# exempt the whole Flutter app and every .md.
|
||||
- id: file-length
|
||||
name: file length <= 250 lines
|
||||
entry: scripts/check_file_length.sh
|
||||
language: system
|
||||
types_or: [python, shell]
|
||||
|
||||
# unittest.mock.patch fails OPEN: once a refactor moves a name, a patch
|
||||
# target that still imports redirects nothing, the test passes, and the
|
||||
# suite writes to the real ~/.local/share/diet_guard. This resolves every
|
||||
# patch target statically so a stale path fails the commit instead.
|
||||
- id: patch-targets
|
||||
name: test patch targets resolve
|
||||
entry: python3 scripts/check_patch_targets.py
|
||||
language: system
|
||||
pass_filenames: false
|
||||
files: ^diet_guard/
|
||||
|
||||
44
app/lib/desktop/content_types.dart
Normal file
44
app/lib/desktop/content_types.dart
Normal file
@ -0,0 +1,44 @@
|
||||
/// Content types for the files the desktop wrapper serves.
|
||||
///
|
||||
/// Split out of `wrapper_server.dart` for file size. A pure function of the
|
||||
/// path with no server state, so it lives as a plain sibling library rather
|
||||
/// than a `part`.
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// Content type for [filePath].
|
||||
///
|
||||
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
|
||||
/// served as anything but `application/wasm`, and the app then renders
|
||||
/// nothing at all.
|
||||
ContentType contentTypeFor(String filePath) {
|
||||
switch (p.extension(filePath).toLowerCase()) {
|
||||
case '.html':
|
||||
return ContentType.html;
|
||||
case '.js' || '.mjs':
|
||||
return ContentType('text', 'javascript', charset: 'utf-8');
|
||||
case '.json':
|
||||
return ContentType.json;
|
||||
case '.wasm':
|
||||
return ContentType('application', 'wasm');
|
||||
case '.css':
|
||||
return ContentType('text', 'css', charset: 'utf-8');
|
||||
case '.png':
|
||||
return ContentType('image', 'png');
|
||||
case '.jpg' || '.jpeg':
|
||||
return ContentType('image', 'jpeg');
|
||||
case '.svg':
|
||||
return ContentType('image', 'svg+xml');
|
||||
case '.ttf':
|
||||
return ContentType('font', 'ttf');
|
||||
case '.otf':
|
||||
return ContentType('font', 'otf');
|
||||
case '.woff2':
|
||||
return ContentType('font', 'woff2');
|
||||
default:
|
||||
return ContentType.binary;
|
||||
}
|
||||
}
|
||||
@ -23,6 +23,7 @@ import 'dart:io';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
|
||||
import 'package:diet_guard_app/desktop/content_types.dart' as content_types;
|
||||
import 'package:diet_guard_app/desktop/github_proxy.dart';
|
||||
import 'package:diet_guard_app/services/desktop_wrapper.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
@ -218,37 +219,10 @@ class WrapperServer {
|
||||
await request.response.addStream(file.openRead());
|
||||
}
|
||||
|
||||
/// Content type for [filePath].
|
||||
/// Content type for [filePath]. See `content_types.dart`.
|
||||
///
|
||||
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
|
||||
/// served as anything but `application/wasm`, and the app then renders
|
||||
/// nothing at all.
|
||||
static ContentType contentTypeFor(String filePath) {
|
||||
switch (p.extension(filePath).toLowerCase()) {
|
||||
case '.html':
|
||||
return ContentType.html;
|
||||
case '.js' || '.mjs':
|
||||
return ContentType('text', 'javascript', charset: 'utf-8');
|
||||
case '.json':
|
||||
return ContentType.json;
|
||||
case '.wasm':
|
||||
return ContentType('application', 'wasm');
|
||||
case '.css':
|
||||
return ContentType('text', 'css', charset: 'utf-8');
|
||||
case '.png':
|
||||
return ContentType('image', 'png');
|
||||
case '.jpg' || '.jpeg':
|
||||
return ContentType('image', 'jpeg');
|
||||
case '.svg':
|
||||
return ContentType('image', 'svg+xml');
|
||||
case '.ttf':
|
||||
return ContentType('font', 'ttf');
|
||||
case '.otf':
|
||||
return ContentType('font', 'otf');
|
||||
case '.woff2':
|
||||
return ContentType('font', 'woff2');
|
||||
default:
|
||||
return ContentType.binary;
|
||||
}
|
||||
}
|
||||
/// Kept as a static forwarder so callers and tests that reach for
|
||||
/// `WrapperServer.contentTypeFor` keep working after the split.
|
||||
static ContentType contentTypeFor(String filePath) =>
|
||||
content_types.contentTypeFor(filePath);
|
||||
}
|
||||
|
||||
@ -1,164 +1,22 @@
|
||||
/// Food bank browser: lists every entry across the log-derived and manual
|
||||
/// banks with filtering, sorting, and the ability to add new manual entries.
|
||||
///
|
||||
/// The filter model, the filter sheet and the add-entry dialog live under
|
||||
/// `lib/widgets/food_bank/` (split for the repo's 250-line cap); this file is
|
||||
/// the screen that wires them together.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/widgets/food_bank/fb_add_entry_dialog.dart';
|
||||
import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
|
||||
import 'package:diet_guard_app/widgets/food_bank/fb_filter_sheet.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filter / sort state
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Sort field for the food bank list.
|
||||
enum FbSortField {
|
||||
/// Sort alphabetically by name.
|
||||
name,
|
||||
|
||||
/// Sort by calories.
|
||||
kcal,
|
||||
|
||||
/// Sort by protein (g).
|
||||
protein,
|
||||
|
||||
/// Sort by carbohydrates (g).
|
||||
carbs,
|
||||
|
||||
/// Sort by fat (g).
|
||||
fat,
|
||||
|
||||
/// Sort by usage count (most-used first by default).
|
||||
count,
|
||||
}
|
||||
|
||||
/// Active filter criteria for the food bank list.
|
||||
class FbFilter {
|
||||
/// Creates a [FbFilter] with the given criteria.
|
||||
FbFilter({
|
||||
this.nameQuery = '',
|
||||
this.minKcal,
|
||||
this.maxKcal,
|
||||
this.minProtein,
|
||||
this.maxProtein,
|
||||
this.minCarbs,
|
||||
this.maxCarbs,
|
||||
this.minFat,
|
||||
this.maxFat,
|
||||
});
|
||||
|
||||
/// Substring match on the food name.
|
||||
String nameQuery;
|
||||
|
||||
/// Minimum kcal.
|
||||
double? minKcal;
|
||||
|
||||
/// Maximum kcal.
|
||||
double? maxKcal;
|
||||
|
||||
/// Minimum protein (g).
|
||||
double? minProtein;
|
||||
|
||||
/// Maximum protein (g).
|
||||
double? maxProtein;
|
||||
|
||||
/// Minimum carbs (g).
|
||||
double? minCarbs;
|
||||
|
||||
/// Maximum carbs (g).
|
||||
double? maxCarbs;
|
||||
|
||||
/// Minimum fat (g).
|
||||
double? minFat;
|
||||
|
||||
/// Maximum fat (g).
|
||||
double? maxFat;
|
||||
|
||||
/// True when any criterion is set.
|
||||
bool get isActive =>
|
||||
nameQuery.isNotEmpty ||
|
||||
minKcal != null ||
|
||||
maxKcal != null ||
|
||||
minProtein != null ||
|
||||
maxProtein != null ||
|
||||
minCarbs != null ||
|
||||
maxCarbs != null ||
|
||||
minFat != null ||
|
||||
maxFat != null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pure filter / sort helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Filters and sorts [entries] by [filter] and [sortField]/[ascending].
|
||||
///
|
||||
/// Exposed as a top-level function for unit tests.
|
||||
List<FoodBankRecord> applyFbFilter(
|
||||
List<FoodBankRecord> entries,
|
||||
FbFilter filter,
|
||||
FbSortField sortField, {
|
||||
required bool ascending,
|
||||
}) {
|
||||
var result = [...entries];
|
||||
if (filter.nameQuery.isNotEmpty) {
|
||||
final q = filter.nameQuery.toLowerCase();
|
||||
result = result.where((e) => e.desc.toLowerCase().contains(q)).toList();
|
||||
}
|
||||
if (filter.minKcal != null) {
|
||||
result = result.where((e) => e.kcal >= filter.minKcal!).toList();
|
||||
}
|
||||
if (filter.maxKcal != null) {
|
||||
result = result.where((e) => e.kcal <= filter.maxKcal!).toList();
|
||||
}
|
||||
if (filter.minProtein != null) {
|
||||
result = result.where((e) => e.proteinG >= filter.minProtein!).toList();
|
||||
}
|
||||
if (filter.maxProtein != null) {
|
||||
result = result.where((e) => e.proteinG <= filter.maxProtein!).toList();
|
||||
}
|
||||
if (filter.minCarbs != null) {
|
||||
result = result.where((e) => e.carbsG >= filter.minCarbs!).toList();
|
||||
}
|
||||
if (filter.maxCarbs != null) {
|
||||
result = result.where((e) => e.carbsG <= filter.maxCarbs!).toList();
|
||||
}
|
||||
if (filter.minFat != null) {
|
||||
result = result.where((e) => e.fatG >= filter.minFat!).toList();
|
||||
}
|
||||
if (filter.maxFat != null) {
|
||||
result = result.where((e) => e.fatG <= filter.maxFat!).toList();
|
||||
}
|
||||
|
||||
result.sort((a, b) {
|
||||
int cmp;
|
||||
switch (sortField) {
|
||||
case FbSortField.name:
|
||||
cmp = a.desc.compareTo(b.desc);
|
||||
case FbSortField.kcal:
|
||||
cmp = a.kcal.compareTo(b.kcal);
|
||||
case FbSortField.protein:
|
||||
cmp = a.proteinG.compareTo(b.proteinG);
|
||||
case FbSortField.carbs:
|
||||
cmp = a.carbsG.compareTo(b.carbsG);
|
||||
case FbSortField.fat:
|
||||
cmp = a.fatG.compareTo(b.fatG);
|
||||
case FbSortField.count:
|
||||
cmp = a.count.compareTo(b.count);
|
||||
}
|
||||
return ascending ? cmp : -cmp;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Screen
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Lists all food bank entries (log-derived + manual) with filtering/sorting
|
||||
/// and a FAB for adding new manual entries.
|
||||
/// Browses every banked food -- log-derived and manually curated -- with
|
||||
/// filtering, sorting, and an add-entry dialog.
|
||||
class FoodBankScreen extends StatefulWidget {
|
||||
/// Creates a [FoodBankScreen].
|
||||
const FoodBankScreen({super.key});
|
||||
@ -235,7 +93,7 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
||||
isScrollControlled: true,
|
||||
useSafeArea: true,
|
||||
builder: (ctx) => StatefulBuilder(
|
||||
builder: (ctx, setSheet) => _FbFilterSheet(
|
||||
builder: (ctx, setSheet) => FbFilterSheet(
|
||||
filter: draft,
|
||||
sortField: draftSort,
|
||||
ascending: draftAsc,
|
||||
@ -274,7 +132,7 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
||||
Future<void> _openAddDialog() async {
|
||||
final result = await showDialog<FoodBankRecord>(
|
||||
context: context,
|
||||
builder: (_) => const _AddEntryDialog(),
|
||||
builder: (_) => const AddEntryDialog(),
|
||||
);
|
||||
if (result == null) return;
|
||||
await FoodBankService.instance.addManualEntry(result);
|
||||
@ -328,7 +186,7 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
||||
)
|
||||
: ListView.builder(
|
||||
itemCount: _displayed.length,
|
||||
itemBuilder: (context, i) => _RecordTile(_displayed[i]),
|
||||
itemBuilder: (context, i) => RecordTile(_displayed[i]),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: _openAddDialog,
|
||||
@ -343,8 +201,12 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
||||
// Record tile
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class _RecordTile extends StatelessWidget {
|
||||
const _RecordTile(this.record);
|
||||
/// One banked food: its name, macros, and how often it has been logged.
|
||||
class RecordTile extends StatelessWidget {
|
||||
/// Creates a [RecordTile] for [record].
|
||||
const RecordTile(this.record, {super.key});
|
||||
|
||||
/// The banked record this tile renders.
|
||||
final FoodBankRecord record;
|
||||
|
||||
@override
|
||||
@ -374,339 +236,3 @@ class _RecordTile extends StatelessWidget {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filter sheet
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class _FbFilterSheet extends StatelessWidget {
|
||||
const _FbFilterSheet({
|
||||
required this.filter,
|
||||
required this.sortField,
|
||||
required this.ascending,
|
||||
required this.maxKcal,
|
||||
required this.maxProtein,
|
||||
required this.maxCarbs,
|
||||
required this.maxFat,
|
||||
required this.onFilterChanged,
|
||||
required this.onSortChanged,
|
||||
required this.onApply,
|
||||
required this.onClear,
|
||||
});
|
||||
|
||||
final FbFilter filter;
|
||||
final FbSortField sortField;
|
||||
final bool ascending;
|
||||
final double maxKcal;
|
||||
final double maxProtein;
|
||||
final double maxCarbs;
|
||||
final double maxFat;
|
||||
final void Function(FbFilter) onFilterChanged;
|
||||
final void Function({required FbSortField field, required bool asc})
|
||||
onSortChanged;
|
||||
final VoidCallback onApply;
|
||||
final VoidCallback onClear;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DraggableScrollableSheet(
|
||||
initialChildSize: 0.85,
|
||||
minChildSize: 0.5,
|
||||
maxChildSize: 0.95,
|
||||
builder: (context, scroll) => Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Filter & Sort',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: onClear,
|
||||
child: const Text('Clear all'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
controller: scroll,
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
TextField(
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Search by name',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
isDense: true,
|
||||
),
|
||||
controller: TextEditingController(text: filter.nameQuery)
|
||||
..selection = TextSelection.collapsed(
|
||||
offset: filter.nameQuery.length,
|
||||
),
|
||||
onChanged: (v) {
|
||||
filter.nameQuery = v;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (maxKcal > 0) ...[
|
||||
Text(
|
||||
'Kcal range',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
RangeSlider(
|
||||
max: maxKcal,
|
||||
values: RangeValues(
|
||||
filter.minKcal ?? 0,
|
||||
filter.maxKcal ?? maxKcal,
|
||||
),
|
||||
labels: RangeLabels(
|
||||
(filter.minKcal ?? 0).toStringAsFixed(0),
|
||||
(filter.maxKcal ?? maxKcal).toStringAsFixed(0),
|
||||
),
|
||||
onChanged: (v) {
|
||||
filter.minKcal = v.start > 0 ? v.start : null;
|
||||
filter.maxKcal = v.end < maxKcal ? v.end : null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
if (maxProtein > 0) ...[
|
||||
Text(
|
||||
'Protein range (g)',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
RangeSlider(
|
||||
max: maxProtein,
|
||||
values: RangeValues(
|
||||
filter.minProtein ?? 0,
|
||||
filter.maxProtein ?? maxProtein,
|
||||
),
|
||||
labels: RangeLabels(
|
||||
(filter.minProtein ?? 0).toStringAsFixed(0),
|
||||
(filter.maxProtein ?? maxProtein).toStringAsFixed(0),
|
||||
),
|
||||
onChanged: (v) {
|
||||
filter.minProtein = v.start > 0 ? v.start : null;
|
||||
filter.maxProtein = v.end < maxProtein ? v.end : null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
if (maxCarbs > 0) ...[
|
||||
Text(
|
||||
'Carbs range (g)',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
RangeSlider(
|
||||
max: maxCarbs,
|
||||
values: RangeValues(
|
||||
filter.minCarbs ?? 0,
|
||||
filter.maxCarbs ?? maxCarbs,
|
||||
),
|
||||
labels: RangeLabels(
|
||||
(filter.minCarbs ?? 0).toStringAsFixed(0),
|
||||
(filter.maxCarbs ?? maxCarbs).toStringAsFixed(0),
|
||||
),
|
||||
onChanged: (v) {
|
||||
filter.minCarbs = v.start > 0 ? v.start : null;
|
||||
filter.maxCarbs = v.end < maxCarbs ? v.end : null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
if (maxFat > 0) ...[
|
||||
Text(
|
||||
'Fat range (g)',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
RangeSlider(
|
||||
max: maxFat,
|
||||
values: RangeValues(
|
||||
filter.minFat ?? 0,
|
||||
filter.maxFat ?? maxFat,
|
||||
),
|
||||
labels: RangeLabels(
|
||||
(filter.minFat ?? 0).toStringAsFixed(0),
|
||||
(filter.maxFat ?? maxFat).toStringAsFixed(0),
|
||||
),
|
||||
onChanged: (v) {
|
||||
filter.minFat = v.start > 0 ? v.start : null;
|
||||
filter.maxFat = v.end < maxFat ? v.end : null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
Text(
|
||||
'Sort by',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: DropdownButton<FbSortField>(
|
||||
isExpanded: true,
|
||||
value: sortField,
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.count,
|
||||
child: Text('Usage count'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.name,
|
||||
child: Text('Name'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.kcal,
|
||||
child: Text('Kcal'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.protein,
|
||||
child: Text('Protein'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.carbs,
|
||||
child: Text('Carbs'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.fat,
|
||||
child: Text('Fat'),
|
||||
),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v != null) {
|
||||
onSortChanged(field: v, asc: ascending);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
ascending ? Icons.arrow_upward : Icons.arrow_downward,
|
||||
),
|
||||
tooltip: ascending ? 'Ascending' : 'Descending',
|
||||
onPressed: () =>
|
||||
onSortChanged(field: sortField, asc: !ascending),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: onApply,
|
||||
child: const Text('Apply'),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Add entry dialog
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class _AddEntryDialog extends StatefulWidget {
|
||||
const _AddEntryDialog();
|
||||
|
||||
@override
|
||||
State<_AddEntryDialog> createState() => _AddEntryDialogState();
|
||||
}
|
||||
|
||||
class _AddEntryDialogState extends State<_AddEntryDialog> {
|
||||
final _name = TextEditingController();
|
||||
final _grams = TextEditingController(text: '100');
|
||||
final _kcal = TextEditingController();
|
||||
final _protein = TextEditingController();
|
||||
final _carbs = TextEditingController();
|
||||
final _fat = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_name.dispose();
|
||||
_grams.dispose();
|
||||
_kcal.dispose();
|
||||
_protein.dispose();
|
||||
_carbs.dispose();
|
||||
_fat.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _save() {
|
||||
final name = _name.text.trim();
|
||||
if (name.isEmpty) return;
|
||||
Navigator.of(context).pop(
|
||||
FoodBankRecord(
|
||||
desc: name,
|
||||
kcal: double.tryParse(_kcal.text) ?? 0,
|
||||
proteinG: double.tryParse(_protein.text) ?? 0,
|
||||
carbsG: double.tryParse(_carbs.text) ?? 0,
|
||||
fatG: double.tryParse(_fat.text) ?? 0,
|
||||
grams: double.tryParse(_grams.text) ?? 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _field(String label, TextEditingController ctrl) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: TextField(
|
||||
controller: ctrl,
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
decoration: InputDecoration(labelText: label, isDense: true),
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Add to food bank'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: TextField(
|
||||
controller: _name,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Name',
|
||||
isDense: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
_field('Reference grams', _grams),
|
||||
_field('Kcal', _kcal),
|
||||
_field('Protein (g)', _protein),
|
||||
_field('Carbs (g)', _carbs),
|
||||
_field('Fat (g)', _fat),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: _save,
|
||||
child: const Text('Save to bank'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
83
app/lib/screens/github_client_id_dialog.dart
Normal file
83
app/lib/screens/github_client_id_dialog.dart
Normal file
@ -0,0 +1,83 @@
|
||||
// The "paste your OAuth client id" dialog shown before the device flow.
|
||||
//
|
||||
// Split out of `github_mirror_screen.dart` for the repo's 250-line cap. A
|
||||
// `part` so the class can stay library-private: it is an implementation
|
||||
// detail of that screen and nothing else may construct it.
|
||||
|
||||
part of 'github_mirror_screen.dart';
|
||||
|
||||
/// Dialog shown when "Connect GitHub" is tapped with no OAuth App client id
|
||||
/// configured yet. Explains what it is, how to get one, and lets the user
|
||||
/// paste it in directly — rather than leaving them to discover a buried
|
||||
/// field on their own. Pops the trimmed client id, or null if cancelled.
|
||||
class _ClientIdSetupDialog extends StatefulWidget {
|
||||
const _ClientIdSetupDialog();
|
||||
|
||||
@override
|
||||
State<_ClientIdSetupDialog> createState() => _ClientIdSetupDialogState();
|
||||
}
|
||||
|
||||
class _ClientIdSetupDialogState extends State<_ClientIdSetupDialog> {
|
||||
final _controller = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('One-time GitHub setup needed'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Diet Guard signs in via a GitHub OAuth App (no password '
|
||||
'typed into this app). You only have to set this up once:',
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const Text(
|
||||
'1. On any device, open '
|
||||
'github.com/settings/developers → "New OAuth App".\n'
|
||||
'2. Name/Homepage/Callback URL can be anything (device flow '
|
||||
"doesn't use the callback) — e.g. "
|
||||
'"Diet Guard" and your GitHub profile URL.\n'
|
||||
'3. Check "Enable Device Flow", then click "Register '
|
||||
'application".\n'
|
||||
"4. Copy the Client ID shown on the app's page and paste it "
|
||||
'below.',
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const Text(
|
||||
'When you connect below, log in with the GitHub account that '
|
||||
'has write access to kuhyx/syncs.',
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _controller,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(labelText: 'Client ID'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
final id = _controller.text.trim();
|
||||
if (id.isNotEmpty) Navigator.of(context).pop(id);
|
||||
},
|
||||
child: const Text('Continue'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
145
app/lib/screens/github_mirror_actions.dart
Normal file
145
app/lib/screens/github_mirror_actions.dart
Normal file
@ -0,0 +1,145 @@
|
||||
// Connect / save / test / sync actions for the GitHub mirror screen.
|
||||
//
|
||||
// Split out of `github_mirror_screen.dart` for the repo's 250-line cap. A
|
||||
// `part` rather than a separate library: every one of these methods drives
|
||||
// the screen's private state (`_busy`, `_status`, `_storedToken`, the four
|
||||
// controllers) and calls its private helpers, none of which are reachable
|
||||
// across a library boundary in Dart.
|
||||
//
|
||||
// A mixin rather than an extension, because these call `setState`, which is
|
||||
// `@protected` -- an extension is not a subclass of `State`, so the analyzer
|
||||
// (correctly) rejects it there.
|
||||
|
||||
part of 'github_mirror_screen.dart';
|
||||
|
||||
mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
||||
// The four text controllers stay declared on the State, which creates and
|
||||
// disposes them; the mixin only reads and writes their text.
|
||||
TextEditingController get _ownerController;
|
||||
TextEditingController get _repoController;
|
||||
TextEditingController get _tokenController;
|
||||
TextEditingController get _clientIdController;
|
||||
|
||||
bool _busy = false;
|
||||
String? _status;
|
||||
String _storedToken = '';
|
||||
SyncSettings _currentSettings() {
|
||||
final typed = _tokenController.text.trim();
|
||||
return SyncSettings(
|
||||
owner: _ownerController.text.trim(),
|
||||
repo: _repoController.text.trim(),
|
||||
// The `_storedToken` side is web-only (the wrapper holds the real
|
||||
// token), so it is unreachable from a VM test.
|
||||
token: typed.isEmpty && !SyncSettings.exposesTokenValue
|
||||
// coverage:ignore-line
|
||||
? _storedToken
|
||||
: typed,
|
||||
clientId: _clientIdController.text.trim(),
|
||||
);
|
||||
}
|
||||
void _showMessage(String message) {
|
||||
if (!mounted) return;
|
||||
setState(() => _status = message);
|
||||
}
|
||||
|
||||
Future<void> _connectGitHub() async {
|
||||
var clientId = _clientIdController.text.trim();
|
||||
if (clientId.isEmpty) {
|
||||
final entered = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => const _ClientIdSetupDialog(),
|
||||
);
|
||||
if (entered == null || entered.isEmpty) return;
|
||||
clientId = entered;
|
||||
if (!mounted) return;
|
||||
setState(() => _clientIdController.text = clientId);
|
||||
await _currentSettings().save();
|
||||
}
|
||||
final auth = createDeviceAuth(clientId, httpClient: widget.httpClient);
|
||||
try {
|
||||
final device = await auth.requestDeviceCode();
|
||||
if (!mounted) return;
|
||||
final token = await showDialog<String>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => DeviceCodeDialog(device: device, auth: auth),
|
||||
);
|
||||
if (token != null && token.isNotEmpty) {
|
||||
setState(() {
|
||||
_storedToken = token;
|
||||
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
|
||||
});
|
||||
_showMessage('Connected — syncing…');
|
||||
await _currentSettings().save();
|
||||
await _syncAfterConnect();
|
||||
}
|
||||
} on Exception catch (e) {
|
||||
_showMessage('Could not start device flow: $e');
|
||||
} finally {
|
||||
auth.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a sync right after connecting so the device-flow token is proven
|
||||
/// to work immediately, with clear confirmation either way.
|
||||
Future<void> _syncAfterConnect() async {
|
||||
final settings = _currentSettings();
|
||||
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
||||
try {
|
||||
await runSync(await syncBackend(client));
|
||||
await SyncHealth.recordSuccess();
|
||||
_showMessage('Connected and synced.');
|
||||
} on Exception catch (e) {
|
||||
await SyncHealth.recordFailure();
|
||||
_showMessage('Connected, but sync failed: $e');
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
setState(() => _busy = true);
|
||||
await _currentSettings().save();
|
||||
if (!mounted) return;
|
||||
setState(() => _busy = false);
|
||||
_showMessage('Saved.');
|
||||
}
|
||||
|
||||
Future<void> _testConnection() async {
|
||||
setState(() => _busy = true);
|
||||
final settings = _currentSettings();
|
||||
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
||||
try {
|
||||
final ok = await client.canAccessRepo();
|
||||
_showMessage(
|
||||
ok ? 'GitHub connection OK.' : 'GitHub connection failed.',
|
||||
);
|
||||
} on Exception catch (e) {
|
||||
_showMessage('GitHub connection failed: $e');
|
||||
} finally {
|
||||
client.close();
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _syncNow() async {
|
||||
setState(() => _busy = true);
|
||||
final settings = _currentSettings();
|
||||
await settings.save();
|
||||
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
||||
try {
|
||||
await runSync(await syncBackend(client));
|
||||
// Clears any stored failure: this is the button a user reaches
|
||||
// *because* the banner told them syncing had stopped, so a successful
|
||||
// run here must dismiss the warning it caused.
|
||||
await SyncHealth.recordSuccess();
|
||||
_showMessage('Synced.');
|
||||
} on Exception catch (e) {
|
||||
await SyncHealth.recordFailure();
|
||||
_showMessage('Sync failed: $e');
|
||||
} finally {
|
||||
client.close();
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -8,7 +8,7 @@ library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||
import 'package:diet_guard_app/services/sync_health.dart';
|
||||
import 'package:diet_guard_app/services/sync_service.dart';
|
||||
@ -18,6 +18,9 @@ import 'package:flutter/material.dart';
|
||||
import 'package:github_device_auth/github_device_auth.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
part 'github_client_id_dialog.dart';
|
||||
part 'github_mirror_actions.dart';
|
||||
|
||||
/// Screen for configuring and triggering the GitHub mirror sync.
|
||||
class GitHubMirrorScreen extends StatefulWidget {
|
||||
/// Creates a [GitHubMirrorScreen].
|
||||
@ -30,14 +33,17 @@ class GitHubMirrorScreen extends StatefulWidget {
|
||||
State<GitHubMirrorScreen> createState() => _GitHubMirrorScreenState();
|
||||
}
|
||||
|
||||
class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
||||
class _GitHubMirrorScreenState extends State<GitHubMirrorScreen>
|
||||
with _GitHubMirrorActions {
|
||||
@override
|
||||
final _ownerController = TextEditingController();
|
||||
@override
|
||||
final _repoController = TextEditingController();
|
||||
@override
|
||||
final _tokenController = TextEditingController();
|
||||
@override
|
||||
final _clientIdController = TextEditingController();
|
||||
bool _loading = true;
|
||||
bool _busy = false;
|
||||
String? _status;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@ -87,129 +93,13 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
||||
|
||||
/// The token as loaded, so a platform that cannot display it (web) still
|
||||
/// round-trips it instead of blanking it on the next save.
|
||||
String _storedToken = '';
|
||||
|
||||
SyncSettings _currentSettings() {
|
||||
final typed = _tokenController.text.trim();
|
||||
return SyncSettings(
|
||||
owner: _ownerController.text.trim(),
|
||||
repo: _repoController.text.trim(),
|
||||
// The `_storedToken` side is web-only (the wrapper holds the real
|
||||
// token), so it is unreachable from a VM test.
|
||||
token: typed.isEmpty && !SyncSettings.exposesTokenValue
|
||||
// coverage:ignore-line
|
||||
? _storedToken
|
||||
: typed,
|
||||
clientId: _clientIdController.text.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
void _showMessage(String message) {
|
||||
if (!mounted) return;
|
||||
setState(() => _status = message);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// Runs the OAuth device flow and, on success, fills in the token field.
|
||||
Future<void> _connectGitHub() async {
|
||||
var clientId = _clientIdController.text.trim();
|
||||
if (clientId.isEmpty) {
|
||||
final entered = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => const _ClientIdSetupDialog(),
|
||||
);
|
||||
if (entered == null || entered.isEmpty) return;
|
||||
clientId = entered;
|
||||
if (!mounted) return;
|
||||
setState(() => _clientIdController.text = clientId);
|
||||
await _currentSettings().save();
|
||||
}
|
||||
final auth = createDeviceAuth(clientId, httpClient: widget.httpClient);
|
||||
try {
|
||||
final device = await auth.requestDeviceCode();
|
||||
if (!mounted) return;
|
||||
final token = await showDialog<String>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => DeviceCodeDialog(device: device, auth: auth),
|
||||
);
|
||||
if (token != null && token.isNotEmpty) {
|
||||
setState(() {
|
||||
_storedToken = token;
|
||||
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
|
||||
});
|
||||
_showMessage('Connected — syncing…');
|
||||
await _currentSettings().save();
|
||||
await _syncAfterConnect();
|
||||
}
|
||||
} on Exception catch (e) {
|
||||
_showMessage('Could not start device flow: $e');
|
||||
} finally {
|
||||
auth.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a sync right after connecting so the device-flow token is proven
|
||||
/// to work immediately, with clear confirmation either way.
|
||||
Future<void> _syncAfterConnect() async {
|
||||
final settings = _currentSettings();
|
||||
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
||||
try {
|
||||
await runSync(await syncBackend(client));
|
||||
await SyncHealth.recordSuccess();
|
||||
_showMessage('Connected and synced.');
|
||||
} on Exception catch (e) {
|
||||
await SyncHealth.recordFailure();
|
||||
_showMessage('Connected, but sync failed: $e');
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
setState(() => _busy = true);
|
||||
await _currentSettings().save();
|
||||
if (!mounted) return;
|
||||
setState(() => _busy = false);
|
||||
_showMessage('Saved.');
|
||||
}
|
||||
|
||||
Future<void> _testConnection() async {
|
||||
setState(() => _busy = true);
|
||||
final settings = _currentSettings();
|
||||
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
||||
try {
|
||||
final ok = await client.canAccessRepo();
|
||||
_showMessage(
|
||||
ok ? 'GitHub connection OK.' : 'GitHub connection failed.',
|
||||
);
|
||||
} on Exception catch (e) {
|
||||
_showMessage('GitHub connection failed: $e');
|
||||
} finally {
|
||||
client.close();
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _syncNow() async {
|
||||
setState(() => _busy = true);
|
||||
final settings = _currentSettings();
|
||||
await settings.save();
|
||||
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
||||
try {
|
||||
await runSync(await syncBackend(client));
|
||||
// Clears any stored failure: this is the button a user reaches
|
||||
// *because* the banner told them syncing had stopped, so a successful
|
||||
// run here must dismiss the warning it caused.
|
||||
await SyncHealth.recordSuccess();
|
||||
_showMessage('Synced.');
|
||||
} on Exception catch (e) {
|
||||
await SyncHealth.recordFailure();
|
||||
_showMessage('Sync failed: $e');
|
||||
} finally {
|
||||
client.close();
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@ -313,79 +203,3 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Dialog shown when "Connect GitHub" is tapped with no OAuth App client id
|
||||
/// configured yet. Explains what it is, how to get one, and lets the user
|
||||
/// paste it in directly — rather than leaving them to discover a buried
|
||||
/// field on their own. Pops the trimmed client id, or null if cancelled.
|
||||
class _ClientIdSetupDialog extends StatefulWidget {
|
||||
const _ClientIdSetupDialog();
|
||||
|
||||
@override
|
||||
State<_ClientIdSetupDialog> createState() => _ClientIdSetupDialogState();
|
||||
}
|
||||
|
||||
class _ClientIdSetupDialogState extends State<_ClientIdSetupDialog> {
|
||||
final _controller = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('One-time GitHub setup needed'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Diet Guard signs in via a GitHub OAuth App (no password '
|
||||
'typed into this app). You only have to set this up once:',
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const Text(
|
||||
'1. On any device, open '
|
||||
'github.com/settings/developers → "New OAuth App".\n'
|
||||
'2. Name/Homepage/Callback URL can be anything (device flow '
|
||||
"doesn't use the callback) — e.g. "
|
||||
'"Diet Guard" and your GitHub profile URL.\n'
|
||||
'3. Check "Enable Device Flow", then click "Register '
|
||||
'application".\n'
|
||||
"4. Copy the Client ID shown on the app's page and paste it "
|
||||
'below.',
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const Text(
|
||||
'When you connect below, log in with the GitHub account that '
|
||||
'has write access to kuhyx/syncs.',
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _controller,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(labelText: 'Client ID'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
final id = _controller.text.trim();
|
||||
if (id.isNotEmpty) Navigator.of(context).pop(id);
|
||||
},
|
||||
child: const Text('Continue'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,276 +1,26 @@
|
||||
/// Logged meal history with day grouping, filtering, and sorting.
|
||||
///
|
||||
/// The filter model, the grouped list and the filter sheet live in
|
||||
/// `lib/widgets/history/` (split for the repo's 250-line cap); this file is the
|
||||
/// screen that wires them together and owns the filter state.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/edit_entry_screen.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/history/history_filter.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_filter_sheet.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_list.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filter & sort state
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Sort field for the history list.
|
||||
enum HistorySortField {
|
||||
/// Sort by entry date/time.
|
||||
date,
|
||||
|
||||
/// Sort by calories.
|
||||
kcal,
|
||||
|
||||
/// Sort by protein (g).
|
||||
protein,
|
||||
|
||||
/// Sort by carbohydrates (g).
|
||||
carbs,
|
||||
|
||||
/// Sort by fat (g).
|
||||
fat,
|
||||
|
||||
/// Sort by description text.
|
||||
description,
|
||||
}
|
||||
|
||||
/// All active filter criteria; [isActive] is true when any criterion is set.
|
||||
class HistoryFilter {
|
||||
/// Creates a [HistoryFilter] with the given criteria.
|
||||
HistoryFilter({
|
||||
this.nameQuery = '',
|
||||
this.dateRange,
|
||||
this.minKcal,
|
||||
this.maxKcal,
|
||||
this.minProtein,
|
||||
this.maxProtein,
|
||||
this.minCarbs,
|
||||
this.maxCarbs,
|
||||
this.minFat,
|
||||
this.maxFat,
|
||||
this.source,
|
||||
});
|
||||
|
||||
/// Substring match on the food description.
|
||||
String nameQuery;
|
||||
|
||||
/// Optional date range filter.
|
||||
DateTimeRange? dateRange;
|
||||
|
||||
/// Minimum kcal.
|
||||
double? minKcal;
|
||||
|
||||
/// Maximum kcal.
|
||||
double? maxKcal;
|
||||
|
||||
/// Minimum protein (g).
|
||||
double? minProtein;
|
||||
|
||||
/// Maximum protein (g).
|
||||
double? maxProtein;
|
||||
|
||||
/// Minimum carbs (g).
|
||||
double? minCarbs;
|
||||
|
||||
/// Maximum carbs (g).
|
||||
double? maxCarbs;
|
||||
|
||||
/// Minimum fat (g).
|
||||
double? minFat;
|
||||
|
||||
/// Maximum fat (g).
|
||||
double? maxFat;
|
||||
|
||||
/// null = all, or a source string from the log.
|
||||
String? source;
|
||||
|
||||
/// True when any filter criterion is active.
|
||||
bool get isActive =>
|
||||
nameQuery.isNotEmpty ||
|
||||
dateRange != null ||
|
||||
minKcal != null ||
|
||||
maxKcal != null ||
|
||||
minProtein != null ||
|
||||
maxProtein != null ||
|
||||
minCarbs != null ||
|
||||
maxCarbs != null ||
|
||||
minFat != null ||
|
||||
maxFat != null ||
|
||||
source != null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// List item sealed hierarchy for day-grouped rendering
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
sealed class _HistoryItem {}
|
||||
|
||||
final class _DayHeader extends _HistoryItem {
|
||||
_DayHeader(
|
||||
this.dateKey,
|
||||
this.totalKcal,
|
||||
this.entryCount,
|
||||
this.totalProtein,
|
||||
this.totalCarbs,
|
||||
this.totalFat,
|
||||
);
|
||||
final String dateKey;
|
||||
final double totalKcal;
|
||||
final int entryCount;
|
||||
final double totalProtein;
|
||||
final double totalCarbs;
|
||||
final double totalFat;
|
||||
}
|
||||
|
||||
final class _EntryRow extends _HistoryItem {
|
||||
_EntryRow(this.entry);
|
||||
final FoodEntry entry;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pure filter / sort / group helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Applies [filter] and sort criteria to [entries] and returns the result.
|
||||
/// Logged meal history: every entry, grouped by day, filterable and sortable.
|
||||
///
|
||||
/// Exposed as a top-level function for unit tests.
|
||||
List<FoodEntry> applyHistoryFilter(
|
||||
List<FoodEntry> entries,
|
||||
HistoryFilter filter,
|
||||
HistorySortField sortField, {
|
||||
required bool ascending,
|
||||
}) {
|
||||
var result = [...entries];
|
||||
|
||||
if (filter.nameQuery.isNotEmpty) {
|
||||
final q = filter.nameQuery.toLowerCase();
|
||||
result = result.where((e) => e.desc.toLowerCase().contains(q)).toList();
|
||||
}
|
||||
if (filter.dateRange != null) {
|
||||
final start = filter.dateRange!.start;
|
||||
final end = filter.dateRange!.end.add(const Duration(days: 1));
|
||||
result = result.where((e) {
|
||||
final t = DateTime.tryParse(e.time);
|
||||
return t != null && !t.isBefore(start) && t.isBefore(end);
|
||||
}).toList();
|
||||
}
|
||||
if (filter.minKcal != null) {
|
||||
result = result.where((e) => e.kcal >= filter.minKcal!).toList();
|
||||
}
|
||||
if (filter.maxKcal != null) {
|
||||
result = result.where((e) => e.kcal <= filter.maxKcal!).toList();
|
||||
}
|
||||
if (filter.minProtein != null) {
|
||||
result = result.where((e) => e.proteinG >= filter.minProtein!).toList();
|
||||
}
|
||||
if (filter.maxProtein != null) {
|
||||
result = result.where((e) => e.proteinG <= filter.maxProtein!).toList();
|
||||
}
|
||||
if (filter.minCarbs != null) {
|
||||
result = result.where((e) => e.carbsG >= filter.minCarbs!).toList();
|
||||
}
|
||||
if (filter.maxCarbs != null) {
|
||||
result = result.where((e) => e.carbsG <= filter.maxCarbs!).toList();
|
||||
}
|
||||
if (filter.minFat != null) {
|
||||
result = result.where((e) => e.fatG >= filter.minFat!).toList();
|
||||
}
|
||||
if (filter.maxFat != null) {
|
||||
result = result.where((e) => e.fatG <= filter.maxFat!).toList();
|
||||
}
|
||||
if (filter.source != null) {
|
||||
result = result.where((e) => e.source == filter.source).toList();
|
||||
}
|
||||
|
||||
result.sort((a, b) {
|
||||
int cmp;
|
||||
switch (sortField) {
|
||||
case HistorySortField.date:
|
||||
final at = DateTime.tryParse(a.time) ?? DateTime(0);
|
||||
final bt = DateTime.tryParse(b.time) ?? DateTime(0);
|
||||
cmp = at.compareTo(bt);
|
||||
case HistorySortField.kcal:
|
||||
cmp = a.kcal.compareTo(b.kcal);
|
||||
case HistorySortField.protein:
|
||||
cmp = a.proteinG.compareTo(b.proteinG);
|
||||
case HistorySortField.carbs:
|
||||
cmp = a.carbsG.compareTo(b.carbsG);
|
||||
case HistorySortField.fat:
|
||||
cmp = a.fatG.compareTo(b.fatG);
|
||||
case HistorySortField.description:
|
||||
cmp = a.desc.compareTo(b.desc);
|
||||
}
|
||||
return ascending ? cmp : -cmp;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
List<_HistoryItem> _buildGroupedItems(List<FoodEntry> entries) {
|
||||
final byDay = <String, List<FoodEntry>>{};
|
||||
for (final e in entries) {
|
||||
final day = e.time.length >= 10 ? e.time.substring(0, 10) : 'unknown';
|
||||
byDay.putIfAbsent(day, () => []).add(e);
|
||||
}
|
||||
final days = byDay.keys.toList()..sort((a, b) => b.compareTo(a));
|
||||
final items = <_HistoryItem>[];
|
||||
for (final day in days) {
|
||||
final dayEntries = byDay[day]!;
|
||||
final totalKcal = sumKcal(dayEntries);
|
||||
final totalProtein = dayEntries.fold<double>(0, (s, e) => s + e.proteinG);
|
||||
final totalCarbs = dayEntries.fold<double>(0, (s, e) => s + e.carbsG);
|
||||
final totalFat = dayEntries.fold<double>(0, (s, e) => s + e.fatG);
|
||||
items
|
||||
..add(
|
||||
_DayHeader(
|
||||
day,
|
||||
totalKcal,
|
||||
dayEntries.length,
|
||||
totalProtein,
|
||||
totalCarbs,
|
||||
totalFat,
|
||||
),
|
||||
)
|
||||
..addAll(dayEntries.map(_EntryRow.new));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
String _dateRangeLabel(DateTimeRange r) =>
|
||||
'${r.start.toString().substring(0, 10)}'
|
||||
' – ${r.end.toString().substring(0, 10)}';
|
||||
|
||||
String _formatDay(String dateKey) {
|
||||
try {
|
||||
final d = DateTime.parse(dateKey);
|
||||
const wd = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
||||
const mo = [
|
||||
'Jan',
|
||||
'Feb',
|
||||
'Mar',
|
||||
'Apr',
|
||||
'May',
|
||||
'Jun',
|
||||
'Jul',
|
||||
'Aug',
|
||||
'Sep',
|
||||
'Oct',
|
||||
'Nov',
|
||||
'Dec',
|
||||
];
|
||||
return '${wd[d.weekday - 1]} ${d.day} ${mo[d.month - 1]} ${d.year}';
|
||||
} on Exception {
|
||||
return dateKey;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Screen
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Shows every non-deleted logged entry, grouped by day, with optional
|
||||
/// filtering and sorting.
|
||||
/// Owns the live [HistoryFilter] and sort order; the sheet that edits them and
|
||||
/// the list that renders the result are separate widgets under
|
||||
/// `lib/widgets/history/`.
|
||||
class HistoryScreen extends StatefulWidget {
|
||||
/// Creates a [HistoryScreen].
|
||||
///
|
||||
@ -368,7 +118,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
isScrollControlled: true,
|
||||
useSafeArea: true,
|
||||
builder: (ctx) => StatefulBuilder(
|
||||
builder: (ctx, setSheet) => _FilterSheet(
|
||||
builder: (ctx, setSheet) => FilterSheet(
|
||||
filter: draft,
|
||||
sortField: draftSortField,
|
||||
ascending: draftSortAscending,
|
||||
@ -447,8 +197,8 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
: 'No entries match the current filter.',
|
||||
),
|
||||
)
|
||||
: _GroupedList(
|
||||
items: _buildGroupedItems(_displayed),
|
||||
: GroupedList(
|
||||
items: buildGroupedItems(_displayed),
|
||||
onDeleteEntry: _load,
|
||||
onEditEntry: _onEditEntry,
|
||||
),
|
||||
@ -459,594 +209,3 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Grouped list widget
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class _GroupedList extends StatelessWidget {
|
||||
const _GroupedList({
|
||||
required this.items,
|
||||
required this.onDeleteEntry,
|
||||
required this.onEditEntry,
|
||||
});
|
||||
final List<_HistoryItem> items;
|
||||
final Future<void> Function() onDeleteEntry;
|
||||
final Future<void> Function(FoodEntry) onEditEntry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView.builder(
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
return switch (item) {
|
||||
_DayHeader() => _DayHeaderTile(item),
|
||||
_EntryRow() => _EntryTile(
|
||||
item.entry,
|
||||
onDelete: onDeleteEntry,
|
||||
onEdit: () => onEditEntry(item.entry),
|
||||
),
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DayHeaderTile extends StatelessWidget {
|
||||
const _DayHeaderTile(this.header);
|
||||
final _DayHeader header;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
// The budget that applied on *that* day, not today's -- a later budget
|
||||
// change must not repaint months of history red.
|
||||
final goal = BudgetHistoryService.schedule.forDay(header.dateKey);
|
||||
final kcalColor = header.totalKcal > goal
|
||||
? colorScheme.error
|
||||
: colorScheme.primary;
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
_formatDay(header.dateKey),
|
||||
style: textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${header.entryCount}'
|
||||
' ${header.entryCount == 1 ? 'entry' : 'entries'}',
|
||||
style: textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
'${header.totalKcal.round()} / $goal kcal',
|
||||
style: textTheme.bodySmall?.copyWith(color: kcalColor),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'P ${header.totalProtein.round()}g · '
|
||||
'C ${header.totalCarbs.round()}g · '
|
||||
'F ${header.totalFat.round()}g',
|
||||
style: textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _EntryTile extends StatelessWidget {
|
||||
const _EntryTile(this.entry, {this.onDelete, this.onEdit});
|
||||
final FoodEntry entry;
|
||||
|
||||
/// Called after a confirmed delete so the parent can reload.
|
||||
final Future<void> Function()? onDelete;
|
||||
|
||||
/// Called when the tile is tapped to open the edit screen.
|
||||
final Future<void> Function()? onEdit;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final canDelete = entry.id != null;
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.restaurant),
|
||||
title: Text(entry.desc),
|
||||
subtitle: Text('${entry.time} • ${entry.source}'),
|
||||
// Delete needs a focusable control, not just a long-press. Long-press has
|
||||
// no keyboard equivalent at all, so on the desktop build (a Chrome --app
|
||||
// window) deleting an entry was pointer-only: unreachable by keyboard and
|
||||
// invisible to a screen reader. The trailing row keeps the kcal figure
|
||||
// and adds an IconButton, which Tab reaches and Enter/Space activates.
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('${entry.kcal.toStringAsFixed(0)} kcal'),
|
||||
if (canDelete)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
tooltip: 'Delete entry',
|
||||
onPressed: () => _confirmDelete(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
// Any entry can be edited (legacy null-id entries gain a UUID on save).
|
||||
// Delete remains id-only to avoid ambiguous time+desc matches.
|
||||
onTap: () => onEdit?.call(),
|
||||
// Retained as a redundant pointer shortcut, never the only route.
|
||||
onLongPress: canDelete ? () => _confirmDelete(context) : null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _confirmDelete(BuildContext context) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
title: const Text('Delete entry?'),
|
||||
content: Text('Remove "${entry.desc}" from history?'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed == true) {
|
||||
await LogStorageService.instance.deleteEntry(entry.id!);
|
||||
await onDelete?.call();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filter sheet
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class _FilterSheet extends StatelessWidget {
|
||||
const _FilterSheet({
|
||||
required this.filter,
|
||||
required this.sortField,
|
||||
required this.ascending,
|
||||
required this.maxKcal,
|
||||
required this.maxProtein,
|
||||
required this.maxCarbs,
|
||||
required this.maxFat,
|
||||
required this.onFilterChanged,
|
||||
required this.onSortChanged,
|
||||
required this.onApply,
|
||||
required this.onClear,
|
||||
});
|
||||
|
||||
final HistoryFilter filter;
|
||||
final HistorySortField sortField;
|
||||
final bool ascending;
|
||||
final double maxKcal;
|
||||
final double maxProtein;
|
||||
final double maxCarbs;
|
||||
final double maxFat;
|
||||
final void Function(HistoryFilter) onFilterChanged;
|
||||
final void Function({required HistorySortField field, required bool asc})
|
||||
onSortChanged;
|
||||
final VoidCallback onApply;
|
||||
final VoidCallback onClear;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DraggableScrollableSheet(
|
||||
initialChildSize: 0.9,
|
||||
minChildSize: 0.5,
|
||||
maxChildSize: 0.95,
|
||||
builder: (context, scroll) => Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Filter & Sort',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
TextButton(onPressed: onClear, child: const Text('Clear all')),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
controller: scroll,
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Name search
|
||||
_NameSearchField(
|
||||
initialQuery: filter.nameQuery,
|
||||
onChanged: (v) {
|
||||
filter.nameQuery = v;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Date range
|
||||
Text(
|
||||
'Date range',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
OutlinedButton.icon(
|
||||
icon: const Icon(Icons.date_range),
|
||||
label: Text(
|
||||
filter.dateRange == null
|
||||
? 'Any date'
|
||||
: _dateRangeLabel(filter.dateRange!),
|
||||
),
|
||||
onPressed: () async {
|
||||
final picked = await showDateRangePicker(
|
||||
context: context,
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime.now().add(const Duration(days: 1)),
|
||||
initialDateRange: filter.dateRange,
|
||||
);
|
||||
if (picked != null) {
|
||||
filter.dateRange = picked;
|
||||
onFilterChanged(filter);
|
||||
}
|
||||
},
|
||||
),
|
||||
if (filter.dateRange != null)
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
filter.dateRange = null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
child: const Text('Clear date range'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Kcal range
|
||||
if (maxKcal > 0) ...[
|
||||
Text(
|
||||
'Kcal range',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
_SliderEndpointLabels(
|
||||
lo: '0',
|
||||
hi: maxKcal.round().toString(),
|
||||
),
|
||||
RangeSlider(
|
||||
key: const Key('kcal-range-slider'),
|
||||
max: maxKcal,
|
||||
values: RangeValues(
|
||||
filter.minKcal ?? 0,
|
||||
filter.maxKcal ?? maxKcal,
|
||||
),
|
||||
labels: RangeLabels(
|
||||
(filter.minKcal ?? 0).toStringAsFixed(0),
|
||||
(filter.maxKcal ?? maxKcal).toStringAsFixed(0),
|
||||
),
|
||||
onChanged: (v) {
|
||||
filter.minKcal = v.start > 0 ? v.start : null;
|
||||
filter.maxKcal = v.end < maxKcal ? v.end : null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
_SliderSelectedLabel(
|
||||
'${(filter.minKcal ?? 0).round()}'
|
||||
' – ${(filter.maxKcal ?? maxKcal).round()} kcal',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
|
||||
// Protein range
|
||||
if (maxProtein > 0) ...[
|
||||
Text(
|
||||
'Protein range (g)',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
_SliderEndpointLabels(
|
||||
lo: '0',
|
||||
hi: '${maxProtein.round()}g',
|
||||
),
|
||||
RangeSlider(
|
||||
key: const Key('protein-range-slider'),
|
||||
max: maxProtein,
|
||||
values: RangeValues(
|
||||
filter.minProtein ?? 0,
|
||||
filter.maxProtein ?? maxProtein,
|
||||
),
|
||||
labels: RangeLabels(
|
||||
(filter.minProtein ?? 0).toStringAsFixed(0),
|
||||
(filter.maxProtein ?? maxProtein).toStringAsFixed(0),
|
||||
),
|
||||
onChanged: (v) {
|
||||
filter.minProtein = v.start > 0 ? v.start : null;
|
||||
filter.maxProtein = v.end < maxProtein ? v.end : null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
_SliderSelectedLabel(
|
||||
'${(filter.minProtein ?? 0).round()}'
|
||||
' – ${(filter.maxProtein ?? maxProtein).round()}g',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
|
||||
// Carbs range
|
||||
if (maxCarbs > 0) ...[
|
||||
Text(
|
||||
'Carbs range (g)',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
_SliderEndpointLabels(lo: '0', hi: '${maxCarbs.round()}g'),
|
||||
RangeSlider(
|
||||
key: const Key('carbs-range-slider'),
|
||||
max: maxCarbs,
|
||||
values: RangeValues(
|
||||
filter.minCarbs ?? 0,
|
||||
filter.maxCarbs ?? maxCarbs,
|
||||
),
|
||||
labels: RangeLabels(
|
||||
(filter.minCarbs ?? 0).toStringAsFixed(0),
|
||||
(filter.maxCarbs ?? maxCarbs).toStringAsFixed(0),
|
||||
),
|
||||
onChanged: (v) {
|
||||
filter.minCarbs = v.start > 0 ? v.start : null;
|
||||
filter.maxCarbs = v.end < maxCarbs ? v.end : null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
_SliderSelectedLabel(
|
||||
'${(filter.minCarbs ?? 0).round()}'
|
||||
' – ${(filter.maxCarbs ?? maxCarbs).round()}g',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
|
||||
// Fat range
|
||||
if (maxFat > 0) ...[
|
||||
Text(
|
||||
'Fat range (g)',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
_SliderEndpointLabels(lo: '0', hi: '${maxFat.round()}g'),
|
||||
RangeSlider(
|
||||
key: const Key('fat-range-slider'),
|
||||
max: maxFat,
|
||||
values: RangeValues(
|
||||
filter.minFat ?? 0,
|
||||
filter.maxFat ?? maxFat,
|
||||
),
|
||||
labels: RangeLabels(
|
||||
(filter.minFat ?? 0).toStringAsFixed(0),
|
||||
(filter.maxFat ?? maxFat).toStringAsFixed(0),
|
||||
),
|
||||
onChanged: (v) {
|
||||
filter.minFat = v.start > 0 ? v.start : null;
|
||||
filter.maxFat = v.end < maxFat ? v.end : null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
_SliderSelectedLabel(
|
||||
'${(filter.minFat ?? 0).round()}'
|
||||
' – ${(filter.maxFat ?? maxFat).round()}g',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
|
||||
// Source filter
|
||||
Text('Source', style: Theme.of(context).textTheme.labelLarge),
|
||||
const SizedBox(height: 4),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
FilterChip(
|
||||
label: const Text('All'),
|
||||
selected: filter.source == null,
|
||||
onSelected: (_) {
|
||||
filter.source = null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
for (final src in ['manual', 'food bank'])
|
||||
FilterChip(
|
||||
label: Text(src),
|
||||
selected: filter.source == src,
|
||||
onSelected: (_) {
|
||||
filter.source = src;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Sort
|
||||
Text(
|
||||
'Sort by',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: DropdownButton<HistorySortField>(
|
||||
isExpanded: true,
|
||||
value: sortField,
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.date,
|
||||
child: Text('Date'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.kcal,
|
||||
child: Text('Kcal'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.protein,
|
||||
child: Text('Protein'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.carbs,
|
||||
child: Text('Carbs'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.fat,
|
||||
child: Text('Fat'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.description,
|
||||
child: Text('Description'),
|
||||
),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v != null) {
|
||||
onSortChanged(field: v, asc: ascending);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
ascending ? Icons.arrow_upward : Icons.arrow_downward,
|
||||
),
|
||||
tooltip: ascending ? 'Ascending' : 'Descending',
|
||||
onPressed: () =>
|
||||
onSortChanged(field: sortField, asc: !ascending),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: onApply,
|
||||
child: const Text('Apply'),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Slider label helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Thin row showing the min (0) and max endpoint values for a range slider.
|
||||
/// The filter sheet's name-search field, owning a persistent controller.
|
||||
///
|
||||
/// Stateful on purpose. The controller used to be built inside
|
||||
/// `_FilterSheet.build` with the caret forced to the end of the text, and
|
||||
/// `onChanged` rebuilds the sheet — so every keystroke discarded the controller
|
||||
/// and re-slammed the caret to end-of-text. Appending worked, but Home/End and
|
||||
/// arrow-key editing in the middle of the query were silently undone on each
|
||||
/// character. Keeping the controller in State fixes that without changing how
|
||||
/// the filter is plumbed.
|
||||
class _NameSearchField extends StatefulWidget {
|
||||
const _NameSearchField({required this.initialQuery, required this.onChanged});
|
||||
|
||||
/// Query text to seed the field with on first build only.
|
||||
final String initialQuery;
|
||||
|
||||
/// Called on each edit with the new query.
|
||||
final ValueChanged<String> onChanged;
|
||||
|
||||
@override
|
||||
State<_NameSearchField> createState() => _NameSearchFieldState();
|
||||
}
|
||||
|
||||
class _NameSearchFieldState extends State<_NameSearchField> {
|
||||
late final TextEditingController _controller = TextEditingController(
|
||||
text: widget.initialQuery,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TextField(
|
||||
controller: _controller,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Search by name',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: widget.onChanged,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SliderEndpointLabels extends StatelessWidget {
|
||||
const _SliderEndpointLabels({required this.lo, required this.hi});
|
||||
final String lo;
|
||||
final String hi;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final style = Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
);
|
||||
return Row(
|
||||
children: [
|
||||
Text(lo, style: style),
|
||||
const Spacer(),
|
||||
Text(hi, style: style),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Centred text showing the currently-selected range value (always visible).
|
||||
class _SliderSelectedLabel extends StatelessWidget {
|
||||
const _SliderSelectedLabel(this.label);
|
||||
final String label;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
34
app/lib/screens/log_meal_actions.dart
Normal file
34
app/lib/screens/log_meal_actions.dart
Normal file
@ -0,0 +1,34 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The four destination buttons in [LogMealScreen]'s app bar.
|
||||
///
|
||||
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. Returned
|
||||
/// as a list to be spread into `AppBar.actions`, so the bar's structure and
|
||||
/// the order of the buttons are unchanged.
|
||||
List<Widget> logMealAppBarActions({
|
||||
required VoidCallback onFoodBank,
|
||||
required VoidCallback onHistory,
|
||||
required VoidCallback onCalendar,
|
||||
required VoidCallback onSettings,
|
||||
}) => [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.restaurant_menu),
|
||||
tooltip: 'Food bank',
|
||||
onPressed: onFoodBank,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.history),
|
||||
tooltip: 'History',
|
||||
onPressed: onHistory,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.calendar_month),
|
||||
tooltip: 'Calendar',
|
||||
onPressed: onCalendar,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.settings),
|
||||
tooltip: 'Sync settings',
|
||||
onPressed: onSettings,
|
||||
),
|
||||
];
|
||||
45
app/lib/screens/log_meal_nav_mixin.dart
Normal file
45
app/lib/screens/log_meal_nav_mixin.dart
Normal file
@ -0,0 +1,45 @@
|
||||
import 'package:diet_guard_app/screens/calendar_screen.dart';
|
||||
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
import 'package:diet_guard_app/screens/settings_screen.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// The four app-bar destinations reachable from [LogMealScreen].
|
||||
///
|
||||
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. The routes
|
||||
/// are unchanged -- each pushes exactly the [MaterialPageRoute] it did before.
|
||||
mixin LogMealNavMixin<T extends StatefulWidget> on State<T> {
|
||||
/// The screen's injected HTTP client, forwarded to [SettingsScreen].
|
||||
http.Client? get syncHttpClient;
|
||||
|
||||
/// Pushes the entry history screen.
|
||||
void onOpenHistory() {
|
||||
Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(builder: (_) => const HistoryScreen()),
|
||||
);
|
||||
}
|
||||
|
||||
/// Pushes the adherence calendar screen.
|
||||
void onOpenCalendar() {
|
||||
Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(builder: (_) => const CalendarScreen()),
|
||||
);
|
||||
}
|
||||
|
||||
/// Pushes the food bank screen.
|
||||
void onOpenFoodBank() {
|
||||
Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(builder: (_) => const FoodBankScreen()),
|
||||
);
|
||||
}
|
||||
|
||||
/// Pushes the settings screen, forwarding the HTTP client.
|
||||
void onOpenSettings() {
|
||||
Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => SettingsScreen(httpClient: syncHttpClient),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
36
app/lib/screens/log_meal_progress.dart
Normal file
36
app/lib/screens/log_meal_progress.dart
Normal file
@ -0,0 +1,36 @@
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/models/local_time.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/day_status_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// Reads a macro field as a number, treating blank or unparsable as zero.
|
||||
double parseMacroField(TextEditingController controller) =>
|
||||
double.tryParse(controller.text.trim()) ?? 0;
|
||||
|
||||
/// Summarises today from the log just written.
|
||||
///
|
||||
/// Takes the already-read [log] rather than re-reading, so the card can
|
||||
/// never disagree with the write that produced it.
|
||||
TodayProgress buildTodayProgress(DayLog log, String desc) {
|
||||
final budget = AppSettingsService.dailyKcalGoal;
|
||||
final today = localDateKey(DateTime.now());
|
||||
final entries = (log[today] ?? const <FoodEntry>[])
|
||||
.where((entry) => !entry.deleted)
|
||||
.toList();
|
||||
final macros = sumMacros(entries);
|
||||
return TodayProgress(
|
||||
justLogged: desc,
|
||||
consumedKcal: sumKcal(entries),
|
||||
budgetKcal: budget,
|
||||
proteinG: macros.proteinG,
|
||||
carbsG: macros.carbsG,
|
||||
fatG: macros.fatG,
|
||||
adherenceStreak: adherenceStreak(
|
||||
statusMap(log, schedule: BudgetHistoryService.schedule),
|
||||
),
|
||||
);
|
||||
}
|
||||
@ -3,29 +3,18 @@
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||
import 'package:diet_guard_app/models/local_time.dart';
|
||||
import 'package:diet_guard_app/models/nutrition.dart';
|
||||
import 'package:diet_guard_app/models/slot.dart';
|
||||
import 'package:diet_guard_app/screens/calendar_screen.dart';
|
||||
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
import 'package:diet_guard_app/screens/settings_screen.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/background_tasks.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/screens/log_meal_actions.dart';
|
||||
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
|
||||
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
||||
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||
import 'package:diet_guard_app/services/due_slot_check.dart';
|
||||
import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_health.dart';
|
||||
import 'package:diet_guard_app/services/sync_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_settings.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||
@ -50,21 +39,22 @@ class LogMealScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _LogMealScreenState extends State<LogMealScreen>
|
||||
with WidgetsBindingObserver {
|
||||
with
|
||||
WidgetsBindingObserver,
|
||||
LogMealSyncMixin<LogMealScreen>,
|
||||
LogMealNavMixin<LogMealScreen> {
|
||||
@override
|
||||
http.Client? get syncHttpClient => widget.httpClient;
|
||||
|
||||
final TextEditingController _descController = TextEditingController();
|
||||
final MacroControllers _macros = MacroControllers();
|
||||
List<FoodSuggestion> _suggestions = const [];
|
||||
Set<int> _loggedSlots = {};
|
||||
int? _selectedSlot;
|
||||
String _source = 'manual';
|
||||
String? _status;
|
||||
TodayProgress? _progress;
|
||||
|
||||
/// Single-flight guard so a launch sync and a lifecycle sync never overlap.
|
||||
bool _autoSyncing = false;
|
||||
|
||||
/// Latest sync health, driving the "not syncing" banner. Null until read.
|
||||
SyncHealthStatus? _syncHealth;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@ -82,12 +72,12 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
controller.addListener(_onMacroEdited);
|
||||
}
|
||||
_selectedSlot = slotForLog(DateTime.now());
|
||||
unawaited(_refreshSlots());
|
||||
unawaited(refreshSlots());
|
||||
unawaited(_onDescChanged());
|
||||
// Read health before the first sync finishes, so a device that stalled in
|
||||
// a previous session says so immediately rather than only after a tick.
|
||||
unawaited(_refreshSyncHealth());
|
||||
unawaited(_autoSync());
|
||||
unawaited(refreshSyncHealth());
|
||||
unawaited(autoSync());
|
||||
}
|
||||
|
||||
@override
|
||||
@ -98,145 +88,37 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
// Pull on resume (catch up on what another device logged while this one
|
||||
// was backgrounded) and push on pause (keep the remote near-current).
|
||||
final isResumeOrPause =
|
||||
state == AppLifecycleState.resumed || state == AppLifecycleState.paused;
|
||||
if (isResumeOrPause) {
|
||||
unawaited(_autoSync());
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort background sync: silent, skips when unconfigured, and never
|
||||
/// overlaps itself. Failures are swallowed -- the Settings screen's manual
|
||||
/// "Sync now" is where errors get surfaced. The try wraps even loading
|
||||
/// [SyncSettings] itself: under `flutter test`, the shared_preferences and
|
||||
/// secure-storage platform channels are unmocked by default and throw
|
||||
/// [MissingPluginException], which must degrade exactly like "offline"
|
||||
/// rather than crash every screen that mounts this widget.
|
||||
///
|
||||
/// [_refreshSlots] only runs after an actual sync (not on the unconfigured
|
||||
/// path, which every existing screen test takes): a fire-and-forget tail
|
||||
/// await here can resolve after a *later* test's `tearDown` has already
|
||||
/// reset [LogStorageService]'s singleton -- `mounted` alone doesn't bound
|
||||
/// that, since widget disposal between tests isn't synchronized with a
|
||||
/// still-pending Future from an earlier one.
|
||||
Future<void> _autoSync() async {
|
||||
if (_autoSyncing) return;
|
||||
_autoSyncing = true;
|
||||
try {
|
||||
final settings = await SyncSettings.load();
|
||||
// Either backend counts. `isConfigured` means "has a GitHub token", so
|
||||
// gating on it alone silently skips every sync on a device connected
|
||||
// only to Firebase -- and once the mirror is retired that is every
|
||||
// device. Same fix workout_app's push() already carries.
|
||||
if (!settings.isConfigured && await openFirebase() == null) {
|
||||
// Never a silent return: an unconfigured device looked exactly like a
|
||||
// healthy one with nothing to send, which is how meals sat unpublished
|
||||
// for days. Recorded so the banner can say so.
|
||||
log(
|
||||
'diet_guard auto-sync: no backend configured; nothing to push',
|
||||
level: 900,
|
||||
);
|
||||
await SyncHealth.recordUnconfigured();
|
||||
if (mounted) await _refreshSyncHealth();
|
||||
return;
|
||||
}
|
||||
final client = createGitHubClient(
|
||||
settings,
|
||||
httpClient: widget.httpClient,
|
||||
);
|
||||
try {
|
||||
await runSync(await syncBackend(client));
|
||||
await SyncHealth.recordSuccess();
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
if (!mounted) return;
|
||||
await _refreshSlots();
|
||||
await _refreshSyncHealth();
|
||||
} on Object catch (error, stackTrace) {
|
||||
// Best-effort, but never silent: this swallowed the reason a desktop
|
||||
// install could not publish at all, which looked identical to "nothing
|
||||
// to sync". Offline and unmocked-platform-channel-under-test both land
|
||||
// here too, so it stays non-fatal -- it just says why now.
|
||||
log(
|
||||
'diet_guard auto-sync failed',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
await SyncHealth.recordFailure();
|
||||
if (mounted) await _refreshSyncHealth();
|
||||
} finally {
|
||||
_autoSyncing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-reads sync health so the banner reflects the tick that just ran.
|
||||
Future<void> _refreshSyncHealth() async {
|
||||
final status = await SyncHealth.read();
|
||||
if (!mounted) return;
|
||||
setState(() => _syncHealth = status);
|
||||
}
|
||||
|
||||
/// Queues the platform's offline push backstop so a meal logged while
|
||||
/// offline still uploads on reconnect. The in-process [_autoSync] covers
|
||||
/// the online case; this is the backstop (a no-op on web, which has no
|
||||
/// out-of-page scheduler -- see background_tasks.dart).
|
||||
// coverage:ignore-start
|
||||
Future<void> _enqueueSyncBackstop() => enqueueSyncBackstop();
|
||||
|
||||
// coverage:ignore-end
|
||||
|
||||
Future<void> _refreshSlots() async {
|
||||
final logged = await LogStorageService.instance.loggedSlotsToday();
|
||||
if (!mounted) return;
|
||||
setState(() => _loggedSlots = logged);
|
||||
}
|
||||
|
||||
void _onMacroEdited() {
|
||||
if (_source == 'food bank') {
|
||||
setState(() => _source = 'manual');
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-runs the food-bank search and dismisses the previous progress card.
|
||||
///
|
||||
/// The card is cleared only when the field is non-empty because
|
||||
/// [_onLogMeal]'s own `clear()` fires this listener too: without the guard
|
||||
/// the two async chains race and the clear can null the card right after
|
||||
/// [_onLogMeal] set it, so it never appears on device (in-memory test
|
||||
/// stores resolve fast enough to hide this).
|
||||
Future<void> _onDescChanged() async {
|
||||
final matches = await FoodBankService.instance.search(
|
||||
_descController.text,
|
||||
);
|
||||
final matches = await FoodBankService.instance.search(_descController.text);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_suggestions = matches;
|
||||
// Typing the *next* meal dismisses the previous log's progress card.
|
||||
// Guarded on non-empty text because _onLogMeal's own
|
||||
// `_descController.clear()` also fires this listener: without the
|
||||
// guard the two async chains race and the clear can null the card
|
||||
// right after _onLogMeal set it, so the card never appears on device
|
||||
// (in-memory test stores resolve fast enough to hide this).
|
||||
if (_descController.text.isNotEmpty) _progress = null;
|
||||
});
|
||||
}
|
||||
|
||||
void _onSuggestionSelected(FoodSuggestion suggestion) {
|
||||
_descController.text = suggestion.name;
|
||||
_macros.kcal.text = suggestion.nutrition.kcal.toStringAsFixed(0);
|
||||
_macros.protein.text = suggestion.nutrition.proteinG.toStringAsFixed(0);
|
||||
_macros.carbs.text = suggestion.nutrition.carbsG.toStringAsFixed(0);
|
||||
_macros.fat.text = suggestion.nutrition.fatG.toStringAsFixed(0);
|
||||
_macros.perGrams.text = suggestion.nutrition.grams.toStringAsFixed(0);
|
||||
_macros.grams.text = suggestion.nutrition.grams.toStringAsFixed(0);
|
||||
_macros.fillFrom(suggestion.nutrition);
|
||||
setState(() {
|
||||
_source = 'food bank';
|
||||
_suggestions = const [];
|
||||
});
|
||||
}
|
||||
|
||||
double _parse(TextEditingController controller) =>
|
||||
double.tryParse(controller.text.trim()) ?? 0;
|
||||
|
||||
Future<void> _onLogMeal() async {
|
||||
final desc = _descController.text.trim();
|
||||
if (desc.isEmpty) {
|
||||
@ -247,12 +129,12 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
return;
|
||||
}
|
||||
final nutrition = nutritionForPortion(
|
||||
kcal: _parse(_macros.kcal),
|
||||
proteinG: _parse(_macros.protein),
|
||||
carbsG: _parse(_macros.carbs),
|
||||
fatG: _parse(_macros.fat),
|
||||
perGrams: _parse(_macros.perGrams),
|
||||
ateGrams: _parse(_macros.grams),
|
||||
kcal: parseMacroField(_macros.kcal),
|
||||
proteinG: parseMacroField(_macros.protein),
|
||||
carbsG: parseMacroField(_macros.carbs),
|
||||
fatG: parseMacroField(_macros.fat),
|
||||
perGrams: parseMacroField(_macros.perGrams),
|
||||
ateGrams: parseMacroField(_macros.grams),
|
||||
source: _source,
|
||||
);
|
||||
await LogStorageService.instance.logMeal(
|
||||
@ -264,11 +146,11 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
await FoodBankService.instance.rebuildAndPersist(log);
|
||||
// Push the new meal now instead of waiting for the next lifecycle event,
|
||||
// so the PC gate can see it in seconds. Fire-and-forget and best-effort:
|
||||
// _autoSync is single-flight and swallows offline/transient failures.
|
||||
unawaited(_autoSync());
|
||||
// autoSync is single-flight and swallows offline/transient failures.
|
||||
unawaited(autoSync());
|
||||
// Offline backstop: if the push above fails (no connectivity), a
|
||||
// connectivity-gated WorkManager task uploads the meal on reconnect.
|
||||
unawaited(_enqueueSyncBackstop());
|
||||
unawaited(enqueueSyncBackstopTask());
|
||||
await _dismissStaleReminder();
|
||||
if (!mounted) return;
|
||||
_descController.clear();
|
||||
@ -277,11 +159,11 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
_source = 'manual';
|
||||
_selectedSlot = slotForLog(DateTime.now());
|
||||
});
|
||||
await _refreshSlots();
|
||||
await refreshSlots();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_status = null;
|
||||
_progress = _buildProgress(log, desc);
|
||||
_progress = buildTodayProgress(log, desc);
|
||||
});
|
||||
}
|
||||
|
||||
@ -290,62 +172,13 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
/// Without this a notification already on screen survives until the next
|
||||
/// background tick (up to 15 minutes), which reads as a false alarm even
|
||||
/// though the meal was logged on this very device. Passes
|
||||
/// `pullWhenDue: false` because [_autoSync] above already owns the network
|
||||
/// `pullWhenDue: false` because [autoSync] above already owns the network
|
||||
/// here and the local log is by definition the freshest copy.
|
||||
///
|
||||
/// [checkAndNotify] already swallows notification-platform failures, so
|
||||
/// the meal -- written before this runs -- can never be lost to one.
|
||||
Future<void> _dismissStaleReminder() => checkAndNotify(pullWhenDue: false);
|
||||
|
||||
/// Summarises today from the log just written.
|
||||
///
|
||||
/// Takes the already-read [log] rather than re-reading, so the card can
|
||||
/// never disagree with the write that produced it.
|
||||
TodayProgress _buildProgress(DayLog log, String desc) {
|
||||
final budget = AppSettingsService.dailyKcalGoal;
|
||||
final today = localDateKey(DateTime.now());
|
||||
final entries = (log[today] ?? const <FoodEntry>[])
|
||||
.where((entry) => !entry.deleted)
|
||||
.toList();
|
||||
final macros = sumMacros(entries);
|
||||
return TodayProgress(
|
||||
justLogged: desc,
|
||||
consumedKcal: sumKcal(entries),
|
||||
budgetKcal: budget,
|
||||
proteinG: macros.proteinG,
|
||||
carbsG: macros.carbsG,
|
||||
fatG: macros.fatG,
|
||||
adherenceStreak: adherenceStreak(
|
||||
statusMap(log, schedule: BudgetHistoryService.schedule),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _onOpenHistory() {
|
||||
Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(builder: (_) => const HistoryScreen()),
|
||||
);
|
||||
}
|
||||
|
||||
void _onOpenCalendar() {
|
||||
Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(builder: (_) => const CalendarScreen()),
|
||||
);
|
||||
}
|
||||
|
||||
void _onOpenFoodBank() {
|
||||
Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(builder: (_) => const FoodBankScreen()),
|
||||
);
|
||||
}
|
||||
|
||||
void _onOpenSettings() {
|
||||
Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => SettingsScreen(httpClient: widget.httpClient),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@ -353,25 +186,11 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
appBar: AppBar(
|
||||
title: const Text('Diet Guard'),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.restaurant_menu),
|
||||
tooltip: 'Food bank',
|
||||
onPressed: _onOpenFoodBank,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.history),
|
||||
tooltip: 'History',
|
||||
onPressed: _onOpenHistory,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.calendar_month),
|
||||
tooltip: 'Calendar',
|
||||
onPressed: _onOpenCalendar,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.settings),
|
||||
tooltip: 'Sync settings',
|
||||
onPressed: _onOpenSettings,
|
||||
...logMealAppBarActions(
|
||||
onFoodBank: onOpenFoodBank,
|
||||
onHistory: onOpenHistory,
|
||||
onCalendar: onOpenCalendar,
|
||||
onSettings: onOpenSettings,
|
||||
),
|
||||
],
|
||||
),
|
||||
@ -380,10 +199,10 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SyncHealthBanner(status: _syncHealth),
|
||||
SyncHealthBanner(status: syncHealth),
|
||||
SlotSelectorRow(
|
||||
now: DateTime.now(),
|
||||
loggedSlots: _loggedSlots,
|
||||
loggedSlots: loggedSlots,
|
||||
selectedSlot: _selectedSlot,
|
||||
onSlotSelected: (slot) => setState(() => _selectedSlot = slot),
|
||||
),
|
||||
|
||||
140
app/lib/screens/log_meal_sync_mixin.dart
Normal file
140
app/lib/screens/log_meal_sync_mixin.dart
Normal file
@ -0,0 +1,140 @@
|
||||
import 'dart:async';
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:diet_guard_app/services/background_tasks.dart';
|
||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_health.dart';
|
||||
import 'package:diet_guard_app/services/sync_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_settings.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// Background-sync and lifecycle behaviour for [LogMealScreen]'s state.
|
||||
///
|
||||
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. It is a
|
||||
/// mixin rather than a helper class because the behaviour is inseparable from
|
||||
/// the State it drives: it observes the widget lifecycle, calls `setState`,
|
||||
/// and reads `mounted`. The screen's own fields stay declared on the State and
|
||||
/// are reached here through the abstract members below, so the split moves
|
||||
/// behaviour without moving ownership of the widget's state.
|
||||
mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
||||
implements WidgetsBindingObserver {
|
||||
/// Single-flight guard so a launch sync and a lifecycle sync never overlap.
|
||||
bool autoSyncing = false;
|
||||
|
||||
/// Latest sync health, driving the "not syncing" banner. Null until read.
|
||||
SyncHealthStatus? syncHealth;
|
||||
|
||||
/// The slots that already carry a logged meal today.
|
||||
Set<int> loggedSlots = {};
|
||||
|
||||
/// The screen's injected HTTP client, or null to use the default.
|
||||
///
|
||||
/// Declared abstract so the mixin stays independent of the widget's own
|
||||
/// field: `widget` is typed `T` here, so `widget.httpClient` would not
|
||||
/// resolve. The State supplies it.
|
||||
http.Client? get syncHttpClient;
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
// Pull on resume (catch up on what another device logged while this one
|
||||
// was backgrounded) and push on pause (keep the remote near-current).
|
||||
final isResumeOrPause =
|
||||
state == AppLifecycleState.resumed || state == AppLifecycleState.paused;
|
||||
if (isResumeOrPause) {
|
||||
unawaited(autoSync());
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort background sync: silent, skips when unconfigured, and never
|
||||
/// overlaps itself. Failures are swallowed -- the Settings screen's manual
|
||||
/// "Sync now" is where errors get surfaced. The try wraps even loading
|
||||
/// [SyncSettings] itself: under `flutter test`, the shared_preferences and
|
||||
/// secure-storage platform channels are unmocked by default and throw
|
||||
/// [MissingPluginException], which must degrade exactly like "offline"
|
||||
/// rather than crash every screen that mounts this widget.
|
||||
///
|
||||
/// [refreshSlots] only runs after an actual sync (not on the unconfigured
|
||||
/// path, which every existing screen test takes): a fire-and-forget tail
|
||||
/// await here can resolve after a *later* test's `tearDown` has already
|
||||
/// reset [LogStorageService]'s singleton -- `mounted` alone doesn't bound
|
||||
/// that, since widget disposal between tests isn't synchronized with a
|
||||
/// still-pending Future from an earlier one.
|
||||
Future<void> autoSync() async {
|
||||
if (autoSyncing) return;
|
||||
autoSyncing = true;
|
||||
try {
|
||||
final settings = await SyncSettings.load();
|
||||
// Either backend counts. `isConfigured` means "has a GitHub token", so
|
||||
// gating on it alone silently skips every sync on a device connected
|
||||
// only to Firebase -- and once the mirror is retired that is every
|
||||
// device. Same fix workout_app's push() already carries.
|
||||
if (!settings.isConfigured && await openFirebase() == null) {
|
||||
// Never a silent return: an unconfigured device looked exactly like a
|
||||
// healthy one with nothing to send, which is how meals sat unpublished
|
||||
// for days. Recorded so the banner can say so.
|
||||
log(
|
||||
'diet_guard auto-sync: no backend configured; nothing to push',
|
||||
level: 900,
|
||||
);
|
||||
await SyncHealth.recordUnconfigured();
|
||||
if (mounted) await refreshSyncHealth();
|
||||
return;
|
||||
}
|
||||
final client = createGitHubClient(
|
||||
settings,
|
||||
httpClient: syncHttpClient,
|
||||
);
|
||||
try {
|
||||
await runSync(await syncBackend(client));
|
||||
await SyncHealth.recordSuccess();
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
if (!mounted) return;
|
||||
await refreshSlots();
|
||||
await refreshSyncHealth();
|
||||
} on Object catch (error, stackTrace) {
|
||||
// Best-effort, but never silent: this swallowed the reason a desktop
|
||||
// install could not publish at all, which looked identical to "nothing
|
||||
// to sync". Offline and unmocked-platform-channel-under-test both land
|
||||
// here too, so it stays non-fatal -- it just says why now.
|
||||
log(
|
||||
'diet_guard auto-sync failed',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
await SyncHealth.recordFailure();
|
||||
if (mounted) await refreshSyncHealth();
|
||||
} finally {
|
||||
autoSyncing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-reads sync health so the banner reflects the tick that just ran.
|
||||
Future<void> refreshSyncHealth() async {
|
||||
final status = await SyncHealth.read();
|
||||
if (!mounted) return;
|
||||
setState(() => syncHealth = status);
|
||||
}
|
||||
|
||||
/// Queues the platform's offline push backstop so a meal logged while
|
||||
/// offline still uploads on reconnect. The in-process [autoSync] covers
|
||||
/// the online case; this is the backstop (a no-op on web, which has no
|
||||
/// out-of-page scheduler -- see background_tasks.dart).
|
||||
// coverage:ignore-start
|
||||
/// Schedules the WorkManager backstop that syncs when the app is closed.
|
||||
Future<void> enqueueSyncBackstopTask() => enqueueSyncBackstop();
|
||||
|
||||
// coverage:ignore-end
|
||||
|
||||
/// Re-reads which meal slots are already logged today.
|
||||
Future<void> refreshSlots() async {
|
||||
final logged = await LogStorageService.instance.loggedSlotsToday();
|
||||
if (!mounted) return;
|
||||
setState(() => loggedSlots = logged);
|
||||
}
|
||||
}
|
||||
62
app/lib/screens/settings_kcal_goal.dart
Normal file
62
app/lib/screens/settings_kcal_goal.dart
Normal file
@ -0,0 +1,62 @@
|
||||
// The debounced daily-kcal-goal field and the battery-exemption request.
|
||||
//
|
||||
// Split out of `settings_screen.dart` for the repo's 250-line cap. A `part`
|
||||
// mixin: these drive the screen's private state and call `setState`, which is
|
||||
// `@protected` and therefore unreachable from an extension.
|
||||
|
||||
part of 'settings_screen.dart';
|
||||
|
||||
mixin _SettingsKcalGoal on State<SettingsScreen> {
|
||||
String? _status;
|
||||
|
||||
void _showMessage(String message) {
|
||||
if (!mounted) return;
|
||||
setState(() => _status = message);
|
||||
}
|
||||
|
||||
Timer? _kcalGoalDebounce;
|
||||
int? _pendingKcalGoal;
|
||||
|
||||
/// Persists the pending goal, if any, and clears it.
|
||||
void _flushKcalGoal() {
|
||||
final goal = _pendingKcalGoal;
|
||||
if (goal == null) return;
|
||||
_pendingKcalGoal = null;
|
||||
unawaited(AppSettingsService.instance.saveDailyKcalGoal(goal));
|
||||
}
|
||||
|
||||
/// Saves the typed goal once typing settles.
|
||||
///
|
||||
/// Debounced because every keystroke would otherwise be a real edit:
|
||||
/// typing "2000" saved 2, 20, 200, 2000 in turn, and a sync tick landing
|
||||
/// between keystrokes would push a nonsense budget to the other device.
|
||||
void _onKcalGoalChanged(String value) {
|
||||
_kcalGoalDebounce?.cancel();
|
||||
final goal = int.tryParse(value);
|
||||
if (goal == null || goal <= 0) return;
|
||||
_pendingKcalGoal = goal;
|
||||
_kcalGoalDebounce = Timer(
|
||||
const Duration(milliseconds: 600),
|
||||
_flushKcalGoal,
|
||||
);
|
||||
}
|
||||
|
||||
/// Requests exemption from OEM battery optimization (MIUI, some Samsung
|
||||
/// configs), which can otherwise degrade the 15-minute background-check
|
||||
/// reliability well past its accepted ±15 min target.
|
||||
Future<void> _requestBatteryExemption() async {
|
||||
final request =
|
||||
widget.requestBatteryExemption ??
|
||||
() => Permission.ignoreBatteryOptimizations.request();
|
||||
try {
|
||||
final status = await request();
|
||||
_showMessage(
|
||||
status.isGranted
|
||||
? 'Battery optimization exemption granted.'
|
||||
: 'Exemption not granted -- notifications may be delayed.',
|
||||
);
|
||||
} on Exception catch (e) {
|
||||
_showMessage('Could not request exemption: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -14,6 +14,7 @@ import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||
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/ui/theme.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
@ -23,6 +24,8 @@ import 'package:http/http.dart' as http;
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||
|
||||
part 'settings_kcal_goal.dart';
|
||||
|
||||
/// Screen for app-specific settings and links to sync configuration.
|
||||
class SettingsScreen extends StatefulWidget {
|
||||
/// Creates a [SettingsScreen].
|
||||
@ -87,7 +90,8 @@ class SettingsScreen extends StatefulWidget {
|
||||
State<SettingsScreen> createState() => _SettingsScreenState();
|
||||
}
|
||||
|
||||
class _SettingsScreenState extends State<SettingsScreen> {
|
||||
class _SettingsScreenState extends State<SettingsScreen>
|
||||
with _SettingsKcalGoal {
|
||||
final _kcalGoalController = TextEditingController();
|
||||
|
||||
@override
|
||||
@ -106,59 +110,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Timer? _kcalGoalDebounce;
|
||||
int? _pendingKcalGoal;
|
||||
|
||||
/// Persists the pending goal, if any, and clears it.
|
||||
void _flushKcalGoal() {
|
||||
final goal = _pendingKcalGoal;
|
||||
if (goal == null) return;
|
||||
_pendingKcalGoal = null;
|
||||
unawaited(AppSettingsService.instance.saveDailyKcalGoal(goal));
|
||||
}
|
||||
|
||||
/// Saves the typed goal once typing settles.
|
||||
///
|
||||
/// Debounced because every keystroke would otherwise be a real edit:
|
||||
/// typing "2000" saved 2, 20, 200, 2000 in turn, and a sync tick landing
|
||||
/// between keystrokes would push a nonsense budget to the other device.
|
||||
void _onKcalGoalChanged(String value) {
|
||||
_kcalGoalDebounce?.cancel();
|
||||
final goal = int.tryParse(value);
|
||||
if (goal == null || goal <= 0) return;
|
||||
_pendingKcalGoal = goal;
|
||||
_kcalGoalDebounce = Timer(
|
||||
const Duration(milliseconds: 600),
|
||||
_flushKcalGoal,
|
||||
);
|
||||
}
|
||||
|
||||
/// Requests exemption from OEM battery optimization (MIUI, some Samsung
|
||||
/// configs), which can otherwise degrade the 15-minute background-check
|
||||
/// reliability well past its accepted ±15 min target.
|
||||
Future<void> _requestBatteryExemption() async {
|
||||
final request =
|
||||
widget.requestBatteryExemption ??
|
||||
() => Permission.ignoreBatteryOptimizations.request();
|
||||
try {
|
||||
final status = await request();
|
||||
_showMessage(
|
||||
status.isGranted
|
||||
? 'Battery optimization exemption granted.'
|
||||
: 'Exemption not granted -- notifications may be delayed.',
|
||||
);
|
||||
} on Exception catch (e) {
|
||||
_showMessage('Could not request exemption: $e');
|
||||
}
|
||||
}
|
||||
|
||||
String? _status;
|
||||
|
||||
void _showMessage(String message) {
|
||||
if (!mounted) return;
|
||||
setState(() => _status = message);
|
||||
}
|
||||
|
||||
/// True on the one platform with OEM battery optimization to exempt from.
|
||||
///
|
||||
/// Uses [defaultTargetPlatform] rather than `Platform.isAndroid` because
|
||||
|
||||
@ -8,7 +8,7 @@ library;
|
||||
import 'dart:developer';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
|
||||
@ -14,9 +14,7 @@ library;
|
||||
|
||||
import 'dart:developer';
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// The shared `kuhy-syncs` project.
|
||||
///
|
||||
@ -99,184 +97,10 @@ Future<void> clearAccount() async {
|
||||
await credentialStore().clear();
|
||||
}
|
||||
|
||||
/// Returns a signed-in Firebase client, or null when not configured.
|
||||
/// Drops just the stored account marker, leaving the opt-out flag alone.
|
||||
///
|
||||
/// Signs in with the stored password only when there is no cached refresh
|
||||
/// token, so the usual path costs no authentication round trip.
|
||||
Future<FirebaseRestClient?> openFirebase() async {
|
||||
final account = await loadAccount();
|
||||
if (account == null) {
|
||||
// A stored refresh token is a signed-in device, even with no account
|
||||
// marker beside it. Treating the marker as the source of truth is what
|
||||
// turned one missing write into "syncs over GitHub and 401s forever":
|
||||
// the credential that actually authenticates was sitting in the keystore
|
||||
// the whole time, unused. Ask the store directly before giving up.
|
||||
return _clientFromStoredSession();
|
||||
}
|
||||
try {
|
||||
return await firebaseClientFor(
|
||||
config: kProject.configFor(account.email),
|
||||
store: credentialStore(),
|
||||
// A Google-provisioned account stores an empty password.
|
||||
// Passing '' would make firebaseClientFor treat it as a usable
|
||||
// credential and sign in with it, which fails; null correctly
|
||||
// means "no password on this device".
|
||||
password: account.password.isEmpty ? null : account.password,
|
||||
// Deliberately NOT offering Google here. This path runs from background
|
||||
// timers and, in some apps, before runApp -- offering it would let a
|
||||
// non-interactive tick raise the OS account picker with no user action
|
||||
// behind it. Interactive sign-in uses openFirebaseWithGoogle instead.
|
||||
expectedUid: kSyncUid,
|
||||
);
|
||||
} on Object catch (error, stackTrace) {
|
||||
// Unreachable keystore or a rejected sign-in must not fail the tick: the
|
||||
// app keeps syncing over GitHub, exactly as before the cutover.
|
||||
// Broader than Exception because an uninitialised platform binding
|
||||
// raises a FlutterError, which is an Error.
|
||||
//
|
||||
// Never silent, for the same reason loadAccount() above says why: a
|
||||
// signed-in-but-failing device looked exactly like an unconfigured one,
|
||||
// which is how the phone went days without publishing a single meal.
|
||||
log(
|
||||
'openFirebase failed; falling back to the GitHub mirror',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this device can actually authenticate against Firebase.
|
||||
///
|
||||
/// True when either half of the state is present: the account marker
|
||||
/// [loadAccount] reads, or a stored refresh token. The token is the half that
|
||||
/// matters -- it is what signs requests -- so a settings screen that reports
|
||||
/// the marker alone calls a working device "Not connected", which is how a
|
||||
/// phone that was in fact syncing looked broken for a whole session.
|
||||
Future<bool> isFirebaseConfigured() async {
|
||||
try {
|
||||
final auth = FirebaseTokenProvider(
|
||||
apiKey: kProject.apiKey,
|
||||
store: credentialStore(),
|
||||
);
|
||||
if (await auth.hasSession()) return true;
|
||||
// storedAccount, not loadAccount: on Android the latter falls back to the
|
||||
// desktop wrapper's /sync-account route, which resolves to file:/// and
|
||||
// throws "No host specified in URI" -- observed on the phone, where it
|
||||
// turned a successful sign-in into "Google sign-in failed".
|
||||
if (await storedAccount() == null) return false;
|
||||
// A marker with no session behind it cannot sign a single request. Drop
|
||||
// just the marker so the settings screen offers a sign-in instead of a
|
||||
// dead banner -- not clearAccount(), which also sets the opt-out flag and
|
||||
// would stop the desktop wrapper re-provisioning after the next sign-in.
|
||||
await _secure.delete(key: kFirebaseAccountKey);
|
||||
return false;
|
||||
} on Object catch (error, stackTrace) {
|
||||
log(
|
||||
'session probe failed; reporting this device as not configured',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a client built from the keystore's refresh token alone, or null.
|
||||
///
|
||||
/// The recovery path for a device that has a live session but no account
|
||||
/// marker -- the state a Google sign-in used to leave behind. Costs one
|
||||
/// keystore read and no network round trip when there is no session, so it is
|
||||
/// safe on the background-tick path that [openFirebase] also serves.
|
||||
///
|
||||
/// Does not re-save the account: a device that reaches this is already signed
|
||||
/// in, and writing a marker from a read path would hide the condition rather
|
||||
/// than repair it. [openFirebaseWithGoogle] is what writes the marker.
|
||||
Future<FirebaseRestClient?> _clientFromStoredSession() async {
|
||||
try {
|
||||
final auth = FirebaseTokenProvider(
|
||||
apiKey: kProject.apiKey,
|
||||
store: credentialStore(),
|
||||
);
|
||||
if (!await auth.hasSession()) return null;
|
||||
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
|
||||
} on Object catch (error, stackTrace) {
|
||||
// Same contract as openFirebase's own catch: an unreachable keystore
|
||||
// degrades to the GitHub mirror instead of failing the tick, but says so.
|
||||
log(
|
||||
'stored-session recovery failed; falling back to the GitHub mirror',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Signs in with Google alone, for a device that has no account stored yet.
|
||||
///
|
||||
/// This is the one-tap path: [openFirebase] needs an account in the keystore
|
||||
/// to know which email to use, but a fresh install has none. The Google token
|
||||
/// carries the identity, so nothing needs to be typed.
|
||||
///
|
||||
/// The account is stored under the email **Firebase reports**, never one read
|
||||
/// from the UI: a fresh install has no email anywhere on the device, so taking
|
||||
/// it from a text field would persist an empty account and send the next
|
||||
/// launch down the password path with ''.
|
||||
///
|
||||
/// Returns null when the user dismisses the picker; throws [FirebaseAuthError]
|
||||
/// when Google succeeds but resolves to a uid the security rules do not pin,
|
||||
/// which would otherwise authenticate fine and then be denied every read and
|
||||
/// write with no other symptom.
|
||||
Future<FirebaseRestClient?> openFirebaseWithGoogle({
|
||||
Future<String?> Function()? tokenFetcher,
|
||||
Future<void> Function(FirebaseAccount)? accountSaver,
|
||||
http.Client? httpClient,
|
||||
}) async {
|
||||
final token = await (tokenFetcher ?? googleIdToken)();
|
||||
if (token == null) return null;
|
||||
final auth = FirebaseTokenProvider(
|
||||
apiKey: kProject.apiKey,
|
||||
store: credentialStore(),
|
||||
httpClient: httpClient,
|
||||
);
|
||||
final email = await auth.signInWithGoogle(
|
||||
idToken: token,
|
||||
expectedUid: kSyncUid,
|
||||
);
|
||||
// The account must be saved unconditionally, and the signed-in email is not
|
||||
// reliable enough to gate it on. `signInWithIdp` omits `email` whenever the
|
||||
// Google account hides it, so gating the save on a non-null email produced
|
||||
// the worst possible outcome: this call returned a perfectly working client
|
||||
// -- "Connected to Firebase" -- while the device stayed unconfigured, so the
|
||||
// next launch found no account, `openFirebase()` returned null, and
|
||||
// `syncBackend()` silently dropped to GitHub-only and 401'd. The session is
|
||||
// already durable at this point (`signInWithGoogle` stores the refresh token
|
||||
// via `_adopt`); only this marker was missing, which is exactly why the
|
||||
// failure survived a restart and looked like a sign-in that never happened.
|
||||
//
|
||||
// The email is a display convenience, not the credential -- the refresh
|
||||
// token in the keystore is. An empty string is the honest value when Google
|
||||
// withholds it, and `openFirebase()` already treats an empty password as
|
||||
// "no password on this device" and authenticates from the stored token.
|
||||
await (accountSaver ?? saveAccount)(
|
||||
FirebaseAccount(email: email ?? '', password: ''),
|
||||
);
|
||||
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
|
||||
}
|
||||
|
||||
// coverage:ignore-end
|
||||
|
||||
/// Wraps [github] so Firebase is primary and GitHub is kept as a mirror.
|
||||
///
|
||||
/// Returns [github] unchanged when this device has not been set up for
|
||||
/// Firebase — a normal state during the cutover, not an error, and also the
|
||||
/// rollback. Reads union both, so a device that has not moved yet still
|
||||
/// converges.
|
||||
Future<RemoteStore> syncBackend(RemoteStore github) async {
|
||||
final firebase = await openFirebase();
|
||||
return firebase == null
|
||||
? github
|
||||
: MirrorStore(primary: firebase, mirror: github);
|
||||
}
|
||||
/// Deliberately narrower than [clearAccount]: a marker with no session behind
|
||||
/// it cannot sign a request, but setting the opt-out flag as well would stop
|
||||
/// the desktop wrapper re-provisioning after the next sign-in.
|
||||
Future<void> forgetAccountMarker() =>
|
||||
_secure.delete(key: kFirebaseAccountKey);
|
||||
|
||||
197
app/lib/services/firebase_client.dart
Normal file
197
app/lib/services/firebase_client.dart
Normal file
@ -0,0 +1,197 @@
|
||||
/// Opening an authenticated Firebase REST client, and choosing a backend.
|
||||
///
|
||||
/// Split out of `firebase_backend.dart` for the repo's 250-line cap. That
|
||||
/// module owns the project constants and the keystore-backed account record;
|
||||
/// this one turns a stored account (or a Google sign-in) into a live client,
|
||||
/// and decides whether a sync tick runs against Firebase or the GitHub
|
||||
/// mirror.
|
||||
library;
|
||||
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// Returns a signed-in Firebase client, or null when not configured.
|
||||
///
|
||||
/// Signs in with the stored password only when there is no cached refresh
|
||||
/// token, so the usual path costs no authentication round trip.
|
||||
Future<FirebaseRestClient?> openFirebase() async {
|
||||
final account = await loadAccount();
|
||||
if (account == null) {
|
||||
// A stored refresh token is a signed-in device, even with no account
|
||||
// marker beside it. Treating the marker as the source of truth is what
|
||||
// turned one missing write into "syncs over GitHub and 401s forever":
|
||||
// the credential that actually authenticates was sitting in the keystore
|
||||
// the whole time, unused. Ask the store directly before giving up.
|
||||
return _clientFromStoredSession();
|
||||
}
|
||||
try {
|
||||
return await firebaseClientFor(
|
||||
config: kProject.configFor(account.email),
|
||||
store: credentialStore(),
|
||||
// A Google-provisioned account stores an empty password.
|
||||
// Passing '' would make firebaseClientFor treat it as a usable
|
||||
// credential and sign in with it, which fails; null correctly
|
||||
// means "no password on this device".
|
||||
password: account.password.isEmpty ? null : account.password,
|
||||
// Deliberately NOT offering Google here. This path runs from background
|
||||
// timers and, in some apps, before runApp -- offering it would let a
|
||||
// non-interactive tick raise the OS account picker with no user action
|
||||
// behind it. Interactive sign-in uses openFirebaseWithGoogle instead.
|
||||
expectedUid: kSyncUid,
|
||||
);
|
||||
} on Object catch (error, stackTrace) {
|
||||
// Unreachable keystore or a rejected sign-in must not fail the tick: the
|
||||
// app keeps syncing over GitHub, exactly as before the cutover.
|
||||
// Broader than Exception because an uninitialised platform binding
|
||||
// raises a FlutterError, which is an Error.
|
||||
//
|
||||
// Never silent, for the same reason loadAccount() above says why: a
|
||||
// signed-in-but-failing device looked exactly like an unconfigured one,
|
||||
// which is how the phone went days without publishing a single meal.
|
||||
log(
|
||||
'openFirebase failed; falling back to the GitHub mirror',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this device can actually authenticate against Firebase.
|
||||
///
|
||||
/// True when either half of the state is present: the account marker
|
||||
/// [loadAccount] reads, or a stored refresh token. The token is the half that
|
||||
/// matters -- it is what signs requests -- so a settings screen that reports
|
||||
/// the marker alone calls a working device "Not connected", which is how a
|
||||
/// phone that was in fact syncing looked broken for a whole session.
|
||||
Future<bool> isFirebaseConfigured() async {
|
||||
try {
|
||||
final auth = FirebaseTokenProvider(
|
||||
apiKey: kProject.apiKey,
|
||||
store: credentialStore(),
|
||||
);
|
||||
if (await auth.hasSession()) return true;
|
||||
// storedAccount, not loadAccount: on Android the latter falls back to the
|
||||
// desktop wrapper's /sync-account route, which resolves to file:/// and
|
||||
// throws "No host specified in URI" -- observed on the phone, where it
|
||||
// turned a successful sign-in into "Google sign-in failed".
|
||||
if (await storedAccount() == null) return false;
|
||||
// A marker with no session behind it cannot sign a single request. Drop
|
||||
// just the marker so the settings screen offers a sign-in instead of a
|
||||
// dead banner -- not clearAccount(), which also sets the opt-out flag and
|
||||
// would stop the desktop wrapper re-provisioning after the next sign-in.
|
||||
await forgetAccountMarker();
|
||||
return false;
|
||||
} on Object catch (error, stackTrace) {
|
||||
log(
|
||||
'session probe failed; reporting this device as not configured',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a client built from the keystore's refresh token alone, or null.
|
||||
///
|
||||
/// The recovery path for a device that has a live session but no account
|
||||
/// marker -- the state a Google sign-in used to leave behind. Costs one
|
||||
/// keystore read and no network round trip when there is no session, so it is
|
||||
/// safe on the background-tick path that [openFirebase] also serves.
|
||||
///
|
||||
/// Does not re-save the account: a device that reaches this is already signed
|
||||
/// in, and writing a marker from a read path would hide the condition rather
|
||||
/// than repair it. [openFirebaseWithGoogle] is what writes the marker.
|
||||
Future<FirebaseRestClient?> _clientFromStoredSession() async {
|
||||
try {
|
||||
final auth = FirebaseTokenProvider(
|
||||
apiKey: kProject.apiKey,
|
||||
store: credentialStore(),
|
||||
);
|
||||
if (!await auth.hasSession()) return null;
|
||||
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
|
||||
} on Object catch (error, stackTrace) {
|
||||
// Same contract as openFirebase's own catch: an unreachable keystore
|
||||
// degrades to the GitHub mirror instead of failing the tick, but says so.
|
||||
log(
|
||||
'stored-session recovery failed; falling back to the GitHub mirror',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Signs in with Google alone, for a device that has no account stored yet.
|
||||
///
|
||||
/// This is the one-tap path: [openFirebase] needs an account in the keystore
|
||||
/// to know which email to use, but a fresh install has none. The Google token
|
||||
/// carries the identity, so nothing needs to be typed.
|
||||
///
|
||||
/// The account is stored under the email **Firebase reports**, never one read
|
||||
/// from the UI: a fresh install has no email anywhere on the device, so taking
|
||||
/// it from a text field would persist an empty account and send the next
|
||||
/// launch down the password path with ''.
|
||||
///
|
||||
/// Returns null when the user dismisses the picker; throws [FirebaseAuthError]
|
||||
/// when Google succeeds but resolves to a uid the security rules do not pin,
|
||||
/// which would otherwise authenticate fine and then be denied every read and
|
||||
/// write with no other symptom.
|
||||
Future<FirebaseRestClient?> openFirebaseWithGoogle({
|
||||
Future<String?> Function()? tokenFetcher,
|
||||
Future<void> Function(FirebaseAccount)? accountSaver,
|
||||
http.Client? httpClient,
|
||||
}) async {
|
||||
final token = await (tokenFetcher ?? googleIdToken)();
|
||||
if (token == null) return null;
|
||||
final auth = FirebaseTokenProvider(
|
||||
apiKey: kProject.apiKey,
|
||||
store: credentialStore(),
|
||||
httpClient: httpClient,
|
||||
);
|
||||
final email = await auth.signInWithGoogle(
|
||||
idToken: token,
|
||||
expectedUid: kSyncUid,
|
||||
);
|
||||
// The account must be saved unconditionally, and the signed-in email is not
|
||||
// reliable enough to gate it on. `signInWithIdp` omits `email` whenever the
|
||||
// Google account hides it, so gating the save on a non-null email produced
|
||||
// the worst possible outcome: this call returned a perfectly working client
|
||||
// -- "Connected to Firebase" -- while the device stayed unconfigured, so the
|
||||
// next launch found no account, `openFirebase()` returned null, and
|
||||
// `syncBackend()` silently dropped to GitHub-only and 401'd. The session is
|
||||
// already durable at this point (`signInWithGoogle` stores the refresh token
|
||||
// via `_adopt`); only this marker was missing, which is exactly why the
|
||||
// failure survived a restart and looked like a sign-in that never happened.
|
||||
//
|
||||
// The email is a display convenience, not the credential -- the refresh
|
||||
// token in the keystore is. An empty string is the honest value when Google
|
||||
// withholds it, and `openFirebase()` already treats an empty password as
|
||||
// "no password on this device" and authenticates from the stored token.
|
||||
await (accountSaver ?? saveAccount)(
|
||||
FirebaseAccount(email: email ?? '', password: ''),
|
||||
);
|
||||
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
|
||||
}
|
||||
|
||||
// coverage:ignore-end
|
||||
|
||||
/// Wraps [github] so Firebase is primary and GitHub is kept as a mirror.
|
||||
///
|
||||
/// Returns [github] unchanged when this device has not been set up for
|
||||
/// Firebase — a normal state during the cutover, not an error, and also the
|
||||
/// rollback. Reads union both, so a device that has not moved yet still
|
||||
/// converges.
|
||||
Future<RemoteStore> syncBackend(RemoteStore github) async {
|
||||
final firebase = await openFirebase();
|
||||
return firebase == null
|
||||
? github
|
||||
: MirrorStore(primary: firebase, mirror: github);
|
||||
}
|
||||
@ -15,6 +15,8 @@ import 'package:diet_guard_app/services/fuzzy.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
part 'foodbank_service_manual.dart';
|
||||
|
||||
/// Below this similarity ratio a non-substring candidate is dropped.
|
||||
/// Mirrors `_foodbank._FUZZY_THRESHOLD`.
|
||||
const double fuzzyThreshold = 0.6;
|
||||
@ -204,111 +206,4 @@ class FoodBankService {
|
||||
await writeBank(bank);
|
||||
return bank;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Manual bank (food items added directly without logging them as eaten)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Future<Map<String, FoodBankRecord>> _readManualBank() =>
|
||||
_readBank(manualDocumentName);
|
||||
|
||||
Future<void> _writeManualBank(Map<String, FoodBankRecord> bank) =>
|
||||
_writeBank(manualDocumentName, bank);
|
||||
|
||||
/// Adds or updates [record] in the manually-curated bank without logging it
|
||||
/// as eaten. A repeated call with the same normalized name overwrites the
|
||||
/// previous entry.
|
||||
Future<void> addManualEntry(FoodBankRecord record) async {
|
||||
final bank = await _readManualBank();
|
||||
bank[_normalize(record.desc)] = FoodBankRecord(
|
||||
desc: record.desc,
|
||||
kcal: record.kcal,
|
||||
proteinG: record.proteinG,
|
||||
carbsG: record.carbsG,
|
||||
fatG: record.fatG,
|
||||
grams: record.grams,
|
||||
count: record.count,
|
||||
components: record.components,
|
||||
// Stamped here, not by callers: this is what the cross-device merge
|
||||
// orders by, so it must be set on every write without exception.
|
||||
editedAt: DateTime.now().toIso8601String(),
|
||||
);
|
||||
await _writeManualBank(bank);
|
||||
}
|
||||
|
||||
/// Returns the hand-curated bank, for the sync layer.
|
||||
Future<Map<String, FoodBankRecord>> readManualBank() => _readManualBank();
|
||||
|
||||
/// Replaces the hand-curated bank with a merge result from the sync layer.
|
||||
Future<void> applyMergedManualBank(Map<String, FoodBankRecord> bank) =>
|
||||
_writeManualBank(bank);
|
||||
|
||||
/// All known food records: log-derived entries merged with manually-added
|
||||
/// ones, sorted by count descending.
|
||||
///
|
||||
/// Log-derived records (from [readBank]) take precedence over manual records
|
||||
/// with the same normalized name.
|
||||
Future<List<FoodBankRecord>> mergedEntries() async {
|
||||
final logBank = await readBank();
|
||||
final manualBank = await _readManualBank();
|
||||
final merged = <String, FoodBankRecord>{...manualBank, ...logBank};
|
||||
return merged.values.toList()..sort((a, b) => b.count.compareTo(a.count));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Search
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Returns banked foods matching [query], best match first.
|
||||
///
|
||||
/// An empty query returns the most-logged foods. Mirrors
|
||||
/// `_foodbank.search_foods`. Searches both log-derived and manually-added
|
||||
/// entries; log-derived entries win on name collision.
|
||||
Future<List<FoodSuggestion>> search(
|
||||
String query, {
|
||||
int limit = defaultSuggestions,
|
||||
}) async {
|
||||
final logBank = await readBank();
|
||||
final manualBank = await _readManualBank();
|
||||
final bank = <String, FoodBankRecord>{...manualBank, ...logBank};
|
||||
final normalized = _normalize(query);
|
||||
if (normalized.isEmpty) return _rankedAll(bank, limit);
|
||||
|
||||
final scored = <(double score, double count, FoodSuggestion suggestion)>[];
|
||||
for (final mapEntry in bank.entries) {
|
||||
final score = matchScore(normalized, mapEntry.key);
|
||||
if (score < fuzzyThreshold) continue;
|
||||
final record = mapEntry.value;
|
||||
scored.add((
|
||||
score,
|
||||
record.count,
|
||||
FoodSuggestion(
|
||||
name: _displayName(record, mapEntry.key),
|
||||
nutrition: _recordToNutrition(record),
|
||||
),
|
||||
));
|
||||
}
|
||||
scored.sort((a, b) {
|
||||
final byScore = b.$1.compareTo(a.$1);
|
||||
return byScore != 0 ? byScore : b.$2.compareTo(a.$2);
|
||||
});
|
||||
return scored.take(limit).map((s) => s.$3).toList();
|
||||
}
|
||||
|
||||
List<FoodSuggestion> _rankedAll(
|
||||
Map<String, FoodBankRecord> bank,
|
||||
int limit,
|
||||
) {
|
||||
final ranked = bank.entries.toList()
|
||||
..sort((a, b) => b.value.count.compareTo(a.value.count));
|
||||
return ranked
|
||||
.take(limit)
|
||||
.map(
|
||||
(mapEntry) => FoodSuggestion(
|
||||
name: _displayName(mapEntry.value, mapEntry.key),
|
||||
nutrition: _recordToNutrition(mapEntry.value),
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
121
app/lib/services/foodbank_service_manual.dart
Normal file
121
app/lib/services/foodbank_service_manual.dart
Normal file
@ -0,0 +1,121 @@
|
||||
// The curated ("manual") half of the food bank, plus ranked search across
|
||||
// both halves.
|
||||
//
|
||||
// Split out of `foodbank_service.dart` for the repo's 250-line cap. It is a
|
||||
// `part` rather than a separate library because these methods reach the
|
||||
// service's private members (`_readBank`, `_writeBank`, `_normalize`,
|
||||
// `_recordToNutrition`), which a `library`-private name makes invisible
|
||||
// across a file boundary -- and widening them to public just to split a file
|
||||
// would leak internals the rest of the app has no business calling.
|
||||
|
||||
part of 'foodbank_service.dart';
|
||||
|
||||
/// The curated bank and cross-bank search, split out for the file cap.
|
||||
extension FoodBankManual on FoodBankService {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Manual bank (food items added directly without logging them as eaten)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Future<Map<String, FoodBankRecord>> _readManualBank() =>
|
||||
_readBank(FoodBankService.manualDocumentName);
|
||||
|
||||
Future<void> _writeManualBank(Map<String, FoodBankRecord> bank) =>
|
||||
_writeBank(FoodBankService.manualDocumentName, bank);
|
||||
|
||||
/// Adds or updates [record] in the manually-curated bank without logging it
|
||||
/// as eaten. A repeated call with the same normalized name overwrites the
|
||||
/// previous entry.
|
||||
Future<void> addManualEntry(FoodBankRecord record) async {
|
||||
final bank = await _readManualBank();
|
||||
bank[_normalize(record.desc)] = FoodBankRecord(
|
||||
desc: record.desc,
|
||||
kcal: record.kcal,
|
||||
proteinG: record.proteinG,
|
||||
carbsG: record.carbsG,
|
||||
fatG: record.fatG,
|
||||
grams: record.grams,
|
||||
count: record.count,
|
||||
components: record.components,
|
||||
// Stamped here, not by callers: this is what the cross-device merge
|
||||
// orders by, so it must be set on every write without exception.
|
||||
editedAt: DateTime.now().toIso8601String(),
|
||||
);
|
||||
await _writeManualBank(bank);
|
||||
}
|
||||
|
||||
/// Returns the hand-curated bank, for the sync layer.
|
||||
Future<Map<String, FoodBankRecord>> readManualBank() => _readManualBank();
|
||||
|
||||
/// Replaces the hand-curated bank with a merge result from the sync layer.
|
||||
Future<void> applyMergedManualBank(Map<String, FoodBankRecord> bank) =>
|
||||
_writeManualBank(bank);
|
||||
|
||||
/// All known food records: log-derived entries merged with manually-added
|
||||
/// ones, sorted by count descending.
|
||||
///
|
||||
/// Log-derived records (from [readBank]) take precedence over manual records
|
||||
/// with the same normalized name.
|
||||
Future<List<FoodBankRecord>> mergedEntries() async {
|
||||
final logBank = await readBank();
|
||||
final manualBank = await _readManualBank();
|
||||
final merged = <String, FoodBankRecord>{...manualBank, ...logBank};
|
||||
return merged.values.toList()..sort((a, b) => b.count.compareTo(a.count));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Search
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Returns banked foods matching [query], best match first.
|
||||
///
|
||||
/// An empty query returns the most-logged foods. Mirrors
|
||||
/// `_foodbank.search_foods`. Searches both log-derived and manually-added
|
||||
/// entries; log-derived entries win on name collision.
|
||||
Future<List<FoodSuggestion>> search(
|
||||
String query, {
|
||||
int limit = defaultSuggestions,
|
||||
}) async {
|
||||
final logBank = await readBank();
|
||||
final manualBank = await _readManualBank();
|
||||
final bank = <String, FoodBankRecord>{...manualBank, ...logBank};
|
||||
final normalized = _normalize(query);
|
||||
if (normalized.isEmpty) return _rankedAll(bank, limit);
|
||||
|
||||
final scored = <(double score, double count, FoodSuggestion suggestion)>[];
|
||||
for (final mapEntry in bank.entries) {
|
||||
final score = matchScore(normalized, mapEntry.key);
|
||||
if (score < fuzzyThreshold) continue;
|
||||
final record = mapEntry.value;
|
||||
scored.add((
|
||||
score,
|
||||
record.count,
|
||||
FoodSuggestion(
|
||||
name: _displayName(record, mapEntry.key),
|
||||
nutrition: _recordToNutrition(record),
|
||||
),
|
||||
));
|
||||
}
|
||||
scored.sort((a, b) {
|
||||
final byScore = b.$1.compareTo(a.$1);
|
||||
return byScore != 0 ? byScore : b.$2.compareTo(a.$2);
|
||||
});
|
||||
return scored.take(limit).map((s) => s.$3).toList();
|
||||
}
|
||||
|
||||
List<FoodSuggestion> _rankedAll(
|
||||
Map<String, FoodBankRecord> bank,
|
||||
int limit,
|
||||
) {
|
||||
final ranked = bank.entries.toList()
|
||||
..sort((a, b) => b.value.count.compareTo(a.value.count));
|
||||
return ranked
|
||||
.take(limit)
|
||||
.map(
|
||||
(mapEntry) => FoodSuggestion(
|
||||
name: _displayName(mapEntry.value, mapEntry.key),
|
||||
nutrition: _recordToNutrition(mapEntry.value),
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@ -29,16 +29,19 @@
|
||||
/// adapters field-for-field.
|
||||
library;
|
||||
|
||||
|
||||
import 'dart:convert';
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:diet_guard_app/models/food_bank_record.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';
|
||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||
|
||||
// The bank and budget adapters moved out for file size. Re-exported here so
|
||||
// `import 'services/sync_merge.dart'` still reaches every adapter, which is
|
||||
// what sync_service.dart and both test files expect.
|
||||
export 'package:diet_guard_app/services/sync_merge_banks.dart';
|
||||
export 'package:diet_guard_app/services/sync_merge_budget.dart';
|
||||
|
||||
/// Derives a deterministic [Hlc] for [entry] from its own `time` field.
|
||||
///
|
||||
/// The same entry always yields the same Hlc regardless of when this runs
|
||||
@ -185,291 +188,3 @@ String encodeLogForPush(Log log) {
|
||||
};
|
||||
return jsonEncode(encoded);
|
||||
}
|
||||
|
||||
/// Converts the log-derived food bank into a crdt_sync [Log].
|
||||
///
|
||||
/// The bank is *derived* -- both devices replay the same synced log and
|
||||
/// compute the same records -- so this exists to make them agree
|
||||
/// **immediately** rather than only after each has replayed.
|
||||
///
|
||||
/// The clock is the record's own `count`, not a wall time, so
|
||||
/// last-writer-wins means *max-count-wins*: the device that has seen more of
|
||||
/// the log has the higher count, and re-merging is idempotent because the
|
||||
/// count does not move unless the log did. Mirrors
|
||||
/// `_sync_merge.food_bank_to_log`.
|
||||
Log foodBankToLog(Map<String, FoodBankRecord> bank) {
|
||||
final log = <String, Record>{};
|
||||
for (final mapEntry in bank.entries) {
|
||||
log[mapEntry.key] = Record(
|
||||
id: mapEntry.key,
|
||||
fields: {
|
||||
'body': (
|
||||
mapEntry.value.toJson(),
|
||||
Hlc.newTick(
|
||||
currentSyncDeviceId,
|
||||
wallTimeMsOverride: mapEntry.value.count.toInt(),
|
||||
),
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
/// Converts a merged food-bank [Log] back into bank shape.
|
||||
Map<String, FoodBankRecord> logToFoodBank(Log log) {
|
||||
final bank = <String, FoodBankRecord>{};
|
||||
for (final mapEntry in log.entries) {
|
||||
if (mapEntry.value.deleted) continue;
|
||||
final body = mapEntry.value.fields['body']?.$1;
|
||||
if (body is! Map) continue;
|
||||
bank[mapEntry.key] = FoodBankRecord.fromJson(
|
||||
Map<String, dynamic>.from(body.cast<String, dynamic>()),
|
||||
);
|
||||
}
|
||||
return bank;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed `food_bank.json` into a crdt_sync [Log].
|
||||
Log parseRemoteFoodBank(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level food-bank payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
return raw.cast<String, dynamic>().map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged food-bank [Log] for push.
|
||||
String encodeFoodBankForPush(Log log) => jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
});
|
||||
|
||||
/// Converts the hand-curated food bank into a crdt_sync [Log].
|
||||
///
|
||||
/// One record per normalized food name, carrying the whole bank record as an
|
||||
/// opaque `body` -- the same shape food-log entries use. Unlike an entry a
|
||||
/// curated food is editable, so its [Hlc] comes from the record's own
|
||||
/// `editedAt` stamp rather than a fixed birth time. Mirrors
|
||||
/// `_sync_merge.manual_bank_to_log`.
|
||||
Log manualBankToLog(Map<String, FoodBankRecord> bank) {
|
||||
final log = <String, Record>{};
|
||||
for (final mapEntry in bank.entries) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(
|
||||
mapEntry.value.editedAt ?? '',
|
||||
)?.toUtc().millisecondsSinceEpoch ??
|
||||
0;
|
||||
final body = Map<String, dynamic>.from(mapEntry.value.toJson())
|
||||
..remove('t');
|
||||
log[mapEntry.key] = Record(
|
||||
id: mapEntry.key,
|
||||
fields: {
|
||||
'body': (
|
||||
body,
|
||||
Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs),
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
/// Converts a merged curated-bank [Log] back into bank shape.
|
||||
///
|
||||
/// Each record's `editedAt` is reconstructed from its field [Hlc], so the
|
||||
/// stored stamp and the clock the merge compared can never drift apart.
|
||||
/// Mirrors `_sync_merge.log_to_manual_bank`.
|
||||
Map<String, FoodBankRecord> logToManualBank(Log log) {
|
||||
final bank = <String, FoodBankRecord>{};
|
||||
for (final mapEntry in log.entries) {
|
||||
if (mapEntry.value.deleted) continue;
|
||||
final field = mapEntry.value.fields['body'];
|
||||
final body = field?.$1;
|
||||
if (body is! Map) continue;
|
||||
final json = Map<String, dynamic>.from(body.cast<String, dynamic>());
|
||||
final hlc = field?.$2;
|
||||
if (hlc != null) {
|
||||
json['t'] = DateTime.fromMillisecondsSinceEpoch(
|
||||
hlc.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String();
|
||||
}
|
||||
bank[mapEntry.key] = FoodBankRecord.fromJson(json);
|
||||
}
|
||||
return bank;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed curated-bank text into a crdt_sync [Log].
|
||||
Log parseRemoteManualBank(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level curated-bank payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
return raw.cast<String, dynamic>().map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged curated-bank [Log] for push.
|
||||
String encodeManualBankForPush(Log log) => jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
});
|
||||
|
||||
/// Stable id: exactly one budget record per device-pushed `budget.json`.
|
||||
const budgetRecordId = 'budget';
|
||||
|
||||
/// Derives a deterministic [Hlc] for a raw budget record from its `t` field.
|
||||
///
|
||||
/// Mirrors [entryHlc]'s determinism -- the same unedited record always
|
||||
/// yields the same Hlc, so re-syncing an unchanged budget is a no-op -- but
|
||||
/// reads `t` (bumped on every explicit edit) rather than a fixed birth
|
||||
/// time, since a budget can be edited repeatedly and the *edit* time is
|
||||
/// what last-writer-wins must compare.
|
||||
Hlc budgetHlc(Map<String, dynamic> record) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(
|
||||
record['t'] as String? ?? '',
|
||||
)?.toUtc().millisecondsSinceEpoch ??
|
||||
0;
|
||||
return Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs);
|
||||
}
|
||||
|
||||
/// Field-name prefix for the effective-from budget history, one field per
|
||||
/// date. A separate *field* rather than a separate document, because
|
||||
/// `mergeRecord` unions field names -- see [budgetToLog].
|
||||
const budgetHistoryFieldPrefix = 'hist:';
|
||||
|
||||
/// Derives a deterministic [Hlc] for one history entry from its edit time.
|
||||
///
|
||||
/// Same trick as [budgetHlc]: identical inputs always yield the same clock,
|
||||
/// so re-syncing unchanged history is a no-op. Two devices that seed the
|
||||
/// history independently derive the same wall time and the same value and
|
||||
/// differ only in node id, so whichever side wins the field-level LWW, the
|
||||
/// value is identical and the merge converges in one round.
|
||||
Hlc historyHlc(BudgetEntry entry) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(entry.editedAt)?.toUtc().millisecondsSinceEpoch ?? 0;
|
||||
return Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs);
|
||||
}
|
||||
|
||||
/// Converts a raw local budget record plus its history into a [Log].
|
||||
///
|
||||
/// Returns an empty [Log] when [record] is null (this device has never
|
||||
/// explicitly set a budget), so it contributes nothing to the merge rather
|
||||
/// than clobbering another device's real value with the unset default.
|
||||
///
|
||||
/// The history rides along as one `hist:<YYYY-MM-DD>` field per entry on the
|
||||
/// *same* record. crdt_sync's `mergeRecord` is per-field LWW over the union
|
||||
/// of field names, so a device that predates the history neither clobbers
|
||||
/// those fields nor blocks them: it merges them in from the remote and
|
||||
/// pushes them straight back out (both sides push the *merged* log). That is
|
||||
/// what makes this safe to roll out without a coordinated release.
|
||||
///
|
||||
/// `w` (body weight) is stripped from `value` for the same reason the
|
||||
/// history is not stored there: inside the shared map it was collateral
|
||||
/// damage of whole-map LWW, since this device rebuilds that map without it.
|
||||
/// Python carries it as its own `weight` field instead, and this device
|
||||
/// relays that field untouched through the merged log even though it has no
|
||||
/// weight of its own to contribute -- so both devices still see one value.
|
||||
Log budgetToLog(
|
||||
Map<String, dynamic>? record, [
|
||||
List<BudgetEntry> entries = const [],
|
||||
]) {
|
||||
if (record == null) return {};
|
||||
final hlc = budgetHlc(record);
|
||||
final value = Map<String, dynamic>.from(record)
|
||||
..remove('t')
|
||||
..remove('w');
|
||||
final fields = <String, (dynamic, Hlc)>{'value': (value, hlc)};
|
||||
for (final entry in entries) {
|
||||
fields['$budgetHistoryFieldPrefix${entry.effectiveFrom}'] = (
|
||||
entry.kcal,
|
||||
historyHlc(entry),
|
||||
);
|
||||
}
|
||||
return {budgetRecordId: Record(id: budgetRecordId, fields: fields)};
|
||||
}
|
||||
|
||||
/// Extracts the effective-from history from a merged budget [Log].
|
||||
///
|
||||
/// Each entry's `editedAt` is reconstructed from its field Hlc rather than
|
||||
/// carried separately, so the stored timestamp and the clock the merge
|
||||
/// compared can never drift apart.
|
||||
List<BudgetEntry> logToHistory(Log log) {
|
||||
final record = log[budgetRecordId];
|
||||
if (record == null) return const [];
|
||||
final entries = <BudgetEntry>[];
|
||||
for (final field in record.fields.entries) {
|
||||
if (!field.key.startsWith(budgetHistoryFieldPrefix)) continue;
|
||||
final kcal = field.value.$1;
|
||||
if (kcal is! int) continue;
|
||||
entries.add(
|
||||
BudgetEntry(
|
||||
effectiveFrom: field.key.substring(budgetHistoryFieldPrefix.length),
|
||||
kcal: kcal,
|
||||
editedAt: DateTime.fromMillisecondsSinceEpoch(
|
||||
field.value.$2.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String(),
|
||||
),
|
||||
);
|
||||
}
|
||||
entries.sort((a, b) => a.effectiveFrom.compareTo(b.effectiveFrom));
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// Converts a merged budget [Log] back into a raw budget record.
|
||||
///
|
||||
/// Returns null when the log has no budget record at all (neither device
|
||||
/// has ever set one yet) -- callers treat that as "nothing to apply
|
||||
/// locally", not an error.
|
||||
Map<String, dynamic>? logToBudget(Log log) {
|
||||
final record = log[budgetRecordId];
|
||||
if (record == null) return null;
|
||||
final field = record.fields['value'];
|
||||
final value = field?.$1;
|
||||
final result = value is Map
|
||||
? Map<String, dynamic>.from(value.cast<String, dynamic>())
|
||||
: <String, dynamic>{};
|
||||
final hlc = field?.$2;
|
||||
if (hlc != null) {
|
||||
result['t'] = DateTime.fromMillisecondsSinceEpoch(
|
||||
hlc.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed `budget.json` text into a crdt_sync [Log].
|
||||
///
|
||||
/// Throwing [FormatException] or [TypeError] is treated as unparsable by
|
||||
/// the caller (`syncLog`'s `decode` callback), matching [parseRemoteLog]'s
|
||||
/// tolerance for a corrupt/truncated push. There is no legacy plain-format
|
||||
/// fallback here -- `budget.json` is a brand-new sync payload.
|
||||
Log parseRemoteBudget(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level budget payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
final rawMap = raw.cast<String, dynamic>();
|
||||
return rawMap.map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged budget [Log] for push.
|
||||
String encodeBudgetForPush(Log log) {
|
||||
final encoded = <String, dynamic>{
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
};
|
||||
return jsonEncode(encoded);
|
||||
}
|
||||
|
||||
151
app/lib/services/sync_merge_banks.dart
Normal file
151
app/lib/services/sync_merge_banks.dart
Normal file
@ -0,0 +1,151 @@
|
||||
/// Food-bank <-> crdt_sync.Record adapters, for both halves of the bank.
|
||||
///
|
||||
/// Split out of `sync_merge.dart` for file size; that file re-exports these
|
||||
/// so existing importers keep working.
|
||||
///
|
||||
/// The derived bank's merge clock is the record's own `count`, not a wall
|
||||
/// time: last-writer-wins therefore means *max-count-wins*, which is the
|
||||
/// correct merge for a derived counter and is idempotent. The curated
|
||||
/// (manual) bank is one record per normalized name, LWW by `editedAt`.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||
|
||||
/// Converts the log-derived food bank into a crdt_sync [Log].
|
||||
///
|
||||
/// The bank is *derived* -- both devices replay the same synced log and
|
||||
/// compute the same records -- so this exists to make them agree
|
||||
/// **immediately** rather than only after each has replayed.
|
||||
///
|
||||
/// The clock is the record's own `count`, not a wall time, so
|
||||
/// last-writer-wins means *max-count-wins*: the device that has seen more of
|
||||
/// the log has the higher count, and re-merging is idempotent because the
|
||||
/// count does not move unless the log did. Mirrors
|
||||
/// `_sync_merge.food_bank_to_log`.
|
||||
Log foodBankToLog(Map<String, FoodBankRecord> bank) {
|
||||
final log = <String, Record>{};
|
||||
for (final mapEntry in bank.entries) {
|
||||
log[mapEntry.key] = Record(
|
||||
id: mapEntry.key,
|
||||
fields: {
|
||||
'body': (
|
||||
mapEntry.value.toJson(),
|
||||
Hlc.newTick(
|
||||
currentSyncDeviceId,
|
||||
wallTimeMsOverride: mapEntry.value.count.toInt(),
|
||||
),
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
/// Converts a merged food-bank [Log] back into bank shape.
|
||||
Map<String, FoodBankRecord> logToFoodBank(Log log) {
|
||||
final bank = <String, FoodBankRecord>{};
|
||||
for (final mapEntry in log.entries) {
|
||||
if (mapEntry.value.deleted) continue;
|
||||
final body = mapEntry.value.fields['body']?.$1;
|
||||
if (body is! Map) continue;
|
||||
bank[mapEntry.key] = FoodBankRecord.fromJson(
|
||||
Map<String, dynamic>.from(body.cast<String, dynamic>()),
|
||||
);
|
||||
}
|
||||
return bank;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed `food_bank.json` into a crdt_sync [Log].
|
||||
Log parseRemoteFoodBank(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level food-bank payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
return raw.cast<String, dynamic>().map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged food-bank [Log] for push.
|
||||
String encodeFoodBankForPush(Log log) => jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
});
|
||||
|
||||
/// Converts the hand-curated food bank into a crdt_sync [Log].
|
||||
///
|
||||
/// One record per normalized food name, carrying the whole bank record as an
|
||||
/// opaque `body` -- the same shape food-log entries use. Unlike an entry a
|
||||
/// curated food is editable, so its [Hlc] comes from the record's own
|
||||
/// `editedAt` stamp rather than a fixed birth time. Mirrors
|
||||
/// `_sync_merge.manual_bank_to_log`.
|
||||
Log manualBankToLog(Map<String, FoodBankRecord> bank) {
|
||||
final log = <String, Record>{};
|
||||
for (final mapEntry in bank.entries) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(
|
||||
mapEntry.value.editedAt ?? '',
|
||||
)?.toUtc().millisecondsSinceEpoch ??
|
||||
0;
|
||||
final body = Map<String, dynamic>.from(mapEntry.value.toJson())
|
||||
..remove('t');
|
||||
log[mapEntry.key] = Record(
|
||||
id: mapEntry.key,
|
||||
fields: {
|
||||
'body': (
|
||||
body,
|
||||
Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs),
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
/// Converts a merged curated-bank [Log] back into bank shape.
|
||||
///
|
||||
/// Each record's `editedAt` is reconstructed from its field [Hlc], so the
|
||||
/// stored stamp and the clock the merge compared can never drift apart.
|
||||
/// Mirrors `_sync_merge.log_to_manual_bank`.
|
||||
Map<String, FoodBankRecord> logToManualBank(Log log) {
|
||||
final bank = <String, FoodBankRecord>{};
|
||||
for (final mapEntry in log.entries) {
|
||||
if (mapEntry.value.deleted) continue;
|
||||
final field = mapEntry.value.fields['body'];
|
||||
final body = field?.$1;
|
||||
if (body is! Map) continue;
|
||||
final json = Map<String, dynamic>.from(body.cast<String, dynamic>());
|
||||
final hlc = field?.$2;
|
||||
if (hlc != null) {
|
||||
json['t'] = DateTime.fromMillisecondsSinceEpoch(
|
||||
hlc.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String();
|
||||
}
|
||||
bank[mapEntry.key] = FoodBankRecord.fromJson(json);
|
||||
}
|
||||
return bank;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed curated-bank text into a crdt_sync [Log].
|
||||
Log parseRemoteManualBank(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level curated-bank payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
return raw.cast<String, dynamic>().map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged curated-bank [Log] for push.
|
||||
String encodeManualBankForPush(Log log) => jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
});
|
||||
170
app/lib/services/sync_merge_budget.dart
Normal file
170
app/lib/services/sync_merge_budget.dart
Normal file
@ -0,0 +1,170 @@
|
||||
/// Budget and budget-history <-> crdt_sync.Record adapters.
|
||||
///
|
||||
/// Split out of `sync_merge.dart` for file size; that file re-exports these
|
||||
/// so existing importers keep working.
|
||||
///
|
||||
/// A budget record is edited repeatedly rather than immutable-after-creation
|
||||
/// like a food-log entry, so its [Hlc] derives from a `t` edit timestamp
|
||||
/// rather than a birth time that never changes. History rides along as
|
||||
/// `hist:<YYYY-MM-DD>` fields on the same record, so a device predating the
|
||||
/// feature relays them untouched. Mirrors `diet_guard/_sync_merge.py`.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/services/budget_schedule.dart';
|
||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||
|
||||
/// Stable id: exactly one budget record per device-pushed `budget.json`.
|
||||
const budgetRecordId = 'budget';
|
||||
|
||||
/// Derives a deterministic [Hlc] for a raw budget record from its `t` field.
|
||||
///
|
||||
/// Mirrors [entryHlc]'s determinism -- the same unedited record always
|
||||
/// yields the same Hlc, so re-syncing an unchanged budget is a no-op -- but
|
||||
/// reads `t` (bumped on every explicit edit) rather than a fixed birth
|
||||
/// time, since a budget can be edited repeatedly and the *edit* time is
|
||||
/// what last-writer-wins must compare.
|
||||
Hlc budgetHlc(Map<String, dynamic> record) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(
|
||||
record['t'] as String? ?? '',
|
||||
)?.toUtc().millisecondsSinceEpoch ??
|
||||
0;
|
||||
return Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs);
|
||||
}
|
||||
|
||||
/// Field-name prefix for the effective-from budget history, one field per
|
||||
/// date. A separate *field* rather than a separate document, because
|
||||
/// `mergeRecord` unions field names -- see [budgetToLog].
|
||||
const budgetHistoryFieldPrefix = 'hist:';
|
||||
|
||||
/// Derives a deterministic [Hlc] for one history entry from its edit time.
|
||||
///
|
||||
/// Same trick as [budgetHlc]: identical inputs always yield the same clock,
|
||||
/// so re-syncing unchanged history is a no-op. Two devices that seed the
|
||||
/// history independently derive the same wall time and the same value and
|
||||
/// differ only in node id, so whichever side wins the field-level LWW, the
|
||||
/// value is identical and the merge converges in one round.
|
||||
Hlc historyHlc(BudgetEntry entry) {
|
||||
final wallTimeMs =
|
||||
DateTime.tryParse(entry.editedAt)?.toUtc().millisecondsSinceEpoch ?? 0;
|
||||
return Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs);
|
||||
}
|
||||
|
||||
/// Converts a raw local budget record plus its history into a [Log].
|
||||
///
|
||||
/// Returns an empty [Log] when [record] is null (this device has never
|
||||
/// explicitly set a budget), so it contributes nothing to the merge rather
|
||||
/// than clobbering another device's real value with the unset default.
|
||||
///
|
||||
/// The history rides along as one `hist:<YYYY-MM-DD>` field per entry on the
|
||||
/// *same* record. crdt_sync's `mergeRecord` is per-field LWW over the union
|
||||
/// of field names, so a device that predates the history neither clobbers
|
||||
/// those fields nor blocks them: it merges them in from the remote and
|
||||
/// pushes them straight back out (both sides push the *merged* log). That is
|
||||
/// what makes this safe to roll out without a coordinated release.
|
||||
///
|
||||
/// `w` (body weight) is stripped from `value` for the same reason the
|
||||
/// history is not stored there: inside the shared map it was collateral
|
||||
/// damage of whole-map LWW, since this device rebuilds that map without it.
|
||||
/// Python carries it as its own `weight` field instead, and this device
|
||||
/// relays that field untouched through the merged log even though it has no
|
||||
/// weight of its own to contribute -- so both devices still see one value.
|
||||
Log budgetToLog(
|
||||
Map<String, dynamic>? record, [
|
||||
List<BudgetEntry> entries = const [],
|
||||
]) {
|
||||
if (record == null) return {};
|
||||
final hlc = budgetHlc(record);
|
||||
final value = Map<String, dynamic>.from(record)
|
||||
..remove('t')
|
||||
..remove('w');
|
||||
final fields = <String, (dynamic, Hlc)>{'value': (value, hlc)};
|
||||
for (final entry in entries) {
|
||||
fields['$budgetHistoryFieldPrefix${entry.effectiveFrom}'] = (
|
||||
entry.kcal,
|
||||
historyHlc(entry),
|
||||
);
|
||||
}
|
||||
return {budgetRecordId: Record(id: budgetRecordId, fields: fields)};
|
||||
}
|
||||
|
||||
/// Extracts the effective-from history from a merged budget [Log].
|
||||
///
|
||||
/// Each entry's `editedAt` is reconstructed from its field Hlc rather than
|
||||
/// carried separately, so the stored timestamp and the clock the merge
|
||||
/// compared can never drift apart.
|
||||
List<BudgetEntry> logToHistory(Log log) {
|
||||
final record = log[budgetRecordId];
|
||||
if (record == null) return const [];
|
||||
final entries = <BudgetEntry>[];
|
||||
for (final field in record.fields.entries) {
|
||||
if (!field.key.startsWith(budgetHistoryFieldPrefix)) continue;
|
||||
final kcal = field.value.$1;
|
||||
if (kcal is! int) continue;
|
||||
entries.add(
|
||||
BudgetEntry(
|
||||
effectiveFrom: field.key.substring(budgetHistoryFieldPrefix.length),
|
||||
kcal: kcal,
|
||||
editedAt: DateTime.fromMillisecondsSinceEpoch(
|
||||
field.value.$2.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String(),
|
||||
),
|
||||
);
|
||||
}
|
||||
entries.sort((a, b) => a.effectiveFrom.compareTo(b.effectiveFrom));
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// Converts a merged budget [Log] back into a raw budget record.
|
||||
///
|
||||
/// Returns null when the log has no budget record at all (neither device
|
||||
/// has ever set one yet) -- callers treat that as "nothing to apply
|
||||
/// locally", not an error.
|
||||
Map<String, dynamic>? logToBudget(Log log) {
|
||||
final record = log[budgetRecordId];
|
||||
if (record == null) return null;
|
||||
final field = record.fields['value'];
|
||||
final value = field?.$1;
|
||||
final result = value is Map
|
||||
? Map<String, dynamic>.from(value.cast<String, dynamic>())
|
||||
: <String, dynamic>{};
|
||||
final hlc = field?.$2;
|
||||
if (hlc != null) {
|
||||
result['t'] = DateTime.fromMillisecondsSinceEpoch(
|
||||
hlc.wallTimeMs,
|
||||
isUtc: true,
|
||||
).toLocal().toIso8601String();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Parses one device's pushed `budget.json` text into a crdt_sync [Log].
|
||||
///
|
||||
/// Throwing [FormatException] or [TypeError] is treated as unparsable by
|
||||
/// the caller (`syncLog`'s `decode` callback), matching [parseRemoteLog]'s
|
||||
/// tolerance for a corrupt/truncated push. There is no legacy plain-format
|
||||
/// fallback here -- `budget.json` is a brand-new sync payload.
|
||||
Log parseRemoteBudget(String text) {
|
||||
final raw = jsonDecode(text);
|
||||
if (raw is! Map) {
|
||||
throw const FormatException(
|
||||
'top-level budget payload is not a JSON object',
|
||||
);
|
||||
}
|
||||
final rawMap = raw.cast<String, dynamic>();
|
||||
return rawMap.map(
|
||||
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serializes a merged budget [Log] for push.
|
||||
String encodeBudgetForPush(Log log) {
|
||||
final encoded = <String, dynamic>{
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
};
|
||||
return jsonEncode(encoded);
|
||||
}
|
||||
180
app/lib/widgets/filters/filter_fields.dart
Normal file
180
app/lib/widgets/filters/filter_fields.dart
Normal file
@ -0,0 +1,180 @@
|
||||
/// Filter-sheet input widgets shared by the history and food-bank screens.
|
||||
///
|
||||
/// Both screens grew the same name-search field, the same slider captions and
|
||||
/// four copies each of the same min/max macro range block. They live here, in a
|
||||
/// neutral `widgets/filters/` rather than under either screen, so neither
|
||||
/// screen owns the other's controls.
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The free-text "search by name" field in the filter sheet.
|
||||
///
|
||||
/// Stateful only to own its [TextEditingController]; the query itself lives in
|
||||
/// the screen's [HistoryFilter].
|
||||
class NameSearchField extends StatefulWidget {
|
||||
/// Creates a [NameSearchField] seeded with [initialQuery].
|
||||
const NameSearchField({
|
||||
required this.initialQuery,
|
||||
required this.onChanged,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Query text to seed the field with on first build only.
|
||||
final String initialQuery;
|
||||
|
||||
/// Called on each edit with the new query.
|
||||
final ValueChanged<String> onChanged;
|
||||
|
||||
@override
|
||||
State<NameSearchField> createState() => NameSearchFieldState();
|
||||
}
|
||||
|
||||
/// State for [NameSearchField], holding its text controller.
|
||||
class NameSearchFieldState extends State<NameSearchField> {
|
||||
late final TextEditingController _controller = TextEditingController(
|
||||
text: widget.initialQuery,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TextField(
|
||||
controller: _controller,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Search by name',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: widget.onChanged,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The min/max captions printed under a range slider's two ends.
|
||||
class SliderEndpointLabels extends StatelessWidget {
|
||||
/// Creates endpoint labels reading [lo] on the left and [hi] on the right.
|
||||
const SliderEndpointLabels({required this.lo, required this.hi, super.key});
|
||||
|
||||
/// Caption for the slider's lower bound.
|
||||
final String lo;
|
||||
|
||||
/// Caption for the slider's upper bound.
|
||||
final String hi;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final style = Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
);
|
||||
return Row(
|
||||
children: [
|
||||
Text(lo, style: style),
|
||||
const Spacer(),
|
||||
Text(hi, style: style),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Centred text showing the currently-selected range value (always visible).
|
||||
class SliderSelectedLabel extends StatelessWidget {
|
||||
/// Creates a centred [label] for the current slider selection.
|
||||
const SliderSelectedLabel(this.label, {super.key});
|
||||
|
||||
/// The formatted selection text, e.g. `120 – 640 kcal`.
|
||||
final String label;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One labelled min/max [RangeSlider] row in the filter sheet.
|
||||
///
|
||||
/// The four macro ranges (kcal, protein, carbs, fat) were four near-identical
|
||||
/// 30-line blocks differing only in label, key, unit suffix and which pair of
|
||||
/// [HistoryFilter] fields they read and write. Reading and writing go through
|
||||
/// [min]/[max] and [onChanged] so this widget never needs to know which pair.
|
||||
class FilterRangeRow extends StatelessWidget {
|
||||
/// Creates a range row bounded by [maxValue].
|
||||
const FilterRangeRow({
|
||||
required this.label,
|
||||
required this.sliderKey,
|
||||
required this.maxValue,
|
||||
required this.min,
|
||||
required this.max,
|
||||
required this.onChanged,
|
||||
this.unit = '',
|
||||
this.showEndpointLabels = true,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Section heading, e.g. `Protein range (g)`.
|
||||
final String label;
|
||||
|
||||
/// Widget key on the slider itself, so tests can drive one row.
|
||||
final Key sliderKey;
|
||||
|
||||
/// Upper bound, derived from the logged data. A value of 0 hides the row.
|
||||
final double maxValue;
|
||||
|
||||
/// Current lower bound, or null when unset (meaning 0).
|
||||
final double? min;
|
||||
|
||||
/// Current upper bound, or null when unset (meaning [maxValue]).
|
||||
final double? max;
|
||||
|
||||
/// Called with the new bounds; null means "no bound", not zero.
|
||||
final void Function(double? min, double? max) onChanged;
|
||||
|
||||
/// Suffix appended to the endpoint and selection labels, e.g. `g`.
|
||||
final String unit;
|
||||
|
||||
/// Whether to print the endpoint captions and the selected-range readout.
|
||||
///
|
||||
/// The history sheet shows both; the food-bank sheet never did, and turning
|
||||
/// them on there would be a UI change smuggled in under a refactor.
|
||||
final bool showEndpointLabels;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (maxValue <= 0) return const SizedBox.shrink();
|
||||
final lo = min ?? 0;
|
||||
final hi = max ?? maxValue;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(label, style: Theme.of(context).textTheme.labelLarge),
|
||||
if (showEndpointLabels)
|
||||
SliderEndpointLabels(lo: '0', hi: '${maxValue.round()}$unit'),
|
||||
RangeSlider(
|
||||
key: sliderKey,
|
||||
max: maxValue,
|
||||
values: RangeValues(lo, hi),
|
||||
labels: RangeLabels(lo.toStringAsFixed(0), hi.toStringAsFixed(0)),
|
||||
onChanged: (v) => onChanged(
|
||||
v.start > 0 ? v.start : null,
|
||||
v.end < maxValue ? v.end : null,
|
||||
),
|
||||
),
|
||||
if (showEndpointLabels)
|
||||
SliderSelectedLabel('${lo.round()} – ${hi.round()}$unit'),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
103
app/lib/widgets/food_bank/fb_add_entry_dialog.dart
Normal file
103
app/lib/widgets/food_bank/fb_add_entry_dialog.dart
Normal file
@ -0,0 +1,103 @@
|
||||
/// The "add a manual food bank entry" dialog.
|
||||
///
|
||||
/// Split out of `food_bank_screen.dart` for the repo's 250-line cap.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Prompts for a new manually-curated food bank entry.
|
||||
///
|
||||
/// Pops with the new [FoodBankRecord], or null when cancelled.
|
||||
class AddEntryDialog extends StatefulWidget {
|
||||
/// Creates an [AddEntryDialog] with empty fields.
|
||||
const AddEntryDialog({super.key});
|
||||
|
||||
@override
|
||||
State<AddEntryDialog> createState() => AddEntryDialogState();
|
||||
}
|
||||
|
||||
/// State for [AddEntryDialog], owning its text controllers.
|
||||
class AddEntryDialogState extends State<AddEntryDialog> {
|
||||
final _name = TextEditingController();
|
||||
final _grams = TextEditingController(text: '100');
|
||||
final _kcal = TextEditingController();
|
||||
final _protein = TextEditingController();
|
||||
final _carbs = TextEditingController();
|
||||
final _fat = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_name.dispose();
|
||||
_grams.dispose();
|
||||
_kcal.dispose();
|
||||
_protein.dispose();
|
||||
_carbs.dispose();
|
||||
_fat.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _save() {
|
||||
final name = _name.text.trim();
|
||||
if (name.isEmpty) return;
|
||||
Navigator.of(context).pop(
|
||||
FoodBankRecord(
|
||||
desc: name,
|
||||
kcal: double.tryParse(_kcal.text) ?? 0,
|
||||
proteinG: double.tryParse(_protein.text) ?? 0,
|
||||
carbsG: double.tryParse(_carbs.text) ?? 0,
|
||||
fatG: double.tryParse(_fat.text) ?? 0,
|
||||
grams: double.tryParse(_grams.text) ?? 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _field(String label, TextEditingController ctrl) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: TextField(
|
||||
controller: ctrl,
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
decoration: InputDecoration(labelText: label, isDense: true),
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Add to food bank'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: TextField(
|
||||
controller: _name,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Name',
|
||||
isDense: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
_field('Reference grams', _grams),
|
||||
_field('Kcal', _kcal),
|
||||
_field('Protein (g)', _protein),
|
||||
_field('Carbs (g)', _carbs),
|
||||
_field('Fat (g)', _fat),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: _save,
|
||||
child: const Text('Save to bank'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
156
app/lib/widgets/food_bank/fb_filter.dart
Normal file
156
app/lib/widgets/food_bank/fb_filter.dart
Normal file
@ -0,0 +1,156 @@
|
||||
/// Filter and sort model for the food bank browser.
|
||||
///
|
||||
/// Split out of `food_bank_screen.dart` for the repo's 250-line cap. Pure data
|
||||
/// -- no widgets -- so the sheet, the list and the screen can each depend on it
|
||||
/// without depending on one another.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
|
||||
/// Sort field for the food bank list.
|
||||
enum FbSortField {
|
||||
/// Sort alphabetically by name.
|
||||
name,
|
||||
|
||||
/// Sort by calories.
|
||||
kcal,
|
||||
|
||||
/// Sort by protein (g).
|
||||
protein,
|
||||
|
||||
/// Sort by carbohydrates (g).
|
||||
carbs,
|
||||
|
||||
/// Sort by fat (g).
|
||||
fat,
|
||||
|
||||
/// Sort by usage count (most-used first by default).
|
||||
count,
|
||||
}
|
||||
|
||||
/// Active filter criteria for the food bank list.
|
||||
class FbFilter {
|
||||
/// Creates a [FbFilter] with the given criteria.
|
||||
FbFilter({
|
||||
this.nameQuery = '',
|
||||
this.minKcal,
|
||||
this.maxKcal,
|
||||
this.minProtein,
|
||||
this.maxProtein,
|
||||
this.minCarbs,
|
||||
this.maxCarbs,
|
||||
this.minFat,
|
||||
this.maxFat,
|
||||
});
|
||||
|
||||
/// Substring match on the food name.
|
||||
String nameQuery;
|
||||
|
||||
/// Minimum kcal.
|
||||
double? minKcal;
|
||||
|
||||
/// Maximum kcal.
|
||||
double? maxKcal;
|
||||
|
||||
/// Minimum protein (g).
|
||||
double? minProtein;
|
||||
|
||||
/// Maximum protein (g).
|
||||
double? maxProtein;
|
||||
|
||||
/// Minimum carbs (g).
|
||||
double? minCarbs;
|
||||
|
||||
/// Maximum carbs (g).
|
||||
double? maxCarbs;
|
||||
|
||||
/// Minimum fat (g).
|
||||
double? minFat;
|
||||
|
||||
/// Maximum fat (g).
|
||||
double? maxFat;
|
||||
|
||||
/// True when any criterion is set.
|
||||
bool get isActive =>
|
||||
nameQuery.isNotEmpty ||
|
||||
minKcal != null ||
|
||||
maxKcal != null ||
|
||||
minProtein != null ||
|
||||
maxProtein != null ||
|
||||
minCarbs != null ||
|
||||
maxCarbs != null ||
|
||||
minFat != null ||
|
||||
maxFat != null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pure filter / sort helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Filters and sorts [entries] by [filter] and [sortField]/[ascending].
|
||||
///
|
||||
/// Exposed as a top-level function for unit tests.
|
||||
List<FoodBankRecord> applyFbFilter(
|
||||
List<FoodBankRecord> entries,
|
||||
FbFilter filter,
|
||||
FbSortField sortField, {
|
||||
required bool ascending,
|
||||
}) {
|
||||
var result = [...entries];
|
||||
if (filter.nameQuery.isNotEmpty) {
|
||||
final q = filter.nameQuery.toLowerCase();
|
||||
result = result.where((e) => e.desc.toLowerCase().contains(q)).toList();
|
||||
}
|
||||
if (filter.minKcal != null) {
|
||||
result = result.where((e) => e.kcal >= filter.minKcal!).toList();
|
||||
}
|
||||
if (filter.maxKcal != null) {
|
||||
result = result.where((e) => e.kcal <= filter.maxKcal!).toList();
|
||||
}
|
||||
if (filter.minProtein != null) {
|
||||
result = result.where((e) => e.proteinG >= filter.minProtein!).toList();
|
||||
}
|
||||
if (filter.maxProtein != null) {
|
||||
result = result.where((e) => e.proteinG <= filter.maxProtein!).toList();
|
||||
}
|
||||
if (filter.minCarbs != null) {
|
||||
result = result.where((e) => e.carbsG >= filter.minCarbs!).toList();
|
||||
}
|
||||
if (filter.maxCarbs != null) {
|
||||
result = result.where((e) => e.carbsG <= filter.maxCarbs!).toList();
|
||||
}
|
||||
if (filter.minFat != null) {
|
||||
result = result.where((e) => e.fatG >= filter.minFat!).toList();
|
||||
}
|
||||
if (filter.maxFat != null) {
|
||||
result = result.where((e) => e.fatG <= filter.maxFat!).toList();
|
||||
}
|
||||
|
||||
result.sort((a, b) {
|
||||
int cmp;
|
||||
switch (sortField) {
|
||||
case FbSortField.name:
|
||||
cmp = a.desc.compareTo(b.desc);
|
||||
case FbSortField.kcal:
|
||||
cmp = a.kcal.compareTo(b.kcal);
|
||||
case FbSortField.protein:
|
||||
cmp = a.proteinG.compareTo(b.proteinG);
|
||||
case FbSortField.carbs:
|
||||
cmp = a.carbsG.compareTo(b.carbsG);
|
||||
case FbSortField.fat:
|
||||
cmp = a.fatG.compareTo(b.fatG);
|
||||
case FbSortField.count:
|
||||
cmp = a.count.compareTo(b.count);
|
||||
}
|
||||
return ascending ? cmp : -cmp;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Screen
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Lists all food bank entries (log-derived + manual) with filtering/sorting
|
||||
/// and a FAB for adding new manual entries.
|
||||
244
app/lib/widgets/food_bank/fb_filter_sheet.dart
Normal file
244
app/lib/widgets/food_bank/fb_filter_sheet.dart
Normal file
@ -0,0 +1,244 @@
|
||||
/// The bottom sheet that edits an [FbFilter].
|
||||
///
|
||||
/// Split out of `food_bank_screen.dart` for the repo's 250-line cap. The macro
|
||||
/// range rows come from `widgets/filters/`, shared with the history sheet.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/widgets/filters/filter_fields.dart';
|
||||
import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The draggable bottom sheet that edits the food bank's filter and sort order.
|
||||
///
|
||||
/// Stateless on purpose: the live [FbFilter] belongs to the screen, and every
|
||||
/// edit goes back out through [onFilterChanged] rather than being held here.
|
||||
class FbFilterSheet extends StatelessWidget {
|
||||
/// Creates an [FbFilterSheet] over the screen's current filter/sort state.
|
||||
const FbFilterSheet({
|
||||
required this.filter,
|
||||
required this.sortField,
|
||||
required this.ascending,
|
||||
required this.maxKcal,
|
||||
required this.maxProtein,
|
||||
required this.maxCarbs,
|
||||
required this.maxFat,
|
||||
required this.onFilterChanged,
|
||||
required this.onSortChanged,
|
||||
required this.onApply,
|
||||
required this.onClear,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The filter criteria currently being edited.
|
||||
final FbFilter filter;
|
||||
|
||||
/// The field the list is sorted by.
|
||||
final FbSortField sortField;
|
||||
|
||||
/// Whether the sort runs ascending.
|
||||
final bool ascending;
|
||||
|
||||
/// Upper bound of the calories slider, from the banked records.
|
||||
final double maxKcal;
|
||||
|
||||
/// Upper bound of the protein slider, from the banked records.
|
||||
final double maxProtein;
|
||||
|
||||
/// Upper bound of the carbohydrate slider, from the banked records.
|
||||
final double maxCarbs;
|
||||
|
||||
/// Upper bound of the fat slider, from the banked records.
|
||||
final double maxFat;
|
||||
|
||||
/// Called with a new filter on every edit.
|
||||
final void Function(FbFilter) onFilterChanged;
|
||||
|
||||
/// Called when the sort field or direction changes.
|
||||
final void Function({required FbSortField field, required bool asc})
|
||||
onSortChanged;
|
||||
|
||||
/// Called when the user applies the filter and dismisses the sheet.
|
||||
final VoidCallback onApply;
|
||||
|
||||
/// Called when the user clears every criterion.
|
||||
final VoidCallback onClear;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DraggableScrollableSheet(
|
||||
initialChildSize: 0.85,
|
||||
minChildSize: 0.5,
|
||||
maxChildSize: 0.95,
|
||||
builder: (context, scroll) => Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Filter & Sort',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: onClear,
|
||||
child: const Text('Clear all'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
controller: scroll,
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
TextField(
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Search by name',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
isDense: true,
|
||||
),
|
||||
controller: TextEditingController(text: filter.nameQuery)
|
||||
..selection = TextSelection.collapsed(
|
||||
offset: filter.nameQuery.length,
|
||||
),
|
||||
onChanged: (v) {
|
||||
filter.nameQuery = v;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilterRangeRow(
|
||||
label: 'Kcal range',
|
||||
sliderKey: const Key('fb-kcal-range-slider'),
|
||||
maxValue: maxKcal,
|
||||
min: filter.minKcal,
|
||||
max: filter.maxKcal,
|
||||
showEndpointLabels: false,
|
||||
onChanged: (lo, hi) {
|
||||
filter.minKcal = lo;
|
||||
filter.maxKcal = hi;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
label: 'Protein range (g)',
|
||||
sliderKey: const Key('fb-protein-range-slider'),
|
||||
maxValue: maxProtein,
|
||||
min: filter.minProtein,
|
||||
max: filter.maxProtein,
|
||||
unit: 'g',
|
||||
showEndpointLabels: false,
|
||||
onChanged: (lo, hi) {
|
||||
filter.minProtein = lo;
|
||||
filter.maxProtein = hi;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
label: 'Carbs range (g)',
|
||||
sliderKey: const Key('fb-carbs-range-slider'),
|
||||
maxValue: maxCarbs,
|
||||
min: filter.minCarbs,
|
||||
max: filter.maxCarbs,
|
||||
unit: 'g',
|
||||
showEndpointLabels: false,
|
||||
onChanged: (lo, hi) {
|
||||
filter.minCarbs = lo;
|
||||
filter.maxCarbs = hi;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
label: 'Fat range (g)',
|
||||
sliderKey: const Key('fb-fat-range-slider'),
|
||||
maxValue: maxFat,
|
||||
min: filter.minFat,
|
||||
max: filter.maxFat,
|
||||
unit: 'g',
|
||||
showEndpointLabels: false,
|
||||
onChanged: (lo, hi) {
|
||||
filter.minFat = lo;
|
||||
filter.maxFat = hi;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
Text(
|
||||
'Sort by',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: DropdownButton<FbSortField>(
|
||||
isExpanded: true,
|
||||
value: sortField,
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.count,
|
||||
child: Text('Usage count'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.name,
|
||||
child: Text('Name'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.kcal,
|
||||
child: Text('Kcal'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.protein,
|
||||
child: Text('Protein'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.carbs,
|
||||
child: Text('Carbs'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.fat,
|
||||
child: Text('Fat'),
|
||||
),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v != null) {
|
||||
onSortChanged(field: v, asc: ascending);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
ascending ? Icons.arrow_upward : Icons.arrow_downward,
|
||||
),
|
||||
tooltip: ascending ? 'Ascending' : 'Descending',
|
||||
onPressed: () =>
|
||||
onSortChanged(field: sortField, asc: !ascending),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: onApply,
|
||||
child: const Text('Apply'),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Add entry dialog
|
||||
// ---------------------------------------------------------------------------
|
||||
102
app/lib/widgets/history/history_filter.dart
Normal file
102
app/lib/widgets/history/history_filter.dart
Normal file
@ -0,0 +1,102 @@
|
||||
/// Filter, sort and grouping model for the history screen.
|
||||
///
|
||||
/// Split out of `history_screen.dart` to hold the repo's 250-line cap. This is
|
||||
/// the pure-data half -- no widgets -- so the sheet, the list and the screen
|
||||
/// can each depend on it without depending on one another.
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filter & sort state
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Sort field for the history list.
|
||||
enum HistorySortField {
|
||||
/// Sort by entry date/time.
|
||||
date,
|
||||
|
||||
/// Sort by calories.
|
||||
kcal,
|
||||
|
||||
/// Sort by protein (g).
|
||||
protein,
|
||||
|
||||
/// Sort by carbohydrates (g).
|
||||
carbs,
|
||||
|
||||
/// Sort by fat (g).
|
||||
fat,
|
||||
|
||||
/// Sort by description text.
|
||||
description,
|
||||
}
|
||||
|
||||
/// All active filter criteria; [isActive] is true when any criterion is set.
|
||||
class HistoryFilter {
|
||||
/// Creates a [HistoryFilter] with the given criteria.
|
||||
HistoryFilter({
|
||||
this.nameQuery = '',
|
||||
this.dateRange,
|
||||
this.minKcal,
|
||||
this.maxKcal,
|
||||
this.minProtein,
|
||||
this.maxProtein,
|
||||
this.minCarbs,
|
||||
this.maxCarbs,
|
||||
this.minFat,
|
||||
this.maxFat,
|
||||
this.source,
|
||||
});
|
||||
|
||||
/// Substring match on the food description.
|
||||
String nameQuery;
|
||||
|
||||
/// Optional date range filter.
|
||||
DateTimeRange? dateRange;
|
||||
|
||||
/// Minimum kcal.
|
||||
double? minKcal;
|
||||
|
||||
/// Maximum kcal.
|
||||
double? maxKcal;
|
||||
|
||||
/// Minimum protein (g).
|
||||
double? minProtein;
|
||||
|
||||
/// Maximum protein (g).
|
||||
double? maxProtein;
|
||||
|
||||
/// Minimum carbs (g).
|
||||
double? minCarbs;
|
||||
|
||||
/// Maximum carbs (g).
|
||||
double? maxCarbs;
|
||||
|
||||
/// Minimum fat (g).
|
||||
double? minFat;
|
||||
|
||||
/// Maximum fat (g).
|
||||
double? maxFat;
|
||||
|
||||
/// null = all, or a source string from the log.
|
||||
String? source;
|
||||
|
||||
/// True when any filter criterion is active.
|
||||
bool get isActive =>
|
||||
nameQuery.isNotEmpty ||
|
||||
dateRange != null ||
|
||||
minKcal != null ||
|
||||
maxKcal != null ||
|
||||
minProtein != null ||
|
||||
maxProtein != null ||
|
||||
minCarbs != null ||
|
||||
maxCarbs != null ||
|
||||
minFat != null ||
|
||||
maxFat != null ||
|
||||
source != null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// List item sealed hierarchy for day-grouped rendering
|
||||
// ---------------------------------------------------------------------------
|
||||
242
app/lib/widgets/history/history_filter_sheet.dart
Normal file
242
app/lib/widgets/history/history_filter_sheet.dart
Normal file
@ -0,0 +1,242 @@
|
||||
/// The bottom sheet that edits a [HistoryFilter].
|
||||
///
|
||||
/// Split out of `history_screen.dart` to hold the repo's 250-line cap.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/widgets/filters/filter_fields.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_filter.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_filter_sort.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The draggable bottom sheet that edits the history filter and sort order.
|
||||
///
|
||||
/// Stateless on purpose: the live [HistoryFilter] belongs to the screen, and
|
||||
/// every edit goes back out through [onFilterChanged] rather than being held
|
||||
/// here, so "apply" and "clear" cannot disagree with what is displayed.
|
||||
class FilterSheet extends StatelessWidget {
|
||||
/// Creates a [FilterSheet] over the screen's current filter and sort state.
|
||||
const FilterSheet({
|
||||
required this.filter,
|
||||
required this.sortField,
|
||||
required this.ascending,
|
||||
required this.maxKcal,
|
||||
required this.maxProtein,
|
||||
required this.maxCarbs,
|
||||
required this.maxFat,
|
||||
required this.onFilterChanged,
|
||||
required this.onSortChanged,
|
||||
required this.onApply,
|
||||
required this.onClear,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The filter criteria currently being edited.
|
||||
final HistoryFilter filter;
|
||||
|
||||
/// The field the list is sorted by.
|
||||
final HistorySortField sortField;
|
||||
|
||||
/// Whether the sort runs ascending.
|
||||
final bool ascending;
|
||||
|
||||
/// Upper bound of the calories slider, from the logged data.
|
||||
final double maxKcal;
|
||||
|
||||
/// Upper bound of the protein slider, from the logged data.
|
||||
final double maxProtein;
|
||||
|
||||
/// Upper bound of the carbohydrate slider, from the logged data.
|
||||
final double maxCarbs;
|
||||
|
||||
/// Upper bound of the fat slider, from the logged data.
|
||||
final double maxFat;
|
||||
|
||||
/// Called with a new filter on every edit.
|
||||
final void Function(HistoryFilter) onFilterChanged;
|
||||
|
||||
/// Called when the sort field or direction changes.
|
||||
final void Function({required HistorySortField field, required bool asc})
|
||||
onSortChanged;
|
||||
|
||||
/// Called when the user applies the filter and dismisses the sheet.
|
||||
final VoidCallback onApply;
|
||||
|
||||
/// Called when the user clears every criterion.
|
||||
final VoidCallback onClear;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DraggableScrollableSheet(
|
||||
initialChildSize: 0.9,
|
||||
minChildSize: 0.5,
|
||||
maxChildSize: 0.95,
|
||||
builder: (context, scroll) => Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Filter & Sort',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
TextButton(onPressed: onClear, child: const Text('Clear all')),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
controller: scroll,
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Name search
|
||||
NameSearchField(
|
||||
initialQuery: filter.nameQuery,
|
||||
onChanged: (v) {
|
||||
filter.nameQuery = v;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Date range
|
||||
Text(
|
||||
'Date range',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
OutlinedButton.icon(
|
||||
icon: const Icon(Icons.date_range),
|
||||
label: Text(
|
||||
filter.dateRange == null
|
||||
? 'Any date'
|
||||
: dateRangeLabel(filter.dateRange!),
|
||||
),
|
||||
onPressed: () async {
|
||||
final picked = await showDateRangePicker(
|
||||
context: context,
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime.now().add(const Duration(days: 1)),
|
||||
initialDateRange: filter.dateRange,
|
||||
);
|
||||
if (picked != null) {
|
||||
filter.dateRange = picked;
|
||||
onFilterChanged(filter);
|
||||
}
|
||||
},
|
||||
),
|
||||
if (filter.dateRange != null)
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
filter.dateRange = null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
child: const Text('Clear date range'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
FilterRangeRow(
|
||||
label: 'Kcal range',
|
||||
sliderKey: const Key('kcal-range-slider'),
|
||||
maxValue: maxKcal,
|
||||
min: filter.minKcal,
|
||||
max: filter.maxKcal,
|
||||
onChanged: (lo, hi) {
|
||||
filter.minKcal = lo;
|
||||
filter.maxKcal = hi;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
label: 'Protein range (g)',
|
||||
sliderKey: const Key('protein-range-slider'),
|
||||
maxValue: maxProtein,
|
||||
min: filter.minProtein,
|
||||
max: filter.maxProtein,
|
||||
unit: 'g',
|
||||
onChanged: (lo, hi) {
|
||||
filter.minProtein = lo;
|
||||
filter.maxProtein = hi;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
label: 'Carbs range (g)',
|
||||
sliderKey: const Key('carbs-range-slider'),
|
||||
maxValue: maxCarbs,
|
||||
min: filter.minCarbs,
|
||||
max: filter.maxCarbs,
|
||||
unit: 'g',
|
||||
onChanged: (lo, hi) {
|
||||
filter.minCarbs = lo;
|
||||
filter.maxCarbs = hi;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
label: 'Fat range (g)',
|
||||
sliderKey: const Key('fat-range-slider'),
|
||||
maxValue: maxFat,
|
||||
min: filter.minFat,
|
||||
max: filter.maxFat,
|
||||
unit: 'g',
|
||||
onChanged: (lo, hi) {
|
||||
filter.minFat = lo;
|
||||
filter.maxFat = hi;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
|
||||
FilterSourceChips(
|
||||
selected: filter.source,
|
||||
onSelected: (src) {
|
||||
filter.source = src;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilterSortControls(
|
||||
sortField: sortField,
|
||||
ascending: ascending,
|
||||
onSortChanged: onSortChanged,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: onApply,
|
||||
child: const Text('Apply'),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Slider label helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Thin row showing the min (0) and max endpoint values for a range slider.
|
||||
/// The filter sheet's name-search field, owning a persistent controller.
|
||||
///
|
||||
/// Stateful on purpose. The controller used to be built inside
|
||||
/// `FilterSheet.build` with the caret forced to the end of the text, and
|
||||
/// `onChanged` rebuilds the sheet — so every keystroke discarded the controller
|
||||
/// and re-slammed the caret to end-of-text. Appending worked, but Home/End and
|
||||
/// arrow-key editing in the middle of the query were silently undone on each
|
||||
/// character. Keeping the controller in State fixes that without changing how
|
||||
/// the filter is plumbed.
|
||||
140
app/lib/widgets/history/history_filter_sort.dart
Normal file
140
app/lib/widgets/history/history_filter_sort.dart
Normal file
@ -0,0 +1,140 @@
|
||||
/// The source-chip and sort controls at the foot of the history filter sheet.
|
||||
///
|
||||
/// Split from `history_filter_sheet.dart` for the repo's 250-line cap. Both are
|
||||
/// stateless and report upward: the live filter and sort order belong to the
|
||||
/// screen, so nothing here holds state that could disagree with what is shown.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/widgets/history/history_filter.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The known `source` values an entry can carry, in display order.
|
||||
///
|
||||
/// Kept next to the chips that render them rather than in the filter model:
|
||||
/// this is a UI affordance (which sources are worth offering as one tap), not
|
||||
/// a constraint on what `source` may contain.
|
||||
const _sources = ['manual', 'food bank'];
|
||||
|
||||
/// Single-select chips filtering by entry source, with an "All" reset.
|
||||
class FilterSourceChips extends StatelessWidget {
|
||||
/// Creates source chips with [selected] currently active.
|
||||
const FilterSourceChips({
|
||||
required this.selected,
|
||||
required this.onSelected,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The active source, or null for "All".
|
||||
final String? selected;
|
||||
|
||||
/// Called with the chosen source, or null when "All" is tapped.
|
||||
final ValueChanged<String?> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text('Source', style: Theme.of(context).textTheme.labelLarge),
|
||||
const SizedBox(height: 4),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
FilterChip(
|
||||
label: const Text('All'),
|
||||
selected: selected == null,
|
||||
onSelected: (_) => onSelected(null),
|
||||
),
|
||||
for (final src in _sources)
|
||||
FilterChip(
|
||||
label: Text(src),
|
||||
selected: selected == src,
|
||||
onSelected: (_) => onSelected(src),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sort-field dropdown plus its ascending/descending toggle.
|
||||
class FilterSortControls extends StatelessWidget {
|
||||
/// Creates sort controls reflecting [sortField] and [ascending].
|
||||
const FilterSortControls({
|
||||
required this.sortField,
|
||||
required this.ascending,
|
||||
required this.onSortChanged,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The field the list is currently sorted by.
|
||||
final HistorySortField sortField;
|
||||
|
||||
/// Whether the sort currently runs ascending.
|
||||
final bool ascending;
|
||||
|
||||
/// Called when either the field or the direction changes.
|
||||
final void Function({required HistorySortField field, required bool asc})
|
||||
onSortChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text('Sort by', style: Theme.of(context).textTheme.labelLarge),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: DropdownButton<HistorySortField>(
|
||||
isExpanded: true,
|
||||
value: sortField,
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.date,
|
||||
child: Text('Date'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.kcal,
|
||||
child: Text('Kcal'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.protein,
|
||||
child: Text('Protein'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.carbs,
|
||||
child: Text('Carbs'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.fat,
|
||||
child: Text('Fat'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.description,
|
||||
child: Text('Description'),
|
||||
),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v != null) {
|
||||
onSortChanged(field: v, asc: ascending);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
ascending ? Icons.arrow_upward : Icons.arrow_downward,
|
||||
),
|
||||
tooltip: ascending ? 'Ascending' : 'Descending',
|
||||
onPressed: () => onSortChanged(field: sortField, asc: !ascending),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
206
app/lib/widgets/history/history_grouping.dart
Normal file
206
app/lib/widgets/history/history_grouping.dart
Normal file
@ -0,0 +1,206 @@
|
||||
/// Grouping, filtering and day-label helpers for the history list.
|
||||
///
|
||||
/// Split from `history_filter.dart` for the repo's 250-line cap: that file is
|
||||
/// the filter *criteria*, this one is what those criteria do to a list.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/services/day_status_service.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_filter.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// One row in the flattened history list: either a [DayHeader] or an
|
||||
/// [EntryRow]. Sealed so the list's `switch` stays exhaustive.
|
||||
sealed class HistoryItem {}
|
||||
|
||||
/// A day's summary row, shown above that day's entries.
|
||||
final class DayHeader extends HistoryItem {
|
||||
/// Creates a [DayHeader] with a day's pre-computed totals.
|
||||
DayHeader(
|
||||
this.dateKey,
|
||||
this.totalKcal,
|
||||
this.entryCount,
|
||||
this.totalProtein,
|
||||
this.totalCarbs,
|
||||
this.totalFat,
|
||||
);
|
||||
|
||||
/// The `YYYY-MM-DD` key this header groups.
|
||||
final String dateKey;
|
||||
|
||||
/// Calories logged across the whole day.
|
||||
final double totalKcal;
|
||||
|
||||
/// How many entries the day holds.
|
||||
final int entryCount;
|
||||
|
||||
/// Protein grams logged across the whole day.
|
||||
final double totalProtein;
|
||||
|
||||
/// Carbohydrate grams logged across the whole day.
|
||||
final double totalCarbs;
|
||||
|
||||
/// Fat grams logged across the whole day.
|
||||
final double totalFat;
|
||||
}
|
||||
|
||||
/// A single logged meal within a day's group.
|
||||
final class EntryRow extends HistoryItem {
|
||||
/// Creates an [EntryRow] wrapping [entry].
|
||||
EntryRow(this.entry);
|
||||
|
||||
/// The entry this row renders.
|
||||
final FoodEntry entry;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pure filter / sort / group helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Applies [filter] and sort criteria to [entries] and returns the result.
|
||||
///
|
||||
/// Exposed as a top-level function for unit tests.
|
||||
List<FoodEntry> applyHistoryFilter(
|
||||
List<FoodEntry> entries,
|
||||
HistoryFilter filter,
|
||||
HistorySortField sortField, {
|
||||
required bool ascending,
|
||||
}) {
|
||||
var result = [...entries];
|
||||
|
||||
if (filter.nameQuery.isNotEmpty) {
|
||||
final q = filter.nameQuery.toLowerCase();
|
||||
result = result.where((e) => e.desc.toLowerCase().contains(q)).toList();
|
||||
}
|
||||
if (filter.dateRange != null) {
|
||||
final start = filter.dateRange!.start;
|
||||
final end = filter.dateRange!.end.add(const Duration(days: 1));
|
||||
result = result.where((e) {
|
||||
final t = DateTime.tryParse(e.time);
|
||||
return t != null && !t.isBefore(start) && t.isBefore(end);
|
||||
}).toList();
|
||||
}
|
||||
if (filter.minKcal != null) {
|
||||
result = result.where((e) => e.kcal >= filter.minKcal!).toList();
|
||||
}
|
||||
if (filter.maxKcal != null) {
|
||||
result = result.where((e) => e.kcal <= filter.maxKcal!).toList();
|
||||
}
|
||||
if (filter.minProtein != null) {
|
||||
result = result.where((e) => e.proteinG >= filter.minProtein!).toList();
|
||||
}
|
||||
if (filter.maxProtein != null) {
|
||||
result = result.where((e) => e.proteinG <= filter.maxProtein!).toList();
|
||||
}
|
||||
if (filter.minCarbs != null) {
|
||||
result = result.where((e) => e.carbsG >= filter.minCarbs!).toList();
|
||||
}
|
||||
if (filter.maxCarbs != null) {
|
||||
result = result.where((e) => e.carbsG <= filter.maxCarbs!).toList();
|
||||
}
|
||||
if (filter.minFat != null) {
|
||||
result = result.where((e) => e.fatG >= filter.minFat!).toList();
|
||||
}
|
||||
if (filter.maxFat != null) {
|
||||
result = result.where((e) => e.fatG <= filter.maxFat!).toList();
|
||||
}
|
||||
if (filter.source != null) {
|
||||
result = result.where((e) => e.source == filter.source).toList();
|
||||
}
|
||||
|
||||
result.sort((a, b) {
|
||||
int cmp;
|
||||
switch (sortField) {
|
||||
case HistorySortField.date:
|
||||
final at = DateTime.tryParse(a.time) ?? DateTime(0);
|
||||
final bt = DateTime.tryParse(b.time) ?? DateTime(0);
|
||||
cmp = at.compareTo(bt);
|
||||
case HistorySortField.kcal:
|
||||
cmp = a.kcal.compareTo(b.kcal);
|
||||
case HistorySortField.protein:
|
||||
cmp = a.proteinG.compareTo(b.proteinG);
|
||||
case HistorySortField.carbs:
|
||||
cmp = a.carbsG.compareTo(b.carbsG);
|
||||
case HistorySortField.fat:
|
||||
cmp = a.fatG.compareTo(b.fatG);
|
||||
case HistorySortField.description:
|
||||
cmp = a.desc.compareTo(b.desc);
|
||||
}
|
||||
return ascending ? cmp : -cmp;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Flatten [entries] into day headers followed by that day's rows.
|
||||
///
|
||||
/// Each day's totals are summed once here rather than per-rebuild in the list.
|
||||
List<HistoryItem> buildGroupedItems(List<FoodEntry> entries) {
|
||||
final byDay = <String, List<FoodEntry>>{};
|
||||
for (final e in entries) {
|
||||
final day = e.time.length >= 10 ? e.time.substring(0, 10) : 'unknown';
|
||||
byDay.putIfAbsent(day, () => []).add(e);
|
||||
}
|
||||
final days = byDay.keys.toList()..sort((a, b) => b.compareTo(a));
|
||||
final items = <HistoryItem>[];
|
||||
for (final day in days) {
|
||||
final dayEntries = byDay[day]!;
|
||||
final totalKcal = sumKcal(dayEntries);
|
||||
final totalProtein = dayEntries.fold<double>(0, (s, e) => s + e.proteinG);
|
||||
final totalCarbs = dayEntries.fold<double>(0, (s, e) => s + e.carbsG);
|
||||
final totalFat = dayEntries.fold<double>(0, (s, e) => s + e.fatG);
|
||||
items
|
||||
..add(
|
||||
DayHeader(
|
||||
day,
|
||||
totalKcal,
|
||||
dayEntries.length,
|
||||
totalProtein,
|
||||
totalCarbs,
|
||||
totalFat,
|
||||
),
|
||||
)
|
||||
..addAll(dayEntries.map(EntryRow.new));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/// Render a picked date range as `YYYY-MM-DD – YYYY-MM-DD` for the filter chip.
|
||||
String dateRangeLabel(DateTimeRange r) =>
|
||||
'${r.start.toString().substring(0, 10)}'
|
||||
' – ${r.end.toString().substring(0, 10)}';
|
||||
|
||||
/// Render a `YYYY-MM-DD` key as a short `Wed 12 Aug`-style label.
|
||||
///
|
||||
/// Falls back to the raw key when it cannot be parsed, so a malformed date
|
||||
/// shows something rather than throwing inside a list build.
|
||||
String formatDay(String dateKey) {
|
||||
try {
|
||||
final d = DateTime.parse(dateKey);
|
||||
const wd = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
||||
const mo = [
|
||||
'Jan',
|
||||
'Feb',
|
||||
'Mar',
|
||||
'Apr',
|
||||
'May',
|
||||
'Jun',
|
||||
'Jul',
|
||||
'Aug',
|
||||
'Sep',
|
||||
'Oct',
|
||||
'Nov',
|
||||
'Dec',
|
||||
];
|
||||
return '${wd[d.weekday - 1]} ${d.day} ${mo[d.month - 1]} ${d.year}';
|
||||
} on Exception {
|
||||
return dateKey;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Screen
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Shows every non-deleted logged entry, grouped by day, with optional
|
||||
/// filtering and sorting.
|
||||
194
app/lib/widgets/history/history_list.dart
Normal file
194
app/lib/widgets/history/history_list.dart
Normal file
@ -0,0 +1,194 @@
|
||||
/// The grouped day/entry list rendered by the history screen.
|
||||
///
|
||||
/// Split out of `history_screen.dart` to hold the repo's 250-line cap.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The history list: a flat [ListView] over pre-grouped day headers and rows.
|
||||
///
|
||||
/// Grouping happens in [buildGroupedItems] rather than here, so the list stays
|
||||
/// a dumb renderer of whatever [HistoryItem] sequence it is handed.
|
||||
class GroupedList extends StatelessWidget {
|
||||
/// Creates a [GroupedList] over already-grouped [items].
|
||||
const GroupedList({
|
||||
required this.items,
|
||||
required this.onDeleteEntry,
|
||||
required this.onEditEntry,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Day headers and entry rows, in display order.
|
||||
final List<HistoryItem> items;
|
||||
|
||||
/// Called after a confirmed delete so the parent can reload.
|
||||
final Future<void> Function() onDeleteEntry;
|
||||
|
||||
/// Called with the entry to edit when a row is tapped.
|
||||
final Future<void> Function(FoodEntry) onEditEntry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView.builder(
|
||||
itemCount: items.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
return switch (item) {
|
||||
DayHeader() => DayHeaderTile(item),
|
||||
EntryRow() => EntryTile(
|
||||
item.entry,
|
||||
onDelete: onDeleteEntry,
|
||||
onEdit: () => onEditEntry(item.entry),
|
||||
),
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sticky-looking header that starts each day's group of entries.
|
||||
class DayHeaderTile extends StatelessWidget {
|
||||
/// Creates a [DayHeaderTile] for [header].
|
||||
const DayHeaderTile(this.header, {super.key});
|
||||
|
||||
/// The day this header summarises (date key, totals, budget for that day).
|
||||
final DayHeader header;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
// The budget that applied on *that* day, not today's -- a later budget
|
||||
// change must not repaint months of history red.
|
||||
final goal = BudgetHistoryService.schedule.forDay(header.dateKey);
|
||||
final kcalColor = header.totalKcal > goal
|
||||
? colorScheme.error
|
||||
: colorScheme.primary;
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
formatDay(header.dateKey),
|
||||
style: textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${header.entryCount}'
|
||||
' ${header.entryCount == 1 ? 'entry' : 'entries'}',
|
||||
style: textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
'${header.totalKcal.round()} / $goal kcal',
|
||||
style: textTheme.bodySmall?.copyWith(color: kcalColor),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'P ${header.totalProtein.round()}g · '
|
||||
'C ${header.totalCarbs.round()}g · '
|
||||
'F ${header.totalFat.round()}g',
|
||||
style: textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One logged meal: description, macros, and swipe/tap actions.
|
||||
class EntryTile extends StatelessWidget {
|
||||
/// Creates an [EntryTile] for [entry].
|
||||
const EntryTile(this.entry, {super.key, this.onDelete, this.onEdit});
|
||||
|
||||
/// The entry this tile renders.
|
||||
final FoodEntry entry;
|
||||
|
||||
/// Called after a confirmed delete so the parent can reload.
|
||||
final Future<void> Function()? onDelete;
|
||||
|
||||
/// Called when the tile is tapped to open the edit screen.
|
||||
final Future<void> Function()? onEdit;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final canDelete = entry.id != null;
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.restaurant),
|
||||
title: Text(entry.desc),
|
||||
subtitle: Text('${entry.time} • ${entry.source}'),
|
||||
// Delete needs a focusable control, not just a long-press. Long-press has
|
||||
// no keyboard equivalent at all, so on the desktop build (a Chrome --app
|
||||
// window) deleting an entry was pointer-only: unreachable by keyboard and
|
||||
// invisible to a screen reader. The trailing row keeps the kcal figure
|
||||
// and adds an IconButton, which Tab reaches and Enter/Space activates.
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('${entry.kcal.toStringAsFixed(0)} kcal'),
|
||||
if (canDelete)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
tooltip: 'Delete entry',
|
||||
onPressed: () => _confirmDelete(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
// Any entry can be edited (legacy null-id entries gain a UUID on save).
|
||||
// Delete remains id-only to avoid ambiguous time+desc matches.
|
||||
onTap: () => onEdit?.call(),
|
||||
// Retained as a redundant pointer shortcut, never the only route.
|
||||
onLongPress: canDelete ? () => _confirmDelete(context) : null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _confirmDelete(BuildContext context) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
title: const Text('Delete entry?'),
|
||||
content: Text('Remove "${entry.desc}" from history?'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed == true) {
|
||||
await LogStorageService.instance.deleteEntry(entry.id!);
|
||||
await onDelete?.call();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filter sheet
|
||||
// ---------------------------------------------------------------------------
|
||||
@ -3,6 +3,7 @@
|
||||
/// directly and scaled to the amount actually eaten.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/nutrition.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Text controllers for one macro-entry row, owned by the calling screen so
|
||||
@ -38,6 +39,19 @@ class MacroControllers {
|
||||
/// equals [perGrams].
|
||||
final TextEditingController grams;
|
||||
|
||||
/// Fills every macro field from [nutrition], as a food-bank pick does.
|
||||
///
|
||||
/// Both [perGrams] and [grams] are set to the suggestion's own weight, so
|
||||
/// the row starts out describing exactly the portion that was banked.
|
||||
void fillFrom(Nutrition nutrition) {
|
||||
kcal.text = nutrition.kcal.toStringAsFixed(0);
|
||||
protein.text = nutrition.proteinG.toStringAsFixed(0);
|
||||
carbs.text = nutrition.carbsG.toStringAsFixed(0);
|
||||
fat.text = nutrition.fatG.toStringAsFixed(0);
|
||||
perGrams.text = nutrition.grams.toStringAsFixed(0);
|
||||
grams.text = nutrition.grams.toStringAsFixed(0);
|
||||
}
|
||||
|
||||
/// Clears every field's text.
|
||||
void clear() {
|
||||
kcal.clear();
|
||||
|
||||
@ -571,7 +571,7 @@ packages:
|
||||
source: hosted
|
||||
version: "3.1.6"
|
||||
plugin_platform_interface:
|
||||
dependency: transitive
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: plugin_platform_interface
|
||||
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
|
||||
|
||||
@ -2,7 +2,7 @@ name: diet_guard_app
|
||||
description: "Companion phone app for diet_guard: log meals on the go."
|
||||
publish_to: 'none'
|
||||
|
||||
version: 1.0.11+1
|
||||
version: 1.0.28+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
@ -54,6 +54,7 @@ dev_dependencies:
|
||||
flutter_launcher_icons: ^0.14.4
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
plugin_platform_interface: any
|
||||
url_launcher_platform_interface: ^2.3.2
|
||||
very_good_analysis: ^10.2.0
|
||||
|
||||
|
||||
121
app/test/desktop/wrapper_server_account_test.dart
Normal file
121
app/test/desktop/wrapper_server_account_test.dart
Normal file
@ -0,0 +1,121 @@
|
||||
// The desktop wrapper is the other half of the web-build desktop app: it
|
||||
// serves the assets, owns the on-disk mirror of the app's storage, and fronts
|
||||
// GitHub. These tests drive it over a real loopback socket, since its
|
||||
// contract is HTTP.
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/desktop/github_proxy.dart';
|
||||
import 'package:diet_guard_app/desktop/wrapper_server.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
void main() {
|
||||
|
||||
|
||||
late Directory tempDir;
|
||||
late String webRoot;
|
||||
late String dataDir;
|
||||
late WrapperServer server;
|
||||
late List<http.Request> outbound;
|
||||
late Map<String, http.Response> canned;
|
||||
|
||||
Future<void> startServer({
|
||||
bool serveSyncAccount = false,
|
||||
String? syncConfigDir,
|
||||
}) async {
|
||||
outbound = [];
|
||||
canned = {};
|
||||
final proxy = GitHubProxy(
|
||||
tokenPath: p.join(tempDir.path, 'config', 'sync_token'),
|
||||
fallbackTokenPath: p.join(tempDir.path, 'config', 'fallback_token'),
|
||||
httpClient: MockClient((request) async {
|
||||
outbound.add(request);
|
||||
return canned[request.url.toString()] ??
|
||||
http.Response('{"ok":true}', 200);
|
||||
}),
|
||||
);
|
||||
server = WrapperServer(
|
||||
webRoot: webRoot,
|
||||
dataDir: dataDir,
|
||||
gitHubProxy: proxy,
|
||||
serveSyncAccount: serveSyncAccount,
|
||||
syncConfigDir: syncConfigDir,
|
||||
);
|
||||
await server.start(0);
|
||||
}
|
||||
|
||||
Uri url(String path) => Uri.parse('http://localhost:${server.port}$path');
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_wrapper_');
|
||||
webRoot = p.join(tempDir.path, 'web');
|
||||
dataDir = p.join(tempDir.path, 'data');
|
||||
await Directory(webRoot).create(recursive: true);
|
||||
File(p.join(webRoot, 'index.html')).writeAsStringSync('<html>app</html>');
|
||||
File(p.join(webRoot, 'main.wasm')).writeAsBytesSync([0, 97, 115, 109]);
|
||||
await startServer();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await server.stop();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
group('sync-account provisioning', () {
|
||||
/// Writes [files] into a temp config dir and restarts with the route on.
|
||||
Future<String> enableWith(Map<String, String> files) async {
|
||||
final configDir = Directory(p.join(tempDir.path, 'crdt-sync'))
|
||||
..createSync(recursive: true);
|
||||
files.forEach((name, contents) {
|
||||
File(p.join(configDir.path, name)).writeAsStringSync(contents);
|
||||
});
|
||||
await server.stop();
|
||||
await startServer(serveSyncAccount: true, syncConfigDir: configDir.path);
|
||||
return 'http://localhost:${server.port}';
|
||||
}
|
||||
|
||||
test('is 404 when not enabled', () async {
|
||||
// The default, and the whole security posture: a credential route must
|
||||
// not be reachable just because the wrapper is running.
|
||||
final response = await http.get(url(kSyncAccountPath));
|
||||
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
});
|
||||
|
||||
test('serves the account when enabled', () async {
|
||||
final origin = await enableWith({
|
||||
'firebase.json': '{"email":"a@b.c"}',
|
||||
'password': 'pw\n',
|
||||
});
|
||||
|
||||
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
||||
final account = FirebaseAccount.tryParse(response.body);
|
||||
|
||||
expect(response.statusCode, HttpStatus.ok);
|
||||
expect(account?.email, 'a@b.c');
|
||||
expect(account?.password, 'pw');
|
||||
});
|
||||
|
||||
test('is 404 when the config files are absent', () async {
|
||||
final origin = await enableWith({});
|
||||
|
||||
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
||||
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
});
|
||||
|
||||
test('is 404 when firebase.json has no usable email', () async {
|
||||
final origin = await enableWith({
|
||||
'firebase.json': '{"apiKey":"x"}',
|
||||
'password': 'pw',
|
||||
});
|
||||
|
||||
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
||||
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
});
|
||||
});
|
||||
}
|
||||
214
app/test/desktop/wrapper_server_proxy_test.dart
Normal file
214
app/test/desktop/wrapper_server_proxy_test.dart
Normal file
@ -0,0 +1,214 @@
|
||||
// The desktop wrapper is the other half of the web-build desktop app: it
|
||||
// serves the assets, owns the on-disk mirror of the app's storage, and fronts
|
||||
// GitHub. These tests drive it over a real loopback socket, since its
|
||||
// contract is HTTP.
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/desktop/github_proxy.dart';
|
||||
import 'package:diet_guard_app/desktop/wrapper_server.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
void main() {
|
||||
|
||||
|
||||
late Directory tempDir;
|
||||
late String webRoot;
|
||||
late String dataDir;
|
||||
late WrapperServer server;
|
||||
late List<http.Request> outbound;
|
||||
late Map<String, http.Response> canned;
|
||||
|
||||
Future<void> startServer({
|
||||
bool serveSyncAccount = false,
|
||||
String? syncConfigDir,
|
||||
}) async {
|
||||
outbound = [];
|
||||
canned = {};
|
||||
final proxy = GitHubProxy(
|
||||
tokenPath: p.join(tempDir.path, 'config', 'sync_token'),
|
||||
fallbackTokenPath: p.join(tempDir.path, 'config', 'fallback_token'),
|
||||
httpClient: MockClient((request) async {
|
||||
outbound.add(request);
|
||||
return canned[request.url.toString()] ??
|
||||
http.Response('{"ok":true}', 200);
|
||||
}),
|
||||
);
|
||||
server = WrapperServer(
|
||||
webRoot: webRoot,
|
||||
dataDir: dataDir,
|
||||
gitHubProxy: proxy,
|
||||
serveSyncAccount: serveSyncAccount,
|
||||
syncConfigDir: syncConfigDir,
|
||||
);
|
||||
await server.start(0);
|
||||
}
|
||||
|
||||
Uri url(String path) => Uri.parse('http://localhost:${server.port}$path');
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_wrapper_');
|
||||
webRoot = p.join(tempDir.path, 'web');
|
||||
dataDir = p.join(tempDir.path, 'data');
|
||||
await Directory(webRoot).create(recursive: true);
|
||||
File(p.join(webRoot, 'index.html')).writeAsStringSync('<html>app</html>');
|
||||
File(p.join(webRoot, 'main.wasm')).writeAsBytesSync([0, 97, 115, 109]);
|
||||
await startServer();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await server.stop();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
group('github proxy', () {
|
||||
test('reports no token before one is stored', () async {
|
||||
final response = await http.get(url('/github/auth/status'));
|
||||
|
||||
expect(jsonDecode(response.body), {'configured': false});
|
||||
});
|
||||
|
||||
test('stores a pasted token and then reports configured', () async {
|
||||
await http.post(url('/github/auth/token'), body: 'ghp_pasted');
|
||||
|
||||
final response = await http.get(url('/github/auth/status'));
|
||||
|
||||
expect(jsonDecode(response.body), {'configured': true});
|
||||
expect(
|
||||
File(p.join(tempDir.path, 'config', 'sync_token')).readAsStringSync(),
|
||||
'ghp_pasted',
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'falls back to the PC gate token when it has none of its own',
|
||||
() async {
|
||||
// The Python side already keeps a token for diet-guard-sync.timer;
|
||||
// reusing it is what makes the desktop app need no second setup.
|
||||
final fallback = File(p.join(tempDir.path, 'config', 'fallback_token'))
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync('ghp_from_gate\n');
|
||||
addTearDown(fallback.deleteSync);
|
||||
|
||||
final response = await http.get(url('/github/auth/status'));
|
||||
|
||||
expect(jsonDecode(response.body), {'configured': true});
|
||||
},
|
||||
);
|
||||
|
||||
test('attaches the token to a proxied API call', () async {
|
||||
await http.post(url('/github/auth/token'), body: 'ghp_stored');
|
||||
canned['https://api.github.com/repos/kuhyx/syncs'] = http.Response(
|
||||
'{"name":"syncs"}',
|
||||
200,
|
||||
);
|
||||
|
||||
final response = await http.get(url('/github/api/repos/kuhyx/syncs'));
|
||||
|
||||
expect(response.body, '{"name":"syncs"}');
|
||||
expect(outbound.single.headers['Authorization'], 'Bearer ghp_stored');
|
||||
});
|
||||
|
||||
test('keeps a device-flow token server-side', () async {
|
||||
canned['https://github.com/login/oauth/access_token'] = http.Response(
|
||||
'{"access_token":"ghp_device"}',
|
||||
200,
|
||||
);
|
||||
|
||||
final response = await http.post(
|
||||
url('/github/auth/device/poll'),
|
||||
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
|
||||
);
|
||||
|
||||
// The point of the proxy: the browser is told "ok", never the token.
|
||||
expect(jsonDecode(response.body), {'status': 'ok'});
|
||||
expect(response.body, isNot(contains('ghp_device')));
|
||||
expect(
|
||||
File(p.join(tempDir.path, 'config', 'sync_token')).readAsStringSync(),
|
||||
'ghp_device',
|
||||
);
|
||||
});
|
||||
|
||||
test('passes a still-pending device-flow poll straight back', () async {
|
||||
canned['https://github.com/login/oauth/access_token'] = http.Response(
|
||||
'{"error":"authorization_pending"}',
|
||||
200,
|
||||
);
|
||||
|
||||
final response = await http.post(
|
||||
url('/github/auth/device/poll'),
|
||||
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
|
||||
);
|
||||
|
||||
expect(jsonDecode(response.body), {'error': 'authorization_pending'});
|
||||
});
|
||||
|
||||
test('forwards the device-code request with the client id', () async {
|
||||
canned['https://github.com/login/device/code'] = http.Response(
|
||||
'{"device_code":"dc","user_code":"ABCD-1234"}',
|
||||
200,
|
||||
);
|
||||
|
||||
final response = await http.post(
|
||||
url('/github/auth/device/start'),
|
||||
body: jsonEncode({'client_id': 'cid'}),
|
||||
);
|
||||
|
||||
expect(jsonDecode(response.body), containsPair('user_code', 'ABCD-1234'));
|
||||
expect(outbound.single.bodyFields['client_id'], 'cid');
|
||||
});
|
||||
|
||||
test('404s an unknown /github path', () async {
|
||||
expect((await http.get(url('/github/nope'))).statusCode, 404);
|
||||
});
|
||||
|
||||
test('clears the stored token when handed an empty one', () async {
|
||||
await http.post(url('/github/auth/token'), body: 'ghp_stored');
|
||||
|
||||
await http.post(url('/github/auth/token'), body: '');
|
||||
|
||||
expect(jsonDecode((await http.get(url('/github/auth/status'))).body), {
|
||||
'configured': false,
|
||||
});
|
||||
});
|
||||
|
||||
test('ignores an unreadable token file rather than failing', () async {
|
||||
// A directory where the token file should be: readToken must fall
|
||||
// through to "no token" instead of throwing out of every request.
|
||||
Directory(
|
||||
p.join(tempDir.path, 'config', 'sync_token'),
|
||||
).createSync(recursive: true);
|
||||
|
||||
expect(jsonDecode((await http.get(url('/github/auth/status'))).body), {
|
||||
'configured': false,
|
||||
});
|
||||
});
|
||||
|
||||
test('passes a non-JSON device-flow response straight back', () async {
|
||||
canned['https://github.com/login/oauth/access_token'] = http.Response(
|
||||
'<html>rate limited</html>',
|
||||
200,
|
||||
);
|
||||
|
||||
final response = await http.post(
|
||||
url('/github/auth/device/poll'),
|
||||
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
|
||||
);
|
||||
|
||||
expect(response.body, contains('rate limited'));
|
||||
});
|
||||
|
||||
test('treats a malformed request body as empty fields', () async {
|
||||
final response = await http.post(
|
||||
url('/github/auth/device/start'),
|
||||
body: 'not json',
|
||||
);
|
||||
|
||||
expect(response.statusCode, 200);
|
||||
expect(outbound.single.bodyFields['client_id'], 'null');
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -14,6 +14,7 @@ import 'package:http/testing.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
late String webRoot;
|
||||
late String dataDir;
|
||||
@ -85,7 +86,6 @@ void main() {
|
||||
expect((await http.get(url('/nope.js'))).statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
group('document mirror', () {
|
||||
test('round-trips a document', () async {
|
||||
final posted = await http.post(
|
||||
@ -124,155 +124,6 @@ void main() {
|
||||
expect((await http.delete(url('/documents/x.json'))).statusCode, 405);
|
||||
});
|
||||
});
|
||||
|
||||
group('github proxy', () {
|
||||
test('reports no token before one is stored', () async {
|
||||
final response = await http.get(url('/github/auth/status'));
|
||||
|
||||
expect(jsonDecode(response.body), {'configured': false});
|
||||
});
|
||||
|
||||
test('stores a pasted token and then reports configured', () async {
|
||||
await http.post(url('/github/auth/token'), body: 'ghp_pasted');
|
||||
|
||||
final response = await http.get(url('/github/auth/status'));
|
||||
|
||||
expect(jsonDecode(response.body), {'configured': true});
|
||||
expect(
|
||||
File(p.join(tempDir.path, 'config', 'sync_token')).readAsStringSync(),
|
||||
'ghp_pasted',
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'falls back to the PC gate token when it has none of its own',
|
||||
() async {
|
||||
// The Python side already keeps a token for diet-guard-sync.timer;
|
||||
// reusing it is what makes the desktop app need no second setup.
|
||||
final fallback = File(p.join(tempDir.path, 'config', 'fallback_token'))
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync('ghp_from_gate\n');
|
||||
addTearDown(fallback.deleteSync);
|
||||
|
||||
final response = await http.get(url('/github/auth/status'));
|
||||
|
||||
expect(jsonDecode(response.body), {'configured': true});
|
||||
},
|
||||
);
|
||||
|
||||
test('attaches the token to a proxied API call', () async {
|
||||
await http.post(url('/github/auth/token'), body: 'ghp_stored');
|
||||
canned['https://api.github.com/repos/kuhyx/syncs'] = http.Response(
|
||||
'{"name":"syncs"}',
|
||||
200,
|
||||
);
|
||||
|
||||
final response = await http.get(url('/github/api/repos/kuhyx/syncs'));
|
||||
|
||||
expect(response.body, '{"name":"syncs"}');
|
||||
expect(outbound.single.headers['Authorization'], 'Bearer ghp_stored');
|
||||
});
|
||||
|
||||
test('keeps a device-flow token server-side', () async {
|
||||
canned['https://github.com/login/oauth/access_token'] = http.Response(
|
||||
'{"access_token":"ghp_device"}',
|
||||
200,
|
||||
);
|
||||
|
||||
final response = await http.post(
|
||||
url('/github/auth/device/poll'),
|
||||
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
|
||||
);
|
||||
|
||||
// The point of the proxy: the browser is told "ok", never the token.
|
||||
expect(jsonDecode(response.body), {'status': 'ok'});
|
||||
expect(response.body, isNot(contains('ghp_device')));
|
||||
expect(
|
||||
File(p.join(tempDir.path, 'config', 'sync_token')).readAsStringSync(),
|
||||
'ghp_device',
|
||||
);
|
||||
});
|
||||
|
||||
test('passes a still-pending device-flow poll straight back', () async {
|
||||
canned['https://github.com/login/oauth/access_token'] = http.Response(
|
||||
'{"error":"authorization_pending"}',
|
||||
200,
|
||||
);
|
||||
|
||||
final response = await http.post(
|
||||
url('/github/auth/device/poll'),
|
||||
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
|
||||
);
|
||||
|
||||
expect(jsonDecode(response.body), {'error': 'authorization_pending'});
|
||||
});
|
||||
|
||||
test('forwards the device-code request with the client id', () async {
|
||||
canned['https://github.com/login/device/code'] = http.Response(
|
||||
'{"device_code":"dc","user_code":"ABCD-1234"}',
|
||||
200,
|
||||
);
|
||||
|
||||
final response = await http.post(
|
||||
url('/github/auth/device/start'),
|
||||
body: jsonEncode({'client_id': 'cid'}),
|
||||
);
|
||||
|
||||
expect(jsonDecode(response.body), containsPair('user_code', 'ABCD-1234'));
|
||||
expect(outbound.single.bodyFields['client_id'], 'cid');
|
||||
});
|
||||
|
||||
test('404s an unknown /github path', () async {
|
||||
expect((await http.get(url('/github/nope'))).statusCode, 404);
|
||||
});
|
||||
|
||||
test('clears the stored token when handed an empty one', () async {
|
||||
await http.post(url('/github/auth/token'), body: 'ghp_stored');
|
||||
|
||||
await http.post(url('/github/auth/token'), body: '');
|
||||
|
||||
expect(jsonDecode((await http.get(url('/github/auth/status'))).body), {
|
||||
'configured': false,
|
||||
});
|
||||
});
|
||||
|
||||
test('ignores an unreadable token file rather than failing', () async {
|
||||
// A directory where the token file should be: readToken must fall
|
||||
// through to "no token" instead of throwing out of every request.
|
||||
Directory(
|
||||
p.join(tempDir.path, 'config', 'sync_token'),
|
||||
).createSync(recursive: true);
|
||||
|
||||
expect(jsonDecode((await http.get(url('/github/auth/status'))).body), {
|
||||
'configured': false,
|
||||
});
|
||||
});
|
||||
|
||||
test('passes a non-JSON device-flow response straight back', () async {
|
||||
canned['https://github.com/login/oauth/access_token'] = http.Response(
|
||||
'<html>rate limited</html>',
|
||||
200,
|
||||
);
|
||||
|
||||
final response = await http.post(
|
||||
url('/github/auth/device/poll'),
|
||||
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
|
||||
);
|
||||
|
||||
expect(response.body, contains('rate limited'));
|
||||
});
|
||||
|
||||
test('treats a malformed request body as empty fields', () async {
|
||||
final response = await http.post(
|
||||
url('/github/auth/device/start'),
|
||||
body: 'not json',
|
||||
);
|
||||
|
||||
expect(response.statusCode, 200);
|
||||
expect(outbound.single.bodyFields['client_id'], 'null');
|
||||
});
|
||||
});
|
||||
|
||||
group('content types', () {
|
||||
test('labels each asset kind the browser is strict about', () {
|
||||
ContentType typeOf(String name) =>
|
||||
@ -291,59 +142,4 @@ void main() {
|
||||
expect(typeOf('data.bin').mimeType, 'application/octet-stream');
|
||||
});
|
||||
});
|
||||
|
||||
group('sync-account provisioning', () {
|
||||
/// Writes [files] into a temp config dir and restarts with the route on.
|
||||
Future<String> enableWith(Map<String, String> files) async {
|
||||
final configDir = Directory(p.join(tempDir.path, 'crdt-sync'))
|
||||
..createSync(recursive: true);
|
||||
files.forEach((name, contents) {
|
||||
File(p.join(configDir.path, name)).writeAsStringSync(contents);
|
||||
});
|
||||
await server.stop();
|
||||
await startServer(serveSyncAccount: true, syncConfigDir: configDir.path);
|
||||
return 'http://localhost:${server.port}';
|
||||
}
|
||||
|
||||
test('is 404 when not enabled', () async {
|
||||
// The default, and the whole security posture: a credential route must
|
||||
// not be reachable just because the wrapper is running.
|
||||
final response = await http.get(url(kSyncAccountPath));
|
||||
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
});
|
||||
|
||||
test('serves the account when enabled', () async {
|
||||
final origin = await enableWith({
|
||||
'firebase.json': '{"email":"a@b.c"}',
|
||||
'password': 'pw\n',
|
||||
});
|
||||
|
||||
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
||||
final account = FirebaseAccount.tryParse(response.body);
|
||||
|
||||
expect(response.statusCode, HttpStatus.ok);
|
||||
expect(account?.email, 'a@b.c');
|
||||
expect(account?.password, 'pw');
|
||||
});
|
||||
|
||||
test('is 404 when the config files are absent', () async {
|
||||
final origin = await enableWith({});
|
||||
|
||||
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
||||
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
});
|
||||
|
||||
test('is 404 when firebase.json has no usable email', () async {
|
||||
final origin = await enableWith({
|
||||
'firebase.json': '{"apiKey":"x"}',
|
||||
'password': 'pw',
|
||||
});
|
||||
|
||||
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
||||
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart' as http_testing;
|
||||
import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
|
||||
|
||||
import 'fake_secure_storage.dart';
|
||||
|
||||
|
||||
157
app/test/repo_invariants_test.dart
Normal file
157
app/test/repo_invariants_test.dart
Normal file
@ -0,0 +1,157 @@
|
||||
/// Structural rules that used to live only as prose in CLAUDE.md.
|
||||
///
|
||||
/// Each rule here was previously a paragraph asking a future reader not to do
|
||||
/// something. A paragraph does not fail a commit, so these are tests instead:
|
||||
/// the rule and its enforcement are the same artifact, and the *why* lives in
|
||||
/// the test name rather than in a document that can drift from the code.
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
/// `app/` from the repo root, resolved relative to the package directory so
|
||||
/// the test works regardless of the working directory `flutter test` uses.
|
||||
Directory get _appDir {
|
||||
var dir = Directory.current;
|
||||
while (!File('${dir.path}/pubspec.yaml').existsSync()) {
|
||||
final parent = dir.parent;
|
||||
if (parent.path == dir.path) {
|
||||
fail('could not locate app/ from ${Directory.current.path}');
|
||||
}
|
||||
dir = parent;
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
List<File> _dartFilesIn(String relative) {
|
||||
final dir = Directory('${_appDir.path}/$relative');
|
||||
if (!dir.existsSync()) return const [];
|
||||
return dir
|
||||
.listSync(recursive: true)
|
||||
.whereType<File>()
|
||||
.where((f) => f.path.endsWith('.dart'))
|
||||
.toList();
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('the desktop target is a web build, not a GTK embedder', () {
|
||||
// Flutter's Linux embedder manages ~20fps at 3840x2160 where the same Dart
|
||||
// in Chrome sustains ~144fps. `flutter create --platforms linux` would
|
||||
// silently restore the slow path, and nothing about the resulting tree
|
||||
// looks wrong at a glance -- so the absence of the directory is asserted.
|
||||
test('app/linux/ does not exist', () {
|
||||
expect(
|
||||
Directory('${_appDir.path}/linux').existsSync(),
|
||||
isFalse,
|
||||
reason: 'A Linux embedder target was re-added. The desktop app is the '
|
||||
'web build served by bin/diet_guard_desktop.dart; see CLAUDE.md.',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('dart:io stays behind the platform seam', () {
|
||||
// dart:io does not fail a web *compile* -- it becomes a stub that throws at
|
||||
// runtime, so the symptom of a bad import is a blank white window rather
|
||||
// than a build error. Widget tests run on the VM and would not catch it.
|
||||
test('only *_io.dart halves and lib/desktop/ import dart:io', () {
|
||||
final offenders = <String>[];
|
||||
for (final file in _dartFilesIn('lib')) {
|
||||
final relative = file.path.split('/app/lib/').last;
|
||||
final isSeam = relative.endsWith('_io.dart');
|
||||
final isDesktopOnly = relative.startsWith('desktop/');
|
||||
if (isSeam || isDesktopOnly) continue;
|
||||
if (file.readAsStringSync().contains("import 'dart:io'")) {
|
||||
offenders.add(relative);
|
||||
}
|
||||
}
|
||||
expect(
|
||||
offenders,
|
||||
isEmpty,
|
||||
reason: 'These files import dart:io outside the conditional-export '
|
||||
'seam, which compiles for web and throws at runtime (blank white '
|
||||
'window). Move the platform edge into a *_io.dart / *_web.dart '
|
||||
'pair, and branch on kIsWeb before any Platform.is… check.',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('deliberately removed features stay removed', () {
|
||||
// The meal builder, "repeat last meal" and the temptation-bundling reward
|
||||
// prompt were each removed as unused. Re-adding one is a decision, not an
|
||||
// accident -- this test exists so it cannot happen by accident.
|
||||
test('no meal builder, repeat-last-meal or reward prompt', () {
|
||||
final banned = RegExp(
|
||||
r'MealBuilder|mealBuilder|repeatLastMeal|rewardPrompt|temptationBundl',
|
||||
);
|
||||
final offenders = <String>[];
|
||||
for (final file in _dartFilesIn('lib')) {
|
||||
if (banned.hasMatch(file.readAsStringSync())) {
|
||||
offenders.add(file.path.split('/app/lib/').last);
|
||||
}
|
||||
}
|
||||
expect(
|
||||
offenders,
|
||||
isEmpty,
|
||||
reason: 'A removed feature came back. See the "Do NOT" section of '
|
||||
'CLAUDE.md before re-adding any of these.',
|
||||
);
|
||||
});
|
||||
|
||||
// Photos took image_picker, the blob stores, the wrapper's /blobs/ route
|
||||
// and the CAMERA permission with them. Re-adding photos means re-adding
|
||||
// all of that *plus* syncing image blobs, since a device-local attachment
|
||||
// would violate the one-source-of-truth rule.
|
||||
test('no image_picker dependency', () {
|
||||
final pubspec = File('${_appDir.path}/pubspec.yaml').readAsStringSync();
|
||||
expect(
|
||||
pubspec.contains('image_picker'),
|
||||
isFalse,
|
||||
reason: 'Meal photos were removed deliberately. A device-local image '
|
||||
'attachment also breaks the shared-source-of-truth rule.',
|
||||
);
|
||||
});
|
||||
|
||||
test('no CAMERA permission in the Android manifest', () {
|
||||
final manifest = File(
|
||||
'${_appDir.path}/android/app/src/main/AndroidManifest.xml',
|
||||
);
|
||||
expect(
|
||||
manifest.readAsStringSync().contains('android.permission.CAMERA'),
|
||||
isFalse,
|
||||
reason: 'The CAMERA permission came back with no photo feature to '
|
||||
'justify it.',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('the desktop wrapper origin is fixed', () {
|
||||
// IndexedDB is keyed by origin and lives in the Chrome profile. Changing
|
||||
// either the port or the --user-data-dir hides the entire local food log
|
||||
// behind a different origin, which reads as data loss to the user.
|
||||
test('the wrapper port is still 8732', () {
|
||||
final source = File(
|
||||
'${_appDir.path}/lib/services/desktop_wrapper.dart',
|
||||
).readAsStringSync();
|
||||
expect(
|
||||
source.contains('desktopWrapperPort = 8732'),
|
||||
isTrue,
|
||||
reason: 'The wrapper port changed. IndexedDB is keyed by origin, so a '
|
||||
'new port looks like a different app with no history at all. '
|
||||
'8730 is ~/todo and 8731 is ~/habit_stack; do not collide.',
|
||||
);
|
||||
});
|
||||
|
||||
test('the Chrome profile directory is still diet-guard-desktop', () {
|
||||
final source = File(
|
||||
'${_appDir.path}/bin/diet_guard_desktop.dart',
|
||||
).readAsStringSync();
|
||||
expect(
|
||||
source.contains("'diet-guard-desktop', 'profile'"),
|
||||
isTrue,
|
||||
reason: 'The Chrome --user-data-dir moved. IndexedDB lives in that '
|
||||
'profile, so relocating it hides the entire local food log.',
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
150
app/test/screens/edit_entry_screen_foodbank_test.dart
Normal file
150
app/test/screens/edit_entry_screen_foodbank_test.dart
Normal file
@ -0,0 +1,150 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
const _entry = FoodEntry(
|
||||
id: 'test-uuid',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'pizza obok pracy',
|
||||
grams: 400,
|
||||
kcal: 1200,
|
||||
proteinG: 52,
|
||||
carbsG: 145,
|
||||
fatG: 42,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_edit_test_');
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
LogStorageService.resetForTesting();
|
||||
FoodBankService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
testWidgets('selecting a food bank suggestion fills all macro fields', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'pizza obok pracy',
|
||||
kcal: 1200,
|
||||
proteinG: 52,
|
||||
carbsG: 145,
|
||||
fatG: 42,
|
||||
grams: 400,
|
||||
count: 1,
|
||||
),
|
||||
);
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [_entry],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: EditEntryScreen(entry: _entry)),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// The desc field already matches the bank entry — a suggestion appears.
|
||||
expect(find.text('pizza obok pracy'), findsWidgets);
|
||||
// Tap the suggestion tile (the one in the autocomplete list, not the
|
||||
// TextField itself).
|
||||
final suggestionTiles = find.text('pizza obok pracy');
|
||||
// At least 2 matches: TextField text + suggestion tile.
|
||||
expect(suggestionTiles, findsWidgets);
|
||||
await tester.tap(suggestionTiles.last);
|
||||
await settle(tester);
|
||||
|
||||
// After selection, suggestions are cleared and macros are filled.
|
||||
expect(find.text('1200'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
testWidgets(
|
||||
'editing a macro after selecting a suggestion resets source to manual',
|
||||
(tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'pizza obok pracy',
|
||||
kcal: 1200,
|
||||
proteinG: 52,
|
||||
carbsG: 145,
|
||||
fatG: 42,
|
||||
grams: 400,
|
||||
count: 1,
|
||||
),
|
||||
);
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [_entry],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: EditEntryScreen(entry: _entry)),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Select the suggestion to set _source = 'food bank'.
|
||||
final suggestionTiles = find.text('pizza obok pracy');
|
||||
await tester.tap(suggestionTiles.last);
|
||||
await settle(tester);
|
||||
|
||||
// Manually edit kcal — should flip _source back to 'manual'.
|
||||
await tester.enterText(
|
||||
find.ancestor(
|
||||
of: find.text('1200'),
|
||||
matching: find.byType(TextField),
|
||||
),
|
||||
'999',
|
||||
);
|
||||
await settle(tester);
|
||||
await tester.tap(find.text('Save'));
|
||||
await settle(tester);
|
||||
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
// Source reverts to 'manual' after macro edit.
|
||||
expect(log['2026-06-22']!.first.source, 'manual');
|
||||
});
|
||||
},
|
||||
);
|
||||
testWidgets('tapping an entry tile navigates to EditEntryScreen', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [_entry],
|
||||
});
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('pizza obok pracy'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Edit meal'), findsOneWidget);
|
||||
expect(find.text('pizza obok pracy'), findsOneWidget);
|
||||
// Macros are pre-filled.
|
||||
expect(find.text('1200'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -23,6 +23,7 @@ const _entry = FoodEntry(
|
||||
);
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
@ -60,7 +61,6 @@ void main() {
|
||||
expect(find.text('400'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Save button is present and AppBar title is correct', (
|
||||
tester,
|
||||
) async {
|
||||
@ -76,7 +76,6 @@ void main() {
|
||||
expect(find.text('Save'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('shows error when description is cleared', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
@ -99,7 +98,6 @@ void main() {
|
||||
expect(find.text('Description cannot be empty.'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Save persists updated kcal to the log', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
@ -128,7 +126,6 @@ void main() {
|
||||
expect(saved.id, 'test-uuid');
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('legacy null-id entry gains a UUID on save', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
const legacy = FoodEntry(
|
||||
@ -159,111 +156,4 @@ void main() {
|
||||
expect(saved.kcal, 1174);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('selecting a food bank suggestion fills all macro fields', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'pizza obok pracy',
|
||||
kcal: 1200,
|
||||
proteinG: 52,
|
||||
carbsG: 145,
|
||||
fatG: 42,
|
||||
grams: 400,
|
||||
count: 1,
|
||||
),
|
||||
);
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [_entry],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: EditEntryScreen(entry: _entry)),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// The desc field already matches the bank entry — a suggestion appears.
|
||||
expect(find.text('pizza obok pracy'), findsWidgets);
|
||||
// Tap the suggestion tile (the one in the autocomplete list, not the
|
||||
// TextField itself).
|
||||
final suggestionTiles = find.text('pizza obok pracy');
|
||||
// At least 2 matches: TextField text + suggestion tile.
|
||||
expect(suggestionTiles, findsWidgets);
|
||||
await tester.tap(suggestionTiles.last);
|
||||
await settle(tester);
|
||||
|
||||
// After selection, suggestions are cleared and macros are filled.
|
||||
expect(find.text('1200'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'editing a macro after selecting a suggestion resets source to manual',
|
||||
(tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'pizza obok pracy',
|
||||
kcal: 1200,
|
||||
proteinG: 52,
|
||||
carbsG: 145,
|
||||
fatG: 42,
|
||||
grams: 400,
|
||||
count: 1,
|
||||
),
|
||||
);
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [_entry],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: EditEntryScreen(entry: _entry)),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Select the suggestion to set _source = 'food bank'.
|
||||
final suggestionTiles = find.text('pizza obok pracy');
|
||||
await tester.tap(suggestionTiles.last);
|
||||
await settle(tester);
|
||||
|
||||
// Manually edit kcal — should flip _source back to 'manual'.
|
||||
await tester.enterText(
|
||||
find.ancestor(
|
||||
of: find.text('1200'),
|
||||
matching: find.byType(TextField),
|
||||
),
|
||||
'999',
|
||||
);
|
||||
await settle(tester);
|
||||
await tester.tap(find.text('Save'));
|
||||
await settle(tester);
|
||||
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
// Source reverts to 'manual' after macro edit.
|
||||
expect(log['2026-06-22']!.first.source, 'manual');
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('tapping an entry tile navigates to EditEntryScreen', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [_entry],
|
||||
});
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('pizza obok pracy'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Edit meal'), findsOneWidget);
|
||||
expect(find.text('pizza obok pracy'), findsOneWidget);
|
||||
// Macros are pre-filled.
|
||||
expect(find.text('1200'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
218
app/test/screens/food_bank/fb_filter_test.dart
Normal file
218
app/test/screens/food_bank/fb_filter_test.dart
Normal file
@ -0,0 +1,218 @@
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'fb_test_support.dart';
|
||||
|
||||
void main() {
|
||||
useTempFoodBankStores();
|
||||
group('applyFbFilter', () {
|
||||
final records = [
|
||||
const FoodBankRecord(
|
||||
desc: 'Apple',
|
||||
kcal: 80,
|
||||
proteinG: 0.5,
|
||||
carbsG: 20,
|
||||
fatG: 0.3,
|
||||
grams: 100,
|
||||
count: 5,
|
||||
),
|
||||
const FoodBankRecord(
|
||||
desc: 'Banana',
|
||||
kcal: 90,
|
||||
proteinG: 1,
|
||||
carbsG: 22,
|
||||
fatG: 0.4,
|
||||
grams: 100,
|
||||
count: 10,
|
||||
),
|
||||
const FoodBankRecord(
|
||||
desc: 'Chicken breast',
|
||||
kcal: 165,
|
||||
proteinG: 31,
|
||||
carbsG: 0,
|
||||
fatG: 3.6,
|
||||
grams: 100,
|
||||
count: 2,
|
||||
),
|
||||
];
|
||||
|
||||
test('no filter returns entries sorted by count descending', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Banana', 'Apple', 'Chicken breast']);
|
||||
});
|
||||
|
||||
test('nameQuery filters by case-insensitive substring', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(nameQuery: 'an'),
|
||||
FbSortField.name,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.map((r) => r.desc), [
|
||||
'Banana',
|
||||
]); // only 'Banana' contains 'an'
|
||||
});
|
||||
|
||||
test('minKcal and maxKcal filter by kcal', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(minKcal: 85, maxKcal: 100),
|
||||
FbSortField.kcal,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Banana']);
|
||||
});
|
||||
|
||||
test('minProtein filters by protein', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(minProtein: 10),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Chicken breast']);
|
||||
});
|
||||
|
||||
test('maxCarbs filters by carbs', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(maxCarbs: 5),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Chicken breast']);
|
||||
});
|
||||
|
||||
test('minFat and maxFat filter by fat', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(minFat: 0.35, maxFat: 1),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Banana']);
|
||||
});
|
||||
|
||||
test('maxProtein filters by protein', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(maxProtein: 5),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
// Banana (1 g) and Apple (0.5 g) have protein ≤ 5 g; sorted count desc.
|
||||
expect(result.map((r) => r.desc), ['Banana', 'Apple']);
|
||||
});
|
||||
|
||||
test('minCarbs filters by carbs', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(minCarbs: 10),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
// Banana (22 g) and Apple (20 g) have carbs ≥ 10 g; sorted count desc.
|
||||
expect(result.map((r) => r.desc), ['Banana', 'Apple']);
|
||||
});
|
||||
|
||||
test('sort ascending by name', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.name,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Apple', 'Banana', 'Chicken breast']);
|
||||
});
|
||||
|
||||
test('sort descending by kcal', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.kcal,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.first.desc, 'Chicken breast');
|
||||
});
|
||||
|
||||
test('sort ascending by protein', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.protein,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.first.desc, 'Apple');
|
||||
});
|
||||
|
||||
test('sort by carbs ascending', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.carbs,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.first.desc, 'Chicken breast'); // 0g
|
||||
});
|
||||
|
||||
test('sort by fat descending', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.fat,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.first.desc, 'Chicken breast'); // 3.6g
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is false when nothing is set', () {
|
||||
expect(FbFilter().isActive, isFalse);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when nameQuery is set', () {
|
||||
expect(FbFilter(nameQuery: 'x').isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when minKcal is set', () {
|
||||
expect(FbFilter(minKcal: 50).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when maxKcal is set', () {
|
||||
expect(FbFilter(maxKcal: 500).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when minProtein is set', () {
|
||||
expect(FbFilter(minProtein: 5).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when maxProtein is set', () {
|
||||
expect(FbFilter(maxProtein: 50).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when minCarbs is set', () {
|
||||
expect(FbFilter(minCarbs: 5).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when maxCarbs is set', () {
|
||||
expect(FbFilter(maxCarbs: 50).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when minFat is set', () {
|
||||
expect(FbFilter(minFat: 1).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when maxFat is set', () {
|
||||
expect(FbFilter(maxFat: 10).isActive, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Widget tests
|
||||
// ---------------------------------------------------------------------------
|
||||
}
|
||||
206
app/test/screens/food_bank/fb_screen_test.dart
Normal file
206
app/test/screens/food_bank/fb_screen_test.dart
Normal file
@ -0,0 +1,206 @@
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'fb_test_support.dart';
|
||||
|
||||
void main() {
|
||||
useTempFoodBankStores();
|
||||
testWidgets('shows empty-bank message when no entries exist', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.textContaining('Food bank is empty'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('lists entries from the merged bank', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Manual oat',
|
||||
kcal: 370,
|
||||
proteinG: 13,
|
||||
carbsG: 66,
|
||||
fatG: 7,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Manual oat'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('FAB opens add-entry dialog and saving adds to bank', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byType(FloatingActionButton));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Add to food bank'), findsOneWidget);
|
||||
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'Name'),
|
||||
'Test food',
|
||||
);
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'Kcal'),
|
||||
'200',
|
||||
);
|
||||
|
||||
await tester.tap(find.text('Save to bank'));
|
||||
await settle(tester);
|
||||
|
||||
// After saving, the screen reloads and shows the new entry.
|
||||
expect(find.text('Test food'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('dialog cancel does not save anything', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byType(FloatingActionButton));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.textContaining('Food bank is empty'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('dialog save with empty name does nothing', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byType(FloatingActionButton));
|
||||
await settle(tester);
|
||||
|
||||
// Tap save without entering a name.
|
||||
await tester.tap(find.text('Save to bank'));
|
||||
await settle(tester);
|
||||
|
||||
// Dialog stays open; no entry saved.
|
||||
expect(find.text('Add to food bank'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter icon appears when entries exist', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Oat',
|
||||
kcal: 370,
|
||||
proteinG: 13,
|
||||
carbsG: 66,
|
||||
fatG: 7,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
expect(
|
||||
find.widgetWithIcon(IconButton, Icons.filter_list),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet opens and Apply filters results', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Oat',
|
||||
kcal: 370,
|
||||
proteinG: 13,
|
||||
carbsG: 66,
|
||||
fatG: 7,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Egg',
|
||||
kcal: 155,
|
||||
proteinG: 13,
|
||||
carbsG: 1,
|
||||
fatG: 11,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsOneWidget);
|
||||
|
||||
// Type in the only TextField in the sheet (the name search field).
|
||||
await tester.enterText(find.byType(TextField).first, 'Oat');
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
// Sheet is closed; only the matching entry is visible.
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
expect(find.text('Oat'), findsOneWidget);
|
||||
expect(find.text('Egg'), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet Clear all resets draft then Apply shows all', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Walnut',
|
||||
kcal: 654,
|
||||
proteinG: 15,
|
||||
carbsG: 14,
|
||||
fatG: 65,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Clear all'));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Walnut'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
184
app/test/screens/food_bank/fb_sheet_test.dart
Normal file
184
app/test/screens/food_bank/fb_sheet_test.dart
Normal file
@ -0,0 +1,184 @@
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'fb_test_support.dart';
|
||||
|
||||
void main() {
|
||||
useTempFoodBankStores();
|
||||
testWidgets('record tile shows usage count for log-derived entries', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.rebuildAndPersist({
|
||||
'2026-06-22': [
|
||||
const FoodEntry(
|
||||
id: '1',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'rice',
|
||||
grams: 100,
|
||||
kcal: 130,
|
||||
proteinG: 3,
|
||||
carbsG: 28,
|
||||
fatG: 0.3,
|
||||
source: 'manual',
|
||||
),
|
||||
const FoodEntry(
|
||||
id: '2',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'rice',
|
||||
grams: 100,
|
||||
kcal: 130,
|
||||
proteinG: 3,
|
||||
carbsG: 28,
|
||||
fatG: 0.3,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// The rice entry was logged twice — the tile trailing shows ×2.
|
||||
expect(find.textContaining('×2'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet sort dropdown changes sort field', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
// Zero macros: no RangeSliders appear, sort section is immediately visible.
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'ZeroItem',
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsOneWidget);
|
||||
|
||||
// With no sliders rendered, 'Sort by' and its dropdown are immediately
|
||||
// visible — open the sort-field dropdown (shows 'Usage count' by default).
|
||||
await tester.tap(find.text('Usage count'));
|
||||
await settle(tester);
|
||||
|
||||
// Tap 'Name' in the dropdown overlay.
|
||||
await tester.tap(find.text('Name').last);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
expect(find.text('ZeroItem'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet RangeSlider onChanged callbacks fire', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
// Non-zero macros: all four RangeSliders appear in the filter sheet.
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'SliderFood',
|
||||
kcal: 200,
|
||||
proteinG: 10,
|
||||
carbsG: 25,
|
||||
fatG: 8,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
// Use getRect() + dragFrom() to bypass the _maybeViewOf ancestor-search
|
||||
// failure that tester.drag(finder, …) triggers inside modal overlays.
|
||||
|
||||
// Kcal slider covers lines 468-471.
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byType(RangeSlider).at(0)).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Protein slider covers lines 491-495.
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byType(RangeSlider).at(1)).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Carbs slider covers lines 515-518.
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byType(RangeSlider).at(2)).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Fat slider covers lines 538-541.
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byType(RangeSlider).at(3)).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet sort direction toggle fires onSortChanged', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
// Zero macros: no RangeSliders appear, sort section is immediately visible.
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'ZeroItem2',
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsOneWidget);
|
||||
|
||||
// Default sort is count-descending; the direction icon is arrow_downward.
|
||||
await tester.tap(find.byIcon(Icons.arrow_downward));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('ZeroItem2'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
42
app/test/screens/food_bank/fb_test_support.dart
Normal file
42
app/test/screens/food_bank/fb_test_support.dart
Normal file
@ -0,0 +1,42 @@
|
||||
/// Shared setup for the food bank screen's split test files.
|
||||
///
|
||||
/// `food_bank_screen_test.dart` was one 614-line file; splitting it for the
|
||||
/// repo's 250-line cap left every part needing the same temp-dir isolation and
|
||||
/// the same settle helper, so they live here rather than being copy-pasted
|
||||
/// (which is how two copies drift and one silently stops isolating).
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
/// Point the food bank and log services at a fresh temp dir per test, and tear
|
||||
/// it down afterwards. Call once at the top of a file's `main()`.
|
||||
void useTempFoodBankStores() {
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_screen_');
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
FoodBankService.resetForTesting();
|
||||
LogStorageService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
}
|
||||
|
||||
/// Pump until the screen has finished its untracked initState load.
|
||||
///
|
||||
/// FoodBankScreen loads via a fire-and-forget Future in initState that
|
||||
/// Flutter's frame scheduler does not track, so every test runs inside
|
||||
/// runAsync() with a short real delay before settling.
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
@ -1,614 +0,0 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_screen_');
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
FoodBankService.resetForTesting();
|
||||
LogStorageService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// applyFbFilter — pure function tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
group('applyFbFilter', () {
|
||||
final records = [
|
||||
const FoodBankRecord(
|
||||
desc: 'Apple',
|
||||
kcal: 80,
|
||||
proteinG: 0.5,
|
||||
carbsG: 20,
|
||||
fatG: 0.3,
|
||||
grams: 100,
|
||||
count: 5,
|
||||
),
|
||||
const FoodBankRecord(
|
||||
desc: 'Banana',
|
||||
kcal: 90,
|
||||
proteinG: 1,
|
||||
carbsG: 22,
|
||||
fatG: 0.4,
|
||||
grams: 100,
|
||||
count: 10,
|
||||
),
|
||||
const FoodBankRecord(
|
||||
desc: 'Chicken breast',
|
||||
kcal: 165,
|
||||
proteinG: 31,
|
||||
carbsG: 0,
|
||||
fatG: 3.6,
|
||||
grams: 100,
|
||||
count: 2,
|
||||
),
|
||||
];
|
||||
|
||||
test('no filter returns entries sorted by count descending', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Banana', 'Apple', 'Chicken breast']);
|
||||
});
|
||||
|
||||
test('nameQuery filters by case-insensitive substring', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(nameQuery: 'an'),
|
||||
FbSortField.name,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.map((r) => r.desc), [
|
||||
'Banana',
|
||||
]); // only 'Banana' contains 'an'
|
||||
});
|
||||
|
||||
test('minKcal and maxKcal filter by kcal', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(minKcal: 85, maxKcal: 100),
|
||||
FbSortField.kcal,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Banana']);
|
||||
});
|
||||
|
||||
test('minProtein filters by protein', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(minProtein: 10),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Chicken breast']);
|
||||
});
|
||||
|
||||
test('maxCarbs filters by carbs', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(maxCarbs: 5),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Chicken breast']);
|
||||
});
|
||||
|
||||
test('minFat and maxFat filter by fat', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(minFat: 0.35, maxFat: 1),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Banana']);
|
||||
});
|
||||
|
||||
test('maxProtein filters by protein', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(maxProtein: 5),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
// Banana (1 g) and Apple (0.5 g) have protein ≤ 5 g; sorted count desc.
|
||||
expect(result.map((r) => r.desc), ['Banana', 'Apple']);
|
||||
});
|
||||
|
||||
test('minCarbs filters by carbs', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(minCarbs: 10),
|
||||
FbSortField.count,
|
||||
ascending: false,
|
||||
);
|
||||
// Banana (22 g) and Apple (20 g) have carbs ≥ 10 g; sorted count desc.
|
||||
expect(result.map((r) => r.desc), ['Banana', 'Apple']);
|
||||
});
|
||||
|
||||
test('sort ascending by name', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.name,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.map((r) => r.desc), ['Apple', 'Banana', 'Chicken breast']);
|
||||
});
|
||||
|
||||
test('sort descending by kcal', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.kcal,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.first.desc, 'Chicken breast');
|
||||
});
|
||||
|
||||
test('sort ascending by protein', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.protein,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.first.desc, 'Apple');
|
||||
});
|
||||
|
||||
test('sort by carbs ascending', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.carbs,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.first.desc, 'Chicken breast'); // 0g
|
||||
});
|
||||
|
||||
test('sort by fat descending', () {
|
||||
final result = applyFbFilter(
|
||||
records,
|
||||
FbFilter(),
|
||||
FbSortField.fat,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.first.desc, 'Chicken breast'); // 3.6g
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is false when nothing is set', () {
|
||||
expect(FbFilter().isActive, isFalse);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when nameQuery is set', () {
|
||||
expect(FbFilter(nameQuery: 'x').isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when minKcal is set', () {
|
||||
expect(FbFilter(minKcal: 50).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when maxKcal is set', () {
|
||||
expect(FbFilter(maxKcal: 500).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when minProtein is set', () {
|
||||
expect(FbFilter(minProtein: 5).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when maxProtein is set', () {
|
||||
expect(FbFilter(maxProtein: 50).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when minCarbs is set', () {
|
||||
expect(FbFilter(minCarbs: 5).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when maxCarbs is set', () {
|
||||
expect(FbFilter(maxCarbs: 50).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when minFat is set', () {
|
||||
expect(FbFilter(minFat: 1).isActive, isTrue);
|
||||
});
|
||||
|
||||
test('FbFilter.isActive is true when maxFat is set', () {
|
||||
expect(FbFilter(maxFat: 10).isActive, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Widget tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
testWidgets('shows empty-bank message when no entries exist', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.textContaining('Food bank is empty'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('lists entries from the merged bank', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Manual oat',
|
||||
kcal: 370,
|
||||
proteinG: 13,
|
||||
carbsG: 66,
|
||||
fatG: 7,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Manual oat'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('FAB opens add-entry dialog and saving adds to bank', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byType(FloatingActionButton));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Add to food bank'), findsOneWidget);
|
||||
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'Name'),
|
||||
'Test food',
|
||||
);
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'Kcal'),
|
||||
'200',
|
||||
);
|
||||
|
||||
await tester.tap(find.text('Save to bank'));
|
||||
await settle(tester);
|
||||
|
||||
// After saving, the screen reloads and shows the new entry.
|
||||
expect(find.text('Test food'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('dialog cancel does not save anything', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byType(FloatingActionButton));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.textContaining('Food bank is empty'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('dialog save with empty name does nothing', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byType(FloatingActionButton));
|
||||
await settle(tester);
|
||||
|
||||
// Tap save without entering a name.
|
||||
await tester.tap(find.text('Save to bank'));
|
||||
await settle(tester);
|
||||
|
||||
// Dialog stays open; no entry saved.
|
||||
expect(find.text('Add to food bank'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter icon appears when entries exist', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Oat',
|
||||
kcal: 370,
|
||||
proteinG: 13,
|
||||
carbsG: 66,
|
||||
fatG: 7,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
expect(
|
||||
find.widgetWithIcon(IconButton, Icons.filter_list),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet opens and Apply filters results', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Oat',
|
||||
kcal: 370,
|
||||
proteinG: 13,
|
||||
carbsG: 66,
|
||||
fatG: 7,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Egg',
|
||||
kcal: 155,
|
||||
proteinG: 13,
|
||||
carbsG: 1,
|
||||
fatG: 11,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsOneWidget);
|
||||
|
||||
// Type in the only TextField in the sheet (the name search field).
|
||||
await tester.enterText(find.byType(TextField).first, 'Oat');
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
// Sheet is closed; only the matching entry is visible.
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
expect(find.text('Oat'), findsOneWidget);
|
||||
expect(find.text('Egg'), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet Clear all resets draft then Apply shows all', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Walnut',
|
||||
kcal: 654,
|
||||
proteinG: 15,
|
||||
carbsG: 14,
|
||||
fatG: 65,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Clear all'));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Walnut'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('record tile shows usage count for log-derived entries', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await FoodBankService.instance.rebuildAndPersist({
|
||||
'2026-06-22': [
|
||||
const FoodEntry(
|
||||
id: '1',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'rice',
|
||||
grams: 100,
|
||||
kcal: 130,
|
||||
proteinG: 3,
|
||||
carbsG: 28,
|
||||
fatG: 0.3,
|
||||
source: 'manual',
|
||||
),
|
||||
const FoodEntry(
|
||||
id: '2',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'rice',
|
||||
grams: 100,
|
||||
kcal: 130,
|
||||
proteinG: 3,
|
||||
carbsG: 28,
|
||||
fatG: 0.3,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// The rice entry was logged twice — the tile trailing shows ×2.
|
||||
expect(find.textContaining('×2'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet sort dropdown changes sort field', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
// Zero macros: no RangeSliders appear, sort section is immediately visible.
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'ZeroItem',
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsOneWidget);
|
||||
|
||||
// With no sliders rendered, 'Sort by' and its dropdown are immediately
|
||||
// visible — open the sort-field dropdown (shows 'Usage count' by default).
|
||||
await tester.tap(find.text('Usage count'));
|
||||
await settle(tester);
|
||||
|
||||
// Tap 'Name' in the dropdown overlay.
|
||||
await tester.tap(find.text('Name').last);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
expect(find.text('ZeroItem'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet RangeSlider onChanged callbacks fire', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
// Non-zero macros: all four RangeSliders appear in the filter sheet.
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'SliderFood',
|
||||
kcal: 200,
|
||||
proteinG: 10,
|
||||
carbsG: 25,
|
||||
fatG: 8,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
// Use getRect() + dragFrom() to bypass the _maybeViewOf ancestor-search
|
||||
// failure that tester.drag(finder, …) triggers inside modal overlays.
|
||||
|
||||
// Kcal slider covers lines 468-471.
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byType(RangeSlider).at(0)).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Protein slider covers lines 491-495.
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byType(RangeSlider).at(1)).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Carbs slider covers lines 515-518.
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byType(RangeSlider).at(2)).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Fat slider covers lines 538-541.
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byType(RangeSlider).at(3)).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet sort direction toggle fires onSortChanged', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
// Zero macros: no RangeSliders appear, sort section is immediately visible.
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'ZeroItem2',
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsOneWidget);
|
||||
|
||||
// Default sort is count-descending; the direction icon is arrow_downward.
|
||||
await tester.tap(find.byIcon(Icons.arrow_downward));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('ZeroItem2'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
195
app/test/screens/github_mirror_device_dialog_test.dart
Normal file
195
app/test/screens/github_mirror_device_dialog_test.dart
Normal file
@ -0,0 +1,195 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:url_launcher_platform_interface/link.dart';
|
||||
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
|
||||
|
||||
import '../fake_secure_storage.dart';
|
||||
|
||||
/// Stub launcher that records the URL instead of opening it, so the device
|
||||
/// dialog's "Open GitHub & copy code" can be exercised without a real
|
||||
/// platform channel.
|
||||
class _FakeUrlLauncher extends UrlLauncherPlatform
|
||||
with MockPlatformInterfaceMixin {
|
||||
String? launched;
|
||||
|
||||
@override
|
||||
final LinkDelegate? linkDelegate = null;
|
||||
|
||||
@override
|
||||
Future<bool> supportsMode(PreferredLaunchMode mode) async => true;
|
||||
|
||||
@override
|
||||
Future<bool> launchUrl(String url, LaunchOptions options) async {
|
||||
launched = url;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_github_');
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
installFakeSecureStorage();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
LogStorageService.resetForTesting();
|
||||
FoodBankService.resetForTesting();
|
||||
AppSettingsService.resetForTesting();
|
||||
BudgetHistoryService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
// GitHubMirrorScreen loads its settings via a fire-and-forget Future in
|
||||
// initState that Flutter's frame scheduler does not track -- same pitfall
|
||||
// as HistoryScreen/LogMealScreen.
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1400);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Drains the device flow's real `Future.delayed` poll (GitHubDeviceAuth
|
||||
/// injects no test delay, so under `runAsync` it is a genuine Timer, not
|
||||
/// the fake-clock one `tester.pump(duration)` advances) by interleaving
|
||||
/// real waits with frame pumps until [done] is true or [maxTries] is hit.
|
||||
Future<void> pumpUntil(
|
||||
WidgetTester tester,
|
||||
bool Function() done, {
|
||||
int maxTries = 200,
|
||||
}) async {
|
||||
for (var i = 0; i < maxTries && !done(); i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
await tester.pump();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Types [clientId] into the client-id field.
|
||||
Future<void> enterClientId(WidgetTester tester, String clientId) async {
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'OAuth App client id'),
|
||||
clientId,
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('device flow happy path saves the token and syncs', (
|
||||
tester,
|
||||
) async {
|
||||
final mock = MockClient((req) async {
|
||||
if (req.url.path.contains('device/code')) {
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'device_code': 'dev123',
|
||||
'user_code': 'WXYZ-1234',
|
||||
'verification_uri': 'https://github.com/login/device',
|
||||
'interval': 0,
|
||||
'expires_in': 900,
|
||||
}),
|
||||
200,
|
||||
);
|
||||
}
|
||||
if (req.url.path.contains('login/oauth/access_token')) {
|
||||
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
||||
}
|
||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||
// A bare `/repos/<owner>/<repo>` GET is crdt_sync's GitHubClient
|
||||
// probing whether the repo itself exists (vs. a content path just
|
||||
// being unused) -- must succeed so an empty repo isn't mistaken for
|
||||
// a missing one.
|
||||
if (req.method == 'GET' && req.url.pathSegments.length == 3) {
|
||||
return http.Response('{}', 200);
|
||||
}
|
||||
return http.Response('', 404); // sync's pull-side list/read calls
|
||||
});
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
|
||||
);
|
||||
await settle(tester);
|
||||
await enterClientId(tester, 'cid');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => find.text('WXYZ-1234').evaluate().isNotEmpty,
|
||||
);
|
||||
expect(find.text('WXYZ-1234'), findsOneWidget);
|
||||
|
||||
// Let the dialog poll (interval 0) and resolve the token, then the
|
||||
// post-connect sync runs against the mock.
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => find.textContaining('Connected and synced').evaluate().isNotEmpty,
|
||||
);
|
||||
|
||||
expect(find.textContaining('Connected and synced'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
testWidgets(
|
||||
'device flow connects but surfaces a post-connect sync failure',
|
||||
(tester) async {
|
||||
final mock = MockClient((req) async {
|
||||
if (req.url.path.contains('device/code')) {
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'device_code': 'dev123',
|
||||
'user_code': 'WXYZ-1234',
|
||||
'verification_uri': 'https://github.com/login/device',
|
||||
'interval': 0,
|
||||
'expires_in': 900,
|
||||
}),
|
||||
200,
|
||||
);
|
||||
}
|
||||
if (req.url.path.contains('login/oauth/access_token')) {
|
||||
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
||||
}
|
||||
return http.Response('boom', 500); // the sync's repo calls fail
|
||||
});
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
|
||||
);
|
||||
await settle(tester);
|
||||
await enterClientId(tester, 'cid');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => find.textContaining('sync failed').evaluate().isNotEmpty,
|
||||
);
|
||||
|
||||
expect(find.textContaining('sync failed'), findsOneWidget);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
189
app/test/screens/github_mirror_device_flow_test.dart
Normal file
189
app/test/screens/github_mirror_device_flow_test.dart
Normal file
@ -0,0 +1,189 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:url_launcher_platform_interface/link.dart';
|
||||
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
|
||||
|
||||
import '../fake_secure_storage.dart';
|
||||
|
||||
/// Stub launcher that records the URL instead of opening it, so the device
|
||||
/// dialog's "Open GitHub & copy code" can be exercised without a real
|
||||
/// platform channel.
|
||||
class _FakeUrlLauncher extends UrlLauncherPlatform
|
||||
with MockPlatformInterfaceMixin {
|
||||
String? launched;
|
||||
|
||||
@override
|
||||
final LinkDelegate? linkDelegate = null;
|
||||
|
||||
@override
|
||||
Future<bool> supportsMode(PreferredLaunchMode mode) async => true;
|
||||
|
||||
@override
|
||||
Future<bool> launchUrl(String url, LaunchOptions options) async {
|
||||
launched = url;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_github_');
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
installFakeSecureStorage();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
LogStorageService.resetForTesting();
|
||||
FoodBankService.resetForTesting();
|
||||
AppSettingsService.resetForTesting();
|
||||
BudgetHistoryService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
// GitHubMirrorScreen loads its settings via a fire-and-forget Future in
|
||||
// initState that Flutter's frame scheduler does not track -- same pitfall
|
||||
// as HistoryScreen/LogMealScreen.
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1400);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Drains the device flow's real `Future.delayed` poll (GitHubDeviceAuth
|
||||
/// injects no test delay, so under `runAsync` it is a genuine Timer, not
|
||||
/// the fake-clock one `tester.pump(duration)` advances) by interleaving
|
||||
/// real waits with frame pumps until [done] is true or [maxTries] is hit.
|
||||
Future<void> pumpUntil(
|
||||
WidgetTester tester,
|
||||
bool Function() done, {
|
||||
int maxTries = 200,
|
||||
}) async {
|
||||
for (var i = 0; i < maxTries && !done(); i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
await tester.pump();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Types [clientId] into the client-id field.
|
||||
Future<void> enterClientId(WidgetTester tester, String clientId) async {
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'OAuth App client id'),
|
||||
clientId,
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('Connect GitHub without a client id opens setup guidance', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: GitHubMirrorScreen()));
|
||||
await settle(tester);
|
||||
await enterClientId(tester, '');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('One-time GitHub setup needed'), findsOneWidget);
|
||||
expect(find.widgetWithText(TextField, 'Client ID'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
testWidgets('cancelling the client id setup dialog aborts the connect', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: GitHubMirrorScreen()));
|
||||
await settle(tester);
|
||||
await enterClientId(tester, '');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await settle(tester);
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('One-time GitHub setup needed'), findsNothing);
|
||||
});
|
||||
});
|
||||
testWidgets(
|
||||
'entering a client id in the setup dialog saves it and proceeds',
|
||||
(tester) async {
|
||||
final mock = MockClient((_) async => http.Response('nope', 422));
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
|
||||
);
|
||||
await settle(tester);
|
||||
await enterClientId(tester, '');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await settle(tester);
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'Client ID'),
|
||||
'cid',
|
||||
);
|
||||
await tester.tap(find.text('Continue'));
|
||||
await settle(tester);
|
||||
|
||||
expect(
|
||||
find.textContaining('Could not start device flow'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.widgetWithText(TextField, 'OAuth App client id'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
(tester.widget(
|
||||
find.widgetWithText(TextField, 'OAuth App client id'),
|
||||
)
|
||||
as TextField)
|
||||
.controller!
|
||||
.text,
|
||||
'cid',
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
testWidgets('device flow failure to start shows a message', (tester) async {
|
||||
final mock = MockClient((_) async => http.Response('nope', 422));
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
|
||||
);
|
||||
await settle(tester);
|
||||
await enterClientId(tester, 'cid');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await settle(tester);
|
||||
|
||||
expect(
|
||||
find.textContaining('Could not start device flow'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
169
app/test/screens/github_mirror_device_poll_test.dart
Normal file
169
app/test/screens/github_mirror_device_poll_test.dart
Normal file
@ -0,0 +1,169 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:url_launcher_platform_interface/link.dart';
|
||||
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
|
||||
|
||||
import '../fake_secure_storage.dart';
|
||||
|
||||
/// Stub launcher that records the URL instead of opening it, so the device
|
||||
/// dialog's "Open GitHub & copy code" can be exercised without a real
|
||||
/// platform channel.
|
||||
class _FakeUrlLauncher extends UrlLauncherPlatform
|
||||
with MockPlatformInterfaceMixin {
|
||||
String? launched;
|
||||
|
||||
@override
|
||||
final LinkDelegate? linkDelegate = null;
|
||||
|
||||
@override
|
||||
Future<bool> supportsMode(PreferredLaunchMode mode) async => true;
|
||||
|
||||
@override
|
||||
Future<bool> launchUrl(String url, LaunchOptions options) async {
|
||||
launched = url;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_github_');
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
installFakeSecureStorage();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
LogStorageService.resetForTesting();
|
||||
FoodBankService.resetForTesting();
|
||||
AppSettingsService.resetForTesting();
|
||||
BudgetHistoryService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
// GitHubMirrorScreen loads its settings via a fire-and-forget Future in
|
||||
// initState that Flutter's frame scheduler does not track -- same pitfall
|
||||
// as HistoryScreen/LogMealScreen.
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1400);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Drains the device flow's real `Future.delayed` poll (GitHubDeviceAuth
|
||||
/// injects no test delay, so under `runAsync` it is a genuine Timer, not
|
||||
/// the fake-clock one `tester.pump(duration)` advances) by interleaving
|
||||
/// real waits with frame pumps until [done] is true or [maxTries] is hit.
|
||||
Future<void> pumpUntil(
|
||||
WidgetTester tester,
|
||||
bool Function() done, {
|
||||
int maxTries = 200,
|
||||
}) async {
|
||||
for (var i = 0; i < maxTries && !done(); i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
await tester.pump();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Types [clientId] into the client-id field.
|
||||
Future<void> enterClientId(WidgetTester tester, String clientId) async {
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'OAuth App client id'),
|
||||
clientId,
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('device dialog: failed poll shows the error and Open launches', (
|
||||
tester,
|
||||
) async {
|
||||
final launcher = _FakeUrlLauncher();
|
||||
UrlLauncherPlatform.instance = launcher;
|
||||
|
||||
// The dialog's Open button copies the code to the clipboard first;
|
||||
// there's no clipboard plugin in the test host, so stub the channel.
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
(call) async => null,
|
||||
);
|
||||
addTearDown(
|
||||
() => messenger.setMockMethodCallHandler(SystemChannels.platform, null),
|
||||
);
|
||||
|
||||
final mock = MockClient((req) async {
|
||||
if (req.url.path.contains('device/code')) {
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'device_code': 'dev123',
|
||||
'user_code': 'WXYZ-1234',
|
||||
'verification_uri': 'https://github.com/login/device',
|
||||
'interval': 0,
|
||||
'expires_in': 900,
|
||||
}),
|
||||
200,
|
||||
);
|
||||
}
|
||||
return http.Response(
|
||||
jsonEncode({'error': 'access_denied', 'error_description': 'no'}),
|
||||
200,
|
||||
);
|
||||
});
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
|
||||
);
|
||||
await settle(tester);
|
||||
await enterClientId(tester, 'cid');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => find.text('WXYZ-1234').evaluate().isNotEmpty,
|
||||
);
|
||||
expect(find.text('WXYZ-1234'), findsOneWidget);
|
||||
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => find.textContaining('access_denied').evaluate().isNotEmpty,
|
||||
);
|
||||
|
||||
expect(find.textContaining('access_denied'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Open GitHub & copy code'));
|
||||
await tester.pump();
|
||||
expect(launcher.launched, 'https://github.com/login/device');
|
||||
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await settle(tester);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -1,15 +1,13 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_health.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
@ -41,6 +39,7 @@ class _FakeUrlLauncher extends UrlLauncherPlatform
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
@ -90,6 +89,15 @@ void main() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Types [clientId] into the client-id field.
|
||||
Future<void> enterClientId(WidgetTester tester, String clientId) async {
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'OAuth App client id'),
|
||||
clientId,
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('shows the kuhyx/syncs defaults on a fresh install', (
|
||||
tester,
|
||||
) async {
|
||||
@ -101,7 +109,6 @@ void main() {
|
||||
expect(find.widgetWithText(TextField, 'syncs'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Save persists the entered token', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: GitHubMirrorScreen()));
|
||||
@ -117,7 +124,6 @@ void main() {
|
||||
expect(find.text('Saved.'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Test connection reports success', (tester) async {
|
||||
final mock = MockClient(
|
||||
(_) async => http.Response('{}', 200),
|
||||
@ -136,7 +142,6 @@ void main() {
|
||||
expect(find.text('GitHub connection OK.'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Test connection reports failure', (tester) async {
|
||||
final mock = MockClient((_) async => http.Response('', 403));
|
||||
await tester.runAsync(() async {
|
||||
@ -153,7 +158,6 @@ void main() {
|
||||
expect(find.text('GitHub connection failed.'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Sync now runs a sync tick and reports success', (
|
||||
tester,
|
||||
) async {
|
||||
@ -180,7 +184,6 @@ void main() {
|
||||
expect(find.text('Synced.'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Sync now clears a stored failure so the banner lifts', (
|
||||
tester,
|
||||
) async {
|
||||
@ -214,7 +217,6 @@ void main() {
|
||||
expect(status.isStalled, isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Test connection reports a network exception', (tester) async {
|
||||
final mock = MockClient((_) async => throw const FormatException('no net'));
|
||||
await tester.runAsync(() async {
|
||||
@ -231,7 +233,6 @@ void main() {
|
||||
expect(find.textContaining('GitHub connection failed:'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Sync now reports a GitHub error', (tester) async {
|
||||
final mock = MockClient((_) async => http.Response('boom', 500));
|
||||
await tester.runAsync(() async {
|
||||
@ -246,267 +247,4 @@ void main() {
|
||||
expect(find.textContaining('Sync failed:'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
/// Types [clientId] into the client-id field.
|
||||
Future<void> enterClientId(WidgetTester tester, String clientId) async {
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'OAuth App client id'),
|
||||
clientId,
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('Connect GitHub without a client id opens setup guidance', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: GitHubMirrorScreen()));
|
||||
await settle(tester);
|
||||
await enterClientId(tester, '');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('One-time GitHub setup needed'), findsOneWidget);
|
||||
expect(find.widgetWithText(TextField, 'Client ID'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('cancelling the client id setup dialog aborts the connect', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: GitHubMirrorScreen()));
|
||||
await settle(tester);
|
||||
await enterClientId(tester, '');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await settle(tester);
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('One-time GitHub setup needed'), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'entering a client id in the setup dialog saves it and proceeds',
|
||||
(tester) async {
|
||||
final mock = MockClient((_) async => http.Response('nope', 422));
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
|
||||
);
|
||||
await settle(tester);
|
||||
await enterClientId(tester, '');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await settle(tester);
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'Client ID'),
|
||||
'cid',
|
||||
);
|
||||
await tester.tap(find.text('Continue'));
|
||||
await settle(tester);
|
||||
|
||||
expect(
|
||||
find.textContaining('Could not start device flow'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.widgetWithText(TextField, 'OAuth App client id'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
(tester.widget(
|
||||
find.widgetWithText(TextField, 'OAuth App client id'),
|
||||
)
|
||||
as TextField)
|
||||
.controller!
|
||||
.text,
|
||||
'cid',
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('device flow failure to start shows a message', (tester) async {
|
||||
final mock = MockClient((_) async => http.Response('nope', 422));
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
|
||||
);
|
||||
await settle(tester);
|
||||
await enterClientId(tester, 'cid');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await settle(tester);
|
||||
|
||||
expect(
|
||||
find.textContaining('Could not start device flow'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('device flow happy path saves the token and syncs', (
|
||||
tester,
|
||||
) async {
|
||||
final mock = MockClient((req) async {
|
||||
if (req.url.path.contains('device/code')) {
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'device_code': 'dev123',
|
||||
'user_code': 'WXYZ-1234',
|
||||
'verification_uri': 'https://github.com/login/device',
|
||||
'interval': 0,
|
||||
'expires_in': 900,
|
||||
}),
|
||||
200,
|
||||
);
|
||||
}
|
||||
if (req.url.path.contains('login/oauth/access_token')) {
|
||||
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
||||
}
|
||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||
// A bare `/repos/<owner>/<repo>` GET is crdt_sync's GitHubClient
|
||||
// probing whether the repo itself exists (vs. a content path just
|
||||
// being unused) -- must succeed so an empty repo isn't mistaken for
|
||||
// a missing one.
|
||||
if (req.method == 'GET' && req.url.pathSegments.length == 3) {
|
||||
return http.Response('{}', 200);
|
||||
}
|
||||
return http.Response('', 404); // sync's pull-side list/read calls
|
||||
});
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
|
||||
);
|
||||
await settle(tester);
|
||||
await enterClientId(tester, 'cid');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => find.text('WXYZ-1234').evaluate().isNotEmpty,
|
||||
);
|
||||
expect(find.text('WXYZ-1234'), findsOneWidget);
|
||||
|
||||
// Let the dialog poll (interval 0) and resolve the token, then the
|
||||
// post-connect sync runs against the mock.
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => find.textContaining('Connected and synced').evaluate().isNotEmpty,
|
||||
);
|
||||
|
||||
expect(find.textContaining('Connected and synced'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'device flow connects but surfaces a post-connect sync failure',
|
||||
(tester) async {
|
||||
final mock = MockClient((req) async {
|
||||
if (req.url.path.contains('device/code')) {
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'device_code': 'dev123',
|
||||
'user_code': 'WXYZ-1234',
|
||||
'verification_uri': 'https://github.com/login/device',
|
||||
'interval': 0,
|
||||
'expires_in': 900,
|
||||
}),
|
||||
200,
|
||||
);
|
||||
}
|
||||
if (req.url.path.contains('login/oauth/access_token')) {
|
||||
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
||||
}
|
||||
return http.Response('boom', 500); // the sync's repo calls fail
|
||||
});
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
|
||||
);
|
||||
await settle(tester);
|
||||
await enterClientId(tester, 'cid');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => find.textContaining('sync failed').evaluate().isNotEmpty,
|
||||
);
|
||||
|
||||
expect(find.textContaining('sync failed'), findsOneWidget);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('device dialog: failed poll shows the error and Open launches', (
|
||||
tester,
|
||||
) async {
|
||||
final launcher = _FakeUrlLauncher();
|
||||
UrlLauncherPlatform.instance = launcher;
|
||||
|
||||
// The dialog's Open button copies the code to the clipboard first;
|
||||
// there's no clipboard plugin in the test host, so stub the channel.
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
(call) async => null,
|
||||
);
|
||||
addTearDown(
|
||||
() => messenger.setMockMethodCallHandler(SystemChannels.platform, null),
|
||||
);
|
||||
|
||||
final mock = MockClient((req) async {
|
||||
if (req.url.path.contains('device/code')) {
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'device_code': 'dev123',
|
||||
'user_code': 'WXYZ-1234',
|
||||
'verification_uri': 'https://github.com/login/device',
|
||||
'interval': 0,
|
||||
'expires_in': 900,
|
||||
}),
|
||||
200,
|
||||
);
|
||||
}
|
||||
return http.Response(
|
||||
jsonEncode({'error': 'access_denied', 'error_description': 'no'}),
|
||||
200,
|
||||
);
|
||||
});
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
|
||||
);
|
||||
await settle(tester);
|
||||
await enterClientId(tester, 'cid');
|
||||
|
||||
await tester.tap(find.text('Connect GitHub'));
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => find.text('WXYZ-1234').evaluate().isNotEmpty,
|
||||
);
|
||||
expect(find.text('WXYZ-1234'), findsOneWidget);
|
||||
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => find.textContaining('access_denied').evaluate().isNotEmpty,
|
||||
);
|
||||
|
||||
expect(find.textContaining('access_denied'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Open GitHub & copy code'));
|
||||
await tester.pump();
|
||||
expect(launcher.launched, 'https://github.com/login/device');
|
||||
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await settle(tester);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
222
app/test/screens/history/history_filter_criteria_test.dart
Normal file
222
app/test/screens/history/history_filter_criteria_test.dart
Normal file
@ -0,0 +1,222 @@
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_filter.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'history_test_support.dart';
|
||||
|
||||
void main() {
|
||||
useTempHistoryStores();
|
||||
group('applyHistoryFilter', () {
|
||||
final entries = [
|
||||
const FoodEntry(
|
||||
id: 'a',
|
||||
time: '2026-06-20T08:00:00+02:00',
|
||||
desc: 'Apple',
|
||||
grams: 100,
|
||||
kcal: 80,
|
||||
proteinG: 0.5,
|
||||
carbsG: 20,
|
||||
fatG: 0.3,
|
||||
source: 'manual',
|
||||
),
|
||||
const FoodEntry(
|
||||
id: 'b',
|
||||
time: '2026-06-21T12:00:00+02:00',
|
||||
desc: 'Banana smoothie',
|
||||
grams: 250,
|
||||
kcal: 200,
|
||||
proteinG: 3,
|
||||
carbsG: 40,
|
||||
fatG: 1,
|
||||
source: 'food bank',
|
||||
),
|
||||
const FoodEntry(
|
||||
id: 'c',
|
||||
time: '2026-06-22T20:00:00+02:00',
|
||||
desc: 'Chicken breast',
|
||||
grams: 150,
|
||||
kcal: 230,
|
||||
proteinG: 45,
|
||||
carbsG: 0,
|
||||
fatG: 5,
|
||||
source: 'meal',
|
||||
),
|
||||
];
|
||||
|
||||
test('no filter returns all entries sorted by date descending', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(),
|
||||
HistorySortField.date,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((e) => e.id), ['c', 'b', 'a']);
|
||||
});
|
||||
|
||||
test('nameQuery filters by case-insensitive substring', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(nameQuery: 'an'),
|
||||
HistorySortField.date,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((e) => e.id), ['b']); // 'Banana smoothie'
|
||||
});
|
||||
|
||||
test('minKcal and maxKcal filter by kcal range', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(minKcal: 100, maxKcal: 210),
|
||||
HistorySortField.date,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((e) => e.id), ['b']); // 200 kcal
|
||||
});
|
||||
|
||||
test('minProtein filters by protein', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(minProtein: 10),
|
||||
HistorySortField.date,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((e) => e.id), ['c']); // 45g protein
|
||||
});
|
||||
|
||||
test('maxCarbs filters by carbs', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(maxCarbs: 5),
|
||||
HistorySortField.date,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((e) => e.id), ['c']); // 0 carbs
|
||||
});
|
||||
|
||||
test('minFat and maxFat filter by fat', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(minFat: 0.4, maxFat: 2),
|
||||
HistorySortField.date,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((e) => e.id), ['b']); // fat=1
|
||||
});
|
||||
|
||||
test('source filter keeps only matching source', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(source: 'meal'),
|
||||
HistorySortField.date,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((e) => e.id), ['c']);
|
||||
});
|
||||
|
||||
test('dateRange filter includes only entries within range', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(
|
||||
dateRange: DateTimeRange(
|
||||
start: DateTime(2026, 6, 21),
|
||||
end: DateTime(2026, 6, 21),
|
||||
),
|
||||
),
|
||||
HistorySortField.date,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.map((e) => e.id), ['b']);
|
||||
});
|
||||
|
||||
test('sort ascending by kcal', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(),
|
||||
HistorySortField.kcal,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.map((e) => e.id), ['a', 'b', 'c']);
|
||||
});
|
||||
|
||||
test('sort descending by protein', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(),
|
||||
HistorySortField.protein,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.first.id, 'c'); // 45g
|
||||
});
|
||||
|
||||
test('sort by description ascending', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(),
|
||||
HistorySortField.description,
|
||||
ascending: true,
|
||||
);
|
||||
// Apple, Banana smoothie, Chicken breast
|
||||
expect(result.map((e) => e.id), ['a', 'b', 'c']);
|
||||
});
|
||||
|
||||
test('sort by fat', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(),
|
||||
HistorySortField.fat,
|
||||
ascending: true,
|
||||
);
|
||||
expect(result.first.id, 'a'); // fat=0.3
|
||||
});
|
||||
|
||||
test('sort by carbs descending', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(),
|
||||
HistorySortField.carbs,
|
||||
ascending: false,
|
||||
);
|
||||
expect(result.first.id, 'b'); // 40g carbs
|
||||
});
|
||||
|
||||
test('HistoryFilter.isActive is false when nothing is set', () {
|
||||
expect(HistoryFilter().isActive, isFalse);
|
||||
});
|
||||
|
||||
test('HistoryFilter.isActive is true when nameQuery is set', () {
|
||||
expect(HistoryFilter(nameQuery: 'x').isActive, isTrue);
|
||||
});
|
||||
|
||||
test('HistoryFilter.isActive is true when source is set', () {
|
||||
expect(HistoryFilter(source: 'manual').isActive, isTrue);
|
||||
});
|
||||
|
||||
test('maxProtein filters by protein', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(maxProtein: 5),
|
||||
HistorySortField.date,
|
||||
ascending: false,
|
||||
);
|
||||
// Apple (0.5 g) and Banana (3 g) have protein ≤ 5 g.
|
||||
expect(result.map((e) => e.id), ['b', 'a']);
|
||||
});
|
||||
|
||||
test('minCarbs filters by carbs', () {
|
||||
final result = applyHistoryFilter(
|
||||
entries,
|
||||
HistoryFilter(minCarbs: 15),
|
||||
HistorySortField.date,
|
||||
ascending: false,
|
||||
);
|
||||
// Banana (40 g) and Apple (20 g) have carbs ≥ 15 g.
|
||||
expect(result.map((e) => e.id), ['b', 'a']);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Widget-level — day grouping and filter badge
|
||||
// ---------------------------------------------------------------------------
|
||||
}
|
||||
44
app/test/screens/history/history_filter_range_test.dart
Normal file
44
app/test/screens/history/history_filter_range_test.dart
Normal file
@ -0,0 +1,44 @@
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'history_test_support.dart';
|
||||
|
||||
void main() {
|
||||
useTempHistoryStores();
|
||||
testWidgets(
|
||||
'_formatDay falls back to raw key for an unparsable date (line 245)',
|
||||
(tester) async {
|
||||
await tester.runAsync(() async {
|
||||
// The day key is e.time.substring(0, 10). Writing an entry whose
|
||||
// `time` field can't be parsed by DateTime.parse exercises the
|
||||
// `on Exception` fallback in _formatDay (line 245), which returns the
|
||||
// raw key unchanged. 'NOT-A-DATE' is exactly 10 chars so substring
|
||||
// doesn't truncate it.
|
||||
await LogStorageService.instance.writeLog({
|
||||
'NOT-A-DATE': [
|
||||
const FoodEntry(
|
||||
id: 'bad1',
|
||||
time: 'NOT-A-DATE',
|
||||
desc: 'bad date entry',
|
||||
grams: 100,
|
||||
kcal: 100,
|
||||
proteinG: 5,
|
||||
carbsG: 10,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// The raw key is shown as the day header when formatting fails.
|
||||
expect(find.text('NOT-A-DATE'), findsOneWidget);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
191
app/test/screens/history/history_filter_sheet_test.dart
Normal file
191
app/test/screens/history/history_filter_sheet_test.dart
Normal file
@ -0,0 +1,191 @@
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'history_test_support.dart';
|
||||
|
||||
void main() {
|
||||
useTempHistoryStores();
|
||||
testWidgets('filter sheet Clear all resets draft then Apply shows all', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [
|
||||
const FoodEntry(
|
||||
id: 'a',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'toast',
|
||||
grams: 100,
|
||||
kcal: 200,
|
||||
proteinG: 7,
|
||||
carbsG: 35,
|
||||
fatG: 3,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Clear all'));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('toast'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet sort direction toggle fires onSortChanged', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
// Zero macros: no RangeSliders render, so the sort section is
|
||||
// immediately visible.
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-20': [
|
||||
const FoodEntry(
|
||||
id: 'sd1',
|
||||
time: '2026-06-20T09:00:00+02:00',
|
||||
desc: 'porridge',
|
||||
grams: 200,
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsOneWidget);
|
||||
|
||||
// The sort section is ~8px below the fold even with zero macros — scroll
|
||||
// it into view before tapping the direction button.
|
||||
await tester.drag(find.byType(ListView).last, const Offset(0, -120));
|
||||
await settle(tester);
|
||||
|
||||
// Default sort is date-descending; direction icon is arrow_downward.
|
||||
await tester.tap(find.byIcon(Icons.arrow_downward));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
expect(find.textContaining('porridge'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet sort field dropdown changes sort field', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
// Zero macros: no RangeSliders render, so the sort section is
|
||||
// immediately visible.
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-21': [
|
||||
const FoodEntry(
|
||||
id: 'sf1',
|
||||
time: '2026-06-21T12:00:00+02:00',
|
||||
desc: 'chicken',
|
||||
grams: 150,
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
// Scroll just enough to make the sort section visible.
|
||||
await tester.drag(find.byType(ListView).last, const Offset(0, -120));
|
||||
await settle(tester);
|
||||
|
||||
// Open the sort dropdown (shows 'Date' by default).
|
||||
await tester.tap(find.text('Date'));
|
||||
await settle(tester);
|
||||
|
||||
// Select 'Kcal' from the dropdown overlay.
|
||||
await tester.tap(find.text('Kcal').last);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
expect(find.textContaining('chicken'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet source chip filters by source', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
// Zero macros: no sliders, source chips appear right after date button.
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-23': [
|
||||
const FoodEntry(
|
||||
id: 'src1',
|
||||
time: '2026-06-23T08:00:00+02:00',
|
||||
desc: 'manual meal',
|
||||
grams: 100,
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
source: 'manual',
|
||||
),
|
||||
const FoodEntry(
|
||||
id: 'src2',
|
||||
time: '2026-06-23T12:00:00+02:00',
|
||||
desc: 'bank meal',
|
||||
grams: 100,
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
source: 'food bank',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.widgetWithText(FilterChip, 'manual'));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
expect(find.textContaining('manual meal'), findsOneWidget);
|
||||
expect(find.textContaining('bank meal'), findsNothing);
|
||||
});
|
||||
});
|
||||
}
|
||||
203
app/test/screens/history/history_filter_sort_test.dart
Normal file
203
app/test/screens/history/history_filter_sort_test.dart
Normal file
@ -0,0 +1,203 @@
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'history_test_support.dart';
|
||||
|
||||
void main() {
|
||||
useTempHistoryStores();
|
||||
testWidgets('shows day headers with date and total kcal', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [
|
||||
const FoodEntry(
|
||||
id: 'a',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'breakfast',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 40,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
),
|
||||
const FoodEntry(
|
||||
id: 'b',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'lunch',
|
||||
grams: 200,
|
||||
kcal: 500,
|
||||
proteinG: 20,
|
||||
carbsG: 60,
|
||||
fatG: 10,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// Day header shows 800 kcal total (300 + 500) vs the 2200 goal.
|
||||
expect(find.textContaining('800 / 2200 kcal'), findsOneWidget);
|
||||
// Both entries appear as list tiles.
|
||||
expect(find.text('breakfast'), findsOneWidget);
|
||||
expect(find.text('lunch'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter icon badge appears when filter is active', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [
|
||||
const FoodEntry(
|
||||
id: 'x',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'oat',
|
||||
grams: 100,
|
||||
kcal: 100,
|
||||
proteinG: 5,
|
||||
carbsG: 15,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// No filter active — the dot Container is absent.
|
||||
// We look for a small Container widget in the Stack above the
|
||||
// filter icon.
|
||||
expect(
|
||||
find.byWidgetPredicate((w) {
|
||||
if (w is Container) {
|
||||
final d = w.decoration;
|
||||
if (d is BoxDecoration) {
|
||||
return d.shape == BoxShape.circle && d.color != null;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}),
|
||||
findsNothing,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('shows "no entries match" when filter eliminates all results', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [
|
||||
const FoodEntry(
|
||||
id: 'x',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'oat',
|
||||
grams: 100,
|
||||
kcal: 100,
|
||||
proteinG: 5,
|
||||
carbsG: 15,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
// Build a custom wrapper that injects a filter through the state.
|
||||
// Easiest: extend HistoryScreen is not possible (private state), so we
|
||||
// test via the pure `applyHistoryFilter` function instead, which is
|
||||
// already covered above. This test verifies the "no match" empty-state
|
||||
// message path through the widget.
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// Verify the normal path renders the entry.
|
||||
expect(find.text('oat'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet opens and renders search field', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [
|
||||
const FoodEntry(
|
||||
id: 'a',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'oat',
|
||||
grams: 100,
|
||||
kcal: 100,
|
||||
proteinG: 5,
|
||||
carbsG: 15,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet Apply filters results and closes sheet', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [
|
||||
const FoodEntry(
|
||||
id: 'a',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'oat porridge',
|
||||
grams: 100,
|
||||
kcal: 100,
|
||||
proteinG: 5,
|
||||
carbsG: 15,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
),
|
||||
const FoodEntry(
|
||||
id: 'b',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'chicken breast',
|
||||
grams: 150,
|
||||
kcal: 250,
|
||||
proteinG: 40,
|
||||
carbsG: 0,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
// Type in the search field (first TextField in the sheet).
|
||||
await tester.enterText(find.byType(TextField).first, 'oat');
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
// Sheet is closed; only the matching entry is visible.
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
expect(find.text('oat porridge'), findsOneWidget);
|
||||
expect(find.text('chicken breast'), findsNothing);
|
||||
});
|
||||
});
|
||||
}
|
||||
196
app/test/screens/history/history_filter_source_test.dart
Normal file
196
app/test/screens/history/history_filter_source_test.dart
Normal file
@ -0,0 +1,196 @@
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'history_test_support.dart';
|
||||
|
||||
void main() {
|
||||
useTempHistoryStores();
|
||||
testWidgets('filter sheet source All chip fires onSelected callback', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-25': [
|
||||
const FoodEntry(
|
||||
id: 'sa1',
|
||||
time: '2026-06-25T08:00:00+02:00',
|
||||
desc: 'all source entry',
|
||||
grams: 100,
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
// Tap 'manual' to set a source filter, then 'All' to reset it.
|
||||
// Tapping 'All' when source is not null covers lines 798-800.
|
||||
await tester.tap(find.widgetWithText(FilterChip, 'manual'));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.widgetWithText(FilterChip, 'All'));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
expect(find.textContaining('all source entry'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('filter sheet RangeSlider onChanged callbacks fire', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
// Non-zero macros: all four RangeSliders appear in the filter sheet.
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-26': [
|
||||
const FoodEntry(
|
||||
id: 'rs1',
|
||||
time: '2026-06-26T08:00:00+02:00',
|
||||
desc: 'slider test entry',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 20,
|
||||
carbsG: 40,
|
||||
fatG: 10,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
// tester.drag(finder, offset) fails for RangeSliders inside a modal
|
||||
// overlay because its internal _maybeViewOf ancestor search cannot find
|
||||
// a View ancestor through the overlay's render subtree. Use
|
||||
// getRect()+dragFrom() instead (resolves via renderObjectOf, no
|
||||
// _maybeViewOf call).
|
||||
//
|
||||
// The filter sheet uses SingleChildScrollView+Column, so all four
|
||||
// sliders are always in the widget tree. ensureVisible() scrolls each
|
||||
// one into the viewport before getRect() is called.
|
||||
|
||||
// Kcal slider.
|
||||
await tester.ensureVisible(find.byKey(const Key('kcal-range-slider')));
|
||||
await settle(tester);
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byKey(const Key('kcal-range-slider'))).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Protein slider.
|
||||
await tester.ensureVisible(
|
||||
find.byKey(const Key('protein-range-slider')),
|
||||
);
|
||||
await settle(tester);
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byKey(const Key('protein-range-slider'))).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Carbs slider.
|
||||
await tester.ensureVisible(find.byKey(const Key('carbs-range-slider')));
|
||||
await settle(tester);
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byKey(const Key('carbs-range-slider'))).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
// Fat slider.
|
||||
await tester.ensureVisible(find.byKey(const Key('fat-range-slider')));
|
||||
await settle(tester);
|
||||
await tester.dragFrom(
|
||||
tester.getRect(find.byKey(const Key('fat-range-slider'))).center,
|
||||
const Offset(-30, 0),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Apply'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Filter & Sort'), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'date range picker selection shows _dateRangeLabel and Clear button '
|
||||
'(lines 232-234, 639-642)',
|
||||
(tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-26': [
|
||||
const FoodEntry(
|
||||
id: 'dr1',
|
||||
time: '2026-06-26T08:00:00+02:00',
|
||||
desc: 'range test',
|
||||
grams: 100,
|
||||
kcal: 200,
|
||||
proteinG: 10,
|
||||
carbsG: 20,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.filter_list));
|
||||
await settle(tester);
|
||||
|
||||
// Open date range picker.
|
||||
await tester.tap(find.widgetWithText(OutlinedButton, 'Any date'));
|
||||
await settle(tester);
|
||||
|
||||
// The picker opens on the current month (no `currentDate` override
|
||||
// and a null `initialDateRange`) and its `lastDate` is capped at
|
||||
// tomorrow, so days "10"+ aren't always selectable this early in a
|
||||
// month. Days "1" and "2" of the displayed month are always within
|
||||
// [firstDate, lastDate] regardless of which day it is when the test
|
||||
// runs.
|
||||
final now = DateTime.now();
|
||||
final expectedStart = DateTime(now.year, now.month);
|
||||
await tester.tap(find.text('1'));
|
||||
await settle(tester);
|
||||
await tester.tap(find.text('2'));
|
||||
await settle(tester);
|
||||
await tester.tap(find.text('Save'));
|
||||
await settle(tester);
|
||||
|
||||
// After a successful selection the filter button label shows the
|
||||
// formatted range via _dateRangeLabel (lines 232-234). Use a date-
|
||||
// specific prefix so the kcal slider's "0 – N kcal" label is excluded.
|
||||
expect(
|
||||
find.textContaining(expectedStart.toString().substring(0, 10)),
|
||||
findsOneWidget,
|
||||
);
|
||||
|
||||
// "Clear date range" is now visible — tap it to exercise lines 639-642.
|
||||
await tester.tap(find.text('Clear date range'));
|
||||
await settle(tester);
|
||||
expect(find.text('Any date'), findsOneWidget);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
191
app/test/screens/history/history_screen_test.dart
Normal file
191
app/test/screens/history/history_screen_test.dart
Normal file
@ -0,0 +1,191 @@
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_schedule.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'history_test_support.dart';
|
||||
|
||||
void main() {
|
||||
useTempHistoryStores();
|
||||
testWidgets('a day header shows the budget that applied on that day', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
// 2200 until 2026-06-15, 2000 from then on.
|
||||
await BudgetHistoryService.instance.applyMerged(const [
|
||||
BudgetEntry(
|
||||
effectiveFrom: kEpochDay,
|
||||
kcal: 2200,
|
||||
editedAt: '2026-01-01T00:00:00.000Z',
|
||||
),
|
||||
BudgetEntry(
|
||||
effectiveFrom: '2026-06-15',
|
||||
kcal: 2000,
|
||||
editedAt: '2026-06-15T00:00:00.000Z',
|
||||
),
|
||||
]);
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-01': [
|
||||
const FoodEntry(
|
||||
id: 'before',
|
||||
time: '2026-06-01T08:00:00+02:00',
|
||||
desc: 'before the cut',
|
||||
grams: 100,
|
||||
kcal: 2100,
|
||||
proteinG: 5,
|
||||
carbsG: 10,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
'2026-06-20': [
|
||||
const FoodEntry(
|
||||
id: 'after',
|
||||
time: '2026-06-20T08:00:00+02:00',
|
||||
desc: 'after the cut',
|
||||
grams: 100,
|
||||
kcal: 2100,
|
||||
proteinG: 5,
|
||||
carbsG: 10,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// Same 2100 kcal on both days, judged against different budgets --
|
||||
// lowering the budget must not repaint the earlier day.
|
||||
expect(find.text('2100 / 2200 kcal'), findsOneWidget);
|
||||
expect(find.text('2100 / 2000 kcal'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('shows a message when nothing has been logged', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('Nothing logged yet.'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('lists logged entries newest first, excluding tombstones', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-01': [
|
||||
const FoodEntry(
|
||||
id: 'old',
|
||||
time: '2026-06-01T08:00:00+02:00',
|
||||
desc: 'old breakfast',
|
||||
grams: 100,
|
||||
kcal: 100,
|
||||
proteinG: 5,
|
||||
carbsG: 10,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
'2026-06-22': [
|
||||
const FoodEntry(
|
||||
id: 'new',
|
||||
time: '2026-06-22T20:00:00+02:00',
|
||||
desc: 'new dinner',
|
||||
grams: 100,
|
||||
kcal: 200,
|
||||
proteinG: 10,
|
||||
carbsG: 20,
|
||||
fatG: 4,
|
||||
source: 'manual',
|
||||
),
|
||||
const FoodEntry(
|
||||
id: 'gone',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'undone lunch',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 1,
|
||||
carbsG: 1,
|
||||
fatG: 1,
|
||||
source: 'manual',
|
||||
deleted: true,
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('new dinner'), findsOneWidget);
|
||||
expect(find.text('old breakfast'), findsOneWidget);
|
||||
expect(find.text('undone lunch'), findsNothing);
|
||||
|
||||
final tiles = tester.widgetList<ListTile>(find.byType(ListTile)).toList();
|
||||
expect((tiles[0].title! as Text).data, 'new dinner');
|
||||
expect((tiles[1].title! as Text).data, 'old breakfast');
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'initialDateRange pre-filters to just that day, matching a Calendar '
|
||||
'screen day tap',
|
||||
(tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-01': [
|
||||
const FoodEntry(
|
||||
id: 'other-day',
|
||||
time: '2026-06-01T08:00:00+02:00',
|
||||
desc: 'other day breakfast',
|
||||
grams: 100,
|
||||
kcal: 100,
|
||||
proteinG: 5,
|
||||
carbsG: 10,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
'2026-06-22': [
|
||||
const FoodEntry(
|
||||
id: 'target-day',
|
||||
time: '2026-06-22T20:00:00+02:00',
|
||||
desc: 'target day dinner',
|
||||
grams: 100,
|
||||
kcal: 200,
|
||||
proteinG: 10,
|
||||
carbsG: 20,
|
||||
fatG: 4,
|
||||
source: 'manual',
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: HistoryScreen(
|
||||
initialDateRange: DateTimeRange(
|
||||
start: DateTime(2026, 6, 22),
|
||||
end: DateTime(2026, 6, 22),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
expect(find.text('target day dinner'), findsOneWidget);
|
||||
expect(find.text('other day breakfast'), findsNothing);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// applyHistoryFilter — pure function tests (no widget required)
|
||||
// ---------------------------------------------------------------------------
|
||||
}
|
||||
43
app/test/screens/history/history_test_support.dart
Normal file
43
app/test/screens/history/history_test_support.dart
Normal file
@ -0,0 +1,43 @@
|
||||
/// Shared setup for the history screen's split test files.
|
||||
///
|
||||
/// `history_screen_test.dart` was one 1017-line file; splitting it for the
|
||||
/// repo's 250-line cap left every part needing the same temp-dir isolation and
|
||||
/// the same settle helper, so they live here rather than being copy-pasted six
|
||||
/// times (which is how two copies drift and one silently stops isolating).
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
/// Point the log and budget-history services at a fresh temp dir per test, and
|
||||
/// tear it down afterwards. Call once at the top of a file's `main()`.
|
||||
void useTempHistoryStores() {
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_history_');
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
LogStorageService.resetForTesting();
|
||||
BudgetHistoryService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
}
|
||||
|
||||
/// Pump until the screen has finished its untracked initState load.
|
||||
///
|
||||
/// HistoryScreen loads via a fire-and-forget Future in initState that Flutter's
|
||||
/// frame scheduler does not track -- see log_meal_screen_test.dart for the same
|
||||
/// issue. Every test therefore runs inside runAsync() with a short real delay
|
||||
/// before settling.
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
184
app/test/screens/log_meal_screen_nav_test.dart
Normal file
184
app/test/screens/log_meal_screen_nav_test.dart
Normal file
@ -0,0 +1,184 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/screens/calendar_screen.dart';
|
||||
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||
import 'package:diet_guard_app/screens/settings_screen.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||
import 'package:url_launcher_platform_interface/link.dart';
|
||||
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
|
||||
|
||||
/// Stub launcher that records the URL instead of opening it -- same pattern
|
||||
/// as settings_screen_test.dart's fake, duplicated locally per this
|
||||
/// codebase's convention of small per-file fakes over a shared mock.
|
||||
class _FakeUrlLauncher extends UrlLauncherPlatform
|
||||
with MockPlatformInterfaceMixin {
|
||||
String? launched;
|
||||
|
||||
@override
|
||||
final LinkDelegate? linkDelegate = null;
|
||||
|
||||
@override
|
||||
Future<bool> supportsMode(PreferredLaunchMode mode) async => true;
|
||||
|
||||
@override
|
||||
Future<bool> launchUrl(String url, LaunchOptions options) async {
|
||||
launched = url;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a fixed [XFile] without touching any real platform channel.
|
||||
|
||||
/// A minimal valid 1x1 transparent PNG, so the thumbnail preview can decode
|
||||
/// it as a real image instead of throwing on bogus bytes.
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_screen_');
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
LogStorageService.resetForTesting();
|
||||
FoodBankService.resetForTesting();
|
||||
AppSettingsService.resetForTesting();
|
||||
BudgetHistoryService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
final logMealButton = find.byTooltip('Log meal');
|
||||
|
||||
// The screen's button handlers and description-field listener trigger
|
||||
// real `dart:io` file I/O as fire-and-forget Futures that Flutter's frame
|
||||
// scheduler does not track -- pumpAndSettle() can return *before* that
|
||||
// I/O (and its eventual setState) actually finishes. Every interaction
|
||||
// that can reach a service call therefore runs inside a single
|
||||
// tester.runAsync() per test, with a short real delay before each
|
||||
// pumpAndSettle() to let the in-flight I/O actually complete first.
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
testWidgets('the history icon navigates to HistoryScreen', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.history));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.byType(HistoryScreen), findsOneWidget);
|
||||
});
|
||||
});
|
||||
testWidgets('the calendar icon navigates to CalendarScreen', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.calendar_month));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.byType(CalendarScreen), findsOneWidget);
|
||||
});
|
||||
});
|
||||
testWidgets('the settings icon navigates to SettingsScreen', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// SettingsScreen briefly shows a perpetually-animating
|
||||
// CircularProgressIndicator while its settings load; pumpAndSettle
|
||||
// never settles against that, so pump explicit frames instead (see
|
||||
// history_screen_test.dart's note on the same pitfall).
|
||||
await tester.tap(find.byIcon(Icons.settings));
|
||||
await tester.pump();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byType(SettingsScreen), findsOneWidget);
|
||||
});
|
||||
});
|
||||
testWidgets('food bank icon navigates to FoodBankScreen', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.restaurant_menu));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.byType(FoodBankScreen), findsOneWidget);
|
||||
});
|
||||
});
|
||||
testWidgets('logged slot chip renders check-icon avatar', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
final now = DateTime.now();
|
||||
final dateKey =
|
||||
'${now.year.toString().padLeft(4, '0')}-'
|
||||
'${now.month.toString().padLeft(2, '0')}-'
|
||||
'${now.day.toString().padLeft(2, '0')}';
|
||||
final at8 = DateTime(now.year, now.month, now.day, 8);
|
||||
|
||||
await LogStorageService.instance.writeLog({
|
||||
dateKey: [
|
||||
FoodEntry(
|
||||
id: 'slot-seed',
|
||||
time: at8.toIso8601String(),
|
||||
desc: 'breakfast',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 40,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
slot: 8,
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// The 08:00 slot is logged — its ChoiceChip has a check-icon avatar.
|
||||
expect(find.byIcon(Icons.check), findsWidgets);
|
||||
});
|
||||
});
|
||||
testWidgets('tapping a slot chip selects it', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// Tap the 08:00 chip to force _selectedSlot = 8.
|
||||
await tester.tap(find.text('08:00'));
|
||||
await settle(tester);
|
||||
|
||||
final chip = tester.widget<ChoiceChip>(
|
||||
find.ancestor(
|
||||
of: find.text('08:00'),
|
||||
matching: find.byType(ChoiceChip),
|
||||
),
|
||||
);
|
||||
expect(chip.selected, isTrue);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -1,16 +1,10 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/models/nutrition.dart';
|
||||
import 'package:diet_guard_app/models/slot.dart';
|
||||
import 'package:diet_guard_app/screens/calendar_screen.dart';
|
||||
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
||||
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
import 'package:diet_guard_app/screens/settings_screen.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
||||
@ -46,6 +40,7 @@ class _FakeUrlLauncher extends UrlLauncherPlatform
|
||||
/// it as a real image instead of throwing on bogus bytes.
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
@ -80,50 +75,6 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
testWidgets('the history icon navigates to HistoryScreen', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.history));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.byType(HistoryScreen), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('the calendar icon navigates to CalendarScreen', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.calendar_month));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.byType(CalendarScreen), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('the settings icon navigates to SettingsScreen', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// SettingsScreen briefly shows a perpetually-animating
|
||||
// CircularProgressIndicator while its settings load; pumpAndSettle
|
||||
// never settles against that, so pump explicit frames instead (see
|
||||
// history_screen_test.dart's note on the same pitfall).
|
||||
await tester.tap(find.byIcon(Icons.settings));
|
||||
await tester.pump();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byType(SettingsScreen), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('logging a manually-typed meal persists it as source manual', (
|
||||
tester,
|
||||
) async {
|
||||
@ -149,7 +100,6 @@ void main() {
|
||||
expect(entries.single.kcal, 150);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('the progress card summarises today after a log', (
|
||||
tester,
|
||||
) async {
|
||||
@ -173,7 +123,6 @@ void main() {
|
||||
expect(find.text('2050 left'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('typing a new description dismisses the progress card', (
|
||||
tester,
|
||||
) async {
|
||||
@ -198,7 +147,6 @@ void main() {
|
||||
expect(find.byType(TodayProgressCard), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('refuses to log with an empty description', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
@ -212,7 +160,6 @@ void main() {
|
||||
expect(await LogStorageService.instance.todayEntries(), isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'per-grams and amount-eaten fields scale macros to the eaten portion',
|
||||
(tester) async {
|
||||
@ -243,7 +190,6 @@ void main() {
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'selecting a food-bank suggestion stamps source food bank, but '
|
||||
'editing a macro afterward reverts it to manual',
|
||||
@ -294,69 +240,4 @@ void main() {
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('food bank icon navigates to FoodBankScreen', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.restaurant_menu));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.byType(FoodBankScreen), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('logged slot chip renders check-icon avatar', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
final now = DateTime.now();
|
||||
final dateKey =
|
||||
'${now.year.toString().padLeft(4, '0')}-'
|
||||
'${now.month.toString().padLeft(2, '0')}-'
|
||||
'${now.day.toString().padLeft(2, '0')}';
|
||||
final at8 = DateTime(now.year, now.month, now.day, 8);
|
||||
|
||||
await LogStorageService.instance.writeLog({
|
||||
dateKey: [
|
||||
FoodEntry(
|
||||
id: 'slot-seed',
|
||||
time: at8.toIso8601String(),
|
||||
desc: 'breakfast',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 40,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
slot: 8,
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// The 08:00 slot is logged — its ChoiceChip has a check-icon avatar.
|
||||
expect(find.byIcon(Icons.check), findsWidgets);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('tapping a slot chip selects it', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
|
||||
await settle(tester);
|
||||
|
||||
// Tap the 08:00 chip to force _selectedSlot = 8.
|
||||
await tester.tap(find.text('08:00'));
|
||||
await settle(tester);
|
||||
|
||||
final chip = tester.widget<ChoiceChip>(
|
||||
find.ancestor(
|
||||
of: find.text('08:00'),
|
||||
matching: find.byType(ChoiceChip),
|
||||
),
|
||||
);
|
||||
expect(chip.selected, isTrue);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
134
app/test/screens/settings_screen_battery_test.dart
Normal file
134
app/test/screens/settings_screen_battery_test.dart
Normal file
@ -0,0 +1,134 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/screens/settings_screen.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../fake_secure_storage.dart';
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_settings_');
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
installFakeSecureStorage();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
LogStorageService.resetForTesting();
|
||||
FoodBankService.resetForTesting();
|
||||
AppSettingsService.resetForTesting();
|
||||
BudgetHistoryService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
// SettingsScreen loads its settings via real (non-fake-clocked) I/O
|
||||
// through FileDocumentStore, so every test body runs under
|
||||
// tester.runAsync() -- without it, those Futures never get a chance to
|
||||
// complete inside TestWidgetsFlutterBinding's fake-clocked zone, and
|
||||
// pumpAndSettle spins forever. Also grows the test viewport: the
|
||||
// Notifications section pushes earlier fields/buttons below the default
|
||||
// 800x600 fold, making them unreachable to tester.tap otherwise.
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1400);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
testWidgets('battery exemption button reports a granted status', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: SettingsScreen(
|
||||
requestBatteryExemption: () async => PermissionStatus.granted,
|
||||
),
|
||||
),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Disable battery optimization'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.textContaining('exemption granted'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
testWidgets('battery exemption button reports a denied status', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: SettingsScreen(
|
||||
requestBatteryExemption: () async => PermissionStatus.denied,
|
||||
),
|
||||
),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Disable battery optimization'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.textContaining('not granted'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
testWidgets('battery exemption defaults to the real permission_handler '
|
||||
'call, which fails predictably under test', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Disable battery optimization'));
|
||||
await settle(tester);
|
||||
|
||||
expect(
|
||||
find.textContaining('Could not request exemption'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
});
|
||||
testWidgets('battery exemption button surfaces a request failure', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: SettingsScreen(
|
||||
requestBatteryExemption: () async =>
|
||||
throw Exception('no permission service'),
|
||||
),
|
||||
),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Disable battery optimization'));
|
||||
await settle(tester);
|
||||
|
||||
expect(
|
||||
find.textContaining('Could not request exemption'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -16,6 +16,7 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../fake_secure_storage.dart';
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
@ -63,7 +64,6 @@ void main() {
|
||||
expect(find.widgetWithText(TextField, '1800'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('typing a kcal goal debounces the save', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
|
||||
@ -81,7 +81,6 @@ void main() {
|
||||
expect(AppSettingsService.dailyKcalGoal, 2100);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('an invalid kcal goal is not saved', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
final initial = AppSettingsService.dailyKcalGoal;
|
||||
@ -98,7 +97,6 @@ void main() {
|
||||
expect(AppSettingsService.dailyKcalGoal, initial);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('disposing mid-debounce still flushes the pending goal', (
|
||||
tester,
|
||||
) async {
|
||||
@ -122,7 +120,6 @@ void main() {
|
||||
expect(AppSettingsService.dailyKcalGoal, 1950);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('tapping Sync settings opens the shared SyncSettingsScreen', (
|
||||
tester,
|
||||
) async {
|
||||
@ -144,7 +141,6 @@ void main() {
|
||||
expect(find.text('Firebase sync'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'Sync settings wires storedAccount, not loadAccount, as the '
|
||||
'default accountLoader',
|
||||
@ -175,7 +171,6 @@ void main() {
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'tapping Advanced sync (GitHub) opens the local GitHubMirrorScreen',
|
||||
(tester) async {
|
||||
@ -191,84 +186,4 @@ void main() {
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('battery exemption button reports a granted status', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: SettingsScreen(
|
||||
requestBatteryExemption: () async => PermissionStatus.granted,
|
||||
),
|
||||
),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Disable battery optimization'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.textContaining('exemption granted'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('battery exemption button reports a denied status', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: SettingsScreen(
|
||||
requestBatteryExemption: () async => PermissionStatus.denied,
|
||||
),
|
||||
),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Disable battery optimization'));
|
||||
await settle(tester);
|
||||
|
||||
expect(find.textContaining('not granted'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('battery exemption defaults to the real permission_handler '
|
||||
'call, which fails predictably under test', (tester) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Disable battery optimization'));
|
||||
await settle(tester);
|
||||
|
||||
expect(
|
||||
find.textContaining('Could not request exemption'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('battery exemption button surfaces a request failure', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: SettingsScreen(
|
||||
requestBatteryExemption: () async =>
|
||||
throw Exception('no permission service'),
|
||||
),
|
||||
),
|
||||
);
|
||||
await settle(tester);
|
||||
|
||||
await tester.tap(find.text('Disable battery optimization'));
|
||||
await settle(tester);
|
||||
|
||||
expect(
|
||||
find.textContaining('Could not request exemption'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
182
app/test/services/app_settings_service_sync_test.dart
Normal file
182
app/test/services/app_settings_service_sync_test.dart
Normal file
@ -0,0 +1,182 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp(
|
||||
'diet_guard_settings_test_',
|
||||
);
|
||||
AppSettingsService.resetForTesting();
|
||||
BudgetHistoryService.resetForTesting();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
AppSettingsService.resetForTesting();
|
||||
BudgetHistoryService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
group('applySyncedBudget', () {
|
||||
test(
|
||||
'persists the given value and updatedAt verbatim, not "now"',
|
||||
() async {
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
final winningEdit = DateTime.utc(2020);
|
||||
|
||||
await AppSettingsService.instance.applySyncedBudget(
|
||||
1700,
|
||||
updatedAt: winningEdit,
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 1700);
|
||||
expect(AppSettingsService.dailyKcalGoalUpdatedAt, winningEdit);
|
||||
|
||||
final raw = await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).readAsString();
|
||||
final data = jsonDecode(raw) as Map;
|
||||
expect(data['daily_kcal_goal'], 1700);
|
||||
expect(
|
||||
data['daily_kcal_goal_updated_at'],
|
||||
winningEdit.toIso8601String(),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('a null updatedAt is accepted and persisted as null', () async {
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
await AppSettingsService.instance.applySyncedBudget(1700);
|
||||
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
|
||||
});
|
||||
});
|
||||
group('initForTesting (_load paths)', () {
|
||||
test('loads daily_kcal_goal from an existing file', () async {
|
||||
await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).writeAsString(jsonEncode({'daily_kcal_goal': 1600}));
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 1600);
|
||||
});
|
||||
|
||||
test('keeps default 2200 when file does not exist', () async {
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
});
|
||||
|
||||
test('keeps default 2200 on unparsable JSON', () async {
|
||||
await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).writeAsString('not json at all');
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
});
|
||||
|
||||
test('keeps default 2200 when JSON root is not a Map', () async {
|
||||
await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).writeAsString(jsonEncode([1, 2, 3]));
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
});
|
||||
|
||||
test('keeps default 2200 when daily_kcal_goal is not an int', () async {
|
||||
await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).writeAsString(jsonEncode({'daily_kcal_goal': 'two thousand'}));
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
});
|
||||
|
||||
test('loads daily_kcal_goal_updated_at from an existing file', () async {
|
||||
await File('${tempDir.path}/app_settings.json').writeAsString(
|
||||
jsonEncode({
|
||||
'daily_kcal_goal': 1600,
|
||||
'daily_kcal_goal_updated_at': '2026-01-01T00:00:00.000Z',
|
||||
}),
|
||||
);
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(
|
||||
AppSettingsService.dailyKcalGoalUpdatedAt,
|
||||
DateTime.parse('2026-01-01T00:00:00.000Z'),
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'dailyKcalGoalUpdatedAt stays null when file has no such key',
|
||||
() async {
|
||||
await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).writeAsString(jsonEncode({'daily_kcal_goal': 1600}));
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'dailyKcalGoalUpdatedAt stays null when the field is not a string',
|
||||
() async {
|
||||
await File('${tempDir.path}/app_settings.json').writeAsString(
|
||||
jsonEncode({
|
||||
'daily_kcal_goal': 1600,
|
||||
'daily_kcal_goal_updated_at': 12345,
|
||||
}),
|
||||
);
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@ -7,6 +7,7 @@ import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
@ -29,7 +30,6 @@ void main() {
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
});
|
||||
});
|
||||
|
||||
group('resetForTesting', () {
|
||||
test('with testDir creates a working instance', () {
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
@ -50,7 +50,6 @@ void main() {
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
});
|
||||
});
|
||||
|
||||
group('init early-return', () {
|
||||
test('returns existing instance without re-initialising', () async {
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
@ -63,7 +62,6 @@ void main() {
|
||||
expect(identical(first, second), isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('saveDailyKcalGoal', () {
|
||||
test('updates in-memory value and persists to file', () async {
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
@ -161,161 +159,4 @@ void main() {
|
||||
expect(updatedAt.isAfter(after), isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
group('applySyncedBudget', () {
|
||||
test(
|
||||
'persists the given value and updatedAt verbatim, not "now"',
|
||||
() async {
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
final winningEdit = DateTime.utc(2020);
|
||||
|
||||
await AppSettingsService.instance.applySyncedBudget(
|
||||
1700,
|
||||
updatedAt: winningEdit,
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 1700);
|
||||
expect(AppSettingsService.dailyKcalGoalUpdatedAt, winningEdit);
|
||||
|
||||
final raw = await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).readAsString();
|
||||
final data = jsonDecode(raw) as Map;
|
||||
expect(data['daily_kcal_goal'], 1700);
|
||||
expect(
|
||||
data['daily_kcal_goal_updated_at'],
|
||||
winningEdit.toIso8601String(),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('a null updatedAt is accepted and persisted as null', () async {
|
||||
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
await AppSettingsService.instance.applySyncedBudget(1700);
|
||||
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
|
||||
});
|
||||
});
|
||||
|
||||
group('initForTesting (_load paths)', () {
|
||||
test('loads daily_kcal_goal from an existing file', () async {
|
||||
await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).writeAsString(jsonEncode({'daily_kcal_goal': 1600}));
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 1600);
|
||||
});
|
||||
|
||||
test('keeps default 2200 when file does not exist', () async {
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
});
|
||||
|
||||
test('keeps default 2200 on unparsable JSON', () async {
|
||||
await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).writeAsString('not json at all');
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
});
|
||||
|
||||
test('keeps default 2200 when JSON root is not a Map', () async {
|
||||
await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).writeAsString(jsonEncode([1, 2, 3]));
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
});
|
||||
|
||||
test('keeps default 2200 when daily_kcal_goal is not an int', () async {
|
||||
await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).writeAsString(jsonEncode({'daily_kcal_goal': 'two thousand'}));
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
});
|
||||
|
||||
test('loads daily_kcal_goal_updated_at from an existing file', () async {
|
||||
await File('${tempDir.path}/app_settings.json').writeAsString(
|
||||
jsonEncode({
|
||||
'daily_kcal_goal': 1600,
|
||||
'daily_kcal_goal_updated_at': '2026-01-01T00:00:00.000Z',
|
||||
}),
|
||||
);
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(
|
||||
AppSettingsService.dailyKcalGoalUpdatedAt,
|
||||
DateTime.parse('2026-01-01T00:00:00.000Z'),
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'dailyKcalGoalUpdatedAt stays null when file has no such key',
|
||||
() async {
|
||||
await File(
|
||||
'${tempDir.path}/app_settings.json',
|
||||
).writeAsString(jsonEncode({'daily_kcal_goal': 1600}));
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'dailyKcalGoalUpdatedAt stays null when the field is not a string',
|
||||
() async {
|
||||
await File('${tempDir.path}/app_settings.json').writeAsString(
|
||||
jsonEncode({
|
||||
'daily_kcal_goal': 1600,
|
||||
'daily_kcal_goal_updated_at': 12345,
|
||||
}),
|
||||
);
|
||||
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
|
||||
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
176
app/test/services/average_service_periods_test.dart
Normal file
176
app/test/services/average_service_periods_test.dart
Normal file
@ -0,0 +1,176 @@
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/models/period_average.dart';
|
||||
import 'package:diet_guard_app/services/average_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_schedule.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
FoodEntry buildEntry({required double kcal, bool deleted = false}) => FoodEntry(
|
||||
time: '2026-01-01T12:00:00',
|
||||
desc: 'test',
|
||||
grams: 100,
|
||||
kcal: kcal,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
source: 'manual',
|
||||
deleted: deleted,
|
||||
);
|
||||
|
||||
BudgetSchedule flat(int budget) => BudgetSchedule(
|
||||
[BudgetEntry(effectiveFrom: kEpochDay, kcal: budget, editedAt: '')],
|
||||
fallback: budget,
|
||||
);
|
||||
|
||||
DayLog logOf(Map<String, double> kcalByDay) => {
|
||||
for (final e in kcalByDay.entries) e.key: [buildEntry(kcal: e.value)],
|
||||
};
|
||||
|
||||
void main() {
|
||||
|
||||
// Every other fixture in this file sits in a DST-free span, so none of them
|
||||
// can see the bug these cover: stepping a local DateTime by
|
||||
// Duration(days: 1) moves 23 or 25 hours across a DST boundary and lands on
|
||||
// the wrong wall-clock day. Under TZ=Europe/Warsaw (spring-forward
|
||||
// 2026-03-29) that made the phone and the PC report different averages for
|
||||
// the same log. Assertions are on the calendar day, never on the DateTime,
|
||||
// so they mean the same thing whatever zone the runner is in.
|
||||
|
||||
group('weeklyAverage', () {
|
||||
test('the current week stops at yesterday', () {
|
||||
final log = logOf({
|
||||
'2026-01-05': 3000,
|
||||
'2026-01-06': 3000,
|
||||
'2026-01-07': 3000,
|
||||
'2026-01-08': 100,
|
||||
});
|
||||
final result = weeklyAverage(
|
||||
log,
|
||||
schedule: flat(2000),
|
||||
today: DateTime(2026, 1, 8),
|
||||
);
|
||||
expect(result.avgKcal, 3000);
|
||||
expect(result.end, '2026-01-07');
|
||||
expect(result.band, AverageBand.veryOver);
|
||||
});
|
||||
|
||||
test('Monday has no complete days this week', () {
|
||||
final result = weeklyAverage(
|
||||
logOf({'2026-01-05': 3000}),
|
||||
schedule: flat(2000),
|
||||
today: DateTime(2026, 1, 5),
|
||||
);
|
||||
expect(result.elapsedDays, 0);
|
||||
expect(result.avgKcal, isNull);
|
||||
});
|
||||
|
||||
test('the previous week is whole', () {
|
||||
final result = weeklyAverage(
|
||||
logOf({'2026-01-05': 2100, '2026-01-11': 2100}),
|
||||
schedule: flat(2000),
|
||||
weeksAgo: 1,
|
||||
today: DateTime(2026, 1, 14),
|
||||
);
|
||||
expect(result.start, '2026-01-05');
|
||||
expect(result.end, '2026-01-11');
|
||||
expect(result.elapsedDays, 7);
|
||||
expect(result.band, AverageBand.slightlyOver);
|
||||
});
|
||||
});
|
||||
group('monthlyAverage', () {
|
||||
test('the current month stops at yesterday', () {
|
||||
final log = logOf({
|
||||
'2026-03-01': 1000,
|
||||
'2026-03-02': 1000,
|
||||
'2026-03-04': 9000,
|
||||
});
|
||||
final result = monthlyAverage(
|
||||
log,
|
||||
schedule: flat(2000),
|
||||
today: DateTime(2026, 3, 4),
|
||||
);
|
||||
expect(result.avgKcal, 1000);
|
||||
expect(result.end, '2026-03-03');
|
||||
expect(result.band, AverageBand.under);
|
||||
});
|
||||
|
||||
test('the first of the month has no complete days', () {
|
||||
final result = monthlyAverage(
|
||||
const {},
|
||||
schedule: flat(2000),
|
||||
today: DateTime(2026, 3),
|
||||
);
|
||||
expect(result.elapsedDays, 0);
|
||||
});
|
||||
|
||||
test('the previous month is whole', () {
|
||||
final result = monthlyAverage(
|
||||
logOf({'2026-02-10': 2500}),
|
||||
schedule: flat(2000),
|
||||
monthsAgo: 1,
|
||||
today: DateTime(2026, 3, 10),
|
||||
);
|
||||
expect(result.start, '2026-02-01');
|
||||
expect(result.end, '2026-02-28');
|
||||
expect(result.elapsedDays, 28);
|
||||
expect(result.band, AverageBand.veryOver);
|
||||
});
|
||||
});
|
||||
group('date arithmetic across a DST boundary', () {
|
||||
test('lastCompleteDay is yesterday even across spring-forward', () {
|
||||
final result = lastCompleteDay(DateTime(2026, 3, 30));
|
||||
expect(
|
||||
(result.year, result.month, result.day),
|
||||
(2026, 3, 29),
|
||||
reason: 'Duration-based arithmetic returned 2026-03-28 23:00 here',
|
||||
);
|
||||
});
|
||||
|
||||
test('a period spanning spring-forward keeps every day', () {
|
||||
final result = periodAverage(
|
||||
logOf({
|
||||
'2026-03-27': 2000,
|
||||
'2026-03-28': 2000,
|
||||
'2026-03-29': 2000,
|
||||
'2026-03-30': 2000,
|
||||
'2026-03-31': 2000,
|
||||
}),
|
||||
schedule: flat(2000),
|
||||
start: DateTime(2026, 3, 27),
|
||||
end: DateTime(2026, 3, 31),
|
||||
);
|
||||
expect(result.elapsedDays, 5);
|
||||
expect(
|
||||
result.loggedDays,
|
||||
5,
|
||||
reason: 'the day-stepping loop used to drop 2026-03-31',
|
||||
);
|
||||
});
|
||||
|
||||
test('the weeksAgo anchor stays in the right ISO week', () {
|
||||
// 2026-04-01 is a Wednesday; one week back is the Mon 03-23..Sun 03-29
|
||||
// week, the one containing the clock change.
|
||||
final result = weeklyAverage(
|
||||
logOf({'2026-03-23': 2000, '2026-03-29': 2000}),
|
||||
schedule: flat(2000),
|
||||
weeksAgo: 1,
|
||||
today: DateTime(2026, 4),
|
||||
);
|
||||
expect(result.start, '2026-03-23');
|
||||
expect(result.end, '2026-03-29');
|
||||
expect(result.loggedDays, 2);
|
||||
});
|
||||
|
||||
test('weekBounds spans Monday to Sunday across the change', () {
|
||||
final (monday, sunday) = weekBounds(DateTime(2026, 3, 29));
|
||||
expect((monday.year, monday.month, monday.day), (2026, 3, 23));
|
||||
expect((sunday.year, sunday.month, sunday.day), (2026, 3, 29));
|
||||
});
|
||||
|
||||
test('monthBounds ends on the real last day of a DST month', () {
|
||||
final (first, last) = monthBounds(DateTime(2026, 3, 15));
|
||||
expect((first.year, first.month, first.day), (2026, 3, 1));
|
||||
expect((last.year, last.month, last.day), (2026, 3, 31));
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -27,6 +27,15 @@ DayLog logOf(Map<String, double> kcalByDay) => {
|
||||
};
|
||||
|
||||
void main() {
|
||||
|
||||
// Every other fixture in this file sits in a DST-free span, so none of them
|
||||
// can see the bug these cover: stepping a local DateTime by
|
||||
// Duration(days: 1) moves 23 or 25 hours across a DST boundary and lands on
|
||||
// the wrong wall-clock day. Under TZ=Europe/Warsaw (spring-forward
|
||||
// 2026-03-29) that made the phone and the PC report different averages for
|
||||
// the same log. Assertions are on the calendar day, never on the DateTime,
|
||||
// so they mean the same thing whatever zone the runner is in.
|
||||
|
||||
group('bandFor', () {
|
||||
test('exactly at budget is under', () {
|
||||
expect(bandFor(2000, 2000), AverageBand.under);
|
||||
@ -41,7 +50,6 @@ void main() {
|
||||
expect(bandFor(2400.01, 2000), AverageBand.veryOver);
|
||||
});
|
||||
});
|
||||
|
||||
group('bandLabel', () {
|
||||
test('mirrors the Python labels exactly', () {
|
||||
expect(bandLabel(null), 'no data');
|
||||
@ -50,7 +58,6 @@ void main() {
|
||||
expect(bandLabel(AverageBand.veryOver), 'very over');
|
||||
});
|
||||
});
|
||||
|
||||
group('bounds', () {
|
||||
test('week starts on Monday', () {
|
||||
// 2026-01-07 is a Wednesday.
|
||||
@ -78,7 +85,6 @@ void main() {
|
||||
expect(shiftMonths(DateTime(2026, 1, 20), 1), DateTime(2025, 12));
|
||||
});
|
||||
});
|
||||
|
||||
group('periodAverage', () {
|
||||
test('averages over logged days only, not elapsed days', () {
|
||||
final log = logOf({
|
||||
@ -149,151 +155,4 @@ void main() {
|
||||
expect(result.band, AverageBand.under);
|
||||
});
|
||||
});
|
||||
|
||||
group('weeklyAverage', () {
|
||||
test('the current week stops at yesterday', () {
|
||||
final log = logOf({
|
||||
'2026-01-05': 3000,
|
||||
'2026-01-06': 3000,
|
||||
'2026-01-07': 3000,
|
||||
'2026-01-08': 100,
|
||||
});
|
||||
final result = weeklyAverage(
|
||||
log,
|
||||
schedule: flat(2000),
|
||||
today: DateTime(2026, 1, 8),
|
||||
);
|
||||
expect(result.avgKcal, 3000);
|
||||
expect(result.end, '2026-01-07');
|
||||
expect(result.band, AverageBand.veryOver);
|
||||
});
|
||||
|
||||
test('Monday has no complete days this week', () {
|
||||
final result = weeklyAverage(
|
||||
logOf({'2026-01-05': 3000}),
|
||||
schedule: flat(2000),
|
||||
today: DateTime(2026, 1, 5),
|
||||
);
|
||||
expect(result.elapsedDays, 0);
|
||||
expect(result.avgKcal, isNull);
|
||||
});
|
||||
|
||||
test('the previous week is whole', () {
|
||||
final result = weeklyAverage(
|
||||
logOf({'2026-01-05': 2100, '2026-01-11': 2100}),
|
||||
schedule: flat(2000),
|
||||
weeksAgo: 1,
|
||||
today: DateTime(2026, 1, 14),
|
||||
);
|
||||
expect(result.start, '2026-01-05');
|
||||
expect(result.end, '2026-01-11');
|
||||
expect(result.elapsedDays, 7);
|
||||
expect(result.band, AverageBand.slightlyOver);
|
||||
});
|
||||
});
|
||||
|
||||
group('monthlyAverage', () {
|
||||
test('the current month stops at yesterday', () {
|
||||
final log = logOf({
|
||||
'2026-03-01': 1000,
|
||||
'2026-03-02': 1000,
|
||||
'2026-03-04': 9000,
|
||||
});
|
||||
final result = monthlyAverage(
|
||||
log,
|
||||
schedule: flat(2000),
|
||||
today: DateTime(2026, 3, 4),
|
||||
);
|
||||
expect(result.avgKcal, 1000);
|
||||
expect(result.end, '2026-03-03');
|
||||
expect(result.band, AverageBand.under);
|
||||
});
|
||||
|
||||
test('the first of the month has no complete days', () {
|
||||
final result = monthlyAverage(
|
||||
const {},
|
||||
schedule: flat(2000),
|
||||
today: DateTime(2026, 3),
|
||||
);
|
||||
expect(result.elapsedDays, 0);
|
||||
});
|
||||
|
||||
test('the previous month is whole', () {
|
||||
final result = monthlyAverage(
|
||||
logOf({'2026-02-10': 2500}),
|
||||
schedule: flat(2000),
|
||||
monthsAgo: 1,
|
||||
today: DateTime(2026, 3, 10),
|
||||
);
|
||||
expect(result.start, '2026-02-01');
|
||||
expect(result.end, '2026-02-28');
|
||||
expect(result.elapsedDays, 28);
|
||||
expect(result.band, AverageBand.veryOver);
|
||||
});
|
||||
});
|
||||
|
||||
// Every other fixture in this file sits in a DST-free span, so none of them
|
||||
// can see the bug these cover: stepping a local DateTime by
|
||||
// Duration(days: 1) moves 23 or 25 hours across a DST boundary and lands on
|
||||
// the wrong wall-clock day. Under TZ=Europe/Warsaw (spring-forward
|
||||
// 2026-03-29) that made the phone and the PC report different averages for
|
||||
// the same log. Assertions are on the calendar day, never on the DateTime,
|
||||
// so they mean the same thing whatever zone the runner is in.
|
||||
group('date arithmetic across a DST boundary', () {
|
||||
test('lastCompleteDay is yesterday even across spring-forward', () {
|
||||
final result = lastCompleteDay(DateTime(2026, 3, 30));
|
||||
expect(
|
||||
(result.year, result.month, result.day),
|
||||
(2026, 3, 29),
|
||||
reason: 'Duration-based arithmetic returned 2026-03-28 23:00 here',
|
||||
);
|
||||
});
|
||||
|
||||
test('a period spanning spring-forward keeps every day', () {
|
||||
final result = periodAverage(
|
||||
logOf({
|
||||
'2026-03-27': 2000,
|
||||
'2026-03-28': 2000,
|
||||
'2026-03-29': 2000,
|
||||
'2026-03-30': 2000,
|
||||
'2026-03-31': 2000,
|
||||
}),
|
||||
schedule: flat(2000),
|
||||
start: DateTime(2026, 3, 27),
|
||||
end: DateTime(2026, 3, 31),
|
||||
);
|
||||
expect(result.elapsedDays, 5);
|
||||
expect(
|
||||
result.loggedDays,
|
||||
5,
|
||||
reason: 'the day-stepping loop used to drop 2026-03-31',
|
||||
);
|
||||
});
|
||||
|
||||
test('the weeksAgo anchor stays in the right ISO week', () {
|
||||
// 2026-04-01 is a Wednesday; one week back is the Mon 03-23..Sun 03-29
|
||||
// week, the one containing the clock change.
|
||||
final result = weeklyAverage(
|
||||
logOf({'2026-03-23': 2000, '2026-03-29': 2000}),
|
||||
schedule: flat(2000),
|
||||
weeksAgo: 1,
|
||||
today: DateTime(2026, 4),
|
||||
);
|
||||
expect(result.start, '2026-03-23');
|
||||
expect(result.end, '2026-03-29');
|
||||
expect(result.loggedDays, 2);
|
||||
});
|
||||
|
||||
test('weekBounds spans Monday to Sunday across the change', () {
|
||||
final (monday, sunday) = weekBounds(DateTime(2026, 3, 29));
|
||||
expect((monday.year, monday.month, monday.day), (2026, 3, 23));
|
||||
expect((sunday.year, sunday.month, sunday.day), (2026, 3, 29));
|
||||
});
|
||||
|
||||
test('monthBounds ends on the real last day of a DST month', () {
|
||||
final (first, last) = monthBounds(DateTime(2026, 3, 15));
|
||||
expect((first.year, first.month, first.day), (2026, 3, 1));
|
||||
expect((last.year, last.month, last.day), (2026, 3, 31));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
152
app/test/services/day_status_service_streaks_test.dart
Normal file
152
app/test/services/day_status_service_streaks_test.dart
Normal file
@ -0,0 +1,152 @@
|
||||
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/day_status_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
FoodEntry buildEntry({required double kcal, bool deleted = false}) => FoodEntry(
|
||||
time: '2026-01-01T12:00:00',
|
||||
desc: 'test',
|
||||
grams: 100,
|
||||
kcal: kcal,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
source: 'manual',
|
||||
deleted: deleted,
|
||||
);
|
||||
|
||||
FoodEntry buildMacroEntry({
|
||||
required double proteinG,
|
||||
required double carbsG,
|
||||
required double fatG,
|
||||
}) => FoodEntry(
|
||||
time: '2026-01-01T12:00:00',
|
||||
desc: 'test',
|
||||
grams: 100,
|
||||
kcal: 0,
|
||||
proteinG: proteinG,
|
||||
carbsG: carbsG,
|
||||
fatG: fatG,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
/// A schedule where one budget has applied since the beginning of time.
|
||||
BudgetSchedule flat(int budget) => BudgetSchedule(
|
||||
[const BudgetEntry(effectiveFrom: kEpochDay, kcal: 0, editedAt: '')]
|
||||
.map(
|
||||
(_) => BudgetEntry(
|
||||
effectiveFrom: kEpochDay,
|
||||
kcal: budget,
|
||||
editedAt: '1970-01-01T00:00:00.000Z',
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
fallback: budget,
|
||||
);
|
||||
|
||||
void main() {
|
||||
group('loggingStreak', () {
|
||||
test('empty map is zero', () {
|
||||
expect(loggingStreak({}, today: DateTime(2026, 1, 5)), 0);
|
||||
});
|
||||
|
||||
test('counts consecutive logged days including today', () {
|
||||
final sm = {
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-04': DayStatus.red,
|
||||
'2026-01-05': DayStatus.yellow,
|
||||
};
|
||||
expect(loggingStreak(sm, today: DateTime(2026, 1, 5)), 3);
|
||||
});
|
||||
|
||||
test('breaks on a gap', () {
|
||||
final sm = {
|
||||
'2026-01-01': DayStatus.green,
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-04': DayStatus.green,
|
||||
};
|
||||
expect(loggingStreak(sm, today: DateTime(2026, 1, 4)), 2);
|
||||
});
|
||||
|
||||
test('today not logged is not a break', () {
|
||||
final sm = {
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-04': DayStatus.yellow,
|
||||
};
|
||||
expect(loggingStreak(sm, today: DateTime(2026, 1, 5)), 2);
|
||||
});
|
||||
|
||||
test('yesterday not logged breaks streak even if today is', () {
|
||||
final sm = {
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-05': DayStatus.green,
|
||||
};
|
||||
expect(loggingStreak(sm, today: DateTime(2026, 1, 5)), 1);
|
||||
});
|
||||
});
|
||||
group('adherenceStreak', () {
|
||||
test('counts consecutive green and yellow', () {
|
||||
final sm = {
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-04': DayStatus.yellow,
|
||||
'2026-01-05': DayStatus.green,
|
||||
};
|
||||
expect(adherenceStreak(sm, today: DateTime(2026, 1, 5)), 3);
|
||||
});
|
||||
|
||||
test('red today breaks the streak immediately', () {
|
||||
final sm = {
|
||||
'2026-01-04': DayStatus.green,
|
||||
'2026-01-05': DayStatus.red,
|
||||
};
|
||||
expect(adherenceStreak(sm, today: DateTime(2026, 1, 5)), 0);
|
||||
});
|
||||
|
||||
test('not-logged today is not a break', () {
|
||||
final sm = {'2026-01-04': DayStatus.green};
|
||||
expect(adherenceStreak(sm, today: DateTime(2026, 1, 5)), 1);
|
||||
});
|
||||
|
||||
test('red in history breaks the streak', () {
|
||||
final sm = {
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-04': DayStatus.red,
|
||||
'2026-01-05': DayStatus.green,
|
||||
};
|
||||
expect(adherenceStreak(sm, today: DateTime(2026, 1, 5)), 1);
|
||||
});
|
||||
});
|
||||
group('yearToDateTally', () {
|
||||
test('counts logged and adherent days this year only', () {
|
||||
final sm = {
|
||||
'2026-01-01': DayStatus.green,
|
||||
'2026-01-02': DayStatus.red,
|
||||
'2026-01-03': DayStatus.notLogged,
|
||||
'2025-12-31': DayStatus.green,
|
||||
};
|
||||
final tally = yearToDateTally(sm, today: DateTime(2026, 1, 3));
|
||||
expect(tally.loggedDays, 2);
|
||||
expect(tally.elapsedDays, 3);
|
||||
expect(tally.adherentDays, 1);
|
||||
});
|
||||
|
||||
test('future day in map is excluded', () {
|
||||
final sm = {
|
||||
'2026-01-01': DayStatus.green,
|
||||
'2026-06-01': DayStatus.green,
|
||||
};
|
||||
final tally = yearToDateTally(sm, today: DateTime(2026));
|
||||
expect(tally.loggedDays, 1);
|
||||
expect(tally.elapsedDays, 1);
|
||||
expect(tally.adherentDays, 1);
|
||||
});
|
||||
|
||||
test('empty map', () {
|
||||
final tally = yearToDateTally({}, today: DateTime(2026, 3));
|
||||
expect(tally.loggedDays, 0);
|
||||
expect(tally.elapsedDays, 60);
|
||||
expect(tally.adherentDays, 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -68,7 +68,6 @@ void main() {
|
||||
expect(dayTotalKcal(log, '2026-01-01'), 100);
|
||||
});
|
||||
});
|
||||
|
||||
group('sumMacros', () {
|
||||
test('sums protein, carbs and fat across entries', () {
|
||||
final totals = sumMacros([
|
||||
@ -87,7 +86,6 @@ void main() {
|
||||
expect(totals.fatG, 0);
|
||||
});
|
||||
});
|
||||
|
||||
group('dayStatus', () {
|
||||
test('missing day is notLogged', () {
|
||||
final log = <String, List<FoodEntry>>{};
|
||||
@ -143,7 +141,6 @@ void main() {
|
||||
expect(dayStatus(log, '2026-01-01', 2000), DayStatus.red);
|
||||
});
|
||||
});
|
||||
|
||||
group('statusMap', () {
|
||||
test('maps every present day', () {
|
||||
final log = {
|
||||
@ -161,110 +158,4 @@ void main() {
|
||||
expect(statusMap(log, schedule: flat(2000)), <String, DayStatus>{});
|
||||
});
|
||||
});
|
||||
|
||||
group('loggingStreak', () {
|
||||
test('empty map is zero', () {
|
||||
expect(loggingStreak({}, today: DateTime(2026, 1, 5)), 0);
|
||||
});
|
||||
|
||||
test('counts consecutive logged days including today', () {
|
||||
final sm = {
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-04': DayStatus.red,
|
||||
'2026-01-05': DayStatus.yellow,
|
||||
};
|
||||
expect(loggingStreak(sm, today: DateTime(2026, 1, 5)), 3);
|
||||
});
|
||||
|
||||
test('breaks on a gap', () {
|
||||
final sm = {
|
||||
'2026-01-01': DayStatus.green,
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-04': DayStatus.green,
|
||||
};
|
||||
expect(loggingStreak(sm, today: DateTime(2026, 1, 4)), 2);
|
||||
});
|
||||
|
||||
test('today not logged is not a break', () {
|
||||
final sm = {
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-04': DayStatus.yellow,
|
||||
};
|
||||
expect(loggingStreak(sm, today: DateTime(2026, 1, 5)), 2);
|
||||
});
|
||||
|
||||
test('yesterday not logged breaks streak even if today is', () {
|
||||
final sm = {
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-05': DayStatus.green,
|
||||
};
|
||||
expect(loggingStreak(sm, today: DateTime(2026, 1, 5)), 1);
|
||||
});
|
||||
});
|
||||
|
||||
group('adherenceStreak', () {
|
||||
test('counts consecutive green and yellow', () {
|
||||
final sm = {
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-04': DayStatus.yellow,
|
||||
'2026-01-05': DayStatus.green,
|
||||
};
|
||||
expect(adherenceStreak(sm, today: DateTime(2026, 1, 5)), 3);
|
||||
});
|
||||
|
||||
test('red today breaks the streak immediately', () {
|
||||
final sm = {
|
||||
'2026-01-04': DayStatus.green,
|
||||
'2026-01-05': DayStatus.red,
|
||||
};
|
||||
expect(adherenceStreak(sm, today: DateTime(2026, 1, 5)), 0);
|
||||
});
|
||||
|
||||
test('not-logged today is not a break', () {
|
||||
final sm = {'2026-01-04': DayStatus.green};
|
||||
expect(adherenceStreak(sm, today: DateTime(2026, 1, 5)), 1);
|
||||
});
|
||||
|
||||
test('red in history breaks the streak', () {
|
||||
final sm = {
|
||||
'2026-01-03': DayStatus.green,
|
||||
'2026-01-04': DayStatus.red,
|
||||
'2026-01-05': DayStatus.green,
|
||||
};
|
||||
expect(adherenceStreak(sm, today: DateTime(2026, 1, 5)), 1);
|
||||
});
|
||||
});
|
||||
|
||||
group('yearToDateTally', () {
|
||||
test('counts logged and adherent days this year only', () {
|
||||
final sm = {
|
||||
'2026-01-01': DayStatus.green,
|
||||
'2026-01-02': DayStatus.red,
|
||||
'2026-01-03': DayStatus.notLogged,
|
||||
'2025-12-31': DayStatus.green,
|
||||
};
|
||||
final tally = yearToDateTally(sm, today: DateTime(2026, 1, 3));
|
||||
expect(tally.loggedDays, 2);
|
||||
expect(tally.elapsedDays, 3);
|
||||
expect(tally.adherentDays, 1);
|
||||
});
|
||||
|
||||
test('future day in map is excluded', () {
|
||||
final sm = {
|
||||
'2026-01-01': DayStatus.green,
|
||||
'2026-06-01': DayStatus.green,
|
||||
};
|
||||
final tally = yearToDateTally(sm, today: DateTime(2026));
|
||||
expect(tally.loggedDays, 1);
|
||||
expect(tally.elapsedDays, 1);
|
||||
expect(tally.adherentDays, 1);
|
||||
});
|
||||
|
||||
test('empty map', () {
|
||||
final tally = yearToDateTally({}, today: DateTime(2026, 3));
|
||||
expect(tally.loggedDays, 0);
|
||||
expect(tally.elapsedDays, 60);
|
||||
expect(tally.adherentDays, 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
245
app/test/services/foodbank_service_manual_test.dart
Normal file
245
app/test/services/foodbank_service_manual_test.dart
Normal file
@ -0,0 +1,245 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/models/meal_component.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
FoodEntry _entry({
|
||||
required String id,
|
||||
required String time,
|
||||
required String desc,
|
||||
double kcal = 100,
|
||||
List<MealComponent>? components,
|
||||
bool deleted = false,
|
||||
}) => FoodEntry(
|
||||
id: id,
|
||||
time: time,
|
||||
desc: desc,
|
||||
grams: 100,
|
||||
kcal: kcal,
|
||||
proteinG: 1,
|
||||
carbsG: 1,
|
||||
fatG: 1,
|
||||
source: components != null ? 'meal' : 'manual',
|
||||
components: components,
|
||||
deleted: deleted,
|
||||
);
|
||||
|
||||
void main() {
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Manual bank — addManualEntry / mergedEntries
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// IO error paths — FileSystemException and FormatException handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
group('FoodBankService manual bank', () {
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_manual_');
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
FoodBankService.resetForTesting();
|
||||
LogStorageService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
test('addManualEntry persists and mergedEntries returns it', () async {
|
||||
const record = FoodBankRecord(
|
||||
desc: 'Manual oat',
|
||||
kcal: 370,
|
||||
proteinG: 13,
|
||||
carbsG: 66,
|
||||
fatG: 7,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
);
|
||||
|
||||
await FoodBankService.instance.addManualEntry(record);
|
||||
final merged = await FoodBankService.instance.mergedEntries();
|
||||
|
||||
expect(merged.any((r) => r.desc == 'Manual oat'), isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'mergedEntries: log-derived entry wins over manual on collision',
|
||||
() async {
|
||||
// Seed log with 'oat' (count=1, kcal=100).
|
||||
final log = {
|
||||
'2026-06-22': [
|
||||
_entry(id: '1', time: '2026-06-22T08:00:00+02:00', desc: 'oat'),
|
||||
],
|
||||
};
|
||||
await FoodBankService.instance.rebuildAndPersist(log);
|
||||
|
||||
// Add manual entry with same normalized key but different kcal.
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'oat',
|
||||
kcal: 999,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
final merged = await FoodBankService.instance.mergedEntries();
|
||||
final oat = merged.firstWhere((r) => r.desc == 'oat');
|
||||
// Log-derived entry (kcal=100) should win over manual (kcal=999).
|
||||
expect(oat.kcal, 100);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'mergedEntries includes both log-derived and manual entries',
|
||||
() async {
|
||||
final log = {
|
||||
'2026-06-22': [
|
||||
_entry(
|
||||
id: '1',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'toast',
|
||||
),
|
||||
],
|
||||
};
|
||||
await FoodBankService.instance.rebuildAndPersist(log);
|
||||
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Quinoa',
|
||||
kcal: 370,
|
||||
proteinG: 14,
|
||||
carbsG: 64,
|
||||
fatG: 6,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
final merged = await FoodBankService.instance.mergedEntries();
|
||||
final descs = merged.map((r) => r.desc).toSet();
|
||||
expect(descs, containsAll(['toast', 'Quinoa']));
|
||||
},
|
||||
);
|
||||
|
||||
test('addManualEntry upserts by normalized key', () async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Oat',
|
||||
kcal: 370,
|
||||
proteinG: 13,
|
||||
carbsG: 66,
|
||||
fatG: 7,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
// Upsert same food with updated kcal.
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'oat',
|
||||
kcal: 400,
|
||||
proteinG: 14,
|
||||
carbsG: 68,
|
||||
fatG: 8,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
final merged = await FoodBankService.instance.mergedEntries();
|
||||
final oats = merged.where((r) => r.desc.toLowerCase() == 'oat').toList();
|
||||
expect(oats.length, 1);
|
||||
expect(oats.single.kcal, 400);
|
||||
});
|
||||
|
||||
test('search includes manual entries', () async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Rare ingredient',
|
||||
kcal: 50,
|
||||
proteinG: 1,
|
||||
carbsG: 10,
|
||||
fatG: 0.5,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
final results = await FoodBankService.instance.search('Rare');
|
||||
expect(results.any((r) => r.name == 'Rare ingredient'), isTrue);
|
||||
});
|
||||
});
|
||||
group('FoodBankService IO error paths', () {
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_err_');
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
FoodBankService.resetForTesting();
|
||||
LogStorageService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
test('readBank returns empty on invalid JSON (FormatException)', () async {
|
||||
await File(
|
||||
'${tempDir.path}/food_bank.json',
|
||||
).writeAsString('not valid json {{{');
|
||||
expect(await FoodBankService.instance.readBank(), isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'readBank returns empty when file is unreadable (FileSystemException)',
|
||||
() async {
|
||||
final bankPath = '${tempDir.path}/food_bank.json';
|
||||
await File(bankPath).writeAsString('{}');
|
||||
await Process.run('chmod', ['000', bankPath]);
|
||||
|
||||
expect(await FoodBankService.instance.readBank(), isEmpty);
|
||||
|
||||
await Process.run('chmod', ['644', bankPath]);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'mergedEntries handles invalid JSON in manual bank (FormatException)',
|
||||
() async {
|
||||
await File(
|
||||
'${tempDir.path}/food_bank_manual.json',
|
||||
).writeAsString('not valid json {{{');
|
||||
expect(await FoodBankService.instance.mergedEntries(), isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'mergedEntries handles unreadable manual bank (FileSystemException)',
|
||||
() async {
|
||||
final manualPath = '${tempDir.path}/food_bank_manual.json';
|
||||
await File(manualPath).writeAsString('{}');
|
||||
await Process.run('chmod', ['000', manualPath]);
|
||||
|
||||
expect(await FoodBankService.instance.mergedEntries(), isEmpty);
|
||||
|
||||
await Process.run('chmod', ['644', manualPath]);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@ -1,9 +1,8 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/models/meal_component.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
@ -30,6 +29,16 @@ FoodEntry _entry({
|
||||
);
|
||||
|
||||
void main() {
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Manual bank — addManualEntry / mergedEntries
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// IO error paths — FileSystemException and FormatException handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
group('FoodBankService.rebuild (pure)', () {
|
||||
test('upserts a single-food entry by normalized name', () {
|
||||
final log = {
|
||||
@ -49,7 +58,6 @@ void main() {
|
||||
id: '1',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'toast',
|
||||
kcal: 100,
|
||||
),
|
||||
_entry(
|
||||
id: '2',
|
||||
@ -78,7 +86,7 @@ void main() {
|
||||
expect(FoodBankService.rebuild(log), isEmpty);
|
||||
});
|
||||
|
||||
test('records a composite entry\'s components and total separately', () {
|
||||
test("records a composite entry's components and total separately", () {
|
||||
const components = [
|
||||
MealComponent(
|
||||
name: 'rice',
|
||||
@ -124,7 +132,6 @@ void main() {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('FoodBankService search/persistence', () {
|
||||
late Directory tempDir;
|
||||
|
||||
@ -180,216 +187,4 @@ void main() {
|
||||
expect(results.first.name, 'common');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Manual bank — addManualEntry / mergedEntries
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
group('FoodBankService manual bank', () {
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_manual_');
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
FoodBankService.resetForTesting();
|
||||
LogStorageService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
test('addManualEntry persists and mergedEntries returns it', () async {
|
||||
const record = FoodBankRecord(
|
||||
desc: 'Manual oat',
|
||||
kcal: 370,
|
||||
proteinG: 13,
|
||||
carbsG: 66,
|
||||
fatG: 7,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
);
|
||||
|
||||
await FoodBankService.instance.addManualEntry(record);
|
||||
final merged = await FoodBankService.instance.mergedEntries();
|
||||
|
||||
expect(merged.any((r) => r.desc == 'Manual oat'), isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'mergedEntries: log-derived entry wins over manual on collision',
|
||||
() async {
|
||||
// Seed log with 'oat' (count=1, kcal=100).
|
||||
final log = {
|
||||
'2026-06-22': [
|
||||
_entry(id: '1', time: '2026-06-22T08:00:00+02:00', desc: 'oat'),
|
||||
],
|
||||
};
|
||||
await FoodBankService.instance.rebuildAndPersist(log);
|
||||
|
||||
// Add manual entry with same normalized key but different kcal.
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'oat',
|
||||
kcal: 999,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
final merged = await FoodBankService.instance.mergedEntries();
|
||||
final oat = merged.firstWhere((r) => r.desc == 'oat');
|
||||
// Log-derived entry (kcal=100) should win over manual (kcal=999).
|
||||
expect(oat.kcal, 100);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'mergedEntries includes both log-derived and manual entries',
|
||||
() async {
|
||||
final log = {
|
||||
'2026-06-22': [
|
||||
_entry(
|
||||
id: '1',
|
||||
time: '2026-06-22T08:00:00+02:00',
|
||||
desc: 'toast',
|
||||
),
|
||||
],
|
||||
};
|
||||
await FoodBankService.instance.rebuildAndPersist(log);
|
||||
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Quinoa',
|
||||
kcal: 370,
|
||||
proteinG: 14,
|
||||
carbsG: 64,
|
||||
fatG: 6,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
final merged = await FoodBankService.instance.mergedEntries();
|
||||
final descs = merged.map((r) => r.desc).toSet();
|
||||
expect(descs, containsAll(['toast', 'Quinoa']));
|
||||
},
|
||||
);
|
||||
|
||||
test('addManualEntry upserts by normalized key', () async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Oat',
|
||||
kcal: 370,
|
||||
proteinG: 13,
|
||||
carbsG: 66,
|
||||
fatG: 7,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
// Upsert same food with updated kcal.
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'oat',
|
||||
kcal: 400,
|
||||
proteinG: 14,
|
||||
carbsG: 68,
|
||||
fatG: 8,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
final merged = await FoodBankService.instance.mergedEntries();
|
||||
final oats = merged.where((r) => r.desc.toLowerCase() == 'oat').toList();
|
||||
expect(oats.length, 1);
|
||||
expect(oats.single.kcal, 400);
|
||||
});
|
||||
|
||||
test('search includes manual entries', () async {
|
||||
await FoodBankService.instance.addManualEntry(
|
||||
const FoodBankRecord(
|
||||
desc: 'Rare ingredient',
|
||||
kcal: 50,
|
||||
proteinG: 1,
|
||||
carbsG: 10,
|
||||
fatG: 0.5,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
),
|
||||
);
|
||||
|
||||
final results = await FoodBankService.instance.search('Rare');
|
||||
expect(results.any((r) => r.name == 'Rare ingredient'), isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// IO error paths — FileSystemException and FormatException handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
group('FoodBankService IO error paths', () {
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_err_');
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
FoodBankService.resetForTesting();
|
||||
LogStorageService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
test('readBank returns empty on invalid JSON (FormatException)', () async {
|
||||
await File(
|
||||
'${tempDir.path}/food_bank.json',
|
||||
).writeAsString('not valid json {{{');
|
||||
expect(await FoodBankService.instance.readBank(), isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'readBank returns empty when file is unreadable (FileSystemException)',
|
||||
() async {
|
||||
final bankPath = '${tempDir.path}/food_bank.json';
|
||||
await File(bankPath).writeAsString('{}');
|
||||
await Process.run('chmod', ['000', bankPath]);
|
||||
|
||||
expect(await FoodBankService.instance.readBank(), isEmpty);
|
||||
|
||||
await Process.run('chmod', ['644', bankPath]);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'mergedEntries handles invalid JSON in manual bank (FormatException)',
|
||||
() async {
|
||||
await File(
|
||||
'${tempDir.path}/food_bank_manual.json',
|
||||
).writeAsString('not valid json {{{');
|
||||
expect(await FoodBankService.instance.mergedEntries(), isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'mergedEntries handles unreadable manual bank (FileSystemException)',
|
||||
() async {
|
||||
final manualPath = '${tempDir.path}/food_bank_manual.json';
|
||||
await File(manualPath).writeAsString('{}');
|
||||
await Process.run('chmod', ['000', manualPath]);
|
||||
|
||||
expect(await FoodBankService.instance.mergedEntries(), isEmpty);
|
||||
|
||||
await Process.run('chmod', ['644', manualPath]);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
229
app/test/services/log_storage_service_edit_test.dart
Normal file
229
app/test/services/log_storage_service_edit_test.dart
Normal file
@ -0,0 +1,229 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/models/nutrition.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
const _manual = Nutrition(
|
||||
kcal: 150,
|
||||
proteinG: 5,
|
||||
carbsG: 20,
|
||||
fatG: 3,
|
||||
grams: 50,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_test_');
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
LogStorageService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
group('deleteEntry', () {
|
||||
const entry = FoodEntry(
|
||||
id: 'del-1',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'to delete',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 30,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
test('tombstones the matching entry', () async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [entry],
|
||||
});
|
||||
await LogStorageService.instance.deleteEntry('del-1');
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
expect(log['2026-06-22']!.first.deleted, isTrue);
|
||||
});
|
||||
|
||||
test('silently ignores an unknown id', () async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [entry],
|
||||
});
|
||||
await LogStorageService.instance.deleteEntry('no-such-id');
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
expect(log['2026-06-22']!.first.deleted, isFalse);
|
||||
});
|
||||
|
||||
test('does not re-tombstone an already-deleted entry', () async {
|
||||
const deleted = FoodEntry(
|
||||
id: 'del-1',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'to delete',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 30,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
deleted: true,
|
||||
);
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [deleted],
|
||||
});
|
||||
await LogStorageService.instance.deleteEntry('del-1');
|
||||
// Still deleted, no error thrown.
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
expect(log['2026-06-22']!.first.deleted, isTrue);
|
||||
});
|
||||
});
|
||||
group('updateEntry', () {
|
||||
const original = FoodEntry(
|
||||
id: 'upd-1',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'original desc',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 30,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
const updated = FoodEntry(
|
||||
id: 'upd-1',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'edited desc',
|
||||
grams: 200,
|
||||
kcal: 600,
|
||||
proteinG: 20,
|
||||
carbsG: 60,
|
||||
fatG: 10,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
test('replaces the entry by id', () async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [original],
|
||||
});
|
||||
await LogStorageService.instance.updateEntry(original, updated);
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
final e = log['2026-06-22']!.first;
|
||||
expect(e.desc, 'edited desc');
|
||||
expect(e.kcal, 600);
|
||||
expect(e.proteinG, 20);
|
||||
});
|
||||
|
||||
test('replaces legacy null-id entry by time+desc', () async {
|
||||
const legacy = FoodEntry(
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'legacy entry',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 30,
|
||||
fatG: 5,
|
||||
source: 'food bank',
|
||||
);
|
||||
const legacyUpdated = FoodEntry(
|
||||
id: 'new-uuid',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'legacy entry',
|
||||
grams: 150,
|
||||
kcal: 450,
|
||||
proteinG: 15,
|
||||
carbsG: 45,
|
||||
fatG: 8,
|
||||
source: 'food bank',
|
||||
);
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [legacy],
|
||||
});
|
||||
await LogStorageService.instance.updateEntry(legacy, legacyUpdated);
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
final e = log['2026-06-22']!.first;
|
||||
expect(e.id, 'new-uuid');
|
||||
expect(e.kcal, 450);
|
||||
});
|
||||
|
||||
test('silently does nothing when no match is found', () async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [original],
|
||||
});
|
||||
const ghost = FoodEntry(
|
||||
id: 'ghost',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'ghost',
|
||||
grams: 0,
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
source: 'manual',
|
||||
);
|
||||
await LogStorageService.instance.updateEntry(ghost, updated);
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
expect(log['2026-06-22']!.first.desc, 'original desc');
|
||||
});
|
||||
});
|
||||
group('allEntriesNewestFirst', () {
|
||||
const oldest = FoodEntry(
|
||||
id: 'oldest',
|
||||
time: '2026-06-01T08:00:00+02:00',
|
||||
desc: 'oldest',
|
||||
grams: 100,
|
||||
kcal: 100,
|
||||
proteinG: 5,
|
||||
carbsG: 10,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
);
|
||||
const newest = FoodEntry(
|
||||
id: 'newest',
|
||||
time: '2026-06-22T20:00:00+02:00',
|
||||
desc: 'newest',
|
||||
grams: 100,
|
||||
kcal: 200,
|
||||
proteinG: 10,
|
||||
carbsG: 20,
|
||||
fatG: 4,
|
||||
source: 'manual',
|
||||
);
|
||||
const tombstoned = FoodEntry(
|
||||
id: 'gone',
|
||||
time: '2026-06-15T12:00:00+02:00',
|
||||
desc: 'undone',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 1,
|
||||
carbsG: 1,
|
||||
fatG: 1,
|
||||
source: 'manual',
|
||||
deleted: true,
|
||||
);
|
||||
|
||||
test(
|
||||
'sorts entries across days newest-first and drops tombstones',
|
||||
() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-01': [oldest],
|
||||
'2026-06-15': [tombstoned],
|
||||
'2026-06-22': [newest],
|
||||
});
|
||||
|
||||
final result = await LogStorageService.instance.allEntriesNewestFirst();
|
||||
|
||||
expect(result.map((e) => e.id), ['newest', 'oldest']);
|
||||
},
|
||||
);
|
||||
|
||||
test('returns empty for an empty log', () async {
|
||||
expect(await LogStorageService.instance.allEntriesNewestFirst(), isEmpty);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -1,10 +1,10 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/models/local_time.dart';
|
||||
import 'package:diet_guard_app/models/meal_component.dart';
|
||||
import 'package:diet_guard_app/models/nutrition.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
@ -18,6 +18,7 @@ const _manual = Nutrition(
|
||||
);
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
@ -53,7 +54,6 @@ void main() {
|
||||
expect(await LogStorageService.instance.readLog(), isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('logMeal', () {
|
||||
test('assigns a fresh id and never an hmac', () async {
|
||||
final entry = await LogStorageService.instance.logMeal(
|
||||
@ -88,14 +88,13 @@ void main() {
|
||||
expect(reloaded.single.components!.single.name, 'bread');
|
||||
});
|
||||
|
||||
test('two logged meals both persist under today\'s date key', () async {
|
||||
test("two logged meals both persist under today's date key", () async {
|
||||
await LogStorageService.instance.logMeal('a', _manual);
|
||||
await LogStorageService.instance.logMeal('b', _manual);
|
||||
final entries = await LogStorageService.instance.todayEntries();
|
||||
expect(entries, hasLength(2));
|
||||
});
|
||||
});
|
||||
|
||||
group('undoLastToday', () {
|
||||
test('returns null when today has no entries', () async {
|
||||
expect(await LogStorageService.instance.undoLastToday(), isNull);
|
||||
@ -118,7 +117,7 @@ void main() {
|
||||
expect(await LogStorageService.instance.todayEntries(), isEmpty);
|
||||
});
|
||||
|
||||
test('never touches a previous day\'s entries', () async {
|
||||
test("never touches a previous day's entries", () async {
|
||||
final yesterdayKey = localDateKey(
|
||||
DateTime.now().subtract(const Duration(days: 1)),
|
||||
);
|
||||
@ -159,9 +158,8 @@ void main() {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('todayTotalKcal', () {
|
||||
test('sums kcal across today\'s non-tombstoned entries', () async {
|
||||
test("sums kcal across today's non-tombstoned entries", () async {
|
||||
await LogStorageService.instance.logMeal('a', _manual);
|
||||
await LogStorageService.instance.logMeal('b', _manual);
|
||||
expect(await LogStorageService.instance.todayTotalKcal(), 300.0);
|
||||
@ -174,7 +172,6 @@ void main() {
|
||||
expect(await LogStorageService.instance.todayTotalKcal(), 150.0);
|
||||
});
|
||||
});
|
||||
|
||||
group('loggedSlotsToday', () {
|
||||
test('returns only the slots with a logged entry', () async {
|
||||
await LogStorageService.instance.logMeal('a', _manual, slot: 8);
|
||||
@ -182,204 +179,4 @@ void main() {
|
||||
expect(await LogStorageService.instance.loggedSlotsToday(), {8});
|
||||
});
|
||||
});
|
||||
|
||||
group('allEntriesNewestFirst', () {
|
||||
const oldest = FoodEntry(
|
||||
id: 'oldest',
|
||||
time: '2026-06-01T08:00:00+02:00',
|
||||
desc: 'oldest',
|
||||
grams: 100,
|
||||
kcal: 100,
|
||||
proteinG: 5,
|
||||
carbsG: 10,
|
||||
fatG: 2,
|
||||
source: 'manual',
|
||||
);
|
||||
const newest = FoodEntry(
|
||||
id: 'newest',
|
||||
time: '2026-06-22T20:00:00+02:00',
|
||||
desc: 'newest',
|
||||
grams: 100,
|
||||
kcal: 200,
|
||||
proteinG: 10,
|
||||
carbsG: 20,
|
||||
fatG: 4,
|
||||
source: 'manual',
|
||||
);
|
||||
const tombstoned = FoodEntry(
|
||||
id: 'gone',
|
||||
time: '2026-06-15T12:00:00+02:00',
|
||||
desc: 'undone',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 1,
|
||||
carbsG: 1,
|
||||
fatG: 1,
|
||||
source: 'manual',
|
||||
deleted: true,
|
||||
);
|
||||
|
||||
test(
|
||||
'sorts entries across days newest-first and drops tombstones',
|
||||
() async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-01': [oldest],
|
||||
'2026-06-15': [tombstoned],
|
||||
'2026-06-22': [newest],
|
||||
});
|
||||
|
||||
final result = await LogStorageService.instance.allEntriesNewestFirst();
|
||||
|
||||
expect(result.map((e) => e.id), ['newest', 'oldest']);
|
||||
},
|
||||
);
|
||||
|
||||
test('returns empty for an empty log', () async {
|
||||
expect(await LogStorageService.instance.allEntriesNewestFirst(), isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('deleteEntry', () {
|
||||
const entry = FoodEntry(
|
||||
id: 'del-1',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'to delete',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 30,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
test('tombstones the matching entry', () async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [entry],
|
||||
});
|
||||
await LogStorageService.instance.deleteEntry('del-1');
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
expect(log['2026-06-22']!.first.deleted, isTrue);
|
||||
});
|
||||
|
||||
test('silently ignores an unknown id', () async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [entry],
|
||||
});
|
||||
await LogStorageService.instance.deleteEntry('no-such-id');
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
expect(log['2026-06-22']!.first.deleted, isFalse);
|
||||
});
|
||||
|
||||
test('does not re-tombstone an already-deleted entry', () async {
|
||||
const deleted = FoodEntry(
|
||||
id: 'del-1',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'to delete',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 30,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
deleted: true,
|
||||
);
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [deleted],
|
||||
});
|
||||
await LogStorageService.instance.deleteEntry('del-1');
|
||||
// Still deleted, no error thrown.
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
expect(log['2026-06-22']!.first.deleted, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('updateEntry', () {
|
||||
const original = FoodEntry(
|
||||
id: 'upd-1',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'original desc',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 30,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
const updated = FoodEntry(
|
||||
id: 'upd-1',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'edited desc',
|
||||
grams: 200,
|
||||
kcal: 600,
|
||||
proteinG: 20,
|
||||
carbsG: 60,
|
||||
fatG: 10,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
test('replaces the entry by id', () async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [original],
|
||||
});
|
||||
await LogStorageService.instance.updateEntry(original, updated);
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
final e = log['2026-06-22']!.first;
|
||||
expect(e.desc, 'edited desc');
|
||||
expect(e.kcal, 600);
|
||||
expect(e.proteinG, 20);
|
||||
});
|
||||
|
||||
test('replaces legacy null-id entry by time+desc', () async {
|
||||
const legacy = FoodEntry(
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'legacy entry',
|
||||
grams: 100,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 30,
|
||||
fatG: 5,
|
||||
source: 'food bank',
|
||||
);
|
||||
const legacyUpdated = FoodEntry(
|
||||
id: 'new-uuid',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'legacy entry',
|
||||
grams: 150,
|
||||
kcal: 450,
|
||||
proteinG: 15,
|
||||
carbsG: 45,
|
||||
fatG: 8,
|
||||
source: 'food bank',
|
||||
);
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [legacy],
|
||||
});
|
||||
await LogStorageService.instance.updateEntry(legacy, legacyUpdated);
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
final e = log['2026-06-22']!.first;
|
||||
expect(e.id, 'new-uuid');
|
||||
expect(e.kcal, 450);
|
||||
});
|
||||
|
||||
test('silently does nothing when no match is found', () async {
|
||||
await LogStorageService.instance.writeLog({
|
||||
'2026-06-22': [original],
|
||||
});
|
||||
const ghost = FoodEntry(
|
||||
id: 'ghost',
|
||||
time: '2026-06-22T12:00:00+02:00',
|
||||
desc: 'ghost',
|
||||
grams: 0,
|
||||
kcal: 0,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
source: 'manual',
|
||||
);
|
||||
await LogStorageService.instance.updateEntry(ghost, updated);
|
||||
final log = await LogStorageService.instance.readLog();
|
||||
expect(log['2026-06-22']!.first.desc, 'original desc');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
136
app/test/services/sync_merge_banks_test.dart
Normal file
136
app/test/services/sync_merge_banks_test.dart
Normal file
@ -0,0 +1,136 @@
|
||||
// Table-driven mergeLogs() tests. `union by id` through `algebraic
|
||||
// properties` are the exact same assertions the pre-migration
|
||||
// `sync_merge.mergeLogs` had -- routed through `dayLogToLog ->
|
||||
// crdt_sync.mergeLogs -> logToDayLog` instead, to prove the migration
|
||||
// preserves the app's merge semantics exactly, mirroring
|
||||
// `test_sync_merge.py`'s equivalent Python-side proof.
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/models/food_bank_record.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';
|
||||
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
FoodEntry _entry({
|
||||
String? id = 'id-1',
|
||||
String time = '2026-06-22T08:00:00',
|
||||
String desc = 'oatmeal',
|
||||
bool deleted = false,
|
||||
}) => FoodEntry(
|
||||
id: id,
|
||||
time: time,
|
||||
desc: desc,
|
||||
grams: 200,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 50,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
deleted: deleted,
|
||||
);
|
||||
|
||||
DayLog _mergeDaylogs(DayLog a, DayLog b) =>
|
||||
logToDayLog(mergeLogs(dayLogToLog(a), dayLogToLog(b)));
|
||||
|
||||
const _history = [
|
||||
BudgetEntry(
|
||||
effectiveFrom: '1970-01-01',
|
||||
kcal: 2200,
|
||||
editedAt: '2026-07-13T21:15:09.000Z',
|
||||
),
|
||||
BudgetEntry(
|
||||
effectiveFrom: '2026-07-26',
|
||||
kcal: 2000,
|
||||
editedAt: '2026-07-26T10:00:00.000Z',
|
||||
),
|
||||
];
|
||||
|
||||
void main() {
|
||||
group('derived food-bank adapters', () {
|
||||
// Mirror of `test_sync_merge.py`'s TestFoodBankAdapters.
|
||||
FoodBankRecord apple({required double count, double kcal = 95}) =>
|
||||
FoodBankRecord(
|
||||
desc: 'Apple',
|
||||
kcal: kcal,
|
||||
proteinG: 0.5,
|
||||
carbsG: 25,
|
||||
fatG: 0.3,
|
||||
grams: 180,
|
||||
count: count,
|
||||
);
|
||||
|
||||
test('count is the clock', () {
|
||||
final log = foodBankToLog({'apple': apple(count: 5)});
|
||||
expect(log['apple']!.fields['body']!.$2.wallTimeMs, 5);
|
||||
});
|
||||
|
||||
test('the higher count wins', () {
|
||||
final behind = foodBankToLog({'apple': apple(count: 3, kcal: 90)});
|
||||
final ahead = foodBankToLog({'apple': apple(count: 9)});
|
||||
final merged = logToFoodBank(mergeLogs(behind, ahead));
|
||||
expect(merged['apple']!.count, 9);
|
||||
expect(merged['apple']!.kcal, 95);
|
||||
});
|
||||
|
||||
test('the merge is order independent', () {
|
||||
final a = foodBankToLog({'apple': apple(count: 3)});
|
||||
final b = foodBankToLog({'apple': apple(count: 9)});
|
||||
expect(
|
||||
logToFoodBank(mergeLogs(a, b))['apple']!.count,
|
||||
logToFoodBank(mergeLogs(b, a))['apple']!.count,
|
||||
);
|
||||
});
|
||||
|
||||
test('re-merging is idempotent', () {
|
||||
final once = foodBankToLog({'apple': apple(count: 5)});
|
||||
expect(logToFoodBank(mergeLogs(once, once))['apple']!.count, 5);
|
||||
});
|
||||
|
||||
test('different foods union', () {
|
||||
final a = foodBankToLog({'apple': apple(count: 1)});
|
||||
final b = foodBankToLog({
|
||||
'pear': const FoodBankRecord(
|
||||
desc: 'Pear',
|
||||
kcal: 57,
|
||||
proteinG: 0,
|
||||
carbsG: 15,
|
||||
fatG: 0,
|
||||
grams: 100,
|
||||
count: 1,
|
||||
),
|
||||
});
|
||||
expect(logToFoodBank(mergeLogs(a, b)).keys.toSet(), {'apple', 'pear'});
|
||||
});
|
||||
|
||||
test('a non-map body is skipped on read', () {
|
||||
final log = {
|
||||
'apple': Record(
|
||||
id: 'apple',
|
||||
fields: {
|
||||
'body': ('x', budgetHlc(const {'t': ''})),
|
||||
},
|
||||
),
|
||||
};
|
||||
expect(logToFoodBank(log), isEmpty);
|
||||
});
|
||||
|
||||
test('parses pushed wire content', () {
|
||||
final wire = encodeFoodBankForPush(
|
||||
foodBankToLog({'apple': apple(count: 5)}),
|
||||
);
|
||||
expect(parseRemoteFoodBank(wire).containsKey('apple'), isTrue);
|
||||
});
|
||||
|
||||
test('non-object top level throws FormatException', () {
|
||||
expect(() => parseRemoteFoodBank('[1,2,3]'), throwsFormatException);
|
||||
});
|
||||
|
||||
test('the wire shape matches the Python side', () {
|
||||
final log = foodBankToLog({'apple': apple(count: 5)});
|
||||
expect(log['apple']!.id, 'apple');
|
||||
expect(log['apple']!.fields.keys.toList(), ['body']);
|
||||
});
|
||||
});
|
||||
}
|
||||
212
app/test/services/sync_merge_budget_test.dart
Normal file
212
app/test/services/sync_merge_budget_test.dart
Normal file
@ -0,0 +1,212 @@
|
||||
// Table-driven mergeLogs() tests. `union by id` through `algebraic
|
||||
// properties` are the exact same assertions the pre-migration
|
||||
// `sync_merge.mergeLogs` had -- routed through `dayLogToLog ->
|
||||
// crdt_sync.mergeLogs -> logToDayLog` instead, to prove the migration
|
||||
// preserves the app's merge semantics exactly, mirroring
|
||||
// `test_sync_merge.py`'s equivalent Python-side proof.
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.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';
|
||||
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
FoodEntry _entry({
|
||||
String? id = 'id-1',
|
||||
String time = '2026-06-22T08:00:00',
|
||||
String desc = 'oatmeal',
|
||||
bool deleted = false,
|
||||
}) => FoodEntry(
|
||||
id: id,
|
||||
time: time,
|
||||
desc: desc,
|
||||
grams: 200,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 50,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
deleted: deleted,
|
||||
);
|
||||
|
||||
DayLog _mergeDaylogs(DayLog a, DayLog b) =>
|
||||
logToDayLog(mergeLogs(dayLogToLog(a), dayLogToLog(b)));
|
||||
|
||||
const _history = [
|
||||
BudgetEntry(
|
||||
effectiveFrom: '1970-01-01',
|
||||
kcal: 2200,
|
||||
editedAt: '2026-07-13T21:15:09.000Z',
|
||||
),
|
||||
BudgetEntry(
|
||||
effectiveFrom: '2026-07-26',
|
||||
kcal: 2000,
|
||||
editedAt: '2026-07-26T10:00:00.000Z',
|
||||
),
|
||||
];
|
||||
|
||||
void main() {
|
||||
group('budget adapters', () {
|
||||
Map<String, dynamic> budgetRecord({
|
||||
int b = 2000,
|
||||
String t = '2026-06-22T08:00:00',
|
||||
double? w,
|
||||
}) => {'v': 2, 'b': b, 't': t, 'w': ?w};
|
||||
|
||||
group('budgetHlc', () {
|
||||
test('same record always yields the same Hlc', () {
|
||||
final record = budgetRecord();
|
||||
expect(budgetHlc(record), budgetHlc({...record}));
|
||||
});
|
||||
|
||||
test('malformed t still yields a valid Hlc', () {
|
||||
final record = budgetRecord(t: 'not-a-timestamp');
|
||||
expect(budgetHlc(record).wallTimeMs, 0);
|
||||
});
|
||||
|
||||
test('a later t yields a greater Hlc', () {
|
||||
final earlier = budgetRecord(t: '2020-01-01T00:00:00Z');
|
||||
final later = budgetRecord(t: '2030-01-01T00:00:00Z');
|
||||
expect(budgetHlc(later) > budgetHlc(earlier), isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('budgetToLog / logToBudget round trip', () {
|
||||
test('null record yields an empty log', () {
|
||||
expect(budgetToLog(null), isEmpty);
|
||||
});
|
||||
|
||||
test('round trip preserves the budget', () {
|
||||
final record = budgetRecord();
|
||||
final roundTripped = logToBudget(budgetToLog(record));
|
||||
expect(roundTripped, isNotNull);
|
||||
expect(roundTripped!['b'], 2000);
|
||||
});
|
||||
|
||||
test('weight never travels', () {
|
||||
// `w` is PC-local, so it must not enter the shared value map: the
|
||||
// phone rebuilds that map without it, and before this fix a winning
|
||||
// phone edit silently deleted the PC's stored weight -- and with it
|
||||
// the protein target. Matches Python's budget_to_log.
|
||||
final record = budgetRecord(w: 80);
|
||||
final roundTripped = logToBudget(budgetToLog(record));
|
||||
expect(roundTripped, isNotNull);
|
||||
expect(roundTripped!.containsKey('w'), isFalse);
|
||||
});
|
||||
|
||||
test('history becomes one field per date', () {
|
||||
final log = budgetToLog(budgetRecord(), _history);
|
||||
final fields = log[budgetRecordId]!.fields;
|
||||
expect(fields.containsKey('value'), isTrue);
|
||||
expect(fields['hist:1970-01-01']!.$1, 2200);
|
||||
expect(fields['hist:2026-07-26']!.$1, 2000);
|
||||
});
|
||||
|
||||
test('history round trips back to entries', () {
|
||||
final entries = logToHistory(budgetToLog(budgetRecord(), _history));
|
||||
expect(entries.map((e) => e.effectiveFrom).toList(), [
|
||||
'1970-01-01',
|
||||
'2026-07-26',
|
||||
]);
|
||||
expect(entries.map((e) => e.kcal).toList(), [2200, 2000]);
|
||||
});
|
||||
|
||||
test('no history round trips to nothing', () {
|
||||
expect(logToHistory(budgetToLog(budgetRecord())), isEmpty);
|
||||
});
|
||||
|
||||
test('an empty log has no history', () {
|
||||
expect(logToHistory(<String, Record>{}), isEmpty);
|
||||
});
|
||||
|
||||
test('non-history fields are ignored', () {
|
||||
final log = budgetToLog(budgetRecord());
|
||||
expect(logToHistory(log), isEmpty);
|
||||
});
|
||||
|
||||
test('a non-int history value is skipped', () {
|
||||
final log = {
|
||||
budgetRecordId: Record(
|
||||
id: budgetRecordId,
|
||||
fields: {
|
||||
'hist:2026-07-26': ('nonsense', budgetHlc(budgetRecord())),
|
||||
},
|
||||
),
|
||||
};
|
||||
expect(logToHistory(log), isEmpty);
|
||||
});
|
||||
|
||||
test('an unparsable edit time still yields a field', () {
|
||||
const broken = BudgetEntry(
|
||||
effectiveFrom: '2026-07-26',
|
||||
kcal: 2000,
|
||||
editedAt: 'not a timestamp',
|
||||
);
|
||||
final log = budgetToLog(budgetRecord(), [broken]);
|
||||
expect(
|
||||
log[budgetRecordId]!.fields.containsKey('hist:2026-07-26'),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('history survives a merge with a history-free peer', () {
|
||||
// The rollout guarantee: mergeRecord is per-field LWW over the
|
||||
// *union* of field names, so a peer that only pushes `value` leaves
|
||||
// `hist:*` untouched -- which is why this needed no coordinated
|
||||
// release. Mirrors the Python test of the same name.
|
||||
final ours = budgetToLog(budgetRecord(), _history);
|
||||
final legacy = {
|
||||
budgetRecordId: Record(
|
||||
id: budgetRecordId,
|
||||
fields: {
|
||||
'value': (
|
||||
{'v': 2, 'b': 2200},
|
||||
budgetHlc({'t': '2099-01-01T00:00:00Z'}),
|
||||
),
|
||||
},
|
||||
),
|
||||
};
|
||||
expect(logToHistory(mergeLogs(ours, legacy)), hasLength(2));
|
||||
});
|
||||
|
||||
test('the wire field names match the Python side exactly', () {
|
||||
// A rename on either side silently splits the two devices' history.
|
||||
expect(budgetHistoryFieldPrefix, 'hist:');
|
||||
expect(budgetRecordId, 'budget');
|
||||
});
|
||||
|
||||
test('round-tripped t reflects the winning Hlc', () {
|
||||
final record = budgetRecord();
|
||||
final roundTripped = logToBudget(budgetToLog(record));
|
||||
expect(roundTripped, isNotNull);
|
||||
expect(roundTripped!['t'], isNotEmpty);
|
||||
});
|
||||
|
||||
test('empty log has no budget', () {
|
||||
expect(logToBudget({}), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
group('parseRemoteBudget', () {
|
||||
test('parses pushed budget wire content', () {
|
||||
final record = budgetRecord();
|
||||
final pushed = encodeBudgetForPush(budgetToLog(record));
|
||||
final log = parseRemoteBudget(pushed);
|
||||
expect(log[budgetRecordId]!.id, budgetRecordId);
|
||||
});
|
||||
|
||||
test('empty object parses as empty log', () {
|
||||
expect(parseRemoteBudget('{}'), isEmpty);
|
||||
});
|
||||
|
||||
test('non-object top level throws FormatException', () {
|
||||
expect(() => parseRemoteBudget('[1, 2, 3]'), throwsFormatException);
|
||||
});
|
||||
|
||||
test('invalid JSON throws FormatException', () {
|
||||
expect(() => parseRemoteBudget('not json{{{'), throwsFormatException);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
166
app/test/services/sync_merge_curated_test.dart
Normal file
166
app/test/services/sync_merge_curated_test.dart
Normal file
@ -0,0 +1,166 @@
|
||||
// Table-driven mergeLogs() tests. `union by id` through `algebraic
|
||||
// properties` are the exact same assertions the pre-migration
|
||||
// `sync_merge.mergeLogs` had -- routed through `dayLogToLog ->
|
||||
// crdt_sync.mergeLogs -> logToDayLog` instead, to prove the migration
|
||||
// preserves the app's merge semantics exactly, mirroring
|
||||
// `test_sync_merge.py`'s equivalent Python-side proof.
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/models/food_bank_record.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';
|
||||
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
FoodEntry _entry({
|
||||
String? id = 'id-1',
|
||||
String time = '2026-06-22T08:00:00',
|
||||
String desc = 'oatmeal',
|
||||
bool deleted = false,
|
||||
}) => FoodEntry(
|
||||
id: id,
|
||||
time: time,
|
||||
desc: desc,
|
||||
grams: 200,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 50,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
deleted: deleted,
|
||||
);
|
||||
|
||||
DayLog _mergeDaylogs(DayLog a, DayLog b) =>
|
||||
logToDayLog(mergeLogs(dayLogToLog(a), dayLogToLog(b)));
|
||||
|
||||
const _history = [
|
||||
BudgetEntry(
|
||||
effectiveFrom: '1970-01-01',
|
||||
kcal: 2200,
|
||||
editedAt: '2026-07-13T21:15:09.000Z',
|
||||
),
|
||||
BudgetEntry(
|
||||
effectiveFrom: '2026-07-26',
|
||||
kcal: 2000,
|
||||
editedAt: '2026-07-26T10:00:00.000Z',
|
||||
),
|
||||
];
|
||||
|
||||
void main() {
|
||||
group('curated food-bank adapters', () {
|
||||
// Mirror of `test_sync_merge.py`'s TestManualBankAdapters. A divergence
|
||||
// here means a food curated on one device never reaches the other.
|
||||
FoodBankRecord skyr({double kcal = 120, String? t}) => FoodBankRecord(
|
||||
desc: 'Skyr',
|
||||
kcal: kcal,
|
||||
proteinG: 20,
|
||||
carbsG: 5,
|
||||
fatG: 0.5,
|
||||
grams: 150,
|
||||
count: 0,
|
||||
editedAt: t ?? '2026-07-26T10:00:00.000Z',
|
||||
);
|
||||
|
||||
test('round trips a record', () {
|
||||
final back = logToManualBank(manualBankToLog({'skyr': skyr()}));
|
||||
expect(back['skyr']!.desc, 'Skyr');
|
||||
expect(back['skyr']!.kcal, 120);
|
||||
});
|
||||
|
||||
test('the edit stamp does not travel inside the body', () {
|
||||
final log = manualBankToLog({'skyr': skyr()});
|
||||
expect(
|
||||
(log['skyr']!.fields['body']!.$1! as Map).containsKey('t'),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('edit time is reconstructed from the Hlc', () {
|
||||
final back = logToManualBank(manualBankToLog({'skyr': skyr()}));
|
||||
expect(back['skyr']!.editedAt, isNotNull);
|
||||
});
|
||||
|
||||
test('a missing edit stamp falls back to the epoch', () {
|
||||
final log = manualBankToLog({
|
||||
'skyr': const FoodBankRecord(
|
||||
desc: 'Skyr',
|
||||
kcal: 1,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
grams: 0,
|
||||
count: 0,
|
||||
),
|
||||
});
|
||||
expect(log['skyr']!.fields['body']!.$2.wallTimeMs, 0);
|
||||
});
|
||||
|
||||
test('a newer edit wins the merge', () {
|
||||
final older = manualBankToLog({'skyr': skyr()});
|
||||
final newer = manualBankToLog({
|
||||
'skyr': skyr(kcal: 999, t: '2999-01-01T00:00:00.000Z'),
|
||||
});
|
||||
expect(logToManualBank(mergeLogs(older, newer))['skyr']!.kcal, 999);
|
||||
});
|
||||
|
||||
test('different foods union rather than replace', () {
|
||||
final a = manualBankToLog({'skyr': skyr()});
|
||||
final b = manualBankToLog({
|
||||
'kefir': const FoodBankRecord(
|
||||
desc: 'Kefir',
|
||||
kcal: 60,
|
||||
proteinG: 3,
|
||||
carbsG: 4,
|
||||
fatG: 2,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
editedAt: '2026-07-26T10:00:00.000Z',
|
||||
),
|
||||
});
|
||||
expect(logToManualBank(mergeLogs(a, b)).keys.toSet(), {'skyr', 'kefir'});
|
||||
});
|
||||
|
||||
test('a non-map body is skipped on read', () {
|
||||
final log = {
|
||||
'skyr': Record(
|
||||
id: 'skyr',
|
||||
fields: {
|
||||
'body': ('nope', budgetHlc(const {'t': ''})),
|
||||
},
|
||||
),
|
||||
};
|
||||
expect(logToManualBank(log), isEmpty);
|
||||
});
|
||||
|
||||
test('a tombstoned record is dropped on read', () {
|
||||
final log = {
|
||||
'skyr': Record(
|
||||
id: 'skyr',
|
||||
fields: {
|
||||
'body': (skyr().toJson(), budgetHlc(const {'t': ''})),
|
||||
},
|
||||
deleted: true,
|
||||
),
|
||||
};
|
||||
expect(logToManualBank(log), isEmpty);
|
||||
});
|
||||
|
||||
test('parses pushed wire content', () {
|
||||
final wire = encodeManualBankForPush(manualBankToLog({'skyr': skyr()}));
|
||||
expect(parseRemoteManualBank(wire).containsKey('skyr'), isTrue);
|
||||
});
|
||||
|
||||
test('non-object top level throws FormatException', () {
|
||||
expect(() => parseRemoteManualBank('[1,2,3]'), throwsFormatException);
|
||||
});
|
||||
|
||||
test('the wire shape matches the Python side', () {
|
||||
// Python uses the same `body` field name and the same normalized-name
|
||||
// record id; a rename on either side silently splits the two banks.
|
||||
final log = manualBankToLog({'skyr': skyr()});
|
||||
expect(log['skyr']!.id, 'skyr');
|
||||
expect(log['skyr']!.fields.keys.toList(), ['body']);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -5,13 +5,10 @@
|
||||
// preserves the app's merge semantics exactly, mirroring
|
||||
// `test_sync_merge.py`'s equivalent Python-side proof.
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_schedule.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
@ -53,7 +50,7 @@ void main() {
|
||||
group('union by id', () {
|
||||
test('disjoint logs union into one', () {
|
||||
final a = {
|
||||
'2026-06-22': [_entry(id: 'a', time: '2026-06-22T08:00:00')],
|
||||
'2026-06-22': [_entry(id: 'a')],
|
||||
};
|
||||
final b = {
|
||||
'2026-06-22': [_entry(id: 'b', time: '2026-06-22T12:00:00')],
|
||||
@ -115,7 +112,6 @@ void main() {
|
||||
expect(merged['2026-06-20'], hasLength(2));
|
||||
});
|
||||
});
|
||||
|
||||
group('tombstone wins', () {
|
||||
test('tombstone beats a non-deleted copy either order', () {
|
||||
final normal = _entry(id: 'x');
|
||||
@ -155,7 +151,6 @@ void main() {
|
||||
expect(merged['2026-06-22']!.single.deleted, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('rebucketing and ordering', () {
|
||||
test(
|
||||
"entry is filed under its own time's date, not the arrival bucket",
|
||||
@ -183,7 +178,7 @@ void main() {
|
||||
|
||||
test("a day's entries are sorted oldest-first", () {
|
||||
final late = _entry(id: 'late', time: '2026-06-22T20:00:00');
|
||||
final early = _entry(id: 'early', time: '2026-06-22T08:00:00');
|
||||
final early = _entry(id: 'early');
|
||||
final merged = _mergeDaylogs(
|
||||
{
|
||||
'2026-06-22': [late],
|
||||
@ -198,7 +193,6 @@ void main() {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
group('algebraic properties', () {
|
||||
test('merge is commutative', () {
|
||||
final a = {
|
||||
@ -235,460 +229,4 @@ void main() {
|
||||
expect(_mergeDaylogs({}, {}), isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('entryHlc', () {
|
||||
test('same entry always yields the same Hlc', () {
|
||||
expect(entryHlc(_entry()), entryHlc(_entry()));
|
||||
});
|
||||
|
||||
test('malformed time still yields a valid Hlc', () {
|
||||
expect(entryHlc(_entry(time: 'not-a-timestamp')).wallTimeMs, 0);
|
||||
});
|
||||
});
|
||||
|
||||
group('legacyEntryId', () {
|
||||
test('same time and desc yields the same id', () {
|
||||
final a = _entry(time: '2026-06-20T08:00:00', desc: 'toast');
|
||||
final b = _entry(time: '2026-06-20T08:00:00', desc: 'toast');
|
||||
expect(legacyEntryId(a), legacyEntryId(b));
|
||||
});
|
||||
|
||||
test('different desc yields a different id', () {
|
||||
final a = _entry(time: '2026-06-20T08:00:00', desc: 'toast');
|
||||
final b = _entry(time: '2026-06-20T08:00:00', desc: 'eggs');
|
||||
expect(legacyEntryId(a), isNot(legacyEntryId(b)));
|
||||
});
|
||||
});
|
||||
|
||||
group('entry <-> Record round trip', () {
|
||||
test('round trip preserves all fields', () {
|
||||
final entry = _entry(id: 'x');
|
||||
final roundTripped = recordToEntry(entryToRecord(entry));
|
||||
expect(roundTripped.toSyncJson(), entry.toSyncJson());
|
||||
});
|
||||
|
||||
test('round trip of a deleted entry preserves the tombstone', () {
|
||||
final entry = _entry(id: 'x', deleted: true);
|
||||
expect(recordToEntry(entryToRecord(entry)).deleted, isTrue);
|
||||
});
|
||||
|
||||
test('legacy entry gets a derived id on round trip', () {
|
||||
final entry = _entry(
|
||||
id: null,
|
||||
time: '2026-06-20T08:00:00',
|
||||
desc: 'toast',
|
||||
);
|
||||
final roundTripped = recordToEntry(entryToRecord(entry));
|
||||
expect(roundTripped.id, legacyEntryId(entry));
|
||||
});
|
||||
|
||||
test('a Record with no body field falls back to an empty body', () {
|
||||
const record = Record(id: 'x', fields: {});
|
||||
final entry = recordToEntry(record);
|
||||
expect(entry.id, 'x');
|
||||
expect(entry.desc, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('parseRemoteLog', () {
|
||||
test('parses new-format wire content', () {
|
||||
final entry = _entry(id: 'x');
|
||||
final pushed = encodeLogForPush({'x': entryToRecord(entry)});
|
||||
final log = parseRemoteLog(pushed);
|
||||
expect(log['x']!.id, 'x');
|
||||
});
|
||||
|
||||
test('parses old DayLog format for backward compatibility', () {
|
||||
final entry = _entry(id: 'x');
|
||||
final oldFormat = jsonEncode({
|
||||
'2026-06-22': [entry.toSyncJson()],
|
||||
});
|
||||
final log = parseRemoteLog(oldFormat);
|
||||
expect(log['x']!.id, 'x');
|
||||
});
|
||||
|
||||
test('empty object parses as empty log', () {
|
||||
expect(parseRemoteLog('{}'), isEmpty);
|
||||
});
|
||||
|
||||
test('non-object top level throws FormatException', () {
|
||||
expect(() => parseRemoteLog('[1, 2, 3]'), throwsFormatException);
|
||||
});
|
||||
|
||||
test('old-format day not a list throws FormatException', () {
|
||||
expect(
|
||||
() => parseRemoteLog('{"2026-06-22": "not-a-list"}'),
|
||||
throwsFormatException,
|
||||
);
|
||||
});
|
||||
|
||||
test('invalid JSON throws FormatException', () {
|
||||
expect(() => parseRemoteLog('not json{{{'), throwsFormatException);
|
||||
});
|
||||
});
|
||||
|
||||
group('derived food-bank adapters', () {
|
||||
// Mirror of `test_sync_merge.py`'s TestFoodBankAdapters.
|
||||
FoodBankRecord apple({required double count, double kcal = 95}) =>
|
||||
FoodBankRecord(
|
||||
desc: 'Apple',
|
||||
kcal: kcal,
|
||||
proteinG: 0.5,
|
||||
carbsG: 25,
|
||||
fatG: 0.3,
|
||||
grams: 180,
|
||||
count: count,
|
||||
);
|
||||
|
||||
test('count is the clock', () {
|
||||
final log = foodBankToLog({'apple': apple(count: 5)});
|
||||
expect(log['apple']!.fields['body']!.$2.wallTimeMs, 5);
|
||||
});
|
||||
|
||||
test('the higher count wins', () {
|
||||
final behind = foodBankToLog({'apple': apple(count: 3, kcal: 90)});
|
||||
final ahead = foodBankToLog({'apple': apple(count: 9, kcal: 95)});
|
||||
final merged = logToFoodBank(mergeLogs(behind, ahead));
|
||||
expect(merged['apple']!.count, 9);
|
||||
expect(merged['apple']!.kcal, 95);
|
||||
});
|
||||
|
||||
test('the merge is order independent', () {
|
||||
final a = foodBankToLog({'apple': apple(count: 3)});
|
||||
final b = foodBankToLog({'apple': apple(count: 9)});
|
||||
expect(
|
||||
logToFoodBank(mergeLogs(a, b))['apple']!.count,
|
||||
logToFoodBank(mergeLogs(b, a))['apple']!.count,
|
||||
);
|
||||
});
|
||||
|
||||
test('re-merging is idempotent', () {
|
||||
final once = foodBankToLog({'apple': apple(count: 5)});
|
||||
expect(logToFoodBank(mergeLogs(once, once))['apple']!.count, 5);
|
||||
});
|
||||
|
||||
test('different foods union', () {
|
||||
final a = foodBankToLog({'apple': apple(count: 1)});
|
||||
final b = foodBankToLog({
|
||||
'pear': FoodBankRecord(
|
||||
desc: 'Pear',
|
||||
kcal: 57,
|
||||
proteinG: 0,
|
||||
carbsG: 15,
|
||||
fatG: 0,
|
||||
grams: 100,
|
||||
count: 1,
|
||||
),
|
||||
});
|
||||
expect(logToFoodBank(mergeLogs(a, b)).keys.toSet(), {'apple', 'pear'});
|
||||
});
|
||||
|
||||
test('a non-map body is skipped on read', () {
|
||||
final log = {
|
||||
'apple': Record(
|
||||
id: 'apple',
|
||||
fields: {
|
||||
'body': ('x', budgetHlc(const {'t': ''})),
|
||||
},
|
||||
),
|
||||
};
|
||||
expect(logToFoodBank(log), isEmpty);
|
||||
});
|
||||
|
||||
test('parses pushed wire content', () {
|
||||
final wire = encodeFoodBankForPush(
|
||||
foodBankToLog({'apple': apple(count: 5)}),
|
||||
);
|
||||
expect(parseRemoteFoodBank(wire).containsKey('apple'), isTrue);
|
||||
});
|
||||
|
||||
test('non-object top level throws FormatException', () {
|
||||
expect(() => parseRemoteFoodBank('[1,2,3]'), throwsFormatException);
|
||||
});
|
||||
|
||||
test('the wire shape matches the Python side', () {
|
||||
final log = foodBankToLog({'apple': apple(count: 5)});
|
||||
expect(log['apple']!.id, 'apple');
|
||||
expect(log['apple']!.fields.keys.toList(), ['body']);
|
||||
});
|
||||
});
|
||||
|
||||
group('curated food-bank adapters', () {
|
||||
// Mirror of `test_sync_merge.py`'s TestManualBankAdapters. A divergence
|
||||
// here means a food curated on one device never reaches the other.
|
||||
FoodBankRecord skyr({double kcal = 120, String? t}) => FoodBankRecord(
|
||||
desc: 'Skyr',
|
||||
kcal: kcal,
|
||||
proteinG: 20,
|
||||
carbsG: 5,
|
||||
fatG: 0.5,
|
||||
grams: 150,
|
||||
count: 0,
|
||||
editedAt: t ?? '2026-07-26T10:00:00.000Z',
|
||||
);
|
||||
|
||||
test('round trips a record', () {
|
||||
final back = logToManualBank(manualBankToLog({'skyr': skyr()}));
|
||||
expect(back['skyr']!.desc, 'Skyr');
|
||||
expect(back['skyr']!.kcal, 120);
|
||||
});
|
||||
|
||||
test('the edit stamp does not travel inside the body', () {
|
||||
final log = manualBankToLog({'skyr': skyr()});
|
||||
expect(
|
||||
(log['skyr']!.fields['body']!.$1 as Map).containsKey('t'),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('edit time is reconstructed from the Hlc', () {
|
||||
final back = logToManualBank(manualBankToLog({'skyr': skyr()}));
|
||||
expect(back['skyr']!.editedAt, isNotNull);
|
||||
});
|
||||
|
||||
test('a missing edit stamp falls back to the epoch', () {
|
||||
final log = manualBankToLog({
|
||||
'skyr': const FoodBankRecord(
|
||||
desc: 'Skyr',
|
||||
kcal: 1,
|
||||
proteinG: 0,
|
||||
carbsG: 0,
|
||||
fatG: 0,
|
||||
grams: 0,
|
||||
count: 0,
|
||||
),
|
||||
});
|
||||
expect(log['skyr']!.fields['body']!.$2.wallTimeMs, 0);
|
||||
});
|
||||
|
||||
test('a newer edit wins the merge', () {
|
||||
final older = manualBankToLog({'skyr': skyr()});
|
||||
final newer = manualBankToLog({
|
||||
'skyr': skyr(kcal: 999, t: '2999-01-01T00:00:00.000Z'),
|
||||
});
|
||||
expect(logToManualBank(mergeLogs(older, newer))['skyr']!.kcal, 999);
|
||||
});
|
||||
|
||||
test('different foods union rather than replace', () {
|
||||
final a = manualBankToLog({'skyr': skyr()});
|
||||
final b = manualBankToLog({
|
||||
'kefir': FoodBankRecord(
|
||||
desc: 'Kefir',
|
||||
kcal: 60,
|
||||
proteinG: 3,
|
||||
carbsG: 4,
|
||||
fatG: 2,
|
||||
grams: 100,
|
||||
count: 0,
|
||||
editedAt: '2026-07-26T10:00:00.000Z',
|
||||
),
|
||||
});
|
||||
expect(logToManualBank(mergeLogs(a, b)).keys.toSet(), {'skyr', 'kefir'});
|
||||
});
|
||||
|
||||
test('a non-map body is skipped on read', () {
|
||||
final log = {
|
||||
'skyr': Record(
|
||||
id: 'skyr',
|
||||
fields: {
|
||||
'body': ('nope', budgetHlc(const {'t': ''})),
|
||||
},
|
||||
),
|
||||
};
|
||||
expect(logToManualBank(log), isEmpty);
|
||||
});
|
||||
|
||||
test('a tombstoned record is dropped on read', () {
|
||||
final log = {
|
||||
'skyr': Record(
|
||||
id: 'skyr',
|
||||
fields: {
|
||||
'body': (skyr().toJson(), budgetHlc(const {'t': ''})),
|
||||
},
|
||||
deleted: true,
|
||||
),
|
||||
};
|
||||
expect(logToManualBank(log), isEmpty);
|
||||
});
|
||||
|
||||
test('parses pushed wire content', () {
|
||||
final wire = encodeManualBankForPush(manualBankToLog({'skyr': skyr()}));
|
||||
expect(parseRemoteManualBank(wire).containsKey('skyr'), isTrue);
|
||||
});
|
||||
|
||||
test('non-object top level throws FormatException', () {
|
||||
expect(() => parseRemoteManualBank('[1,2,3]'), throwsFormatException);
|
||||
});
|
||||
|
||||
test('the wire shape matches the Python side', () {
|
||||
// Python uses the same `body` field name and the same normalized-name
|
||||
// record id; a rename on either side silently splits the two banks.
|
||||
final log = manualBankToLog({'skyr': skyr()});
|
||||
expect(log['skyr']!.id, 'skyr');
|
||||
expect(log['skyr']!.fields.keys.toList(), ['body']);
|
||||
});
|
||||
});
|
||||
|
||||
group('budget adapters', () {
|
||||
Map<String, dynamic> budgetRecord({
|
||||
int b = 2000,
|
||||
String t = '2026-06-22T08:00:00',
|
||||
double? w,
|
||||
}) => {'v': 2, 'b': b, 't': t, if (w != null) 'w': w};
|
||||
|
||||
group('budgetHlc', () {
|
||||
test('same record always yields the same Hlc', () {
|
||||
final record = budgetRecord();
|
||||
expect(budgetHlc(record), budgetHlc({...record}));
|
||||
});
|
||||
|
||||
test('malformed t still yields a valid Hlc', () {
|
||||
final record = budgetRecord(t: 'not-a-timestamp');
|
||||
expect(budgetHlc(record).wallTimeMs, 0);
|
||||
});
|
||||
|
||||
test('a later t yields a greater Hlc', () {
|
||||
final earlier = budgetRecord(t: '2020-01-01T00:00:00Z');
|
||||
final later = budgetRecord(t: '2030-01-01T00:00:00Z');
|
||||
expect(budgetHlc(later) > budgetHlc(earlier), isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('budgetToLog / logToBudget round trip', () {
|
||||
test('null record yields an empty log', () {
|
||||
expect(budgetToLog(null), isEmpty);
|
||||
});
|
||||
|
||||
test('round trip preserves the budget', () {
|
||||
final record = budgetRecord();
|
||||
final roundTripped = logToBudget(budgetToLog(record));
|
||||
expect(roundTripped, isNotNull);
|
||||
expect(roundTripped!['b'], 2000);
|
||||
});
|
||||
|
||||
test('weight never travels', () {
|
||||
// `w` is PC-local, so it must not enter the shared value map: the
|
||||
// phone rebuilds that map without it, and before this fix a winning
|
||||
// phone edit silently deleted the PC's stored weight -- and with it
|
||||
// the protein target. Matches Python's budget_to_log.
|
||||
final record = budgetRecord(w: 80);
|
||||
final roundTripped = logToBudget(budgetToLog(record));
|
||||
expect(roundTripped, isNotNull);
|
||||
expect(roundTripped!.containsKey('w'), isFalse);
|
||||
});
|
||||
|
||||
test('history becomes one field per date', () {
|
||||
final log = budgetToLog(budgetRecord(), _history);
|
||||
final fields = log[budgetRecordId]!.fields;
|
||||
expect(fields.containsKey('value'), isTrue);
|
||||
expect(fields['hist:1970-01-01']!.$1, 2200);
|
||||
expect(fields['hist:2026-07-26']!.$1, 2000);
|
||||
});
|
||||
|
||||
test('history round trips back to entries', () {
|
||||
final entries = logToHistory(budgetToLog(budgetRecord(), _history));
|
||||
expect(entries.map((e) => e.effectiveFrom).toList(), [
|
||||
'1970-01-01',
|
||||
'2026-07-26',
|
||||
]);
|
||||
expect(entries.map((e) => e.kcal).toList(), [2200, 2000]);
|
||||
});
|
||||
|
||||
test('no history round trips to nothing', () {
|
||||
expect(logToHistory(budgetToLog(budgetRecord())), isEmpty);
|
||||
});
|
||||
|
||||
test('an empty log has no history', () {
|
||||
expect(logToHistory(<String, Record>{}), isEmpty);
|
||||
});
|
||||
|
||||
test('non-history fields are ignored', () {
|
||||
final log = budgetToLog(budgetRecord());
|
||||
expect(logToHistory(log), isEmpty);
|
||||
});
|
||||
|
||||
test('a non-int history value is skipped', () {
|
||||
final log = {
|
||||
budgetRecordId: Record(
|
||||
id: budgetRecordId,
|
||||
fields: {
|
||||
'hist:2026-07-26': ('nonsense', budgetHlc(budgetRecord())),
|
||||
},
|
||||
),
|
||||
};
|
||||
expect(logToHistory(log), isEmpty);
|
||||
});
|
||||
|
||||
test('an unparsable edit time still yields a field', () {
|
||||
const broken = BudgetEntry(
|
||||
effectiveFrom: '2026-07-26',
|
||||
kcal: 2000,
|
||||
editedAt: 'not a timestamp',
|
||||
);
|
||||
final log = budgetToLog(budgetRecord(), [broken]);
|
||||
expect(
|
||||
log[budgetRecordId]!.fields.containsKey('hist:2026-07-26'),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('history survives a merge with a history-free peer', () {
|
||||
// The rollout guarantee: mergeRecord is per-field LWW over the
|
||||
// *union* of field names, so a peer that only pushes `value` leaves
|
||||
// `hist:*` untouched -- which is why this needed no coordinated
|
||||
// release. Mirrors the Python test of the same name.
|
||||
final ours = budgetToLog(budgetRecord(), _history);
|
||||
final legacy = {
|
||||
budgetRecordId: Record(
|
||||
id: budgetRecordId,
|
||||
fields: {
|
||||
'value': (
|
||||
{'v': 2, 'b': 2200},
|
||||
budgetHlc({'t': '2099-01-01T00:00:00Z'}),
|
||||
),
|
||||
},
|
||||
),
|
||||
};
|
||||
expect(logToHistory(mergeLogs(ours, legacy)), hasLength(2));
|
||||
});
|
||||
|
||||
test('the wire field names match the Python side exactly', () {
|
||||
// A rename on either side silently splits the two devices' history.
|
||||
expect(budgetHistoryFieldPrefix, 'hist:');
|
||||
expect(budgetRecordId, 'budget');
|
||||
});
|
||||
|
||||
test('round-tripped t reflects the winning Hlc', () {
|
||||
final record = budgetRecord();
|
||||
final roundTripped = logToBudget(budgetToLog(record));
|
||||
expect(roundTripped, isNotNull);
|
||||
expect(roundTripped!['t'], isNotEmpty);
|
||||
});
|
||||
|
||||
test('empty log has no budget', () {
|
||||
expect(logToBudget({}), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
group('parseRemoteBudget', () {
|
||||
test('parses pushed budget wire content', () {
|
||||
final record = budgetRecord();
|
||||
final pushed = encodeBudgetForPush(budgetToLog(record));
|
||||
final log = parseRemoteBudget(pushed);
|
||||
expect(log[budgetRecordId]!.id, budgetRecordId);
|
||||
});
|
||||
|
||||
test('empty object parses as empty log', () {
|
||||
expect(parseRemoteBudget('{}'), isEmpty);
|
||||
});
|
||||
|
||||
test('non-object top level throws FormatException', () {
|
||||
expect(() => parseRemoteBudget('[1, 2, 3]'), throwsFormatException);
|
||||
});
|
||||
|
||||
test('invalid JSON throws FormatException', () {
|
||||
expect(() => parseRemoteBudget('not json{{{'), throwsFormatException);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
139
app/test/services/sync_merge_wire_test.dart
Normal file
139
app/test/services/sync_merge_wire_test.dart
Normal file
@ -0,0 +1,139 @@
|
||||
// Table-driven mergeLogs() tests. `union by id` through `algebraic
|
||||
// properties` are the exact same assertions the pre-migration
|
||||
// `sync_merge.mergeLogs` had -- routed through `dayLogToLog ->
|
||||
// crdt_sync.mergeLogs -> logToDayLog` instead, to prove the migration
|
||||
// preserves the app's merge semantics exactly, mirroring
|
||||
// `test_sync_merge.py`'s equivalent Python-side proof.
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.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';
|
||||
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
FoodEntry _entry({
|
||||
String? id = 'id-1',
|
||||
String time = '2026-06-22T08:00:00',
|
||||
String desc = 'oatmeal',
|
||||
bool deleted = false,
|
||||
}) => FoodEntry(
|
||||
id: id,
|
||||
time: time,
|
||||
desc: desc,
|
||||
grams: 200,
|
||||
kcal: 300,
|
||||
proteinG: 10,
|
||||
carbsG: 50,
|
||||
fatG: 5,
|
||||
source: 'manual',
|
||||
deleted: deleted,
|
||||
);
|
||||
|
||||
DayLog _mergeDaylogs(DayLog a, DayLog b) =>
|
||||
logToDayLog(mergeLogs(dayLogToLog(a), dayLogToLog(b)));
|
||||
|
||||
const _history = [
|
||||
BudgetEntry(
|
||||
effectiveFrom: '1970-01-01',
|
||||
kcal: 2200,
|
||||
editedAt: '2026-07-13T21:15:09.000Z',
|
||||
),
|
||||
BudgetEntry(
|
||||
effectiveFrom: '2026-07-26',
|
||||
kcal: 2000,
|
||||
editedAt: '2026-07-26T10:00:00.000Z',
|
||||
),
|
||||
];
|
||||
|
||||
void main() {
|
||||
group('entryHlc', () {
|
||||
test('same entry always yields the same Hlc', () {
|
||||
expect(entryHlc(_entry()), entryHlc(_entry()));
|
||||
});
|
||||
|
||||
test('malformed time still yields a valid Hlc', () {
|
||||
expect(entryHlc(_entry(time: 'not-a-timestamp')).wallTimeMs, 0);
|
||||
});
|
||||
});
|
||||
group('legacyEntryId', () {
|
||||
test('same time and desc yields the same id', () {
|
||||
final a = _entry(time: '2026-06-20T08:00:00', desc: 'toast');
|
||||
final b = _entry(time: '2026-06-20T08:00:00', desc: 'toast');
|
||||
expect(legacyEntryId(a), legacyEntryId(b));
|
||||
});
|
||||
|
||||
test('different desc yields a different id', () {
|
||||
final a = _entry(time: '2026-06-20T08:00:00', desc: 'toast');
|
||||
final b = _entry(time: '2026-06-20T08:00:00', desc: 'eggs');
|
||||
expect(legacyEntryId(a), isNot(legacyEntryId(b)));
|
||||
});
|
||||
});
|
||||
group('entry <-> Record round trip', () {
|
||||
test('round trip preserves all fields', () {
|
||||
final entry = _entry(id: 'x');
|
||||
final roundTripped = recordToEntry(entryToRecord(entry));
|
||||
expect(roundTripped.toSyncJson(), entry.toSyncJson());
|
||||
});
|
||||
|
||||
test('round trip of a deleted entry preserves the tombstone', () {
|
||||
final entry = _entry(id: 'x', deleted: true);
|
||||
expect(recordToEntry(entryToRecord(entry)).deleted, isTrue);
|
||||
});
|
||||
|
||||
test('legacy entry gets a derived id on round trip', () {
|
||||
final entry = _entry(
|
||||
id: null,
|
||||
time: '2026-06-20T08:00:00',
|
||||
desc: 'toast',
|
||||
);
|
||||
final roundTripped = recordToEntry(entryToRecord(entry));
|
||||
expect(roundTripped.id, legacyEntryId(entry));
|
||||
});
|
||||
|
||||
test('a Record with no body field falls back to an empty body', () {
|
||||
const record = Record(id: 'x', fields: {});
|
||||
final entry = recordToEntry(record);
|
||||
expect(entry.id, 'x');
|
||||
expect(entry.desc, isEmpty);
|
||||
});
|
||||
});
|
||||
group('parseRemoteLog', () {
|
||||
test('parses new-format wire content', () {
|
||||
final entry = _entry(id: 'x');
|
||||
final pushed = encodeLogForPush({'x': entryToRecord(entry)});
|
||||
final log = parseRemoteLog(pushed);
|
||||
expect(log['x']!.id, 'x');
|
||||
});
|
||||
|
||||
test('parses old DayLog format for backward compatibility', () {
|
||||
final entry = _entry(id: 'x');
|
||||
final oldFormat = jsonEncode({
|
||||
'2026-06-22': [entry.toSyncJson()],
|
||||
});
|
||||
final log = parseRemoteLog(oldFormat);
|
||||
expect(log['x']!.id, 'x');
|
||||
});
|
||||
|
||||
test('empty object parses as empty log', () {
|
||||
expect(parseRemoteLog('{}'), isEmpty);
|
||||
});
|
||||
|
||||
test('non-object top level throws FormatException', () {
|
||||
expect(() => parseRemoteLog('[1, 2, 3]'), throwsFormatException);
|
||||
});
|
||||
|
||||
test('old-format day not a list throws FormatException', () {
|
||||
expect(
|
||||
() => parseRemoteLog('{"2026-06-22": "not-a-list"}'),
|
||||
throwsFormatException,
|
||||
);
|
||||
});
|
||||
|
||||
test('invalid JSON throws FormatException', () {
|
||||
expect(() => parseRemoteLog('not json{{{'), throwsFormatException);
|
||||
});
|
||||
});
|
||||
}
|
||||
127
app/test/services/sync_service_budget_test.dart
Normal file
127
app/test/services/sync_service_budget_test.dart
Normal file
@ -0,0 +1,127 @@
|
||||
// Mirrors `test_sync.py`'s `TestRunSync` and `TestSyncBudget` cases
|
||||
// (own-id-skip, no-prior-push, non-object payload, corrupt JSON, remote
|
||||
// merge, food bank rebuild, budget last-writer-wins), plus one Dart-specific
|
||||
// that has no PC-side equivalent.
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'sync_service_test_support.dart';
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_sync_test_');
|
||||
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
|
||||
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
|
||||
BudgetHistoryService.resetForTesting(
|
||||
store: FileDocumentStore(tempDir),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
LogStorageService.resetForTesting();
|
||||
FoodBankService.resetForTesting();
|
||||
AppSettingsService.resetForTesting();
|
||||
BudgetHistoryService.resetForTesting();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
group('budget sync', () {
|
||||
test(
|
||||
'pushes the local budget when no other devices have synced',
|
||||
() async {
|
||||
await AppSettingsService.instance.saveDailyKcalGoal(2000);
|
||||
final fake = FakeGitHub();
|
||||
await runSync(fake.buildClient());
|
||||
|
||||
expect(
|
||||
fake.putsByPath.containsKey(
|
||||
'diet-guard-sync/devices/phone/budget.json',
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('remote-only budget is adopted locally', () async {
|
||||
final remoteJson = remoteBudgetJson(
|
||||
kcal: 1800,
|
||||
t: '2026-01-01T09:00:00',
|
||||
);
|
||||
final fake = FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: {'diet-guard-sync/devices/pc/budget.json': remoteJson},
|
||||
);
|
||||
await runSync(fake.buildClient());
|
||||
expect(AppSettingsService.dailyKcalGoal, 1800);
|
||||
});
|
||||
|
||||
test('a local edit later than a remote edit wins', () async {
|
||||
await AppSettingsService.instance.saveDailyKcalGoal(1500); // now
|
||||
final remoteJson = remoteBudgetJson(
|
||||
kcal: 1800,
|
||||
t: '2020-01-01T09:00:00',
|
||||
);
|
||||
final fake = FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: {'diet-guard-sync/devices/pc/budget.json': remoteJson},
|
||||
);
|
||||
await runSync(fake.buildClient());
|
||||
expect(AppSettingsService.dailyKcalGoal, 1500);
|
||||
});
|
||||
|
||||
test('a remote edit later than a local edit wins', () async {
|
||||
await AppSettingsService.instance.saveDailyKcalGoal(1500); // now
|
||||
final remoteJson = remoteBudgetJson(
|
||||
kcal: 1800,
|
||||
t: '2999-01-01T09:00:00',
|
||||
);
|
||||
final fake = FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: {'diet-guard-sync/devices/pc/budget.json': remoteJson},
|
||||
);
|
||||
await runSync(fake.buildClient());
|
||||
expect(AppSettingsService.dailyKcalGoal, 1800);
|
||||
});
|
||||
|
||||
test('a malformed remote budget is skipped, not a crash', () async {
|
||||
await AppSettingsService.instance.saveDailyKcalGoal(2000);
|
||||
final fake = FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: const {
|
||||
'diet-guard-sync/devices/pc/budget.json': '{not valid json',
|
||||
},
|
||||
);
|
||||
await runSync(fake.buildClient());
|
||||
expect(AppSettingsService.dailyKcalGoal, 2000);
|
||||
});
|
||||
|
||||
test(
|
||||
'a fresh install with no budget ever set contributes nothing',
|
||||
() async {
|
||||
final fake = FakeGitHub();
|
||||
await runSync(fake.buildClient());
|
||||
|
||||
final pushed =
|
||||
fake.putsByPath['diet-guard-sync/devices/phone/budget.json']!;
|
||||
final pushedText = utf8.decode(
|
||||
base64.decode(pushed['content'] as String),
|
||||
);
|
||||
expect(jsonDecode(pushedText), isEmpty);
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@ -6,118 +6,20 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/models/nutrition.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/document_store_io.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||
import 'package:diet_guard_app/services/sync_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
|
||||
/// Builds the wire text a remote device would push for a given budget edit.
|
||||
String _remoteBudgetJson({required int kcal, required String t}) {
|
||||
final record = <String, dynamic>{'v': 2, 'b': kcal, 't': t};
|
||||
final log = budgetToLog(record);
|
||||
return jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
});
|
||||
}
|
||||
|
||||
const _manual = Nutrition(
|
||||
kcal: 200,
|
||||
proteinG: 10,
|
||||
carbsG: 20,
|
||||
fatG: 5,
|
||||
grams: 100,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
/// A tiny in-memory stand-in for the GitHub Contents API, scoped to exactly
|
||||
/// the calls [runSync] makes via crdt_sync's [GitHubClient]: list `devices`,
|
||||
/// get a device's file text (which crdt_sync also uses internally to
|
||||
/// resolve this device's own existing sha before a push), and put this
|
||||
/// device's file text.
|
||||
class _FakeGitHub {
|
||||
_FakeGitHub({this.deviceDirs = const [], Map<String, String>? files})
|
||||
: files = {...?files};
|
||||
|
||||
final List<String> deviceDirs;
|
||||
final Map<String, String> files;
|
||||
|
||||
/// Every `diet-guard-sync/devices/<id>/food_log.json` path this fake
|
||||
/// actually served a file-content GET for.
|
||||
final List<String> fileGets = [];
|
||||
|
||||
/// Every PUT this fake received, decoded.
|
||||
final List<Map<String, dynamic>> puts = [];
|
||||
|
||||
/// Same PUTs, keyed by the repo-relative path they targeted -- lets a
|
||||
/// test pick out the food-log push from the budget push, now that a
|
||||
/// sync tick does both.
|
||||
final Map<String, Map<String, dynamic>> putsByPath = {};
|
||||
|
||||
GitHubClient buildClient() => GitHubClient(
|
||||
owner: 'o',
|
||||
repo: 'r',
|
||||
token: 't',
|
||||
httpClient: MockClient(_handle),
|
||||
);
|
||||
|
||||
Future<http.Response> _handle(http.Request req) async {
|
||||
if (req.url.path == '/repos/o/r') {
|
||||
// Repo-existence probe: crdt_sync's GitHubClient calls this to
|
||||
// disambiguate "path unused yet" (still 404, but a real repo) from
|
||||
// "repo missing/inaccessible" whenever a content-path GET 404s.
|
||||
return http.Response('{}', 200);
|
||||
}
|
||||
final path = req.url.path.replaceFirst('/repos/o/r/contents/', '');
|
||||
if (req.method == 'PUT') {
|
||||
final body = jsonDecode(req.body) as Map<String, dynamic>;
|
||||
puts.add(body);
|
||||
putsByPath[path] = body;
|
||||
return http.Response('{}', 200);
|
||||
}
|
||||
if (path == 'diet-guard-sync/devices') {
|
||||
return http.Response(
|
||||
jsonEncode([
|
||||
for (final d in deviceDirs)
|
||||
{
|
||||
'type': 'dir',
|
||||
'name': d,
|
||||
'path': 'diet-guard-sync/devices/$d',
|
||||
'sha': 'd-$d',
|
||||
},
|
||||
]),
|
||||
200,
|
||||
);
|
||||
}
|
||||
if (!files.containsKey(path)) return http.Response('', 404);
|
||||
fileGets.add(path);
|
||||
final content = base64.encode(utf8.encode(files[path]!));
|
||||
// Real GitHub always returns `sha` alongside `content` for a
|
||||
// get-file-contents call -- crdt_sync's GitHubClient reads it back to
|
||||
// resolve this device's own existing sha before a push.
|
||||
final segments = path.split('/');
|
||||
final sha =
|
||||
segments.length == 4 &&
|
||||
segments[0] == 'diet-guard-sync' &&
|
||||
segments[1] == 'devices'
|
||||
? 'f-${segments[2]}'
|
||||
: null;
|
||||
return http.Response(
|
||||
jsonEncode({'content': content, if (sha != null) 'sha': sha}),
|
||||
200,
|
||||
);
|
||||
}
|
||||
}
|
||||
import 'sync_service_test_support.dart';
|
||||
|
||||
void main() {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
@ -139,8 +41,8 @@ void main() {
|
||||
});
|
||||
|
||||
test('pushes the local log when no other devices have synced', () async {
|
||||
await LogStorageService.instance.logMeal('oatmeal', _manual);
|
||||
final fake = _FakeGitHub();
|
||||
await LogStorageService.instance.logMeal('oatmeal', manualNutrition);
|
||||
final fake = FakeGitHub();
|
||||
final merged = await runSync(fake.buildClient());
|
||||
|
||||
expect(merged.values.expand((e) => e).length, 1);
|
||||
@ -150,9 +52,8 @@ void main() {
|
||||
// "seen rev X" against a log it never received.
|
||||
expect(fake.puts, hasLength(5));
|
||||
});
|
||||
|
||||
test("skips its own device id ('phone') when listing", () async {
|
||||
final fake = _FakeGitHub(
|
||||
final fake = FakeGitHub(
|
||||
deviceDirs: const ['pc', 'phone'],
|
||||
files: const {
|
||||
'diet-guard-sync/devices/pc/food_log.json': '{}',
|
||||
@ -167,24 +68,21 @@ void main() {
|
||||
'diet-guard-sync/devices/pc/budget.json',
|
||||
]);
|
||||
});
|
||||
|
||||
test('skips a device with no pushed file yet', () async {
|
||||
final fake = _FakeGitHub(deviceDirs: const ['pc']);
|
||||
final fake = FakeGitHub(deviceDirs: const ['pc']);
|
||||
final merged = await runSync(fake.buildClient());
|
||||
expect(merged, isEmpty);
|
||||
});
|
||||
|
||||
test('ignores a device whose pushed file is not a JSON object', () async {
|
||||
final fake = _FakeGitHub(
|
||||
final fake = FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: const {'diet-guard-sync/devices/pc/food_log.json': '[]'},
|
||||
);
|
||||
final merged = await runSync(fake.buildClient());
|
||||
expect(merged, isEmpty);
|
||||
});
|
||||
|
||||
test('skips a device whose pushed file is corrupt json', () async {
|
||||
final fake = _FakeGitHub(
|
||||
final fake = FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: const {
|
||||
'diet-guard-sync/devices/pc/food_log.json': '{not valid json',
|
||||
@ -193,7 +91,6 @@ void main() {
|
||||
final merged = await runSync(fake.buildClient());
|
||||
expect(merged, isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
"merges in a remote device's entries (old pre-migration format)",
|
||||
() async {
|
||||
@ -212,7 +109,7 @@ void main() {
|
||||
},
|
||||
],
|
||||
});
|
||||
final fake = _FakeGitHub(
|
||||
final fake = FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: {'diet-guard-sync/devices/pc/food_log.json': remoteLog},
|
||||
);
|
||||
@ -221,7 +118,6 @@ void main() {
|
||||
expect(descs, contains('pc meal'));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
"merges in a remote device's entries (new Record-based format)",
|
||||
() async {
|
||||
@ -247,7 +143,7 @@ void main() {
|
||||
},
|
||||
).toJson(),
|
||||
});
|
||||
final fake = _FakeGitHub(
|
||||
final fake = FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: {'diet-guard-sync/devices/pc/food_log.json': remoteLog},
|
||||
);
|
||||
@ -256,22 +152,20 @@ void main() {
|
||||
expect(descs, contains('pc meal'));
|
||||
},
|
||||
);
|
||||
|
||||
test('rebuilds the food bank after merge', () async {
|
||||
await LogStorageService.instance.logMeal('oatmeal', _manual);
|
||||
final fake = _FakeGitHub();
|
||||
await LogStorageService.instance.logMeal('oatmeal', manualNutrition);
|
||||
final fake = FakeGitHub();
|
||||
await runSync(fake.buildClient());
|
||||
|
||||
final bank = await FoodBankService.instance.readBank();
|
||||
expect(bank.containsKey('oatmeal'), isTrue);
|
||||
});
|
||||
|
||||
test('pushes a payload without hmac', () async {
|
||||
await LogStorageService.instance.logMeal(
|
||||
'oatmeal',
|
||||
_manual,
|
||||
manualNutrition,
|
||||
);
|
||||
final fake = _FakeGitHub();
|
||||
final fake = FakeGitHub();
|
||||
await runSync(fake.buildClient());
|
||||
|
||||
final pushed =
|
||||
@ -279,10 +173,9 @@ void main() {
|
||||
final pushedText = utf8.decode(base64.decode(pushed['content'] as String));
|
||||
expect(pushedText, isNot(contains('hmac')));
|
||||
});
|
||||
|
||||
test('pushes in the new Record-based wire format', () async {
|
||||
await LogStorageService.instance.logMeal('oatmeal', _manual);
|
||||
final fake = _FakeGitHub();
|
||||
await LogStorageService.instance.logMeal('oatmeal', manualNutrition);
|
||||
final fake = FakeGitHub();
|
||||
await runSync(fake.buildClient());
|
||||
|
||||
final pushed =
|
||||
@ -293,9 +186,8 @@ void main() {
|
||||
expect(record, containsPair('id', isA<String>()));
|
||||
expect(record, contains('fields'));
|
||||
});
|
||||
|
||||
test("reuses this device's existing sha when it has pushed before", () async {
|
||||
final fake = _FakeGitHub(
|
||||
final fake = FakeGitHub(
|
||||
files: const {'diet-guard-sync/devices/phone/food_log.json': '{}'},
|
||||
);
|
||||
await runSync(fake.buildClient());
|
||||
@ -304,91 +196,4 @@ void main() {
|
||||
'f-phone',
|
||||
);
|
||||
});
|
||||
|
||||
group('budget sync', () {
|
||||
test(
|
||||
'pushes the local budget when no other devices have synced',
|
||||
() async {
|
||||
await AppSettingsService.instance.saveDailyKcalGoal(2000);
|
||||
final fake = _FakeGitHub();
|
||||
await runSync(fake.buildClient());
|
||||
|
||||
expect(
|
||||
fake.putsByPath.containsKey(
|
||||
'diet-guard-sync/devices/phone/budget.json',
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('remote-only budget is adopted locally', () async {
|
||||
final remoteJson = _remoteBudgetJson(
|
||||
kcal: 1800,
|
||||
t: '2026-01-01T09:00:00',
|
||||
);
|
||||
final fake = _FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: {'diet-guard-sync/devices/pc/budget.json': remoteJson},
|
||||
);
|
||||
await runSync(fake.buildClient());
|
||||
expect(AppSettingsService.dailyKcalGoal, 1800);
|
||||
});
|
||||
|
||||
test('a local edit later than a remote edit wins', () async {
|
||||
await AppSettingsService.instance.saveDailyKcalGoal(1500); // now
|
||||
final remoteJson = _remoteBudgetJson(
|
||||
kcal: 1800,
|
||||
t: '2020-01-01T09:00:00',
|
||||
);
|
||||
final fake = _FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: {'diet-guard-sync/devices/pc/budget.json': remoteJson},
|
||||
);
|
||||
await runSync(fake.buildClient());
|
||||
expect(AppSettingsService.dailyKcalGoal, 1500);
|
||||
});
|
||||
|
||||
test('a remote edit later than a local edit wins', () async {
|
||||
await AppSettingsService.instance.saveDailyKcalGoal(1500); // now
|
||||
final remoteJson = _remoteBudgetJson(
|
||||
kcal: 1800,
|
||||
t: '2999-01-01T09:00:00',
|
||||
);
|
||||
final fake = _FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: {'diet-guard-sync/devices/pc/budget.json': remoteJson},
|
||||
);
|
||||
await runSync(fake.buildClient());
|
||||
expect(AppSettingsService.dailyKcalGoal, 1800);
|
||||
});
|
||||
|
||||
test('a malformed remote budget is skipped, not a crash', () async {
|
||||
await AppSettingsService.instance.saveDailyKcalGoal(2000);
|
||||
final fake = _FakeGitHub(
|
||||
deviceDirs: const ['pc'],
|
||||
files: const {
|
||||
'diet-guard-sync/devices/pc/budget.json': '{not valid json',
|
||||
},
|
||||
);
|
||||
await runSync(fake.buildClient());
|
||||
expect(AppSettingsService.dailyKcalGoal, 2000);
|
||||
});
|
||||
|
||||
test(
|
||||
'a fresh install with no budget ever set contributes nothing',
|
||||
() async {
|
||||
final fake = _FakeGitHub();
|
||||
await runSync(fake.buildClient());
|
||||
|
||||
final pushed =
|
||||
fake.putsByPath['diet-guard-sync/devices/phone/budget.json']!;
|
||||
final pushedText = utf8.decode(
|
||||
base64.decode(pushed['content'] as String),
|
||||
);
|
||||
expect(jsonDecode(pushedText), isEmpty);
|
||||
expect(AppSettingsService.dailyKcalGoal, 2200);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
121
app/test/services/sync_service_test_support.dart
Normal file
121
app/test/services/sync_service_test_support.dart
Normal file
@ -0,0 +1,121 @@
|
||||
// Shared fixtures for the sync_service test siblings.
|
||||
//
|
||||
// Split out of `sync_service_test.dart` for the repo's 250-line cap: these
|
||||
// helpers are ~100 lines that both siblings need, so duplicating them per
|
||||
// file would put each back over the cap on its own.
|
||||
//
|
||||
// The names are public because they now cross a file boundary; a `_` prefix
|
||||
// is library-private in Dart, so the siblings could not see them.
|
||||
|
||||
// Mirrors `test_sync.py`'s `TestRunSync` and `TestSyncBudget` cases
|
||||
// (own-id-skip, no-prior-push, non-object payload, corrupt JSON, remote
|
||||
// merge, food bank rebuild, budget last-writer-wins), plus one Dart-specific
|
||||
// that has no PC-side equivalent.
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/models/nutrition.dart';
|
||||
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||
import 'package:diet_guard_app/services/sync_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
|
||||
/// Builds the wire text a remote device would push for a given budget edit.
|
||||
String remoteBudgetJson({required int kcal, required String t}) {
|
||||
final record = <String, dynamic>{'v': 2, 'b': kcal, 't': t};
|
||||
final log = budgetToLog(record);
|
||||
return jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
});
|
||||
}
|
||||
|
||||
/// A plain manual-source nutrition value used across the sync fixtures.
|
||||
const manualNutrition = Nutrition(
|
||||
kcal: 200,
|
||||
proteinG: 10,
|
||||
carbsG: 20,
|
||||
fatG: 5,
|
||||
grams: 100,
|
||||
source: 'manual',
|
||||
);
|
||||
|
||||
/// A tiny in-memory stand-in for the GitHub Contents API, scoped to exactly
|
||||
/// the calls [runSync] makes via crdt_sync's [GitHubClient]: list `devices`,
|
||||
/// get a device's file text (which crdt_sync also uses internally to
|
||||
/// resolve this device's own existing sha before a push), and put this
|
||||
/// device's file text.
|
||||
class FakeGitHub {
|
||||
FakeGitHub({this.deviceDirs = const [], Map<String, String>? files})
|
||||
: files = {...?files};
|
||||
|
||||
final List<String> deviceDirs;
|
||||
final Map<String, String> files;
|
||||
|
||||
/// Every `diet-guard-sync/devices/<id>/food_log.json` path this fake
|
||||
/// actually served a file-content GET for.
|
||||
final List<String> fileGets = [];
|
||||
|
||||
/// Every PUT this fake received, decoded.
|
||||
final List<Map<String, dynamic>> puts = [];
|
||||
|
||||
/// Same PUTs, keyed by the repo-relative path they targeted -- lets a
|
||||
/// test pick out the food-log push from the budget push, now that a
|
||||
/// sync tick does both.
|
||||
final Map<String, Map<String, dynamic>> putsByPath = {};
|
||||
|
||||
GitHubClient buildClient() => GitHubClient(
|
||||
owner: 'o',
|
||||
repo: 'r',
|
||||
token: 't',
|
||||
httpClient: MockClient(_handle),
|
||||
);
|
||||
|
||||
Future<http.Response> _handle(http.Request req) async {
|
||||
if (req.url.path == '/repos/o/r') {
|
||||
// Repo-existence probe: crdt_sync's GitHubClient calls this to
|
||||
// disambiguate "path unused yet" (still 404, but a real repo) from
|
||||
// "repo missing/inaccessible" whenever a content-path GET 404s.
|
||||
return http.Response('{}', 200);
|
||||
}
|
||||
final path = req.url.path.replaceFirst('/repos/o/r/contents/', '');
|
||||
if (req.method == 'PUT') {
|
||||
final body = jsonDecode(req.body) as Map<String, dynamic>;
|
||||
puts.add(body);
|
||||
putsByPath[path] = body;
|
||||
return http.Response('{}', 200);
|
||||
}
|
||||
if (path == 'diet-guard-sync/devices') {
|
||||
return http.Response(
|
||||
jsonEncode([
|
||||
for (final d in deviceDirs)
|
||||
{
|
||||
'type': 'dir',
|
||||
'name': d,
|
||||
'path': 'diet-guard-sync/devices/$d',
|
||||
'sha': 'd-$d',
|
||||
},
|
||||
]),
|
||||
200,
|
||||
);
|
||||
}
|
||||
if (!files.containsKey(path)) return http.Response('', 404);
|
||||
fileGets.add(path);
|
||||
final content = base64.encode(utf8.encode(files[path]!));
|
||||
// Real GitHub always returns `sha` alongside `content` for a
|
||||
// get-file-contents call -- crdt_sync's GitHubClient reads it back to
|
||||
// resolve this device's own existing sha before a push.
|
||||
final segments = path.split('/');
|
||||
final sha =
|
||||
segments.length == 4 &&
|
||||
segments[0] == 'diet-guard-sync' &&
|
||||
segments[1] == 'devices'
|
||||
? 'f-${segments[2]}'
|
||||
: null;
|
||||
return http.Response(
|
||||
jsonEncode({'content': content, 'sha': ?sha}),
|
||||
200,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -10,7 +10,7 @@ library;
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||
import 'package:diet_guard_app/services/sync_state_factory_io.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
@ -1,28 +1,9 @@
|
||||
import 'package:diet_guard_app/models/day_status.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/day_status_calendar.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
// The real app theme, not a bare default MaterialApp -- the widget under
|
||||
// test reads its colors from Theme.of(context), so asserting against the
|
||||
// same theme the app actually ships is what makes these assertions mean
|
||||
// anything (a bare MaterialApp's own default colors would be arbitrary).
|
||||
final _theme = buildAppTheme();
|
||||
final _statusColors = _theme.extension<AppStatusColors>()!;
|
||||
|
||||
Widget _wrap(Widget child) => MaterialApp(
|
||||
theme: _theme,
|
||||
home: Scaffold(body: child),
|
||||
);
|
||||
|
||||
Color _colorOfDay(WidgetTester tester, String day) {
|
||||
final container = tester.widget<Container>(
|
||||
find.ancestor(of: find.text(day), matching: find.byType(Container)).first,
|
||||
);
|
||||
final decoration = container.decoration! as BoxDecoration;
|
||||
return decoration.color!;
|
||||
}
|
||||
import 'day_status_calendar_test_support.dart';
|
||||
|
||||
void main() {
|
||||
group('DayStatusCalendar', () {
|
||||
@ -31,7 +12,7 @@ void main() {
|
||||
|
||||
testWidgets('shows month and year in header', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {},
|
||||
month: june2026,
|
||||
@ -46,7 +27,7 @@ void main() {
|
||||
|
||||
testWidgets('shows day-of-week headers', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {},
|
||||
month: june2026,
|
||||
@ -63,7 +44,7 @@ void main() {
|
||||
testWidgets('calls onPrevMonth when left arrow tapped', (tester) async {
|
||||
var called = false;
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {},
|
||||
month: june2026,
|
||||
@ -80,7 +61,7 @@ void main() {
|
||||
testWidgets('calls onNextMonth when right arrow tapped', (tester) async {
|
||||
var called = false;
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {},
|
||||
month: june2026,
|
||||
@ -96,7 +77,7 @@ void main() {
|
||||
|
||||
testWidgets('colors a green day', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {'2026-06-15': DayStatus.green},
|
||||
month: june2026,
|
||||
@ -106,12 +87,12 @@ void main() {
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(_colorOfDay(tester, '15'), _statusColors.success);
|
||||
expect(colorOfDay(tester, '15'), statusColors.success);
|
||||
});
|
||||
|
||||
testWidgets('colors a yellow day', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {'2026-06-15': DayStatus.yellow},
|
||||
month: june2026,
|
||||
@ -121,12 +102,12 @@ void main() {
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(_colorOfDay(tester, '15'), _statusColors.warning);
|
||||
expect(colorOfDay(tester, '15'), statusColors.warning);
|
||||
});
|
||||
|
||||
testWidgets('colors a red day', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {'2026-06-15': DayStatus.red},
|
||||
month: june2026,
|
||||
@ -136,14 +117,14 @@ void main() {
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(_colorOfDay(tester, '15'), _theme.colorScheme.error);
|
||||
expect(colorOfDay(tester, '15'), appTheme.colorScheme.error);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'a past day absent from statusByDate renders black (not logged)',
|
||||
(tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {},
|
||||
month: june2026,
|
||||
@ -153,7 +134,7 @@ void main() {
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(_colorOfDay(tester, '15'), _theme.colorScheme.surface);
|
||||
expect(colorOfDay(tester, '15'), appTheme.colorScheme.surface);
|
||||
},
|
||||
);
|
||||
|
||||
@ -161,7 +142,7 @@ void main() {
|
||||
'a future day renders neutrally, never as a false not-logged cell',
|
||||
(tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {},
|
||||
month: june2026,
|
||||
@ -173,17 +154,17 @@ void main() {
|
||||
);
|
||||
// Day 25 is after the reference "today" of June 10.
|
||||
expect(
|
||||
_colorOfDay(tester, '25'),
|
||||
_theme.colorScheme.surfaceContainerHigh,
|
||||
colorOfDay(tester, '25'),
|
||||
appTheme.colorScheme.surfaceContainerHigh,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets("today itself is classified, not treated as future", (
|
||||
testWidgets('today itself is classified, not treated as future', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {'2026-06-20': DayStatus.red},
|
||||
month: june2026,
|
||||
@ -193,7 +174,7 @@ void main() {
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(_colorOfDay(tester, '20'), _theme.colorScheme.error);
|
||||
expect(colorOfDay(tester, '20'), appTheme.colorScheme.error);
|
||||
});
|
||||
|
||||
testWidgets('renders a month starting on Sunday correctly', (
|
||||
@ -201,11 +182,11 @@ void main() {
|
||||
) async {
|
||||
final sep2026 = DateTime(2026, 9);
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {},
|
||||
month: sep2026,
|
||||
today: DateTime(2026, 9, 1),
|
||||
today: DateTime(2026, 9),
|
||||
onPrevMonth: () {},
|
||||
onNextMonth: () {},
|
||||
),
|
||||
@ -219,7 +200,7 @@ void main() {
|
||||
) async {
|
||||
DateTime? selected;
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {'2026-06-15': DayStatus.green},
|
||||
month: june2026,
|
||||
@ -238,7 +219,7 @@ void main() {
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
wrapInApp(
|
||||
DayStatusCalendar(
|
||||
statusByDate: const {},
|
||||
month: june2026,
|
||||
|
||||
33
app/test/widgets/day_status_calendar_test_support.dart
Normal file
33
app/test/widgets/day_status_calendar_test_support.dart
Normal file
@ -0,0 +1,33 @@
|
||||
// Shared fixtures for the day_status_calendar widget tests.
|
||||
//
|
||||
// Split out of `day_status_calendar_test.dart` for the repo's 250-line cap.
|
||||
// Public because the names now cross a file boundary -- a leading underscore
|
||||
// is library-private in Dart.
|
||||
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
// The real app theme, not a bare default MaterialApp -- the widget under
|
||||
// test reads its colors from Theme.of(context), so asserting against the
|
||||
// same theme the app actually ships is what makes these assertions mean
|
||||
// anything (a bare MaterialApp's own default colors would be arbitrary).
|
||||
/// The real app theme the widget under test reads its colors from.
|
||||
final ThemeData appTheme = buildAppTheme();
|
||||
/// The app's status-color extension, for asserting per-day cell colors.
|
||||
final AppStatusColors statusColors = appTheme.extension<AppStatusColors>()!;
|
||||
|
||||
/// Wraps [child] in a MaterialApp carrying the real app theme.
|
||||
Widget wrapInApp(Widget child) => MaterialApp(
|
||||
theme: appTheme,
|
||||
home: Scaffold(body: child),
|
||||
);
|
||||
|
||||
/// Returns the background color of the calendar cell showing [day].
|
||||
Color colorOfDay(WidgetTester tester, String day) {
|
||||
final container = tester.widget<Container>(
|
||||
find.ancestor(of: find.text(day), matching: find.byType(Container)).first,
|
||||
);
|
||||
final decoration = container.decoration! as BoxDecoration;
|
||||
return decoration.color!;
|
||||
}
|
||||
@ -1,14 +0,0 @@
|
||||
[Unit]
|
||||
Description=Periodically sync the Diet Guard log with other devices
|
||||
|
||||
[Timer]
|
||||
# Every 15 minutes -- matches the phone app's WorkManager periodic sync (15
|
||||
# min is also Android's WorkManager periodic floor), so both sides converge
|
||||
# on roughly the same cadence. Persistent catches a run missed while the
|
||||
# machine was suspended; OnCalendar re-arms every period regardless (see
|
||||
# diet-guard-gate.timer's comment for why OnCalendar over OnBootSec here too).
|
||||
OnCalendar=*-*-* *:00/15:00
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@ -38,14 +38,12 @@ boundaries and the period edges are testable with synthetic data.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
import enum
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from diet_guard._daystatus import OVER_BUDGET_YELLOW_CEILING, day_total_kcal
|
||||
from diet_guard._state import now_local
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from diet_guard._budget_history import BudgetSchedule
|
||||
@ -118,30 +116,6 @@ def band_for(avg_kcal: float, avg_budget: float) -> AverageBand:
|
||||
return AverageBand.VERY_OVER
|
||||
|
||||
|
||||
def last_complete_day(today: date) -> date:
|
||||
"""Return the last day whose log is finished: the day before ``today``."""
|
||||
return today - timedelta(days=1)
|
||||
|
||||
|
||||
def week_bounds(day: date) -> tuple[date, date]:
|
||||
"""Return the Monday and Sunday of the ISO week containing ``day``."""
|
||||
monday = day - timedelta(days=day.weekday())
|
||||
return monday, monday + timedelta(days=_DAYS_PER_WEEK - 1)
|
||||
|
||||
|
||||
def month_bounds(day: date) -> tuple[date, date]:
|
||||
"""Return the first and last dates of ``day``'s calendar month."""
|
||||
last = calendar.monthrange(day.year, day.month)[1]
|
||||
return day.replace(day=1), day.replace(day=last)
|
||||
|
||||
|
||||
def _shift_months(day: date, months: int) -> date:
|
||||
"""Return the first of the month ``months`` before ``day``'s month."""
|
||||
index = day.year * _MONTHS_PER_YEAR + (day.month - 1) - months
|
||||
year, month = divmod(index, _MONTHS_PER_YEAR)
|
||||
return date(year, month + 1, 1)
|
||||
|
||||
|
||||
def period_average(
|
||||
log: DayLog,
|
||||
*,
|
||||
@ -194,105 +168,3 @@ def period_average(
|
||||
avg_budget=avg_budget,
|
||||
band=band_for(avg_kcal, avg_budget),
|
||||
)
|
||||
|
||||
|
||||
def _resolve_today(today: date | None) -> date:
|
||||
"""Return ``today`` or the real current local date when it is None."""
|
||||
return today if today is not None else now_local().date()
|
||||
|
||||
|
||||
def _capped(
|
||||
log: DayLog,
|
||||
schedule: BudgetSchedule,
|
||||
bounds: tuple[date, date],
|
||||
ref: date,
|
||||
) -> PeriodAverage:
|
||||
"""Average ``bounds``, truncated so it never includes ``ref`` itself.
|
||||
|
||||
The single place the "today is excluded" rule is applied, so a caller
|
||||
cannot construct a period that half-counts an unfinished day.
|
||||
"""
|
||||
start, end = bounds
|
||||
return period_average(
|
||||
log,
|
||||
schedule=schedule,
|
||||
start=start,
|
||||
end=min(end, last_complete_day(ref)),
|
||||
)
|
||||
|
||||
|
||||
def weekly_average(
|
||||
log: DayLog,
|
||||
*,
|
||||
schedule: BudgetSchedule,
|
||||
weeks_ago: int = 0,
|
||||
today: date | None = None,
|
||||
) -> PeriodAverage:
|
||||
"""Return the average for an ISO week, ``weeks_ago`` weeks back.
|
||||
|
||||
Args:
|
||||
log: A filtered log (see :func:`period_average`).
|
||||
schedule: Resolves each day's budget.
|
||||
weeks_ago: 0 for the current week (through yesterday), 1 for the
|
||||
previous complete week, and so on.
|
||||
today: The reference "today"; defaults to the real current date.
|
||||
|
||||
Returns:
|
||||
That week's :class:`PeriodAverage`.
|
||||
"""
|
||||
ref = _resolve_today(today)
|
||||
anchor = ref - timedelta(weeks=weeks_ago)
|
||||
return _capped(log, schedule, week_bounds(anchor), ref)
|
||||
|
||||
|
||||
def monthly_average(
|
||||
log: DayLog,
|
||||
*,
|
||||
schedule: BudgetSchedule,
|
||||
months_ago: int = 0,
|
||||
today: date | None = None,
|
||||
) -> PeriodAverage:
|
||||
"""Return the average for a calendar month, ``months_ago`` months back.
|
||||
|
||||
Args:
|
||||
log: A filtered log (see :func:`period_average`).
|
||||
schedule: Resolves each day's budget.
|
||||
months_ago: 0 for the current month (through yesterday), 1 for the
|
||||
previous complete month, and so on.
|
||||
today: The reference "today"; defaults to the real current date.
|
||||
|
||||
Returns:
|
||||
That month's :class:`PeriodAverage`.
|
||||
"""
|
||||
ref = _resolve_today(today)
|
||||
return _capped(log, schedule, month_bounds(_shift_months(ref, months_ago)), ref)
|
||||
|
||||
|
||||
def recent_weeks(
|
||||
log: DayLog,
|
||||
*,
|
||||
schedule: BudgetSchedule,
|
||||
count: int,
|
||||
today: date | None = None,
|
||||
) -> tuple[PeriodAverage, ...]:
|
||||
"""Return the last ``count`` weekly averages, most recent first."""
|
||||
ref = _resolve_today(today)
|
||||
return tuple(
|
||||
weekly_average(log, schedule=schedule, weeks_ago=back, today=ref)
|
||||
for back in range(count)
|
||||
)
|
||||
|
||||
|
||||
def recent_months(
|
||||
log: DayLog,
|
||||
*,
|
||||
schedule: BudgetSchedule,
|
||||
count: int,
|
||||
today: date | None = None,
|
||||
) -> tuple[PeriodAverage, ...]:
|
||||
"""Return the last ``count`` monthly averages, most recent first."""
|
||||
ref = _resolve_today(today)
|
||||
return tuple(
|
||||
monthly_average(log, schedule=schedule, months_ago=back, today=ref)
|
||||
for back in range(count)
|
||||
)
|
||||
|
||||
76
diet_guard/_averages_periods.py
Normal file
76
diet_guard/_averages_periods.py
Normal file
@ -0,0 +1,76 @@
|
||||
"""Weekly and monthly average intake, and how that average met the budget.
|
||||
|
||||
PERIOD AVERAGE SPEC (keep in sync with
|
||||
``app/lib/services/average_service.dart``):
|
||||
|
||||
* the average is over **logged days only** -- ``sum(kcal) / logged_days``. A
|
||||
day you forgot to log is not a zero-calorie day, and counting it as one
|
||||
would make every gap in the log read as "well under budget", which is the
|
||||
exact opposite of the truth. ``logged_days`` / ``elapsed_days`` travel with
|
||||
the average so a caller can show how much of the period it actually covers.
|
||||
* the yardstick is the **mean of the per-day budgets over those same logged
|
||||
days**, resolved through a
|
||||
:class:`~diet_guard._budget_history.BudgetSchedule` -- never today's budget.
|
||||
Comparing a past week's intake against a budget you lowered yesterday would
|
||||
retroactively reclassify it, which is precisely what
|
||||
:mod:`diet_guard._budget_history` exists to prevent.
|
||||
* bands, reusing the calendar's own over-budget boundary
|
||||
(:data:`~diet_guard._daystatus.OVER_BUDGET_YELLOW_CEILING`) so a period and
|
||||
its days can never disagree about what "over" means:
|
||||
|
||||
- ``under``: ``avg_kcal <= avg_budget``
|
||||
- ``slightly_over``: ``avg_budget < avg_kcal <= avg_budget * ceiling``
|
||||
- ``very_over``: ``avg_kcal > avg_budget * ceiling``
|
||||
|
||||
* **today is excluded.** A period ending at "now" mixes complete days with
|
||||
one that is three hours old, and a half-logged today drags the mean down far
|
||||
enough to flip the band. Every period therefore ends at
|
||||
:func:`last_complete_day` -- yesterday -- so "this week" means "this week so
|
||||
far, in finished days". A period with no finished days yet (Monday, or the
|
||||
1st) reports ``elapsed_days == 0`` and a ``None`` average rather than a
|
||||
flattering fake one.
|
||||
* weeks are **ISO weeks, Monday through Sunday**; months are calendar months.
|
||||
|
||||
Every function here is a pure function of its explicit ``log`` / ``schedule``
|
||||
/ ``today`` arguments and never reaches into on-disk state, so the band
|
||||
boundaries and the period edges are testable with synthetic data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
from datetime import date, timedelta
|
||||
|
||||
from diet_guard._state import now_local
|
||||
|
||||
_DAYS_PER_WEEK = 7
|
||||
_MONTHS_PER_YEAR = 12
|
||||
|
||||
|
||||
def last_complete_day(today: date) -> date:
|
||||
"""Return the last day whose log is finished: the day before ``today``."""
|
||||
return today - timedelta(days=1)
|
||||
|
||||
|
||||
def week_bounds(day: date) -> tuple[date, date]:
|
||||
"""Return the Monday and Sunday of the ISO week containing ``day``."""
|
||||
monday = day - timedelta(days=day.weekday())
|
||||
return monday, monday + timedelta(days=_DAYS_PER_WEEK - 1)
|
||||
|
||||
|
||||
def month_bounds(day: date) -> tuple[date, date]:
|
||||
"""Return the first and last dates of ``day``'s calendar month."""
|
||||
last = calendar.monthrange(day.year, day.month)[1]
|
||||
return day.replace(day=1), day.replace(day=last)
|
||||
|
||||
|
||||
def _shift_months(day: date, months: int) -> date:
|
||||
"""Return the first of the month ``months`` before ``day``'s month."""
|
||||
index = day.year * _MONTHS_PER_YEAR + (day.month - 1) - months
|
||||
year, month = divmod(index, _MONTHS_PER_YEAR)
|
||||
return date(year, month + 1, 1)
|
||||
|
||||
|
||||
def _resolve_today(today: date | None) -> date:
|
||||
"""Return ``today`` or the real current local date when it is None."""
|
||||
return today if today is not None else now_local().date()
|
||||
155
diet_guard/_averages_report.py
Normal file
155
diet_guard/_averages_report.py
Normal file
@ -0,0 +1,155 @@
|
||||
"""Weekly and monthly average intake, and how that average met the budget.
|
||||
|
||||
PERIOD AVERAGE SPEC (keep in sync with
|
||||
``app/lib/services/average_service.dart``):
|
||||
|
||||
* the average is over **logged days only** -- ``sum(kcal) / logged_days``. A
|
||||
day you forgot to log is not a zero-calorie day, and counting it as one
|
||||
would make every gap in the log read as "well under budget", which is the
|
||||
exact opposite of the truth. ``logged_days`` / ``elapsed_days`` travel with
|
||||
the average so a caller can show how much of the period it actually covers.
|
||||
* the yardstick is the **mean of the per-day budgets over those same logged
|
||||
days**, resolved through a
|
||||
:class:`~diet_guard._budget_history.BudgetSchedule` -- never today's budget.
|
||||
Comparing a past week's intake against a budget you lowered yesterday would
|
||||
retroactively reclassify it, which is precisely what
|
||||
:mod:`diet_guard._budget_history` exists to prevent.
|
||||
* bands, reusing the calendar's own over-budget boundary
|
||||
(:data:`~diet_guard._daystatus.OVER_BUDGET_YELLOW_CEILING`) so a period and
|
||||
its days can never disagree about what "over" means:
|
||||
|
||||
- ``under``: ``avg_kcal <= avg_budget``
|
||||
- ``slightly_over``: ``avg_budget < avg_kcal <= avg_budget * ceiling``
|
||||
- ``very_over``: ``avg_kcal > avg_budget * ceiling``
|
||||
|
||||
* **today is excluded.** A period ending at "now" mixes complete days with
|
||||
one that is three hours old, and a half-logged today drags the mean down far
|
||||
enough to flip the band. Every period therefore ends at
|
||||
:func:`last_complete_day` -- yesterday -- so "this week" means "this week so
|
||||
far, in finished days". A period with no finished days yet (Monday, or the
|
||||
1st) reports ``elapsed_days == 0`` and a ``None`` average rather than a
|
||||
flattering fake one.
|
||||
* weeks are **ISO weeks, Monday through Sunday**; months are calendar months.
|
||||
|
||||
Every function here is a pure function of its explicit ``log`` / ``schedule``
|
||||
/ ``today`` arguments and never reaches into on-disk state, so the band
|
||||
boundaries and the period edges are testable with synthetic data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from diet_guard._averages import PeriodAverage, period_average
|
||||
from diet_guard._averages_periods import (
|
||||
_resolve_today,
|
||||
_shift_months,
|
||||
last_complete_day,
|
||||
month_bounds,
|
||||
week_bounds,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from diet_guard._budget_history import BudgetSchedule
|
||||
from diet_guard._state import DayLog
|
||||
|
||||
_DAYS_PER_WEEK = 7
|
||||
_MONTHS_PER_YEAR = 12
|
||||
|
||||
|
||||
def _capped(
|
||||
log: DayLog,
|
||||
schedule: BudgetSchedule,
|
||||
bounds: tuple[date, date],
|
||||
ref: date,
|
||||
) -> PeriodAverage:
|
||||
"""Average ``bounds``, truncated so it never includes ``ref`` itself.
|
||||
|
||||
The single place the "today is excluded" rule is applied, so a caller
|
||||
cannot construct a period that half-counts an unfinished day.
|
||||
"""
|
||||
start, end = bounds
|
||||
return period_average(
|
||||
log,
|
||||
schedule=schedule,
|
||||
start=start,
|
||||
end=min(end, last_complete_day(ref)),
|
||||
)
|
||||
|
||||
|
||||
def weekly_average(
|
||||
log: DayLog,
|
||||
*,
|
||||
schedule: BudgetSchedule,
|
||||
weeks_ago: int = 0,
|
||||
today: date | None = None,
|
||||
) -> PeriodAverage:
|
||||
"""Return the average for an ISO week, ``weeks_ago`` weeks back.
|
||||
|
||||
Args:
|
||||
log: A filtered log (see :func:`period_average`).
|
||||
schedule: Resolves each day's budget.
|
||||
weeks_ago: 0 for the current week (through yesterday), 1 for the
|
||||
previous complete week, and so on.
|
||||
today: The reference "today"; defaults to the real current date.
|
||||
|
||||
Returns:
|
||||
That week's :class:`PeriodAverage`.
|
||||
"""
|
||||
ref = _resolve_today(today)
|
||||
anchor = ref - timedelta(weeks=weeks_ago)
|
||||
return _capped(log, schedule, week_bounds(anchor), ref)
|
||||
|
||||
|
||||
def monthly_average(
|
||||
log: DayLog,
|
||||
*,
|
||||
schedule: BudgetSchedule,
|
||||
months_ago: int = 0,
|
||||
today: date | None = None,
|
||||
) -> PeriodAverage:
|
||||
"""Return the average for a calendar month, ``months_ago`` months back.
|
||||
|
||||
Args:
|
||||
log: A filtered log (see :func:`period_average`).
|
||||
schedule: Resolves each day's budget.
|
||||
months_ago: 0 for the current month (through yesterday), 1 for the
|
||||
previous complete month, and so on.
|
||||
today: The reference "today"; defaults to the real current date.
|
||||
|
||||
Returns:
|
||||
That month's :class:`PeriodAverage`.
|
||||
"""
|
||||
ref = _resolve_today(today)
|
||||
return _capped(log, schedule, month_bounds(_shift_months(ref, months_ago)), ref)
|
||||
|
||||
|
||||
def recent_weeks(
|
||||
log: DayLog,
|
||||
*,
|
||||
schedule: BudgetSchedule,
|
||||
count: int,
|
||||
today: date | None = None,
|
||||
) -> tuple[PeriodAverage, ...]:
|
||||
"""Return the last ``count`` weekly averages, most recent first."""
|
||||
ref = _resolve_today(today)
|
||||
return tuple(
|
||||
weekly_average(log, schedule=schedule, weeks_ago=back, today=ref)
|
||||
for back in range(count)
|
||||
)
|
||||
|
||||
|
||||
def recent_months(
|
||||
log: DayLog,
|
||||
*,
|
||||
schedule: BudgetSchedule,
|
||||
count: int,
|
||||
today: date | None = None,
|
||||
) -> tuple[PeriodAverage, ...]:
|
||||
"""Return the last ``count`` monthly averages, most recent first."""
|
||||
ref = _resolve_today(today)
|
||||
return tuple(
|
||||
monthly_average(log, schedule=schedule, months_ago=back, today=ref)
|
||||
for back in range(count)
|
||||
)
|
||||
@ -19,7 +19,6 @@ keeps up to date on every edit.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
@ -83,65 +82,6 @@ class BudgetFileCorruptError(BudgetError):
|
||||
super().__init__("daily budget file is corrupt")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Biometrics:
|
||||
"""Body metrics that feed the Mifflin-St Jeor budget formula.
|
||||
|
||||
Grouped into one value object so the budget calculation stays under the
|
||||
repo's five-argument lint ceiling and so the inputs travel together.
|
||||
|
||||
Attributes:
|
||||
weight_kg: Body mass in kilograms.
|
||||
height_cm: Height in centimetres.
|
||||
age_years: Age in years.
|
||||
is_male: True for the male BMR constant (+5), False for female (-161).
|
||||
"""
|
||||
|
||||
weight_kg: float
|
||||
height_cm: float
|
||||
age_years: float
|
||||
is_male: bool
|
||||
|
||||
|
||||
def mifflin_st_jeor_bmr(bio: Biometrics) -> float:
|
||||
"""Return resting metabolic rate via the Mifflin-St Jeor equation.
|
||||
|
||||
Args:
|
||||
bio: The person's body metrics.
|
||||
|
||||
Returns:
|
||||
Basal metabolic rate in kcal/day.
|
||||
"""
|
||||
base = 10.0 * bio.weight_kg + 6.25 * bio.height_cm - 5.0 * bio.age_years
|
||||
return base + 5.0 if bio.is_male else base - 161.0
|
||||
|
||||
|
||||
def compute_target_budget(
|
||||
bio: Biometrics,
|
||||
*,
|
||||
activity_factor: float,
|
||||
deficit_kcal: float,
|
||||
) -> int:
|
||||
"""Return the daily kcal target: TDEE minus a deficit, floored for safety.
|
||||
|
||||
TDEE (total daily energy expenditure) is the BMR scaled by an activity
|
||||
factor; subtracting a deficit yields a target that drives gradual loss.
|
||||
|
||||
Args:
|
||||
bio: The person's body metrics.
|
||||
activity_factor: Multiplier for daily activity (e.g. 1.2 sedentary,
|
||||
1.375 light, 1.55 moderate, 1.725 very active).
|
||||
deficit_kcal: Calories subtracted from TDEE for weight loss.
|
||||
|
||||
Returns:
|
||||
The target budget in kcal, never below ``_MIN_SANE_BUDGET``.
|
||||
"""
|
||||
bmr = mifflin_st_jeor_bmr(bio)
|
||||
tdee = bmr * activity_factor
|
||||
target = round(tdee - deficit_kcal)
|
||||
return max(target, _MIN_SANE_BUDGET)
|
||||
|
||||
|
||||
def is_initialized() -> bool:
|
||||
"""Return True if a budget file exists on disk."""
|
||||
return BUDGET_FILE.exists()
|
||||
@ -254,43 +194,6 @@ def daily_budget() -> int:
|
||||
return value
|
||||
|
||||
|
||||
def budget_weight() -> float | None:
|
||||
"""Return the body weight stored with the budget, or None if unavailable.
|
||||
|
||||
Returns:
|
||||
The stored weight in kg, or None for a pre-v2 (budget-only) record.
|
||||
|
||||
Raises:
|
||||
BudgetNotInitializedError: If no budget has been set yet.
|
||||
BudgetFileCorruptError: If the file exists but cannot be parsed.
|
||||
"""
|
||||
record = _read_record()
|
||||
value = record.get("w")
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return None
|
||||
return float(value)
|
||||
|
||||
|
||||
def protein_target_g() -> float | None:
|
||||
"""Return the daily protein target in grams, or None if it cannot be derived.
|
||||
|
||||
Derived from the stored body weight at :data:`PROTEIN_G_PER_KG`. Returns
|
||||
None -- rather than raising -- whenever the target is simply unavailable
|
||||
(no budget set, a pre-v2 record without weight, or a corrupt file), so
|
||||
the dashboard can show calories and quietly omit the protein line.
|
||||
|
||||
Returns:
|
||||
The protein target in grams, or None when weight is unknown.
|
||||
"""
|
||||
try:
|
||||
weight = budget_weight()
|
||||
except BudgetError:
|
||||
return None
|
||||
if weight is None:
|
||||
return None
|
||||
return round(weight * PROTEIN_G_PER_KG, 1)
|
||||
|
||||
|
||||
def read_raw_record() -> dict[str, object] | None:
|
||||
"""Return the on-disk budget record verbatim, or None if unset/corrupt.
|
||||
|
||||
|
||||
80
diet_guard/_budget_biometrics.py
Normal file
80
diet_guard/_budget_biometrics.py
Normal file
@ -0,0 +1,80 @@
|
||||
"""Biometrics and the one-time budget computation seeded from them.
|
||||
|
||||
Split out of :mod:`._budget` to keep both files under the repo's 250-line
|
||||
limit. This half is pure arithmetic -- Mifflin-St Jeor BMR, the activity and
|
||||
goal multipliers -- and touches no file, which is why ``BUDGET_FILE`` stays
|
||||
named by :mod:`._budget` alone.
|
||||
|
||||
The biometrics themselves are used once and discarded: only the computed
|
||||
budget is ever persisted.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
# The floor a computed target can never go below, however aggressive the
|
||||
# deficit. Defined here with the computation it guards rather than imported
|
||||
# from _budget, which would make the dependency circular.
|
||||
_MIN_SANE_BUDGET = 1200
|
||||
|
||||
__all__ = ["Biometrics", "compute_target_budget", "mifflin_st_jeor_bmr"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Biometrics:
|
||||
"""Body metrics that feed the Mifflin-St Jeor budget formula.
|
||||
|
||||
Grouped into one value object so the budget calculation stays under the
|
||||
repo's five-argument lint ceiling and so the inputs travel together.
|
||||
|
||||
Attributes:
|
||||
weight_kg: Body mass in kilograms.
|
||||
height_cm: Height in centimetres.
|
||||
age_years: Age in years.
|
||||
is_male: True for the male BMR constant (+5), False for female (-161).
|
||||
"""
|
||||
|
||||
weight_kg: float
|
||||
height_cm: float
|
||||
age_years: float
|
||||
is_male: bool
|
||||
|
||||
|
||||
def mifflin_st_jeor_bmr(bio: Biometrics) -> float:
|
||||
"""Return resting metabolic rate via the Mifflin-St Jeor equation.
|
||||
|
||||
Args:
|
||||
bio: The person's body metrics.
|
||||
|
||||
Returns:
|
||||
Basal metabolic rate in kcal/day.
|
||||
"""
|
||||
base = 10.0 * bio.weight_kg + 6.25 * bio.height_cm - 5.0 * bio.age_years
|
||||
return base + 5.0 if bio.is_male else base - 161.0
|
||||
|
||||
|
||||
def compute_target_budget(
|
||||
bio: Biometrics,
|
||||
*,
|
||||
activity_factor: float,
|
||||
deficit_kcal: float,
|
||||
) -> int:
|
||||
"""Return the daily kcal target: TDEE minus a deficit, floored for safety.
|
||||
|
||||
TDEE (total daily energy expenditure) is the BMR scaled by an activity
|
||||
factor; subtracting a deficit yields a target that drives gradual loss.
|
||||
|
||||
Args:
|
||||
bio: The person's body metrics.
|
||||
activity_factor: Multiplier for daily activity (e.g. 1.2 sedentary,
|
||||
1.375 light, 1.55 moderate, 1.725 very active).
|
||||
deficit_kcal: Calories subtracted from TDEE for weight loss.
|
||||
|
||||
Returns:
|
||||
The target budget in kcal, never below ``_MIN_SANE_BUDGET``.
|
||||
"""
|
||||
bmr = mifflin_st_jeor_bmr(bio)
|
||||
tdee = bmr * activity_factor
|
||||
target = round(tdee - deficit_kcal)
|
||||
return max(target, _MIN_SANE_BUDGET)
|
||||
51
diet_guard/_budget_derived.py
Normal file
51
diet_guard/_budget_derived.py
Normal file
@ -0,0 +1,51 @@
|
||||
"""Values derived from the stored budget record.
|
||||
|
||||
Split out of :mod:`._budget` to keep both files under the repo's 250-line
|
||||
limit. Nothing here opens a file: both helpers read through
|
||||
:func:`diet_guard._budget._read_record`, so ``BUDGET_FILE`` stays named by
|
||||
:mod:`._budget` alone -- which is what ``tests/conftest.py`` redirects, and
|
||||
what ``test_state_redirect.py`` enforces.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from diet_guard._budget import PROTEIN_G_PER_KG, BudgetError, _read_record
|
||||
|
||||
__all__ = ["budget_weight", "protein_target_g"]
|
||||
|
||||
|
||||
def protein_target_g() -> float | None:
|
||||
"""Return the daily protein target in grams, or None if it cannot be derived.
|
||||
|
||||
Derived from the stored body weight at :data:`PROTEIN_G_PER_KG`. Returns
|
||||
None -- rather than raising -- whenever the target is simply unavailable
|
||||
(no budget set, a pre-v2 record without weight, or a corrupt file), so
|
||||
the dashboard can show calories and quietly omit the protein line.
|
||||
|
||||
Returns:
|
||||
The protein target in grams, or None when weight is unknown.
|
||||
"""
|
||||
try:
|
||||
weight = budget_weight()
|
||||
except BudgetError:
|
||||
return None
|
||||
if weight is None:
|
||||
return None
|
||||
return round(weight * PROTEIN_G_PER_KG, 1)
|
||||
|
||||
|
||||
def budget_weight() -> float | None:
|
||||
"""Return the body weight stored with the budget, or None if unavailable.
|
||||
|
||||
Returns:
|
||||
The stored weight in kg, or None for a pre-v2 (budget-only) record.
|
||||
|
||||
Raises:
|
||||
BudgetNotInitializedError: If no budget has been set yet.
|
||||
BudgetFileCorruptError: If the file exists but cannot be parsed.
|
||||
"""
|
||||
record = _read_record()
|
||||
value = record.get("w")
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return None
|
||||
return float(value)
|
||||
@ -16,7 +16,7 @@ Storage and sync are deliberately split:
|
||||
* the entries live in their own file (``.budget_history``), leaving
|
||||
:mod:`diet_guard._budget`'s ``.budget`` schema untouched at v2;
|
||||
* they travel as extra ``hist:<YYYY-MM-DD>`` *fields* on the existing
|
||||
``budget`` CRDT record (see :mod:`diet_guard._sync_merge`).
|
||||
``budget`` CRDT record (see :mod:`diet_guard.sync_merge`).
|
||||
|
||||
That second point is the load-bearing one. ``crdt_sync``'s ``merge_record``
|
||||
does per-field last-writer-wins over the *union* of field names, and both
|
||||
|
||||
@ -16,12 +16,8 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock import LockConfig
|
||||
|
||||
from diet_guard._averages import (
|
||||
PeriodAverage,
|
||||
band_label,
|
||||
monthly_average,
|
||||
weekly_average,
|
||||
)
|
||||
from diet_guard._averages import PeriodAverage, band_label
|
||||
from diet_guard._averages_report import monthly_average, weekly_average
|
||||
from diet_guard._daystatus import (
|
||||
DayStatus,
|
||||
adherence_streak,
|
||||
|
||||
@ -16,90 +16,44 @@ are left of the day's budget, plus which meal slots still need logging.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from dataclasses import dataclass
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from diet_guard._budget import (
|
||||
Biometrics,
|
||||
BudgetFileCorruptError,
|
||||
BudgetNotInitializedError,
|
||||
compute_target_budget,
|
||||
daily_budget,
|
||||
protein_target_g,
|
||||
write_budget,
|
||||
)
|
||||
from diet_guard._cli_averages import cmd_averages, register_averages_subparser
|
||||
from diet_guard._budget_derived import protein_target_g
|
||||
from diet_guard._cli_args import parse_args
|
||||
from diet_guard._cli_averages import cmd_averages
|
||||
from diet_guard._cli_gate import cmd_gate
|
||||
from diet_guard._cli_sync import cmd_sync, register_sync_subparser
|
||||
from diet_guard._foodbank import remember_food
|
||||
from diet_guard._cli_init import cmd_init
|
||||
from diet_guard._cli_log import ManualMacroArgs, Portion, cmd_ate
|
||||
from diet_guard._cli_sync import cmd_sync
|
||||
from diet_guard._gate import due_slots
|
||||
from diet_guard._portions import (
|
||||
DEFAULT_ITEM_GRAMS,
|
||||
estimate_unit_grams,
|
||||
)
|
||||
from diet_guard._resolve import ManualMacros, resolve_nutrition
|
||||
from diet_guard._slots import day_slots, slot_for_log, slot_label
|
||||
from diet_guard._slots import day_slots, slot_label
|
||||
from diet_guard._state import (
|
||||
entry_kcal,
|
||||
log_meal,
|
||||
)
|
||||
from diet_guard._state_sync import (
|
||||
undo_last_today,
|
||||
)
|
||||
from diet_guard._state_today import (
|
||||
logged_slots_today,
|
||||
now_local,
|
||||
today_entries,
|
||||
today_total_kcal,
|
||||
today_total_macros,
|
||||
undo_last_today,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import argparse
|
||||
from collections.abc import Callable
|
||||
|
||||
# Column width for a meal description in the status listing.
|
||||
_DESC_WIDTH = 24
|
||||
# An ISO timestamp formats as "YYYY-MM-DDTHH:MM:SS"; HH:MM is chars 11..16.
|
||||
_TIME_SLICE = slice(11, 16)
|
||||
# Accepted answers for the sex prompt that map to the male BMR constant.
|
||||
_MALE_ANSWERS = {"m", "male"}
|
||||
_FEMALE_ANSWERS = {"f", "female"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _ManualMacros:
|
||||
"""User-supplied calories/macros for ``ate``, all optional.
|
||||
|
||||
Grouping these keeps :func:`_cmd_ate` within the argument-count limit and
|
||||
makes "manual values were supplied" a single, testable value object.
|
||||
|
||||
Attributes:
|
||||
kcal: Calories entered manually (None means look the food up instead).
|
||||
protein: Protein grams, recorded alongside ``kcal``.
|
||||
carbs: Carbohydrate grams, recorded alongside ``kcal``.
|
||||
fat: Fat grams, recorded alongside ``kcal``.
|
||||
"""
|
||||
|
||||
kcal: float | None
|
||||
protein: float | None
|
||||
carbs: float | None
|
||||
fat: float | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Portion:
|
||||
"""How much was eaten and the basis for any typed macros.
|
||||
|
||||
Grouped so :func:`_cmd_ate` stays within the argument-count limit.
|
||||
|
||||
Attributes:
|
||||
grams: Explicit grams eaten, or None.
|
||||
count: Number of items eaten (an alternative to ``grams``), or None.
|
||||
per_grams: Reference weight the typed macros are stated for (e.g. 100
|
||||
for a per-100 g label), or None to treat the macros as totals.
|
||||
"""
|
||||
|
||||
grams: float | None
|
||||
count: float | None
|
||||
per_grams: float | None
|
||||
|
||||
|
||||
def _emit(text: str = "") -> None:
|
||||
@ -117,88 +71,6 @@ def _ask(label: str) -> str:
|
||||
return sys.stdin.readline().strip()
|
||||
|
||||
|
||||
def _parse_args(argv: list[str]) -> argparse.Namespace:
|
||||
"""Parse diet_guard CLI arguments."""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="diet_guard",
|
||||
description="Log calories and check your daily budget.",
|
||||
)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
sub.add_parser(
|
||||
"init",
|
||||
help="Compute your starting daily budget from biometrics.",
|
||||
)
|
||||
|
||||
ate = sub.add_parser("ate", help="Log a meal you just ate.")
|
||||
ate.add_argument("description", help='What you ate, e.g. "big mac".')
|
||||
ate.add_argument(
|
||||
"--grams",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Portion size in grams (default: OFF serving size, else 100 g).",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--kcal",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Calories entered manually; skips the food bank and OFF lookup.",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--protein",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Protein in grams (recorded with --kcal to seed the food bank).",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--carbs",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Carbohydrate in grams (recorded with --kcal).",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--fat",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Fat in grams (recorded with --kcal).",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--per",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Grams the macros are stated for (e.g. 100 for a per-100 g label);"
|
||||
" the typed macros are scaled from this to how much you ate.",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--count",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Number of items eaten (e.g. 5 apples) instead of --grams;"
|
||||
" multiplied by the staple's unit weight.",
|
||||
)
|
||||
|
||||
sub.add_parser("status", help="Show today's calories and budget band.")
|
||||
sub.add_parser("undo", help="Remove today's most recent entry.")
|
||||
register_averages_subparser(sub)
|
||||
register_sync_subparser(sub)
|
||||
|
||||
gate = sub.add_parser(
|
||||
"gate",
|
||||
help="Log-to-unlock screen gate (intended to be run by a timer).",
|
||||
)
|
||||
gate.add_argument(
|
||||
"--check",
|
||||
action="store_true",
|
||||
help="Headless: exit 0 if NOT due, 1 if a lock is due. Prints, no window.",
|
||||
)
|
||||
gate.add_argument(
|
||||
"--demo",
|
||||
action="store_true",
|
||||
help="Show the lock in safe demo mode (local grab + close button).",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def _print_summary() -> None:
|
||||
"""Print today's total and how much of the daily budget is left.
|
||||
|
||||
@ -232,137 +104,6 @@ def _print_entry_line(entry: dict[str, object]) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _read_init_inputs() -> tuple[Biometrics, float, float] | None:
|
||||
"""Prompt for biometrics on stdin; return (bio, activity, deficit) or None.
|
||||
|
||||
Returns None (after printing why) on any unparsable or out-of-range input,
|
||||
so a typo never sets a wrong budget.
|
||||
"""
|
||||
try:
|
||||
weight = float(_ask("weight in kg:"))
|
||||
height = float(_ask("height in cm:"))
|
||||
age = float(_ask("age in years:"))
|
||||
sex_raw = _ask("sex (m/f):").lower()
|
||||
activity = float(
|
||||
_ask(
|
||||
"activity factor "
|
||||
"(1.2 sedentary / 1.375 light / 1.55 moderate / 1.725 active):",
|
||||
),
|
||||
)
|
||||
deficit = float(_ask("daily deficit in kcal (e.g. 200):"))
|
||||
except ValueError:
|
||||
_emit("that was not a number; nothing was set.")
|
||||
return None
|
||||
|
||||
if sex_raw in _MALE_ANSWERS:
|
||||
is_male = True
|
||||
elif sex_raw in _FEMALE_ANSWERS:
|
||||
is_male = False
|
||||
else:
|
||||
_emit('sex must be "m" or "f"; nothing was set.')
|
||||
return None
|
||||
|
||||
bio = Biometrics(
|
||||
weight_kg=weight,
|
||||
height_cm=height,
|
||||
age_years=age,
|
||||
is_male=is_male,
|
||||
)
|
||||
return bio, activity, deficit
|
||||
|
||||
|
||||
def _cmd_init() -> int:
|
||||
"""Compute the starting budget from biometrics and write it."""
|
||||
inputs = _read_init_inputs()
|
||||
if inputs is None:
|
||||
return 2
|
||||
bio, activity, deficit = inputs
|
||||
budget = compute_target_budget(
|
||||
bio,
|
||||
activity_factor=activity,
|
||||
deficit_kcal=deficit,
|
||||
)
|
||||
write_budget(budget, weight_kg=bio.weight_kg)
|
||||
_emit(f"budget computed from your biometrics: {budget:g} kcal/day.")
|
||||
_emit("edit it any time from the gate's calendar tab or the phone app.")
|
||||
return 0
|
||||
|
||||
|
||||
def _eaten_grams(
|
||||
description: str,
|
||||
portion: _Portion,
|
||||
) -> tuple[float | None, str | None]:
|
||||
"""Resolve how many grams were eaten, plus a note if a weight was assumed.
|
||||
|
||||
A count of items is turned into grams via the staple's unit weight; an
|
||||
unknown item falls back to a default weight, with a note so the estimate is
|
||||
never silent.
|
||||
|
||||
Args:
|
||||
description: The food name (used to look up a per-item weight).
|
||||
portion: The user's portion inputs.
|
||||
|
||||
Returns:
|
||||
``(grams, note)`` where ``grams`` may be None (no portion given) and
|
||||
``note`` is a one-line caveat to print, or None.
|
||||
"""
|
||||
if portion.count is not None:
|
||||
unit = estimate_unit_grams(description)
|
||||
if unit is None:
|
||||
return (
|
||||
portion.count * DEFAULT_ITEM_GRAMS,
|
||||
f"(assumed {DEFAULT_ITEM_GRAMS:g} g per item; "
|
||||
"pass --grams to be exact)",
|
||||
)
|
||||
return portion.count * unit, None
|
||||
return portion.grams, None
|
||||
|
||||
|
||||
def _cmd_ate(description: str, portion: _Portion, macros: _ManualMacros) -> int:
|
||||
"""Resolve and log a meal, tag its slot, bank it, then print the total.
|
||||
|
||||
Resolution order is manual, then food bank, then the staple table, then
|
||||
Open Food Facts (see :func:`resolve_nutrition`). A per-item count or a
|
||||
per-reference macro basis is converted to the amount actually eaten first,
|
||||
and the food is remembered so next time it is served from local history.
|
||||
"""
|
||||
eaten, note = _eaten_grams(description, portion)
|
||||
if note is not None:
|
||||
_emit(note)
|
||||
manual_macros = (
|
||||
ManualMacros(
|
||||
kcal=macros.kcal,
|
||||
protein=macros.protein or 0.0,
|
||||
carbs=macros.carbs or 0.0,
|
||||
fat=macros.fat or 0.0,
|
||||
per_grams=portion.per_grams,
|
||||
)
|
||||
if macros.kcal is not None
|
||||
else None
|
||||
)
|
||||
nutrition = resolve_nutrition(
|
||||
description,
|
||||
grams=eaten,
|
||||
manual_macros=manual_macros,
|
||||
)
|
||||
if nutrition is None:
|
||||
_emit(
|
||||
f'no food bank, staple, or Open Food Facts match for "{description}". '
|
||||
"re-run with --kcal <number> to log it manually.",
|
||||
)
|
||||
return 1
|
||||
log_meal(description, nutrition, slot_for_log(now_local()))
|
||||
remember_food(description, nutrition)
|
||||
macro_str = f"P{nutrition.protein_g:g} C{nutrition.carbs_g:g} F{nutrition.fat_g:g}"
|
||||
portion_str = f"{nutrition.grams:g} g" if nutrition.grams else "portion n/a"
|
||||
_emit(
|
||||
f"logged: {description} {nutrition.kcal:g} kcal "
|
||||
f"({macro_str}) [{nutrition.source}, {portion_str}]",
|
||||
)
|
||||
_print_summary()
|
||||
return 0
|
||||
|
||||
|
||||
def _print_slot_status() -> None:
|
||||
"""Print each meal slot as logged / DUE / upcoming for today."""
|
||||
logged = logged_slots_today()
|
||||
@ -422,10 +163,12 @@ def _cmd_undo() -> int:
|
||||
|
||||
def _dispatch_ate(args: argparse.Namespace) -> int:
|
||||
"""Marshal ``ate``'s flags into value objects, then log the meal."""
|
||||
return _cmd_ate(
|
||||
return cmd_ate(
|
||||
_emit,
|
||||
_print_summary,
|
||||
args.description,
|
||||
_Portion(grams=args.grams, count=args.count, per_grams=args.per),
|
||||
_ManualMacros(
|
||||
Portion(grams=args.grams, count=args.count, per_grams=args.per),
|
||||
ManualMacroArgs(
|
||||
kcal=args.kcal,
|
||||
protein=args.protein,
|
||||
carbs=args.carbs,
|
||||
@ -443,7 +186,7 @@ def _dispatch_gate(args: argparse.Namespace) -> int:
|
||||
# tripped ruff's return-count limit at the seventh, and a table also has no
|
||||
# unreachable trailing branch for the 100%-coverage gate to chase.
|
||||
_COMMANDS: dict[str, Callable[[argparse.Namespace], int]] = {
|
||||
"init": lambda _args: _cmd_init(),
|
||||
"init": lambda _args: cmd_init(_emit, _ask),
|
||||
"ate": _dispatch_ate,
|
||||
"status": lambda _args: _cmd_status(),
|
||||
"averages": lambda _args: cmd_averages(_emit),
|
||||
@ -462,5 +205,5 @@ def main(argv: list[str] | None = None) -> int:
|
||||
Returns:
|
||||
A process exit code (0 on success).
|
||||
"""
|
||||
args = _parse_args(sys.argv[1:] if argv is None else argv)
|
||||
args = parse_args(sys.argv[1:] if argv is None else argv)
|
||||
return _COMMANDS[args.command](args)
|
||||
|
||||
100
diet_guard/_cli_args.py
Normal file
100
diet_guard/_cli_args.py
Normal file
@ -0,0 +1,100 @@
|
||||
"""Argument parsing for the diet_guard CLI.
|
||||
|
||||
Split out of :mod:`diet_guard._cli` to hold the repo's 250-line cap. This is
|
||||
the declarative half -- every subcommand and flag the CLI accepts -- kept apart
|
||||
from the handlers that act on them, so adding a flag never grows a file that
|
||||
also contains logic.
|
||||
|
||||
Subparsers owned by a sibling handler register themselves through their own
|
||||
module (``register_averages_subparser``, ``register_sync_subparser``) rather
|
||||
than being spelled out here, so a subcommand's flags live next to its code.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
from diet_guard._cli_averages import register_averages_subparser
|
||||
from diet_guard._cli_sync import register_sync_subparser
|
||||
|
||||
|
||||
def parse_args(argv: list[str]) -> argparse.Namespace:
|
||||
"""Parse diet_guard CLI arguments."""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="diet_guard",
|
||||
description="Log calories and check your daily budget.",
|
||||
)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
sub.add_parser(
|
||||
"init",
|
||||
help="Compute your starting daily budget from biometrics.",
|
||||
)
|
||||
|
||||
ate = sub.add_parser("ate", help="Log a meal you just ate.")
|
||||
ate.add_argument("description", help='What you ate, e.g. "big mac".')
|
||||
ate.add_argument(
|
||||
"--grams",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Portion size in grams (default: OFF serving size, else 100 g).",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--kcal",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Calories entered manually; skips the food bank and OFF lookup.",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--protein",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Protein in grams (recorded with --kcal to seed the food bank).",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--carbs",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Carbohydrate in grams (recorded with --kcal).",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--fat",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Fat in grams (recorded with --kcal).",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--per",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Grams the macros are stated for (e.g. 100 for a per-100 g label);"
|
||||
" the typed macros are scaled from this to how much you ate.",
|
||||
)
|
||||
ate.add_argument(
|
||||
"--count",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Number of items eaten (e.g. 5 apples) instead of --grams;"
|
||||
" multiplied by the staple's unit weight.",
|
||||
)
|
||||
|
||||
sub.add_parser("status", help="Show today's calories and budget band.")
|
||||
sub.add_parser("undo", help="Remove today's most recent entry.")
|
||||
register_averages_subparser(sub)
|
||||
register_sync_subparser(sub)
|
||||
|
||||
gate = sub.add_parser(
|
||||
"gate",
|
||||
help="Log-to-unlock screen gate (intended to be run by a timer).",
|
||||
)
|
||||
gate.add_argument(
|
||||
"--check",
|
||||
action="store_true",
|
||||
help="Headless: exit 0 if NOT due, 1 if a lock is due. Prints, no window.",
|
||||
)
|
||||
gate.add_argument(
|
||||
"--demo",
|
||||
action="store_true",
|
||||
help="Show the lock in safe demo mode (local grab + close button).",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
@ -16,11 +16,8 @@ from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from diet_guard._averages import (
|
||||
band_label,
|
||||
monthly_average,
|
||||
weekly_average,
|
||||
)
|
||||
from diet_guard._averages import band_label
|
||||
from diet_guard._averages_report import monthly_average, weekly_average
|
||||
from diet_guard._budget import (
|
||||
BudgetFileCorruptError,
|
||||
BudgetNotInitializedError,
|
||||
|
||||
@ -14,6 +14,7 @@ from diet_guard._gate import gate_is_due
|
||||
from diet_guard._gatelock import MealGate, acquire_gate_lock, release_gate_lock
|
||||
from diet_guard._gatelock_support import wait_for_display
|
||||
from diet_guard._sync import pull_shared_log
|
||||
from diet_guard._sync_events import publish_after_log
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
@ -79,4 +80,13 @@ def cmd_gate(emit: Callable[[str], None], *, check: bool, demo: bool) -> int:
|
||||
MealGate(demo_mode=demo).run()
|
||||
finally:
|
||||
release_gate_lock(handle)
|
||||
# Publish only once ``run()`` has returned -- i.e. the mainloop has ended and
|
||||
# the window is gone. Deliberately NOT inside the unlock handler: that runs
|
||||
# on the Tk thread with the lock still up, so a slow or hanging network call
|
||||
# would keep the user locked in behind a successful log. Here the worst case
|
||||
# is a late publish. One call site covers every unlock reason, including the
|
||||
# "Synced from another device" path, which hooking the log itself would miss.
|
||||
reason = publish_after_log()
|
||||
if reason is not None:
|
||||
emit(f"logged locally, not yet published ({reason}).")
|
||||
return 0
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user