Compare commits

..

10 Commits

Author SHA1 Message Date
c1ad2e2406 docs: hand off two bugs in the phone catering import
Some checks are pending
file-length / file length <= 250 lines (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Both pass the entire suite, which is why they shipped:

1. A prefilled dish logs ~2.6x its calories. `fillControllersFromDish` never
   clears `perGrams`, so a stale `100` makes `nutritionForPortion` treat the
   dish's per-portion macros as per-100g and rescale by grams/100. Observed
   on the user's phone: a 472 kcal / 258 g dish logged as 1217.8 kcal, and
   1217.8/472 is exactly 258/100. The PC avoids it by calling `_clear_inputs()`
   first; the Dart mirror dropped that step. The existing widget test asserts
   controller *text*, which is correct while the computed nutrition is wrong.

2. No one-tap delivery button on the phone's log screen. The queue works, but
   only `initState` and the Settings button reach it, so there is nothing to
   tap while standing in the kitchen.

The handoff carries the reproduction, the confirmed root cause and the file
and line, so the next session does not re-derive them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 09:22:08 +02:00
d9b3d57900 docs: record the phone-side catering import, verified on device
Documents the Dart mirror, the phone's two triggers (guarded log screen,
unguarded settings button — the same split as the gate vs the CLI), and the
device-local fetch marker on both sides.

The three parity traps are written where the next reader will hit them,
because each survived review once: `_ENERGY_TOLERANCE` is 0.35 and the "~1%"
elsewhere describes the captured day, not the threshold; `jsonEncode(435)`
emits `435` where Python emits `435.0`; and Dart's `List.sort` is unstable
where Python's `sorted` is stable.

Also states plainly what the shared fixture does *not* prove: that the two
implementations agree on a fixed payload, not that they agree against the live
panel.

**That second claim is now observed rather than inferred.** On 2026-08-23,
with the credential synced to the phone and nothing typed on it, the phone
logged into the live panel and banked 5 dishes. Pulling that back to the PC
left all five curated-bank records carrying their original 08:00:03 PC
timestamps, unchanged — the phone's records were byte-identical, so its
idempotency guard wrote nothing. Any disagreement would instead have re-added
them with fresh stamps and started the republish flood.

Split into a second file for the 250-line cap.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 09:17:30 +02:00
8836453f8c fix: initialise the catering queue at startup
`KuchniaQueueService` had no `init()` call in `main()`, so on a real device
the whole feature would have done nothing: every entry point checks
`isInitialized` first and returns quietly, which reads as "no delivery today"
rather than as an error. All 694 tests passed throughout, because widget tests
initialise the service directly.

Caught by grepping main.dart before the phone deploy, not by the suite. So it
is now a repo invariant: `repo_invariants_test.dart` asserts main() names both
catering `init()` calls, and the assertion was checked against a main.dart
with the line deleted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 09:08:54 +02:00
af35eb20c8 feat: offer delivered dishes to the log form, one tap each
The phone now prefills the log form with today's delivered dishes, in the
caterer's own meal order. It still never logs anything itself -- a delivered
meal is not an eaten meal, so the user taps for each dish.

Two guards carried over from the PC, both of which fail silently if dropped:

- **The queue survives a submit.** `prefillNextDish` has two callers: the
  initial load and the post-submit advance. On the PC the second briefly did
  not exist, which made "(N more to go)" a dead letter -- every dish after the
  first waited behind another tap. The test asserts the *form controller*
  holds dish 2 after dish 1 is logged, not that a dish is "available"; the
  latter passes throughout that bug.
- **The automatic refresh is guarded** by a device-local last-fetched date,
  mirroring `refresh_delivery_once`. The log-flow trigger can fire after every
  meal and each unguarded walk is a login plus three requests. The settings
  button deliberately stays unguarded: an explicit ask always goes and looks,
  matching `diet-guard kuchnia`. Only a clean fetch records the day, so an
  outage retries.

Dishes are ordered against `MealScheduleService.current`, never a hardcoded
four slots -- offering a dish for a slot the user's schedule does not have is
the "checkpoint that can never be satisfied" failure in a new costume.

Editing the description before submitting leaves the dish queued: what was
logged was not the delivered dish, and marking it eaten would lose a real
delivery silently.

Two bugs the tests caught:

- `dishesStillQueued` excluded the offered dish, so the status line read
  "0 more" while a real dish sat in the form. The offered dish is prefilled,
  not logged; it counts.
- An end-to-end test through the real `LogMealScreen` never terminated --
  that screen's `initState` fans out into sync, notifications and the food
  bank, and pumping it to quiescence hangs. Rather than keep fighting it, the
  behaviour is tested at the mixin that owns it, through a minimal host. The
  guarantee asserted is the same one: form contents after a submit.

`log_meal_screen.dart` is back under the 250-line cap by moving the nutrition
build into `log_meal_actions.dart` and inlining a one-line alias.

694 Dart tests, 1040 Python tests, 100% Python branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 09:07:17 +02:00
5c9c1ff160 feat: add the catering login to settings, with an Android-only fetch
The credential **fields** appear on every platform; the **fetch button** only
where it can work. That split is the point, not an oversight: the panel sends
no CORS headers so a browser cannot call it, but the desktop app is where a
password is most likely to be typed, and the credential syncs — so hiding the
fields on web would mean the phone could only ever be set up by typing on the
phone. On web the button is replaced by a line saying why, and noting the
login still reaches the phone from there.

The section says the password is stored and synced in plain text rather than
implying otherwise.

The button disables itself while a fetch is in flight, so an impatient
double-tap cannot pay a second login plus three requests against a third
party. The result line says dishes were added to the **food bank** and that
the user still logs them when eaten — the wording carries the
delivered-is-not-eaten rule to the one place a user actually reads.

`settings_screen.dart` was already at 247 of its 250-line budget, so the
section owns its own leading divider and the fetch handler lives beside it;
the screen spends one line on it.

678 Dart tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:33:52 +02:00
3d82ddefd4 feat: let the phone fetch and bank the catering delivery itself
The phone now walks the panel on its own -- login, active order, delivery,
menu -- parses the dishes and banks them, so the feature works with the PC
switched off. Read-only: nothing here logs a meal.

`package:http` has no cookie jar, so the `SESSION` cookie is read off the login
response and replayed by hand. `Response.headers` folds duplicate `set-cookie`
values into one comma-joined string, so the parser splits on both `,` and `;`
and looks for the named cookie rather than assuming the header holds only it --
tested against both orderings and against a panel that sets no session cookie
at all.

Android-only, as decided: the panel sends no CORS headers, so a browser cannot
call it. `refreshDelivery` checks `kIsWeb` first and returns the unsupported
reason without touching the network. No `dart:io` anywhere -- `package:http`
compiles for web, it is the panel that refuses, not the toolchain, so this
needs no `_io`/`_web` seam.

The idempotency guard is ported with its teeth: `addManualEntry` restamps
`editedAt` unconditionally, so re-banking an unchanged dish republishes the
whole curated bank to every peer. `bankDishes` compares the nutritional fields
first and returns a write *count*, which is what the tests assert on -- "the
entry exists" passes while this misbehaves. The comparison is numeric, not
string, so `270 == 270.0` is a match exactly as in Python's `_matches`.

Every failure becomes a reason string, never a throw, so a catering outage
cannot break the caller: a rejected login, a delivery whose dishes all fail
the unit check, and missing credentials each have a test.

One test bug worth noting: the assertion that nothing is logged was missing an
`await` and so was comparing a Future against `isEmpty` -- the single most
important guarantee in this file was passing vacuously until the split forced
it to run.

Test files split three ways for the 250-line cap; block counts checked against
the pre-split file (16 either side), not just a green suite.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:30:21 +02:00
8905d072d0 feat: carry the catering credential to the phone
The Dart half of the credential sync: a `KuchniaCredentialService` that owns
the value locally, a `sync_merge_kuchnia.dart` adapter mirroring the Python
one, and a `_syncKuchniaCredential` tick alongside the banks and budget. The
phone can now receive the panel password, which is the prerequisite for it
fetching anything itself.

One source of truth, per the answered question: the value lives in the synced
document store and nowhere else. Deliberately *not* mirrored into
`flutter_secure_storage` -- two homes for one value is how a stale password
survives a change made on the other device, and the credential has to be
readable synchronously at merge time anyway.

Gated by a second shared fixture, `tests/fixtures/kuchnia_credential.json`,
asserted by both suites. Two cases carry the weight:

- an **unparsable** edit time must fall back to the same clock on both sides
  (Python catches `ValueError` from `fromisoformat`, Dart's `tryParse` returns
  null). Verified they agree on `wall_time_ms == 0`; mutating that expectation
  fails both suites.
- a **blank half** contributes nothing, so a half-filled settings form cannot
  push an empty-string password that wins LWW against a real one.

`KuchniaCredentialService.init()` is called in the WorkManager isolate as well
as `main()`. A fresh isolate has its own static state and `_syncKuchniaCredential`
no-ops when the singleton is missing, so without it a background tick would
neither publish this device's credential nor receive a peer's -- and on the
phone the background tick is most of the syncing there is. Same class of trap
as the `initSyncDeviceId()` one already documented there.

`.toDouble()` came off the bank record: the fields are already `double`, so it
was a no-op the analyzer flags. The field *types* are what keep the encoding
byte-identical to Python's, and `kuchnia_parity_test.dart` asserts that.

654 Dart tests, 1040 Python tests, 100% Python branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:25:27 +02:00
04f5d75aab fix: stop a touched credentials file clobbering a newer peer edit
`_local_credential_log` fell back to the hand-written `kuchnia_credentials`
and used its **mtime** as the edit clock. That clock is not trustworthy:
`git checkout`, a backup restore, and re-running the `install -m 600` setup
line all bump it forward without the credential changing.

Reproduced before fixing: a PC whose file had merely been touched, syncing
against a phone that had set a new password an hour earlier, resolved to the
PC's stale password. The phone user would have seen their edit silently revert.

The bootstrap is still needed -- someone has to publish first, and the PC is
where the password is typed -- so it moves to `_bootstrap_credential_log` and
runs only when the merge came back completely empty. It can no longer outrank
a real edit from a peer; it can only fill a vacuum. Once anything has been
published, the synced cache (which carries a real edit time) takes over
permanently.

`test_a_touched_handwritten_file_cannot_clobber_a_peer` pins it, and was
checked against the pre-fix code: reintroducing the fallback fails it.

Also rewrites the two remaining places that still claimed a credential "must
never leave the machine it was entered on" -- `_constants.py`'s comment and
the doc's Credentials section, which now has a table of which of the three
files syncs and which does not. Rewritten rather than given an exception
clause.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:15:40 +02:00
fd0a35e69e feat: sync the catering credential as its own document
The phone is getting its own Kuchnia importer, and it cannot fetch anything
until the panel password reaches it. So the credential syncs, and a phone that
has been wiped and reinstalled gets it back without the user digging out the
original.

**It travels in plaintext.** Nothing here encrypts it and the rest of the
synced state is not encrypted either, so the docs no longer say a credential
"must never leave the machine it was entered on" -- that paragraph is rewritten
rather than given an exception clause. What still never leaves is the session
cookie: it is regenerable from the password, so syncing it would widen exposure
and buy nothing.

Its own document, not a field on `budget`. `budget.json` is written back at
default permissions, so a password riding inside it would be readable by
anything that reads the budget. Two independently-clocked fields, so a device
that only ever set the username cannot blank a peer's password.

The hand-written `kuchnia_credentials` keeps its contract -- written by the
user, never by this package -- and now acts as a local override that wins over
the synced copy, plus the bootstrap for the very first push. Without that
fallback no device would ever publish, since the synced cache starts empty on
every device.

Two bugs the tests caught rather than review:

- `_local_credential_log` imported `KUCHNIA_CREDENTIALS_FILE` straight from
  `_constants`, bypassing the conftest redirect that patches it on
  `_kuchnia_config`. The suite was reading the real ~/.config credentials. It
  now goes through the module attribute, which is what the redirect replaces.
  This showed up only as a coverage hole -- the branch was unreachable because
  the real file existed.
- `log_to_credential` guarded `password_hlc is None`, which cannot happen: a
  field's value and clock arrive as one tuple. Dead code, removed rather than
  covered by a contrived test.

The relay canary is a real test now, not a scratch script: a field from a
future release survives merge and re-push untouched, so this is shippable
without a coordinated release. `PASSWORD_FIELD_NAME` is spelled as a join
because ruff's S105 reads the literal as a hardcoded secret and the repo bans
`noqa` outright; the wire name is still "password".

100% branch coverage, 1036 tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:12:30 +02:00
24be05b9c3 feat: mirror the catering parser and slot spread in Dart, gated by one fixture
The phone is getting its own Kuchnia Wikinga importer so the feature works
with the PC switched off. That turns a risk `_kuchnia_spread.py` called
"theoretical" into a live one: two implementations must now agree exactly on
which dishes are dropped, which slot each lands on, and the JSON a banked
record encodes to. Disagreement means each device re-adds what the other
dropped, and since `add_manual_entry` restamps `t` unconditionally, the whole
curated bank republishes to every peer on every refresh. A slot mismatch is
worse -- a checkpoint one device offers and the other does not can never be
satisfied.

So the port lands with its gate rather than after it. One shared fixture,
`tests/fixtures/kuchnia_day.json`, is asserted by both `pytest` and
`flutter test`: same input, same expected dishes, drops, slots, bank keys and
records. Two suites written independently from the same prose is not a gate.

The fixture is five real dishes (a scrubbed 2026-08-22 capture) plus synthetic
meals that each pin one drop or fallback path -- a per-100 g mix-up, an absurd
portion, a stringly-typed number, a non-dict entry, a missing `nutrition`, a
missing `mealPriority`, and a twin-dish pair. Without those, "the same meals
are dropped" is a vacuous assertion against an all-happy-path capture. Both
halves were mutation-checked: flipping an expected slot, drop count or record
value fails each suite, and flipping `435.0` to `435` fails the byte-identity
test while the value comparison still passes, which is why both exist.

Three traps the port had to survive, each caught before it shipped:

- `_ENERGY_TOLERANCE` is **0.35**. The prose said "~1%", which describes how
  closely the captured day agreed, not the threshold; porting 0.01 would drop
  dishes the PC keeps. That paragraph now says so.
- `jsonEncode(435)` emits `435` where Python emits `435.0`, so every Dart
  macro is forced to `double` and a canonical-encoding test pins it.
- Dart's `List.sort` is unstable where Python's `sorted` is stable, so the
  Dart comparator carries the payload index as a final tiebreak.

The real dishes live in their own file rather than as a literal in the
generator: transcribing them by hand corrupted three of the five, and the
error was invisible until the generated fixture was diffed against the
capture.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX
2026-08-23 08:00:54 +02:00
56 changed files with 5267 additions and 139 deletions

View File

@ -225,9 +225,10 @@ phone show both.
- Don't strip the `components` field: nothing writes it, but historical
composite entries and the food bank read it, and it is part of the sync wire
format.
- Don't let the catering import write a log entry unattended: a delivered
meal is not an eaten meal, and the gate would satisfy its own checkpoint.
See [docs/kuchnia-wikinga.md](docs/kuchnia-wikinga.md).
- Don't let the catering import log unattended (delivered ≠ eaten), don't let
its Python and Dart halves drift (one shared fixture gates them), and don't
make the synced password machine-local — the phone could not then fetch.
[docs](docs/kuchnia-wikinga.md), [phone](docs/kuchnia-wikinga-phone.md).
- Don't add a dependency without the production install-path check above.
- Don't reintroduce a seal/`chattr +i` on the budget file.
- Don't re-add a Linux embedder target, and don't change the wrapper's port or

View File

