mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-28 15:09:05 +01:00
Let the PC gate set the eating window and meal count
The second edit surface, so the schedule is editable from either device the way the budget already is. A row on the History tab beside the budget row, with the same Edit/Save toggle: first hour, last hour, meals per day, and the derived checkpoint times underneath so the effect of a change is visible before it is saved. Validated rather than clamped. MealSchedule.normalized() would happily turn "20 to 8" into a two-meal day ending at 09:00, which is a sensible defence against a peer's corrupt sync data and a terrible response to a typo at the keyboard. Each rejection says what is wrong and leaves the row in edit mode so the value can be corrected instead of silently becoming a different schedule. The narrow-window case has its own message, because that one is genuinely non-obvious: six meals between 08:00 and 11:00 would round two checkpoints onto the same hour, and a duplicate slot silently drops one. Three structural notes: - The row's widgets are their own module. _gatelock_calendar_widgets.py was at 216 of the 250-line cap and is now 233; adding the row inline would have breached it. - The five new StringVars are grouped in a ScheduleVars dataclass rather than flattened onto CalendarVars, which pylint flagged at 11 attributes. Grouping two unrelated concerns separately is the better shape anyway. - _gate_fixtures.py's _GATE_TK_MODULES is a hand-listed patch target, so both new modules are registered there. Left out, they build real tk widgets under a fake parent -- which is how it failed the first time, loudly, rather than silently opening a window. 785 tests, 100% branch coverage. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
This commit is contained in:
parent
da8822006f
commit
c0564c05a2
@ -2,7 +2,7 @@ name: diet_guard_app
|
|||||||
description: "Companion phone app for diet_guard: log meals on the go."
|
description: "Companion phone app for diet_guard: log meals on the go."
|
||||||
publish_to: 'none'
|
publish_to: 'none'
|
||||||
|
|
||||||
version: 1.0.35+1
|
version: 1.0.36+1
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.12.2
|
sdk: ^3.12.2
|
||||||
|
|||||||
@ -37,7 +37,6 @@ from diet_guard._calendar_view import (
|
|||||||
ytd_text,
|
ytd_text,
|
||||||
)
|
)
|
||||||
from diet_guard._daystatus import DayStatus, status_map
|
from diet_guard._daystatus import DayStatus, status_map
|
||||||
from diet_guard._gatelock_budgetedit import _GateBudgetEdit
|
|
||||||
from diet_guard._gatelock_calendar_ui import (
|
from diet_guard._gatelock_calendar_ui import (
|
||||||
_DECEMBER,
|
_DECEMBER,
|
||||||
_DEFAULT_BUDGET_KCAL,
|
_DEFAULT_BUDGET_KCAL,
|
||||||
@ -51,6 +50,10 @@ from diet_guard._gatelock_calendar_ui import (
|
|||||||
make_calendar_vars,
|
make_calendar_vars,
|
||||||
)
|
)
|
||||||
from diet_guard._gatelock_layout import build_layout
|
from diet_guard._gatelock_layout import build_layout
|
||||||
|
from diet_guard._gatelock_scheduleedit import _GateScheduleEdit
|
||||||
|
from diet_guard._meal_schedule_store import (
|
||||||
|
current_schedule as current_meal_schedule,
|
||||||
|
)
|
||||||
from diet_guard._state import load_log, now_local
|
from diet_guard._state import load_log, now_local
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -69,7 +72,7 @@ __all__ = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class _GateCalendar(_GateBudgetEdit):
|
class _GateCalendar(_GateScheduleEdit):
|
||||||
"""History tab: calendar, streaks, YTD tally, and budget editing."""
|
"""History tab: calendar, streaks, YTD tally, and budget editing."""
|
||||||
|
|
||||||
_cal_vars: CalendarVars
|
_cal_vars: CalendarVars
|
||||||
@ -78,6 +81,7 @@ class _GateCalendar(_GateBudgetEdit):
|
|||||||
_cal_year: int
|
_cal_year: int
|
||||||
_cal_month: int
|
_cal_month: int
|
||||||
_cal_editing_budget: bool
|
_cal_editing_budget: bool
|
||||||
|
_cal_editing_schedule: bool
|
||||||
_notebook: ttk.Notebook
|
_notebook: ttk.Notebook
|
||||||
|
|
||||||
def _build_tabs(self, parent: tk.Misc, callbacks: GateCallbacks) -> GateWidgets:
|
def _build_tabs(self, parent: tk.Misc, callbacks: GateCallbacks) -> GateWidgets:
|
||||||
@ -95,6 +99,7 @@ class _GateCalendar(_GateBudgetEdit):
|
|||||||
self._cal_year = today.year
|
self._cal_year = today.year
|
||||||
self._cal_month = today.month
|
self._cal_month = today.month
|
||||||
self._cal_editing_budget = False
|
self._cal_editing_budget = False
|
||||||
|
self._cal_editing_schedule = False
|
||||||
_style_notebook(parent)
|
_style_notebook(parent)
|
||||||
notebook = ttk.Notebook(parent)
|
notebook = ttk.Notebook(parent)
|
||||||
notebook.place(relx=0, rely=0, relwidth=1, relheight=1)
|
notebook.place(relx=0, rely=0, relwidth=1, relheight=1)
|
||||||
@ -109,6 +114,7 @@ class _GateCalendar(_GateBudgetEdit):
|
|||||||
on_prev_month=self._on_prev_month,
|
on_prev_month=self._on_prev_month,
|
||||||
on_next_month=self._on_next_month,
|
on_next_month=self._on_next_month,
|
||||||
on_edit_or_save_budget=self._on_edit_or_save_budget,
|
on_edit_or_save_budget=self._on_edit_or_save_budget,
|
||||||
|
on_edit_or_save_schedule=self._on_edit_or_save_schedule,
|
||||||
)
|
)
|
||||||
cal_widgets = build_calendar_frame(notebook, self._cal_vars, cal_callbacks)
|
cal_widgets = build_calendar_frame(notebook, self._cal_vars, cal_callbacks)
|
||||||
notebook.add(cal_widgets.frame, text="History")
|
notebook.add(cal_widgets.frame, text="History")
|
||||||
@ -162,6 +168,8 @@ class _GateCalendar(_GateBudgetEdit):
|
|||||||
self._cal_vars.averages.set(averages_text(log, schedule=schedule))
|
self._cal_vars.averages.set(averages_text(log, schedule=schedule))
|
||||||
if not self._cal_editing_budget:
|
if not self._cal_editing_budget:
|
||||||
self._refresh_budget_field(budget)
|
self._refresh_budget_field(budget)
|
||||||
|
if not self._cal_editing_schedule:
|
||||||
|
self._show_schedule(current_meal_schedule())
|
||||||
|
|
||||||
def _render_month(self, status_map_: dict[str, DayStatus] | None) -> None:
|
def _render_month(self, status_map_: dict[str, DayStatus] | None) -> None:
|
||||||
"""Redraw the day-cell grid and month label for the displayed month."""
|
"""Redraw the day-cell grid and month label for the displayed month."""
|
||||||
|
|||||||
109
diet_guard/_gatelock_calendar_schedule.py
Normal file
109
diet_guard/_gatelock_calendar_schedule.py
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
"""The History tab's meal-schedule row widgets.
|
||||||
|
|
||||||
|
Split out of :mod:`._gatelock_calendar_widgets` (216 lines against the repo's
|
||||||
|
250-line cap) rather than added to it. The behaviour behind these widgets
|
||||||
|
lives in :mod:`._gatelock_scheduleedit`, mirroring how the budget row's
|
||||||
|
widgets and its edit/save logic are split.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from gatelock import make_button
|
||||||
|
|
||||||
|
from diet_guard._gatelock_calendar_types import _COLORS, _FIELD_BG
|
||||||
|
from diet_guard._gatelock_spacing import SM, XS
|
||||||
|
from diet_guard._gatelock_typography import BODY, LABEL
|
||||||
|
from diet_guard._gatelock_ui import BG, FG
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
from diet_guard._gatelock_calendar_types import CalendarVars
|
||||||
|
|
||||||
|
__all__ = ["build_schedule_row"]
|
||||||
|
|
||||||
|
_ENTRY_WIDTH = 4
|
||||||
|
|
||||||
|
|
||||||
|
def _spin_entry(row: tk.Frame, variable: tk.StringVar) -> tk.Entry:
|
||||||
|
"""Return one read-only-by-default numeric entry in the schedule row."""
|
||||||
|
entry = tk.Entry(
|
||||||
|
row,
|
||||||
|
textvariable=variable,
|
||||||
|
font=(_COLORS.font_family, BODY),
|
||||||
|
width=_ENTRY_WIDTH,
|
||||||
|
bg=_FIELD_BG,
|
||||||
|
fg=FG,
|
||||||
|
insertbackground=FG,
|
||||||
|
justify="center",
|
||||||
|
state="readonly",
|
||||||
|
readonlybackground=_FIELD_BG,
|
||||||
|
)
|
||||||
|
entry.pack(side="left", padx=(XS, SM), ipady=XS)
|
||||||
|
return entry
|
||||||
|
|
||||||
|
|
||||||
|
def build_schedule_row(
|
||||||
|
parent: tk.Frame,
|
||||||
|
vars_: CalendarVars,
|
||||||
|
on_edit_or_save_schedule: Callable[[], None],
|
||||||
|
) -> tuple[tk.Entry, tk.Entry, tk.Entry, tk.Button, tk.Label]:
|
||||||
|
"""Build the meal-schedule row.
|
||||||
|
|
||||||
|
Returns the three hour/count entries, the edit button, and the status
|
||||||
|
label, in that order. Like the budget row the entries start read-only:
|
||||||
|
the schedule is displayed but not directly typeable until "Edit".
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``(first_entry, last_entry, count_entry, edit_button, status_label)``.
|
||||||
|
"""
|
||||||
|
row = tk.Frame(parent, bg=BG)
|
||||||
|
row.pack(pady=(SM, XS))
|
||||||
|
tk.Label(
|
||||||
|
row,
|
||||||
|
text="Meals:",
|
||||||
|
font=(_COLORS.font_family, LABEL),
|
||||||
|
bg=BG,
|
||||||
|
fg=FG,
|
||||||
|
).pack(side="left")
|
||||||
|
first_entry = _spin_entry(row, vars_.schedule.first)
|
||||||
|
tk.Label(
|
||||||
|
row,
|
||||||
|
text="to",
|
||||||
|
font=(_COLORS.font_family, LABEL),
|
||||||
|
bg=BG,
|
||||||
|
fg=FG,
|
||||||
|
).pack(side="left")
|
||||||
|
last_entry = _spin_entry(row, vars_.schedule.last)
|
||||||
|
tk.Label(
|
||||||
|
row,
|
||||||
|
text="x",
|
||||||
|
font=(_COLORS.font_family, LABEL),
|
||||||
|
bg=BG,
|
||||||
|
fg=FG,
|
||||||
|
).pack(side="left")
|
||||||
|
count_entry = _spin_entry(row, vars_.schedule.count)
|
||||||
|
edit_button = make_button(row, _COLORS, "Edit", on_edit_or_save_schedule)
|
||||||
|
edit_button.pack(side="left")
|
||||||
|
|
||||||
|
# The derived checkpoint times, so the effect of a change is visible
|
||||||
|
# before it is saved rather than only after the next lock.
|
||||||
|
tk.Label(
|
||||||
|
parent,
|
||||||
|
textvariable=vars_.schedule.times,
|
||||||
|
font=(_COLORS.font_family, LABEL),
|
||||||
|
bg=BG,
|
||||||
|
fg=FG,
|
||||||
|
).pack(pady=(0, XS))
|
||||||
|
status_label = tk.Label(
|
||||||
|
parent,
|
||||||
|
textvariable=vars_.schedule.status,
|
||||||
|
font=(_COLORS.font_family, LABEL),
|
||||||
|
bg=BG,
|
||||||
|
fg=FG,
|
||||||
|
)
|
||||||
|
status_label.pack(pady=(0, XS))
|
||||||
|
return first_entry, last_entry, count_entry, edit_button, status_label
|
||||||
@ -45,10 +45,27 @@ __all__ = [
|
|||||||
"CalendarCallbacks",
|
"CalendarCallbacks",
|
||||||
"CalendarVars",
|
"CalendarVars",
|
||||||
"CalendarWidgets",
|
"CalendarWidgets",
|
||||||
|
"ScheduleVars",
|
||||||
"make_calendar_vars",
|
"make_calendar_vars",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ScheduleVars:
|
||||||
|
"""Tk string variables backing the History tab's meal-schedule row.
|
||||||
|
|
||||||
|
Grouped rather than flattened into :class:`CalendarVars`, which would
|
||||||
|
otherwise carry eleven fields for two unrelated concerns.
|
||||||
|
"""
|
||||||
|
|
||||||
|
status: tk.StringVar
|
||||||
|
first: tk.StringVar
|
||||||
|
last: tk.StringVar
|
||||||
|
count: tk.StringVar
|
||||||
|
times: tk.StringVar
|
||||||
|
"""The derived checkpoint times, e.g. ``"08:00 11:00 14:00"``."""
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class CalendarVars:
|
class CalendarVars:
|
||||||
"""Tk string variables bound to the History tab's live fields."""
|
"""Tk string variables bound to the History tab's live fields."""
|
||||||
@ -60,6 +77,7 @@ class CalendarVars:
|
|||||||
budget_status: tk.StringVar
|
budget_status: tk.StringVar
|
||||||
budget: tk.StringVar
|
budget: tk.StringVar
|
||||||
"""Backs the budget entry so its per-monitor copies cannot disagree."""
|
"""Backs the budget entry so its per-monitor copies cannot disagree."""
|
||||||
|
schedule: ScheduleVars
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@ -71,6 +89,11 @@ class CalendarWidgets:
|
|||||||
budget_entry: tk.Entry
|
budget_entry: tk.Entry
|
||||||
budget_edit_button: tk.Button
|
budget_edit_button: tk.Button
|
||||||
budget_status_label: tk.Label
|
budget_status_label: tk.Label
|
||||||
|
schedule_first_entry: tk.Entry
|
||||||
|
schedule_last_entry: tk.Entry
|
||||||
|
schedule_count_entry: tk.Entry
|
||||||
|
schedule_edit_button: tk.Button
|
||||||
|
schedule_status_label: tk.Label
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@ -80,6 +103,7 @@ class CalendarCallbacks:
|
|||||||
on_prev_month: Callable[[], None]
|
on_prev_month: Callable[[], None]
|
||||||
on_next_month: Callable[[], None]
|
on_next_month: Callable[[], None]
|
||||||
on_edit_or_save_budget: Callable[[], None]
|
on_edit_or_save_budget: Callable[[], None]
|
||||||
|
on_edit_or_save_schedule: Callable[[], None]
|
||||||
|
|
||||||
|
|
||||||
def make_calendar_vars(root: tk.Misc) -> CalendarVars:
|
def make_calendar_vars(root: tk.Misc) -> CalendarVars:
|
||||||
@ -91,4 +115,11 @@ def make_calendar_vars(root: tk.Misc) -> CalendarVars:
|
|||||||
averages=tk.StringVar(master=root, value=""),
|
averages=tk.StringVar(master=root, value=""),
|
||||||
budget_status=tk.StringVar(master=root, value=""),
|
budget_status=tk.StringVar(master=root, value=""),
|
||||||
budget=tk.StringVar(master=root, value=""),
|
budget=tk.StringVar(master=root, value=""),
|
||||||
|
schedule=ScheduleVars(
|
||||||
|
status=tk.StringVar(master=root, value=""),
|
||||||
|
first=tk.StringVar(master=root, value=""),
|
||||||
|
last=tk.StringVar(master=root, value=""),
|
||||||
|
count=tk.StringVar(master=root, value=""),
|
||||||
|
times=tk.StringVar(master=root, value=""),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@ -20,6 +20,7 @@ from typing import TYPE_CHECKING
|
|||||||
|
|
||||||
from gatelock import ButtonStyle, make_button
|
from gatelock import ButtonStyle, make_button
|
||||||
|
|
||||||
|
from diet_guard._gatelock_calendar_schedule import build_schedule_row
|
||||||
from diet_guard._gatelock_calendar_types import (
|
from diet_guard._gatelock_calendar_types import (
|
||||||
_ACCENT,
|
_ACCENT,
|
||||||
_COLORS,
|
_COLORS,
|
||||||
@ -182,6 +183,17 @@ def build_calendar_frame(
|
|||||||
vars_,
|
vars_,
|
||||||
callbacks.on_edit_or_save_budget,
|
callbacks.on_edit_or_save_budget,
|
||||||
)
|
)
|
||||||
|
(
|
||||||
|
schedule_first_entry,
|
||||||
|
schedule_last_entry,
|
||||||
|
schedule_count_entry,
|
||||||
|
schedule_edit_button,
|
||||||
|
schedule_status_label,
|
||||||
|
) = build_schedule_row(
|
||||||
|
frame,
|
||||||
|
vars_,
|
||||||
|
callbacks.on_edit_or_save_schedule,
|
||||||
|
)
|
||||||
_build_month_nav(frame, vars_, callbacks)
|
_build_month_nav(frame, vars_, callbacks)
|
||||||
day_cells = _build_grid(frame)
|
day_cells = _build_grid(frame)
|
||||||
|
|
||||||
@ -213,4 +225,9 @@ def build_calendar_frame(
|
|||||||
budget_entry=budget_entry,
|
budget_entry=budget_entry,
|
||||||
budget_edit_button=budget_edit_button,
|
budget_edit_button=budget_edit_button,
|
||||||
budget_status_label=budget_status_label,
|
budget_status_label=budget_status_label,
|
||||||
|
schedule_first_entry=schedule_first_entry,
|
||||||
|
schedule_last_entry=schedule_last_entry,
|
||||||
|
schedule_count_entry=schedule_count_entry,
|
||||||
|
schedule_edit_button=schedule_edit_button,
|
||||||
|
schedule_status_label=schedule_status_label,
|
||||||
)
|
)
|
||||||
|
|||||||
152
diet_guard/_gatelock_scheduleedit.py
Normal file
152
diet_guard/_gatelock_scheduleedit.py
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
"""Meal-schedule editing on the gate's History tab.
|
||||||
|
|
||||||
|
Sibling of :mod:`._gatelock_budgetedit`, with the same edit/save toggle shape:
|
||||||
|
the row displays the schedule read-only, "Edit" unlocks it, "Save" validates
|
||||||
|
and persists. ``_GateScheduleEdit`` sits between
|
||||||
|
:class:`~diet_guard._gatelock_budgetedit._GateBudgetEdit` and
|
||||||
|
:class:`~diet_guard._gatelock_calendar._GateCalendar` in the mixin chain.
|
||||||
|
|
||||||
|
Editing here changes what the gate itself asks for, so the value is validated
|
||||||
|
before it is written rather than relying on
|
||||||
|
:meth:`~diet_guard._meal_schedule.MealSchedule.normalized` to clamp it. The
|
||||||
|
clamp is the defence against a peer's corrupt sync data; a typo at the
|
||||||
|
keyboard should say so instead of silently becoming a different schedule.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import abc
|
||||||
|
import contextlib
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from diet_guard._gatelock_budgetedit import _GateBudgetEdit
|
||||||
|
from diet_guard._gatelock_ui import ERR, FG
|
||||||
|
from diet_guard._meal_schedule import (
|
||||||
|
FIRST_HOUR,
|
||||||
|
LAST_HOUR,
|
||||||
|
MAX_MEAL_COUNT,
|
||||||
|
MIN_MEAL_COUNT,
|
||||||
|
MealSchedule,
|
||||||
|
)
|
||||||
|
from diet_guard._meal_schedule_store import current_schedule, record_schedule_change
|
||||||
|
from diet_guard._slots import day_slots, slot_label
|
||||||
|
|
||||||
|
__all__ = ["_GateScheduleEdit", "schedule_summary"]
|
||||||
|
|
||||||
|
|
||||||
|
def schedule_summary(schedule: MealSchedule) -> str:
|
||||||
|
"""Return the derived checkpoint times, e.g. ``"08:00 11:00 ..."``."""
|
||||||
|
return " ".join(slot_label(slot) for slot in day_slots(schedule))
|
||||||
|
|
||||||
|
|
||||||
|
class _GateScheduleEdit(_GateBudgetEdit):
|
||||||
|
"""The History tab's meal-schedule row: display, edit, validate, persist.
|
||||||
|
|
||||||
|
Like :class:`~diet_guard._gatelock_budgetedit._GateBudgetEdit`, this half
|
||||||
|
only reads and writes its own row; the tab's construction and refresh are
|
||||||
|
owned by :class:`~diet_guard._gatelock_calendar._GateCalendar`, further
|
||||||
|
down the mixin chain.
|
||||||
|
"""
|
||||||
|
|
||||||
|
_cal_editing_schedule: bool
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def _refresh_calendar(self) -> None:
|
||||||
|
"""Repaint the History tab; implemented by ``_GateCalendar``."""
|
||||||
|
|
||||||
|
def _set_schedule_entry_state(self, state: str) -> None:
|
||||||
|
"""Lock or unlock the three schedule entries on every monitor."""
|
||||||
|
for surface in self._cal_surfaces:
|
||||||
|
with contextlib.suppress(tk.TclError):
|
||||||
|
surface.schedule_first_entry.config(state=state)
|
||||||
|
surface.schedule_last_entry.config(state=state)
|
||||||
|
surface.schedule_count_entry.config(state=state)
|
||||||
|
|
||||||
|
def _set_schedule_button_text(self, text: str) -> None:
|
||||||
|
"""Relabel the schedule edit/save button on every monitor."""
|
||||||
|
for surface in self._cal_surfaces:
|
||||||
|
with contextlib.suppress(tk.TclError):
|
||||||
|
surface.schedule_edit_button.config(text=text)
|
||||||
|
|
||||||
|
def _set_schedule_status(self, text: str, *, error: bool) -> None:
|
||||||
|
"""Update the schedule-edit status line, red for errors."""
|
||||||
|
self._cal_vars.schedule.status.set(text)
|
||||||
|
colour = ERR if error else FG
|
||||||
|
for surface in self._cal_surfaces:
|
||||||
|
with contextlib.suppress(tk.TclError):
|
||||||
|
surface.schedule_status_label.config(fg=colour)
|
||||||
|
|
||||||
|
def _show_schedule(self, schedule: MealSchedule) -> None:
|
||||||
|
"""Populate the row's fields and derived-times label."""
|
||||||
|
self._cal_vars.schedule.first.set(str(schedule.first))
|
||||||
|
self._cal_vars.schedule.last.set(str(schedule.last))
|
||||||
|
self._cal_vars.schedule.count.set(str(schedule.count))
|
||||||
|
self._cal_vars.schedule.times.set(schedule_summary(schedule))
|
||||||
|
|
||||||
|
def _on_edit_or_save_schedule(self) -> None:
|
||||||
|
"""Toggle the schedule row between read-only display and editing.
|
||||||
|
|
||||||
|
Mirrors :meth:`_GateBudgetEdit._on_edit_or_save_budget`: a failed
|
||||||
|
validation leaves editing open so the value can be corrected rather
|
||||||
|
than silently discarded.
|
||||||
|
"""
|
||||||
|
if not self._cal_editing_schedule:
|
||||||
|
self._cal_editing_schedule = True
|
||||||
|
self._set_schedule_entry_state("normal")
|
||||||
|
self._set_schedule_button_text("Save")
|
||||||
|
self._set_schedule_status("", error=False)
|
||||||
|
return
|
||||||
|
if not self._save_schedule_entry():
|
||||||
|
return
|
||||||
|
self._cal_editing_schedule = False
|
||||||
|
self._set_schedule_entry_state("readonly")
|
||||||
|
self._set_schedule_button_text("Edit")
|
||||||
|
self._refresh_calendar()
|
||||||
|
|
||||||
|
def _read_schedule_fields(self) -> MealSchedule | None:
|
||||||
|
"""Parse the three entries, or None (with a status set) if unusable."""
|
||||||
|
raw = (
|
||||||
|
self._cal_vars.schedule.first.get().strip(),
|
||||||
|
self._cal_vars.schedule.last.get().strip(),
|
||||||
|
self._cal_vars.schedule.count.get().strip(),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
first, last, count = (int(value) for value in raw)
|
||||||
|
except ValueError:
|
||||||
|
self._set_schedule_status("Enter whole hours, e.g. 8 20 5.", error=True)
|
||||||
|
return None
|
||||||
|
return MealSchedule(first, last, count)
|
||||||
|
|
||||||
|
def _save_schedule_entry(self) -> bool:
|
||||||
|
"""Validate and persist the row's current values.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Whether the schedule was valid and persisted.
|
||||||
|
"""
|
||||||
|
schedule = self._read_schedule_fields()
|
||||||
|
if schedule is None:
|
||||||
|
return False
|
||||||
|
if not FIRST_HOUR <= schedule.first < schedule.last <= LAST_HOUR:
|
||||||
|
self._set_schedule_status(
|
||||||
|
f"First meal must be before the last, both {FIRST_HOUR}-{LAST_HOUR}.",
|
||||||
|
error=True,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
if not MIN_MEAL_COUNT <= schedule.count <= MAX_MEAL_COUNT:
|
||||||
|
self._set_schedule_status(
|
||||||
|
f"Meals per day must be {MIN_MEAL_COUNT}-{MAX_MEAL_COUNT}.",
|
||||||
|
error=True,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
# A window of N hours holds at most N+1 whole-hour checkpoints; asking
|
||||||
|
# for more would round two meals onto the same hour.
|
||||||
|
if schedule.count > schedule.last - schedule.first + 1:
|
||||||
|
self._set_schedule_status(
|
||||||
|
"Too many meals for that window -- widen it or eat less often.",
|
||||||
|
error=True,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
record_schedule_change(schedule)
|
||||||
|
self._show_schedule(current_schedule())
|
||||||
|
self._set_schedule_status("Saved.", error=False)
|
||||||
|
return True
|
||||||
@ -25,6 +25,7 @@ from diet_guard import (
|
|||||||
_gatelock,
|
_gatelock,
|
||||||
_gatelock_budgetedit,
|
_gatelock_budgetedit,
|
||||||
_gatelock_calendar,
|
_gatelock_calendar,
|
||||||
|
_gatelock_calendar_schedule,
|
||||||
_gatelock_calendar_types,
|
_gatelock_calendar_types,
|
||||||
_gatelock_calendar_ui,
|
_gatelock_calendar_ui,
|
||||||
_gatelock_calendar_widgets,
|
_gatelock_calendar_widgets,
|
||||||
@ -33,6 +34,7 @@ from diet_guard import (
|
|||||||
_gatelock_layout,
|
_gatelock_layout,
|
||||||
_gatelock_mealflow,
|
_gatelock_mealflow,
|
||||||
_gatelock_nutrition,
|
_gatelock_nutrition,
|
||||||
|
_gatelock_scheduleedit,
|
||||||
_gatelock_ui,
|
_gatelock_ui,
|
||||||
)
|
)
|
||||||
from diet_guard._gatelock import MealGate
|
from diet_guard._gatelock import MealGate
|
||||||
@ -155,11 +157,14 @@ _GATE_TK_MODULES = (
|
|||||||
# separately in fake_tk(). Listing it here fails with "does not have the
|
# separately in fake_tk(). Listing it here fails with "does not have the
|
||||||
# attribute 'tk'".
|
# attribute 'tk'".
|
||||||
_gatelock_calendar_widgets,
|
_gatelock_calendar_widgets,
|
||||||
|
# The History tab's meal-schedule row builds its own tk widgets.
|
||||||
|
_gatelock_calendar_schedule,
|
||||||
# Builds the History tab's StringVars (make_calendar_vars); without the
|
# Builds the History tab's StringVars (make_calendar_vars); without the
|
||||||
# fake those are REAL tkinter vars over a MagicMock root, so every
|
# fake those are REAL tkinter vars over a MagicMock root, so every
|
||||||
# `.get()` returns a MagicMock instead of the text under test.
|
# `.get()` returns a MagicMock instead of the text under test.
|
||||||
_gatelock_calendar_types,
|
_gatelock_calendar_types,
|
||||||
_gatelock_budgetedit,
|
_gatelock_budgetedit,
|
||||||
|
_gatelock_scheduleedit,
|
||||||
_gatelock_core,
|
_gatelock_core,
|
||||||
_gatelock_fields,
|
_gatelock_fields,
|
||||||
_gatelock_layout,
|
_gatelock_layout,
|
||||||
|
|||||||
145
diet_guard/tests/test_gatelock_scheduleedit.py
Normal file
145
diet_guard/tests/test_gatelock_scheduleedit.py
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
"""Tests for the gate History tab's meal-schedule row.
|
||||||
|
|
||||||
|
Covers :mod:`._gatelock_scheduleedit`. The functional fake ``tk`` widgets and
|
||||||
|
the ``gate`` fixture live in ``conftest.py``, shared with the other gate
|
||||||
|
tests.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from diet_guard._gatelock_scheduleedit import schedule_summary
|
||||||
|
from diet_guard._meal_schedule import DEFAULT_SCHEDULE, MealSchedule
|
||||||
|
from diet_guard._meal_schedule_store import current_schedule, record_schedule_change
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from diet_guard._gatelock import MealGate
|
||||||
|
|
||||||
|
|
||||||
|
def _type(gate: MealGate, first: str, last: str, count: str) -> None:
|
||||||
|
"""Fill the three schedule entries as the user would."""
|
||||||
|
gate._cal_vars.schedule.first.set(first)
|
||||||
|
gate._cal_vars.schedule.last.set(last)
|
||||||
|
gate._cal_vars.schedule.count.set(count)
|
||||||
|
|
||||||
|
|
||||||
|
class TestScheduleSummary:
|
||||||
|
"""The derived-times label."""
|
||||||
|
|
||||||
|
def test_lists_every_checkpoint(self) -> None:
|
||||||
|
"""The label spells out the hours the schedule derives."""
|
||||||
|
assert schedule_summary(MealSchedule(8, 20, 5)) == (
|
||||||
|
"08:00 11:00 14:00 17:00 20:00"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestEditToggle:
|
||||||
|
"""The Edit/Save button's two states."""
|
||||||
|
|
||||||
|
def test_first_click_unlocks_without_saving(self, gate: MealGate) -> None:
|
||||||
|
"""Clicking Edit opens the fields but persists nothing yet."""
|
||||||
|
gate._on_edit_or_save_schedule()
|
||||||
|
|
||||||
|
assert gate._cal_editing_schedule
|
||||||
|
assert current_schedule() == DEFAULT_SCHEDULE
|
||||||
|
|
||||||
|
def test_second_click_persists_and_relocks(self, gate: MealGate) -> None:
|
||||||
|
"""Clicking Save validates, writes, and returns to read-only."""
|
||||||
|
gate._on_edit_or_save_schedule()
|
||||||
|
_type(gate, "8", "20", "5")
|
||||||
|
gate._on_edit_or_save_schedule()
|
||||||
|
|
||||||
|
assert not gate._cal_editing_schedule
|
||||||
|
assert current_schedule() == MealSchedule(8, 20, 5)
|
||||||
|
assert gate._cal_vars.schedule.status.get() == "Saved."
|
||||||
|
|
||||||
|
def test_a_failed_save_leaves_editing_open(self, gate: MealGate) -> None:
|
||||||
|
"""A bad value can be corrected rather than silently discarded."""
|
||||||
|
gate._on_edit_or_save_schedule()
|
||||||
|
_type(gate, "20", "8", "4")
|
||||||
|
gate._on_edit_or_save_schedule()
|
||||||
|
|
||||||
|
assert gate._cal_editing_schedule
|
||||||
|
assert current_schedule() == DEFAULT_SCHEDULE
|
||||||
|
|
||||||
|
|
||||||
|
class TestValidation:
|
||||||
|
"""Rejected input, with the reason shown rather than silently clamped."""
|
||||||
|
|
||||||
|
def test_rejects_non_numeric(self, gate: MealGate) -> None:
|
||||||
|
"""Letters in an hour field are refused, not coerced."""
|
||||||
|
_type(gate, "eight", "20", "4")
|
||||||
|
|
||||||
|
assert not gate._save_schedule_entry()
|
||||||
|
assert "whole hours" in gate._cal_vars.schedule.status.get()
|
||||||
|
|
||||||
|
def test_rejects_a_backwards_window(self, gate: MealGate) -> None:
|
||||||
|
"""The last meal must come after the first."""
|
||||||
|
_type(gate, "20", "8", "4")
|
||||||
|
|
||||||
|
assert not gate._save_schedule_entry()
|
||||||
|
assert "before the last" in gate._cal_vars.schedule.status.get()
|
||||||
|
|
||||||
|
def test_rejects_an_out_of_range_hour(self, gate: MealGate) -> None:
|
||||||
|
"""Hours outside 0-23 are refused."""
|
||||||
|
_type(gate, "8", "25", "4")
|
||||||
|
|
||||||
|
assert not gate._save_schedule_entry()
|
||||||
|
assert "0-23" in gate._cal_vars.schedule.status.get()
|
||||||
|
|
||||||
|
def test_rejects_too_few_meals(self, gate: MealGate) -> None:
|
||||||
|
"""One meal a day is below the supported range."""
|
||||||
|
_type(gate, "8", "20", "1")
|
||||||
|
|
||||||
|
assert not gate._save_schedule_entry()
|
||||||
|
assert "Meals per day" in gate._cal_vars.schedule.status.get()
|
||||||
|
|
||||||
|
def test_rejects_too_many_meals(self, gate: MealGate) -> None:
|
||||||
|
"""More than the cap is refused."""
|
||||||
|
_type(gate, "8", "20", "9")
|
||||||
|
|
||||||
|
assert not gate._save_schedule_entry()
|
||||||
|
assert "Meals per day" in gate._cal_vars.schedule.status.get()
|
||||||
|
|
||||||
|
def test_rejects_more_meals_than_the_window_holds(self, gate: MealGate) -> None:
|
||||||
|
"""A narrow window cannot hold six distinct whole-hour checkpoints.
|
||||||
|
|
||||||
|
Without this the derivation would round two meals onto the same hour,
|
||||||
|
and a duplicate slot silently drops a checkpoint.
|
||||||
|
"""
|
||||||
|
_type(gate, "8", "11", "6")
|
||||||
|
|
||||||
|
assert not gate._save_schedule_entry()
|
||||||
|
assert "Too many meals" in gate._cal_vars.schedule.status.get()
|
||||||
|
|
||||||
|
|
||||||
|
class TestDisplay:
|
||||||
|
"""Showing the stored schedule in the row."""
|
||||||
|
|
||||||
|
def test_shows_the_stored_schedule(self, gate: MealGate) -> None:
|
||||||
|
"""The fields and the derived-times label reflect what is stored."""
|
||||||
|
gate._show_schedule(MealSchedule(7, 21, 3))
|
||||||
|
|
||||||
|
assert gate._cal_vars.schedule.first.get() == "7"
|
||||||
|
assert gate._cal_vars.schedule.last.get() == "21"
|
||||||
|
assert gate._cal_vars.schedule.count.get() == "3"
|
||||||
|
assert gate._cal_vars.schedule.times.get() == "07:00 14:00 21:00"
|
||||||
|
|
||||||
|
def test_a_refresh_does_not_clobber_an_open_edit(self, gate: MealGate) -> None:
|
||||||
|
"""Typing survives a calendar refresh landing mid-edit."""
|
||||||
|
gate._on_edit_or_save_schedule()
|
||||||
|
_type(gate, "6", "22", "6")
|
||||||
|
gate._refresh_calendar()
|
||||||
|
|
||||||
|
assert gate._cal_vars.schedule.first.get() == "6"
|
||||||
|
|
||||||
|
def test_a_refresh_shows_the_stored_schedule_when_idle(
|
||||||
|
self, gate: MealGate
|
||||||
|
) -> None:
|
||||||
|
"""Outside an edit the row tracks whatever is stored."""
|
||||||
|
record_schedule_change(MealSchedule(9, 19, 3))
|
||||||
|
gate._refresh_calendar()
|
||||||
|
|
||||||
|
assert gate._cal_vars.schedule.first.get() == "9"
|
||||||
|
assert gate._cal_vars.schedule.times.get() == "09:00 14:00 19:00"
|
||||||
Loading…
Reference in New Issue
Block a user