Prefill a catering dish as a whole-portion reference so the gate logs its own calories, not grams/100 times them

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-09-20 08:30:05 +02:00
parent 2984683027
commit 74057f195f
6 changed files with 83 additions and 57 deletions

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.86+1
version: 1.0.87+1
environment:
sdk: ^3.12.2

View File

@ -25,7 +25,8 @@ from diet_guard._gate import due_slots
from diet_guard._gatelock_fetch import FETCH_POLL_MS, start_fetch
from diet_guard._gatelock_kuchnia import start_delivery_fetch
from diet_guard._gatelock_nutrition import _GateNutrition
from diet_guard._kuchnia_spread import dish_field_values, dishes_in_slot_order
from diet_guard._kuchnia_log import dish_nutrition
from diet_guard._kuchnia_spread import dishes_in_slot_order
from diet_guard._state import now_local
from diet_guard._sync_refresh import pull_peer_logs
@ -79,16 +80,13 @@ class _PullFlows(_GateNutrition):
#: prompt to report that the caterer had nothing today.
_delivery_asked: bool = False
#: The in-flight sync fetch's queue, or None when none is running.
#: Slots still to be filled; owned by the controller this mixes into.
# Supplied by ``_GateMealFlow``, which mixes this class in. Declared so the
# contract is explicit and pylint can see it: the dependency runs both ways
# (the flows drive the meal form, the form hosts the flows) and the
# ancestor cap leaves no room for another chain link.
_set_status: Callable[..., None]
_clear_inputs: Callable[[], None]
_apply_reference: Callable[..., None]
_refresh_dashboard: Callable[[], None]
_unlock: Callable[[str], None]
@ -152,13 +150,12 @@ class _PullFlows(_GateNutrition):
dish, *rest = self._delivery_pending
self._delivery_pending = tuple(rest)
self._clear_inputs()
self._set_desc(dish.name)
grams, macros = dish_field_values(dish)
self._widgets.amount_entry.insert(0, grams)
for entry, value in zip(self._macro_entries(), macros, strict=True):
entry.insert(0, value)
self._state.source = "kuchnia wikinga"
self._refresh_projection()
# Through the reference model, never straight into the fields: the
# form scales the macros from the "per" basis to the amount eaten, so
# the basis must be the dish's own portion. Writing the macros with
# the basis left at ``_clear_inputs``'s 100 g default logged a 350 g
# dish at 3.5x its calories while the fields still read correctly.
self._apply_reference(dish_nutrition(dish), name=dish.name)
remaining = len(self._delivery_pending)
suffix = f" ({remaining} more to go)" if remaining else ""
prefix = f"{logged} — " if logged else ""

View File

@ -24,6 +24,7 @@ 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
@ -41,6 +42,23 @@ def _already_logged(entries: Sequence[dict[str, object]], name: str, slot: int)
)
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.
@ -56,18 +74,7 @@ def log_dishes(chosen: Sequence[SlottedDish]) -> list[str]:
dish = item.dish
if _already_logged(entries, dish.name, item.slot):
continue
log_meal(
dish.name,
Nutrition(
kcal=dish.kcal,
protein_g=dish.protein_g,
carbs_g=dish.carbs_g,
fat_g=dish.fat_g,
grams=dish.grams,
source=SOURCE,
),
item.slot,
)
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": item.slot}]

View File