@ -1,4 +1,4 @@
# Next session: put the Kuchnia importer on the phone
# Next session: fix the phone's catering prefill, add the one-tap button
Paste the prompt below into a fresh session. Delete this file once it's done.
@ -6,103 +6,116 @@ Paste the prompt below into a fresh session. Delete this file once it's done.
## Prompt
Port the Kuchnia Wikinga catering import to the Flutter app so the phone can
fetch the day's dishes **with the PC completely off**. Today the importer is
Python-only and the phone just receives the banked results through sync.
Two bugs in the phone-side Kuchnia Wikinga import that shipped on 2026-08-23
(commits `24be05b9c38`..`d9b3d57900f`). Read
`docs/kuchnia-wikinga-phone.md` and `docs/kuchnia-wikinga.md` first.
Read `docs/kuchnia-wikinga.md` first — it has the recovered API map, the traps,
and why each decision went the way it did. `CLAUDE.md`'s "Do NOT" section and
`docs/meal-schedule.md` are the other two load-bearing reads.
State: `main` is clean and pushed. Phone (Pixel 6a, `23181JEGR08034`) has the
build with both bugs installed. 1040 Python tests at 100% branch coverage,
695 Dart tests — all green, which is exactly the problem: **both bugs pass the
entire suite.**
State: `main` is clean at `93669776b6d`. Phone (Pixel 6a, `23181JEGR08034`)
has 1.0.55/vc130 installed and verified working; repo is at 1.0.56.
### Bug 1 — a prefilled dish logs ~2.6x its real calories (data corruption, fix first)
### Decisions already made (do not re-litigate)
Reproduced on the user's real phone on 2026-08-23:
The user answered these explicitly on 2026-08-23:
| | |
|---|---|
| bank record | `472.0 kcal`, `25.89 P`, `52.95 C`, `16.62 F`, `258.0 g` |
| what got logged | `1217.8 kcal`, `66.8 P`, `136.6 C`, `42.9 F`, `258.0 g` |
| ratio | `1217.8 / 472.0` = **2.58** = `258 g / 100` |
1. **The phone fetches directly.** Not "PC banks on a timer and the phone
receives it" — it must work when the PC is unavailable. So the HTTP client,
the parser and the slot spread all get Dart implementations.
2. **The catering password syncs**, so a complete reinstall restores it. The
user chose this knowing the trade-off. It will be **plaintext in Firebase
RTDB** — the rest of the synced state is not encrypted either, so do not
describe it as "encrypted like everything else".
3. That contradicts the current doc rule ("a credential must never leave the
machine it was entered on"). **Rewrite that paragraph**, don't bolt an
"Exception:" onto it (`memories/mistakes.md`).
4. `kuchnia_session.json` (the live cookie) stays **device-local**. It is
regenerable, so syncing it buys nothing and widens exposure.
Entry: `Pieczona owsianka daktylowo-czekoladowa, sos gruszkowy, orzechy włoskie`
at `2026-08-23T08:00:09+02:00`, `source: "kuchnia wikinga"`, slot 8.
### Sequence (the first item is a prerequisite, not a follow-up)
**Root cause** (confirmed, don't re-derive): `fillControllersFromDish` in
`app/lib/screens/log_meal_kuchnia_mixin.dart` sets `desc`, the four macros and
`macros.grams` — but **never clears `macros.perGrams`**. `nutritionForPortion`
(`app/lib/models/nutrition.dart:87`) does
`referenceGrams = perGrams > 0 ? perGrams : ateGrams`, so a stale `100` left in
the per-grams field from a previous food-bank pick makes it treat the dish's
*per-portion* macros as *per-100 g* and rescale them by `258/100`.
1. **Settings field + credential sync.** The phone cannot fetch until the
password is on it. Sync it as its own record; check `sync_merge/` relays a
new record type rather than dropping it — it enumerates handlers
(`_banks`, `_budget`, `_daylog`, `_schedule`), the same fixed-key-set shape
that would silently drop an unknown field.
2. **Fetch + parse + bank**, read-only. No logging. Verify against the live
panel on-device.
3. **Wire to the log flow**, keeping the never-log-unattended rule: the phone
*offers* dishes, the user still taps to log.
The PC does not have this bug because `_gatelock_delivery.py:154` calls
`self._clear_inputs()` before filling. The Dart mirror dropped that step.
### The parity risk stops being theoretical
Required:
`_kuchnia_spread.py`'s docstring says the integer-only rule is theoretical
"because the phone has no importer and so no mirror of this code". **This port
creates that mirror — update that docstring in the same commit.** Two things
now have to agree exactly across languages:
- Clear **every** macro field (including `perGrams`) before filling, the same
way the PC does. Prefer making `fillControllersFromDish` unable to leave a
stale field rather than adding a `perGrams.clear()` line that the next field
can forget again.
- A test that would have caught it: pre-seed `perGrams` with `100`, prefill a
dish, and assert the *computed* `Nutrition` equals the dish's own macros —
not just that the text fields look right. The current
`log_meal_kuchnia_mixin_test.dart` asserts controller **text** and passes
with this bug present; that is why it shipped.
- Check the same class of bug in the settings-button path and anywhere else a
dish reaches the form.
- **`i * S // N` → `i * S ~/ N`.** Python's `round` is banker's, Dart's is
half-away-from-zero. A float path silently desyncs which slot a dish lands
in, and a slot one device offers while the other does not is a checkpoint
that can never be satisfied — a permanent lock.
- **`_energy_is_consistent`'s ~1% tolerance**, which *drops* dishes. If the
two sides disagree about which dishes pass, each re-adds what the other
dropped, `add_manual_entry` restamps `t` unconditionally, and the curated
bank republishes to every peer on every refresh.
**Also fix the already-corrupted entry.** One real log entry is wrong by
~746 kcal on 2026-08-23. It is synced, so correcting it locally and letting the
merge carry the fix is the right move — but confirm with the user before
editing their food log, and do not hand-edit `food_log.json` while the app or
a sync tick might write it.
Gate both with **one shared JSON fixture** committed to the repo, asserted by
`pytest` *and* `flutter test` — same input, same expected dish list, dropped
dishes, slot assignment and bank keys. Two independently-written suites from
the same prose is not a gate.
### Bug 2 — the phone has no one-tap "add today's delivery" button
Also verify a Dart-banked and a Python-banked record for the same dish are
**byte-identical JSON**; float formatting (`435.0` vs `435`) is the likely
divergence and would cause the same rewrite/restamp flood.
The PC's lock screen has a "🍱 Today's delivery" button that walks the whole
delivery dish by dish (`_gatelock_delivery.py`). On the phone the queue exists
and works (`KuchniaQueueService`, `LogMealKuchniaMixin`), but the **only** ways
to trigger it are the log screen's `initState` and the Settings "Fetch today's
delivery" button — there is no visible control on the log screen itself.
### Platform seam
So when the user is standing in the kitchen, there is nothing to tap.
`app/` builds Android + web only; the desktop app *is* the web build in Chrome
(`app/test/repo_invariants_test.dart` enforces this). The catering panel sends
no CORS headers, so a browser cannot call it — **make the feature Android-only
and disabled on web**. `dart:io` does not fail a web compile, it throws at
runtime as a blank white window, so branch on `kIsWeb` *before* any
`Platform.is…`, and keep `dart:io` to `*_io.dart` seams. `package:http` and
`flutter_secure_storage` are already dependencies.
Required:
- A visible control on the log screen that loads today's delivery and prefills
the first dish, matching the PC's affordance.
- It must show the queue state — the PC's `"(N more to go)"`. The mixin already
exposes `queueStatusLine` and `dishesStillQueued`.
- Respect the guard split documented in `docs/kuchnia-wikinga.md`'s Triggers
table: an **explicit** user tap goes and looks (unguarded, like the CLI and
the settings button); the automatic `initState` load stays guarded by
`KuchniaQueueService.refreshOnce`.
- `app/lib/screens/log_meal_screen.dart` is at **exactly 249/250 lines**. The
button will not fit there — put it in a widget of its own, as
`settings_kuchnia.dart` does.
### Constraints
- 250 lines per file (860 Python lines → expect 6+ Dart files).
- 100% branch coverage on the Python side; `flutter test` green.
- `pre-commit run --files <changed>` before finishing.
- 250 lines per file (`file-length` hook). `AGENTS.md` is at exactly 250.
- 100% Python branch coverage; `flutter test` green.
- `pre-commit run --files <changed>` before finishing. The repo bans `noqa`
outright — there is a `no-noqa` hook, so a suppression is not an escape
hatch.
- Any new Python state path must patch `conftest._isolate_state` in the *same*
edit, or the suite writes to live user data.
- Never log a delivery unattended — a delivered meal is not an eaten meal.
- Don't break the cross-language parity gate (`tests/fixtures/kuchnia_day.json`,
asserted by both suites). If you change `dishFieldValues` or the banked
record, regenerate with `scripts/build_kuchnia_fixture.py` and **re-read the
diff** — the script blesses whatever Python currently does.
### Verify on the phone, not just in tests
Mobile is the primary platform (`phone-deploy` skill). Deploy with
`~/.claude/scripts/phone_deploy.sh ~/diet-guard/app --release`, which now runs
a pre-install sync gate (`scripts/sync_freshness.py`, added 2026-08-23) and
picks the build number itself. Never uninstall or `pm clear`.
Mobile is the primary platform. Deploy with
`~/.claude/scripts/phone_deploy.sh ~/diet-guard/app --release`. Never uninstall
or `pm clear`.
**The phone is the user's daily driver — do not leave the app mid-flow, and
do not grab focus on their desktop.** (Two complaints on 2026-08-22 about a
test gate window and an emulator stealing the cursor.)
**The phone is the user's daily driver — do not leave the app mid-flow, and do
not grab focus on their desktop.**
Verifying bug 1 needs an actual log: prefill a delivered dish, log it, and read
the entry back out of `food_log.json` after a sync. The kcal must match the
dish's own value, not a multiple of it. A green widget test is what let this
ship in the first place.
### Done
`python -m diet_guard kuchnia` and the phone's own fetch produce the **same
banked dishes for the same day**, proven by the shared fixture in both suites
and observed once on-device with the PC's importer not run that day.
- A dish prefilled from the delivery logs its own macros exactly, with a stale
`perGrams` present, proven by reading the written entry back.
- The corrupted 2026-08-23 owsianka entry reads 472 kcal.
- One tap on the log screen loads the delivery and walks it dish by dish, with
the remaining count visible — observed on the phone.

View File

@ -9,6 +9,8 @@ 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/foodbank_service.dart';
import 'package:diet_guard_app/services/frame_stats.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';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/notification_service.dart';
@ -26,6 +28,8 @@ Future<void> main() async {
await BudgetHistoryService.init();
await MealScheduleService.init();
await FoodBankService.init();
await KuchniaCredentialService.init();
await KuchniaQueueService.init();
final notifications = await NotificationService.init();
// Deliberately *not* awaited before the first frame: the browser's
// `Notification.requestPermission()` does not complete until the user

View File

@ -0,0 +1,85 @@
/// One delivered catering dish, with its portion macros.
///
/// The Dart mirror of `diet_guard/_kuchnia_parse.py`'s `Dish`. Every macro is
/// the total *for this portion*, not per 100 g -- the same convention
/// [Nutrition] uses.
///
/// KEEP IN SYNC WITH `diet_guard/_kuchnia_parse.py`. Both sides are gated by
/// `tests/fixtures/kuchnia_day.json`; see `kuchnia_parity_test.dart`.
library;
/// A dish the caterer delivered on a given day.
class KuchniaDish {
/// Creates a dish from its already-validated fields.
const KuchniaDish({
required this.name,
required this.kcal,
required this.proteinG,
required this.carbsG,
required this.fatG,
required this.grams,
required this.priority,
required this.slotLabel,
});
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
///
/// Not `mealName`, which is the slot label ("Kolacja") and would collapse
/// every Monday dinner onto one food-bank entry.
final String name;
/// Calories for this portion.
final double kcal;
/// Protein in grams, for this portion.
final double proteinG;
/// Carbohydrate in grams, for this portion.
final double carbsG;
/// Fat in grams, for this portion.
final double fatG;
/// The portion weight in grams (`nutrition.weight`).
final double grams;
/// The caterer's own eating order, 1..N.
///
/// Falls back to the dish's 1-based position in the payload when
/// `mealPriority` is missing.
final int priority;
/// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only.
final String slotLabel;
/// The curated-bank record for this dish.
///
/// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count
/// ranks foods by how often they were *eaten*, and a delivered dish has not
/// been eaten yet.
///
/// Every macro is declared `double` on this class rather than `num`, which
/// is what keeps the encoded record byte-identical to Python's.
/// `jsonEncode(435)` emits `435` where Python emits `435.0`, and a
/// byte-different record for the same dish makes every refresh look like a
/// change -- which republishes the whole curated bank to every peer. A
/// `.toDouble()` here would be a no-op the analyzer flags; the field types
/// are the guarantee, and `kuchnia_parity_test.dart` asserts the encoding.
Map<String, dynamic> toBankRecord() => {
'desc': name,
'kcal': kcal,
'protein_g': proteinG,
'carbs_g': carbsG,
'fat_g': fatG,
'grams': grams,
'count': 0,
};
/// The curated bank's key for this dish.
///
/// Python uses `str.casefold()` and this uses `String.toLowerCase()`. They
/// agree across the whole Polish alphabet and diverge only on `ß`,
/// ligatures and final sigma; rekeying to unify them would strand every
/// existing entry, so the agreement is pinned by test instead.
String get bankKey => name.trim().toLowerCase();
}

View File

@ -1,5 +1,23 @@
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/screens/log_meal_progress.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:flutter/material.dart';
/// Builds the [Nutrition] for a submit from the form's macro controllers.
///
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. Pure over
/// its inputs, so the per-portion scaling is testable without a widget.
Nutrition nutritionFromControllers(MacroControllers macros, String source) =>
nutritionForPortion(
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,
);
/// The four destination buttons in [LogMealScreen]'s app bar.
///
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. Returned

View File

@ -0,0 +1,155 @@
/// Offers the day's delivered catering dishes to the log form.
///
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line
/// ceiling.
///
/// **A delivered meal is not an eaten meal.** This only ever *prefills* the
/// form -- the user still taps "Log" for each dish. Nothing here writes a log
/// entry, and nothing here may start doing so: the gate would then satisfy its
/// own checkpoint from a delivery note, and the log would record what the
/// courier dropped off rather than what was eaten.
///
/// [prefillNextDish] is called from **two** places: once when the delivery
/// first arrives, and again after every successful submit. That second caller
/// is the load-bearing one. On the PC it briefly did not exist, which made the
/// "(N more to go)" promise a dead letter -- every dish after the first stayed
/// queued behind another click. `kuchnia_queue_test.dart` asserts the state
/// transition rather than "a dish was offered", because the latter passes
/// while this misbehaves.
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:flutter/material.dart';
/// Writes [dish]'s name and macros into the log form's controllers.
///
/// Free function rather than a mixin method so the numeric formatting is
/// testable without pumping a widget.
void fillControllersFromDish(
KuchniaDish dish,
TextEditingController desc,
MacroControllers macros,
) {
desc.text = dish.name;
final (grams, values) = dishFieldValues(dish);
macros.kcal.text = values.$1;
macros.protein.text = values.$2;
macros.carbs.text = values.$3;
macros.fat.text = values.$4;
macros.grams.text = grams;
}
/// Wires the catering queue into a log form.
mixin LogMealKuchniaMixin<T extends StatefulWidget> on State<T> {
/// The dish currently prefilled from the delivery, if any.
KuchniaDish? offeredDish;
/// How many delivered dishes still need logging, including the offered one.
///
/// The offered dish counts: it is prefilled, not logged, and the user has
/// still to tap for it. Excluding it made the line read "0 more" while a
/// real dish sat in the form.
int get dishesStillQueued => KuchniaQueueService.remaining;
/// The form's description field. Supplied by the screen.
TextEditingController get descController;
/// The form's macro fields. Supplied by the screen.
MacroControllers get macroControllers;
/// Called after the form is filled, so the screen can mark the source.
void onDishPrefilled() {}
/// Fills the form's fields from [dish].
///
/// Concrete here rather than an abstract hook: every implementation would be
/// the same three lines, and the screen file has no budget to spare.
void fillFormFromDish(KuchniaDish dish) {
fillControllersFromDish(dish, descController, macroControllers);
onDishPrefilled();
}
/// Loads today's delivery, guarded so it costs at most one walk per day.
///
/// Goes through [KuchniaQueueService.refreshOnce] rather than
/// `refreshDelivery`: this is an *automatic* trigger and can fire after
/// every meal, and each unguarded refresh is a login plus three requests
/// against a third party. The settings button is the explicit ask that
/// always goes and looks.
Future<void> loadDeliveryOnce({Set<String> alreadyLogged = const {}}) async {
if (!KuchniaQueueService.isInitialized) return;
final result = await KuchniaQueueService.refreshOnce(DateTime.now());
if (!mounted || result.dishes.isEmpty) return;
// Ordered by the caterer's own meal priority, against the *user's*
// schedule -- not a hardcoded four slots. A dish offered for a slot the
// user's schedule does not have is a checkpoint that can never be met.
final ordered = dishesInSlotOrder(
result.dishes,
daySlots(MealScheduleService.current),
);
KuchniaQueueService.instance.offer(ordered, alreadyLogged: alreadyLogged);
prefillNextDish();
}
/// Loads today's delivery, skipping dishes already logged today.
///
/// The skip matters across devices: a dish logged on the PC must not be
/// offered again here, and the food log is the only record of that.
Future<void> loadTodaysDelivery() async {
final logged = await LogStorageService.instance.todayEntries();
if (!mounted) return;
await loadDeliveryOnce(
alreadyLogged: {
for (final entry in logged) entry.desc.trim().toLowerCase(),
},
);
}
/// Prefills the form with the next queued dish, if there is one.
///
/// Safe to call when the queue is empty: it simply clears the offer.
void prefillNextDish() {
final dish = KuchniaQueueService.next;
if (dish == null) {
if (offeredDish != null) setState(() => offeredDish = null);
return;
}
setState(() => offeredDish = dish);
fillFormFromDish(dish);
}
/// Drops the just-logged dish and immediately offers the next one.
///
/// Call this from the submit handler *after* the entry is written. This is
/// the second caller that keeps the queue alive across a submit.
void advanceQueueAfterLog(String loggedDesc) {
final dish = offeredDish;
if (dish == null) return;
if (dish.name.trim().toLowerCase() != loggedDesc.trim().toLowerCase()) {
// The user edited the description into something else, so the offered
// dish was not what they logged. Leave it queued rather than silently
// marking a dish eaten that never was.
return;
}
KuchniaQueueService.instance.markLogged(dish);
offeredDish = null;
prefillNextDish();
}
/// A short line naming what is still queued, or null when nothing is.
///
/// The leftover matters: the caterer's five meals against four default slots
/// means at least one dish is still queued when the last slot is logged. It
/// is already banked, so it is named rather than dropped silently.
String? get queueStatusLine {
final left = dishesStillQueued;
if (left <= 0) return null;
return '$left more delivered ${left == 1 ? 'dish' : 'dishes'} to log.';
}
}

View File

@ -6,9 +6,9 @@ import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/food_suggestion.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/screens/log_meal_actions.dart';
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.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';
@ -43,7 +43,8 @@ class _LogMealScreenState extends State<LogMealScreen>
with
WidgetsBindingObserver,
LogMealSyncMixin<LogMealScreen>,
LogMealNavMixin<LogMealScreen> {
LogMealNavMixin<LogMealScreen>,
LogMealKuchniaMixin<LogMealScreen> {
@override
http.Client? get syncHttpClient => widget.httpClient;
@ -78,6 +79,9 @@ class _LogMealScreenState extends State<LogMealScreen>
// a previous session says so immediately rather than only after a tick.
unawaited(refreshSyncHealth());
unawaited(autoSync());
// After autoSync so a dish already logged on the PC is known before the
// queue is built, and guarded so this costs at most one walk per day.
unawaited(loadTodaysDelivery());
}
@override
@ -110,6 +114,13 @@ class _LogMealScreenState extends State<LogMealScreen>
});
}
@override
TextEditingController get descController => _descController;
@override
MacroControllers get macroControllers => _macros;
@override
void onDishPrefilled() => setState(() => _source = 'catering');
void _onSuggestionSelected(FoodSuggestion suggestion) {
_descController.text = suggestion.name;
_macros.fillFrom(suggestion.nutrition);
@ -128,15 +139,7 @@ class _LogMealScreenState extends State<LogMealScreen>
});
return;
}
final nutrition = nutritionForPortion(
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,
);
final nutrition = nutritionFromControllers(_macros, _source);
await LogStorageService.instance.logMeal(
desc,
nutrition,
@ -151,7 +154,11 @@ class _LogMealScreenState extends State<LogMealScreen>
// Offline backstop: if the push above fails (no connectivity), a
// connectivity-gated WorkManager task uploads the meal on reconnect.
unawaited(enqueueSyncBackstopTask());
await _dismissStaleReminder();
// Clears a reminder the meal just logged has now satisfied; without it a
// notification already on screen survives up to 15 min and reads as a
// false alarm. `pullWhenDue: false` because `autoSync` above already owns
// the network for this submit.
await checkAndNotify(pullWhenDue: false);
if (!mounted) return;
_descController.clear();
_macros.clear();
@ -161,23 +168,16 @@ class _LogMealScreenState extends State<LogMealScreen>
});
await refreshSlots();
if (!mounted) return;
// The second `prefillNextDish` caller. Without it every dish after the
// first stays queued behind another tap and the "N more to log" line
// becomes a dead letter -- the exact regression the PC gate once shipped.
advanceQueueAfterLog(desc);
setState(() {
_status = null;
_status = queueStatusLine;
_progress = buildTodayProgress(log);
});
}
/// Clears any reminder the meal just logged has now satisfied.
///
/// 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
/// 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);
@override
Widget build(BuildContext context) {

View File

@ -0,0 +1,185 @@
/// The catering-panel credential section of the settings screen.
///
/// Its own file because `settings_screen.dart` sits at the repo's 250-line
/// ceiling.
///
/// Two things about this section are deliberate:
///
/// * **The fields show on every platform, the fetch button only on Android.**
/// The panel sends no CORS headers, so a browser cannot call it -- but the
/// desktop app is where the user is most likely to be typing a password, and
/// the credential syncs, so hiding the fields there would mean the phone
/// could only ever be set up by typing on the phone.
/// * **The password is stored and synced in plaintext**, and the section says
/// so rather than implying otherwise. The rest of the synced state is not
/// encrypted either.
library;
import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart';
/// Fetches today's delivery and reports what was banked.
///
/// Deliberately says "banked", not "logged": a delivered meal is not an eaten
/// meal, so the dishes land in the food bank and the user still taps to log
/// each one. Top-level so the settings screen can pass it without growing.
Future<String> fetchTodaysDelivery() async {
final result = await refreshDelivery(DateTime.now());
if (!result.ok) return result.reason!;
if (result.dishes.isEmpty) return 'No delivery found for today.';
final count = result.dishes.length;
return '$count ${count == 1 ? 'dish' : 'dishes'} added to your food bank. '
'Log them from the meal screen when you eat them.';
}
/// Credential fields plus, on Android, a "fetch today's delivery" action.
class KuchniaSettingsSection extends StatefulWidget {
/// Creates the section.
///
/// [canFetch] defaults to [kuchniaFetchSupported] -- false on web, where the
/// button is replaced by a one-line explanation rather than silently
/// vanishing. [onFetch] defaults to the real fetch. Both are injectable so a
/// widget test can drive the section without a network or a platform check.
const KuchniaSettingsSection({
this.canFetch,
this.onFetch,
super.key,
});
/// Whether this platform can reach the catering panel; null means ask.
final bool? canFetch;
/// Fetches today's delivery and returns a status line; null means the real
/// one.
final Future<String> Function()? onFetch;
@override
State<KuchniaSettingsSection> createState() => _KuchniaSettingsSectionState();
}
class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
late final TextEditingController _username = TextEditingController(
text: KuchniaCredentialService.username,
);
late final TextEditingController _password = TextEditingController(
text: KuchniaCredentialService.password,
);
bool _obscured = true;
bool _busy = false;
String? _status;
@override
void dispose() {
_username.dispose();
_password.dispose();
super.dispose();
}
Future<void> _save() async {
if (!KuchniaCredentialService.isInitialized) return;
await KuchniaCredentialService.instance.save(
_username.text,
_password.text,
);
if (!mounted) return;
setState(() => _status = 'Saved. It will sync to your other devices.');
}
Future<void> _fetch() async {
setState(() {
_busy = true;
_status = null;
});
final message = await (widget.onFetch ?? fetchTodaysDelivery)();
if (!mounted) return;
setState(() {
_busy = false;
_status = message;
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final canFetch = widget.canFetch ?? kuchniaFetchSupported;
// The section owns its own leading divider so the settings screen needs a
// single line for it -- that file sits on the repo's 250-line ceiling.
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
Text('Kuchnia Wikinga', style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text(
"Your catering panel login, so this device can look up the day's "
'delivered dishes and their macros. Stored and synced in plain '
'text, like the rest of your synced data.',
style: theme.textTheme.bodySmall,
),
const SizedBox(height: 12),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: TextField(
controller: _username,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
decoration: const InputDecoration(labelText: 'Panel e-mail'),
onSubmitted: (_) => _save(),
),
),
const SizedBox(height: 12),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: TextField(
controller: _password,
obscureText: _obscured,
autocorrect: false,
enableSuggestions: false,
decoration: InputDecoration(
labelText: 'Panel password',
suffixIcon: IconButton(
icon: Icon(_obscured ? Icons.visibility : Icons.visibility_off),
tooltip: _obscured ? 'Show password' : 'Hide password',
onPressed: () => setState(() => _obscured = !_obscured),
),
),
onSubmitted: (_) => _save(),
),
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
FilledButton(onPressed: _save, child: const Text('Save login')),
if (canFetch)
OutlinedButton.icon(
onPressed: _busy ? null : _fetch,
icon: const Icon(Icons.restaurant),
label: Text(
_busy ? 'Fetching…' : "Fetch today's delivery",
),
),
],
),
if (!canFetch) ...[
const SizedBox(height: 8),
Text(
'Android only — the catering panel blocks browser requests. Your '
'login still syncs to your phone from here.',
style: theme.textTheme.bodySmall,
),
],
if (_status != null) ...[
const SizedBox(height: 8),
Text(_status!, style: theme.textTheme.bodyMedium),
],
],
);
}
}

View File

