mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-23 21:06:32 +01:00
Final batch of the 250-line sweep. `check_file_length.sh --all` exits 0: every file in the repo is at or under 250 lines. github_mirror_screen.dart 391 -> 205 (+ actions, client_id_dialog parts) foodbank_service.dart 314 -> 209 (+ foodbank_service_manual part) settings_screen.dart 286 -> 237 (+ settings_kcal_goal part) firebase_backend.dart 282 -> 100 (+ firebase_client.dart) Three of the four are `part` files rather than separate libraries, and that is forced rather than stylistic: the moved code drives private state (`_busy`, `_status`, the text controllers) and calls private helpers (`_readBank`, `_normalize`), none of which are visible across a library boundary in Dart. Widening them to public just to split a file would leak internals the rest of the app has no business calling. Within those parts, mixins rather than extensions, for a concrete reason: an extension is not a subclass of `State`, so calling `setState` from one is an `invalid_use_of_protected_member`. Fields the State must own (the controllers it creates and disposes) stay declared there and are reached through abstract getters. `firebase_client.dart` is a real library split -- opening an authenticated client has no private coupling to the keystore-backed account record, only to its public API. The one exception, dropping the account marker without setting the opt-out flag, became `forgetAccountMarker()` rather than exposing the secure store. Verified: flutter test 555 (unchanged), flutter analyze clean, 707 Python tests / 100% branch coverage, check_patch_targets 0, pre-commit clean, check_file_length.sh --all exit 0. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
210 lines
6.5 KiB
Dart
210 lines
6.5 KiB
Dart
/// Local food-bank (autocomplete index), mirroring diet_guard's
|
|
/// `_foodbank.py` -- but *derived*, not synced (see Milestone 3's decision
|
|
/// to avoid counter-merge logic entirely: every device rebuilds its own
|
|
/// bank by replaying its own post-merge log).
|
|
library;
|
|
|
|
import 'dart:convert';
|
|
|
|
import 'package:diet_guard_app/models/food_bank_record.dart';
|
|
import 'package:diet_guard_app/models/food_suggestion.dart';
|
|
import 'package:diet_guard_app/models/nutrition.dart';
|
|
import 'package:diet_guard_app/services/document_store.dart';
|
|
import 'package:diet_guard_app/services/document_store_factory.dart';
|
|
import 'package:diet_guard_app/services/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;
|
|
|
|
/// Default number of autocomplete suggestions to surface. Mirrors
|
|
/// `_foodbank.DEFAULT_SUGGESTIONS`.
|
|
const int defaultSuggestions = 8;
|
|
|
|
String _normalize(String description) => description.trim().toLowerCase();
|
|
|
|
Nutrition _recordToNutrition(FoodBankRecord record) => Nutrition(
|
|
kcal: record.kcal,
|
|
proteinG: record.proteinG,
|
|
carbsG: record.carbsG,
|
|
fatG: record.fatG,
|
|
grams: record.grams,
|
|
source: 'food bank',
|
|
);
|
|
|
|
String _displayName(FoodBankRecord record, String key) =>
|
|
record.desc.trim().isEmpty ? key : record.desc;
|
|
|
|
/// Singleton service for the locally-rebuilt food bank.
|
|
class FoodBankService {
|
|
FoodBankService._(this._store);
|
|
|
|
/// Document holding the log-derived bank. Unchanged from the pre-web
|
|
/// on-disk filename so an installed phone keeps its existing bank.
|
|
static const documentName = 'food_bank.json';
|
|
|
|
/// Document holding the manually-curated bank.
|
|
static const manualDocumentName = 'food_bank_manual.json';
|
|
|
|
static FoodBankService? _instance;
|
|
|
|
/// Returns the initialized singleton; throws if [init] was not called.
|
|
static FoodBankService get instance => _instance!;
|
|
|
|
final DocumentStore _store;
|
|
|
|
/// Initializes the singleton, pointing at the app's documents directory.
|
|
static Future<FoodBankService> init() async {
|
|
if (_instance != null) return _instance!;
|
|
final svc = FoodBankService._(await openDocumentStore());
|
|
_instance = svc;
|
|
return svc;
|
|
}
|
|
|
|
/// Resets the singleton so [init] can be called again in tests.
|
|
@visibleForTesting
|
|
static void resetForTesting({DocumentStore? store}) {
|
|
_instance = store == null ? null : FoodBankService._(store);
|
|
}
|
|
|
|
/// Reads the persisted bank (empty map on a missing/unparsable document).
|
|
Future<Map<String, FoodBankRecord>> readBank() => _readBank(documentName);
|
|
|
|
/// Persists [bank].
|
|
Future<void> writeBank(Map<String, FoodBankRecord> bank) =>
|
|
_writeBank(documentName, bank);
|
|
|
|
Future<Map<String, FoodBankRecord>> _readBank(String name) async {
|
|
final raw = await _store.read(name);
|
|
if (raw == null) return {};
|
|
Object? data;
|
|
try {
|
|
data = jsonDecode(raw);
|
|
} on FormatException {
|
|
return {};
|
|
}
|
|
if (data is! Map) return {};
|
|
final result = <String, FoodBankRecord>{};
|
|
for (final mapEntry in data.entries) {
|
|
final key = mapEntry.key;
|
|
final value = mapEntry.value;
|
|
if (key is String && value is Map) {
|
|
result[key] = FoodBankRecord.fromJson(value.cast<String, dynamic>());
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
Future<void> _writeBank(
|
|
String name,
|
|
Map<String, FoodBankRecord> bank,
|
|
) async {
|
|
final encoded = <String, Object?>{
|
|
for (final mapEntry in bank.entries)
|
|
mapEntry.key: mapEntry.value.toJson(),
|
|
};
|
|
await _store.write(name, jsonEncode(encoded));
|
|
}
|
|
|
|
/// Rebuilds the bank by replaying [log]'s entries in a fixed, device-
|
|
/// independent order (by `time` then `id`), so any two devices that
|
|
/// converge on the same merged log also converge on the same bank.
|
|
///
|
|
/// Pure -- no I/O -- so it is independently unit-testable, mirroring
|
|
/// `_foodbank.remember_food`/`remember_meal`'s upsert semantics: latest
|
|
/// macros win per normalized name, `count` increments per occurrence.
|
|
static Map<String, FoodBankRecord> rebuild(DayLog log) {
|
|
final entries =
|
|
log.values
|
|
.expand((entries) => entries)
|
|
.where((entry) => !entry.deleted)
|
|
.toList()
|
|
..sort((a, b) {
|
|
final byTime = a.time.compareTo(b.time);
|
|
return byTime != 0 ? byTime : (a.id ?? '').compareTo(b.id ?? '');
|
|
});
|
|
final bank = <String, FoodBankRecord>{};
|
|
for (final entry in entries) {
|
|
final components = entry.components;
|
|
if (components != null) {
|
|
for (final component in components) {
|
|
_upsert(
|
|
bank,
|
|
component.name,
|
|
Nutrition(
|
|
kcal: component.kcal,
|
|
proteinG: component.proteinG,
|
|
carbsG: component.carbsG,
|
|
fatG: component.fatG,
|
|
grams: component.grams,
|
|
source: 'food bank',
|
|
),
|
|
null,
|
|
);
|
|
}
|
|
_upsert(
|
|
bank,
|
|
entry.desc,
|
|
Nutrition(
|
|
kcal: entry.kcal,
|
|
proteinG: entry.proteinG,
|
|
carbsG: entry.carbsG,
|
|
fatG: entry.fatG,
|
|
grams: entry.grams,
|
|
source: entry.source,
|
|
),
|
|
components.map((c) => c.name).toList(),
|
|
);
|
|
} else {
|
|
_upsert(
|
|
bank,
|
|
entry.desc,
|
|
Nutrition(
|
|
kcal: entry.kcal,
|
|
proteinG: entry.proteinG,
|
|
carbsG: entry.carbsG,
|
|
fatG: entry.fatG,
|
|
grams: entry.grams,
|
|
source: entry.source,
|
|
),
|
|
null,
|
|
);
|
|
}
|
|
}
|
|
return bank;
|
|
}
|
|
|
|
static void _upsert(
|
|
Map<String, FoodBankRecord> bank,
|
|
String description,
|
|
Nutrition nutrition,
|
|
List<String>? components,
|
|
) {
|
|
final key = _normalize(description);
|
|
if (key.isEmpty) return;
|
|
final previous = bank[key];
|
|
final count = (previous?.count ?? 0) + 1;
|
|
bank[key] = FoodBankRecord(
|
|
desc: description.trim(),
|
|
kcal: nutrition.kcal,
|
|
proteinG: nutrition.proteinG,
|
|
carbsG: nutrition.carbsG,
|
|
fatG: nutrition.fatG,
|
|
grams: nutrition.grams,
|
|
count: count,
|
|
components: components,
|
|
);
|
|
}
|
|
|
|
/// Rebuilds the bank from [log] and persists it, returning the result.
|
|
Future<Map<String, FoodBankRecord>> rebuildAndPersist(DayLog log) async {
|
|
final bank = rebuild(log);
|
|
await writeBank(bank);
|
|
return bank;
|
|
}
|
|
}
|