diet-guard/diet_guard/_kuchnia_log.py
Krzysztof kuhy Rudnicki 03b6a455cb Auto-log due catering before the lock
kuhy's 2026-11-17 override of "delivered is not eaten": before the lock
opens, the PC logs the due slots' dishes by id uuid5(kuchnia📅key),
shared with the phone (fixture-pinned).

Failure paths:
- fetch error, no credentials, > 5 s: fail-closed, nothing is logged,
  the lock opens as before, reason emitted and logged.
- log write error (OSError/ValueError): fail-closed, same.
- gate --check: never logs (a decision, not a write).
- an undone (tombstoned) entry counts as logged: fail-closed against
  resurrecting a meal kuhy removed.
- publish outage after a clearing auto-log: fail-open by design, the
  local entry stays and the reason is emitted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:42:34 +01:00

111 lines
4.3 KiB
Python

"""Turn confirmed catering dishes into log entries.
Nothing in this module runs without an explicit confirmation: the CLI
``--log``, the lock window's buttons and "Fill all" all ask first. The one
unattended path is separate -- :mod:`diet_guard._kuchnia_autolog`, the PC's
pre-lock auto-log, which kuhy chose on 2026-11-17 ("LOG EVEN WITHOUT TAP")
knowing a delivered meal is not always an eaten one (skipped, shared or binned
dishes are logged as eaten).
Duplicate suppression works off **today's log**, not a local "already
imported" marker. ``log_meal`` mints a fresh uuid per entry, so a re-import
after a lost marker would merge as duplicates on every peer; comparing against
the synced log instead is robust to marker loss *and* correct across devices --
if the phone already logged the dish, the PC sees it and skips.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from diet_guard._estimator import Nutrition
from diet_guard._meal_schedule_store import current_schedule
from diet_guard._slot_wire import entry_slot_minute, satisfied_by_entries, slot_fields
from diet_guard._state import log_meal
from diet_guard._state_today import today_entries
if TYPE_CHECKING: # pragma: no cover - typing only
from collections.abc import Sequence
from diet_guard._kuchnia_parse import Dish
from diet_guard._kuchnia_spread import SlottedDish
#: Marks entries this importer created, so the provenance is visible in the log
#: and in the food bank's ``source`` column.
SOURCE = "kuchnia wikinga"
def _already_logged(entries: Sequence[dict[str, object]], name: str, slot: int) -> bool:
"""Return True when today's log already holds this dish at this slot minute.
Compares the entry's *recorded* minute (:func:`entry_slot_minute`), not its
snapped slot -- the app's catering fill uses the same rule, which is the
point: both devices must agree on which dishes are duplicates, or one
re-logs what the other skipped. Snapping still guards the fill flow,
because :func:`fill_plan` skips any slot an entry snaps to (occupancy).
"""
wanted = name.strip().casefold()
return any(
str(entry.get("desc", "")).strip().casefold() == wanted
and entry_slot_minute(entry) == slot
for entry in entries
)
def fill_plan(slotted: Sequence[SlottedDish]) -> list[SlottedDish]:
"""Keep only the dishes whose slot has nothing logged in it today.
"Fill all with catering" fills *empty* slots: a slot the user already
logged something else into keeps that meal rather than gaining a second
one. Occupancy is read once, before the batch, so two dishes the spread
put in the same empty slot (5 dishes on 4 slots) both land.
Args:
slotted: Today's dishes, already paired with slots.
Returns:
The dishes to log, in the order given.
"""
taken = satisfied_by_entries(today_entries(), current_schedule())
return [item for item in slotted if item.slot not in taken]
def dish_nutrition(dish: Dish) -> Nutrition:
"""Return a dish as the whole-portion :class:`Nutrition` it gets logged as.
``grams`` is the dish's own portion, which matters to the gate: its form
scales the label macros from the "per" basis to the amount eaten, and a
dish whose basis was left at the 100 g default logged 3.5x too much.
"""
return Nutrition(
kcal=dish.kcal,
protein_g=dish.protein_g,
carbs_g=dish.carbs_g,
fat_g=dish.fat_g,
grams=dish.grams,
source=SOURCE,
)
def log_dishes(chosen: Sequence[SlottedDish]) -> list[str]:
"""Log each chosen dish, skipping any already logged today in that slot.
Args:
chosen: The dishes the user confirmed, already paired with slots.
Returns:
The descriptions actually written, in the order they were logged.
"""
entries = today_entries()
written: list[str] = []
for item in chosen:
dish = item.dish
if _already_logged(entries, dish.name, item.slot):
continue
log_meal(dish.name, dish_nutrition(dish), item.slot)
# Reflect the write locally so two identical dishes in one batch do not
# both land: today_entries() was read once, before the loop.
entries = [*entries, {"desc": dish.name, **slot_fields(item.slot)}]
written.append(dish.name)
return written