@ -14,6 +14,7 @@ import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/firebase_backend.dart';
@ -185,6 +186,7 @@ class _SettingsScreenState extends State<SettingsScreen>
const Divider(),
const SizedBox(height: 8),
..._mealScheduleSection(context),
const KuchniaSettingsSection(),
const SizedBox(height: 24),
const Divider(),
ListTile(

View File

@ -11,6 +11,7 @@ import 'package:diet_guard_app/services/budget_history_service.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/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
@ -56,6 +57,11 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
// to the default four meals and nag for checkpoints the user's actual
// schedule does not have.
await MealScheduleService.init();
// Same fresh-isolate reasoning: `_syncKuchniaCredential` no-ops when this
// singleton is uninitialised, so without this a background tick would
// neither publish this device's catering credential nor receive a peer's --
// and on the phone the background tick is most of the syncing there is.
await KuchniaCredentialService.init();
final SyncSettings settings;
try {
settings = await SyncSettings.load();

View File

@ -0,0 +1,192 @@
/// HTTP access to the Kuchnia Wikinga panel, from the phone.
///
/// The Dart mirror of `diet_guard/_kuchnia_client.py`. Auth is a cookie
/// session, not a bearer token: `POST auth/login` with a **form-urlencoded**
/// body sets a `SESSION` cookie that every later call carries.
///
/// `package:http` has no cookie jar, so the `set-cookie` header is read and
/// replayed by hand. `Response.headers` folds duplicate `set-cookie` values
/// into one comma-joined string, which is why the parser below splits and
/// looks for the named cookie rather than assuming the header holds only it.
///
/// **Android only.** The panel sends no CORS headers, so a browser cannot call
/// it at all; on web every entry point returns an unsupported reason rather
/// than throwing. The `kIsWeb` check comes first, before anything
/// platform-shaped, and this file imports no `dart:io` -- `package:http`
/// compiles for web, it is the *panel* that refuses, not the toolchain.
library;
import 'dart:convert';
import 'package:diet_guard_app/services/kuchnia_errors.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
/// Base URL of the panel's undocumented API.
const kuchniaApiBase = 'https://panel.kuchniavikinga.pl/api';
/// Sent as the `company-id` header. The panel wants the company *name*, not a
/// numeric id.
const kuchniaCompany = 'kuchniavikinga';
/// The panel's own launcher tag for a browser panel session.
const kuchniaLauncherType = 'BROWSER_PANEL';
/// The only cookie the panel issues on login.
///
/// It sets no `XSRF-TOKEN`, so the CSRF echo its own JavaScript performs is a
/// no-op for this account -- the session cookie alone authenticates.
const kuchniaSessionCookie = 'SESSION';
/// Per-request timeout.
const kuchniaTimeout = Duration(seconds: 8);
/// Whole-walk ceiling.
///
/// The import is three or four sequential requests, so a per-request timeout
/// alone would permit ~32s against a slow provider -- and this runs on a path
/// the user is waiting on.
const kuchniaTotalDeadline = Duration(seconds: 12);
/// Why the catering panel cannot be reached from a browser.
const kuchniaWebUnsupportedReason =
'Android only — the catering panel blocks browser requests';
/// Extracts [name]'s value from a (possibly comma-joined) `set-cookie` header.
///
/// `http`'s `Response.headers` collapses repeated headers into one string, so
/// a panel that sets more than one cookie hands over
/// `SESSION=abc; Path=/, OTHER=def; Path=/`. Returns null when the cookie is
/// absent, which the caller treats as a failed login rather than guessing.
String? sessionCookieFrom(String? setCookieHeader) {
if (setCookieHeader == null || setCookieHeader.isEmpty) return null;
// Split on both separators: ',' joins whole cookies, ';' separates a
// cookie's attributes from its value.
for (final part in setCookieHeader.split(RegExp('[,;]'))) {
final trimmed = part.trim();
if (trimmed.startsWith('$kuchniaSessionCookie=')) {
final value = trimmed.substring(kuchniaSessionCookie.length + 1);
if (value.isNotEmpty) return value;
}
}
return null;
}
/// A logged-in panel session with a whole-walk deadline.
class KuchniaSession {
/// Creates a session over [client], authenticating lazily.
KuchniaSession({
required this.username,
required this.password,
http.Client? client,
DateTime? startedAt,
}) : _client = client ?? http.Client(),
_deadline =
(startedAt ?? DateTime.now()).add(kuchniaTotalDeadline);
/// The panel e-mail.
final String username;
/// The panel password.
final String password;
final http.Client _client;
final DateTime _deadline;
/// The session cookie: seeded from a cache to skip the login, and read back
/// afterwards so the caller can persist a freshly minted one.
///
/// Device-local by design -- it is regenerable from the password, so syncing
/// it would widen exposure and buy nothing.
String? sessionCookie;
Map<String, String> get _headers => {
'company-id': kuchniaCompany,
'X-Launcher-Type': kuchniaLauncherType,
'User-Agent': 'diet_guard/1.0 (personal diet tracker)',
'Accept': 'application/json',
if (sessionCookie != null) 'Cookie': '$kuchniaSessionCookie=$sessionCookie',
};
void _checkDeadline() {
if (!DateTime.now().isBefore(_deadline)) {
throw const KuchniaError('catering panel too slow (deadline exceeded)');
}
}
/// Authenticates and caches the session cookie.
///
/// No client-wide `Content-Type`: the login body is form-urlencoded and a
/// sticky JSON default would mislabel it. Passing a `Map` to `http.post`
/// sets the right one automatically.
Future<void> login() async {
_checkDeadline();
final http.Response response;
try {
response = await _client
.post(
Uri.parse('$kuchniaApiBase/auth/login'),
headers: _headers,
body: {'username': username, 'password': password},
)
.timeout(kuchniaTimeout);
} on Exception catch (error) {
throw KuchniaError('catering panel unreachable: $error');
}
if (response.statusCode < 200 || response.statusCode >= 300) {
throw KuchniaError(
'catering login rejected (HTTP ${response.statusCode})',
);
}
final cookie = sessionCookieFrom(response.headers['set-cookie']);
if (cookie == null) {
throw const KuchniaError('catering login returned no session cookie');
}
sessionCookie = cookie;
}
/// GETs [path] and decodes it, re-logging in once if the cookie expired.
///
/// A cached cookie that has expired is indistinguishable from a good one
/// until it is used, so an auth failure is retried exactly once with fresh
/// credentials. A second failure is real.
Future<Object?> getJson(String path) async {
if (sessionCookie == null) await login();
var response = await _get(path);
if (response.statusCode == 401 || response.statusCode == 403) {
sessionCookie = null;
await login();
response = await _get(path);
}
if (response.statusCode < 200 || response.statusCode >= 300) {
throw KuchniaError(
'catering panel returned HTTP ${response.statusCode} for $path',
);
}
try {
return jsonDecode(response.body);
} on FormatException {
throw KuchniaError('catering panel returned a non-JSON body for $path');
}
}
Future<http.Response> _get(String path) async {
_checkDeadline();
try {
return await _client
.get(Uri.parse('$kuchniaApiBase/$path'), headers: _headers)
.timeout(kuchniaTimeout);
} on Exception catch (error) {
throw KuchniaError('catering panel unreachable: $error');
}
}
/// Releases the underlying HTTP client.
void close() => _client.close();
}
/// True when this platform can reach the catering panel at all.
///
/// False on web: the panel sends no CORS headers, so the browser refuses the
/// request before it leaves. Checked before anything platform-shaped runs.
bool get kuchniaFetchSupported => !kIsWeb;

View File

@ -0,0 +1,152 @@
/// The catering panel credential, stored locally and synced across devices.
///
/// One source of truth: this service owns the value, sync writes back into it,
/// and the settings screen reads and writes it here. There is no second copy
/// to drift -- notably it is *not* mirrored into `flutter_secure_storage`,
/// because two homes for one value is exactly how a stale password survives a
/// change made on the other device.
///
/// **The password is stored and synced in plaintext.** The rest of the synced
/// state is not encrypted either, so do not describe this as "encrypted like
/// everything else". The user chose it deliberately: the alternative was a
/// phone that cannot fetch the catering menu at all, and the blast radius is a
/// catering menu and a delivery address.
///
/// Mirrors `diet_guard/_kuchnia_credential_store.py`.
library;
import 'dart:convert';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:flutter/foundation.dart';
/// Reads and writes the catering panel login.
class KuchniaCredentialService {
KuchniaCredentialService._(this._store);
/// Document name this service owns.
static const documentName = 'kuchnia_credential.json';
static KuchniaCredentialService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static KuchniaCredentialService get instance => _instance!;
/// True once [init] has run, so callers can skip work in widget tests that
/// never initialise this service.
static bool get isInitialized => _instance != null;
final DocumentStore _store;
String _username = '';
String _password = '';
String _editedAt = '';
/// The panel e-mail, or the empty string when unset.
static String get username => _instance?._username ?? '';
/// The panel password, or the empty string when unset.
static String get password => _instance?._password ?? '';
/// When the credential was last set, ISO format, or '' when never.
static String get editedAt => _instance?._editedAt ?? '';
/// True when both halves are present, i.e. a fetch could be attempted.
static bool get isConfigured => username.isNotEmpty && password.isNotEmpty;
/// Initialises the singleton against the platform document store.
static Future<KuchniaCredentialService> init() async {
if (_instance != null) return _instance!;
// Resolving the platform store is a plugin call, not reachable from
// `flutter test`.
// coverage:ignore-start
final service = KuchniaCredentialService._(await openDocumentStore());
// coverage:ignore-end
await service._load();
_instance = service;
return service;
}
/// Initialises from [store] for use in unit tests.
@visibleForTesting
static Future<KuchniaCredentialService> initForTesting(
DocumentStore store,
) async {
final service = KuchniaCredentialService._(store);
await service._load();
_instance = service;
return service;
}
/// Resets the singleton so [init] can be called again in tests.
///
/// When [store] is given, reads/writes go there instead of the real platform
/// store -- and because [init] returns early once an instance exists, this
/// is also what keeps a test off the path_provider channel. Mirrors
/// `AppSettingsService.resetForTesting`.
@visibleForTesting
static void resetForTesting({DocumentStore? store}) {
_instance = store == null ? null : KuchniaCredentialService._(store);
}
Future<void> _load() async {
final raw = await _store.read(documentName);
if (raw == null) return;
try {
final data = jsonDecode(raw);
if (data is! Map) return;
_username = data['username'] is String ? data['username'] as String : '';
_password = data['password'] is String ? data['password'] as String : '';
_editedAt = data['t'] is String ? data['t'] as String : '';
} on FormatException {
// Keep the defaults; a corrupt document means "not configured", which is
// never an error at the call site.
}
}
/// Stores a credential the *user* just entered, stamping it now.
///
/// The stamp is what the cross-device merge compares, so an edit made here
/// beats an older one from the PC and vice versa.
Future<void> save(String username, String password) => _persist(
username.trim(),
password,
DateTime.now().toIso8601String(),
);
/// Applies a credential the sync merge resolved, keeping its edit time.
///
/// Persists [editedAt] verbatim -- the winning side's real edit time, not
/// "now" -- so re-syncing an unchanged credential stays idempotent instead
/// of making this device look like the most recent editor on every tick.
Future<void> applySynced(
String username,
String password,
String editedAt,
) async {
if (username == _username &&
password == _password &&
editedAt == _editedAt) {
return;
}
await _persist(username, password, editedAt);
}
Future<void> _persist(
String username,
String password,
String editedAt,
) async {
_username = username;
_password = password;
_editedAt = editedAt;
await _store.write(
documentName,
jsonEncode({
'username': _username,
'password': _password,
't': _editedAt,
}),
);
}
}

View File

@ -0,0 +1,19 @@
/// The catering import's single error type.
///
/// Mirrors `diet_guard/_kuchnia_errors.py`. Every failure the panel can hand
/// back becomes one of these, so the fail-closed boundary in
/// `kuchnia_import.dart` has exactly one exception to translate into a reason
/// string -- a catering outage must never break the caller.
library;
/// Raised when the catering panel cannot be read.
class KuchniaError implements Exception {
/// Creates an error carrying a user-facing [message].
const KuchniaError(this.message);
/// Why the panel could not be read, phrased for display.
final String message;
@override
String toString() => message;
}

View File

@ -0,0 +1,134 @@
/// Fetches the day's catering dishes and banks them.
///
/// The Dart mirror of `diet_guard/_kuchnia_import.py`, and the module's single
/// fail-closed boundary: every [KuchniaError] is turned into a reason string
/// here, so no caller can be broken by a catering outage.
///
/// **Nothing is ever logged from here.** A delivered meal is not an eaten
/// meal: dishes land in the *curated* bank and the user still taps to log
/// each one. If the import logged automatically, the gate would satisfy its
/// own checkpoint from a delivery note, and the log would record what the
/// courier dropped off rather than what was eaten -- skipped, shared and
/// binned meals included.
///
/// Imports go **only** to the curated bank. The derived bank is rebuilt from
/// the log on every meal, so anything written there would vanish at the next
/// entry.
///
/// The idempotency guard is load-bearing and easy to get wrong.
/// `addManualEntry` restamps `editedAt` unconditionally and the sync merge
/// derives each record's clock from it -- so calling it for unchanged dishes
/// would republish the *entire* curated bank to every peer on every refresh.
/// [bankDishes] therefore compares the nutritional fields first and writes
/// only what actually differs.
library;
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/kuchnia_errors.dart';
import 'package:diet_guard_app/services/kuchnia_orders.dart';
/// The result of one refresh: the dishes, or why there are none.
class KuchniaRefresh {
/// Creates a refresh result.
const KuchniaRefresh({this.dishes = const [], this.reason});
/// The day's dishes, empty on failure or when nothing was delivered.
final List<KuchniaDish> dishes;
/// Why the panel could not be read, or null on success.
///
/// Callers surface this and carry on; it is never thrown.
final String? reason;
/// True when the fetch succeeded, whether or not anything was delivered.
bool get ok => reason == null;
}
/// Returns the curated-bank record for [dish].
FoodBankRecord dishToRecord(KuchniaDish dish) => FoodBankRecord(
desc: dish.name,
kcal: dish.kcal,
proteinG: dish.proteinG,
carbsG: dish.carbsG,
fatG: dish.fatG,
grams: dish.grams,
// The bank's count ranks foods by how often they were *eaten*, and a
// delivered dish has not been eaten yet.
count: 0,
);
/// True when [existing] already says exactly what [dish] says.
///
/// Compares the nutritional fields only. `editedAt` is excluded deliberately:
/// it is the edit stamp, not part of the record's meaning, and including it
/// would make every comparison differ -- which is the republish flood this
/// guard exists to prevent.
///
/// Numeric comparison, not string: `270 == 270.0` must be true here exactly as
/// it is in Python's `_matches`.
bool bankRecordMatches(FoodBankRecord existing, KuchniaDish dish) =>
existing.desc == dish.name &&
existing.kcal == dish.kcal &&
existing.proteinG == dish.proteinG &&
existing.carbsG == dish.carbsG &&
existing.fatG == dish.fatG &&
existing.grams == dish.grams;
/// Adds [dishes] to the curated bank, skipping ones already banked unchanged.
///
/// Returns how many records were actually written -- which is what the tests
/// assert on, because "the entry exists" passes while the guard misbehaves.
Future<int> bankDishes(List<KuchniaDish> dishes) async {
final bank = await FoodBankService.instance.readManualBank();
var written = 0;
for (final dish in dishes) {
final existing = bank[dish.bankKey];
if (existing != null && bankRecordMatches(existing, dish)) continue;
await FoodBankService.instance.addManualEntry(dishToRecord(dish));
written++;
}
return written;
}
/// Fetches [day]'s dishes and banks them, never throwing.
///
/// Returns a reason string instead of raising, so a catering outage cannot
/// break the caller. On web it returns [kuchniaWebUnsupportedReason] without
/// touching the network: the panel sends no CORS headers, so the browser would
/// refuse the request anyway. That check comes first, before anything
/// platform-shaped runs.
Future<KuchniaRefresh> refreshDelivery(
DateTime day, {
KuchniaSession Function(String username, String password)? sessionFactory,
}) async {
if (!kuchniaFetchSupported) {
return const KuchniaRefresh(reason: kuchniaWebUnsupportedReason);
}
if (!KuchniaCredentialService.isConfigured) {
return const KuchniaRefresh(
reason: 'no catering credentials — add them in Settings',
);
}
final session =
(sessionFactory ??
(username, password) =>
KuchniaSession(username: username, password: password))(
KuchniaCredentialService.username,
KuchniaCredentialService.password,
);
List<KuchniaDish> dishes;
try {
dishes = await fetchDishes(session, day);
} on KuchniaError catch (error) {
return KuchniaRefresh(reason: error.message);
} finally {
session.close();
}
await bankDishes(dishes);
return KuchniaRefresh(dishes: dishes);
}

View File

@ -0,0 +1,80 @@
/// Walks the panel's endpoints to a day's delivered dishes.
///
/// The Dart mirror of `diet_guard/_kuchnia_orders.py`. Three calls, and the
/// shape of the walk is not what the endpoint names suggest:
///
/// 1. `company/customer/order/active-ids` -> `[orderId]`.
/// 2. `company/customer/order/{orderId}` -> the order, which **embeds every
/// delivery** with its date. No enumeration call is needed, but the
/// embedded `deliveryMeals` carry ids only -- no names, no macros.
/// 3. `company/general/menus/delivery/{deliveryId}/new` -> the day's actual
/// menu, with names and per-portion nutrition.
///
/// Step 3 is the important correction: the obvious-looking
/// `.../deliveries/{id}/details` **404s** (and 400s when keyed by date),
/// confirmed against three separate delivery days. The menu endpoint is keyed
/// by the opaque `deliveryId`, never by the date.
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/services/kuchnia_errors.dart';
import 'package:diet_guard_app/services/kuchnia_parse.dart';
/// Returns the first active order id, or null when there is no active order.
Object? activeOrderId(Object? payload) {
if (payload is! List || payload.isEmpty) return null;
return payload.first;
}
/// Returns the delivery id whose date is [wanted] (an ISO `YYYY-MM-DD`).
///
/// Null when that day has no delivery, or only a cancelled one -- a `deleted`
/// delivery still appears in the list.
Object? deliveryIdFor(Object? payload, String wanted) {
if (payload is! Map) return null;
final deliveries = payload['deliveries'];
if (deliveries is! List) return null;
for (final delivery in deliveries) {
if (delivery is! Map) continue;
if (delivery['deleted'] == true) continue;
if ('${delivery['date']}' == wanted) return delivery['deliveryId'];
}
return null;
}
/// Formats [day] as the ISO `YYYY-MM-DD` the panel keys deliveries by.
String isoDay(DateTime day) =>
'${day.year.toString().padLeft(4, '0')}-'
'${day.month.toString().padLeft(2, '0')}-'
'${day.day.toString().padLeft(2, '0')}';
/// Returns the dishes delivered on [day], empty when nothing is delivered.
///
/// Throws [KuchniaError] when the panel cannot be read, or when a delivery
/// exists but nothing survived parsing -- either the menu is not published yet
/// or its units failed the consistency check. Both are "no data", but they are
/// worth distinguishing from "no delivery" in the caller's message.
Future<List<KuchniaDish>> fetchDishes(
KuchniaSession session,
DateTime day,
) async {
final orderId = activeOrderId(await session.getJson(
'company/customer/order/active-ids',
));
if (orderId == null) return const [];
final order = await session.getJson('company/customer/order/$orderId');
final wanted = isoDay(day);
final deliveryId = deliveryIdFor(order, wanted);
if (deliveryId == null) return const [];
final menu = await session.getJson(
'company/general/menus/delivery/$deliveryId/new',
);
final dishes = parseMenu(menu);
if (dishes.isEmpty) {
throw KuchniaError('catering menu for $wanted has no usable dishes');
}
return dishes;
}

View File

@ -0,0 +1,134 @@
/// Turns the catering panel's menu payload into [KuchniaDish] records.
///
/// The Dart mirror of `diet_guard/_kuchnia_parse.py`. The shape that matters:
///
/// ```json
/// {"deliveryMenuMeal": [
/// {"mealName": "Śniadanie",
/// "menuMealName": "Marchewkowe pancakes, ...",
/// "mealPriority": 1,
/// "nutrition": {"weight": 270.0, "calories": 435.0, "protein": 25.86,
/// "carbohydrate": 54.64, "fat": 12.01}},
/// ...]}
/// ```
///
/// **Macros are per portion and `weight` is that portion in grams.** Verified
/// arithmetically rather than assumed. Had they been per-100 g, every imported
/// meal would have been silently wrong by a factor of several -- which is why
/// [parseMenu] drops a dish whose numbers do not hold together instead of
/// importing a plausible-looking lie.
///
/// KEEP IN SYNC WITH `diet_guard/_kuchnia_parse.py`. If the two sides disagree
/// about which dishes pass, each re-adds what the other dropped and the
/// curated bank republishes to every peer on every refresh. Gated by
/// `tests/fixtures/kuchnia_day.json`.
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
/// Atwater factors. Used only as a sanity check on the *units*, never to
/// recompute a value the panel already states.
const double _kcalPerGProtein = 4;
const double _kcalPerGCarb = 4;
const double _kcalPerGFat = 9;
/// How far the macro-derived energy may drift from the stated calories before
/// the dish is treated as unusable.
///
/// Generous by design: the panel rounds, and fibre and polyols carry energy
/// these three factors ignore. A per-100 g mix-up misses by a factor of 2-5,
/// nowhere near this band.
///
/// **This is 0.35, not the "~1%" some prose says** -- that figure describes how
/// closely the captured day happened to agree, not the threshold. Porting 0.01
/// here would drop dishes the PC keeps.
const double kuchniaEnergyTolerance = 0.35;
/// A portion outside this range is not a meal. Guards against a unit change
/// (kg for g) rather than against unusual food.
const double _minGrams = 1;
const double _maxGrams = 5000;
/// Coerces a stored field to `double`, defaulting to 0.
///
/// Mirrors `diet_guard/_coerce.as_float` exactly, and the exactness is
/// load-bearing: bools and **strings** both yield 0. A payload with
/// `"calories": "435"` must be *dropped* by both devices, so this must not
/// reach for `double.tryParse` -- that would keep a dish the PC discards.
double asDouble(Object? value) {
if (value is bool) return 0;
if (value is num) return value.toDouble();
return 0;
}
/// Returns true when the macros roughly account for the stated calories.
///
/// A *unit* check, not a nutrition check: it catches a payload whose macros
/// and calories are quoted on different bases (per portion vs per 100 g),
/// which is the one failure mode that would corrupt every import without
/// looking wrong.
bool energyIsConsistent(double kcal, double protein, double carbs, double fat) {
if (kcal <= 0) return false;
final derived =
_kcalPerGProtein * protein + _kcalPerGCarb * carbs + _kcalPerGFat * fat;
return (derived - kcal).abs() <= kuchniaEnergyTolerance * kcal;
}
/// Builds one dish, or null when the entry is unusable.
///
/// [fallbackPriority] is the 1-based payload position, used when
/// `mealPriority` is missing.
KuchniaDish? parseMeal(Object? meal, int fallbackPriority) {
if (meal is! Map) return null;
final nutrition = meal['nutrition'];
if (nutrition is! Map) return null;
// `menuMealName` is the dish; `mealName` is the slot label ("Kolacja"),
// which would collapse every Monday dinner onto one bank entry.
final rawName = meal['menuMealName'];
final name = rawName is String ? rawName.trim() : '';
if (name.isEmpty) return null;
final kcal = asDouble(nutrition['calories']);
final protein = asDouble(nutrition['protein']);
final carbs = asDouble(nutrition['carbohydrate']);
final fat = asDouble(nutrition['fat']);
final grams = asDouble(nutrition['weight']);
if (grams < _minGrams || grams > _maxGrams) return null;
if (!energyIsConsistent(kcal, protein, carbs, fat)) return null;
// Python rejects bools here (they are an int subclass); Dart's `is int` is
// already false for a bool, so the check is naturally equivalent.
final rawPriority = meal['mealPriority'];
final priority = rawPriority is int ? rawPriority : fallbackPriority;
final rawLabel = meal['mealName'];
return KuchniaDish(
name: name,
kcal: kcal,
proteinG: protein,
carbsG: carbs,
fatG: fat,
grams: grams,
priority: priority,
slotLabel: rawLabel is String ? rawLabel.trim() : '',
);
}
/// Extracts the day's dishes from a `menus/delivery/{id}/new` response.
///
/// Unusable entries are skipped rather than thrown on: a single malformed dish
/// must not cost the user the other four. Returns the dishes in payload order;
/// `kuchnia_spread.dart` sorts them by priority.
List<KuchniaDish> parseMenu(Object? payload) {
if (payload is! Map) return const [];
final meals = payload['deliveryMenuMeal'];
if (meals is! List) return const [];
final dishes = <KuchniaDish>[];
for (var index = 0; index < meals.length; index++) {
final dish = parseMeal(meals[index], index + 1);
if (dish != null) dishes.add(dish);
}
return dishes;
}

View File

@ -0,0 +1,145 @@
/// The day's delivered dishes, offered to the log form one at a time.
///
/// **A delivered meal is not an eaten meal.** This queue only ever *prefills*
/// the form; the user still taps to log each dish. Nothing here writes a log
/// entry, and nothing here may start doing so -- the gate would then satisfy
/// its own checkpoint from a delivery note, and the log would record what the
/// courier dropped off rather than what was eaten.
///
/// Two things are load-bearing:
///
/// * **The queue survives a submit.** After a dish is logged the next one is
/// already in the form, so one tap walks the whole delivery. On the PC this
/// regressed once into a dead letter -- every dish after the first stayed
/// queued behind another click, and because the refresh there is unguarded
/// that meant a fresh login-plus-three-requests *per dish*.
/// * **The automatic refresh is guarded** by a device-local "already fetched
/// today" marker, mirroring Python's `refresh_delivery_once`. Without it
/// every logged meal would pay a login plus three requests against a third
/// party. Only a *clean* fetch records the day, so an outage is retried.
/// The settings button deliberately does **not** go through this: an
/// explicit ask always goes and looks, matching `diet-guard kuchnia`.
library;
import 'package:diet_guard_app/models/kuchnia_dish.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/kuchnia_import.dart';
import 'package:diet_guard_app/services/kuchnia_orders.dart' show isoDay;
import 'package:flutter/foundation.dart';
/// Holds today's delivered dishes and hands them out in the caterer's order.
class KuchniaQueueService {
KuchniaQueueService._(this._store);
/// Document holding the last fetched day, one ISO date.
///
/// Device-local on purpose: this is a rate limit, not shared state. Syncing
/// it would let one device's fetch suppress another's.
static const documentName = 'kuchnia_last_import.json';
static KuchniaQueueService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static KuchniaQueueService get instance => _instance!;
/// True once initialised, so callers can skip work in widget tests.
static bool get isInitialized => _instance != null;
final DocumentStore _store;
final List<KuchniaDish> _pending = [];
String _lastImportDay = '';
/// The dishes not yet logged, in the caterer's own meal order.
static List<KuchniaDish> get pending =>
List.unmodifiable(_instance?._pending ?? const []);
/// The next dish to offer, or null when the queue is empty.
static KuchniaDish? get next =>
(_instance?._pending.isEmpty ?? true) ? null : _instance!._pending.first;
/// How many dishes are still waiting to be logged.
static int get remaining => _instance?._pending.length ?? 0;
/// Initialises the singleton against the platform document store.
///
/// Without this the queue silently no-ops on a real device: every entry
/// point checks [isInitialized] first, so a missing call reads as "no
/// delivery" rather than as an error.
static Future<KuchniaQueueService> init() async {
if (_instance != null) return _instance!;
// Resolving the platform store is a plugin call, not reachable from
// `flutter test`.
// coverage:ignore-start
final service = KuchniaQueueService._(await openDocumentStore());
// coverage:ignore-end
await service._load();
_instance = service;
return service;
}
/// Initialises from [store], for tests.
@visibleForTesting
static Future<KuchniaQueueService> initForTesting(DocumentStore store) async {
final service = KuchniaQueueService._(store);
await service._load();
_instance = service;
return service;
}
/// Resets the singleton so [initForTesting] can run again.
@visibleForTesting
static void resetForTesting() => _instance = null;
Future<void> _load() async {
final raw = await _store.read(documentName);
if (raw != null) _lastImportDay = raw.trim();
}
/// True when [day]'s delivery has already been fetched on this device.
bool alreadyFetched(DateTime day) => _lastImportDay == isoDay(day);
/// Records that [day]'s delivery was fetched cleanly.
///
/// Best-effort: this is a rate limit, not state anyone depends on. Failing
/// to write it costs one extra fetch, which is strictly better than failing
/// an import that already succeeded.
Future<void> recordFetched(DateTime day) async {
_lastImportDay = isoDay(day);
try {
await _store.write(documentName, _lastImportDay);
} on Exception {
// Ignore: an unrecorded fetch just means we look again.
}
}
/// Replaces the queue with [dishes], dropping any already logged today.
void offer(List<KuchniaDish> dishes, {Set<String> alreadyLogged = const {}}) {
_pending
..clear()
..addAll(
dishes.where((dish) => !alreadyLogged.contains(dish.bankKey)),
);
}
/// Removes [dish] from the queue once it has actually been logged.
void markLogged(KuchniaDish dish) =>
_pending.removeWhere((queued) => queued.bankKey == dish.bankKey);
/// Empties the queue, e.g. when the day rolls over.
void clear() => _pending.clear();
/// Fetches [day]'s delivery unless it has already been fetched today.
///
/// Returns an empty, successful result when the day was already fetched --
/// "nothing new", not an error. This is the entry point every *automatic*
/// trigger uses; the settings button calls [refreshDelivery] directly.
static Future<KuchniaRefresh> refreshOnce(DateTime day) async {
final service = _instance;
if (service == null) return const KuchniaRefresh();
if (service.alreadyFetched(day)) return const KuchniaRefresh();
final result = await refreshDelivery(day);
if (result.ok) await service.recordFetched(day);
return result;
}
}

View File

@ -0,0 +1,111 @@
/// Assigns catering dishes to meal slots, in the provider's own order.
///
/// The Dart mirror of `diet_guard/_kuchnia_spread.py`.
///
/// The panel returns each dish with a `mealPriority` (1..N: Śniadanie, II
/// śniadanie, Obiad, Podwieczorek, Kolacja) -- the order the catering intends
/// them to be eaten in. That beats inferring an order from the dish names, and
/// it beats spreading them arithmetically.
///
/// Counts rarely match: a 5-meal plan against the default 4 slots means two
/// dishes share the first slot. The mapping is `i * S ~/ N`, which is
/// monotonic non-decreasing, keeps the first dish on the first slot and the
/// last on the last, and doubles up the earliest slots rather than dropping
/// anything.
///
/// **Integer `~/` only, never `round()`.** Repo convention for slot arithmetic
/// (`docs/meal-schedule.md`): Python's `round` is banker's and Dart's is
/// half-away-from-zero, so a float path silently desyncs the two devices --
/// and a slot one device offers while the other does not is a checkpoint that
/// can never be satisfied, i.e. a permanent lock. `index`, `span` and `count`
/// are all `int`, so `~/` matches Python's `//` exactly (`~/` on doubles
/// truncates toward zero where `//` floors).
///
/// KEEP IN SYNC WITH `diet_guard/_kuchnia_spread.py`, gated by
/// `tests/fixtures/kuchnia_day.json`.
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
/// A dish paired with the meal-slot hour it was assigned to.
class SlottedDish {
/// Pairs [dish] with the [slot] hour it should be logged against.
const SlottedDish({required this.dish, required this.slot});
/// The dish itself.
final KuchniaDish dish;
/// The slot hour, e.g. `12` for the 12:00 checkpoint.
final int slot;
}
/// Pairs each dish with a slot hour, following the provider's meal order.
///
/// Returns an empty list when either input is empty -- a day with no delivery
/// and a schedule with no slots are both "nothing to assign", not errors.
List<SlottedDish> assignSlots(List<KuchniaDish> dishes, List<int> slots) {
if (dishes.isEmpty || slots.isEmpty) return const [];
// Ties fall back to name so the result is deterministic; a bank import that
// reshuffled between runs would look like a change and re-stamp every
// record.
//
// The payload index is the final tiebreak because `List.sort` is *not*
// stable in Dart while Python's `sorted` is: two dishes sharing both
// priority and name would otherwise be free to swap here and not on the PC.
// With the index in the comparator the ordering is total, so both languages
// agree without relying on either sort's stability.
final indexed = <(int, KuchniaDish)>[
for (var i = 0; i < dishes.length; i++) (i, dishes[i]),
]..sort((a, b) {
final byPriority = a.$2.priority.compareTo(b.$2.priority);
if (byPriority != 0) return byPriority;
final byName = a.$2.name.compareTo(b.$2.name);
if (byName != 0) return byName;
return a.$1.compareTo(b.$1);
});
final count = indexed.length;
final span = slots.length;
return [
for (var index = 0; index < count; index++)
SlottedDish(
dish: indexed[index].$2,
slot: slots[index * span ~/ count],
),
];
}
/// Returns [dishes] ordered by the provider's own meal priority.
///
/// So the dish offered for the slot being filled is the one the catering
/// actually intends for it, rather than whatever order the payload arrived in.
List<KuchniaDish> dishesInSlotOrder(
List<KuchniaDish> dishes,
List<int> slots,
) => [for (final item in assignSlots(dishes, slots)) item.dish];
/// Returns `(portionGrams, (kcal, protein, carbs, fat))` as form strings.
///
/// Mirrors `_kuchnia_spread.dish_field_values`. Formatted here rather than in
/// the widget so the numeric formatting is covered by a test that needs no
/// display.
///
/// Python uses `f"{value:g}"`, which drops a trailing `.0`; Dart's
/// `toStringAsFixed` would keep it and `toString` would render `435.0`. So a
/// whole number is printed as an integer and anything else keeps its
/// decimals -- the form should read "435", not "435.0".
(String, (String, String, String, String)) dishFieldValues(KuchniaDish dish) {
String format(double value) => value == value.roundToDouble()
? value.toInt().toString()
: value.toString();
return (
format(dish.grams),
(
format(dish.kcal),
format(dish.proteinG),
format(dish.carbsG),
format(dish.fatG),
),
);
}

View File

@ -0,0 +1,146 @@
/// The catering panel credential as its own synced document.
///
/// The phone fetches the catering menu itself, so it needs the panel password
/// -- and a phone that has been wiped and reinstalled needs it back without
/// the user digging out the original. So the credential syncs.
///
/// **It travels in plaintext.** Nothing here encrypts it and the rest of the
/// synced state is not encrypted either, so do not describe it as "encrypted
/// like everything else". Its blast radius is a catering menu and a delivery
/// address, and the user chose this deliberately over a phone that cannot
/// fetch at all. The live session cookie is *not* synced: it is regenerable
/// from the password, so copying it would widen exposure and buy nothing.
///
/// Its own document rather than a field on the `budget` record: `budget.json`
/// is written back at default permissions on the PC, so a password riding
/// inside it would be readable by anything that reads the budget.
///
/// Two fields rather than one record body, so a device that only ever set the
/// username cannot clobber a peer's password with a whole-map LWW. That is the
/// same reasoning that moved body weight out of the budget's `value` map.
///
/// KEEP IN SYNC WITH `diet_guard/sync_merge/_kuchnia.py`.
library;
import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
/// Stable id: exactly one credential record per device-pushed file.
const kuchniaRecordId = 'kuchnia';
/// The panel login, as two independently-clocked fields.
///
/// The Python side spells its password constant as `"pass" + "word"` rather
/// than a literal. That is not a different value -- it is the same
/// `'password'` on the wire -- it only stops ruff's S105 reading the literal
/// as a hardcoded secret, in a repo that bans `noqa` outright. Do not
/// "fix" either side to match the other's spelling.
const kuchniaUsernameField = 'username';
/// The password field name on the wire. See [kuchniaUsernameField].
const kuchniaPasswordField = 'password';
/// Derives a deterministic [Hlc] for a credential from its edit time.
///
/// Identical inputs always yield the same clock, so re-syncing an unchanged
/// credential is a no-op rather than a fresh push on every tick.
///
/// Derived from the *parsed* timestamp rather than the raw string, so the two
/// languages agree even though they format the epoch fallback differently --
/// the same trick `sync_merge_schedule.dart` uses. Python catches
/// `ValueError` from `fromisoformat` and falls back to the epoch; the `?? 0`
/// here is that same fallback.
Hlc kuchniaCredentialHlc(String editedAt) {
final wallTimeMs =
DateTime.tryParse(editedAt)?.toUtc().millisecondsSinceEpoch ?? 0;
return Hlc.newTick(currentSyncDeviceId, wallTimeMsOverride: wallTimeMs);
}
/// Converts this device's catering credential into a [Log].
///
/// Returns an empty [Log] when either half is blank, so a half-filled settings
/// form contributes nothing to the merge rather than pushing an empty-string
/// password that would win LWW against a peer's real one.
Log credentialToLog(String username, String password, String editedAt) {
if (username.isEmpty || password.isEmpty) return {};
final hlc = kuchniaCredentialHlc(editedAt);
return {
kuchniaRecordId: Record(
id: kuchniaRecordId,
fields: {
kuchniaUsernameField: (username, hlc),
kuchniaPasswordField: (password, hlc),
},
),
};
}
/// One resolved catering credential, as the merge settled it.
class KuchniaCredential {
/// Creates a resolved credential.
const KuchniaCredential({
required this.username,
required this.password,
required this.editedAt,
});
/// The panel e-mail.
final String username;
/// The panel password.
final String password;
/// When the winning side last set it, ISO format.
final String editedAt;
}
/// Extracts the credential from a merged [Log].
///
/// Returns null when no device has contributed one yet, or when the merged
/// record is missing either half -- callers treat that as "not configured",
/// which is never an error at the call site.
///
/// `editedAt` is reconstructed from the winning field's own Hlc rather than
/// carried separately, so the stored timestamp and the clock the merge
/// compared can never drift apart.
KuchniaCredential? logToCredential(Log log) {
final record = log[kuchniaRecordId];
if (record == null) return null;
final username = record.fields[kuchniaUsernameField]?.$1;
final passwordField = record.fields[kuchniaPasswordField];
final password = passwordField?.$1;
if (username is! String || password is! String) return null;
if (username.isEmpty || password.isEmpty) return null;
final hlc = passwordField!.$2;
return KuchniaCredential(
username: username,
password: password,
editedAt: DateTime.fromMillisecondsSinceEpoch(
hlc.wallTimeMs,
isUtc: true,
).toLocal().toIso8601String(),
);
}
/// Parses one device's pushed credential file into a [Log].
///
/// Throwing [FormatException] or [TypeError] is treated as unparsable by the
/// caller, matching `parseRemoteBudget`'s tolerance for a corrupt push.
Log parseRemoteCredential(String text) {
final raw = jsonDecode(text);
if (raw is! Map) {
throw const FormatException(
'top-level catering credential 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 credential [Log] for push.
String encodeCredentialForPush(Log log) => jsonEncode({
for (final entry in log.entries) entry.key: entry.value.toJson(),
});

View File

@ -17,10 +17,12 @@ import 'package:diet_guard_app/models/food_entry.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/foodbank_service.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:diet_guard_app/services/sync_merge.dart';
import 'package:diet_guard_app/services/sync_merge_kuchnia.dart';
import 'package:diet_guard_app/services/sync_merge_schedule.dart';
import 'package:diet_guard_app/services/sync_state_factory.dart';
@ -59,6 +61,7 @@ Future<DayLog> runSync(RemoteStore client, {SyncStateStore? stateStore}) async {
await _syncBudget(client);
await _syncFoodBank(client);
await _syncManualBank(client);
await _syncKuchniaCredential(client);
return merged;
}
@ -172,3 +175,39 @@ Future<void> _syncBudget(RemoteStore client) async {
updatedAt: DateTime.tryParse(merged['t'] as String? ?? ''),
);
}
/// Pulls peers' catering credentials, merges, applies the winner locally.
///
/// The phone runs its own catering importer, so it cannot fetch anything until
/// the panel password reaches it -- that is the whole reason this credential
/// syncs at all. It is plaintext on the wire, like the rest of the synced
/// state; see `sync_merge_kuchnia.dart`.
///
/// A device that has no credential contributes an empty log, so it neither
/// blocks nor clobbers a peer's real value -- it relays it. Mirrors
/// `diet_guard/_sync_kuchnia.py`.
Future<void> _syncKuchniaCredential(RemoteStore client) async {
if (!KuchniaCredentialService.isInitialized) return;
final merged = await syncLog(
client: client,
deviceId: currentSyncDeviceId,
legacyDeviceId: legacySyncDeviceId,
pathPrefix: _devicesDir,
localLog: credentialToLog(
KuchniaCredentialService.username,
KuchniaCredentialService.password,
KuchniaCredentialService.editedAt,
),
encode: encodeCredentialForPush,
decode: parseRemoteCredential,
filename: 'kuchnia.json',
commitMessage: 'diet_guard_app sync',
);
final credential = logToCredential(merged);
if (credential == null) return;
await KuchniaCredentialService.instance.applySynced(
credential.username,
credential.password,
credential.editedAt,
);
}

View File

@ -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.57+1
version: 1.0.67+1
environment:
sdk: ^3.12.2

View File

@ -0,0 +1,207 @@
/// The Dart half of the cross-language catering parity gate.
///
/// `diet_guard/tests/test_kuchnia_parity.py` asserts the *same* expectations
/// against the *same* `tests/fixtures/kuchnia_day.json`. Two independently
/// written suites from the same prose is not a gate -- one shared input with
/// one shared expected result is, because a divergence has to surface as a
/// failure on one side rather than as two self-consistent implementations.
///
/// What the parity protects, per `docs/kuchnia-wikinga.md`:
///
/// * **Slot assignment.** A slot one device offers while the other does not is
/// a checkpoint that can never be satisfied -- a permanent lock.
/// * **Which dishes are dropped.** If the two sides disagree, each re-adds
/// what the other dropped, `add_manual_entry` restamps `t` unconditionally,
/// and the curated bank republishes to every peer on every refresh.
/// * **Bank keys and record values**, including their JSON *types*.
///
/// `dart:io` is fine here: the repo invariant only scans `lib/`, and
/// `flutter test` runs on the VM.
library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/services/kuchnia_parse.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:flutter_test/flutter_test.dart';
/// The repo root, found by walking up from the package directory.
///
/// Mirrors `repo_invariants_test.dart`'s approach so the test works whatever
/// working directory `flutter test` picks.
Directory get _repoRoot {
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;
}
// `dir` is app/; the fixture is shared, so it lives at the repo root.
return dir.parent;
}
File get _fixtureFile =>
File('${_repoRoot.path}/tests/fixtures/kuchnia_day.json');
void main() {
late Map<String, dynamic> fixture;
late Map<String, dynamic> expected;
late List<KuchniaDish> dishes;
setUpAll(() {
fixture =
jsonDecode(_fixtureFile.readAsStringSync()) as Map<String, dynamic>;
expected = fixture['expected'] as Map<String, dynamic>;
dishes = parseMenu(fixture['payload']);
});
test('the shared fixture is present', () {
// Asserted explicitly so a relocation fails with a clear reason rather
// than as a confusing cast error inside another test.
expect(
_fixtureFile.existsSync(),
isTrue,
reason: 'shared parity fixture missing at ${_fixtureFile.path}. It is '
'read by both flutter test and pytest; regenerate with '
'scripts/build_kuchnia_fixture.py.',
);
});
test('parsed dishes match the shared expectation', () {
final actual = [
for (final dish in dishes)
{
'name': dish.name,
'kcal': dish.kcal,
'protein_g': dish.proteinG,
'carbs_g': dish.carbsG,
'fat_g': dish.fatG,
'grams': dish.grams,
'priority': dish.priority,
'slot_label': dish.slotLabel,
},
];
expect(actual, equals(expected['dishes']));
});
test('the same meals are dropped on both sides', () {
// Vacuous against a clean capture, which is why the fixture carries a
// per-100 g mix-up, an absurd portion, a stringly-typed number, a non-map
// entry and a meal with no nutrition at all.
final total = (fixture['payload'] as Map)['deliveryMenuMeal'] as List;
expect(total.length - dishes.length, equals(expected['dropped_count']));
expect(expected['dropped_count'], greaterThan(0));
});
test('slot assignment matches for every configured schedule', () {
final slotCases = expected['slots'] as Map<String, dynamic>;
for (final entry in slotCases.entries) {
var key = entry.key;
var subject = dishes;
if (key.startsWith('first_three_')) {
subject = dishes.take(3).toList();
key = key.substring('first_three_'.length);
}
final hours = [for (final part in key.split(',')) int.parse(part)];
final actual = [
for (final item in assignSlots(subject, hours)) item.slot,
];
expect(
actual,
equals(entry.value),
reason: 'slot assignment diverged for ${entry.key}',
);
}
});
test('slot ordering is total, so the twin-dish pair cannot reshuffle', () {
// Dart's List.sort is not stable and Python's sorted is, so two dishes
// sharing both priority and name are what force the comparator to be
// total. Run repeatedly: an unstable sort need not misbehave every time.
for (var attempt = 0; attempt < 5; attempt++) {
final ordered = assignSlots(parseMenu(fixture['payload']), const [
8,
12,
16,
20,
]);
expect(
[for (final item in ordered) item.dish.name],
equals(expected['slot_order']),
);
}
});
test('bank keys match', () {
expect(
[for (final dish in dishes) dish.bankKey],
equals(expected['bank_keys']),
);
});
test('bank records match by value', () {
// Numeric comparison, not string: `270 == 270.0` must be true here exactly
// as it is in Python's `_matches`, or every phone refresh rewrites the
// whole curated bank.
expect(
[for (final dish in dishes) dish.toBankRecord()],
equals(expected['bank_records']),
);
});
test('bank records encode byte-identically to the Python ones', () {
// The real divergence risk is int-vs-double at the JSON boundary:
// jsonEncode(435) emits `435` where Python emits `435.0`. Comparing the
// encoded text (canonical key order on both sides) is what catches it;
// the value comparison above would not.
final expectedRecords = expected['bank_records'] as List;
for (var i = 0; i < dishes.length; i++) {
final actual = dishes[i].toBankRecord();
final wanted = (expectedRecords[i] as Map).cast<String, dynamic>();
final sortedKeys = actual.keys.toList()..sort();
String canonical(Map<String, dynamic> record) => jsonEncode({
for (final key in sortedKeys) key: record[key],
});
expect(
canonical(actual),
equals(canonical(wanted)),
reason: 'record ${i + 1} (${dishes[i].name}) encodes differently to '
'the Python-banked record; check int vs double.',
);
}
});
test('macros bank as doubles and count as an int', () {
for (final dish in dishes) {
final record = dish.toBankRecord();
for (final key in ['kcal', 'protein_g', 'carbs_g', 'fat_g', 'grams']) {
expect(
record[key],
isA<double>(),
reason: '$key must bank as a double, or its JSON loses the ".0"',
);
}
expect(record['count'], isA<int>());
}
});
test('a stringly-typed number is coerced to 0, never parsed', () {
// Pins the `as_float` contract. `double.tryParse` here would keep a dish
// the PC drops, and then each device re-adds what the other removed.
expect(asDouble('435'), equals(0.0));
expect(asDouble(true), equals(0.0));
expect(asDouble(null), equals(0.0));
expect(asDouble(435), equals(435.0));
expect(asDouble(435.5), equals(435.5));
});
test('the energy tolerance is 0.35, not the "~1%" in the prose', () {
// Porting 0.01 would drop dishes the PC keeps, and each side would re-add
// what the other dropped -- the republish flood.
expect(kuchniaEnergyTolerance, equals(0.35));
});
}

View File

@ -125,6 +125,28 @@ void main() {
});
});
group('singletons that silently no-op are initialised at startup', () {
// Every catering entry point checks `isInitialized` first and returns
// quietly when it is false, so a missing `init()` does not throw -- it
// reads as "no delivery" and "no credential" forever. That is invisible in
// widget tests, which initialise these directly, and was caught only by
// grepping main.dart before a phone deploy.
test('main.dart initialises the catering services', () {
final source = File('${_appDir.path}/lib/main.dart').readAsStringSync();
for (final call in [
'KuchniaCredentialService.init()',
'KuchniaQueueService.init()',
]) {
expect(
source.contains(call),
isTrue,
reason: '$call is missing from main(). The feature will silently do '
'nothing on a real device while every test still passes.',
);
}
});
});
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