@ -84,13 +84,3 @@ def dishes_in_slot_order(dishes: tuple[Dish, ...]) -> tuple[Dish, ...]:
"""
slotted = assign_slots(dishes, day_slots(current_schedule()))
return tuple(item.dish for item in slotted)
def dish_field_values(dish: Dish) -> tuple[str, tuple[str, ...]]:
"""Return ``(portion_grams, (kcal, protein, carbs, fat))`` as form strings.
Formatted here rather than in the widget code so the numeric formatting is
covered by a test that needs no display.
"""
macros = (dish.kcal, dish.protein_g, dish.carbs_g, dish.fat_g)
return f"{dish.grams:g}", tuple(f"{value:g}" for value in macros)

View File

@ -24,17 +24,20 @@ from unittest.mock import MagicMock, patch
import pytest
from diet_guard import _gatelock_delivery
from diet_guard._gatelock_delivery import _PullFlows, dish_field_values
from diet_guard._gatelock_delivery import _PullFlows
from diet_guard._gatelock_kuchnia import (
UNEXPECTED,
DeliveryResult,
start_delivery_fetch,
)
from diet_guard._kuchnia_log import SOURCE, dish_nutrition
from diet_guard._kuchnia_parse import Dish
if TYPE_CHECKING:
from collections.abc import Sequence
from diet_guard._estimator import Nutrition
DAY = datetime.date(2026, 8, 22)
@ -80,12 +83,10 @@ class _Gate(_PullFlows):
self.root = MagicMock()
self.demo_mode = False
self.statuses: list[tuple[str, bool]] = []
self._widgets = SimpleNamespace(amount_entry=MagicMock())
self._state = SimpleNamespace(source="manual")
self._descs: list[str] = []
self._references: list[Nutrition] = []
self._cleared = 0
self._projections = 0
self._entries = [MagicMock() for _ in range(4)]
def _set_status(self, text: str, *, error: bool = False) -> None:
self.statuses.append((text, error))
@ -96,11 +97,14 @@ class _Gate(_PullFlows):
def _clear_inputs(self) -> None:
self._cleared += 1
def _refresh_projection(self) -> None:
self._projections += 1
def _macro_entries(self) -> tuple[MagicMock, ...]:
return tuple(self._entries)
def _apply_reference(
self, nutrition: Nutrition, *, name: str | None = None
) -> None:
# The real one also fills the fields; the queue tests only need to
# know which dish was offered and as what reference.
if name is not None:
self._set_desc(name)
self._references.append(nutrition)
@property
def last_status(self) -> str:
@ -155,9 +159,11 @@ class TestLoadButton:
def test_a_dish_is_offered_but_never_logged(self) -> None:
gate = _Gate()
_deliver(gate, DeliveryResult(dishes=(_dish(),), reason=None))
# The form is filled...
# The form is filled -- as a whole-portion reference, so the basis
# is the dish's 318 g and not the form's 100 g default...
assert gate._descs == ["Kaszotto"]
gate._widgets.amount_entry.insert.assert_called_once_with(0, "318")
assert gate._references == [dish_nutrition(_dish())]
assert gate._references[0].grams == 318.0
# ...and that is all. Submitting stays the user's explicit action.
assert "Log & Continue" in gate.last_status
@ -198,19 +204,24 @@ class TestLoadButton:
gate.root.after.assert_not_called()
class TestFieldFormatting:
def test_values_are_trimmed_not_padded(self) -> None:
grams, macros = dish_field_values(_dish())
assert grams == "318"
assert macros == ("391", "32.5", "35.6", "13")
class TestDishNutrition:
def test_the_basis_is_the_dish_portion(self) -> None:
# The gate scales the reference from this basis to the amount eaten;
# anything other than the dish's own grams scales a whole-portion
# label as if it were per 100 g.
nutrition = dish_nutrition(_dish())
assert nutrition.grams == 318.0
assert nutrition.source == SOURCE
def test_the_macro_order_matches_the_form(self) -> None:
# _macro_entries() is (kcal, protein, carbs, fat); a mismatch here
# would silently swap a dish's protein and carbohydrate.
_grams, macros = dish_field_values(
Dish("x", 100.0, 1.0, 2.0, 3.0, 50.0, 1, ""),
def test_the_macro_order_matches_the_dish(self) -> None:
# A mismatch here would silently swap a dish's protein and carbs.
nutrition = dish_nutrition(Dish("x", 100.0, 1.0, 2.0, 3.0, 50.0, 1, ""))
assert (nutrition.kcal, nutrition.protein_g, nutrition.carbs_g) == (
100.0,
1.0,
2.0,
)
assert macros == ("100", "1", "2", "3")
assert nutrition.fat_g == 3.0
def test_unknown_lazy_attribute_raises() -> None:

View File

@ -24,6 +24,7 @@ from unittest.mock import patch
from diet_guard import _gatelock_mealflow
from diet_guard._gatelock_kuchnia import DeliveryResult
from diet_guard._kuchnia_log import dish_nutrition
from diet_guard.tests.conftest import _nutrition
from diet_guard.tests.test_kuchnia_gate import _deliver, _dish, _Gate
@ -145,6 +146,26 @@ class TestTheGateAdvancesTheQueue:
assert "Loaded: Second course" in gate._vars.status.get()
assert "Logged 08:00" in gate._vars.status.get()
def test_a_prefilled_dish_logs_exactly_its_own_values(self, gate: MealGate) -> None:
"""What the submit logs is the dish, not the dish scaled by grams/100.
The fields alone cannot catch this: they read the right numbers either
way. The regression it pins is a 350 g dish prefilled with its
whole-portion macros while the "per" basis sat at the 100 g default,
so ``Log & Continue`` recorded 3.5x the calories the form showed.
"""
dish = _dish("Owsianka")
gate._delivery_pending = (dish,)
gate._prefill_next_dish()
assert gate._current_nutrition() == dish_nutrition(dish)
assert "→ 391 kcal" in gate._vars.preview.get()
with (
patch.object(_gatelock_mealflow, "log_meal") as log,
patch.object(_gatelock_mealflow, "remember_food"),
):
gate._on_submit()
assert log.call_args.args[1] == dish_nutrition(dish)
def test_dishes_left_when_the_last_slot_unlocks_are_named(
self, gate: MealGate
) -> None: