Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e0474ef71 | ||
|
|
e287c145b0 | ||
|
|
7adee7c3c0 | ||
|
|
59e072602b | ||
|
|
87566689aa | ||
|
|
744d80e645 | ||
|
|
8f38946c04 | ||
|
|
9916d83138 | ||
|
|
c5b313a5e3 |
@@ -1,217 +1,5 @@
|
||||
# NestQuest Release Notes
|
||||
|
||||
## 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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -17,14 +17,6 @@ export interface HouseholdSettings {
|
||||
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;
|
||||
/**
|
||||
* True once the admin explicitly chose `timezone` (even ""); false on a
|
||||
* fresh install, where the screen auto-sets the browser's zone. API-only:
|
||||
* never shown in the form.
|
||||
*/
|
||||
timezone_configured: boolean;
|
||||
}
|
||||
|
||||
/** Only the supplied fields are updated; the API answers with all of them. */
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -121,8 +121,6 @@ function fakeApi(initial: QuestDefinition[]) {
|
||||
const calls: Call[] = [];
|
||||
let nextWrite: Response | null = null;
|
||||
let preview: PreviewHandler = async () => jsonResponse({ dates: [] });
|
||||
// Definitions with completion history: the API retires these on DELETE.
|
||||
const withHistory = new Set<number>();
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL, init: RequestInit = {}) => {
|
||||
const path = new URL(String(input), "http://localhost").pathname;
|
||||
const method = init.method ?? "GET";
|
||||
@@ -189,16 +187,6 @@ function fakeApi(initial: QuestDefinition[]) {
|
||||
);
|
||||
return jsonResponse(definitions.find((d) => d.id === id));
|
||||
}
|
||||
if (method === "DELETE" && match) {
|
||||
const id = Number(match[1]);
|
||||
if (withHistory.has(id)) {
|
||||
definitions = definitions.map((d) => (d.id === id ? { ...d, is_active: false } : d));
|
||||
const retired = definitions.find((d) => d.id === id);
|
||||
return jsonResponse({ definition_id: id, deleted: false, retired: true, definition: retired });
|
||||
}
|
||||
definitions = definitions.filter((d) => d.id !== id);
|
||||
return jsonResponse({ definition_id: id, deleted: true, retired: false, definition: null });
|
||||
}
|
||||
return jsonResponse({ detail: "unexpected" }, 500);
|
||||
});
|
||||
return {
|
||||
@@ -215,9 +203,6 @@ function fakeApi(initial: QuestDefinition[]) {
|
||||
failNextWrite: (response: Response) => {
|
||||
nextWrite = response;
|
||||
},
|
||||
markHistory: (id: number) => {
|
||||
withHistory.add(id);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -593,15 +578,14 @@ describe("DefinitionsTab", () => {
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
const s = sheet();
|
||||
const title = within(s).getByRole("textbox", { name: "Title" });
|
||||
// The edit sheet's last focusable control is its Delete button.
|
||||
const last = within(s).getByRole("button", { name: "Delete task" });
|
||||
const save = within(s).getByRole("button", { name: "Save changes" });
|
||||
|
||||
last.focus();
|
||||
save.focus();
|
||||
fireEvent.keyDown(s, { key: "Tab" });
|
||||
expect(document.activeElement).toBe(title);
|
||||
|
||||
fireEvent.keyDown(s, { key: "Tab", shiftKey: true });
|
||||
expect(document.activeElement).toBe(last);
|
||||
expect(document.activeElement).toBe(save);
|
||||
});
|
||||
|
||||
it("Escape does not close the sheet while saving", async () => {
|
||||
@@ -710,73 +694,6 @@ describe("DefinitionsTab", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("the Delete control is only offered for an existing task", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByRole("button", { name: "New" }));
|
||||
expect(within(sheet()).queryByRole("button", { name: "Delete task" })).toBeNull();
|
||||
fireEvent.click(within(sheet()).getByRole("button", { name: "Cancel" }));
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
expect(within(sheet()).getByRole("button", { name: "Delete task" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Delete asks first, explaining delete-vs-retire; Go back writes nothing", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
|
||||
const confirm = screen.getByTestId("delete-confirm");
|
||||
expect(confirm.textContent).toContain("If it has no completion history it is deleted");
|
||||
expect(confirm.textContent).toContain("otherwise it is retired");
|
||||
expect(api.writes()).toHaveLength(0);
|
||||
fireEvent.click(within(confirm).getByRole("button", { name: "Go back" }));
|
||||
expect(screen.queryByTestId("delete-confirm")).toBeNull();
|
||||
expect(api.writes()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("confirming Delete on a task without history removes its row", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
|
||||
fireEvent.click(
|
||||
within(screen.getByTestId("delete-confirm")).getByRole("button", { name: "Delete task" }),
|
||||
);
|
||||
await waitFor(() => expect(screen.queryByTestId("definition-10")).toBeNull());
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
expect(api.writes()).toEqual([
|
||||
{ method: "DELETE", path: "/api/v1/admin/quest-definitions/10", body: null },
|
||||
]);
|
||||
expect(screen.getByTestId("definition-11")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("confirming Delete on a task with history shows it retired (inactive)", async () => {
|
||||
await renderReady();
|
||||
api.markHistory(10);
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
|
||||
fireEvent.click(
|
||||
within(screen.getByTestId("delete-confirm")).getByRole("button", { name: "Delete task" }),
|
||||
);
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
|
||||
const row = screen.getByTestId("definition-10");
|
||||
expect(row.className).toContain("defs-row--inactive");
|
||||
expect(meta(row)).toContain("· inactive");
|
||||
expect(api.writes().map((c) => c.method)).toEqual(["DELETE"]);
|
||||
});
|
||||
|
||||
it("a failed Delete shows the API's detail and keeps the sheet open", async () => {
|
||||
await renderReady();
|
||||
api.failNextWrite(jsonResponse({ detail: "Quest definition not found" }, 404));
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
|
||||
fireEvent.click(
|
||||
within(screen.getByTestId("delete-confirm")).getByRole("button", { name: "Delete task" }),
|
||||
);
|
||||
expect((await screen.findByTestId("sheet-error")).textContent).toBe(
|
||||
"Quest definition not found",
|
||||
);
|
||||
expect(screen.getByRole("dialog")).toBeTruthy();
|
||||
expect(screen.getByTestId("definition-10")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("scroll column carries the 92px bottom padding", async () => {
|
||||
await renderReady();
|
||||
expect(screen.getByTestId("definitions-scroll").style.paddingBottom).toBe("92px");
|
||||
|
||||
@@ -13,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,
|
||||
@@ -275,12 +273,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];
|
||||
}
|
||||
@@ -457,13 +449,11 @@ function EditSheet({
|
||||
activeChildren,
|
||||
onCancel,
|
||||
onSaved,
|
||||
onDeleted,
|
||||
}: {
|
||||
target: "new" | QuestDefinition;
|
||||
activeChildren: AdminChild[];
|
||||
onCancel: () => void;
|
||||
onSaved: () => void;
|
||||
onDeleted: (result: DefinitionDeleteResult) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<Draft>(() =>
|
||||
target === "new" ? newDraft(activeChildren) : draftFrom(target, activeChildren),
|
||||
@@ -483,7 +473,6 @@ function EditSheet({
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
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);
|
||||
@@ -501,8 +490,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") {
|
||||
@@ -570,21 +559,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
|
||||
@@ -932,56 +906,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>
|
||||
@@ -1105,21 +1038,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>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
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";
|
||||
@@ -22,8 +21,6 @@ const DEFAULT_SETTINGS: HouseholdSettings = {
|
||||
afternoon_reminder_enabled: false,
|
||||
end_of_day_report_enabled: true,
|
||||
celebration_enabled: false,
|
||||
timezone: "America/Chicago",
|
||||
timezone_configured: true,
|
||||
};
|
||||
|
||||
function child(
|
||||
@@ -373,11 +370,10 @@ describe("SettingsScreen — preferences", () => {
|
||||
fireEvent.click(within(form).getByRole("button", { name: "Save preferences" }));
|
||||
}
|
||||
|
||||
it("renders the current value of all eleven settings form fields", async () => {
|
||||
it("renders the current value of the ten settings form fields (timezone is API-only)", 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");
|
||||
@@ -500,48 +496,6 @@ describe("SettingsScreen — preferences", () => {
|
||||
expect(writes()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("a changed timezone patches exactly the timezone", async () => {
|
||||
const { form } = await renderPreferences();
|
||||
const input = field(form, "Timezone");
|
||||
expect(input.getAttribute("list")).toBe("settings-timezones");
|
||||
fireEvent.change(input, { target: { value: " Europe/London " } });
|
||||
save(form);
|
||||
await screen.findByText("Preferences saved.");
|
||||
expect(writes()).toEqual([
|
||||
{ method: "PATCH", path: SETTINGS_PATH, body: { timezone: "Europe/London", timezone_configured: true } },
|
||||
]);
|
||||
const reloaded = screen.getByRole("form", { name: "Preferences" });
|
||||
expect(field(reloaded, "Timezone").value).toBe("Europe/London");
|
||||
});
|
||||
|
||||
it.each(["New York", "America/New York", "EST5EDT?", "/Chicago"])(
|
||||
"an invalid timezone %j is rejected before any request",
|
||||
async (value) => {
|
||||
const { form } = await renderPreferences();
|
||||
fireEvent.change(field(form, "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, "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: "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, "Timezone").value).toBe("Mars/Olympus_Mons");
|
||||
expect(field(form, "Timezone").disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("a failed load shows the reason and Try again refetches", async () => {
|
||||
let fail = true;
|
||||
fetchMock.mockImplementation(async (url: string, init?: RequestInit) => {
|
||||
@@ -558,133 +512,3 @@ describe("SettingsScreen — preferences", () => {
|
||||
await screen.findByRole("form", { name: "Preferences" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("SettingsScreen — 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, and the admin never chose one.
|
||||
settings = { ...DEFAULT_SETTINGS, timezone: "", timezone_configured: false };
|
||||
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 unset timezone is set once, on load, to the browser's zone and shown", async () => {
|
||||
mockBrowserZone("America/New_York");
|
||||
const form = await renderForm();
|
||||
expect(field(form, "Timezone").value).toBe("America/New_York");
|
||||
expect(writes()).toEqual([
|
||||
{ method: "PATCH", path: SETTINGS_PATH, body: { timezone: "America/New_York", timezone_configured: true } },
|
||||
]);
|
||||
expect(settings.timezone).toBe("America/New_York");
|
||||
expect(settings.timezone_configured).toBe(true);
|
||||
|
||||
// A later save of another field does not re-send the timezone.
|
||||
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()).toHaveLength(2);
|
||||
expect(writes()[1].body).toEqual({ horizon_days: 21 });
|
||||
});
|
||||
|
||||
it("StrictMode's doubled effects still auto-set exactly once", 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("America/New_York");
|
||||
expect(writes()).toEqual([
|
||||
{ method: "PATCH", path: SETTINGS_PATH, body: { timezone: "America/New_York", timezone_configured: true } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("an admin clearing the timezone is not re-set by the browser zone, even after a reopen", async () => {
|
||||
mockBrowserZone("America/New_York");
|
||||
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: "America/New_York", timezone_configured: true },
|
||||
{ timezone: "", timezone_configured: true },
|
||||
]);
|
||||
const reloaded = screen.getByRole("form", { name: "Preferences" });
|
||||
expect(field(reloaded, "Timezone").value).toBe("");
|
||||
|
||||
// Close and reopen: the screen re-fetches "" but the choice persisted.
|
||||
cleanup();
|
||||
const reopened = await renderForm();
|
||||
expect(field(reopened, "Timezone").value).toBe("");
|
||||
expect(writes()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("an empty timezone the admin chose is never auto-set", async () => {
|
||||
mockBrowserZone("America/New_York");
|
||||
settings = { ...settings, timezone_configured: true };
|
||||
const form = await renderForm();
|
||||
expect(field(form, "Timezone").value).toBe("");
|
||||
expect(writes()).toEqual([]);
|
||||
});
|
||||
|
||||
it("a set timezone is shown and never overwritten by the browser zone", async () => {
|
||||
mockBrowserZone("America/New_York");
|
||||
settings = { ...DEFAULT_SETTINGS, timezone: "Europe/Dublin", timezone_configured: false };
|
||||
const form = await renderForm();
|
||||
expect(field(form, "Timezone").value).toBe("Europe/Dublin");
|
||||
expect(writes()).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["nothing", undefined],
|
||||
["an empty zone", ""],
|
||||
["an unknown zone", "Etc/Unknown"],
|
||||
["a non-IANA zone", "not a zone"],
|
||||
])("detection returning %s leaves the field empty and sends nothing", async (_case, zone) => {
|
||||
mockBrowserZone(zone);
|
||||
const form = await renderForm();
|
||||
expect(field(form, "Timezone").value).toBe("");
|
||||
expect(screen.queryByTestId("preferences-message")).toBeNull();
|
||||
expect(writes()).toEqual([]);
|
||||
});
|
||||
|
||||
it("a rejected auto-set shows why and leaves the field empty for manual entry", async () => {
|
||||
mockBrowserZone("America/New_York");
|
||||
writeResponse = () => jsonResponse({ detail: "timezone is not known" }, 422);
|
||||
const form = await renderForm();
|
||||
expect(field(form, "Timezone").value).toBe("");
|
||||
expect(field(form, "Timezone").disabled).toBe(false);
|
||||
expect(screen.getByTestId("preferences-message").textContent).toBe(
|
||||
"The timezone could not be set to America/New_York: timezone is not known",
|
||||
);
|
||||
expect(writes()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
* 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. A timezone
|
||||
* the admin never chose is set once, on load, to the browser's own zone;
|
||||
* saving the timezone (even clearing it) marks it chosen, so it sticks.
|
||||
* notifications). Save patches only the changed fields.
|
||||
*
|
||||
* One write at a time across both sections.
|
||||
*/
|
||||
@@ -254,56 +252,6 @@ const NOTIFICATIONS: { label: string; time: TimeField; toggle: ToggleField }[] =
|
||||
|
||||
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 field's suggestions; any other IANA zone can be typed. */
|
||||
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 browser's own IANA zone — the location-derived default for an unset
|
||||
* household timezone — or "" when it is missing or not a usable zone name.
|
||||
*/
|
||||
export function detectTimezone(): string {
|
||||
try {
|
||||
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
return typeof zone === "string" && zone !== "Etc/Unknown" && IANA_ZONE.test(zone) ? zone : "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** The form's working copy: the number is text so it can be mid-edit. */
|
||||
type PreferencesDraft = Omit<HouseholdSettings, "horizon_days"> & { horizon_days: string };
|
||||
|
||||
@@ -327,24 +275,16 @@ function buildChanges(draft: PreferencesDraft, loaded: HouseholdSettings): Setti
|
||||
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];
|
||||
}
|
||||
// An explicit choice — including "" (the API host's local time) — must
|
||||
// persist, or the next load would auto-set the browser's zone over it.
|
||||
if ("timezone" in changes) changes.timezone_configured = true;
|
||||
if (Object.keys(changes).length === 0) return "No changes to save.";
|
||||
return changes;
|
||||
}
|
||||
@@ -417,25 +357,6 @@ function PreferencesForm({
|
||||
/>
|
||||
</label>
|
||||
{timeInput("day_rollover_time", "Day rollover")}
|
||||
<label className="settings-field">
|
||||
<span className="settings-label">Timezone</span>
|
||||
<input
|
||||
className="settings-input"
|
||||
type="text"
|
||||
list="settings-timezones"
|
||||
placeholder="Host local time"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
value={draft.timezone}
|
||||
disabled={disabled}
|
||||
onChange={(event) => update({ timezone: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<datalist id="settings-timezones">
|
||||
{COMMON_TIMEZONES.map((zone) => (
|
||||
<option key={zone} value={zone} />
|
||||
))}
|
||||
</datalist>
|
||||
<label className="settings-field">
|
||||
<span className="settings-label">Notify target</span>
|
||||
<input
|
||||
@@ -574,8 +495,6 @@ export default function SettingsScreen({ onClose }: { onClose: () => void }) {
|
||||
} | null>(null);
|
||||
// A ref, not state: two taps in one frame must not both see `busy === null`.
|
||||
const inFlight = useRef(false);
|
||||
// The never-chosen-timezone auto-set fires at most once per screen.
|
||||
const timezoneAutoSet = useRef(false);
|
||||
const screenRef = useRef<HTMLDivElement>(null);
|
||||
const titleRef = useRef<HTMLHeadingElement>(null);
|
||||
const addRef = useRef<HTMLButtonElement>(null);
|
||||
@@ -620,29 +539,8 @@ export default function SettingsScreen({ onClose }: { onClose: () => void }) {
|
||||
let cancelled = false;
|
||||
setPreferences({ kind: "loading" });
|
||||
fetchSettings()
|
||||
.then(async (settings) => {
|
||||
if (cancelled) return;
|
||||
// Never chosen: adopt the browser's zone before the form shows, so
|
||||
// nothing the admin enters can be overwritten by it. An empty zone the
|
||||
// admin chose (timezone_configured) is left alone.
|
||||
const unchosen = settings.timezone === "" && !settings.timezone_configured;
|
||||
const detected = unchosen ? detectTimezone() : "";
|
||||
if (!detected || timezoneAutoSet.current) {
|
||||
setPreferences({ kind: "ready", settings });
|
||||
return;
|
||||
}
|
||||
timezoneAutoSet.current = true;
|
||||
try {
|
||||
const saved = await updateSettings({ timezone: detected, timezone_configured: true });
|
||||
if (!cancelled) setPreferences({ kind: "ready", settings: saved });
|
||||
} catch (error) {
|
||||
if (cancelled) return;
|
||||
setPreferences({ kind: "ready", settings });
|
||||
setPreferencesMessage({
|
||||
kind: "error",
|
||||
text: errorMessage(error, `The timezone could not be set to ${detected}`),
|
||||
});
|
||||
}
|
||||
.then((settings) => {
|
||||
if (!cancelled) setPreferences({ kind: "ready", settings });
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (cancelled) return;
|
||||
|
||||
+14
-90
@@ -165,13 +165,12 @@ 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 twelve
|
||||
- ``GET /settings`` returns the current effective settings: all eleven
|
||||
documented fields (the rolling horizon, the day rollover time, the
|
||||
notify target, the three notification times, the four enable
|
||||
toggles, the ``timezone`` — the IANA household zone the
|
||||
household-local dates derive from, empty meaning host local — and
|
||||
``timezone_configured``, whether the admin explicitly chose that
|
||||
zone) — the defaults on a fresh database.
|
||||
toggles and the ``timezone`` — the IANA household zone the
|
||||
household-local dates derive from, empty meaning host local) — 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
|
||||
@@ -201,25 +200,6 @@ integration's rollover listener shares:
|
||||
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.
|
||||
|
||||
The occurrence-preview route (task 5f843564) lets the admin PWA's
|
||||
Definitions edit sheet show the next dates a rule fires on WITHOUT
|
||||
reimplementing the recurrence rules client-side:
|
||||
@@ -473,19 +453,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``.
|
||||
|
||||
@@ -569,10 +536,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
|
||||
@@ -906,7 +872,7 @@ class AdminSettingsResponse(BaseModel):
|
||||
"""The effective settings as the admin plane serializes them.
|
||||
|
||||
Mirrors the core :class:`~nestquest_core.settings.NestQuestSettings`
|
||||
— all TWELVE documented fields, resolved (every absent stored field
|
||||
— all ELEVEN 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,9 +890,6 @@ class AdminSettingsResponse(BaseModel):
|
||||
#: The household IANA time zone the API reads its clock in; ``""``
|
||||
#: means the API host's local time.
|
||||
timezone: str
|
||||
#: Whether the admin explicitly chose ``timezone`` (even ``""``);
|
||||
#: ``False`` lets the admin UI auto-set the browser's zone once.
|
||||
timezone_configured: bool
|
||||
|
||||
|
||||
class AdminMissedSweepResponse(BaseModel):
|
||||
@@ -1647,16 +1610,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.
|
||||
"""
|
||||
@@ -1670,44 +1633,6 @@ 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,
|
||||
)
|
||||
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",
|
||||
@@ -2183,7 +2108,7 @@ 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 twelve documented fields even if the core
|
||||
stays pinned to the eleven documented fields even if the core
|
||||
dataclass later grows another one.
|
||||
"""
|
||||
return AdminSettingsResponse(
|
||||
@@ -2198,7 +2123,6 @@ def _settings_response(
|
||||
end_of_day_report_enabled=settings.end_of_day_report_enabled,
|
||||
celebration_enabled=settings.celebration_enabled,
|
||||
timezone=settings.timezone,
|
||||
timezone_configured=settings.timezone_configured,
|
||||
)
|
||||
|
||||
|
||||
@@ -2296,7 +2220,7 @@ async def admin_history_csv(
|
||||
response_model=AdminSettingsResponse,
|
||||
)
|
||||
async def admin_get_settings(request: Request) -> AdminSettingsResponse:
|
||||
"""Return the current effective settings (all twelve documented fields).
|
||||
"""Return the current effective settings (all eleven documented fields).
|
||||
|
||||
Requires a valid admin JWT (the router's shared
|
||||
:func:`~api.auth.require_admin` dependency — the ONE check; this
|
||||
|
||||
+10
-45
@@ -9,9 +9,8 @@ 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 API host may run UTC while the household
|
||||
does not; until the admin chooses a zone it is the Home Assistant zone
|
||||
the integration reports in :data:`PANEL_TIMEZONE_HEADER`), calls the pure
|
||||
stored household ``timezone`` setting — the API host may run UTC while
|
||||
the household does not), 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
|
||||
@@ -54,7 +53,6 @@ from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import importlib
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
@@ -64,7 +62,6 @@ from api.database import DatabaseState
|
||||
from api.dependencies import require_panel_token
|
||||
from api.nestquest_core import (
|
||||
core_completion,
|
||||
core_const,
|
||||
core_events,
|
||||
core_settings_store,
|
||||
core_snapshot,
|
||||
@@ -72,12 +69,6 @@ from api.nestquest_core import (
|
||||
from api import transitions as api_transitions
|
||||
from api.sse import transition_event_stream
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
#: The request header the integration reports Home Assistant's
|
||||
#: configured IANA ``time_zone`` in.
|
||||
PANEL_TIMEZONE_HEADER = core_const.PANEL_TIMEZONE_HEADER
|
||||
|
||||
#: The instance DAO, imported on the app's core copy for the
|
||||
#: child-mismatch guard on the complete route.
|
||||
_dao_instances = importlib.import_module("nestquest_core.dao_instances")
|
||||
@@ -188,42 +179,16 @@ def _local_now() -> datetime.datetime:
|
||||
|
||||
|
||||
async def _household_clock(
|
||||
database: object, request: Request
|
||||
database: object,
|
||||
) -> tuple[object, datetime.datetime]:
|
||||
"""Return the settings and ONE household-local clock read.
|
||||
"""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 settings' ``timezone``
|
||||
(:meth:`NestQuestSettings.household_now`). The integration reports
|
||||
Home Assistant's ``time_zone`` in :data:`PANEL_TIMEZONE_HEADER`;
|
||||
until the admin chooses a zone it is adopted and persisted
|
||||
(:func:`nestquest_core.settings_store.adopt_reported_timezone`), so
|
||||
the admin plane follows it too, and the already-sleeping missed-sweep
|
||||
scheduler is told (:meth:`MissedSweepScheduler.settings_changed`) so
|
||||
it re-plans for the household rollover — under the scheduler's
|
||||
``settings_lock``, so the adoption never lands between its settings
|
||||
check and its sweep. An invalid
|
||||
reported zone is logged and ignored — the panel keeps serving on
|
||||
the stored settings.
|
||||
: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.
|
||||
"""
|
||||
reported = request.headers.get(PANEL_TIMEZONE_HEADER, "").strip()
|
||||
if reported:
|
||||
scheduler = request.app.state.sweep_scheduler
|
||||
try:
|
||||
async with scheduler.settings_lock:
|
||||
settings = await core_settings_store.adopt_reported_timezone(
|
||||
database, reported
|
||||
)
|
||||
scheduler.settings_changed(settings)
|
||||
except ValueError:
|
||||
LOGGER.warning(
|
||||
"Ignoring invalid %s header value %r",
|
||||
PANEL_TIMEZONE_HEADER,
|
||||
reported,
|
||||
)
|
||||
settings = await core_settings_store.load_settings(database)
|
||||
else:
|
||||
settings = await core_settings_store.load_settings(database)
|
||||
settings = await core_settings_store.load_settings(database)
|
||||
return settings, settings.household_now(_local_now())
|
||||
|
||||
|
||||
@@ -245,7 +210,7 @@ async def panel_snapshot(request: Request) -> PanelSnapshotResponse:
|
||||
:class:`PanelSnapshotResponse`.
|
||||
"""
|
||||
state: DatabaseState = request.app.state.db
|
||||
settings, now = await _household_clock(state.database, request)
|
||||
settings, now = await _household_clock(state.database)
|
||||
snapshot = await core_snapshot.build_snapshot(
|
||||
state.database, settings, now
|
||||
)
|
||||
@@ -332,7 +297,7 @@ async def panel_complete_instance(
|
||||
detail="Quest instance not found for this child",
|
||||
)
|
||||
|
||||
_settings, now = await _household_clock(database, request)
|
||||
_settings, now = await _household_clock(database)
|
||||
try:
|
||||
result = await core_completion.complete_instance(
|
||||
database,
|
||||
|
||||
+13
-100
@@ -13,27 +13,6 @@ local date when unset) 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 adopted from Home Assistant 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 adoption has replaced.
|
||||
An adopting writer 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 an adoption 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
|
||||
panel request 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,
|
||||
@@ -145,14 +124,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 adoption 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)."""
|
||||
@@ -171,20 +142,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. a zone adopted from
|
||||
Home Assistant), 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."""
|
||||
@@ -194,18 +151,12 @@ class MissedSweepScheduler:
|
||||
"""Schedule → sweep → repeat, forever (until cancelled)."""
|
||||
while True:
|
||||
try:
|
||||
# Under the lock no adoption 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
|
||||
@@ -227,30 +178,15 @@ class MissedSweepScheduler:
|
||||
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 an adoption 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(
|
||||
settings.household_now(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",
|
||||
@@ -258,29 +194,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.
|
||||
|
||||
|
||||
@@ -6,9 +6,6 @@ speaks the API's panel plane — ``GET /api/v1/panel/snapshot`` (today's
|
||||
household snapshot) and ``POST /api/v1/panel/instances/{id}/complete``
|
||||
(completion as the tapped child profile) — authenticated with the
|
||||
static panel service token as a Bearer credential on every request.
|
||||
Every request also reports Home Assistant's configured ``time_zone`` in
|
||||
the ``X-NestQuest-Timezone`` header, so the API (which may run UTC)
|
||||
reads the household's clock until the admin chooses a zone there.
|
||||
|
||||
Transport-injected by construction: the constructor takes the base URL,
|
||||
the panel token, and the HTTP session to use. The session speaks the
|
||||
@@ -57,7 +54,6 @@ from .const import (
|
||||
CONF_PANEL_TOKEN,
|
||||
DEFAULT_API_BASE_URL,
|
||||
DEFAULT_PANEL_TOKEN,
|
||||
PANEL_TIMEZONE_HEADER,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -160,8 +156,7 @@ def client_from_entry(hass: Any, entry: Any) -> NestQuestApiClient:
|
||||
"""Build the production client for a config entry.
|
||||
|
||||
Reads the configured base URL and panel token off the entry
|
||||
(:func:`resolve_api_config`), reports ``hass.config.time_zone`` as
|
||||
the household zone, and hands the client Home Assistant's
|
||||
(:func:`resolve_api_config`) and hands the client Home Assistant's
|
||||
SHARED aiohttp session (``homeassistant.helpers.aiohttp_client
|
||||
.async_get_clientsession``) so panel calls ride HA's one connection
|
||||
pool. The helper import is deferred into this function on purpose:
|
||||
@@ -173,10 +168,7 @@ def client_from_entry(hass: Any, entry: Any) -> NestQuestApiClient:
|
||||
|
||||
base_url, panel_token = resolve_api_config(entry)
|
||||
return NestQuestApiClient(
|
||||
base_url,
|
||||
panel_token,
|
||||
async_get_clientsession(hass),
|
||||
household_timezone=hass.config.time_zone,
|
||||
base_url, panel_token, async_get_clientsession(hass)
|
||||
)
|
||||
|
||||
|
||||
@@ -197,14 +189,9 @@ class NestQuestApiClient:
|
||||
session: aiohttp.ClientSession,
|
||||
*,
|
||||
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
||||
household_timezone: str | None = None,
|
||||
) -> None:
|
||||
"""Store the connection settings; the session is injected.
|
||||
|
||||
``household_timezone`` is Home Assistant's configured IANA
|
||||
``time_zone``; when given it rides every request in the
|
||||
``X-NestQuest-Timezone`` header.
|
||||
|
||||
``session`` is an aiohttp ``ClientSession`` in production and a
|
||||
stub transport in tests. ``base_url`` must be a full http(s)
|
||||
URL and ``panel_token`` must be non-empty — a client built
|
||||
@@ -229,14 +216,6 @@ class NestQuestApiClient:
|
||||
self._panel_token = panel_token
|
||||
self._session = session
|
||||
self._timeout_seconds = float(timeout_seconds)
|
||||
self._household_timezone = household_timezone
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
"""The Bearer credential plus the reported household zone."""
|
||||
headers = {"Authorization": f"Bearer {self._panel_token}"}
|
||||
if self._household_timezone:
|
||||
headers[PANEL_TIMEZONE_HEADER] = self._household_timezone
|
||||
return headers
|
||||
|
||||
async def get_snapshot(self) -> dict[str, Any]:
|
||||
"""Fetch and parse today's household snapshot.
|
||||
@@ -296,7 +275,7 @@ class NestQuestApiClient:
|
||||
cleanly and closes the underlying response in every path.
|
||||
"""
|
||||
url = f"{self._base_url}{EVENTS_PATH}"
|
||||
headers = self._headers()
|
||||
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.
|
||||
@@ -400,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(
|
||||
|
||||
@@ -372,10 +372,7 @@ def coordinator_client_from_entry(
|
||||
return _UnconfiguredApiClient()
|
||||
if session_factory is not None:
|
||||
return NestQuestApiClient(
|
||||
base_url,
|
||||
panel_token,
|
||||
session_factory(hass),
|
||||
household_timezone=hass.config.time_zone,
|
||||
base_url, panel_token, session_factory(hass)
|
||||
)
|
||||
from custom_components.nestquest.api_client import client_from_entry
|
||||
|
||||
|
||||
@@ -113,25 +113,12 @@ 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. While the admin has not chosen a zone
|
||||
# (``timezone_configured`` is ``False``) the API adopts the zone the
|
||||
# integration reports from Home Assistant's configured ``time_zone``
|
||||
# (:data:`PANEL_TIMEZONE_HEADER`), so the default is the household's
|
||||
# zone without any manual setup. The integration itself always uses
|
||||
# Home Assistant's ``time_zone`` and ignores this field.
|
||||
# service reads its clock in. The empty string keeps the historical
|
||||
# behaviour — the API host's own local time — so an existing install is
|
||||
# unchanged until the owner sets it. The integration itself always uses
|
||||
# Home Assistant's configured ``time_zone`` and ignores this field.
|
||||
CONF_TIMEZONE = "timezone"
|
||||
DEFAULT_TIMEZONE = ""
|
||||
# Whether the admin has made an explicit ``timezone`` choice. ``False``
|
||||
# (a fresh install) lets the API follow Home Assistant's reported zone
|
||||
# and the admin UI auto-set the browser's zone once while none is
|
||||
# stored; ``True`` pins the stored value — including an explicitly-chosen
|
||||
# empty ``timezone`` (the API host's local time) — so neither changes it.
|
||||
CONF_TIMEZONE_CONFIGURED = "timezone_configured"
|
||||
DEFAULT_TIMEZONE_CONFIGURED = False
|
||||
# The panel-plane request header carrying Home Assistant's configured
|
||||
# IANA ``time_zone`` from the integration to the API service.
|
||||
PANEL_TIMEZONE_HEADER = "X-NestQuest-Timezone"
|
||||
|
||||
# Panel-plane API client (Feature 18): the integration reaches the
|
||||
# NestQuest API service (Feature 16) over HTTP instead of the database.
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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`:
|
||||
@@ -82,21 +80,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(
|
||||
@@ -521,19 +504,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
|
||||
@@ -586,68 +562,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:
|
||||
|
||||
@@ -49,7 +49,6 @@ from .const import (
|
||||
CONF_MORNING_SUMMARY_TIME,
|
||||
CONF_NOTIFY_TARGET,
|
||||
CONF_TIMEZONE,
|
||||
CONF_TIMEZONE_CONFIGURED,
|
||||
DEFAULT_AFTERNOON_REMINDER_TIME,
|
||||
DEFAULT_AUTOMATION_ENABLED,
|
||||
DEFAULT_DAY_ROLLOVER_TIME,
|
||||
@@ -57,7 +56,6 @@ from .const import (
|
||||
DEFAULT_HORIZON_DAYS,
|
||||
DEFAULT_MORNING_SUMMARY_TIME,
|
||||
DEFAULT_TIMEZONE,
|
||||
DEFAULT_TIMEZONE_CONFIGURED,
|
||||
LOGGER,
|
||||
TIME_PATTERN,
|
||||
)
|
||||
@@ -243,12 +241,6 @@ _FIELDS: tuple[tuple[str, str, Any, Callable[[Any], Any]], ...] = (
|
||||
_resolve_bool,
|
||||
),
|
||||
("timezone", CONF_TIMEZONE, DEFAULT_TIMEZONE, _resolve_timezone),
|
||||
(
|
||||
"timezone_configured",
|
||||
CONF_TIMEZONE_CONFIGURED,
|
||||
DEFAULT_TIMEZONE_CONFIGURED,
|
||||
_resolve_bool,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -279,10 +271,6 @@ class NestQuestSettings:
|
||||
end_of_day_report_enabled: bool = DEFAULT_AUTOMATION_ENABLED
|
||||
celebration_enabled: bool = DEFAULT_AUTOMATION_ENABLED
|
||||
timezone: str = DEFAULT_TIMEZONE
|
||||
#: ``True`` once the admin explicitly chose :attr:`timezone` (even
|
||||
#: the empty host-local value); ``False`` on a fresh install, where
|
||||
#: the admin UI may auto-set the browser's zone.
|
||||
timezone_configured: bool = DEFAULT_TIMEZONE_CONFIGURED
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Validate STRICTLY at construction so a hand-built instance
|
||||
@@ -315,7 +303,6 @@ class NestQuestSettings:
|
||||
"afternoon_reminder_enabled",
|
||||
"end_of_day_report_enabled",
|
||||
"celebration_enabled",
|
||||
"timezone_configured",
|
||||
):
|
||||
value = getattr(self, name)
|
||||
if not isinstance(value, bool):
|
||||
@@ -327,14 +314,12 @@ class NestQuestSettings:
|
||||
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
|
||||
The API service has no Home Assistant ``time_zone``, so its one
|
||||
clock read (an aware host-local ``now``) is converted here: with
|
||||
:attr:`timezone` set — the admin's choice, or else the zone the
|
||||
integration reports from Home Assistant — 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).
|
||||
:attr:`timezone` set 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
|
||||
|
||||
@@ -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 ELEVEN settings fields, keyed by field name
|
||||
(which equals the ``CONF_*`` option key for every field), complete
|
||||
after the first update:
|
||||
|
||||
@@ -33,12 +33,7 @@ after the first update:
|
||||
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 ``""``,
|
||||
- ``timezone_configured`` — a real boolean: ``True`` once the admin
|
||||
explicitly chose ``timezone`` (including the empty host-local value),
|
||||
so neither Home Assistant's reported zone
|
||||
(:func:`adopt_reported_timezone`) nor the admin UI changes it again. A document stored before
|
||||
this field existed lacks it and resolves to ``False``.
|
||||
this field existed simply lacks it and resolves to ``""``.
|
||||
|
||||
Only values whose core validators ACCEPTED are ever written, so a
|
||||
stored document always round-trips through the core's option builders.
|
||||
@@ -180,7 +175,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, twelve-field) document is persisted
|
||||
settings and the merged (complete, eleven-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.
|
||||
@@ -201,49 +196,18 @@ async def update_settings(
|
||||
)
|
||||
async with _settings_lock(database):
|
||||
current = await load_settings(database)
|
||||
return await _write_merged(database, current, changes)
|
||||
|
||||
|
||||
async def adopt_reported_timezone(
|
||||
database: NestQuestDatabase, zone: str
|
||||
) -> NestQuestSettings:
|
||||
"""Adopt Home Assistant's reported ``zone`` unless the admin chose one.
|
||||
|
||||
While ``timezone_configured`` is ``False`` the stored ``timezone``
|
||||
follows the zone the integration reports, so the API's clock is the
|
||||
household's without any manual setup; ``timezone_configured`` stays
|
||||
``False`` (the value is automatic, not an admin choice). Once the
|
||||
admin has chosen — including an explicitly-chosen empty zone — the
|
||||
stored settings are returned untouched. The check and the write
|
||||
share the settings lock, so a concurrent admin choice is never
|
||||
overwritten. An invalid ``zone`` raises a ``ValueError`` naming
|
||||
``timezone`` and writes nothing.
|
||||
"""
|
||||
async with _settings_lock(database):
|
||||
current = await load_settings(database)
|
||||
if current.timezone_configured or current.timezone == zone:
|
||||
return current
|
||||
return await _write_merged(database, current, {"timezone": zone})
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -15,5 +15,5 @@
|
||||
"iot_class": "local_polling",
|
||||
"issue_tracker": "https://github.com/Maniacs-Mansion/NestQuest/issues",
|
||||
"requirements": [],
|
||||
"version": "0.9.5"
|
||||
"version": "0.8.0"
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ const { is: nt, defineProperty: it, getOwnPropertyDescriptor: st, getOwnProperty
|
||||
return t;
|
||||
} }, Ze = (i, e) => !nt(i, e), ye = { attribute: !0, type: String, converter: ae, reflect: !1, useDefault: !1, hasChanged: Ze };
|
||||
Symbol.metadata ??= /* @__PURE__ */ Symbol("metadata"), K.litPropertyMetadata ??= /* @__PURE__ */ new WeakMap();
|
||||
let T = class extends HTMLElement {
|
||||
let z = class extends HTMLElement {
|
||||
static addInitializer(e) {
|
||||
this._$Ei(), (this.l ??= []).push(e);
|
||||
}
|
||||
@@ -246,7 +246,7 @@ let T = class extends HTMLElement {
|
||||
firstUpdated(e) {
|
||||
}
|
||||
};
|
||||
T.elementStyles = [], T.shadowRootOptions = { mode: "open" }, T[I("elementProperties")] = /* @__PURE__ */ new Map(), T[I("finalized")] = /* @__PURE__ */ new Map(), ct?.({ ReactiveElement: T }), (K.reactiveElementVersions ??= []).push("2.1.2");
|
||||
z.elementStyles = [], z.shadowRootOptions = { mode: "open" }, z[I("elementProperties")] = /* @__PURE__ */ new Map(), z[I("finalized")] = /* @__PURE__ */ new Map(), ct?.({ ReactiveElement: z }), (K.reactiveElementVersions ??= []).push("2.1.2");
|
||||
const pe = globalThis, be = (i) => i, V = pe.trustedTypes, ve = V ? V.createPolicy("lit-html", { createHTML: (i) => i }) : void 0, Qe = "$lit$", k = `lit$${Math.random().toFixed(9).slice(2)}$`, We = "?" + k, dt = `<${We}>`, A = document, P = () => A.createComment(""), H = (i) => i === null || typeof i != "object" && typeof i != "function", he = Array.isArray, pt = (i) => he(i) || typeof i?.[Symbol.iterator] == "function", Y = `[
|
||||
\f\r]`, L = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g, xe = /-->/g, we = />/g, $ = RegExp(`>|${Y}(?:([^\\s"'>=/]+)(${Y}*=${Y}*(?:[^
|
||||
\f\r"'\`<>=]|("|')|))|$)`, "g"), ke = /'/g, $e = /"/g, Ge = /^(?:script|style|textarea|title)$/i, Ke = (i) => (e, ...t) => ({ _$litType$: i, strings: e, values: t }), d = Ke(1), qe = Ke(2), S = /* @__PURE__ */ Symbol.for("lit-noChange"), g = /* @__PURE__ */ Symbol.for("lit-nothing"), Me = /* @__PURE__ */ new WeakMap(), M = A.createTreeWalker(A, 129);
|
||||
@@ -266,13 +266,13 @@ const ht = (i, e) => {
|
||||
}
|
||||
return [Je(i, a + (i[t] || "<?>") + (e === 2 ? "</svg>" : e === 3 ? "</math>" : "")), n];
|
||||
};
|
||||
class R {
|
||||
class U {
|
||||
constructor({ strings: e, _$litType$: t }, n) {
|
||||
let s;
|
||||
this.parts = [];
|
||||
let a = 0, r = 0;
|
||||
const l = e.length - 1, o = this.parts, [p, u] = ht(e, t);
|
||||
if (this.el = R.createElement(p, n), M.currentNode = this.el.content, t === 2 || t === 3) {
|
||||
if (this.el = U.createElement(p, n), M.currentNode = this.el.content, t === 2 || t === 3) {
|
||||
const c = this.el.content.firstChild;
|
||||
c.replaceWith(...c.childNodes);
|
||||
}
|
||||
@@ -303,11 +303,11 @@ class R {
|
||||
return n.innerHTML = e, n;
|
||||
}
|
||||
}
|
||||
function z(i, e, t = i, n) {
|
||||
function T(i, e, t = i, n) {
|
||||
if (e === S) return e;
|
||||
let s = n !== void 0 ? t._$Co?.[n] : t._$Cl;
|
||||
const a = H(e) ? void 0 : e._$litDirective$;
|
||||
return s?.constructor !== a && (s?._$AO?.(!1), a === void 0 ? s = void 0 : (s = new a(i), s._$AT(i, t, n)), n !== void 0 ? (t._$Co ??= [])[n] = s : t._$Cl = s), s !== void 0 && (e = z(i, s._$AS(i, e.values), s, n)), e;
|
||||
return s?.constructor !== a && (s?._$AO?.(!1), a === void 0 ? s = void 0 : (s = new a(i), s._$AT(i, t, n)), n !== void 0 ? (t._$Co ??= [])[n] = s : t._$Cl = s), s !== void 0 && (e = T(i, s._$AS(i, e.values), s, n)), e;
|
||||
}
|
||||
class ut {
|
||||
constructor(e, t) {
|
||||
@@ -356,7 +356,7 @@ class N {
|
||||
return this._$AB;
|
||||
}
|
||||
_$AI(e, t = this) {
|
||||
e = z(this, e, t), H(e) ? e === g || e == null || e === "" ? (this._$AH !== g && this._$AR(), this._$AH = g) : e !== this._$AH && e !== S && this._(e) : e._$litType$ !== void 0 ? this.$(e) : e.nodeType !== void 0 ? this.T(e) : pt(e) ? this.k(e) : this._(e);
|
||||
e = T(this, e, t), H(e) ? e === g || e == null || e === "" ? (this._$AH !== g && this._$AR(), this._$AH = g) : e !== this._$AH && e !== S && this._(e) : e._$litType$ !== void 0 ? this.$(e) : e.nodeType !== void 0 ? this.T(e) : pt(e) ? this.k(e) : this._(e);
|
||||
}
|
||||
O(e) {
|
||||
return this._$AA.parentNode.insertBefore(e, this._$AB);
|
||||
@@ -368,7 +368,7 @@ class N {
|
||||
this._$AH !== g && H(this._$AH) ? this._$AA.nextSibling.data = e : this.T(A.createTextNode(e)), this._$AH = e;
|
||||
}
|
||||
$(e) {
|
||||
const { values: t, _$litType$: n } = e, s = typeof n == "number" ? this._$AC(e) : (n.el === void 0 && (n.el = R.createElement(Je(n.h, n.h[0]), this.options)), n);
|
||||
const { values: t, _$litType$: n } = e, s = typeof n == "number" ? this._$AC(e) : (n.el === void 0 && (n.el = U.createElement(Je(n.h, n.h[0]), this.options)), n);
|
||||
if (this._$AH?._$AD === s) this._$AH.p(t);
|
||||
else {
|
||||
const a = new ut(s, this), r = a.u(this.options);
|
||||
@@ -377,7 +377,7 @@ class N {
|
||||
}
|
||||
_$AC(e) {
|
||||
let t = Me.get(e.strings);
|
||||
return t === void 0 && Me.set(e.strings, t = new R(e)), t;
|
||||
return t === void 0 && Me.set(e.strings, t = new U(e)), t;
|
||||
}
|
||||
k(e) {
|
||||
he(this._$AH) || (this._$AH = [], this._$AR());
|
||||
@@ -409,11 +409,11 @@ class J {
|
||||
_$AI(e, t = this, n, s) {
|
||||
const a = this.strings;
|
||||
let r = !1;
|
||||
if (a === void 0) e = z(this, e, t, 0), r = !H(e) || e !== this._$AH && e !== S, r && (this._$AH = e);
|
||||
if (a === void 0) e = T(this, e, t, 0), r = !H(e) || e !== this._$AH && e !== S, r && (this._$AH = e);
|
||||
else {
|
||||
const l = e;
|
||||
let o, p;
|
||||
for (e = a[0], o = 0; o < a.length - 1; o++) p = z(this, l[n + o], t, o), p === S && (p = this._$AH[o]), r ||= !H(p) || p !== this._$AH[o], p === g ? e = g : e !== g && (e += (p ?? "") + a[o + 1]), this._$AH[o] = p;
|
||||
for (e = a[0], o = 0; o < a.length - 1; o++) p = T(this, l[n + o], t, o), p === S && (p = this._$AH[o]), r ||= !H(p) || p !== this._$AH[o], p === g ? e = g : e !== g && (e += (p ?? "") + a[o + 1]), this._$AH[o] = p;
|
||||
}
|
||||
r && !s && this.j(e);
|
||||
}
|
||||
@@ -442,7 +442,7 @@ class gt extends J {
|
||||
super(e, t, n, s, a), this.type = 5;
|
||||
}
|
||||
_$AI(e, t = this) {
|
||||
if ((e = z(this, e, t, 0) ?? g) === S) return;
|
||||
if ((e = T(this, e, t, 0) ?? g) === S) return;
|
||||
const n = this._$AH, s = e === g && n !== g || e.capture !== n.capture || e.once !== n.once || e.passive !== n.passive, a = e !== g && (n === g || s);
|
||||
s && this.element.removeEventListener(this.name, this, n), a && this.element.addEventListener(this.name, this, e), this._$AH = e;
|
||||
}
|
||||
@@ -458,11 +458,11 @@ class _t {
|
||||
return this._$AM._$AU;
|
||||
}
|
||||
_$AI(e) {
|
||||
z(this, e);
|
||||
T(this, e);
|
||||
}
|
||||
}
|
||||
const yt = { I: N }, bt = pe.litHtmlPolyfillSupport;
|
||||
bt?.(R, N), (pe.litHtmlVersions ??= []).push("3.3.3");
|
||||
bt?.(U, N), (pe.litHtmlVersions ??= []).push("3.3.3");
|
||||
const vt = (i, e, t) => {
|
||||
const n = t?.renderBefore ?? e;
|
||||
let s = n._$litPart$;
|
||||
@@ -473,7 +473,7 @@ const vt = (i, e, t) => {
|
||||
return s._$AI(i), s;
|
||||
};
|
||||
const ue = globalThis;
|
||||
let C = class extends T {
|
||||
let C = class extends z {
|
||||
constructor() {
|
||||
super(...arguments), this.renderOptions = { host: this }, this._$Do = void 0;
|
||||
}
|
||||
@@ -592,7 +592,7 @@ function Ct(i) {
|
||||
function Se(i) {
|
||||
return Number.isFinite(i) ? Math.min(100, Math.max(0, i)) : 0;
|
||||
}
|
||||
function Te(i) {
|
||||
function ze(i) {
|
||||
return Math.max(0, Math.round(i));
|
||||
}
|
||||
function At(i) {
|
||||
@@ -620,7 +620,7 @@ function St(i, e) {
|
||||
);
|
||||
return Number.isFinite(s) ? s - i : 0;
|
||||
}
|
||||
function Tt(i, e) {
|
||||
function zt(i, e) {
|
||||
if (typeof i != "string")
|
||||
return null;
|
||||
const t = i.split("-");
|
||||
@@ -636,14 +636,14 @@ function Tt(i, e) {
|
||||
const r = Date.UTC(n, s - 1, a), l = new Date(r - St(r, e));
|
||||
return Number.isNaN(l.getTime()) ? null : l;
|
||||
}
|
||||
function zt(i) {
|
||||
function Tt(i) {
|
||||
const e = qt[i];
|
||||
return e || i.charAt(0).toUpperCase() + i.slice(1);
|
||||
}
|
||||
function Et(i, e) {
|
||||
return Mt[i] ?? e;
|
||||
}
|
||||
const ze = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 24.1 50 26 55.5 24.1Z M100 50 75.9 44.5 74 50 75.9 55.5Z M50 97 55.5 75.9 50 74 44.5 75.9Z M0 50 24.1 55.5 26 50 24.1 44.5Z M29.1 29.1 29.7 36.3 36.3 29.7Z M70.9 29.1 63.7 29.7 70.3 36.3Z M70.9 70.9 70.3 63.7 63.7 70.3Z M29.1 70.9 36.3 70.3 29.7 63.7Z", Nt = "M50 26.5 70.4 38.2 70.4 61.8 50 73.5 29.6 61.8 29.6 38.2Z", Lt = "M29.6 38.2H70.4M29.6 61.8H70.4M50 26.5 36.5 38.2M50 26.5 63.5 38.2M50 73.5 36.5 61.8M50 73.5 63.5 61.8M36.5 38.2V61.8M63.5 38.2V61.8M29.6 38.2 36.5 61.8M36.5 38.2 29.6 61.8M70.4 38.2 63.5 61.8M63.5 38.2 70.4 61.8", Ot = d`<svg
|
||||
const Te = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 24.1 50 26 55.5 24.1Z M100 50 75.9 44.5 74 50 75.9 55.5Z M50 97 55.5 75.9 50 74 44.5 75.9Z M0 50 24.1 55.5 26 50 24.1 44.5Z M29.1 29.1 29.7 36.3 36.3 29.7Z M70.9 29.1 63.7 29.7 70.3 36.3Z M70.9 70.9 70.3 63.7 63.7 70.3Z M29.1 70.9 36.3 70.3 29.7 63.7Z", Nt = "M50 26.5 70.4 38.2 70.4 61.8 50 73.5 29.6 61.8 29.6 38.2Z", Lt = "M29.6 38.2H70.4M29.6 61.8H70.4M50 26.5 36.5 38.2M50 26.5 63.5 38.2M50 73.5 36.5 61.8M50 73.5 63.5 61.8M36.5 38.2V61.8M63.5 38.2V61.8M29.6 38.2 36.5 61.8M36.5 38.2 29.6 61.8M70.4 38.2 63.5 61.8M63.5 38.2 70.4 61.8", Ot = d`<svg
|
||||
class="monogram"
|
||||
viewBox="0 0 100 100"
|
||||
aria-hidden="true"
|
||||
@@ -850,7 +850,7 @@ const ze = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 2
|
||||
width: 188px;
|
||||
height: 214px;
|
||||
padding: 4px;
|
||||
clip-path: ${x(ze)};
|
||||
clip-path: ${x(Te)};
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
|
||||
@@ -861,7 +861,7 @@ const ze = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 2
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding-bottom: 70px;
|
||||
clip-path: ${x(ze)};
|
||||
clip-path: ${x(Te)};
|
||||
background: var(--nq-p-crest);
|
||||
}
|
||||
|
||||
@@ -1113,7 +1113,7 @@ const ze = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 2
|
||||
>
|
||||
<circle cx="12" cy="12" r="10"></circle>
|
||||
<polygon points="16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88 16.24 7.76"></polygon>
|
||||
</svg>`, Rt = d`<svg
|
||||
</svg>`, Ut = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -1125,7 +1125,7 @@ const ze = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 2
|
||||
<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path>
|
||||
<path d="M12 9v4"></path>
|
||||
<path d="M12 17h.01"></path>
|
||||
</svg>`, Ut = d`<svg
|
||||
</svg>`, Rt = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -1137,11 +1137,11 @@ const ze = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 2
|
||||
<path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"></path>
|
||||
<path d="m2 2 20 20"></path>
|
||||
</svg>`, Ne = {
|
||||
icon: Rt,
|
||||
icon: Ut,
|
||||
headline: "NestQuest is not set up yet",
|
||||
body: "A parent needs to finish setting up NestQuest before the party can gather."
|
||||
}, jt = {
|
||||
icon: Ut,
|
||||
icon: Rt,
|
||||
headline: "The records cannot be reached",
|
||||
body: "The party's records are quiet right now. NestQuest will return shortly."
|
||||
}, Dt = d`<svg
|
||||
@@ -1280,7 +1280,7 @@ const ze = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 2
|
||||
`sensor.nestquest_${e}_completion_pct_today`
|
||||
), r = this._state(
|
||||
`binary_sensor.nestquest_${e}_present_today`
|
||||
), l = n?.attributes ?? {}, o = Te(te(n?.state, 0)), p = Te(te(s?.state, 0)), u = a ? te(a.state, Number.NaN) : Number.NaN, c = Number.isFinite(u) ? Se(u) : o > 0 ? Se(p / o * 100) : 0;
|
||||
), l = n?.attributes ?? {}, o = ze(te(n?.state, 0)), p = ze(te(s?.state, 0)), u = a ? te(a.state, Number.NaN) : Number.NaN, c = Number.isFinite(u) ? Se(u) : o > 0 ? Se(p / o * 100) : 0;
|
||||
let f = !0;
|
||||
const h = l.present;
|
||||
typeof h == "boolean" ? f = h : r && (f = String(r.state ?? "").trim().toLowerCase() === "on");
|
||||
@@ -1293,10 +1293,10 @@ const ze = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 2
|
||||
typeof X == "string" && X.trim() && (m = X.trim());
|
||||
}
|
||||
m || (m = At(e));
|
||||
const v = Tt(
|
||||
const v = zt(
|
||||
r?.attributes?.next_present,
|
||||
this._timeZone()
|
||||
), U = v ? `Returns ${ee(v, this._timeZone())}` : null;
|
||||
), R = v ? `Returns ${ee(v, this._timeZone())}` : null;
|
||||
return {
|
||||
slug: e,
|
||||
name: m,
|
||||
@@ -1305,7 +1305,7 @@ const ze = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 2
|
||||
completed: p,
|
||||
due: o,
|
||||
pct: c,
|
||||
returns: U,
|
||||
returns: R,
|
||||
unresolved: t
|
||||
};
|
||||
}
|
||||
@@ -1439,7 +1439,7 @@ const ze = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", Ee = "M50 3 44.5 2
|
||||
<span class="clock">${$t(this._now, this._timeZone())}</span>
|
||||
</div>
|
||||
`;
|
||||
const t = zt(e.condition), n = Et(e.condition, t), s = e.temperature === null ? g : d`<span class="temp">${Math.round(e.temperature)}°</span>`, a = e.high === null || e.low === null ? null : `${Math.round(e.high)}° / ${Math.round(e.low)}°`;
|
||||
const t = Tt(e.condition), n = Et(e.condition, t), s = e.temperature === null ? g : d`<span class="temp">${Math.round(e.temperature)}°</span>`, a = e.high === null || e.low === null ? null : `${Math.round(e.high)}° / ${Math.round(e.low)}°`;
|
||||
return d`
|
||||
<div class="dock">
|
||||
${Dt}
|
||||
@@ -1539,8 +1539,8 @@ const Be = (i, e, t) => {
|
||||
else if (p === void 0 && (p = Be(r, h, m), u = Be(l, c, f)), p.has(l[c])) if (p.has(l[f])) {
|
||||
const _ = u.get(r[h]), v = _ !== void 0 ? s[_] : null;
|
||||
if (v === null) {
|
||||
const U = O(i, s[c]);
|
||||
q(U, a[h]), o[h] = U;
|
||||
const R = O(i, s[c]);
|
||||
q(R, a[h]), o[h] = R;
|
||||
} else o[h] = q(v, a[h]), O(i, s[c], v), s[_] = null;
|
||||
h++;
|
||||
} else ne(s[f]), f--;
|
||||
@@ -2387,7 +2387,7 @@ function pn(i, e) {
|
||||
);
|
||||
return Number.isFinite(s) ? s - i : 0;
|
||||
}
|
||||
function Re(i, e) {
|
||||
function Ue(i, e) {
|
||||
if (typeof i != "string")
|
||||
return null;
|
||||
const t = i.split("-");
|
||||
@@ -2470,7 +2470,7 @@ function gn(i) {
|
||||
function _n(i, e) {
|
||||
return mn[i] ?? e;
|
||||
}
|
||||
const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50% 0, 93% 25%, 93% 75%, 50% 100%, 7% 75%, 7% 25%)", je = [-9, 6, -4], bn = Ve`
|
||||
const Re = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50% 0, 93% 25%, 93% 75%, 50% 100%, 7% 75%, 7% 25%)", je = [-9, 6, -4], bn = Ve`
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
@@ -2524,44 +2524,13 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
gap: 28px;
|
||||
}
|
||||
|
||||
button.return {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
height: var(--nq-p-button-height);
|
||||
padding: 0 28px 0 20px;
|
||||
border: 2px solid rgba(92, 62, 26, 0.5);
|
||||
border-radius: 10px;
|
||||
background: rgba(92, 62, 26, 0.1);
|
||||
color: var(--nq-p-ink);
|
||||
font-family: var(--nq-p-font-heading);
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
transition: transform var(--nq-dur-micro) var(--nq-ease-out);
|
||||
}
|
||||
|
||||
button.return:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
button.return svg {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
}
|
||||
|
||||
.crest {
|
||||
position: relative;
|
||||
flex: none;
|
||||
width: 96px;
|
||||
height: 110px;
|
||||
padding: 4px;
|
||||
clip-path: ${x(Ue)};
|
||||
clip-path: ${x(Re)};
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
|
||||
@@ -2572,7 +2541,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding-bottom: 32px;
|
||||
clip-path: ${x(Ue)};
|
||||
clip-path: ${x(Re)};
|
||||
background: var(--nq-p-crest);
|
||||
}
|
||||
|
||||
@@ -3374,16 +3343,6 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
>
|
||||
<path d="M18 6 6 18"></path>
|
||||
<path d="m6 6 12 12"></path>
|
||||
</svg>`, xn = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="m15 18-6-6 6-6"></path>
|
||||
</svg>`, se = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
@@ -3396,7 +3355,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
<polygon
|
||||
points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26"
|
||||
></polygon>
|
||||
</svg>`, wn = d`<svg
|
||||
</svg>`, xn = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -3431,7 +3390,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
<path d="M20 12h2"></path>
|
||||
<path d="m6.34 17.66-1.41 1.41"></path>
|
||||
<path d="m19.07 4.93-1.41 1.41"></path>
|
||||
</svg>`, kn = d`<svg
|
||||
</svg>`, wn = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -3441,7 +3400,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"></path>
|
||||
</svg>`, $n = d`<svg
|
||||
</svg>`, kn = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -3452,7 +3411,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
>
|
||||
<path d="M3.5 21 12 3.5 20.5 21"></path>
|
||||
<path d="M9 21l3-8 3 8"></path>
|
||||
</svg>`, qn = d`<svg
|
||||
</svg>`, $n = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -3463,7 +3422,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
>
|
||||
<circle cx="12" cy="12" r="10"></circle>
|
||||
<polygon points="16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88 16.24 7.76"></polygon>
|
||||
</svg>`, Mn = d`<svg
|
||||
</svg>`, qn = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -3475,7 +3434,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path>
|
||||
<path d="M12 9v4"></path>
|
||||
<path d="M12 17h.01"></path>
|
||||
</svg>`, Cn = d`<svg
|
||||
</svg>`, Mn = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -3486,7 +3445,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
>
|
||||
<path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"></path>
|
||||
<path d="m2 2 20 20"></path>
|
||||
</svg>`, An = d`<svg
|
||||
</svg>`, Cn = d`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -3497,22 +3456,22 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
>
|
||||
<path d="M13 16a3 3 0 1 1 0 6H7a5 5 0 1 1 4.9-6Z"></path>
|
||||
<path d="M10.1 9A6 6 0 0 1 16 4a4.5 4.5 0 0 0 8.9 4.2v.1a6 6 0 0 1-5.2 5.7"></path>
|
||||
</svg>`, Sn = {
|
||||
icon: qn,
|
||||
</svg>`, An = {
|
||||
icon: $n,
|
||||
headline: "No adventurer chosen",
|
||||
body: "Open The Party and tap your crest to open your quest log."
|
||||
}, Tn = {
|
||||
icon: Mn,
|
||||
}, Sn = {
|
||||
icon: qn,
|
||||
headline: "NestQuest is not set up yet",
|
||||
body: "A parent needs to finish setting up NestQuest."
|
||||
}, zn = {
|
||||
icon: Cn,
|
||||
icon: Mn,
|
||||
headline: "The records cannot be reached",
|
||||
body: "The party's records are quiet right now. NestQuest will return shortly."
|
||||
}, De = [
|
||||
{ key: "morning", name: "Morning", range: "Until 11:59 AM", icon: wn },
|
||||
{ key: "morning", name: "Morning", range: "Until 11:59 AM", icon: xn },
|
||||
{ key: "afternoon", name: "Afternoon", range: "12:00–5:00 PM", icon: Ye },
|
||||
{ key: "evening", name: "Evening", range: "5:00–9:00 PM", icon: kn }
|
||||
{ key: "evening", name: "Evening", range: "5:00–9:00 PM", icon: wn }
|
||||
], W = class W extends C {
|
||||
constructor() {
|
||||
super(...arguments), this._now = /* @__PURE__ */ new Date(), this._confirm = null, this._optimistic = /* @__PURE__ */ new Map(), this._toast = null, this._countdown = null, this._unsubs = [], this._subscribed = !1, this._subGeneration = 0, this._onActivity = () => {
|
||||
@@ -3595,9 +3554,9 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
_renderMain(e) {
|
||||
switch (e.kind) {
|
||||
case "no-adventurer":
|
||||
return this._renderNotice(Sn);
|
||||
return this._renderNotice(An);
|
||||
case "not-set-up":
|
||||
return this._renderNotice(Tn);
|
||||
return this._renderNotice(Sn);
|
||||
case "unreachable":
|
||||
return this._renderNotice(zn);
|
||||
case "away": {
|
||||
@@ -3606,7 +3565,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
${this._renderHeader(e)}
|
||||
<div class="notice-wrap">
|
||||
<div class="notice away" role="status">
|
||||
${$n}
|
||||
${kn}
|
||||
<span class="notice-headline">${e.name} is on travels</span>
|
||||
${t.map((n) => d`<p class="notice-body">${n}</p>`)}
|
||||
</div>
|
||||
@@ -3710,7 +3669,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
_awayReturns(e) {
|
||||
const t = this._timeZone(), n = this._state(
|
||||
`binary_sensor.nestquest_${e}_present_today`
|
||||
), s = Re(
|
||||
), s = Ue(
|
||||
n?.attributes?.next_present,
|
||||
t
|
||||
);
|
||||
@@ -3856,7 +3815,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
if (!u) {
|
||||
const _ = this._state(
|
||||
`binary_sensor.nestquest_${l}_present_today`
|
||||
), v = Re(
|
||||
), v = Ue(
|
||||
_?.attributes?.next_present,
|
||||
n
|
||||
);
|
||||
@@ -3877,16 +3836,6 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
const t = this._childSlug(), n = e.kind === "away", s = n ? e.name : this._childName(t) ?? (t ? ie(t) : null), { due: a, completed: r } = this._childCounts(t), l = this._remaining(), o = this._partyCounts(), p = s ? `${s}'s Quest Log` : "Quest Log", u = (s?.charAt(0) || "?").toUpperCase();
|
||||
return d`
|
||||
<header class="header">
|
||||
${this._boardPath() ? d`
|
||||
<button
|
||||
class="return"
|
||||
type="button"
|
||||
@click=${() => this._returnToBoard()}
|
||||
>
|
||||
${xn}
|
||||
<span>The Party</span>
|
||||
</button>
|
||||
` : g}
|
||||
<span class="crest${n ? " away" : ""}" aria-hidden="true">
|
||||
<span class="crest-face">
|
||||
<span class="initial">${u}</span>
|
||||
@@ -4234,7 +4183,7 @@ const Ue = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)", yn = "polygon(50%
|
||||
const t = gn(e.condition), n = _n(e.condition, t), s = e.temperature === null ? g : d`<span class="temp">${Math.round(e.temperature)}°</span>`, a = e.high === null || e.low === null ? null : `${Math.round(e.high)}° / ${Math.round(e.low)}°`;
|
||||
return d`
|
||||
<div class="dock">
|
||||
${An}
|
||||
${Cn}
|
||||
${s}
|
||||
<span class="divider"></span>
|
||||
<span class="condition">
|
||||
@@ -4269,7 +4218,7 @@ fe({
|
||||
name: "NestQuest Quest Log",
|
||||
description: "One child's daily quests, grouped by window."
|
||||
});
|
||||
const En = ":host{--nq-brand-blue: #3B3AB8;--nq-brand-purple: #A035CC;--nq-brand-gradient: linear-gradient(135deg, var(--nq-brand-blue), var(--nq-brand-purple));--nq-brand-gradient-h: linear-gradient(90deg, var(--nq-brand-blue), var(--nq-brand-purple));--nq-a-page: #F4F4F6;--nq-a-surface: #FFFFFF;--nq-a-surface-subtle: #FAFAFA;--nq-a-selected: #EBEBF8;--nq-a-border: #E4E4EA;--nq-a-divider: #EDEDF1;--nq-a-ink: #18181D;--nq-a-ink-secondary: #52525E;--nq-a-ink-tertiary: #70707E;--nq-a-success: #15803D;--nq-a-danger: #DC2626;--nq-a-danger-strong: #B91C1C;--nq-a-danger-bg: #FEE2E2;--nq-a-warning-ink: #92400E;--nq-a-warning-ink-2: #78350F;--nq-a-warning-bg: #FEF3C7;--nq-a-warning-border: rgba(217,119,6,.35);--nq-a-info-bg: #DBEAFE;--nq-a-info-ink: #1E3A8A;--nq-a-info-icon: #1D4ED8;--nq-a-reversal: #7D28A0;--nq-a-font: Nunito, system-ui, sans-serif;--nq-a-size-screen: 24px;--nq-a-size-hero: 32px;--nq-a-size-card-title: 19px;--nq-a-size-stat: 22px;--nq-a-size-row: 13.5px;--nq-a-size-meta: 11px;--nq-a-size-label: 10px;--nq-a-track-label: .1em;--nq-a-density-page-pad: 14px 16px 92px;--nq-a-density-gap: 10px;--nq-a-density-card-pad: 13px;--nq-a-density-row-pad: 11px 13px;--nq-a-density-radius: 8px;--nq-a-density-shadow: none;--nq-a-tabbar-height: 70px;--nq-a-tap-min: 44px;--nq-a-radius-pill: 9999px;--nq-a-radius-sheet: 20px 20px 0 0;--nq-a-sheet-shadow: 0 -8px 28px rgba(9,9,11,.18);--nq-a-progress-height: 6px;--nq-ease-out: cubic-bezier(0, 0, .2, 1);--nq-dur-micro: .12s;--nq-dur-base: .2s;--nq-dur-modal: .35s}", G = class G extends C {
|
||||
const Tn = ":host{--nq-brand-blue: #3B3AB8;--nq-brand-purple: #A035CC;--nq-brand-gradient: linear-gradient(135deg, var(--nq-brand-blue), var(--nq-brand-purple));--nq-brand-gradient-h: linear-gradient(90deg, var(--nq-brand-blue), var(--nq-brand-purple));--nq-a-page: #F4F4F6;--nq-a-surface: #FFFFFF;--nq-a-surface-subtle: #FAFAFA;--nq-a-selected: #EBEBF8;--nq-a-border: #E4E4EA;--nq-a-divider: #EDEDF1;--nq-a-ink: #18181D;--nq-a-ink-secondary: #52525E;--nq-a-ink-tertiary: #70707E;--nq-a-success: #15803D;--nq-a-danger: #DC2626;--nq-a-danger-strong: #B91C1C;--nq-a-danger-bg: #FEE2E2;--nq-a-warning-ink: #92400E;--nq-a-warning-ink-2: #78350F;--nq-a-warning-bg: #FEF3C7;--nq-a-warning-border: rgba(217,119,6,.35);--nq-a-info-bg: #DBEAFE;--nq-a-info-ink: #1E3A8A;--nq-a-info-icon: #1D4ED8;--nq-a-reversal: #7D28A0;--nq-a-font: Nunito, system-ui, sans-serif;--nq-a-size-screen: 24px;--nq-a-size-hero: 32px;--nq-a-size-card-title: 19px;--nq-a-size-stat: 22px;--nq-a-size-row: 13.5px;--nq-a-size-meta: 11px;--nq-a-size-label: 10px;--nq-a-track-label: .1em;--nq-a-density-page-pad: 14px 16px 92px;--nq-a-density-gap: 10px;--nq-a-density-card-pad: 13px;--nq-a-density-row-pad: 11px 13px;--nq-a-density-radius: 8px;--nq-a-density-shadow: none;--nq-a-tabbar-height: 70px;--nq-a-tap-min: 44px;--nq-a-radius-pill: 9999px;--nq-a-radius-sheet: 20px 20px 0 0;--nq-a-sheet-shadow: 0 -8px 28px rgba(9,9,11,.18);--nq-a-progress-height: 6px;--nq-ease-out: cubic-bezier(0, 0, .2, 1);--nq-dur-micro: .12s;--nq-dur-base: .2s;--nq-dur-modal: .35s}", G = class G extends C {
|
||||
setConfig(e) {
|
||||
if (!e || typeof e != "object")
|
||||
throw new Error("Invalid configuration");
|
||||
@@ -4285,7 +4234,7 @@ const En = ":host{--nq-brand-blue: #3B3AB8;--nq-brand-purple: #A035CC;--nq-brand
|
||||
G.properties = {
|
||||
hass: { attribute: !1 },
|
||||
_config: { state: !0 }
|
||||
}, G.styles = [x(En)];
|
||||
}, G.styles = [x(Tn)];
|
||||
let le = G;
|
||||
customElements.define("nestquest-admin-card", le);
|
||||
fe({
|
||||
@@ -4296,29 +4245,29 @@ fe({
|
||||
function et(i) {
|
||||
return typeof i == "string" ? i.trim() : "";
|
||||
}
|
||||
function Nn(i) {
|
||||
function En(i) {
|
||||
if (i === null || typeof i != "object" || Array.isArray(i))
|
||||
return "";
|
||||
const e = i.slug;
|
||||
return typeof e == "string" ? e.trim() : "";
|
||||
}
|
||||
function Ln(i) {
|
||||
function Nn(i) {
|
||||
const e = et(i.url_path).replace(/^\/+|\/+$/g, "");
|
||||
return e || (window.location.pathname.split("/").filter(Boolean)[0] ?? "");
|
||||
}
|
||||
function On(i) {
|
||||
function Ln(i) {
|
||||
if (i === null || typeof i != "object" || Array.isArray(i))
|
||||
return "";
|
||||
const e = i.name;
|
||||
return typeof e == "string" ? e.trim() : "";
|
||||
}
|
||||
function Bn(i) {
|
||||
function On(i) {
|
||||
const n = i?.states?.["sensor.nestquest_household_quests_due_today"]?.attributes?.child_roster;
|
||||
return Array.isArray(n) ? n.map((s) => ({ slug: Nn(s), name: On(s) })).filter((s) => s.slug.length > 0) : [];
|
||||
return Array.isArray(n) ? n.map((s) => ({ slug: En(s), name: Ln(s) })).filter((s) => s.slug.length > 0) : [];
|
||||
}
|
||||
class In {
|
||||
class Bn {
|
||||
static async generate(e, t) {
|
||||
const n = `/${Ln(e)}`, s = et(e.weather_entity), a = {
|
||||
const n = `/${Nn(e)}`, s = et(e.weather_entity), a = {
|
||||
type: "custom:nestquest-party-board-card",
|
||||
quest_log_path: n
|
||||
};
|
||||
@@ -4335,7 +4284,7 @@ class In {
|
||||
type: "panel",
|
||||
cards: [a]
|
||||
},
|
||||
...Bn(t).map((l) => ({
|
||||
...On(t).map((l) => ({
|
||||
path: l.slug,
|
||||
title: l.name ? `${l.name}'s Quest Log` : `${l.slug}'s Quest Log`,
|
||||
type: "panel",
|
||||
@@ -4346,9 +4295,9 @@ class In {
|
||||
}
|
||||
}
|
||||
window.customStrategies = window.customStrategies ?? {};
|
||||
window.customStrategies["nestquest-party"] = In;
|
||||
const Pn = "/nestquest-static/nestquest-fonts.css";
|
||||
window.customStrategies["nestquest-party"] = Bn;
|
||||
const In = "/nestquest-static/nestquest-fonts.css";
|
||||
if (!document.querySelector('link[data-nq-fonts=""]')) {
|
||||
const i = document.createElement("link");
|
||||
i.rel = "stylesheet", i.href = Pn, i.dataset.nqFonts = "", document.head.appendChild(i);
|
||||
i.rel = "stylesheet", i.href = In, i.dataset.nqFonts = "", document.head.appendChild(i);
|
||||
}
|
||||
|
||||
+1
-18
@@ -64,8 +64,7 @@ Header `Tasks` / `7 definitions · 3 children` + gradient `New` button. Filter c
|
||||
(All / one per child): active `#18181D` fill white text, inactive white with border.
|
||||
Rows: glyph 17px · title 13.5px/700 · meta 11px/600 `<assignees> · <recurrence> · <windows>`
|
||||
· `chevron-right`. An inactive definition renders the whole row at
|
||||
`--nq-a-ink-tertiary` with `· inactive` in the meta. A definition with completion
|
||||
history is never hard-deleted (glossary, D-017): Delete retires it to this inactive state.
|
||||
`--nq-a-ink-tertiary` with `· inactive` in the meta — never hard-deleted (glossary).
|
||||
The row being edited takes `--nq-a-selected` with brand-blue glyph, `Editing` meta and
|
||||
`chevron-down`.
|
||||
|
||||
@@ -84,22 +83,6 @@ Bottom sheet, `--nq-a-radius-sheet`, `--nq-a-sheet-shadow`, 38×4px grabber, pad
|
||||
Footer: `Cancel` (flex 1, bordered) + `Save changes` (flex 2, gradient), both 13px vertical
|
||||
padding. Sheet enters over the dimmed list in `--nq-dur-modal`.
|
||||
|
||||
Delete (editing an existing definition only, never on `New`): a full-width bordered
|
||||
`Delete task` button below the footer, danger-ink text. Tapping it swaps the footer for a
|
||||
danger-tinted confirm — "Delete this task? If it has no completion history it is deleted;
|
||||
otherwise it is retired (deactivated) and its history is kept." — with `Go back` and a
|
||||
danger-filled `Delete task`. Confirming calls `DELETE /api/v1/admin/quest-definitions/{id}`
|
||||
(admin plane only; the kids' panel has no equivalent control). Hybrid outcome (D-017): no
|
||||
completion event on any instance → the definition, its instances, assignees, windows and
|
||||
unreferenced rule are hard-deleted and the row leaves the list; otherwise the definition
|
||||
is retired (deactivated) and the row stays, shown inactive. 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`. An error keeps the sheet open with the API's
|
||||
detail.
|
||||
|
||||
### 3.3 Icon picker
|
||||
Each definition carries one optional icon, shown on both surfaces. The picker offers three
|
||||
sources:
|
||||
|
||||
@@ -71,14 +71,6 @@ and time only rather than removing it (the strip is part of the frame).
|
||||
|
||||
Reached by tapping a present crest. Header at y=56, page inset 62px:
|
||||
|
||||
- **Return control** first in the header, left of the crest: a `--nq-p-button-height`
|
||||
72px button, radius 10px, `rgba(92,62,26,.1)` with a 2px `rgba(92,62,26,.5)` border
|
||||
(the confirm dialog's **Not yet** treatment), `chevron-left` 34px + `The Party`
|
||||
26px/700 Cinzel `--nq-p-ink`, 28px header gap to the crest. Tapping it takes the same
|
||||
path as the idle return (§3.5) — navigate to `board_path` — immediately. Press
|
||||
feedback `scale(.98)`, `--nq-dur-micro`. Not rendered when no `board_path` is
|
||||
configured. The party board is the main display and has no return control; the
|
||||
Quest complete screen (§5) keeps its auto-return.
|
||||
- Small crest 96×110 (initial 44px/700 display).
|
||||
- Title `<Name>'s Quest Log` 56px/700 display.
|
||||
- Sub `<weekday>, <Month D> · N of M claimed` 20px/600 Cinzel, tracking .24em, uppercase.
|
||||
|
||||
@@ -374,37 +374,6 @@ const logStyles = css`
|
||||
gap: 28px;
|
||||
}
|
||||
|
||||
button.return {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
height: var(--nq-p-button-height);
|
||||
padding: 0 28px 0 20px;
|
||||
border: 2px solid rgba(92, 62, 26, 0.5);
|
||||
border-radius: 10px;
|
||||
background: rgba(92, 62, 26, 0.1);
|
||||
color: var(--nq-p-ink);
|
||||
font-family: var(--nq-p-font-heading);
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
transition: transform var(--nq-dur-micro) var(--nq-ease-out);
|
||||
}
|
||||
|
||||
button.return:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
button.return svg {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
}
|
||||
|
||||
.crest {
|
||||
position: relative;
|
||||
flex: none;
|
||||
@@ -1230,18 +1199,6 @@ const ICON_X = html`<svg
|
||||
<path d="m6 6 12 12"></path>
|
||||
</svg>`;
|
||||
|
||||
const ICON_CHEVRON_LEFT = html`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="m15 18-6-6 6-6"></path>
|
||||
</svg>`;
|
||||
|
||||
const ICON_STAR = html`<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
@@ -1987,18 +1944,6 @@ export class NestQuestQuestLogCard extends LitElement {
|
||||
const initial = (name?.charAt(0) || "?").toUpperCase();
|
||||
return html`
|
||||
<header class="header">
|
||||
${this._boardPath()
|
||||
? html`
|
||||
<button
|
||||
class="return"
|
||||
type="button"
|
||||
@click=${() => this._returnToBoard()}
|
||||
>
|
||||
${ICON_CHEVRON_LEFT}
|
||||
<span>The Party</span>
|
||||
</button>
|
||||
`
|
||||
: nothing}
|
||||
<span class="crest${away ? " away" : ""}" aria-hidden="true">
|
||||
<span class="crest-face">
|
||||
<span class="initial">${initial}</span>
|
||||
|
||||
@@ -14,8 +14,6 @@
|
||||
* tap_complete: <instance id> the harness taps that card's Complete button,
|
||||
* records whether the confirm dialog opened, taps the dialog's Complete, and
|
||||
* reports every hass.callService call as tap: {dialog_opened, service_calls}.
|
||||
* With tap_return: true the harness taps the header's return control and
|
||||
* reports it as returned: {rendered, label} before the final snapshot.
|
||||
* The Python panel tests drive this harness so the
|
||||
* assertions run against the exact bundle HACS ships.
|
||||
*/
|
||||
@@ -77,17 +75,6 @@ if (spec.tap_complete !== undefined) {
|
||||
tap = { dialog_opened: confirm !== null, service_calls: serviceCalls };
|
||||
}
|
||||
|
||||
let returned = null;
|
||||
if (spec.tap_return) {
|
||||
const control = element.shadowRoot.querySelector(".header button.return");
|
||||
returned = {
|
||||
rendered: control !== null,
|
||||
label: control?.textContent?.trim() ?? "",
|
||||
};
|
||||
control?.click();
|
||||
await element.updateComplete;
|
||||
}
|
||||
|
||||
const snapshot = () => ({
|
||||
location: window.location.pathname,
|
||||
headline: element.shadowRoot.querySelector(".title")?.textContent?.trim() ?? "",
|
||||
@@ -123,6 +110,6 @@ if (spec.idle_ms !== undefined) {
|
||||
await new Promise((resolve) => setTimeout(resolve, spec.idle_ms));
|
||||
}
|
||||
|
||||
const payload = JSON.stringify({ ...snapshot(), probe, tap, returned });
|
||||
const payload = JSON.stringify({ ...snapshot(), probe, tap });
|
||||
await new Promise((resolve) => process.stdout.write(payload, () => resolve()));
|
||||
process.exit(0);
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "nestquest"
|
||||
version = "0.9.5"
|
||||
version = "0.8.0"
|
||||
description = "NestQuest Home Assistant Integration"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
|
||||
@@ -817,141 +817,3 @@ async def test_set_active_malformed_body_is_422(
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
# --- delete: hybrid (delete if no history, retire if there is) --------------
|
||||
|
||||
_dao_instances = importlib.import_module("nestquest_core.dao_instances")
|
||||
|
||||
|
||||
def test_delete_route_lives_on_the_admin_router() -> None:
|
||||
"""The DELETE route is on the admin router, which carries the ONE
|
||||
require_admin dependency — no second auth check is added."""
|
||||
from api.auth import require_admin
|
||||
from api.routes_admin import router as admin_router
|
||||
|
||||
assert require_admin in [d.dependency for d in admin_router.dependencies]
|
||||
matches = [
|
||||
route
|
||||
for route in admin_router.routes
|
||||
if route.path == "/api/v1/admin/quest-definitions/{definition_id}"
|
||||
and "DELETE" in route.methods
|
||||
]
|
||||
assert len(matches) == 1
|
||||
|
||||
|
||||
async def test_delete_refuses_non_admin_and_absent(
|
||||
admin_questdefs: SimpleNamespace,
|
||||
) -> None:
|
||||
"""A non-admin JWT is 403 and an absent credential 401: nothing is
|
||||
deleted or retired."""
|
||||
client = admin_questdefs.client
|
||||
ada = (await _create_children(client, ("Ada",)))[0]
|
||||
definition_id = (await _create_definition(client, [ada])).json()["id"]
|
||||
non_admin = make_token(groups=("some-other-group",))
|
||||
|
||||
forbidden = await client.delete(
|
||||
f"/api/v1/admin/quest-definitions/{definition_id}",
|
||||
headers={"Authorization": f"Bearer {non_admin}"},
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
unauthenticated = await client.delete(
|
||||
f"/api/v1/admin/quest-definitions/{definition_id}"
|
||||
)
|
||||
assert unauthenticated.status_code == 401
|
||||
|
||||
record = await _dao_rules.QuestDefinitionsDao(
|
||||
admin_questdefs.database
|
||||
).get(definition_id)
|
||||
assert record is not None
|
||||
assert record.is_active is True
|
||||
|
||||
|
||||
async def test_delete_without_history_hard_deletes(
|
||||
admin_questdefs: SimpleNamespace,
|
||||
) -> None:
|
||||
"""No completion history: 200 ``deleted`` and the row and its
|
||||
unreferenced rule are gone."""
|
||||
client = admin_questdefs.client
|
||||
ada = (await _create_children(client, ("Ada",)))[0]
|
||||
definition_id = (await _create_definition(client, [ada])).json()["id"]
|
||||
dao = _dao_rules.QuestDefinitionsDao(admin_questdefs.database)
|
||||
rule_id = (await dao.get(definition_id)).schedule_rule_id
|
||||
|
||||
response = await client.delete(
|
||||
f"/api/v1/admin/quest-definitions/{definition_id}",
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"definition_id": definition_id,
|
||||
"deleted": True,
|
||||
"retired": False,
|
||||
"definition": None,
|
||||
}
|
||||
assert await dao.get(definition_id) is None
|
||||
assert await _dao_rules.ScheduleRulesDao(
|
||||
admin_questdefs.database
|
||||
).get(rule_id) is None
|
||||
|
||||
|
||||
async def test_delete_with_history_retires(
|
||||
admin_questdefs: SimpleNamespace,
|
||||
) -> None:
|
||||
"""Completion history present: 200 ``retired`` with the now-inactive
|
||||
definition; the row, instance and history all remain."""
|
||||
client = admin_questdefs.client
|
||||
database = admin_questdefs.database
|
||||
ada = (await _create_children(client, ("Ada",)))[0]
|
||||
definition_id = (await _create_definition(client, [ada])).json()["id"]
|
||||
instance = await _dao_instances.QuestInstancesDao(database).upsert(
|
||||
definition_id,
|
||||
ada,
|
||||
datetime.date.today().isoformat(),
|
||||
"2026-09-14T12:00:00+00:00",
|
||||
window="morning",
|
||||
)
|
||||
events = _dao_instances.CompletionEventsDao(database)
|
||||
event = await events.append(
|
||||
instance.id,
|
||||
ada,
|
||||
"completed",
|
||||
"user",
|
||||
"2026-09-14T12:00:00+00:00",
|
||||
True,
|
||||
actor_user_id="admin-1",
|
||||
)
|
||||
|
||||
response = await client.delete(
|
||||
f"/api/v1/admin/quest-definitions/{definition_id}",
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.json()
|
||||
assert payload["definition_id"] == definition_id
|
||||
assert payload["deleted"] is False
|
||||
assert payload["retired"] is True
|
||||
assert payload["definition"]["id"] == definition_id
|
||||
assert payload["definition"]["is_active"] is False
|
||||
assert payload["definition"]["title"] == "Tidy the den"
|
||||
record = await _dao_rules.QuestDefinitionsDao(database).get(definition_id)
|
||||
assert record is not None
|
||||
assert record.is_active is False
|
||||
assert await _dao_instances.QuestInstancesDao(database).get_by_id(
|
||||
instance.id
|
||||
) == instance
|
||||
assert await events.list_by_instance(instance.id) == [event]
|
||||
|
||||
|
||||
async def test_delete_unknown_definition_is_404(
|
||||
admin_questdefs: SimpleNamespace,
|
||||
) -> None:
|
||||
"""A DELETE naming a definition that does not exist is 404."""
|
||||
response = await admin_questdefs.client.delete(
|
||||
"/api/v1/admin/quest-definitions/999",
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert response.status_code == 404
|
||||
assert response.json()["detail"] == "Quest definition not found"
|
||||
|
||||
@@ -13,7 +13,7 @@ proven against the DATABASE the routes wrote, not a parallel copy.
|
||||
Proven per the done-condition, everything read back through the API:
|
||||
|
||||
- ``GET /api/v1/admin/settings`` returns the current effective settings
|
||||
— the twelve documented fields at their defaults on a fresh database.
|
||||
— the eleven documented fields at their defaults on a fresh database.
|
||||
- ``PATCH /api/v1/admin/settings`` PERSISTS the supplied fields and the
|
||||
NEXT read reflects them; a later partial update merges onto the
|
||||
current effective settings (omitted fields keep their stored value),
|
||||
@@ -60,7 +60,7 @@ _dao_meta = importlib.import_module("nestquest_core.dao_meta")
|
||||
SETTINGS_META_KEY = "settings"
|
||||
|
||||
#: The all-defaults effective settings a fresh database reports — the
|
||||
#: documented twelve fields, asserted literally so the payload contract is
|
||||
#: documented eleven fields, asserted literally so the payload contract is
|
||||
#: pinned here, independent of the core constants.
|
||||
DEFAULT_SETTINGS = {
|
||||
"horizon_days": 14,
|
||||
@@ -74,7 +74,6 @@ DEFAULT_SETTINGS = {
|
||||
"end_of_day_report_enabled": True,
|
||||
"celebration_enabled": True,
|
||||
"timezone": "",
|
||||
"timezone_configured": False,
|
||||
}
|
||||
|
||||
|
||||
@@ -105,7 +104,7 @@ async def settings_client(temp_db_path: str) -> SimpleNamespace:
|
||||
async def test_get_settings_returns_defaults_on_a_fresh_database(
|
||||
settings_client: SimpleNamespace,
|
||||
) -> None:
|
||||
"""GET returns the twelve documented fields at their defaults."""
|
||||
"""GET returns the eleven documented fields at their defaults."""
|
||||
response = await settings_client.client.get(
|
||||
"/api/v1/admin/settings", headers=_admin_headers()
|
||||
)
|
||||
@@ -141,7 +140,7 @@ async def test_update_persists_and_the_next_read_reflects_it(
|
||||
assert reread.status_code == 200
|
||||
assert reread.json() == expected
|
||||
|
||||
# ...and the DATABASE holds the merged document: the complete twelve
|
||||
# ...and the DATABASE holds the merged document: the complete eleven
|
||||
# fields, keyed by field name, under the well-known meta_state key.
|
||||
raw = await _dao_meta.MetaStateDao(settings_client.database).get(
|
||||
SETTINGS_META_KEY
|
||||
@@ -223,40 +222,6 @@ async def test_null_resets_a_field_to_its_default(
|
||||
assert reread.json()["horizon_days"] == 14
|
||||
|
||||
|
||||
async def test_timezone_configured_round_trips_with_an_explicit_empty_zone(
|
||||
settings_client: SimpleNamespace,
|
||||
) -> None:
|
||||
"""An explicit empty (host-local) zone persists as configured.
|
||||
|
||||
The admin clearing the zone PATCHes ``timezone: ""`` together with
|
||||
``timezone_configured: true``; the NEXT read — a reopened settings
|
||||
screen — sees the marker, so the empty value is a persisted choice
|
||||
rather than a fresh install to auto-set.
|
||||
"""
|
||||
client = settings_client.client
|
||||
fresh = await client.get("/api/v1/admin/settings", headers=_admin_headers())
|
||||
assert fresh.json()["timezone_configured"] is False
|
||||
|
||||
patched = await client.patch(
|
||||
"/api/v1/admin/settings",
|
||||
json={"timezone": "", "timezone_configured": True},
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert patched.status_code == 200
|
||||
expected = {**DEFAULT_SETTINGS, "timezone_configured": True}
|
||||
assert patched.json() == expected
|
||||
|
||||
reread = await client.get(
|
||||
"/api/v1/admin/settings", headers=_admin_headers()
|
||||
)
|
||||
assert reread.json() == expected
|
||||
raw = await _dao_meta.MetaStateDao(settings_client.database).get(
|
||||
SETTINGS_META_KEY
|
||||
)
|
||||
assert raw is not None
|
||||
assert json.loads(raw)["timezone_configured"] is True
|
||||
|
||||
|
||||
# --- validation: rejected values never change the stored settings -------
|
||||
|
||||
|
||||
@@ -273,8 +238,6 @@ async def test_timezone_configured_round_trips_with_an_explicit_empty_zone(
|
||||
({"morning_summary_enabled": "yes"}, "morning_summary_enabled"),
|
||||
({"celebration_enabled": 1}, "celebration_enabled"),
|
||||
({"notify_target": 5}, "notify_target"),
|
||||
({"timezone_configured": "true"}, "timezone_configured"),
|
||||
({"timezone_configured": 1}, "timezone_configured"),
|
||||
],
|
||||
)
|
||||
async def test_invalid_value_is_rejected_and_stored_settings_unchanged(
|
||||
|
||||
@@ -196,27 +196,6 @@ async def test_complete_instance_posts_body_and_headers() -> None:
|
||||
assert call["headers"]["Authorization"] == f"Bearer {TOKEN}"
|
||||
|
||||
|
||||
async def test_household_timezone_rides_every_request_header() -> None:
|
||||
"""Home Assistant's zone is reported so the API reads the household
|
||||
clock (task 6351b36d); it is sent only when the client has one."""
|
||||
transport = StubTransport(
|
||||
StubResponse(200, json.dumps(SNAPSHOT_PAYLOAD)),
|
||||
StubResponse(200, '{"status": "done"}'),
|
||||
)
|
||||
client = NestQuestApiClient(
|
||||
BASE_URL, TOKEN, transport, household_timezone="America/New_York"
|
||||
)
|
||||
|
||||
await client.get_snapshot()
|
||||
await client.complete_instance(42, 3)
|
||||
|
||||
for call in transport.calls:
|
||||
assert call["headers"] == {
|
||||
"Authorization": f"Bearer {TOKEN}",
|
||||
"X-NestQuest-Timezone": "America/New_York",
|
||||
}
|
||||
|
||||
|
||||
async def test_base_url_trailing_slash_is_normalized() -> None:
|
||||
"""A base URL with a trailing slash must not double the path slash."""
|
||||
transport = StubTransport(StubResponse(200, "{}"))
|
||||
@@ -413,20 +392,11 @@ def test_client_from_entry_reads_config_and_shared_session(monkeypatch) -> None:
|
||||
}
|
||||
)
|
||||
|
||||
hass = types.SimpleNamespace(
|
||||
config=types.SimpleNamespace(time_zone="America/New_York")
|
||||
)
|
||||
|
||||
client = api_client.client_from_entry(hass, entry)
|
||||
client = api_client.client_from_entry(object(), entry)
|
||||
|
||||
assert client._session is shared_session
|
||||
assert client._base_url == "http://panel.lan:8443"
|
||||
assert client._panel_token == "entry-token"
|
||||
assert client._household_timezone == "America/New_York"
|
||||
|
||||
|
||||
#: A minimal hass stand-in carrying the configured time zone.
|
||||
_HASS_UTC = types.SimpleNamespace(config=types.SimpleNamespace(time_zone="UTC"))
|
||||
|
||||
|
||||
def test_client_from_entry_unconfigured_token_raises_at_construction(
|
||||
@@ -449,12 +419,12 @@ def test_client_from_entry_unconfigured_token_raises_at_construction(
|
||||
assert resolve_api_config(entry)[1] == DEFAULT_PANEL_TOKEN == ""
|
||||
|
||||
with pytest.raises(ValueError, match="panel_token must be a non-empty"):
|
||||
api_client.client_from_entry(_HASS_UTC, entry)
|
||||
api_client.client_from_entry(object(), entry)
|
||||
|
||||
# Same for a whitespace-only stored token: whitespace is not a token.
|
||||
entry_ws = make_config_entry(options={CONF_PANEL_TOKEN: " "})
|
||||
with pytest.raises(ValueError, match="panel_token must be a non-empty"):
|
||||
api_client.client_from_entry(_HASS_UTC, entry_ws)
|
||||
api_client.client_from_entry(object(), entry_ws)
|
||||
|
||||
|
||||
async def test_client_logs_nothing() -> None:
|
||||
|
||||
@@ -31,7 +31,6 @@ from zoneinfo import ZoneInfo
|
||||
import pytest
|
||||
|
||||
from api import routes_admin, routes_panel
|
||||
from api import scheduler as scheduler_module
|
||||
from api.database import _executor
|
||||
from api.scheduler import MissedSweepScheduler, _delay_seconds
|
||||
from tests.admin_jwt_harness import (
|
||||
@@ -237,25 +236,6 @@ def test_from_options_reads_and_resiliently_defaults_timezone() -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_settings_timezone_configured_defaults_false_and_is_strict() -> None:
|
||||
assert _settings.NestQuestSettings().timezone_configured is False
|
||||
assert _settings.NestQuestSettings.from_options({}).timezone_configured is False
|
||||
assert (
|
||||
_settings.NestQuestSettings.from_options(
|
||||
{"timezone_configured": True}
|
||||
).timezone_configured
|
||||
is True
|
||||
)
|
||||
for value in ("true", 1, None):
|
||||
with pytest.raises(ValueError, match="timezone_configured"):
|
||||
_settings.NestQuestSettings(timezone_configured=value)
|
||||
if value is not None:
|
||||
with pytest.raises(ValueError):
|
||||
_settings.NestQuestSettings.from_options(
|
||||
{"timezone_configured": value}
|
||||
)
|
||||
|
||||
|
||||
# --- the missed-sweep scheduler ----------------------------------------------
|
||||
|
||||
|
||||
@@ -327,481 +307,3 @@ def test_delay_seconds_is_true_elapsed_time_across_dst(
|
||||
now: datetime.datetime, target: datetime.time, expected: float
|
||||
) -> None:
|
||||
assert _delay_seconds(target, now) == expected
|
||||
|
||||
|
||||
# --- the Home Assistant-reported zone (task 6351b36d) ------------------------
|
||||
#
|
||||
# The deployed household never set ``timezone``, so the UTC API host marked
|
||||
# morning quests overdue. The integration reports Home Assistant's
|
||||
# ``time_zone`` on every panel request; while the admin has not chosen a
|
||||
# zone the API adopts it (persisted, so the scheduler and the admin plane
|
||||
# follow too), and an explicit admin choice still wins.
|
||||
|
||||
|
||||
def _reporting_panel_headers(zone: str) -> dict[str, str]:
|
||||
return {**_panel_headers(), "X-NestQuest-Timezone": zone}
|
||||
|
||||
|
||||
async def _panel_pack_bag(
|
||||
household: SimpleNamespace, zone: str
|
||||
) -> tuple[str, dict]:
|
||||
response = await household.client.get(
|
||||
"/api/v1/panel/snapshot", headers=_reporting_panel_headers(zone)
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
ada = next(
|
||||
child
|
||||
for child in body["children"]
|
||||
if child["child_id"] == household.seed.ada.id
|
||||
)
|
||||
(instance,) = ada["instances"]
|
||||
return body["today_iso"], instance
|
||||
|
||||
|
||||
async def _stored_settings(household: SimpleNamespace) -> dict:
|
||||
response = await household.client.get(
|
||||
"/api/v1/admin/settings", headers=_admin_headers()
|
||||
)
|
||||
assert response.status_code == 200
|
||||
return response.json()
|
||||
|
||||
|
||||
async def test_unset_zone_adopts_reported_zone_for_overdue(
|
||||
household: SimpleNamespace,
|
||||
) -> None:
|
||||
"""09:59:59 EDT on a UTC host, zone never set: NOT overdue."""
|
||||
household.clock["now"] = _utc(13, 59, 59)
|
||||
today_iso, instance = await _panel_pack_bag(household, HOUSEHOLD_ZONE)
|
||||
assert today_iso == TODAY.isoformat()
|
||||
assert instance["overdue"] is False
|
||||
# Persisted as the automatic (not admin-chosen) household zone, so
|
||||
# the admin plane and the missed-sweep scheduler read it too.
|
||||
stored = await _stored_settings(household)
|
||||
assert stored["timezone"] == HOUSEHOLD_ZONE
|
||||
assert stored["timezone_configured"] is False
|
||||
_today, admin_instance = await _pack_bag(household, "admin")
|
||||
assert admin_instance["overdue"] is False
|
||||
|
||||
|
||||
async def test_unset_zone_adopts_reported_zone_for_today(
|
||||
household: SimpleNamespace,
|
||||
) -> None:
|
||||
"""23:30 EDT is tomorrow in UTC; the household day is still today."""
|
||||
household.clock["now"] = _utc(3, 30, day=27)
|
||||
today_iso, _instance = await _panel_pack_bag(household, HOUSEHOLD_ZONE)
|
||||
assert today_iso == TODAY.isoformat()
|
||||
|
||||
|
||||
async def test_reported_zone_completion_is_on_time(
|
||||
household: SimpleNamespace,
|
||||
) -> None:
|
||||
"""A 09:30 EDT tap with the zone never set is on time."""
|
||||
household.clock["now"] = _utc(13, 30)
|
||||
seed = household.seed
|
||||
response = await household.client.post(
|
||||
f"/api/v1/panel/instances/{seed.pack_bag_instance.id}/complete",
|
||||
headers=_reporting_panel_headers(HOUSEHOLD_ZONE),
|
||||
json={"actor_child_id": seed.ada.id},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
_today_iso, instance = await _pack_bag(household, "admin")
|
||||
assert instance["on_time"] is True
|
||||
|
||||
|
||||
async def test_reported_zone_follows_home_assistant_changes(
|
||||
household: SimpleNamespace,
|
||||
) -> None:
|
||||
"""An automatically adopted zone tracks a later Home Assistant change."""
|
||||
await _panel_pack_bag(household, "America/Chicago")
|
||||
await _panel_pack_bag(household, HOUSEHOLD_ZONE)
|
||||
assert (await _stored_settings(household))["timezone"] == HOUSEHOLD_ZONE
|
||||
|
||||
|
||||
async def _adopt_new_york(household: SimpleNamespace) -> None:
|
||||
"""Prove automatic adoption first, so later assertions can't pass
|
||||
on code that ignores the reported zone altogether."""
|
||||
await _panel_pack_bag(household, HOUSEHOLD_ZONE)
|
||||
stored = await _stored_settings(household)
|
||||
assert stored["timezone"] == HOUSEHOLD_ZONE
|
||||
assert stored["timezone_configured"] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chosen", ["America/Los_Angeles", ""])
|
||||
async def test_admin_chosen_zone_wins_over_reported_zone(
|
||||
household: SimpleNamespace, chosen: str
|
||||
) -> None:
|
||||
await _adopt_new_york(household)
|
||||
response = await household.client.patch(
|
||||
"/api/v1/admin/settings",
|
||||
json={"timezone": chosen, "timezone_configured": True},
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
# A conflicting report is no longer adopted.
|
||||
await _panel_pack_bag(household, "America/Chicago")
|
||||
stored = await _stored_settings(household)
|
||||
assert stored["timezone"] == chosen
|
||||
assert stored["timezone_configured"] is True
|
||||
|
||||
|
||||
async def test_invalid_reported_zone_is_ignored(
|
||||
household: SimpleNamespace,
|
||||
) -> None:
|
||||
await _adopt_new_york(household)
|
||||
household.clock["now"] = _utc(13, 59, 59)
|
||||
_today_iso, instance = await _panel_pack_bag(household, "Mars/Olympus_Mons")
|
||||
# Still read in the adopted zone: 09:59:59 EDT is not overdue.
|
||||
assert instance["overdue"] is False
|
||||
assert (await _stored_settings(household))["timezone"] == HOUSEHOLD_ZONE
|
||||
|
||||
|
||||
# --- the scheduler follows an adopted zone (task 6351b36d) -------------------
|
||||
#
|
||||
# On a UTC host with no stored zone the scheduler first plans for UTC
|
||||
# midnight; a zone adopted while it sleeps must move the sweep to the
|
||||
# household's midnight rather than sweep at 20:00 EDT.
|
||||
|
||||
#: 13:00 UTC (09:00 EDT) to UTC midnight.
|
||||
_UTC_MIDNIGHT_DELAY = 11 * 3600
|
||||
#: 13:00 UTC (09:00 EDT) to New York midnight (04:00 UTC).
|
||||
_NEW_YORK_MIDNIGHT_DELAY = 15 * 3600
|
||||
|
||||
|
||||
async def test_scheduler_replans_when_panel_adopts_zone_while_sleeping(
|
||||
temp_db_path: str,
|
||||
) -> None:
|
||||
runner = AdminRunner(temp_db_path, jwks_for(ADMIN_KEY, KID))
|
||||
async with runner as client:
|
||||
app_state = runner.app.state
|
||||
await app_state.sweep_scheduler.stop()
|
||||
delays: list[float] = []
|
||||
slept = asyncio.Condition()
|
||||
|
||||
async def sleep_stub(seconds: float) -> None:
|
||||
async with slept:
|
||||
delays.append(seconds)
|
||||
slept.notify_all()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
scheduler = MissedSweepScheduler(
|
||||
app_state.db.database, clock=lambda: _utc(13, 0), sleep=sleep_stub
|
||||
)
|
||||
app_state.sweep_scheduler = scheduler
|
||||
scheduler.start()
|
||||
try:
|
||||
async with slept:
|
||||
await asyncio.wait_for(
|
||||
slept.wait_for(lambda: len(delays) == 1), timeout=5
|
||||
)
|
||||
response = await client.get(
|
||||
"/api/v1/panel/snapshot",
|
||||
headers=_reporting_panel_headers(HOUSEHOLD_ZONE),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
async with slept:
|
||||
await asyncio.wait_for(
|
||||
slept.wait_for(lambda: len(delays) == 2), timeout=5
|
||||
)
|
||||
finally:
|
||||
await scheduler.stop()
|
||||
assert delays == [
|
||||
pytest.approx(_UTC_MIDNIGHT_DELAY),
|
||||
pytest.approx(_NEW_YORK_MIDNIGHT_DELAY),
|
||||
]
|
||||
|
||||
|
||||
async def test_scheduler_rechecks_settings_before_sweeping(
|
||||
temp_db_path: str, monkeypatch
|
||||
) -> None:
|
||||
"""A zone stored without a wake-up still stops the stale sweep."""
|
||||
database = _core_db.NestQuestDatabase(_executor)
|
||||
await database.open(temp_db_path)
|
||||
try:
|
||||
await _core_migrations.apply_migrations(database)
|
||||
sweeps: list[datetime.date] = []
|
||||
|
||||
async def sweep_stub(_database, *, today):
|
||||
sweeps.append(today)
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
scheduler_module.core_sweep, "run_missed_sweep", sweep_stub
|
||||
)
|
||||
delays: list[float] = []
|
||||
replanned = asyncio.Event()
|
||||
|
||||
async def sleep_stub(seconds: float) -> None:
|
||||
delays.append(seconds)
|
||||
if len(delays) == 1:
|
||||
# The UTC rollover "arrives" after the zone was stored
|
||||
# behind the scheduler's back.
|
||||
await _settings_store.adopt_reported_timezone(
|
||||
database, HOUSEHOLD_ZONE
|
||||
)
|
||||
return
|
||||
replanned.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
scheduler = MissedSweepScheduler(
|
||||
database, clock=lambda: _utc(13, 0), sleep=sleep_stub
|
||||
)
|
||||
scheduler.start()
|
||||
try:
|
||||
await asyncio.wait_for(replanned.wait(), timeout=5)
|
||||
finally:
|
||||
await scheduler.stop()
|
||||
assert sweeps == []
|
||||
assert delays == [
|
||||
pytest.approx(_UTC_MIDNIGHT_DELAY),
|
||||
pytest.approx(_NEW_YORK_MIDNIGHT_DELAY),
|
||||
]
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
|
||||
# --- adoption is serialised with planning and sweeping (TZ-003) --------------
|
||||
#
|
||||
# An adoption racing the loop's own settings reads must never leave a
|
||||
# stale plan behind. Each test holds the loop at one of its reads and
|
||||
# issues a real panel adoption there; when the scheduler's settings lock
|
||||
# is held at that point the adoption provably cannot commit until the
|
||||
# loop moves on, otherwise it is awaited to commit inside the window.
|
||||
|
||||
|
||||
def _hold_scheduler_read(monkeypatch, scheduler, nth: int, during):
|
||||
"""Run ``during(settings)`` inside the scheduler task's ``nth`` read."""
|
||||
real_load = _settings_store.load_settings
|
||||
reads = {"count": 0}
|
||||
|
||||
async def load_settings(database):
|
||||
settings = await real_load(database)
|
||||
if asyncio.current_task() is scheduler._task:
|
||||
reads["count"] += 1
|
||||
if reads["count"] == nth:
|
||||
await during(settings)
|
||||
return settings
|
||||
|
||||
monkeypatch.setattr(
|
||||
scheduler_module.core_settings_store, "load_settings", load_settings
|
||||
)
|
||||
return real_load
|
||||
|
||||
|
||||
async def _adopt_via(client, zone: str) -> None:
|
||||
response = await client.get(
|
||||
"/api/v1/panel/snapshot", headers=_reporting_panel_headers(zone)
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
async def _adopt_inside_read(client, scheduler, zone: str) -> asyncio.Task:
|
||||
"""Start a panel adoption of ``zone``; let it commit unless serialised."""
|
||||
adoption = asyncio.create_task(
|
||||
client.get(
|
||||
"/api/v1/panel/snapshot", headers=_reporting_panel_headers(zone)
|
||||
)
|
||||
)
|
||||
lock = getattr(scheduler, "settings_lock", None)
|
||||
if lock is None or not lock.locked():
|
||||
await adoption
|
||||
return adoption
|
||||
|
||||
|
||||
async def test_scheduler_follows_successive_zone_changes(
|
||||
temp_db_path: str, monkeypatch
|
||||
) -> None:
|
||||
"""New York -> UTC -> New York while the re-plan read is in flight."""
|
||||
runner = AdminRunner(temp_db_path, jwks_for(ADMIN_KEY, KID))
|
||||
async with runner as client:
|
||||
app_state = runner.app.state
|
||||
await app_state.sweep_scheduler.stop()
|
||||
delays: list[float] = []
|
||||
slept = asyncio.Condition()
|
||||
|
||||
async def sleep_stub(seconds: float) -> None:
|
||||
async with slept:
|
||||
delays.append(seconds)
|
||||
slept.notify_all()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
scheduler = MissedSweepScheduler(
|
||||
app_state.db.database, clock=lambda: _utc(13, 0), sleep=sleep_stub
|
||||
)
|
||||
app_state.sweep_scheduler = scheduler
|
||||
await _adopt_via(client, HOUSEHOLD_ZONE)
|
||||
adoptions: list[asyncio.Task] = []
|
||||
|
||||
async def back_to_new_york(_settings) -> None:
|
||||
adoptions.append(
|
||||
await _adopt_inside_read(client, scheduler, HOUSEHOLD_ZONE)
|
||||
)
|
||||
|
||||
# Read 1 plans New York; read 2 is the re-plan after UTC.
|
||||
_hold_scheduler_read(monkeypatch, scheduler, 2, back_to_new_york)
|
||||
scheduler.start()
|
||||
try:
|
||||
async with slept:
|
||||
await asyncio.wait_for(
|
||||
slept.wait_for(lambda: len(delays) == 1), timeout=5
|
||||
)
|
||||
await _adopt_via(client, "UTC")
|
||||
async with slept:
|
||||
await asyncio.wait_for(
|
||||
slept.wait_for(lambda: len(delays) == 3), timeout=5
|
||||
)
|
||||
(adoption,) = adoptions
|
||||
assert (await adoption).status_code == 200
|
||||
finally:
|
||||
await scheduler.stop()
|
||||
# The in-flight read planned UTC; the New York adoption that followed
|
||||
# it woke the wait, so the scheduler sleeps on New York midnight.
|
||||
assert delays == [
|
||||
pytest.approx(_NEW_YORK_MIDNIGHT_DELAY),
|
||||
pytest.approx(_UTC_MIDNIGHT_DELAY),
|
||||
pytest.approx(_NEW_YORK_MIDNIGHT_DELAY),
|
||||
]
|
||||
|
||||
|
||||
async def test_adoption_after_presweep_check_cannot_precede_the_sweep(
|
||||
temp_db_path: str, monkeypatch
|
||||
) -> None:
|
||||
"""No sweep runs once an adoption has replaced its plan."""
|
||||
runner = AdminRunner(temp_db_path, jwks_for(ADMIN_KEY, KID))
|
||||
async with runner as client:
|
||||
app_state = runner.app.state
|
||||
await app_state.sweep_scheduler.stop()
|
||||
delays: list[float] = []
|
||||
replanned = asyncio.Event()
|
||||
|
||||
async def sleep_stub(seconds: float) -> None:
|
||||
delays.append(seconds)
|
||||
if len(delays) == 1:
|
||||
return # the UTC rollover arrives
|
||||
replanned.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
scheduler = MissedSweepScheduler(
|
||||
app_state.db.database, clock=lambda: _utc(13, 0), sleep=sleep_stub
|
||||
)
|
||||
app_state.sweep_scheduler = scheduler
|
||||
adoptions: list[asyncio.Task] = []
|
||||
|
||||
async def adopt_new_york(_settings) -> None:
|
||||
adoptions.append(
|
||||
await _adopt_inside_read(client, scheduler, HOUSEHOLD_ZONE)
|
||||
)
|
||||
|
||||
# Read 1 plans UTC; read 2 is the pre-sweep re-check.
|
||||
real_load = _hold_scheduler_read(
|
||||
monkeypatch, scheduler, 2, adopt_new_york
|
||||
)
|
||||
swept_under: list[str] = []
|
||||
|
||||
async def sweep_stub(database, *, today):
|
||||
swept_under.append((await real_load(database)).timezone)
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
scheduler_module.core_sweep, "run_missed_sweep", sweep_stub
|
||||
)
|
||||
scheduler.start()
|
||||
try:
|
||||
await asyncio.wait_for(replanned.wait(), timeout=5)
|
||||
(adoption,) = adoptions
|
||||
assert (await adoption).status_code == 200
|
||||
finally:
|
||||
await scheduler.stop()
|
||||
# The sweep ran for the UTC plan with UTC still stored, never after
|
||||
# New York had been adopted; the next plan is New York midnight.
|
||||
assert swept_under == [""]
|
||||
assert delays == [
|
||||
pytest.approx(_UTC_MIDNIGHT_DELAY),
|
||||
pytest.approx(_NEW_YORK_MIDNIGHT_DELAY),
|
||||
]
|
||||
|
||||
|
||||
# --- the wait's child tasks (TZ-004) ------------------------------------------
|
||||
|
||||
|
||||
async def test_failed_sleep_is_retried_not_swept(
|
||||
temp_db_path: str, monkeypatch
|
||||
) -> None:
|
||||
"""A sleep that raises backs off and re-plans; nothing is swept."""
|
||||
database = _core_db.NestQuestDatabase(_executor)
|
||||
await database.open(temp_db_path)
|
||||
try:
|
||||
await _core_migrations.apply_migrations(database)
|
||||
sweeps: list[datetime.date] = []
|
||||
|
||||
async def sweep_stub(_database, *, today):
|
||||
sweeps.append(today)
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
scheduler_module.core_sweep, "run_missed_sweep", sweep_stub
|
||||
)
|
||||
delays: list[float] = []
|
||||
replanned = asyncio.Event()
|
||||
|
||||
async def sleep_stub(seconds: float) -> None:
|
||||
delays.append(seconds)
|
||||
if len(delays) == 1:
|
||||
raise RuntimeError("timer failed")
|
||||
if len(delays) == 2:
|
||||
return # the retry backoff
|
||||
replanned.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
scheduler = MissedSweepScheduler(
|
||||
database, clock=lambda: _utc(13, 0), sleep=sleep_stub
|
||||
)
|
||||
scheduler.start()
|
||||
try:
|
||||
await asyncio.wait_for(replanned.wait(), timeout=5)
|
||||
finally:
|
||||
await scheduler.stop()
|
||||
assert sweeps == []
|
||||
assert delays == [
|
||||
pytest.approx(_UTC_MIDNIGHT_DELAY),
|
||||
scheduler_module._RETRY_BACKOFF_SECONDS,
|
||||
pytest.approx(_UTC_MIDNIGHT_DELAY),
|
||||
]
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
|
||||
async def test_stop_waits_for_the_sleep_to_finish_cancelling(
|
||||
temp_db_path: str,
|
||||
) -> None:
|
||||
database = _core_db.NestQuestDatabase(_executor)
|
||||
await database.open(temp_db_path)
|
||||
try:
|
||||
await _core_migrations.apply_migrations(database)
|
||||
sleeping = asyncio.Event()
|
||||
sleepers: list[asyncio.Task] = []
|
||||
cleaned_up: list[bool] = []
|
||||
|
||||
async def sleep_stub(_seconds: float) -> None:
|
||||
sleepers.append(asyncio.current_task())
|
||||
sleeping.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
# Cancellation cleanup that takes a loop turn.
|
||||
await asyncio.sleep(0)
|
||||
cleaned_up.append(True)
|
||||
|
||||
scheduler = MissedSweepScheduler(
|
||||
database, clock=lambda: _utc(13, 0), sleep=sleep_stub
|
||||
)
|
||||
scheduler.start()
|
||||
try:
|
||||
await asyncio.wait_for(sleeping.wait(), timeout=5)
|
||||
finally:
|
||||
await scheduler.stop()
|
||||
(sleeper,) = sleepers
|
||||
assert sleeper.done()
|
||||
assert cleaned_up == [True]
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
@@ -686,8 +686,6 @@ async def test_coordinator_configured_token_builds_real_client(
|
||||
hass, entry, session_factory=_session_factory
|
||||
)
|
||||
assert isinstance(real_client, NestQuestApiClient)
|
||||
# Home Assistant's zone is reported to the API (task 6351b36d).
|
||||
assert real_client._household_timezone == hass.config.time_zone
|
||||
|
||||
set_coordinator_client(entry, real_client)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
|
||||
@@ -996,9 +996,8 @@ def test_definition_set_active_missing_returns_zero(tmp_path) -> None:
|
||||
assert _with_db(tmp_path, "definition-set-active-missing.db")(_body) == 0
|
||||
|
||||
|
||||
def test_definition_only_delete_method_is_history_guarded(tmp_path) -> None:
|
||||
"""Guardrail: the ONLY definition delete path is the history-guarded
|
||||
one (owner decision 2026-09-26); there is no unconditional delete."""
|
||||
def test_definition_no_delete_method_exists(tmp_path) -> None:
|
||||
"""Guardrail: definitions are deactivated, never hard-deleted."""
|
||||
async def _body(database, rules, definitions, children, child):
|
||||
import inspect
|
||||
|
||||
@@ -1009,9 +1008,7 @@ def test_definition_only_delete_method_is_history_guarded(tmp_path) -> None:
|
||||
)
|
||||
}
|
||||
assert "delete" not in methods
|
||||
assert {
|
||||
name for name in methods if name.startswith("delete")
|
||||
} == {"delete_if_no_history"}
|
||||
assert not any(name.startswith("delete") for name in methods)
|
||||
return methods
|
||||
|
||||
_with_db(tmp_path, "definition-no-delete.db")(_body)
|
||||
|
||||
@@ -302,15 +302,14 @@ def test_quest_log_entrances_use_the_design_timing_and_easing() -> None:
|
||||
".quest.tappable:active",
|
||||
"button.complete:active",
|
||||
"button.confirm-button:active",
|
||||
"button.return:active",
|
||||
):
|
||||
start = style.index(selector)
|
||||
block = style[start : style.index("}", start)]
|
||||
assert "transform: scale(0.98);" in block, selector
|
||||
assert (
|
||||
style.count("transition: transform var(--nq-dur-micro) var(--nq-ease-out);")
|
||||
== 4
|
||||
) # quest card, Complete button, confirm buttons, header return control
|
||||
== 3
|
||||
) # quest card, Complete button, confirm buttons
|
||||
board_style = _style_literal(_read(PARTY_BOARD), STYLE_CONSTANTS[PARTY_BOARD])
|
||||
start = board_style.index("button.plate:active")
|
||||
block = board_style[start : board_style.index("}", start)]
|
||||
@@ -830,7 +829,6 @@ def _render_quest_log(
|
||||
idle_ms: int | None = None,
|
||||
probe_ms: int | None = None,
|
||||
tap_complete: int | None = None,
|
||||
tap_return: bool = False,
|
||||
) -> dict:
|
||||
"""Render the built bundle's quest log and report its location.
|
||||
|
||||
@@ -856,8 +854,6 @@ def _render_quest_log(
|
||||
spec["probe_ms"] = probe_ms
|
||||
if tap_complete is not None:
|
||||
spec["tap_complete"] = tap_complete
|
||||
if tap_return:
|
||||
spec["tap_return"] = True
|
||||
completed = subprocess.run(
|
||||
["node", str(QUEST_LOG_HARNESS)],
|
||||
input=json.dumps(spec),
|
||||
@@ -927,40 +923,6 @@ def test_quest_log_idle_return_navigates_to_the_board() -> None:
|
||||
assert result["location"] == "/nestquest"
|
||||
|
||||
|
||||
def test_quest_log_return_control_navigates_to_the_board() -> None:
|
||||
"""PANEL-SPEC §3: the Quest Log header carries an explicit return
|
||||
control labelled for a child. Tapping it takes the same path as the
|
||||
idle return — the strategy-computed board_path (the dashboard root) —
|
||||
without waiting out the idle window."""
|
||||
generated = _generate_dashboard(
|
||||
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
|
||||
)
|
||||
result = _render_quest_log(
|
||||
generated["views"][1]["cards"][0],
|
||||
_three_child_states(),
|
||||
url="http://homeassistant.local/nestquest/ada",
|
||||
tap_return=True,
|
||||
)
|
||||
assert result["headline"] == "Ada's Quest Log"
|
||||
assert result["returned"] == {"rendered": True, "label": "The Party"}
|
||||
assert result["location"] == "/nestquest"
|
||||
|
||||
|
||||
def test_quest_log_return_control_follows_the_panel_hard_rules() -> None:
|
||||
"""The return control is a 72px button with :active feedback only,
|
||||
lives in the header (never the dock), and reuses the idle return's
|
||||
_returnToBoard navigation rather than a second mechanism."""
|
||||
log = _read(QUEST_LOG)
|
||||
style = _style_literal(log, STYLE_CONSTANTS[QUEST_LOG])
|
||||
rules = {selector.strip(): body for selector, body in _css_rules(style)}
|
||||
assert "height: var(--nq-p-button-height);" in rules["button.return"]
|
||||
assert "transform: scale(0.98);" in rules["button.return:active"]
|
||||
header = log[log.index("private _renderHeader") : log.index("private _renderColumn")]
|
||||
assert 'class="return"' in header
|
||||
assert "@click=${() => this._returnToBoard()}" in header
|
||||
assert log.count("this._returnToBoard()") == 4
|
||||
|
||||
|
||||
def test_quest_complete_screen_returns_to_the_board_after_the_countdown() -> None:
|
||||
"""The 1c screen renders with its countdown line and auto-returns to
|
||||
the strategy-computed board path when it reaches zero. The design
|
||||
@@ -1073,12 +1035,9 @@ def test_quest_log_crest_keeps_its_shield_classes() -> None:
|
||||
)
|
||||
header = result["html"][result["html"].index('<header class="header">') :]
|
||||
crest = re.match(
|
||||
r'<header class="header">\s*(?:<!--[^>]*-->\s*)*'
|
||||
r'(?:<button class="return"[^>]*>.*?</button>\s*(?:<!--[^>]*-->\s*)*)?'
|
||||
r'<span ([^>]*)>\s*'
|
||||
r'<header class="header">\s*(?:<!--[^>]*-->\s*)*<span ([^>]*)>\s*'
|
||||
r'<span class="crest-face">\s*<span class="initial">',
|
||||
header,
|
||||
re.DOTALL,
|
||||
)
|
||||
assert crest is not None, header[:600]
|
||||
assert f'class="{crest_class}"' in crest.group(1), crest.group(1)
|
||||
|
||||
@@ -22,10 +22,8 @@ from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.quest_definitions import (
|
||||
CreatedQuestDefinition,
|
||||
DeletedQuestDefinition,
|
||||
assign_child,
|
||||
create_quest_definition,
|
||||
delete_quest_definition,
|
||||
edit_quest_definition,
|
||||
list_active_definitions,
|
||||
list_definitions_firing_on,
|
||||
@@ -2128,188 +2126,3 @@ def test_wrappers_forward_horizon_days(tmp_path, mode) -> None:
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, f"wrapper-horizon-{mode}.db")(_body)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# delete_quest_definition: hybrid delete (owner decision 2026-09-26)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _count(database, sql, definition_id) -> int:
|
||||
row = await database.fetch_one(sql, (definition_id,))
|
||||
return row[0]
|
||||
|
||||
|
||||
def test_delete_without_history_hard_deletes_everything(tmp_path) -> None:
|
||||
"""No completion event on any instance: the definition, its
|
||||
instances, assignees, windows and unreferenced rule are all gone."""
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
created = await create_quest_definition(
|
||||
database,
|
||||
"Brush teeth",
|
||||
_daily_rule(),
|
||||
[child.id],
|
||||
["morning", "evening"],
|
||||
)
|
||||
definition_id = created.definition.id
|
||||
rule_id = created.definition.schedule_rule_id
|
||||
instances_sql = (
|
||||
"SELECT COUNT(*) FROM quest_instances WHERE definition_id = ?"
|
||||
)
|
||||
# Create materialized future instances, so the delete has
|
||||
# instance rows to remove (not just an empty table).
|
||||
assert await _count(database, instances_sql, definition_id) > 0
|
||||
|
||||
result = await delete_quest_definition(database, definition_id)
|
||||
|
||||
assert result == DeletedQuestDefinition(
|
||||
definition_id=definition_id,
|
||||
deleted=True,
|
||||
retired=False,
|
||||
definition=None,
|
||||
)
|
||||
assert await definitions.get(definition_id) is None
|
||||
assert await rules.get(rule_id) is None
|
||||
assert await _count(database, instances_sql, definition_id) == 0
|
||||
for table in (
|
||||
"quest_definition_assignees",
|
||||
"quest_definition_windows",
|
||||
):
|
||||
assert await _count(
|
||||
database,
|
||||
f"SELECT COUNT(*) FROM {table} WHERE definition_id = ?",
|
||||
definition_id,
|
||||
) == 0
|
||||
# The child itself is untouched.
|
||||
assert (await children.get(child.id)) is not None
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-no-history.db")(_body)
|
||||
|
||||
|
||||
def test_delete_without_history_keeps_a_shared_rule(tmp_path) -> None:
|
||||
"""The rule is deleted only when no other definition references it."""
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
rule = await rules.create("daily", "2026-09-14")
|
||||
first = await definitions.create(
|
||||
"First", rule.id, NOW, assignee_child_ids=[child.id]
|
||||
)
|
||||
second = await definitions.create(
|
||||
"Second", rule.id, NOW, assignee_child_ids=[child.id]
|
||||
)
|
||||
|
||||
result = await delete_quest_definition(database, first.id)
|
||||
|
||||
assert result.deleted is True
|
||||
assert await definitions.get(first.id) is None
|
||||
assert await definitions.get(second.id) is not None
|
||||
assert await rules.get(rule.id) is not None
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-shared-rule.db")(_body)
|
||||
|
||||
|
||||
def test_delete_with_history_retires_and_preserves_everything(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
"""A completion event on ANY instance: the definition is retired
|
||||
(deactivated) and its row, rule, assignees, windows and completion
|
||||
history all remain. The completed instance survives; only future
|
||||
UNCOMPLETED instances are cleared by the deactivation's regeneration."""
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
created = await create_quest_definition(
|
||||
database, "Brush teeth", _daily_rule(), [child.id], ["morning"]
|
||||
)
|
||||
definition_id = created.definition.id
|
||||
rule_id = created.definition.schedule_rule_id
|
||||
instances = QuestInstancesDao(database)
|
||||
events = CompletionEventsDao(database)
|
||||
instance = await instances.upsert(
|
||||
definition_id, child.id, _today_iso(), NOW, window="morning"
|
||||
)
|
||||
event = await events.append(
|
||||
instance.id,
|
||||
child.id,
|
||||
"completed",
|
||||
"user",
|
||||
NOW,
|
||||
True,
|
||||
actor_user_id="admin-1",
|
||||
)
|
||||
|
||||
result = await delete_quest_definition(database, definition_id)
|
||||
|
||||
assert result.deleted is False
|
||||
assert result.retired is True
|
||||
assert result.definition_id == definition_id
|
||||
assert isinstance(result.definition, CreatedQuestDefinition)
|
||||
assert result.definition.definition.is_active is False
|
||||
stored = await definitions.get(definition_id)
|
||||
assert stored is not None
|
||||
assert stored.is_active is False
|
||||
assert await rules.get(rule_id) is not None
|
||||
assert [c.id for c in await definitions.list_assignees(
|
||||
definition_id
|
||||
)] == [child.id]
|
||||
assert [w.window for w in await definitions.list_windows(
|
||||
definition_id
|
||||
)] == ["morning"]
|
||||
assert await instances.get_by_id(instance.id) == instance
|
||||
assert await events.list_by_instance(instance.id) == [event]
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-with-history.db")(_body)
|
||||
|
||||
|
||||
def test_delete_with_uncompleted_history_still_retires(tmp_path) -> None:
|
||||
"""ANY completion event counts as history — even when the latest
|
||||
event is an un-completion, the definition is retired, not deleted."""
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
created = await create_quest_definition(
|
||||
database, "Brush teeth", _daily_rule(), [child.id], ["morning"]
|
||||
)
|
||||
definition_id = created.definition.id
|
||||
instances = QuestInstancesDao(database)
|
||||
events = CompletionEventsDao(database)
|
||||
instance = await instances.upsert(
|
||||
definition_id, child.id, _today_iso(), NOW, window="morning"
|
||||
)
|
||||
await events.append(
|
||||
instance.id, child.id, "completed", "user", NOW, True,
|
||||
actor_user_id="admin-1",
|
||||
)
|
||||
await events.append(
|
||||
instance.id, child.id, "uncompleted", "user", NOW, None,
|
||||
actor_user_id="admin-1",
|
||||
)
|
||||
|
||||
result = await delete_quest_definition(database, definition_id)
|
||||
|
||||
assert result.retired is True
|
||||
assert await instances.get_by_id(instance.id) == instance
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-uncompleted-history.db")(_body)
|
||||
|
||||
|
||||
def test_delete_nonexistent_definition_names_field(tmp_path) -> None:
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
with pytest.raises(ValueError, match=r"^definition_id:"):
|
||||
await delete_quest_definition(database, 999)
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-missing.db")(_body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [True, 1.0, "1", None])
|
||||
def test_delete_rejects_non_int_definition_id(tmp_path, bad) -> None:
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
created = await create_quest_definition(
|
||||
database, "Brush teeth", _daily_rule(), [child.id], ["morning"]
|
||||
)
|
||||
with pytest.raises(ValueError, match="definition_id"):
|
||||
await delete_quest_definition(database, bad)
|
||||
assert await definitions.get(created.definition.id) is not None
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-bad-id.db")(_body)
|
||||
|
||||
@@ -351,24 +351,6 @@ async def test_stream_events_yields_documented_frames_and_sends_bearer() -> None
|
||||
assert call["json"] is None
|
||||
|
||||
|
||||
async def test_stream_events_reports_household_timezone() -> None:
|
||||
"""The SSE GET carries Home Assistant's zone beside the Bearer token
|
||||
(task 6351b36d), like the snapshot and completion requests."""
|
||||
frame = _frame_text(*DOCUMENTED_FRAMES[0])
|
||||
transport = _StreamTransport(_StreamingResponse(200, [frame]))
|
||||
client = NestQuestApiClient(
|
||||
BASE_URL, TOKEN, transport, household_timezone="America/New_York"
|
||||
)
|
||||
|
||||
frames = [frame async for frame in client.stream_events()]
|
||||
|
||||
assert frames == [DOCUMENTED_FRAMES[0]]
|
||||
assert transport.calls[0]["headers"] == {
|
||||
"Authorization": f"Bearer {TOKEN}",
|
||||
"X-NestQuest-Timezone": "America/New_York",
|
||||
}
|
||||
|
||||
|
||||
async def test_stream_events_buffers_lines_across_chunks_and_joins_data() -> None:
|
||||
"""Chunk-split lines parse, and multi-line data joins per SSE rules."""
|
||||
first_type, first_payload = DOCUMENTED_FRAMES[0]
|
||||
|
||||
Reference in New Issue
Block a user