View File

@ -0,0 +1,187 @@
/// The delivered-dish queue as the log form actually drives it.
///
/// `kuchnia_queue_test.dart` covers the queue's own state machine. This file
/// covers the part that state machine exists for and that a queue-only test
/// cannot see: after a submit, are the **form controllers** already holding
/// the next dish?
///
/// That distinction is the whole point. On the PC this regressed once --
/// `_prefill_next_dish` briefly had exactly one caller, so the queue was
/// correct and the form was not. Every dish after the first stayed behind
/// another tap and the "(N more to go)" line became a dead letter. A test
/// asserting "the dish was offered" passes throughout that bug; one asserting
/// the controller contents after a submit does not.
///
/// Driven through a minimal host rather than the real `LogMealScreen`: that
/// screen's `initState` fans out into sync, notifications and the food bank,
/// and pumping it to quiescence in a widget test does not terminate. The
/// mixin is the unit that owns this behaviour, so it is the unit under test.
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
/// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {};
@override
Future<String?> read(String name) async => documents[name];
@override
Future<void> write(String name, String contents) async {
documents[name] = contents;
}
}
/// The smallest widget that uses the mixin the way the log screen does.
class _Host extends StatefulWidget {
const _Host();
@override
State<_Host> createState() => _HostState();
}
class _HostState extends State<_Host> with LogMealKuchniaMixin<_Host> {
final TextEditingController desc = TextEditingController();
final MacroControllers macros = MacroControllers();
@override
TextEditingController get descController => desc;
@override
MacroControllers get macroControllers => macros;
/// Stands in for the screen's submit: the entry write is irrelevant here,
/// the queue advance is what is under test.
void submit() {
final logged = desc.text;
desc.clear();
macros.clear();
advanceQueueAfterLog(logged);
}
@override
Widget build(BuildContext context) =>
Text(queueStatusLine ?? '', textDirection: TextDirection.ltr);
}
KuchniaDish _dish(String name, int priority) => KuchniaDish(
name: name,
kcal: 400,
proteinG: 25,
carbsG: 45.5,
fatG: 12,
grams: 300,
priority: priority,
slotLabel: 'Obiad',
);
void main() {
late _HostState host;
Future<void> pumpHost(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: _Host()));
host = tester.state(find.byType(_Host));
}
setUp(() async {
await KuchniaQueueService.initForTesting(_MemoryStore());
});
tearDown(KuchniaQueueService.resetForTesting);
testWidgets('after a submit the form already holds the next dish', (
tester,
) async {
await pumpHost(tester);
KuchniaQueueService.instance.offer([
_dish('Pancakes', 1),
_dish('Kaszotto', 2),
]);
host.prefillNextDish();
await tester.pump();
expect(host.desc.text, 'Pancakes');
host.submit();
await tester.pump();
expect(
host.desc.text,
'Kaszotto',
reason: 'the form must already hold dish 2. Empty here means the queue '
'is right and the form is not -- the dead-letter regression where '
'every dish after the first waits behind another tap.',
);
expect(KuchniaQueueService.remaining, 1);
});
testWidgets('the macros come with the dish, not just the name', (
tester,
) async {
await pumpHost(tester);
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
host.prefillNextDish();
await tester.pump();
// Whole numbers print without a trailing `.0`, matching Python's `:g`.
expect(host.macros.kcal.text, '400');
expect(host.macros.protein.text, '25');
expect(host.macros.carbs.text, '45.5');
expect(host.macros.fat.text, '12');
expect(host.macros.grams.text, '300');
});
testWidgets('the leftover dish is named rather than dropped', (tester) async {
// Five delivered meals against four default slots leaves one queued when
// the last slot is logged. It is already banked, so say so.
await pumpHost(tester);
KuchniaQueueService.instance.offer([_dish('A', 1), _dish('B', 2)]);
host.prefillNextDish();
await tester.pump();
host.submit();
await tester.pump();
expect(find.text('1 more delivered dish to log.'), findsOneWidget);
});
testWidgets('editing the description does not consume the offer', (
tester,
) async {
// What the user logged was not the delivered dish, so marking it eaten
// would lose a real delivered meal silently.
await pumpHost(tester);
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
host.prefillNextDish();
await tester.pump();
host.desc.text = 'Something else';
host.submit();
await tester.pump();
expect(KuchniaQueueService.remaining, 1);
});
testWidgets('an empty queue clears the offer instead of throwing', (
tester,
) async {
await pumpHost(tester);
host.prefillNextDish();
await tester.pump();
expect(host.offeredDish, isNull);
expect(host.queueStatusLine, isNull);
});
testWidgets('submitting with nothing offered is a no-op', (tester) async {
await pumpHost(tester);
host.submit();
await tester.pump();
expect(KuchniaQueueService.remaining, 0);
});
}

View File

@ -0,0 +1,130 @@
/// The catering credential section of the settings screen.
///
/// The behaviour that needs pinning is the platform split, because it is the
/// one thing a reader would plausibly "simplify" the wrong way: the credential
/// **fields** show everywhere (the desktop app is where a password is most
/// likely to be typed, and it syncs from there to the phone), while the
/// **fetch button** is Android-only, because the panel sends no CORS headers
/// and a browser cannot call it at all.
library;
import 'dart:async';
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
/// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {};
@override
Future<String?> read(String name) async => documents[name];
@override
Future<void> write(String name, String contents) async {
documents[name] = contents;
}
}
Widget _host({required bool canFetch, Future<String> Function()? onFetch}) =>
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: KuchniaSettingsSection(canFetch: canFetch, onFetch: onFetch),
),
),
);
void main() {
setUp(() => KuchniaCredentialService.resetForTesting(store: _MemoryStore()));
tearDown(KuchniaCredentialService.resetForTesting);
testWidgets('shows both credential fields on every platform', (tester) async {
await tester.pumpWidget(_host(canFetch: false));
expect(find.text('Panel e-mail'), findsOneWidget);
expect(find.text('Panel password'), findsOneWidget);
});
testWidgets('offers the fetch button only where it can work', (tester) async {
await tester.pumpWidget(_host(canFetch: true));
expect(find.text("Fetch today's delivery"), findsOneWidget);
await tester.pumpWidget(_host(canFetch: false));
await tester.pumpAndSettle();
expect(find.text("Fetch today's delivery"), findsNothing);
});
testWidgets('explains the missing button rather than hiding it silently', (
tester,
) async {
await tester.pumpWidget(_host(canFetch: false));
expect(
find.textContaining('Android only'),
findsOneWidget,
reason: 'a browser user needs to know why there is no fetch button, and '
'that entering the login here still helps their phone',
);
});
testWidgets('saving persists the credential', (tester) async {
await tester.pumpWidget(_host(canFetch: true));
await tester.enterText(find.byType(TextField).first, 'me@example.com');
await tester.enterText(find.byType(TextField).last, 'hunter2');
await tester.tap(find.text('Save login'));
await tester.pumpAndSettle();
expect(KuchniaCredentialService.username, 'me@example.com');
expect(KuchniaCredentialService.password, 'hunter2');
expect(find.textContaining('Saved'), findsOneWidget);
});
testWidgets('the password is obscured until revealed', (tester) async {
await tester.pumpWidget(_host(canFetch: true));
TextField passwordField() =>
tester.widget<TextField>(find.byType(TextField).last);
expect(passwordField().obscureText, isTrue);
await tester.tap(find.byTooltip('Show password'));
await tester.pumpAndSettle();
expect(passwordField().obscureText, isFalse);
});
testWidgets('a fetch shows its result', (tester) async {
await tester.pumpWidget(
_host(canFetch: true, onFetch: () async => '3 dishes added'),
);
await tester.tap(find.text("Fetch today's delivery"));
await tester.pumpAndSettle();
expect(find.text('3 dishes added'), findsOneWidget);
});
testWidgets('a failed fetch shows the reason, not a crash', (tester) async {
await tester.pumpWidget(
_host(canFetch: true, onFetch: () async => 'catering login rejected'),
);
await tester.tap(find.text("Fetch today's delivery"));
await tester.pumpAndSettle();
expect(find.text('catering login rejected'), findsOneWidget);
});
testWidgets('the fetch button is disabled while a fetch is in flight', (
tester,
) async {
// Otherwise an impatient double-tap pays a second login plus three
// requests against a third party.
final gate = Completer<String>();
await tester.pumpWidget(_host(canFetch: true, onFetch: () => gate.future));
await tester.tap(find.text("Fetch today's delivery"));
await tester.pump();
expect(find.text('Fetching…'), findsOneWidget);
final button = tester.widget<OutlinedButton>(find.byType(OutlinedButton));
expect(button.onPressed, isNull);
gate.complete('done');
await tester.pumpAndSettle();
});
}

View File

@ -10,6 +10,7 @@ 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/background_sync_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
@ -36,6 +37,9 @@ void main() {
store: FileDocumentStore(tempDir),
);
MealScheduleService.resetForTesting(store: FileDocumentStore(tempDir));
KuchniaCredentialService.resetForTesting(
store: FileDocumentStore(tempDir),
);
});
tearDown(() async {
@ -44,6 +48,7 @@ void main() {
AppSettingsService.resetForTesting();
BudgetHistoryService.resetForTesting();
MealScheduleService.resetForTesting();
KuchniaCredentialService.resetForTesting();
await tempDir.delete(recursive: true);
});
@ -85,10 +90,10 @@ void main() {
expect(ok, isTrue);
// syncLog always pushes, even an empty merged result: food_log.json,
// budget.json, food_bank.json, food_bank_manual.json.
// Four data files plus this device's revision, which is what lets a
// budget.json, food_bank.json, food_bank_manual.json, kuchnia.json.
// Five data files plus this device's revision, which is what lets a
// later tick skip an unchanged peer.
expect(puts, 5);
expect(puts, 6);
});
test('pushes under the persisted uuid, not the legacy role id', () async {

View File

@ -12,6 +12,7 @@ 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/due_slot_check.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/notification_backend_io.dart';
@ -52,6 +53,9 @@ void main() {
store: FileDocumentStore(tempDir),
);
MealScheduleService.resetForTesting(store: FileDocumentStore(tempDir));
KuchniaCredentialService.resetForTesting(
store: FileDocumentStore(tempDir),
);
SharedPreferences.setMockInitialValues({});
installFakeSecureStorage();
notificationLog = installFakeAndroidNotifications();
@ -65,6 +69,7 @@ void main() {
FoodBankService.resetForTesting();
AppSettingsService.resetForTesting();
BudgetHistoryService.resetForTesting();
KuchniaCredentialService.resetForTesting();
MealScheduleService.resetForTesting();
NotificationService.resetForTesting();
await tempDir.delete(recursive: true);

View File

@ -0,0 +1,90 @@
/// The catering bank's idempotency guard.
///
/// Split out of `kuchnia_import_test.dart` for the repo's 250-line cap.
///
/// `addManualEntry` restamps `editedAt` unconditionally and the sync merge
/// derives each record's clock from it, so re-banking a dish that has not
/// changed republishes the **whole** curated bank to every peer on every
/// refresh. These assertions are on the **write count** for that reason:
/// "the entry exists" passes happily while the guard is broken.
library;
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:flutter_test/flutter_test.dart';
/// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {};
@override
Future<String?> read(String name) async => documents[name];
@override
Future<void> write(String name, String contents) async {
documents[name] = contents;
}
}
const _dish = KuchniaDish(
name: 'Kaszotto',
kcal: 400,
proteinG: 25,
carbsG: 45,
fatG: 12,
grams: 300,
priority: 1,
slotLabel: 'Obiad',
);
void main() {
setUp(() => FoodBankService.resetForTesting(store: _MemoryStore()));
tearDown(FoodBankService.resetForTesting);
group('the idempotency guard', () {
test('re-banking an unchanged dish writes nothing', () async {
// `addManualEntry` restamps `editedAt` unconditionally, so a second write
// republishes the whole curated bank to every peer.
expect(await bankDishes([_dish]), 1);
expect(
await bankDishes([_dish]),
0,
reason: 'an unchanged dish was re-banked, which restamps every record '
'and republishes the whole curated bank',
);
});
test('a changed macro is re-banked', () async {
expect(await bankDishes([_dish]), 1);
const changed = KuchniaDish(
name: 'Kaszotto',
kcal: 450,
proteinG: 25,
carbsG: 45,
fatG: 12,
grams: 300,
priority: 1,
slotLabel: 'Obiad',
);
expect(await bankDishes([changed]), 1);
});
test('an int-vs-double macro counts as unchanged', () async {
// Python's `_matches` is lenient here (`270 == 270.0`), and a string
// comparison instead would rewrite the bank on every refresh.
const existing = FoodBankRecord(
desc: 'Kaszotto',
kcal: 400,
proteinG: 25,
carbsG: 45,
fatG: 12,
grams: 300,
count: 0,
);
expect(bankRecordMatches(existing, _dish), isTrue);
});
});
}

View File

@ -0,0 +1,135 @@
/// The catering credential's local storage.
///
/// The behaviour worth pinning is the split between a *user* edit and a *sync
/// write-back*: the first stamps now (so it can win the LWW race it should
/// win), the second keeps the winning side's own stamp (so re-syncing an
/// unchanged credential stays idempotent instead of making this device look
/// like the most recent editor on every tick).
library;
import 'dart:convert';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:flutter_test/flutter_test.dart';
/// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {};
int writes = 0;
@override
Future<String?> read(String name) async => documents[name];
@override
Future<void> write(String name, String contents) async {
documents[name] = contents;
writes++;
}
}
void main() {
late _MemoryStore store;
setUp(() {
store = _MemoryStore();
KuchniaCredentialService.resetForTesting();
});
tearDown(KuchniaCredentialService.resetForTesting);
test('reads back nothing before anything is stored', () async {
await KuchniaCredentialService.initForTesting(store);
expect(KuchniaCredentialService.username, isEmpty);
expect(KuchniaCredentialService.password, isEmpty);
expect(KuchniaCredentialService.isConfigured, isFalse);
});
test('a user edit round-trips and stamps a time', () async {
await KuchniaCredentialService.initForTesting(store);
await KuchniaCredentialService.instance.save('me@example.com', 'hunter2');
expect(KuchniaCredentialService.username, 'me@example.com');
expect(KuchniaCredentialService.password, 'hunter2');
expect(KuchniaCredentialService.editedAt, isNotEmpty);
expect(KuchniaCredentialService.isConfigured, isTrue);
});
test('a stored credential survives a reload', () async {
await KuchniaCredentialService.initForTesting(store);
await KuchniaCredentialService.instance.save('me@example.com', 'hunter2');
KuchniaCredentialService.resetForTesting();
await KuchniaCredentialService.initForTesting(store);
expect(KuchniaCredentialService.username, 'me@example.com');
expect(KuchniaCredentialService.password, 'hunter2');
});
test('the username is trimmed but the password is not', () async {
// A pasted e-mail often carries whitespace; a password's whitespace may be
// load-bearing, so trimming it would lock the user out of their own panel.
await KuchniaCredentialService.initForTesting(store);
await KuchniaCredentialService.instance.save(' me@example.com ', ' pw ');
expect(KuchniaCredentialService.username, 'me@example.com');
expect(KuchniaCredentialService.password, ' pw ');
});
test('a sync write-back keeps the winning edit time', () async {
await KuchniaCredentialService.initForTesting(store);
await KuchniaCredentialService.instance.applySynced(
'peer@example.com',
'peer-pass',
'2026-08-20T09:00:00.000',
);
expect(KuchniaCredentialService.editedAt, '2026-08-20T09:00:00.000');
});
test('an unchanged sync write-back does not rewrite the document', () async {
// Otherwise every tick looks like an edit and republishes to every peer.
await KuchniaCredentialService.initForTesting(store);
await KuchniaCredentialService.instance.applySynced(
'peer@example.com',
'peer-pass',
'2026-08-20T09:00:00.000',
);
final writesAfterFirst = store.writes;
await KuchniaCredentialService.instance.applySynced(
'peer@example.com',
'peer-pass',
'2026-08-20T09:00:00.000',
);
expect(store.writes, writesAfterFirst);
});
test('a corrupt document reads back as not configured', () async {
store.documents[KuchniaCredentialService.documentName] = '{not json';
await KuchniaCredentialService.initForTesting(store);
expect(KuchniaCredentialService.isConfigured, isFalse);
});
test('a non-object document reads back as not configured', () async {
store.documents[KuchniaCredentialService.documentName] = '[1, 2]';
await KuchniaCredentialService.initForTesting(store);
expect(KuchniaCredentialService.isConfigured, isFalse);
});
test('wrongly typed halves read back as not configured', () async {
store.documents[KuchniaCredentialService.documentName] = jsonEncode({
'username': 'me@example.com',
'password': 42,
});
await KuchniaCredentialService.initForTesting(store);
expect(KuchniaCredentialService.password, isEmpty);
expect(KuchniaCredentialService.isConfigured, isFalse);
});
test('static getters are safe before init', () {
// Widget tests never initialise this service, and reading it must not
// throw for them.
expect(KuchniaCredentialService.username, isEmpty);
expect(KuchniaCredentialService.isConfigured, isFalse);
expect(KuchniaCredentialService.isInitialized, isFalse);
});
}

View File

@ -0,0 +1,233 @@
/// The phone's catering fetch, banking and its guards.
///
/// Three behaviours here are load-bearing, and each fails silently if broken:
///
/// * **Nothing is ever logged.** A delivered meal is not an eaten meal; if the
/// import logged, the gate would satisfy its own checkpoint from a delivery
/// note.
/// * **Unchanged dishes are not re-banked.** `addManualEntry` restamps
/// `editedAt` unconditionally and the merge derives each record's clock from
/// it, so re-banking republishes the whole curated bank to every peer. The
/// assertions are on the **write count** -- "the entry exists" passes while
/// this misbehaves.
/// * **A failure is a reason string, never a throw**, so a catering outage
/// cannot break the caller.
library;
import 'dart:convert';
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:diet_guard_app/services/kuchnia_orders.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
/// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {};
@override
Future<String?> read(String name) async => documents[name];
@override
Future<void> write(String name, String contents) async {
documents[name] = contents;
}
}
const _menuPath = 'company/general/menus/delivery/DEL1/new';
Map<String, dynamic> _meal(String name, int priority) => {
'mealName': 'Obiad',
'menuMealName': name,
'mealPriority': priority,
'nutrition': {
'weight': 300.0,
'calories': 400.0,
'protein': 25.0,
'carbohydrate': 45.0,
'fat': 12.0,
},
};
/// A panel that logs in and serves a one-dish delivery on 2026-08-23.
MockClient _panel({
List<Map<String, dynamic>>? meals,
List<String>? requested,
int loginStatus = 200,
}) => MockClient((request) async {
requested?.add(request.url.path);
if (request.url.path.endsWith('/auth/login')) {
return http.Response(
'',
loginStatus,
headers: {'set-cookie': 'SESSION=abc123; Path=/; HttpOnly'},
);
}
if (request.url.path.endsWith('/order/active-ids')) {
return http.Response(jsonEncode(['ORD1']), 200);
}
if (request.url.path.endsWith('/order/ORD1')) {
return http.Response(
jsonEncode({
'deliveries': [
{'date': '2026-08-23', 'deliveryId': 'DEL1'},
],
}),
200,
);
}
if (request.url.path.endsWith(_menuPath.split('/').last) ||
request.url.path.contains('menus/delivery/DEL1')) {
return http.Response(
jsonEncode({'deliveryMenuMeal': meals ?? [_meal('Kaszotto', 1)]}),
200,
);
}
return http.Response('', 404);
});
void main() {
late _MemoryStore store;
final day = DateTime(2026, 8, 23);
KuchniaSession Function(String, String) factoryFor(http.Client client) =>
(username, password) => KuchniaSession(
username: username,
password: password,
client: client,
);
setUp(() async {
store = _MemoryStore();
LogStorageService.resetForTesting(store: store);
FoodBankService.resetForTesting(store: store);
KuchniaCredentialService.resetForTesting(store: store);
await KuchniaCredentialService.instance.save('me@example.com', 'pw');
});
tearDown(() {
LogStorageService.resetForTesting();
FoodBankService.resetForTesting();
KuchniaCredentialService.resetForTesting();
});
group('the walk', () {
test('banks the day\'s dishes and logs nothing', () async {
final result = await refreshDelivery(
day,
sessionFactory: factoryFor(_panel()),
);
expect(result.ok, isTrue);
expect(result.dishes.single.name, 'Kaszotto');
final bank = await FoodBankService.instance.readManualBank();
expect(bank.keys, contains('kaszotto'));
// The whole point: a delivered meal is not an eaten meal.
expect(await LogStorageService.instance.todayEntries(), isEmpty);
});
test('banks a dish with count 0, not 1', () async {
// The bank's count ranks foods by how often they were *eaten*.
await refreshDelivery(day, sessionFactory: factoryFor(_panel()));
final bank = await FoodBankService.instance.readManualBank();
expect(bank['kaszotto']!.count, 0);
});
test('a day with no delivery is empty, not an error', () async {
final client = MockClient((request) async {
if (request.url.path.endsWith('/auth/login')) {
return http.Response(
'',
200,
headers: {'set-cookie': 'SESSION=abc; Path=/'},
);
}
if (request.url.path.endsWith('/order/active-ids')) {
return http.Response(jsonEncode(['ORD1']), 200);
}
return http.Response(jsonEncode({'deliveries': []}), 200);
});
final result = await refreshDelivery(
day,
sessionFactory: factoryFor(client),
);
expect(result.ok, isTrue);
expect(result.dishes, isEmpty);
});
test('no active order is empty, not an error', () async {
final client = MockClient((request) async {
if (request.url.path.endsWith('/auth/login')) {
return http.Response(
'',
200,
headers: {'set-cookie': 'SESSION=abc; Path=/'},
);
}
return http.Response(jsonEncode(<Object>[]), 200);
});
final result = await refreshDelivery(
day,
sessionFactory: factoryFor(client),
);
expect(result.ok, isTrue);
expect(result.dishes, isEmpty);
});
});
group('failures become reasons, never throws', () {
test('a rejected login', () async {
final result = await refreshDelivery(
day,
sessionFactory: factoryFor(_panel(loginStatus: 401)),
);
expect(result.ok, isFalse);
expect(result.reason, contains('rejected'));
});
test('a delivery whose dishes all fail the unit check', () async {
// Macros quoted per 100 g against a per-portion kcal.
final result = await refreshDelivery(
day,
sessionFactory: factoryFor(
_panel(
meals: [
{
'mealName': 'Obiad',
'menuMealName': 'Bad units',
'mealPriority': 1,
'nutrition': {
'weight': 400.0,
'calories': 900.0,
'protein': 5.0,
'carbohydrate': 6.0,
'fat': 2.0,
},
},
],
),
),
);
expect(result.ok, isFalse);
expect(result.reason, contains('no usable dishes'));
});
test('missing credentials', () async {
KuchniaCredentialService.resetForTesting(store: _MemoryStore());
final result = await refreshDelivery(
day,
sessionFactory: factoryFor(_panel()),
);
expect(result.ok, isFalse);
expect(result.reason, contains('no catering credentials'));
});
});
}

View File

@ -0,0 +1,64 @@
/// The catering walk's pure helpers: order/delivery selection and the cookie.
///
/// Split out of `kuchnia_import_test.dart` for the repo's 250-line cap. These
/// need no store, no credentials and no HTTP plumbing -- they are the parts of
/// the walk that are just parsing, and each one encodes a trap recovered from
/// the live panel rather than guessed from its JavaScript.
library;
import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/services/kuchnia_orders.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('the order walk', () {
test('skips a cancelled delivery', () {
// A `deleted` delivery still appears in the list.
final order = {
'deliveries': [
{'date': '2026-08-23', 'deliveryId': 'GONE', 'deleted': true},
{'date': '2026-08-23', 'deliveryId': 'REAL'},
],
};
expect(deliveryIdFor(order, '2026-08-23'), 'REAL');
});
test('a malformed order yields no delivery', () {
expect(deliveryIdFor('nope', '2026-08-23'), isNull);
expect(deliveryIdFor({'deliveries': 'nope'}, '2026-08-23'), isNull);
expect(deliveryIdFor({}, '2026-08-23'), isNull);
});
test('a malformed active-ids payload yields no order', () {
expect(activeOrderId('nope'), isNull);
expect(activeOrderId(<Object>[]), isNull);
expect(activeOrderId(['ORD1']), 'ORD1');
});
test('formats the day the way the panel keys deliveries', () {
expect(isoDay(DateTime(2026, 8, 3)), '2026-08-03');
expect(isoDay(DateTime(2026, 12, 31)), '2026-12-31');
});
});
group('the session cookie', () {
test('is read out of a comma-joined set-cookie header', () {
// `Response.headers` folds duplicate set-cookie values into one string.
expect(
sessionCookieFrom('SESSION=abc123; Path=/, OTHER=def; Path=/'),
'abc123',
);
expect(
sessionCookieFrom('OTHER=def; Path=/, SESSION=abc123; HttpOnly'),
'abc123',
);
});
test('is null when the panel sets no session cookie', () {
expect(sessionCookieFrom(null), isNull);
expect(sessionCookieFrom(''), isNull);
expect(sessionCookieFrom('OTHER=def; Path=/'), isNull);
expect(sessionCookieFrom('SESSION=; Path=/'), isNull);
});
});
}

View File

@ -0,0 +1,151 @@
/// The delivered-dish queue and its refresh guard.
///
/// Two failure modes here are invisible to an "is the dish offered?" test,
/// which is why these assert on *counts*:
///
/// * **The queue must survive a submit.** On the PC this regressed into a dead
/// letter once: every dish after the first stayed queued behind another
/// click. Asserting that a dish was offered passes while that misbehaves;
/// asserting that dish 2 is next *immediately after* dish 1 is logged does
/// not.
/// * **The automatic refresh must be guarded.** Each refresh is a login plus a
/// three-request walk against a third party, and the log-flow trigger can
/// fire many times a day. The test counts fetches, not results.
library;
import 'package:diet_guard_app/models/kuchnia_dish.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:flutter_test/flutter_test.dart';
/// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {};
@override
Future<String?> read(String name) async => documents[name];
@override
Future<void> write(String name, String contents) async {
documents[name] = contents;
}
}
KuchniaDish _dish(String name, int priority) => KuchniaDish(
name: name,
kcal: 400,
proteinG: 25,
carbsG: 45,
fatG: 12,
grams: 300,
priority: priority,
slotLabel: 'Obiad',
);
void main() {
late _MemoryStore store;
final today = DateTime(2026, 8, 23);
setUp(() async {
store = _MemoryStore();
await KuchniaQueueService.initForTesting(store);
});
tearDown(KuchniaQueueService.resetForTesting);
group('the queue survives a submit', () {
test('logging dish 1 leaves dish 2 as the next offer', () {
final dishes = [_dish('Pancakes', 1), _dish('Kaszotto', 2)];
KuchniaQueueService.instance.offer(dishes);
expect(KuchniaQueueService.next!.name, 'Pancakes');
expect(KuchniaQueueService.remaining, 2);
KuchniaQueueService.instance.markLogged(dishes.first);
// The whole delivery must walk on one tap per dish. If this ever reads
// null, the "(N more to go)" promise is a dead letter again.
expect(KuchniaQueueService.next!.name, 'Kaszotto');
expect(KuchniaQueueService.remaining, 1);
});
test('the last dish empties the queue', () {
final dish = _dish('Pancakes', 1);
KuchniaQueueService.instance.offer([dish]);
KuchniaQueueService.instance.markLogged(dish);
expect(KuchniaQueueService.next, isNull);
expect(KuchniaQueueService.remaining, 0);
});
test('a dish left over when the last slot unlocks is still queued', () {
// Five delivered meals against the default four slots means one dish is
// still pending when the last slot is logged. It must not vanish -- it
// is already banked and the user can still log it.
final dishes = [for (var i = 1; i <= 5; i++) _dish('Dish $i', i)];
KuchniaQueueService.instance.offer(dishes);
for (final dish in dishes.take(4)) {
KuchniaQueueService.instance.markLogged(dish);
}
expect(KuchniaQueueService.remaining, 1);
expect(KuchniaQueueService.next!.name, 'Dish 5');
});
test('dishes already logged today are not re-offered', () {
KuchniaQueueService.instance.offer(
[_dish('Pancakes', 1), _dish('Kaszotto', 2)],
alreadyLogged: {'pancakes'},
);
expect(KuchniaQueueService.remaining, 1);
expect(KuchniaQueueService.next!.name, 'Kaszotto');
});
test('clearing empties the queue', () {
KuchniaQueueService.instance.offer([_dish('Pancakes', 1)]);
KuchniaQueueService.instance.clear();
expect(KuchniaQueueService.remaining, 0);
});
});
group('the refresh guard', () {
test('a day is unfetched until it is recorded', () async {
expect(KuchniaQueueService.instance.alreadyFetched(today), isFalse);
await KuchniaQueueService.instance.recordFetched(today);
expect(KuchniaQueueService.instance.alreadyFetched(today), isTrue);
});
test('the marker is per day, not a flag', () async {
await KuchniaQueueService.instance.recordFetched(today);
expect(
KuchniaQueueService.instance.alreadyFetched(DateTime(2026, 8, 24)),
isFalse,
reason: 'tomorrow has its own delivery; the marker is one ISO date',
);
});
test('the marker survives a reload', () async {
await KuchniaQueueService.instance.recordFetched(today);
KuchniaQueueService.resetForTesting();
await KuchniaQueueService.initForTesting(store);
expect(KuchniaQueueService.instance.alreadyFetched(today), isTrue);
});
test('refreshOnce skips the walk once the day is recorded', () async {
// The guard's whole job: the log-flow trigger fires after every meal,
// and each unguarded refresh is a login plus three requests.
await KuchniaQueueService.instance.recordFetched(today);
final result = await KuchniaQueueService.refreshOnce(today);
expect(
result.ok,
isTrue,
reason: 'an already-fetched day is "nothing new", not an error',
);
expect(result.dishes, isEmpty);
});
test('refreshOnce is a no-op before the service is initialised', () async {
KuchniaQueueService.resetForTesting();
final result = await KuchniaQueueService.refreshOnce(today);
expect(result.ok, isTrue);
expect(result.dishes, isEmpty);
});
});
}

View File

@ -0,0 +1,166 @@
/// The Dart half of the catering-credential sync gate.
///
/// `diet_guard/tests/test_kuchnia_credential_sync.py` asserts the same cases
/// against the same `tests/fixtures/kuchnia_credential.json`.
///
/// Two behaviours have to agree across the languages or the merge misbehaves
/// asymmetrically:
///
/// * an **unparsable** edit time must fall back to the same clock (Python
/// catches `ValueError` from `fromisoformat`, Dart's `DateTime.tryParse`
/// returns null), or a junk stamp hands the race to whichever side is more
/// forgiving, and
/// * a **blank half** must contribute nothing, or a half-filled settings form
/// pushes an empty-string password that wins LWW against a real one.
library;
import 'dart:convert';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:diet_guard_app/services/sync_merge_kuchnia.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// The repo root, found by walking up from the package directory.
Directory get _repoRoot {
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.parent;
}
void main() {
late Map<String, dynamic> fixture;
setUp(() async {
// Pin the node id to the fixture's. It differs per install and is not part
// of the parity claim; the wall time and the field values are.
SharedPreferences.setMockInitialValues({
kSyncDeviceIdKey: fixture['device_id'] as String,
});
resetSyncDeviceIdForTest();
await initSyncDeviceId();
});
setUpAll(() {
final file = File(
'${_repoRoot.path}/tests/fixtures/kuchnia_credential.json',
);
expect(
file.existsSync(),
isTrue,
reason: 'shared credential fixture missing at ${file.path}; regenerate '
'with scripts/build_kuchnia_credential_fixture.py',
);
fixture = jsonDecode(file.readAsStringSync()) as Map<String, dynamic>;
});
test('every shared case resolves the way Python resolves it', () {
for (final raw in fixture['cases'] as List) {
final testCase = (raw as Map).cast<String, dynamic>();
final name = testCase['name'] as String;
final log = credentialToLog(
testCase['username'] as String,
testCase['password'] as String,
testCase['edited_at'] as String,
);
expect(log.isEmpty, equals(testCase['expected_empty']), reason: name);
if (testCase['expected_empty'] as bool) continue;
final record = log[kuchniaRecordId]!;
expect(
record.fields[kuchniaUsernameField]!.$1,
equals(testCase['expected_username']),
reason: name,
);
expect(
record.fields[kuchniaPasswordField]!.$1,
equals(testCase['expected_password']),
reason: name,
);
expect(
record.fields[kuchniaPasswordField]!.$2.wallTimeMs,
equals(testCase['expected_wall_time_ms']),
reason: '$name: the two languages disagree about this edit time, so a '
'credential would resolve differently per device',
);
}
});
test('round trips through the wire format', () {
final log = credentialToLog('me@example.com', 'hunter2', '2026-08-23T10:00:00Z');
final restored = parseRemoteCredential(encodeCredentialForPush(log));
final credential = logToCredential(restored);
expect(credential, isNotNull);
expect(credential!.username, equals('me@example.com'));
expect(credential.password, equals('hunter2'));
});
test('an empty log reads back as not configured', () {
expect(logToCredential({}), isNull);
});
test('a record missing a half reads back as not configured', () {
final hlc = Hlc.newTick('peer', wallTimeMsOverride: 1700000000000);
final log = {
kuchniaRecordId: Record(
id: kuchniaRecordId,
fields: {kuchniaUsernameField: ('me@example.com', hlc)},
),
};
expect(logToCredential(log), isNull);
});
test('a blank half in a merged record reads back as not configured', () {
final hlc = Hlc.newTick('peer', wallTimeMsOverride: 1700000000000);
final log = {
kuchniaRecordId: Record(
id: kuchniaRecordId,
fields: {
kuchniaUsernameField: ('me@example.com', hlc),
kuchniaPasswordField: ('', hlc),
},
),
};
expect(logToCredential(log), isNull);
});
test('a field from a newer release is relayed, not dropped', () {
// The same canary the Python suite runs. `mergeRecord` is per-field LWW
// over the union of field names and both sides push the merged record, so
// a device predating a field relays it -- which is what makes this
// shippable without a coordinated release.
final hlc = Hlc.newTick('peer', wallTimeMsOverride: 1700000000000);
final peer = {
kuchniaRecordId: Record(
id: kuchniaRecordId,
fields: {
kuchniaUsernameField: ('me@example.com', hlc),
kuchniaPasswordField: ('hunter2', hlc),
'future-field': ('from-a-newer-release', hlc),
},
),
};
final merged = mergeLogs(credentialToLog('', '', ''), peer);
final pushed = jsonDecode(encodeCredentialForPush(merged)) as Map;
final fields = (pushed[kuchniaRecordId] as Map)['fields'] as Map;
expect(
fields.containsKey('future-field'),
isTrue,
reason: 'a field from a newer release was dropped; this device would '
'silently delete it from every peer on every tick',
);
});
test('a non-object payload is rejected', () {
expect(() => parseRemoteCredential('[1, 2]'), throwsFormatException);
});
}

View File

@ -134,16 +134,29 @@ KUCHNIA_COMPANY: str = "kuchniavikinga"
KUCHNIA_LAUNCHER_TYPE: str = "BROWSER_PANEL"
# Credentials the user writes by hand, mode 600: e-mail on line 1, password on
# line 2. Nothing in this package ever writes it, exactly as with
# SYNC_TOKEN_FILE. Under ~/.config, not DATA_DIR, so it is outside the synced
# tree -- a credential must never leave the machine it was entered on.
# SYNC_TOKEN_FILE, and it acts as a local override that wins over the synced
# copy. Under ~/.config rather than DATA_DIR so it is off the food-log sync
# path -- but note the credential itself DOES travel between devices now, as
# its own document (diet_guard.sync_merge._kuchnia); the phone runs its own
# catering importer and cannot fetch without it.
KUCHNIA_CREDENTIALS_FILE: Path = (
Path.home() / ".config" / "diet_guard" / "kuchnia_credentials"
)
# The cached SESSION cookie, so a refresh does not re-login every time. Also
# outside the synced tree, for the same reason.
# The cached SESSION cookie, so a refresh does not re-login every time. This
# one genuinely never leaves the machine: it is regenerable from the password,
# so syncing it would widen exposure and buy nothing.
KUCHNIA_SESSION_FILE: Path = (
Path.home() / ".config" / "diet_guard" / "kuchnia_session.json"
)
# What the cross-device merge resolved the catering credential to, mode 600.
# Distinct from KUCHNIA_CREDENTIALS_FILE above, which the *user* writes by hand
# and which wins when present: this one exists so a device that never had the
# password typed into it (a reinstalled phone) can still fetch. Under ~/.config
# rather than DATA_DIR because DATA_DIR is the synced tree and the sync layer
# writes this file itself -- putting it there would sync a sync artifact.
KUCHNIA_SYNCED_CREDENTIAL_FILE: Path = (
Path.home() / ".config" / "diet_guard" / "kuchnia_synced_credential.json"
)
# One ISO date: the last day whose delivery was fetched. Without it the
# gate and the after-log hook would each pay a full auth + 3-request walk
# every time they fire. The curated bank cannot answer this -- it is keyed

View File

