diff --git a/AGENTS.md b/AGENTS.md index b4830fd..26d8853 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -143,6 +143,7 @@ install -e`, so the clone must persist for `git pull` to reach the running servi `test_budget_history.py`; it syncs as `hist:` fields on the existing `budget` record, so devices predating the feature relay them untouched. +- **Offline first**: save locally before any network call; store fetched data on disk (`kuchnia_delivery.json`, both devices). - **Body data persists and syncs** (profile, weight log, PC workouts) as `body.json`; its tables are informational. [docs/DOCS-body.md](docs/DOCS-body.md). - **PC and phone share one source of truth for everything**: food log, budget, diff --git a/app/android/gradle/wrapper/gradle-wrapper.properties b/app/android/gradle/wrapper/gradle-wrapper.properties index 1e395d3..4307e1c 100644 --- a/app/android/gradle/wrapper/gradle-wrapper.properties +++ b/app/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.2-all.zip diff --git a/app/lib/main.dart b/app/lib/main.dart index e9b4af8..d6a8e9b 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -13,9 +13,11 @@ import 'package:diet_guard_app/services/body_service.dart'; import 'package:diet_guard_app/services/budget_history_service.dart'; import 'package:diet_guard_app/services/claude_relay_client.dart'; import 'package:diet_guard_app/services/claude_relay_firebase.dart'; +import 'package:diet_guard_app/services/document_store_factory.dart'; import 'package:diet_guard_app/services/firebase_client.dart' show openFirebase; import 'package:diet_guard_app/services/foodbank_service.dart'; import 'package:diet_guard_app/services/frame_stats.dart'; +import 'package:diet_guard_app/services/kuchnia_autolog.dart'; import 'package:diet_guard_app/services/kuchnia_credential_service.dart'; import 'package:diet_guard_app/services/kuchnia_queue.dart'; import 'package:diet_guard_app/services/log_storage_service.dart'; @@ -56,6 +58,8 @@ Future main() async { await KuchniaCredentialService.init(); await BodyService.init(); await KuchniaQueueService.init(); + // Offline first: the day's catering dishes survive a restart. + KuchniaAutoLog.instance = KuchniaAutoLog(store: await openDocumentStore()); // The sparkle button's transport; until this line it fails closed. claudeRelay = RtdbClaudeRelay.firebase(); final notifications = await NotificationService.init(); diff --git a/app/lib/models/kuchnia_dish.dart b/app/lib/models/kuchnia_dish.dart index e0a0451..699b81d 100644 --- a/app/lib/models/kuchnia_dish.dart +++ b/app/lib/models/kuchnia_dish.dart @@ -23,6 +23,32 @@ class KuchniaDish { this.dishId = '', }); + /// Rebuilds a dish stored by [toJson]; throws on a malformed record. + factory KuchniaDish.fromJson(Map json) => KuchniaDish( + name: json['name']! as String, + kcal: (json['kcal']! as num).toDouble(), + proteinG: (json['protein_g']! as num).toDouble(), + carbsG: (json['carbs_g']! as num).toDouble(), + fatG: (json['fat_g']! as num).toDouble(), + grams: (json['grams']! as num).toDouble(), + priority: json['priority']! as int, + slotLabel: json['slot_label']! as String, + dishId: json['dish_id'] as String? ?? '', + ); + + /// The stored form; the keys follow the PC's `kuchnia_delivery.json`. + Map toJson() => { + 'name': name, + 'kcal': kcal, + 'protein_g': proteinG, + 'carbs_g': carbsG, + 'fat_g': fatG, + 'grams': grams, + 'priority': priority, + 'slot_label': slotLabel, + 'dish_id': dishId, + }; + /// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...". /// /// Not `mealName`, which is the slot label ("Kolacja") and would collapse diff --git a/app/lib/services/kuchnia_autolog.dart b/app/lib/services/kuchnia_autolog.dart index f8e810c..1a0cfbd 100644 --- a/app/lib/services/kuchnia_autolog.dart +++ b/app/lib/services/kuchnia_autolog.dart @@ -13,16 +13,21 @@ /// An undone dish keeps its tombstone, so it is never logged a second time. /// /// The fetch is a third-party login, so the day's dishes are cached in memory -/// and a failed or empty fetch is retried at most every [retryAfter]. +/// and in `store` (`kuchnia_delivery.json`), so a restart or an outage still +/// has them (offline first); a failed or empty fetch is retried at most every +/// [retryAfter]. /// `KuchniaQueueService.refreshOnce` cannot serve here: after the first clean /// fetch of the day it returns nothing, and slots that fall due later would /// never see their dish. library; +import 'dart:convert'; + import 'package:diet_guard_app/models/food_entry.dart'; import 'package:diet_guard_app/models/kuchnia_dish.dart'; import 'package:diet_guard_app/models/local_time.dart'; import 'package:diet_guard_app/models/slot.dart'; +import 'package:diet_guard_app/services/document_store.dart'; import 'package:diet_guard_app/services/kuchnia_fill.dart'; import 'package:diet_guard_app/services/kuchnia_fill_flow.dart'; import 'package:diet_guard_app/services/kuchnia_import.dart'; @@ -44,6 +49,7 @@ class KuchniaAutoLog { DeliveryFetch? fetch, DateTime Function()? now, this.retryAfter = const Duration(minutes: 10), + this.store, }) : _fetch = fetch ?? refreshDelivery, _now = now ?? DateTime.now; @@ -53,6 +59,12 @@ class KuchniaAutoLog { /// Minimum gap between fetches that found nothing or failed. final Duration retryAfter; + /// Keeps the day's dishes across restarts; null keeps them in memory only. + final DocumentStore? store; + + /// The document [store] holds the last fetched delivery in. + static const documentName = 'kuchnia_delivery.json'; + final DeliveryFetch _fetch; final DateTime Function() _now; String? _cachedDay; @@ -94,14 +106,56 @@ class KuchniaAutoLog { Future> _dishesFor(DateTime today, String dayKey) async { if (_cachedDay == dayKey) return _cachedDishes; + final stored = await _readStored(dayKey); + if (stored.isNotEmpty) { + _cachedDay = dayKey; + return _cachedDishes = stored; + } final last = _lastEmptyFetch; if (last != null && _now().difference(last) < retryAfter) return const []; final result = await _fetch(today); if (result.ok && result.dishes.isNotEmpty) { _cachedDay = dayKey; + await _writeStored(dayKey, result.dishes); return _cachedDishes = result.dishes; } _lastEmptyFetch = _now(); return const []; } + + Future> _readStored(String dayKey) async { + final target = store; + if (target == null) return const []; + try { + final raw = await target.read(documentName); + if (raw == null) return const []; + final data = jsonDecode(raw); + if (data is! Map || data['day'] != dayKey) { + return const []; + } + final dishes = data['dishes']; + if (dishes is! List) return const []; + return [ + for (final item in dishes) + if (item is Map) KuchniaDish.fromJson(item), + ]; + } on Object { + // A missing, foreign or malformed file is "nothing stored": fetch again. + return const []; + } + } + + Future _writeStored(String dayKey, List dishes) async { + final target = store; + if (target == null) return; + final body = { + 'day': dayKey, + 'dishes': [for (final dish in dishes) dish.toJson()], + }; + try { + await target.write(documentName, jsonEncode(body)); + } on Exception { + // Best-effort: an unsaved delivery only costs a refetch after a restart. + } + } } diff --git a/app/pubspec.lock b/app/pubspec.lock index 7e35f0b..9f42d3d 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -157,20 +157,20 @@ packages: dependency: "direct main" description: path: crdt_sync_dart - ref: "crdt_sync_dart-v0.14.1" - resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df + ref: "crdt_sync_dart-v0.14.2" + resolved-ref: "171a7f8ae34cec78df17a680e42878ca0b97c137" url: "https://github.com/kuhyx/utils" source: git - version: "0.14.1" + version: "0.14.2" crdt_sync_flutter: dependency: "direct main" description: path: crdt_sync_flutter - ref: "crdt_sync_flutter-v0.9.1" - resolved-ref: "48dc28ad97b97c787aba4479c3ce51aade6e86b5" + ref: "crdt_sync_flutter-v0.9.2" + resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf" url: "https://github.com/kuhyx/utils" source: git - version: "0.9.1" + version: "0.9.2" cross_file: dependency: transitive description: @@ -413,10 +413,10 @@ packages: dependency: "direct main" description: name: flutter_local_notifications - sha256: "7d37d69ded3028af4f22531a0097a3baa478a384dff2e23e873707c93df3b704" + sha256: "2b7579556c117b535ef83835798a7f3c4003dc892a888a4a99f2107bca7b6675" url: "https://pub.dev" source: hosted - version: "23.0.3" + version: "23.0.4" flutter_local_notifications_linux: dependency: transitive description: @@ -1076,11 +1076,11 @@ packages: dependency: "direct main" description: path: sync_settings_ui - ref: "sync_settings_ui-v0.8.5" - resolved-ref: abfb596d7ce2f28acfefbd55e7b3227257325261 + ref: "sync_settings_ui-v0.8.6" + resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf" url: "https://github.com/kuhyx/utils" source: git - version: "0.8.5" + version: "0.8.6" synchronized: dependency: transitive description: diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 3ace666..5c65fe2 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -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.193+1 +version: 1.0.194+1 environment: sdk: ^3.12.2 @@ -12,13 +12,13 @@ dependencies: crdt_sync: git: url: https://github.com/kuhyx/utils - ref: crdt_sync_dart-v0.14.1 + ref: crdt_sync_dart-v0.14.2 path: crdt_sync_dart # Keystore-backed end-to-end encryption open + the passphrase lock button. crdt_sync_flutter: git: url: https://github.com/kuhyx/utils - ref: crdt_sync_flutter-v0.9.1 + ref: crdt_sync_flutter-v0.9.2 path: crdt_sync_flutter crypto: 3.0.8 cryptography: 2.9.0 @@ -32,7 +32,7 @@ dependencies: fl_chart: 1.3.1 flutter: sdk: flutter - flutter_local_notifications: 23.0.3 + flutter_local_notifications: 23.0.4 flutter_secure_storage: 11.2.0 # One-tap sign-in for the sync account. App-side only: crdt_sync stays pure @@ -71,7 +71,7 @@ dependencies: sync_settings_ui: git: url: https://github.com/kuhyx/utils - ref: sync_settings_ui-v0.8.5 + ref: sync_settings_ui-v0.8.6 path: sync_settings_ui url_launcher: 6.3.3 uuid: 4.6.0 diff --git a/app/test/services/kuchnia_autolog_store_test.dart b/app/test/services/kuchnia_autolog_store_test.dart new file mode 100644 index 0000000..0d7ef07 --- /dev/null +++ b/app/test/services/kuchnia_autolog_store_test.dart @@ -0,0 +1,123 @@ +// The auto-log keeps the day's delivery on disk: offline first. +// +// A restart, or the caterer's panel being down, must not cost the dishes +// already fetched today. These tests pass an in-memory store as the disk. +import 'dart:convert'; + +import 'package:diet_guard_app/models/kuchnia_dish.dart'; +import 'package:diet_guard_app/models/local_time.dart'; +import 'package:diet_guard_app/services/document_store.dart'; +import 'package:diet_guard_app/services/kuchnia_autolog.dart'; +import 'package:diet_guard_app/services/kuchnia_import.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../kuchnia_fill_support.dart'; + +KuchniaDish _dish(int n) => KuchniaDish( + name: 'D$n', + kcal: 100.0 * n, + proteinG: 10, + carbsG: 20, + fatG: 5, + grams: 300, + priority: n, + slotLabel: 'Obiad', + dishId: '${1000 + n}', +); + +/// A disk that is full: every write fails. +class _FullStore implements DocumentStore { + @override + Future read(String name) async => null; + + @override + Future write(String name, String contents) async => + throw Exception('disk'); +} + +void main() { + late int fetches; + late DateTime clock; + + setUp(() { + freshStorage(); + fetches = 0; + final today = DateTime.now(); + clock = DateTime(today.year, today.month, today.day, 13); + }); + + KuchniaAutoLog autoLog(DocumentStore store, KuchniaRefresh result) => + KuchniaAutoLog( + store: store, + fetch: (day) async { + fetches++; + return result; + }, + now: () => clock, + ); + + const down = KuchniaRefresh(reason: 'down'); + final delivered = KuchniaRefresh(dishes: [_dish(1), _dish(2)]); + + test('a restart with the panel down still logs the stored dish', () async { + final store = MemoryStore(); + await autoLog(store, delivered).logDue([960]); + expect(fetches, 1); + final written = await autoLog(store, down).logDue([480]); + expect(fetches, 1, reason: 'the stored delivery answers, no refetch'); + expect(written.map((e) => e.desc), ['D1']); + }); + + test('a stored delivery of another day is ignored', () async { + final store = MemoryStore(); + store.documents[KuchniaAutoLog.documentName] = jsonEncode({ + 'day': '1999-01-01', + 'dishes': [_dish(1).toJson()], + }); + expect(await autoLog(store, down).logDue([480]), isEmpty); + expect(fetches, 1); + }); + + test('a malformed stored document is ignored', () async { + final store = MemoryStore(); + for (final raw in [ + 'not json', + '[]', + jsonEncode({'day': localDateKey(clock), 'dishes': 'x'}), + jsonEncode({ + 'day': localDateKey(clock), + 'dishes': [ + {'name': 'D1'}, + ], + }), + ]) { + store.documents[KuchniaAutoLog.documentName] = raw; + expect(await autoLog(store, down).logDue([480]), isEmpty, reason: raw); + } + expect(fetches, 4); + }); + + test('non-map items in a stored delivery are skipped', () async { + final store = MemoryStore(); + store.documents[KuchniaAutoLog.documentName] = jsonEncode({ + 'day': localDateKey(clock), + 'dishes': [1, _dish(1).toJson()], + }); + final written = await autoLog(store, down).logDue([480]); + expect(written.map((e) => e.desc), ['D1']); + expect(fetches, 0); + }); + + test('a failing disk does not break logging', () async { + final written = await autoLog(_FullStore(), delivered).logDue([480]); + expect(written.map((e) => e.desc), ['D1']); + }); + + test('toJson and fromJson round-trip every field', () { + final dish = _dish(3); + final back = KuchniaDish.fromJson(dish.toJson()); + expect(back.toJson(), dish.toJson()); + final noId = Map.of(dish.toJson())..remove('dish_id'); + expect(KuchniaDish.fromJson(noId).dishId, ''); + }); +} diff --git a/dependency-freshness.allowlist.yaml b/dependency-freshness.allowlist.yaml index 1546ffa..d4c68c0 100644 --- a/dependency-freshness.allowlist.yaml +++ b/dependency-freshness.allowlist.yaml @@ -3,11 +3,11 @@ # they carry no `expires`; everything else is discretionary and expires. exceptions: - - ecosystem: gittag - package: kuhy-credit - pinned: 0.3.1 + - ecosystem: pypi + package: httpx + pinned: 0.28.1 reason: >- - sickdays 0.5.8 (its newest release) pins kuhy-credit 0.3.1 exactly, so - pip refuses 0.3.2 next to it. Taking 0.3.2 means holding sickdays back - instead; sickdays is the dependency the gate actually runs. - blocked_by: transitive:sickdays@0.5.8 + rtdb-relay 0.2.2 (its newest release) pins httpx 0.28.1 exactly, so pip + refuses 0.29.0 next to it. rtdb-relay is the Claude relay transport, so + httpx waits for it. + blocked_by: transitive:rtdb-relay@0.2.2 diff --git a/diet_guard/_constants.py b/diet_guard/_constants.py index 8e11f23..8e025f2 100644 --- a/diet_guard/_constants.py +++ b/diet_guard/_constants.py @@ -171,6 +171,10 @@ KUCHNIA_SYNCED_CREDENTIAL_FILE: Path = ( KUCHNIA_LAST_IMPORT_FILE: Path = ( Path.home() / ".config" / "diet_guard" / "kuchnia_last_import" ) +# The last successfully-fetched delivery, so a panel outage can fall back to +# it instead of a blank import. Under DATA_DIR, not ~/.config: it is a cache, +# regenerable on the next successful fetch. +KUCHNIA_DELIVERY_CACHE_FILE: Path = DATA_DIR / "kuchnia_delivery.json" KUCHNIA_TIMEOUT_SECONDS: float = 8.0 # Whole-walk ceiling. The import is 3-4 sequential requests, so a per-request # timeout alone would permit ~32s against a slow provider. diff --git a/diet_guard/_kuchnia_delivery_cache.py b/diet_guard/_kuchnia_delivery_cache.py new file mode 100644 index 0000000..995e6b7 --- /dev/null +++ b/diet_guard/_kuchnia_delivery_cache.py @@ -0,0 +1,85 @@ +"""A local cache of the last successfully-fetched Kuchnia delivery. + +Offline first: the panel is a third party that goes down, and a day's +delivery, once fetched, must stay usable without it. This module owns that +cache: :func:`save_delivery` after a successful fetch, :func:`load_delivery` +when the panel fails or the day was already fetched. + +Every failure mode is "no cache": a missing file, bad JSON, another day's +delivery, or a half-written record all mean "fetch again", which is always +safe. The phone keeps the same file (``KuchniaAutoLog.store``). +""" + +from __future__ import annotations + +import dataclasses +import json +import logging +from typing import TYPE_CHECKING + +from diet_guard import _constants +from diet_guard._kuchnia_parse import Dish + +if TYPE_CHECKING: # pragma: no cover - typing only + from collections.abc import Sequence + from datetime import date + +_LOGGER = logging.getLogger(__name__) + + +def load_delivery(day: date) -> list[Dish]: + """Return the dishes cached for ``day``'s delivery, or ``[]``. + + Any unreadable, malformed or foreign-day cache is treated as "no cache" + rather than an error: the caller falls back to the panel fetch, which is + strictly better than a stale import. + """ + path = _constants.KUCHNIA_DELIVERY_CACHE_FILE + try: + if not path.exists(): + return [] + raw = path.read_text() + except OSError: + return [] + try: + data = json.loads(raw) + except json.JSONDecodeError: + return [] + if not isinstance(data, dict) or data.get("day") != day.isoformat(): + return [] + dishes = data.get("dishes") + if not isinstance(dishes, list): + return [] + out: list[Dish] = [] + for item in dishes: + if not isinstance(item, dict): + continue + try: + out.append(Dish(**item)) + except TypeError: + continue + return out + + +def save_delivery(day: date, dishes: Sequence[Dish]) -> None: + """Persist ``day``'s delivery so a later outage can still import it. + + Best-effort: a write failure only costs the fallback, so it is logged + and swallowed, never raised into the import path. The write goes to a + sibling ``.tmp`` and is atomically renamed, so a half-written file can + never poison :func:`load_delivery`. + """ + path = _constants.KUCHNIA_DELIVERY_CACHE_FILE + payload = json.dumps( + { + "day": day.isoformat(), + "dishes": [dataclasses.asdict(d) for d in dishes], + } + ) + try: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(payload) + tmp.replace(path) + except OSError: + _LOGGER.warning("could not save the kitchen delivery cache") diff --git a/diet_guard/_kuchnia_import.py b/diet_guard/_kuchnia_import.py index 9ee5490..6952cc1 100644 --- a/diet_guard/_kuchnia_import.py +++ b/diet_guard/_kuchnia_import.py @@ -24,6 +24,7 @@ from typing import TYPE_CHECKING from diet_guard._foodbank_manual import add_manual_entry, read_manual_bank from diet_guard._kuchnia_client import PanelSession from diet_guard._kuchnia_config import last_import_day, record_import_day +from diet_guard._kuchnia_delivery_cache import load_delivery, save_delivery from diet_guard._kuchnia_errors import KuchniaError from diet_guard._kuchnia_orders import fetch_dishes @@ -90,16 +91,22 @@ def refresh_delivery(day: date) -> tuple[list[Dish], str | None]: day: The delivery date to fetch. Returns: - ``(dishes, None)`` on success, or ``([], reason)`` when the catering - panel could not be read. Callers surface the reason and carry on. + ``(dishes, None)`` on success. On a panel outage, the cached + delivery for ``day`` when one exists ``(cached, None)``, otherwise + ``([], reason)`` with the failure reason so callers can surface it + and carry on. """ try: session = PanelSession() session.authenticate() dishes = fetch_dishes(session, day) except KuchniaError as exc: + if cached := load_delivery(day): + return cached, None return [], str(exc) bank_dishes(dishes) + if dishes: + save_delivery(day, dishes) return dishes, None @@ -123,12 +130,13 @@ def refresh_delivery_once(day: date) -> tuple[list[Dish], str | None]: day: The delivery date to fetch. Returns: - ``([], None)`` when today was already fetched -- "nothing new", not an + ``(cached, None)`` when today was already fetched -- ``cached`` is the + saved delivery for the day (possibly empty), "nothing new", not an error. Otherwise whatever :func:`refresh_delivery` returns. """ stamp = day.isoformat() if last_import_day() == stamp: - return [], None + return load_delivery(day), None dishes, reason = refresh_delivery(day) if reason is None and dishes: # Only a fetch that found dishes counts: an outage, or a walk that diff --git a/diet_guard/tests/_state_redirects.py b/diet_guard/tests/_state_redirects.py index 738bcf0..46dabf4 100644 --- a/diet_guard/tests/_state_redirects.py +++ b/diet_guard/tests/_state_redirects.py @@ -151,6 +151,12 @@ def state_redirects(tmp_path: Path) -> list[_patch[object]]: "diet_guard._kuchnia_config.KUCHNIA_LAST_IMPORT_FILE", tmp_path / "kuchnia_last_import", ), + # The outage fallback cache: without this a refresh_delivery test that + # saves one lands in the real DATA_DIR. + patch( + "diet_guard._constants.KUCHNIA_DELIVERY_CACHE_FILE", + tmp_path / "kuchnia_delivery.json", + ), # The catering fetch is a third network entry point. Patched at each # call site, so a test importing `refresh_delivery` directly still # exercises the real helper. diff --git a/diet_guard/tests/test_kuchnia_delivery_cache.py b/diet_guard/tests/test_kuchnia_delivery_cache.py new file mode 100644 index 0000000..0b46b01 --- /dev/null +++ b/diet_guard/tests/test_kuchnia_delivery_cache.py @@ -0,0 +1,155 @@ +"""The Kuchnia delivery cache: an outage falls back to the last fetched day. + +Every on-disk write in these tests lands in the conftest-redirected tmp +state; the two ``pathlib`` patches below are the only fault injection. +""" + +from __future__ import annotations + +from contextlib import contextmanager +import dataclasses +from datetime import date +import json +from typing import TYPE_CHECKING +from unittest.mock import Mock, patch + +from diet_guard import _constants +from diet_guard._kuchnia_config import record_import_day +from diet_guard._kuchnia_delivery_cache import load_delivery, save_delivery +from diet_guard._kuchnia_errors import KuchniaError +from diet_guard._kuchnia_import import refresh_delivery, refresh_delivery_once +from diet_guard._kuchnia_parse import Dish + +if TYPE_CHECKING: + from collections.abc import Iterator + +DAY = date(2026, 11, 27) + + +def _dish() -> Dish: + return Dish("Osobiste danie", 300.0, 10.0, 20.0, 2.0, 250.0, 1, "obiad") + + +def _write_cache(payload: object) -> None: + _constants.KUCHNIA_DELIVERY_CACHE_FILE.write_text(json.dumps(payload)) + + +# --- load_delivery ---------------------------------------------------------- + + +def test_save_then_load_round_trip() -> None: + save_delivery(DAY, [_dish()]) + assert load_delivery(DAY) == [_dish()] + + +def test_load_missing_file() -> None: + assert load_delivery(DAY) == [] + + +def test_load_wrong_day() -> None: + save_delivery(DAY, [_dish()]) + assert load_delivery(date(2026, 11, 28)) == [] + + +def test_load_malformed_json() -> None: + _constants.KUCHNIA_DELIVERY_CACHE_FILE.write_text("not json") + assert load_delivery(DAY) == [] + + +def test_load_top_level_not_a_dict() -> None: + _write_cache([]) + assert load_delivery(DAY) == [] + + +def test_load_dishes_not_a_list() -> None: + _write_cache({"day": DAY.isoformat(), "dishes": "nope"}) + assert load_delivery(DAY) == [] + + +def test_load_skips_non_dict_items() -> None: + _write_cache( + { + "day": DAY.isoformat(), + "dishes": [42, dataclasses.asdict(_dish())], + } + ) + assert load_delivery(DAY) == [_dish()] + + +def test_load_skips_unknown_key_items() -> None: + _write_cache( + { + "day": DAY.isoformat(), + "dishes": [{"bogus_key": 1}, dataclasses.asdict(_dish())], + } + ) + assert load_delivery(DAY) == [_dish()] + + +def test_load_oserror_on_read() -> None: + save_delivery(DAY, [_dish()]) + with patch("pathlib.Path.read_text", side_effect=OSError("io")): + assert load_delivery(DAY) == [] + + +def test_save_oserror_on_write() -> None: + with patch("pathlib.Path.write_text", side_effect=OSError("io")): + save_delivery(DAY, [_dish()]) # must not raise + assert not _constants.KUCHNIA_DELIVERY_CACHE_FILE.exists() + + +# --- refresh_delivery ------------------------------------------------------- + + +@contextmanager +def _patched_fetch(**mock_kwargs: object) -> Iterator[Mock]: + """Patch the panel login and the dish walk; yield the ``fetch_dishes`` mock.""" + with ( + patch("diet_guard._kuchnia_import.PanelSession", return_value=Mock()), + patch("diet_guard._kuchnia_import.fetch_dishes", **mock_kwargs) as fetch, + ): + yield fetch + + +def test_refresh_delivery_success_saves_cache() -> None: + with _patched_fetch(return_value=[_dish()]): + dishes, reason = refresh_delivery(DAY) + assert dishes == [_dish()] + assert reason is None + assert load_delivery(DAY) == [_dish()] + + +def test_refresh_delivery_outage_falls_back_to_cache() -> None: + save_delivery(DAY, [_dish()]) + with _patched_fetch(side_effect=KuchniaError("down")): + dishes, reason = refresh_delivery(DAY) + assert dishes == [_dish()] + assert reason is None + + +def test_refresh_delivery_outage_without_cache_reports_reason() -> None: + with _patched_fetch(side_effect=KuchniaError("down")): + dishes, reason = refresh_delivery(DAY) + assert dishes == [] + assert reason == "down" + + +def test_refresh_delivery_success_with_no_dishes_skips_cache() -> None: + with _patched_fetch(return_value=[]): + dishes, reason = refresh_delivery(DAY) + assert dishes == [] + assert reason is None + assert load_delivery(DAY) == [] + + +# --- refresh_delivery_once -------------------------------------------------- + + +def test_refresh_delivery_once_after_import_day_reads_cache() -> None: + record_import_day(DAY.isoformat()) + save_delivery(DAY, [_dish()]) + with patch("diet_guard._kuchnia_import.fetch_dishes") as fetch: + dishes, reason = refresh_delivery_once(DAY) + fetch.assert_not_called() + assert dishes == [_dish()] + assert reason is None diff --git a/docs/DOCS-kuchnia-wikinga-phone.md b/docs/DOCS-kuchnia-wikinga-phone.md index b3d5ce4..d4cb396 100644 --- a/docs/DOCS-kuchnia-wikinga-phone.md +++ b/docs/DOCS-kuchnia-wikinga-phone.md @@ -40,8 +40,10 @@ from the phone; `FillAllFlow` stays as the tested plan logic. undo plus the next resume would log the dish again. - **The fetch is cached.** `KuchniaQueueService.refreshOnce` returns nothing after the day's first clean fetch, so a slot falling due at 12:00 would never - see its dish. `KuchniaAutoLog` keeps the day's dishes in memory and retries a - failed or empty fetch at most every 10 minutes (a login per try). + see its dish. `KuchniaAutoLog` keeps the day's dishes in memory and in + `kuchnia_delivery.json` (offline first: a restart or a panel outage still has + them), and retries a failed or empty fetch at most every 10 minutes (a login + per try). The PC keeps the same file (`_kuchnia_delivery_cache.py`). - Each logged dish shows as a row: restaurant glyph, name, kcal and macro dots, a 48 dp undo. One publish per batch (`publishAfterLog`). - Unverified: whether `deliveryMealId` is stable across fetches on the live diff --git a/pyproject.toml b/pyproject.toml index a9a28be..bcb1aa5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,17 +4,17 @@ version = "1.0.0" description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget tracking" requires-python = ">=3.14" dependencies = [ - "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.0#subdirectory=gatelock", + "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock", "crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync", - "freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays", - "kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit", + "freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays", + "kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit", "holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds", - "sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.8#subdirectory=sickdays", - "claude-agent-sdk==0.2.187", + "sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays", + "claude-agent-sdk==0.2.189", "defusedxml==0.7.1", "httpx==0.28.1", "requests==2.34.2", - "rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay", + "rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.2#subdirectory=rtdb_relay", ] # Optional extras. The `mcp` group is ONLY needed by the MCP server diff --git a/requirements.txt b/requirements.txt index 047f7a1..ddefbfb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,17 +1,17 @@ # Diet Guard — runtime + development dependencies # Runtime: tkinter/json/hmac/fcntl (stdlib) plus gatelock and requests below. bandit==1.9.4 -claude-agent-sdk==0.2.187 +claude-agent-sdk==0.2.189 codespell==2.4.3 -coverage==7.17.4 +coverage==7.17.5 crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync defusedxml==0.7.1 -freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays -gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.0#subdirectory=gatelock +freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays +gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds httpx==0.28.1 hypothesis==6.170.17 -kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit +kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit mcp==2.3.0 mypy==2.4.1 pre-commit==4.7.0 @@ -24,6 +24,6 @@ pytest-sugar==1.1.1 pytest-xdist==3.8.0 pytest-xvfb==3.1.1 requests==2.34.2 -rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay +rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.2#subdirectory=rtdb_relay ruff==0.17.6 -sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.8#subdirectory=sickdays +sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays