overlaying rule to ALL apps that sync and share c…
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run

Todo: c5ee9e59
This commit is contained in:
Krzysztof Rudnicki 2026-11-27 12:38:31 +01:00
parent e3790d41e7
commit fab0c937cf
17 changed files with 512 additions and 44 deletions

View File

@ -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:<YYYY-MM-DD>` fields on the `test_budget_history.py`; it syncs as `hist:<YYYY-MM-DD>` fields on the
existing `budget` record, so devices predating the feature relay them existing `budget` record, so devices predating the feature relay them
untouched. 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 data persists and syncs** (profile, weight log, PC workouts) as
`body.json`; its tables are informational. [docs/DOCS-body.md](docs/DOCS-body.md). `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, - **PC and phone share one source of truth for everything**: food log, budget,

View File

@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists 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

View File

@ -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/budget_history_service.dart';
import 'package:diet_guard_app/services/claude_relay_client.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/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/firebase_client.dart' show openFirebase;
import 'package:diet_guard_app/services/foodbank_service.dart'; import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/frame_stats.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_credential_service.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart'; import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
@ -56,6 +58,8 @@ Future<void> main() async {
await KuchniaCredentialService.init(); await KuchniaCredentialService.init();
await BodyService.init(); await BodyService.init();
await KuchniaQueueService.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. // The sparkle button's transport; until this line it fails closed.
claudeRelay = RtdbClaudeRelay.firebase(); claudeRelay = RtdbClaudeRelay.firebase();
final notifications = await NotificationService.init(); final notifications = await NotificationService.init();

View File

@ -23,6 +23,32 @@ class KuchniaDish {
this.dishId = '', this.dishId = '',
}); });
/// Rebuilds a dish stored by [toJson]; throws on a malformed record.
factory KuchniaDish.fromJson(Map<String, Object?> 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<String, Object?> 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...". /// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
/// ///
/// Not `mealName`, which is the slot label ("Kolacja") and would collapse /// Not `mealName`, which is the slot label ("Kolacja") and would collapse

View File

@ -13,16 +13,21 @@
/// An undone dish keeps its tombstone, so it is never logged a second time. /// 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 /// 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 /// `KuchniaQueueService.refreshOnce` cannot serve here: after the first clean
/// fetch of the day it returns nothing, and slots that fall due later would /// fetch of the day it returns nothing, and slots that fall due later would
/// never see their dish. /// never see their dish.
library; library;
import 'dart:convert';
import 'package:diet_guard_app/models/food_entry.dart'; import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/kuchnia_dish.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/local_time.dart';
import 'package:diet_guard_app/models/slot.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.dart';
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart'; import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart'; import 'package:diet_guard_app/services/kuchnia_import.dart';
@ -44,6 +49,7 @@ class KuchniaAutoLog {
DeliveryFetch? fetch, DeliveryFetch? fetch,
DateTime Function()? now, DateTime Function()? now,
this.retryAfter = const Duration(minutes: 10), this.retryAfter = const Duration(minutes: 10),
this.store,
}) : _fetch = fetch ?? refreshDelivery, }) : _fetch = fetch ?? refreshDelivery,
_now = now ?? DateTime.now; _now = now ?? DateTime.now;
@ -53,6 +59,12 @@ class KuchniaAutoLog {
/// Minimum gap between fetches that found nothing or failed. /// Minimum gap between fetches that found nothing or failed.
final Duration retryAfter; 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 DeliveryFetch _fetch;
final DateTime Function() _now; final DateTime Function() _now;
String? _cachedDay; String? _cachedDay;
@ -94,14 +106,56 @@ class KuchniaAutoLog {
Future<List<KuchniaDish>> _dishesFor(DateTime today, String dayKey) async { Future<List<KuchniaDish>> _dishesFor(DateTime today, String dayKey) async {
if (_cachedDay == dayKey) return _cachedDishes; if (_cachedDay == dayKey) return _cachedDishes;
final stored = await _readStored(dayKey);
if (stored.isNotEmpty) {
_cachedDay = dayKey;
return _cachedDishes = stored;
}
final last = _lastEmptyFetch; final last = _lastEmptyFetch;
if (last != null && _now().difference(last) < retryAfter) return const []; if (last != null && _now().difference(last) < retryAfter) return const [];
final result = await _fetch(today); final result = await _fetch(today);
if (result.ok && result.dishes.isNotEmpty) { if (result.ok && result.dishes.isNotEmpty) {
_cachedDay = dayKey; _cachedDay = dayKey;
await _writeStored(dayKey, result.dishes);
return _cachedDishes = result.dishes; return _cachedDishes = result.dishes;
} }
_lastEmptyFetch = _now(); _lastEmptyFetch = _now();
return const []; return const [];
} }
Future<List<KuchniaDish>> _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<String, Object?> || 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<String, Object?>) KuchniaDish.fromJson(item),
];
} on Object {
// A missing, foreign or malformed file is "nothing stored": fetch again.
return const [];
}
}
Future<void> _writeStored(String dayKey, List<KuchniaDish> 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.
}
}
} }

View File

@ -157,20 +157,20 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
path: crdt_sync_dart path: crdt_sync_dart
ref: "crdt_sync_dart-v0.14.1" ref: "crdt_sync_dart-v0.14.2"
resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df resolved-ref: "171a7f8ae34cec78df17a680e42878ca0b97c137"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.14.1" version: "0.14.2"
crdt_sync_flutter: crdt_sync_flutter:
dependency: "direct main" dependency: "direct main"
description: description:
path: crdt_sync_flutter path: crdt_sync_flutter
ref: "crdt_sync_flutter-v0.9.1" ref: "crdt_sync_flutter-v0.9.2"
resolved-ref: "48dc28ad97b97c787aba4479c3ce51aade6e86b5" resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.9.1" version: "0.9.2"
cross_file: cross_file:
dependency: transitive dependency: transitive
description: description:
@ -413,10 +413,10 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: flutter_local_notifications name: flutter_local_notifications
sha256: "7d37d69ded3028af4f22531a0097a3baa478a384dff2e23e873707c93df3b704" sha256: "2b7579556c117b535ef83835798a7f3c4003dc892a888a4a99f2107bca7b6675"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "23.0.3" version: "23.0.4"
flutter_local_notifications_linux: flutter_local_notifications_linux:
dependency: transitive dependency: transitive
description: description:
@ -1076,11 +1076,11 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
path: sync_settings_ui path: sync_settings_ui
ref: "sync_settings_ui-v0.8.5" ref: "sync_settings_ui-v0.8.6"
resolved-ref: abfb596d7ce2f28acfefbd55e7b3227257325261 resolved-ref: "41af57870207f80a5bf571f15544a08fddcbe7bf"
url: "https://github.com/kuhyx/utils" url: "https://github.com/kuhyx/utils"
source: git source: git
version: "0.8.5" version: "0.8.6"
synchronized: synchronized:
dependency: transitive dependency: transitive
description: description:

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go." description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none' publish_to: 'none'
version: 1.0.193+1 version: 1.0.194+1
environment: environment:
sdk: ^3.12.2 sdk: ^3.12.2
@ -12,13 +12,13 @@ dependencies:
crdt_sync: crdt_sync:
git: git:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.14.1 ref: crdt_sync_dart-v0.14.2
path: crdt_sync_dart path: crdt_sync_dart
# Keystore-backed end-to-end encryption open + the passphrase lock button. # Keystore-backed end-to-end encryption open + the passphrase lock button.
crdt_sync_flutter: crdt_sync_flutter:
git: git:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: crdt_sync_flutter-v0.9.1 ref: crdt_sync_flutter-v0.9.2
path: crdt_sync_flutter path: crdt_sync_flutter
crypto: 3.0.8 crypto: 3.0.8
cryptography: 2.9.0 cryptography: 2.9.0
@ -32,7 +32,7 @@ dependencies:
fl_chart: 1.3.1 fl_chart: 1.3.1
flutter: flutter:
sdk: flutter sdk: flutter
flutter_local_notifications: 23.0.3 flutter_local_notifications: 23.0.4
flutter_secure_storage: 11.2.0 flutter_secure_storage: 11.2.0
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure # One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
@ -71,7 +71,7 @@ dependencies:
sync_settings_ui: sync_settings_ui:
git: git:
url: https://github.com/kuhyx/utils url: https://github.com/kuhyx/utils
ref: sync_settings_ui-v0.8.5 ref: sync_settings_ui-v0.8.6
path: sync_settings_ui path: sync_settings_ui
url_launcher: 6.3.3 url_launcher: 6.3.3
uuid: 4.6.0 uuid: 4.6.0

View File

@ -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<String?> read(String name) async => null;
@override
Future<void> 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<String, Object?>.of(dish.toJson())..remove('dish_id');
expect(KuchniaDish.fromJson(noId).dishId, '');
});
}

View File

@ -3,11 +3,11 @@
# they carry no `expires`; everything else is discretionary and expires. # they carry no `expires`; everything else is discretionary and expires.
exceptions: exceptions:
- ecosystem: gittag - ecosystem: pypi
package: kuhy-credit package: httpx
pinned: 0.3.1 pinned: 0.28.1
reason: >- reason: >-
sickdays 0.5.8 (its newest release) pins kuhy-credit 0.3.1 exactly, so rtdb-relay 0.2.2 (its newest release) pins httpx 0.28.1 exactly, so pip
pip refuses 0.3.2 next to it. Taking 0.3.2 means holding sickdays back refuses 0.29.0 next to it. rtdb-relay is the Claude relay transport, so
instead; sickdays is the dependency the gate actually runs. httpx waits for it.
blocked_by: transitive:sickdays@0.5.8 blocked_by: transitive:rtdb-relay@0.2.2

View File

@ -171,6 +171,10 @@ KUCHNIA_SYNCED_CREDENTIAL_FILE: Path = (
KUCHNIA_LAST_IMPORT_FILE: Path = ( KUCHNIA_LAST_IMPORT_FILE: Path = (
Path.home() / ".config" / "diet_guard" / "kuchnia_last_import" 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 KUCHNIA_TIMEOUT_SECONDS: float = 8.0
# Whole-walk ceiling. The import is 3-4 sequential requests, so a per-request # Whole-walk ceiling. The import is 3-4 sequential requests, so a per-request
# timeout alone would permit ~32s against a slow provider. # timeout alone would permit ~32s against a slow provider.

View File

@ -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")

View File

@ -24,6 +24,7 @@ from typing import TYPE_CHECKING
from diet_guard._foodbank_manual import add_manual_entry, read_manual_bank from diet_guard._foodbank_manual import add_manual_entry, read_manual_bank
from diet_guard._kuchnia_client import PanelSession from diet_guard._kuchnia_client import PanelSession
from diet_guard._kuchnia_config import last_import_day, record_import_day 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_errors import KuchniaError
from diet_guard._kuchnia_orders import fetch_dishes 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. day: The delivery date to fetch.
Returns: Returns:
``(dishes, None)`` on success, or ``([], reason)`` when the catering ``(dishes, None)`` on success. On a panel outage, the cached
panel could not be read. Callers surface the reason and carry on. delivery for ``day`` when one exists ``(cached, None)``, otherwise
``([], reason)`` with the failure reason so callers can surface it
and carry on.
""" """
try: try:
session = PanelSession() session = PanelSession()
session.authenticate() session.authenticate()
dishes = fetch_dishes(session, day) dishes = fetch_dishes(session, day)
except KuchniaError as exc: except KuchniaError as exc:
if cached := load_delivery(day):
return cached, None
return [], str(exc) return [], str(exc)
bank_dishes(dishes) bank_dishes(dishes)
if dishes:
save_delivery(day, dishes)
return dishes, None return dishes, None
@ -123,12 +130,13 @@ def refresh_delivery_once(day: date) -> tuple[list[Dish], str | None]:
day: The delivery date to fetch. day: The delivery date to fetch.
Returns: 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. error. Otherwise whatever :func:`refresh_delivery` returns.
""" """
stamp = day.isoformat() stamp = day.isoformat()
if last_import_day() == stamp: if last_import_day() == stamp:
return [], None return load_delivery(day), None
dishes, reason = refresh_delivery(day) dishes, reason = refresh_delivery(day)
if reason is None and dishes: if reason is None and dishes:
# Only a fetch that found dishes counts: an outage, or a walk that # Only a fetch that found dishes counts: an outage, or a walk that

View File

@ -151,6 +151,12 @@ def state_redirects(tmp_path: Path) -> list[_patch[object]]:
"diet_guard._kuchnia_config.KUCHNIA_LAST_IMPORT_FILE", "diet_guard._kuchnia_config.KUCHNIA_LAST_IMPORT_FILE",
tmp_path / "kuchnia_last_import", 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 # The catering fetch is a third network entry point. Patched at each
# call site, so a test importing `refresh_delivery` directly still # call site, so a test importing `refresh_delivery` directly still
# exercises the real helper. # exercises the real helper.

View File

@ -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

View File

@ -40,8 +40,10 @@ from the phone; `FillAllFlow` stays as the tested plan logic.
undo plus the next resume would log the dish again. undo plus the next resume would log the dish again.
- **The fetch is cached.** `KuchniaQueueService.refreshOnce` returns nothing - **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 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 see its dish. `KuchniaAutoLog` keeps the day's dishes in memory and in
failed or empty fetch at most every 10 minutes (a login per try). `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 - Each logged dish shows as a row: restaurant glyph, name, kcal and macro
dots, a 48 dp undo. One publish per batch (`publishAfterLog`). dots, a 48 dp undo. One publish per batch (`publishAfterLog`).
- Unverified: whether `deliveryMealId` is stable across fetches on the live - Unverified: whether `deliveryMealId` is stable across fetches on the live

View File

@ -4,17 +4,17 @@ version = "1.0.0"
description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget tracking" description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget tracking"
requires-python = ">=3.14" requires-python = ">=3.14"
dependencies = [ 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", "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", "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.1#subdirectory=kuhy_credit", "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", "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", "sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays",
"claude-agent-sdk==0.2.187", "claude-agent-sdk==0.2.189",
"defusedxml==0.7.1", "defusedxml==0.7.1",
"httpx==0.28.1", "httpx==0.28.1",
"requests==2.34.2", "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 # Optional extras. The `mcp` group is ONLY needed by the MCP server

View File

@ -1,17 +1,17 @@
# Diet Guard — runtime + development dependencies # Diet Guard — runtime + development dependencies
# Runtime: tkinter/json/hmac/fcntl (stdlib) plus gatelock and requests below. # Runtime: tkinter/json/hmac/fcntl (stdlib) plus gatelock and requests below.
bandit==1.9.4 bandit==1.9.4
claude-agent-sdk==0.2.187 claude-agent-sdk==0.2.189
codespell==2.4.3 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 crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
defusedxml==0.7.1 defusedxml==0.7.1
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays
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
holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds
httpx==0.28.1 httpx==0.28.1
hypothesis==6.170.17 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 mcp==2.3.0
mypy==2.4.1 mypy==2.4.1
pre-commit==4.7.0 pre-commit==4.7.0
@ -24,6 +24,6 @@ pytest-sugar==1.1.1
pytest-xdist==3.8.0 pytest-xdist==3.8.0
pytest-xvfb==3.1.1 pytest-xvfb==3.1.1
requests==2.34.2 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 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