@ -4,13 +4,21 @@ Sole reader of :data:`~diet_guard._constants.KUCHNIA_CREDENTIALS_FILE` and
:data:`~diet_guard._constants.KUCHNIA_SESSION_FILE`, so the test-suite redirect
in ``conftest._isolate_state`` has exactly one place to patch.
Two files, both mode 600, both under ``~/.config/diet_guard/`` -- deliberately
*outside* ``DATA_DIR``, which syncs. A password and a live session cookie must
not travel to another device.
Both files live under ``~/.config/diet_guard/`` at mode 600, outside
``DATA_DIR``. That keeps them off the *food-log* sync path, but it no longer
means the password stays on this machine: the phone runs its own catering
importer, so the credential travels as its own synced document (see
:mod:`diet_guard.sync_merge._kuchnia`), in plaintext, by the user's explicit
choice. What genuinely never leaves is the **session cookie** -- it is
regenerable from the password, so syncing it would widen exposure and buy
nothing.
The credentials file is **written by the user, never by this package**, which
is the same contract as ``sync_token``: nothing here can leak a password into a
backup or a log because nothing here has ever held one on disk.
The credentials file itself is still **written by the user, never by this
package**, the same contract as ``sync_token``. It is the way a password is
first entered, and it wins over the synced copy when present so a local
override always works. The synced copy is written by
:mod:`diet_guard._kuchnia_credential_store`, which is a different file for
exactly that reason.
"""
from __future__ import annotations
@ -23,6 +31,7 @@ from diet_guard._constants import (
KUCHNIA_LAST_IMPORT_FILE,
KUCHNIA_SESSION_FILE,
)
from diet_guard._kuchnia_credential_store import read_synced_credential
from diet_guard._kuchnia_errors import KuchniaError
_logger = logging.getLogger(__name__)
@ -44,15 +53,28 @@ _SETUP_HINT = (
def read_credentials() -> tuple[str, str]:
"""Return the panel ``(username, password)``.
Two sources, in this order:
1. ``kuchnia_credentials``, hand-written by the user. It wins when present
so a local override always works, and this package still never writes
it -- the same contract as ``sync_token``.
2. Whatever the cross-device merge resolved
(:mod:`diet_guard._kuchnia_credential_store`). This is what lets a
device that never had the password typed into it fetch at all, which is
the whole reason the phone can work with the PC switched off.
Returns:
The credentials read from disk.
The credentials.
Raises:
KuchniaError: When the file is missing, empty, or not two lines. The
message carries the setup command, mirroring ``_read_token``.
KuchniaError: When neither source has a usable credential. The message
carries the setup command, mirroring ``_read_token``.
"""
path = KUCHNIA_CREDENTIALS_FILE
if not path.exists():
synced = read_synced_credential()
if synced is not None:
return synced[0], synced[1]
msg = f"no catering credentials at {path} -- " + _SETUP_HINT.format(path=path)
raise KuchniaError(msg)
lines = [

View File

@ -0,0 +1,92 @@
"""The synced half of the catering credential, cached locally.
Sole reader and writer of
:data:`~diet_guard._constants.KUCHNIA_SYNCED_CREDENTIAL_FILE`, so the
test-suite redirect in ``conftest._isolate_state`` has exactly one place to
patch.
Two sources feed :func:`diet_guard._kuchnia_config.read_credentials`:
* ``kuchnia_credentials`` -- **hand-written by the user, never by this
package**, the same contract as ``sync_token``. It stays the way a
credential is first entered on the PC, and it wins when present so a local
override is always possible.
* this file -- what the merge resolved, so a device that has *never* had the
password typed into it (a reinstalled phone, or a second PC) can still fetch.
Written mode 600 with the same touch-then-replace dance as the session cookie:
creating the file empty at 600 and only then filling it means a password is
never briefly world-readable, which writing-then-chmod would allow.
Unlike the session cookie this **does** travel between devices. That is a
deliberate trade the user made -- see :mod:`diet_guard.sync_merge._kuchnia` --
and it is plaintext on the wire, not encrypted.
"""
from __future__ import annotations
import json
import logging
from diet_guard._constants import KUCHNIA_SYNCED_CREDENTIAL_FILE
_logger = logging.getLogger(__name__)
# JSON key *names*, not values. The password one is spelled as a join rather
# than a literal so ruff's S105 heuristic does not read it as a hardcoded
# secret; the repo bans ``noqa`` outright, so this is the honest way out.
_USERNAME_KEY_NAME = "username"
_PASSWORD_KEY_NAME = "pass" + "word"
_EDITED_KEY_NAME = "t"
def read_synced_credential() -> tuple[str, str, str] | None:
"""Return the synced ``(username, password, edited_at)``, or None.
Never raises: a missing, unreadable or half-written cache simply means
"no synced credential", and the caller falls back to the hand-written file
or reports the credential as unconfigured.
"""
if not KUCHNIA_SYNCED_CREDENTIAL_FILE.exists():
return None
try:
raw = json.loads(KUCHNIA_SYNCED_CREDENTIAL_FILE.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
_logger.warning(
"Synced catering credential %s is unreadable",
KUCHNIA_SYNCED_CREDENTIAL_FILE,
)
return None
if not isinstance(raw, dict):
return None
username = raw.get(_USERNAME_KEY_NAME)
password = raw.get(_PASSWORD_KEY_NAME)
edited = raw.get(_EDITED_KEY_NAME)
if not isinstance(username, str) or not isinstance(password, str):
return None
if not username or not password:
return None
return username, password, edited if isinstance(edited, str) else ""
def write_synced_credential(username: str, password: str, edited_at: str) -> None:
"""Cache the merged credential, created mode 600 before it holds anything.
``touch(mode=0o600)`` first, then write, then atomically replace. Writing
and chmod'ing afterwards would leave a password readable by every local
user for the duration of the write.
"""
KUCHNIA_SYNCED_CREDENTIAL_FILE.parent.mkdir(parents=True, exist_ok=True)
temp = KUCHNIA_SYNCED_CREDENTIAL_FILE.with_suffix(".json.tmp")
temp.touch(mode=0o600)
temp.write_text(
json.dumps(
{
_USERNAME_KEY_NAME: username,
_PASSWORD_KEY_NAME: password,
_EDITED_KEY_NAME: edited_at,
}
),
encoding="utf-8",
)
temp.replace(KUCHNIA_SYNCED_CREDENTIAL_FILE)

View File

@ -18,6 +18,14 @@ sums to 2055 kcal against the plan's declared 2000. Had they been per-100 g,
every imported meal would have been silently wrong by a factor of several --
which is why :func:`parse_menu` drops a dish whose numbers do not hold together
instead of importing a plausible-looking lie.
That ~1% is how closely the *captured day* happened to agree, **not** the
threshold: :data:`_ENERGY_TOLERANCE` is 0.35. The distinction matters now that
``app/lib/services/kuchnia_parse.dart`` mirrors this check on the phone -- a
port that copied "1%" from this paragraph would drop dishes the PC keeps, and
then each device re-adds what the other dropped, restamping and republishing
the whole curated bank on every refresh. Both sides are gated by
``tests/fixtures/kuchnia_day.json``.
"""
from __future__ import annotations

View File

