Compare commits

..
Author SHA1 Message Date
overseerandClaude Opus 5.5 bc20a3a2be Export the History tab's filtered range as CSV
Wire the CSV button to GET /api/v1/admin/history.csv through apiFetch
(token in the Authorization header) with the active filter and the
displayed start/end. The response is offered as a download via a blob
URL and a temporary anchor using the Content-Disposition filename
(falling back to nestquest-history-<start>-to-<end>.csv), then the URL
is revoked and the anchor removed. The button is disabled while the
request is in flight, and a failure shows a dismissible, non-blocking
message.

Task: e5133d0f-b373-4fcd-b666-6c77dfa49b98

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 23:28:04 -04:00
dev_agent bc3e64b4f8 Task 9b9188b8: History tab - filters, rows, stats and footer (#208) 2026-09-23 23:26:03 -04:00
dev_agent cc970bb646 Task 4ae0c879: Presence override with live consequence count (#207) 2026-09-23 23:16:04 -04:00
dev_agent 7b5177d055 Task d96d8925: Presence schedule month grid (#206) 2026-09-23 22:51:16 -04:00
dev_agent a22f990bd6 Task b50b048f: Lucide icon picker (shipped subset) (#205) 2026-09-23 22:39:25 -04:00
dev_agent 4b56e2f68a Task 85b2f166: Recurrence occurrence preview (#204) 2026-09-23 22:30:04 -04:00
overseer d0c236b569 Merge dev into feature/24ce7ebf (Feature 23: admin API completion) 2026-09-23 22:17:08 -04:00
dev_agent 33d8e0d2ac Task 2e96585c: Definitions list and edit sheet (#198) 2026-09-23 21:26:27 -04:00
overseer dbe873eb2a Merge dev into feature/24ce7ebf (Feature 22 follow-up: editable assignees) 2026-09-23 21:11:21 -04:00
overseer 706a7954d8 Merge dev into feature/24ce7ebf (Feature 22: definitions read + skip_on_away) 2026-09-23 20:52:48 -04:00
dev_agent be4fd04754 Task e0a2b862: Today tab (#192) 2026-09-23 20:13:52 -04:00
overseer 4ff40f00a2 Merge dev into feature/24ce7ebf (bring the Feature 21 admin snapshot route) 2026-09-23 20:03:05 -04:00
dev_agent f476821e8e Task 96ab3c0b: PWA manifest and service worker (#189) 2026-09-23 19:42:27 -04:00
dev_agent 75ad9892b8 Task 630c3472: Authentik OIDC PKCE login and refusal handling (#188) 2026-09-23 18:30:07 -04:00
dev_agent 48d0c4ef86 Task 0df715b5: React scaffold, build and serve (#187) 2026-09-23 16:39:36 -04:00
161 changed files with 3166 additions and 25065 deletions
-27
View File
@@ -1,27 +0,0 @@
# Keep the image build context minimal: only api/ and the bundled
# custom_components/nestquest/core/ are copied (see the Dockerfile);
# everything else — VCS state, virtualenvs, tests, the frontend, and
# any local secrets or database files — never enters the build.
.git
.gitignore
.venv
**/__pycache__
**/*.py[cod]
.pytest_cache
**/*.db
**/*.db-wal
**/*.db-shm
# Local configuration — never baked into an image.
.env
**/.env
deploy
design
docs
frontend
orchestration_tests
scripts
templates
tests
uv.lock
hacs.json
*.md
-13
View File
@@ -5,16 +5,3 @@ __pycache__/
.pytest_cache/
*.metadata.json
frontend/node_modules/
# Feature 17 (API deployment): local secret config and runtime data
# are never committed — compose reads deploy/.env; SQLite/WAL sidecar
# files are container/volume artifacts.
.env
**/.env
*.db
*.db-wal
*.db-shm
# Dedicated Litestream SFTP backup keypair — lives only on the API box.
deploy/*key*
deploy/litestream_key*
-51
View File
@@ -1,51 +0,0 @@
# Container image for the NestQuest API service (Feature 17).
#
# Build context is the REPOSITORY ROOT (compose sets it), because the
# API loads the bundled domain layer from
# custom_components/nestquest/core/ by file location
# (api/nestquest_core.py): the image must carry both api/ and the
# bundled core at their relative positions. Everything else in the
# repository is excluded via .dockerignore.
#
# Multi-stage so no pip/build toolchain survives into the runtime:
# the builder installs the deployable's own manifest
# (api/requirements.txt) into a staging prefix and the runtime copies
# only the installed packages. The service runs as a non-root user;
# the SQLite database lives on the mounted volume at
# /var/lib/nestquest (compose supplies NESTQUEST_DB_PATH pointing
# there — configuration is environment-supplied, never baked in).
#
# Both stages use the same base image pinned by digest, and
# api/requirements.txt pins exact versions, so a rebuild reproduces
# the deployed image instead of floating to whatever is newest.
FROM python:3.12-slim@sha256:2f17fc044b579bab302c2e8054d3a686e2cb9a83de48e70534b94cd8ebbe06a9 AS builder
COPY api/requirements.txt /tmp/requirements.txt
RUN pip install --no-cache-dir --prefix=/install -r /tmp/requirements.txt
FROM python:3.12-slim@sha256:2f17fc044b579bab302c2e8054d3a686e2cb9a83de48e70534b94cd8ebbe06a9
# The staged dependency install from the builder (no pip, no wheels).
COPY --from=builder /install /usr/local
# /app is the repository-root equivalent: api/ resolves imports as
# ``api.*`` and nestquest_core.py finds the bundled core one level up.
WORKDIR /app
COPY api/ ./api/
COPY custom_components/nestquest/core/ ./custom_components/nestquest/core/
# Non-root runtime user; owns the database volume mount point.
RUN useradd --system --create-home --home-dir /home/nestquest nestquest \
&& mkdir -p /var/lib/nestquest \
&& chown nestquest:nestquest /var/lib/nestquest
USER nestquest
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
# The database path and the service token / OIDC settings are supplied
# by the environment (compose env_file), never committed into the image.
ENV NESTQUEST_DB_PATH=/var/lib/nestquest/nestquest.db
VOLUME /var/lib/nestquest
EXPOSE 8080
CMD ["uvicorn", "--factory", "api.app:create_app", "--host", "0.0.0.0", "--port", "8080"]
+5 -35
View File
@@ -1,7 +1,3 @@
<p align="center">
<img src="design/logos/NestQuest-NoBG.png" alt="NestQuest logo" width="200">
</p>
# NestQuest - House Chaos Coordination
Home Assistant custom integration for managing chores, custody schedules, and house coordination.
@@ -73,12 +69,12 @@ actions:
## Automation Blueprints
NestQuest ships five automation blueprints in
NestQuest ships four automation blueprints in
`custom_components/nestquest/blueprints/automation/`. Import them in
Home Assistant under **Settings → Automations & Scenes → Blueprints**
(or place the files in your `config/blueprints/automation/` folder),
then create automations from the blueprints, filling the inputs with your
household's choices. The UniFi blueprint needs one automation per child.
then create one automation per blueprint, filling the inputs with your
household's choices.
### Wiring to the integration's notification settings
@@ -100,7 +96,7 @@ The end-of-day report deliberately runs BEFORE the midnight missed
sweep and reads the same day's data — do not schedule it at the
day-rollover time.
### The five blueprints
### The four blueprints
1. **Morning summary** (`morning_summary.yaml`) — at the configured
time, lists every child whose `binary_sensor.nestquest_<child>_present_today`
@@ -128,36 +124,10 @@ day-rollover time.
not re-fire, but a second child clearing the same day still
celebrates.
5. **UniFi quest access** (`unifi_quest_access.yaml`) — create one
automation per child. Select that child's quests-remaining-today
sensor, present-today sensor, and all of their UniFi client access
switches. At 18:25 local
time Monday-Friday or 14:00 Saturday-Sunday, clients with open
quests lose all network access; access returns as soon as the count
reaches zero. When the child is **On travels** (`present today` is off),
access stays on regardless of open quests. An unavailable presence sensor
also leaves access on; verify that sensor before relying on enforcement.
Returning after the cutoff reapplies the rule immediately. At midnight
the old day's quests stop affecting access.
The automation also reconciles after Home Assistant starts and every
five minutes. If the quest sensor is unavailable after the cutoff,
it keeps the child blocked until a valid zero is observed.
First configure the [Home Assistant UniFi Network integration](https://www.home-assistant.io/integrations/unifi/)
with a local account that can manage clients. Under its **Network
access controlled clients** option, add each child's devices by MAC
address, then verify the resulting client access switches manually.
Those switches are **on = allowed** and **off = blocked**. Do not
select gateway, access-point, Home Assistant, or adult-device
switches. To override in an emergency, disable that child's
automation and turn their client switches on; re-enable the
automation to resume the quest rule. Device MAC randomization or
cellular data can bypass a MAC-based Wi-Fi block.
### Example package
```yaml
# Create automations from blueprints — Settings → Automations & Scenes →
# One automation per blueprint — Settings → Automations & Scenes →
# Create → Blueprint, then pick each NestQuest blueprint.
#
# morning_summary: morning_time 08:00, notify_target notify.mobile_app_your_phone
-762
View File
@@ -1,767 +1,5 @@
# NestQuest Release Notes
## Version 0.10.3 — 2026-10-06
### Scope
Patch release carrying the admin PWA desktop-icon update onto `main` (PR #301,
task 55e1e687).
### Behaviour
- The admin PWA's installable icons (192, 512, and 512 maskable) are now
generated from `design/logos/NestQuest_Logo.png` instead of placeholder
graphics, so a home-screen install of the admin app shows the NestQuest logo.
### Requirements
- Home Assistant floor 2024.6.0 (unchanged).
### Breaking changes
- None. Schema unchanged at version 9; no migration, no database backup
required.
### Rollback
- No schema change: rolling back to 0.10.2 requires no database restore.
## Version 0.10.2 — 2026-10-06
### Scope
Patch release carrying the panel SSE idle-timeout fix onto `main` (PR #298, task
6c4b0fa4).
### Behaviour
- The panel event-stream request is no longer subject to aiohttp's default
~300 s total timeout; it now uses an unbounded total with a bounded connect,
so a healthy stream stays open instead of reconnecting every ~5 minutes.
Because the API does not replay transitions onto the Home Assistant event bus,
this also shrinks the windows in which a transition could be missed.
### Requirements
- Home Assistant floor 2024.6.0 (unchanged).
### Breaking changes
- None. Schema unchanged at version 9; no migration, no database backup
required.
### Rollback
- No schema change: rolling back to 0.10.1 requires no database restore.
## Version 0.10.1 — 2026-10-06
### Scope
Patch release carrying the panel SSE stream fix onto `main` (PR #295, task
4cbf2e96).
### Behaviour
- The Home Assistant integration now reads the panel event stream from the
response body (`response.content`), fixing the logged failure
`'async for' requires an object with __aiter__ method, got HassClientResponse`
that logged ~935 times and prevented live panel events (completions,
un-completions, day-complete, missed) from re-firing from the API's SSE
stream. SSE line-buffering and JSON-frame parsing are unchanged.
### Requirements
- Home Assistant floor 2024.6.0 (unchanged).
### Breaking changes
- None. Schema unchanged at version 9; no migration, no database backup
required.
### Known limitations
- Intermittent `GET /api/v1/panel/events failed with HTTP 502` during API
restarts/redeploys is expected (the integration reconnects with backoff).
- The event stream still reconnects periodically because Home Assistant's
shared aiohttp session applies a default total timeout — tracked as a
follow-up; it does not affect correctness.
### Rollback
- No schema change: rolling back to 0.10.0 requires no database restore.
## Version 0.10.0 — 2026-09-30
### Scope
Feature release: choose task icons by typing any Font Awesome Free **solid**
icon name, not just the curated subset. The shared icon registry now embeds the
full Font Awesome Free solid set offline (no CDN — the panel may be offline),
the admin icon picker is searchable with free-text entry and validation, and the
kids' panel renders any Free Solid icon. (Feature `6c681b17`; PRs #289–#292.)
### Behaviour
- **Full Free Solid set**: the panel and admin bundles now carry ~1,422 Font
Awesome Free solid glyphs as inline SVG path data, in addition to the existing
curated quick-pick lists (Lucide and Font Awesome). `fa:<name>` resolves any
Free Solid icon; unknown names still render the fallback glyph.
- **Searchable picker**: the admin definition icon picker's Font Awesome tab has
a search input. Empty shows the curated quick picks; typing filters the full
set into a bounded (≤40 per page) result grid, with Previous / Show more.
- **Free-text entry**: typing an exact Free Solid name selects and stores
`fa:<name>`. A partial, misspelled, Pro, or Brands name is rejected with an
inline message and nothing is saved.
- Stored format is unchanged: `lucide:<name>`, `fa:<name>`, `emoji:<grapheme>`,
or a legacy bare name.
### Requirements
- Home Assistant floor 2024.6.0 (unchanged).
### Breaking changes
- None to the database: schema unchanged at version 9, no migration and no
database backup required.
- Font Awesome **Pro** and **Brands/Regular** icons are NOT included — only the
Free Solid set. A Pro/Brands name is rejected in the picker (and an unknown
`fa:` name falls back on the panel).
### Known limitations
- **Bundle size**: the embedded icon set increases the committed panel bundle to
~1.06 MB raw (~276 kB gzip) and the admin PWA bundle similarly. This is
expected for the full Free Solid set.
- Alias names (e.g. Font Awesome's `fa:home` alias of `fa:house`) are
de-duplicated to the canonical name, so `fa:house` resolves but `fa:home`
falls back.
- The backend still validates only the `fa:<kebab-name>` format; unknown names
are caught in the picker and render as the fallback on the panel.
### Rollback
- No schema change: rolling back to 0.9.8 requires no database restore.
## Version 0.9.8 — 2026-09-30
### Scope
Owner-directed change: the application's timezone is now **manual-only and
admin-authoritative**. Nothing sets it automatically any more; an admin sets it
from the admin app, and the saved value is the single source of local time for
the whole application. This reverses the automatic Home Assistant zone adoption
shipped in 0.9.6 and the admin app's browser-zone auto-set, and supersedes
decision D-018 with D-019. (PRs #282, #283, #285, #286; feature
`a3cd8e27` "Manual application timezone control".)
### Behaviour
- **No automatic timezone setting.** Removed: the API's adoption of Home
Assistant's reported zone (the `X-NestQuest-Timezone` request header and the
`adopt_reported_timezone` path), the integration's reporting of
`hass.config.time_zone`, the admin app's browser-zone auto-detect and
automatic save, and the `timezone_configured` marker.
- **The admin sets it manually**, in the admin app's Preferences: a curated IANA
zone picker plus a free "Other IANA zone" entry, with an explicit choice for
empty ("API host local time"). Nothing is auto-filled or auto-saved.
- **The saved value is authoritative across the whole application**: the panel
snapshot's overdue/today derivation, both panel cards' dates and clocks,
completion timestamps, the missed-sweep scheduler, and the admin reads all use
it. The API publishes the effective zone (`api/host_zone.effective_timezone`:
the saved value, else the API host's own zone) on the panel snapshot and the
admin settings response, so the panel and admin app render in the same zone.
- **The kids' panel now follows the application zone, not the browser.** This
supersedes the panel-local overdue behaviour from 0.9.7; a quest is overdue
when the application clock says so, not when the panel device's clock does.
- **An admin save of the timezone or the day-rollover time re-plans the running
missed-sweep scheduler.**
- The integration tolerates an API snapshot without the timezone field, so the
integration and the API may be upgraded in either order.
### Requirements
- Home Assistant floor 2024.6.0 (unchanged).
### Breaking changes
- None to the database. The schema is unchanged at version 9: no migration and
no database backup is required for this release.
- Behavioural reversal: if a timezone had been auto-set by 0.9.6–0.9.7, the
stored value persists after upgrading (it is simply no longer changed
automatically), so no action is needed unless a different zone is wanted.
- With no timezone saved, the API host's local zone applies (UTC on the standard
deployment). Set the timezone in the admin Preferences for correct
household-local behaviour. A previously auto-set value counts as saved and
will be kept.
### Known limitations
- If no timezone has been saved, the API host zone applies; on the standard
UTC-host deployment, overdue and day boundaries will be wrong until an admin
sets the zone.
- The admin app's timezone picker replaces any zone outside its curated list via
the "Other IANA zone" entry; the value is validated as an IANA name.
### Rollback
- No schema change: rolling back to 0.9.7 requires no database restore.
## Version 0.9.7 — 2026-09-29
### Scope
Patch release carrying the panel-local overdue correction onto `main` (PR #279,
task fd1093b5 "Tasks are still showing over due when the local time has not
passed").
### Behaviour
- The kids' Quest Log card now decides whether an open quest is OVERDUE from
the panel's OWN local clock (the wall time where the panel physically is)
compared with the quest's due time, instead of trusting the API snapshot's
`overdue` flag. A quest therefore cannot read OVERDUE before its due time has
passed on the panel, regardless of the API host's timezone, Home Assistant's
configured `time_zone`, or whether the 0.9.6 timezone changes have been
deployed. A quest is overdue at the due minute and after (`>=`); a quest with
no due time is never overdue.
- The API's `overdue` field is unchanged; it still serves the admin plane and
automations. This is a panel display correction only.
### Requirements
- Home Assistant floor 2024.6.0 (unchanged).
### Breaking changes
- None. The database schema is unchanged at version 9: no migration and no
database backup is required for this release.
### Known limitations
- The comparison uses only wall-clock time. If the API is unreachable across
local midnight and the coordinator serves its last-good snapshot, a quest
from the previous day with a later due time can briefly read as not overdue
until that time passes again. On the normal path the API rolls the household
day over and the missed sweep removes the previous day's open quests.
- The Quest Log header clock still formats in Home Assistant's configured
`time_zone`; if HA is set to a zone other than the household's, that header
remains wrong. Set Home Assistant's own `time_zone` correctly — the admin/API
timezone setting does not affect the header clock.
### Rollback
- No schema change: rolling back to 0.9.6 requires no database restore.
## Version 0.9.6 — 2026-09-28
### Scope
Patch release carrying the household time-zone fix onto `main` (PR #275, task
6351b36d "Time zone errors"), plus its release-review correction (PR #277, task
45243478).
### Behaviour
- The Home Assistant integration now reports `hass.config.time_zone` to the API
in an `X-NestQuest-Timezone` header on every panel request.
- While the API's `timezone` setting has never been explicitly chosen
(`timezone_configured` false), the API adopts and persists the reported zone
(under the settings lock), so the panel's overdue/today calculation, the
admin plane and the missed-sweep scheduler are all household-local even when
the API host runs UTC. No manual setup is required.
- The missed-sweep scheduler re-plans immediately when the adopted zone changes
while it is sleeping, and re-reads the stored zone before sweeping, so it no
longer fires at the old (UTC) rollover.
- An admin-chosen zone — including an explicit choice of empty (API-host local)
— still wins over the reported zone. A timezone-only admin update is recorded
as an explicit choice (`timezone_configured` true); an explicitly supplied
`timezone_configured` value in the same update is honored as given. An invalid
reported zone is logged and ignored; the panel keeps serving on the stored
settings.
### Requirements
- Home Assistant floor 2024.6.0 (unchanged).
### Breaking changes
- None. The database schema is unchanged at version 9: no migration and no
database backup is required for this release.
- Deployment note: this fix needs BOTH the API service and the HA integration
upgraded. The integration supplies the zone and the API adopts it; upgrading
only one side leaves the previous behaviour. An install that sets or clears
its zone on 0.9.6 or later keeps that choice; see Known limitations for a zone
stored by an older release.
### Known limitations
- A zone stored by a release before 0.9.6 without the explicit-choice marker
(for example through the previously documented
`PATCH /api/v1/admin/settings {"timezone": ...}`) is not distinguishable from
an automatically adopted value, so 0.9.6 adopts Home Assistant's reported zone
over it once. If a zone different from Home Assistant's is intended, re-save
it in the admin Preferences, which now records the explicit choice.
- If `timezone` is empty and `timezone_configured` is true (an explicit
"host local" choice), that choice is respected and the API host's zone (UTC
on the standard deployment) still applies until an admin selects a zone in
the admin Preferences.
- A change to Home Assistant's own `time_zone` takes effect after the
integration reloads or Home Assistant restarts.
### Rollback
- No schema change: rolling back to 0.9.5 requires no database restore. The API
and the integration may be rolled back independently; rolling back only the
integration restores the previous stored-setting-only behaviour.
## Version 0.9.5 — 2026-09-27
### Scope
Patch release carrying the kids' panel Return button onto `main`.
- **Return button:** the Quest Log header now shows an explicit Return control —
a left chevron plus "The Party", 72px high and sized to its label, sitting left
of the crest — so a child
can go straight back to the main Party board instead of waiting out the 40 s
idle return. It calls the same navigation the idle return uses
(`board_path` + `location-changed`), so there is exactly one navigation path.
It is hidden when no board path is configured, appears on every header-bearing
Quest Log screen (normal, away, and "no quests today"), and does not appear on
the Quest-complete screen, which keeps its 12 s auto-return. The control meets
the panel's hard rules (72px tap target, 26px label, `:active` feedback only,
clear of the window columns and the dock), and the 40 s idle return and
crest-tap navigation are unchanged. (PR #272.)
### Upgrade note
The database schema is unchanged at version **9**; no migration or backup step is
needed. No runtime dependency is added — only the bundled panel card changed.
### Requirements
Home Assistant 2024.6.0 or newer. Install through HACS from the
`Maniacs-Mansion/NestQuest` GitHub mirror (kept current by the Gitea push
mirror).
## Version 0.9.4 — 2026-09-26
### Scope
Patch release fixing the admin timezone control that shipped in 0.9.3.
- **Clearing the timezone now persists:** in 0.9.3 the Settings screen
re-detected the browser zone whenever the timezone field was empty, so an admin
could not leave it empty ("use the API host's local time") — closing and
reopening the screen set it again. A new persisted, API-only
`timezone_configured` marker (default `false`) now distinguishes "never set"
from "admin chose empty": the one-time auto-set runs only when the timezone is
empty AND the marker is false, and any saved timezone change — including
clearing it — sets the marker, so an explicit empty choice survives. (PRs #266,
#268.)
- Nothing else changes: the `timezone` setting, its auto-set from the browser zone
on a fresh install, the Add/Save flow, and the rest of the Settings screen are
as in 0.9.3.
### Upgrade note
The database schema is unchanged at version **9**; no migration or backup step is
needed. Settings stored before this release have no `timezone_configured` value
and read it as `false`, so an install whose timezone is empty will auto-set the
browser zone once on the next open — after which the choice persists.
### Requirements
Home Assistant 2024.6.0 or newer. Install through HACS from the
`Maniacs-Mansion/NestQuest` GitHub mirror (kept current by the Gitea push
mirror).
## Version 0.9.3 — 2026-09-26
### Scope
Patch release carrying the admin timezone control onto `main`.
- **Admins set the system timezone from the PWA:** the Preferences screen gains a
Timezone field (a text input with a local datalist of common IANA zones;
`UTC` or `Area/Location`). On a fresh install the value is set AUTOMATICALLY
from the browser's IANA zone when the setting is empty on first load — no
geolocation prompt and no network lookup — and an admin can change or clear it
at any time. Only a changed value is sent, and the API's 422 for an unknown zone
is shown by the form. (PR #266.)
- This makes the household-local clock (overdue, daily rollover) configurable
from the UI, replacing the manual
`PATCH /api/v1/admin/settings {"timezone": ...}` step noted in 0.9.1. The
setting still defaults to the API host's local time when left empty.
### Upgrade note
The database schema is unchanged at version **9**; no migration or backup step is
needed. No runtime dependency is added.
### Requirements
Home Assistant 2024.6.0 or newer. Install through HACS from the
`Maniacs-Mansion/NestQuest` GitHub mirror (kept current by the Gitea push
mirror).
## Version 0.9.2 — 2026-09-26
### Scope
Patch release carrying the admin "Delete task" capability onto `main`.
- **Delete a task in the admin PWA:** the definition edit sheet gains an
admin-only Delete action with hybrid semantics (D-017, owner decision "delete
if there's no history, retire/deactivate if there is"). If the definition has
**no completion history**, it is hard-deleted together with its instances,
assignees, windows and its schedule rule (when unreferenced), all in one
transaction under the connection lock. If it has **any completion history** (a
completion or an un-completion), nothing is deleted: it is retired by
deactivation instead, preserving the definition, rule, assignees, windows and
all history, with future uncompleted instances cleared as with any
deactivation. (PR #262.)
- **API:** `DELETE /api/v1/admin/quest-definitions/{id}` lives on the admin plane
(`require_admin`; a non-admin is refused and an unknown id is 404). The response
reports `deleted`/`retired` and carries the retired definition (`null` when
deleted). The kids' panel gains no control, and `QuestDefinitionsDao` now has
exactly one, history-guarded, delete method.
### Upgrade note
The database schema is unchanged at version **9**; no migration or backup step is
needed beyond the 0.8.0 note. No runtime dependency is added.
### Requirements
Home Assistant 2024.6.0 or newer. Install through HACS from the
`Maniacs-Mansion/NestQuest` GitHub mirror (kept current by the Gitea push
mirror).
## Version 0.9.1 — 2026-09-26
### Scope
Patch release carrying the owner-reported UI-bug fixes for the kids' panel, plus a
household-timezone correction, onto `main`.
- **Household-local time:** a new `timezone` setting (an IANA name such as
`America/New_York`; empty keeps the API host's local time) is threaded into the
API's clock reads, so overdue and the daily rollover use the household's day
rather than a UTC host's. **Set it once after upgrading** (see the Upgrade
note); the admin UI has no field for it yet. (PR #254.)
- **Overdue and rollover correctness:** quests are no longer marked overdue
before their due time, and the missed-sweep scheduler fires at the configured
rollover across DST transitions — its delay is now a true elapsed-time
difference, with documented handling of nonexistent/ambiguous local times.
(PRs #254, #257.)
- **Complete works on the panel:** a TypeScript ES2022 `useDefineForClassFields`
default emitted native class fields that shadowed Lit's reactive accessors, so
the confirm dialog never re-rendered and a tap appeared to do nothing; the
panel now opens the confirm and completes. (PR #254.)
- **Panel polish:** the party-board hint line no longer hides behind the dock
(#244); the Quest Log header crest renders with its shield classes (#252); the
party-board wordmark is the new compass-rose monogram plus Cinzel Decorative
text, replacing the d20 dice (#253); and the quest meta line keeps its `meta`
class when not late (#255).
### Upgrade note
The database schema is unchanged at version **9**. After upgrading, set the
household timezone once so date, overdue and rollover behaviour match the house
(otherwise it falls back to the API host's local time, which may be UTC):
```
PATCH /api/v1/admin/settings {"timezone": "America/New_York"}
```
No runtime dependency is added.
### Requirements
Home Assistant 2024.6.0 or newer. Install through HACS from the
`Maniacs-Mansion/NestQuest` GitHub mirror (kept current by the Gitea push
mirror).
## Version 0.9.0 — 2026-09-26
### Scope
Minor release carrying expanded, customisable task icons — Lucide, Font Awesome
Free and emoji — onto `main`.
- **Namespaced icon keys:** a quest definition's `icon` now accepts
`lucide:<kebab-name>`, `fa:<kebab-name>` and `emoji:<grapheme>`. A legacy bare
name (e.g. `dog`) is read as `lucide:dog`, so existing rows keep working with
no stored-data migration. The strict write validator rejects an unknown
namespace, a malformed name, an over-cap or markup-bearing emoji payload, and
`javascript:`. (PRs #241, #249.)
- **Shared icon registry:** one canonical set — the curated Lucide set plus a
curated Font Awesome Free solid subset — generates identical,
framework-agnostic registry modules for the admin and panel bundles, guarded by
a drift test. There is no CDN and no runtime fetch, and only the curated Font
Awesome glyphs are shipped. (PR #242.)
- **Admin PWA picker:** the definition edit sheet offers the Lucide set, the
Font Awesome subset and an emoji input; a selection stores the namespaced key
and an existing namespaced or legacy icon pre-fills correctly. The definition
list renders all three forms with a fallback glyph. Editing a definition whose
stored icon is a legacy value no longer resubmits the unchanged icon.
(PRs #243, #250.)
- **Kids' panel:** open quest cards render the definition's icon (Lucide stroked,
Font Awesome filled, emoji as text) with the existing star fallback; the sealed
card keeps its star/seal glyph. (PR #245.)
- **Docs and attribution:** ADMIN-SPEC and PANEL-SPEC describe the namespaced
model; `THIRD-PARTY-NOTICES.md` records Font Awesome Free (icons CC BY 4.0,
fonts SIL OFL 1.1, code MIT) and Lucide (ISC). (PR #246.)
### Upgrade note
The database schema is unchanged at version **9**; no migration or backup step
is needed beyond the 0.8.0 note. This release adds no runtime dependency — the
icon path data is embedded in the shipped bundles at build time.
### Requirements
Home Assistant 2024.6.0 or newer. Install through HACS from the
`Maniacs-Mansion/NestQuest` GitHub mirror (kept current by the Gitea push
mirror).
## Version 0.8.0 — 2026-09-25
### Scope
Minor release carrying the multi-pattern presence model (schema 9), the
Sunday-first calendar week, and the create-materializes fix, plus the
definition start-date field, onto `main`.
- **Multiple presence patterns per child (schema 9):** a child now has zero or
more presence patterns instead of at most one. Each pattern has a name, a kind
(`home` or `away`), its own cycle length (1–4 weeks), its own anchor date and a
per-week weekday set. Evaluation is first-match-wins — overrides, then away,
then home, then absent when the child has at least one home pattern, else
present. Migration 9 copies each existing schedule into a `home` pattern named
"Home schedule" and drops the old `presence_schedules` table. (PRs #231, #232.)
- **Sunday-first calendar week:** the admin Schedule month grid and the
Definitions weekday picker now render weeks Sunday-first; the stored/API
weekday numbering is unchanged (Monday=0..Sunday=6). (PR #230.)
- **Fix — newly created tasks materialize immediately:** creating a quest
definition now regenerates its future instances over the rolling horizon, so a
new task reaches the panel without waiting for an unrelated write. (PRs #235,
#236.)
- **Definition start date:** the definition edit sheet gains a Start date field
so a task can be scheduled to begin on a future date. (PRs #237, #238.)
- **Docs:** the multi-pattern decision (D-016), the migration-9 rollback step in
the runbook, and the ADMIN-SPEC Schedule section. (PRs #233, #234.)
### Upgrade note
This release runs schema version **9**. Version 0.7.1 refuses a version-9
database, so take a copy of the SQLite file (or note the Litestream generation)
before the first start on 0.8.0 if you need a rollback path.
### Requirements
## Version 0.7.1 — 2026-09-24
### Scope
Patch release bringing the admin PWA follow-ups and its hosting deployment from
`dev` onto 0.7.0.
- **Feature 24 — Admin PWA Hosting:** the admin PWA's static hosting is now
reproducible from the repository — `deploy/pwa/Dockerfile` (multi-stage, pinned
`node`/`nginx` base images by digest, `VITE_AUTHENTIK_CLIENT_ID` /
`VITE_AUTHENTIK_ISSUER` / `VITE_API_BASE_URL` build args), `deploy/pwa/nginx.conf`
(SPA fallback plus a source allow-list for the reverse proxy and the host), a
`pwa` service in `deploy/compose.yaml` published on `:8081`, and a
`deploy/RUNBOOK.md` section describing the build/serve and the Traefik
`nestquest-app` router. (PRs #220, #221.)
- **Feature 19 follow-up — Manage children:** the Today header's Settings button
now opens a Settings screen. Its **Children** section lists the household's
children and lets a parent add (POST `/api/v1/admin/children`), edit
(PATCH `.../{id}`), activate/deactivate (PATCH `.../{id}/active`) and reorder
them (POST `.../reorder`). (PRs #222, #223.)
- **Feature 19 follow-up — Settings preferences:** the same screen has a
**Preferences** section for the planning horizon, day rollover time, notify
target, the morning/afternoon/end-of-day notification times and their toggles,
and celebration, read from `GET /api/v1/admin/settings` and saved with a partial
`PATCH` of only the changed fields. (PRs #224, #225, #226.)
### Requirements
- Minimum Home Assistant version: **2024.6.0**.
- A running NestQuest API service as in 0.7.0 (the Feature 17 deployment); the
`admin/` PWA is served from the owner's deployment at
`https://nestquest.cubecraftlabs.com`, not by HACS.
### Breaking changes
- **None.** The schema is unchanged at version 8 and no migration runs.
`custom_components/` is unchanged from 0.7.0 apart from the manifest
release-version metadata — no Home Assistant entity, service, event or
automation surface changes. This release adds admin PWA screens and deployment
artifacts only.
### Known Limitations
- **HACS does not ship the admin PWA or the deployment artifacts.** HACS copies
only `custom_components/nestquest`, so upgrading via HACS changes nothing
functional over 0.7.0; the PWA screens and hosting are deployed from `admin/`
and `deploy/` per the runbook.
- Serving the PWA and API still requires the Feature 17 deployment (host, reverse
proxy, Authentik, backup target) as documented in `deploy/RUNBOOK.md`.
- **Feature 12's TouchHub/DAKOS runbook task remains physically unverified**
(needs the wall panel).
- The Settings UI does not expose resetting a field to its default with `null`.
### Rollback
Schema is unchanged (8), so no migration is involved in either direction.
`custom_components/` is unchanged from 0.7.0 apart from the release-version
metadata; rolling back the integration is a plain swap, and the PWA/hosting can be
redeployed from the 0.7.0 tree.
**HACS installs:** HACS > Integrations > NestQuest > Redownload > 0.7.0, then
restart Home Assistant.
**Manual installs:** replace `custom_components/nestquest/` with the 0.7.0 tree,
then restart Home Assistant.
**Repository operators:** git-revert the 0.7.1 release merge on `main`.
## Version 0.7.0 — 2026-09-24
### Scope
Seventh release of NestQuest, promoting the re-imagined architecture's admin
surface from `dev` onto 0.6.0: the API deployment and identity layer, the
admin-plane API work, and the standalone admin PWA that uses them.
- **Feature 17 — API Deployment and Identity:** the NestQuest API is packaged as
a container (`Dockerfile`, `deploy/compose.yaml`, pinned base image and exact
dependencies) and deployed behind a TLS reverse proxy (the shared Traefik, ACME
via the Cloudflare DNS-01 challenge); the Authentik application, OIDC provider
and `nestquest-admins` group are wired and the API validates the provider's
issuer/audience/JWKS (RS256); the panel plane is restricted to the Home
Assistant box while the admin plane is internet-facing behind Authentik;
continuous backup runs as a contained Litestream sidecar over SFTP to a NAS and
a restore is proven; a deployment runbook (`deploy/RUNBOOK.md`) and the
host-firewall unit (`deploy/systemd/nestquest-api-firewall.service`) ship.
(PRs #183, #214, #215, #216, #218.)
- **Feature 19 — Admin PWA:** the parent-facing admin surface is now a
standalone mobile-first React progressive web app (`admin/`), implementing
`design/ADMIN-SPEC.md`: Authentik OIDC authorization-code + PKCE login with
an explicit refusal for a user outside `nestquest-admins`; an installable
PWA (manifest + service worker); and the Today, Definitions, Schedule and
History screens. Every mutating action goes through the API admin routes;
the API remains the security boundary (D-003/D-012). Today shows the
household snapshot; Definitions supports create/edit with multi-select
assignees, a recurrence rule with interval and per-window due times, a
skip-on-away toggle, a shipped Lucide icon subset and a backend-computed
occurrence preview; Schedule has a presence month grid (cycle position from
the anchor date, never ISO parity, D-004) and an override editor with a live
"removes N upcoming tasks" consequence count; History has All/Reversals/
Missed filters, day-grouped rows, per-period stats, CSV export and the
append-only footer. Undo reverses a completion, and live updates arrive over
the admin SSE stream without a manual reload. (PRs #187–#210, plus the
feature-review fix #212.)
- **Feature 21 — Admin Today Snapshot API:** `GET /api/v1/admin/snapshot`
serves the Today view's household snapshot on the admin plane (reusing the
core snapshot builder with missed instances included, D-009). (PRs #190/#191.)
- **Feature 22 — Admin Definitions Read and skip_on_away:**
`GET /api/v1/admin/quest-definitions` lists all definitions (active and
inactive), and a persisted per-definition `skip_on_away` boolean is accepted
by create/update and honoured by materialization. Adds an optional
`assignee_child_ids` to the edit route so the PWA can reassign children.
(PRs #193, #194, #196, #197.)
- **Feature 23 — Admin API Completion (preview, presence, live):** a bounded
rule occurrence-preview route; presence-schedule and presence-override
reads; a live override consequence count computed from the same core
generator the materializer uses; and an admin-plane transition SSE stream
(`GET /api/v1/admin/events`) off the one in-process publisher. (PRs
#199–#203.)
### Requirements
- Minimum Home Assistant version: **2024.6.0**.
- A running NestQuest API service, reachable at the base URL and panel service
token configured in the integration options. The deployable ships in this
release: `Dockerfile`, `deploy/compose.yaml` (API + a contained Litestream
backup sidecar), `api/requirements.txt`, the host-firewall unit and
`deploy/RUNBOOK.md`. Deploying it needs a host, the DNS/TLS path and the
Authentik/Synology services described in the runbook.
- The admin PWA is built to run at `https://nestquest.cubecraftlabs.com` behind
Authentik. Serving the built `admin/` static bundle at that hostname is part of
the deployment described in the runbook.
### Breaking changes
- **Schema version advances 7 → 8.** Migration 8 adds the additive
`skip_on_away` column to `quest_definitions` (default 1, so every existing
definition keeps today's skip-when-absent behaviour). The migration runs on
the first start of this version.
- **Once migrated, a plain downgrade to 0.6.0 is impossible** — older builds
refuse a newer schema version. **Back up `nestquest.db` (plus `-wal`/`-shm`)
before upgrading**; see Rollback.
- No Home Assistant entity, service, event or automation surface changes in
this release. The API's new admin routes are additive.
### Known Limitations
- **The API and its identity/backup layer are deployed by the owner's
infrastructure, not by this release alone.** The deployment artifacts and
runbook ship here, but a running service still requires the host, the shared
reverse proxy, the Authentik application/provider/`nestquest-admins` group, the
backup target and the panel/admin network separation to be in place as the
runbook describes.
- **Serving the admin PWA is still outstanding.** `admin/` builds and is
unit/integration tested and the API it talks to is live, but the built static
bundle must still be hosted at `https://nestquest.cubecraftlabs.com` behind
Authentik; until then the PWA is not reachable end-to-end.
- **Feature 12's TouchHub/DAKOS runbook task remains physically unverified**
(needs the wall panel).
- Moving the household database from Home Assistant to the API box is a manual
file copy (the schema is unchanged by that move beyond the v8 migration).
- Single household; single API service.
### Rollback
**Schema version advances 7 → 8.** Migration 8 is additive, but a migrated
database **cannot** be read by 0.6.0 or earlier (they refuse a newer schema
version). The database is owned and migrated by the **NestQuest API service**,
not by Home Assistant: it is the file at the API's configured
`NESTQUEST_DB_PATH` on the API host, which need not be anywhere near the Home
Assistant config directory. To return to 0.6.0 you must restore a backup of
that file taken before the upgrade; a plain downgrade is impossible once
migrated.
**API host (database):**
1. Before upgrading, stop the NestQuest API service and back up the database
file at its configured `NESTQUEST_DB_PATH`, plus its `-wal` and `-shm`
sidecars (`<NESTQUEST_DB_PATH>-wal`, `<NESTQUEST_DB_PATH>-shm`) if present.
Only then deploy 0.7.0 and start the API service, which applies migration 8.
2. To roll back: stop the API service, restore the backed-up database and
sidecars to `NESTQUEST_DB_PATH`, redeploy the API service at 0.6.0, and roll
back the Home Assistant integration to 0.6.0 (below). Then restart the API
service and Home Assistant.
**Home Assistant integration — HACS installs** (integration component only;
the database lives with the API, see above):
1. To roll back: HACS > Integrations > NestQuest > Redownload > 0.6.0, then
restart Home Assistant.
**Home Assistant integration — Manual installs** (integration component only;
the database lives with the API, see above):
1. To roll back: replace `custom_components/nestquest/` with the 0.6.0 tree,
then restart Home Assistant.
**Repository operators:** git-revert the 0.7.0 release merge on `main`.
## Version 0.6.0 — 2026-09-23
### Scope
-31
View File
@@ -1,31 +0,0 @@
# Third-party notices
NestQuest bundles glyph data from the icon sets below. The curated Lucide names and the
Font Awesome quick-pick names are listed in `tools/icons/curated-icons.json`;
`tools/icons/generate.mjs` reads each glyph's SVG path data from the locally installed packages and generates it into both bundles
(`admin/src/icons/registry.generated.ts` and `frontend/src/icons/registry.generated.ts`).
Nothing is loaded from a CDN or fetched at runtime. The package versions used are recorded
in the header of each generated file.
## Font Awesome Free
- Project: <https://fontawesome.com> · repository: <https://github.com/FortAwesome/Font-Awesome>
- Package: `@fortawesome/free-solid-svg-icons`
- Licence: <https://fontawesome.com/license/free>
- Icons: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
- Fonts: [SIL OFL 1.1](https://openfontlicense.org)
- Code: [MIT](https://opensource.org/licenses/MIT)
- Use in NestQuest: the full Free **solid** icon set, embedded as SVG path data (a curated
subset doubles as the admin picker's quick picks). No fonts are bundled.
Font Awesome Free by @fontawesome — https://fontawesome.com — icons licensed under CC BY 4.0.
## Lucide
- Project: <https://lucide.dev> · repository: <https://github.com/lucide-icons/lucide>
- Package: `lucide-react`
- Licence: [ISC](https://github.com/lucide-icons/lucide/blob/main/LICENSE)
- Use in NestQuest: a curated subset of Lucide icons, embedded as SVG path data.
Lucide icons are Copyright (c) Lucide Contributors, licensed under the ISC License.
Portions derived from Feather are Copyright (c) Cole Bemis, licensed under the MIT License.
+1 -26
View File
@@ -8,18 +8,17 @@
"name": "nestquest-admin",
"version": "0.0.0",
"dependencies": {
"lucide-react": "^1.47.0",
"react": "^19.2.0",
"react-dom": "^19.2.0"
},
"devDependencies": {
"@fortawesome/free-solid-svg-icons": "7.3.1",
"@testing-library/dom": "^10.4.1",
"@testing-library/react": "^16.3.0",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^5.0.0",
"jsdom": "^30.1.1",
"lucide-react": "1.47.0",
"typescript": "^5.9.2",
"vite": "^7.1.5",
"vitest": "^3.2.4"
@@ -983,29 +982,6 @@
}
}
},
"node_modules/@fortawesome/fontawesome-common-types": {
"version": "7.3.1",
"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-7.3.1.tgz",
"integrity": "sha512-k0C0sdHmZtAo6dRDtd1Z/qcpyHbL0CKsjV8seMY/21xGhY5Wsv0XRmiI/xEEH4y2c9b1+jvgNs/3EqhV27yUEA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/@fortawesome/free-solid-svg-icons": {
"version": "7.3.1",
"resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-7.3.1.tgz",
"integrity": "sha512-v0BLa0eqg7ubvVWeNSHVBs8fWH/GJicERZoJaxJ3FE/lj67VSqzoMg9pzfZVOfLMX10y0pGwQAuxoRVVH2patg==",
"dev": true,
"license": "(CC-BY-4.0 AND MIT)",
"dependencies": {
"@fortawesome/fontawesome-common-types": "7.3.1"
},
"engines": {
"node": ">=6"
}
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -2286,7 +2262,6 @@
"version": "1.47.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.47.0.tgz",
"integrity": "sha512-o8C23aXpNQypRY73W7fW02EyvWJinEMXgKeGjFoKym0zj3Q73hD97A1IQps1g8C14HTGsOpZL0Am+xjfgFZAbg==",
"dev": true,
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+1 -2
View File
@@ -10,18 +10,17 @@
"test": "vitest run"
},
"dependencies": {
"lucide-react": "^1.47.0",
"react": "^19.2.0",
"react-dom": "^19.2.0"
},
"devDependencies": {
"@fortawesome/free-solid-svg-icons": "7.3.1",
"@testing-library/dom": "^10.4.1",
"@testing-library/react": "^16.3.0",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^5.0.0",
"jsdom": "^30.1.1",
"lucide-react": "1.47.0",
"typescript": "^5.9.2",
"vite": "^7.1.5",
"vitest": "^3.2.4"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 KiB

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 178 KiB

After

Width:  |  Height:  |  Size: 8.2 KiB

+22 -112
View File
@@ -1,12 +1,14 @@
// Generates the committed PWA icons under public/icons/ from the brand logo
// (design/logos/NestQuest_Logo.png), box-filter downscaled.
// Generates the committed PWA icons under public/icons/ as genuine PNGs.
// Pure Node (zlib only) — no network, no image dependencies.
// Run: node scripts/generate-icons.mjs
import { readFileSync, writeFileSync } from "node:fs";
import { deflateSync, inflateSync } from "node:zlib";
import { writeFileSync } from "node:fs";
import { deflateSync } from "node:zlib";
import { fileURLToPath } from "node:url";
const SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
// Brand tokens (design/tokens/nestquest-admin-tokens.css).
const BLUE = [0x3b, 0x3a, 0xb8];
const PURPLE = [0xa0, 0x35, 0xcc];
const WHITE = [0xff, 0xff, 0xff];
const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
let c = n;
@@ -42,129 +44,37 @@ function encodePng(size, pixel) {
for (let x = 0; x < size; x++) raw.set(pixel(x, y), row + 1 + x * 3);
}
return Buffer.concat([
SIG,
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk("IHDR", ihdr),
chunk("IDAT", deflateSync(raw, { level: 9 })),
chunk("IEND", Buffer.alloc(0)),
]);
}
// Minimal decoder for the source logo: 8-bit RGB, non-interlaced only.
// Anything else fails loudly rather than producing a wrong icon.
function decodePng(buf) {
if (!buf.subarray(0, 8).equals(SIG)) throw new Error("not a PNG");
let width, height;
const idat = [];
for (let off = 8; off < buf.length; ) {
const len = buf.readUInt32BE(off);
const type = buf.toString("ascii", off + 4, off + 8);
const data = buf.subarray(off + 8, off + 8 + len);
if (type === "IHDR") {
width = data.readUInt32BE(0);
height = data.readUInt32BE(4);
const [depth, colour, , , interlace] = data.subarray(8);
if (depth !== 8 || colour !== 2 || interlace !== 0) {
throw new Error(`unsupported PNG: depth ${depth}, colour type ${colour}, interlace ${interlace}`);
}
} else if (type === "IDAT") idat.push(data);
else if (type === "IEND") break;
off += 12 + len;
}
const raw = inflateSync(Buffer.concat(idat));
const stride = width * 3;
const px = Buffer.alloc(stride * height);
for (let y = 0; y < height; y++) {
const filter = raw[y * (stride + 1)];
const src = y * (stride + 1) + 1;
const dst = y * stride;
for (let i = 0; i < stride; i++) {
const a = i >= 3 ? px[dst + i - 3] : 0;
const b = y > 0 ? px[dst - stride + i] : 0;
const c = i >= 3 && y > 0 ? px[dst - stride + i - 3] : 0;
let p;
if (filter === 0) p = 0;
else if (filter === 1) p = a;
else if (filter === 2) p = b;
else if (filter === 3) p = (a + b) >> 1;
else if (filter === 4) {
const pa = Math.abs(b - c), pb = Math.abs(a - c), pc = Math.abs(a + b - 2 * c);
p = pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
} else throw new Error(`bad PNG filter ${filter} on row ${y}`);
px[dst + i] = (raw[src + i] + p) & 0xff;
}
}
return { width, height, px };
}
// Box-filter (area-average) resize along one axis: each output sample is the
// coverage-weighted mean of the source samples it spans.
function boxWeights(srcLen, dstLen) {
const scale = srcLen / dstLen;
return Array.from({ length: dstLen }, (_, o) => {
const start = o * scale, end = start + scale;
const taps = [];
for (let s = Math.floor(start); s < Math.min(Math.ceil(end), srcLen); s++) {
taps.push([s, (Math.min(end, s + 1) - Math.max(start, s)) / scale]);
}
return taps;
});
}
function resize({ width, height, px }, size) {
const wx = boxWeights(width, size);
const wy = boxWeights(height, size);
const tmp = new Float64Array(size * height * 3); // horizontal pass
for (let y = 0; y < height; y++) {
for (let x = 0; x < size; x++) {
for (const [s, w] of wx[x]) {
for (let k = 0; k < 3; k++) tmp[(y * size + x) * 3 + k] += px[(y * width + s) * 3 + k] * w;
}
}
}
const out = new Uint8Array(size * size * 3); // vertical pass
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
for (let k = 0; k < 3; k++) {
let v = 0;
for (const [s, w] of wy[y]) v += tmp[(s * size + x) * 3 + k] * w;
out[(y * size + x) * 3 + k] = Math.min(255, Math.round(v));
}
}
}
return (x, y) => out.subarray((y * size + x) * 3, (y * size + x) * 3 + 3);
}
// Mean of the four corner pixels — the logo's solid background colour.
function cornerColour({ width, height, px }) {
const corners = [[0, 0], [width - 1, 0], [0, height - 1], [width - 1, height - 1]];
return [0, 1, 2].map((k) =>
Math.round(corners.reduce((sum, [x, y]) => sum + px[(y * width + x) * 3 + k], 0) / 4),
);
}
// `scale` < 1 shrinks the logo onto a background-coloured canvas so a
// maskable icon keeps the whole emblem inside the safe zone (inner 80% circle).
function logoIcon(logo, size, scale) {
if (scale === 1) return resize(logo, size);
const inner = Math.round(size * scale);
const offset = Math.floor((size - inner) / 2);
const pixel = resize(logo, inner);
const bg = cornerColour(logo);
// Flat brand mark: diagonal blue→purple gradient with a white ring ("nest")
// around a white dot ("quest"). `scale` shrinks the mark for the maskable
// safe zone (inner 80% circle).
function brandMark(size, scale) {
const c = size / 2;
const outer = size * 0.34 * scale;
const inner = size * 0.24 * scale;
const dot = size * 0.1 * scale;
return (x, y) => {
const ix = x - offset, iy = y - offset;
return ix >= 0 && iy >= 0 && ix < inner && iy < inner ? pixel(ix, iy) : bg;
const d = Math.hypot(x + 0.5 - c, y + 0.5 - c);
if ((d <= outer && d >= inner) || d <= dot) return WHITE;
const t = (x + y) / (2 * (size - 1));
return BLUE.map((b, i) => Math.round(b + (PURPLE[i] - b) * t));
};
}
const logo = decodePng(readFileSync(new URL("../../design/logos/NestQuest_Logo.png", import.meta.url)));
const outDir = new URL("../public/icons/", import.meta.url);
const icons = [
["icon-192.png", 192, 1],
["icon-512.png", 512, 1],
["icon-maskable-512.png", 512, 0.8],
["icon-maskable-512.png", 512, 0.75],
];
for (const [name, size, scale] of icons) {
const path = fileURLToPath(new URL(name, outDir));
writeFileSync(path, encodePng(size, logoIcon(logo, size, scale)));
writeFileSync(path, encodePng(size, brandMark(size, scale)));
console.log(`wrote ${path}`);
}
+7 -50
View File
@@ -2,29 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import App from "./App";
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
}
let settingsResponse: () => Promise<Response>;
describe("NestQuest Admin shell", () => {
beforeEach(() => {
settingsResponse = () =>
Promise.resolve(jsonResponse({ timezone: "", effective_timezone: "Europe/London" }));
// The shell loads the stored application timezone; every tab's own
// requests stay pending so the shell tests remain offline.
vi.stubGlobal(
"fetch",
vi.fn((url: string) =>
String(url).endsWith("/api/v1/admin/settings")
? settingsResponse()
: new Promise<Response>(() => {}),
),
);
// The Today tab fetches the admin snapshot; keep the shell tests offline.
vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>(() => {})));
});
afterEach(() => {
@@ -41,10 +22,10 @@ describe("NestQuest Admin shell", () => {
}
});
it("starts on the Today screen and switches on tab click", async () => {
it("starts on the Today screen and switches on tab click", () => {
render(<App />);
expect(await screen.findByRole("heading", { name: "Today" })).toBeTruthy();
expect(screen.getByRole("heading", { name: "Today" })).toBeTruthy();
fireEvent.click(screen.getByRole("tab", { name: "History" }));
@@ -55,36 +36,12 @@ describe("NestQuest Admin shell", () => {
);
});
it("the Tasks tab renders the definitions screen", async () => {
it("the Tasks tab renders the definitions screen", () => {
render(<App />);
fireEvent.click(screen.getByRole("tab", { name: "Tasks" }));
expect(await screen.findByRole("heading", { name: "Tasks" })).toBeTruthy();
expect(screen.getByRole("heading", { name: "Tasks" })).toBeTruthy();
expect(screen.getByRole("tabpanel").textContent).not.toContain("placeholder");
});
it("renders no screen until the stored application timezone is known", async () => {
settingsResponse = () => new Promise<Response>(() => {});
render(<App />);
expect(screen.getByTestId("timezone-loading")).toBeTruthy();
expect(screen.queryByRole("heading", { name: "Today" })).toBeNull();
});
it("a failed timezone load says so and retries", async () => {
settingsResponse = () => Promise.resolve(jsonResponse({ detail: "boom" }, 500));
render(<App />);
await screen.findByTestId("timezone-error");
expect(screen.queryByRole("heading", { name: "Today" })).toBeNull();
settingsResponse = () =>
Promise.resolve(
jsonResponse({ timezone: "Pacific/Auckland", effective_timezone: "Pacific/Auckland" }),
);
fireEvent.click(screen.getByRole("button", { name: "Try again" }));
expect(await screen.findByRole("heading", { name: "Today" })).toBeTruthy();
});
});
});
+38 -45
View File
@@ -1,10 +1,8 @@
import { useState } from "react";
import "./App.css";
import { TransitionsProvider } from "./api/useTransitions";
import DefinitionsTab from "./definitions/DefinitionsTab";
import HistoryTab from "./history/HistoryTab";
import ScheduleTab from "./schedule/ScheduleTab";
import { AppTimezoneProvider } from "./time/AppTimezone";
import TodayTab from "./today/TodayTab";
const TABS = [
@@ -20,48 +18,43 @@ export default function App() {
const [active, setActive] = useState<TabId>("today");
return (
<TransitionsProvider>
<div className="admin-shell">
{/* Every tab is a built screen that owns its header (ADMIN-SPEC §1); the
generic shell header stays only as a visually hidden page heading. */}
<header className="admin-header visually-hidden">
<h1 className="admin-title">NestQuest Admin</h1>
<p className="admin-subline">Admin console</p>
</header>
<main
className="admin-panel admin-panel--screen"
role="tabpanel"
aria-labelledby={`tab-${active}`}
>
{/* Every screen's local time is the stored application timezone. */}
<AppTimezoneProvider>
{active === "today" ? (
<TodayTab />
) : active === "tasks" ? (
<DefinitionsTab />
) : active === "schedule" ? (
<ScheduleTab />
) : (
<HistoryTab />
)}
</AppTimezoneProvider>
</main>
<nav className="admin-tabbar" aria-label="Admin sections">
{TABS.map((tab) => (
<button
key={tab.id}
id={`tab-${tab.id}`}
type="button"
role="tab"
aria-selected={tab.id === active}
className={tab.id === active ? "admin-tab active" : "admin-tab"}
onClick={() => setActive(tab.id)}
>
{tab.label}
</button>
))}
</nav>
</div>
</TransitionsProvider>
<div className="admin-shell">
{/* Every tab is a built screen that owns its header (ADMIN-SPEC §1); the
generic shell header stays only as a visually hidden page heading. */}
<header className="admin-header visually-hidden">
<h1 className="admin-title">NestQuest Admin</h1>
<p className="admin-subline">Admin console</p>
</header>
<main
className="admin-panel admin-panel--screen"
role="tabpanel"
aria-labelledby={`tab-${active}`}
>
{active === "today" ? (
<TodayTab />
) : active === "tasks" ? (
<DefinitionsTab />
) : active === "schedule" ? (
<ScheduleTab />
) : (
<HistoryTab />
)}
</main>
<nav className="admin-tabbar" aria-label="Admin sections">
{TABS.map((tab) => (
<button
key={tab.id}
id={`tab-${tab.id}`}
type="button"
role="tab"
aria-selected={tab.id === active}
className={tab.id === active ? "admin-tab active" : "admin-tab"}
onClick={() => setActive(tab.id)}
>
{tab.label}
</button>
))}
</nav>
</div>
);
}
+1 -121
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import AppRoutes from "./AppRoutes";
import { storeTokens } from "./auth/oidc";
import { config } from "./config";
@@ -32,32 +32,6 @@ describe("AppRoutes auth gating", () => {
).toBeTruthy();
});
function probeCalls(fetchMock: ReturnType<typeof vi.fn>): string[] {
return fetchMock.mock.calls
.map(([url]) => String(url))
.filter((url) => url.includes("/api/"));
}
it("probes exactly GET /api/v1/admin/ping and no non-admin path", async () => {
storeTokens({ access_token: "at-123", expires_in: 600 });
const fetchMock = vi.fn().mockResolvedValue(new Response("", { status: 500 }));
vi.stubGlobal("fetch", fetchMock);
render(<AppRoutes />);
await waitFor(() => {
expect(screen.getByTestId("probe-error-screen")).toBeTruthy();
});
const calls = probeCalls(fetchMock);
expect(calls).toEqual([`${config.apiBaseUrl}/api/v1/admin/ping`]);
const [, init] = fetchMock.mock.calls[0];
expect(init.method ?? "GET").toBe("GET");
expect(init.headers.Authorization).toBe("Bearer at-123");
for (const url of calls) {
expect(new URL(url, "http://localhost").pathname.startsWith("/api/v1/admin/")).toBe(true);
}
});
it("renders the four-tab shell after a successful authenticated probe", async () => {
storeTokens({ access_token: "at-123", expires_in: 600 });
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([]));
@@ -71,9 +45,6 @@ describe("AppRoutes auth gating", () => {
for (const label of ["Today", "Tasks", "Schedule", "History"]) {
expect(screen.getByRole("tab", { name: label })).toBeTruthy();
}
expect(String(fetchMock.mock.calls[0][0])).toBe(
`${config.apiBaseUrl}/api/v1/admin/ping`,
);
});
it("renders the explicit refusal when the API answers 403", async () => {
@@ -87,97 +58,6 @@ describe("AppRoutes auth gating", () => {
expect(screen.getByTestId("refusal-screen")).toBeTruthy();
});
expect(screen.getByText(/not in the nestquest-admins group/i)).toBeTruthy();
expect(screen.queryByRole("tab", { name: "Today" })).toBeNull();
});
it("keeps the login flow when the probe answers 401", async () => {
storeTokens({ access_token: "stale", expires_in: 600 });
const assign = vi.fn();
vi.stubGlobal("location", { ...window.location, assign });
const fetchMock = vi.fn().mockImplementation(async (url: string) =>
String(url).includes("/api/v1/admin/ping")
? new Response("", { status: 401 })
: jsonResponse({
issuer: config.issuer,
authorization_endpoint: "https://auth.example.com/authorize/",
token_endpoint: "https://auth.example.com/token/",
userinfo_endpoint: "https://auth.example.com/userinfo/",
end_session_endpoint: "https://auth.example.com/end-session/",
jwks_uri: "https://auth.example.com/jwks/",
}),
);
vi.stubGlobal("fetch", fetchMock);
render(<AppRoutes />);
await waitFor(() => {
expect(screen.getByTestId("login-screen")).toBeTruthy();
});
expect(assign).toHaveBeenCalledTimes(1);
const redirect = new URL(assign.mock.calls[0][0] as string);
expect(redirect.origin + redirect.pathname).toBe("https://auth.example.com/authorize/");
expect(probeCalls(fetchMock)).toEqual([`${config.apiBaseUrl}/api/v1/admin/ping`]);
expect(screen.queryByRole("tab", { name: "Today" })).toBeNull();
expect(screen.queryByTestId("probe-error-screen")).toBeNull();
});
for (const status of [404, 500]) {
it(`shows the error screen, not the shell, when the probe answers ${status}`, async () => {
storeTokens({ access_token: "at-123", expires_in: 600 });
const fetchMock = vi.fn().mockResolvedValue(new Response("", { status }));
vi.stubGlobal("fetch", fetchMock);
render(<AppRoutes />);
await waitFor(() => {
expect(screen.getByTestId("probe-error-screen")).toBeTruthy();
});
expect(screen.getByText(new RegExp(`answered ${status}`))).toBeTruthy();
expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Sign out" })).toBeTruthy();
expect(screen.queryByRole("tab", { name: "Today" })).toBeNull();
expect(screen.queryByTestId("refusal-screen")).toBeNull();
});
}
it("shows the error screen, not the shell, when the probe request fails", async () => {
storeTokens({ access_token: "at-123", expires_in: 600 });
const fetchMock = vi.fn().mockRejectedValue(new TypeError("Failed to fetch"));
vi.stubGlobal("fetch", fetchMock);
render(<AppRoutes />);
await waitFor(() => {
expect(screen.getByTestId("probe-error-screen")).toBeTruthy();
});
expect(screen.getByText(/could not be reached/i)).toBeTruthy();
expect(screen.queryByRole("tab", { name: "Today" })).toBeNull();
});
it("re-probes on retry and enters the shell once the probe succeeds", async () => {
storeTokens({ access_token: "at-123", expires_in: 600 });
// After the retry the ping succeeds; the shell's own tab loads stay pending.
let pings = 0;
const fetchMock = vi.fn().mockImplementation((url: string) => {
if (!String(url).endsWith("/api/v1/admin/ping")) return new Promise(() => {});
pings += 1;
return Promise.resolve(new Response("", { status: pings === 1 ? 500 : 200 }));
});
vi.stubGlobal("fetch", fetchMock);
render(<AppRoutes />);
await waitFor(() => {
expect(screen.getByTestId("probe-error-screen")).toBeTruthy();
});
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await waitFor(() => {
expect(screen.getByRole("tab", { name: "Today" })).toBeTruthy();
});
expect(String(fetchMock.mock.calls[1][0])).toBe(
`${config.apiBaseUrl}/api/v1/admin/ping`,
);
});
it("shows the configuration error screen when the client id is missing", () => {
+8 -43
View File
@@ -12,7 +12,7 @@ import {
handleCallback,
isAuthenticated,
} from "./auth/oidc";
import { ApiForbiddenError, ApiUnauthorizedError, apiFetch } from "./api/client";
import { ApiForbiddenError, apiFetch } from "./api/client";
import AdminShell from "./App";
type Screen =
@@ -21,28 +21,18 @@ type Screen =
| { kind: "config-error"; message: string }
| { kind: "auth-error"; message: string }
| { kind: "refusal"; message: string }
| { kind: "probe-error"; message: string }
| { kind: "app" };
function currentPath(): string {
return window.location.pathname.replace(/\/+$/, "") || "/";
}
const ADMIN_PROBE_PATH = "/api/v1/admin/ping";
async function probeApi(setScreen: (screen: Screen) => void) {
// The admin plane's authorization probe: only a 2xx enters the shell, so a
// non-admin (403) sees the explicit refusal and any other failure an error.
// A cheap authenticated probe so a 403 surfaces as an explicit refusal
// right after login instead of a silent empty shell.
try {
const response = await apiFetch(ADMIN_PROBE_PATH, {}, config);
if (response.ok) {
setScreen({ kind: "app" });
return;
}
setScreen({
kind: "probe-error",
message: `The admin API answered ${response.status}. The admin console cannot load.`,
});
await apiFetch("/api/v1/children", {}, config);
setScreen({ kind: "app" });
} catch (error) {
if (error instanceof ConfigError) {
setScreen({ kind: "config-error", message: error.message });
@@ -52,15 +42,9 @@ async function probeApi(setScreen: (screen: Screen) => void) {
setScreen({ kind: "refusal", message: error.message });
return;
}
if (error instanceof ApiUnauthorizedError) {
// apiFetch has already started the login redirect.
setScreen({ kind: "login" });
return;
}
setScreen({
kind: "probe-error",
message: "The admin API could not be reached. Check your connection and try again.",
});
// Network or other failures still allow the shell to render; API screens
// handle their own errors in later tasks.
setScreen({ kind: "app" });
}
}
@@ -186,25 +170,6 @@ export default function AppRoutes() {
</button>
</div>
);
case "probe-error":
return (
<div className="admin-error" role="alert" data-testid="probe-error-screen">
<h1>Admin console unavailable</h1>
<p>{screen.message}</p>
<button
type="button"
onClick={() => {
setScreen({ kind: "loading" });
void probeApi(setScreen);
}}
>
Retry
</button>
<button type="button" onClick={() => { clearAuth(); window.history.replaceState({}, "", "/"); setScreen({ kind: "login" }); }}>
Sign out
</button>
</div>
);
case "app":
return <AdminShell />;
}
-50
View File
@@ -1,50 +0,0 @@
/**
* Typed client for the admin child-profile write routes
* (/api/v1/admin/children). The list read is `fetchChildren` in ./definitions.
*/
import { apiFetch } from "./client";
import { CHILDREN_PATH, readJson, type AdminChild } from "./definitions";
export interface ChildCreateBody {
display_name: string;
colour?: string;
avatar_ref?: string;
sort_order?: number;
}
/**
* Omitted fields stay unchanged. The API rejects an explicit null, so a set
* colour or avatar cannot be cleared through this route.
*/
export type ChildEditBody = Partial<ChildCreateBody>;
export const CHILDREN_REORDER_PATH = `${CHILDREN_PATH}/reorder`;
function sendJson(path: string, method: "POST" | "PATCH", body: unknown): Promise<Response> {
return apiFetch(path, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}
export async function createChild(body: ChildCreateBody): Promise<AdminChild> {
return readJson<AdminChild>(await sendJson(CHILDREN_PATH, "POST", body));
}
export async function updateChild(id: number, body: ChildEditBody): Promise<AdminChild> {
return readJson<AdminChild>(await sendJson(`${CHILDREN_PATH}/${id}`, "PATCH", body));
}
export async function setChildActive(id: number, isActive: boolean): Promise<AdminChild> {
return readJson<AdminChild>(
await sendJson(`${CHILDREN_PATH}/${id}/active`, "PATCH", { is_active: isActive }),
);
}
/** `orderedIds` must be every child id in the household, in the new order. */
export async function reorderChildren(orderedIds: number[]): Promise<void> {
await readJson<{ status: string }>(
await sendJson(CHILDREN_REORDER_PATH, "POST", { ordered_ids: orderedIds }),
);
}
+1 -27
View File
@@ -147,36 +147,10 @@ export async function updateDefinition(
return readJson<QuestDefinition>(await sendJson(`${DEFINITIONS_PATH}/${id}`, "PATCH", body));
}
/** `DELETE /quest-definitions/{id}`: exactly one of `deleted` / `retired` is true. */
export interface DefinitionDeleteResult {
definition_id: number;
deleted: boolean;
retired: boolean;
/** The retired (now inactive) definition; null when it was deleted. */
definition: QuestDefinition | null;
}
/**
* Delete a task if it has no completion history; otherwise the API retires
* (deactivates) it. Retirement preserves the definition row, schedule rule,
* assignees, windows and ALL durable completion history. Like any
* deactivation it regenerates, so future UNCOMPLETED instances are cleared
* (rolling, regenerable rows) and not recreated while inactive; durable
* history lives only in the append-only `completion_events`.
*/
export async function deleteDefinition(id: number): Promise<DefinitionDeleteResult> {
return readJson<DefinitionDeleteResult>(
await apiFetch(`${DEFINITIONS_PATH}/${id}`, { method: "DELETE" }),
);
}
export const OCCURRENCES_PREVIEW_PATH = `${DEFINITIONS_PATH}/occurrences-preview`;
export interface OccurrencesPreviewOptions {
/**
* "YYYY-MM-DD"; the API defaults to the household-local today in the
* configured `timezone` (the API host's local time when that is empty).
*/
/** "YYYY-MM-DD"; the API defaults to its host's today. */
startDate?: string;
/** 1..50; the API defaults to 10. */
count?: number;
-162
View File
@@ -1,162 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { waitFor } from "@testing-library/react";
import { EVENTS_PATH, SseParser, openTransitionStream, type TransitionEvent } from "./events";
import { frame, testStream, type TestStream } from "./testStream";
import { storeTokens } from "../auth/oidc";
const COMPLETED = {
child_id: 1,
child_name: "Declan",
instance_id: 12,
quest_title: "Make bed",
window: "morning",
due_date: "2026-09-23",
due_time: null,
occurred_at: "2026-09-23T11:04:00Z",
};
const DAY_COMPLETE = {
child_id: 2,
child_name: "Maeve",
quests_due: 4,
quests_completed: 4,
occurred_at: "2026-09-23T12:00:00Z",
};
describe("SseParser", () => {
it("yields every frame from one chunk", () => {
const parser = new SseParser();
const events = parser.push(
frame("nestquest_quest_completed", COMPLETED) +
frame("nestquest_child_day_complete", DAY_COMPLETE),
);
expect(events).toEqual([
{ type: "nestquest_quest_completed", payload: COMPLETED },
{ type: "nestquest_child_day_complete", payload: DAY_COMPLETE },
]);
});
it("buffers a frame split across two chunks", () => {
const parser = new SseParser();
const text = frame("nestquest_quest_uncompleted", COMPLETED);
const cut = text.indexOf("Make");
expect(parser.push(text.slice(0, cut))).toEqual([]);
expect(parser.push(text.slice(cut))).toEqual([
{ type: "nestquest_quest_uncompleted", payload: COMPLETED },
]);
});
it("buffers a split inside the event name and the blank-line terminator", () => {
const parser = new SseParser();
const text = frame("nestquest_quest_missed", COMPLETED);
expect(parser.push(text.slice(0, 12))).toEqual([]);
expect(parser.push(text.slice(12, -1))).toEqual([]);
expect(parser.push(text.slice(-1))).toEqual([
{ type: "nestquest_quest_missed", payload: COMPLETED },
]);
});
it("treats a CRLF split across chunks as one line break", () => {
const parser = new SseParser();
const text = `event: nestquest_quest_completed\r\ndata: ${JSON.stringify(COMPLETED)}\r\n\r\n`;
const cut = text.indexOf("\n"); // chunk ends on "\r"
expect(parser.push(text.slice(0, cut))).toEqual([]);
expect(parser.push(text.slice(cut))).toEqual([
{ type: "nestquest_quest_completed", payload: COMPLETED },
]);
});
it("drops malformed, unknown and comment frames without throwing", () => {
const parser = new SseParser();
const events = parser.push(
"event: nestquest_quest_completed\ndata: not-json\n\n" +
"event: nestquest_quest_completed\ndata: [1,2]\n\n" +
"event: something_else\ndata: {}\n\n" +
": keep-alive\n\n" +
"data: {}\n\n" +
frame("nestquest_quest_completed", COMPLETED),
);
expect(events).toEqual([{ type: "nestquest_quest_completed", payload: COMPLETED }]);
});
});
describe("openTransitionStream", () => {
let fetchMock: ReturnType<typeof vi.fn>;
let streams: TestStream[];
let stop: (() => void) | null;
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
streams = [];
stop = null;
fetchMock = vi.fn(() => {
const stream = testStream();
streams.push(stream);
return Promise.resolve(stream.response);
});
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
stop?.();
vi.unstubAllGlobals();
});
it("sends the token in the Authorization header, never in the URL", async () => {
stop = openTransitionStream({ onTransition: () => {} });
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toMatch(new RegExp(`${EVENTS_PATH}$`));
expect(String(url)).not.toContain("at-123");
expect(init.headers.Authorization).toBe("Bearer at-123");
expect(init.headers.Accept).toBe("text/event-stream");
});
it("delivers transitions from frames split across chunks", async () => {
const seen: TransitionEvent[] = [];
stop = openTransitionStream({ onTransition: (event) => seen.push(event) });
await waitFor(() => expect(streams).toHaveLength(1));
const text = frame("nestquest_quest_completed", COMPLETED);
streams[0].push(text.slice(0, 20));
streams[0].push(text.slice(20));
await waitFor(() =>
expect(seen).toEqual([{ type: "nestquest_quest_completed", payload: COMPLETED }]),
);
});
it("stop aborts the request and cancels the body", async () => {
stop = openTransitionStream({ onTransition: () => {} });
await waitFor(() => expect(streams).toHaveLength(1));
const signal = fetchMock.mock.calls[0][1].signal as AbortSignal;
stop();
expect(signal.aborted).toBe(true);
await waitFor(() => expect(streams[0].cancelled()).toBe(true));
});
it("reconnects after the stream drops", async () => {
const seen: TransitionEvent[] = [];
stop = openTransitionStream({ onTransition: (event) => seen.push(event), minDelayMs: 5 });
await waitFor(() => expect(streams).toHaveLength(1));
streams[0].close();
await waitFor(() => expect(streams).toHaveLength(2));
streams[1].push(frame("nestquest_quest_missed", COMPLETED));
await waitFor(() => expect(seen).toHaveLength(1));
});
it("does not reconnect after stop, even with a reconnect pending", async () => {
stop = openTransitionStream({ onTransition: () => {}, minDelayMs: 20 });
await waitFor(() => expect(streams).toHaveLength(1));
streams[0].close();
stop();
await new Promise((resolve) => setTimeout(resolve, 60));
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it("gives up on a 403 refusal instead of retrying", async () => {
fetchMock.mockImplementation(() => Promise.resolve(new Response("", { status: 403 })));
stop = openTransitionStream({ onTransition: () => {}, minDelayMs: 5 });
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
await new Promise((resolve) => setTimeout(resolve, 40));
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
-196
View File
@@ -1,196 +0,0 @@
/**
* Live transition stream: GET /api/v1/admin/events (text/event-stream).
*
* The admin JWT travels in the Authorization header (via apiFetch), so the
* stream is read with fetch + a ReadableStream reader — EventSource cannot
* set headers, and the token must never go into a URL.
*/
import { ApiForbiddenError, ApiUnauthorizedError, apiFetch } from "./client";
export const EVENTS_PATH = "/api/v1/admin/events";
/** The four documented transitions, as the API names them on the wire. */
export const TRANSITION_TYPES = [
"nestquest_quest_completed",
"nestquest_quest_uncompleted",
"nestquest_quest_missed",
"nestquest_child_day_complete",
] as const;
export type TransitionType = (typeof TRANSITION_TYPES)[number];
/** Quest transitions carry the instance; a day-complete carries the child's counts. */
export interface QuestTransitionPayload {
child_id: number;
child_name: string | null;
instance_id: number;
quest_title: string | null;
window: string;
due_date: string;
due_time: string | null;
occurred_at: string;
}
export interface ChildDayCompletePayload {
child_id: number;
child_name: string | null;
quests_due: number;
quests_completed: number;
occurred_at: string;
}
export type TransitionEvent =
| {
type:
| "nestquest_quest_completed"
| "nestquest_quest_uncompleted"
| "nestquest_quest_missed";
payload: QuestTransitionPayload;
}
| { type: "nestquest_child_day_complete"; payload: ChildDayCompletePayload };
function isTransitionType(value: string): value is TransitionType {
return (TRANSITION_TYPES as readonly string[]).includes(value);
}
/**
* Incremental SSE frame parser. Feed it decoded text in whatever chunks the
* network delivers; it buffers a partial line or frame until it completes.
* Comments (keep-alives), unknown event types and frames whose data is not a
* JSON object are dropped, never thrown.
*/
export class SseParser {
private buffer = "";
private eventType = "";
private data: string[] = [];
/** A chunk ended on "\r": a leading "\n" in the next chunk is the same line break. */
private pendingCr = false;
push(text: string): TransitionEvent[] {
if (this.pendingCr && text.startsWith("\n")) text = text.slice(1);
this.pendingCr = text.endsWith("\r");
this.buffer += text;
const lines = this.buffer.split(/\r\n|\r|\n/);
this.buffer = lines.pop() ?? "";
const events: TransitionEvent[] = [];
for (const line of lines) {
const event = this.line(line);
if (event) events.push(event);
}
return events;
}
private line(line: string): TransitionEvent | null {
if (line === "") return this.dispatch();
if (line.startsWith(":")) return null;
const colon = line.indexOf(":");
const field = colon === -1 ? line : line.slice(0, colon);
let value = colon === -1 ? "" : line.slice(colon + 1);
if (value.startsWith(" ")) value = value.slice(1);
if (field === "event") this.eventType = value;
else if (field === "data") this.data.push(value);
return null;
}
private dispatch(): TransitionEvent | null {
const type = this.eventType;
const data = this.data.join("\n");
this.eventType = "";
this.data = [];
if (!isTransitionType(type)) return null;
let payload: unknown;
try {
payload = JSON.parse(data);
} catch {
return null;
}
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
return { type, payload } as TransitionEvent;
}
}
export interface TransitionStreamOptions {
onTransition: (event: TransitionEvent) => void;
/** Reconnect delay after a drop: starts at `minDelayMs`, doubles up to `maxDelayMs`. */
minDelayMs?: number;
maxDelayMs?: number;
}
function wait(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve) => {
const timer = setTimeout(done, ms);
signal.addEventListener("abort", done, { once: true });
function done() {
clearTimeout(timer);
signal.removeEventListener("abort", done);
resolve();
}
});
}
/** Read one connection until the body ends (or the signal aborts). */
async function readOnce(
signal: AbortSignal,
onTransition: (event: TransitionEvent) => void,
): Promise<void> {
const response = await apiFetch(EVENTS_PATH, {
signal,
headers: { Accept: "text/event-stream" },
});
if (!response.ok || !response.body) {
throw new Error(`Event stream request failed (HTTP ${response.status}).`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
const parser = new SseParser();
const cancel = () => void reader.cancel().catch(() => {});
signal.addEventListener("abort", cancel, { once: true });
try {
for (;;) {
const { value, done } = await reader.read();
if (done || signal.aborted) break;
for (const event of parser.push(decoder.decode(value, { stream: true }))) {
if (signal.aborted) break;
onTransition(event);
}
}
} finally {
signal.removeEventListener("abort", cancel);
reader.releaseLock();
}
}
/**
* Subscribe to the admin transition stream, reconnecting with a bounded
* backoff after a drop. Returns a stop function that aborts the open request
* and any pending reconnect. A 401/403 stops the stream for good: apiFetch
* has already started a login (401) or the account is refused (403).
*/
export function openTransitionStream({
onTransition,
minDelayMs = 1_000,
maxDelayMs = 30_000,
}: TransitionStreamOptions): () => void {
const controller = new AbortController();
const { signal } = controller;
void (async () => {
let delay = minDelayMs;
while (!signal.aborted) {
try {
await readOnce(signal, onTransition);
// A connection that was accepted and then ended starts the backoff over.
delay = minDelayMs;
} catch (error: unknown) {
if (signal.aborted) return;
if (error instanceof ApiUnauthorizedError || error instanceof ApiForbiddenError) return;
// Dropped or refused connection: fall through to the backoff.
}
if (signal.aborted) return;
await wait(delay, signal);
delay = Math.min(delay * 2, maxDelayMs);
}
})();
return () => controller.abort();
}
-23
View File
@@ -1,23 +0,0 @@
/**
* Typed client for the admin instance mutation route
* (POST /api/v1/admin/instances/{id}/uncomplete).
*/
import { apiFetch } from "./client";
import { readJson } from "./definitions";
export interface UncompleteResult {
instance_id: number;
/** The derived state after the reversal: "open", or "missed" when past due. */
state: string;
/** False when the instance was already open (a no-op). */
appended: boolean;
}
export function uncompletePath(instanceId: number): string {
return `/api/v1/admin/instances/${instanceId}/uncomplete`;
}
/** Reverse one completion; raises ApiRequestError with the API's detail on failure. */
export async function uncompleteInstance(instanceId: number): Promise<UncompleteResult> {
return readJson<UncompleteResult>(await apiFetch(uncompletePath(instanceId), { method: "POST" }));
}
+36 -56
View File
@@ -1,35 +1,25 @@
/**
* Typed client for the admin presence routes: a child's repeating patterns
* (/api/v1/admin/children/{id}/presence-patterns, /presence-patterns/{id})
* and the household's date-range overrides (/api/v1/admin/presence-overrides).
* Typed client for the admin presence routes: a child's repeating schedule
* (/api/v1/admin/children/{id}/presence-schedule) and the household's
* date-range overrides (/api/v1/admin/presence-overrides).
*/
import { apiFetch } from "./client";
import { CHILDREN_PATH, readJson } from "./definitions";
/** A pattern claims its covered days as the child being home or away. */
export type PatternKind = "home" | "away";
/**
* Cycle week index ("0".."n-1", JSON object keys) -> covered weekdays
* (0 = Monday .. 6 = Sunday). An empty list covers nothing that week.
* Cycle week index ("0".."n-1", JSON object keys) -> present weekdays
* (0 = Monday .. 6 = Sunday). An empty list is away that whole week.
*/
export type PatternWeeks = Record<string, number[]>;
export type PresencePattern = Record<string, number[]>;
/** The anchor-based cycle every pattern repeats on. */
export interface PatternCycle {
export interface PresenceScheduleBody {
cycle_length_weeks: number;
/** "YYYY-MM-DD"; pins cycle week 0. */
anchor_date: string;
pattern: PatternWeeks;
pattern: PresencePattern;
}
export interface PresencePatternBody extends PatternCycle {
name: string;
kind: PatternKind;
}
export interface PresencePattern extends PresencePatternBody {
id: number;
export interface PresenceSchedule extends PresenceScheduleBody {
child_id: number;
}
@@ -50,48 +40,30 @@ export interface PresenceOverrideFilter {
}
export const PRESENCE_OVERRIDES_PATH = "/api/v1/admin/presence-overrides";
export const PRESENCE_PATTERNS_PATH = "/api/v1/admin/presence-patterns";
export function childPatternsPath(childId: number): string {
return `${CHILDREN_PATH}/${childId}/presence-patterns`;
export function presenceSchedulePath(childId: number): string {
return `${CHILDREN_PATH}/${childId}/presence-schedule`;
}
function sendJson(path: string, method: "POST" | "PATCH", body: unknown): Promise<Response> {
return apiFetch(path, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}
/** The child's patterns in id order; empty when it has none (present every day). */
export async function fetchPresencePatterns(childId: number): Promise<PresencePattern[]> {
const body = await readJson<{ patterns: PresencePattern[] }>(
await apiFetch(childPatternsPath(childId)),
/** The child's schedule, or null when it has none (present every day). */
export async function fetchPresenceSchedule(childId: number): Promise<PresenceSchedule | null> {
const body = await readJson<{ schedule: PresenceSchedule | null }>(
await apiFetch(presenceSchedulePath(childId)),
);
return body.patterns;
return body.schedule;
}
export async function createPresencePattern(
/** Set (upsert) the child's schedule; resolves to the schedule as stored. */
export async function savePresenceSchedule(
childId: number,
body: PresencePatternBody,
): Promise<PresencePattern> {
return readJson<PresencePattern>(await sendJson(childPatternsPath(childId), "POST", body));
}
/** Change only the supplied fields; resolves to the pattern as stored. */
export async function updatePresencePattern(
patternId: number,
body: Partial<PresencePatternBody>,
): Promise<PresencePattern> {
return readJson<PresencePattern>(
await sendJson(`${PRESENCE_PATTERNS_PATH}/${patternId}`, "PATCH", body),
);
}
export async function deletePresencePattern(patternId: number): Promise<void> {
await readJson<{ status: string }>(
await apiFetch(`${PRESENCE_PATTERNS_PATH}/${patternId}`, { method: "DELETE" }),
body: PresenceScheduleBody,
): Promise<PresenceSchedule> {
return readJson<PresenceSchedule>(
await apiFetch(presenceSchedulePath(childId), {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}),
);
}
@@ -124,19 +96,27 @@ export interface PresenceOverrideBody extends PresenceOverrideRange {
export const PRESENCE_OVERRIDE_CONSEQUENCE_PATH = `${PRESENCE_OVERRIDES_PATH}/consequence`;
function postJson(path: string, body: unknown): Promise<Response> {
return apiFetch(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}
/**
* How many open upcoming tasks saving this override would remove. Computed
* by the API before anything is saved; completed instances never count.
*/
export async function previewOverrideConsequence(range: PresenceOverrideRange): Promise<number> {
const body = await readJson<{ removed: number }>(
await sendJson(PRESENCE_OVERRIDE_CONSEQUENCE_PATH, "POST", range),
await postJson(PRESENCE_OVERRIDE_CONSEQUENCE_PATH, range),
);
return body.removed;
}
export async function createPresenceOverride(body: PresenceOverrideBody): Promise<PresenceOverride> {
return readJson<PresenceOverride>(await sendJson(PRESENCE_OVERRIDES_PATH, "POST", body));
return readJson<PresenceOverride>(await postJson(PRESENCE_OVERRIDES_PATH, body));
}
export async function deletePresenceOverride(overrideId: number): Promise<void> {
-46
View File
@@ -1,46 +0,0 @@
/**
* Typed client for the admin household-settings routes
* (/api/v1/admin/settings).
*/
import { apiFetch } from "./client";
import { readJson } from "./definitions";
export interface HouseholdSettings {
horizon_days: number;
/** Local wall-clock "HH:MM", as are the other *_time fields. */
day_rollover_time: string;
notify_target: string;
morning_summary_time: string;
afternoon_reminder_time: string;
end_of_day_report_time: string;
morning_summary_enabled: boolean;
afternoon_reminder_enabled: boolean;
end_of_day_report_enabled: boolean;
celebration_enabled: boolean;
/** IANA zone name (e.g. "America/New_York"); "" means the API host's local time. */
timezone: string;
/**
* Read-only: the zone the API reads its clock in — `timezone`, or the API
* host's own zone when that is "" ("" only when the host's zone has no name).
*/
effective_timezone: string;
}
/** Only the supplied fields are updated; the API answers with all of them. */
export type SettingsChanges = Partial<Omit<HouseholdSettings, "effective_timezone">>;
export const SETTINGS_PATH = "/api/v1/admin/settings";
export async function fetchSettings(): Promise<HouseholdSettings> {
return readJson<HouseholdSettings>(await apiFetch(SETTINGS_PATH));
}
export async function updateSettings(changes: SettingsChanges): Promise<HouseholdSettings> {
return readJson<HouseholdSettings>(
await apiFetch(SETTINGS_PATH, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(changes),
}),
);
}
-39
View File
@@ -1,39 +0,0 @@
/**
* Test helper: a controllable text/event-stream Response whose body the test
* feeds chunk by chunk (so a frame can be split across chunk boundaries).
*/
export interface TestStream {
response: Response;
push(text: string): void;
close(): void;
/** True once the reader cancelled the body (the stream was torn down). */
cancelled(): boolean;
}
export function testStream(): TestStream {
const encoder = new TextEncoder();
let controller!: ReadableStreamDefaultController<Uint8Array>;
let cancelled = false;
const body = new ReadableStream<Uint8Array>({
start(c) {
controller = c;
},
cancel() {
cancelled = true;
},
});
return {
response: new Response(body, {
status: 200,
headers: { "Content-Type": "text/event-stream" },
}),
push: (text) => controller.enqueue(encoder.encode(text)),
close: () => controller.close(),
cancelled: () => cancelled,
};
}
/** One SSE frame exactly as api/sse.py writes it. */
export function frame(type: string, payload: unknown): string {
return `event: ${type}\ndata: ${JSON.stringify(payload)}\n\n`;
}
-61
View File
@@ -1,61 +0,0 @@
/**
* One live transition stream per signed-in shell, fanned out to the screens.
*
* <TransitionsProvider> opens the stream on mount and aborts it on unmount;
* useTransitions(handler) registers a screen's handler for as long as the
* screen is mounted. Without a provider the hook does nothing, so a screen
* rendered on its own (e.g. in a test) never opens a stream.
*/
import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react";
import { openTransitionStream, type TransitionEvent } from "./events";
type Listener = (event: TransitionEvent) => void;
interface TransitionHub {
subscribe(listener: Listener): () => void;
}
const TransitionsContext = createContext<TransitionHub | null>(null);
export function TransitionsProvider({ children }: { children: ReactNode }) {
const [hub] = useState(() => {
const listeners = new Set<Listener>();
return {
listeners,
subscribe(listener: Listener) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
};
});
useEffect(
() =>
openTransitionStream({
onTransition: (event) => {
for (const listener of [...hub.listeners]) {
try {
listener(event);
} catch {
// One screen's handler must not tear down the shared stream.
}
}
},
}),
[hub],
);
return <TransitionsContext.Provider value={hub}>{children}</TransitionsContext.Provider>;
}
/** Call `handler` for every transition while the calling component is mounted. */
export function useTransitions(handler: Listener): void {
const hub = useContext(TransitionsContext);
const handlerRef = useRef(handler);
useEffect(() => {
handlerRef.current = handler;
});
useEffect(() => hub?.subscribe((event) => handlerRef.current(event)), [hub]);
}
-62
View File
@@ -569,26 +569,6 @@
color: #fff;
}
.defs-save--danger {
background: var(--nq-a-danger);
}
.defs-delete {
display: block;
width: 100%;
margin-top: 10px;
padding: 11px 0;
border: 1px solid var(--nq-a-danger-bg);
border-radius: var(--nq-a-density-radius);
background: var(--nq-a-surface);
color: var(--nq-a-danger-strong);
font-family: inherit;
font-size: 13px;
font-weight: 700;
cursor: pointer;
}
.defs-delete:disabled,
.defs-cancel:disabled,
.defs-save:disabled {
opacity: 0.6;
@@ -603,45 +583,3 @@
color: var(--nq-a-ink-secondary);
font-style: italic;
}
.defs-sublabel {
margin-top: 4px;
font-size: 12px;
font-weight: 700;
color: var(--nq-a-ink-secondary);
}
.defs-emoji {
line-height: 1;
}
/* Font Awesome search: glyph + label tiles, inline validation, paging */
.defs-icon-grid--results {
grid-template-columns: repeat(auto-fill, minmax(88px, 1fr));
}
.defs-icon-result {
flex-direction: column;
gap: 4px;
padding: 6px 4px;
font-family: inherit;
}
.defs-icon-label {
max-width: 100%;
overflow: hidden;
font-size: 11px;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.defs-hint--error {
color: var(--nq-a-danger-strong);
}
.defs-show-more {
align-self: flex-start;
display: flex;
gap: 8px;
}
File diff suppressed because it is too large Load Diff
+54 -301
View File
@@ -4,7 +4,6 @@
*/
import {
useEffect,
useMemo,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
@@ -14,14 +13,12 @@ import { ApiForbiddenError } from "../api/client";
import {
ApiRequestError,
createDefinition,
deleteDefinition,
fetchChildren,
fetchDefinitions,
previewOccurrences,
updateDefinition,
type AdminChild,
type DefinitionCreateBody,
type DefinitionDeleteResult,
type DefinitionEditBody,
type DefinitionRule,
type QuestDefinition,
@@ -30,7 +27,6 @@ import {
} from "../api/definitions";
import {
MONTH_SHORT,
WEEKDAY_DISPLAY_ORDER,
WEEKDAY_SHORT,
WINDOW_LABELS,
WINDOW_ORDER,
@@ -46,25 +42,7 @@ import {
PlusGlyph,
TaskGlyph,
} from "./glyphs";
import {
DEFINITION_ICONS,
DefinitionIcon,
FA_DEFINITION_ICONS,
emojiIconKey,
emojiIconText,
faIconKey,
faIconName,
faTextProblem,
faTypedIconKey,
findDefinitionIcon,
lucideIconKey,
normalizeDefinitionIconName,
searchFaIcons,
} from "./definitionIcons";
import { GlyphSvg } from "../icons/GlyphSvg";
import { weekdayOf } from "../schedule/cycle";
import { useAppTimezone } from "../time/AppTimezone";
import { todayIn } from "../time/zone";
import { DEFINITION_ICONS, DefinitionIcon } from "./definitionIcons";
import "./DefinitionsTab.css";
/** ADMIN-SPEC §1: every scroll column ends with 92px so content clears the tab bar. */
@@ -92,9 +70,6 @@ const REPEATS_BY_RULE: Record<DefinitionRule["rule_type"], Repeats> = {
/** How many upcoming dates the edit sheet previews. */
const PREVIEW_COUNT = 5;
/** Font Awesome search results per page; only one page is ever mounted. */
const FA_RESULTS_PAGE = 40;
/** Quiet period after the last rule edit before the preview is requested. */
const PREVIEW_DEBOUNCE_MS = 300;
@@ -102,18 +77,8 @@ const WEEKDAY_LONG = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "S
interface Draft {
title: string;
/**
* The stored icon key (`lucide:`, `fa:` or `emoji:`); a legacy value
* outside the curated sets is kept until replaced.
*/
/** A Lucide name; a legacy value outside the subset is kept until replaced. */
icon: string | null;
/** The emoji field's text; typing in it sets `icon` to `emoji:<text>`. */
emoji: string;
/**
* The Font Awesome search text; typing an exact Free Solid name sets
* `icon` to `fa:<name>`, and picking a search result keeps the text.
*/
faText: string;
assigneeIds: number[];
repeats: Repeats;
interval: string;
@@ -137,47 +102,48 @@ type LoadState =
/** `null` = closed, `"new"` = creating, a definition = editing it. */
type SheetTarget = null | "new" | QuestDefinition;
function pad2(n: number): string {
return String(n).padStart(2, "0");
}
function localIsoDate(date: Date): string {
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
}
function emptyDueTimes(): Record<WindowName, string> {
return { morning: "", afternoon: "", evening: "" };
}
/** Draft defaults take `today` ("YYYY-MM-DD") in the application timezone. */
function newDraft(activeChildren: AdminChild[], today: string): Draft {
const [, month, day] = today.split("-").map(Number);
function newDraft(activeChildren: AdminChild[]): Draft {
const today = new Date();
return {
title: "",
icon: null,
emoji: "",
faText: "",
assigneeIds: activeChildren.length === 1 ? [activeChildren[0].id] : [],
repeats: "daily",
interval: "1",
weekdays: [weekdayOf(today)],
dayOfMonth: String(day),
month: String(month),
weekdays: [(today.getDay() + 6) % 7],
dayOfMonth: String(today.getDate()),
month: String(today.getMonth() + 1),
monthlyWeekday: null,
windows: [],
dueTimes: emptyDueTimes(),
// Mirrors the API's create default: no instance on an away day.
skipOnAway: true,
startDate: today,
startDate: localIsoDate(today),
endDate: null,
};
}
function draftFrom(definition: QuestDefinition, activeChildren: AdminChild[], today: string): Draft {
function draftFrom(definition: QuestDefinition, activeChildren: AdminChild[]): Draft {
const { rule } = definition;
const [, month, day] = today.split("-").map(Number);
const today = new Date();
const active = new Set(activeChildren.map((child) => child.id));
const dueTimes = emptyDueTimes();
for (const w of definition.windows) dueTimes[w.window] = w.due_time ?? "";
const fa = findDefinitionIcon(definition.icon);
return {
title: definition.title,
icon: definition.icon,
emoji: emojiIconText(definition.icon),
// A Free Solid icon outside the quick picks opens as its search result.
faText: fa?.kind === "fa" && !FA_DEFINITION_ICONS.includes(fa) ? fa.name : "",
// Inactive children cannot be submitted (the API rejects them with 422).
assigneeIds: definition.assignees.map((a) => a.id).filter((id) => active.has(id)),
repeats: REPEATS_BY_RULE[rule.rule_type],
@@ -185,9 +151,9 @@ function draftFrom(definition: QuestDefinition, activeChildren: AdminChild[], to
weekdays:
rule.rule_type === "weekly" || rule.rule_type === "custom_days"
? [...(rule.weekday_set ?? [])]
: [weekdayOf(today)],
dayOfMonth: String(rule.day_of_month ?? day),
month: String(rule.month ?? month),
: [(today.getDay() + 6) % 7],
dayOfMonth: String(rule.day_of_month ?? today.getDate()),
month: String(rule.month ?? today.getMonth() + 1),
monthlyWeekday:
rule.rule_type === "monthly_weekday"
? { nth: rule.nth_weekday ?? 1, weekday: rule.nth_weekday_weekday ?? 0 }
@@ -210,7 +176,6 @@ function parseWhole(value: string, min: number, max: number): number | null {
function buildRule(draft: Draft): DefinitionRule | string {
const interval = parseWhole(draft.interval, 1, 999);
if (interval === null) return "Interval must be a whole number of at least 1.";
if (draft.startDate === "") return "Pick a start date.";
const rule: DefinitionRule = {
rule_type: "daily",
interval,
@@ -264,10 +229,6 @@ function buildBody(draft: Draft, keepsAssignees = false): DefinitionCreateBody |
if (!title) return "Give the task a title.";
if (draft.assigneeIds.length === 0 && !keepsAssignees) return "Assign at least one child.";
if (draft.windows.length === 0) return "Pick at least one window.";
if (draft.emoji && draft.icon === null) {
return "Enter a single emoji (no spaces or < > &), or clear the emoji field.";
}
if (draft.faText.trim() && draft.icon === null) return faTextProblem(draft.faText);
const rule = buildRule(draft);
if (typeof rule === "string") return rule;
const windows: WindowEntry[] = WINDOW_ORDER.filter((w) => draft.windows.includes(w)).map(
@@ -289,12 +250,6 @@ function saveErrorMessage(error: unknown): string {
return "The task could not be saved. Check your connection and try again.";
}
function deleteErrorMessage(error: unknown): string {
if (error instanceof ApiForbiddenError) return error.message;
if (error instanceof ApiRequestError && error.detail) return error.detail;
return "The task could not be deleted. Check your connection and try again.";
}
function toggle<T>(list: T[], value: T): T[] {
return list.includes(value) ? list.filter((item) => item !== value) : [...list, value];
}
@@ -471,40 +426,26 @@ function EditSheet({
activeChildren,
onCancel,
onSaved,
onDeleted,
}: {
target: "new" | QuestDefinition;
activeChildren: AdminChild[];
onCancel: () => void;
onSaved: () => void;
onDeleted: (result: DefinitionDeleteResult) => void;
}) {
const timeZone = useAppTimezone();
const [draft, setDraft] = useState<Draft>(() => {
const today = todayIn(timeZone);
return target === "new" ? newDraft(activeChildren, today) : draftFrom(target, activeChildren, today);
});
const [draft, setDraft] = useState<Draft>(() =>
target === "new" ? newDraft(activeChildren) : draftFrom(target, activeChildren),
);
// The active selection as loaded: while it is unchanged, the PATCH omits
// assignee_child_ids, because the API replaces the whole set and inactive
// children cannot be sent back.
const [originalActiveIds] = useState(() => draft.assigneeIds);
// The icon as loaded: while it is unchanged, the PATCH omits `icon` (absent
// means unchanged), because a legacy value read back as `lucide:<old>` would
// fail the API's strict icon validation if sent back.
const [originalIcon] = useState(() => draft.icon);
const inactiveAssignees =
target === "new"
? []
: target.assignees.filter((a) => !activeChildren.some((child) => child.id === a.id));
const [pickerOpen, setPickerOpen] = useState(false);
const faResults = useMemo(() => searchFaIcons(draft.faText), [draft.faText]);
const [faPage, setFaPage] = useState(0);
const faStart = faPage * FA_RESULTS_PAGE;
const faEnd = Math.min(faStart + FA_RESULTS_PAGE, faResults.length);
const noIcon = draft.icon === null && !draft.emoji && !draft.faText.trim();
const [saving, setSaving] = useState(false);
const [confirming, setConfirming] = useState(false);
const [confirmingDelete, setConfirmingDelete] = useState(false);
const [error, setError] = useState<string | null>(null);
// A ref, not state: two taps in one frame must not both see `saving === false`.
const inFlight = useRef(false);
@@ -522,8 +463,8 @@ function EditSheet({
}, []);
useEffect(() => {
if (confirming || confirmingDelete) confirmRef.current?.focus();
}, [confirming, confirmingDelete]);
if (confirming) confirmRef.current?.focus();
}, [confirming]);
function onKeyDown(event: ReactKeyboardEvent<HTMLDivElement>) {
if (event.key === "Escape") {
@@ -580,7 +521,6 @@ function EditSheet({
} else {
const edit: DefinitionEditBody = { ...body };
if (keepsAssignees) delete edit.assignee_child_ids;
if (draft.icon === originalIcon) delete edit.icon;
await updateDefinition(target.id, edit);
}
onSaved();
@@ -591,21 +531,6 @@ function EditSheet({
}
}
async function remove() {
if (target === "new" || inFlight.current) return;
setConfirmingDelete(false);
inFlight.current = true;
setSaving(true);
setError(null);
try {
onDeleted(await deleteDefinition(target.id));
} catch (err) {
setError(deleteErrorMessage(err));
inFlight.current = false;
setSaving(false);
}
}
return (
<div className="defs-sheet-layer">
<div
@@ -642,134 +567,28 @@ function EditSheet({
<button
type="button"
role="radio"
aria-checked={noIcon}
aria-checked={draft.icon === null}
aria-label="No icon"
className={noIcon ? "defs-icon defs-icon--on" : "defs-icon"}
onClick={() => update({ icon: null, emoji: "", faText: "" })}
className={draft.icon === null ? "defs-icon defs-icon--on" : "defs-icon"}
onClick={() => update({ icon: null })}
>
<TaskGlyph size={18} />
</button>
{DEFINITION_ICONS.map((icon) => {
const { name, label } = icon;
const on = normalizeDefinitionIconName(draft.icon) === name;
return (
<button
key={name}
type="button"
role="radio"
aria-checked={on}
aria-label={label}
data-icon-option={name}
className={on ? "defs-icon defs-icon--on" : "defs-icon"}
onClick={() => update({ icon: lucideIconKey(name), emoji: "", faText: "" })}
>
<GlyphSvg icon={icon} size={18} />
</button>
);
})}
{DEFINITION_ICONS.map(({ name, label, Icon }) => (
<button
key={name}
type="button"
role="radio"
aria-checked={draft.icon === name}
aria-label={label}
data-icon-option={name}
className={draft.icon === name ? "defs-icon defs-icon--on" : "defs-icon"}
onClick={() => update({ icon: name })}
>
<Icon size={18} aria-hidden="true" focusable="false" />
</button>
))}
</div>
<span className="defs-sublabel" id="defs-label-icon-fa">
Font Awesome
</span>
<input
className="defs-input"
type="search"
aria-label="Search Font Awesome icons"
placeholder="Search or type an icon name, e.g. dog"
value={draft.faText}
onChange={(e) => {
setFaPage(0);
update({ faText: e.target.value, icon: faTypedIconKey(e.target.value), emoji: "" });
}}
/>
{draft.faText.trim() && draft.icon === null ? (
<p className="defs-hint defs-hint--error" role="alert">
{faTextProblem(draft.faText)}
</p>
) : null}
{draft.faText.trim() ? (
faResults.length > 0 ? (
<>
<div
className="defs-icon-grid defs-icon-grid--results"
role="radiogroup"
aria-label="Font Awesome search results"
>
{faResults.slice(faStart, faEnd).map((icon) => {
const { name, label } = icon;
const on = faIconName(draft.icon) === name;
return (
<button
key={name}
type="button"
role="radio"
aria-checked={on}
aria-label={label}
data-icon-option={faIconKey(name)}
className={
on ? "defs-icon defs-icon-result defs-icon--on" : "defs-icon defs-icon-result"
}
onClick={() => update({ icon: faIconKey(name), emoji: "" })}
>
<GlyphSvg icon={icon} size={18} />
<span className="defs-icon-label">{label}</span>
</button>
);
})}
</div>
<p className="defs-hint">
Showing {faStart + 1}–{faEnd} of {faResults.length}
</p>
{faResults.length > FA_RESULTS_PAGE ? (
<div className="defs-show-more">
{faPage > 0 ? (
<button type="button" className="defs-retry" onClick={() => setFaPage((page) => page - 1)}>
Previous
</button>
) : null}
{faEnd < faResults.length ? (
<button type="button" className="defs-retry" onClick={() => setFaPage((page) => page + 1)}>
Show more
</button>
) : null}
</div>
) : null}
</>
) : null
) : (
<div className="defs-icon-grid" role="radiogroup" aria-labelledby="defs-label-icon-fa">
{FA_DEFINITION_ICONS.map((icon) => {
const { name, label } = icon;
const on = faIconName(draft.icon) === name;
return (
<button
key={name}
type="button"
role="radio"
aria-checked={on}
aria-label={label}
data-icon-option={faIconKey(name)}
className={on ? "defs-icon defs-icon--on" : "defs-icon"}
onClick={() => update({ icon: faIconKey(name), emoji: "", faText: "" })}
>
<GlyphSvg icon={icon} size={18} />
</button>
);
})}
</div>
)}
<label className="defs-due">
<span>Emoji</span>
<input
className="defs-input"
aria-label="Emoji"
placeholder="e.g. 🐶"
value={draft.emoji}
onChange={(e) =>
update({ emoji: e.target.value, icon: emojiIconKey(e.target.value), faText: "" })
}
/>
</label>
</Field>
<Field label="Assigned children" id="defs-label-children">
@@ -861,9 +680,9 @@ function EditSheet({
</div>
{draft.repeats === "weekly" || draft.repeats === "custom" ? (
<div className="defs-weekdays" role="group" aria-label="Days">
{WEEKDAY_DISPLAY_ORDER.map((day) => (
{WEEKDAY_SHORT.map((label, day) => (
<button
key={day}
key={label}
type="button"
aria-pressed={draft.weekdays.includes(day)}
aria-label={WEEKDAY_LONG[day]}
@@ -872,7 +691,7 @@ function EditSheet({
}
onClick={() => update({ weekdays: toggle(draft.weekdays, day) })}
>
{WEEKDAY_SHORT[day].charAt(0)}
{label.charAt(0)}
</button>
))}
</div>
@@ -920,16 +739,6 @@ function EditSheet({
<OccurrencePreview ruleKey={previewKey} />
</Field>
<Field label="Start date" id="defs-label-start">
<input
className="defs-input"
type="date"
aria-labelledby="defs-label-start"
value={draft.startDate}
onChange={(e) => update({ startDate: e.target.value })}
/>
</Field>
<Field label="Due time" id="defs-label-due">
{orderedWindows.length === 0 ? (
<p className="defs-hint">Pick a window to set its due time.</p>
@@ -1020,56 +829,15 @@ function EditSheet({
</button>
</div>
</div>
) : confirmingDelete ? (
<div
className="defs-confirm"
role="group"
aria-labelledby="defs-delete-confirm-text"
data-testid="delete-confirm"
ref={confirmRef}
tabIndex={-1}
>
<p id="defs-delete-confirm-text">
Delete this task? If it has no completion history it is deleted; otherwise it is
retired (deactivated) and its history is kept.
</p>
<div className="defs-sheet-footer">
<button
type="button"
className="defs-cancel"
onClick={() => setConfirmingDelete(false)}
>
Go back
</button>
<button type="button" className="defs-save defs-save--danger" onClick={remove}>
Delete task
</button>
</div>
</div>
) : (
<>
<div className="defs-sheet-footer">
<button type="button" className="defs-cancel" onClick={onCancel} disabled={saving}>
Cancel
</button>
<button type="button" className="defs-save" onClick={() => save()} disabled={saving}>
{saving ? "Saving…" : "Save changes"}
</button>
</div>
{target !== "new" ? (
<button
type="button"
className="defs-delete"
disabled={saving}
onClick={() => {
setError(null);
setConfirmingDelete(true);
}}
>
Delete task
</button>
) : null}
</>
<div className="defs-sheet-footer">
<button type="button" className="defs-cancel" onClick={onCancel} disabled={saving}>
Cancel
</button>
<button type="button" className="defs-save" onClick={() => save()} disabled={saving}>
{saving ? "Saving…" : "Save changes"}
</button>
</div>
)}
</div>
</div>
@@ -1193,21 +961,6 @@ export default function DefinitionsTab() {
setSheet(null);
setAttempt((n) => n + 1);
}}
onDeleted={(result) => {
setSheet(null);
setState((current) =>
current.kind !== "ready"
? current
: {
...current,
definitions: result.definition
? current.definitions.map((d) =>
d.id === result.definition_id ? result.definition! : d,
)
: current.definitions.filter((d) => d.id !== result.definition_id),
},
);
}}
/>
) : null}
</div>
+92 -124
View File
@@ -1,135 +1,103 @@
/**
* The icons a definition's `icon` may name (ADMIN-SPEC §3.3): the curated
* Lucide set, any icon in the full Font Awesome Free Solid set, or an emoji.
* The Font Awesome quick picks (`FA_DEFINITION_ICONS`) are only a curated
* shortcut list; `fa:<name>` resolves against the full set
* (`FA_SOLID_ICONS`). The names, labels and path data come from the shared
* icon registry (`src/icons/registry.generated.ts`, generated by
* `tools/icons/generate.mjs` from `tools/icons/curated-icons.json` and the
* installed Free Solid package) — no CDN, no runtime fetch. The stored value
* is namespaced — `lucide:<name>`, `fa:<name>` or `emoji:<grapheme>` — and a
* legacy bare `<kebab-name>` still names the same Lucide entry.
* The shipped Lucide subset a definition's `icon` may name (ADMIN-SPEC §3.3).
* Only these named imports are bundled — no CDN, no runtime fetch. The stored
* value is the Lucide kebab-case name, so it stays meaningful to any surface.
*/
import { GlyphSvg } from "../icons/GlyphSvg";
import {
FA_ICONS,
FA_SOLID_ICONS,
LUCIDE_ICONS,
resolveIcon,
type GlyphIcon,
} from "../icons/registry.generated";
Apple,
Backpack,
Bath,
Bed,
Bike,
BookOpen,
Brush,
BrushCleaning,
Calendar,
Cat,
Clock,
CookingPot,
Dog,
Droplets,
Fish,
Gamepad2,
Heart,
House,
ListChecks,
Moon,
Music,
Pencil,
Recycle,
Shirt,
ShowerHead,
Smile,
Sofa,
SprayCan,
Sprout,
Star,
Sun,
Toilet,
Trash2,
Utensils,
Volleyball,
WashingMachine,
type LucideIcon,
} from "lucide-react";
import { TaskGlyph } from "./glyphs";
export type DefinitionIconEntry = GlyphIcon;
export const DEFINITION_ICONS: readonly DefinitionIconEntry[] = LUCIDE_ICONS;
export const FA_DEFINITION_ICONS: readonly DefinitionIconEntry[] = FA_ICONS;
const LUCIDE_PREFIX = "lucide:";
const FA_PREFIX = "fa:";
const EMOJI_PREFIX = "emoji:";
/** The canonical stored key for a Lucide choice, e.g. `lucide:dog`. */
export function lucideIconKey(name: string): string {
return `${LUCIDE_PREFIX}${name}`;
export interface DefinitionIconEntry {
name: string;
label: string;
Icon: LucideIcon;
}
/** The canonical stored key for a Font Awesome choice, e.g. `fa:dog`. */
export function faIconKey(name: string): string {
return `${FA_PREFIX}${name}`;
export const DEFINITION_ICONS: readonly DefinitionIconEntry[] = [
{ name: "bed", label: "Bed", Icon: Bed },
{ name: "bath", label: "Bath", Icon: Bath },
{ name: "shower-head", label: "Shower", Icon: ShowerHead },
{ name: "toilet", label: "Toilet", Icon: Toilet },
{ name: "brush", label: "Brush", Icon: Brush },
{ name: "smile", label: "Smile", Icon: Smile },
{ name: "shirt", label: "Clothes", Icon: Shirt },
{ name: "washing-machine", label: "Laundry", Icon: WashingMachine },
{ name: "utensils", label: "Meal", Icon: Utensils },
{ name: "cooking-pot", label: "Cooking", Icon: CookingPot },
{ name: "apple", label: "Snack", Icon: Apple },
{ name: "brush-cleaning", label: "Sweep", Icon: BrushCleaning },
{ name: "spray-can", label: "Clean", Icon: SprayCan },
{ name: "trash-2", label: "Bins", Icon: Trash2 },
{ name: "recycle", label: "Recycling", Icon: Recycle },
{ name: "sofa", label: "Tidy", Icon: Sofa },
{ name: "house", label: "Home", Icon: House },
{ name: "backpack", label: "School bag", Icon: Backpack },
{ name: "book-open", label: "Reading", Icon: BookOpen },
{ name: "pencil", label: "Homework", Icon: Pencil },
{ name: "music", label: "Music", Icon: Music },
{ name: "dog", label: "Dog", Icon: Dog },
{ name: "cat", label: "Cat", Icon: Cat },
{ name: "fish", label: "Fish", Icon: Fish },
{ name: "sprout", label: "Plants", Icon: Sprout },
{ name: "droplets", label: "Water", Icon: Droplets },
{ name: "bike", label: "Bike", Icon: Bike },
{ name: "volleyball", label: "Sport", Icon: Volleyball },
{ name: "gamepad-2", label: "Games", Icon: Gamepad2 },
{ name: "star", label: "Star", Icon: Star },
{ name: "heart", label: "Heart", Icon: Heart },
{ name: "sun", label: "Morning", Icon: Sun },
{ name: "moon", label: "Bedtime", Icon: Moon },
{ name: "clock", label: "Clock", Icon: Clock },
{ name: "calendar", label: "Calendar", Icon: Calendar },
{ name: "list-checks", label: "Checklist", Icon: ListChecks },
];
const BY_NAME = new Map(DEFINITION_ICONS.map((entry) => [entry.name, entry]));
export function findDefinitionIcon(name: string | null): DefinitionIconEntry | null {
return name === null ? null : (BY_NAME.get(name) ?? null);
}
/**
* The stored key for typed emoji text, e.g. `emoji:🐶`. The raw text — not
* trimmed, as the backend rejects any whitespace — must pass the registry's
* emoji check (1-8 code points, no whitespace, control characters or `<`,
* `>`, `&`), else null. Only an empty field means "no icon".
*/
export function emojiIconKey(text: string): string | null {
const key = `${EMOJI_PREFIX}${text}`;
return resolveIcon(key).kind === "emoji" ? key : null;
}
/**
* The Lucide name an icon value refers to: `lucide:dog` and a legacy bare
* `dog` both give `dog`. Any other namespace (`fa:`, `emoji:`, unknown) and
* null give null — the admin has no Lucide entry for them.
*/
export function normalizeDefinitionIconName(value: string | null): string | null {
if (value === null) return null;
if (value.startsWith(LUCIDE_PREFIX)) return value.slice(LUCIDE_PREFIX.length);
return value.includes(":") ? null : value;
}
/** The Font Awesome name an `fa:<name>` value refers to; anything else gives null. */
export function faIconName(value: string | null): string | null {
return value?.startsWith(FA_PREFIX) ? value.slice(FA_PREFIX.length) : null;
}
/**
* The Font Awesome Free Solid icons whose name or label contains `query`
* (trimmed, case-insensitive): an exact name first, then name-prefix
* matches, then the rest, each in registry (name) order. An empty query
* gives no results — the curated quick picks cover that case.
*/
export function searchFaIcons(query: string): DefinitionIconEntry[] {
const q = query.trim().toLowerCase();
if (!q) return [];
const rank = (icon: DefinitionIconEntry) => (icon.name === q ? 0 : icon.name.startsWith(q) ? 1 : 2);
return FA_SOLID_ICONS.filter(
(icon) => icon.name.includes(q) || icon.label.toLowerCase().includes(q),
).sort((a, b) => rank(a) - rank(b));
}
/**
* The stored key for a typed Font Awesome name, e.g. `Dog` → `fa:dog`: the
* trimmed, lower-cased text must be the exact name of a Free Solid icon,
* else null (a misspelling, a partial search, or a Pro/Brands name).
*/
export function faTypedIconKey(text: string): string | null {
const key = faIconKey(text.trim().toLowerCase());
return resolveIcon(key).kind === "fa" ? key : null;
}
/**
* Why Font Awesome search text cannot be saved as it stands: it matches
* icons but names none of them, or it matches nothing in the Free Solid set.
*/
export function faTextProblem(text: string): string {
return searchFaIcons(text).length > 0
? "Select a Font Awesome icon from the results, or type its full name."
: `“${text.trim()}” is not a Font Awesome Free Solid icon.`;
}
/** The emoji text an `emoji:<grapheme>` value holds; anything else gives "". */
export function emojiIconText(value: string | null): string {
return value?.startsWith(EMOJI_PREFIX) ? value.slice(EMOJI_PREFIX.length) : "";
}
/**
* The glyph an icon value resolves to via the shared parser: a curated
* Lucide entry or any Font Awesome Free Solid icon (quick pick or not);
* emoji, unknown and null values give null.
*/
export function findDefinitionIcon(value: string | null): DefinitionIconEntry | null {
const icon = resolveIcon(value);
return icon.kind === "lucide" || icon.kind === "fa" ? icon : null;
}
/**
* A definition's icon: a Lucide or Font Awesome glyph, an emoji drawn as
* text, or — for no icon or an unknown value — the generic task glyph.
*/
/** A definition's glyph; no icon, or one outside the subset, gets the generic task glyph. */
export function DefinitionIcon({ name, size = 17 }: { name: string | null; size?: number }) {
const icon = resolveIcon(name);
if (icon.kind === "fallback") return <TaskGlyph size={size} />;
if (icon.kind === "emoji") {
return (
<span className="defs-emoji" style={{ fontSize: size }} aria-hidden="true" data-emoji={icon.text}>
{icon.text}
</span>
);
}
return <GlyphSvg icon={icon} size={size} />;
const entry = findDefinitionIcon(name);
if (!entry) return <TaskGlyph size={size} />;
return <entry.Icon size={size} aria-hidden="true" focusable="false" data-icon={entry.name} />;
}
+1 -4
View File
@@ -21,9 +21,6 @@ export const WINDOW_LABELS: Record<WindowName, string> = {
/** Index 0 = Monday .. 6 = Sunday, the core's weekday numbering. */
export const WEEKDAY_SHORT = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
/** Display order for a week: Sunday first. The stored indices stay Monday=0. */
export const WEEKDAY_DISPLAY_ORDER = [6, 0, 1, 2, 3, 4, 5];
export const MONTH_SHORT = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
@@ -54,7 +51,7 @@ export function assigneeSummary(
function weekdayList(days: number[] | null): string {
return [...(days ?? [])]
.sort((a, b) => WEEKDAY_DISPLAY_ORDER.indexOf(a) - WEEKDAY_DISPLAY_ORDER.indexOf(b))
.sort((a, b) => a - b)
.map((day) => WEEKDAY_SHORT[day])
.join(", ");
}
+1 -322
View File
@@ -1,11 +1,8 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import HistoryTab, { FOOTER_NOTE, computeStats } from "./HistoryTab";
import type { HistoryFilter, HistoryRow } from "../api/history";
import { storeTokens } from "../auth/oidc";
import { TransitionsProvider } from "../api/useTransitions";
import { frame, testStream, type TestStream } from "../api/testStream";
import { AppTimezoneProvider } from "../time/AppTimezone";
const TODAY = "2026-09-23";
@@ -426,321 +423,3 @@ describe("HistoryTab", () => {
expect(screen.getByTestId("history-scroll").style.paddingBottom).toBe("92px");
});
});
describe("HistoryTab live updates", () => {
let fetchMock: ReturnType<typeof vi.fn>;
let streams: TestStream[];
function historyRequests(): URL[] {
return fetchMock.mock.calls
.map(([url]) => new URL(String(url), "http://x"))
.filter((url) => url.pathname === "/api/v1/admin/history");
}
const PAYLOAD = {
child_id: 2,
child_name: "Maeve",
instance_id: 2,
quest_title: "Make bed",
window: "morning",
due_date: TODAY,
due_time: null,
occurred_at: "2026-09-23T15:10:00Z",
};
beforeAll(() => {
vi.stubEnv("TZ", "America/Los_Angeles");
});
afterAll(() => {
vi.unstubAllEnvs();
});
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
streams = [];
fetchMock = vi.fn((url: string) => {
if (new URL(url, "http://x").pathname.endsWith("/api/v1/admin/events")) {
const stream = testStream();
streams.push(stream);
return Promise.resolve(stream.response);
}
return Promise.resolve(routeFetch(url));
});
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
it("a quest transition refetches the active filter; a day-complete does not", async () => {
render(
<TransitionsProvider>
<HistoryTab today={TODAY} />
</TransitionsProvider>,
);
await screen.findByTestId("stat-on-time");
fireEvent.click(screen.getByRole("button", { name: "Reversals" }));
await waitFor(() =>
expect(historyRequests().some((u) => u.searchParams.get("filter") === "reversals")).toBe(true),
);
await screen.findByTestId("stat-on-time");
await waitFor(() => expect(streams).toHaveLength(1));
const before = historyRequests().length;
streams[0].push(
frame("nestquest_child_day_complete", {
child_id: 2,
child_name: "Maeve",
quests_due: 4,
quests_completed: 4,
occurred_at: "2026-09-23T15:00:00Z",
}),
);
await new Promise((resolve) => setTimeout(resolve, 30));
expect(historyRequests().length).toBe(before);
streams[0].push(frame("nestquest_quest_uncompleted", PAYLOAD));
await waitFor(() => expect(historyRequests().length).toBe(before + 3));
const refetched = historyRequests().slice(before);
// One refetch (reversals + the two stats queries), same range and filter.
expect(refetched.map((u) => u.searchParams.get("filter")).sort()).toEqual([
"all",
"missed",
"reversals",
]);
for (const url of refetched) {
expect(url.searchParams.get("start")).toBe("2026-09-10");
expect(url.searchParams.get("end")).toBe(TODAY);
}
await new Promise((resolve) => setTimeout(resolve, 30));
expect(historyRequests().length).toBe(before + 3);
expect(screen.queryByTestId("history-loading")).toBeNull();
expect(screen.getByRole("button", { name: "Reversals" }).getAttribute("aria-pressed")).toBe("true");
// Rows stay read-only (D-005): no row carries a control.
for (const row of screen.getAllByTestId("history-row")) {
expect(within(row).queryByRole("button")).toBeNull();
}
});
describe("a filter change interleaved with a quest transition", () => {
// Both land before the load effect runs, so one load serves both.
async function interleave(order: "sse-first" | "chip-first") {
await act(async () => {
const click = () => fireEvent.click(screen.getByRole("button", { name: "Reversals" }));
if (order === "chip-first") click();
streams[0].push(frame("nestquest_quest_uncompleted", PAYLOAD));
await new Promise((resolve) => setTimeout(resolve, 30));
if (order === "sse-first") click();
});
}
async function renderLive() {
render(
<TransitionsProvider>
<HistoryTab today={TODAY} />
</TransitionsProvider>,
);
await screen.findByTestId("stat-on-time");
await waitFor(() => expect(streams).toHaveLength(1));
expect(screen.getAllByTestId("history-row")).toHaveLength(ROWS.all.length);
}
function titles(): string[] {
return screen.getAllByTestId("history-row").map((el) => el.textContent ?? "");
}
for (const order of ["sse-first", "chip-first"] as const) {
it(`${order}: shows loading, then only the active filter's rows`, async () => {
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const route = fetchMock.getMockImplementation()!;
await renderLive();
fetchMock.mockImplementation((url: string) => {
const parsed = new URL(url, "http://x");
if (parsed.searchParams.get("filter") === "reversals") {
return gate.then(() => route(url));
}
return route(url);
});
await interleave(order);
expect(screen.getByRole("button", { name: "Reversals" }).getAttribute("aria-pressed")).toBe("true");
// The previous filter's rows never show under the new chip.
expect(screen.getByTestId("history-loading")).toBeTruthy();
expect(screen.queryAllByTestId("history-row")).toHaveLength(0);
release();
await screen.findByTestId("stat-on-time");
expect(titles()).toHaveLength(1);
expect(titles()[0]).toContain("Make bed · Maeve");
expect(screen.getAllByTestId("history-dot")[0].className).toContain("history-dot--uncompleted");
});
it(`${order}: a failed filter-change load shows the error state, not stale rows`, async () => {
const route = fetchMock.getMockImplementation()!;
await renderLive();
fetchMock.mockImplementation((url: string) => {
const parsed = new URL(url, "http://x");
if (parsed.pathname === "/api/v1/admin/history") {
return Promise.resolve(jsonResponse({ detail: "boom" }, 500));
}
return route(url);
});
await interleave(order);
const error = await screen.findByTestId("history-error");
expect(error.textContent).toContain("The history could not be loaded");
expect(screen.getByRole("button", { name: "Reversals" }).getAttribute("aria-pressed")).toBe("true");
expect(screen.queryAllByTestId("history-row")).toHaveLength(0);
expect(screen.queryByTestId("stat-on-time")).toBeNull();
});
}
});
it("a failed transition refresh keeps the active filter's rows on screen", async () => {
render(
<TransitionsProvider>
<HistoryTab today={TODAY} />
</TransitionsProvider>,
);
await screen.findByTestId("stat-on-time");
await waitFor(() => expect(streams).toHaveLength(1));
const route = fetchMock.getMockImplementation()!;
fetchMock.mockImplementation((url: string) => {
if (new URL(url, "http://x").pathname === "/api/v1/admin/history") {
return Promise.resolve(jsonResponse({ detail: "boom" }, 500));
}
return route(url);
});
const before = historyRequests().length;
streams[0].push(frame("nestquest_quest_uncompleted", PAYLOAD));
// The "all" filter plus the missed stats query.
await waitFor(() => expect(historyRequests().length).toBe(before + 2));
await new Promise((resolve) => setTimeout(resolve, 30));
expect(screen.queryByTestId("history-error")).toBeNull();
expect(screen.queryByTestId("history-loading")).toBeNull();
expect(screen.getAllByTestId("history-row")).toHaveLength(ROWS.all.length);
});
});
describe("HistoryTab in the stored application timezone", () => {
// 13:00 UTC on Sep 23 is 01:00 on Sep 24 in Auckland (NZST, UTC+12).
const NOW = new Date("2026-09-23T13:00:00Z");
// Due 00:10 Auckland on Sep 24, done 00:30 Auckland (12:30 UTC on Sep 23).
const LATE_NZ = row({
instance_id: 7,
quest_title: "Feed cat",
due_date: "2026-09-24",
due_time: "00:10",
occurred_at: "2026-09-23T12:30:00Z",
was_on_time: false,
});
// 22:00 Auckland on Sep 23; 10:00 UTC.
const EVENING_NZ = row({ instance_id: 8, occurred_at: "2026-09-23T10:00:00Z" });
let fetchMock: ReturnType<typeof vi.fn>;
function historyRequests(): URL[] {
return fetchMock.mock.calls
.map(([url]) => new URL(String(url), "http://x"))
.filter((url) => url.pathname === "/api/v1/admin/history");
}
async function renderWithZone(timezone: string, effective_timezone = timezone) {
fetchMock = vi.fn((url: string) => {
const parsed = new URL(url, "http://x");
if (parsed.pathname.endsWith("/api/v1/admin/settings")) {
return Promise.resolve(jsonResponse({ timezone, effective_timezone }));
}
const filter = parsed.searchParams.get("filter");
const rows = filter === "all" ? [EVENING_NZ, LATE_NZ] : [];
return Promise.resolve(
jsonResponse({
filter,
start: parsed.searchParams.get("start"),
end: parsed.searchParams.get("end"),
count: rows.length,
rows,
}),
);
});
vi.stubGlobal("fetch", fetchMock);
render(
<AppTimezoneProvider>
<HistoryTab />
</AppTimezoneProvider>,
);
await screen.findByTestId("stat-on-time");
}
function times(section: HTMLElement): string[] {
return Array.from(section.querySelectorAll(".history-event-time")).map(
(el) => el.textContent ?? "",
);
}
beforeAll(() => {
vi.stubEnv("TZ", "UTC");
});
afterAll(() => {
vi.unstubAllEnvs();
});
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
vi.useFakeTimers({ toFake: ["Date"], now: NOW });
});
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.unstubAllGlobals();
});
it.each([
["the stored zone", "Pacific/Auckland"],
["the API host's published zone when none is stored", ""],
])("today, day grouping, clock and lateness follow %s", async (_label, stored) => {
await renderWithZone(stored, "Pacific/Auckland");
for (const url of historyRequests()) {
expect(url.searchParams.get("end")).toBe("2026-09-24");
expect(url.searchParams.get("start")).toBe("2026-09-11");
}
const today = screen.getByTestId("day-2026-09-24");
expect(within(today).getByText("Today")).toBeTruthy();
expect(times(today)).toEqual(["12:30 AM"]);
expect(metas(today)).toEqual(["completed · panel (Declan) · late 20 min"]);
const yesterday = screen.getByTestId("day-2026-09-23");
expect(within(yesterday).getByText("Yesterday")).toBeTruthy();
expect(times(yesterday)).toEqual(["10:00 PM"]);
});
it("only an API that publishes no zone leaves the browser's local day and clock", async () => {
await renderWithZone("", "");
for (const url of historyRequests()) {
expect(url.searchParams.get("end")).toBe("2026-09-23");
}
expect(screen.queryByTestId("day-2026-09-24")).toBeNull();
const today = screen.getByTestId("day-2026-09-23");
expect(within(today).getByText("Today")).toBeTruthy();
expect(times(today)).toEqual(["12:30 PM", "10:00 AM"]);
// Due 00:10 UTC on Sep 24 is after the 12:30 UTC completion: no minutes.
expect(metas(today)).toEqual([
"completed · panel (Declan) · late",
"completed · panel (Declan) · on time",
]);
});
});
+16 -39
View File
@@ -6,13 +6,10 @@
*/
import { useEffect, useRef, useState } from "react";
import { ApiForbiddenError } from "../api/client";
import type { TransitionEvent } from "../api/events";
import { useTransitions } from "../api/useTransitions";
import { exportHistoryCsv, fetchHistory, type HistoryFilter, type HistoryRow } from "../api/history";
import { localTodayIso } from "../schedule/cycle";
import { dayLabel, groupByDay, rowMeta, rowTime, shiftIso } from "./format";
import { DownloadGlyph, LockGlyph } from "./glyphs";
import { useAppTimezone } from "../time/AppTimezone";
import { todayIn } from "../time/zone";
import "./HistoryTab.css";
/** ADMIN-SPEC §1: every scroll column ends with 92px so content clears the tab bar. */
@@ -54,8 +51,7 @@ interface Loaded {
type LoadState =
| { kind: "loading" }
| { kind: "error"; message: string }
/** `key` is the (filter, start, end) the rows were loaded for. */
| { kind: "ready"; data: Loaded; key: string };
| { kind: "ready"; data: Loaded };
/**
* The selected filter's rows plus the period stats. Stats always come from
@@ -130,7 +126,7 @@ function StatRow({ stats }: { stats: HistoryStats }) {
);
}
function EventRow({ row, timeZone }: { row: HistoryRow; timeZone: string }) {
function EventRow({ row }: { row: HistoryRow }) {
return (
<li className="history-event" data-testid="history-row">
<span
@@ -143,10 +139,10 @@ function EventRow({ row, timeZone }: { row: HistoryRow; timeZone: string }) {
{row.quest_title} · {row.child_name}
</div>
<div className="history-event-meta" data-testid="history-meta">
{rowMeta(row, timeZone)}
{rowMeta(row)}
</div>
</div>
<span className="history-event-time">{rowTime(row, timeZone)}</span>
<span className="history-event-time">{rowTime(row)}</span>
</li>
);
}
@@ -162,10 +158,7 @@ function FooterNote() {
);
}
/** `today` ("YYYY-MM-DD") defaults to today in the application timezone. */
export default function HistoryTab({ today: todayProp }: { today?: string }) {
const timeZone = useAppTimezone();
const today = todayProp ?? todayIn(timeZone);
export default function HistoryTab({ today = localTodayIso() }: { today?: string }) {
const [filter, setFilter] = useState<HistoryFilter>("all");
const [state, setState] = useState<LoadState>({ kind: "loading" });
const [attempt, setAttempt] = useState(0);
@@ -173,14 +166,6 @@ export default function HistoryTab({ today: todayProp }: { today?: string }) {
const [exportError, setExportError] = useState<string | null>(null);
const exportingRef = useRef(false);
const start = shiftIso(today, -(RANGE_DAYS - 1));
const key = `${filter}|${start}|${today}`;
// A quest transition is a new history row (or changes a derived missed row);
// a day-complete adds none. The refetch keeps the active filter and range.
useTransitions((event: TransitionEvent) => {
if (event.type === "nestquest_child_day_complete") return;
setAttempt((n) => n + 1);
});
/** Download the CSV for the active filter over the displayed range. */
async function exportCsv() {
@@ -205,13 +190,10 @@ export default function HistoryTab({ today: todayProp }: { today?: string }) {
useEffect(() => {
let cancelled = false;
// Rows already loaded for this (filter, range) stay on screen while they
// refresh; any other rows give way to the loading state.
const isCurrent = (prev: LoadState) => prev.kind === "ready" && prev.key === key;
setState((prev) => (isCurrent(prev) ? prev : { kind: "loading" }));
setState({ kind: "loading" });
loadHistory(filter, start, today)
.then((data) => {
if (!cancelled) setState({ kind: "ready", data, key });
if (!cancelled) setState({ kind: "ready", data });
})
.catch((error: unknown) => {
if (cancelled) return;
@@ -219,36 +201,31 @@ export default function HistoryTab({ today: todayProp }: { today?: string }) {
error instanceof ApiForbiddenError
? error.message
: "The history could not be loaded. Check your connection and try again.";
// A failed refresh keeps the rows already on screen.
setState((prev) => (isCurrent(prev) ? prev : { kind: "error", message }));
setState({ kind: "error", message });
});
return () => {
cancelled = true;
};
}, [filter, start, today, key, attempt]);
// Never render one filter's rows under another's chip, even for the render
// before the load effect runs.
const shown: LoadState = state.kind === "ready" && state.key !== key ? { kind: "loading" } : state;
}, [filter, start, today, attempt]);
let body;
if (shown.kind === "loading") {
if (state.kind === "loading") {
body = (
<div className="history-status" role="status" data-testid="history-loading">
Loading history…
</div>
);
} else if (shown.kind === "error") {
} else if (state.kind === "error") {
body = (
<div className="history-status history-status--error" role="alert" data-testid="history-error">
<p>{shown.message}</p>
<p>{state.message}</p>
<button type="button" className="history-retry" onClick={() => setAttempt((n) => n + 1)}>
Try again
</button>
</div>
);
} else {
const groups = groupByDay(shown.data.rows, timeZone);
const groups = groupByDay(state.data.rows);
body =
groups.length > 0 ? (
groups.map((group) => (
@@ -256,7 +233,7 @@ export default function HistoryTab({ today: todayProp }: { today?: string }) {
<h3 className="history-section-label">{dayLabel(group.day, today)}</h3>
<ul className="history-card history-list">
{group.rows.map((row, index) => (
<EventRow key={`${row.instance_id}-${row.event_type}-${row.occurred_at ?? ""}-${index}`} row={row} timeZone={timeZone} />
<EventRow key={`${row.instance_id}-${row.event_type}-${row.occurred_at ?? ""}-${index}`} row={row} />
))}
</ul>
</section>
@@ -282,7 +259,7 @@ export default function HistoryTab({ today: todayProp }: { today?: string }) {
</button>
</div>
) : null}
{shown.kind === "ready" ? <StatRow stats={shown.data.stats} /> : null}
{state.kind === "ready" ? <StatRow stats={state.data.stats} /> : null}
<div className="history-chips" role="group" aria-label="Filter events">
{FILTERS.map((item) => (
<button
+24 -21
View File
@@ -4,13 +4,12 @@
* Calendar dates ("YYYY-MM-DD") are handled by their components (never
* `new Date("YYYY-MM-DD")`, which is UTC midnight and reads as the previous
* day in negative-offset zones); event stamps are UTC and shown in the
* application timezone (`timeZone`: the stored IANA zone, "" = browser).
* viewer's local time.
*/
import type { HistoryRow } from "../api/history";
import { dayNumber, isoFromDayNumber } from "../schedule/cycle";
import { dayNumber, isoFromDayNumber, localTodayIso } from "../schedule/cycle";
import { shortDate } from "../schedule/format";
import { formatClockTime, formatDueTime } from "../today/format";
import { isoDateIn, wallClockInstant } from "../time/zone";
const MS_PER_MINUTE = 60_000;
@@ -20,21 +19,25 @@ export function shiftIso(iso: string, days: number): string {
}
/** The local calendar day an event belongs to (due_date for missed rows). */
export function rowDay(row: HistoryRow, timeZone: string): string {
return row.occurred_at ? isoDateIn(new Date(row.occurred_at), timeZone) : row.due_date;
export function rowDay(row: HistoryRow): string {
return row.occurred_at ? localTodayIso(new Date(row.occurred_at)) : row.due_date;
}
/** The row's due moment (epoch ms) as local wall-clock time, or null without a due time. */
function dueMoment(row: HistoryRow, timeZone: string): number | null {
/** The row's due moment as local wall-clock time, or null without a due time. */
function dueMoment(row: HistoryRow): Date | null {
const match = /^(\d{2}):(\d{2})/.exec(row.due_time ?? "");
if (!match) return null;
return wallClockInstant(row.due_date, Number(match[1]), Number(match[2]), timeZone);
const [year, month, day] = row.due_date.split("-").map(Number);
return new Date(year, month - 1, day, Number(match[1]), Number(match[2]));
}
/** Newest first; a missed row sorts at its due moment (or the end of its day). */
function sortKey(row: HistoryRow, timeZone: string): number {
function sortKey(row: HistoryRow): number {
if (row.occurred_at) return Date.parse(row.occurred_at);
return dueMoment(row, timeZone) ?? wallClockInstant(row.due_date, 23, 59, timeZone);
const due = dueMoment(row);
if (due) return due.getTime();
const [year, month, day] = row.due_date.split("-").map(Number);
return new Date(year, month - 1, day, 23, 59).getTime();
}
export interface DayGroup {
@@ -43,10 +46,10 @@ export interface DayGroup {
}
/** Rows grouped by day, newest day first and newest row first within a day. */
export function groupByDay(rows: HistoryRow[], timeZone: string): DayGroup[] {
export function groupByDay(rows: HistoryRow[]): DayGroup[] {
const groups = new Map<string, HistoryRow[]>();
for (const row of rows) {
const day = rowDay(row, timeZone);
const day = rowDay(row);
groups.set(day, [...(groups.get(day) ?? []), row]);
}
return [...groups.entries()]
@@ -54,7 +57,7 @@ export function groupByDay(rows: HistoryRow[], timeZone: string): DayGroup[] {
.map(([day, dayRows]) => ({
day,
// Stable sort: rows at the same moment keep the API's append order.
rows: [...dayRows].sort((a, b) => sortKey(b, timeZone) - sortKey(a, timeZone)),
rows: [...dayRows].sort((a, b) => sortKey(b) - sortKey(a)),
}));
}
@@ -69,23 +72,23 @@ export function dayLabel(day: string, today: string): string {
}
/** "on time", "late 22 min", or "late" when the lateness is not derivable. */
function onTimeFlag(row: HistoryRow, timeZone: string): string | null {
function onTimeFlag(row: HistoryRow): string | null {
if (row.event_type !== "completed" || row.was_on_time === null) return null;
if (row.was_on_time) return "on time";
const due = dueMoment(row, timeZone);
if (due === null || !row.occurred_at) return "late";
const minutes = Math.round((Date.parse(row.occurred_at) - due) / MS_PER_MINUTE);
const due = dueMoment(row);
if (!due || !row.occurred_at) return "late";
const minutes = Math.round((Date.parse(row.occurred_at) - due.getTime()) / MS_PER_MINUTE);
return minutes > 0 ? `late ${minutes} min` : "late";
}
/** `<event type> · <actor>` plus the on-time flag for completions. */
export function rowMeta(row: HistoryRow, timeZone: string): string {
const flag = onTimeFlag(row, timeZone);
export function rowMeta(row: HistoryRow): string {
const flag = onTimeFlag(row);
return [row.event_type, row.actor, flag].filter(Boolean).join(" · ");
}
/** The event's local clock time; a missed row shows its due time, if any. */
export function rowTime(row: HistoryRow, timeZone: string): string {
if (row.occurred_at) return formatClockTime(row.occurred_at, timeZone);
export function rowTime(row: HistoryRow): string {
if (row.occurred_at) return formatClockTime(row.occurred_at);
return row.due_time ? formatDueTime(row.due_time) : "";
}
-29
View File
@@ -1,29 +0,0 @@
/**
* Draws a registry glyph (`registry.generated.ts`) as an inline SVG — the
* path data is bundled, so there is no CDN and no runtime fetch. Lucide
* glyphs are stroked on their 24px grid; Font Awesome glyphs are filled.
*/
import type { GlyphIcon } from "./registry.generated";
export function GlyphSvg({ icon, size }: { icon: GlyphIcon; size: number }) {
const stroked = icon.kind === "lucide";
return (
<svg
width={size}
height={size}
viewBox={icon.viewBox}
fill={stroked ? "none" : "currentColor"}
stroke={stroked ? "currentColor" : undefined}
strokeWidth={stroked ? 2 : undefined}
strokeLinecap={stroked ? "round" : undefined}
strokeLinejoin={stroked ? "round" : undefined}
aria-hidden="true"
focusable="false"
data-icon={icon.name}
>
{icon.paths.map((d, index) => (
<path key={index} d={d} />
))}
</svg>
);
}
File diff suppressed because it is too large Load Diff
-170
View File
@@ -1,170 +0,0 @@
import { readFileSync, readdirSync, statSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
// The offline generator is the only writer of both registry artefacts.
import { OUTPUT_PATHS, REPO_ROOT, SOURCE_PATH, renderRegistry } from "../../../tools/icons/generate.mjs";
import {
EMOJI_MAX_CODE_POINTS,
FALLBACK_ICON,
FA_ICONS,
FA_SOLID_ICONS,
LUCIDE_ICONS,
resolveIcon,
} from "./registry.generated";
type Curated = { lucide: { name: string; label: string }[]; fa: { name: string; label: string }[] };
const curated = JSON.parse(readFileSync(SOURCE_PATH, "utf8")) as Curated;
type EmojiPayloadCase = { payload: string; valid: boolean; why: string };
const emojiPayloadCases = JSON.parse(
readFileSync(join(REPO_ROOT, "tools", "icons", "emoji-payload-cases.json"), "utf8"),
) as { cases: EmojiPayloadCase[] };
describe("shared icon registry — one source of truth", () => {
it("both committed artefacts are byte-identical to a fresh generation", async () => {
const fresh = await renderRegistry();
expect(OUTPUT_PATHS).toHaveLength(2);
for (const path of OUTPUT_PATHS) {
expect(readFileSync(path, "utf8"), `${path} drifted — run node tools/icons/generate.mjs`).toBe(fresh);
}
});
it("the generated sets carry exactly the curated names and labels, in order", () => {
expect(LUCIDE_ICONS.map(({ name, label }) => ({ name, label }))).toEqual(curated.lucide);
expect(FA_ICONS.map(({ name, label }) => ({ name, label }))).toEqual(curated.fa);
expect(curated.lucide).toHaveLength(36);
expect(FA_ICONS.length).toBeGreaterThanOrEqual(15);
expect(FA_ICONS.length).toBeLessThanOrEqual(25);
});
it("every glyph is plain data: a viewBox and at least one path", () => {
for (const icon of LUCIDE_ICONS) {
expect(icon.kind).toBe("lucide");
expect(icon.key).toBe(`lucide:${icon.name}`);
expect(icon.viewBox).toBe("0 0 24 24");
expect(icon.paths.length, icon.name).toBeGreaterThan(0);
}
for (const icon of FA_ICONS) {
expect(icon.kind).toBe("fa");
expect(icon.key).toBe(`fa:${icon.name}`);
expect(icon.viewBox).toMatch(/^0 0 \d+ 512$/);
expect(icon.paths.length, icon.name).toBeGreaterThan(0);
}
const solidNames = FA_SOLID_ICONS.map((icon) => icon.name);
expect(solidNames.length).toBeGreaterThanOrEqual(1400);
expect(solidNames).toEqual([...solidNames].sort());
expect(new Set(solidNames).size).toBe(solidNames.length);
for (const { name } of FA_ICONS) expect(solidNames, name).toContain(name);
for (const icon of FA_SOLID_ICONS) {
expect(icon.kind).toBe("fa");
expect(icon.key).toBe(`fa:${icon.name}`);
expect(icon.viewBox).toMatch(/^0 0 \d+ 512$/);
expect(icon.paths.length, icon.name).toBeGreaterThan(0);
}
for (const icon of [...LUCIDE_ICONS, ...FA_ICONS, ...FA_SOLID_ICONS]) {
for (const d of icon.paths) expect(d, icon.key).toMatch(/^[Mm][-0-9.,\sA-Za-z]+$/);
}
});
});
describe("resolveIcon", () => {
it("resolves lucide:, fa: and emoji: keys", () => {
const dog = resolveIcon("lucide:dog");
expect(dog.kind).toBe("lucide");
expect(dog).toBe(LUCIDE_ICONS.find((icon) => icon.name === "dog"));
const broom = resolveIcon("fa:broom");
expect(broom.kind).toBe("fa");
expect(broom).toBe(FA_ICONS.find((icon) => icon.name === "broom"));
// Any Free Solid name resolves, not just the curated quick-pick set.
const rocket = resolveIcon("fa:rocket");
expect(rocket).toBe(FA_SOLID_ICONS.find((icon) => icon.name === "rocket"));
expect(rocket).toMatchObject({ kind: "fa", key: "fa:rocket", label: "Rocket" });
expect(resolveIcon("fa:person-dress-burst")).toMatchObject({ kind: "fa", label: "Person Dress Burst" });
expect(resolveIcon("emoji:🐶")).toEqual({ kind: "emoji", key: "emoji:🐶", text: "🐶" });
expect(resolveIcon("emoji:👨‍👩‍👧")).toEqual({ kind: "emoji", key: "emoji:👨‍👩‍👧", text: "👨‍👩‍👧" });
});
it("reads a legacy bare name as Lucide", () => {
expect(resolveIcon("dog")).toBe(resolveIcon("lucide:dog"));
expect(resolveIcon("trash-2")).toBe(LUCIDE_ICONS.find((icon) => icon.name === "trash-2"));
});
it("falls back — never throws — for empty or unknown values", () => {
for (const value of [
null,
undefined,
"",
" ",
"rocket-ship-9000",
"lucide:",
"lucide:rocket-ship-9000",
"fa:",
"fa:rocket-ship-9000",
"fa:Dog",
"mystery:dog",
"emoji:",
"emoji:<b>",
"emoji:a b",
"emoji:123456789",
]) {
expect(resolveIcon(value), String(value)).toBe(FALLBACK_ICON);
}
expect(FALLBACK_ICON).toEqual({ kind: "fallback", key: null });
});
// tests/test_core_icons.py asserts the same table against the backend's
// validate_icon, so the two emoji rules cannot drift apart silently.
it.each(emojiPayloadCases.cases)("emoji verdict matches the shared table: $why", ({ payload, valid }) => {
const value = `emoji:${payload}`;
expect(resolveIcon(value)).toEqual(valid ? { kind: "emoji", key: value, text: payload } : FALLBACK_ICON);
});
it("the shared emoji table covers the contract edges", () => {
const verdicts = new Map(emojiPayloadCases.cases.map(({ payload, valid }) => [payload, valid]));
expect(verdicts.get("\ufeff")).toBe(false);
expect(verdicts.get("👨\u200d👩\u200d👧\u200d👦")).toBe(true);
expect(verdicts.get("🐕 ")).toBe(false);
expect(verdicts.get("🐕\u0000")).toBe(false);
for (const markup of ["<b>", "a>b", "a&b"]) expect(verdicts.get(markup)).toBe(false);
expect(verdicts.get("⭐".repeat(EMOJI_MAX_CODE_POINTS))).toBe(true);
expect(verdicts.get("⭐".repeat(EMOJI_MAX_CODE_POINTS + 1))).toBe(false);
});
});
function filesUnder(dir: string): string[] {
return readdirSync(dir).flatMap((entry) => {
const path = join(dir, entry);
return statSync(path).isDirectory() ? filesUnder(path) : [path];
});
}
describe("offline bundling", () => {
const registryFiles = [SOURCE_PATH, join(REPO_ROOT, "tools", "icons", "generate.mjs"), ...OUTPUT_PATHS];
it("the registry has no remote URL, CDN reference or data-lucide runtime", () => {
for (const path of registryFiles) {
const text = readFileSync(path, "utf8");
expect(text, path).not.toMatch(/https?:\/\//i);
expect(text, path).not.toMatch(/\/\/[a-z0-9.-]+\.[a-z]{2,}\//i);
expect(text, path).not.toMatch(/\bcdn\b|jsdelivr|unpkg|cdnjs|kit\.fontawesome/i);
expect(text, path).not.toContain("data-lucide");
expect(text, path).not.toMatch(/\bfetch\s*\(/);
}
});
it("no bundled source imports an icon package — only the generated registry data ships", () => {
const sources = [join(REPO_ROOT, "admin", "src"), join(REPO_ROOT, "frontend", "src")]
.flatMap(filesUnder)
.filter((path) => /\.(ts|tsx)$/.test(path) && !path.endsWith(".test.ts") && !path.endsWith(".test.tsx"));
expect(sources.length).toBeGreaterThan(0);
for (const path of sources) {
const text = readFileSync(path, "utf8");
expect(text, path).not.toMatch(/from\s+["'](lucide|lucide-react|lucide-static|@fortawesome\/[^"']+)["']/);
}
});
});
-9
View File
@@ -95,15 +95,6 @@
grid-template-columns: repeat(2, 1fr);
}
.override-segments--7 {
grid-template-columns: repeat(7, 1fr);
gap: 4px;
}
.override-segments--7 .override-segment {
padding: 0;
}
.override-segment {
min-height: var(--nq-a-tap-min);
padding: 0 8px;
+9 -16
View File
@@ -4,7 +4,7 @@ import App from "../App";
import ScheduleTab from "./ScheduleTab";
import { CONSEQUENCE_DEBOUNCE_MS, isIsoDate, isValidRange } from "./OverrideEditor";
import type { AdminChild } from "../api/definitions";
import type { PresenceOverride, PresencePattern } from "../api/presence";
import type { PresenceOverride, PresenceSchedule } from "../api/presence";
import { storeTokens } from "../auth/oidc";
function child(id: number, display_name: string, sort_order: number): AdminChild {
@@ -13,11 +13,8 @@ function child(id: number, display_name: string, sort_order: number): AdminChild
const CHILDREN = [child(1, "Declan", 1), child(2, "Maeve", 2), child(3, "Rory", 3)];
const DECLAN: PresencePattern = {
id: 1,
const DECLAN: PresenceSchedule = {
child_id: 1,
name: "Home weeks",
kind: "home",
cycle_length_weeks: 2,
anchor_date: "2026-09-07",
pattern: { "0": [0, 1, 2, 3, 4, 5, 6], "1": [5, 6] },
@@ -74,14 +71,10 @@ async function routeFetch(url: string, init: RequestInit = {}): Promise<Response
overrides = overrides.filter((o) => o.id !== Number(deleteMatch[1]));
return jsonResponse({ status: "ok" });
}
// The shell loads the application timezone first ("" = none published).
if (path.endsWith("/admin/settings")) {
return jsonResponse({ timezone: "", effective_timezone: "" });
}
if (path.endsWith("/admin/children")) return jsonResponse({ children: CHILDREN });
const patternsMatch = /\/children\/(\d+)\/presence-patterns$/.exec(path);
if (patternsMatch) {
return jsonResponse({ patterns: Number(patternsMatch[1]) === 1 ? [DECLAN] : [] });
const scheduleMatch = /\/children\/(\d+)\/presence-schedule$/.exec(path);
if (scheduleMatch) {
return jsonResponse({ schedule: Number(scheduleMatch[1]) === 1 ? DECLAN : null });
}
if (path === OVERRIDES_PATH) return jsonResponse({ overrides });
return jsonResponse({ detail: "unexpected" }, 500);
@@ -300,7 +293,7 @@ describe("OverrideEditor", () => {
});
await waitFor(() => expect(saveButton().disabled).toBe(false));
const before = calls().length;
const patternsBefore = calls().filter((c) => c.path.endsWith("/presence-patterns")).length;
const schedulesBefore = calls().filter((c) => c.path.endsWith("/presence-schedule")).length;
fireEvent.click(saveButton());
const row = await screen.findByTestId("override-50");
@@ -328,10 +321,10 @@ describe("OverrideEditor", () => {
},
]);
expect(after.some((c) => c.method === "DELETE")).toBe(false);
// The overrides and the presence patterns are refetched for the grid.
// The overrides and the presence schedules are refetched for the grid.
expect(after.some((c) => c.method === "GET" && c.path === OVERRIDES_PATH)).toBe(true);
expect(calls().filter((c) => c.path.endsWith("/presence-patterns")).length).toBeGreaterThan(
patternsBefore,
expect(calls().filter((c) => c.path.endsWith("/presence-schedule")).length).toBeGreaterThan(
schedulesBefore,
);
// The grid reflects the new override.
expect(document.querySelector('[data-date="2026-09-25"]')?.getAttribute("data-state")).toBe(
+17 -22
View File
@@ -39,13 +39,13 @@ type Consequence =
| { kind: "ready"; removed: number }
| { kind: "error"; message: string };
export function errorMessage(error: unknown, fallback: string): string {
function errorMessage(error: unknown, fallback: string): string {
if (error instanceof ApiForbiddenError) return error.message;
if (error instanceof ApiRequestError && error.detail) return error.detail;
return fallback;
}
export const FOCUSABLE =
const FOCUSABLE =
'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex="-1"])';
/**
@@ -53,7 +53,7 @@ export const FOCUSABLE =
* <body>), so the tab bar behind the pushed screen cannot take focus.
* Returns the undo.
*/
export function inertOutside(root: HTMLElement): () => void {
function inertOutside(root: HTMLElement): () => void {
const made: HTMLElement[] = [];
for (let node: HTMLElement = root; node.parentElement && node !== document.body; node = node.parentElement) {
for (const sibling of Array.from(node.parentElement.children)) {
@@ -71,24 +71,6 @@ export function inertOutside(root: HTMLElement): () => void {
};
}
/** Keep Tab / Shift+Tab cycling inside `root` (a pushed modal screen). */
export function trapTab(event: ReactKeyboardEvent<HTMLElement>, root: HTMLElement | null): void {
if (event.key !== "Tab" || !root) return;
const focusable = Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE));
if (focusable.length === 0) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
const current = document.activeElement;
const outside = !focusable.includes(current as HTMLElement);
if (event.shiftKey && (current === first || outside)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (current === last || outside)) {
event.preventDefault();
first.focus();
}
}
function tasksPhrase(count: number): string {
return `${count} upcoming ${count === 1 ? "task" : "tasks"}`;
}
@@ -136,7 +118,20 @@ export default function OverrideEditor({
if (!saving) onCancel();
return;
}
trapTab(event, screenRef.current);
if (event.key !== "Tab" || !screenRef.current) return;
const focusable = Array.from(screenRef.current.querySelectorAll<HTMLElement>(FOCUSABLE));
if (focusable.length === 0) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
const current = document.activeElement;
const outside = !focusable.includes(current as HTMLElement);
if (event.shiftKey && (current === first || outside)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (current === last || outside)) {
event.preventDefault();
first.focus();
}
}
const child = childOptions.find((c) => c.id === childId) ?? childOptions[0];
-255
View File
@@ -1,255 +0,0 @@
/**
* Presence pattern editor — a pushed screen like the override editor.
*
* Adds a pattern to the child's collection (POST) or edits one in place
* (PATCH with only the changed fields). The weekday numbering sent to the
* API stays Monday=0 .. Sunday=6; only the display is Sunday-first.
*/
import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
import type { AdminChild } from "../api/definitions";
import {
createPresencePattern,
updatePresencePattern,
type PatternKind,
type PatternWeeks,
type PresencePattern,
type PresencePatternBody,
} from "../api/presence";
import {
DISPLAY_WEEKDAYS,
WEEKDAY_SHORT,
dayNumber,
emptyPattern,
isoFromDayNumber,
resizePattern,
togglePatternDay,
} from "./cycle";
import { anchorLabel, shortDate } from "./format";
import { ChevronLeftGlyph } from "./glyphs";
import { errorMessage, inertOutside, isIsoDate, trapTab } from "./OverrideEditor";
import "./OverrideEditor.css";
export const CYCLE_LENGTH_CHOICES = [1, 2, 3, 4];
const WEEKDAY_NAMES = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
/** The fields of `next` that differ from the stored pattern. */
export function changedFields(
stored: PresencePatternBody,
next: PresencePatternBody,
): Partial<PresencePatternBody> {
const changes: Partial<PresencePatternBody> = {};
if (next.name !== stored.name) changes.name = next.name;
if (next.kind !== stored.kind) changes.kind = next.kind;
if (next.cycle_length_weeks !== stored.cycle_length_weeks) {
changes.cycle_length_weeks = next.cycle_length_weeks;
}
if (next.anchor_date !== stored.anchor_date) changes.anchor_date = next.anchor_date;
const samePattern = Array.from({ length: next.cycle_length_weeks }, (_, week) => week).every(
(week) =>
JSON.stringify([...(stored.pattern[week] ?? [])].sort()) ===
JSON.stringify([...(next.pattern[week] ?? [])].sort()),
);
if (!samePattern || changes.cycle_length_weeks !== undefined) changes.pattern = next.pattern;
return changes;
}
export interface PatternEditorProps {
child: AdminChild;
/** The pattern being edited, or null to add a new one. */
pattern: PresencePattern | null;
/** "YYYY-MM-DD"; a new pattern's anchor starts here. */
today: string;
onCancel: () => void;
onSaved: (pattern: PresencePattern) => void;
}
export default function PatternEditor({ child, pattern, today, onCancel, onSaved }: PatternEditorProps) {
const [name, setName] = useState(pattern?.name ?? "");
const [kind, setKind] = useState<PatternKind>(pattern?.kind ?? "away");
const [cycleLength, setCycleLength] = useState(pattern?.cycle_length_weeks ?? 1);
const [anchor, setAnchor] = useState(pattern?.anchor_date ?? today);
const [weeks, setWeeks] = useState<PatternWeeks>(pattern?.pattern ?? emptyPattern(1));
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const screenRef = useRef<HTMLDivElement>(null);
const titleRef = useRef<HTMLHeadingElement>(null);
useEffect(() => {
titleRef.current?.focus();
return screenRef.current ? inertOutside(screenRef.current) : undefined;
}, []);
function onKeyDown(event: ReactKeyboardEvent<HTMLDivElement>) {
if (event.key === "Escape") {
event.preventDefault();
if (!saving) onCancel();
return;
}
trapTab(event, screenRef.current);
}
const body: PresencePatternBody = {
name: name.trim(),
kind,
cycle_length_weeks: cycleLength,
anchor_date: anchor,
pattern: resizePattern(weeks, cycleLength),
};
const changes = pattern ? changedFields(pattern, body) : body;
// A pattern covering no day is valid (e.g. a migrated all-absent home schedule).
const canSave = body.name !== "" && isIsoDate(anchor) && Object.keys(changes).length > 0 && !saving;
function save() {
if (!canSave) return;
setSaving(true);
setError(null);
const request = pattern
? updatePresencePattern(pattern.id, changes)
: createPresencePattern(child.id, body);
request.then(onSaved).catch((err: unknown) => {
setError(errorMessage(err, "The pattern could not be saved. Check your connection and try again."));
setSaving(false);
});
}
const title = pattern ? "Edit pattern" : "New pattern";
return (
<div
ref={screenRef}
className="override-screen"
role="dialog"
aria-modal="true"
aria-labelledby="pattern-title"
onKeyDown={onKeyDown}
>
<header className="override-header">
<button type="button" className="override-back" aria-label="Back" onClick={onCancel}>
<ChevronLeftGlyph size={20} />
</button>
<div>
<h2 className="override-title" id="pattern-title" ref={titleRef} tabIndex={-1}>
{title}
</h2>
<p className="override-sub">Repeating presence for {child.display_name}</p>
</div>
</header>
<div className="override-scroll">
<section className="override-card" aria-label="Pattern details">
<label className="override-field">
<span className="override-label">Name</span>
<input
className="override-input"
type="text"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</label>
<div className="override-field">
<span className="override-label" id="pattern-label-kind">
Covered days are
</span>
<div className="override-segments override-segments--2" role="group" aria-labelledby="pattern-label-kind">
{(["away", "home"] as PatternKind[]).map((value) => (
<button
key={value}
type="button"
className="override-segment override-segment--ink"
aria-pressed={kind === value}
onClick={() => setKind(value)}
>
{value === "away" ? "Away" : "Home"}
</button>
))}
</div>
</div>
<div className="override-dates">
<label className="override-field">
<span className="override-label">Cycle length</span>
<select
className="override-input"
value={cycleLength}
onChange={(event) => {
const next = Number(event.target.value);
setCycleLength(next);
setWeeks((current) => resizePattern(current, next));
}}
>
{CYCLE_LENGTH_CHOICES.map((count) => (
<option key={count} value={count}>
{count} {count === 1 ? "week" : "weeks"}
</option>
))}
</select>
</label>
<label className="override-field">
<span className="override-label">Anchor date</span>
<input
className="override-input override-date"
type="date"
value={anchor}
onChange={(event) => setAnchor(event.target.value)}
/>
</label>
</div>
{Array.from({ length: cycleLength }, (_, week) => {
const days = body.pattern[week];
const from = isIsoDate(anchor)
? shortDate(isoFromDayNumber(dayNumber(anchor) + week * 7))
: null;
return (
<div key={week} className="override-field">
<span className="override-label" id={`pattern-label-week-${week}`}>
Week {week + 1}
{from ? ` · from ${from}` : ""}
</span>
<div
className="override-segments override-segments--7"
role="group"
aria-labelledby={`pattern-label-week-${week}`}
>
{DISPLAY_WEEKDAYS.map((weekday) => (
<button
key={weekday}
type="button"
className="override-segment override-segment--ink"
aria-pressed={days.includes(weekday)}
aria-label={WEEKDAY_NAMES[weekday]}
onClick={() => setWeeks((current) => togglePatternDay(current, week, weekday))}
>
{WEEKDAY_SHORT[weekday].slice(0, 2)}
</button>
))}
</div>
</div>
);
})}
<p className="override-sub">
{isIsoDate(anchor)
? `Week 1 starts ${anchorLabel(anchor)}; the cycle repeats from there.`
: "Choose an anchor date."}
</p>
</section>
{error ? (
<p className="override-error" role="alert" data-testid="pattern-error">
{error}
</p>
) : null}
<div className="override-footer">
<button type="button" className="override-cancel" onClick={onCancel} disabled={saving}>
Cancel
</button>
<button type="button" className="override-save" onClick={save} disabled={!canSave}>
{saving ? "Saving…" : "Save pattern"}
</button>
</div>
</div>
</div>
);
}
+64 -11
View File
@@ -119,13 +119,14 @@
}
.schedule-day {
display: grid;
place-items: center;
aspect-ratio: 1;
padding: 0;
border: 1px solid transparent;
border-radius: 6px;
font-family: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
.schedule-day--home {
@@ -183,11 +184,60 @@
border-radius: 3px;
}
.schedule-legend-note {
margin: 8px 0 0;
font-size: 10.5px;
/* Pattern editing controls */
.schedule-controls {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 8px;
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--nq-a-divider);
}
.schedule-field {
display: flex;
flex-direction: column;
gap: 3px;
font-size: var(--nq-a-size-label);
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--nq-a-ink-secondary);
}
.schedule-field input,
.schedule-field select {
min-height: 36px;
padding: 0 8px;
border: 1px solid var(--nq-a-border);
border-radius: 6px;
background: var(--nq-a-surface);
color: var(--nq-a-ink);
font-family: inherit;
font-size: 13px;
font-weight: 600;
color: var(--nq-a-ink-tertiary);
text-transform: none;
letter-spacing: normal;
}
.schedule-save {
min-height: 36px;
margin-left: auto;
padding: 0 14px;
border: 0;
border-radius: var(--nq-a-density-radius);
background: var(--nq-brand-gradient);
color: #fff;
font-family: inherit;
font-size: 13px;
font-weight: 700;
cursor: pointer;
}
.schedule-save:disabled {
opacity: 0.45;
cursor: default;
}
.schedule-save-status {
@@ -201,7 +251,7 @@
color: var(--nq-a-danger-strong);
}
/* Presence patterns + overrides cards */
/* Presence pattern + overrides cards */
.schedule-section-head {
display: flex;
align-items: center;
@@ -268,6 +318,13 @@
color: var(--nq-a-ink-secondary);
}
.schedule-rule {
flex: none;
font-size: 12px;
font-weight: 600;
color: var(--nq-a-ink-secondary);
}
.schedule-icon-action {
flex: none;
display: grid;
@@ -282,10 +339,6 @@
cursor: pointer;
}
.schedule-icon-action--edit {
margin-right: -4px;
}
.schedule-empty {
padding: var(--nq-a-density-card-pad);
font-size: 13px;
+88 -522
View File
@@ -1,11 +1,9 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import ScheduleTab from "./ScheduleTab";
import type { AdminChild } from "../api/definitions";
import type { PresenceOverride, PresencePattern } from "../api/presence";
import type { PresenceOverride, PresenceSchedule } from "../api/presence";
import { storeTokens } from "../auth/oidc";
import { AppTimezoneProvider } from "../time/AppTimezone";
import { cycleWeekIndex, monthDates, weekdayOf } from "./cycle";
function child(id: number, display_name: string, sort_order: number, is_active = true): AdminChild {
return { id, display_name, colour: null, avatar_ref: null, sort_order, is_active };
@@ -18,39 +16,20 @@ const CHILDREN = [
child(9, "Former", 4, false),
];
// Declan: the migrated single schedule — one `home` pattern anchored Monday
// 2026-09-07; cycle week 0 home every day, week 1 Sat/Sun only. Keys arrive
// as JSON strings, exactly as the API serializes them.
const DECLAN_HOME: PresencePattern = {
id: 1,
// Declan: anchor Monday 2026-09-07; cycle week 0 home every day, week 1 Sat/Sun.
// Keys arrive as JSON strings, exactly as the API serializes them.
const DECLAN: PresenceSchedule = {
child_id: 1,
name: "Home weeks",
kind: "home",
cycle_length_weeks: 2,
anchor_date: "2026-09-07",
pattern: { "0": [0, 1, 2, 3, 4, 5, 6], "1": [5, 6] },
};
// Maeve: the owner scenario — away Thursday+Friday every week, and away
// weekends every 2 weeks (the "on" week is cycle week 0 from Sep 7).
const MAEVE_THU_FRI: PresencePattern = {
id: 2,
const MAEVE: PresenceSchedule = {
child_id: 2,
name: "Thursday+Friday",
kind: "away",
cycle_length_weeks: 1,
cycle_length_weeks: 4,
anchor_date: "2026-09-07",
pattern: { "0": [3, 4] },
};
const MAEVE_WEEKENDS: PresencePattern = {
id: 3,
child_id: 2,
name: "Alternate weekends",
kind: "away",
cycle_length_weeks: 2,
anchor_date: "2026-09-07",
pattern: { "0": [5, 6], "1": [] },
pattern: { "0": [0, 1, 2, 3, 4, 5, 6], "1": [], "2": [0, 1, 2, 3, 4, 5, 6], "3": [] },
};
const OVERRIDES: PresenceOverride[] = [
@@ -60,7 +39,6 @@ const OVERRIDES: PresenceOverride[] = [
];
const TODAY = "2026-09-23";
const PATTERNS_PATH = "/api/v1/admin/presence-patterns";
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
@@ -69,69 +47,17 @@ function jsonResponse(body: unknown, status = 200): Response {
});
}
interface Call {
method: string;
path: string;
body: unknown;
}
/** The server's pattern store; POST/PATCH/DELETE mutate it like the API. */
let patterns: Record<number, PresencePattern[]>;
let nextId: number;
let writeFailure: Response | null;
let fetchMock: ReturnType<typeof vi.fn>;
function calls(): Call[] {
return fetchMock.mock.calls.map((args: unknown[]) => {
const [url, init] = args as [string, RequestInit | undefined];
return {
method: init?.method ?? "GET",
path: new URL(String(url), "http://x").pathname,
body: init?.body ? JSON.parse(String(init.body)) : undefined,
};
});
}
function writes(): Call[] {
return calls().filter((c) => c.method !== "GET");
}
function findPattern(id: number): PresencePattern | undefined {
return Object.values(patterns)
.flat()
.find((p) => p.id === id);
}
let putResponse: (body: unknown) => Response;
function routeFetch(url: string, init: RequestInit = {}): Response {
const path = new URL(url, "http://x").pathname;
const method = init.method ?? "GET";
const body = init.body ? JSON.parse(String(init.body)) : undefined;
if (method !== "GET" && writeFailure) return writeFailure;
if (init.method === "PUT") return putResponse(JSON.parse(String(init.body)));
if (path.endsWith("/admin/children")) return jsonResponse({ children: CHILDREN });
const collection = /\/children\/(\d+)\/presence-patterns$/.exec(path);
if (collection) {
const childId = Number(collection[1]);
if (method === "POST") {
const stored: PresencePattern = { id: nextId++, child_id: childId, ...body };
patterns[childId] = [...(patterns[childId] ?? []), stored];
return jsonResponse(stored, 201);
}
return jsonResponse({ patterns: patterns[childId] ?? [] });
}
const single = /\/presence-patterns\/(\d+)$/.exec(path);
if (single) {
const id = Number(single[1]);
const existing = findPattern(id);
if (!existing) return jsonResponse({ detail: "Presence pattern not found" }, 404);
if (method === "PATCH") {
const updated = { ...existing, ...body };
patterns[existing.child_id] = patterns[existing.child_id].map((p) => (p.id === id ? updated : p));
return jsonResponse(updated);
}
if (method === "DELETE") {
patterns[existing.child_id] = patterns[existing.child_id].filter((p) => p.id !== id);
return jsonResponse({ status: "ok" });
}
const match = /\/children\/(\d+)\/presence-schedule$/.exec(path);
if (match) {
const id = Number(match[1]);
return jsonResponse({ schedule: id === 1 ? DECLAN : id === 2 ? MAEVE : null });
}
if (path.endsWith("/presence-overrides")) return jsonResponse({ overrides: OVERRIDES });
return jsonResponse({ detail: "unexpected" }, 500);
@@ -143,32 +69,16 @@ function day(date: string): HTMLElement {
return cell;
}
function saveButton(): HTMLButtonElement {
return screen.getByRole("button", { name: "Save pattern" }) as HTMLButtonElement;
}
function weekGroup(week: number): HTMLElement {
return screen.getByRole("group", { name: new RegExp(`^Week ${week}\\b`) });
}
async function renderReady() {
render(<ScheduleTab today={TODAY} />);
await screen.findByTestId("pattern-1");
}
async function selectMaeve() {
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Maeve" }));
await screen.findByTestId("pattern-3");
}
describe("ScheduleTab", () => {
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
patterns = { 1: [DECLAN_HOME], 2: [MAEVE_THU_FRI, MAEVE_WEEKENDS], 3: [] };
nextId = 50;
writeFailure = null;
putResponse = (body) => jsonResponse({ child_id: 1, ...(body as object) });
fetchMock = vi.fn(async (url: string, init?: RequestInit) => routeFetch(url, init));
vi.stubGlobal("fetch", fetchMock);
});
@@ -178,31 +88,27 @@ describe("ScheduleTab", () => {
vi.unstubAllGlobals();
});
it("loads active children, their patterns and the overrides", async () => {
it("loads active children, their schedules and the overrides", async () => {
await renderReady();
const urls = calls().map((c) => c.path);
const urls = fetchMock.mock.calls.map(([url]) => new URL(String(url), "http://x").pathname);
expect(urls).toContain("/api/v1/admin/children");
expect(urls).toContain("/api/v1/admin/children/1/presence-patterns");
expect(urls).toContain("/api/v1/admin/children/2/presence-patterns");
expect(urls).toContain("/api/v1/admin/children/3/presence-patterns");
expect(urls).not.toContain("/api/v1/admin/children/9/presence-patterns");
expect(urls).toContain("/api/v1/admin/children/1/presence-schedule");
expect(urls).toContain("/api/v1/admin/children/2/presence-schedule");
expect(urls).toContain("/api/v1/admin/children/3/presence-schedule");
expect(urls).not.toContain("/api/v1/admin/children/9/presence-schedule");
expect(urls).toContain("/api/v1/admin/presence-overrides");
const chips = within(screen.getByRole("group", { name: "Child" })).getAllByRole("button");
expect(chips.map((chip) => chip.textContent)).toEqual(["Declan", "Maeve", "Rory"]);
expect(chips[0].getAttribute("aria-pressed")).toBe("true");
});
it("header names the child and how many patterns it has", async () => {
it("header shows the cycle length and anchor", async () => {
await renderReady();
expect(screen.getByRole("heading", { name: "Schedule" })).toBeTruthy();
expect(screen.getByText("Declan · 1 pattern")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Maeve" }));
expect(screen.getByText("Maeve · 2 patterns")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Rory" }));
expect(screen.getByText("Rory · no patterns, home every day")).toBeTruthy();
expect(screen.getByText("2-week cycle · anchor Monday, Sep 7")).toBeTruthy();
});
it("a home-pattern-only child is away on days no home pattern covers", async () => {
it("month grid renders home, away, override and today states from the anchor", async () => {
await renderReady();
expect(screen.getByTestId("month-label").textContent).toBe("September 2026");
const states: Record<string, string> = {
@@ -225,22 +131,10 @@ describe("ScheduleTab", () => {
expect(today.className).toContain("schedule-day--today");
expect(today.dataset.state).toBe("home");
expect(today.getAttribute("aria-label")).toBe("Sep 23 (today): Home");
// The grid is a read-out of the combined presence, not a set of toggles.
expect(today.tagName).toBe("SPAN");
// Sunday-first header; September 2026 starts on a Tuesday: two leading pads.
// September 2026 starts on a Tuesday: one leading pad after the initials.
const grid = screen.getByRole("group", { name: "Month grid" });
expect(Array.from(grid.children, (c) => c.textContent).slice(0, 7)).toEqual([
"S",
"M",
"T",
"W",
"T",
"F",
"S",
]);
expect(grid.children[7].getAttribute("data-date")).toBeNull();
expect(grid.children[8].getAttribute("data-date")).toBeNull();
expect(grid.children[9].getAttribute("data-date")).toBe("2026-09-01");
expect(grid.children[7].tagName).toBe("SPAN");
expect(grid.children[8].getAttribute("data-date")).toBe("2026-09-01");
const legend = screen.getByRole("list", { name: "Legend" });
expect(within(legend).getAllByRole("listitem").map((li) => li.textContent)).toEqual([
@@ -250,29 +144,6 @@ describe("ScheduleTab", () => {
"Override · home",
"Today",
]);
expect(screen.getByText(/Combined from every pattern/)).toBeTruthy();
});
it("the owner scenario: Thu/Fri away every week, Sat/Sun away only in the on week", async () => {
await selectMaeve();
for (const date of monthDates("2026-09-01")) {
if (date >= "2026-09-28") continue; // Camp override, checked below
const weekday = weekdayOf(date);
const onWeek = cycleWeekIndex("2026-09-07", date, 2) === 0;
const away = weekday === 3 || weekday === 4 || (weekday >= 5 && onWeek);
expect(day(date).dataset.state, date).toBe(away ? "away" : "home");
}
// Explicit spot checks of that rule.
expect(day("2026-09-03").dataset.state).toBe("away"); // Thu
expect(day("2026-09-04").dataset.state).toBe("away"); // Fri
expect(day("2026-09-05").dataset.state).toBe("home"); // Sat, off week (pre-anchor)
expect(day("2026-09-12").dataset.state).toBe("away"); // Sat, on week
expect(day("2026-09-13").dataset.state).toBe("away"); // Sun, on week
expect(day("2026-09-19").dataset.state).toBe("home"); // Sat, off week
expect(day("2026-09-20").dataset.state).toBe("home"); // Sun, off week
expect(day("2026-09-26").dataset.state).toBe("away"); // Sat, on week again
expect(day("2026-09-14").dataset.state).toBe("home"); // Mon
expect(day("2026-09-28").dataset.state).toBe("override-away");
});
it("navigates months with the chevrons", async () => {
@@ -287,36 +158,14 @@ describe("ScheduleTab", () => {
expect(screen.getByTestId("month-label").textContent).toBe("September 2026");
});
it("patterns list shows each pattern's name, kind, cycle and weekday set", async () => {
await selectMaeve();
const list = screen.getByRole("list", { name: "Presence patterns" });
expect(within(list).getAllByRole("listitem")).toHaveLength(2);
const thuFri = within(list).getByTestId("pattern-2");
expect(within(thuFri).getByText("Thursday+Friday")).toBeTruthy();
expect(within(thuFri).getByText("Away · Every week")).toBeTruthy();
expect(within(thuFri).getByText("Thu, Fri")).toBeTruthy();
const weekends = within(list).getByTestId("pattern-3");
expect(within(weekends).getByText("Alternate weekends")).toBeTruthy();
expect(within(weekends).getByText("Away · Every 2 weeks")).toBeTruthy();
expect(within(weekends).getByText("Week 1: Sat, Sun · Week 2: No days")).toBeTruthy();
expect(within(weekends).getByRole("button", { name: "Edit Alternate weekends" })).toBeTruthy();
expect(within(weekends).getByRole("button", { name: "Delete Alternate weekends" })).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Declan" }));
const declan = screen.getByTestId("pattern-1");
expect(within(declan).getByText("Home · Every 2 weeks")).toBeTruthy();
expect(within(declan).getByText("Week 1: Every day · Week 2: Sat, Sun")).toBeTruthy();
});
it("a child with no patterns is home every day", async () => {
it("presence pattern card shows a rule per child", async () => {
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Rory" }));
expect(screen.getByTestId("patterns-empty").textContent).toBe("No patterns for Rory — home every day.");
for (const date of monthDates("2026-09-01")) expect(day(date).dataset.state, date).toBe("home");
expect(screen.getByText("No overrides for Rory.")).toBeTruthy();
expect(within(screen.getByTestId("pattern-1")).getByText("Weeks 1 & 2 of cycle")).toBeTruthy();
expect(within(screen.getByTestId("pattern-2")).getByText("Weeks 1 & 3 of cycle")).toBeTruthy();
expect(within(screen.getByTestId("pattern-3")).getByText("Every day")).toBeTruthy();
});
it("overrides card lists the selected child's overrides", async () => {
it("overrides card lists the selected child's overrides with inert actions", async () => {
await renderReady();
const list = screen.getByRole("list", { name: "Overrides" });
expect(within(list).getAllByRole("listitem")).toHaveLength(2);
@@ -329,317 +178,86 @@ describe("ScheduleTab", () => {
fireEvent.click(screen.getByRole("button", { name: "Maeve" }));
expect(screen.getByText("Maeve away · Sep 28 – Oct 2")).toBeTruthy();
expect(screen.getByText("4-week cycle · anchor Monday, Sep 7")).toBeTruthy();
});
it("Add POSTs a new pattern to the child's collection and refreshes the list from the API", async () => {
it("a child with no schedule is home every day and defaults to a 2-week cycle", async () => {
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Rory" }));
fireEvent.click(screen.getByRole("button", { name: "Add pattern" }));
expect(await screen.findByRole("heading", { name: "New pattern" })).toBeTruthy();
// Nothing named yet.
expect(saveButton().disabled).toBe(true);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: " Dad's weekends " } });
fireEvent.change(screen.getByLabelText("Cycle length"), { target: { value: "2" } });
fireEvent.change(screen.getByLabelText("Anchor date"), { target: { value: "2026-09-07" } });
// Sunday-first buttons; the body keeps Monday=0 numbering.
const week1 = weekGroup(1);
expect(within(week1).getAllByRole("button").map((b) => b.textContent)).toEqual([
"Su",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa",
]);
fireEvent.click(within(week1).getByRole("button", { name: "Saturday" }));
fireEvent.click(within(week1).getByRole("button", { name: "Sunday" }));
expect(saveButton().disabled).toBe(false);
const before = calls().length;
fireEvent.click(saveButton());
const row = await screen.findByTestId("pattern-50");
expect(screen.queryByRole("heading", { name: "New pattern" })).toBeNull();
expect(writes()).toEqual([
{
method: "POST",
path: "/api/v1/admin/children/3/presence-patterns",
body: {
name: "Dad's weekends",
kind: "away",
cycle_length_weeks: 2,
anchor_date: "2026-09-07",
pattern: { "0": [5, 6], "1": [] },
},
},
]);
const after = calls().slice(before);
expect(after.some((c) => c.method === "GET" && c.path === "/api/v1/admin/children/3/presence-patterns")).toBe(
expect(screen.getByText("2-week cycle · anchor Tuesday, Sep 1")).toBeTruthy();
expect(day("2026-09-15").dataset.state).toBe("home");
expect(screen.getByText("No overrides for Rory.")).toBeTruthy();
expect((screen.getByRole("button", { name: "Save pattern" }) as HTMLButtonElement).disabled).toBe(
true,
);
expect(within(row).getByText("Dad's weekends")).toBeTruthy();
expect(within(row).getByText("Away · Every 2 weeks")).toBeTruthy();
expect(day("2026-09-12").dataset.state).toBe("away");
expect(day("2026-09-19").dataset.state).toBe("home");
// Focus returns to the Add control of the patterns section.
expect(document.activeElement).toBe(screen.getByRole("button", { name: "Add pattern" }));
});
it("Add can save a Home pattern", async () => {
it("editing a day and saving PUTs the pattern; the grid reflects the saved schedule", async () => {
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Rory" }));
fireEvent.click(screen.getByRole("button", { name: "Add pattern" }));
await screen.findByRole("heading", { name: "New pattern" });
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "School nights" } });
fireEvent.click(screen.getByRole("button", { name: "Home" }));
fireEvent.click(within(weekGroup(1)).getByRole("button", { name: "Monday" }));
fireEvent.click(saveButton());
await screen.findByTestId("pattern-50");
expect(writes()[0].body).toEqual({
name: "School nights",
kind: "home",
cycle_length_weeks: 1,
anchor_date: TODAY,
pattern: { "0": [0] },
});
// A home pattern: uncovered days are now away.
expect(day("2026-09-14").dataset.state).toBe("home"); // Monday
expect(day("2026-09-15").dataset.state).toBe("away"); // Tuesday
});
expect(day("2026-09-01").dataset.state).toBe("away");
fireEvent.click(day("2026-09-01")); // cycle week 1 (pre-anchor), Tuesday
it("Save requires a name; covered days alone are not enough", async () => {
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Rory" }));
fireEvent.click(screen.getByRole("button", { name: "Add pattern" }));
await screen.findByRole("heading", { name: "New pattern" });
fireEvent.click(within(weekGroup(1)).getByRole("button", { name: "Monday" }));
expect(saveButton().disabled).toBe(true);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: " " } });
expect(saveButton().disabled).toBe(true);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Mondays" } });
expect(saveButton().disabled).toBe(false);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "" } });
expect(saveButton().disabled).toBe(true);
fireEvent.click(saveButton());
expect(writes()).toEqual([]);
});
// The draft already shows the edit, and every other week-1 Tuesday follows.
expect(day("2026-09-01").dataset.state).toBe("home");
expect(day("2026-09-15").dataset.state).toBe("home");
expect(day("2026-09-08").dataset.state).toBe("home");
it("Add saves a pattern that covers no weekday and lists it", async () => {
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Rory" }));
fireEvent.click(screen.getByRole("button", { name: "Add pattern" }));
await screen.findByRole("heading", { name: "New pattern" });
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Always away" } });
fireEvent.click(screen.getByRole("button", { name: "Home" }));
fireEvent.change(screen.getByLabelText("Cycle length"), { target: { value: "2" } });
expect(saveButton().disabled).toBe(false);
fireEvent.click(saveButton());
const row = await screen.findByTestId("pattern-50");
fireEvent.click(screen.getByRole("button", { name: "Save pattern" }));
expect(await screen.findByText("Pattern saved.")).toBeTruthy();
expect(writes()).toEqual([
{
method: "POST",
path: "/api/v1/admin/children/3/presence-patterns",
body: {
name: "Always away",
kind: "home",
cycle_length_weeks: 2,
anchor_date: TODAY,
pattern: { "0": [], "1": [] },
},
},
]);
expect(findPattern(50)?.pattern).toEqual({ "0": [], "1": [] });
expect(within(row).getByText("Always away")).toBeTruthy();
expect(within(row).getByText("Home · Every 2 weeks")).toBeTruthy();
expect(within(row).getByText("Week 1: No days · Week 2: No days")).toBeTruthy();
// A home pattern covering no day: the child is away every day.
for (const date of monthDates("2026-09-01")) expect(day(date).dataset.state, date).toBe("away");
});
it("Edit of a migrated all-absent home pattern saves without touching any weekday", async () => {
const migrated: PresencePattern = {
id: 7,
child_id: 3,
name: "Home weeks",
kind: "home",
const put = fetchMock.mock.calls.find(([, init]) => init?.method === "PUT");
expect(put).toBeTruthy();
const [url, init] = put!;
expect(new URL(String(url), "http://x").pathname).toBe("/api/v1/admin/children/1/presence-schedule");
expect(init.headers.Authorization).toBe("Bearer at-123");
expect(JSON.parse(init.body)).toEqual({
cycle_length_weeks: 2,
anchor_date: "2026-09-07",
pattern: { "0": [], "1": [] },
};
patterns[3] = [migrated];
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Rory" }));
fireEvent.click(await screen.findByRole("button", { name: "Edit Home weeks" }));
await screen.findByRole("heading", { name: "Edit pattern" });
for (const week of [1, 2]) {
for (const button of within(weekGroup(week)).getAllByRole("button")) {
expect(button.getAttribute("aria-pressed")).toBe("false");
}
}
// Unchanged: nothing to save.
expect(saveButton().disabled).toBe(true);
pattern: { "0": [0, 1, 2, 3, 4, 5, 6], "1": [1, 5, 6] },
});
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Never home" } });
expect(saveButton().disabled).toBe(false);
fireEvent.click(saveButton());
await waitFor(() => expect(screen.queryByRole("heading", { name: "Edit pattern" })).toBeNull());
expect(writes()).toEqual([{ method: "PATCH", path: `${PATTERNS_PATH}/7`, body: { name: "Never home" } }]);
expect(findPattern(7)).toEqual({ ...migrated, name: "Never home" });
const row = await screen.findByTestId("pattern-7");
expect(within(row).getByText("Week 1: No days · Week 2: No days")).toBeTruthy();
});
it("Edit PATCHes only the changed fields to /presence-patterns/{id} and refreshes", async () => {
await selectMaeve();
fireEvent.click(screen.getByRole("button", { name: "Edit Alternate weekends" }));
expect(await screen.findByRole("heading", { name: "Edit pattern" })).toBeTruthy();
expect((screen.getByLabelText("Name") as HTMLInputElement).value).toBe("Alternate weekends");
expect((screen.getByLabelText("Cycle length") as HTMLSelectElement).value).toBe("2");
expect((screen.getByLabelText("Anchor date") as HTMLInputElement).value).toBe("2026-09-07");
expect(within(weekGroup(1)).getByRole("button", { name: "Saturday" }).getAttribute("aria-pressed")).toBe(
"true",
);
// Unchanged: nothing to save.
expect(saveButton().disabled).toBe(true);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Every other weekend" } });
fireEvent.click(within(weekGroup(1)).getByRole("button", { name: "Sunday" }));
const before = calls().length;
fireEvent.click(saveButton());
await waitFor(() => expect(screen.queryByRole("heading", { name: "Edit pattern" })).toBeNull());
expect(writes()).toEqual([
{
method: "PATCH",
path: `${PATTERNS_PATH}/3`,
body: { name: "Every other weekend", pattern: { "0": [5], "1": [] } },
},
]);
const after = calls().slice(before);
expect(after.some((c) => c.method === "GET" && c.path === "/api/v1/admin/children/2/presence-patterns")).toBe(
expect(day("2026-09-15").dataset.state).toBe("home");
expect(day("2026-09-29").dataset.state).toBe("home");
expect(day("2026-09-30").dataset.state).toBe("away");
expect((screen.getByRole("button", { name: "Save pattern" }) as HTMLButtonElement).disabled).toBe(
true,
);
const row = await screen.findByText("Every other weekend");
expect(within(row.closest("li")!).getByText("Week 1: Sat · Week 2: No days")).toBeTruthy();
expect(day("2026-09-12").dataset.state).toBe("away"); // Sat, on week
expect(day("2026-09-13").dataset.state).toBe("home"); // Sun no longer covered
});
it("Delete asks first, DELETEs /presence-patterns/{id} and refreshes the list", async () => {
await selectMaeve();
fireEvent.click(screen.getByRole("button", { name: "Delete Thursday+Friday" }));
const confirm = within(screen.getByTestId("pattern-2")).getByRole("group", { name: "Confirm delete" });
fireEvent.click(within(confirm).getByRole("button", { name: "Keep" }));
expect(writes()).toEqual([]);
fireEvent.click(screen.getByRole("button", { name: "Delete Thursday+Friday" }));
fireEvent.click(within(screen.getByTestId("pattern-2")).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(screen.queryByTestId("pattern-2")).toBeNull());
expect(writes()).toEqual([{ method: "DELETE", path: `${PATTERNS_PATH}/2`, body: undefined }]);
expect(screen.getByTestId("pattern-3")).toBeTruthy();
expect(day("2026-09-17").dataset.state).toBe("home"); // Thursday, no longer away
expect(day("2026-09-12").dataset.state).toBe("away"); // weekends pattern still applies
});
it("deleting the last pattern leaves the child with none: home every day", async () => {
it("saves an edited anchor date and cycle length", async () => {
await renderReady();
expect(day("2026-09-15").dataset.state).toBe("away");
fireEvent.click(screen.getByRole("button", { name: "Delete Home weeks" }));
fireEvent.click(within(screen.getByTestId("pattern-1")).getByRole("button", { name: "Delete" }));
expect(await screen.findByTestId("patterns-empty")).toBeTruthy();
expect(screen.queryByRole("list", { name: "Presence patterns" })).toBeNull();
expect(patterns[1]).toEqual([]);
expect(day("2026-09-15").dataset.state).toBe("home");
expect(day("2026-09-11").dataset.state).toBe("override-away"); // overrides still win
expect(screen.getByText("Declan · no patterns, home every day")).toBeTruthy();
fireEvent.change(screen.getByLabelText("Anchor date"), { target: { value: "2026-09-14" } });
fireEvent.change(screen.getByLabelText("Cycle length"), { target: { value: "3" } });
expect(screen.getByText("3-week cycle · anchor Monday, Sep 14")).toBeTruthy();
// Anchor moved a week: Sep 7-13 is now the last week of the cycle (full, added).
fireEvent.click(screen.getByRole("button", { name: "Save pattern" }));
await screen.findByText("Pattern saved.");
const [, init] = fetchMock.mock.calls.find(([, i]) => i?.method === "PUT")!;
expect(JSON.parse(init.body)).toEqual({
cycle_length_weeks: 3,
anchor_date: "2026-09-14",
pattern: {
"0": [0, 1, 2, 3, 4, 5, 6],
"1": [5, 6],
"2": [0, 1, 2, 3, 4, 5, 6],
},
});
});
it("a 422 on save shows the API detail naming the field and keeps the editor open", async () => {
writeFailure = jsonResponse({ detail: "name must not be empty" }, 422);
await selectMaeve();
fireEvent.click(screen.getByRole("button", { name: "Edit Thursday+Friday" }));
await screen.findByRole("heading", { name: "Edit pattern" });
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Thu/Fri" } });
fireEvent.click(saveButton());
const alert = await screen.findByTestId("pattern-error");
expect(alert.getAttribute("role")).toBe("alert");
expect(alert.textContent).toBe("name must not be empty");
expect(screen.getByRole("heading", { name: "Edit pattern" })).toBeTruthy();
expect((screen.getByLabelText("Name") as HTMLInputElement).value).toBe("Thu/Fri");
expect(saveButton().disabled).toBe(false);
});
it("a 403 on add is surfaced as the refusal, not swallowed", async () => {
writeFailure = new Response("", { status: 403 });
it("a 422 shows the API detail and keeps the draft", async () => {
putResponse = () => jsonResponse({ detail: "anchor_date must be a Monday" }, 422);
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Add pattern" }));
await screen.findByRole("heading", { name: "New pattern" });
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Fridays" } });
fireEvent.click(within(weekGroup(1)).getByRole("button", { name: "Friday" }));
fireEvent.click(saveButton());
const alert = await screen.findByTestId("pattern-error");
expect(alert.textContent).toBe("Your account is not in the nestquest-admins group.");
expect(patterns[1]).toEqual([DECLAN_HOME]);
});
fireEvent.click(day("2026-09-01"));
fireEvent.click(screen.getByRole("button", { name: "Save pattern" }));
it("a 403 on delete is surfaced and the pattern stays listed", async () => {
writeFailure = new Response("", { status: 403 });
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Delete Home weeks" }));
fireEvent.click(within(screen.getByTestId("pattern-1")).getByRole("button", { name: "Delete" }));
const alert = await screen.findByRole("alert");
expect(alert.textContent).toBe("Your account is not in the nestquest-admins group.");
expect(screen.getByTestId("pattern-1")).toBeTruthy();
});
it("a 422 on delete shows the API detail", async () => {
writeFailure = jsonResponse({ detail: "pattern_id must be an integer" }, 422);
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Delete Home weeks" }));
fireEvent.click(within(screen.getByTestId("pattern-1")).getByRole("button", { name: "Delete" }));
expect((await screen.findByRole("alert")).textContent).toBe("pattern_id must be an integer");
});
it("Cancel closes the editor without any request", async () => {
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "Add pattern" }));
await screen.findByRole("heading", { name: "New pattern" });
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Draft" } });
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.queryByRole("heading", { name: "New pattern" })).toBeNull();
expect(writes()).toEqual([]);
expect(document.activeElement).toBe(screen.getByRole("button", { name: "Add pattern" }));
});
it("never calls the removed one-per-child /presence-schedule route", async () => {
await selectMaeve();
// Add, edit and delete: every pattern path the screen can take.
fireEvent.click(screen.getByRole("button", { name: "Add pattern" }));
await screen.findByRole("heading", { name: "New pattern" });
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Mondays" } });
fireEvent.click(within(weekGroup(1)).getByRole("button", { name: "Monday" }));
fireEvent.click(saveButton());
await screen.findByTestId("pattern-50");
fireEvent.click(screen.getByRole("button", { name: "Edit Mondays" }));
await screen.findByRole("heading", { name: "Edit pattern" });
fireEvent.click(screen.getByRole("button", { name: "Home" }));
fireEvent.click(saveButton());
await waitFor(() => expect(screen.queryByRole("heading", { name: "Edit pattern" })).toBeNull());
fireEvent.click(await screen.findByRole("button", { name: "Delete Mondays" }));
fireEvent.click(within(screen.getByTestId("pattern-50")).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(screen.queryByTestId("pattern-50")).toBeNull());
expect(writes().map((c) => `${c.method} ${c.path}`)).toEqual([
"POST /api/v1/admin/children/2/presence-patterns",
`PATCH ${PATTERNS_PATH}/50`,
`DELETE ${PATTERNS_PATH}/50`,
]);
expect(calls().filter((c) => c.path.includes("presence-schedule"))).toEqual([]);
expect(alert.textContent).toBe("anchor_date must be a Monday");
expect(day("2026-09-01").dataset.state).toBe("home");
expect((screen.getByRole("button", { name: "Save pattern" }) as HTMLButtonElement).disabled).toBe(
false,
);
// The saved rule is unchanged.
expect(within(screen.getByTestId("pattern-1")).getByText("Weeks 1 & 2 of cycle")).toBeTruthy();
});
it("scroll column ends with 92px bottom padding", async () => {
@@ -656,55 +274,3 @@ describe("ScheduleTab", () => {
expect(await screen.findByTestId("pattern-1")).toBeTruthy();
});
});
describe("ScheduleTab today in the stored application timezone", () => {
async function renderWithZone(timezone: string, effective_timezone = timezone) {
fetchMock = vi.fn(async (url: string, init?: RequestInit) =>
String(url).endsWith("/api/v1/admin/settings")
? jsonResponse({ timezone, effective_timezone })
: routeFetch(url, init),
);
vi.stubGlobal("fetch", fetchMock);
render(
<AppTimezoneProvider>
<ScheduleTab />
</AppTimezoneProvider>,
);
await screen.findByTestId("pattern-1");
}
beforeAll(() => {
vi.stubEnv("TZ", "UTC");
});
afterAll(() => {
vi.unstubAllEnvs();
});
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
patterns = { 1: [DECLAN_HOME], 2: [MAEVE_THU_FRI, MAEVE_WEEKENDS], 3: [] };
writeFailure = null;
// 13:00 UTC on Sep 23 is already 01:00 on Sep 24 in Auckland.
vi.useFakeTimers({ toFake: ["Date"], now: new Date("2026-09-23T13:00:00Z") });
});
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.unstubAllGlobals();
});
it("marks today in the stored zone", async () => {
await renderWithZone("Pacific/Auckland");
expect(day("2026-09-24").className).toContain("schedule-day--today");
expect(day("2026-09-23").className).not.toContain("schedule-day--today");
});
it("an empty stored zone marks today in the API host's published zone", async () => {
await renderWithZone("", "Pacific/Auckland");
expect(day("2026-09-24").className).toContain("schedule-day--today");
expect(day("2026-09-23").className).not.toContain("schedule-day--today");
});
});
+170 -202
View File
@@ -1,51 +1,52 @@
/**
* Schedule tab — the presence month grid (design/ADMIN-SPEC.md §4) and the
* selected child's presence patterns and overrides.
* Schedule tab — the presence month grid (design/ADMIN-SPEC.md §4).
*
* The grid shows the COMBINED presence of every pattern (./cycle.ts
* `dayState`); each pattern's cycle position comes from its own anchor date,
* never from ISO week numbers or week parity (D-004).
* Every day's cycle position comes from the anchor date (./cycle.ts), never
* from ISO week numbers or week parity (D-004).
*/
import { useEffect, useRef, useState } from "react";
import { ApiForbiddenError } from "../api/client";
import { ApiRequestError, fetchChildren, type AdminChild } from "../api/definitions";
import {
deletePresenceOverride,
deletePresencePattern,
fetchPresenceOverrides,
fetchPresencePatterns,
fetchPresenceSchedule,
savePresenceSchedule,
type PresenceOverride,
type PresencePattern,
type PresenceSchedule,
type PresenceScheduleBody,
} from "../api/presence";
import {
cycleLabel,
cycleWeekIndex,
dayState,
fullPattern,
localTodayIso,
monthDates,
monthStart,
patternDaysLabel,
patternIncludes,
presenceRule,
resizePattern,
togglePatternDay,
weekdayOf,
type DayState,
} from "./cycle";
import { dateRange, monthLabel, shortDate } from "./format";
import { anchorLabel, dateRange, monthLabel, shortDate } from "./format";
import {
CalendarCheckGlyph,
CalendarXGlyph,
ChevronLeftGlyph,
ChevronRightGlyph,
PencilGlyph,
Trash2Glyph,
} from "./glyphs";
import OverrideEditor from "./OverrideEditor";
import PatternEditor from "./PatternEditor";
import { useAppTimezone } from "../time/AppTimezone";
import { todayIn } from "../time/zone";
import "./ScheduleTab.css";
/** ADMIN-SPEC §1: every scroll column ends with 92px so content clears the tab bar. */
export const SCROLL_BOTTOM_PADDING = "92px";
/** Sunday-first header; `weekdayOf` stays Monday=0. */
const WEEKDAY_INITIALS = ["S", "M", "T", "W", "T", "F", "S"];
export const DEFAULT_CYCLE_LENGTH_WEEKS = 2;
const CYCLE_LENGTH_CHOICES = [1, 2, 3, 4];
const WEEKDAY_INITIALS = ["M", "T", "W", "T", "F", "S", "S"];
export const STATE_LABELS: Record<DayState, string> = {
home: "Home",
@@ -56,7 +57,7 @@ export const STATE_LABELS: Record<DayState, string> = {
interface Loaded {
children: AdminChild[];
patterns: Record<number, PresencePattern[]>;
schedules: Record<number, PresenceSchedule | null>;
overrides: PresenceOverride[];
}
@@ -71,22 +72,23 @@ type DeleteState =
| { kind: "deleting"; id: number }
| { kind: "error"; id: number; message: string };
type EditorState =
| { kind: "closed" }
| { kind: "override" }
| { kind: "pattern"; pattern: PresencePattern | null };
type SaveState =
| { kind: "idle" }
| { kind: "saving" }
| { kind: "saved" }
| { kind: "error"; message: string };
async function loadSchedule(): Promise<Loaded> {
const children = (await fetchChildren())
.filter((child) => child.is_active)
.sort((a, b) => a.sort_order - b.sort_order);
const [patterns, overrides] = await Promise.all([
Promise.all(children.map((child) => fetchPresencePatterns(child.id))),
const [schedules, overrides] = await Promise.all([
Promise.all(children.map((child) => fetchPresenceSchedule(child.id))),
fetchPresenceOverrides(),
]);
return {
children,
patterns: Object.fromEntries(children.map((child, i) => [child.id, patterns[i]])),
schedules: Object.fromEntries(children.map((child, i) => [child.id, schedules[i]])),
overrides,
};
}
@@ -97,7 +99,10 @@ function loadErrorMessage(error: unknown): string {
: "The schedule could not be loaded. Check your connection and try again.";
}
function saveErrorMessage(error: unknown, fallback: string): string {
function saveErrorMessage(
error: unknown,
fallback = "The pattern could not be saved. Check your connection and try again.",
): string {
if (error instanceof ApiForbiddenError) return error.message;
if (error instanceof ApiRequestError && error.detail) return error.detail;
return fallback;
@@ -115,15 +120,17 @@ function ScreenHeader({ sub }: { sub: string }) {
interface MonthGridProps {
month: string;
today: string;
/** Every pattern of the child; none means home every day. */
patterns: PresencePattern[];
schedule: PresenceScheduleBody;
/** Null when the child has no saved schedule and no edits: home every day. */
effective: PresenceScheduleBody | null;
overrides: PresenceOverride[];
onMonth: (delta: number) => void;
onToggle: (date: string) => void;
}
function MonthGrid({ month, today, patterns, overrides, onMonth }: MonthGridProps) {
function MonthGrid({ month, today, schedule, effective, overrides, onMonth, onToggle }: MonthGridProps) {
const dates = monthDates(month);
const leading = (weekdayOf(month) + 1) % 7;
const leading = weekdayOf(month);
return (
<>
<div className="schedule-month-head">
@@ -159,21 +166,23 @@ function MonthGrid({ month, today, patterns, overrides, onMonth }: MonthGridProp
<span key={`pad-${i}`} aria-hidden="true" />
))}
{dates.map((date) => {
const state = dayState(patterns, overrides, date);
const state = dayState(effective, overrides, date);
const isToday = date === today;
let className = `schedule-day schedule-day--${state}`;
if (isToday) className += " schedule-day--today";
return (
<span
<button
key={date}
role="img"
type="button"
className={className}
data-date={date}
data-state={state}
aria-pressed={patternIncludes(schedule, date)}
aria-label={`${shortDate(date)}${isToday ? " (today)" : ""}: ${STATE_LABELS[state]}`}
onClick={() => onToggle(date)}
>
{Number(date.slice(8))}
</span>
</button>
);
})}
</div>
@@ -189,83 +198,10 @@ function MonthGrid({ month, today, patterns, overrides, onMonth }: MonthGridProp
Today
</li>
</ul>
<p className="schedule-legend-note">
Combined from every pattern: away beats home; overrides beat both.
</p>
</>
);
}
interface PatternRowProps {
pattern: PresencePattern;
deletion: DeleteState;
onEdit: () => void;
onAskDelete: () => void;
onKeep: () => void;
onDelete: () => void;
}
function PatternRow({ pattern, deletion, onEdit, onAskDelete, onKeep, onDelete }: PatternRowProps) {
const mine =
(deletion.kind === "confirming" || deletion.kind === "deleting") && deletion.id === pattern.id;
return (
<li className="schedule-row" data-testid={`pattern-${pattern.id}`}>
<span className="schedule-row-glyph">
{pattern.kind === "home" ? <CalendarCheckGlyph /> : <CalendarXGlyph />}
</span>
<div className="schedule-row-text">
<div className="schedule-row-title">{pattern.name}</div>
<div className="schedule-row-meta">
{pattern.kind === "home" ? "Home" : "Away"} · {cycleLabel(pattern.cycle_length_weeks)}
</div>
<div className="schedule-row-meta" data-testid={`pattern-days-${pattern.id}`}>
{patternDaysLabel(pattern)}
</div>
</div>
{mine ? (
<div className="schedule-confirm" role="group" aria-label="Confirm delete">
<span className="schedule-confirm-text">Delete pattern?</span>
<button
type="button"
className="schedule-confirm-keep"
onClick={onKeep}
disabled={deletion.kind === "deleting"}
>
Keep
</button>
<button
type="button"
className="schedule-confirm-delete"
onClick={onDelete}
disabled={deletion.kind === "deleting"}
>
{deletion.kind === "deleting" ? "Deleting…" : "Delete"}
</button>
</div>
) : (
<>
<button
type="button"
className="schedule-icon-action schedule-icon-action--edit"
aria-label={`Edit ${pattern.name}`}
onClick={onEdit}
>
<PencilGlyph />
</button>
<button
type="button"
className="schedule-icon-action"
aria-label={`Delete ${pattern.name}`}
onClick={onAskDelete}
>
<Trash2Glyph />
</button>
</>
)}
</li>
);
}
interface OverrideRowProps {
override: PresenceOverride;
childName: string;
@@ -325,35 +261,30 @@ function OverrideRow({ override, childName, deletion, onAskDelete, onKeep, onDel
}
export interface ScheduleTabProps {
/** "YYYY-MM-DD"; defaults to today in the application timezone. */
/** "YYYY-MM-DD"; defaults to the viewer's local date. */
today?: string;
}
export default function ScheduleTab({ today: todayProp }: ScheduleTabProps) {
const timeZone = useAppTimezone();
const today = todayProp ?? todayIn(timeZone);
export default function ScheduleTab({ today = localTodayIso() }: ScheduleTabProps) {
const [state, setState] = useState<LoadState>({ kind: "loading" });
const [attempt, setAttempt] = useState(0);
const [selectedId, setSelectedId] = useState<number | null>(null);
const [month, setMonth] = useState(() => monthStart(today));
const [editor, setEditor] = useState<EditorState>({ kind: "closed" });
const [drafts, setDrafts] = useState<Record<number, PresenceScheduleBody>>({});
const [save, setSave] = useState<SaveState>({ kind: "idle" });
const [editorOpen, setEditorOpen] = useState(false);
const [deletion, setDeletion] = useState<DeleteState>({ kind: "idle" });
const [patternDeletion, setPatternDeletion] = useState<DeleteState>({ kind: "idle" });
const addRef = useRef<HTMLButtonElement>(null);
const addPatternRef = useRef<HTMLButtonElement>(null);
const openedEditor = useRef<EditorState["kind"]>("closed");
const editorWasOpen = useRef(false);
// An editor replaces this screen, so the Add controls are remounted when
// it closes; hand focus back to the one that belongs to that editor.
// The editor replaces this screen, so Add is remounted when it closes;
// hand focus back to it then.
useEffect(() => {
if (editor.kind === "closed") {
if (openedEditor.current === "override") addRef.current?.focus();
if (openedEditor.current === "pattern") addPatternRef.current?.focus();
}
openedEditor.current = editor.kind;
}, [editor.kind]);
if (editorWasOpen.current && !editorOpen) addRef.current?.focus();
editorWasOpen.current = editorOpen;
}, [editorOpen]);
/** Reload children, patterns and overrides in place (no loading flash). */
/** Reload children, schedules and overrides in place (no loading flash). */
const refresh = () =>
loadSchedule()
.then((data) => setState({ kind: "ready", data }))
@@ -377,31 +308,16 @@ export default function ScheduleTab({ today: todayProp }: ScheduleTabProps) {
};
}, [attempt]);
if (editor.kind !== "closed" && state.kind === "ready" && state.data.children.length > 0) {
if (editorOpen && state.kind === "ready" && state.data.children.length > 0) {
const { children } = state.data;
const current = children.find((c) => c.id === selectedId) ?? children[0];
if (editor.kind === "pattern") {
return (
<PatternEditor
child={current}
pattern={editor.pattern}
today={today}
onCancel={() => setEditor({ kind: "closed" })}
onSaved={() => {
setEditor({ kind: "closed" });
void refresh();
}}
/>
);
}
return (
<OverrideEditor
childOptions={children}
initialChildId={current.id}
initialChildId={children.find((c) => c.id === selectedId)?.id ?? children[0].id}
today={today}
onCancel={() => setEditor({ kind: "closed" })}
onCancel={() => setEditorOpen(false)}
onSaved={(override) => {
setEditor({ kind: "closed" });
setEditorOpen(false);
setSelectedId(override.child_id);
void refresh();
}}
@@ -431,13 +347,28 @@ export default function ScheduleTab({ today: todayProp }: ScheduleTabProps) {
} else {
const { data } = state;
const child = data.children.find((c) => c.id === selectedId) ?? data.children[0];
const patterns = data.patterns[child.id] ?? [];
const saved = data.schedules[child.id] ?? null;
const draft = drafts[child.id];
// Edits start from the saved schedule, or — with none — from "home every
// day" on a 2-week cycle anchored at the displayed month's 1st.
const schedule: PresenceScheduleBody = draft ??
saved ?? {
cycle_length_weeks: DEFAULT_CYCLE_LENGTH_WEEKS,
anchor_date: month,
pattern: fullPattern(DEFAULT_CYCLE_LENGTH_WEEKS),
};
const effective = draft ?? saved;
const childOverrides = data.overrides.filter((o) => o.child_id === child.id);
sub =
patterns.length === 0
? `${child.display_name} · no patterns, home every day`
: `${child.display_name} · ${patterns.length} ${patterns.length === 1 ? "pattern" : "patterns"}`;
sub = `${schedule.cycle_length_weeks}-week cycle · anchor ${anchorLabel(schedule.anchor_date)}`;
const edit = (next: PresenceScheduleBody) => {
setDrafts((all) => ({ ...all, [child.id]: next }));
setSave({ kind: "idle" });
};
const toggle = (date: string) => {
const week = cycleWeekIndex(schedule.anchor_date, date, schedule.cycle_length_weeks);
edit({ ...schedule, pattern: togglePatternDay(schedule.pattern, week, weekdayOf(date)) });
};
const confirmDelete = (id: number) => {
setDeletion({ kind: "deleting", id });
deletePresenceOverride(id)
@@ -454,21 +385,32 @@ export default function ScheduleTab({ today: todayProp }: ScheduleTabProps) {
}),
);
};
const confirmPatternDelete = (id: number) => {
setPatternDeletion({ kind: "deleting", id });
deletePresencePattern(id)
.then(() => refresh())
.then(() => setPatternDeletion({ kind: "idle" }))
.catch((error: unknown) =>
setPatternDeletion({
kind: "error",
id,
message: saveErrorMessage(
error,
"The pattern could not be deleted. Check your connection and try again.",
),
}),
);
const submit = () => {
if (!draft) return;
const childId = child.id;
setSave({ kind: "saving" });
const { cycle_length_weeks, anchor_date, pattern } = draft;
savePresenceSchedule(childId, { cycle_length_weeks, anchor_date, pattern })
.then((stored) => {
setState((current) =>
current.kind === "ready"
? {
kind: "ready",
data: {
...current.data,
schedules: { ...current.data.schedules, [childId]: stored },
},
}
: current,
);
setDrafts((all) => {
const rest = { ...all };
delete rest[childId];
return rest;
});
setSave({ kind: "saved" });
})
.catch((error: unknown) => setSave({ kind: "error", message: saveErrorMessage(error) }));
};
body = (
@@ -482,7 +424,7 @@ export default function ScheduleTab({ today: todayProp }: ScheduleTabProps) {
aria-pressed={c.id === child.id}
onClick={() => {
setSelectedId(c.id);
setPatternDeletion({ kind: "idle" });
setSave({ kind: "idle" });
}}
>
{c.display_name}
@@ -494,48 +436,74 @@ export default function ScheduleTab({ today: todayProp }: ScheduleTabProps) {
<MonthGrid
month={month}
today={today}
patterns={patterns}
schedule={schedule}
effective={effective}
overrides={childOverrides}
onMonth={(delta) => setMonth((m) => monthStart(m, delta))}
onToggle={toggle}
/>
<div className="schedule-controls">
<label className="schedule-field">
<span>Anchor date</span>
<input
type="date"
value={schedule.anchor_date}
onChange={(event) => {
if (event.target.value) edit({ ...schedule, anchor_date: event.target.value });
}}
/>
</label>
<label className="schedule-field">
<span>Cycle length</span>
<select
value={schedule.cycle_length_weeks}
onChange={(event) => {
const weeks = Number(event.target.value);
edit({
...schedule,
cycle_length_weeks: weeks,
pattern: resizePattern(schedule.pattern, weeks),
});
}}
>
{CYCLE_LENGTH_CHOICES.map((weeks) => (
<option key={weeks} value={weeks}>
{weeks} {weeks === 1 ? "week" : "weeks"}
</option>
))}
</select>
</label>
<button
type="button"
className="schedule-save"
disabled={!draft || save.kind === "saving"}
onClick={submit}
>
{save.kind === "saving" ? "Saving…" : "Save pattern"}
</button>
</div>
{save.kind === "error" ? (
<p className="schedule-save-status schedule-save-status--error" role="alert">
{save.message}
</p>
) : save.kind === "saved" ? (
<p className="schedule-save-status" role="status">
Pattern saved.
</p>
) : null}
</section>
<div className="schedule-section-head">
<h3 className="schedule-section-label">Presence patterns</h3>
<button
ref={addPatternRef}
type="button"
className="schedule-text-action"
aria-label="Add pattern"
onClick={() => setEditor({ kind: "pattern", pattern: null })}
>
Add
</button>
</div>
{patterns.length > 0 ? (
<ul className="schedule-card schedule-list" aria-label="Presence patterns">
{patterns.map((pattern) => (
<PatternRow
key={pattern.id}
pattern={pattern}
deletion={patternDeletion}
onEdit={() => setEditor({ kind: "pattern", pattern })}
onAskDelete={() => setPatternDeletion({ kind: "confirming", id: pattern.id })}
onKeep={() => setPatternDeletion({ kind: "idle" })}
onDelete={() => confirmPatternDelete(pattern.id)}
/>
))}
</ul>
) : (
<div className="schedule-card schedule-empty" data-testid="patterns-empty">
No patterns for {child.display_name} — home every day.
</div>
)}
{patternDeletion.kind === "error" ? (
<p className="schedule-save-status schedule-save-status--error" role="alert">
{patternDeletion.message}
</p>
) : null}
<h3 className="schedule-section-label">Presence pattern</h3>
<ul className="schedule-card schedule-list" aria-label="Presence pattern">
{data.children.map((c) => (
<li key={c.id} className="schedule-row" data-testid={`pattern-${c.id}`}>
<div className="schedule-row-text">
<div className="schedule-row-title">{c.display_name}</div>
</div>
<span className="schedule-rule">{presenceRule(data.schedules[c.id] ?? null)}</span>
</li>
))}
</ul>
<div className="schedule-section-head">
<h3 className="schedule-section-label">Overrides</h3>
@@ -543,7 +511,7 @@ export default function ScheduleTab({ today: todayProp }: ScheduleTabProps) {
ref={addRef}
type="button"
className="schedule-text-action"
onClick={() => setEditor({ kind: "override" })}
onClick={() => setEditorOpen(true)}
>
Add
</button>
+28 -104
View File
@@ -1,44 +1,23 @@
import { describe, expect, it } from "vitest";
import {
cycleLabel,
cycleWeekIndex,
dayState,
emptyPattern,
monthDates,
monthStart,
patternDaysLabel,
patternIncludes,
presenceRule,
resizePattern,
togglePatternDay,
weekdayOf,
} from "./cycle";
import type { PatternCycle, PatternKind, PresenceOverride } from "../api/presence";
import type { PresenceOverride, PresenceScheduleBody } from "../api/presence";
type KindedCycle = PatternCycle & { kind: PatternKind };
// The migrated single schedule: anchor Monday 2026-09-07; week 0 home every
// day, week 1 home Sat/Sun only.
const SCHEDULE: KindedCycle = {
kind: "home",
// Anchor Monday 2026-09-07; week 0 home every day, week 1 home Sat/Sun only.
const SCHEDULE: PresenceScheduleBody = {
cycle_length_weeks: 2,
anchor_date: "2026-09-07",
pattern: { 0: [0, 1, 2, 3, 4, 5, 6], 1: [5, 6] },
};
// The owner scenario: away Thu+Fri every week, away weekends every 2 weeks.
const THU_FRI: KindedCycle = {
kind: "away",
cycle_length_weeks: 1,
anchor_date: "2026-09-07",
pattern: { 0: [3, 4] },
};
const ALTERNATE_WEEKENDS: KindedCycle = {
kind: "away",
cycle_length_weeks: 2,
anchor_date: "2026-09-07",
pattern: { 0: [5, 6], 1: [] },
};
describe("cycleWeekIndex", () => {
it("follows the anchor across a month, wrapping every 2 weeks", () => {
const expected: Record<string, number> = {};
@@ -79,24 +58,6 @@ describe("calendar helpers", () => {
expect(weekdayOf("2026-09-06")).toBe(6);
});
it("weekdayOf keeps the stored Monday=0 .. Sunday=6 numbering (display order is separate)", () => {
// A full known week plus dates across month and year ends.
expect(
[
"2026-09-07",
"2026-09-08",
"2026-09-09",
"2026-09-10",
"2026-09-11",
"2026-09-12",
"2026-09-13",
].map(weekdayOf),
).toEqual([0, 1, 2, 3, 4, 5, 6]);
expect(weekdayOf("2026-11-01")).toBe(6); // Sunday
expect(weekdayOf("2027-01-01")).toBe(4); // Friday
expect(weekdayOf("2024-02-29")).toBe(3); // Thursday
});
it("monthStart shifts across year ends", () => {
expect(monthStart("2026-12-15", 1)).toBe("2027-01-01");
expect(monthStart("2026-01-31", -1)).toBe("2025-12-01");
@@ -110,61 +71,22 @@ describe("dayState", () => {
{ id: 2, child_id: 1, start_date: "2026-09-16", end_date: "2026-09-16", is_present: true, note: null },
];
it("a home-only child: overrides first, then absent on days no home pattern covers", () => {
const patterns = [SCHEDULE];
expect(dayState(patterns, overrides, "2026-09-08")).toBe("home");
expect(dayState(patterns, overrides, "2026-09-11")).toBe("override-away");
expect(dayState(patterns, overrides, "2026-09-15")).toBe("away");
expect(dayState(patterns, overrides, "2026-09-16")).toBe("override-home");
expect(dayState(patterns, overrides, "2026-09-19")).toBe("home");
expect(dayState(patterns, overrides, "2026-09-01")).toBe("away");
expect(dayState(patterns, overrides, "2026-09-05")).toBe("home");
it("applies overrides first, then the anchor-based pattern", () => {
expect(dayState(SCHEDULE, overrides, "2026-09-08")).toBe("home");
expect(dayState(SCHEDULE, overrides, "2026-09-11")).toBe("override-away");
expect(dayState(SCHEDULE, overrides, "2026-09-15")).toBe("away");
expect(dayState(SCHEDULE, overrides, "2026-09-16")).toBe("override-home");
expect(dayState(SCHEDULE, overrides, "2026-09-19")).toBe("home");
expect(dayState(SCHEDULE, overrides, "2026-09-01")).toBe("away");
expect(dayState(SCHEDULE, overrides, "2026-09-05")).toBe("home");
});
it("combines the owner's two away patterns; every other day is home", () => {
const patterns = [THU_FRI, ALTERNATE_WEEKENDS];
const expected: Record<string, string> = {};
for (const date of monthDates("2026-09-01")) {
const weekday = weekdayOf(date);
const onWeek = cycleWeekIndex("2026-09-07", date, 2) === 0;
const away = weekday === 3 || weekday === 4 || (onWeek && weekday >= 5);
expected[date] = away ? "away" : "home";
}
for (const [date, state] of Object.entries(expected)) {
expect(dayState(patterns, [], date), date).toBe(state);
}
// Spot checks: Thu/Fri every week; weekends alternate from the anchor.
expect(dayState(patterns, [], "2026-09-10")).toBe("away"); // Thu, week 0
expect(dayState(patterns, [], "2026-09-18")).toBe("away"); // Fri, week 1
expect(dayState(patterns, [], "2026-09-12")).toBe("away"); // Sat, week 0
expect(dayState(patterns, [], "2026-09-20")).toBe("home"); // Sun, week 1
expect(dayState(patterns, [], "2026-09-27")).toBe("away"); // Sun, week 0
expect(dayState(patterns, [], "2026-09-15")).toBe("home"); // Tue
});
it("away beats home when both cover a date; a home pattern makes uncovered days away", () => {
const patterns = [SCHEDULE, THU_FRI];
expect(dayState(patterns, [], "2026-09-10")).toBe("away"); // home week 0 Thu, but away wins
expect(dayState(patterns, [], "2026-09-08")).toBe("home"); // home covers, away does not
expect(dayState(patterns, [], "2026-09-15")).toBe("away"); // no home pattern covers it
// An override still beats every pattern.
expect(
dayState(patterns, [{ ...overrides[1], start_date: "2026-09-10", end_date: "2026-09-10" }], "2026-09-10"),
).toBe("override-home");
});
it("treats a child with no patterns as home every day", () => {
expect(dayState([], [], "2026-09-15")).toBe("home");
it("treats a child with no schedule as home every day", () => {
expect(dayState(null, [], "2026-09-15")).toBe("home");
});
});
describe("pattern editing and labels", () => {
it("patternIncludes reads the date's cycle week from the anchor", () => {
expect(patternIncludes(ALTERNATE_WEEKENDS, "2026-09-12")).toBe(true);
expect(patternIncludes(ALTERNATE_WEEKENDS, "2026-09-19")).toBe(false);
expect(patternIncludes(ALTERNATE_WEEKENDS, "2026-09-05")).toBe(false); // pre-anchor week 1
});
describe("pattern editing and rule text", () => {
it("toggles one weekday of one cycle week", () => {
expect(togglePatternDay(SCHEDULE.pattern, 1, 1)).toEqual({
0: [0, 1, 2, 3, 4, 5, 6],
@@ -173,19 +95,21 @@ describe("pattern editing and labels", () => {
expect(togglePatternDay(SCHEDULE.pattern, 1, 5)[1]).toEqual([6]);
});
it("resizes the pattern to the cycle length; added weeks cover no day", () => {
it("resizes the pattern to the cycle length", () => {
expect(resizePattern(SCHEDULE.pattern, 1)).toEqual({ 0: [0, 1, 2, 3, 4, 5, 6] });
expect(resizePattern(SCHEDULE.pattern, 3)[2]).toEqual([]);
expect(emptyPattern(2)).toEqual({ 0: [], 1: [] });
expect(resizePattern(SCHEDULE.pattern, 3)[2]).toEqual([0, 1, 2, 3, 4, 5, 6]);
});
it("describes the cycle and the weekday set in plain language", () => {
expect(cycleLabel(1)).toBe("Every week");
expect(cycleLabel(2)).toBe("Every 2 weeks");
expect(patternDaysLabel(THU_FRI)).toBe("Thu, Fri");
expect(patternDaysLabel(ALTERNATE_WEEKENDS)).toBe("Week 1: Sat, Sun · Week 2: No days");
expect(patternDaysLabel(SCHEDULE)).toBe("Week 1: Every day · Week 2: Sat, Sun");
// Listed Monday-first by weekday number, whatever order they were stored in.
expect(patternDaysLabel({ ...THU_FRI, pattern: { "0": [6, 0] } })).toBe("Mon, Sun");
it("describes the presence rule in plain language", () => {
expect(presenceRule(null)).toBe("Every day");
expect(presenceRule({ ...SCHEDULE, pattern: { 0: [0, 1, 2, 3, 4, 5, 6], 1: [0, 1, 2, 3, 4, 5, 6] } })).toBe(
"Every day",
);
expect(presenceRule(SCHEDULE)).toBe("Weeks 1 & 2 of cycle");
expect(
presenceRule({ cycle_length_weeks: 4, anchor_date: "2026-09-07", pattern: { 0: [0], 1: [], 2: [3], 3: [] } }),
).toBe("Weeks 1 & 3 of cycle");
expect(presenceRule({ ...SCHEDULE, pattern: { 0: [1], 1: [] } })).toBe("Week 1 of cycle");
expect(presenceRule({ ...SCHEDULE, pattern: { 0: [], 1: [] } })).toBe("Never home");
});
});
+44 -58
View File
@@ -10,23 +10,12 @@
* Calendar dates are "YYYY-MM-DD" strings handled as whole UTC days, so no
* viewer offset or DST change can shift a day.
*/
import type {
PatternCycle,
PatternKind,
PatternWeeks,
PresenceOverride,
} from "../api/presence";
import type { PresenceOverride, PresencePattern, PresenceScheduleBody } from "../api/presence";
const MS_PER_DAY = 86_400_000;
export const ALL_WEEKDAYS = [0, 1, 2, 3, 4, 5, 6];
/** Monday=0 weekday numbers in Sunday-first display order. */
export const DISPLAY_WEEKDAYS = [6, 0, 1, 2, 3, 4, 5];
/** Short names indexed by Monday=0 weekday number. */
export const WEEKDAY_SHORT = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
/** Days since 1970-01-01 for a "YYYY-MM-DD" calendar date. */
export function dayNumber(iso: string): number {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
@@ -55,6 +44,13 @@ export function cycleWeekIndex(anchorDate: string, date: string, cycleLengthWeek
return mod(Math.floor(days / 7), cycleLengthWeeks);
}
/** The viewer's local calendar date. */
export function localTodayIso(now: Date = new Date()): string {
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
return `${now.getFullYear()}-${month}-${day}`;
}
/** "YYYY-MM-01" of the month containing `iso`, shifted by `delta` months. */
export function monthStart(iso: string, delta = 0): string {
const [year, month] = iso.split("-").map(Number);
@@ -71,50 +67,44 @@ export function monthDates(firstIso: string): string[] {
return dates;
}
/** Every week of the cycle covers no day yet (a new pattern). */
export function emptyPattern(cycleLengthWeeks: number): PatternWeeks {
const pattern: PatternWeeks = {};
for (let week = 0; week < cycleLengthWeeks; week += 1) pattern[week] = [];
/** Present every day for every week of the cycle (the no-schedule case). */
export function fullPattern(cycleLengthWeeks: number): PresencePattern {
const pattern: PresencePattern = {};
for (let week = 0; week < cycleLengthWeeks; week += 1) pattern[week] = [...ALL_WEEKDAYS];
return pattern;
}
export type DayState = "home" | "away" | "override-home" | "override-away";
/** Does the pattern cover `date` (its cycle week lists the date's weekday)? */
export function patternIncludes(cycle: PatternCycle, date: string): boolean {
const week = cycleWeekIndex(cycle.anchor_date, date, cycle.cycle_length_weeks);
return (cycle.pattern[week] ?? []).includes(weekdayOf(date));
export function patternIncludes(
schedule: PresenceScheduleBody,
date: string,
): boolean {
const week = cycleWeekIndex(schedule.anchor_date, date, schedule.cycle_length_weeks);
return (schedule.pattern[week] ?? []).includes(weekdayOf(date));
}
/**
* A date's combined state for one child, mirroring core/presence.py
* `is_present` — first match wins:
* 1. an override covering the date;
* 2. away when any `away` pattern covers it;
* 3. home when any `home` pattern covers it;
* 4. away when the child has at least one `home` pattern (a home pattern
* lists the days the child IS here), else home (no patterns, or only
* `away` ones).
* A date's state for one child: an override covering the date wins;
* otherwise the schedule's pattern decides (no schedule = home every day).
*/
export function dayState(
patterns: (PatternCycle & { kind: PatternKind })[],
schedule: PresenceScheduleBody | null,
overrides: PresenceOverride[],
date: string,
): DayState {
const override = overrides.find((o) => o.start_date <= date && date <= o.end_date);
if (override) return override.is_present ? "override-home" : "override-away";
if (patterns.some((p) => p.kind === "away" && patternIncludes(p, date))) return "away";
const homes = patterns.filter((p) => p.kind === "home");
if (homes.some((p) => patternIncludes(p, date))) return "home";
return homes.length > 0 ? "away" : "home";
if (!schedule) return "home";
return patternIncludes(schedule, date) ? "home" : "away";
}
/** Flip `weekday` in `week` of the pattern; returns a new pattern. */
export function togglePatternDay(
pattern: PatternWeeks,
pattern: PresencePattern,
week: number,
weekday: number,
): PatternWeeks {
): PresencePattern {
const days = pattern[week] ?? [];
const next = days.includes(weekday)
? days.filter((d) => d !== weekday)
@@ -122,35 +112,31 @@ export function togglePatternDay(
return { ...pattern, [week]: next };
}
/** Fit the pattern to a new cycle length; added weeks start covering no day. */
export function resizePattern(pattern: PatternWeeks, cycleLengthWeeks: number): PatternWeeks {
const next: PatternWeeks = {};
/** Fit the pattern to a new cycle length; added weeks start present every day. */
export function resizePattern(pattern: PresencePattern, cycleLengthWeeks: number): PresencePattern {
const next: PresencePattern = {};
for (let week = 0; week < cycleLengthWeeks; week += 1) {
next[week] = pattern[week] ? [...pattern[week]] : [];
next[week] = pattern[week] ? [...pattern[week]] : [...ALL_WEEKDAYS];
}
return next;
}
function daysLabel(days: number[]): string {
if (days.length === 7) return "Every day";
if (days.length === 0) return "No days";
return [...days].sort((a, b) => a - b).map((d) => WEEKDAY_SHORT[d]).join(", ");
function joinWeeks(weeks: number[]): string {
if (weeks.length === 1) return String(weeks[0]);
return `${weeks.slice(0, -1).join(", ")} & ${weeks[weeks.length - 1]}`;
}
/**
* Plain-language weekday set: `Thu, Fri` for a 1-week cycle, otherwise one
* entry per cycle week, e.g. `Week 1: Sat, Sun · Week 2: No days`.
*/
export function patternDaysLabel(cycle: PatternCycle): string {
if (cycle.cycle_length_weeks === 1) return daysLabel(cycle.pattern[0] ?? []);
const weeks: string[] = [];
for (let week = 0; week < cycle.cycle_length_weeks; week += 1) {
weeks.push(`Week ${week + 1}: ${daysLabel(cycle.pattern[week] ?? [])}`);
/** Plain-language rule: `Every day`, `Weeks 1 & 3 of cycle`, `Never home`. */
export function presenceRule(schedule: PresenceScheduleBody | null): string {
if (!schedule) return "Every day";
const weeks: number[] = [];
let full = true;
for (let week = 0; week < schedule.cycle_length_weeks; week += 1) {
const days = schedule.pattern[week] ?? [];
if (days.length > 0) weeks.push(week + 1);
if (days.length < 7) full = false;
}
return weeks.join(" · ");
}
/** `Every week`, `Every 2 weeks`. */
export function cycleLabel(cycleLengthWeeks: number): string {
return cycleLengthWeeks === 1 ? "Every week" : `Every ${cycleLengthWeeks} weeks`;
if (full) return "Every day";
if (weeks.length === 0) return "Never home";
return `${weeks.length === 1 ? "Week" : "Weeks"} ${joinWeeks(weeks)} of cycle`;
}
-9
View File
@@ -67,15 +67,6 @@ export function CalendarCheckGlyph({ size = 18 }: { size?: number }) {
);
}
export function PencilGlyph({ size = 16 }: { size?: number }) {
return (
<Glyph size={size}>
<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z" />
<path d="m15 5 4 4" />
</Glyph>
);
}
export function Trash2Glyph({ size = 16 }: { size?: number }) {
return (
<Glyph size={size}>
-373
View File
@@ -1,373 +0,0 @@
/* Settings — pushed screen over the Today tab (and the tab bar), like the
presence override editor. Compact density list, roomy form card. */
.settings-screen {
position: fixed;
inset: 0;
z-index: 30;
overflow-y: auto;
background: var(--nq-a-page);
}
.settings-header {
display: flex;
align-items: center;
gap: 8px;
padding: 14px 16px;
background: var(--nq-a-surface);
border-bottom: 1px solid var(--nq-a-border);
}
.settings-back {
flex: none;
display: grid;
place-items: center;
width: var(--nq-a-tap-min);
height: var(--nq-a-tap-min);
margin: -6px 0 -6px -12px;
padding: 0;
border: 0;
background: none;
color: var(--nq-a-ink);
cursor: pointer;
}
.settings-title {
margin: 0;
font-size: var(--nq-a-size-screen);
font-weight: 800;
letter-spacing: -0.02em;
}
.settings-sub {
margin: 2px 0 0;
font-size: 12px;
font-weight: 600;
color: var(--nq-a-ink-secondary);
}
/* Scroll column: 14px 16px, bottom 92px (set inline, ADMIN-SPEC §1). */
.settings-scroll {
display: flex;
flex-direction: column;
gap: var(--nq-a-density-gap);
width: 100%;
max-width: 640px;
margin: 0 auto;
padding: 14px 16px;
}
.settings-section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.settings-section-label {
margin: 0;
font-size: var(--nq-a-size-label);
font-weight: 700;
text-transform: uppercase;
letter-spacing: var(--nq-a-track-label);
color: var(--nq-a-ink-secondary);
}
.settings-add {
display: inline-flex;
align-items: center;
gap: 4px;
min-height: 36px;
padding: 0 12px;
border: 0;
border-radius: var(--nq-a-radius-pill);
background: var(--nq-brand-gradient);
color: #fff;
font-family: inherit;
font-size: 12.5px;
font-weight: 700;
cursor: pointer;
}
.settings-card {
background: var(--nq-a-surface);
border: 1px solid var(--nq-a-border);
border-radius: var(--nq-a-density-radius);
}
.settings-list {
margin: 0;
padding: 0;
list-style: none;
}
.settings-list > li + li {
border-top: 1px solid var(--nq-a-divider);
}
.settings-child {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
padding: var(--nq-a-density-row-pad);
}
.settings-child--inactive .settings-child-name {
color: var(--nq-a-ink-tertiary);
}
.settings-swatch {
flex: none;
width: 22px;
height: 22px;
border-radius: var(--nq-a-radius-pill);
border: 1px solid rgba(9, 9, 11, 0.12);
}
.settings-child-text {
flex: 1;
min-width: 0;
}
.settings-child-name {
font-size: var(--nq-a-size-row);
font-weight: 700;
}
.settings-child-meta {
margin-top: 1px;
font-size: var(--nq-a-size-meta);
font-weight: 600;
color: var(--nq-a-ink-tertiary);
}
.settings-pill {
flex: none;
padding: 2px 8px;
border-radius: var(--nq-a-radius-pill);
background: var(--nq-a-divider);
color: var(--nq-a-ink-secondary);
font-size: var(--nq-a-size-meta);
font-weight: 700;
}
.settings-pill--active {
background: #dcfce7;
color: var(--nq-a-success);
}
.settings-child-actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 6px;
width: 100%;
}
.settings-icon-button,
.settings-action {
min-height: 36px;
border: 1px solid var(--nq-a-border);
border-radius: var(--nq-a-density-radius);
background: var(--nq-a-surface);
color: var(--nq-a-ink);
font-family: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
.settings-icon-button {
display: grid;
place-items: center;
width: 36px;
padding: 0;
}
.settings-action {
padding: 0 12px;
}
.settings-icon-button:disabled,
.settings-action:disabled,
.settings-add:disabled,
.settings-back:disabled,
.settings-cancel:disabled,
.settings-save:disabled {
opacity: 0.45;
cursor: default;
}
.settings-empty,
.settings-status {
padding: 16px;
font-size: 13px;
font-weight: 600;
color: var(--nq-a-ink-secondary);
text-align: center;
}
.settings-status--error {
color: var(--nq-a-danger-strong);
}
.settings-status p {
margin: 0 0 10px;
}
.settings-action-error {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 10px 12px;
border-radius: var(--nq-a-density-radius);
background: var(--nq-a-danger-bg);
color: var(--nq-a-danger-strong);
font-size: 12.5px;
font-weight: 700;
}
/* Add / edit form: roomy density, 18px padding, 16px gaps. */
.settings-form {
display: flex;
flex-direction: column;
gap: 16px;
padding: 18px;
}
.settings-form-title {
margin: 0;
font-size: 17px;
font-weight: 800;
}
.settings-field {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.settings-label {
font-size: var(--nq-a-size-label);
font-weight: 700;
text-transform: uppercase;
letter-spacing: var(--nq-a-track-label);
color: var(--nq-a-ink-secondary);
}
.settings-hint {
margin: 0;
font-size: 12.5px;
color: var(--nq-a-ink-secondary);
}
.settings-input {
width: 100%;
min-height: var(--nq-a-tap-min);
padding: 13px;
border: 1px solid var(--nq-a-border);
border-radius: 10px;
background: var(--nq-a-surface);
color: var(--nq-a-ink);
font-family: inherit;
font-size: 14px;
font-weight: 600;
}
.settings-swatches {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.settings-swatch-option {
width: 32px;
height: 32px;
padding: 0;
border: 2px solid transparent;
border-radius: var(--nq-a-radius-pill);
cursor: pointer;
}
.settings-swatch-option[aria-pressed="true"] {
border-color: var(--nq-a-ink);
box-shadow: inset 0 0 0 2px var(--nq-a-surface);
}
.settings-error {
margin: 0;
padding: 10px 12px;
border-radius: var(--nq-a-density-radius);
background: var(--nq-a-danger-bg);
color: var(--nq-a-danger-strong);
font-size: 12.5px;
font-weight: 700;
}
.settings-form-footer {
display: flex;
gap: 10px;
}
.settings-cancel,
.settings-save {
padding: 15px 12px;
border-radius: 12px;
font-family: inherit;
font-size: 14px;
font-weight: 700;
cursor: pointer;
}
.settings-cancel {
flex: 1;
border: 1px solid var(--nq-a-border);
background: var(--nq-a-surface);
color: var(--nq-a-ink);
}
.settings-save {
flex: 2;
border: 0;
background: var(--nq-brand-gradient);
color: #fff;
}
/* Preferences: one box per notification — its toggle, then its time. */
.settings-notification {
display: flex;
flex-direction: column;
gap: 10px;
padding: 12px;
border: 1px solid var(--nq-a-divider);
border-radius: var(--nq-a-density-radius);
}
.settings-toggle {
display: flex;
align-items: center;
gap: 10px;
min-height: var(--nq-a-tap-min);
font-size: 14px;
font-weight: 600;
cursor: pointer;
}
.settings-toggle > input {
width: 20px;
height: 20px;
margin: 0;
}
.settings-notice {
margin: 0;
padding: 10px 12px;
border-radius: var(--nq-a-density-radius);
background: var(--nq-a-divider);
color: var(--nq-a-ink-secondary);
font-size: 12.5px;
font-weight: 700;
}
-843
View File
@@ -1,843 +0,0 @@
import { StrictMode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import App from "../App";
import SettingsScreen, { SCROLL_BOTTOM_PADDING } from "./SettingsScreen";
import type { AdminChild } from "../api/definitions";
import type { HouseholdSettings } from "../api/settings";
import { storeTokens } from "../auth/oidc";
import { AppTimezoneProvider, useAppTimezone } from "../time/AppTimezone";
const CHILDREN_PATH = "/api/v1/admin/children";
const REORDER_PATH = `${CHILDREN_PATH}/reorder`;
const SETTINGS_PATH = "/api/v1/admin/settings";
const DEFAULT_SETTINGS: HouseholdSettings = {
horizon_days: 14,
day_rollover_time: "03:00",
notify_target: "notify.family",
morning_summary_time: "07:00",
afternoon_reminder_time: "15:30",
end_of_day_report_time: "20:00",
morning_summary_enabled: true,
afternoon_reminder_enabled: false,
end_of_day_report_enabled: true,
celebration_enabled: false,
timezone: "America/Chicago",
effective_timezone: "America/Chicago",
};
/** The API host's own zone: the effective zone while none is stored. */
const API_HOST_ZONE = "Europe/London";
/** The settings as the API answers: `effective_timezone` derived like the API's. */
function settingsBody(): HouseholdSettings {
return { ...settings, effective_timezone: settings.timezone || API_HOST_ZONE };
}
function child(
id: number,
display_name: string,
sort_order: number,
extra: Partial<AdminChild> = {},
): AdminChild {
return { id, display_name, colour: null, avatar_ref: null, sort_order, is_active: true, ...extra };
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
}
interface Call {
method: string;
path: string;
body: unknown;
}
let children: AdminChild[];
let settings: HouseholdSettings;
/** Overrides the next write's response (the store is left untouched). */
let writeResponse: (() => Response) | null;
let fetchMock: ReturnType<typeof vi.fn>;
function calls(): Call[] {
return fetchMock.mock.calls.map((args: unknown[]) => {
const [url, init] = args as [string, RequestInit | undefined];
return {
method: init?.method ?? "GET",
path: new URL(String(url), "http://x").pathname,
body: init?.body ? JSON.parse(String(init.body)) : undefined,
};
});
}
function writes(): Call[] {
return calls().filter((c) => c.method !== "GET");
}
function childGets(): number {
return calls().filter((c) => c.method === "GET" && c.path === CHILDREN_PATH).length;
}
async function routeFetch(url: string, init: RequestInit = {}): Promise<Response> {
const path = new URL(url, "http://x").pathname;
const method = init.method ?? "GET";
const body = init.body ? JSON.parse(String(init.body)) : undefined;
if (method !== "GET" && writeResponse) {
const respond = writeResponse;
writeResponse = null;
return respond();
}
if (path === CHILDREN_PATH && method === "GET") return jsonResponse({ children });
if (path === SETTINGS_PATH && method === "GET") return jsonResponse(settingsBody());
if (path === SETTINGS_PATH && method === "PATCH") {
settings = { ...settings, ...body };
return jsonResponse(settingsBody());
}
if (path === CHILDREN_PATH && method === "POST") {
const created = child(9, body.display_name, body.sort_order ?? 0, {
colour: body.colour ?? null,
avatar_ref: body.avatar_ref ?? null,
});
children = [...children, created];
return jsonResponse(created, 201);
}
if (path === REORDER_PATH && method === "POST") {
const ids = body.ordered_ids as number[];
children = children.map((c) => ({ ...c, sort_order: ids.indexOf(c.id) + 1 }));
return jsonResponse({ status: "ok" });
}
const activeMatch = /\/children\/(\d+)\/active$/.exec(path);
if (activeMatch && method === "PATCH") {
const id = Number(activeMatch[1]);
children = children.map((c) => (c.id === id ? { ...c, is_active: body.is_active } : c));
return jsonResponse(children.find((c) => c.id === id));
}
const editMatch = /\/children\/(\d+)$/.exec(path);
if (editMatch && method === "PATCH") {
const id = Number(editMatch[1]);
children = children.map((c) => (c.id === id ? { ...c, ...body } : c));
return jsonResponse(children.find((c) => c.id === id));
}
if (path.endsWith("/admin/snapshot")) {
return jsonResponse({ today_iso: "2026-09-23", cycle_day: 5, children: [] });
}
return jsonResponse({ detail: "unexpected" }, 500);
}
function row(id: number) {
return within(screen.getByTestId(`settings-child-${id}`));
}
function listNames(): string[] {
return within(screen.getByRole("list", { name: "Children" }))
.getAllByRole("listitem")
.map((li) => li.querySelector(".settings-child-name")?.textContent ?? "");
}
function field(form: HTMLElement, label: string): HTMLInputElement {
return within(form).getByLabelText(label) as HTMLInputElement;
}
async function renderScreen(onClose = vi.fn()) {
render(<SettingsScreen onClose={onClose} />);
await screen.findByTestId("settings-child-1");
return onClose;
}
describe("SettingsScreen — children", () => {
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
children = [
child(2, "Maeve", 2, { colour: "#16a34a" }),
child(1, "Declan", 1, { colour: "#0ea5e9", avatar_ref: "fox" }),
child(3, "Rory", 3, { is_active: false }),
];
settings = { ...DEFAULT_SETTINGS };
writeResponse = null;
fetchMock = vi.fn(async (url: string, init?: RequestInit) => routeFetch(url, init));
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
it("lists each child with name, colour swatch, active state and order", async () => {
await renderScreen();
expect(listNames()).toEqual(["Declan", "Maeve", "Rory"]);
expect(row(1).getByText("Order 1 · #0ea5e9")).toBeTruthy();
expect(screen.getByTestId("settings-swatch-1").style.background).toBe("rgb(14, 165, 233)");
expect(screen.getByTestId("settings-active-1").textContent).toBe("Active");
expect(row(3).getByText("Order 3 · no colour")).toBeTruthy();
expect(screen.getByTestId("settings-swatch-3").style.background).toBe("var(--nq-a-border)");
expect(screen.getByTestId("settings-active-3").textContent).toBe("Inactive");
expect(screen.getByTestId("settings-scroll").style.paddingBottom).toBe(SCROLL_BOTTOM_PADDING);
});
it("Add posts exactly the entered values, then shows the new child", async () => {
await renderScreen();
fireEvent.click(screen.getByRole("button", { name: "Add child" }));
const form = screen.getByRole("form", { name: "Add child" });
expect(field(form, "Order").value).toBe("4");
fireEvent.change(field(form, "Display name"), { target: { value: " Nora " } });
fireEvent.click(within(form).getByRole("button", { name: "Colour #7c3aed" }));
fireEvent.change(field(form, "Avatar ref (optional)"), { target: { value: "owl" } });
fireEvent.change(field(form, "Order"), { target: { value: "5" } });
const gets = childGets();
fireEvent.click(within(form).getByRole("button", { name: "Add child" }));
await screen.findByTestId("settings-child-9");
expect(writes()).toEqual([
{
method: "POST",
path: CHILDREN_PATH,
body: { display_name: "Nora", colour: "#7c3aed", avatar_ref: "owl", sort_order: 5 },
},
]);
expect(childGets()).toBe(gets + 1);
expect(listNames()).toEqual(["Declan", "Maeve", "Rory", "Nora"]);
expect(screen.queryByRole("form", { name: "Add child" })).toBeNull();
});
it("Add omits optional fields left blank and rejects a missing name", async () => {
await renderScreen();
fireEvent.click(screen.getByRole("button", { name: "Add child" }));
const form = screen.getByRole("form", { name: "Add child" });
fireEvent.change(field(form, "Order"), { target: { value: "" } });
fireEvent.click(within(form).getByRole("button", { name: "Add child" }));
expect(screen.getByTestId("child-form-error").textContent).toBe("Enter a display name.");
expect(writes()).toEqual([]);
fireEvent.change(field(form, "Display name"), { target: { value: "Nora" } });
fireEvent.click(within(form).getByRole("button", { name: "Add child" }));
await screen.findByTestId("settings-child-9");
expect(writes()[0].body).toEqual({ display_name: "Nora" });
});
it("Edit patches only the changed fields", async () => {
await renderScreen();
fireEvent.click(row(1).getByRole("button", { name: "Edit Declan" }));
const form = screen.getByRole("form", { name: "Edit Declan" });
expect(field(form, "Display name").value).toBe("Declan");
expect(field(form, "Colour").value).toBe("#0ea5e9");
fireEvent.change(field(form, "Display name"), { target: { value: "Dec" } });
fireEvent.change(field(form, "Colour"), { target: { value: "#FF8800" } });
fireEvent.click(within(form).getByRole("button", { name: "Save child" }));
await waitFor(() => expect(row(1).getByText("Dec")).toBeTruthy());
expect(writes()).toEqual([
{ method: "PATCH", path: `${CHILDREN_PATH}/1`, body: { display_name: "Dec", colour: "#FF8800" } },
]);
expect(row(1).getByText("Order 1 · #FF8800")).toBeTruthy();
});
it("Edit refuses to clear a set colour instead of sending null", async () => {
await renderScreen();
fireEvent.click(row(1).getByRole("button", { name: "Edit Declan" }));
const form = screen.getByRole("form", { name: "Edit Declan" });
fireEvent.change(field(form, "Colour"), { target: { value: "" } });
fireEvent.click(within(form).getByRole("button", { name: "Save child" }));
expect(screen.getByTestId("child-form-error").textContent).toMatch(/cannot be removed/);
expect(writes()).toEqual([]);
});
it("the active toggle patches /children/{id}/active with the new value", async () => {
await renderScreen();
fireEvent.click(row(1).getByRole("button", { name: "Deactivate Declan" }));
await waitFor(() => expect(screen.getByTestId("settings-active-1").textContent).toBe("Inactive"));
fireEvent.click(row(3).getByRole("button", { name: "Reactivate Rory" }));
await waitFor(() => expect(screen.getByTestId("settings-active-3").textContent).toBe("Active"));
expect(writes()).toEqual([
{ method: "PATCH", path: `${CHILDREN_PATH}/1/active`, body: { is_active: false } },
{ method: "PATCH", path: `${CHILDREN_PATH}/3/active`, body: { is_active: true } },
]);
});
it("reorder posts the complete ordered id list, then shows the new order", async () => {
await renderScreen();
expect((row(1).getByRole("button", { name: "Move Declan up" }) as HTMLButtonElement).disabled).toBe(true);
expect((row(3).getByRole("button", { name: "Move Rory down" }) as HTMLButtonElement).disabled).toBe(true);
fireEvent.click(row(3).getByRole("button", { name: "Move Rory up" }));
await waitFor(() => expect(listNames()).toEqual(["Declan", "Rory", "Maeve"]));
expect(writes()).toEqual([{ method: "POST", path: REORDER_PATH, body: { ordered_ids: [1, 3, 2] } }]);
});
it("disables the write controls while a request is in flight (no double submit)", async () => {
await renderScreen();
let release!: () => void;
writeResponse = () => jsonResponse({ status: "ok" });
const gate = new Promise<void>((r) => {
release = r;
});
fetchMock.mockImplementationOnce(async (url: string, init?: RequestInit) => {
await gate;
return routeFetch(url, init);
});
const up = row(2).getByRole("button", { name: "Move Maeve up" }) as HTMLButtonElement;
fireEvent.click(up);
fireEvent.click(up);
await waitFor(() => expect(up.disabled).toBe(true));
expect((row(1).getByRole("button", { name: "Deactivate Declan" }) as HTMLButtonElement).disabled).toBe(true);
expect(writes()).toHaveLength(1);
release();
await waitFor(() => expect((row(1).getByRole("button", { name: "Edit Declan" }) as HTMLButtonElement).disabled).toBe(false));
expect(writes()).toHaveLength(1);
});
it("a 422 shows the API detail and keeps the form and the screen open", async () => {
const onClose = await renderScreen();
fireEvent.click(screen.getByRole("button", { name: "Add child" }));
const form = screen.getByRole("form", { name: "Add child" });
fireEvent.change(field(form, "Display name"), { target: { value: "Nora" } });
writeResponse = () => jsonResponse({ detail: "display_name is required" }, 422);
fireEvent.click(within(form).getByRole("button", { name: "Add child" }));
const error = await screen.findByTestId("child-form-error");
expect(error.textContent).toBe("The child could not be added: display_name is required");
expect(screen.getByRole("form", { name: "Add child" })).toBeTruthy();
expect(field(form, "Display name").value).toBe("Nora");
expect(onClose).not.toHaveBeenCalled();
expect(screen.getByRole("dialog", { name: "Settings" })).toBeTruthy();
});
it("a 403 on a row action shows the refusal message and keeps the screen open", async () => {
const onClose = await renderScreen();
writeResponse = () => jsonResponse({ detail: "forbidden" }, 403);
fireEvent.click(row(1).getByRole("button", { name: "Deactivate Declan" }));
const error = await screen.findByTestId("settings-action-error");
expect(error.textContent).toContain("Your account is not in the nestquest-admins group.");
expect(screen.getByTestId("settings-active-1").textContent).toBe("Active");
expect(onClose).not.toHaveBeenCalled();
});
it("a 403 on load shows the refusal message", async () => {
fetchMock.mockImplementation(async () => jsonResponse({ detail: "forbidden" }, 403));
render(<SettingsScreen onClose={vi.fn()} />);
const error = await screen.findByTestId("settings-error");
expect(error.textContent).toContain("Your account is not in the nestquest-admins group.");
});
it("Escape and Back close the screen", async () => {
const onClose = await renderScreen();
fireEvent.keyDown(screen.getByRole("dialog", { name: "Settings" }), { key: "Escape" });
expect(onClose).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole("button", { name: "Back" }));
expect(onClose).toHaveBeenCalledTimes(2);
});
it("the Today Settings button opens the screen; closing restores focus and the background", async () => {
render(<App />);
const settings = await screen.findByRole("button", { name: "Settings" });
settings.focus();
fireEvent.click(settings);
const dialog = await screen.findByRole("dialog", { name: "Settings" });
await screen.findByTestId("settings-child-1");
expect(document.activeElement).toBe(screen.getByRole("heading", { name: "Settings" }));
const tabbar = document.querySelector("nav.admin-tabbar") as HTMLElement;
expect(tabbar.hasAttribute("inert")).toBe(true);
expect(dialog.closest("[inert]")).toBeNull();
fireEvent.keyDown(dialog, { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Settings" })).toBeNull());
expect(tabbar.hasAttribute("inert")).toBe(false);
expect(document.activeElement).toBe(screen.getByRole("button", { name: "Settings" }));
});
});
describe("SettingsScreen — preferences", () => {
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
children = [child(1, "Declan", 1)];
settings = { ...DEFAULT_SETTINGS };
writeResponse = null;
fetchMock = vi.fn(async (url: string, init?: RequestInit) => routeFetch(url, init));
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
async function renderPreferences(onClose = vi.fn()) {
render(<SettingsScreen onClose={onClose} />);
await screen.findByTestId("settings-child-1");
const form = await screen.findByRole("form", { name: "Preferences" });
return { form, onClose };
}
function checkbox(form: HTMLElement, label: string): HTMLInputElement {
return within(form).getByRole("checkbox", { name: label }) as HTMLInputElement;
}
function save(form: HTMLElement) {
fireEvent.click(within(form).getByRole("button", { name: "Save preferences" }));
}
it("renders the current value of all eleven settings form fields", async () => {
const { form } = await renderPreferences();
expect(field(form, "Planning horizon (days)").value).toBe("14");
expect(field(form, "Day rollover").value).toBe("03:00");
expect(field(form, "Timezone").value).toBe("America/Chicago");
expect(field(form, "Notify target").value).toBe("notify.family");
expect(field(form, "Morning summary time").value).toBe("07:00");
expect(field(form, "Afternoon reminder time").value).toBe("15:30");
expect(field(form, "End-of-day report time").value).toBe("20:00");
expect(checkbox(form, "Morning summary").checked).toBe(true);
expect(checkbox(form, "Afternoon reminder").checked).toBe(false);
expect(checkbox(form, "End-of-day report").checked).toBe(true);
expect(checkbox(form, "Celebration").checked).toBe(false);
});
it("saving one changed field patches exactly that field", async () => {
const { form } = await renderPreferences();
fireEvent.change(field(form, "Planning horizon (days)"), { target: { value: "21" } });
save(form);
await screen.findByText("Preferences saved.");
expect(writes()).toEqual([{ method: "PATCH", path: SETTINGS_PATH, body: { horizon_days: 21 } }]);
const reloaded = screen.getByRole("form", { name: "Preferences" });
expect(field(reloaded, "Planning horizon (days)").value).toBe("21");
});
it("saving several changed fields sends exactly those", async () => {
const { form } = await renderPreferences();
fireEvent.change(field(form, "Day rollover"), { target: { value: "04:15" } });
fireEvent.change(field(form, "Notify target"), { target: { value: " notify.parents " } });
fireEvent.change(field(form, "End-of-day report time"), { target: { value: "21:45" } });
fireEvent.click(checkbox(form, "Afternoon reminder"));
fireEvent.click(checkbox(form, "Celebration"));
save(form);
await screen.findByText("Preferences saved.");
expect(writes()).toEqual([
{
method: "PATCH",
path: SETTINGS_PATH,
body: {
day_rollover_time: "04:15",
notify_target: "notify.parents",
end_of_day_report_time: "21:45",
afternoon_reminder_enabled: true,
celebration_enabled: true,
},
},
]);
const reloaded = screen.getByRole("form", { name: "Preferences" });
expect(checkbox(reloaded, "Celebration").checked).toBe(true);
expect(field(reloaded, "Notify target").value).toBe("notify.parents");
});
it("with nothing changed it says so and sends no request", async () => {
const { form } = await renderPreferences();
fireEvent.click(checkbox(form, "Celebration"));
fireEvent.click(checkbox(form, "Celebration"));
save(form);
expect(screen.getByTestId("preferences-message").textContent).toBe("No changes to save.");
expect(writes()).toEqual([]);
});
it("a 422 shows the API detail naming the field and keeps the edit", async () => {
const { form, onClose } = await renderPreferences();
fireEvent.change(field(form, "Notify target"), { target: { value: "notify.nobody" } });
writeResponse = () => jsonResponse({ detail: "notify_target is not a notify service" }, 422);
save(form);
const message = await screen.findByTestId("preferences-message");
expect(message.textContent).toBe(
"The preferences could not be saved: notify_target is not a notify service",
);
expect(message.getAttribute("role")).toBe("alert");
expect(field(form, "Notify target").value).toBe("notify.nobody");
expect(writes()).toEqual([
{ method: "PATCH", path: SETTINGS_PATH, body: { notify_target: "notify.nobody" } },
]);
expect(onClose).not.toHaveBeenCalled();
});
it("a 403 on save shows the refusal message", async () => {
const { form } = await renderPreferences();
fireEvent.click(checkbox(form, "Celebration"));
writeResponse = () => jsonResponse({ detail: "forbidden" }, 403);
save(form);
const message = await screen.findByTestId("preferences-message");
expect(message.textContent).toContain("Your account is not in the nestquest-admins group.");
expect(checkbox(form, "Celebration").checked).toBe(true);
});
it.each([
["empty", ""],
["zero", "0"],
["oversized (Infinity would serialize as null and reset the field)", "9".repeat(400)],
["past the safe-integer range", "123456789012345678901"],
])("a %s horizon is rejected before any request", async (_case, value) => {
const { form } = await renderPreferences();
fireEvent.change(field(form, "Planning horizon (days)"), { target: { value } });
save(form);
expect(screen.getByTestId("preferences-message").textContent).toBe(
"Planning horizon must be a whole number of days, at least 1.",
);
expect(writes()).toEqual([]);
});
it("disables every write control while a save is in flight (no double submit)", async () => {
const { form } = await renderPreferences();
let release!: () => void;
const gate = new Promise<void>((r) => {
release = r;
});
fetchMock.mockImplementationOnce(async (url: string, init?: RequestInit) => {
await gate;
return routeFetch(url, init);
});
fireEvent.click(checkbox(form, "Celebration"));
const button = within(form).getByRole("button", { name: "Save preferences" }) as HTMLButtonElement;
fireEvent.click(button);
fireEvent.click(button);
await waitFor(() => expect(button.disabled).toBe(true));
expect(checkbox(form, "Celebration").disabled).toBe(true);
expect(field(form, "Planning horizon (days)").disabled).toBe(true);
expect((row(1).getByRole("button", { name: "Edit Declan" }) as HTMLButtonElement).disabled).toBe(true);
expect(writes()).toHaveLength(1);
release();
await screen.findByText("Preferences saved.");
expect(writes()).toHaveLength(1);
});
it("a timezone picked from the list patches exactly the timezone", async () => {
const { form } = await renderPreferences();
fireEvent.change(field(form, "Timezone"), { target: { value: "America/New_York" } });
save(form);
await screen.findByText("Preferences saved.");
expect(writes()).toEqual([
{ method: "PATCH", path: SETTINGS_PATH, body: { timezone: "America/New_York" } },
]);
const reloaded = screen.getByRole("form", { name: "Preferences" });
expect(field(reloaded, "Timezone").value).toBe("America/New_York");
});
it.each(["New York", "America/New York", "EST5EDT?", "/Chicago"])(
"an invalid other timezone %j is rejected before any request",
async (value) => {
const { form } = await renderPreferences();
fireEvent.change(field(form, "Timezone"), { target: { value: "__other__" } });
fireEvent.change(field(form, "Other timezone"), { target: { value } });
save(form);
expect(screen.getByTestId("preferences-message").textContent).toBe(
"Timezone must be an IANA zone like America/New_York, or UTC.",
);
expect(field(form, "Other timezone").value).toBe(value);
expect(writes()).toEqual([]);
},
);
it("a 422 on an unknown timezone shows the API detail and keeps the edit", async () => {
const { form } = await renderPreferences();
fireEvent.change(field(form, "Timezone"), { target: { value: "__other__" } });
fireEvent.change(field(form, "Other timezone"), { target: { value: "Mars/Olympus_Mons" } });
writeResponse = () =>
jsonResponse({ detail: "timezone must be an IANA time zone name such as 'America/New_York'" }, 422);
save(form);
const message = await screen.findByTestId("preferences-message");
expect(message.textContent).toBe(
"The preferences could not be saved: timezone must be an IANA time zone name such as 'America/New_York'",
);
expect(field(form, "Other timezone").value).toBe("Mars/Olympus_Mons");
expect(field(form, "Other timezone").disabled).toBe(false);
expect(settings.timezone).toBe("America/Chicago");
});
it("a failed load shows the reason and Try again refetches", async () => {
let fail = true;
fetchMock.mockImplementation(async (url: string, init?: RequestInit) => {
if (fail && new URL(url, "http://x").pathname === SETTINGS_PATH) {
return jsonResponse({ detail: "boom" }, 500);
}
return routeFetch(url, init);
});
render(<SettingsScreen onClose={vi.fn()} />);
const error = await screen.findByTestId("preferences-error");
expect(error.textContent).toContain("Preferences could not be loaded: boom");
fail = false;
fireEvent.click(within(error).getByRole("button", { name: "Try again" }));
await screen.findByRole("form", { name: "Preferences" });
});
});
describe("SettingsScreen — no timezone auto-set", () => {
let zoneSpy: ReturnType<typeof vi.spyOn> | null;
function mockBrowserZone(timeZone: string | undefined) {
const real = Intl.DateTimeFormat.prototype.resolvedOptions;
zoneSpy = vi
.spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions")
.mockImplementation(function (this: Intl.DateTimeFormat) {
return { ...real.call(this), timeZone } as Intl.ResolvedDateTimeFormatOptions;
});
}
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
children = [child(1, "Declan", 1)];
// A fresh install: no zone stored.
settings = { ...DEFAULT_SETTINGS, timezone: "" };
writeResponse = null;
zoneSpy = null;
fetchMock = vi.fn(async (url: string, init?: RequestInit) => routeFetch(url, init));
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
cleanup();
zoneSpy?.mockRestore();
vi.unstubAllGlobals();
});
async function renderForm() {
render(<SettingsScreen onClose={vi.fn()} />);
await screen.findByTestId("settings-child-1");
return screen.findByRole("form", { name: "Preferences" });
}
it("an empty timezone stays empty on load and nothing is written", async () => {
mockBrowserZone("America/New_York");
const form = await renderForm();
expect(field(form, "Timezone").value).toBe("");
expect(writes()).toEqual([]);
expect(settings.timezone).toBe("");
});
it("StrictMode's doubled effects write nothing either", async () => {
mockBrowserZone("America/New_York");
render(
<StrictMode>
<SettingsScreen onClose={vi.fn()} />
</StrictMode>,
);
const form = await screen.findByRole("form", { name: "Preferences" });
expect(field(form, "Timezone").value).toBe("");
expect(writes()).toEqual([]);
});
it("a stored timezone is shown as stored, never replaced by the browser zone", async () => {
mockBrowserZone("America/New_York");
settings = { ...DEFAULT_SETTINGS, timezone: "Europe/Dublin" };
const form = await renderForm();
expect(field(form, "Timezone").value).toBe("Europe/Dublin");
expect(writes()).toEqual([]);
});
it("saving another field sends only that field, never a timezone", async () => {
mockBrowserZone("America/New_York");
const form = await renderForm();
fireEvent.change(field(form, "Planning horizon (days)"), { target: { value: "21" } });
fireEvent.click(within(form).getByRole("button", { name: "Save preferences" }));
await screen.findByText("Preferences saved.");
expect(writes().map((w) => w.body)).toEqual([{ horizon_days: 21 }]);
expect(settings.timezone).toBe("");
});
it("an admin clearing the timezone saves exactly the empty zone", async () => {
mockBrowserZone("America/New_York");
settings = { ...DEFAULT_SETTINGS, timezone: "Europe/Dublin" };
const form = await renderForm();
fireEvent.change(field(form, "Timezone"), { target: { value: "" } });
fireEvent.click(within(form).getByRole("button", { name: "Save preferences" }));
await screen.findByText("Preferences saved.");
expect(writes().map((w) => w.body)).toEqual([{ timezone: "" }]);
expect(field(screen.getByRole("form", { name: "Preferences" }), "Timezone").value).toBe("");
});
});
describe("SettingsScreen — manual timezone control", () => {
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
children = [child(1, "Declan", 1)];
settings = { ...DEFAULT_SETTINGS, timezone: "" };
writeResponse = null;
fetchMock = vi.fn(async (url: string, init?: RequestInit) => routeFetch(url, init));
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
async function renderForm() {
render(<SettingsScreen onClose={vi.fn()} />);
await screen.findByTestId("settings-child-1");
return screen.findByRole("form", { name: "Preferences" });
}
function save(form: HTMLElement) {
fireEvent.click(within(form).getByRole("button", { name: "Save preferences" }));
}
/** The Timezone control, which must be a real select, not a free-text box. */
function picker(form: HTMLElement): HTMLSelectElement {
const control = within(form).getByRole("combobox", { name: "Timezone" });
expect(control).toBeInstanceOf(HTMLSelectElement);
return control as HTMLSelectElement;
}
it("is a picker of curated zones with host-local and other-zone choices", async () => {
const form = await renderForm();
const select = picker(form);
const values = Array.from(select.options).map((o) => o.value);
expect(values[0]).toBe("");
expect(select.options[0].textContent).toBe("API host local time (no zone set)");
for (const zone of [
"UTC",
"America/New_York",
"America/Chicago",
"America/Denver",
"America/Phoenix",
"America/Los_Angeles",
"America/Anchorage",
"Pacific/Honolulu",
]) {
expect(values).toContain(zone);
}
expect(select.options[select.options.length - 1].textContent).toBe("Other IANA zone…");
expect(select.value).toBe("");
expect(within(form).queryByLabelText("Other timezone")).toBeNull();
});
it("explains that it is the application timezone for every surface", async () => {
const form = await renderForm();
const help = document.getElementById(picker(form).getAttribute("aria-describedby") ?? "");
expect(help?.textContent).toMatch(/application timezone/);
expect(help?.textContent).toMatch(/panel, the scheduler and this admin app/);
expect(help?.textContent).toMatch(/API host's local time/);
});
it("a picked zone saves via PATCH and is shown after a reload", async () => {
const form = await renderForm();
expect(writes()).toEqual([]);
fireEvent.change(picker(form), { target: { value: "America/New_York" } });
save(form);
await screen.findByText("Preferences saved.");
expect(writes()).toEqual([
{ method: "PATCH", path: SETTINGS_PATH, body: { timezone: "America/New_York" } },
]);
cleanup();
const reloaded = await renderForm();
expect(picker(reloaded).value).toBe("America/New_York");
expect(writes()).toHaveLength(1);
});
it("an other zone typed by hand saves via PATCH and is shown after a reload", async () => {
const form = await renderForm();
fireEvent.change(picker(form), { target: { value: "__other__" } });
const entry = within(form).getByLabelText("Other timezone") as HTMLInputElement;
expect(entry.value).toBe("");
fireEvent.change(entry, { target: { value: " America/Boise " } });
save(form);
await screen.findByText("Preferences saved.");
expect(writes()).toEqual([
{ method: "PATCH", path: SETTINGS_PATH, body: { timezone: "America/Boise" } },
]);
cleanup();
const reloaded = await renderForm();
expect(picker(reloaded).value).toBe("__other__");
expect((within(reloaded).getByLabelText("Other timezone") as HTMLInputElement).value).toBe(
"America/Boise",
);
});
it("a saved zone outside the list is shown in the other-zone entry on load", async () => {
settings = { ...DEFAULT_SETTINGS, timezone: "Asia/Kathmandu" };
const form = await renderForm();
expect(picker(form).value).toBe("__other__");
expect((within(form).getByLabelText("Other timezone") as HTMLInputElement).value).toBe(
"Asia/Kathmandu",
);
expect(writes()).toEqual([]);
});
it("choosing API host local time clears the zone and persists after a reload", async () => {
settings = { ...DEFAULT_SETTINGS, timezone: "America/Denver" };
const form = await renderForm();
expect(picker(form).value).toBe("America/Denver");
fireEvent.change(picker(form), { target: { value: "" } });
save(form);
await screen.findByText("Preferences saved.");
expect(writes().map((w) => w.body)).toEqual([{ timezone: "" }]);
cleanup();
const reloaded = await renderForm();
expect(picker(reloaded).value).toBe("");
});
it("picking a zone and then the saved one again sends nothing", async () => {
settings = { ...DEFAULT_SETTINGS, timezone: "UTC" };
const form = await renderForm();
fireEvent.change(picker(form), { target: { value: "Europe/Paris" } });
fireEvent.change(picker(form), { target: { value: "UTC" } });
save(form);
expect(screen.getByTestId("preferences-message").textContent).toBe("No changes to save.");
expect(writes()).toEqual([]);
});
it("never sends a timezone_configured field", async () => {
const form = await renderForm();
fireEvent.change(picker(form), { target: { value: "America/Los_Angeles" } });
save(form);
await screen.findByText("Preferences saved.");
const again = screen.getByRole("form", { name: "Preferences" });
fireEvent.change(picker(again), { target: { value: "" } });
save(again);
await waitFor(() => expect(writes()).toHaveLength(2));
for (const write of writes()) {
expect(Object.keys(write.body as object)).toEqual(["timezone"]);
expect(write.body).not.toHaveProperty("timezone_configured");
}
});
});
describe("SettingsScreen — the saved zone applies app-wide", () => {
function ZoneProbe() {
return <output data-testid="app-zone">{useAppTimezone() || "(browser)"}</output>;
}
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
children = [child(1, "Declan", 1)];
settings = { ...DEFAULT_SETTINGS, timezone: "" };
writeResponse = null;
fetchMock = vi.fn(async (url: string, init?: RequestInit) => routeFetch(url, init));
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
it("a saved zone becomes the application timezone at once", async () => {
render(
<AppTimezoneProvider>
<ZoneProbe />
<SettingsScreen onClose={vi.fn()} />
</AppTimezoneProvider>,
);
const form = await screen.findByRole("form", { name: "Preferences" });
// No zone stored: the application runs in the API host's zone.
expect(screen.getByTestId("app-zone").textContent).toBe(API_HOST_ZONE);
fireEvent.change(within(form).getByRole("combobox", { name: "Timezone" }), {
target: { value: "America/New_York" },
});
fireEvent.click(within(form).getByRole("button", { name: "Save preferences" }));
await screen.findByText("Preferences saved.");
expect(screen.getByTestId("app-zone").textContent).toBe("America/New_York");
});
});
-911
View File
@@ -1,911 +0,0 @@
/**
* Settings — a pushed screen opened from the Today header's Settings button.
*
* Children: list, add, edit, deactivate/reactivate and reorder the
* household's child profiles. Every write refetches the list.
*
* Preferences: the household settings (planning horizon, day rollover,
* timezone, notifications). Save patches only the changed fields. The
* timezone — the application's source of local time — is only ever set by
* the admin picking or typing a zone here and saving it; every zone loaded
* or saved here is published app-wide (time/AppTimezone.tsx).
*
* One write at a time across both sections.
*/
import {
useEffect,
useRef,
useState,
type FormEvent,
type KeyboardEvent as ReactKeyboardEvent,
} from "react";
import { ApiForbiddenError } from "../api/client";
import {
createChild,
reorderChildren,
setChildActive,
updateChild,
type ChildCreateBody,
type ChildEditBody,
} from "../api/children";
import { ApiRequestError, fetchChildren, type AdminChild } from "../api/definitions";
import {
fetchSettings,
updateSettings,
type HouseholdSettings,
type SettingsChanges,
} from "../api/settings";
import { FOCUSABLE, inertOutside } from "../schedule/OverrideEditor";
import { usePublishAppTimezone } from "../time/AppTimezone";
import { ArrowDownGlyph, ArrowUpGlyph, ChevronLeftGlyph, PlusGlyph } from "./glyphs";
import "./SettingsScreen.css";
/** The swatch picker's presets; any other "#RRGGBB" can be typed. */
export const COLOUR_PRESETS = ["#e11d48", "#f97316", "#eab308", "#16a34a", "#0ea5e9", "#7c3aed"];
/** ADMIN-SPEC §1: every scroll column ends with 92px so content clears the tab bar. */
export const SCROLL_BOTTOM_PADDING = "92px";
const HEX_COLOUR = /^#[0-9a-fA-F]{6}$/;
type LoadState =
| { kind: "loading" }
| { kind: "error"; message: string }
| { kind: "ready"; children: AdminChild[] };
type FormTarget = null | "new" | AdminChild;
interface Draft {
name: string;
colour: string;
avatar: string;
order: string;
}
/** Display order: sort_order, ties broken by id (the API's own order). */
function sortChildren(children: AdminChild[]): AdminChild[] {
return [...children].sort((a, b) => a.sort_order - b.sort_order || a.id - b.id);
}
function errorMessage(error: unknown, action: string): string {
if (error instanceof ApiForbiddenError) return error.message;
if (error instanceof ApiRequestError && error.detail) return `${action}: ${error.detail}`;
return `${action}. Check your connection and try again.`;
}
function draftFor(target: "new" | AdminChild, siblings: AdminChild[]): Draft {
if (target === "new") {
const next = siblings.reduce((max, c) => Math.max(max, c.sort_order), 0) + 1;
return { name: "", colour: "", avatar: "", order: String(next) };
}
return {
name: target.display_name,
colour: target.colour ?? "",
avatar: target.avatar_ref ?? "",
order: String(target.sort_order),
};
}
/** The request body for the draft, or a validation message. */
function buildBody(
draft: Draft,
target: "new" | AdminChild,
): ChildCreateBody | ChildEditBody | string {
const name = draft.name.trim();
const colour = draft.colour.trim();
const avatar = draft.avatar.trim();
const order = draft.order.trim();
if (!name) return "Enter a display name.";
if (colour && !HEX_COLOUR.test(colour)) return "Colour must be a hex value like #0ea5e9.";
if (order && !/^-?\d+$/.test(order)) return "Order must be a whole number.";
if (target === "new") {
const body: ChildCreateBody = { display_name: name };
if (colour) body.colour = colour;
if (avatar) body.avatar_ref = avatar;
if (order) body.sort_order = Number(order);
return body;
}
// The API rejects null, so a set colour, avatar or order cannot be cleared.
if (!colour && target.colour !== null) return "A colour, once set, cannot be removed. Pick another.";
if (!avatar && target.avatar_ref !== null) return "An avatar ref, once set, cannot be removed.";
if (!order) return "Enter an order.";
const body: ChildEditBody = {};
if (name !== target.display_name) body.display_name = name;
if (colour && colour !== target.colour) body.colour = colour;
if (avatar && avatar !== target.avatar_ref) body.avatar_ref = avatar;
if (Number(order) !== target.sort_order) body.sort_order = Number(order);
if (Object.keys(body).length === 0) return "No changes to save.";
return body;
}
function ChildForm({
target,
siblings,
saving,
error,
onCancel,
onSubmit,
}: {
target: "new" | AdminChild;
/** The current list; a new child's order defaults to after the last. */
siblings: AdminChild[];
saving: boolean;
error: string | null;
onCancel: () => void;
onSubmit: (body: ChildCreateBody | ChildEditBody | string) => void;
}) {
const [draft, setDraft] = useState<Draft>(() => draftFor(target, siblings));
const nameRef = useRef<HTMLInputElement>(null);
const update = (patch: Partial<Draft>) => setDraft((d) => ({ ...d, ...patch }));
const isNew = target === "new";
const title = isNew ? "Add child" : `Edit ${target.display_name}`;
useEffect(() => {
nameRef.current?.focus();
}, []);
function submit(event: FormEvent) {
event.preventDefault();
onSubmit(buildBody(draft, target));
}
return (
<form className="settings-card settings-form" aria-label={title} onSubmit={submit} noValidate>
<h4 className="settings-form-title">{title}</h4>
<label className="settings-field">
<span className="settings-label">Display name</span>
<input
ref={nameRef}
className="settings-input"
type="text"
required
value={draft.name}
disabled={saving}
onChange={(event) => update({ name: event.target.value })}
/>
</label>
<div className="settings-field">
<label className="settings-field">
<span className="settings-label">Colour</span>
<input
className="settings-input"
type="text"
placeholder="#0ea5e9"
value={draft.colour}
disabled={saving}
onChange={(event) => update({ colour: event.target.value })}
/>
</label>
<div className="settings-swatches" role="group" aria-label="Colour presets">
{COLOUR_PRESETS.map((hex) => (
<button
key={hex}
type="button"
className="settings-swatch-option"
style={{ background: hex }}
aria-label={`Colour ${hex}`}
aria-pressed={draft.colour.toLowerCase() === hex}
disabled={saving}
onClick={() => update({ colour: hex })}
/>
))}
</div>
</div>
<label className="settings-field">
<span className="settings-label">Avatar ref (optional)</span>
<input
className="settings-input"
type="text"
value={draft.avatar}
disabled={saving}
onChange={(event) => update({ avatar: event.target.value })}
/>
</label>
<label className="settings-field">
<span className="settings-label">Order</span>
<input
className="settings-input"
type="text"
inputMode="numeric"
value={draft.order}
disabled={saving}
onChange={(event) => update({ order: event.target.value })}
/>
</label>
{error ? (
<p className="settings-error" role="alert" data-testid="child-form-error">
{error}
</p>
) : null}
<div className="settings-form-footer">
<button type="button" className="settings-cancel" disabled={saving} onClick={onCancel}>
Cancel
</button>
<button type="submit" className="settings-save" disabled={saving} aria-busy={saving}>
{saving ? "Saving…" : isNew ? "Add child" : "Save child"}
</button>
</div>
</form>
);
}
type PreferencesState =
| { kind: "loading" }
| { kind: "error"; message: string }
| { kind: "ready"; settings: HouseholdSettings };
type TimeField =
| "day_rollover_time"
| "morning_summary_time"
| "afternoon_reminder_time"
| "end_of_day_report_time";
type ToggleField =
| "morning_summary_enabled"
| "afternoon_reminder_enabled"
| "end_of_day_report_enabled"
| "celebration_enabled";
const NOTIFICATIONS: { label: string; time: TimeField; toggle: ToggleField }[] = [
{ label: "Morning summary", time: "morning_summary_time", toggle: "morning_summary_enabled" },
{ label: "Afternoon reminder", time: "afternoon_reminder_time", toggle: "afternoon_reminder_enabled" },
{ label: "End-of-day report", time: "end_of_day_report_time", toggle: "end_of_day_report_enabled" },
];
const HH_MM = /^([01]\d|2[0-3]):[0-5]\d$/;
/** "UTC" or an IANA-looking "Area/Location" (the API checks it resolves). */
const IANA_ZONE = /^(UTC|[A-Za-z]+(\/[A-Za-z0-9_+-]+)+)$/;
/** The Timezone picker's zones; any other IANA zone can be typed via "Other". */
export const COMMON_TIMEZONES = [
"UTC",
"America/New_York",
"America/Chicago",
"America/Denver",
"America/Phoenix",
"America/Los_Angeles",
"America/Anchorage",
"Pacific/Honolulu",
"America/Halifax",
"America/St_Johns",
"America/Toronto",
"America/Vancouver",
"America/Mexico_City",
"America/Sao_Paulo",
"Europe/London",
"Europe/Dublin",
"Europe/Paris",
"Europe/Berlin",
"Europe/Madrid",
"Europe/Rome",
"Europe/Athens",
"Africa/Johannesburg",
"Asia/Dubai",
"Asia/Kolkata",
"Asia/Singapore",
"Asia/Shanghai",
"Asia/Tokyo",
"Australia/Perth",
"Australia/Sydney",
"Pacific/Auckland",
];
/** The picker's "Other IANA zone…" option; never sent to the API. */
const OTHER_ZONE = "__other__";
/** The form's working copy: the number is text so it can be mid-edit. */
type PreferencesDraft = Omit<HouseholdSettings, "horizon_days"> & { horizon_days: string };
function preferencesDraft(settings: HouseholdSettings): PreferencesDraft {
return { ...settings, horizon_days: String(settings.horizon_days) };
}
/** Only the fields that differ from `loaded`, or a validation message. */
function buildChanges(draft: PreferencesDraft, loaded: HouseholdSettings): SettingsChanges | string {
const horizon = draft.horizon_days.trim();
const horizonDays = Number(horizon);
// A digit string too long for a safe integer would become Infinity, which
// JSON serializes as null, and the API reads null as "reset to default".
if (!/^\d+$/.test(horizon) || !Number.isSafeInteger(horizonDays) || horizonDays < 1) {
return "Planning horizon must be a whole number of days, at least 1.";
}
const times: [TimeField, string][] = [
["day_rollover_time", "Day rollover"],
...NOTIFICATIONS.map((n): [TimeField, string] => [n.time, `${n.label} time`]),
];
for (const [key, label] of times) {
if (!HH_MM.test(draft[key])) return `${label} must be a time like 07:30.`;
}
const timezone = draft.timezone.trim();
if (timezone && !IANA_ZONE.test(timezone)) {
return "Timezone must be an IANA zone like America/New_York, or UTC.";
}
const next: HouseholdSettings = {
...draft,
horizon_days: horizonDays,
notify_target: draft.notify_target.trim(),
timezone,
};
const changes: SettingsChanges = {};
for (const key of Object.keys(loaded) as (keyof HouseholdSettings)[]) {
if (next[key] !== loaded[key]) (changes as Record<string, unknown>)[key] = next[key];
}
if (Object.keys(changes).length === 0) return "No changes to save.";
return changes;
}
function PreferencesForm({
settings,
saving,
locked,
message,
onSubmit,
}: {
settings: HouseholdSettings;
saving: boolean;
/** Another write is in flight. */
locked: boolean;
message: { kind: "error" | "info"; text: string } | null;
onSubmit: (changes: SettingsChanges | string) => void;
}) {
const [draft, setDraft] = useState<PreferencesDraft>(() => preferencesDraft(settings));
const update = (patch: Partial<PreferencesDraft>) => setDraft((d) => ({ ...d, ...patch }));
// A saved zone outside the curated list opens in the free-text entry.
const [otherZone, setOtherZone] = useState(
() => settings.timezone !== "" && !COMMON_TIMEZONES.includes(settings.timezone),
);
const disabled = saving || locked;
function submit(event: FormEvent) {
event.preventDefault();
onSubmit(buildChanges(draft, settings));
}
function timeInput(key: TimeField, label: string) {
return (
<label className="settings-field">
<span className="settings-label">{label}</span>
<input
className="settings-input"
type="time"
value={draft[key]}
disabled={disabled}
onChange={(event) => update({ [key]: event.target.value })}
/>
</label>
);
}
function toggle(key: ToggleField, label: string) {
return (
<label className="settings-toggle">
<input
type="checkbox"
checked={draft[key]}
disabled={disabled}
onChange={(event) => update({ [key]: event.target.checked })}
/>
<span>{label}</span>
</label>
);
}
return (
<form className="settings-card settings-form" aria-label="Preferences" onSubmit={submit} noValidate>
<label className="settings-field">
<span className="settings-label">Planning horizon (days)</span>
<input
className="settings-input"
type="number"
min={1}
step={1}
inputMode="numeric"
value={draft.horizon_days}
disabled={disabled}
onChange={(event) => update({ horizon_days: event.target.value })}
/>
</label>
{timeInput("day_rollover_time", "Day rollover")}
<div className="settings-field">
<label className="settings-label" htmlFor="settings-timezone">
Timezone
</label>
<select
id="settings-timezone"
className="settings-input"
aria-describedby="settings-timezone-help"
value={otherZone ? OTHER_ZONE : draft.timezone}
disabled={disabled}
onChange={(event) => {
const choice = event.target.value;
setOtherZone(choice === OTHER_ZONE);
if (choice !== OTHER_ZONE) update({ timezone: choice });
}}
>
<option value="">API host local time (no zone set)</option>
{COMMON_TIMEZONES.map((zone) => (
<option key={zone} value={zone}>
{zone}
</option>
))}
<option value={OTHER_ZONE}>Other IANA zone…</option>
</select>
{otherZone ? (
<input
className="settings-input"
type="text"
aria-label="Other timezone"
placeholder="Area/Location, e.g. America/Boise"
autoComplete="off"
spellCheck={false}
value={draft.timezone}
disabled={disabled}
onChange={(event) => update({ timezone: event.target.value })}
/>
) : null}
<p className="settings-hint" id="settings-timezone-help">
The application timezone: the source of local time for the panel, the scheduler and this
admin app. It changes only when you save it here; with no zone set, the API host&apos;s
local time is used.
</p>
</div>
<label className="settings-field">
<span className="settings-label">Notify target</span>
<input
className="settings-input"
type="text"
value={draft.notify_target}
disabled={disabled}
onChange={(event) => update({ notify_target: event.target.value })}
/>
</label>
{NOTIFICATIONS.map((n) => (
<div key={n.toggle} className="settings-notification">
{toggle(n.toggle, n.label)}
{timeInput(n.time, `${n.label} time`)}
</div>
))}
{toggle("celebration_enabled", "Celebration")}
{message ? (
<p
className={message.kind === "error" ? "settings-error" : "settings-notice"}
role={message.kind === "error" ? "alert" : "status"}
data-testid="preferences-message"
>
{message.text}
</p>
) : null}
<div className="settings-form-footer">
<button type="submit" className="settings-save" disabled={disabled} aria-busy={saving}>
{saving ? "Saving…" : "Save preferences"}
</button>
</div>
</form>
);
}
function ChildRow({
child,
index,
count,
busy,
onEdit,
onMove,
onToggleActive,
}: {
child: AdminChild;
index: number;
count: number;
/** The in-flight action key, or null. Every write control waits on it. */
busy: string | null;
onEdit: () => void;
onMove: (delta: -1 | 1) => void;
onToggleActive: () => void;
}) {
const locked = busy !== null;
const toggling = busy === `active-${child.id}`;
return (
<li
className={child.is_active ? "settings-child" : "settings-child settings-child--inactive"}
data-testid={`settings-child-${child.id}`}
>
<span
className="settings-swatch"
data-testid={`settings-swatch-${child.id}`}
style={{ background: child.colour ?? "var(--nq-a-border)" }}
aria-hidden="true"
/>
<div className="settings-child-text">
<div className="settings-child-name">{child.display_name}</div>
<div className="settings-child-meta">
Order {child.sort_order} · {child.colour ?? "no colour"}
</div>
</div>
<span
className={child.is_active ? "settings-pill settings-pill--active" : "settings-pill"}
data-testid={`settings-active-${child.id}`}
>
{child.is_active ? "Active" : "Inactive"}
</span>
<div className="settings-child-actions">
<button
type="button"
className="settings-icon-button"
aria-label={`Move ${child.display_name} up`}
aria-busy={busy === `move-${child.id}`}
disabled={locked || index === 0}
onClick={() => onMove(-1)}
>
<ArrowUpGlyph />
</button>
<button
type="button"
className="settings-icon-button"
aria-label={`Move ${child.display_name} down`}
aria-busy={busy === `move-${child.id}`}
disabled={locked || index === count - 1}
onClick={() => onMove(1)}
>
<ArrowDownGlyph />
</button>
<button
type="button"
className="settings-action"
aria-label={`Edit ${child.display_name}`}
disabled={locked}
onClick={onEdit}
>
Edit
</button>
<button
type="button"
className="settings-action"
aria-label={`${child.is_active ? "Deactivate" : "Reactivate"} ${child.display_name}`}
aria-busy={toggling}
disabled={locked}
onClick={onToggleActive}
>
{toggling ? "Saving…" : child.is_active ? "Deactivate" : "Reactivate"}
</button>
</div>
</li>
);
}
export default function SettingsScreen({ onClose }: { onClose: () => void }) {
const [state, setState] = useState<LoadState>({ kind: "loading" });
const [attempt, setAttempt] = useState(0);
const [form, setForm] = useState<FormTarget>(null);
const [formError, setFormError] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [preferences, setPreferences] = useState<PreferencesState>({ kind: "loading" });
const [preferencesAttempt, setPreferencesAttempt] = useState(0);
const [preferencesMessage, setPreferencesMessage] = useState<{
kind: "error" | "info";
text: string;
} | null>(null);
// A ref, not state: two taps in one frame must not both see `busy === null`.
const inFlight = useRef(false);
const screenRef = useRef<HTMLDivElement>(null);
const titleRef = useRef<HTMLHeadingElement>(null);
const addRef = useRef<HTMLButtonElement>(null);
const formWasOpen = useRef(false);
const publishTimezone = usePublishAppTimezone();
// Modal focus: move in on open, keep the background out of reach, and hand
// focus back to the opener (the Settings button) on close.
useEffect(() => {
const trigger = document.activeElement as HTMLElement | null;
titleRef.current?.focus();
const restoreBackground = screenRef.current ? inertOutside(screenRef.current) : undefined;
return () => {
restoreBackground?.();
if (trigger && trigger.isConnected) trigger.focus();
};
}, []);
// The form's controls unmount when it closes; hand focus to Add child then
// (after the render that re-enables it).
useEffect(() => {
if (formWasOpen.current && form === null) addRef.current?.focus();
formWasOpen.current = form !== null;
}, [form]);
useEffect(() => {
let cancelled = false;
setState((current) => (current.kind === "ready" ? current : { kind: "loading" }));
fetchChildren()
.then((children) => {
if (!cancelled) setState({ kind: "ready", children: sortChildren(children) });
})
.catch((error: unknown) => {
if (cancelled) return;
setState({ kind: "error", message: errorMessage(error, "Children could not be loaded") });
});
return () => {
cancelled = true;
};
}, [attempt]);
useEffect(() => {
let cancelled = false;
setPreferences({ kind: "loading" });
fetchSettings()
.then((settings) => {
if (cancelled) return;
setPreferences({ kind: "ready", settings });
publishTimezone(settings.effective_timezone);
})
.catch((error: unknown) => {
if (cancelled) return;
setPreferences({ kind: "error", message: errorMessage(error, "Preferences could not be loaded") });
});
return () => {
cancelled = true;
};
}, [preferencesAttempt]);
function onKeyDown(event: ReactKeyboardEvent<HTMLDivElement>) {
if (event.key === "Escape") {
event.preventDefault();
if (!inFlight.current) onClose();
return;
}
if (event.key !== "Tab" || !screenRef.current) return;
const focusable = Array.from(screenRef.current.querySelectorAll<HTMLElement>(FOCUSABLE));
if (focusable.length === 0) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
const current = document.activeElement;
const outside = !focusable.includes(current as HTMLElement);
if (event.shiftKey && (current === first || outside)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (current === last || outside)) {
event.preventDefault();
first.focus();
}
}
/**
* Run one write, then refetch the list. One write at a time; a failure
* keeps the screen (and any open form) as it was and says why.
*/
async function run(key: string, write: () => Promise<unknown>, action: string): Promise<boolean> {
if (inFlight.current) return false;
inFlight.current = true;
setBusy(key);
setActionError(null);
setFormError(null);
try {
await write();
} catch (error) {
const message = errorMessage(error, action);
if (key === "form") setFormError(message);
else setActionError(message);
inFlight.current = false;
setBusy(null);
return false;
}
try {
const children = await fetchChildren();
setState({ kind: "ready", children: sortChildren(children) });
} catch (error) {
setActionError(errorMessage(error, "Saved, but the children list could not be refreshed"));
}
inFlight.current = false;
setBusy(null);
return true;
}
function closeForm() {
setForm(null);
setFormError(null);
}
async function submitForm(body: ChildCreateBody | ChildEditBody | string) {
if (form === null) return;
if (typeof body === "string") {
setFormError(body);
return;
}
const saved =
form === "new"
? await run("form", () => createChild(body as ChildCreateBody), "The child could not be added")
: await run("form", () => updateChild(form.id, body), "The child could not be saved");
if (saved) closeForm();
}
async function savePreferences(changes: SettingsChanges | string) {
if (typeof changes === "string") {
setPreferencesMessage({ kind: changes === "No changes to save." ? "info" : "error", text: changes });
return;
}
if (inFlight.current) return;
inFlight.current = true;
setBusy("preferences");
setPreferencesMessage(null);
try {
const settings = await updateSettings(changes);
setPreferences({ kind: "ready", settings });
publishTimezone(settings.effective_timezone);
setPreferencesMessage({ kind: "info", text: "Preferences saved." });
} catch (error) {
setPreferencesMessage({
kind: "error",
text: errorMessage(error, "The preferences could not be saved"),
});
}
inFlight.current = false;
setBusy(null);
}
function move(children: AdminChild[], index: number, delta: -1 | 1) {
const ids = children.map((c) => c.id);
const target = index + delta;
[ids[index], ids[target]] = [ids[target], ids[index]];
void run(`move-${children[index].id}`, () => reorderChildren(ids), "The order could not be saved");
}
function toggleActive(child: AdminChild) {
void run(
`active-${child.id}`,
() => setChildActive(child.id, !child.is_active),
child.is_active ? "The child could not be deactivated" : "The child could not be reactivated",
);
}
let body;
if (state.kind === "loading") {
body = (
<div className="settings-status" role="status" data-testid="settings-loading">
Loading children…
</div>
);
} else if (state.kind === "error") {
body = (
<div className="settings-status settings-status--error" role="alert" data-testid="settings-error">
<p>{state.message}</p>
<button type="button" className="settings-action" onClick={() => setAttempt((n) => n + 1)}>
Try again
</button>
</div>
);
} else {
const { children } = state;
body = (
<>
{children.length > 0 ? (
<ul className="settings-card settings-list" aria-label="Children">
{children.map((child, index) => (
<ChildRow
key={child.id}
child={child}
index={index}
count={children.length}
busy={busy}
onEdit={() => {
setFormError(null);
setForm(child);
}}
onMove={(delta) => move(children, index, delta)}
onToggleActive={() => toggleActive(child)}
/>
))}
</ul>
) : (
<div className="settings-card settings-empty">No children yet.</div>
)}
{form !== null ? (
<ChildForm
key={form === "new" ? "new" : form.id}
target={form}
siblings={children}
saving={busy === "form"}
error={formError}
onCancel={closeForm}
onSubmit={(b) => void submitForm(b)}
/>
) : null}
</>
);
}
return (
<div
ref={screenRef}
className="settings-screen"
role="dialog"
aria-modal="true"
aria-labelledby="settings-title"
onKeyDown={onKeyDown}
>
<header className="settings-header">
<button
type="button"
className="settings-back"
aria-label="Back"
disabled={busy !== null}
onClick={onClose}
>
<ChevronLeftGlyph size={20} />
</button>
<div>
<h2 className="settings-title" id="settings-title" ref={titleRef} tabIndex={-1}>
Settings
</h2>
<p className="settings-sub">Household setup</p>
</div>
</header>
<div
className="settings-scroll"
data-testid="settings-scroll"
style={{ paddingBottom: SCROLL_BOTTOM_PADDING }}
>
<div className="settings-section-head">
<h3 className="settings-section-label">Children</h3>
<button
ref={addRef}
type="button"
className="settings-add"
disabled={state.kind !== "ready" || busy !== null || form === "new"}
onClick={() => {
setFormError(null);
setForm("new");
}}
>
<PlusGlyph />
Add child
</button>
</div>
{actionError !== null ? (
<div className="settings-action-error" role="alert" data-testid="settings-action-error">
<span>{actionError}</span>
<button type="button" className="settings-action" onClick={() => setActionError(null)}>
Dismiss
</button>
</div>
) : null}
{body}
<div className="settings-section-head">
<h3 className="settings-section-label">Preferences</h3>
</div>
{preferences.kind === "loading" ? (
<div className="settings-status" role="status" data-testid="preferences-loading">
Loading preferences…
</div>
) : preferences.kind === "error" ? (
<div
className="settings-status settings-status--error"
role="alert"
data-testid="preferences-error"
>
<p>{preferences.message}</p>
<button
type="button"
className="settings-action"
onClick={() => setPreferencesAttempt((n) => n + 1)}
>
Try again
</button>
</div>
) : (
<PreferencesForm
// A saved response remounts the form so its draft matches the store.
key={JSON.stringify(preferences.settings)}
settings={preferences.settings}
saving={busy === "preferences"}
locked={busy !== null && busy !== "preferences"}
message={preferencesMessage}
onSubmit={(changes) => void savePreferences(changes)}
/>
)}
</div>
</div>
);
}
-56
View File
@@ -1,56 +0,0 @@
/**
* Inline stroke glyphs for the Settings screen (Lucide-style 24px grid),
* CDN-free like the tabs' glyphs.
*/
import type { ReactNode } from "react";
function Glyph({ size, children }: { size: number; children: ReactNode }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
>
{children}
</svg>
);
}
export function ChevronLeftGlyph({ size = 16 }: { size?: number }) {
return (
<Glyph size={size}>
<path d="m15 18-6-6 6-6" />
</Glyph>
);
}
export function ArrowUpGlyph({ size = 16 }: { size?: number }) {
return (
<Glyph size={size}>
<path d="m5 12 7-7 7 7M12 19V5" />
</Glyph>
);
}
export function ArrowDownGlyph({ size = 16 }: { size?: number }) {
return (
<Glyph size={size}>
<path d="M12 5v14M19 12l-7 7-7-7" />
</Glyph>
);
}
export function PlusGlyph({ size = 16 }: { size?: number }) {
return (
<Glyph size={size}>
<path d="M12 5v14M5 12h14" />
</Glyph>
);
}
-93
View File
@@ -1,93 +0,0 @@
/**
* The effective application timezone, loaded once per signed-in shell: the
* API's `effective_timezone` — the stored zone, or the API host's own zone
* when none is stored — so every screen's local time matches the API's.
*
* <AppTimezoneProvider> fetches the household settings and renders its
* screens only once the zone is known (a failed load says so and offers a
* retry), so no screen ever computes local time in a zone it will not keep.
* The Settings screen publishes every zone it loads or saves, so a change
* applies app-wide at once.
*
* Without a provider (a screen rendered on its own, e.g. in a test)
* useAppTimezone() is "" — the documented unset value, i.e. browser-local.
*/
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import { ApiForbiddenError } from "../api/client";
import { fetchSettings } from "../api/settings";
interface ZoneHub {
timeZone: string;
publish(timeZone: string): void;
}
const AppTimezoneContext = createContext<ZoneHub | null>(null);
type LoadState =
| { kind: "loading" }
| { kind: "error"; message: string }
| { kind: "ready"; timeZone: string };
export function AppTimezoneProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<LoadState>({ kind: "loading" });
const [attempt, setAttempt] = useState(0);
useEffect(() => {
let cancelled = false;
setState({ kind: "loading" });
fetchSettings()
.then((settings) => {
if (!cancelled) setState({ kind: "ready", timeZone: settings.effective_timezone });
})
.catch((error: unknown) => {
if (cancelled) return;
setState({
kind: "error",
message:
error instanceof ApiForbiddenError
? error.message
: "The application timezone could not be loaded. Check your connection and try again.",
});
});
return () => {
cancelled = true;
};
}, [attempt]);
if (state.kind === "loading") {
return (
<div className="admin-loading" role="status" data-testid="timezone-loading">
Loading…
</div>
);
}
if (state.kind === "error") {
return (
<div className="admin-error" role="alert" data-testid="timezone-error">
<p>{state.message}</p>
<button type="button" onClick={() => setAttempt((n) => n + 1)}>
Try again
</button>
</div>
);
}
const hub: ZoneHub = {
timeZone: state.timeZone,
publish: (timeZone) =>
setState((prev) =>
prev.kind === "ready" && prev.timeZone === timeZone ? prev : { kind: "ready", timeZone },
),
};
return <AppTimezoneContext.Provider value={hub}>{children}</AppTimezoneContext.Provider>;
}
/** The effective application timezone: an IANA name, or "" (browser-local). */
export function useAppTimezone(): string {
return useContext(AppTimezoneContext)?.timeZone ?? "";
}
/** Publish an effective zone just loaded or saved; a no-op without a provider. */
export function usePublishAppTimezone(): (timeZone: string) => void {
const hub = useContext(AppTimezoneContext);
return (timeZone) => hub?.publish(timeZone);
}
-60
View File
@@ -1,60 +0,0 @@
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { isoDateIn, todayIn, wallClockInstant, zoneOption } from "./zone";
import { formatClockTime } from "../today/format";
// 13:00 UTC on Sep 23 is already 01:00 on Sep 24 in Auckland (NZST, UTC+12).
const NOW = new Date("2026-09-23T13:00:00Z");
describe("application timezone helpers (process in UTC)", () => {
beforeAll(() => {
vi.stubEnv("TZ", "UTC");
});
afterAll(() => {
vi.unstubAllEnvs();
});
it("a stored zone decides the calendar date; empty means the browser's zone", () => {
expect(todayIn("Pacific/Auckland", NOW)).toBe("2026-09-24");
expect(isoDateIn(NOW, "Pacific/Auckland")).toBe("2026-09-24");
expect(todayIn("", NOW)).toBe("2026-09-23");
});
it("wall-clock time converts in the stored zone, across its DST change", () => {
// NZST (UTC+12) before 27 Sep 2026, NZDT (UTC+13) after.
expect(wallClockInstant("2026-09-24", 0, 10, "Pacific/Auckland")).toBe(
Date.parse("2026-09-23T12:10:00Z"),
);
expect(wallClockInstant("2026-09-28", 7, 30, "Pacific/Auckland")).toBe(
Date.parse("2026-09-27T18:30:00Z"),
);
expect(wallClockInstant("2026-09-24", 0, 10, "")).toBe(Date.parse("2026-09-24T00:10:00Z"));
});
it("the completion clock reads in the stored zone", () => {
expect(formatClockTime("2026-09-23T11:04:00Z", "Pacific/Auckland")).toBe("11:04 PM");
expect(formatClockTime("2026-09-23T11:04:00Z", "")).toBe("11:04 AM");
});
it("an invalid stored zone fails fast", () => {
expect(zoneOption("")).toBeUndefined();
expect(() => todayIn("Not/AZone", NOW)).toThrow(RangeError);
});
});
describe("empty zone keeps browser-local behavior", () => {
beforeAll(() => {
vi.stubEnv("TZ", "America/Los_Angeles");
});
afterAll(() => {
vi.unstubAllEnvs();
});
it("matches the browser's own calendar and wall clock", () => {
// 13:00 UTC is 06:00 PDT on Sep 23.
expect(todayIn("", NOW)).toBe("2026-09-23");
expect(wallClockInstant("2026-09-23", 7, 30, "")).toBe(new Date(2026, 8, 23, 7, 30).getTime());
expect(formatClockTime("2026-09-23T14:04:00Z", "")).toBe("7:04 AM");
});
});
-81
View File
@@ -1,81 +0,0 @@
/**
* Local time in the application timezone.
*
* The admin-saved zone (settings `timezone`, an IANA name) is the single
* source of local-time truth for the whole application; the API publishes it
* as `effective_timezone`, naming its host's own zone when none is stored.
* "" means the API published no zone, and only then does the browser's own
* zone apply. Every helper takes
* that stored value as-is; an invalid zone name throws (Intl's RangeError).
*/
/** The `timeZone` option for Intl: the zone, or undefined (browser) for "". */
export function zoneOption(timeZone: string): string | undefined {
return timeZone === "" ? undefined : timeZone;
}
interface WallClock {
year: number;
month: number;
day: number;
hour: number;
minute: number;
second: number;
}
function wallClock(instant: number, timeZone: string): WallClock {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: zoneOption(timeZone),
hourCycle: "h23",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
}).formatToParts(instant);
const part = (type: Intl.DateTimeFormatPartTypes) =>
Number(parts.find((p) => p.type === type)?.value);
return {
year: part("year"),
month: part("month"),
day: part("day"),
hour: part("hour"),
minute: part("minute"),
second: part("second"),
};
}
/** The "YYYY-MM-DD" calendar date of `instant` in the zone. */
export function isoDateIn(instant: Date, timeZone: string): string {
const { year, month, day } = wallClock(instant.getTime(), timeZone);
return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
}
/** Today's calendar date in the zone. */
export function todayIn(timeZone: string, now: Date = new Date()): string {
return isoDateIn(now, timeZone);
}
/** The zone's UTC offset in ms at `instant` (wall clock minus UTC). */
function offsetAt(instant: number, timeZone: string): number {
const c = wallClock(instant, timeZone);
const wholeSeconds = Math.floor(instant / 1000) * 1000;
return Date.UTC(c.year, c.month - 1, c.day, c.hour, c.minute, c.second) - wholeSeconds;
}
/**
* Epoch ms at which the zone's wall clock reads `hour:minute` on the
* "YYYY-MM-DD" date. Two passes settle the offset across a DST change.
*/
export function wallClockInstant(
iso: string,
hour: number,
minute: number,
timeZone: string,
): number {
const [year, month, day] = iso.split("-").map(Number);
const asUtc = Date.UTC(year, month - 1, day, hour, minute);
const guess = asUtc - offsetAt(asUtc, timeZone);
return asUtc - offsetAt(guess, timeZone);
}
-31
View File
@@ -241,37 +241,6 @@
color: var(--nq-brand-purple);
}
.today-action:disabled {
cursor: default;
opacity: 0.5;
}
/* Non-blocking Undo failure message. */
.today-action-error {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: var(--nq-a-density-row-pad);
border-radius: var(--nq-a-density-radius);
background: var(--nq-a-danger-bg);
color: var(--nq-a-danger-strong);
font-size: 13px;
font-weight: 600;
}
.today-action-dismiss {
flex: none;
padding: 4px 8px;
border: none;
background: none;
color: inherit;
font-family: inherit;
font-size: 12.5px;
font-weight: 700;
cursor: pointer;
}
.today-empty {
padding: var(--nq-a-density-card-pad);
font-size: 13px;
+1 -246
View File
@@ -1,11 +1,8 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import TodayTab, { PERMISSION_NOTE } from "./TodayTab";
import type { AdminSnapshot, SnapshotInstance } from "../api/snapshot";
import { TransitionsProvider } from "../api/useTransitions";
import { frame, testStream, type TestStream } from "../api/testStream";
import { storeTokens } from "../auth/oidc";
import { AppTimezoneProvider } from "../time/AppTimezone";
function instance(overrides: Partial<SnapshotInstance>): SnapshotInstance {
return {
@@ -224,245 +221,3 @@ describe("TodayTab", () => {
expect(error.textContent).toContain("nestquest-admins");
});
});
/** SNAPSHOT after instance 12 ("Make bed") is reversed back to open. */
const AFTER_UNDO: AdminSnapshot = {
...SNAPSHOT,
children: SNAPSHOT.children.map((child) =>
child.child_id !== 1
? child
: {
...child,
completed_today: 2,
remaining_today: 5,
completion_pct: 29,
instances: child.instances.map((i) =>
i.id === 12 ? { ...i, state: "open" as const, completed_at: null, on_time: null } : i,
),
},
),
};
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((r) => {
resolve = r;
});
return { promise, resolve };
}
describe("TodayTab Undo and live updates", () => {
let fetchMock: ReturnType<typeof vi.fn>;
let snapshots: AdminSnapshot[];
let uncomplete: () => Promise<Response>;
let streams: TestStream[];
function calls(pathSuffix: string, method = "GET") {
return fetchMock.mock.calls.filter(
([url, init]) =>
new URL(String(url), "http://x").pathname.endsWith(pathSuffix) &&
(init?.method ?? "GET") === method,
);
}
beforeAll(() => {
vi.stubEnv("TZ", "America/Los_Angeles");
});
afterAll(() => {
vi.unstubAllEnvs();
});
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
snapshots = [SNAPSHOT, AFTER_UNDO];
uncomplete = () =>
Promise.resolve(jsonResponse({ instance_id: 12, state: "open", appended: true }));
streams = [];
fetchMock = vi.fn((url: string) => {
const path = new URL(url, "http://x").pathname;
if (path.endsWith("/api/v1/admin/snapshot")) {
const next = snapshots.length > 1 ? snapshots.shift()! : snapshots[0];
return Promise.resolve(jsonResponse(next));
}
if (path.endsWith("/api/v1/admin/instances/12/uncomplete")) return uncomplete();
if (path.endsWith("/api/v1/admin/events")) {
const stream = testStream();
streams.push(stream);
return Promise.resolve(stream.response);
}
return Promise.resolve(jsonResponse({ detail: "unexpected" }, 500));
});
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
it("Undo POSTs uncomplete for the completed instance and refetches the snapshot", async () => {
render(<TodayTab />);
const row = await screen.findByTestId("attention-12");
fireEvent.click(within(row).getByRole("button", { name: "Undo" }));
await waitFor(() => expect(screen.queryByTestId("attention-12")).toBeNull());
const posts = calls("/api/v1/admin/instances/12/uncomplete", "POST");
expect(posts).toHaveLength(1);
expect(posts[0][1].headers.Authorization).toBe("Bearer at-123");
expect(calls("/api/v1/admin/snapshot")).toHaveLength(2);
// The reversed instance is open again: one fewer done, one more remaining.
expect(screen.getByTestId("stat-done").textContent).toBe("6Done");
expect(screen.getByTestId("stat-remaining").textContent).toBe("5Remaining");
expect(screen.queryByTestId("today-undo-error")).toBeNull();
});
it("disables Undo while the request is in flight (no double submit)", async () => {
const pending = deferred<Response>();
uncomplete = () => pending.promise;
render(<TodayTab />);
const row = await screen.findByTestId("attention-12");
const button = within(row).getByRole("button", { name: "Undo" }) as HTMLButtonElement;
fireEvent.click(button);
await waitFor(() => expect(button.disabled).toBe(true));
expect(button.textContent).toBe("Undoing…");
// Every Undo is disabled while one reversal is in flight.
const other = within(screen.getByTestId("attention-14")).getByRole("button", {
name: "Undo",
}) as HTMLButtonElement;
expect(other.disabled).toBe(true);
fireEvent.click(button);
fireEvent.click(other);
expect(calls("/api/v1/admin/instances/12/uncomplete", "POST")).toHaveLength(1);
expect(calls("/uncomplete", "POST")).toHaveLength(1);
pending.resolve(jsonResponse({ instance_id: 12, state: "open", appended: true }));
await waitFor(() => expect(screen.queryByTestId("attention-12")).toBeNull());
expect(other.disabled).toBe(false);
});
it("a failed Undo shows a message and leaves the view intact", async () => {
uncomplete = () => Promise.resolve(jsonResponse({ detail: "instance 12 not found" }, 404));
render(<TodayTab />);
const row = await screen.findByTestId("attention-12");
fireEvent.click(within(row).getByRole("button", { name: "Undo" }));
const alert = await screen.findByTestId("today-undo-error");
expect(alert.textContent).toContain("The completion could not be undone: instance 12 not found");
// Still the original snapshot: nothing refetched, the row and its Undo remain usable.
expect(calls("/api/v1/admin/snapshot")).toHaveLength(1);
const button = within(screen.getByTestId("attention-12")).getByRole("button", {
name: "Undo",
}) as HTMLButtonElement;
expect(button.disabled).toBe(false);
expect(screen.getByTestId("stat-done").textContent).toBe("7Done");
fireEvent.click(within(alert).getByRole("button", { name: "Dismiss" }));
expect(screen.queryByTestId("today-undo-error")).toBeNull();
});
it("Mark done stays inert", async () => {
render(<TodayTab />);
const row = await screen.findByTestId("attention-11");
fireEvent.click(within(row).getByRole("button", { name: "Mark done" }));
expect(fetchMock.mock.calls.filter(([, init]) => init?.method === "POST")).toHaveLength(0);
});
it("a transition on the live stream refetches the snapshot without a reload", async () => {
const { unmount } = render(
<TransitionsProvider>
<TodayTab />
</TransitionsProvider>,
);
await screen.findByTestId("attention-12");
await waitFor(() => expect(streams).toHaveLength(1));
const [, init] = calls("/api/v1/admin/events")[0];
expect(init.headers.Authorization).toBe("Bearer at-123");
// An uncompletion made elsewhere, its frame split across two chunks.
const text = frame("nestquest_quest_uncompleted", {
child_id: 1,
child_name: "Declan",
instance_id: 12,
quest_title: "Make bed",
window: "morning",
due_date: "2026-09-23",
due_time: null,
occurred_at: "2026-09-23T12:00:00Z",
});
streams[0].push(text.slice(0, 25));
streams[0].push(text.slice(25));
await waitFor(() => expect(calls("/api/v1/admin/snapshot")).toHaveLength(2));
await waitFor(() => expect(screen.queryByTestId("attention-12")).toBeNull());
// Refreshed in place: the loading state never replaced the view.
expect(screen.queryByTestId("today-loading")).toBeNull();
const signal = init.signal as AbortSignal;
expect(signal.aborted).toBe(false);
unmount();
expect(signal.aborted).toBe(true);
await waitFor(() => expect(streams[0].cancelled()).toBe(true));
});
});
describe("TodayTab in the stored application timezone", () => {
function renderWithZone(timezone: string, effective_timezone = timezone) {
fetchMock.mockImplementation((url: string) =>
Promise.resolve(
String(url).endsWith("/api/v1/admin/settings")
? jsonResponse({ timezone, effective_timezone })
: jsonResponse(SNAPSHOT),
),
);
render(
<AppTimezoneProvider>
<TodayTab />
</AppTimezoneProvider>,
);
}
beforeAll(() => {
// The browser runs in UTC; the household lives in Auckland (UTC+12 on Sep 23).
vi.stubEnv("TZ", "UTC");
});
afterAll(() => {
vi.unstubAllEnvs();
});
beforeEach(() => {
sessionStorage.clear();
storeTokens({ access_token: "at-123", expires_in: 600 });
fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
it("shows the completion clock in the stored zone, not the browser's", async () => {
renderWithZone("Pacific/Auckland");
const completed = await screen.findByTestId("attention-12");
// 11:04 UTC is 11:04 PM in Auckland.
expect(within(completed).getByText("Completed 11:04 PM")).toBeTruthy();
// The header's day is the API's household-local today_iso, as-is.
expect(screen.getByText("Wednesday, September 23 · cycle day 5 of 14")).toBeTruthy();
});
it("an empty stored zone shows the clock in the API host's published zone", async () => {
renderWithZone("", "Pacific/Auckland");
const completed = await screen.findByTestId("attention-12");
expect(within(completed).getByText("Completed 11:04 PM")).toBeTruthy();
});
it("only an API that publishes no zone leaves the browser's local clock", async () => {
renderWithZone("", "");
const completed = await screen.findByTestId("attention-12");
expect(within(completed).getByText("Completed 11:04 AM")).toBeTruthy();
});
});
+18 -108
View File
@@ -1,7 +1,7 @@
/**
* Today tab — compact density (design/ADMIN-SPEC.md §2.1–2.3, §2.5–2.6).
*/
import { useEffect, useRef, useState } from "react";
import { useEffect, useState } from "react";
import {
fetchSnapshot,
type AdminSnapshot,
@@ -9,11 +9,6 @@ import {
type SnapshotInstance,
} from "../api/snapshot";
import { ApiForbiddenError } from "../api/client";
import { ApiRequestError } from "../api/definitions";
import { uncompleteInstance } from "../api/instances";
import { useTransitions } from "../api/useTransitions";
import SettingsScreen from "../settings/SettingsScreen";
import { useAppTimezone } from "../time/AppTimezone";
import {
formatClockTime,
formatDueTime,
@@ -45,22 +40,15 @@ function isOverdueOpen(instance: SnapshotInstance): boolean {
return instance.overdue && instance.state === "open";
}
function ScreenHeader({ sub, onSettings }: { sub: string; onSettings: () => void }) {
function ScreenHeader({ sub }: { sub: string }) {
return (
<header className="today-header">
<div>
<h2 className="today-title">Today</h2>
<p className="today-sub">{sub}</p>
</div>
{/* Opens the Settings screen. Only its Children section exists so far.
TODO: horizon days, day rollover time and notification config are a
separate later task. */}
<button
type="button"
className="today-icon-button"
aria-label="Settings"
onClick={onSettings}
>
{/* Settings screen is a later task; the control is not wired yet. */}
<button type="button" className="today-icon-button" aria-label="Settings">
<SettingsGlyph />
</button>
</header>
@@ -156,19 +144,11 @@ function attentionItems(snapshot: AdminSnapshot): AttentionItem[] {
return [...overdue, ...completed];
}
interface UndoControl {
/** The instance whose Undo is in flight, or null. */
pendingId: number | null;
onUndo: (instanceId: number) => void;
}
function AttentionRow({ item, undo }: { item: AttentionItem; undo: UndoControl }) {
function AttentionRow({ item }: { item: AttentionItem }) {
const { instance, childName } = item;
const overdue = isOverdueOpen(instance);
const undoing = undo.pendingId === instance.id;
const timeZone = useAppTimezone();
// TODO(e57facc2): wire "Mark done". The admin plane has no complete route
// yet, so that action is inert here.
// TODO(e57facc2): wire "Mark done" / "Undo" mutations and live updates.
// The admin plane has no complete route yet, so both actions are inert here.
return (
<li className="today-event" data-testid={`attention-${instance.id}`}>
<span
@@ -189,25 +169,16 @@ function AttentionRow({ item, undo }: { item: AttentionItem; undo: UndoControl }
) : (
// The snapshot carries no completion actor, so "from panel" is not printed.
<div className="today-event-meta">
Completed {formatClockTime(instance.completed_at as string, timeZone)}
Completed {formatClockTime(instance.completed_at as string)}
</div>
)}
</div>
{overdue ? (
<button type="button" className="today-action today-action--done">
Mark done
</button>
) : (
<button
type="button"
className="today-action today-action--undo"
disabled={undo.pendingId !== null}
aria-busy={undoing}
onClick={() => undo.onUndo(instance.id)}
>
{undoing ? "Undoing…" : "Undo"}
</button>
)}
<button
type="button"
className={overdue ? "today-action today-action--done" : "today-action today-action--undo"}
>
{overdue ? "Mark done" : "Undo"}
</button>
</li>
);
}
@@ -226,26 +197,10 @@ function PermissionNote() {
export default function TodayTab() {
const [state, setState] = useState<LoadState>({ kind: "loading" });
const [attempt, setAttempt] = useState(0);
/** The next load is a refresh in place: keep the current view, no loading state. */
const silentNext = useRef(false);
const [undoingId, setUndoingId] = useState<number | null>(null);
const undoingRef = useRef(false);
const [undoError, setUndoError] = useState<string | null>(null);
const [settingsOpen, setSettingsOpen] = useState(false);
function refresh() {
silentNext.current = true;
setAttempt((n) => n + 1);
}
// Any transition (completed, uncompleted, missed, day complete) changes the snapshot.
useTransitions(refresh);
useEffect(() => {
let cancelled = false;
const silent = silentNext.current;
silentNext.current = false;
if (!silent) setState({ kind: "loading" });
setState({ kind: "loading" });
fetchSnapshot()
.then((snapshot) => {
if (!cancelled) setState({ kind: "ready", snapshot });
@@ -256,37 +211,13 @@ export default function TodayTab() {
error instanceof ApiForbiddenError
? error.message
: "Today's snapshot could not be loaded. Check your connection and try again.";
// A failed refresh keeps the snapshot already on screen.
setState((prev) => (silent && prev.kind === "ready" ? prev : { kind: "error", message }));
setState({ kind: "error", message });
});
return () => {
cancelled = true;
};
}, [attempt]);
/** Reverse one completion, then refetch the snapshot. One request at a time. */
async function undo(instanceId: number) {
if (undoingRef.current) return;
undoingRef.current = true;
setUndoingId(instanceId);
setUndoError(null);
try {
await uncompleteInstance(instanceId);
refresh();
} catch (error: unknown) {
setUndoError(
error instanceof ApiForbiddenError
? error.message
: error instanceof ApiRequestError && error.detail
? `The completion could not be undone: ${error.detail}`
: "The completion could not be undone. Check your connection and try again.",
);
} finally {
undoingRef.current = false;
setUndoingId(null);
}
}
let sub = "";
let body;
if (state.kind === "loading") {
@@ -320,11 +251,7 @@ export default function TodayTab() {
{attention.length > 0 ? (
<ul className="today-card today-list" aria-label="Needs attention">
{attention.map((item) => (
<AttentionRow
key={item.instance.id}
item={item}
undo={{ pendingId: undoingId, onUndo: (id) => void undo(id) }}
/>
<AttentionRow key={item.instance.id} item={item} />
))}
</ul>
) : (
@@ -337,31 +264,14 @@ export default function TodayTab() {
return (
<div className="today-screen">
<ScreenHeader sub={sub} onSettings={() => setSettingsOpen(true)} />
<ScreenHeader sub={sub} />
<div
className="today-scroll"
data-testid="today-scroll"
style={{ paddingBottom: SCROLL_BOTTOM_PADDING }}
>
{undoError !== null ? (
<div className="today-action-error" role="alert" data-testid="today-undo-error">
<span>{undoError}</span>
<button type="button" className="today-action-dismiss" onClick={() => setUndoError(null)}>
Dismiss
</button>
</div>
) : null}
{body}
</div>
{settingsOpen ? (
<SettingsScreen
onClose={() => {
setSettingsOpen(false);
// Child names and order feed the snapshot.
refresh();
}}
/>
) : null}
</div>
);
}
+4 -10
View File
@@ -4,10 +4,8 @@
* Calendar dates ("YYYY-MM-DD") are parsed by their components and formatted
* in UTC, so the printed day never shifts with the viewer's offset — unlike
* `new Date("YYYY-MM-DD")`, which is UTC midnight and reads as the previous
* day in negative-offset zones. Instants are shown in the application
* timezone (time/zone.ts).
* day in negative-offset zones.
*/
import { zoneOption } from "../time/zone";
const LOCALE = "en-US";
@@ -46,11 +44,7 @@ export function formatDueTime(hhmm: string): string {
return format(date, { hour: "numeric", minute: "2-digit", timeZone: "UTC" });
}
/** A UTC ISO timestamp shown as wall-clock time in `timeZone` ("" = browser), "7:04 AM". */
export function formatClockTime(isoTimestamp: string, timeZone: string): string {
return format(new Date(isoTimestamp), {
hour: "numeric",
minute: "2-digit",
timeZone: zoneOption(timeZone),
});
/** A UTC ISO timestamp shown as the viewer's local time, "7:04 AM". */
export function formatClockTime(isoTimestamp: string): string {
return format(new Date(isoTimestamp), { hour: "numeric", minute: "2-digit" });
}
-83
View File
@@ -1,83 +0,0 @@
# NestQuest API
Standalone FastAPI service owning the NestQuest database (Feature 16).
Served with ``uvicorn --factory api.app:create_app``; configuration is
environment-supplied (``api/config.py``) and every variable is required.
## Runtime dependencies
``api/requirements.txt`` is the API deployable's OWN dependency
manifest (fastapi, uvicorn, pyjwt[crypto], httpx) — deliberately kept
out of the integration's ``pyproject.toml`` dev group, which exists only
so the monorepo test venv can run the API tests.
## Container deployment (scaffold)
The image is built from the repository ROOT context (the API loads the
bundled domain core from ``custom_components/nestquest/core/`` by file
location, so both trees must be in the build context):
docker build -t nestquest-api:latest .
Run it with compose — the SQLite file lives on the named volume
``nestquest-db`` so recreating the container keeps household data:
cp deploy/.env.example deploy/.env # then fill in real values
docker compose -f deploy/compose.yaml up -d --build
``deploy/.env`` is git-ignored and supplies the secrets (panel service
token, Authentik OIDC settings); ``NESTQUEST_DB_PATH`` is fixed to
``/var/lib/nestquest/nestquest.db`` by compose.
The published port binds ``NESTQUEST_BIND_ADDRESS`` from
``deploy/.env`` and defaults to ``127.0.0.1`` (localhost only). In
production TLS is terminated by the shared Traefik reverse proxy,
which serves ``https://nestquest.cubecraftlabs.com`` (Let's Encrypt,
auto-renewed, HTTP redirected to HTTPS) and forwards to the API box
on port 8080 — so on that box set ``NESTQUEST_BIND_ADDRESS`` to its
LAN address (``10.60.1.14``). Traefik only allows
``/api/v1/panel`` from the Home Assistant host. The full deployment,
restore and verification procedure is in ``deploy/RUNBOOK.md``.
## Continuous backup (Litestream)
Compose also runs a ``litestream`` sidecar
(``litestream/litestream:0.5.17``, config ``deploy/litestream.yml``).
It mounts the same ``nestquest-db`` volume and continuously replicates
``/var/lib/nestquest/nestquest.db`` over SFTP to the Synology NAS
``CubeCraft-SRVR1`` (``joshua@10.60.1.50``), directory
``/volume1/homes/Joshua/nestquest-backups`` (``/homes/Joshua/...`` in
the NAS's chrooted SFTP view) — so the backup is outside the Docker
host and its volume. A snapshot is taken daily and a week of
snapshots plus incremental changes is retained; the NAS host key is
pinned in the config.
The SFTP login uses a dedicated keypair that lives only on the API
box and is git-ignored. Create it once, before ``up``:
ssh-keygen -t ed25519 -N "" -C nestquest-litestream -f deploy/litestream_key
then append ``restrict `` + the contents of ``deploy/litestream_key.pub``
to ``joshua@10.60.1.50:~/.ssh/authorized_keys``. Compose mounts the
private key read-only at ``/etc/litestream/sftp_key``. The sidecar runs
as uid/gid 999 (the API's ``nestquest`` user), so give it the key:
sudo chown 999:999 deploy/litestream_key && chmod 600 deploy/litestream_key
The sidecar needs WRITE access to the database volume: Litestream adds
its own ``_litestream_seq``/``_litestream_lock`` tables to the database,
writes the ``-wal``/``-shm`` files and checkpoints the WAL, and fails
with "unable to open database file" on a read-only mount. That access
is contained rather than removed — the sidecar runs as the non-root
volume owner with a read-only root filesystem, ``no-new-privileges``
and all Linux capabilities dropped.
Check replication with
``docker compose -f deploy/compose.yaml logs litestream`` or
``docker compose -f deploy/compose.yaml exec litestream litestream ltx /var/lib/nestquest/nestquest.db``.
To restore (high level): stop the ``api`` service, run
``litestream restore -config /etc/litestream.yml -o <new path>
/var/lib/nestquest/nestquest.db`` from a litestream container with the
same mounts, verify the restored file, move it into place on the
volume (removing any stale ``-wal``/``-shm`` files), and start ``api``
again.
-62
View File
@@ -1,62 +0,0 @@
"""The API's effective application timezone (task 7e173881).
The admin-stored ``timezone`` setting is the single source of local-time
truth; stored empty, the API reads its clock in the API host's local
time. :func:`effective_timezone` names the zone the API actually uses —
the stored zone, or else the host's own IANA zone — so the panel cards
and the admin app format local time in exactly the API's zone instead of
guessing with Home Assistant's or the browser's. ``""`` only when the
host's zone genuinely cannot be named.
"""
from __future__ import annotations
import os
from collections.abc import Mapping
from pathlib import Path
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
def _valid_zone(name: str) -> str:
"""Return ``name`` if it is a loadable IANA zone key, else ``""``."""
name = name.strip().removeprefix(":")
if not name:
return ""
try:
ZoneInfo(name)
except (ZoneInfoNotFoundError, ValueError):
return ""
return name
def host_timezone(
environ: Mapping[str, str] = os.environ,
timezone_file: Path = Path("/etc/timezone"),
localtime: Path = Path("/etc/localtime"),
) -> str:
"""Name the API host's local zone as an IANA key, or ``""``.
In the order the C library honours them: the ``TZ`` environment
variable, then the ``/etc/localtime`` zoneinfo link (with Debian's
``/etc/timezone`` naming it when the link is a copy). A host with
none of them configured runs UTC. A setting that names no IANA
zone (a POSIX rule string, a copied file) is ``""``.
"""
configured = environ.get("TZ")
if configured is not None:
# An empty TZ is UTC to the C library.
return _valid_zone(configured) if configured.strip() else "UTC"
if localtime.is_symlink():
target = str(localtime.resolve())
marker = "/zoneinfo/"
if marker in target:
return _valid_zone(target.split(marker, 1)[1])
if timezone_file.is_file():
return _valid_zone(timezone_file.read_text(encoding="utf-8"))
if not localtime.exists():
return "UTC"
return ""
def effective_timezone(stored: str) -> str:
"""The zone the API reads its clock in: ``stored``, else the host's."""
return stored or host_timezone()
+3 -8
View File
@@ -152,10 +152,6 @@ core_quest_definitions = importlib.import_module(
f"{_CORE_MODULE_NAME}.quest_definitions"
)
#: The icon-key module (``core.icons.normalize_icon_for_read``) the
#: admin plane's quest-definition responses normalize ``icon`` through.
core_icons = importlib.import_module(f"{_CORE_MODULE_NAME}.icons")
#: The recurrence model (``core.recurrence.ScheduleRule`` and
#: ``RuleValidationError``) the quest-definition routes build request
#: rules with — the model validates at construction, the routes never
@@ -163,12 +159,12 @@ core_icons = importlib.import_module(f"{_CORE_MODULE_NAME}.icons")
core_recurrence = importlib.import_module(f"{_CORE_MODULE_NAME}.recurrence")
#: The presence model (``core.presence.PresenceEngine``,
#: ``PresencePattern``, ``PresenceOverride``) the admin plane's
#: ``PresenceSchedule``, ``PresenceOverride``) the admin plane's
#: presence routes serialize and the tests resolve presence with.
core_presence = importlib.import_module(f"{_CORE_MODULE_NAME}.presence")
#: The presence-write business layer
#: (``core.presence_management.create_presence_pattern`` et al.) the
#: (``core.presence_management.set_presence_schedule`` et al.) the
#: admin plane's presence routes call — the ONE implementation the HA
#: services share.
core_presence_management = importlib.import_module(
@@ -176,7 +172,7 @@ core_presence_management = importlib.import_module(
)
#: The typed presence DAOs (``core.dao_presence``) the admin-plane tests
#: read stored patterns and overrides back through.
#: read stored schedules and overrides back through.
core_dao_presence = importlib.import_module(
f"{_CORE_MODULE_NAME}.dao_presence"
)
@@ -219,7 +215,6 @@ __all__ = [
"core_db",
"core_events",
"core_history",
"core_icons",
"core_materialize",
"core_migrations",
"core_presence",
-38
View File
@@ -1,38 +0,0 @@
# Runtime dependency manifest for the NestQuest API deployable.
#
# The monorepo's pyproject.toml carries fastapi/uvicorn/pyjwt/httpx in
# the INTEGRATION's dev group only (so the test venv can exercise the
# API); they are deliberately NOT integration runtime dependencies.
# Per that manifest's own comment, the API deployable declares its own
# runtime dependencies HERE — this file is what the container image
# installs (see the Dockerfile at the repository root).
#
# EXACT pins: the versions installed in the deployed image
# (nestquest-api:latest on the API box, read with importlib.metadata),
# so a rebuild resolves the same packages. The four direct
# dependencies come first; the rest is their resolved transitive
# closure, pinned too so nothing floats. The dev group's floors in
# pyproject.toml are unchanged. Bump deliberately, together with the
# Dockerfile's digest-pinned base image.
fastapi==0.141.1
uvicorn==0.53.0
pyjwt[crypto]==2.15.0
httpx==0.28.1
# Transitive dependencies of the above.
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.15.1
certifi==2026.7.22
cffi==2.1.1
click==8.5.0
cryptography==50.0.1
h11==0.16.0
httpcore==1.0.9
idna==3.20
pycparser==3.0
pydantic==2.13.5
pydantic_core==2.46.5
starlette==1.7.0
typing-inspection==0.4.4
typing_extensions==4.16.0
+156 -406
View File
@@ -39,27 +39,15 @@ The presence routes follow the same pattern over
:mod:`nestquest_core.presence_management` — the ONE presence write
layer the HA services share, so the two planes cannot drift:
- ``GET /children/{child_id}/presence-patterns`` lists the child's
repeating presence patterns (zero or more, schema 9) through ONE
``list_presence_patterns`` call, wrapped as ``{"patterns": [...]}``
ordered by id — an empty list when the child has none (present
every day), never a 404; an unknown child is 404.
- ``POST /children/{child_id}/presence-patterns`` adds one pattern:
the body's ``name``, ``kind`` (``home``/``away``),
``cycle_length_weeks``, ``anchor_date`` and ``pattern`` go straight
into ONE :class:`~nestquest_core.presence.PresencePattern` (the model
validates the name, the kind, cycle length, the strict anchor date
and the pattern's week coverage at construction), the core inserts
it beside the child's other patterns and regenerates the child's
future instances; the response (201) is the STORED pattern with its
``id``, its weekday sets decoded back through the model.
- ``PATCH /presence-patterns/{pattern_id}`` edits one pattern: only
SUPPLIED fields are forwarded (``exclude_unset``), the core lays them
over the stored pattern and rebuilds the WHOLE model, so a partial
edit is validated exactly as a create; it regenerates the pattern's
child.
- ``DELETE /presence-patterns/{pattern_id}`` deletes one pattern and
regenerates its child. It answers ``{"status": "ok"}``.
- ``PUT /children/{child_id}/presence-schedule`` sets (UPSERTS) the
child's repeating schedule: the body's ``cycle_length_weeks``,
``anchor_date`` and ``pattern`` go straight into ONE
:class:`~nestquest_core.presence.PresenceSchedule` (the model
validates cycle length, the strict anchor date and the pattern's
week coverage at construction), the core upserts by child (setting
again REPLACES the one schedule a child can have) and regenerates
the child's future instances; the response is the STORED schedule
decoded back through the model.
- ``POST /presence-overrides`` creates one date-range override: the
body becomes ONE :class:`~nestquest_core.presence.PresenceOverride`
(the model validates the dates, ``end >= start``, the real bool and
@@ -77,6 +65,11 @@ layer the HA services share, so the two planes cannot drift:
(instances with a completion event are never counted, D-005).
Nothing is written; an unknown child is 404, a malformed or inverted
range 422.
- ``GET /children/{child_id}/presence-schedule`` reads the child's
schedule through ONE ``get_presence_schedule`` call, wrapped as
``{"schedule": ...}`` in the PUT response's shape — ``null`` when the
child has none (present every day), never a 404; an unknown child is
404.
- ``GET /presence-overrides`` lists the household's overrides through
ONE ``list_presence_overrides`` call, wrapped as
``{"overrides": [...]}`` in the POST response's shape, ordered by
@@ -165,15 +158,10 @@ integration's Home-Assistant config-entry options remain a temporary,
SEPARATE source until Feature 18 wires the client to the API — the two
are deliberately not unified here:
- ``GET /settings`` returns the current effective settings: all eleven
- ``GET /settings`` returns the current effective settings: all ten
documented fields (the rolling horizon, the day rollover time, the
notify target, the three notification times, the four enable
toggles, and the ``timezone`` — the IANA household zone the
household-local dates derive from, empty meaning host local; only an
admin's ``PATCH`` ever sets it) — the defaults on a fresh database —
plus the read-only ``effective_timezone`` (:mod:`api.host_zone`): the
zone the API actually reads its clock in, which the admin app formats
local time in.
notify target, the three notification times and the four enable
toggles) — the defaults on a fresh database.
- ``PATCH /settings`` updates ONLY the supplied fields: the body is a
JSON object of settings field names to new values, passed STRAIGHT
to :func:`nestquest_core.settings_store.update_settings` — the
@@ -189,38 +177,18 @@ The missed-sweep trigger (task 058c7b69) follows the same pattern over
:mod:`nestquest_core.sweep` — the HA-free sweep policy the
integration's rollover listener shares:
- ``POST /missed-sweep`` runs the sweep for the household-local
``today`` (ONE :func:`_local_now` clock read re-expressed in the
configured household ``timezone`` — empty falls back to host local —
threaded into the core call) and publishes each returned
``(event_type, payload)`` pair DIRECTLY on the app's ONE transition
publisher — the sweep-built payload, never re-fetched (the core
commits its watermark before returning, so a failed re-fetch after it
would lose the missed event forever), the same
publish-what-the-core-built shape api/scheduler.py uses. The
watermark rule (a same-day rerun announces nothing, a post-downtime
run sweeps the accumulated window once), the no-completion-event rule
and the read-only-over-the-domain-tables guarantee all live in the
core; the response reports how many transitions were published.
The quest-definition DELETE route (task 3efb07b4) is the hybrid admin
delete (owner decision 2026-09-26: "delete if there's no history,
retire/deactivate if there is"):
- ``DELETE /quest-definitions/{definition_id}`` is a thin adapter over
:func:`nestquest_core.quest_definitions.delete_quest_definition`. A
definition with NO completion event on any instance is hard-deleted
(instances, assignees, windows, the row and its unreferenced rule, in
one core transaction); one WITH history is retired by deactivation.
Retirement preserves the definition row, schedule rule, assignees,
windows and ALL durable completion history; like any deactivation it
regenerates, so future UNCOMPLETED instances are cleared (rolling,
regenerable rows) and none are recreated while the definition is
inactive — the retired task stops generating and shows no open work.
Durable instance history lives only in the append-only
``completion_events``. The response reports which happened
(``deleted`` / ``retired``) and carries the retired definition, or
``null`` when deleted. An unknown id is 404.
- ``POST /missed-sweep`` runs the sweep for the API host's local
``today`` (ONE :func:`_local_now` clock read threaded into the core
call) and publishes each returned ``(event_type, payload)`` pair
DIRECTLY on the app's ONE transition publisher — the sweep-built
payload, never re-fetched (the core commits its watermark before
returning, so a failed re-fetch after it would lose the missed event
forever), the same publish-what-the-core-built shape
api/scheduler.py uses. The watermark rule
(a same-day rerun announces nothing, a post-downtime run sweeps the
accumulated window once), the no-completion-event rule and the
read-only-over-the-domain-tables guarantee all live in the core; the
response reports how many transitions were published.
The occurrence-preview route (task 5f843564) lets the admin PWA's
Definitions edit sheet show the next dates a rule fires on WITHOUT
@@ -230,10 +198,9 @@ reimplementing the recurrence rules client-side:
``rule`` object create/edit take (:class:`AdminRuleRequest`, built
through the SAME :func:`_rule_from_request` / core ``from_dict``
validation, so a rejected rule is 422 exactly as on create), an
optional ``start_date`` (default: the household-local ``today`` —
ONE :func:`_local_now` clock read re-expressed in the configured
household ``timezone``, empty falling back to host local) and an
optional ``count`` (1..50, default 10). The dates come from ONE
optional ``start_date`` (default: the API host's local ``today``,
ONE :func:`_local_now` clock read) and an optional ``count`` (1..50,
default 10). The dates come from ONE
:func:`nestquest_core.recurrence.occurrences_between` call — the
same engine the materializer walks — so the preview can only agree
with what would be generated. The scan is BOUNDED server-side: the
@@ -271,24 +238,21 @@ deliberately narrow):
``rule_type``, a shape-missing field such as a weekly rule without
weekdays, a malformed date, a forbidden field), a bad window name or
due time, a rejected window or assignee list (empty, duplicate,
wrong-typed); a rejected presence pattern or override (a blank name,
an unknown kind, a bad cycle length, a pattern not covering the
cycle's weeks, a malformed anchor date, a malformed or
wrong-typed); a rejected presence schedule or override (bad cycle
length, a pattern not covering the cycle's weeks, a malformed or
inverted date range, an override overlapping the same child's
existing one) — is mapped to 422: the body was well-formed JSON but
semantically invalid, the same failure class Pydantic reports. The
core rejects these BEFORE any write, so a 422 never leaves a
half-applied change behind.
- A non-existent CHILD on a presence route (listing or creating a
pattern, or creating an override, for an unknown id) is mapped to 404
through the SAME :func:`_raise_child_error` the children routes use —
the message reads ``child N does not exist``. A non-existent
OVERRIDE on the delete route is mapped to 404 through
- A non-existent CHILD on a presence route (setting a schedule or
creating an override for an unknown id) is mapped to 404 through the
SAME :func:`_raise_child_error` the children routes use — the
message reads ``child N does not exist``. A non-existent OVERRIDE
on the delete route is mapped to 404 through
:func:`_raise_presence_override_error`, keyed on the
``override_id:`` prefix the core's unknown-id error carries (the
same convention as the quest-definition 404); a non-existent PATTERN
on the pattern edit/delete routes likewise through
:func:`_raise_presence_pattern_error`, keyed on ``pattern_id:``.
same convention as the quest-definition 404).
- The UNCOMPLETE route maps the core completion layer's unknown-
``instance_id`` error (prefixed ``instance_id:``, the same
convention the panel complete route keys on) to 404; every other
@@ -352,7 +316,6 @@ from pydantic import (
model_validator,
)
from api import host_zone
from api import transitions as api_transitions
from api.auth import require_admin
from api.database import DatabaseState
@@ -363,8 +326,8 @@ from api.nestquest_core import (
core_dao_children,
core_dao_rules,
core_history,
core_icons,
core_materialize,
core_presence,
core_presence_management,
core_quest_definitions,
core_recurrence,
@@ -476,19 +439,6 @@ class AdminQuestDefinitionListResponse(BaseModel):
definitions: list[AdminQuestDefinitionResponse]
class AdminQuestDefinitionDeleteResponse(BaseModel):
"""The body ``DELETE /api/v1/admin/quest-definitions/{id}`` answers.
Exactly one of ``deleted`` / ``retired`` is true. ``definition`` is
the retired (now inactive) definition, or null when it was deleted.
"""
definition_id: int
deleted: bool
retired: bool
definition: AdminQuestDefinitionResponse | None
class AdminChildCreateRequest(BaseModel):
"""The body of ``POST /api/v1/admin/children``.
@@ -572,10 +522,9 @@ class AdminOccurrencesPreviewRequest(BaseModel):
``rule`` is the SAME object create/edit take. ``start_date`` is an
optional strict ``YYYY-MM-DD`` (validated by the core; default the
household-local today in the configured ``timezone``, empty falling
back to the API host's local time). ``count`` is a strict JSON
integer in 1..``_PREVIEW_MAX_COUNT`` — anything else is 422 before
any handler code runs.
API host's today). ``count`` is a strict JSON integer in
1..``_PREVIEW_MAX_COUNT`` — anything else is 422 before any handler
code runs.
"""
rule: AdminRuleRequest
@@ -656,68 +605,35 @@ class AdminQuestDefinitionActiveRequest(BaseModel):
is_active: bool
class AdminPresencePatternCreateRequest(BaseModel):
"""The body of ``POST /api/v1/admin/children/{child_id}/presence-patterns``.
class AdminPresenceScheduleRequest(BaseModel):
"""The body of ``PUT /api/v1/admin/children/{child_id}/presence-schedule``.
The shape of :class:`~nestquest_core.presence.PresencePattern` —
The shape of :class:`~nestquest_core.presence.PresenceSchedule` —
nothing more. ``pattern`` maps each cycle week index (JSON object
keys, coerced to ints by the model) to the weekdays the pattern
covers that week (Monday=0); every week of the cycle must be
covered, which the PRESENCE MODEL enforces at construction, not
this shape — as it does the non-blank ``name`` and the
``home``/``away`` ``kind``. ``cycle_length_weeks`` and the weekday
values are strict JSON integers: ``2.0``, ``"2"`` or ``true`` is a
422, not a silent coercion.
keys, coerced to ints by the model) to that week's present weekdays
(Monday=0); every week of the cycle must be covered, which the
PRESENCE MODEL enforces at construction, not this shape. A week
with an empty list means absent every day of that week.
"""
name: str
kind: str
cycle_length_weeks: StrictInt
anchor_date: str
pattern: dict[int, list[StrictInt]]
class AdminPresencePatternEditRequest(BaseModel):
"""The body of ``PATCH /api/v1/admin/presence-patterns/{pattern_id}``.
Every field optional; only SUPPLIED fields are forwarded, and an
explicit ``null`` is forwarded too — and rejected by the model.
The pattern's child cannot be changed.
"""
name: str | None = None
kind: str | None = None
cycle_length_weeks: StrictInt | None = None
anchor_date: str | None = None
pattern: dict[int, list[StrictInt]] | None = None
class AdminPresencePatternResponse(BaseModel):
"""One presence pattern as the admin plane serializes it.
The stored row with its weekday sets decoded back through
:meth:`nestquest_core.presence.PresencePattern.decode`: each
pattern week is the sorted list of covered weekdays. The ``id`` is
the handle the PATCH and DELETE routes take.
"""
id: int
child_id: int
name: str
kind: str
cycle_length_weeks: int
anchor_date: str
pattern: dict[int, list[int]]
class AdminPresencePatternListResponse(BaseModel):
"""The ``GET /children/{child_id}/presence-patterns`` payload.
class AdminPresenceScheduleResponse(BaseModel):
"""A child's repeating presence schedule as the admin plane serializes it.
``patterns`` is empty when the child has none — the child is
present every day (Feature 05); absence is state, not an error.
The stored schedule decoded back through
:meth:`nestquest_core.presence.PresenceSchedule.decode`: each
pattern week is the sorted list of present weekdays, and the child
has exactly ONE schedule (setting again replaces it).
"""
patterns: list[AdminPresencePatternResponse]
child_id: int
cycle_length_weeks: int
anchor_date: str
pattern: dict[int, list[int]]
class AdminPresenceOverrideCreateRequest(BaseModel):
@@ -753,6 +669,16 @@ class AdminPresenceOverrideResponse(BaseModel):
note: str | None
class AdminPresenceScheduleReadResponse(BaseModel):
"""The ``GET /children/{child_id}/presence-schedule`` payload.
``schedule`` is ``None`` when the child has no schedule — the child
is present every day (Feature 05); absence is state, not an error.
"""
schedule: AdminPresenceScheduleResponse | None
class AdminPresenceOverrideListResponse(BaseModel):
"""The ``GET /presence-overrides`` payload: the matching overrides."""
@@ -909,7 +835,7 @@ class AdminSettingsResponse(BaseModel):
"""The effective settings as the admin plane serializes them.
Mirrors the core :class:`~nestquest_core.settings.NestQuestSettings`
— all ELEVEN documented fields, resolved (every absent stored field
— all TEN documented fields, resolved (every absent stored field
already fell back to its default in the core). The same shape both
the GET and the PATCH route answer with.
"""
@@ -924,14 +850,6 @@ class AdminSettingsResponse(BaseModel):
afternoon_reminder_enabled: bool
end_of_day_report_enabled: bool
celebration_enabled: bool
#: The household IANA time zone the admin stored; ``""`` means the
#: API host's local time.
timezone: str
#: The zone the API actually reads its clock in — ``timezone``, or
#: the API host's own zone when that is ``""`` (``""`` only when the
#: host's zone cannot be named). Read-only; the admin app formats
#: local time in it.
effective_timezone: str
class AdminMissedSweepResponse(BaseModel):
@@ -1071,9 +989,8 @@ def _raise_presence_override_error(error: ValueError) -> NoReturn:
``override_id:`` (an unknown id), and that one case is this route's
404. Every other ``ValueError`` — a non-integer id the path
parser's ``int`` already makes unreachable — becomes 422. The
pattern list/create and override-CREATE routes do NOT use this
mapper: their only 404 is an unknown CHILD, mapped by
:func:`_raise_child_error`.
schedule and override-CREATE routes do NOT use this mapper: their
only 404 is an unknown CHILD, mapped by :func:`_raise_child_error`.
"""
if str(error).startswith("override_id:"):
raise HTTPException(
@@ -1082,26 +999,6 @@ def _raise_presence_override_error(error: ValueError) -> NoReturn:
raise HTTPException(status_code=422, detail=str(error)) from error
#: 404 detail for a pattern id the core layer reports as non-existent.
_PRESENCE_PATTERN_NOT_FOUND_DETAIL = "Presence pattern not found"
def _raise_presence_pattern_error(error: ValueError) -> NoReturn:
"""Map a core ``ValueError`` from the pattern PATCH/DELETE routes.
Mirrors :func:`_raise_presence_override_error`: the core names a
missing pattern by prefixing its error with ``pattern_id:``, and
that one case is 404. Every other ``ValueError`` — a rejected edit
(blank name, unknown kind, bad cycle length, malformed anchor date
or pattern), each naming its field — becomes 422.
"""
if str(error).startswith("pattern_id:"):
raise HTTPException(
status_code=404, detail=_PRESENCE_PATTERN_NOT_FOUND_DETAIL
) from error
raise HTTPException(status_code=422, detail=str(error)) from error
#: 404 detail for an instance id the core layer reports as non-existent.
_QUEST_INSTANCE_NOT_FOUND_DETAIL = "Quest instance not found"
@@ -1228,26 +1125,6 @@ def _local_now() -> datetime.datetime:
return datetime.datetime.now().astimezone()
async def _household_clock(
database: object,
) -> tuple[object, datetime.datetime]:
"""Return the stored settings and ONE household-local clock read.
The API host may run UTC while the household does not, so the one
:func:`_local_now` read is re-expressed in the stored settings'
``timezone`` (:meth:`NestQuestSettings.household_now`); an unset
zone keeps the host's local time.
"""
settings = await core_settings_store.load_settings(database)
return settings, settings.household_now(_local_now())
async def _household_today(database: object) -> datetime.date:
"""Return the household-local date of ONE :func:`_household_clock` read."""
_settings, now = await _household_clock(database)
return now.date()
def _rule_from_request(rule: AdminRuleRequest) -> core_recurrence.ScheduleRule:
"""Build the core ScheduleRule from the request's ``rule`` object.
@@ -1275,7 +1152,7 @@ def _quest_definition_response(
id=bundle.definition.id,
title=bundle.definition.title,
description=bundle.definition.description,
icon=core_icons.normalize_icon_for_read(bundle.definition.icon),
icon=bundle.definition.icon,
is_active=bundle.definition.is_active,
skip_on_away=bundle.definition.skip_on_away,
rule=_rule_response(bundle.rule),
@@ -1292,20 +1169,16 @@ def _quest_definition_response(
)
def _presence_pattern_response(
record: core_presence_management.PresencePatternRecord,
) -> AdminPresencePatternResponse:
"""Serialize one stored core pattern, weekday sets decoded."""
pattern = core_presence_management.decode_pattern_record(record)
return AdminPresencePatternResponse(
id=record.id,
child_id=pattern.child_id,
name=pattern.name,
kind=pattern.kind,
cycle_length_weeks=pattern.cycle_length_weeks,
anchor_date=pattern.anchor_date.isoformat(),
def _presence_schedule_response(
schedule: core_presence.PresenceSchedule,
) -> AdminPresenceScheduleResponse:
"""Serialize one decoded core PresenceSchedule into the payload."""
return AdminPresenceScheduleResponse(
child_id=schedule.child_id,
cycle_length_weeks=schedule.cycle_length_weeks,
anchor_date=schedule.anchor_date.isoformat(),
pattern={
week: sorted(days) for week, days in pattern.pattern.items()
week: sorted(days) for week, days in schedule.pattern.items()
},
)
@@ -1566,7 +1439,7 @@ async def admin_create_quest_definition(
response_model=AdminOccurrencesPreviewResponse,
)
async def admin_preview_occurrences(
body: AdminOccurrencesPreviewRequest, request: Request
body: AdminOccurrencesPreviewRequest,
) -> AdminOccurrencesPreviewResponse:
"""Return the first ``count`` dates the supplied rule fires on.
@@ -1579,15 +1452,12 @@ async def admin_preview_occurrences(
call over the bounded window ``[start_date, start_date + 366
days]`` — ``start_date`` defaulting to ONE :func:`_local_now` clock
read — truncated to ``count``. Every core ``ValueError`` is 422
(:func:`_raise_preview_error`). The only database access is the
settings read behind the household clock.
(:func:`_raise_preview_error`). No database access.
"""
start_date = (
body.start_date
if body.start_date is not None
else (
await _household_today(request.app.state.db.database)
).isoformat()
else _local_now().date().isoformat()
)
try:
rule = _rule_from_request(body.rule)
@@ -1652,16 +1522,16 @@ async def admin_set_quest_definition_active(
body: AdminQuestDefinitionActiveRequest,
request: Request,
) -> AdminQuestDefinitionResponse:
"""Deactivate (or reactivate) a definition; it is never deleted here.
"""Deactivate (or reactivate) a definition; it is NEVER deleted.
Requires a valid admin JWT (the router's shared
:func:`~api.auth.require_admin` dependency — the ONE check; this
handler performs NO auth of its own). Thin adapter: ``is_active``
goes straight to
:func:`nestquest_core.quest_definitions.set_quest_definition_active`
— the row, rule, assignees and windows all survive, so completion
history keeps its references (the hybrid DELETE route is the only
hard-delete path, and only for a definition without history). An unknown definition id is mapped to 404
— deactivation is the only removal path (the row, rule, assignees
and windows all survive, so completion history keeps its
references). An unknown definition id is mapped to 404
(:func:`_raise_quest_definition_error`); the body model already
makes the core's real-bool check unreachable from this route.
"""
@@ -1675,174 +1545,40 @@ async def admin_set_quest_definition_active(
return _quest_definition_response(bundle)
@router.delete(
"/quest-definitions/{definition_id}",
summary="Delete a quest definition, or retire it if it has history",
response_model=AdminQuestDefinitionDeleteResponse,
@router.put(
"/children/{child_id}/presence-schedule",
summary="Set a child's repeating presence schedule",
response_model=AdminPresenceScheduleResponse,
)
async def admin_delete_quest_definition(
definition_id: int, request: Request
) -> AdminQuestDefinitionDeleteResponse:
"""Hard-delete a history-free definition; retire one with history.
Requires a valid admin JWT (the router's shared
:func:`~api.auth.require_admin` dependency — the ONE check; this
handler performs NO auth of its own). Thin adapter: the id goes
straight to
:func:`nestquest_core.quest_definitions.delete_quest_definition`,
which decides delete-vs-retire atomically in the core. An unknown
definition id is mapped to 404
(:func:`_raise_quest_definition_error`).
"""
state: DatabaseState = request.app.state.db
try:
result = await core_quest_definitions.delete_quest_definition(
state.database, definition_id
)
except ValueError as error:
_raise_quest_definition_error(error)
return AdminQuestDefinitionDeleteResponse(
definition_id=result.definition_id,
deleted=result.deleted,
retired=result.retired,
definition=(
None
if result.definition is None
else _quest_definition_response(result.definition)
),
)
@router.get(
"/children/{child_id}/presence-patterns",
summary="List a child's repeating presence patterns",
response_model=AdminPresencePatternListResponse,
)
async def admin_list_presence_patterns(
child_id: int, request: Request
) -> AdminPresencePatternListResponse:
"""Return the child's presence patterns, ordered by id.
Requires a valid admin JWT (the router's shared
:func:`~api.auth.require_admin` dependency — the ONE check; this
handler performs NO auth of its own). Thin adapter: one
:func:`nestquest_core.presence_management.list_presence_patterns`
call, each pattern serialized exactly as the POST response is; a
child without one answers ``{"patterns": []}`` (present every day).
Errors are mapped by :func:`_raise_child_error`: an unknown child
is 404.
"""
state: DatabaseState = request.app.state.db
try:
records = await core_presence_management.list_presence_patterns(
state.database, child_id
)
except ValueError as error:
_raise_child_error(error)
return AdminPresencePatternListResponse(
patterns=[_presence_pattern_response(record) for record in records]
)
@router.post(
"/children/{child_id}/presence-patterns",
summary="Add a repeating presence pattern to a child",
status_code=201,
response_model=AdminPresencePatternResponse,
)
async def admin_create_presence_pattern(
child_id: int, body: AdminPresencePatternCreateRequest, request: Request
) -> AdminPresencePatternResponse:
"""Add one repeating presence pattern to a child.
async def admin_set_presence_schedule(
child_id: int, body: AdminPresenceScheduleRequest, request: Request
) -> AdminPresenceScheduleResponse:
"""Set (upsert) a child's repeating presence schedule.
Requires a valid admin JWT (the router's shared
:func:`~api.auth.require_admin` dependency — the ONE check; this
handler performs NO auth of its own). Thin adapter: the body model
carries the shape, and the name, kind, cycle-length, anchor-date
and pattern-coverage policies all live in the
:class:`~nestquest_core.presence.PresencePattern` constructor the
core builds the pattern with; the core regenerates the child's
future instances so they track the new presence. Errors are
mapped by :func:`_raise_child_error`: an unknown child is 404, a
rejected pattern 422.
carries the shape, and the cycle-length, anchor-date and
pattern-coverage policies all live in the
:class:`~nestquest_core.presence.PresenceSchedule` constructor the
core builds the schedule with — setting again REPLACES the child's
one schedule, and the core regenerates the child's future instances
so they track the new presence. Errors are mapped by
:func:`_raise_child_error`: an unknown child is 404, a rejected
schedule 422.
"""
state: DatabaseState = request.app.state.db
try:
record = await core_presence_management.create_presence_pattern(
schedule = await core_presence_management.set_presence_schedule(
state.database,
child_id,
body.name,
body.kind,
body.cycle_length_weeks,
body.anchor_date,
body.pattern,
)
except ValueError as error:
_raise_child_error(error)
return _presence_pattern_response(record)
@router.patch(
"/presence-patterns/{pattern_id}",
summary="Edit a repeating presence pattern",
response_model=AdminPresencePatternResponse,
)
async def admin_edit_presence_pattern(
pattern_id: int, body: AdminPresencePatternEditRequest, request: Request
) -> AdminPresencePatternResponse:
"""Edit one presence pattern; only supplied fields change.
Requires a valid admin JWT (the router's shared
:func:`~api.auth.require_admin` dependency — the ONE check; this
handler performs NO auth of its own). Thin adapter: the supplied
fields are forwarded with ``exclude_unset`` semantics to
:func:`nestquest_core.presence_management.update_presence_pattern`,
which rebuilds the whole pattern through the model (an explicit
``null`` is rejected there) and regenerates the pattern's child.
Error mapping (:func:`_raise_presence_pattern_error`): an unknown
pattern id is 404; a rejected edit is 422.
"""
state: DatabaseState = request.app.state.db
try:
record = await core_presence_management.update_presence_pattern(
state.database,
pattern_id,
**body.model_dump(exclude_unset=True),
)
except ValueError as error:
_raise_presence_pattern_error(error)
return _presence_pattern_response(record)
@router.delete(
"/presence-patterns/{pattern_id}",
summary="Delete a repeating presence pattern",
)
async def admin_delete_presence_pattern(
pattern_id: int, request: Request
) -> dict[str, str]:
"""Delete one presence pattern.
Requires a valid admin JWT (the router's shared
:func:`~api.auth.require_admin` dependency — the ONE check; this
handler performs NO auth of its own). Thin adapter: the id goes
straight to
:func:`nestquest_core.presence_management.delete_presence_pattern`,
which looks the pattern up first (an unknown id is refused BEFORE
any delete), removes it and regenerates ITS child's future
instances. On success the route answers ``{"status": "ok"}``.
Error mapping (:func:`_raise_presence_pattern_error`): an unknown
pattern id is 404; every other core ``ValueError`` is 422.
"""
state: DatabaseState = request.app.state.db
try:
await core_presence_management.delete_presence_pattern(
state.database, pattern_id
)
except ValueError as error:
_raise_presence_pattern_error(error)
return {"status": "ok"}
return _presence_schedule_response(schedule)
@router.post(
@@ -1950,7 +1686,7 @@ async def admin_presence_override_consequence(
body.start_date,
body.end_date,
body.is_present,
today=await _household_today(state.database),
today=_local_now().date(),
)
)
except ValueError as error:
@@ -1958,6 +1694,39 @@ async def admin_presence_override_consequence(
return AdminPresenceOverrideConsequenceResponse(removed=removed)
@router.get(
"/children/{child_id}/presence-schedule",
summary="Read a child's repeating presence schedule",
response_model=AdminPresenceScheduleReadResponse,
)
async def admin_get_presence_schedule(
child_id: int, request: Request
) -> AdminPresenceScheduleReadResponse:
"""Return the child's presence schedule, or ``schedule: null``.
Requires a valid admin JWT (the router's shared
:func:`~api.auth.require_admin` dependency — the ONE check; this
handler performs NO auth of its own). Thin adapter: one
:func:`nestquest_core.presence_management.get_presence_schedule`
call; a stored schedule is serialized exactly as the PUT response
is, and a child without one answers ``{"schedule": null}`` (present
every day). Errors are mapped by :func:`_raise_child_error`: an
unknown child is 404.
"""
state: DatabaseState = request.app.state.db
try:
schedule = await core_presence_management.get_presence_schedule(
state.database, child_id
)
except ValueError as error:
_raise_child_error(error)
return AdminPresenceScheduleReadResponse(
schedule=(
None if schedule is None else _presence_schedule_response(schedule)
)
)
@router.get(
"/presence-overrides",
summary="List presence overrides",
@@ -2037,7 +1806,7 @@ async def admin_uncomplete_instance(
"""
state: DatabaseState = request.app.state.db
database = state.database
_settings, now = await _household_clock(database)
now = _local_now()
sub = claims.get("sub")
try:
result = await core_completion.uncomplete_instance(
@@ -2103,7 +1872,7 @@ async def admin_regenerate(
"""
state: DatabaseState = request.app.state.db
database = state.database
today = await _household_today(state.database)
today = _local_now().date()
if body.scope == "household":
end_date = today + datetime.timedelta(
@@ -2188,9 +1957,8 @@ def _settings_response(
"""Serialize one core NestQuestSettings into the documented payload.
Explicit field-by-field (not ``dataclasses.asdict``) so the payload
stays pinned to the eleven documented fields (plus the read-only
``effective_timezone``) even if the core dataclass later grows
another one.
stays pinned to the ten documented fields even if the core
dataclass later grows another one.
"""
return AdminSettingsResponse(
horizon_days=settings.horizon_days,
@@ -2203,8 +1971,6 @@ def _settings_response(
afternoon_reminder_enabled=settings.afternoon_reminder_enabled,
end_of_day_report_enabled=settings.end_of_day_report_enabled,
celebration_enabled=settings.celebration_enabled,
timezone=settings.timezone,
effective_timezone=host_zone.effective_timezone(settings.timezone),
)
@@ -2236,7 +2002,7 @@ async def admin_history_query(
``ValueError`` is 422 (:func:`_raise_history_error`).
"""
state: DatabaseState = request.app.state.db
today = await _household_today(state.database)
today = _local_now().date()
try:
rows = await core_history.query_history(
state.database, filter, start, end, today=today
@@ -2279,7 +2045,7 @@ async def admin_history_csv(
JSON route's (:func:`_raise_history_error`).
"""
state: DatabaseState = request.app.state.db
today = await _household_today(state.database)
today = _local_now().date()
try:
csv_text = await core_history.export_history_csv(
state.database, filter, start, end, today=today
@@ -2302,7 +2068,7 @@ async def admin_history_csv(
response_model=AdminSettingsResponse,
)
async def admin_get_settings(request: Request) -> AdminSettingsResponse:
"""Return the current effective settings (all eleven documented fields).
"""Return the current effective settings (all ten documented fields).
Requires a valid admin JWT (the router's shared
:func:`~api.auth.require_admin` dependency — the ONE check; this
@@ -2341,25 +2107,12 @@ async def admin_update_settings(
every value has validated — so a rejected update never changes the
stored settings. Every core ``ValueError`` is 422
(:func:`_raise_settings_error`); anything else re-raises.
The write holds the missed-sweep scheduler's ``settings_lock`` and
then tells it (:meth:`~api.scheduler.MissedSweepScheduler.settings_changed`),
so a saved ``timezone`` or ``day_rollover_time`` re-plans a sleeping
scheduler (an app without one — no lifespan — just writes).
"""
state: DatabaseState = request.app.state.db
scheduler = getattr(request.app.state, "sweep_scheduler", None)
try:
if scheduler is None:
settings = await core_settings_store.update_settings(
state.database, changes
)
else:
async with scheduler.settings_lock:
settings = await core_settings_store.update_settings(
state.database, changes
)
scheduler.settings_changed(settings)
settings = await core_settings_store.update_settings(
state.database, changes
)
except ValueError as error:
_raise_settings_error(error)
return _settings_response(settings)
@@ -2380,9 +2133,7 @@ async def admin_run_missed_sweep(
handler performs NO auth of its own). Thin adapter over the SAME
HA-free sweep policy the integration's rollover listener runs
(:mod:`nestquest_core.sweep`): ONE timezone-aware clock read
(:func:`_local_now`, re-expressed in the configured household
``timezone``; empty falls back to host local) pins the
household-local ``today``, and ONE
(:func:`_local_now`) pins the API host's local ``today``, and ONE
:func:`nestquest_core.sweep.run_missed_sweep` call does everything
else — the past-due open-instance query, the documented payload
build and the watermark update (a same-day rerun is an empty
@@ -2409,7 +2160,7 @@ async def admin_run_missed_sweep(
"""
state: DatabaseState = request.app.state.db
database = state.database
today = await _household_today(state.database)
today = _local_now().date()
try:
events = await core_sweep.run_missed_sweep(database, today=today)
except ValueError as error:
@@ -2438,9 +2189,8 @@ async def admin_snapshot(request: Request) -> AdminSnapshotResponse:
:class:`AdminSnapshotResponse`.
"""
state: DatabaseState = request.app.state.db
settings, now = await _household_clock(state.database)
snapshot = await core_snapshot.build_snapshot(
state.database, settings, now
state.database, core_settings.NestQuestSettings(), _local_now()
)
return AdminSnapshotResponse(
today_iso=snapshot.today_iso,
+9 -34
View File
@@ -8,9 +8,9 @@ this router inherits the check).
The snapshot route is a thin adapter over the bundled core: it performs
NO business logic. It reads the live database off ``app.state.db``,
resolves ONE timezone-aware ``now`` (the host clock re-expressed in the
household ``timezone`` the admin stored — the API host may run UTC
while the household does not), calls the pure
resolves ONE timezone-aware ``now`` (the API host's local time — the
API is the household's "local" host now that the domain no longer lives
inside Home Assistant), calls the pure
:func:`nestquest_core.snapshot.build_snapshot`, shapes each child's
instances through :func:`nestquest_core.snapshot.instance_payload` with
``include_missed=False`` (D-009: missed instances are OMITTED from the
@@ -21,7 +21,6 @@ panel payload), and returns the documented JSON shape:
{
"today_iso": "2026-09-22",
"cycle_day": 2,
"timezone": "Pacific/Auckland",
"children": [
{
"child_id": 1,
@@ -46,11 +45,7 @@ panel payload), and returns the documented JSON shape:
active children ``ORDER BY sort_order, id``); ``state`` is the
documented panel spelling ``open`` | ``completed`` (§1 of
design/ENTITIES-AND-SERVICES.md); ``cycle_day`` is today's 1-based day
in the first scheduled child's custody cycle (0 when no child has one);
``timezone`` is the effective application timezone — the zone the admin
stored, or the API host's own zone when none is (``""`` only when the
host's zone cannot be named; :mod:`api.host_zone`) — which the panel
cards format their visible date and clock in.
in the first scheduled child's custody cycle (0 when no child has one).
The same :class:`PanelSnapshotResponse` Pydantic model is the route's
``response_model``, so the OpenAPI document carries the shape too.
"""
@@ -68,10 +63,9 @@ from api.dependencies import require_panel_token
from api.nestquest_core import (
core_completion,
core_events,
core_settings_store,
core_settings,
core_snapshot,
)
from api import host_zone
from api import transitions as api_transitions
from api.sse import transition_event_stream
@@ -132,14 +126,12 @@ class PanelSnapshotResponse(BaseModel):
``today_iso`` anchors the payload's day; ``cycle_day`` is today's
1-based day in the first scheduled child's custody cycle (0 when no
child has a schedule); ``timezone`` is the effective application
timezone (:func:`api.host_zone.effective_timezone`); ``children`` is
in the household's sort order.
child has a schedule); ``children`` is in the household's sort
order.
"""
today_iso: str
cycle_day: int
timezone: str
children: list[PanelChildPayload]
@@ -186,21 +178,6 @@ def _local_now() -> datetime.datetime:
return datetime.datetime.now().astimezone()
async def _household_clock(
database: object,
) -> tuple[object, datetime.datetime]:
"""Return the stored settings and ONE household-local clock read.
The API host may run UTC while the household does not, so the one
:func:`_local_now` read is re-expressed in the stored settings'
``timezone`` (:meth:`NestQuestSettings.household_now`). The zone
comes from the stored settings ONLY — nothing the request carries
can change it.
"""
settings = await core_settings_store.load_settings(database)
return settings, settings.household_now(_local_now())
@router.get(
"/snapshot",
summary="Today's household snapshot",
@@ -219,14 +196,12 @@ async def panel_snapshot(request: Request) -> PanelSnapshotResponse:
:class:`PanelSnapshotResponse`.
"""
state: DatabaseState = request.app.state.db
settings, now = await _household_clock(state.database)
snapshot = await core_snapshot.build_snapshot(
state.database, settings, now
state.database, core_settings.NestQuestSettings(), _local_now()
)
return PanelSnapshotResponse(
today_iso=snapshot.today_iso,
cycle_day=snapshot.cycle_day,
timezone=host_zone.effective_timezone(snapshot.timezone),
children=[
PanelChildPayload(
child_id=child.child_id,
@@ -307,7 +282,7 @@ async def panel_complete_instance(
detail="Quest instance not found for this child",
)
_settings, now = await _household_clock(database)
now = _local_now()
try:
result = await core_completion.complete_instance(
database,
+23 -155
View File
@@ -8,33 +8,10 @@ configured ``day_rollover_time`` — read fresh from the settings store
at the top of EVERY cycle, so an admin's settings change applies on
the next scheduling decision without a restart — then runs the
HA-free core's :func:`nestquest_core.sweep.run_missed_sweep` for the
household-local date (the stored ``timezone`` setting; the API host's
local date when unset) and publishes each returned
API host's local date and publishes each returned
``nestquest_quest_missed`` event on the app's ONE transition publisher
(the same SSE stream every route publishes through).
A household zone changed while the loop is asleep
must not leave it waiting for the OLD zone's rollover (a UTC host would
otherwise sweep at UTC midnight — 20:00 in New York — marking quests
missed hours early). :meth:`MissedSweepScheduler.settings_changed`
wakes the sleeping loop to re-plan whenever the zone or rollover time
it planned with has moved, and the loop re-reads the settings before
sweeping and re-plans instead if they no longer match its plan.
Guarantee: no sweep runs for a plan a committed settings write has
replaced. The settings writer — the admin ``PATCH /api/v1/admin/settings``
route, the only one — holds :attr:`MissedSweepScheduler.settings_lock`
across its write AND its :meth:`~MissedSweepScheduler.settings_changed`
call; the loop holds the same lock across its plan read (read, record
the plan, clear the wake flag) and across the pre-sweep re-read plus
the sweep itself. So a write commits either before a plan read
(which then sees it), after one (``settings_changed`` compares against
that exact plan and wakes the wait), or after the sweep — never between
a read and what the loop does with it. The lock is never held across
the wait, and the loop takes nothing else before it, so a waiting
writer cannot deadlock: it is delayed at most by one settings
read or one sweep.
All sweep policy lives in the core (the watermark, the
``[watermark, today)`` window, the no-completion-event rule): this
scheduler only decides WHEN. A same-night rerun — e.g. two workers,
@@ -66,56 +43,19 @@ LOGGER = logging.getLogger(__name__)
_RETRY_BACKOFF_SECONDS = 60.0
#: Upper bound on the minute-by-minute search past a nonexistent wall
#: time; real DST gaps are an hour, the largest ever skipped a day.
_MAX_GAP_MINUTES = 2 * 24 * 60
def _resolve_wall_time(
day: datetime.date, target: datetime.time, zone: datetime.tzinfo
) -> datetime.datetime:
"""The aware instant ``target`` (``HH:MM``) names on ``day`` in ``zone``.
A nonexistent wall time (inside a spring-forward gap) resolves to
the first valid wall minute at/after it — the gap's end, e.g. 02:30
on a 02:00→03:00 day becomes 03:00. An ambiguous wall time (the
repeated fall-back hour) resolves to its FIRST occurrence
(``fold=0``).
"""
wall = datetime.datetime.combine(
day, datetime.time(target.hour, target.minute)
)
for _ in range(_MAX_GAP_MINUTES):
candidate = wall.replace(tzinfo=zone)
round_trip = candidate.astimezone(datetime.timezone.utc).astimezone(
zone
)
if round_trip.replace(tzinfo=None) == wall:
return candidate
wall += datetime.timedelta(minutes=1)
raise ValueError(f"no valid wall time at/after {target} on {day}")
def _delay_seconds(target: datetime.time, now: datetime.datetime) -> float:
"""Real seconds from ``now`` until the next occurrence of ``target``.
"""Seconds from ``now`` until the next occurrence of ``target``.
``target`` is a plain ``HH:MM`` household time of day, resolved in
``now``'s zone by :func:`_resolve_wall_time` (nonexistent → first
valid instant after the gap; ambiguous → first occurrence). The
result is the next such instant strictly AFTER ``now`` (an equal
time schedules for tomorrow, so the just-run sweep is never
instantly re-run). Both instants are compared and subtracted in
UTC: same-``tzinfo`` aware arithmetic is wall-clock arithmetic and
would be an hour off across a DST transition.
``target`` is a plain ``HH:MM`` time of day: the next wall-clock
occurrence strictly AFTER ``now`` (an equal time schedules for
tomorrow, so the just-run sweep is never instantly re-run).
"""
now_utc = now.astimezone(datetime.timezone.utc)
day = now.date()
while True:
scheduled = _resolve_wall_time(day, target, now.tzinfo)
scheduled_utc = scheduled.astimezone(datetime.timezone.utc)
if scheduled_utc > now_utc:
return (scheduled_utc - now_utc).total_seconds()
day += datetime.timedelta(days=1)
scheduled = now.replace(
hour=target.hour, minute=target.minute, second=0, microsecond=0
)
if scheduled <= now:
scheduled += datetime.timedelta(days=1)
return (scheduled - now).total_seconds()
class MissedSweepScheduler:
@@ -146,14 +86,6 @@ class MissedSweepScheduler:
)
self._sleep = sleep if sleep is not None else asyncio.sleep
self._task: asyncio.Task | None = None
#: ``(timezone, day_rollover_time)`` the pending sweep was
#: planned with; ``None`` until the first plan.
self._planned: tuple[str, str] | None = None
#: Set by :meth:`settings_changed` to cut the current wait short.
self._wake = asyncio.Event()
#: Serialises settings writes with planning and sweeping (see
#: the module docstring's guarantee).
self.settings_lock = asyncio.Lock()
def start(self) -> None:
"""Start the background loop (idempotent: a running one stays)."""
@@ -172,20 +104,6 @@ class MissedSweepScheduler:
pass
self._task = None
def settings_changed(self, settings: object) -> None:
"""Re-plan the pending sweep if ``settings`` moved its rollover.
Called with freshly stored settings (e.g. an admin's zone
change), with :attr:`settings_lock` held across the write
and this call so the comparison is against the loop's current
plan, never a read still in flight. A differing ``timezone`` or
``day_rollover_time`` wakes the sleeping loop, which reloads the
settings and schedules the next sweep for the new household
rollover; an unchanged plan is left sleeping.
"""
if (settings.timezone, settings.day_rollover_time) != self._planned:
self._wake.set()
@property
def running(self) -> bool:
"""Whether the background loop task is alive."""
@@ -195,18 +113,12 @@ class MissedSweepScheduler:
"""Schedule → sweep → repeat, forever (until cancelled)."""
while True:
try:
# Under the lock no settings write can commit between this read
# and the recorded plan, so any later one wakes the wait.
async with self.settings_lock:
self._wake.clear()
settings = await core_settings_store.load_settings(
self._database
)
rollover = datetime.time.fromisoformat(
settings.day_rollover_time
)
plan = (settings.timezone, settings.day_rollover_time)
self._planned = plan
settings = await core_settings_store.load_settings(
self._database
)
rollover = datetime.time.fromisoformat(
settings.day_rollover_time
)
except Exception:
# Not silent: the failure is logged and retried after
# the backoff, so one bad settings document or a
@@ -218,40 +130,19 @@ class MissedSweepScheduler:
)
await self._sleep(_RETRY_BACKOFF_SECONDS)
continue
# The host may run UTC: the rollover is a household wall-clock
# time, so the clock read is re-expressed in the stored zone.
delay = _delay_seconds(
rollover, settings.household_now(self._clock())
)
delay = _delay_seconds(rollover, self._clock())
LOGGER.info(
"NestQuest missed sweep scheduled for %s (%.0fs from now)",
settings.day_rollover_time,
delay,
)
await self._sleep(delay)
try:
if not await self._sleep_unless_woken(delay):
continue
# Re-read before sweeping: a zone or rollover change the
# wake-up missed means this is not the household's
# rollover any more, so re-plan instead of sweeping. The
# lock keeps a settings write from committing between this
# check and the sweep.
async with self.settings_lock:
settings = await core_settings_store.load_settings(
self._database
)
if (
settings.timezone,
settings.day_rollover_time,
) != plan:
continue
await self._run_once(
settings.household_now(self._clock()).date()
)
await self._run_once(self._clock().date())
except Exception:
# Not silent either: a failed wait or sweep is logged and
# the loop backs off before the next cycle, whose
# watermark re-read makes an already-swept day a no-op.
# Not silent either: the sweep error is logged and the
# loop backs off before the next cycle, whose watermark
# re-read makes an already-swept day a no-op.
LOGGER.exception(
"NestQuest scheduled missed sweep failed; retrying in "
"%gs",
@@ -259,29 +150,6 @@ class MissedSweepScheduler:
)
await self._sleep(_RETRY_BACKOFF_SECONDS)
async def _sleep_unless_woken(self, delay: float) -> bool:
"""Wait ``delay``; ``False`` if :meth:`settings_changed` woke it.
Both children are cancelled AND awaited before returning (or
before a cancellation propagates), so none outlives :meth:`stop`;
a sleep that failed re-raises its exception here for the loop's
retry policy.
"""
sleeper = asyncio.ensure_future(self._sleep(delay))
waker = asyncio.ensure_future(self._wake.wait())
try:
await asyncio.wait(
{sleeper, waker}, return_when=asyncio.FIRST_COMPLETED
)
finally:
slept = sleeper.done()
sleeper.cancel()
waker.cancel()
await asyncio.gather(sleeper, waker, return_exceptions=True)
if slept:
sleeper.result()
return slept
async def _run_once(self, today: datetime.date) -> None:
"""Run ONE sweep for ``today`` and publish what it built.
+8 -32
View File
@@ -16,11 +16,9 @@ network and NO aiohttp installed; production builds the client through
:func:`client_from_entry`, which hands in Home Assistant's shared
aiohttp session (``homeassistant.helpers.aiohttp_client
.async_get_clientsession``). The module itself imports NEITHER
homeassistant NOR aiohttp at module import (aiohttp appears only
behind ``TYPE_CHECKING`` for annotations, plus one lazy import inside
:meth:`NestQuestApiClient.stream_events` for its ``ClientTimeout``), so
the client is importable anywhere — the HA coupling lives in the one
production factory.
homeassistant NOR aiohttp at runtime (aiohttp appears only behind
``TYPE_CHECKING`` for annotations), so the client is usable anywhere —
the HA coupling lives in the one production factory.
Every failure is typed: a transport failure (connection refused, DNS
failure, timeout — the exchange never produced a response) and every
@@ -40,11 +38,7 @@ frame (``event: <type>`` / ``data: <json>`` lines separated by a blank
line). Opening the stream gets the same one-timeout, typed-error
contract as every other call; reading it has NO body-wide timeout (a
healthy stream is long-lived — the subscription manager owns
reconnection and backoff). That includes the session's own default:
Home Assistant's shared session carries ``ClientTimeout(total=300)``,
which would cut a healthy stream every five minutes, so the stream
request overrides it with ``total=None`` (keeping a finite
``sock_connect``).
reconnection and backoff).
"""
from __future__ import annotations
@@ -223,10 +217,6 @@ class NestQuestApiClient:
self._session = session
self._timeout_seconds = float(timeout_seconds)
def _headers(self) -> dict[str, str]:
"""The Bearer credential every panel-plane request carries."""
return {"Authorization": f"Bearer {self._panel_token}"}
async def get_snapshot(self) -> dict[str, Any]:
"""Fetch and parse today's household snapshot.
@@ -284,19 +274,8 @@ class NestQuestApiClient:
(``aclose``, i.e. the consumer's task being cancelled) stops
cleanly and closes the underlying response in every path.
"""
# Lazy: aiohttp ships with Home Assistant, but importing it at
# module level would make the client unimportable without it.
import aiohttp
url = f"{self._base_url}{EVENTS_PATH}"
headers = self._headers()
# The session's default total timeout (HA's shared session:
# 300 s) would cut a healthy stream mid-body, and events fired
# while reconnecting are not replayed — so the stream request
# is unbounded in total time; only connecting stays bounded.
stream_timeout = aiohttp.ClientTimeout(
total=None, sock_connect=self._timeout_seconds
)
headers = {"Authorization": f"Bearer {self._panel_token}"}
# Opening the response gets ONE request timeout, exactly like
# ``_request_json``; the read loop below runs WITHOUT one — a
# body-wide timeout would kill a healthy long-lived stream.
@@ -306,7 +285,7 @@ class NestQuestApiClient:
try:
async with asyncio.timeout(self._timeout_seconds):
stream_cm = self._session.request(
"GET", url, headers=headers, json=None, timeout=stream_timeout
"GET", url, headers=headers, json=None
)
response = await stream_cm.__aenter__()
except asyncio.CancelledError:
@@ -332,10 +311,7 @@ class NestQuestApiClient:
event_type: str | None = None
data_lines: list[str] = []
buffer = ""
# The body is ``response.content`` (aiohttp's StreamReader,
# yielding bytes); the response object itself — HA's
# ``HassClientResponse`` included — is NOT async-iterable.
async for chunk in response.content:
async for chunk in response:
if isinstance(chunk, (bytes, bytearray)):
chunk = chunk.decode("utf-8")
buffer += chunk
@@ -403,7 +379,7 @@ class NestQuestApiClient:
raises typed too, carrying the status it arrived with.
"""
url = f"{self._base_url}{path}"
headers = self._headers()
headers = {"Authorization": f"Bearer {self._panel_token}"}
try:
async with asyncio.timeout(self._timeout_seconds):
async with self._session.request(
+1 -1
View File
@@ -9,7 +9,7 @@ snapshot (the same ChildDaySnapshot the day sensors read):
celebration automation must never fire on an empty day (the
day-complete event carries the same rule, Feature 10 task 7).
- ``binary_sensor.nestquest_<child>_present_today`` — ON when the
presence engine resolves the child present on the household-local date
presence engine resolves the child present on the HA-local date
(schedules and overrides, D-004 anchor-date arithmetic).
Naming and registry identity follow the day sensors' contract: names
@@ -1,96 +0,0 @@
blueprint:
name: NestQuest UniFi quest access
description: >-
One automation per child. Completely block the selected UniFi clients
after the local weekday/weekend cutoff while that child has quests
remaining TODAY. Restore network access immediately when the count
reaches zero, and at midnight even if yesterday was incomplete.
A missing or unavailable quest sensor is treated as still open after
the cutoff; verify the sensor before enabling this automation. The
selected UniFi client switches are ON when access is allowed and
OFF when blocked. Do not select infrastructure or adult devices.
domain: automation
input:
remaining_sensor:
name: Child's quests remaining today
description: Select this child's NestQuest quests remaining today sensor.
selector:
entity:
filter:
- integration: nestquest
domain: sensor
client_switches:
name: Child's UniFi client access switches
description: >-
Select every UniFi client access switch for this child. These
switches are ON when network access is allowed and OFF when blocked.
selector:
entity:
multiple: true
filter:
- integration: unifi
domain: switch
weekday_cutoff:
name: Monday-Friday cutoff
default: "18:25:00"
selector:
time: {}
weekend_cutoff:
name: Saturday-Sunday cutoff
default: "14:00:00"
selector:
time: {}
mode: restart
variables:
remaining_sensor: !input remaining_sensor
client_switches: !input client_switches
weekday_cutoff: !input weekday_cutoff
weekend_cutoff: !input weekend_cutoff
triggers:
- trigger: state
entity_id: !input remaining_sensor
- trigger: time
at: !input weekday_cutoff
- trigger: time
at: !input weekend_cutoff
- trigger: time
at: "00:00:00"
- trigger: homeassistant
event: start
# Reconcile after missed events or a temporary UniFi outage.
- trigger: time_pattern
minutes: "/5"
conditions:
- condition: template
value_template: "{{ client_switches | count > 0 }}"
actions:
- variables:
should_block: >-
{{ now().strftime('%H:%M') >=
(weekday_cutoff[:5] if now().weekday() < 5 else weekend_cutoff[:5])
and (states(remaining_sensor) | int(-1)) != 0 }}
- repeat:
for_each: "{{ client_switches }}"
sequence:
- choose:
- conditions:
- condition: template
value_template: >-
{{ should_block | bool and is_state(repeat.item, 'on') }}
sequence:
- action: switch.turn_off
target:
entity_id: "{{ repeat.item }}"
- conditions:
- condition: template
value_template: >-
{{ not (should_block | bool) and is_state(repeat.item, 'off') }}
sequence:
- action: switch.turn_on
target:
entity_id: "{{ repeat.item }}"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 191 KiB

@@ -111,9 +111,6 @@ def snapshot_from_api_payload(payload: dict[str, Any]) -> NestQuestSnapshot:
through verbatim;
- ``present`` and ``next_present`` pass through verbatim (the API
resolved them through the same presence engine server-side);
- ``timezone`` (the API's effective application timezone) passes
through verbatim for the cards' date and clock; an API older than
the field omits it, which reads as ``""`` (the cards' fallback);
- the instance list is rebuilt IN ORDER, so the panel payload the
sensors emit matches the route's order byte for byte.
@@ -164,7 +161,6 @@ def snapshot_from_api_payload(payload: dict[str, Any]) -> NestQuestSnapshot:
today_iso=payload["today_iso"],
children=tuple(children),
cycle_day=payload["cycle_day"],
timezone=payload.get("timezone", ""),
)
+11 -11
View File
@@ -10,7 +10,7 @@ un-completing (no-op if already open) is :func:`uncomplete_instance`.
Instance current state is derived from the latest event via
:func:`instance_state` (``open`` / ``done`` / ``missed``); there is
no status column. ``missed`` is derived for past-due open instances
(``due_date`` before household-local ``today``) and is never stored as an
(``due_date`` before HA-local ``today``) and is never stored as an
event_type.
Actor policy matches the schema CHECKs (D-008): ``actor_source`` is
@@ -71,10 +71,10 @@ def _completion_moment(
now: datetime.datetime | None,
today: datetime.date | None,
) -> tuple[datetime.date, datetime.time | None]:
"""Return the household-local completion date and optional wall-clock time.
"""Return the HA-local completion date and optional wall-clock time.
``today`` is the household-local calendar date when threaded (Feature 07
style). ``now`` is a timezone-aware household-local datetime; its wall
``today`` is the HA-local calendar date when threaded (Feature 07
style). ``now`` is a timezone-aware HA-local datetime; its wall
clock is used as-is and is never converted to UTC. When ``today``
is omitted the date comes from ``now``. When both are omitted the
host calendar date is the Feature 07 fallback — never the UTC
@@ -98,7 +98,7 @@ def _completion_moment(
def _resolve_today(today: datetime.date | None) -> datetime.date:
"""Return the threaded household-local date, or the host calendar date."""
"""Return the threaded HA-local date, or the host calendar date."""
if today is None:
return datetime.date.today()
return today
@@ -138,7 +138,7 @@ def derive_state(
Thin wrapper over :func:`_derived_state`: ``open``, ``done``, or
``missed`` from the latest event plus the due date (``missed`` is
derived, never an event_type). ``today`` is the caller-resolved
household-local date.
HA-local date.
"""
return _derived_state(instance, latest, today)
@@ -345,7 +345,7 @@ async def instance_state(
"""Return ``open``, ``done``, or ``missed`` from the latest event.
No events, or a latest event of uncompleted, is ``open`` unless
``due_date`` is before ``today`` (household-local, threaded), in which
``due_date`` is before ``today`` (HA-local, threaded), in which
case it is ``missed``. A latest event of completed is ``done``
even when past due. ``missed`` is never stored as an event_type.
Unknown ``instance_id`` raises ValueError naming the field.
@@ -414,9 +414,9 @@ async def complete_instance(
latest-event, and the append run under one connection lock so a
concurrent complete cannot double-append.
``was_on_time`` is computed from the household-local completion moment
``was_on_time`` is computed from the HA-local completion moment
(threaded ``now`` / ``today``) against the instance ``due_date``
and optional ``due_time``. ``now`` is the timezone-aware household-local
and optional ``due_time``. ``now`` is the timezone-aware HA-local
datetime; its wall clock is never converted to UTC. Same-day
``due_time`` comparison requires ``now``.
"""
@@ -471,7 +471,7 @@ async def uncomplete_instance(
"""Append an uncompleted event unless the instance is already open.
Returns the derived state ``open``, or ``missed`` when the instance
is past due (``due_date`` before household-local ``today``); ``appended``
is past due (``due_date`` before HA-local ``today``); ``appended``
reports whether THIS call appended (False on an already-open
no-op). Unknown ``instance_id`` raises ValueError naming the
field. Existence, latest-event, and the append run under one
@@ -529,7 +529,7 @@ async def list_missed_for_child(
"""Return the child's missed instances due in the closed date range.
Missed means the latest event state is open and ``due_date`` is
before ``today`` (household-local, threaded). Uses
before ``today`` (HA-local, threaded). Uses
:meth:`QuestInstancesDao.list_by_date_range` plus derived state.
Never appends a missed event. Instances and latest events are
read inside the connection lock so the list is one snapshot.
-11
View File
@@ -112,17 +112,6 @@ CONF_AFTERNOON_REMINDER_ENABLED = "afternoon_reminder_enabled"
CONF_END_OF_DAY_REPORT_ENABLED = "end_of_day_report_enabled"
CONF_CELEBRATION_ENABLED = "celebration_enabled"
DEFAULT_AUTOMATION_ENABLED = True
# The household's IANA time zone (e.g. ``America/New_York``) the API
# service reads its clock in. The empty string is the API host's own
# local time. Only an admin sets it (manually, from the admin app);
# nothing sets it automatically. The integration relays the API's
# effective application timezone (the coordinator carries it and the
# household sensor publishes it for the panel cards) and never derives
# the application clock from Home Assistant's configuration; the Home
# Assistant / browser zone applies only when the API publishes no zone
# (e.g. an older API).
CONF_TIMEZONE = "timezone"
DEFAULT_TIMEZONE = ""
# Panel-plane API client (Feature 18): the integration reaches the
# NestQuest API service (Feature 16) over HTTP instead of the database.
@@ -68,7 +68,7 @@ def _resolve_today(today: datetime.date | None) -> datetime.date:
around midnight, so when the caller has already resolved the local
date (``today``) that anchor is authoritative; ``None`` falls back to
the host clock (:func:`_today`), which is exactly the previous
behavior for callers with no household-local date.
behavior for callers with no HA-local date.
"""
return _today() if today is None else today
@@ -225,7 +225,7 @@ class QuestInstancesDao:
- ``due_date`` must be TODAY or later: instances are never
generated in the past (Feature 07). The caller's
materialization horizon is future-dated by definition.
``today`` optionally pins the resolved household-local date the
``today`` optionally pins the resolved HA-local date the
guard compares against (falling back to the host clock when
omitted) so a household time zone behind the host around
midnight is not misread as "past".
@@ -248,7 +248,7 @@ class QuestInstancesDao:
# check runs after the lock is acquired, because a caller can
# wait on the lock across midnight — a date that was "today"
# at call time may be "yesterday" by the time the INSERT runs.
# A caller-supplied ``today`` (household-local) is used for BOTH
# A caller-supplied ``today`` (HA-local) is used for BOTH
# checks and never re-read, since it is already the anchor the
# batch runs against.
today_date = _resolve_today(today)
@@ -257,7 +257,7 @@ class QuestInstancesDao:
async with self._database.transaction():
# Re-read "today" under the lock: this is the date the
# insert actually executes on, so the no-past rule
# holds across midnight rollovers. A pinned household-local
# holds across midnight rollovers. A pinned HA-local
# anchor is exempt from the re-read (see above).
if today is None:
today_date = _today()
@@ -364,7 +364,7 @@ class QuestInstancesDao:
rather than raising, so the rest of the batch is unaffected. The
no-past rule (instances are never generated in the past) is
preserved from :meth:`upsert` and still raises ValueError; ``today``
optionally pins the household-local anchor it compares against. An
optionally pins the HA-local anchor it compares against. An
instance that ALREADY has a completion event is also skipped
(returns ``None``) rather than raised: it is immutable, so the
walk leaves it untouched instead of failing the batch — the
@@ -504,7 +504,7 @@ class QuestInstancesDao:
append-only contract: an instance that was ever completed is
never reported missed, even when later reversed — history keeps
both rows and the sweep never mutates any). The watermark is
the household-local date the sweep last ran, and the window is
the HA-local date the sweep last ran, and the window is
``[watermark, today)``: the nightly run entering day D+1 sweeps
exactly day D's instances, so every day's quests are announced
once — at the midnight after their due date — and a same-night
@@ -544,10 +544,9 @@ class QuestInstancesDao:
rolling horizon from now), so a caller cannot use this to
rewrite past open instances either — the day-rollover missed
sweep (Feature 11) handles past-due instances instead. ``today``
optionally pins the household-local anchor the clamp compares
against (falling back to the host clock when omitted). Any
instance with a completion event is never touched, regardless of
its date.
optionally pins the HA-local anchor the clamp compares against
(falling back to the host clock when omitted). Any instance with
a completion event is never touched, regardless of its date.
Returns the number deleted.
"""
_validate_date(cutoff_date, "cutoff_date")
@@ -582,9 +581,8 @@ class QuestInstancesDao:
one transaction — an instance that gains a completion event
mid-flight cannot be deleted. The cutoff cannot be backdated below
today, for the same reason as the definition-scoped method (see its
docstring). ``today`` optionally pins the household-local anchor
the clamp compares against (falling back to the host clock when
omitted).
docstring). ``today`` optionally pins the HA-local anchor the clamp
compares against (falling back to the host clock when omitted).
Any instance with a completion event is never touched, regardless
of its date.
+74 -123
View File
@@ -1,4 +1,4 @@
"""Typed DAO layer for the presence_patterns and presence_overrides tables.
"""Typed DAO layer for the presence_schedules and presence_overrides tables.
All SQL for these tables lives in this module per the feature
guardrails: callers get typed dataclasses back and never see raw rows
@@ -8,12 +8,11 @@ executor and the event loop never blocks.
Semantics per the done-condition and Feature 05:
- A child has ZERO OR MORE presence patterns (schema 9 — no UNIQUE on
``child_id``); each is created, updated and deleted by its own id.
- A child with NO pattern row is present every day — the absence of a
row is meaningful state, expressed by
:meth:`PresencePatternsDao.list_by_child` returning an empty list,
never by an empty pattern row.
- A child has AT MOST ONE presence schedule (schema UNIQUE); upserting
by child updates the existing row rather than raising.
- A child with NO schedule row is present every day — the absence of a
row is meaningful state, expressed by :meth:`PresenceSchedulesDao.get_by_child`
returning None, never by an empty pattern row.
- Overrides beat the pattern for their date range (that resolution is
the presence engine's job, Feature 05); the DAO only stores and
lists them. A single-day override stores the same date as both
@@ -33,13 +32,11 @@ from .db import NestQuestDatabase
@dataclass(frozen=True)
class PresencePatternRecord:
"""One row of ``presence_patterns``."""
class PresenceScheduleRecord:
"""One row of ``presence_schedules``."""
id: int
child_id: int
name: str
kind: str
cycle_length_weeks: int
anchor_date: str
pattern: str
@@ -57,23 +54,21 @@ class PresenceOverrideRecord:
note: str | None
_PATTERN_COLUMNS = (
"id, child_id, name, kind, cycle_length_weeks, anchor_date, pattern"
_SCHEDULE_COLUMNS = (
"id, child_id, cycle_length_weeks, anchor_date, pattern"
)
_OVERRIDE_COLUMNS = (
"id, child_id, start_date, end_date, is_present, note"
)
def _pattern_from_row(row: tuple) -> PresencePatternRecord:
return PresencePatternRecord(
def _schedule_from_row(row: tuple) -> PresenceScheduleRecord:
return PresenceScheduleRecord(
id=row[0],
child_id=row[1],
name=row[2],
kind=row[3],
cycle_length_weeks=row[4],
anchor_date=row[5],
pattern=row[6],
cycle_length_weeks=row[2],
anchor_date=row[3],
pattern=row[4],
)
@@ -88,27 +83,29 @@ def _override_from_row(row: tuple) -> PresenceOverrideRecord:
)
class PresencePatternsDao:
"""Typed async access to the ``presence_patterns`` table."""
class PresenceSchedulesDao:
"""Typed async access to the ``presence_schedules`` table."""
def __init__(self, database: NestQuestDatabase) -> None:
self._database = database
async def create(
async def upsert_by_child(
self,
child_id: int,
name: str,
kind: str,
cycle_length_weeks: int,
anchor_date: str,
pattern: str,
) -> PresencePatternRecord:
"""Insert one pattern for the child and return it as stored.
) -> PresenceScheduleRecord:
"""Set the child's presence schedule, replacing any existing one.
The child must exist (FK) — validated atomically under the
connection lock so a deleted child cannot pass a stale check.
``kind``, the cycle length and the pattern shape (segment count
= ``cycle_length_weeks``) are enforced by the schema CHECKs.
Upsert semantics are the done-condition: a second schedule for
the same child updates the existing row rather than raising.
Runs under the connection lock so a concurrent upsert/delete
for the same child serializes instead of colliding on the
schema's UNIQUE(child_id). Pattern validity (segment shape,
segment count = cycle_length_weeks) is enforced by the schema
CHECKs; the child must exist (FK) — validated atomically here
so a deleted child cannot pass a stale check.
"""
_validate_date(anchor_date, "anchor_date")
async with _connection_lock(self._database):
@@ -118,98 +115,53 @@ class PresencePatternsDao:
)
if child is None:
raise ValueError(f"child {child_id} does not exist")
result = await self._database.execute(
"INSERT INTO presence_patterns (child_id, name, kind, "
await self._database.execute(
"INSERT INTO presence_schedules (child_id, "
"cycle_length_weeks, anchor_date, pattern) "
"VALUES (?, ?, ?, ?, ?, ?)",
(
child_id,
name,
kind,
cycle_length_weeks,
anchor_date,
pattern,
),
"VALUES (?, ?, ?, ?) "
"ON CONFLICT (child_id) DO UPDATE SET "
"cycle_length_weeks = excluded.cycle_length_weeks, "
"anchor_date = excluded.anchor_date, "
"pattern = excluded.pattern",
(child_id, cycle_length_weeks, anchor_date, pattern),
)
record = await self.get(result.lastrowid)
assert record is not None
return record
schedule = await self.get_by_child(child_id)
assert schedule is not None
return schedule
async def list_by_child(self, child_id: int) -> list[PresencePatternRecord]:
"""Return the child's patterns ordered by id; empty when none.
async def get_by_child(
self, child_id: int
) -> PresenceScheduleRecord | None:
"""Return the child's schedule, or None when the child has none.
An empty list is meaningful and UNAMBIGUOUS here: the child
exists and has no pattern row, i.e. the child is present every
day (Feature 05 guardrail). An unknown child id raises
ValueError instead of returning an empty list, because
"nonexistent child" must never be silently read as "present
every day".
None is meaningful and UNAMBIGUOUS here: the child exists and
has no schedule row, i.e. the child is present every day
(Feature 05 guardrail). An unknown child id raises ValueError
instead of returning None, because "nonexistent child" must
never be silently read as "present every day".
"""
child = await self._database.fetch_one(
"SELECT 1 FROM children WHERE id = ?", (child_id,)
)
if child is None:
raise ValueError(f"child {child_id} does not exist")
rows = await self._database.fetch_all(
f"SELECT {_PATTERN_COLUMNS} FROM presence_patterns "
"WHERE child_id = ? ORDER BY id",
row = await self._database.fetch_one(
f"SELECT {_SCHEDULE_COLUMNS} FROM presence_schedules "
"WHERE child_id = ?",
(child_id,),
)
return [_pattern_from_row(row) for row in rows]
return _schedule_from_row(row) if row is not None else None
async def get(self, pattern_id: int) -> PresencePatternRecord | None:
"""Return one pattern by id, or None when it does not exist."""
row = await self._database.fetch_one(
f"SELECT {_PATTERN_COLUMNS} FROM presence_patterns WHERE id = ?",
(pattern_id,),
)
return _pattern_from_row(row) if row is not None else None
async def delete(self, child_id: int) -> bool:
"""Remove the child's schedule; True if a row was removed.
async def update(
self,
pattern_id: int,
name: str,
kind: str,
cycle_length_weeks: int,
anchor_date: str,
pattern: str,
) -> PresencePatternRecord | None:
"""Replace one pattern's fields; None when the id does not exist.
Every column but ``id`` and ``child_id`` is rewritten — a
pattern never moves to another child. The schema CHECKs apply
exactly as on :meth:`create`.
"""
_validate_date(anchor_date, "anchor_date")
async with _connection_lock(self._database):
async with self._database.transaction():
result = await self._database.execute(
"UPDATE presence_patterns SET name = ?, kind = ?, "
"cycle_length_weeks = ?, anchor_date = ?, pattern = ? "
"WHERE id = ?",
(
name,
kind,
cycle_length_weeks,
anchor_date,
pattern,
pattern_id,
),
)
if result.rowcount == 0:
return None
record = await self.get(pattern_id)
return record
async def delete(self, pattern_id: int) -> bool:
"""Remove one pattern by id; True if a row was removed.
Deleting a child's last pattern leaves it present every day (no
row means no restriction).
After deletion the child is present every day (no row means
no restriction). Deleting a schedule the child never had
returns False.
"""
result = await self._database.execute(
"DELETE FROM presence_patterns WHERE id = ?",
(pattern_id,),
"DELETE FROM presence_schedules WHERE child_id = ?",
(child_id,),
)
return result.rowcount > 0
@@ -393,23 +345,22 @@ async def read_snapshot_unlocked(
range_start: str,
range_end: str,
) -> tuple[
dict[int, list[PresencePatternRecord]],
dict[int, PresenceScheduleRecord],
dict[int, list[PresenceOverrideRecord]],
]:
"""Read patterns and overrides for ``child_ids`` WITHOUT locking.
"""Read schedules and overrides for ``child_ids`` WITHOUT locking.
MUST be called inside the connection lock and an open transaction, so
the patterns and overrides returned here stay coherent with every
the schedules and overrides returned here stay coherent with every
other table the caller reads inside that same transaction (the
materialization walk's single input snapshot does exactly that). The
date range comes already validated by the caller.
Returns ``(patterns, overrides)``:
Returns ``(schedules, overrides)``:
- ``patterns`` maps ``child_id`` to its :class:`PresencePatternRecord`
list (ordered by id) for every child that HAS a pattern row. A
child absent from the mapping has no pattern, i.e. is present
every day (Feature 05).
- ``schedules`` maps ``child_id`` to its :class:`PresenceScheduleRecord`
for every child that HAS a schedule row. A child absent from the
mapping has no schedule, i.e. is present every day (Feature 05).
- ``overrides`` maps ``child_id`` to that child's overrides overlapping
``[range_start, range_end]`` (inclusive boundaries), ordered by start
date; a child with no matching override is absent from the mapping.
@@ -421,9 +372,9 @@ async def read_snapshot_unlocked(
if not children:
return {}, {}
placeholders = ",".join("?" for _ in children)
pattern_rows = await database.fetch_all(
f"SELECT {_PATTERN_COLUMNS} FROM presence_patterns "
f"WHERE child_id IN ({placeholders}) ORDER BY id",
schedule_rows = await database.fetch_all(
f"SELECT {_SCHEDULE_COLUMNS} FROM presence_schedules "
f"WHERE child_id IN ({placeholders})",
tuple(children),
)
override_rows = await database.fetch_all(
@@ -432,12 +383,12 @@ async def read_snapshot_unlocked(
"AND start_date <= ? ORDER BY start_date",
tuple(children) + (range_start, range_end),
)
patterns: dict[int, list[PresencePatternRecord]] = {}
for row in pattern_rows:
record = _pattern_from_row(row)
patterns.setdefault(record.child_id, []).append(record)
schedules = {
record.child_id: record
for record in map(_schedule_from_row, schedule_rows)
}
overrides: dict[int, list[PresenceOverrideRecord]] = {}
for row in override_rows:
record = _override_from_row(row)
overrides.setdefault(record.child_id, []).append(record)
return patterns, overrides
return schedules, overrides
+23 -91
View File
@@ -13,12 +13,8 @@ Guardrail mapping:
- ``schedule_rules`` deletion is delete-if-unreferenced: a rule still
referenced by any quest definition is rejected (the done-condition),
not cascaded.
- ``quest_definitions`` has exactly one delete path,
:meth:`QuestDefinitionsDao.delete_if_no_history` (owner decision
2026-09-26): a definition with NO completion event on any of its
instances is hard-deleted with its instances, assignees, windows and
(if unreferenced) rule; a definition WITH history is never deleted —
it is retired by deactivation, so history always survives.
- ``quest_definitions`` has no delete path at all: definitions are
deactivated, never hard-deleted, and history must survive.
- Assignment is multi-assignee (D-008): :meth:`add_assignee` and
:meth:`remove_assignee` change future instances only — the DAO writes
the assignee table and nothing else; assignment edits never rewrite
@@ -29,8 +25,8 @@ Guardrail mapping:
:meth:`QuestDefinitionsDao.add_assignee` (active child); no
permission checks here, that is the Feature 09 gate's job.
Concurrency: ``delete_rule_if_unreferenced``,
``delete_if_no_history`` and the assignee mutations perform their checks and writes inside one transaction under
Concurrency: ``delete_rule_if_unreferenced`` and the assignee
mutations perform their checks and writes inside one transaction under
the connection-scoped lock shared with :mod:`.dao_children`, so a
definition referencing the rule (or an assignee appearing) cannot slip
in between check and write on this connection.
@@ -612,42 +608,26 @@ class ScheduleRulesDao:
"""
async with _connection_lock(self._database):
async with self._database.transaction():
return await _delete_rule_if_unreferenced_in_transaction(
self._database, rule_id
row = await self._database.fetch_one(
"SELECT 1 FROM quest_definitions "
"WHERE schedule_rule_id = ? LIMIT 1",
(rule_id,),
)
async def _delete_rule_if_unreferenced_in_transaction(
database: NestQuestDatabase, rule_id: int
) -> bool:
"""Delete-if-unreferenced body; the CALLER holds lock + transaction.
Shared by :meth:`ScheduleRulesDao.delete_if_unreferenced` and
:meth:`QuestDefinitionsDao.delete_if_no_history`, so the rule's
reference check runs in whichever transaction removed the last
definition that could reference it.
"""
row = await database.fetch_one(
"SELECT 1 FROM quest_definitions "
"WHERE schedule_rule_id = ? LIMIT 1",
(rule_id,),
)
if row is not None:
return False
result = await database.execute(
"DELETE FROM schedule_rules WHERE id = ?",
(rule_id,),
)
return result.rowcount > 0
if row is not None:
return False
result = await self._database.execute(
"DELETE FROM schedule_rules WHERE id = ?",
(rule_id,),
)
return result.rowcount > 0
class QuestDefinitionsDao:
"""Typed async access to ``quest_definitions`` and its assignees.
The only delete method is :meth:`delete_if_no_history`: a
definition with completion history is never hard-deleted (it is
deactivated via :meth:`set_active` instead), so completion history
always keeps its references (feature guardrail, D-005). Assignment is multi-assignee
No delete method exists: definitions are deactivated via
:meth:`set_active`, never hard-deleted, so completion history keeps
its references (feature guardrail). Assignment is multi-assignee
(D-008): the definition row carries no child; assignees live in
``quest_definition_assignees`` and are managed explicitly so the
operations stay separately loggable and permission-gateable.
@@ -1160,54 +1140,6 @@ class QuestDefinitionsDao:
)
return result.rowcount
async def delete_if_no_history(self, definition_id: int) -> bool | None:
"""Hard-delete a definition that has NO completion history.
Returns None when the definition does not exist, False when any
of its instances has a completion event (nothing is touched —
the caller retires it by deactivation instead), and True when it
was deleted: its ``quest_instances``, assignee and window rows,
the definition row, and its schedule rule if no other definition
references it.
The history check and every DELETE run inside ONE transaction
under the connection lock, so a completion recorded concurrently
cannot land between the check and the delete (D-005: an instance
with a completion event is never deleted).
"""
async with _connection_lock(self._database):
async with self._database.transaction():
row = await self._database.fetch_one(
"SELECT schedule_rule_id FROM quest_definitions "
"WHERE id = ?",
(definition_id,),
)
if row is None:
return None
schedule_rule_id = row[0]
history = await self._database.fetch_one(
"SELECT 1 FROM completion_events "
"JOIN quest_instances "
"ON quest_instances.id = completion_events.instance_id "
"WHERE quest_instances.definition_id = ? LIMIT 1",
(definition_id,),
)
if history is not None:
return False
for statement in (
"DELETE FROM quest_instances WHERE definition_id = ?",
"DELETE FROM quest_definition_assignees "
"WHERE definition_id = ?",
"DELETE FROM quest_definition_windows "
"WHERE definition_id = ?",
"DELETE FROM quest_definitions WHERE id = ?",
):
await self._database.execute(statement, (definition_id,))
await _delete_rule_if_unreferenced_in_transaction(
self._database, schedule_rule_id
)
return True
async def add_assignee(
self, definition_id: int, child_id: int
) -> list[ChildRecord]:
@@ -1387,16 +1319,16 @@ async def load_materialization_input(
):
"""Read every materialization input in ONE locked transaction.
Returns ``(snapshots, patterns, overrides)``:
Returns ``(snapshots, schedules, overrides)``:
- ``snapshots``: every active definition with its rule, assignees and
windows (the :class:`QuestDefinitionSnapshot` shape).
- ``patterns`` / ``overrides``: the presence patterns and
- ``schedules`` / ``overrides``: the presence schedules and
range-scoped overrides of every assignee child, in
:mod:`.dao_presence`'s record shapes.
The whole read — definitions, rules, assignees, windows, and the
assignees' presence patterns and overrides — runs inside a single
assignees' presence schedules and overrides — runs inside a single
BEGIN..COMMIT span under the connection lock, so a concurrent edit
(definition, assignment, window, or presence) cannot interleave
between the parts and the walk never sees a mixed-time view. Each
@@ -1417,7 +1349,7 @@ async def load_materialization_input(
)
from . import dao_presence # lazy: dao_presence imports us
patterns, overrides = await dao_presence.read_snapshot_unlocked(
schedules, overrides = await dao_presence.read_snapshot_unlocked(
database, child_ids, range_start, range_end
)
return snapshots, patterns, overrides
return snapshots, schedules, overrides
+8 -9
View File
@@ -39,11 +39,10 @@ ISO-8601 timestamp. Completion payloads additionally carry
``was_on_time``. No other personal data: names and titles are the
household's own records, and nothing beyond them leaks.
Timezone policy: the day-complete check needs the household-local
"today", which the caller passes in as a plain :class:`datetime.date`.
Nothing here reads a timezone — the API owns the clock (the
admin-stored application timezone, or the API host's local zone when
none is stored), the core owns the calendar arithmetic.
Timezone policy: the day-complete check needs the HA-local "today",
which the caller passes in as a plain :class:`datetime.date`. Nothing
here reads ``hass.config.time_zone`` — the integration owns HA
timezone, the core owns the calendar arithmetic.
"""
from __future__ import annotations
@@ -148,10 +147,10 @@ async def build_child_day_complete_event(
completion of TODAY'S instance evaluates it: completing a
back-dated or future instance must not announce a cleared day.
``today`` is the household-local calendar date the day-complete
rule is evaluated against; the API resolves it in the application
timezone and passes it in, so this module never reads a clock or a
timezone of its own.
``today`` is the HA-local calendar date the day-complete rule is
evaluated against; the integration reads it from
``hass.config.time_zone`` and passes it in, so this module never
touches HA config.
"""
# Only a completion of TODAY'S instance evaluates the day-complete
# rule: completing a back-dated or future instance must not
+2 -2
View File
@@ -153,7 +153,7 @@ def _validate_range(start_date: str, end_date: str) -> tuple[str, str]:
def _resolve_today(today: datetime.date | None) -> datetime.date:
"""Return the threaded household-local date, or the host calendar date."""
"""Return the threaded HA-local date, or the host calendar date."""
if today is None:
return datetime.date.today()
return today
@@ -283,7 +283,7 @@ async def query_history(
Rows are ordered deterministically by ``due_date``, then instance,
then event id (the per-instance append order, so a completion and
its reversal keep their order). ``today`` pins the household-local date
its reversal keep their order). ``today`` pins the HA-local date
the missed derivation compares due dates against (the host calendar
date when omitted). The whole read runs under the task-reentrant
connection lock — :func:`list_missed_for_child` re-enters it — so
-119
View File
@@ -1,119 +0,0 @@
"""Namespaced quest-definition icon keys.
A definition's ``icon`` is stored as ``<namespace>:<name>`` where the
namespace is one of :data:`ICON_NAMESPACES`:
- ``lucide:<name>`` / ``fa:<name>`` — ``<name>`` is a lowercase kebab
name (ASCII ``[a-z0-9-]``, not starting or ending with ``-``).
- ``emoji:<payload>`` — a short emoji string of at most
:data:`EMOJI_MAX_CODE_POINTS` code points, with no whitespace (JS
``\\s``, so including U+FEFF), no control characters and none of
``<``, ``>``, ``&``.
Rows written before namespacing hold a bare Lucide name (``dog``).
:func:`validate_icon` (writes) normalizes such a legacy value to
``lucide:<name>``; :func:`normalize_icon_for_read` (reads) does the same
leniently so legacy rows render without a data migration.
Nothing here imports :mod:`homeassistant`.
"""
from __future__ import annotations
import re
import unicodedata
ICON_NAMESPACE_LUCIDE = "lucide"
ICON_NAMESPACE_FA = "fa"
ICON_NAMESPACE_EMOJI = "emoji"
ICON_NAMESPACES = frozenset(
{ICON_NAMESPACE_LUCIDE, ICON_NAMESPACE_FA, ICON_NAMESPACE_EMOJI}
)
#: Upper bound on an emoji payload's length in code points — enough for
#: ZWJ sequences such as a family emoji, too short for arbitrary text.
EMOJI_MAX_CODE_POINTS = 8
_KEBAB_NAME = re.compile(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
# U+FEFF (BOM / zero-width no-break space) is neither str.isspace() nor
# ``Cc`` in Python, but JS ``\s`` matches it, so it is listed here to keep
# this rule identical to the frontends' isEmojiPayload (/[\s<>&]|\p{Cc}/u).
# Other format characters, notably the ZWJ U+200D that emoji sequences
# need, stay valid in both runtimes.
_EMOJI_FORBIDDEN = frozenset("<>&\ufeff")
def _is_kebab_name(value: str) -> bool:
return _KEBAB_NAME.fullmatch(value) is not None
def _is_valid_emoji_payload(value: str) -> bool:
if not value or len(value) > EMOJI_MAX_CODE_POINTS:
return False
return not any(
char.isspace()
or char in _EMOJI_FORBIDDEN
or unicodedata.category(char) == "Cc"
for char in value
)
def validate_icon(value: object) -> str | None:
"""Return the canonical namespaced icon key, or raise naming ``icon``.
``None`` or an empty/whitespace-only string returns ``None`` (the
icon is cleared). Otherwise the raw value is validated untrimmed, so
edge whitespace or control characters are rejected rather than
silently stripped. A value with no ``:`` is a legacy bare Lucide
name and is stored as ``lucide:<value>``. An unknown namespace, an
empty or malformed name, or an invalid emoji payload raises
ValueError.
"""
if value is None:
return None
if not isinstance(value, str):
raise ValueError(f"icon must be a string, got {value!r}")
if not value.strip():
return None
namespace, separator, name = value.partition(":")
if not separator:
if not _is_kebab_name(value):
raise ValueError(
f"icon must be a lowercase kebab name, got {value!r}"
)
return f"{ICON_NAMESPACE_LUCIDE}:{value}"
if namespace not in ICON_NAMESPACES:
raise ValueError(
f"icon has an unknown namespace {namespace!r}; expected one of "
f"{sorted(ICON_NAMESPACES)}"
)
if namespace == ICON_NAMESPACE_EMOJI:
if not _is_valid_emoji_payload(name):
raise ValueError(
f"icon emoji must be 1-{EMOJI_MAX_CODE_POINTS} code points "
f"with no whitespace, control characters or markup, "
f"got {value!r}"
)
elif not _is_kebab_name(name):
raise ValueError(
f"icon {namespace} name must be a lowercase kebab name, "
f"got {value!r}"
)
return value
def normalize_icon_for_read(value: str | None) -> str | None:
"""Return a stored icon in namespaced form for output.
Lenient: ``None``/empty returns ``None``, a recognised namespace is
returned unchanged, and anything else becomes ``lucide:<value>`` so
legacy rows render (an unknown name falls through to the frontend's
fallback icon rather than erroring).
"""
if not value or not value.strip():
return None
namespace, separator, _ = value.partition(":")
if separator and namespace in ICON_NAMESPACES:
return value
return f"{ICON_NAMESPACE_LUCIDE}:{value}"
+36 -41
View File
@@ -9,7 +9,7 @@ task and lives elsewhere.
The walk is deterministic and idempotent:
- All inputs — the active definitions with their rules, assignees and
windows, AND the assignee children's presence patterns and scoped
windows, AND the assignee children's presence schedules and scoped
overrides — are read inside ONE locked transaction (see
:func:`~.dao_rules.load_materialization_input`), so the walk sees a
single coherent snapshot rather than a definition state from one
@@ -51,12 +51,12 @@ never the past — and re-run the walk over the rolling horizon
HOOK (Feature 09 presence services): the presence business layer that
lands in Feature 09 MUST call :func:`regenerate_for_child` after EVERY
presence-state write so a child's future instances track its presence:
creating, updating and deleting a presence pattern
(:mod:`.presence_management`'s ``create_presence_pattern`` /
``update_presence_pattern`` / ``delete_presence_pattern``),
``set_presence_pattern`` (including clearing/setting an empty pattern),
deleting/clearing the presence schedule
(:meth:`~.dao_presence.PresenceSchedulesDao.delete`),
``create_presence_override``, and ``delete_presence_override``. A
pattern delete changes presence state too, so it must regenerate just
like the others. This hook
schedule delete changes presence state too (the child becomes
always-present), so it must regenerate just like the others. This hook
is documented, not yet wired: no presence business layer exists yet, and
the presence DAO (``dao_presence.py``) must stay free of business rules
— never call :func:`regenerate_for_child` from inside the DAO layer.
@@ -79,7 +79,7 @@ from .dao_rules import (
schedule_rule_storage_from_record,
)
from .db import NestQuestDatabase
from .presence import PresenceEngine, PresenceOverride, PresencePattern
from .presence import PresenceEngine, PresenceOverride, PresenceSchedule
from .recurrence import ScheduleRule, occurs_on
@@ -129,7 +129,7 @@ def _decode_rule(snapshot) -> ScheduleRule:
def _build_engine(
patterns_records,
schedules_records,
overrides_records,
*,
extra_overrides: tuple[PresenceOverride, ...] = (),
@@ -140,18 +140,11 @@ def _build_engine(
overrides on top of the stored ones — the consequence preview's
proposed override (:func:`count_removed_by_override`).
"""
patterns: dict[int, list[PresencePattern]] = {}
for child_id, records in patterns_records.items():
patterns[child_id] = [
PresencePattern.decode(
record.child_id,
record.name,
record.kind,
record.anchor_date,
record.pattern,
)
for record in records
]
schedules: dict[int, PresenceSchedule] = {}
for child_id, record in schedules_records.items():
schedules[child_id] = PresenceSchedule.decode(
child_id, record.anchor_date, record.pattern
)
overrides: dict[int, list[PresenceOverride]] = {}
for child_id, records in overrides_records.items():
overrides[child_id] = [
@@ -166,7 +159,7 @@ def _build_engine(
]
for override in extra_overrides:
overrides.setdefault(override.child_id, []).append(override)
return PresenceEngine(patterns, overrides)
return PresenceEngine(schedules, overrides)
class GeneratedTuple(NamedTuple):
@@ -255,12 +248,12 @@ async def materialize(
after a presence change) cannot touch any unrelated child's rows.
When omitted (or None) the walk covers every assignee as before.
``today`` optionally pins the resolved household-local date the walk's
``today`` optionally pins the resolved HA-local date the walk's
no-past guard compares against; it is threaded into every
:meth:`~.dao_instances.QuestInstancesDao.upsert_if_valid` write. When
omitted the host clock (``datetime.date.today``) is used, which is the
historical default. A caller that computed the horizon in the
household's application time zone MUST pass that same date here so a
historical default. A caller that computed the horizon in Home
Assistant's configured time zone MUST pass that same date here so a
time zone behind the host around midnight is not rejected as "past".
``start_date`` is clamped up to the resolved "today" (the same
@@ -286,10 +279,10 @@ async def materialize(
f"{end_date!r} < {start_date!r}"
)
snapshots, patterns_records, overrides_records = await (
snapshots, schedules_records, overrides_records = await (
load_materialization_input(database, start_date, end_date)
)
engine = _build_engine(patterns_records, overrides_records)
engine = _build_engine(schedules_records, overrides_records)
child_filter = None if child_ids is None else set(child_ids)
generated_at = _now_stamp()
@@ -298,8 +291,8 @@ async def materialize(
start = datetime.datetime.strptime(start_date, "%Y-%m-%d").date()
end = datetime.datetime.strptime(end_date, "%Y-%m-%d").date()
# Clamp a past start up to today (the household-local anchor when the
# caller pinned one, else the host clock) so the walk can never emit a
# Clamp a past start up to today (the HA-local anchor when the caller
# pinned one, else the host clock) so the walk can never emit a
# past-dated instance; the DAO's no-past guard remains the backstop.
# A range entirely in the past therefore yields zero instances.
today_date = _resolve_today(today)
@@ -345,7 +338,7 @@ async def regenerate_for_definition(
:func:`~.dao_instances._today` — so the delete cutoff and the
re-materialization range share one anchor, and the walk's
``upsert_if_valid`` no-past guard never rejects the regenerated
range. ``today`` optionally pins a caller-resolved household-local date
range. ``today`` optionally pins a caller-resolved HA-local date
(threaded into both the delete cutoff and the re-materialization)
so a household time zone behind the host around midnight stays
consistent. ``horizon_days`` sizes the re-materialization window;
@@ -373,11 +366,12 @@ async def regenerate_for_definition(
# child-presence counterpart to ``regenerate_for_definition``. The
# presence business layer that lands in Feature 09 MUST call
# ``regenerate_for_child`` after EVERY presence-state write, so future
# instances track a child's changed presence: create_presence_pattern,
# update_presence_pattern, delete_presence_pattern,
# create_presence_override, and delete_presence_override. A pattern
# delete changes presence state too, so it must regenerate just like
# the others. It is deliberately NOT
# instances track a child's changed presence: set_presence_pattern
# (including clearing/setting an empty pattern), deleting/clearing the
# presence schedule (PresenceSchedulesDao.delete),
# create_presence_override, and delete_presence_override. A schedule
# delete changes presence state too (the child becomes always-present),
# so it must regenerate just like the others. It is deliberately NOT
# wired into ``dao_presence.py``: the DAO layer stays pure storage (no
# business rules), and no presence business layer exists yet to host the
# call — see the module docstring note above.
@@ -391,8 +385,9 @@ async def regenerate_for_child(
"""Regenerate a child's future instances after a presence change.
The Feature 09 presence services call this after every
presence-state write — create_presence_pattern,
update_presence_pattern, delete_presence_pattern,
presence-state write — set_presence_pattern (including clearing or
setting an empty pattern), deleting/clearing the presence schedule
(:meth:`~.dao_presence.PresenceSchedulesDao.delete`),
create_presence_override, and delete_presence_override — so a
child's future instances track its new presence: the child's open
instances at or after today are deleted across ALL its definitions
@@ -413,9 +408,9 @@ async def regenerate_for_child(
:meth:`~.dao_instances.QuestInstancesDao.delete_future_uncompleted_for_child`),
so the delete cutoff and the re-materialization window share ONE
execution-day anchor even when the call is queued across midnight.
``today`` optionally pins a caller-resolved household-local date, threaded
``today`` optionally pins a caller-resolved HA-local date, threaded
into the delete cutoff and the re-materialization for the same
host-vs-household time-zone consistency. ``horizon_days`` sizes the
host-vs-HA time-zone consistency. ``horizon_days`` sizes the
re-materialization window; when omitted it falls back to
:data:`~.const.DEFAULT_HORIZON_DAYS`. A bool, non-int, or sub-1 value
raises ValueError BEFORE any delete. Returns the number of instances
@@ -486,12 +481,12 @@ async def count_removed_by_override(
start_date, end_date = start.isoformat(), end.isoformat()
child_id = override.child_id
snapshots, patterns_records, overrides_records = await (
snapshots, schedules_records, overrides_records = await (
load_materialization_input(database, start_date, end_date)
)
current = _generation_preview(
snapshots,
_build_engine(patterns_records, overrides_records),
_build_engine(schedules_records, overrides_records),
start,
end,
child_filter={child_id},
@@ -500,7 +495,7 @@ async def count_removed_by_override(
_generation_preview(
snapshots,
_build_engine(
patterns_records,
schedules_records,
overrides_records,
extra_overrides=(override,),
),
+3 -78
View File
@@ -31,11 +31,7 @@ widened (definition_id, child_id, due_date, window) key, and migration
column. Migration 7 adds the generic ``nestquest_meta_state``
key/value table for integration-owned bookkeeping (Feature 11's
missed-sweep watermark). Migration 8 adds the ``skip_on_away``
column to ``quest_definitions`` (Feature 22), defaulting to 1.
Migration 9 replaces the one-per-child ``presence_schedules`` table
with ``presence_patterns`` (zero or more patterns per child), copying
every schedule across as a ``home`` pattern and dropping the old table
— see :data:`MIGRATION_9_PRESENCE_PATTERNS` for the rollback note. Each
column to ``quest_definitions`` (Feature 22), defaulting to 1. Each
callable migration runs inside its own transaction
together with its version stamp, so a crash mid-step rolls the
statements and the stamp back together.
@@ -89,7 +85,6 @@ from .schema import (
SCHEMA_V1_QUEST_DEFINITION_ASSIGNEES_DDL,
SCHEMA_V1_QUEST_DEFINITION_WINDOWS_DDL,
SCHEMA_V7_META_STATE_DDL,
SCHEMA_V9_PRESENCE_PATTERNS_DDL,
)
LOGGER = logging.getLogger(__name__)
@@ -121,76 +116,9 @@ VERSION_TABLE_DDL = f"""
)
"""
#: The retired ``presence_schedules`` DDL (one schedule per child),
#: frozen here verbatim: migration 1 shipped creating this table and
#: applied migrations are never edited, so a fresh file still walks
#: through it and migration 9 retires it. :mod:`.schema` no longer
#: declares it.
_MIGRATION_1_PRESENCE_SCHEDULES_DDL = """
CREATE TABLE IF NOT EXISTS presence_schedules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
child_id INTEGER NOT NULL UNIQUE REFERENCES children(id),
cycle_length_weeks INTEGER NOT NULL CHECK (typeof(cycle_length_weeks) = 'integer' AND cycle_length_weeks >= 1 AND cycle_length_weeks <= 4),
anchor_date TEXT NOT NULL,
pattern TEXT NOT NULL CHECK (
NOT pattern GLOB '*[^0-6,|]*'
AND NOT pattern GLOB '*[0-6][0-6]*'
AND NOT pattern GLOB '*,,*'
AND NOT pattern GLOB '*,|*'
AND NOT pattern GLOB '*|,*'
AND NOT pattern GLOB ',*'
AND NOT pattern GLOB '*,'
AND NOT pattern GLOB '*[0-6],[0-6],[0-6],[0-6],[0-6],[0-6],[0-6],[0-6]*'
AND (LENGTH(pattern) - LENGTH(REPLACE(pattern, '|', '')) + 1) = cycle_length_weeks
)
)
"""
#: One-based index into :data:`MIGRATIONS`: entry ``n`` upgrades
#: version ``n-1`` to version ``n``. Migration 1 is the v1 DDL as it
#: shipped: the current tables, except that it still creates the
#: retired ``presence_schedules`` table in place of
#: ``presence_patterns`` (which migration 9 creates).
MIGRATION_1_V1_DDL: list[str] = [
_MIGRATION_1_PRESENCE_SCHEDULES_DDL
if sql in SCHEMA_V9_PRESENCE_PATTERNS_DDL
else sql
for sql in SCHEMA_V1_STATEMENTS
]
#: The label every migrated ``presence_schedules`` row carries as a
#: ``presence_patterns`` row.
MIGRATED_PRESENCE_PATTERN_NAME = "Home schedule"
#: Migration 9 (schema 9): multiple presence patterns per child.
#: Creates ``presence_patterns``, copies EVERY ``presence_schedules``
#: row into it as a ``home`` pattern named
#: :data:`MIGRATED_PRESENCE_PATTERN_NAME` — ``cycle_length_weeks``,
#: ``anchor_date`` and ``pattern`` verbatim, the row id kept — and
#: drops ``presence_schedules``. A ``home`` pattern with no other
#: pattern beside it answers exactly as the old schedule did (the
#: engine treats a date no home pattern covers as a day away), so every
#: child's presence is unchanged. A plain statement list: the runner
#: applies it and the version stamp in ONE transaction, so a failure
#: rolls the copy and the drop back together. Dropping a table nothing
#: references needs no ``foreign_keys = OFF`` bracket.
#:
#: Rollback: the drop is one-way. A 0.7.1 build refuses a version-9
#: file ("newer than this integration understands") and could not read
#: ``presence_patterns`` anyway, so take a copy of the SQLite file (or
#: note the Litestream generation) BEFORE the first start of the release
#: carrying migration 9; rolling back to 0.7.1 means restoring that
#: pre-migration copy, which still holds the single-schedule rows.
#: Pattern edits made after the upgrade are not in that copy.
MIGRATION_9_PRESENCE_PATTERNS: list[str] = [
*SCHEMA_V9_PRESENCE_PATTERNS_DDL,
"INSERT INTO presence_patterns (id, child_id, name, kind, "
"cycle_length_weeks, anchor_date, pattern) "
f"SELECT id, child_id, '{MIGRATED_PRESENCE_PATTERN_NAME}', 'home', "
"cycle_length_weeks, anchor_date, pattern "
"FROM presence_schedules ORDER BY id",
"DROP TABLE presence_schedules",
]
#: version ``n-1`` to version ``n``.
MIGRATION_1_V1_DDL: list[str] = list(SCHEMA_V1_STATEMENTS)
#: The assignees table DDL, shared with migration 1 via the schema
#: module so a rebuilt and a freshly created table cannot drift.
@@ -522,9 +450,6 @@ MIGRATIONS: Sequence[MigrationStep] = [
# quest_definitions — an additive column defaulting to 1, so every
# pre-existing definition keeps today's skip-when-absent behaviour.
_add_skip_on_away,
# Migration 9 (schema 9): presence_schedules -> presence_patterns,
# each schedule copied across as a 'home' pattern.
MIGRATION_9_PRESENCE_PATTERNS,
]
+70 -139
View File
@@ -5,24 +5,21 @@ timezone logic — it operates on plain calendar dates only (feature
guardrail). The later engine (cycle position, ``is_present``,
overrides, previews) builds directly on this model.
A :class:`PresencePattern` answers "on which weekdays of which cycle
week does this rule apply to this child?" for an N-week repeating
custody rule, and its ``kind`` says what the rule claims on those
days: ``home`` (the child is at this house) or ``away``. A child
carries ZERO OR MORE patterns (schema 9), e.g. "away every Thursday
and Friday" plus "away every other weekend"; a child with NO pattern
is present every day (that default, and how patterns combine, lives in
the engine, not here).
A :class:`PresenceSchedule` answers "on which weekdays of which cycle
week is this child at this house?" for an N-week repeating custody
pattern. Two of the household's three children follow a two-week
rotation; a child with NO schedule row is present every day (that
default lives in the engine, not here).
Pattern encoding: the model's canonical serialization is the SAME
pipe-separated CSV the database stores (see schema.py's
``presence_patterns.pattern``): segment ``i`` (week index ``i``) is a
comma-separated list of the weekdays the pattern covers, 0 = Monday ..
6 = Sunday, e.g. ``'0,2,4|1,3'`` = Mon/Wed/Fri in week 0, Tue/Thu in
week 1. An empty segment means the pattern covers no day of that
week. Encoding sorts each segment's weekdays and uses the exact
segment order, so ``decode(encode(pattern))`` round-trips losslessly
and two patterns with equal weekday sets produce equal strings.
``presence_schedules.pattern``): segment ``i`` (week index ``i``) is a
comma-separated list of present weekdays, 0 = Monday .. 6 = Sunday,
e.g. ``'0,2,4|1,3'`` = Mon/Wed/Fri in week 0, Tue/Thu in week 1. An
empty segment means absent every day of that week. Encoding sorts
each segment's weekdays and uses the exact segment order, so
``decode(encode(schedule))`` round-trips losslessly and two schedules
with equal patterns produce equal strings.
Anchor-date policy: ``anchor_date`` pins the cycle. Cycle position is
computed from anchor-date arithmetic ONLY — never ISO week numbers or
@@ -31,9 +28,7 @@ week parity (D-004): 53-week years silently invert parity on January
that the anchor is a strict calendar date.
Validation policy: construction is total — every reject happens in
``__init__`` so no invalid pattern can ever exist:
- ``name`` must be a string that is not blank; it is stored trimmed.
- ``kind`` must be ``'home'`` or ``'away'``.
``__init__`` so no invalid schedule can ever exist:
- ``cycle_length_weeks`` must be an integer 1..4. The 4 cap matches
the database CHECK (schema.py) and keeps anchor arithmetic and the
encoded pattern human-readable; revisit both together if a longer
@@ -54,10 +49,6 @@ from types import MappingProxyType
#: the pattern human-readable and the anchor arithmetic small).
MAX_CYCLE_LENGTH_WEEKS = 4
#: The pattern kinds the schema's CHECK allows: what a covering
#: pattern claims about the child on that date.
PATTERN_KINDS = ("home", "away")
_DATE_FORMAT = "%Y-%m-%d"
@@ -135,25 +126,6 @@ def _validate_weekday_set(week: int, weekdays: object) -> frozenset[int]:
return frozenset(members)
def _validate_name(value: object) -> str:
"""Reject non-string and blank pattern names; return it trimmed."""
if not isinstance(value, str):
raise ValueError(f"name must be a string, got {value!r}")
trimmed = value.strip()
if not trimmed:
raise ValueError("name must not be empty")
return trimmed
def _validate_kind(value: object) -> str:
"""Reject any kind other than the schema's ``home`` / ``away``."""
if not isinstance(value, str) or value not in PATTERN_KINDS:
raise ValueError(
f"kind must be one of {', '.join(PATTERN_KINDS)}, got {value!r}"
)
return value
def _validate_cycle_length(value: object) -> int:
"""Reject non-int and out-of-range cycle lengths (bools included)."""
if isinstance(value, bool) or not isinstance(value, int):
@@ -176,19 +148,17 @@ def _validate_child_id(value: object) -> int:
@dataclass(frozen=True, init=False)
class PresencePattern:
"""One of a child's N-week repeating presence rules.
class PresenceSchedule:
"""One child's N-week repeating presence pattern.
``pattern`` maps each week index of the cycle (``0`` .. ``n-1``)
to the set of weekdays the rule covers (ints, Monday=0); ``kind``
is what the rule claims on a covered date (``home`` or ``away``).
A week with an empty set covers no day of that week. How several
patterns combine is the engine's job (:class:`PresenceEngine`).
to the set of present weekdays (ints, Monday=0). A week with an
empty set means the child is absent every day of that week — which
is distinct from having no schedule at all (the engine treats a
missing schedule as present every day).
"""
child_id: int
name: str
kind: str
cycle_length_weeks: int
anchor_date: datetime.date
pattern: MappingProxyType # week index -> frozenset of weekdays
@@ -196,15 +166,11 @@ class PresencePattern:
def __init__(
self,
child_id: int,
name: str,
kind: str,
cycle_length_weeks: int,
anchor_date: object,
pattern: dict[int, object],
) -> None:
object.__setattr__(self, "child_id", _validate_child_id(child_id))
object.__setattr__(self, "name", _validate_name(name))
object.__setattr__(self, "kind", _validate_kind(kind))
cycle = _validate_cycle_length(cycle_length_weeks)
object.__setattr__(self, "cycle_length_weeks", cycle)
object.__setattr__(
@@ -212,7 +178,7 @@ class PresencePattern:
)
if not isinstance(pattern, dict):
raise ValueError(
"pattern must map week index to a set of covered "
"pattern must map week index to a set of present "
f"weekdays, got {pattern!r}"
)
normalised: dict[int, frozenset[int]] = {}
@@ -238,9 +204,9 @@ class PresencePattern:
"""Serialize to the database's pipe-separated CSV shape.
Segments appear in week order; each segment is the week's
covered weekdays as a sorted comma-separated list (an empty set
encodes as an empty segment). Two patterns with equal weekday
sets encode identically.
present weekdays as a sorted comma-separated list (an empty set
encodes as an empty segment). Two schedules with equal
patterns encode identically.
"""
segments = [
",".join(str(day) for day in sorted(self.pattern[week]))
@@ -252,12 +218,10 @@ class PresencePattern:
def decode(
cls,
child_id: int,
name: str,
kind: str,
anchor_date: object,
encoded: str,
) -> "PresencePattern":
"""Build a pattern from its encoded weekday sets.
) -> "PresenceSchedule":
"""Build a schedule from its encoded pattern.
The cycle length is derived from the segment count, mirroring
the database's segment-count CHECK. Decoding is strict: wrong
@@ -284,15 +248,7 @@ class PresencePattern:
)
weekdays.add(int(part))
pattern[week] = weekdays
return cls(child_id, name, kind, len(segments), anchor_date, pattern)
def covers(self, date: datetime.date) -> bool:
"""Return True when ``date``'s weekday is in its cycle week's set.
The cycle week comes from :func:`cycle_week_index` — anchor-date
arithmetic only, never ISO week numbers or parity (D-004).
"""
return date.weekday() in self.pattern[cycle_week_index(self, date)]
return cls(child_id, len(segments), anchor_date, pattern)
@dataclass(frozen=True, init=False)
@@ -345,7 +301,7 @@ class PresenceOverride:
def cycle_week_index(
pattern: PresencePattern, target_date: object
schedule: PresenceSchedule, target_date: object
) -> int:
"""Return the cycle week index ``target_date`` falls in.
@@ -359,14 +315,14 @@ def cycle_week_index(
valid week index.
"""
target = _parse_date(target_date, "target_date")
days = (target - pattern.anchor_date).days
return (days // 7) % pattern.cycle_length_weeks
days = (target - schedule.anchor_date).days
return (days // 7) % schedule.cycle_length_weeks
#: Search cap for :meth:`PresenceEngine.next_present_dates`: two full
#: years of daily checks. A child absent every day (an away pattern
#: covering every weekday) would otherwise loop forever; the cap bounds
#: the scan and surfaces the situation as an error instead.
#: years of daily checks. A child absent every day (an all-absent
#: pattern with a blocking override) would otherwise loop forever; the
#: cap bounds the scan and surfaces the situation as an error instead.
MAX_PREVIEW_SCAN_DAYS = 366 * 2
@@ -374,45 +330,40 @@ class PresenceEngine:
"""Answers "is this child at this house on this date?".
Pure and side-effect-free: built from an immutable snapshot of the
children's patterns (``child_id -> list of PresencePattern``), it
never touches the database — callers build a snapshot from the DAO
layer and pass it in. A child with NO pattern is present every day
(the third household child's case). Evaluation order, first match
wins — see :meth:`is_present`. Pattern coverage is anchor-date
arithmetic (:func:`cycle_week_index`, never ISO week parity).
children's schedules (``child_id -> PresenceSchedule``), it never
touches the database — callers build a snapshot from the DAO layer
and pass it in. A child with NO schedule entry is present every
day (the third household child's case); a child WITH a schedule is
present exactly when the date's weekday is in that schedule's
pattern for the date's cycle week index (anchor-date arithmetic —
:func:`cycle_week_index`, never ISO week parity).
"""
def __init__(
self,
patterns: dict[int, list[PresencePattern]],
schedules: dict[int, PresenceSchedule],
overrides: dict[int, list[PresenceOverride]] | None = None,
) -> None:
if not isinstance(patterns, dict):
if not isinstance(schedules, dict):
raise ValueError(
"patterns must map child_id to a list of PresencePattern, "
f"got {patterns!r}"
f"schedules must map child_id to PresenceSchedule, got "
f"{schedules!r}"
)
for child_id, entries in patterns.items():
for child_id, schedule in schedules.items():
# Validate the KEY as a model child id too: True and 1.0
# compare equal to 1, so {True: [pattern(1)]} would be
# compare equal to 1, so {True: schedule(1)} would be
# accepted and then behave differently on lookup.
_validate_child_id(child_id)
if not isinstance(entries, list):
if not isinstance(schedule, PresenceSchedule):
raise ValueError(
f"patterns[{child_id!r}] must be a list of "
f"PresencePattern, got {entries!r}"
f"schedules[{child_id!r}] must be a PresenceSchedule, "
f"got {schedule!r}"
)
if schedule.child_id != child_id:
raise ValueError(
f"schedules is keyed {child_id!r} but holds the "
f"schedule of child {schedule.child_id}"
)
for entry in entries:
if not isinstance(entry, PresencePattern):
raise ValueError(
f"patterns[{child_id!r}] entries must be "
f"PresencePattern, got {entry!r}"
)
if entry.child_id != child_id:
raise ValueError(
f"patterns is keyed {child_id!r} but holds a "
f"pattern of child {entry.child_id}"
)
if overrides is None:
overrides = {}
if not isinstance(overrides, dict):
@@ -440,17 +391,11 @@ class PresenceEngine:
)
# Read-only snapshot: reassignment is refused and no mutator
# exists, so a built engine answers consistently for its
# lifetime. The patterns and overrides lists are copied to
# immutable tuples — a shallow mapping copy alone would leave
# caller-owned lists reachable, and mutating one later would
# change is_present results.
object.__setattr__(
self,
"_patterns",
MappingProxyType(
{child_id: tuple(entries) for child_id, entries in patterns.items()}
),
)
# lifetime. The overrides lists are copied to immutable
# tuples — a shallow mapping copy alone would leave caller-
# owned lists reachable through _overrides, and mutating one
# later would change is_present results.
object.__setattr__(self, "_schedules", MappingProxyType(dict(schedules)))
object.__setattr__(
self,
"_overrides",
@@ -462,22 +407,12 @@ class PresenceEngine:
def is_present(self, child_id: object, date: object) -> bool:
"""Return whether ``child_id`` is present on ``date``.
Ordered, first match wins:
1. An override covering the date — its flag IS the answer,
including for a child with no pattern at all. The DAO layer
guarantees a child's overrides never overlap; if a snapshot
still carries two covering the same date, the one with the
LATEST start date wins (deterministic, and matches "the most
specific swap wins").
2. Any ``away`` pattern covering the date — absent.
3. Any ``home`` pattern covering the date — present.
4. Otherwise: absent when the child has at least one ``home``
pattern (a home pattern lists the days the child IS here, so
an uncovered date is a day away — the retired single-schedule
semantics, which migration 9 carries across as ``home``
patterns unchanged), else present (no pattern, or ``away``
patterns only: the household default).
Overrides take precedence over the repeating pattern: when an
override covers the date, its flag IS the answer — including
for a child with no schedule at all. The DAO layer guarantees
a child's overrides never overlap; if a snapshot still carries
two covering the same date, the one with the LATEST start date
wins (deterministic, and matches "the most specific swap wins").
"""
if isinstance(child_id, bool) or not isinstance(child_id, int):
raise ValueError(f"child_id must be an integer, got {child_id!r}")
@@ -489,16 +424,12 @@ class PresenceEngine:
if covering:
winner = max(covering, key=lambda entry: entry.start_date)
return winner.is_present
patterns = self._patterns.get(child_id) or ()
if any(
pattern.kind == "away" and pattern.covers(target)
for pattern in patterns
):
return False
homes = [pattern for pattern in patterns if pattern.kind == "home"]
if any(pattern.covers(target) for pattern in homes):
schedule = self._schedules.get(child_id)
if schedule is None:
# No schedule at all: present every day (household default).
return True
return not homes
week = cycle_week_index(schedule, target)
return target.weekday() in schedule.pattern[week]
def next_present_dates(
self,
@@ -511,7 +442,7 @@ class PresenceEngine:
Walks forward from ``start_date`` (INCLUSIVE — a parent
previewing "starting Monday" expects Monday itself when the
child is present) checking :meth:`is_present` for every day,
so overrides and the patterns are honoured identically. The
so overrides and the pattern are honoured identically. The
admin Schedule tab renders this preview so a parent can confirm
a custody pattern is right before saving it.
@@ -2,11 +2,11 @@
Sits between the write callers (the Feature 09 HA service handlers and
the API admin plane's presence routes) and the typed presence DAOs plus
the pure presence model: callers get the model validation, the create /
update / delete operations and the regeneration side effect here, and
the pure presence model: callers get the model validation, the upsert /
create / delete operations and the regeneration side effect here, and
never touch the DAO or SQL directly. This is the ONE implementation of
these business rules — every caller constructs the same
:class:`~.presence.PresencePattern` / :class:`~.presence.PresenceOverride`
:class:`~.presence.PresenceSchedule` / :class:`~.presence.PresenceOverride`
models (whose constructors are total, so no re-validation happens in a
handler) and gets the same post-write
:func:`~.materialize.regenerate_for_child`, so a child's future quest
@@ -15,16 +15,16 @@ write. Like the model it is Home-Assistant-free: ``today`` is a plain
calendar date threaded through to the regeneration, defaulting to the
host clock there.
Pattern policy (schema 9): a child has ZERO OR MORE presence patterns,
each created, edited and deleted by its own id. Patterns and overrides
are deletable by design (children are not — the children layer owns
that guardrail). An unknown pattern or override id raises ValueError
prefixed ``pattern_id:`` / ``override_id:`` so a caller can distinguish
"unknown id" from a rejected argument the same way the
Upsert policy (Feature 05, unchanged): a child has AT MOST ONE presence
schedule — setting again REPLACES the existing row rather than
duplicating it. Overrides are deletable by design (children are not —
the children layer owns that guardrail). Deleting a nonexistent
override raises ValueError prefixed ``override_id:`` so a caller can
distinguish "unknown id" from a rejected argument the same way the
quest-definitions layer prefixes ``definition_id:``.
The admin plane's presence READS go through here too
(:func:`list_presence_patterns`, :func:`list_presence_overrides`), so a
(:func:`get_presence_schedule`, :func:`list_presence_overrides`), so a
reader never touches the DAO directly either.
"""
from __future__ import annotations
@@ -35,13 +35,11 @@ from .dao_children import ChildrenDao
from .dao_presence import (
PresenceOverrideRecord,
PresenceOverridesDao,
PresencePatternRecord,
PresencePatternsDao,
PresenceSchedulesDao,
)
from .dao_rules import _UNSET
from .db import NestQuestDatabase
from .materialize import count_removed_by_override, regenerate_for_child
from .presence import PresenceOverride, PresencePattern
from .presence import PresenceOverride, PresenceSchedule
def _validate_override_id(value: object) -> int:
@@ -51,159 +49,49 @@ def _validate_override_id(value: object) -> int:
return value
def _validate_pattern_id(value: object) -> int:
"""Reject non-int pattern ids (bools would silently address id 1)."""
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError(f"pattern_id must be an integer, got {value!r}")
return value
async def _get_pattern_or_raise(
dao: PresencePatternsDao, pattern_id: object
) -> PresencePatternRecord:
"""Return the stored pattern; an unknown id raises ``pattern_id:``."""
record = await dao.get(_validate_pattern_id(pattern_id))
if record is None:
raise ValueError(
f"pattern_id: presence pattern {pattern_id} does not exist"
)
return record
def decode_pattern_record(record: PresencePatternRecord) -> PresencePattern:
"""Decode one stored pattern row back through the model."""
return PresencePattern.decode(
record.child_id,
record.name,
record.kind,
record.anchor_date,
record.pattern,
)
async def create_presence_pattern(
async def set_presence_schedule(
database: NestQuestDatabase,
child_id: int,
name: str,
kind: str,
cycle_length_weeks: int,
anchor_date: object,
pattern: dict[int, object],
*,
today: datetime.date | None = None,
horizon_days: int | None = None,
) -> PresencePatternRecord:
"""Add one repeating presence pattern to a child.
) -> PresenceSchedule:
"""Set (upsert) a child's repeating presence schedule.
The :class:`~.presence.PresencePattern` model validates at
construction — a non-blank name, ``kind`` ``home``/``away``, cycle
length 1..4, a strict calendar anchor date, and a pattern covering
week indices 0..n-1 with weekday sets — so no invalid pattern
reaches the DAO. The encoded pattern is inserted beside the
child's other patterns, then :func:`~.materialize.regenerate_for_child`
The :class:`~.presence.PresenceSchedule` model validates at
construction — cycle length 1..4, a strict calendar anchor date,
and a pattern covering week indices 0..n-1 with weekday sets — so
no invalid schedule reaches the DAO. The encoded pattern is
UPSERTed by child (a second set REPLACES the child's existing
schedule; the schema's UNIQUE(child_id) makes duplication
unrepresentable), then :func:`~.materialize.regenerate_for_child`
re-materializes the child's future instances against the new
presence. ``today``/``horizon_days`` thread through to that
regeneration; raising ValueError names what to fix (an unknown
child reads ``child N does not exist``).
Returns the STORED record WITH its ``id`` — the handle
:func:`update_presence_pattern` and :func:`delete_presence_pattern`
take.
Returns the STORED schedule decoded back through the model — the
round-trip proves the encoded pattern the database now holds is
exactly the one the caller asked for.
"""
model = PresencePattern(
child_id, name, kind, cycle_length_weeks, anchor_date, pattern
schedule = PresenceSchedule(
child_id, cycle_length_weeks, anchor_date, pattern
)
record = await PresencePatternsDao(database).create(
model.child_id,
model.name,
model.kind,
model.cycle_length_weeks,
model.anchor_date.isoformat(),
model.encode(),
record = await PresenceSchedulesDao(database).upsert_by_child(
schedule.child_id,
schedule.cycle_length_weeks,
schedule.anchor_date.isoformat(),
schedule.encode(),
)
await regenerate_for_child(
database, model.child_id, today=today, horizon_days=horizon_days
database, schedule.child_id, today=today, horizon_days=horizon_days
)
return record
async def update_presence_pattern(
database: NestQuestDatabase,
pattern_id: int,
*,
name: str | object = _UNSET,
kind: str | object = _UNSET,
cycle_length_weeks: int | object = _UNSET,
anchor_date: object = _UNSET,
pattern: dict[int, object] | object = _UNSET,
today: datetime.date | None = None,
horizon_days: int | None = None,
) -> PresencePatternRecord:
"""Edit one presence pattern; only supplied fields change.
The pattern is looked up FIRST (an unknown id raises ValueError
prefixed ``pattern_id:``), the supplied fields are laid over the
stored ones and the WHOLE result is rebuilt through the
:class:`~.presence.PresencePattern` model — so a partial edit is
validated exactly as a create is (changing ``cycle_length_weeks``
without a matching ``pattern`` is rejected), and an explicit None
is rejected rather than ignored. The pattern stays with its child;
the child's future instances are regenerated afterwards.
"""
dao = PresencePatternsDao(database)
stored = decode_pattern_record(await _get_pattern_or_raise(dao, pattern_id))
model = PresencePattern(
stored.child_id,
stored.name if name is _UNSET else name,
stored.kind if kind is _UNSET else kind,
(
stored.cycle_length_weeks
if cycle_length_weeks is _UNSET
else cycle_length_weeks
),
stored.anchor_date if anchor_date is _UNSET else anchor_date,
dict(stored.pattern) if pattern is _UNSET else pattern,
return PresenceSchedule.decode(
record.child_id, record.anchor_date, record.pattern
)
record = await dao.update(
pattern_id,
model.name,
model.kind,
model.cycle_length_weeks,
model.anchor_date.isoformat(),
model.encode(),
)
if record is None:
raise ValueError(
f"pattern_id: presence pattern {pattern_id} does not exist"
)
await regenerate_for_child(
database, model.child_id, today=today, horizon_days=horizon_days
)
return record
async def delete_presence_pattern(
database: NestQuestDatabase,
pattern_id: int,
*,
today: datetime.date | None = None,
horizon_days: int | None = None,
) -> PresencePatternRecord:
"""Delete one presence pattern by id and return it as it was stored.
The pattern is looked up FIRST and an unknown id raises ValueError
prefixed ``pattern_id:`` BEFORE any delete, so a mistyped id can
never be silently swallowed by a no-op. The deletion is followed
by :func:`~.materialize.regenerate_for_child` for the pattern's own
child — the id decides the child, never a caller-supplied one.
"""
dao = PresencePatternsDao(database)
record = await _get_pattern_or_raise(dao, pattern_id)
await dao.delete(record.id)
await regenerate_for_child(
database, record.child_id, today=today, horizon_days=horizon_days
)
return record
async def create_presence_override(
@@ -283,16 +171,21 @@ async def preview_presence_override_consequence(
)
async def list_presence_patterns(
async def get_presence_schedule(
database: NestQuestDatabase, child_id: int
) -> list[PresencePatternRecord]:
"""Return the child's presence patterns ordered by id.
) -> PresenceSchedule | None:
"""Return the child's presence schedule decoded, or None when unset.
An empty list means the child exists and has no pattern — present
None means the child exists and has no schedule row — present
every day (Feature 05). An unknown child raises ValueError
(``child N does not exist``) rather than reading as present.
"""
return await PresencePatternsDao(database).list_by_child(child_id)
record = await PresenceSchedulesDao(database).get_by_child(child_id)
if record is None:
return None
return PresenceSchedule.decode(
record.child_id, record.anchor_date, record.pattern
)
async def list_presence_overrides(
@@ -7,9 +7,7 @@ all-or-nothing create/edit here, and never touch the DAO SQL directly.
:func:`edit_quest_definition` the edit path (which may also replace the
whole assignee set), :func:`assign_child` and
:func:`unassign_child` the single-child assignment paths, and
:func:`set_quest_definition_active` the deactivate/reactivate path,
and :func:`delete_quest_definition` the hybrid admin delete (hard-delete
when there is no completion history, retire by deactivation otherwise).
:func:`set_quest_definition_active` the deactivate/reactivate path.
There is no permission check here (that is Feature 09).
Validation policy mirrors :mod:`.children`:
@@ -61,7 +59,6 @@ from .dao_rules import (
schedule_rule_to_storage,
)
from .db import NestQuestDatabase
from .icons import validate_icon
from .materialize import regenerate_for_definition
from .recurrence import ScheduleRule, occurs_on
@@ -82,21 +79,6 @@ class CreatedQuestDefinition:
windows: list[QuestDefinitionWindowRecord]
@dataclass(frozen=True)
class DeletedQuestDefinition:
"""What :func:`delete_quest_definition` actually did.
Exactly one of ``deleted`` / ``retired`` is True. ``definition`` is
the retired (deactivated) definition's updated view, or None when
the definition was hard-deleted and no longer exists.
"""
definition_id: int
deleted: bool
retired: bool
definition: CreatedQuestDefinition | None
def _now_stamp() -> str:
"""Return the module's strict UTC second-precision stamp."""
return datetime.datetime.now(datetime.timezone.utc).isoformat(
@@ -253,11 +235,6 @@ async def create_quest_definition(
transaction, so the returned bundle is a consistent creation
snapshot. Raises ValueError on any rejected argument; a rejected or
failed create persists nothing.
After the write, :func:`~.materialize.regenerate_for_definition`
materializes the new definition's instances over the rolling horizon
(host clock, :data:`~.const.DEFAULT_HORIZON_DAYS`), so it reaches the
board without waiting for an unrelated write.
"""
name = _validate_text(title, "title", required=True)
assert name is not None
@@ -266,7 +243,7 @@ async def create_quest_definition(
assignee_ids = _validate_assignee_ids(assignee_child_ids)
window_specs = _normalize_windows(windows)
description_value = _validate_text(description, "description")
icon_value = validate_icon(icon)
icon_value = _validate_text(icon, "icon")
skip_on_away_value = _validate_skip_on_away(skip_on_away)
storage = schedule_rule_to_storage(rule)
@@ -292,9 +269,6 @@ async def create_quest_definition(
) from error
raise
decoded_rule = schedule_rule_from_storage(storage)
await regenerate_for_definition(database, snapshot.definition.id)
return CreatedQuestDefinition(
definition=snapshot.definition,
rule=decoded_rule,
@@ -345,7 +319,7 @@ async def edit_quest_definition(
future instances only; no ``quest_instances`` or
``completion_events`` row is touched.
``today`` optionally pins the caller-resolved household-local date the
``today`` optionally pins the caller-resolved HA-local date the
regeneration's no-past guard and horizon are anchored to (threaded
into :func:`~.materialize.regenerate_for_definition`); it is a plain
``datetime.date`` with no HA import here — the Feature 09 service
@@ -369,7 +343,7 @@ async def edit_quest_definition(
icon_value: str | None | object = _UNSET
if icon is not _UNSET:
icon_value = validate_icon(icon)
icon_value = _validate_text(icon, "icon")
rule_storage: ScheduleRuleStorage | object = _UNSET
if rule is not _UNSET:
@@ -449,7 +423,7 @@ async def assign_child(
``quest_definition_assignees`` link is written; existing instances
and completion history are never touched.
``today`` optionally pins the caller-resolved household-local date threaded
``today`` optionally pins the caller-resolved HA-local date threaded
into the assignment's regeneration (see :func:`edit_quest_definition`).
``horizon_days`` optionally sizes the regeneration's re-materialization
window the same way.
@@ -491,7 +465,7 @@ async def unassign_child(
argument. Only the ``quest_definition_assignees`` link is written;
existing instances and completion history are never touched.
``today`` optionally pins the caller-resolved household-local date threaded
``today`` optionally pins the caller-resolved HA-local date threaded
into the unassignment's regeneration (see :func:`edit_quest_definition`).
``horizon_days`` optionally sizes the regeneration's re-materialization
window the same way.
@@ -521,19 +495,12 @@ async def set_quest_definition_active(
) -> CreatedQuestDefinition:
"""Deactivate or reactivate a definition; returns the updated view.
Flipping the flag is the only removal path for a definition with
completion history (Feature 06 guardrail; a history-free definition
may instead be hard-deleted by :func:`delete_quest_definition`):
Flipping the flag is the only removal path (Feature 06 guardrail):
a deactivated definition stops future instance generation but its
row, schedule rule, assignees and windows all survive, and its
durable completion history (the append-only ``completion_events``)
is never touched. Like every Feature 06 config change, the flip is
followed by :func:`~.materialize.regenerate_for_definition`: the
definition's future (today onward) UNCOMPLETED instances are cleared
— they are rolling, regenerable rows — and, while the definition is
inactive, none are re-materialized. Completed and past instances
are kept. Reactivation re-enables generation, and the same
regeneration re-materializes the rolling horizon.
row, schedule rule, assignees and windows all survive, and existing
instances plus completion history are never touched. Reactivation
re-enables future generation; generating or removing instances is
Feature 07 and does not happen here.
``definition_id`` must be a plain int (bools and floats rejected,
since SQLite would bind ``True`` onto definition 1) and
@@ -548,7 +515,7 @@ async def set_quest_definition_active(
connection-scoped lock, so the returned bundle is a consistent
snapshot that a concurrent mutation cannot race.
``today`` optionally pins the caller-resolved household-local date threaded
``today`` optionally pins the caller-resolved HA-local date threaded
into the activation change's regeneration (see
:func:`edit_quest_definition`). ``horizon_days`` optionally sizes the
regeneration's re-materialization window the same way.
@@ -586,68 +553,6 @@ async def set_quest_definition_active(
)
async def delete_quest_definition(
database: NestQuestDatabase,
definition_id: int,
*,
today: datetime.date | None = None,
horizon_days: int | None = None,
) -> DeletedQuestDefinition:
"""Delete a definition if it has no history; otherwise retire it.
Owner decision (2026-09-26): "delete if there's no history,
retire/deactivate if there is". When NO instance of the definition
has a completion event, the definition, its instances, assignees,
windows and (if no other definition references it) its schedule
rule are hard-deleted in ONE transaction by
:meth:`~.dao_rules.QuestDefinitionsDao.delete_if_no_history` — the
history check is inside that transaction, so a completion recorded
concurrently can never be deleted (D-005). When history exists,
the definition is retired through :func:`set_quest_definition_active`
(``False``). Retirement preserves the definition row, schedule
rule, assignees, windows and ALL durable completion history. Like
any deactivation it regenerates, so future UNCOMPLETED instances are
cleared (they are rolling, regenerable rows) and none are recreated
while the definition is inactive — the retired task stops generating
and no longer shows open work. Durable instance history lives only
in the append-only ``completion_events``.
``definition_id`` must be a plain int (bools and floats rejected).
Raises ValueError naming the field when the id is malformed or the
definition does not exist. ``today`` / ``horizon_days`` are threaded
into the retire path's regeneration, as in
:func:`set_quest_definition_active`.
"""
_validate_definition_id(definition_id)
deleted = await QuestDefinitionsDao(database).delete_if_no_history(
definition_id
)
if deleted is None:
raise ValueError(
f"definition_id: quest definition {definition_id} does not exist"
)
if deleted:
return DeletedQuestDefinition(
definition_id=definition_id,
deleted=True,
retired=False,
definition=None,
)
retired = await set_quest_definition_active(
database,
definition_id,
False,
today=today,
horizon_days=horizon_days,
)
return DeletedQuestDefinition(
definition_id=definition_id,
deleted=False,
retired=True,
definition=retired,
)
def _bundle_snapshot(
snapshot: QuestDefinitionSnapshot,
) -> CreatedQuestDefinition:
+14 -24
View File
@@ -43,19 +43,18 @@ rule or a monthly rule could later be pinned to a month) nor extra
fields on weekly/monthly/yearly rules generally, so the CHECKs only
reject what the rule engine definitively cannot express now.
Presence pattern format: ``presence_patterns.pattern`` encodes the
Presence pattern format: ``presence_schedules.pattern`` encodes the
whole N-week repeating cycle in one TEXT column as pipe-separated
segments, one per week of the cycle: segment ``i`` is a ``weekday_set``
CSV (same single-digit 0-6 convention as ``schedule_rules.weekday_set``)
for week ``i``, e.g. ``'0,2,4|1,3'`` = Mon/Wed/Fri in week 0, Tue/Thu in
week 1. An empty segment means the pattern covers no day of that week.
A child carries zero or more patterns, each ``kind`` ``home`` or
``away``; a child with no pattern row at all is present every day, per
the feature guardrails (how patterns combine is the presence engine's
job). The encoding and its CHECKs are carried over verbatim from the
retired ``presence_schedules`` table (schema 9). Chosen over JSON or
per-week rows to stay consistent with the CSV ``weekday_set``
convention and fully checkable by plain CHECKs. DB-level validation is pure CHECK, no triggers or
week 1. An empty segment means the child is absent every day of that
week; a wholly empty pattern with ``cycle_length_weeks = 1`` means
absent every day of every week, which is distinct from having no
schedule row at all (a child with no schedule is present every day, per
the feature guardrails). Chosen over JSON or per-week rows to stay
consistent with the CSV ``weekday_set`` convention and fully checkable
by plain CHECKs. DB-level validation is pure CHECK, no triggers or
custom functions: char-class GLOBs reject every character outside
digits 0-6, comma and pipe; adjacency GLOBs reject empty elements
(double comma, comma next to a pipe, leading/trailing comma) and
@@ -69,8 +68,7 @@ weekday_set this is not full CSV-set normalisation (duplicates like
the engine treats the segment as a set. A
one-row-per-``week_index`` normalization was considered and rejected:
the flat single-column encoding keeps the done-condition's table shape
and proved fully checkable with plain CHECKs. ``name`` is a short
label and carries no CHECK; the model rejects a blank one.
and proved fully checkable with plain CHECKs.
``cycle_length_weeks`` is capped at 4: 2 (alternating weeks) is the
common case, and a small cap keeps anchor arithmetic and the encoded
@@ -290,19 +288,11 @@ SCHEMA_V1_QUEST_DEFINITION_WINDOWS_DDL: list[str] = [
""",
]
#: ``presence_patterns`` (schema version 9): zero or more repeating
#: presence rules per child, replacing the retired one-per-child
#: ``presence_schedules`` table. ``child_id`` is deliberately NOT
#: unique; ``kind`` is what a covering pattern claims (``home`` or
#: ``away``); ``pattern`` keeps the retired table's encoding and CHECKs
#: verbatim.
SCHEMA_V9_PRESENCE_PATTERNS_DDL: list[str] = [
"""
CREATE TABLE IF NOT EXISTS presence_patterns (
SCHEMA_V1_PRESENCE_SCHEDULES_DDL: list[str] = [
f"""
CREATE TABLE IF NOT EXISTS presence_schedules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
child_id INTEGER NOT NULL REFERENCES children(id),
name TEXT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('home', 'away')),
child_id INTEGER NOT NULL UNIQUE REFERENCES children(id),
cycle_length_weeks INTEGER NOT NULL CHECK (typeof(cycle_length_weeks) = 'integer' AND cycle_length_weeks >= 1 AND cycle_length_weeks <= 4),
anchor_date TEXT NOT NULL,
pattern TEXT NOT NULL CHECK (
@@ -417,7 +407,7 @@ SCHEMA_V1_STATEMENTS: list[str] = [
*SCHEMA_V1_QUEST_DEFINITIONS_DDL,
*SCHEMA_V1_QUEST_DEFINITION_ASSIGNEES_DDL,
*SCHEMA_V1_QUEST_DEFINITION_WINDOWS_DDL,
*SCHEMA_V9_PRESENCE_PATTERNS_DDL,
*SCHEMA_V1_PRESENCE_SCHEDULES_DDL,
*SCHEMA_V1_PRESENCE_OVERRIDES_DDL,
*SCHEMA_V1_QUEST_INSTANCES_DDL,
*SCHEMA_V1_COMPLETION_EVENTS_DDL,
+1 -45
View File
@@ -35,7 +35,6 @@ from collections.abc import Callable
from dataclasses import dataclass
from types import MappingProxyType
from typing import Any, Mapping
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from .const import (
CONF_AFTERNOON_REMINDER_ENABLED,
@@ -48,14 +47,12 @@ from .const import (
CONF_MORNING_SUMMARY_ENABLED,
CONF_MORNING_SUMMARY_TIME,
CONF_NOTIFY_TARGET,
CONF_TIMEZONE,
DEFAULT_AFTERNOON_REMINDER_TIME,
DEFAULT_AUTOMATION_ENABLED,
DEFAULT_DAY_ROLLOVER_TIME,
DEFAULT_END_OF_DAY_REPORT_TIME,
DEFAULT_HORIZON_DAYS,
DEFAULT_MORNING_SUMMARY_TIME,
DEFAULT_TIMEZONE,
LOGGER,
TIME_PATTERN,
)
@@ -156,29 +153,6 @@ def _resolve_optional_str(value: Any) -> str:
return value.strip()
def _resolve_timezone(value: Any) -> str:
"""Validate a household time zone and return it.
The empty string means "the API host's local time" (the historical
behaviour); anything else must be an IANA key :class:`ZoneInfo`
resolves (e.g. ``America/New_York``). A non-str (including
``None``) is rejected; the ``None``-as-absent mapping lives ONLY in
:meth:`NestQuestSettings.from_options` (via :func:`_option_value`).
"""
if not isinstance(value, str):
raise ValueError(f"timezone must be a string, got {value!r}")
if value == "":
return value
try:
ZoneInfo(value)
except (ZoneInfoNotFoundError, ValueError) as error:
raise ValueError(
f"timezone must be an IANA time zone name such as "
f"'America/New_York', got {value!r}"
) from error
return value
#: The single field table the two builders share. Each row is
#: ``(field_name, CONF_* key, default, validator)``. ``from_options``
#: applies every validator (raising on the first invalid value) while
@@ -240,7 +214,6 @@ _FIELDS: tuple[tuple[str, str, Any, Callable[[Any], Any]], ...] = (
DEFAULT_AUTOMATION_ENABLED,
_resolve_bool,
),
("timezone", CONF_TIMEZONE, DEFAULT_TIMEZONE, _resolve_timezone),
)
@@ -270,7 +243,6 @@ class NestQuestSettings:
afternoon_reminder_enabled: bool = DEFAULT_AUTOMATION_ENABLED
end_of_day_report_enabled: bool = DEFAULT_AUTOMATION_ENABLED
celebration_enabled: bool = DEFAULT_AUTOMATION_ENABLED
timezone: str = DEFAULT_TIMEZONE
def __post_init__(self) -> None:
# Validate STRICTLY at construction so a hand-built instance
@@ -309,22 +281,6 @@ class NestQuestSettings:
raise ValueError(
f"{name} must be a boolean, got {value!r}"
)
_resolve_timezone(self.timezone)
def household_now(self, instant: datetime.datetime) -> datetime.datetime:
"""Return the aware ``instant`` expressed in the household's zone.
The API service does not run inside Home Assistant, so its one
clock read (an aware host-local ``now``) is converted here: with
:attr:`timezone` set — only ever by an admin, from the admin
app — the SAME instant is re-expressed in that zone, so
``.date()`` and ``.time()`` are the household's wall clock even
when the host runs UTC. With :attr:`timezone` empty the instant
is returned unchanged (the host's local time).
"""
if not self.timezone:
return instant
return instant.astimezone(ZoneInfo(self.timezone))
@property
def day_rollover_hour_minute(self) -> tuple[int, int]:
@@ -340,7 +296,7 @@ class NestQuestSettings:
"""Return the rolling horizon window ``[today, today + horizon_days]``.
``today`` is REQUIRED (there is no host-clock default): the
API passes the household-local date (:meth:`household_now`) so
integration passes the HA-local ``hass.config.time_zone`` date so
the horizon tracks the household's own day, and a silent
host-clock fallback would be a wrong-day footgun (a test or a
caller that forgets to pass ``today`` would otherwise materialize
@@ -18,7 +18,7 @@ API client; the two are deliberately NOT unified here, and neither
side reads the other's values.
STORED SERIALIZATION — the document at ``SETTINGS_META_KEY`` is a JSON
object holding exactly the TWELVE settings fields, keyed by field name
object holding exactly the TEN settings fields, keyed by field name
(which equals the ``CONF_*`` option key for every field), complete
after the first update:
@@ -30,11 +30,7 @@ after the first update:
core's normalizer),
- ``morning_summary_enabled``, ``afternoon_reminder_enabled``,
``end_of_day_report_enabled``, ``celebration_enabled`` — real
booleans,
- ``timezone`` — ``""`` (the API host's local time) or an IANA time
zone name such as ``America/New_York``. A document stored before
this field existed simply lacks it and resolves to ``""``. Only an
admin's explicit update ever writes it; nothing sets it automatically.
booleans.
Only values whose core validators ACCEPTED are ever written, so a
stored document always round-trips through the core's option builders.
@@ -176,7 +172,7 @@ async def update_settings(
update can never leave a half-applied document behind.
The validated changes are merged onto the current effective
settings and the merged (complete, eleven-field) document is persisted
settings and the merged (complete, ten-field) document is persisted
in one atomic upsert; the updated settings are returned. The whole
read → merge → write span runs inside the per-database settings
lock, so concurrent updates queue instead of interleaving.
@@ -197,27 +193,18 @@ async def update_settings(
)
async with _settings_lock(database):
current = await load_settings(database)
return await _write_merged(database, current, changes)
async def _write_merged(
database: NestQuestDatabase,
current: NestQuestSettings,
changes: Mapping[str, Any],
) -> NestQuestSettings:
"""Validate ``changes``, merge onto ``current``, persist; lock held."""
document: dict[str, Any] = {
field: getattr(current, field) for field in _FIELD_NAMES
}
for name, raw_value in changes.items():
default, validator = _RESOLUTIONS[name]
try:
document[name] = validator(
default if raw_value is None else raw_value
)
except ValueError as error:
raise ValueError(_named(name, error)) from error
await MetaStateDao(database).set(
SETTINGS_META_KEY, json.dumps(document, sort_keys=True)
)
document: dict[str, Any] = {
field: getattr(current, field) for field in _FIELD_NAMES
}
for name, raw_value in changes.items():
default, validator = _RESOLUTIONS[name]
try:
document[name] = validator(
default if raw_value is None else raw_value
)
except ValueError as error:
raise ValueError(_named(name, error)) from error
await MetaStateDao(database).set(
SETTINGS_META_KEY, json.dumps(document, sort_keys=True)
)
return NestQuestSettings(**document)
+24 -46
View File
@@ -18,7 +18,7 @@ the panel payload shaper (:func:`instance_payload`), and the async
service's panel snapshot route share ONE implementation of both the
snapshot assembly and the entity-facing attribute payload shape.
Nothing here imports :mod:`homeassistant`; the builder takes the
database, the settings object, and the household-local ``now`` (a single
database, the settings object, and the HA-local ``now`` (a single
clock read the caller already resolved, from which it derives
``today``) and returns the snapshot, mirroring exactly what the
coordinator used to do inline.
@@ -39,15 +39,14 @@ from typing import Any
from .completion import derive_state
from .dao_children import ChildrenDao
from .dao_instances import CompletionEventsDao, QuestInstancesDao
from .dao_presence import PresenceOverridesDao, PresencePatternsDao
from .dao_presence import PresenceOverridesDao, PresenceSchedulesDao
from .dao_rules import QuestDefinitionsDao
from .db import NestQuestDatabase
from .icons import normalize_icon_for_read
from .presence import (
MAX_PREVIEW_SCAN_DAYS,
PresenceEngine,
PresenceOverride,
PresencePattern,
PresenceSchedule,
)
from .settings import NestQuestSettings
@@ -96,34 +95,23 @@ class NestQuestSnapshot:
today_iso: str
children: tuple[ChildDaySnapshot, ...]
cycle_day: int
#: The application timezone the admin stored (``""`` when unset —
#: the host's local time; the API publishes its effective zone in
#: its place, api/host_zone.py). The panel cards format their
#: visible date and clock in it; it never re-resolves the day itself.
timezone: str = ""
def _cycle_day(
patterns: dict[int, list[PresencePattern]],
children,
today: datetime.date,
schedules: dict[int, PresenceSchedule], children, today: datetime.date
) -> int:
"""Return today's 1-based day in the first patterned child's cycle.
"""Return today's 1-based day in the first scheduled child's cycle.
The cycle is that child's FIRST pattern (lowest id) — one number
for the household's cycle-day sensor even when a child carries
several patterns. Anchor-date arithmetic ONLY (D-004): the day
offset is computed from the pattern's own anchor, never ISO week
numbers or parity, so a 53-week year cannot silently invert the
cycle.
Anchor-date arithmetic ONLY (D-004): the day offset is computed from
the schedule's own anchor, never ISO week numbers or parity, so a
53-week year cannot silently invert the cycle.
"""
for child in children:
entries = patterns.get(child.id)
if not entries:
schedule = schedules.get(child.id)
if schedule is None:
continue
pattern = entries[0]
days = (today - pattern.anchor_date).days
cycle_length = pattern.cycle_length_weeks * 7
days = (today - schedule.anchor_date).days
cycle_length = schedule.cycle_length_weeks * 7
return (days % cycle_length) + 1
return 0
@@ -187,7 +175,7 @@ async def build_snapshot(
:func:`instance_payload` layer — this builder produces the shared
shape both consumers read.
``now`` is the household-local timezone-aware datetime the caller already
``now`` is the HA-local timezone-aware datetime the caller already
resolved (a SINGLE clock read); the overdue check compares
``now.time()`` against the instance's ``due_time`` for today's open
instances. The builder performs NO internal clock read — it never
@@ -203,21 +191,16 @@ async def build_snapshot(
children = await ChildrenDao(database).list_active()
patterns: dict[int, list[PresencePattern]] = {}
schedules: dict[int, PresenceSchedule] = {}
overrides: dict[int, list[PresenceOverride]] = {}
for child in children:
records = await PresencePatternsDao(database).list_by_child(child.id)
if records:
patterns[child.id] = [
PresencePattern.decode(
record.child_id,
record.name,
record.kind,
record.anchor_date,
record.pattern,
)
for record in records
]
schedule = await PresenceSchedulesDao(database).get_by_child(
child.id
)
if schedule is not None:
schedules[child.id] = PresenceSchedule.decode(
child.id, schedule.anchor_date, schedule.pattern
)
window_end = today + datetime.timedelta(
days=MAX_PREVIEW_SCAN_DAYS
)
@@ -239,7 +222,7 @@ async def build_snapshot(
)
for record in ranged
]
engine = PresenceEngine(patterns, overrides)
engine = PresenceEngine(schedules, overrides)
instances_dao = QuestInstancesDao(database)
events_dao = CompletionEventsDao(database)
@@ -268,11 +251,7 @@ async def build_snapshot(
definition_id=instance.definition_id,
child_id=instance.child_id,
title=definition.title if definition else "Quest",
icon=(
normalize_icon_for_read(definition.icon)
if definition
else None
),
icon=definition.icon if definition else None,
window=instance.window,
due_date=instance.due_date,
due_time=instance.due_time,
@@ -323,6 +302,5 @@ async def build_snapshot(
return NestQuestSnapshot(
today_iso=today_iso,
children=tuple(snapshots),
cycle_day=_cycle_day(patterns, children, today),
timezone=settings.timezone,
cycle_day=_cycle_day(schedules, children, today),
)
+5 -7
View File
@@ -39,10 +39,9 @@ lets exactly one of them win the claim — the loser returns [] and
announces nothing.
The caller supplies ``today`` as a plain :class:`datetime.date`: the
household-local calendar date, which the API reads in the
admin-stored application timezone (the API host's local zone when none
is stored). This module never reads a timezone database or config of
its own.
household-local calendar date, read from ``hass.config.time_zone`` by
the integration or from the API host's local clock by the API. This
module never reads a timezone database or config of its own.
"""
from __future__ import annotations
@@ -98,9 +97,8 @@ async def run_missed_sweep(
"""Build one missed event per unswept past-due open instance.
``today`` is the household-local calendar date the sweep runs for
(the caller owns the clock: the API reads it in the admin-stored
application timezone, falling back to its host's local time when
unset).
(the caller owns the clock: the integration reads it from
``hass.config.time_zone``, the API from its host's local time).
Returns the ``(event_type, payload)`` tuples to announce, EMPTY
when the watermark already covers ``today`` (a same-night rerun) —
the caller decides how to publish them and announces nothing on
+1 -1
View File
@@ -15,5 +15,5 @@
"iot_class": "local_polling",
"issue_tracker": "https://github.com/Maniacs-Mansion/NestQuest/issues",
"requirements": [],
"version": "0.10.3"
"version": "0.6.0"
}
-4
View File
@@ -441,10 +441,6 @@ class NestQuestHouseholdDueTodaySensor(_NestQuestHouseholdSensor):
for child in data.children
},
"child_roster": _child_roster(data.children),
# The API's effective application timezone ("" only when
# it could not name one): the panel cards format their
# visible date and clock in it.
"timezone": data.timezone,
}
File diff suppressed because it is too large Load Diff
-34
View File
@@ -1,34 +0,0 @@
# Example environment for the NestQuest API container deployment.
#
# Copy to ``deploy/.env`` (git-ignored) and fill in REAL values there;
# this example carries placeholder names only and is never a source of
# secrets. Compose loads ``deploy/.env`` into the api service; the
# API fails fast on startup when any of these is unset or empty
# (api/config.py — there are no silent defaults).
# The static panel-plane service token the HA integration presents as
# a Bearer credential on /api/v1/panel/* routes. Generate one, e.g.:
# python -c "import secrets; print(secrets.token_urlsafe(32))"
NESTQUEST_PANEL_TOKEN=
# The Authentik OIDC settings the admin plane verifies JWTs against.
NESTQUEST_OIDC_ISSUER=
NESTQUEST_OIDC_AUDIENCE=
NESTQUEST_OIDC_JWKS_URL=
# The host interface the API's port 8080 is published on (compose
# interpolation, not read by the API). Defaults to 127.0.0.1 when
# unset; on the API box set the LAN address the reverse proxy
# forwards to, e.g. 10.60.1.14.
NESTQUEST_BIND_ADDRESS=
# Admin PWA build args (compose interpolation into the pwa service's
# VITE_* build args; baked into the bundle, so rebuild after changing).
# PUBLIC values, not secrets: the Authentik application is a PKCE client
# with no client secret. All three are required — the pwa image build
# fails when any is empty.
# NESTQUEST_AUTHENTIK_ISSUER=https://auth.cubecraftlabs.com/application/o/nestquest/
# NESTQUEST_API_BASE_URL=https://nestquest.cubecraftlabs.com
NESTQUEST_AUTHENTIK_CLIENT_ID=
NESTQUEST_AUTHENTIK_ISSUER=
NESTQUEST_API_BASE_URL=
-622
View File
@@ -1,622 +0,0 @@
# NestQuest API — deployment and restore runbook
Operator procedure to rebuild the production NestQuest API deployment end
to end from this repository, restore its database from backup, and verify
it. Every value below is the real, non-secret production value. **No
secret appears in this file** — secrets are named and their location is
given, never their content.
| Piece | Where | Real value |
| --- | --- | --- |
| API box (Docker host) | this repository's `deploy/` | `10.60.1.14`, port `8080` (API), `8081` (admin PWA, section 10) |
| Reverse proxy / TLS | shared Traefik on `nukapi-03` | `10.60.1.33` |
| Public hostname | Cloudflare DNS | `nestquest.cubecraftlabs.com` |
| Identity | Authentik | `https://auth.cubecraftlabs.com` |
| Home Assistant box (panel client) | LAN | `10.60.1.80` |
| Local DNS | Pi-hole | `10.60.1.101` |
| Backup target | Synology NAS `CubeCraft-SRVR1`, SFTP | `10.60.1.50:/homes/Joshua/nestquest-backups` |
All `docker compose` commands below are run **on the API box, from the
repository root**. The shorthand `dc` means:
alias dc='docker compose -f deploy/compose.yaml'
Compose v2.24 or newer is required (`env_file` uses the `path`/`required`
form).
---
## 1. Image build
The image is defined by the root `Dockerfile` and is built from the
**repository root** as the build context: the API (`api/`) loads the
bundled domain core from `custom_components/nestquest/core/` by file
location, so both trees must be in the context. `.dockerignore` keeps
everything else (including `deploy/`, `.env` files and `*.db`) out of the
build.
- Multi-stage on `python:3.12-slim`: the builder installs
`api/requirements.txt`, the runtime copies only the installed packages
plus `api/` and `custom_components/nestquest/core/` into `/app`.
- Runs as the non-root system user `nestquest` (uid/gid `999`), which owns
`/var/lib/nestquest`.
- Command: `uvicorn --factory api.app:create_app --host 0.0.0.0 --port 8080`.
Get the code and build:
git clone ssh://code.cubecraftlabs.com:2288/Maniacs_Mansion/NestQuest.git
cd NestQuest
git checkout <release branch or tag being deployed>
dc build api # equivalent: docker build -t nestquest-api:latest .
Confirm the runtime user (the Litestream sidecar and the key ownership in
section 5 depend on uid 999):
docker run --rm --entrypoint id nestquest-api:latest
# uid=999(nestquest) gid=999(nestquest) groups=999(nestquest)
## 2. Compose
`deploy/compose.yaml` defines three services and one named volume:
| Service | Image | Role |
| --- | --- | --- |
| `api` | `nestquest-api:latest` (built, section 1) | FastAPI service on `8080`, healthcheck on `/health` |
| `litestream` | `litestream/litestream:0.5.17` | Continuous SFTP backup of the database (section 7); starts only once `api` is healthy |
| `pwa` | `nestquest-pwa:latest` (built from `deploy/pwa`, section 10) | Admin PWA served by nginx on `8081`; independent of the other two |
- **Volume `nestquest-db`** is mounted at `/var/lib/nestquest` in both
services. The database is `NESTQUEST_DB_PATH=/var/lib/nestquest/nestquest.db`
(fixed by compose, not a secret). `docker compose down` keeps named
volumes; **never run `down -v`** on the API box. Docker prefixes the
volume with the compose project name — with the default project
(`deploy`, the compose file's directory) it is `deploy_nestquest-db`;
confirm with `docker volume ls | grep nestquest-db`.
- **Published port**: `${NESTQUEST_BIND_ADDRESS:-127.0.0.1}:8080:8080`.
The default binds localhost only, so an unconfigured host is never
exposed. On the API box `deploy/.env` sets
`NESTQUEST_BIND_ADDRESS=10.60.1.14` so Traefik on nukapi-03 can reach
`http://10.60.1.14:8080`.
- **Secrets** come from `deploy/.env` (git-ignored, section 5) via
`env_file`.
Bring the stack up (after section 5's secrets exist):
dc up -d --build
dc ps # api "healthy", litestream "Up"
curl -s http://10.60.1.14:8080/health # {"status":"ok"}
## 3. TLS and reverse proxy (Traefik on nukapi-03)
TLS is terminated by the **shared** Traefik instance on `nukapi-03`
(`10.60.1.33`), not by this repository. Its NestQuest routing is the
owner-authored dynamic file-provider config
**`config/dynamic/nestquest-ccl.yml`** in the Traefik deployment on
nukapi-03 — that live file is authoritative; it is not stored in this
repository. What it must contain:
| Router | Rule | Middleware | Service |
| --- | --- | --- | --- |
| `nestquest-panel` (priority 200) | ``Host(`nestquest.cubecraftlabs.com`) && PathPrefix(`/api/v1/panel`)`` | `nestquest-panel-lan`: `ipAllowList`, `sourceRange: ["10.60.1.80/32"]` (HA box only) | `nestquest-api` → `http://10.60.1.14:8080` |
| `nestquest-admin` (priority 100: `/api/v1/admin`, `/health`, `/openapi.json`, `/docs`) | ``Host(`nestquest.cubecraftlabs.com`) && (PathPrefix(`/api/v1/admin`) \|\| Path(`/health`) \|\| Path(`/openapi.json`) \|\| PathPrefix(`/docs`))`` | `nestquest-headers` — no source restriction; the API itself enforces Authentik JWTs (section 4) | `nestquest-api` → `http://10.60.1.14:8080` |
| `nestquest-app` (priority 50: everything else — the admin PWA) | see section 10 | none at Traefik; nginx allow-lists the proxy | `nestquest-pwa` → `http://10.60.1.14:8081` |
All routers use the HTTPS entrypoint `websecure` with `tls.certResolver: myresolver`
(HTTP is redirected to HTTPS by the shared Traefik). Priorities are set
explicitly so the order never depends on rule length: panel (200) above
admin (100), and the PWA's `nestquest-app` router (50) below both. The
admin router is scoped to `/api/v1/admin`, `/health`, `/openapi.json`
and `/docs` — a bare ``Host(...)`` rule at a higher priority would
swallow `/` and every PWA route. Any other `/api/*` path matches no
router (the app router excludes `/api`), so Traefik answers `404`.
Reference shape, to rebuild the file if it is ever lost (entrypoint names
must match the shared Traefik's static config on nukapi-03):
```yaml
http:
routers:
nestquest-panel:
rule: "Host(`nestquest.cubecraftlabs.com`) && PathPrefix(`/api/v1/panel`)"
priority: 200
entryPoints: [websecure]
middlewares: [nestquest-panel-lan]
service: nestquest-api
tls:
certResolver: myresolver
nestquest-admin:
rule: "Host(`nestquest.cubecraftlabs.com`) && (PathPrefix(`/api/v1/admin`) || Path(`/health`) || Path(`/openapi.json`) || PathPrefix(`/docs`))"
priority: 100
entryPoints: [websecure]
middlewares: [nestquest-headers]
service: nestquest-api
tls:
certResolver: myresolver
nestquest-app:
rule: "Host(`nestquest.cubecraftlabs.com`) && !PathPrefix(`/api`) && !Path(`/health`) && !Path(`/openapi.json`) && !PathPrefix(`/docs`)"
priority: 50
entryPoints: [websecure]
service: nestquest-pwa
tls:
certResolver: myresolver
middlewares:
nestquest-panel-lan:
ipAllowList:
sourceRange: ["10.60.1.80/32"]
nestquest-headers:
# headers middleware; copy its definition from the live file
services:
nestquest-api:
loadBalancer:
servers:
- url: "http://10.60.1.14:8080"
nestquest-pwa:
loadBalancer:
servers:
- url: "http://10.60.1.14:8081"
```
**Certificates.** `myresolver` is the shared Traefik's ACME (Let's
Encrypt) resolver using the **Cloudflare DNS-01 challenge**; the
Cloudflare API token is held by the Traefik deployment on
nukapi-03, never in this repository. Because DNS-01 proves control
through a DNS TXT record, issuance and renewal need no inbound HTTP and
work regardless of the Cloudflare proxy setting. Certificates renew
automatically.
**Cloudflare proxy note.** Public traffic for
`nestquest.cubecraftlabs.com` resolves through Cloudflare, so a request
from the internet reaches Traefik from a Cloudflare edge address, never
from `10.60.1.80` — which is exactly why the panel allowlist refuses it
(403). The HA box does not go through Cloudflare at all: the local DNS
override in section 6 sends it straight to Traefik on the LAN, so Traefik
sees its real address. Do **not** add Cloudflare ranges to the panel
allowlist or make the allowlist trust `X-Forwarded-For`; that would let
any internet client through to the panel plane.
## 4. Authentik (admin identity)
Admin-plane requests (`/api/v1/admin/*`) carry an Authentik OIDC access
token (JWT). The API verifies issuer, audience, RS256 signature against
the JWKS, and expiry, then requires the `groups` claim to contain
`nestquest-admins` (`api/auth.py`). Configure in Authentik
(`https://auth.cubecraftlabs.com`, admin interface):
1. **Provider** — *OAuth2/OpenID Provider*:
- Client type: **Public** (no client secret; the admin PWA is a browser
SPA).
- PKCE: the PWA always uses the authorization-code flow with PKCE,
`code_challenge_method=S256`, and never sends a client secret.
- Redirect URI (strict): `https://nestquest.cubecraftlabs.com/auth/callback`.
- Signing key: an **RSA** certificate (the API only accepts `RS256`).
- Scopes: the default `openid`, `email`, `profile` mappings (the PWA
requests `openid email profile`; Authentik's default `profile`
mapping emits the `groups` claim the API checks).
- Note the generated **Client ID** — it is the audience below and the
PWA's `VITE_AUTHENTIK_CLIENT_ID`.
2. **Application** — slug **`nestquest`**, bound to the provider above.
The slug fixes the issuer URL.
3. **Group** — **`nestquest-admins`**. Add each parent's Authentik user.
Membership is the single source of truth for "who is an admin"; the
API refuses a signed-in non-member with 403.
API settings (in `deploy/.env`, section 5):
| Variable | Value |
| --- | --- |
| `NESTQUEST_OIDC_ISSUER` | `https://auth.cubecraftlabs.com/application/o/nestquest/` |
| `NESTQUEST_OIDC_AUDIENCE` | the provider's Client ID |
| `NESTQUEST_OIDC_JWKS_URL` | `https://auth.cubecraftlabs.com/application/o/nestquest/jwks/` |
Check them against Authentik's discovery document (the issuer must match
byte for byte, including the trailing slash):
curl -s https://auth.cubecraftlabs.com/application/o/nestquest/.well-known/openid-configuration \
| python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["issuer"]); print(d["jwks_uri"])'
## 5. Secrets
Nothing below is ever committed; `.gitignore` excludes `.env`,
`**/.env`, `deploy/*key*` and `deploy/litestream_key*`.
**`deploy/.env`** — created on the API box from the committed example:
cp deploy/.env.example deploy/.env
chmod 600 deploy/.env
# edit deploy/.env and fill in:
# NESTQUEST_PANEL_TOKEN = a new random token, e.g.
# python3 -c "import secrets; print(secrets.token_urlsafe(32))"
# (the same value is configured in the HA integration)
# NESTQUEST_OIDC_ISSUER = section 4
# NESTQUEST_OIDC_AUDIENCE = section 4 (Authentik Client ID)
# NESTQUEST_OIDC_JWKS_URL = section 4
# NESTQUEST_BIND_ADDRESS = 10.60.1.14
The API fails fast at startup if any of the four API
variables is unset or empty (`api/config.py`); `dc logs api` names the
missing one. `NESTQUEST_BIND_ADDRESS` is read by compose only.
**Litestream SFTP key `deploy/litestream_key`** — a dedicated keypair that
lives only on the API box. Create it once, before the first `up`:
ssh-keygen -t ed25519 -N "" -C nestquest-litestream -f deploy/litestream_key
sudo chown 999:999 deploy/litestream_key
chmod 600 deploy/litestream_key
Then append `restrict ` followed by the contents of
`deploy/litestream_key.pub` as one line to
`joshua@10.60.1.50:~/.ssh/authorized_keys` on the NAS. Compose mounts the
private key read-only at `/etc/litestream/sftp_key` in the sidecar, which
runs as uid 999 — hence the ownership. The NAS host key is pinned in the
committed `deploy/litestream.yml` (`host-key`, the NAS's ECDSA key), so no
`known_hosts` is involved.
| Secret | Supplied by | Consumed by |
| --- | --- | --- |
| `NESTQUEST_PANEL_TOKEN` | `deploy/.env` → `env_file` | `api` (panel plane); also set in the HA integration |
| `NESTQUEST_OIDC_*` (not secret, but environment-supplied) | `deploy/.env` → `env_file` | `api` (admin plane) |
| SFTP private key | `deploy/litestream_key` → read-only bind mount | `litestream` |
| Cloudflare DNS API token | Traefik deployment on nukapi-03 | Traefik ACME `myresolver` |
## 6. Network separation and firewall
- **Panel plane** (`/api/v1/panel/*`, static service token): reachable
only from the HA box. Traefik's `ipAllowList` on the panel router allows
`10.60.1.80/32` and returns **403** to every other source, before the
request reaches the API. The API additionally requires the panel token
(401 without it).
- **Admin plane** (`/api/v1/admin/*`) and `/health`, `/docs`: public
through Cloudflare and Traefik; admin routes are protected by the API's
Authentik JWT check (401 without a valid token, 403 without
`nestquest-admins` or when a panel token is presented).
- **Local DNS override** so the HA box reaches Traefik directly, keeping
its real source address: in Pi-hole (`10.60.1.101`) local DNS records,
add `nestquest.cubecraftlabs.com` → `10.60.1.33`. The HA box
must use Pi-hole as its resolver. Check from the HA box:
nslookup nestquest.cubecraftlabs.com 10.60.1.101 # Address: 10.60.1.33
- **Direct `:8080` access is firewalled.** The API box publishes `8080`
on `10.60.1.14`, which alone would let any LAN host bypass Traefik and
the panel `ipAllowList`. This is enforced on the API box in Docker's
`DOCKER-USER` chain (which Docker evaluates before its own forwarding
rules for published ports), in this order:
-A DOCKER-USER -s 10.60.1.33/32 -p tcp --dport 8080 -j RETURN # Traefik on nukapi-03
-A DOCKER-USER -s 10.60.1.14/32 -p tcp --dport 8080 -j RETURN # the API box itself
-A DOCKER-USER -p tcp --dport 8080 -j DROP # every other source
The rules are persisted by the systemd oneshot unit
**`nestquest-api-firewall.service`**, committed as
`deploy/systemd/nestquest-api-firewall.service` (ordered after
`docker.service`, it idempotently applies the three rules at every
boot). Install and enable it on the API box, from the repository
checkout, **before** exposing the API:
sudo cp deploy/systemd/nestquest-api-firewall.service /etc/systemd/system/ \
&& sudo systemctl daemon-reload \
&& sudo systemctl enable --now nestquest-api-firewall.service
The HA box and every other client must use the Traefik hostname,
never `:8080` directly. Check it:
sudo systemctl is-enabled nestquest-api-firewall.service # enabled
sudo systemctl is-active nestquest-api-firewall.service # active
sudo iptables -S DOCKER-USER # the three rules above, in that order
# on nukapi-03 (10.60.1.33) — allowed:
curl -s -o /dev/null -w '%{http_code}\n' http://10.60.1.14:8080/health # 200
# on any other LAN host, e.g. 10.60.1.101 — dropped:
curl -s -m 5 -o /dev/null -w '%{http_code}\n' http://10.60.1.14:8080/health # 000, timeout
# public path still works:
curl -s -o /dev/null -w '%{http_code}\n' https://nestquest.cubecraftlabs.com/health # 200
On a rebuilt API box, install the unit with the commands above before
exposing the API. The committed file is the authoritative copy; the
deployed unit must match it:
diff deploy/systemd/nestquest-api-firewall.service \
/etc/systemd/system/nestquest-api-firewall.service # no output
## 7. Backup (Litestream to the Synology NAS)
The `litestream` sidecar (config `deploy/litestream.yml`, mounted at
`/etc/litestream.yml`) replicates `/var/lib/nestquest/nestquest.db` to:
- SFTP `joshua@10.60.1.50`, path `/homes/Joshua/nestquest-backups` (the
NAS's SFTP view is chrooted to the shared folders; over SSH the same
directory is `/volume1/homes/Joshua/nestquest-backups`).
- Every committed change is shipped as an LTX file within about a second.
Litestream 0.5.17 compacts them into coarser levels on its built-in
schedule (level 1 every 30s, level 2 every 5m, level 3 every 1h).
- **Snapshots**: `snapshot.interval: 24h` (a full snapshot daily);
**retention**: `snapshot.retention: 168h` — a week of snapshots plus the
changes between them, i.e. a 7-day point-in-time restore window.
The sidecar runs as uid 999 with a read-only root filesystem,
`no-new-privileges` and all capabilities dropped. It needs the database
volume read-write (it keeps its `_litestream_*` tables and writes the
WAL); its local state lives beside the database in
`/var/lib/nestquest/.nestquest.db-litestream/`.
Check it:
dc ps litestream # Up
dc logs --tail 50 litestream # no "error" lines
dc exec litestream litestream status # status "ok", local txid advancing
dc exec litestream litestream ltx /var/lib/nestquest/nestquest.db | tail # newest LTX files and timestamps
A change made in the app should appear as a new level-0 LTX file within
seconds. On the NAS, the files are under
`/volume1/homes/Joshua/nestquest-backups/ltx/`.
## 8. Restore
Restores the database from the SFTP replica into the `nestquest-db`
volume at `NESTQUEST_DB_PATH` (`/var/lib/nestquest/nestquest.db`). The
same procedure serves both a damaged database on the existing box and a
rebuilt box. The restore runs in one-off `litestream` containers so it
has the same user (999), volume, config and SFTP key as the sidecar.
**0. Fresh box only.** Complete sections 1 and 5, then start **only the
API** once so the volume exists and is owned by uid 999:
dc up -d api
Do not start `litestream` yet — it would begin replicating the new,
empty database the API just created. The swap in step 4 moves that empty
file aside, and step 5 creates and starts the sidecar with
`dc up -d litestream` once the API is healthy.
**1. Stop writers** — both the API and the sidecar (Litestream must not
replicate while the file is being replaced):
dc stop api litestream
**2. Restore beside the live database** (never over it), with a full
integrity check:
dc run --rm --no-deps litestream restore \
-config /etc/litestream.yml \
-integrity-check full \
-o /var/lib/nestquest/nestquest.db.restored \
/var/lib/nestquest/nestquest.db
Expect `post-restore integrity check passed` and exit code 0. For a
point in time within the retention window, add
`-timestamp 2026-09-24T12:00:00Z` (UTC). To preview without writing, add
`-dry-run`.
**3. Inspect the restored file** before switching to it — confirm known
children and definitions are present:
dc run --rm --no-deps --entrypoint sqlite3 litestream \
/var/lib/nestquest/nestquest.db.restored \
'PRAGMA integrity_check;' \
'SELECT id, display_name FROM children;' \
'SELECT id, title FROM quest_definitions;'
Expect `ok`, then the household's children and quest definitions.
**4. Swap it into place**, keeping the old files (database, its
`-wal`/`-shm`, and Litestream's local state) in a timestamped directory
on the volume:
dc run --rm --no-deps --entrypoint sh litestream -c '
set -e
cd /var/lib/nestquest
ts=$(date -u +%Y%m%dT%H%M%SZ)
mkdir -p "pre-restore-$ts"
for f in nestquest.db nestquest.db-wal nestquest.db-shm .nestquest.db-litestream; do
if [ -e "$f" ]; then mv "$f" "pre-restore-$ts/"; fi
done
mv nestquest.db.restored nestquest.db
ls -la'
**5. Start the API, then the sidecar:**
dc start api
dc ps api # wait for "healthy"
dc up -d litestream
dc ps litestream # Up
dc logs --tail 20 litestream
Use `dc up -d litestream`, not `dc start`: on a fresh box step 0 never
created the sidecar container, and `start` cannot start a container that
does not exist. `up -d` creates it if needed (or starts the existing one),
so continuous replication is back online on both paths.
The sidecar resumes replication from the restored position (it logs
`detected database behind replica` / `fetched latest L0 file from
replica`, then continues normally).
**6. Verify through the API** — the panel snapshot lists the restored
children. On the API box against `10.60.1.14:8080` directly (other LAN
hosts, including the HA box, are dropped on `:8080` by the section 6
firewall; from the HA box use the Traefik hostname instead):
PANEL_TOKEN=$(grep '^NESTQUEST_PANEL_TOKEN=' deploy/.env | cut -d= -f2-)
curl -s -H "Authorization: Bearer $PANEL_TOKEN" \
http://10.60.1.14:8080/api/v1/panel/snapshot
Expect HTTP 200 and `children` naming the known child(ren). Then run
section 9.
Once satisfied, remove the old copy:
`dc run --rm --no-deps --entrypoint rm litestream -rf /var/lib/nestquest/pre-restore-<ts>`.
This exact sequence (stop, restore with integrity check, inspect, swap,
start, snapshot shows the restored child, replication resumes) was
rehearsed against a local file replica with the committed compose file;
the live proof against the SFTP replica is recorded separately by the
controller.
## 9. Verification checklist
Run after every deploy and every restore. `$PANEL_TOKEN` is the value from
`deploy/.env`; never paste it into shared logs.
| # | Check | Command | Expect |
| --- | --- | --- | --- |
| 1 | Health over TLS | `curl -s -o /dev/null -w '%{http_code}\n' https://nestquest.cubecraftlabs.com/health` | `200` |
| 2 | Valid certificate | `curl -sv https://nestquest.cubecraftlabs.com/health 2>&1 \| grep -E 'issuer\|expire date'` | Let's Encrypt issuer, future expiry (no `-k` needed) |
| 3 | Docs public | `curl -s -o /dev/null -w '%{http_code}\n' https://nestquest.cubecraftlabs.com/docs` | `200` |
| 4 | Panel refused externally | from any host other than `10.60.1.80` (e.g. a phone off Wi-Fi, or a LAN machine): `curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $PANEL_TOKEN" https://nestquest.cubecraftlabs.com/api/v1/panel/snapshot` | `403` (Traefik allowlist) |
| 5 | Panel allowed from HA box | on `10.60.1.80`: same command | `200`, snapshot JSON |
| 6 | Panel needs the token | on `10.60.1.80`, without the header | `401` |
| 7 | Admin JWT accepted | `curl -s -w '\n%{http_code}\n' -H "Authorization: Bearer $ADMIN_JWT" https://nestquest.cubecraftlabs.com/api/v1/admin/ping` with a token of a `nestquest-admins` member | `200`, `{"status":"ok","sub":...}` |
| 8 | Non-admin refused | same, with a token of a user **not** in `nestquest-admins` | `403`, "Admin access requires membership in the nestquest-admins group" |
| 9 | No/invalid token refused | same, without a header or with garbage | `401` |
| 10 | Panel token refused on admin | same, with `$PANEL_TOKEN` | `403` |
| 11 | Backup running | `dc exec litestream litestream status` | status `ok` |
To obtain `$ADMIN_JWT`: sign in to the admin PWA as the user, open the
browser developer tools, and copy the session-storage value
`nestquest.access_token`. Tokens are short-lived and are credentials —
do not store them.
## 10. Admin PWA hosting
The admin PWA (`admin/`, a Vite + React single-page app) is served from
the API box by the compose service **`pwa`**: nginx on container port
`80`, published on `${NESTQUEST_BIND_ADDRESS:-127.0.0.1}:8081` (on the API
box `10.60.1.14:8081`). Traefik sends every path of
`nestquest.cubecraftlabs.com` that is not the API to it.
**Image** — `deploy/pwa/Dockerfile`, built from the **repository root**
(it needs `admin/`); `deploy/pwa/Dockerfile.dockerignore` limits the
context to `admin/` (without `node_modules`, `dist` or `.env` files) and
`deploy/pwa/nginx.conf`.
- Stage 1, `node:22-alpine` (pinned by digest): `npm ci`, then
`npm run build` with the three `VITE_*` build args below. Vite bakes
them into the bundle, so **changing any of them needs a rebuild**. The
build fails if any is empty.
- Stage 2, `nginx:alpine` pinned to
`sha256:1ed1b0e1d7652937d6cbdaf4018c7b6fc009a7dd6c3047351e2eddda745de43f`
(nginx 1.31.6): the built `dist/` in `/usr/share/nginx/html` and
`deploy/pwa/nginx.conf` as `conf.d/default.conf`.
**Build args** — compose reads them from `deploy/.env` (documented in
`deploy/.env.example`). They are **public values, not secrets**: the
Authentik application is a PKCE client with no client secret.
| `deploy/.env` variable | Build arg | Production value |
| --- | --- | --- |
| `NESTQUEST_AUTHENTIK_CLIENT_ID` | `VITE_AUTHENTIK_CLIENT_ID` | client id of the Authentik NestQuest application (Authentik admin → Applications → Providers) |
| `NESTQUEST_AUTHENTIK_ISSUER` | `VITE_AUTHENTIK_ISSUER` | `https://auth.cubecraftlabs.com/application/o/nestquest/` |
| `NESTQUEST_API_BASE_URL` | `VITE_API_BASE_URL` | `https://nestquest.cubecraftlabs.com` |
The Authentik application's redirect URI must include
`https://nestquest.cubecraftlabs.com/auth/callback`.
**nginx** (`deploy/pwa/nginx.conf`):
- `allow 10.60.1.33; allow 10.60.1.14; deny all;` — only Traefik on
nukapi-03 and the API box itself get content; any other source gets
`403`, even with the port reachable on the LAN. Checks run on the API
box must use its LAN address (`10.60.1.14:8081`), not `127.0.0.1`.
- SPA fallback: unknown paths (e.g. `/auth/callback`) serve `index.html`;
`/assets/*` (content-hashed, cached for a year) returns a real `404`
when missing.
- `/sw.js` and `/manifest.webmanifest` (`application/manifest+json`) are
served from the site root with `Cache-Control: no-cache`, as is
`index.html`, so a new release's service worker is picked up.
Build and start (the `api` and `litestream` services are unaffected):
dc build pwa
dc up -d pwa
dc ps pwa # "Up"
**Traefik router** — in `config/dynamic/nestquest-ccl.yml` on nukapi-03
(reference shape in section 3):
| Router | Rule | Priority | Service |
| --- | --- | --- | --- |
| `nestquest-app` | ``Host(`nestquest.cubecraftlabs.com`) && !PathPrefix(`/api`) && !Path(`/health`) && !Path(`/openapi.json`) && !PathPrefix(`/docs`)`` | `50` — below `nestquest-admin` (100) and `nestquest-panel` (200) | `nestquest-pwa` → `http://10.60.1.14:8081` |
Same `websecure` entrypoint and `myresolver` certificate as the API
routers; no Traefik middleware (nginx enforces the source allow-list).
The file provider reloads the dynamic file on save.
**Verification** (in addition to section 9):
| # | Check | Command | Expect |
| --- | --- | --- | --- |
| 1 | PWA root over TLS | `curl -s -w '\n%{http_code}\n' https://nestquest.cubecraftlabs.com/ \| tail -3` | `200`, the `NestQuest Admin` shell |
| 2 | Client route fallback | `curl -s -o /dev/null -w '%{http_code} %{content_type}\n' https://nestquest.cubecraftlabs.com/auth/callback` | `200 text/html` |
| 3 | Manifest and worker | `curl -s -o /dev/null -w '%{http_code} %{content_type}\n' https://nestquest.cubecraftlabs.com/manifest.webmanifest` and the same for `/sw.js` | `200 application/manifest+json`, `200 application/javascript` |
| 4 | API still routed to the API | `curl -s -o /dev/null -w '%{http_code}\n' https://nestquest.cubecraftlabs.com/health` | `200` (`{"status":"ok"}`, not HTML) |
| 5 | Panel refused externally | section 9 check 4 | `403` |
| 6 | Non-Traefik source refused | from a LAN machine other than `10.60.1.33`/`10.60.1.14`: `curl -s -o /dev/null -w '%{http_code}\n' http://10.60.1.14:8081/` | `403` (nginx `deny all`) |
| 7 | Proxy source allowed | on `10.60.1.14`: `curl -s -o /dev/null -w '%{http_code}\n' http://10.60.1.14:8081/` | `200` |
## 11. Upgrades and rollback
The API applies pending schema migrations when it starts (FastAPI
lifespan, before `/health` answers), so **the first start of a new
version is the point of no return** for any migration it carries. A
build refuses a database whose schema version is newer than it
understands ("newer than this integration understands … downgrades are
not supported") and does not start.
### Migration 9 (multiple presence patterns)
Migration 9 creates `presence_patterns`, copies every row of the old
one-per-child `presence_schedules` table into it as a `home` pattern
named `Home schedule`, and **drops `presence_schedules`**. Version 0.7.1
refuses the resulting version-9 database, and could not read
`presence_patterns` anyway, so the only way back to 0.7.1 is a copy of
the database taken **before** the first start on the new version.
**Before the first start on the new version**, with the old version
still deployed:
1. Stop writers (as section 8 step 1):
dc stop api litestream
2. Copy the database file beside the live one with SQLite's online
backup (includes anything still in the WAL), then check it:
ts=$(date -u +%Y%m%dT%H%M%SZ)
dc run --rm --no-deps --entrypoint sqlite3 litestream \
/var/lib/nestquest/nestquest.db \
".backup /var/lib/nestquest/pre-v9-$ts.db"
dc run --rm --no-deps --entrypoint sqlite3 litestream \
/var/lib/nestquest/pre-v9-$ts.db \
'PRAGMA integrity_check;' \
'SELECT version FROM nestquest_schema_version;' \
'SELECT count(*) FROM presence_schedules;'
Expect `ok`, schema version `8`, and the number of presence
schedules. Write down `$ts`.
3. Also record the Litestream replica position and the UTC time, so a
point-in-time restore (section 8, `-timestamp`) can reach the
pre-upgrade state even if the local copy is lost:
dc up -d litestream
dc exec litestream litestream status # note the txid
date -u +%Y-%m-%dT%H:%M:%SZ # note the time
dc stop litestream
The replica only covers the 7-day retention window (section 7).
4. Deploy the new version (sections 1–2) and run section 9. Confirm the
live database is at version `9` (the section 8 step 3 `sqlite3`
command against `nestquest.db`, with
`'SELECT version FROM nestquest_schema_version;'`) and that the
Schedule tab lists each child's old schedule as a `Home schedule`
pattern.
**Rollback to 0.7.1:** check out and build 0.7.1 (section 1), then put
the pre-upgrade database back with section 8: either steps 1 and 4–6
with `pre-v9-<ts>.db` in place of `nestquest.db.restored`, or the full
restore with `-timestamp` set to the time noted in step 3. Presence
pattern changes made after the upgrade are not in that copy and are
lost. Once the new version has proven itself, remove the copy:
`dc run --rm --no-deps --entrypoint rm litestream -f /var/lib/nestquest/pre-v9-<ts>.db`.
This rollback has not yet been rehearsed.
-98
View File
@@ -1,98 +0,0 @@
# Compose deployment scaffold for the NestQuest API service (Feature
# 17). The SQLite database lives on the NAMED VOLUME ``nestquest-db``
# mounted at /var/lib/nestquest — recreating the container keeps the
# household data (``docker compose down`` leaves named volumes alone).
#
# Configuration is supplied by the environment: the fixed database
# path here, and the secret values (panel service token, Authentik
# OIDC settings) from ``deploy/.env`` — a git-ignored file you create
# from ``deploy/.env.example`` (placeholder names only; never commit
# real values).
#
# TLS is terminated by the shared Traefik reverse proxy on another
# host, which forwards to this service on port 8080. The published
# port binds NESTQUEST_BIND_ADDRESS (read from deploy/.env, the
# project directory's env file): it defaults to 127.0.0.1 so an
# unconfigured deployment is never exposed; set it to the host's LAN
# address on the API box so the proxy can reach it.
services:
api:
build:
context: ..
dockerfile: Dockerfile
image: nestquest-api:latest
init: true
restart: unless-stopped
ports:
- "${NESTQUEST_BIND_ADDRESS:-127.0.0.1}:8080:8080"
environment:
# The SQLite file inside the named volume; fixed, not a secret.
NESTQUEST_DB_PATH: /var/lib/nestquest/nestquest.db
env_file:
# Secret values (NESTQUEST_PANEL_TOKEN, NESTQUEST_OIDC_*); absent
# until you create deploy/.env from the example.
- path: .env
required: false
volumes:
- nestquest-db:/var/lib/nestquest
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health')"]
interval: 10s
timeout: 5s
retries: 5
start_period: 15s
# Admin PWA (Feature 24): the Vite bundle from admin/ served by nginx
# (deploy/pwa/). Traefik routes every non-API path of the public host
# here on port 8081; nginx itself only accepts the proxy (10.60.1.33)
# and this host (10.60.1.14). The three build args are PUBLIC values
# (the OIDC client is a PKCE client, no secret) read from deploy/.env
# by compose interpolation; the image build fails if any is empty.
pwa:
build:
context: ..
dockerfile: deploy/pwa/Dockerfile
args:
VITE_AUTHENTIK_CLIENT_ID: ${NESTQUEST_AUTHENTIK_CLIENT_ID:-}
VITE_AUTHENTIK_ISSUER: ${NESTQUEST_AUTHENTIK_ISSUER:-}
VITE_API_BASE_URL: ${NESTQUEST_API_BASE_URL:-}
image: nestquest-pwa:latest
restart: unless-stopped
ports:
- "${NESTQUEST_BIND_ADDRESS:-127.0.0.1}:8081:80"
# Continuous backup: streams the SQLite database on the shared named
# volume to the Synology NAS over SFTP (config: deploy/litestream.yml).
# The SFTP private key deploy/litestream_key is git-ignored and must be
# created on the API box before starting (see api/README.md).
#
# The database volume is mounted READ-WRITE on purpose: Litestream
# cannot run against a read-only mount ("unable to open database file
# (14)", even with its metadata moved elsewhere) because it writes its
# _litestream_seq/_litestream_lock tables into the database, opens the
# -wal/-shm files for writing, and checkpoints the WAL. The write
# access is contained instead: it runs as the API's own non-root user
# (uid/gid 999, owner of the volume) with a read-only root filesystem,
# no privilege escalation and no Linux capabilities.
litestream:
image: litestream/litestream:0.5.17@sha256:4b02b9859a6b6b4087d8b8944e15f7e984bd7957cba322bbeee38b0e27b9656a
restart: unless-stopped
command: ["replicate", "-config", "/etc/litestream.yml"]
user: "999:999"
read_only: true
tmpfs:
- /tmp
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
depends_on:
api:
condition: service_healthy
volumes:
- nestquest-db:/var/lib/nestquest
- ./litestream.yml:/etc/litestream.yml:ro
- ./litestream_key:/etc/litestream/sftp_key:ro
volumes:
nestquest-db:
-32
View File
@@ -1,32 +0,0 @@
# Litestream continuous backup of the NestQuest SQLite database (Feature
# 17). The ``litestream`` compose service mounts the same named volume
# as the API and streams every committed change to the Synology NAS
# over SFTP, so the backup lives OUTSIDE the container's volume.
#
# Nothing here is secret. The SFTP private key is a dedicated,
# git-ignored keypair (deploy/litestream_key) mounted read-only by
# compose at /etc/litestream/sftp_key; its public half is in
# joshua@10.60.1.50:~/.ssh/authorized_keys. ``host-key`` pins the
# NAS's host key so the connection is verified; it must be the ECDSA
# key, because that is the algorithm Litestream's SSH client negotiates
# with this NAS (pinning the ed25519 key fails with "host key mismatch").
#
# The Synology SFTP server is chrooted to the shared folders, so the
# directory seen over SSH as /volume1/homes/Joshua/nestquest-backups is
# /homes/Joshua/nestquest-backups over SFTP.
# Take a full snapshot daily and keep a week of snapshots plus the
# incremental changes between them (point-in-time restore window).
snapshot:
interval: 24h
retention: 168h
dbs:
- path: /var/lib/nestquest/nestquest.db
replicas:
- type: sftp
host: 10.60.1.50
user: joshua
path: /homes/Joshua/nestquest-backups
key-path: /etc/litestream/sftp_key
host-key: ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNujay9nYEiXuRQf4wDRDU1gp+CDvpeMdhuhC2XypIihzKGEtB654kwrUGfA2kDWAoSPGlmojeS3OIRtHPkj6GY=
-29
View File
@@ -1,29 +0,0 @@
# Admin PWA image (Feature 24): builds the Vite bundle from admin/ and
# serves it with nginx. Build context is the REPOSITORY ROOT (it needs
# admin/); deploy/pwa/Dockerfile.dockerignore limits that context to
# admin/ and this directory's nginx.conf.
#
# docker compose -f deploy/compose.yaml build pwa
#
# The VITE_* values are baked into the bundle at build time. None is a
# secret (the OIDC client is a public PKCE client), and all three are
# required: the build fails fast rather than relying on app defaults.
FROM node:22-alpine@sha256:0a7108bf6c7bf5de370ffb1a3ed6be93d405b43ff159f681a8d18c0e2bc2e402 AS build
ARG VITE_AUTHENTIK_CLIENT_ID
ARG VITE_AUTHENTIK_ISSUER
ARG VITE_API_BASE_URL
WORKDIR /src/admin
COPY admin/package.json admin/package-lock.json ./
RUN npm ci
COPY admin/ ./
RUN test -n "$VITE_AUTHENTIK_CLIENT_ID" && test -n "$VITE_AUTHENTIK_ISSUER" && test -n "$VITE_API_BASE_URL" \
|| { echo "VITE_AUTHENTIK_CLIENT_ID, VITE_AUTHENTIK_ISSUER and VITE_API_BASE_URL build args are required" >&2; exit 1; }
RUN npm run build
FROM nginx:alpine@sha256:1ed1b0e1d7652937d6cbdaf4018c7b6fc009a7dd6c3047351e2eddda745de43f
COPY deploy/pwa/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /src/admin/dist/ /usr/share/nginx/html/
-11
View File
@@ -1,11 +0,0 @@
# Build-context filter for deploy/pwa/Dockerfile (BuildKit reads
# <Dockerfile>.dockerignore in place of the root .dockerignore, which
# excludes deploy/). Only admin/ sources and nginx.conf enter the
# build; local dependencies, build output and .env files never do.
*
!admin/
!deploy/pwa/nginx.conf
admin/node_modules
admin/dist
**/.env
**/.env.*
-53
View File
@@ -1,53 +0,0 @@
# nginx server for the NestQuest admin PWA (Feature 24). Replaces the
# image's /etc/nginx/conf.d/default.conf. The shared Traefik on
# nukapi-03 (10.60.1.33) terminates TLS for nestquest.cubecraftlabs.com
# and forwards every path that is not the API (/api, /health,
# /openapi.json, /docs) here; see deploy/RUNBOOK.md section 10.
server {
listen 80;
server_name _;
# Only the reverse proxy and the API box itself may connect; every
# other source is refused (403) even if the port is reachable.
allow 10.60.1.33;
allow 10.60.1.14;
deny all;
root /usr/share/nginx/html;
index index.html;
server_tokens off;
# Content-hashed bundle files: cache forever, and a missing asset is
# a real 404 rather than the SPA shell.
location /assets/ {
try_files $uri =404;
add_header Cache-Control "public, max-age=31536000, immutable";
}
# The service worker must be revalidated on every load so a new
# release's worker (fresh revision, see admin/vite-sw-plugin.ts) is
# picked up.
location = /sw.js {
try_files $uri =404;
add_header Cache-Control "no-cache";
}
# nginx's stock mime.types has no .webmanifest entry.
location = /manifest.webmanifest {
types { }
default_type application/manifest+json;
try_files $uri =404;
add_header Cache-Control "no-cache";
}
# SPA fallback: client routes such as /auth/callback resolve to the
# app shell, which is never cached so it always names the current
# hashed assets.
location / {
try_files $uri $uri/ /index.html;
}
location = /index.html {
add_header Cache-Control "no-cache";
}
}

Some files were not shown because too many files have changed in this diff Show More