Quest windows via quest_definition_windows (D-008)
Per IMPLEMENTATION-ORDER.md 1.4: a quest_definition_windows table (definition_id, window, due_time) declares which day windows a definition spans, one row per definition+window via the composite primary key; window is CHECK-constrained to morning/afternoon/evening. - const.py: WINDOW_MORNING/AFTERNOON/EVENING, QUEST_WINDOWS canonical order, WINDOW_CLOCK_RANGES with the documented boundaries and the boundary-to-later-window rule documented for Feature 07. - schema.py: windows DDL joins SCHEMA_V1_STATEMENTS; due_time is caller-validated strict HH:MM (DAO layer), matching the date policy. - migrations.py: migration 4 is a plain CREATE IF NOT EXISTS statement list (no rebuild needed for a new table). - dao_rules.py: QuestDefinitionsDao gains upsert_window (idempotent per window, due_time refresh in place), list_windows (const order), remove_window; _validate_time/_validate_window helpers. - tests: windows DDL shape/constraints (CHECK matrix, duplicate, unknown definition), DAO round-trips, const range shapes; leak guards extended to the new table.
This commit is contained in:
@@ -20,3 +20,28 @@ DEFAULT_DAY_ROLLOVER_TIME = "00:00"
|
||||
|
||||
CONF_PANEL_IDLE_TIMEOUT = "panel_idle_timeout"
|
||||
DEFAULT_PANEL_IDLE_TIMEOUT = 300
|
||||
|
||||
# Quest windows (D-008): a definition may declare several day windows;
|
||||
# each produces its own instance per day and groups the panel's Quest
|
||||
# Log into three columns. The clock ranges are stored here so they stay
|
||||
# configurable later. Boundaries: a window's end equals the next
|
||||
# window's start; classification (Feature 07 materialisation) treats a
|
||||
# due time exactly on the boundary as belonging to the LATER window, so
|
||||
# 12:00 is afternoon (not morning) and 17:00 is evening (not
|
||||
# afternoon). Times after 21:00 belong to no window.
|
||||
WINDOW_MORNING = "morning"
|
||||
WINDOW_AFTERNOON = "afternoon"
|
||||
WINDOW_EVENING = "evening"
|
||||
|
||||
QUEST_WINDOWS: tuple[str, ...] = (
|
||||
WINDOW_MORNING,
|
||||
WINDOW_AFTERNOON,
|
||||
WINDOW_EVENING,
|
||||
)
|
||||
|
||||
#: Inclusive "HH:MM" bounds per window, in 24-hour local time.
|
||||
WINDOW_CLOCK_RANGES: dict[str, tuple[str, str]] = {
|
||||
WINDOW_MORNING: ("00:00", "11:59"),
|
||||
WINDOW_AFTERNOON: ("12:00", "17:00"),
|
||||
WINDOW_EVENING: ("17:00", "21:00"),
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ from __future__ import annotations
|
||||
import datetime
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .const import QUEST_WINDOWS
|
||||
from .dao_children import ChildRecord, _child_from_row, _connection_lock
|
||||
from .dao_children import _CHILD_COLUMNS
|
||||
from .db import NestQuestDatabase
|
||||
@@ -71,6 +72,38 @@ def _validate_date(value: str, field: str) -> None:
|
||||
)
|
||||
|
||||
|
||||
_TIME_FORMAT = "%H:%M"
|
||||
|
||||
|
||||
def _validate_time(value: str, field: str) -> None:
|
||||
"""Raise ValueError unless ``value`` is a strict 24-hour HH:MM.
|
||||
|
||||
Same strictness policy as _validate_date: parse with the exact
|
||||
format, then round-trip so '9:30' (non-padded) is rejected. Time
|
||||
shapes are caller-side policy (the schema stores TEXT): windows'
|
||||
optional ``due_time`` and definition ``due_time`` both use this.
|
||||
"""
|
||||
try:
|
||||
parsed = datetime.datetime.strptime(value, _TIME_FORMAT).time()
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(
|
||||
f"{field} must be a 24-hour HH:MM time, got {value!r}"
|
||||
) from None
|
||||
if parsed.strftime(_TIME_FORMAT) != value:
|
||||
raise ValueError(
|
||||
f"{field} must be a strict HH:MM time, got {value!r}"
|
||||
)
|
||||
|
||||
|
||||
def _validate_window(window: str) -> None:
|
||||
"""Raise ValueError unless ``window`` is a ``const`` window name."""
|
||||
if window not in QUEST_WINDOWS:
|
||||
raise ValueError(
|
||||
f"window must be one of {', '.join(QUEST_WINDOWS)}, "
|
||||
f"got {window!r}"
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScheduleRuleRecord:
|
||||
"""One row of ``schedule_rules``."""
|
||||
@@ -100,6 +133,15 @@ class QuestDefinitionRecord:
|
||||
created_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class QuestDefinitionWindowRecord:
|
||||
"""One row of ``quest_definition_windows``."""
|
||||
|
||||
definition_id: int
|
||||
window: str
|
||||
due_time: str | None
|
||||
|
||||
|
||||
_RULE_COLUMNS = (
|
||||
"id, rule_type, interval, weekday_set, day_of_month, nth_weekday, "
|
||||
"month, start_date, end_date"
|
||||
@@ -108,6 +150,7 @@ _DEFINITION_COLUMNS = (
|
||||
"id, title, description, icon, schedule_rule_id, due_time, "
|
||||
"is_active, created_at"
|
||||
)
|
||||
_WINDOW_COLUMNS = "definition_id, window, due_time"
|
||||
|
||||
|
||||
def _rule_from_row(row: tuple) -> ScheduleRuleRecord:
|
||||
@@ -137,6 +180,14 @@ def _definition_from_row(row: tuple) -> QuestDefinitionRecord:
|
||||
)
|
||||
|
||||
|
||||
def _window_from_row(row: tuple) -> QuestDefinitionWindowRecord:
|
||||
return QuestDefinitionWindowRecord(
|
||||
definition_id=row[0],
|
||||
window=row[1],
|
||||
due_time=row[2],
|
||||
)
|
||||
|
||||
|
||||
class ScheduleRulesDao:
|
||||
"""Typed async access to the ``schedule_rules`` table."""
|
||||
|
||||
@@ -507,6 +558,92 @@ class QuestDefinitionsDao:
|
||||
)
|
||||
return [_child_from_row(row) for row in rows]
|
||||
|
||||
async def upsert_window(
|
||||
self,
|
||||
definition_id: int,
|
||||
window: str,
|
||||
*,
|
||||
due_time: str | None = None,
|
||||
) -> QuestDefinitionWindowRecord:
|
||||
"""Declare (or re-declare) ``window`` on the definition.
|
||||
|
||||
The composite primary key makes the write idempotent per
|
||||
(definition, window): re-declaring updates ``due_time`` in
|
||||
place instead of duplicating. The window name must be one of
|
||||
``const.QUEST_WINDOWS`` (the schema CHECK backs this up) and a
|
||||
provided ``due_time`` must be strict 24-hour HH:MM. The
|
||||
definition must exist — validated under the connection lock so
|
||||
the verdict cannot go stale before the write.
|
||||
"""
|
||||
_validate_window(window)
|
||||
if due_time is not None:
|
||||
_validate_time(due_time, "due_time")
|
||||
async with _connection_lock(self._database):
|
||||
async with self._database.transaction():
|
||||
definition = await self._database.fetch_one(
|
||||
"SELECT 1 FROM quest_definitions WHERE id = ?",
|
||||
(definition_id,),
|
||||
)
|
||||
if definition is None:
|
||||
raise ValueError(
|
||||
f"quest definition {definition_id} does not exist"
|
||||
)
|
||||
await self._database.execute(
|
||||
"INSERT INTO quest_definition_windows "
|
||||
"(definition_id, window, due_time) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT (definition_id, window) DO UPDATE SET "
|
||||
"due_time = excluded.due_time",
|
||||
(definition_id, window, due_time),
|
||||
)
|
||||
row = await self._database.fetch_one(
|
||||
f"SELECT {_WINDOW_COLUMNS} "
|
||||
"FROM quest_definition_windows "
|
||||
"WHERE definition_id = ? AND window = ?",
|
||||
(definition_id, window),
|
||||
)
|
||||
assert row is not None
|
||||
return _window_from_row(row)
|
||||
|
||||
async def list_windows(
|
||||
self, definition_id: int
|
||||
) -> list[QuestDefinitionWindowRecord]:
|
||||
"""Return the definition's windows in ``const`` order.
|
||||
|
||||
Ordered by the canonical window sequence (morning, afternoon,
|
||||
evening) rather than insertion order, so callers always render
|
||||
the Quest Log's three columns consistently. A definition with
|
||||
no windows returns [].
|
||||
"""
|
||||
rows = await self._database.fetch_all(
|
||||
f"SELECT {_WINDOW_COLUMNS} FROM quest_definition_windows "
|
||||
"WHERE definition_id = ?",
|
||||
(definition_id,),
|
||||
)
|
||||
by_name = {row[1]: _window_from_row(row) for row in rows}
|
||||
return [
|
||||
by_name[name]
|
||||
for name in QUEST_WINDOWS
|
||||
if name in by_name
|
||||
]
|
||||
|
||||
async def remove_window(
|
||||
self, definition_id: int, window: str
|
||||
) -> bool:
|
||||
"""Remove the window declaration; True when a row was removed.
|
||||
|
||||
Future materialization stops producing instances for this
|
||||
(definition, window); existing instances and completion history
|
||||
are never touched here (Feature 06 guardrail).
|
||||
"""
|
||||
_validate_window(window)
|
||||
async with _connection_lock(self._database):
|
||||
result = await self._database.execute(
|
||||
"DELETE FROM quest_definition_windows "
|
||||
"WHERE definition_id = ? AND window = ?",
|
||||
(definition_id, window),
|
||||
)
|
||||
return result.rowcount > 0
|
||||
|
||||
async def _validate_assignable_child(self, child_id: int) -> None:
|
||||
"""Raise ValueError unless the child exists and is active.
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@ from .schema import (
|
||||
QUEST_DEFINITIONS_TABLE_SQL,
|
||||
SCHEMA_V1_STATEMENTS,
|
||||
SCHEMA_V1_QUEST_DEFINITION_ASSIGNEES_DDL,
|
||||
SCHEMA_V1_QUEST_DEFINITION_WINDOWS_DDL,
|
||||
)
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
@@ -256,6 +257,10 @@ MIGRATIONS: Sequence[MigrationStep] = [
|
||||
MIGRATION_1_V1_DDL,
|
||||
_rename_legacy_task_tables,
|
||||
_add_definition_assignees,
|
||||
# Migration 4 (D-008): the windows table is a plain new table — a
|
||||
# CREATE IF NOT EXISTS suffices for both fresh databases (which
|
||||
# already made it in migration 1) and pre-window databases.
|
||||
list(SCHEMA_V1_QUEST_DEFINITION_WINDOWS_DDL),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -95,6 +95,15 @@ migration runner rebuilds a pre-D-008 table into this shape and copies
|
||||
its single-assignee column across. The composite primary key makes
|
||||
duplicate assignment impossible at the storage layer.
|
||||
|
||||
Quest windows (D-008): ``quest_definition_windows`` declares which day
|
||||
windows a definition spans — one row per (definition, window), the
|
||||
composite primary key making a window idempotent per definition.
|
||||
``window`` is CHECK-constrained to the three spellings ``const`` owns;
|
||||
``due_time`` optionally pins a due time inside the window and is
|
||||
caller-validated (strict HH:MM) by the DAO layer, matching the date
|
||||
policy above. The window clock ranges live in ``const.py``, not here:
|
||||
this layer stores what the caller declares and never interprets clocks.
|
||||
|
||||
Quest instances: ``quest_instances`` deliberately carries NO completion
|
||||
status column. An instance's current state derives from the latest row
|
||||
in ``completion_events`` (Feature 08), so materialization (Feature 07)
|
||||
@@ -260,6 +269,17 @@ SCHEMA_V1_QUEST_DEFINITION_ASSIGNEES_DDL: list[str] = [
|
||||
""",
|
||||
]
|
||||
|
||||
SCHEMA_V1_QUEST_DEFINITION_WINDOWS_DDL: list[str] = [
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS quest_definition_windows (
|
||||
definition_id INTEGER NOT NULL REFERENCES quest_definitions(id),
|
||||
window TEXT NOT NULL CHECK (window IN ('morning', 'afternoon', 'evening')),
|
||||
due_time TEXT,
|
||||
PRIMARY KEY (definition_id, window)
|
||||
)
|
||||
""",
|
||||
]
|
||||
|
||||
SCHEMA_V1_PRESENCE_SCHEDULES_DDL: list[str] = [
|
||||
f"""
|
||||
CREATE TABLE IF NOT EXISTS presence_schedules (
|
||||
@@ -342,6 +362,7 @@ SCHEMA_V1_STATEMENTS: list[str] = [
|
||||
*SCHEMA_V1_SCHEDULE_RULES_DDL,
|
||||
*SCHEMA_V1_QUEST_DEFINITIONS_DDL,
|
||||
*SCHEMA_V1_QUEST_DEFINITION_ASSIGNEES_DDL,
|
||||
*SCHEMA_V1_QUEST_DEFINITION_WINDOWS_DDL,
|
||||
*SCHEMA_V1_PRESENCE_SCHEDULES_DDL,
|
||||
*SCHEMA_V1_PRESENCE_OVERRIDES_DDL,
|
||||
*SCHEMA_V1_QUEST_INSTANCES_DDL,
|
||||
|
||||
Reference in New Issue
Block a user