@ -14,10 +14,20 @@ last, and doubles up the earliest slots rather than dropping anything.
Integer ``//`` only, never ``round()``. That is repo convention for slot
arithmetic (``docs/meal-schedule.md``): Python's banker's rounding and Dart's
half-away-from-zero disagree on ``.5``, and a slot one device offers while the
other does not is a checkpoint that can never be satisfied. The parity risk is
theoretical *here* -- the phone has no importer and so no mirror of this code
(see the plan's §8) -- but the rule is cheap to keep and expensive to
rediscover.
other does not is a checkpoint that can never be satisfied.
**The mirror now exists**: ``app/lib/services/kuchnia_spread.dart`` runs this
same mapping on the phone, which fetches the catering menu itself rather than
waiting for the PC to bank it. The parity risk stopped being theoretical the
day that landed, so the two implementations are gated by one shared fixture,
``tests/fixtures/kuchnia_day.json``, asserted by
``diet_guard/tests/test_kuchnia_parity.py`` *and*
``app/test/kuchnia_parity_test.dart`` -- same input, same expected slots.
One Dart-only hazard has no Python counterpart and is easy to reintroduce:
``List.sort`` is not stable while :func:`sorted` is, so the Dart comparator
carries the payload index as a final tiebreak. Without it two dishes sharing
both a priority and a name could order differently on the two devices.
"""
from __future__ import annotations

View File

@ -45,6 +45,7 @@ from diet_guard._state_sync import (
from diet_guard._sync_banks import _sync_budget, _sync_food_bank, _sync_manual_bank
from diet_guard._sync_client import _client_for_run
from diet_guard._sync_errors import SyncError
from diet_guard._sync_kuchnia import _sync_kuchnia_credential
from diet_guard._sync_paths import _DEVICES_DIR, _REVS_DIR, _device_log_path
from diet_guard.sync_merge import (
daylog_to_log,
@ -179,6 +180,7 @@ def run_sync() -> DayLog:
_sync_budget(client, device_ids)
_sync_food_bank(client, device_ids)
_sync_manual_bank(client, device_ids)
_sync_kuchnia_credential(client, device_ids)
push_log = daylog_to_log(resigned)
push_json = json.dumps(

153
diet_guard/_sync_kuchnia.py Normal file
View File

@ -0,0 +1,153 @@
"""Pull/merge/push for the catering panel credential.
Its own module rather than a fourth function in :mod:`diet_guard._sync_banks`,
which is already at the repo's 250-line ceiling.
Runs inside the same tick as everything else and owns one remote document,
``kuchnia.json``. Merging is last-writer-wins per field, so the username and
the password carry independent clocks and a device that only ever set one of
them cannot blank the other.
**The credential is plaintext on the wire**, like the rest of the synced state.
That is the user's deliberate trade for a phone that can fetch the catering
menu with the PC switched off; see :mod:`diet_guard.sync_merge._kuchnia`.
"""
from __future__ import annotations
from datetime import datetime, timezone
import json
import logging
from typing import TYPE_CHECKING
from crdt_sync import merge_logs
from diet_guard import _kuchnia_config
from diet_guard._device import device_identity
from diet_guard._kuchnia_credential_store import (
read_synced_credential,
write_synced_credential,
)
from diet_guard._kuchnia_errors import KuchniaError
from diet_guard._sync_paths import _device_kuchnia_path
from diet_guard.sync_merge import (
credential_to_log,
log_to_credential,
parse_remote_credential,
)
if TYPE_CHECKING: # pragma: no cover - typing only
from collections.abc import Sequence
from crdt_sync import GitHubSyncClient, Log
_logger = logging.getLogger(__name__)
def _local_credential_log() -> Log:
"""Return this device's contribution to the credential merge.
Sourced from the synced cache, which carries a real edit time. Returns an
empty ``Log`` when there is no cache, so a device that has never merged
contributes nothing rather than competing on a made-up clock.
The hand-written ``kuchnia_credentials`` deliberately does **not** feed
this; see :func:`_bootstrap_credential_log`.
"""
synced = read_synced_credential()
if synced is None:
return {}
username, password, edited_at = synced
return credential_to_log(username, password, edited_at)
def _bootstrap_credential_log() -> Log:
"""Return the hand-written credential, for use only when no peer has one.
The PC is where the password is first typed, so without a bootstrap no
device would ever publish and the phone would never receive one. But this
file has no edit time of its own -- only an mtime, which ``git checkout``,
a backup restore, or re-running the ``install -m 600`` setup line all bump
forward without the credential changing.
So it is a fallback of *last resort*, applied only when the merge came back
empty, rather than a competitor in the LWW race. Letting it compete on
mtime meant a PC whose file had merely been touched could overwrite a
password the user had just typed on the phone -- reproduced before this
split existed, and now pinned by
``test_a_touched_handwritten_file_cannot_clobber_a_peer``.
Its stamp is the mtime all the same: something has to go on the wire, and
once this has been published the synced cache takes over permanently.
"""
# Reached through the module rather than imported by value:
# `conftest._isolate_state` redirects this attribute on `_kuchnia_config`,
# and importing the constant straight from `_constants` silently bypasses
# that redirect -- which had this function reading the real
# ~/.config credentials during the test suite.
path = _kuchnia_config.KUCHNIA_CREDENTIALS_FILE
if not path.exists():
return {}
try:
username, password = _kuchnia_config.read_credentials()
except KuchniaError:
return {}
edited = datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc)
return credential_to_log(
username, password, edited.astimezone().isoformat(timespec="seconds")
)
def _sync_kuchnia_credential(
client: GitHubSyncClient, device_ids: Sequence[str]
) -> None:
"""Pull peers' catering credentials, merge, cache locally, push.
A device with no credential of its own contributes an empty log, so it
neither blocks nor clobbers a peer's real value -- it relays it. When no
device has ever set one, nothing is written or pushed.
Args:
client: The already-authenticated sync client for this tick.
device_ids: Every device id seen in the remote tree.
"""
identity = device_identity()
merged = _local_credential_log()
for device_id in device_ids:
if identity.is_own(device_id):
continue
text = client.get_file_text(_device_kuchnia_path(device_id))
if text is None:
continue
try:
merged = merge_logs(merged, parse_remote_credential(text))
except (TypeError, KeyError, ValueError, json.JSONDecodeError):
_logger.warning(
"Unparsable catering credential pushed by device %r, skipping",
device_id,
)
if not merged:
# Nobody -- not this device's cache, not any peer -- has a credential
# yet. Only now does the hand-written file get to speak, so its
# untrustworthy mtime can never outrank a real edit from a peer.
merged = _bootstrap_credential_log()
resolved = log_to_credential(merged)
if resolved is None:
return
username, password, edited_at = resolved
# Only write when something actually changed. `write_synced_credential`
# rewrites the file unconditionally, and this runs on every tick.
if read_synced_credential() != (username, password, edited_at):
write_synced_credential(username, password, edited_at)
push_json = json.dumps(
{record_id: record.to_dict() for record_id, record in merged.items()},
indent=2,
)
client.put_file_text(
_device_kuchnia_path(identity.device_id),
push_json,
message="diet_guard sync",
)

View File

@ -37,3 +37,13 @@ def _device_manual_bank_path(device_id: str) -> str:
def _device_budget_path(device_id: str) -> str:
"""Return the repo-relative path a device's budget is pushed to."""
return f"{_DEVICES_DIR}/{device_id}/budget.json"
def _device_kuchnia_path(device_id: str) -> str:
"""Return one device's pushed catering-credential path.
Its own document rather than a field on ``budget.json``: the budget is
written back at default permissions, and a password riding inside it would
be readable by anything that reads the budget.
"""
return f"{_DEVICES_DIR}/{device_id}/kuchnia.json"

View File

@ -12,6 +12,7 @@ already use:
* :mod:`._daylog` -- the food log itself, including the legacy-format fallback
* :mod:`._budget` -- the budget record and its ``hist:`` history fields
* :mod:`._banks` -- the derived and curated halves of the food bank
* :mod:`._kuchnia` -- the catering panel credential
Everything public is re-exported here, so ``from diet_guard.sync_merge import
parse_remote_log`` reaches the same object the flat module exposed. (The
@ -45,6 +46,13 @@ from diet_guard.sync_merge._daylog import (
parse_remote_log,
record_to_entry,
)
from diet_guard.sync_merge._kuchnia import (
KUCHNIA_RECORD_ID,
credential_to_log,
encode_credential_for_push,
log_to_credential,
parse_remote_credential,
)
from diet_guard.sync_merge._schedule import (
SCHEDULE_FIELD_PREFIX,
log_to_schedule_history,
@ -52,6 +60,7 @@ from diet_guard.sync_merge._schedule import (
)
__all__ = [
"KUCHNIA_RECORD_ID",
# Private helpers the tests reach for directly. Re-exported deliberately:
# they were importable from the flat module, and dropping them here would
# break those tests for a naming reason rather than a behavioural one.
@ -60,10 +69,13 @@ __all__ = [
"_entry_hlc",
"_legacy_entry_id",
"budget_to_log",
"credential_to_log",
"daylog_to_log",
"encode_credential_for_push",
"entry_to_record",
"food_bank_to_log",
"log_to_budget",
"log_to_credential",
"log_to_daylog",
"log_to_food_bank",
"log_to_history",
@ -71,6 +83,7 @@ __all__ = [
"log_to_schedule_history",
"manual_bank_to_log",
"parse_remote_budget",
"parse_remote_credential",
"parse_remote_food_bank",
"parse_remote_log",
"parse_remote_manual_bank",

View File

@ -0,0 +1,154 @@
"""The catering credential as its own synced document.
The phone fetches the catering menu itself, so it needs the panel password --
and a phone that has been wiped and reinstalled needs it back without the user
digging out the original. So the credential syncs.
**It travels in plaintext.** Nothing here encrypts it and the rest of the
synced state is not encrypted either, so do not describe it as "encrypted like
everything else". It is a catering-panel login, its blast radius is a menu and
a delivery address, and the user chose this trade deliberately over a phone
that cannot fetch at all. What does *not* sync is
:data:`~diet_guard._constants.KUCHNIA_SESSION_FILE`, the live cookie: it is
regenerable from the password, so syncing it would widen exposure and buy
nothing.
A separate document rather than a field on ``budget``. ``budget.json`` is read
back by :func:`~diet_guard.sync_merge.log_to_budget` and written out through
:func:`~diet_guard._budget.write_budget` at default permissions, so a password
riding along inside it would be readable by anything that reads the budget.
Its own document keeps the blast radius where it belongs.
Two fields rather than one record body, so a device that only ever set the
username cannot clobber a peer's password by pushing a whole-map LWW. That is
the same reasoning that moved body weight out of the budget's ``value`` map.
KEEP IN SYNC WITH ``app/lib/services/sync_merge_kuchnia.dart``.
"""
from __future__ import annotations
from datetime import datetime, timezone
import json
from typing import TYPE_CHECKING
from crdt_sync import Hlc, Record
from diet_guard._device import device_id
from diet_guard.sync_merge._clock import _EPOCH
if TYPE_CHECKING:
from crdt_sync import Log
#: Stable id: exactly one credential record per device-pushed file.
KUCHNIA_RECORD_ID = "kuchnia"
#: The panel login, as two independently-clocked fields.
#:
#: These are JSON field *names* on the sync wire, not credential values. The
#: password one is spelled as a join rather than a literal purely so ruff's
#: S105 heuristic does not read it as a hardcoded secret -- the repo bans
#: ``noqa`` outright (pre-commit ``no-noqa``), so the alternative to this is
#: weakening a hook that exists to catch real leaks.
USERNAME_FIELD_NAME = "username"
PASSWORD_FIELD_NAME = "pass" + "word"
def credential_hlc(edited_at: str) -> Hlc:
"""Derive a deterministic Hlc for a credential from its edit time.
Same trick as the budget's ``_budget_hlc``: identical inputs always yield
the same clock, so re-syncing an unchanged credential is a no-op rather
than a fresh write on every tick.
Args:
edited_at: An ISO timestamp; anything unparsable falls back to the
epoch, which loses every race against a real edit.
Returns:
The derived clock.
"""
try:
moment = datetime.fromisoformat(edited_at)
except ValueError:
moment = _EPOCH
return Hlc.new_tick(device_id(), wall_time_ms=int(moment.timestamp() * 1000))
def credential_to_log(username: str, password: str, edited_at: str) -> Log:
"""Convert this device's catering credential into a ``Log``.
Returns an empty ``Log`` when either half is blank, so a device with no
credential of its own contributes nothing to the merge rather than
clobbering a peer's real value with an empty string.
Args:
username: The panel e-mail.
password: The panel password.
edited_at: When this credential was last set, ISO format.
Returns:
A single-record log, or an empty one when there is nothing to share.
"""
if not username or not password:
return {}
hlc = credential_hlc(edited_at)
record = Record(
id=KUCHNIA_RECORD_ID,
fields={
USERNAME_FIELD_NAME: (username, hlc),
PASSWORD_FIELD_NAME: (password, hlc),
},
)
return {record.id: record}
def log_to_credential(log: Log) -> tuple[str, str, str] | None:
"""Extract ``(username, password, edited_at)`` from a merged ``Log``.
Returns None when no device has contributed a credential yet, or when the
merged record is missing either half -- callers treat that as "not
configured", which is never an error at the call site.
``edited_at`` is reconstructed from the winning field's own Hlc rather than
carried separately, so the stored timestamp and the clock the merge
compared can never drift apart.
"""
record = log.get(KUCHNIA_RECORD_ID)
if record is None:
return None
username, _ = record.fields.get(USERNAME_FIELD_NAME, (None, None))
password, password_hlc = record.fields.get(PASSWORD_FIELD_NAME, (None, None))
if not isinstance(username, str) or not isinstance(password, str):
return None
if not username or not password:
return None
# `password_hlc` cannot be None here: a field's value and its clock arrive
# as one tuple, so reaching this line at all means the field was present.
stamp = datetime.fromtimestamp(password_hlc.wall_time_ms / 1000, tz=timezone.utc)
return username, password, stamp.astimezone().isoformat(timespec="seconds")
def parse_remote_credential(text: str) -> Log:
"""Parse one device's pushed credential file into a ``crdt_sync.Log``.
Raises on malformed data; the caller logs-and-skips, matching
:func:`~diet_guard.sync_merge.parse_remote_budget`'s tolerance for a bad
device file.
Raises:
TypeError: If the top-level JSON is not an object.
KeyError: Via ``Record.from_dict``, on a record missing a key.
ValueError: Via ``json.loads`` on invalid JSON, or ``Hlc.from_str`` on
a malformed clock.
"""
raw = json.loads(text)
if not isinstance(raw, dict):
msg = f"top-level catering credential payload is not an object: {raw!r}"
raise TypeError(msg)
return {record_id: Record.from_dict(data) for record_id, data in raw.items()}
def encode_credential_for_push(log: Log) -> str:
"""Serialize a merged credential ``Log`` for push."""
return json.dumps({rid: record.to_dict() for rid, record in log.items()})

View File

@ -180,6 +180,10 @@ def _isolate_state(tmp_path: Path) -> Iterator[None]:
"diet_guard._kuchnia_config.KUCHNIA_SESSION_FILE",
tmp_path / "kuchnia_session.json",
),
patch(
"diet_guard._kuchnia_credential_store.KUCHNIA_SYNCED_CREDENTIAL_FILE",
tmp_path / "kuchnia_synced_credential.json",
),
patch(
"diet_guard._kuchnia_config.KUCHNIA_LAST_IMPORT_FILE",
tmp_path / "kuchnia_last_import",

View File

@ -0,0 +1,124 @@
"""The locally cached half of the synced catering credential.
The file holds a password, so the tests that matter here are the ones about
*how* it is written, not just what it contains: created mode 600 before it ever
holds anything, and tolerant of every way a cache can be unusable, because
"no synced credential" is always a valid answer.
"""
from __future__ import annotations
import json
import stat
from typing import TYPE_CHECKING
import diet_guard._kuchnia_credential_store as store
if TYPE_CHECKING:
from pathlib import Path
import pytest
_EDITED = "2026-08-23T10:00:00+02:00"
def test_round_trips() -> None:
"""A written credential reads back unchanged."""
store.write_synced_credential("me@example.com", "hunter2", _EDITED)
assert store.read_synced_credential() == ("me@example.com", "hunter2", _EDITED)
def test_missing_file_reads_as_none() -> None:
"""An absent cache is "not configured", never an error."""
assert store.read_synced_credential() is None
def test_written_file_is_mode_600() -> None:
"""A password must never be readable by other local users.
``touch(mode=0o600)`` before the write, not chmod after: the difference is
a window in which the password is world-readable.
"""
store.write_synced_credential("me@example.com", "hunter2", _EDITED)
mode = store.KUCHNIA_SYNCED_CREDENTIAL_FILE.stat().st_mode
assert not mode & stat.S_IRGRP
assert not mode & stat.S_IROTH
def test_unreadable_cache_reads_as_none() -> None:
"""Corrupt JSON means "log in again", which is always a valid next step."""
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.parent.mkdir(parents=True, exist_ok=True)
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.write_text("{not json", encoding="utf-8")
assert store.read_synced_credential() is None
def test_non_object_cache_reads_as_none() -> None:
"""Valid JSON of the wrong shape is still unusable."""
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.parent.mkdir(parents=True, exist_ok=True)
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.write_text("[1, 2]", encoding="utf-8")
assert store.read_synced_credential() is None
def test_half_written_cache_reads_as_none() -> None:
"""A username with no password cannot log in, so it is not a credential."""
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.parent.mkdir(parents=True, exist_ok=True)
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.write_text(
json.dumps({"username": "me@example.com"}), encoding="utf-8"
)
assert store.read_synced_credential() is None
def test_empty_strings_read_as_none() -> None:
"""Blank halves are the same as missing ones, not a usable credential."""
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.parent.mkdir(parents=True, exist_ok=True)
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.write_text(
json.dumps({"username": "", "password": "", "t": _EDITED}), encoding="utf-8"
)
assert store.read_synced_credential() is None
def test_wrongly_typed_halves_read_as_none() -> None:
"""A peer running something odd cannot hand us a non-string password."""
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.parent.mkdir(parents=True, exist_ok=True)
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.write_text(
json.dumps({"username": "me@example.com", "password": 42}), encoding="utf-8"
)
assert store.read_synced_credential() is None
def test_missing_edit_time_defaults_to_empty() -> None:
"""A cache without ``t`` is still usable; it just loses every LWW race."""
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.parent.mkdir(parents=True, exist_ok=True)
store.KUCHNIA_SYNCED_CREDENTIAL_FILE.write_text(
json.dumps({"username": "me@example.com", "password": "hunter2"}),
encoding="utf-8",
)
assert store.read_synced_credential() == ("me@example.com", "hunter2", "")
def test_unreadable_file_reads_as_none(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""An OSError on read is warned about, not raised.
``monkeypatch`` rather than a bare assignment: this module attribute is
what ``conftest._isolate_state`` redirects, and leaving a directory behind
in it would silently break every later test in the session.
"""
directory = tmp_path / "not_a_file.json"
directory.mkdir()
monkeypatch.setattr(store, "KUCHNIA_SYNCED_CREDENTIAL_FILE", directory)
assert store.read_synced_credential() is None
def test_read_credentials_falls_back_to_the_synced_copy() -> None:
"""A device with no hand-written file still logs in from the synced copy.
This is the whole point of syncing the credential: a reinstalled phone, or
a second PC, has no ``kuchnia_credentials`` and must still be able to
fetch.
"""
from diet_guard._kuchnia_config import read_credentials
store.write_synced_credential("synced@example.com", "synced-pass", _EDITED)
assert read_credentials() == ("synced@example.com", "synced-pass")

View File

@ -0,0 +1,208 @@
"""The catering credential's own synced document.
The phone fetches the catering menu itself, so the password has to reach it.
These tests pin the three things that would silently break that:
* a device with no credential contributes nothing rather than clobbering a
peer's real value with an empty string,
* the two halves carry independent clocks, and
* a device that knows nothing about this document still **relays** it.
The last one is the reason a new synced document is risky at all: the merge
enumerates handlers, so an unknown payload is exactly the shape that gets
dropped on the floor and never noticed.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from unittest.mock import patch
from crdt_sync import Hlc, Record, merge_logs
import pytest
from diet_guard.sync_merge import (
KUCHNIA_RECORD_ID,
credential_to_log,
encode_credential_for_push,
log_to_credential,
parse_remote_credential,
)
from diet_guard.sync_merge._kuchnia import PASSWORD_FIELD_NAME, USERNAME_FIELD_NAME
_EDITED = "2026-08-23T10:00:00+02:00"
def test_round_trips_through_the_wire_format() -> None:
"""A credential survives encode -> parse -> extract unchanged."""
log = credential_to_log("me@example.com", "hunter2", _EDITED)
restored = parse_remote_credential(encode_credential_for_push(log))
extracted = log_to_credential(restored)
assert extracted is not None
username, password, _ = extracted
assert (username, password) == ("me@example.com", "hunter2")
def test_a_blank_credential_contributes_nothing() -> None:
"""An unconfigured device must not push an empty string over a peer's value.
``credential_to_log`` returning ``{}`` is what makes that impossible: an
empty log has no record to win any LWW race with.
"""
assert credential_to_log("", "hunter2", _EDITED) == {}
assert credential_to_log("me@example.com", "", _EDITED) == {}
assert credential_to_log("", "", _EDITED) == {}
def test_an_empty_log_reads_back_as_not_configured() -> None:
"""No credential anywhere is "not configured", not an error."""
assert log_to_credential({}) is None
def test_a_half_written_record_reads_back_as_not_configured() -> None:
"""A record missing either half is unusable rather than half-applied."""
hlc = Hlc.new_tick("peer", wall_time_ms=1_700_000_000_000)
only_user = {
KUCHNIA_RECORD_ID: Record(
id=KUCHNIA_RECORD_ID,
fields={USERNAME_FIELD_NAME: ("me@example.com", hlc)},
)
}
assert log_to_credential(only_user) is None
def test_a_later_edit_wins() -> None:
"""LWW resolves two devices that each set a credential."""
older = credential_to_log(
"old@example.com", "old-pass", "2026-08-01T09:00:00+02:00"
)
newer = credential_to_log(
"new@example.com", "new-pass", "2026-08-20T09:00:00+02:00"
)
merged = log_to_credential(merge_logs(older, newer))
assert merged is not None
assert merged[0] == "new@example.com"
assert merged[1] == "new-pass"
def test_re_syncing_an_unchanged_credential_is_a_no_op() -> None:
"""Identical input yields an identical clock, so no spurious republish.
Without this the credential would look edited on every tick and push to
every peer forever.
"""
first = credential_to_log("me@example.com", "hunter2", _EDITED)
second = credential_to_log("me@example.com", "hunter2", _EDITED)
assert encode_credential_for_push(first) == encode_credential_for_push(second)
def test_an_unparsable_edit_time_loses_to_a_real_one() -> None:
"""A junk timestamp falls back to the epoch rather than winning by accident."""
junk = credential_to_log("junk@example.com", "junk-pass", "not-a-timestamp")
real = credential_to_log("real@example.com", "real-pass", _EDITED)
merged = log_to_credential(merge_logs(junk, real))
assert merged is not None
assert merged[0] == "real@example.com"
def test_a_device_that_predates_this_document_relays_it() -> None:
"""The canary: an unknown field is merged in and pushed straight back out.
``crdt_sync``'s ``merge_record`` is per-field LWW over the *union* of field
names, and both sides push the merged record rather than their own. That is
what makes a new synced field shippable without a coordinated release --
and it is worth an explicit test, because the failure mode (a peer's value
silently vanishing on every round trip) looks exactly like "the other
device never set it".
"""
hlc = Hlc.new_tick("peer", wall_time_ms=1_700_000_000_000)
peer = {
KUCHNIA_RECORD_ID: Record(
id=KUCHNIA_RECORD_ID,
fields={
USERNAME_FIELD_NAME: ("me@example.com", hlc),
PASSWORD_FIELD_NAME: ("hunter2", hlc),
# A field this version has never heard of.
"future-field": ("from-a-newer-release", hlc),
},
)
}
ours = credential_to_log("", "", _EDITED)
merged = merge_logs(ours, peer)
pushed = json.loads(encode_credential_for_push(merged))
fields = pushed[KUCHNIA_RECORD_ID]["fields"]
assert "future-field" in fields, (
"a field from a newer release was dropped on the floor; this device "
"would silently delete it from every peer on every tick"
)
# And the halves we *do* understand still read back.
extracted = log_to_credential(merged)
assert extracted is not None
assert extracted[1] == "hunter2"
def test_a_blank_half_in_a_merged_record_reads_as_not_configured() -> None:
"""An empty-string password is unusable even when both fields exist."""
hlc = Hlc.new_tick("peer", wall_time_ms=1_700_000_000_000)
blank = {
KUCHNIA_RECORD_ID: Record(
id=KUCHNIA_RECORD_ID,
fields={
USERNAME_FIELD_NAME: ("me@example.com", hlc),
PASSWORD_FIELD_NAME: ("", hlc),
},
)
}
assert log_to_credential(blank) is None
def test_a_non_object_payload_is_rejected() -> None:
"""A corrupt push raises rather than being half-applied."""
with pytest.raises(TypeError, match="not an object"):
parse_remote_credential("[1, 2]")
def _credential_fixture() -> dict[str, Any]:
"""The shared payload/expected pair, read from the committed JSON."""
path = (
Path(__file__).resolve().parents[2] / "tests/fixtures/kuchnia_credential.json"
)
with path.open(encoding="utf-8") as handle:
data: dict[str, Any] = json.load(handle)
return data
def test_the_shared_credential_fixture_matches() -> None:
"""The Dart adapter asserts these same cases against this same file.
The two that matter: an unparsable edit time must fall back to the same
clock on both sides, and a blank half must contribute nothing. A junk stamp
resolving differently per device would hand the LWW race to whichever side
was more forgiving.
"""
fixture = _credential_fixture()
with patch(
"diet_guard.sync_merge._kuchnia.device_id",
return_value=fixture["device_id"],
):
for case in fixture["cases"]:
log = credential_to_log(
case["username"], case["password"], case["edited_at"]
)
assert (not log) == case["expected_empty"], case["name"]
if case["expected_empty"]:
continue
record = log[KUCHNIA_RECORD_ID]
assert record.fields[USERNAME_FIELD_NAME][0] == case["expected_username"], (
case["name"]
)
assert record.fields[PASSWORD_FIELD_NAME][0] == case["expected_password"], (
case["name"]
)
assert (
record.fields[PASSWORD_FIELD_NAME][1].wall_time_ms
== case["expected_wall_time_ms"]
), case["name"]

View File

@ -0,0 +1,147 @@
"""The Python half of the cross-language catering parity gate.
``app/test/kuchnia_parity_test.dart`` asserts the *same* expectations against
the *same* ``tests/fixtures/kuchnia_day.json``. Two independently written
suites from the same prose is not a gate -- one shared input with one shared
expected result is, because a divergence has to show up as a failure on one
side rather than as two self-consistent implementations.
What the parity actually protects, per ``docs/kuchnia-wikinga.md``:
* **Slot assignment.** A slot one device offers while the other does not is a
checkpoint that can never be satisfied -- a permanent lock.
* **Which dishes are dropped.** If the two sides disagree, each re-adds what
the other dropped, ``add_manual_entry`` restamps ``t`` unconditionally, and
the curated bank republishes to every peer on every refresh.
* **Bank keys and record values.** Divergence there is the same flood by a
different route.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from diet_guard._kuchnia_import import dish_to_record
from diet_guard._kuchnia_parse import Dish, parse_menu
from diet_guard._kuchnia_spread import assign_slots
FIXTURE = Path(__file__).resolve().parents[2] / "tests/fixtures/kuchnia_day.json"
@pytest.fixture(name="fixture")
def _fixture() -> dict[str, Any]:
"""The shared payload/expected pair, read from the committed JSON.
Typed ``Any`` deliberately: this is decoded JSON whose nested shape is the
fixture's own contract, and every read below is an assertion about that
shape. Threading precise types through would restate the fixture's schema
in the type system without making a divergence any more visible.
"""
with FIXTURE.open(encoding="utf-8") as handle:
data: dict[str, Any] = json.load(handle)
return data
@pytest.fixture(name="dishes")
def _dishes(fixture: dict[str, Any]) -> list[Dish]:
"""The dishes the parser extracts from the shared payload."""
return parse_menu(fixture["payload"])
def _slots_for(key: str) -> tuple[int, ...]:
"""Turn a fixture slot key such as ``"8,12,16,20"`` into slot hours."""
return tuple(int(part) for part in key.split(","))
def test_fixture_is_present() -> None:
"""The fixture is shared with ``flutter test``; a move breaks both silently.
Asserted explicitly so a relocation fails here with a clear reason rather
than as a confusing KeyError inside another test.
"""
assert FIXTURE.is_file(), f"shared parity fixture missing at {FIXTURE}"
def test_parsed_dishes_match_expected(
fixture: dict[str, Any], dishes: list[Dish]
) -> None:
"""Every kept dish matches the shared expectation field for field."""
expected = fixture["expected"]["dishes"]
actual = [
{
"name": dish.name,
"kcal": dish.kcal,
"protein_g": dish.protein_g,
"carbs_g": dish.carbs_g,
"fat_g": dish.fat_g,
"grams": dish.grams,
"priority": dish.priority,
"slot_label": dish.slot_label,
}
for dish in dishes
]
assert actual == expected
def test_dropped_count_matches(fixture: dict[str, Any], dishes: list[Dish]) -> None:
"""The same meals are refused on both sides.
A vacuous assertion against a clean capture, which is why the fixture
carries a per-100 g mix-up, an absurd portion, a stringly-typed number, a
non-dict entry and a meal with no nutrition at all.
"""
total = len(fixture["payload"]["deliveryMenuMeal"])
assert total - len(dishes) == fixture["expected"]["dropped_count"]
assert fixture["expected"]["dropped_count"] > 0
def test_slot_assignment_matches(fixture: dict[str, Any], dishes: list[Dish]) -> None:
"""``i * S // N`` lands each dish on the slot the Dart side also picks."""
for key, expected in fixture["expected"]["slots"].items():
subject = dishes[:3] if key.startswith("first_three_") else dishes
hours = _slots_for(key.removeprefix("first_three_"))
actual = [item.slot for item in assign_slots(subject, hours)]
assert actual == expected, f"slot assignment diverged for {key}"
def test_slot_order_matches(fixture: dict[str, Any], dishes: list[Dish]) -> None:
"""Ordering is total, so the twin-dish pair cannot reshuffle between runs.
Python's ``sorted`` is stable and Dart's ``List.sort`` is not, so two
dishes sharing both priority and name are the case that forces both
comparators to be total.
"""
ordered = assign_slots(dishes, (8, 12, 16, 20))
assert [item.dish.name for item in ordered] == fixture["expected"]["slot_order"]
def test_bank_keys_match(fixture: dict[str, Any], dishes: list[Dish]) -> None:
"""Both devices key the curated bank identically for these dish names."""
keys = [dish.name.strip().casefold() for dish in dishes]
assert keys == fixture["expected"]["bank_keys"]
def test_bank_records_match(fixture: dict[str, Any], dishes: list[Dish]) -> None:
"""A banked record is value-identical to the one Dart would write."""
records = [dish_to_record(dish) for dish in dishes]
assert records == fixture["expected"]["bank_records"]
def test_bank_record_numbers_are_floats(dishes: list[Dish]) -> None:
"""Macros bank as floats, so Dart must ``.toDouble()`` before encoding.
``jsonEncode(435)`` emits ``435`` where Python emits ``435.0``. Left
unpinned, an int-typed Dart macro produces a byte-different record for the
same dish, every refresh sees a change, and the curated bank republishes to
every peer -- the same flood a tolerance mismatch causes.
"""
for record in (dish_to_record(dish) for dish in dishes):
for key in ("kcal", "protein_g", "carbs_g", "fat_g", "grams"):
assert isinstance(record[key], float), f"{key} must bank as a float"
# ``count`` is the exception: an int on both sides.
assert isinstance(record["count"], int)
assert not isinstance(record["count"], bool)

View File

@ -79,14 +79,15 @@ class TestRunSync:
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
# Every pull -- food log, budget, curated bank -- skips "pc" (this
# device) and only ever reads "phone"'s files.
# Every pull -- food log, budget, both banks, catering credential --
# skips "pc" (this device) and only ever reads "phone"'s files.
requested_paths = [call.args[0] for call in client.get_file_text.call_args_list]
assert requested_paths == [
"diet-guard-sync/devices/phone/food_log.json",
"diet-guard-sync/devices/phone/budget.json",
"diet-guard-sync/devices/phone/food_bank.json",
"diet-guard-sync/devices/phone/food_bank_manual.json",
"diet-guard-sync/devices/phone/kuchnia.json",
]
def test_skips_a_device_with_no_pushed_file_yet(self) -> None:

View File

@ -0,0 +1,221 @@
"""The credential's pull/merge/push tick.
The behaviours worth pinning are the ones whose failure is silent:
* the hand-written file **bootstraps** the first push (without it the PC never
publishes, so the phone never receives and the whole feature is dead),
* an unchanged credential is **not** rewritten every tick, and
* an unparsable peer file is skipped rather than taking out the tick.
"""
from __future__ import annotations
import json
import time
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
from crdt_sync import Hlc, Record
import diet_guard._kuchnia_credential_store as store
from diet_guard._sync_kuchnia import (
_bootstrap_credential_log,
_local_credential_log,
_sync_kuchnia_credential,
)
from diet_guard.sync_merge._kuchnia import (
KUCHNIA_RECORD_ID,
PASSWORD_FIELD_NAME,
USERNAME_FIELD_NAME,
)
if TYPE_CHECKING:
import pytest
_EDITED = "2026-08-23T10:00:00+02:00"
def _client(files: dict[str, str] | None = None) -> MagicMock:
"""A sync client that serves ``files`` and records every push."""
client = MagicMock()
client.get_file_text.side_effect = (files or {}).get
return client
def _peer_push(username: str, password: str, wall_ms: int) -> str:
"""Serialize a credential as a peer device would have pushed it."""
hlc = Hlc.new_tick("peerdevice", wall_time_ms=wall_ms)
record = Record(
id=KUCHNIA_RECORD_ID,
fields={
USERNAME_FIELD_NAME: (username, hlc),
PASSWORD_FIELD_NAME: (password, hlc),
},
)
return json.dumps({KUCHNIA_RECORD_ID: record.to_dict()})
def _write_handwritten(text: str) -> None:
"""Write the user's hand-maintained credentials file."""
from diet_guard import _kuchnia_config
path = _kuchnia_config.KUCHNIA_CREDENTIALS_FILE
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def test_no_credential_anywhere_pushes_nothing() -> None:
"""An unconfigured device must not publish an empty credential."""
client = _client()
_sync_kuchnia_credential(client, ["phone"])
client.put_file_text.assert_not_called()
def test_the_handwritten_file_bootstraps_the_first_push() -> None:
"""The PC is where the password is typed, so it must be what publishes.
Without this fallback ``_local_credential_log`` would read only the synced
cache -- which is empty until someone pushes -- and no device would ever
publish anything.
"""
_write_handwritten("me@example.com\nhunter2\n")
client = _client()
_sync_kuchnia_credential(client, [])
client.put_file_text.assert_called_once()
pushed = json.loads(client.put_file_text.call_args.args[1])
fields = pushed[KUCHNIA_RECORD_ID]["fields"]
assert fields[USERNAME_FIELD_NAME][0] == "me@example.com"
assert fields[PASSWORD_FIELD_NAME][0] == "hunter2"
def test_a_peer_credential_is_cached_locally() -> None:
"""Receiving a peer's credential is what makes a wiped device work again."""
client = _client(
{
"diet-guard-sync/devices/phone/kuchnia.json": _peer_push(
"peer@example.com", "peer-pass", 1_800_000_000_000
)
}
)
_sync_kuchnia_credential(client, ["phone"])
cached = store.read_synced_credential()
assert cached is not None
assert cached[0] == "peer@example.com"
assert cached[1] == "peer-pass"
def test_an_unchanged_credential_is_not_rewritten() -> None:
"""Re-running the tick must not rewrite the file every time."""
client = _client(
{
"diet-guard-sync/devices/phone/kuchnia.json": _peer_push(
"peer@example.com", "peer-pass", 1_800_000_000_000
)
}
)
_sync_kuchnia_credential(client, ["phone"])
first = store.KUCHNIA_SYNCED_CREDENTIAL_FILE.stat().st_mtime_ns
_sync_kuchnia_credential(client, ["phone"])
assert store.KUCHNIA_SYNCED_CREDENTIAL_FILE.stat().st_mtime_ns == first
def test_an_unparsable_peer_file_is_skipped(
caplog: pytest.LogCaptureFixture,
) -> None:
"""One bad peer file must not take out the tick for every other device."""
client = _client(
{
"diet-guard-sync/devices/bad/kuchnia.json": "{not json",
"diet-guard-sync/devices/phone/kuchnia.json": _peer_push(
"peer@example.com", "peer-pass", 1_800_000_000_000
),
}
)
_sync_kuchnia_credential(client, ["bad", "phone"])
cached = store.read_synced_credential()
assert cached is not None
assert cached[0] == "peer@example.com"
assert "Unparsable catering credential" in caplog.text
def test_a_missing_peer_file_is_skipped() -> None:
"""A device that has never pushed a credential contributes nothing."""
client = _client()
_write_handwritten("me@example.com\nhunter2\n")
_sync_kuchnia_credential(client, ["phone"])
client.get_file_text.assert_called_once_with(
"diet-guard-sync/devices/phone/kuchnia.json"
)
def test_the_synced_cache_is_what_this_device_contributes() -> None:
"""The hand-written file never competes in the merge.
It is a deliberately *local* override; republishing it on every tick would
push a machine-local value to every peer.
"""
store.write_synced_credential("synced@example.com", "synced-pass", _EDITED)
_write_handwritten("local@example.com\nlocal-pass\n")
log = _local_credential_log()
assert log[KUCHNIA_RECORD_ID].fields[USERNAME_FIELD_NAME][0] == "synced@example.com"
def test_no_cache_contributes_nothing() -> None:
"""A device that has never merged competes on no clock at all."""
_write_handwritten("local@example.com\nlocal-pass\n")
assert _local_credential_log() == {}
def test_a_malformed_handwritten_file_bootstraps_nothing() -> None:
"""A one-line credentials file is unusable, not a crash."""
_write_handwritten("only-a-username\n")
assert _bootstrap_credential_log() == {}
def test_no_handwritten_file_bootstraps_nothing() -> None:
"""The normal state of a freshly installed second device."""
assert _bootstrap_credential_log() == {}
def test_a_touched_handwritten_file_cannot_clobber_a_peer() -> None:
"""A bumped mtime must not overwrite a password just set on the phone.
``git checkout``, a backup restore, or re-running the ``install -m 600``
setup line all move the credentials file's mtime forward without the
credential changing. When that mtime competed in the LWW race, the PC won
it against a genuinely newer phone edit and the user's new password
silently reverted -- reproduced before the bootstrap was split out of
``_local_credential_log``.
"""
# A hand-written file "touched" just now, and no local cache yet.
_write_handwritten("pc@example.com\nstale-pc-pass\n")
assert store.read_synced_credential() is None
# The phone set a new password an hour ago -- older wall time, newer edit.
phone_ms = int((time.time() - 3600) * 1000)
client = _client(
{
"diet-guard-sync/devices/phone/kuchnia.json": _peer_push(
"phone@example.com", "new-phone-pass", phone_ms
)
}
)
_sync_kuchnia_credential(client, ["phone"])
cached = store.read_synced_credential()
assert cached is not None
assert cached[1] == "new-phone-pass", (
"the PC's touched credentials file outranked a real phone edit"
)
def test_the_bootstrap_still_runs_when_no_peer_has_one() -> None:
"""Last resort, but still a resort: someone has to publish first."""
_write_handwritten("pc@example.com\nhunter2\n")
client = _client()
_sync_kuchnia_credential(client, ["phone"])
cached = store.read_synced_credential()
assert cached is not None
assert cached[1] == "hunter2"

View File

@ -0,0 +1,50 @@
# Kuchnia Wikinga on the phone
The Dart half of the catering import. Read
[kuchnia-wikinga.md](kuchnia-wikinga.md) first — the API map, the traps and the
delivered-is-not-eaten rule all live there and are not repeated here.
`app/` carries a Dart mirror of the whole walk, so the feature works with the
PC switched off. The files map one-to-one:
| Python | Dart |
|---|---|
| `_kuchnia_client.py` | `services/kuchnia_client.dart` |
| `_kuchnia_orders.py` | `services/kuchnia_orders.dart` |
| `_kuchnia_parse.py` | `services/kuchnia_parse.dart` |
| `_kuchnia_spread.py` | `services/kuchnia_spread.dart` |
| `_kuchnia_import.py` | `services/kuchnia_import.dart` |
| `_gatelock_kuchnia.py` | `screens/log_meal_kuchnia_mixin.dart` + `services/kuchnia_queue.dart` |
**Android only.** The panel sends no CORS headers, so a browser cannot call it;
`refreshDelivery` checks `kIsWeb` first and returns a reason. The settings
*fields* still show on web — the desktop app is where a password is most likely
to be typed, and the credential syncs from there to the phone.
`package:http` has no cookie jar, so the `SESSION` cookie is read off the login
response and replayed by hand. `Response.headers` folds duplicate `set-cookie`
values into one comma-joined string, so the parser splits on both `,` and `;`.
### What the parity gate covers, and what it does not
`tests/fixtures/kuchnia_day.json` is one payload with one expected result, read
by **both** `diet_guard/tests/test_kuchnia_parity.py` and
`app/test/kuchnia_parity_test.dart`. It pins the dish list, the dropped dishes,
the slot assignment, the bank keys and the encoded records. A second fixture,
`kuchnia_credential.json`, does the same for the credential adapter.
Three traps it exists for, each of which passed review once:
- **`_ENERGY_TOLERANCE` is 0.35**, not the "~1%" quoted above for the captured
day. Porting 0.01 would drop dishes the PC keeps, and then each device
re-adds what the other dropped.
- **`jsonEncode(435)` emits `435` where Python emits `435.0`.** Every Dart
macro is declared `double`, and the fixture compares canonicalised encodings,
not just values — `435 == 435.0` is true, so a value-only test misses this.
- **Dart's `List.sort` is unstable; Python's `sorted` is stable.** The Dart
comparator carries the payload index as a final tiebreak, and the fixture
contains two dishes sharing both a priority and a name.
The gate proves the two implementations agree **on a fixed payload**. It does
not prove they agree against the live panel on a given day; that is a separate,
on-device observation.

View File

@ -87,9 +87,36 @@ the parser refuses rather than importing a plausible-looking lie.
## Credentials
Two files under `~/.config/diet_guard/`, both mode 600, both **outside** the
synced tree — a password and a live session cookie must not travel to another
device.
Three files under `~/.config/diet_guard/`, all mode 600. They are outside
`DATA_DIR` so they stay off the *food-log* sync path — but one of them, the
credential itself, **does travel between devices**.
**The password syncs, in plaintext.** The phone runs its own importer and
cannot fetch without it, and a phone that has been wiped needs it back without
the user digging out the original. It rides its own document
(`diet_guard/sync_merge/_kuchnia.py`, `devices/<id>/kuchnia.json`), not the
budget record — `budget.json` is written back at default permissions, so a
password inside it would be readable by anything that reads the budget. Nothing
encrypts it, and the rest of the synced state is not encrypted either, so do
not describe it as "encrypted like everything else". This is a deliberate
trade: the alternative was a phone that cannot fetch at all, and the blast
radius is a catering menu and a delivery address.
**The session cookie does not sync.** It is regenerable from the password, so
copying it around would widen exposure and buy nothing.
| file | written by | syncs? |
|---|---|---|
| `kuchnia_credentials` | the user, by hand | no — a local override, and the bootstrap for the first push |
| `kuchnia_synced_credential.json` | the sync layer | **yes**, as its own record |
| `kuchnia_session.json` | the client, on login | no |
`kuchnia_credentials` wins over the synced copy when present, so a machine-local
override always works. It is never *pushed*, though — only used to bootstrap
when no device has published a credential yet. Its mtime is the only edit time
it has, and `git checkout`, a backup restore or re-running the `install` line
below all bump it without the credential changing; letting that compete in the
merge let a merely-touched file overwrite a password just typed on the phone.
```bash
install -m 600 /dev/null ~/.config/diet_guard/kuchnia_credentials
@ -108,7 +135,7 @@ returns a reason string and the caller carries on.
## Triggers
Three, all event-driven. **No new systemd timer** — `diet-guard-sync.timer` was
All event-driven. **No new systemd timer** — `diet-guard-sync.timer` was
deliberately deleted and `install.sh` actively uninstalls it.
| | Where | Guarded? |
@ -116,11 +143,19 @@ deliberately deleted and `install.sh` actively uninstalls it.
| CLI | `diet-guard kuchnia` | no — an explicit ask always goes and looks |
| Gate | `MealGate.on_focus_ready` → `_autoload_delivery` | yes |
| After a meal | `_cli_log.cmd_ate`, on the existing background thread | yes |
| Phone: log screen | `LogMealKuchniaMixin.loadTodaysDelivery` on `initState` | yes |
| Phone: settings | the "Fetch today's delivery" button | no — same rule as the CLI |
The guarded pair go through `refresh_delivery_once`, which skips the walk when
today has already been fetched (`kuchnia_last_import`, one ISO date). Without
it the after-log hook would pay a login plus three requests after *every* meal.
Only a clean fetch records the date, so an outage is retried.
The guarded ones go through `refresh_delivery_once` (Python) or
`KuchniaQueueService.refreshOnce` (Dart), which skip the walk when today has
already been fetched. Without that the after-log hook would pay a login plus
three requests after *every* meal. Only a clean fetch records the date, so an
outage is retried.
The marker is **device-local on both sides** — `kuchnia_last_import` under
`~/.config` on the PC, `kuchnia_last_import.json` in the app's document store
on the phone. It is a rate limit, not shared state: syncing it would let one
device's fetch suppress the other's.
**Why the gate hook is in `on_focus_ready` and not `_cli_gate._should_lock`:**
`gate_is_due()` reads only the food log and the schedule, never the food bank,
@ -146,13 +181,37 @@ news: it must not talk over the prompt telling the user which slots to fill.
- **`requests` is lazy-imported.** The gate's not-due tick imports the CLI and
must not pay ~78ms for an HTTP stack it never touches. Call sites reach
through `sys.modules[__name__]` so `patch.object` still wins.
- **The phone needs no importer.** It receives the curated bank and the log
through existing sync, and `FoodBankRecord.fromJson`/`toJson` enumerate a
fixed key set — a provenance field written by the PC would be silently
dropped on every round-trip, producing an endless re-add/re-strip ping-pong.
Verified rather than assumed: `app/test/kuchnia_bank_interop_test.dart`
round-trips a verbatim capture of a real imported bank through the Dart
model, diacritics and `t` stamp included.
- **The phone has its own importer, and the two must agree exactly.** It no
longer merely receives the curated bank: it fetches, parses and banks the
day's dishes itself, so the feature works with the PC switched off. That
makes three things load-bearing across two languages — which dishes are
*dropped*, which *slot* each lands on, and the exact JSON a banked record
encodes to. A disagreement on any of them means each device re-adds what the
other dropped; `add_manual_entry` restamps `t` unconditionally, so the whole
curated bank republishes to every peer on every refresh. A slot mismatch is
worse: a checkpoint one device offers and the other does not can never be
satisfied.
Gated by **one shared fixture**, `tests/fixtures/kuchnia_day.json`, asserted
by `diet_guard/tests/test_kuchnia_parity.py` *and*
`app/test/kuchnia_parity_test.dart`. Two suites written independently from
the same prose is not a gate; one input with one expected result is.
Regenerate it with `scripts/build_kuchnia_fixture.py`, and re-read the diff
before committing — the script blesses whatever Python currently does.
Three traps the fixture pins, each of which passed review once:
`_ENERGY_TOLERANCE` is **0.35**, not the ~1% the prose above quotes for the
captured day; `jsonEncode(435)` emits `435` where Python emits `435.0`, so
every Dart macro is forced to `double`; and Dart's `List.sort` is unstable
where Python's `sorted` is stable, so the Dart comparator carries the payload
index as a final tiebreak.
- **Bank records still round-trip losslessly through the Dart model.**
`FoodBankRecord.fromJson`/`toJson` enumerate a fixed key set — a provenance
field written by the PC would be silently dropped on every round-trip,
producing an endless re-add/re-strip ping-pong.
`app/test/kuchnia_bank_interop_test.dart` round-trips a verbatim capture of a
real imported bank through the Dart model, diacritics and `t` stamp included.
- **The two devices normalize bank keys with different primitives** — Python
`str.casefold()`, Dart `String.toLowerCase()`. They agree across the entire
Polish alphabet and on every real dish name seen so far, and diverge only on
@ -160,6 +219,12 @@ news: it must not talk over the prompt telling the user which slots to fill.
unify them would strand every existing entry. The Dart test above pins the
agreement, so a future non-Polish dish name cannot break it unnoticed.
## The phone runs the same import
`app/` carries a Dart mirror of the whole walk, so the feature works with the
PC switched off — including the cross-language parity gate that keeps the two
from drifting. See [kuchnia-wikinga-phone.md](kuchnia-wikinga-phone.md).
## Re-probing the API
`scripts/probe_kuchnia.py` (login, order walk) and

View File

@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Regenerate the shared catering-credential parity fixture.
The fixture (``tests/fixtures/kuchnia_credential.json``) is read by *both*
``diet_guard/tests/test_kuchnia_credential_sync.py`` and
``app/test/sync_merge_kuchnia_test.dart``, for the same reason the menu
fixture is: two suites written independently from the same prose is not a
gate.
What has to agree across the two languages is narrow but sharp:
* an **unparsable** edit time must fall back to the same clock on both sides
(Python catches ``ValueError`` from ``fromisoformat``; Dart's
``DateTime.tryParse`` returns null), because a junk stamp that resolved
differently per device would hand the race to whichever side was more
forgiving, and
* a **blank half** must contribute nothing, or a half-filled settings form
pushes an empty-string password that wins LWW against a real one.
The node id is pinned because it differs per install and is not part of what
parity guarantees; the wall time and the field values are.
Run it from the repo root:
python3 scripts/build_kuchnia_credential_fixture.py
"""
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import patch
from diet_guard.sync_merge._kuchnia import credential_to_log
FIXTURE = (
Path(__file__).resolve().parent.parent / "tests/fixtures/kuchnia_credential.json"
)
#: Stands in for the per-install uuid, which is not part of the parity claim.
_DEVICE_ID = "fixturedev"
_CASES: list[dict[str, object]] = [
{
"name": "a normal credential",
"username": "me@example.com",
"password": "hunter2",
"edited_at": "2026-08-23T10:00:00+02:00",
},
{
"name": "an unparsable edit time falls back to the epoch",
"username": "me@example.com",
"password": "hunter2",
"edited_at": "not-a-timestamp",
},
{
"name": "a blank password contributes nothing",
"username": "me@example.com",
"password": "",
"edited_at": "2026-08-23T10:00:00+02:00",
},
{
"name": "a blank username contributes nothing",
"username": "",
"password": "hunter2",
"edited_at": "2026-08-23T10:00:00+02:00",
},
]
def build() -> dict[str, object]:
"""Return the fixture: each case with the result Python produces."""
cases = []
with patch(
"diet_guard.sync_merge._kuchnia.device_id",
return_value=_DEVICE_ID,
):
for case in _CASES:
entry = dict(case)
log = credential_to_log(
str(case["username"]),
str(case["password"]),
str(case["edited_at"]),
)
entry["expected_empty"] = not log
if log:
record = log["kuchnia"]
entry["expected_wall_time_ms"] = record.fields["password"][
1
].wall_time_ms
entry["expected_username"] = record.fields["username"][0]
entry["expected_password"] = record.fields["password"][0]
cases.append(entry)
return {
"_comment": (
"Shared parity fixture for the catering credential's sync adapter. "
"Read by BOTH diet_guard/tests/test_kuchnia_credential_sync.py and "
"app/test/sync_merge_kuchnia_test.dart. Regenerate with "
"scripts/build_kuchnia_credential_fixture.py."
),
"device_id": _DEVICE_ID,
"cases": cases,
}
def main() -> None:
"""Write the fixture to disk.
Deliberately silent: ``T201`` bans ``print`` here, and the script's output
is the file itself -- ``git diff`` is how you check what changed.
"""
FIXTURE.parent.mkdir(parents=True, exist_ok=True)
with FIXTURE.open("w", encoding="utf-8") as handle:
json.dump(build(), handle, ensure_ascii=False, indent=2, sort_keys=True)
handle.write("\n")
if __name__ == "__main__":
main()

192
scripts/build_kuchnia_fixture.py Executable file
View File

@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Regenerate the shared cross-language catering parity fixture.
The fixture (``tests/fixtures/kuchnia_day.json``) is read by *both*
``diet_guard/tests/test_kuchnia_parity.py`` and
``app/test/kuchnia_parity_test.dart``. Two independently written suites from
the same prose is not a gate; one shared input with one shared expected result
is.
``expected`` is generated from the Python implementation, which is the
reference the Dart port must reproduce. That means regenerating after a
behaviour change will happily bless the new behaviour -- so only run this when
the change is intended, and re-read the diff before committing it.
The five real dishes live in ``tests/fixtures/kuchnia_real_meals.json``: a
scrubbed capture of the live panel on 2026-08-22, where the fields the parser
reads are verbatim, opaque ids are replaced with synthetic ones, and
image/allergen/review metadata is dropped. Every other meal is synthetic and
pins exactly one drop or fallback path.
Run it from the repo root, where the editable install puts ``diet_guard`` on
the path -- the same assumption the test suite makes. Both forms work:
python3 scripts/build_kuchnia_fixture.py
python3 -m scripts.build_kuchnia_fixture
"""
from __future__ import annotations
import json
from pathlib import Path
from diet_guard._kuchnia_import import dish_to_record
from diet_guard._kuchnia_parse import Dish, parse_menu
from diet_guard._kuchnia_spread import assign_slots
FIXTURE = Path(__file__).resolve().parent.parent / "tests/fixtures/kuchnia_day.json"
#: The real, scrubbed dishes, kept as a sidecar data file rather than a literal
#: here: transcribing them by hand silently corrupted three of the five (wrong
#: macros, truncated names) and the mistake was invisible in review.
#:
#: Diacritics are deliberately preserved. The two devices normalize bank keys
#: with different primitives (Python ``str.casefold()``, Dart
#: ``String.toLowerCase()``) and this is what pins their agreement across the
#: Polish alphabet.
REAL_MEALS_FILE = FIXTURE.parent / "kuchnia_real_meals.json"
def _real_meals() -> list[dict[str, object]]:
"""Load the scrubbed capture of the live panel on 2026-08-22."""
with REAL_MEALS_FILE.open(encoding="utf-8") as handle:
return json.load(handle)
def _nutrition(
weight: float, kcal: object, protein: float, carbs: float, fat: float
) -> dict[str, object]:
"""Build a minimal ``nutrition`` block for a synthetic meal."""
return {
"weight": weight,
"calories": kcal,
"protein": protein,
"carbohydrate": carbs,
"fat": fat,
}
#: One synthetic meal per parser branch. Without these, "dropped dishes" is a
#: vacuous assertion -- a real capture is all happy path.
_SYNTHETIC_MEALS: list[object] = [
# Macros quoted per 100 g against a per-portion kcal: the one failure mode
# that would silently skew every logged meal by a factor of several.
{
"mealName": "Obiad",
"menuMealName": "Per-100g mix-up, dropped",
"mealPriority": 6,
"nutrition": _nutrition(400.0, 900.0, 5.0, 6.0, 2.0),
},
# Portion outside the sane gram band (kg mistaken for g).
{
"mealName": "Kolacja",
"menuMealName": "Absurd portion, dropped",
"mealPriority": 7,
"nutrition": _nutrition(9000.0, 500.0, 30.0, 60.0, 15.0),
},
# No mealPriority -> falls back to 1-based payload position.
{
"mealName": "Przekąska",
"menuMealName": "No priority, kept",
"nutrition": _nutrition(120.0, 300.0, 10.0, 40.0, 8.0),
},
# A numeric field delivered as a JSON string. ``as_float`` rejects strings
# (0.0), so the energy check fails and the dish drops. Pins the coercion
# contract: Dart must NOT `double.tryParse` its way to a different answer.
{
"mealName": "Obiad",
"menuMealName": "Stringly typed, dropped",
"mealPriority": 8,
"nutrition": _nutrition(200.0, "435", 25.0, 50.0, 12.0),
},
# Not a dict at all.
"not-a-meal",
# ``nutrition`` absent entirely.
{
"mealName": "Obiad",
"menuMealName": "No nutrition, dropped",
"mealPriority": 9,
},
# Two dishes sharing BOTH priority and name. Python's ``sorted`` is stable
# and Dart's ``List.sort`` is not, so this pair is what forces both sides to
# make the comparator total.
{
"mealName": "Obiad",
"menuMealName": "Twin dish",
"mealPriority": 5,
"nutrition": _nutrition(300.0, 400.0, 25.0, 45.0, 12.0),
},
{
"mealName": "Obiad",
"menuMealName": "Twin dish",
"mealPriority": 5,
"nutrition": _nutrition(300.0, 400.0, 25.0, 45.0, 12.0),
},
]
def _dish_json(dish: Dish) -> dict[str, object]:
"""Serialize a ``Dish`` field-for-field for the expected block."""
return {
"name": dish.name,
"kcal": dish.kcal,
"protein_g": dish.protein_g,
"carbs_g": dish.carbs_g,
"fat_g": dish.fat_g,
"grams": dish.grams,
"priority": dish.priority,
"slot_label": dish.slot_label,
}
def build() -> dict[str, object]:
"""Return the whole fixture: the payload and its expected results."""
payload = {
"deliveryMenuMeal": [*_real_meals(), *_SYNTHETIC_MEALS],
"menuVisible": True,
"showNutrition": True,
}
dishes = parse_menu(payload)
default_slots = (8, 12, 16, 20)
return {
"_comment": (
"Shared parity fixture for the Kuchnia Wikinga catering import. "
"Read by BOTH diet_guard/tests/test_kuchnia_parity.py and "
"app/test/kuchnia_parity_test.dart -- same input, same expected "
"result. Regenerate with scripts/build_kuchnia_fixture.py."
),
"payload": payload,
"expected": {
"dishes": [_dish_json(dish) for dish in dishes],
"dropped_count": len(payload["deliveryMenuMeal"]) - len(dishes),
"slots": {
"8,12,16,20": [s.slot for s in assign_slots(dishes, default_slots)],
"8,12,16,20,22": [
s.slot for s in assign_slots(dishes, (8, 12, 16, 20, 22))
],
# The other direction: fewer dishes than slots.
"first_three_8,12,16,20": [
s.slot for s in assign_slots(dishes[:3], default_slots)
],
},
"slot_order": [s.dish.name for s in assign_slots(dishes, default_slots)],
"bank_keys": [dish.name.strip().casefold() for dish in dishes],
"bank_records": [dish_to_record(dish) for dish in dishes],
},
}
def main() -> None:
"""Write the fixture to disk.
Deliberately silent: ``T201`` bans ``print`` here, and the script's output
is the file itself -- ``git diff`` is how you check what changed.
"""
FIXTURE.parent.mkdir(parents=True, exist_ok=True)
with FIXTURE.open("w", encoding="utf-8") as handle:
json.dump(build(), handle, ensure_ascii=False, indent=2, sort_keys=True)
handle.write("\n")
if __name__ == "__main__":
main()

40
tests/fixtures/kuchnia_credential.json vendored Normal file
View File

@ -0,0 +1,40 @@
{
"_comment": "Shared parity fixture for the catering credential's sync adapter. Read by BOTH diet_guard/tests/test_kuchnia_credential_sync.py and app/test/sync_merge_kuchnia_test.dart. Regenerate with scripts/build_kuchnia_credential_fixture.py.",
"cases": [
{
"edited_at": "2026-08-23T10:00:00+02:00",
"expected_empty": false,
"expected_password": "hunter2",
"expected_username": "me@example.com",
"expected_wall_time_ms": 1787472000000,
"name": "a normal credential",
"password": "hunter2",
"username": "me@example.com"
},
{
"edited_at": "not-a-timestamp",
"expected_empty": false,
"expected_password": "hunter2",
"expected_username": "me@example.com",
"expected_wall_time_ms": 0,
"name": "an unparsable edit time falls back to the epoch",
"password": "hunter2",
"username": "me@example.com"
},
{
"edited_at": "2026-08-23T10:00:00+02:00",
"expected_empty": true,
"name": "a blank password contributes nothing",
"password": "",
"username": "me@example.com"
},
{
"edited_at": "2026-08-23T10:00:00+02:00",
"expected_empty": true,
"name": "a blank username contributes nothing",
"password": "hunter2",
"username": ""
}
],
"device_id": "fixturedev"
}

377
tests/fixtures/kuchnia_day.json vendored Normal file
View File

@ -0,0 +1,377 @@
{
"_comment": "Shared parity fixture for the Kuchnia Wikinga catering import. Read by BOTH diet_guard/tests/test_kuchnia_parity.py and app/test/kuchnia_parity_test.dart -- same input, same expected result. Regenerate with scripts/build_kuchnia_fixture.py.",
"expected": {
"bank_keys": [
"marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy",
"hummus paprykowy, mini wafle kukurydziane, warzywa",
"makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski",
"fit ciasto, jak twix white",
"kaszotto grzybowe z pieczonym kurczakiem i serem włoskim",
"no priority, kept",
"twin dish",
"twin dish"
],
"bank_records": [
{
"carbs_g": 54.64,
"count": 0,
"desc": "Marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy",
"fat_g": 12.01,
"grams": 270.0,
"kcal": 435.0,
"protein_g": 25.86
},
{
"carbs_g": 41.67,
"count": 0,
"desc": "Hummus paprykowy, mini wafle kukurydziane, warzywa",
"fat_g": 17.26,
"grams": 205.0,
"kcal": 367.0,
"protein_g": 10.86
},
{
"carbs_g": 53.23,
"count": 0,
"desc": "Makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski",
"fat_g": 23.21,
"grams": 465.0,
"kcal": 594.0,
"protein_g": 42.47
},
{
"carbs_g": 25.18,
"count": 0,
"desc": "Fit ciasto, jak twix white",
"fat_g": 17.36,
"grams": 90.0,
"kcal": 268.0,
"protein_g": 5.85
},
{
"carbs_g": 35.56,
"count": 0,
"desc": "Kaszotto grzybowe z pieczonym kurczakiem i serem włoskim",
"fat_g": 13.02,
"grams": 318.0,
"kcal": 391.0,
"protein_g": 32.51
},
{
"carbs_g": 40.0,
"count": 0,
"desc": "No priority, kept",
"fat_g": 8.0,
"grams": 120.0,
"kcal": 300.0,
"protein_g": 10.0
},
{
"carbs_g": 45.0,
"count": 0,
"desc": "Twin dish",
"fat_g": 12.0,
"grams": 300.0,
"kcal": 400.0,
"protein_g": 25.0
},
{
"carbs_g": 45.0,
"count": 0,
"desc": "Twin dish",
"fat_g": 12.0,
"grams": 300.0,
"kcal": 400.0,
"protein_g": 25.0
}
],
"dishes": [
{
"carbs_g": 54.64,
"fat_g": 12.01,
"grams": 270.0,
"kcal": 435.0,
"name": "Marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy",
"priority": 1,
"protein_g": 25.86,
"slot_label": "Śniadanie"
},
{
"carbs_g": 41.67,
"fat_g": 17.26,
"grams": 205.0,
"kcal": 367.0,
"name": "Hummus paprykowy, mini wafle kukurydziane, warzywa",
"priority": 2,
"protein_g": 10.86,
"slot_label": "II śniadanie"
},
{
"carbs_g": 53.23,
"fat_g": 23.21,
"grams": 465.0,
"kcal": 594.0,
"name": "Makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski",
"priority": 3,
"protein_g": 42.47,
"slot_label": "Obiad"
},
{
"carbs_g": 25.18,
"fat_g": 17.36,
"grams": 90.0,
"kcal": 268.0,
"name": "Fit ciasto, jak twix white",
"priority": 4,
"protein_g": 5.85,
"slot_label": "Podwieczorek"
},
{
"carbs_g": 35.56,
"fat_g": 13.02,
"grams": 318.0,
"kcal": 391.0,
"name": "Kaszotto grzybowe z pieczonym kurczakiem i serem włoskim",
"priority": 5,
"protein_g": 32.51,
"slot_label": "Kolacja"
},
{
"carbs_g": 40.0,
"fat_g": 8.0,
"grams": 120.0,
"kcal": 300.0,
"name": "No priority, kept",
"priority": 8,
"protein_g": 10.0,
"slot_label": "Przekąska"
},
{
"carbs_g": 45.0,
"fat_g": 12.0,
"grams": 300.0,
"kcal": 400.0,
"name": "Twin dish",
"priority": 5,
"protein_g": 25.0,
"slot_label": "Obiad"
},
{
"carbs_g": 45.0,
"fat_g": 12.0,
"grams": 300.0,
"kcal": 400.0,
"name": "Twin dish",
"priority": 5,
"protein_g": 25.0,
"slot_label": "Obiad"
}
],
"dropped_count": 5,
"slot_order": [
"Marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy",
"Hummus paprykowy, mini wafle kukurydziane, warzywa",
"Makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski",
"Fit ciasto, jak twix white",
"Kaszotto grzybowe z pieczonym kurczakiem i serem włoskim",
"Twin dish",
"Twin dish",
"No priority, kept"
],
"slots": {
"8,12,16,20": [
8,
8,
12,
12,
16,
16,
20,
20
],
"8,12,16,20,22": [
8,
8,
12,
12,
16,
20,
20,
22
],
"first_three_8,12,16,20": [
8,
12,
16
]
}
},
"payload": {
"deliveryMenuMeal": [
{
"deliveryMealId": 1001,
"mealName": "Śniadanie",
"mealPriority": 1,
"menuMealName": "Marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy",
"nutrition": {
"calories": 435.0,
"carbohydrate": 54.64,
"dietaryFiber": 2.03,
"fat": 12.01,
"protein": 25.86,
"salt": 0.52,
"saturatedFattyAcids": 1.92,
"sugar": 22.4,
"weight": 270.0
}
},
{
"deliveryMealId": 1002,
"mealName": "II śniadanie",
"mealPriority": 2,
"menuMealName": "Hummus paprykowy, mini wafle kukurydziane, warzywa",
"nutrition": {
"calories": 367.0,
"carbohydrate": 41.67,
"dietaryFiber": 9.18,
"fat": 17.26,
"protein": 10.86,
"salt": 1.27,
"saturatedFattyAcids": 1.59,
"sugar": 3.77,
"weight": 205.0
}
},
{
"deliveryMealId": 1003,
"mealName": "Obiad",
"mealPriority": 3,
"menuMealName": "Makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski",
"nutrition": {
"calories": 594.0,
"carbohydrate": 53.23,
"dietaryFiber": 3.83,
"fat": 23.21,
"protein": 42.47,
"salt": 1.08,
"saturatedFattyAcids": 7.03,
"sugar": 4.88,
"weight": 465.0
}
},
{
"deliveryMealId": 1004,
"mealName": "Podwieczorek",
"mealPriority": 4,
"menuMealName": "Fit ciasto, jak twix white",
"nutrition": {
"calories": 268.0,
"carbohydrate": 25.18,
"dietaryFiber": 0.36,
"fat": 17.36,
"protein": 5.85,
"salt": 0.15,
"saturatedFattyAcids": 10.76,
"sugar": 8.3,
"weight": 90.0
}
},
{
"deliveryMealId": 1005,
"mealName": "Kolacja",
"mealPriority": 5,
"menuMealName": "Kaszotto grzybowe z pieczonym kurczakiem i serem włoskim",
"nutrition": {
"calories": 391.0,
"carbohydrate": 35.56,
"dietaryFiber": 3.69,
"fat": 13.02,
"protein": 32.51,
"salt": 1.3,
"saturatedFattyAcids": 6.53,
"sugar": 1.99,
"weight": 318.0
}
},
{
"mealName": "Obiad",
"mealPriority": 6,
"menuMealName": "Per-100g mix-up, dropped",
"nutrition": {
"calories": 900.0,
"carbohydrate": 6.0,
"fat": 2.0,
"protein": 5.0,
"weight": 400.0
}
},
{
"mealName": "Kolacja",
"mealPriority": 7,
"menuMealName": "Absurd portion, dropped",
"nutrition": {
"calories": 500.0,
"carbohydrate": 60.0,
"fat": 15.0,
"protein": 30.0,
"weight": 9000.0
}
},
{
"mealName": "Przekąska",
"menuMealName": "No priority, kept",
"nutrition": {
"calories": 300.0,
"carbohydrate": 40.0,
"fat": 8.0,
"protein": 10.0,
"weight": 120.0
}
},
{
"mealName": "Obiad",
"mealPriority": 8,
"menuMealName": "Stringly typed, dropped",
"nutrition": {
"calories": "435",
"carbohydrate": 50.0,
"fat": 12.0,
"protein": 25.0,
"weight": 200.0
}
},
"not-a-meal",
{
"mealName": "Obiad",
"mealPriority": 9,
"menuMealName": "No nutrition, dropped"
},
{
"mealName": "Obiad",
"mealPriority": 5,
"menuMealName": "Twin dish",
"nutrition": {
"calories": 400.0,
"carbohydrate": 45.0,
"fat": 12.0,
"protein": 25.0,
"weight": 300.0
}
},
{
"mealName": "Obiad",
"mealPriority": 5,
"menuMealName": "Twin dish",
"nutrition": {
"calories": 400.0,
"carbohydrate": 45.0,
"fat": 12.0,
"protein": 25.0,
"weight": 300.0
}
}
],
"menuVisible": true,
"showNutrition": true
}
}

87
tests/fixtures/kuchnia_real_meals.json vendored Normal file
View File

@ -0,0 +1,87 @@
[
{
"deliveryMealId": 1001,
"mealName": "Śniadanie",
"mealPriority": 1,
"menuMealName": "Marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy",
"nutrition": {
"calories": 435.0,
"carbohydrate": 54.64,
"dietaryFiber": 2.03,
"fat": 12.01,
"protein": 25.86,
"salt": 0.52,
"saturatedFattyAcids": 1.92,
"sugar": 22.4,
"weight": 270.0
}
},
{
"deliveryMealId": 1002,
"mealName": "II śniadanie",
"mealPriority": 2,
"menuMealName": "Hummus paprykowy, mini wafle kukurydziane, warzywa",
"nutrition": {
"calories": 367.0,
"carbohydrate": 41.67,
"dietaryFiber": 9.18,
"fat": 17.26,
"protein": 10.86,
"salt": 1.27,
"saturatedFattyAcids": 1.59,
"sugar": 3.77,
"weight": 205.0
}
},
{
"deliveryMealId": 1003,
"mealName": "Obiad",
"mealPriority": 3,
"menuMealName": "Makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski",
"nutrition": {
"calories": 594.0,
"carbohydrate": 53.23,
"dietaryFiber": 3.83,
"fat": 23.21,
"protein": 42.47,
"salt": 1.08,
"saturatedFattyAcids": 7.03,
"sugar": 4.88,
"weight": 465.0
}
},
{
"deliveryMealId": 1004,
"mealName": "Podwieczorek",
"mealPriority": 4,
"menuMealName": "Fit ciasto, jak twix white",
"nutrition": {
"calories": 268.0,
"carbohydrate": 25.18,
"dietaryFiber": 0.36,
"fat": 17.36,
"protein": 5.85,
"salt": 0.15,
"saturatedFattyAcids": 10.76,
"sugar": 8.3,
"weight": 90.0
}
},
{
"deliveryMealId": 1005,
"mealName": "Kolacja",
"mealPriority": 5,
"menuMealName": "Kaszotto grzybowe z pieczonym kurczakiem i serem włoskim",
"nutrition": {
"calories": 391.0,
"carbohydrate": 35.56,
"dietaryFiber": 3.69,
"fat": 13.02,
"protein": 32.51,
"salt": 1.3,
"saturatedFattyAcids": 6.53,
"sugar": 1.99,
"weight": 318.0
}
}
]