diet-guard/diet_guard/_kuchnia_ids.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

43 lines
1.6 KiB
Python

"""The id a catering dish gets when it is logged without a tap.
One formula on every device, so the PC's entry and the phone's entry for the
same delivered dish are the same record and the sync merge keeps one::
uuid5(NAMESPACE_URL, f"kuchnia:{delivery date YYYY-MM-DD}:{dish key}")
The dish key is the panel's ``deliveryMealId`` (an ``int``, or a stripped
``str``); anything else -- a ``bool``, a float, a blank or missing id --
falls back to the lower-cased dish name. The phone's port and this module are
pinned by one fixture, ``tests/fixtures/kuchnia_autolog_ids.json``
(``scripts/build_kuchnia_autolog_fixture.py``), asserted by
``test_kuchnia_ids.py`` and ``app/test/services/kuchnia_autolog_ids_test.dart``.
"""
from __future__ import annotations
from datetime import date
import uuid
def dish_key(meal_id: object, name: str) -> str:
"""The dish half of the id string.
``bool`` is tested before ``int`` because ``isinstance(True, int)`` is
true in Python and not in Dart; ``.lower()`` (not ``casefold``) matches
the Dart port on the fixture's ASCII fallback names.
"""
key = ""
if isinstance(meal_id, bool):
key = ""
elif isinstance(meal_id, int):
key = str(meal_id)
elif isinstance(meal_id, str):
key = meal_id.strip()
return key or name.strip().lower()
def autolog_id(day: date | str, key: str) -> str:
"""The deterministic entry id for dish ``key`` delivered on ``day``."""
stamp = day.isoformat() if isinstance(day, date) else day
return str(uuid.uuid5(uuid.NAMESPACE_URL, f"kuchnia:{stamp}:{key}"))