diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md index 3a88b77a..04ad07c0 100644 --- a/addon-edge/CHANGELOG.md +++ b/addon-edge/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## 0.0.0-edge.37 + +- Retry a draft conflict review without losing the local edit or saving over a stale revision. + +## 0.0.0-edge.36 + +- Keep the draft editor locked while opening a saved rule or checking for an interrupted save. + +## 0.0.0-edge.35 + +- Show the latest saved condition when reviewing a conflicting draft revision. + +## 0.0.0-edge.34 + +- Match the automation draft API contract to the exact supported revision range. + +## 0.0.0-edge.33 + +- Save and reopen inactive manual automation drafts in Household settings. +- Preserve immutable revisions and recover a save after a lost response. +- Migrate existing data to SQLite schema 32. Keep the compatible backup for rollback. + ## 0.0.0-edge.32 - Show the exact number of items still to buy and the first 25 shared-list items on Overview. diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md index 52159b81..e8c22adb 100644 --- a/addon-edge/DOCS.md +++ b/addon-edge/DOCS.md @@ -1,10 +1,15 @@ # Installation and operation -Edge 0.0.0-edge.31 packages the immutable runtime declared in +Edge 0.0.0-edge.37 packages the immutable runtime declared in [artifact.json](artifact.json). Overview shows the signed-in member's completed tasks and posted earned points for the current Family week. Open Family for the full report. In Household settings, authorized members can preview a manual task proposal and see whether an optional stock condition matches. Preview leaves tasks and stock unchanged. +Save the rule as an inactive draft to reopen its exact definition or append a revision. +Use the original save receipt after an interrupted response. The editor +waits while Domus checks for a pending save or opens a draft. +Review the latest saved condition before keeping your edits after a conflict. +If the latest revision fails to load, retry the review from the same draft. If the product list fails to load, the title-only preview remains available and the draft is preserved while reloading the list. People with task configuration permission can set optional base points when creating a task. @@ -13,8 +18,8 @@ the due-today and overdue task counts shown on Overview through a dedicated inst grant. Enable the [native deadline sensors](../docs/tasks/ha-deadline-sensors.md) using the optional `ha_deadline_digest` setting. The calendar uses its own `ha_calendar_digest` setting. Both share the private app port `8100` when enabled. -This preview retains SQLite schema 31. Edge.13 introduced that schema and is listed -in `breaking_versions`. Keep a compatible image and stopped-app backup before +Edge.33 introduces SQLite schema 32 and is listed in `breaking_versions`. +Keep a compatible image and stopped-app backup before upgrading from an earlier schema. A binary that expects the earlier schema requires its compatible data backup. A separate Supervisor repository source creates an independent app and data diff --git a/addon-edge/Dockerfile b/addon-edge/Dockerfile index 0b042676..d0981218 100644 --- a/addon-edge/Dockerfile +++ b/addon-edge/Dockerfile @@ -1,8 +1,8 @@ # The Supervisor builds this folder. Fetch only the reviewed immutable runtime and UI. FROM ghcr.io/astral-sh/uv:0.11.29@sha256:eb2843a1e56fd9e30c7276ce1a52cba86e64c7b385f5e3279a0e08e02dd058fc AS uv FROM python:3.14.6-slim-trixie@sha256:7bec7ddcddeff7975d6ba9b4be7dd6f6b2f55e7491539145e2978f7f97ce9144 AS source -ARG DOMUS_SOURCE_COMMIT=43bace9576b9468f789fe9975a3dd5fe427d83ae -ARG DOMUS_SOURCE_SHA256=7ad1c19b3452f2be9f8385be113c7d5a1f7f1a74ee094c11ad99c2513732d0d4 +ARG DOMUS_SOURCE_COMMIT=63890ace59d55ec76e0b9c3c7c832598eeeab7a1 +ARG DOMUS_SOURCE_SHA256=683f22b93d1e26d6145f51d005d8cfca1324f7d27425786050d1f54fc4cb9b9b ADD https://codeload.github.com/vypdev/domus/tar.gz/${DOMUS_SOURCE_COMMIT} /tmp/source.tar.gz RUN printf '%s /tmp/source.tar.gz\n' "$DOMUS_SOURCE_SHA256" | sha256sum --check - \ && mkdir /app \ @@ -24,9 +24,9 @@ RUN uv sync --frozen --no-dev --package domus-server --no-editable RUN .venv/bin/python -c "from pathlib import Path; import domus; from domus.entrypoints.ui_bundle import load_bundle; assert load_bundle(Path(domus.__file__).parent / 'ui') is not None" FROM python:3.14.6-slim-trixie@sha256:7bec7ddcddeff7975d6ba9b4be7dd6f6b2f55e7491539145e2978f7f97ce9144 -ARG BUILD_VERSION=0.0.0-edge.32 +ARG BUILD_VERSION=0.0.0-edge.37 ARG BUILD_ARCH -ARG DOMUS_SOURCE_COMMIT=43bace9576b9468f789fe9975a3dd5fe427d83ae +ARG DOMUS_SOURCE_COMMIT=63890ace59d55ec76e0b9c3c7c832598eeeab7a1 LABEL io.hass.type="app" \ io.hass.version="${BUILD_VERSION}" \ io.hass.arch="${BUILD_ARCH}" \ diff --git a/addon-edge/README.md b/addon-edge/README.md index da0b4a68..c7e0594b 100644 --- a/addon-edge/README.md +++ b/addon-edge/README.md @@ -7,10 +7,10 @@ Edge.32 shows the outstanding shopping count and the first 25 rows in Overview. Select a row to open the matching item in the shared list in Inventory. In Household settings, preview a manual task proposal and optionally check available -stock against a product's minimum. Edge.31 keeps the preview available when the -product list fails to load and preserves the draft while retrying the list. +stock against a product's minimum. Edge.33 saves that rule as an inactive draft, +retains immutable revisions and lets you check the original save after a lost response. -This candidate uses SQLite schema 31. Keep a +This candidate uses SQLite schema 32. Keep a compatible image and cold data backup before upgrading a previous preview. See [installation and operation](DOCS.md) for the source pin and rollback instructions. diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json index ba6de089..6a6aea40 100644 --- a/addon-edge/artifact.json +++ b/addon-edge/artifact.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, - "version": "0.0.0-edge.32", - "sourceCommit": "43bace9576b9468f789fe9975a3dd5fe427d83ae", - "sourceArchiveSHA256": "7ad1c19b3452f2be9f8385be113c7d5a1f7f1a74ee094c11ad99c2513732d0d4", - "storageSchema": 31, - "wheelSHA256": "7075e3aa3f8c085615a256a1eea73bdc55831d08590eb7c7b6904a3109bfb903", + "version": "0.0.0-edge.37", + "sourceCommit": "63890ace59d55ec76e0b9c3c7c832598eeeab7a1", + "sourceArchiveSHA256": "683f22b93d1e26d6145f51d005d8cfca1324f7d27425786050d1f54fc4cb9b9b", + "storageSchema": 32, + "wheelSHA256": "6e4827b460380674a1b8cf72225ad7126679c5e61bfd8907e0f61873d548a4a2", "pythonFiles": { "domus/__init__.py": "7182c88b92234b4328f94497f4e70222d4390d8093e4b62893dfa78ac5530ac6", "domus/application/__init__.py": "1e8c0c87bf2a8ca947112543070583c0cc55d9d40b56eab0d86ed59a4ec1e82c", @@ -13,10 +13,11 @@ "domus/application/authentication.py": "3ab940f76455365c4d40d40645c5f9ba5a65754e382665a0266057baaae04bf8", "domus/application/authentication_values.py": "e83491791e6d323e1fb12aaafb11fc39d2f89a12d10c9ae415c055a1e33aa314", "domus/application/authorization.py": "bb301cc7c1e37f26f176f6bb132a8d04fa166b014a5f06f00bccaea1c463e2fe", - "domus/application/automation_preview.py": "f78e2a6bfa04df16380a5111094e93cf5979a20e8cf01dbf6f408bea3ab711df", + "domus/application/automation_drafts.py": "441230c946bba0c8e56545cd971af18c72003c32fbcafb1145d78b58f45da2b4", + "domus/application/automation_preview.py": "5f44b1c2ebd3d8ade4b1f2110c8babd98c5ca4b83928a0a4e71d0e74b170dab2", "domus/application/calendar_commands.py": "bec257c2b7ba07166e69b1dd7ed0016541cd30ab6cb26f18f4fc4dce11017001", "domus/application/calendar_queries.py": "37b9b8f1d43d9a21cc73c2533a908570783116ff7e5b6db47d6591dfbe2393d9", - "domus/application/commands.py": "6d1d735b4a725086b0d37f6895dd4201f3944e132763f6825142e038f7635354", + "domus/application/commands.py": "b41069d5db23e594f135bc742f2479e25fce537dc0966052546d95409dc7bc05", "domus/application/fair_recurrence.py": "ce4a9bbe48ed4762e0456669c21e1b6d573b3b9b7b53912a960bab797f7ad610", "domus/application/family_ports.py": "f2d089eb617b311b305f1ff696437bc5075b9092750b06a1189e4e51e93c5b16", "domus/application/family_queries.py": "2945045adada3c7bacba211a565ef2c19de3227a3dc6c0ab934dbea9fc93568f", @@ -47,7 +48,7 @@ "domus/application/points.py": "a2a660198151d5b65a62b57cb90b35a82a28f38a9a3b7b214b49d6cf6cf0294e", "domus/application/points_ports.py": "8392b778007d4c55bc55498d38c959d6dc1d4eeaa1dc501cf4d4928ce09f4ac0", "domus/application/policy_commands.py": "bc588b5b5feb72fd5cb57d7b4a10ef5a05ae48da5ec042fd569142ce50fedeb6", - "domus/application/ports.py": "9a7d2e39c07896faf6799789971174687a7290035ac6283af2f8b699a2ed45d0", + "domus/application/ports.py": "efe45af508d744d4d45e7a3a6c8ee5e0ae5a49272096fc74c5e5e1155f130693", "domus/application/recovery_commands.py": "2b8c198cde97f0213ec1612ea32bce5e00637aab99862fe08b59418d3c64af49", "domus/application/recurrence_commands.py": "4d91c498ced40c335b8a081719a33dde97ab081a050ab352c3f1fac83e6f1447", "domus/application/recurrence_ports.py": "651d86417a20810c198aba0cd48129de6396db185278c01836366575027d6c24", @@ -98,15 +99,15 @@ "domus/composition/recurrence.py": "62adda116cec8667e9142b03f422a138818575cf5814a79e219a65999dbed1e6", "domus/composition/restore.py": "fe4f5040a99db1404938e402eefa54fc93139055a5bc92abdfb7bf35d0c87297", "domus/composition/server.py": "f857338e254477cd7b1d452fc85434e75fd7a25781ed237bb0d5658ac13ad719", - "domus/composition/tasks.py": "8d15d3cb5c1ed53ddfb48d28efb440fa6698d86b1acc5a7e36bc0fc823dfe40b", + "domus/composition/tasks.py": "cc34f06ce5fa0c5da426b73b79f44d5d93cd25c0dc0c97edd7287a3e2e92da42", "domus/domain/__init__.py": "0aac8a2ba41471d7a174ef7baca6073c95009a9db96df3e032392aa4f80bd079", "domus/domain/activation.py": "fcb2e47e939127d5e254e2136fb7f1459b40fa8c8561100579fced49666ad0fe", - "domus/domain/automation.py": "17a7220c2d70f677c758623702f783df3869e4d664e948addae82e916ae257bd", + "domus/domain/automation.py": "b2a91bdde8c027f746e20ed7b4b2a5287dfc4e8de80a26151edd3a3a2d01ee10", "domus/domain/calendar_values.py": "5a0f3821391f10fbab05c00f775133683203e7f4b7c5861718bef1f98dedc219", "domus/domain/errors.py": "0af3fadacc89835a4778b07ec45a1cf45539825c3756f44e8f78cebb37f354b6", "domus/domain/fold_policy.py": "fb938ee4cfae747b569a074d2be4e29ed3024012e09ef7645909a7f86122b2c4", "domus/domain/generations.py": "bd8d665c7b6e832f881784c07475d2b8911c08d0894cf8e125681a9f27e1ba97", - "domus/domain/identity.py": "a35980712e1717f5f225165080916d8cfefa8c5d1b01f8b08a78089ff2a29b91", + "domus/domain/identity.py": "3f30a61e1de77a7457f131e8e8371b86ac2ccd3e589060429d091624ee1e75ed", "domus/domain/inventory.py": "d2e559cfc75fbe2557b0112cd7e2b75b05ac8b8b54dff8bbea7131d7d0b98c0c", "domus/domain/member_profiles.py": "2790ca55a7b37a390d006165a44520085e1ff513783b9cf1a7b681435b8ae4d2", "domus/domain/member_sources.py": "b5e9d19d501d3d5dd5caf5b4ce945d4c3ff71b1967e92bd8933f26661a416c01", @@ -142,7 +143,7 @@ "domus/entrypoints/__init__.py": "d46875cbfef7220c7244bf1b89112ece8122ecb0d66cd908f08f098f0f3c419f", "domus/entrypoints/administration_dto.py": "aefac6648dd8fefae9d2366abed1c9d595c24a356f7caf945b742043b2c39777", "domus/entrypoints/administration_http.py": "9ab62ee9759a4b31c5e994354562b48b947bd3428a5866dd9faeb0545ae37afe", - "domus/entrypoints/automation_http.py": "1537aa6954b7ac7881ab755d0d313b5c9ab22ad13f24e83e6d01c9f5c6a53056", + "domus/entrypoints/automation_http.py": "fbafe23af2ef0fa08b4a6b3fb52b22ce096749fb27dee9067a789cd11e50a927", "domus/entrypoints/bounded_http.py": "d8047746eddb7193f1aa9f16007958c79cc6ae7ac1c30ab93909883e3aa97b54", "domus/entrypoints/calendar_http.py": "5a7359ac2a876296a13bfe4bc63ac69bd36aec48e55c536a20470a789a6fef13", "domus/entrypoints/console_recovery.py": "854a3f8d7a2e74f301ac5bd4b54682e409e2669a3bb7e05546e479c113c09026", @@ -154,11 +155,11 @@ "domus/entrypoints/household_http.py": "37e948848115bfa8714c9cccc50058389114f2e665cad965a66964b0dcd098c8", "domus/entrypoints/http.py": "5fe33029b7ca04aae3f41fde9e8e7c517f48cff65d3cc3ac5dcb08b25a26a42b", "domus/entrypoints/http_contract.py": "613be310d4ff6a6c7e2a699c20f1c4a142d0b34073629884e58e973c4b040039", - "domus/entrypoints/http_errors.py": "20b1a88494154178e002a98a03549b9223ab2432d2ab7291c4cc70b9e18011d6", + "domus/entrypoints/http_errors.py": "ab0d521c5799abbcd554ada9f10e2b8fb7ea455bc2527711a7920c08e7ecc0ee", "domus/entrypoints/ingress_boundary.py": "1aa1d684b8625464b5d36d272f71d94b4cd32b84819ff8765a821c9a722f8f28", "domus/entrypoints/ingress_http.py": "f6557eb5481d132131f66ad7691e30c223c63a66a6f0ae5754c9fba3bc7f3626", "domus/entrypoints/inventory_http.py": "a58e114de6ff684f6d7d1a93f7f4cb316b8ffa60b0c662733df2c1fd70c2ab6e", - "domus/entrypoints/native_http.py": "471e3485bbafb4ea6fb928f476169b3976cb2cf32f4f3c879564633619a06602", + "domus/entrypoints/native_http.py": "68aa8a19bc303345dec44cb67dfc3855cc4d4be9cbe8143b6c63859b8f9f2def", "domus/entrypoints/openapi.py": "01a3fab9e5890ebcc1fb9c70bce9ced43d45b9190afd134db7dd45e0c5eb28f1", "domus/entrypoints/point_allocation_http.py": "7339c88c083206c0778885b55793c80af219b15af7004c5a51d34dbc28f4da5c", "domus/entrypoints/recurrence_dto.py": "094e6f64e1f963bfb053e830b214eed1189258e4f0eb8ff15ddba1f059649a1a", @@ -167,7 +168,7 @@ "domus/entrypoints/schedule_creation_http.py": "2a3c3ea682f978eb2767dc8808a218c312861f31079cc2c76dbc3847ddec3197", "domus/entrypoints/task_category_http.py": "e5443015f5e5cb2684eb6807e0a3bac5116703b5611508281afd7d1addee9672", "domus/entrypoints/task_dto.py": "10657d1df0180bf05e71d1f38ac3214d2cea34c8822f50ea25ab331b9c014049", - "domus/entrypoints/task_http.py": "6fa79282c6b75ed1e15ef465e5c830364eb377117893fcc4c4aa7d86fa3e27df", + "domus/entrypoints/task_http.py": "a8fbdaf9f45610f53e90bb094262375ac4954276095732245b58ae6a6b53139d", "domus/entrypoints/task_response.py": "d2f4c0795aee429fc318b32495601031c559fa38af1d7da63b4735f7e6eb5d13", "domus/entrypoints/ui_bundle.py": "beae3d4a7a57375ee195cca81efccdbc899d9db4286029d53eabaf30de6e14f7", "domus/entrypoints/ui_http.py": "b6c47baa742f3862173a93e4121dc9914fd972eb6287ffffb9ffccecbf2ebe4a", @@ -189,8 +190,9 @@ "domus/infrastructure/recurrence_worker.py": "23f76be62ed3ce5ddd557338d7e553d818001f1b3083e6e2f17b1e53723297b0", "domus/infrastructure/restore_source.py": "71917a2db52f5f6794504fd8caa7fd23b0732e8328760c728ea3f082acd2d203", "domus/infrastructure/session_access.py": "1e8bc8d44b60d985da7b44d7bb75fd21bb05f3a45ec38dc7031eff1a2709197d", - "domus/infrastructure/sqlite.py": "63c9db9c4bd114503e8a410472e3f745ed63502c15836e081875f23f34874851", + "domus/infrastructure/sqlite.py": "c75a669b02c98b24006c623f8810198c464e9df2bfe7feda3797a02ae094525d", "domus/infrastructure/sqlite_activation.py": "eabd490e86eab9dec76104d7d65c687133b8768a0ec8679e6cca97ba8616ded2", + "domus/infrastructure/sqlite_automation_drafts.py": "b1c2cc69c8be585668a261663a3519f7cfec790d752ee1c33d1329b113c6aac9", "domus/infrastructure/sqlite_calendar.py": "ad71b0ee9398131664662531b262da00ec6be312e068a97ef9c3a92172c7c80e", "domus/infrastructure/sqlite_calendar_preferences.py": "0e10804e9571a885518868b5bcbb69ad4eb1d006cafc33bf8b563e7067e69a4e", "domus/infrastructure/sqlite_history.py": "e7f8d4f2b79aed851a4056364f67d1c7806c52d011b46c597968bea86dd1d144", @@ -213,7 +215,7 @@ "domus/infrastructure/sqlite_restoration.py": "2f28207974082bdee48d72afdca08956e077b957377b1a2894b3eb6f4e6c224a", "domus/infrastructure/sqlite_rewards.py": "91a9d549198d523d5cd12beefa31cc2d947dc9fe55af245c8cb12017ff1cad5d", "domus/infrastructure/sqlite_shopping.py": "521e335ae6419f6cd1ee8286c3c6689932ae06330ef370a666581ec915b29688", - "domus/infrastructure/sqlite_snapshots.py": "70cf919b4e877f3c57bbd7152281a25762d8d6a0971fc090d5850e29c1ef4fe7", + "domus/infrastructure/sqlite_snapshots.py": "8cda49c61f19c95638e734fe8c8caee7912ecc6c5dd5aaf0b358b25709dd4f6b", "domus/infrastructure/sqlite_task_categories.py": "88adfacc0cbb4408ae902f0dceb4db8cf138073e98314a92fb85d881184e2e3d", "domus/infrastructure/sqlite_task_history.py": "d701c2ce24f8116976b524130dfd6406f0419144b9b68fed7341f18929f77aaf", "domus/infrastructure/sqlite_task_integrity.py": "982435ff6b6742506c98204292893744aff7b1d64645762eba131e7951e4d09c", @@ -229,9 +231,9 @@ "domus/infrastructure/task_materials.py": "d5d2934e36f290c7bf44b473392f014eab8749f1f3b3d26a3402079e65d2818f" }, "uiFiles": { - ".vite/manifest.json": "8157d0110594f50f64ef9eaf26ccde2b9762d2ec1d9a65788015cef05d51be1e", - "assets/index-CK0b1_ig.js": "62063f545d4cd9609d9cc807e8eea8cf89587e904803de7ec44ef6fcc7dc3543", + ".vite/manifest.json": "fafa17b6976362a2a437ce99e0b87d6afb465acf1ae0ae634d29bb24b050297e", + "assets/index-CJX6CQDY.js": "ceb1aa767bf164682dababadfb0f60d3217988372995b365cf38f3b26546f02f", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "005c1c8afae3913690ee9e83248d4d23cc5775b2f14d14718e544ba696037616" + "index.html": "9704bae64d589f1512faec3f59e963c8a6363804d57dece08f77832f96b95c87" } } diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml index 7d870464..55f438a5 100644 --- a/addon-edge/config.yaml +++ b/addon-edge/config.yaml @@ -1,5 +1,5 @@ name: Domus Edge -version: "0.0.0-edge.32" +version: "0.0.0-edge.37" slug: domus_edge description: Development preview of the local Domus household application url: https://github.com/vypdev/domus @@ -16,6 +16,7 @@ breaking_versions: - "0.0.0-edge.6" - "0.0.0-edge.10" - "0.0.0-edge.13" + - "0.0.0-edge.33" init: true timeout: 30 backup: cold diff --git a/backend/src/domus/application/automation_drafts.py b/backend/src/domus/application/automation_drafts.py new file mode 100644 index 00000000..976b7351 --- /dev/null +++ b/backend/src/domus/application/automation_drafts.py @@ -0,0 +1,183 @@ +"""Save inactive rules and recover the exact original, under current local authority.""" + +from collections.abc import Callable +from dataclasses import dataclass +from typing import Literal + +from domus.application.automation_preview import owned_product, require_configuration +from domus.application.commands import AtomicCommands, Change +from domus.application.fixed_materialization import MaintenanceScope +from domus.application.identity_ports import CurrentHuman +from domus.application.ports import Clock, Identifiers, Transactions, UnitOfWork +from domus.application.task_authorization import TaskAccess +from domus.application.task_ports import TaskCursors +from domus.domain.automation import AutomationDraft, AutomationRule +from domus.domain.errors import Forbidden, InvalidInput, NotFound +from domus.domain.identity import ( + HumanIdentity, + Member, + Permission, + effective_role, + validate_revision, +) +from domus.domain.storage import CommandKey, JsonDocument, Receipt, validate_identifier + +SAVE_DRAFT = "automation.draft.save" + + +@dataclass(frozen=True, slots=True) +class SaveDraft: + rule_id: str | None + expected_revision: int + rule: AutomationRule + + def __post_init__(self) -> None: + if self.rule_id is None: + if type(self.expected_revision) is not int or self.expected_revision != 0: + raise InvalidInput("invalid_revision") + else: + validate_identifier(self.rule_id) + validate_revision(self.expected_revision) + + def document(self) -> JsonDocument: + return JsonDocument.from_value( + { + **self.rule.document().decode(), + "rule_id": self.rule_id, + "expected_revision": self.expected_revision, + } + ) + + +@dataclass(frozen=True, slots=True) +class DraftSummary: + rule_id: str + revision: str + title: str + state: Literal["draft"] = "draft" + enabled: Literal[False] = False + + +@dataclass(frozen=True, slots=True) +class DraftPage: + drafts: tuple[DraftSummary, ...] + next_cursor: str | None + + +@dataclass(frozen=True, slots=True) +class _DraftAuthority: + human: HumanIdentity + scope: MaintenanceScope + command: CommandKey + + def owner(self, unit: UnitOfWork) -> Member: + home = self.scope.require(unit).household_id + member = require_configuration(unit, home, self.human) + TaskAccess(self.human).require(unit, home, Permission.TASKS_CREATE) + return member + + def require(self, command: CommandKey, unit: UnitOfWork) -> None: + if command != self.command: + raise Forbidden("permission_denied") + owner = self.owner(unit) + original = unit.receipts.get(command) + if original is not None and original.result.decode().get("member_id") != owner.member_id: + raise Forbidden("permission_denied") + + +@dataclass(frozen=True, slots=True) +class AutomationDrafts: + transactions: Transactions + scope: MaintenanceScope + actor: CurrentHuman + read_actor: Callable[[], HumanIdentity] + clock: Clock + identifiers: Identifiers + cursors: TaskCursors + + def list(self, *, limit: int, cursor: str | None) -> DraftPage: + if type(limit) is not int or not 1 <= limit <= 100: + raise InvalidInput("invalid_page_size") + human = self.read_actor() + with self.transactions.read() as unit: + home = self.scope.require(unit).household_id + member = require_configuration(unit, home, human) + policy = unit.policies.get(home) + assert policy is not None + role = effective_role(human, member, policy) + assert role is not None + binding = JsonDocument.from_value( + { + "query": "automation-drafts-v1", + "installation": self.scope.installation.instance_id, + "channel": self.scope.installation.channel, + "household": home, + "member": member.member_id, + "membership_revision": member.revision, + "policy_revision": policy.revision, + "role": role.value, + "limit": limit, + } + ) + after = "" if cursor is None else self.cursors.decode(binding, cursor) + drafts = unit.automation_drafts.page(home, after, limit + 1) + next_cursor = ( + self.cursors.encode(binding, drafts[limit - 1].rule_id) + if len(drafts) > limit + else None + ) + return DraftPage( + tuple( + DraftSummary(item.rule_id, str(item.revision), item.rule.task.title) + for item in drafts[:limit] + ), + next_cursor, + ) + + def reopen(self, rule_id: str) -> AutomationDraft: + human = self.read_actor() + with self.transactions.read() as unit: + home = self.scope.require(unit).household_id + require_configuration(unit, home, human) + validate_identifier(rule_id) + draft = unit.automation_drafts.latest(home, rule_id) + if draft is None: + raise NotFound("automation_draft_missing") + return draft + + def _authority(self, human: HumanIdentity, key: str) -> _DraftAuthority: + command = CommandKey(self.scope.household_id, human.ha_user_id, SAVE_DRAFT, key) + return _DraftAuthority(human, self.scope, command) + + def save(self, key: str, request: SaveDraft) -> Receipt: + authority = self._authority(self.actor.current(), key) + home = authority.command.household_id + commands = AtomicCommands(self.transactions, authority, self.clock, self.identifiers) + + def apply(unit: UnitOfWork) -> Change: + rule_id = self.identifiers.new() if request.rule_id is None else request.rule_id + for product_id in request.rule.stock_products(): + owned_product(unit, home, product_id) + draft = AutomationDraft(rule_id, request.expected_revision + 1, request.rule) + unit.automation_drafts.append(home, draft) + fact = JsonDocument.from_value({"rule_id": rule_id, "revision": str(draft.revision)}) + result = JsonDocument.from_value( + { + **fact.decode(), + "member_id": authority.owner(unit).member_id, + "state": "draft", + "enabled": False, + } + ) + return Change(result, fact, fact, requires_delivery=False) + + return commands.execute(authority.command, request.document(), apply) + + def original(self, key: str) -> Receipt: + authority = self._authority(self.read_actor(), key) + with self.transactions.read() as unit: + authority.require(authority.command, unit) + receipt = unit.receipts.get(authority.command) + if receipt is None: + raise NotFound("operation_missing") + return receipt diff --git a/backend/src/domus/application/automation_preview.py b/backend/src/domus/application/automation_preview.py index 5b52e81e..6727073b 100644 --- a/backend/src/domus/application/automation_preview.py +++ b/backend/src/domus/application/automation_preview.py @@ -9,7 +9,21 @@ from domus.application.task_authorization import TaskAccess from domus.domain.automation import AutomationRule, AutomationSimulation, simulate from domus.domain.errors import NotFound -from domus.domain.identity import HumanIdentity, Permission +from domus.domain.identity import HumanIdentity, Member, Permission +from domus.domain.inventory import CatalogProduct + + +def require_configuration(unit: UnitOfWork, home: str, human: HumanIdentity) -> Member: + access = HouseholdAccess(human) + access.require(unit, home, Permission.HOUSEHOLD_READ) + return access.require(unit, home, Permission.AUTOMATIONS_CONFIGURE) + + +def owned_product(unit: UnitOfWork, home: str, product_id: str) -> CatalogProduct: + product = unit.inventory.product(home, product_id) + if product is None: + raise NotFound("inventory_product_missing") + return product @dataclass(frozen=True, slots=True) @@ -25,9 +39,7 @@ class AutomationPreview: def _require(self, unit: UnitOfWork) -> str: home = self.scope.require(unit).household_id - access = HouseholdAccess(self.human) - access.require(unit, home, Permission.HOUSEHOLD_READ) - access.require(unit, home, Permission.AUTOMATIONS_CONFIGURE) + require_configuration(unit, home, self.human) TaskAccess(self.human).require(unit, home, Permission.TASKS_CREATE) return home @@ -42,9 +54,7 @@ def preview(self, rule: AutomationRule) -> AutomationSimulation: @cache def below_minimum(product_id: str) -> bool: - product = stock.product(home, product_id) - if product is None: - raise NotFound("inventory_product_missing") + product = owned_product(unit, home, product_id) available = stock.balance(home, product.reference_id) - stock.reserved( home, product.reference_id ) diff --git a/backend/src/domus/application/commands.py b/backend/src/domus/application/commands.py index 6c564d91..6401d177 100644 --- a/backend/src/domus/application/commands.py +++ b/backend/src/domus/application/commands.py @@ -19,6 +19,7 @@ class Change: result: JsonDocument audit_detail: JsonDocument event_payload: JsonDocument + requires_delivery: bool = True @dataclass @@ -85,4 +86,8 @@ def in_unit( created_at, ) ) + if not change.requires_delivery: + # Restoration joins the receipt and audit to this envelope. Keep it + # out of the pending queue from the moment the transaction commits. + unit.outbox.acknowledge(operation_id) return receipt diff --git a/backend/src/domus/application/ports.py b/backend/src/domus/application/ports.py index 0a080fec..45ff2778 100644 --- a/backend/src/domus/application/ports.py +++ b/backend/src/domus/application/ports.py @@ -12,6 +12,7 @@ from domus.application.shopping_ports import ShoppingRecords from domus.application.task_material_ports import TaskMaterialRepository from domus.application.task_ports import TaskRepository +from domus.domain.automation import AutomationDraft from domus.domain.calendar_values import ( CalendarCandidate, CalendarFilters, @@ -100,7 +101,16 @@ def get(self, household_id: str, category_id: str) -> TaskCategory | None: ... def save(self, category: TaskCategory, expected_revision: int) -> None: ... +class AutomationDraftRecords(Protocol): + def latest(self, household_id: str, rule_id: str) -> AutomationDraft | None: ... + def page(self, household_id: str, after: str, limit: int) -> tuple[AutomationDraft, ...]: ... + def append(self, household_id: str, draft: AutomationDraft) -> None: ... + + class UnitOfWork(Protocol): + @property + def automation_drafts(self) -> AutomationDraftRecords: ... + @property def inventory(self) -> InventoryRecords: ... diff --git a/backend/src/domus/composition/tasks.py b/backend/src/domus/composition/tasks.py index a15c3f46..7e2bb128 100644 --- a/backend/src/domus/composition/tasks.py +++ b/backend/src/domus/composition/tasks.py @@ -3,6 +3,7 @@ from collections.abc import Callable from typing import Protocol +from domus.application.automation_drafts import AutomationDrafts from domus.application.automation_preview import AutomationPreview from domus.application.calendar_commands import CalendarCommands from domus.application.calendar_queries import CalendarQueries @@ -107,6 +108,7 @@ def family() -> FamilyQueries: catalog, lambda action, key: catalog.original(action, key, actor.read()), lambda: AutomationPreview(store, scope, actor.read()), + AutomationDrafts(store, scope, actor, actor.read, clock, identifiers, cursors), ) return context diff --git a/backend/src/domus/domain/automation.py b/backend/src/domus/domain/automation.py index 36cd2d81..74f3957e 100644 --- a/backend/src/domus/domain/automation.py +++ b/backend/src/domus/domain/automation.py @@ -5,7 +5,8 @@ from typing import Literal from domus.domain.errors import InvalidInput -from domus.domain.storage import validate_identifier +from domus.domain.identity import validate_revision +from domus.domain.storage import JsonDocument, JsonObject, JsonValue, validate_identifier from domus.domain.task_values import TaskContent AUTOMATION_RULE_VERSION = 1 @@ -50,6 +51,33 @@ def _children(condition: Condition) -> tuple[Condition, ...]: raise InvalidInput("invalid_automation_condition") +def _condition_value(condition: Condition) -> JsonObject: + if isinstance(condition, StockCondition): + return {"kind": "stock_below_minimum", "product_id": condition.product_id} + if isinstance(condition, NegatedCondition): + return {"kind": "not", "child": _condition_value(condition.child)} + return { + "kind": condition.kind, + "children": [_condition_value(child) for child in condition.children], + } + + +def _read_condition(value: JsonValue) -> Condition: + match value: + case {"kind": "stock_below_minimum", "product_id": str() as product, **extra} if not extra: + return StockCondition(product) + case {"kind": "not", "child": child, **extra} if not extra: + return NegatedCondition(_read_condition(child)) + case { + "kind": ("all" | "any") as kind, + "children": list() as children, + **extra, + } if not extra: + return ConditionGroup(kind, tuple(_read_condition(child) for child in children)) + case _: + raise InvalidInput("invalid_automation_condition") + + @dataclass(frozen=True, slots=True) class AutomationRule: version: int @@ -77,6 +105,59 @@ def __post_init__(self) -> None: raise InvalidInput("automation_rule_node_limit") pending.extend((child, depth + 1) for child in reversed(children)) + def document(self) -> JsonDocument: + """Persist exactly what the version-one task proposal can represent.""" + if self.task != TaskContent(self.task.title): + raise InvalidInput("invalid_automation_rule") + return JsonDocument.from_value( + { + "version": self.version, + "trigger": {"kind": self.trigger}, + "action": {"kind": "task.create", "title": self.task.title}, + "condition": None if self.condition is None else _condition_value(self.condition), + } + ) + + def stock_products(self) -> tuple[str, ...]: + pending = [] if self.condition is None else [self.condition] + products: dict[str, None] = {} + while pending: + condition = pending.pop() + if isinstance(condition, StockCondition): + products[condition.product_id] = None + pending.extend(reversed(_children(condition))) + return tuple(products) + + @classmethod + def from_document(cls, document: JsonDocument) -> AutomationRule: + match document.decode(): + case { + "version": int() as version, + "trigger": {"kind": "manual", **trigger_extra}, + "action": {"kind": "task.create", "title": str() as title, **action_extra}, + "condition": condition, + **extra, + } if not (extra or trigger_extra or action_extra): + return cls( + version, + "manual", + None if condition is None else _read_condition(condition), + TaskContent(title), + ) + case _: + raise InvalidInput("invalid_automation_rule") + + +@dataclass(frozen=True, slots=True) +class AutomationDraft: + rule_id: str + revision: int + rule: AutomationRule + + def __post_init__(self) -> None: + validate_identifier(self.rule_id) + validate_revision(self.revision) + @dataclass(frozen=True, slots=True) class ConditionDecision: diff --git a/backend/src/domus/domain/identity.py b/backend/src/domus/domain/identity.py index eff80f00..253ecca5 100644 --- a/backend/src/domus/domain/identity.py +++ b/backend/src/domus/domain/identity.py @@ -90,9 +90,11 @@ class Permission(StrEnum): Role.VIEWER: COMMON, } +MAX_REVISION = 2**63 - 1 + def validate_revision(revision: int) -> None: - if type(revision) is not int or not 1 <= revision <= 2**63 - 1: + if type(revision) is not int or not 1 <= revision <= MAX_REVISION: raise InvalidInput("invalid_revision") diff --git a/backend/src/domus/entrypoints/automation_http.py b/backend/src/domus/entrypoints/automation_http.py index 599aa75b..8d9f6569 100644 --- a/backend/src/domus/entrypoints/automation_http.py +++ b/backend/src/domus/entrypoints/automation_http.py @@ -7,6 +7,7 @@ from fastapi.params import Depends from pydantic import Field +from domus.application.automation_drafts import DraftPage, SaveDraft from domus.application.automation_preview import AutomationPreviewAccess from domus.domain.automation import ( AUTOMATION_RULE_VERSION, @@ -18,11 +19,18 @@ NegatedCondition, StockCondition, ) +from domus.domain.identity import MAX_REVISION from domus.domain.task_values import TaskContent -from domus.entrypoints.household_http import _EmptyQuery, _JSONRoute +from domus.entrypoints.household_http import ( + ReceiptResponse, + _EmptyQuery, + _JSONRoute, + _key, + _receipt, +) from domus.entrypoints.http_contract import StrictModel from domus.entrypoints.recurrence_http import _require_context -from domus.entrypoints.task_dto import Identifier +from domus.entrypoints.task_dto import Identifier, PageQuery from domus.entrypoints.task_http import TaskHTTPContext @@ -78,6 +86,37 @@ def domain(self) -> AutomationRule: ) +def _draft_revision_pattern() -> str: + # JSON Schema applies a numeric maximum to numbers only. For a decimal + # string, match shorter values and each prefix that first falls below the limit. + maximum = str(MAX_REVISION) + alternatives = ["0", f"[1-9][0-9]{{0,{len(maximum) - 2}}}", maximum] + for index, digit in enumerate(maximum): + first_digit = 1 if index == 0 else 0 + last_digit = int(digit) - 1 + if first_digit <= last_digit: + remaining = len(maximum) - index - 1 + alternatives.append( + f"{maximum[:index]}[{first_digit}-{last_digit}][0-9]{{{remaining}}}" + ) + return "^(?:" + "|".join(alternatives) + ")$" + + +class AutomationDraftBody(AutomationPreviewBody): + rule_id: Identifier | None + expected_revision: str = Field( + pattern=_draft_revision_pattern(), + description="Use zero to create a draft and a positive signed 64-bit revision to edit.", + ) + + +class AutomationDraftDetail(AutomationPreviewBody): + rule_id: Identifier + revision: str + state: Literal["draft"] = "draft" + enabled: Literal[False] = False + + def create_automation_router( context: Callable[[Request], TaskHTTPContext], *, security: Depends ) -> APIRouter: @@ -106,4 +145,45 @@ def preview( ) -> AutomationSimulation: return context(request).automation().preview(body.domain()) + @router.get("/drafts", response_model=DraftPage) + def drafts(request: Request, query: Annotated[PageQuery, Query()]) -> DraftPage: + return context(request).automation_drafts.list(limit=query.limit, cursor=query.cursor) + + @router.get("/drafts/{rule_id}", response_model=AutomationDraftDetail) + def reopen( + request: Request, rule_id: Identifier, query: Annotated[_EmptyQuery, Query()] + ) -> AutomationDraftDetail: + draft = context(request).automation_drafts.reopen(rule_id) + return AutomationDraftDetail.model_validate( + { + **draft.rule.document().decode(), + "rule_id": draft.rule_id, + "revision": str(draft.revision), + } + ) + + @router.post( + "/drafts", + response_model=ReceiptResponse, + openapi_extra={ + "parameters": [ + {"name": name, "in": "header", "required": True, "schema": {"type": "string"}} + for name in ("Idempotency-Key", "Origin", "X-CSRF-Token") + ] + }, + ) + def save( + request: Request, body: AutomationDraftBody, query: Annotated[_EmptyQuery, Query()] + ) -> ReceiptResponse: + receipt = context(request).automation_drafts.save( + _key(request), SaveDraft(body.rule_id, int(body.expected_revision), body.domain()) + ) + return _receipt(receipt) + + @router.get("/drafts/requests/{key}", response_model=ReceiptResponse) + def original( + request: Request, key: Identifier, query: Annotated[_EmptyQuery, Query()] + ) -> ReceiptResponse: + return _receipt(context(request).automation_drafts.original(key)) + return router diff --git a/backend/src/domus/entrypoints/http_errors.py b/backend/src/domus/entrypoints/http_errors.py index 569169a8..874a5521 100644 --- a/backend/src/domus/entrypoints/http_errors.py +++ b/backend/src/domus/entrypoints/http_errors.py @@ -165,6 +165,7 @@ "inventory_unavailable", "invalid_inventory_unit", "invalid_automation_rule", + "automation_draft_missing", "invalid_automation_condition", "automation_condition_depth", "automation_rule_node_limit", diff --git a/backend/src/domus/entrypoints/native_http.py b/backend/src/domus/entrypoints/native_http.py index d82f4a62..74a22cb6 100644 --- a/backend/src/domus/entrypoints/native_http.py +++ b/backend/src/domus/entrypoints/native_http.py @@ -114,6 +114,7 @@ def _allowed(self, scope: Scope) -> None: ) or scope["path"] in ( + "/api/v1/automation/drafts", "/api/v1/family", "/api/v1/family/allocation", "/api/v1/family/rewards", diff --git a/backend/src/domus/entrypoints/task_http.py b/backend/src/domus/entrypoints/task_http.py index f6289ff0..665105aa 100644 --- a/backend/src/domus/entrypoints/task_http.py +++ b/backend/src/domus/entrypoints/task_http.py @@ -7,6 +7,7 @@ from fastapi import APIRouter, Query, Request from fastapi.params import Depends +from domus.application.automation_drafts import AutomationDrafts from domus.application.automation_preview import AutomationPreview from domus.application.calendar_commands import CalendarCommands from domus.application.calendar_queries import CalendarQueries @@ -124,6 +125,7 @@ class TaskHTTPContext: inventory_commands: InventoryCommands inventory_original: Callable[[CatalogAction, str], Receipt] automation: Callable[[], AutomationPreview] + automation_drafts: AutomationDrafts def create_task_router( diff --git a/backend/src/domus/infrastructure/sqlite.py b/backend/src/domus/infrastructure/sqlite.py index ac0060f2..6e1c9449 100644 --- a/backend/src/domus/infrastructure/sqlite.py +++ b/backend/src/domus/infrastructure/sqlite.py @@ -30,6 +30,11 @@ OutboxEvent, validate_identifier, ) +from domus.infrastructure.sqlite_automation_drafts import ( + AUTOMATION_DRAFT_STATEMENT, + AUTOMATION_DRAFT_TABLE, + SQLiteAutomationDrafts, +) from domus.infrastructure.sqlite_calendar import SQLiteCalendar from domus.infrastructure.sqlite_calendar_preferences import ( CALENDAR_PREFERENCE_STATEMENT, @@ -103,7 +108,7 @@ ) from domus.infrastructure.sqlite_tasks import SQLiteTasks -SCHEMA_VERSION = 31 +SCHEMA_VERSION = 32 APPLICATION_ID = 0x444F4D55 BASE_STATEMENTS = ( "CREATE TABLE installation(singleton INTEGER PRIMARY KEY CHECK(singleton=1), " @@ -191,6 +196,7 @@ *SHOPPING_RECEIPT_RETURN_STATEMENTS, *LOCATION_STATEMENTS, SHOPPING_SESSION_STORE_STATEMENT, + AUTOMATION_DRAFT_STATEMENT, ) BASE_TABLES = {"installation", "households", "receipts", "audit", "outbox"} IDENTITY_TABLES = BASE_TABLES | {"members", "household_policy"} @@ -217,7 +223,8 @@ VOID_SCHEMA_TABLES = CANCELLATION_SCHEMA_TABLES | {SHOPPING_RECEIPT_VOID_TABLE} CORRECTION_SCHEMA_TABLES = VOID_SCHEMA_TABLES | {SHOPPING_RECEIPT_CORRECTION_TABLE} RETURN_SCHEMA_TABLES = CORRECTION_SCHEMA_TABLES | {SHOPPING_RECEIPT_RETURN_TABLE} -TABLES = RETURN_SCHEMA_TABLES | LOCATION_TABLES +LOCATION_SCHEMA_TABLES = RETURN_SCHEMA_TABLES | LOCATION_TABLES +TABLES = LOCATION_SCHEMA_TABLES | {AUTOMATION_DRAFT_TABLE} def _schema(connection: sqlite3.Connection) -> tuple[tuple[str, str], ...]: @@ -264,6 +271,7 @@ def _expected_schema(version: int) -> tuple[tuple[str, str], ...]: *(SHOPPING_RECEIPT_RETURN_STATEMENTS if version >= 29 else ()), *(LOCATION_STATEMENTS if version >= 30 else ()), *((SHOPPING_SESSION_STORE_STATEMENT,) if version >= 31 else ()), + *((AUTOMATION_DRAFT_STATEMENT,) if version >= 32 else ()), ) for statement in statements: connection.execute(statement) @@ -443,6 +451,7 @@ def delivered(self, event_id: str) -> bool | None: class SQLiteUnit: def __init__(self, connection: sqlite3.Connection, installation: Installation) -> None: + self.automation_drafts = SQLiteAutomationDrafts(connection) self.recurrence = SQLiteRecurrences(connection, installation) self.calendar = SQLiteCalendar(connection) self.calendar_preferences = SQLiteCalendarPreferences(connection) @@ -543,6 +552,8 @@ def _inspect( 27: VOID_SCHEMA_TABLES, 28: CORRECTION_SCHEMA_TABLES, 29: RETURN_SCHEMA_TABLES, + 30: LOCATION_SCHEMA_TABLES, + 31: LOCATION_SCHEMA_TABLES, }.get(version, TABLES) if application_id != APPLICATION_ID or objects != expected_tables: raise DatabaseRejected("unrelated_database") @@ -619,7 +630,8 @@ def initialize(self, *, require_existing: bool = False) -> None: *(SHOPPING_RECEIPT_CORRECTION_STATEMENTS if version < 28 else ()), *(SHOPPING_RECEIPT_RETURN_STATEMENTS if version < 29 else ()), *(LOCATION_STATEMENTS if version < 30 else ()), - SHOPPING_SESSION_STORE_STATEMENT, + *((SHOPPING_SESSION_STORE_STATEMENT,) if version < 31 else ()), + AUTOMATION_DRAFT_STATEMENT, ) for statement in migration: connection.execute(statement) diff --git a/backend/src/domus/infrastructure/sqlite_automation_drafts.py b/backend/src/domus/infrastructure/sqlite_automation_drafts.py new file mode 100644 index 00000000..3e1893ce --- /dev/null +++ b/backend/src/domus/infrastructure/sqlite_automation_drafts.py @@ -0,0 +1,83 @@ +"""Immutable revisions of household automation drafts.""" + +import sqlite3 +from dataclasses import dataclass + +from domus.domain.automation import AutomationDraft, AutomationRule +from domus.domain.errors import Conflict, InvalidInput, StorageFailure +from domus.domain.storage import JsonDocument + +AUTOMATION_DRAFT_TABLE = "automation_draft_revisions" +AUTOMATION_DRAFT_STATEMENT = ( + "CREATE TABLE automation_draft_revisions(" + "household_id TEXT NOT NULL REFERENCES households(household_id), " + "rule_id TEXT NOT NULL, revision INTEGER NOT NULL " + "CHECK(typeof(revision)='integer' AND revision>=1), definition TEXT NOT NULL, " + "PRIMARY KEY(household_id,rule_id,revision))" +) + + +def _draft(row: sqlite3.Row) -> AutomationDraft: + try: + rule = AutomationRule.from_document(JsonDocument(row["definition"])) + return AutomationDraft(row["rule_id"], row["revision"], rule) + except InvalidInput: + raise StorageFailure("invalid_automation_draft_record") from None + + +@dataclass +class SQLiteAutomationDrafts: + connection: sqlite3.Connection + + def latest(self, household_id: str, rule_id: str) -> AutomationDraft | None: + row = self.connection.execute( + "SELECT rule_id,revision,definition FROM automation_draft_revisions " + "WHERE household_id=? AND rule_id=? ORDER BY revision DESC LIMIT 1", + (household_id, rule_id), + ).fetchone() + return _draft(row) if row is not None else None + + def page(self, household_id: str, after: str, limit: int) -> tuple[AutomationDraft, ...]: + return tuple( + _draft(row) + for row in self.connection.execute( + "SELECT d.rule_id,d.revision,d.definition FROM automation_draft_revisions d " + "JOIN (SELECT rule_id,max(revision) AS revision FROM automation_draft_revisions " + "WHERE household_id=? AND rule_id>? GROUP BY rule_id ORDER BY rule_id LIMIT ?) " + "AS heads ON d.rule_id=heads.rule_id AND d.revision=heads.revision " + "WHERE d.household_id=? ORDER BY d.rule_id", + (household_id, after, limit, household_id), + ) + ) + + def append(self, household_id: str, draft: AutomationDraft) -> None: + changed = self.connection.execute( + "INSERT INTO automation_draft_revisions(household_id,rule_id,revision,definition) " + "SELECT ?,?,?,? WHERE coalesce((SELECT max(revision) FROM automation_draft_revisions " + "WHERE household_id=? AND rule_id=?),0)=?", + ( + household_id, + draft.rule_id, + draft.revision, + draft.rule.document().encoded, + household_id, + draft.rule_id, + draft.revision - 1, + ), + ).rowcount + if changed != 1: + raise Conflict("revision_conflict") + + +def verify_automation_drafts(connection: sqlite3.Connection) -> None: + previous: tuple[str, str] | None = None + revision = 0 + for row in connection.execute( + "SELECT * FROM automation_draft_revisions ORDER BY household_id,rule_id,revision" + ): + scope = row["household_id"], row["rule_id"] + revision = revision + 1 if scope == previous else 1 + draft = _draft(row) + if draft.revision != revision or draft.rule.document().encoded != row["definition"]: + raise StorageFailure("invalid_automation_draft_record") + previous = scope diff --git a/backend/src/domus/infrastructure/sqlite_snapshots.py b/backend/src/domus/infrastructure/sqlite_snapshots.py index dc590d2c..a7e75301 100644 --- a/backend/src/domus/infrastructure/sqlite_snapshots.py +++ b/backend/src/domus/infrastructure/sqlite_snapshots.py @@ -37,6 +37,7 @@ _schema, _storage_error, ) +from domus.infrastructure.sqlite_automation_drafts import verify_automation_drafts from domus.infrastructure.sqlite_history import ( last_committed_at, verify_history, @@ -226,6 +227,8 @@ def _records(connection: sqlite3.Connection, version: int, installation: Install verify_shopping_sessions(connection, has_store=version >= 31) if version >= 30: verify_inventory_locations(connection) + if version >= 32: + verify_automation_drafts(connection) except DomusError as error: raise DatabaseRejected("invalid_snapshot_records") from error diff --git a/docs/contracts/household-api.openapi.json b/docs/contracts/household-api.openapi.json index baed44ce..eda4b03d 100644 --- a/docs/contracts/household-api.openapi.json +++ b/docs/contracts/household-api.openapi.json @@ -716,6 +716,119 @@ "title": "AssignmentBody", "type": "object" }, + "AutomationDraftBody": { + "additionalProperties": false, + "properties": { + "action": { + "$ref": "#/components/schemas/CreateTaskProposalBody" + }, + "condition": { + "anyOf": [ + { + "$ref": "#/components/schemas/ConditionBody-Input" + }, + { + "type": "null" + } + ] + }, + "expected_revision": { + "description": "Use zero to create a draft and a positive signed 64-bit revision to edit.", + "pattern": "^(?:0|[1-9][0-9]{0,17}|9223372036854775807|[1-8][0-9]{18}|9[0-1][0-9]{17}|92[0-1][0-9]{16}|922[0-2][0-9]{15}|9223[0-2][0-9]{14}|92233[0-6][0-9]{13}|922337[0-1][0-9]{12}|92233720[0-2][0-9]{10}|922337203[0-5][0-9]{9}|9223372036[0-7][0-9]{8}|92233720368[0-4][0-9]{7}|922337203685[0-3][0-9]{6}|9223372036854[0-6][0-9]{5}|92233720368547[0-6][0-9]{4}|922337203685477[0-4][0-9]{3}|9223372036854775[0-7][0-9]{2}|922337203685477580[0-6][0-9]{0})$", + "title": "Expected Revision", + "type": "string" + }, + "rule_id": { + "anyOf": [ + { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Rule Id" + }, + "trigger": { + "$ref": "#/components/schemas/ManualTriggerBody" + }, + "version": { + "maximum": 1.0, + "minimum": 1.0, + "title": "Version", + "type": "integer" + } + }, + "required": [ + "version", + "trigger", + "condition", + "action", + "rule_id", + "expected_revision" + ], + "title": "AutomationDraftBody", + "type": "object" + }, + "AutomationDraftDetail": { + "additionalProperties": false, + "properties": { + "action": { + "$ref": "#/components/schemas/CreateTaskProposalBody" + }, + "condition": { + "anyOf": [ + { + "$ref": "#/components/schemas/ConditionBody-Output" + }, + { + "type": "null" + } + ] + }, + "enabled": { + "const": false, + "default": false, + "title": "Enabled", + "type": "boolean" + }, + "revision": { + "title": "Revision", + "type": "string" + }, + "rule_id": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Rule Id", + "type": "string" + }, + "state": { + "const": "draft", + "default": "draft", + "title": "State", + "type": "string" + }, + "trigger": { + "$ref": "#/components/schemas/ManualTriggerBody" + }, + "version": { + "maximum": 1.0, + "minimum": 1.0, + "title": "Version", + "type": "integer" + } + }, + "required": [ + "version", + "trigger", + "condition", + "action", + "rule_id", + "revision" + ], + "title": "AutomationDraftDetail", + "type": "object" + }, "AutomationPreviewAccess": { "properties": { "household_id": { @@ -738,7 +851,7 @@ "condition": { "anyOf": [ { - "$ref": "#/components/schemas/ConditionBody" + "$ref": "#/components/schemas/ConditionBody-Input" }, { "type": "null" @@ -1459,12 +1572,12 @@ "title": "CompleteBody", "type": "object" }, - "ConditionBody": { + "ConditionBody-Input": { "discriminator": { "mapping": { - "all": "#/components/schemas/ConditionGroupBody", - "any": "#/components/schemas/ConditionGroupBody", - "not": "#/components/schemas/NegatedConditionBody", + "all": "#/components/schemas/ConditionGroupBody-Input", + "any": "#/components/schemas/ConditionGroupBody-Input", + "not": "#/components/schemas/NegatedConditionBody-Input", "stock_below_minimum": "#/components/schemas/StockConditionBody" }, "propertyName": "kind" @@ -1474,10 +1587,32 @@ "$ref": "#/components/schemas/StockConditionBody" }, { - "$ref": "#/components/schemas/ConditionGroupBody" + "$ref": "#/components/schemas/ConditionGroupBody-Input" }, { - "$ref": "#/components/schemas/NegatedConditionBody" + "$ref": "#/components/schemas/NegatedConditionBody-Input" + } + ] + }, + "ConditionBody-Output": { + "discriminator": { + "mapping": { + "all": "#/components/schemas/ConditionGroupBody-Output", + "any": "#/components/schemas/ConditionGroupBody-Output", + "not": "#/components/schemas/NegatedConditionBody-Output", + "stock_below_minimum": "#/components/schemas/StockConditionBody" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/components/schemas/StockConditionBody" + }, + { + "$ref": "#/components/schemas/ConditionGroupBody-Output" + }, + { + "$ref": "#/components/schemas/NegatedConditionBody-Output" } ] }, @@ -1517,12 +1652,40 @@ "title": "ConditionDecision", "type": "object" }, - "ConditionGroupBody": { + "ConditionGroupBody-Input": { + "additionalProperties": false, + "properties": { + "children": { + "items": { + "$ref": "#/components/schemas/ConditionBody-Input" + }, + "maxItems": 64, + "minItems": 1, + "title": "Children", + "type": "array" + }, + "kind": { + "enum": [ + "all", + "any" + ], + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind", + "children" + ], + "title": "ConditionGroupBody", + "type": "object" + }, + "ConditionGroupBody-Output": { "additionalProperties": false, "properties": { "children": { "items": { - "$ref": "#/components/schemas/ConditionBody" + "$ref": "#/components/schemas/ConditionBody-Output" }, "maxItems": 64, "minItems": 1, @@ -2125,6 +2288,69 @@ "title": "DirectoryResponse", "type": "object" }, + "DraftPage": { + "properties": { + "drafts": { + "items": { + "$ref": "#/components/schemas/DraftSummary" + }, + "title": "Drafts", + "type": "array" + }, + "next_cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Next Cursor" + } + }, + "required": [ + "drafts", + "next_cursor" + ], + "title": "DraftPage", + "type": "object" + }, + "DraftSummary": { + "properties": { + "enabled": { + "const": false, + "default": false, + "title": "Enabled", + "type": "boolean" + }, + "revision": { + "title": "Revision", + "type": "string" + }, + "rule_id": { + "title": "Rule Id", + "type": "string" + }, + "state": { + "const": "draft", + "default": "draft", + "title": "State", + "type": "string" + }, + "title": { + "title": "Title", + "type": "string" + } + }, + "required": [ + "rule_id", + "revision", + "title" + ], + "title": "DraftSummary", + "type": "object" + }, "EmptyRequest": { "additionalProperties": false, "properties": {}, @@ -4136,11 +4362,30 @@ "title": "NeedKind", "type": "string" }, - "NegatedConditionBody": { + "NegatedConditionBody-Input": { + "additionalProperties": false, + "properties": { + "child": { + "$ref": "#/components/schemas/ConditionBody-Input" + }, + "kind": { + "const": "not", + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind", + "child" + ], + "title": "NegatedConditionBody", + "type": "object" + }, + "NegatedConditionBody-Output": { "additionalProperties": false, "properties": { "child": { - "$ref": "#/components/schemas/ConditionBody" + "$ref": "#/components/schemas/ConditionBody-Output" }, "kind": { "const": "not", @@ -11935,6 +12180,664 @@ "summary": "Access" } }, + "/api/v1/automation/drafts": { + "get": { + "operationId": "drafts_api_v1_automation_drafts_get", + "parameters": [ + { + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 25, + "maximum": 100, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "anyOf": [ + { + "maxLength": 512, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Cursor" + } + }, + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DraftPage" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Method Not Allowed" + }, + "408": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Request Timeout" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Content Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unprocessable Content" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "DomusSession": [] + } + ], + "summary": "Drafts" + }, + "post": { + "operationId": "save_api_v1_automation_drafts_post", + "parameters": [ + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + }, + { + "in": "header", + "name": "Idempotency-Key", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "header", + "name": "Origin", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "header", + "name": "X-CSRF-Token", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AutomationDraftBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReceiptResponse" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Method Not Allowed" + }, + "408": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Request Timeout" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Content Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unprocessable Content" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "DomusSession": [] + } + ], + "summary": "Save" + } + }, + "/api/v1/automation/drafts/requests/{key}": { + "get": { + "operationId": "original_api_v1_automation_drafts_requests__key__get", + "parameters": [ + { + "in": "path", + "name": "key", + "required": true, + "schema": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Key", + "type": "string" + } + }, + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReceiptResponse" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Method Not Allowed" + }, + "408": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Request Timeout" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Content Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unprocessable Content" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "DomusSession": [] + } + ], + "summary": "Original" + } + }, + "/api/v1/automation/drafts/{rule_id}": { + "get": { + "operationId": "reopen_api_v1_automation_drafts__rule_id__get", + "parameters": [ + { + "in": "path", + "name": "rule_id", + "required": true, + "schema": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Rule Id", + "type": "string" + } + }, + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AutomationDraftDetail" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Method Not Allowed" + }, + "408": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Request Timeout" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Content Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unprocessable Content" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "DomusSession": [] + } + ], + "summary": "Reopen" + } + }, "/api/v1/automation/preview": { "post": { "operationId": "preview_api_v1_automation_preview_post", diff --git a/docs/contracts/native-household-api.openapi.json b/docs/contracts/native-household-api.openapi.json index bdb9a125..c2ea6f88 100644 --- a/docs/contracts/native-household-api.openapi.json +++ b/docs/contracts/native-household-api.openapi.json @@ -716,6 +716,119 @@ "title": "AssignmentBody", "type": "object" }, + "AutomationDraftBody": { + "additionalProperties": false, + "properties": { + "action": { + "$ref": "#/components/schemas/CreateTaskProposalBody" + }, + "condition": { + "anyOf": [ + { + "$ref": "#/components/schemas/ConditionBody-Input" + }, + { + "type": "null" + } + ] + }, + "expected_revision": { + "description": "Use zero to create a draft and a positive signed 64-bit revision to edit.", + "pattern": "^(?:0|[1-9][0-9]{0,17}|9223372036854775807|[1-8][0-9]{18}|9[0-1][0-9]{17}|92[0-1][0-9]{16}|922[0-2][0-9]{15}|9223[0-2][0-9]{14}|92233[0-6][0-9]{13}|922337[0-1][0-9]{12}|92233720[0-2][0-9]{10}|922337203[0-5][0-9]{9}|9223372036[0-7][0-9]{8}|92233720368[0-4][0-9]{7}|922337203685[0-3][0-9]{6}|9223372036854[0-6][0-9]{5}|92233720368547[0-6][0-9]{4}|922337203685477[0-4][0-9]{3}|9223372036854775[0-7][0-9]{2}|922337203685477580[0-6][0-9]{0})$", + "title": "Expected Revision", + "type": "string" + }, + "rule_id": { + "anyOf": [ + { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Rule Id" + }, + "trigger": { + "$ref": "#/components/schemas/ManualTriggerBody" + }, + "version": { + "maximum": 1.0, + "minimum": 1.0, + "title": "Version", + "type": "integer" + } + }, + "required": [ + "version", + "trigger", + "condition", + "action", + "rule_id", + "expected_revision" + ], + "title": "AutomationDraftBody", + "type": "object" + }, + "AutomationDraftDetail": { + "additionalProperties": false, + "properties": { + "action": { + "$ref": "#/components/schemas/CreateTaskProposalBody" + }, + "condition": { + "anyOf": [ + { + "$ref": "#/components/schemas/ConditionBody-Output" + }, + { + "type": "null" + } + ] + }, + "enabled": { + "const": false, + "default": false, + "title": "Enabled", + "type": "boolean" + }, + "revision": { + "title": "Revision", + "type": "string" + }, + "rule_id": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Rule Id", + "type": "string" + }, + "state": { + "const": "draft", + "default": "draft", + "title": "State", + "type": "string" + }, + "trigger": { + "$ref": "#/components/schemas/ManualTriggerBody" + }, + "version": { + "maximum": 1.0, + "minimum": 1.0, + "title": "Version", + "type": "integer" + } + }, + "required": [ + "version", + "trigger", + "condition", + "action", + "rule_id", + "revision" + ], + "title": "AutomationDraftDetail", + "type": "object" + }, "AutomationPreviewAccess": { "properties": { "household_id": { @@ -738,7 +851,7 @@ "condition": { "anyOf": [ { - "$ref": "#/components/schemas/ConditionBody" + "$ref": "#/components/schemas/ConditionBody-Input" }, { "type": "null" @@ -1459,12 +1572,12 @@ "title": "CompleteBody", "type": "object" }, - "ConditionBody": { + "ConditionBody-Input": { "discriminator": { "mapping": { - "all": "#/components/schemas/ConditionGroupBody", - "any": "#/components/schemas/ConditionGroupBody", - "not": "#/components/schemas/NegatedConditionBody", + "all": "#/components/schemas/ConditionGroupBody-Input", + "any": "#/components/schemas/ConditionGroupBody-Input", + "not": "#/components/schemas/NegatedConditionBody-Input", "stock_below_minimum": "#/components/schemas/StockConditionBody" }, "propertyName": "kind" @@ -1474,10 +1587,32 @@ "$ref": "#/components/schemas/StockConditionBody" }, { - "$ref": "#/components/schemas/ConditionGroupBody" + "$ref": "#/components/schemas/ConditionGroupBody-Input" }, { - "$ref": "#/components/schemas/NegatedConditionBody" + "$ref": "#/components/schemas/NegatedConditionBody-Input" + } + ] + }, + "ConditionBody-Output": { + "discriminator": { + "mapping": { + "all": "#/components/schemas/ConditionGroupBody-Output", + "any": "#/components/schemas/ConditionGroupBody-Output", + "not": "#/components/schemas/NegatedConditionBody-Output", + "stock_below_minimum": "#/components/schemas/StockConditionBody" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/components/schemas/StockConditionBody" + }, + { + "$ref": "#/components/schemas/ConditionGroupBody-Output" + }, + { + "$ref": "#/components/schemas/NegatedConditionBody-Output" } ] }, @@ -1517,12 +1652,40 @@ "title": "ConditionDecision", "type": "object" }, - "ConditionGroupBody": { + "ConditionGroupBody-Input": { + "additionalProperties": false, + "properties": { + "children": { + "items": { + "$ref": "#/components/schemas/ConditionBody-Input" + }, + "maxItems": 64, + "minItems": 1, + "title": "Children", + "type": "array" + }, + "kind": { + "enum": [ + "all", + "any" + ], + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind", + "children" + ], + "title": "ConditionGroupBody", + "type": "object" + }, + "ConditionGroupBody-Output": { "additionalProperties": false, "properties": { "children": { "items": { - "$ref": "#/components/schemas/ConditionBody" + "$ref": "#/components/schemas/ConditionBody-Output" }, "maxItems": 64, "minItems": 1, @@ -2125,6 +2288,69 @@ "title": "DirectoryResponse", "type": "object" }, + "DraftPage": { + "properties": { + "drafts": { + "items": { + "$ref": "#/components/schemas/DraftSummary" + }, + "title": "Drafts", + "type": "array" + }, + "next_cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Next Cursor" + } + }, + "required": [ + "drafts", + "next_cursor" + ], + "title": "DraftPage", + "type": "object" + }, + "DraftSummary": { + "properties": { + "enabled": { + "const": false, + "default": false, + "title": "Enabled", + "type": "boolean" + }, + "revision": { + "title": "Revision", + "type": "string" + }, + "rule_id": { + "title": "Rule Id", + "type": "string" + }, + "state": { + "const": "draft", + "default": "draft", + "title": "State", + "type": "string" + }, + "title": { + "title": "Title", + "type": "string" + } + }, + "required": [ + "rule_id", + "revision", + "title" + ], + "title": "DraftSummary", + "type": "object" + }, "EnrollmentRequest": { "additionalProperties": false, "properties": { @@ -4157,11 +4383,30 @@ "title": "NeedKind", "type": "string" }, - "NegatedConditionBody": { + "NegatedConditionBody-Input": { + "additionalProperties": false, + "properties": { + "child": { + "$ref": "#/components/schemas/ConditionBody-Input" + }, + "kind": { + "const": "not", + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind", + "child" + ], + "title": "NegatedConditionBody", + "type": "object" + }, + "NegatedConditionBody-Output": { "additionalProperties": false, "properties": { "child": { - "$ref": "#/components/schemas/ConditionBody" + "$ref": "#/components/schemas/ConditionBody-Output" }, "kind": { "const": "not", @@ -11423,6 +11668,664 @@ "summary": "Access" } }, + "/api/v1/automation/drafts": { + "get": { + "operationId": "drafts_api_v1_automation_drafts_get", + "parameters": [ + { + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 25, + "maximum": 100, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "anyOf": [ + { + "maxLength": 512, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Cursor" + } + }, + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DraftPage" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Method Not Allowed" + }, + "408": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Request Timeout" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Content Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unprocessable Content" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "HomeAssistantIngress": [] + } + ], + "summary": "Drafts" + }, + "post": { + "operationId": "save_api_v1_automation_drafts_post", + "parameters": [ + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + }, + { + "in": "header", + "name": "Idempotency-Key", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "header", + "name": "Origin", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "header", + "name": "X-CSRF-Token", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AutomationDraftBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReceiptResponse" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Method Not Allowed" + }, + "408": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Request Timeout" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Content Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unprocessable Content" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "HomeAssistantIngress": [] + } + ], + "summary": "Save" + } + }, + "/api/v1/automation/drafts/requests/{key}": { + "get": { + "operationId": "original_api_v1_automation_drafts_requests__key__get", + "parameters": [ + { + "in": "path", + "name": "key", + "required": true, + "schema": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Key", + "type": "string" + } + }, + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReceiptResponse" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Method Not Allowed" + }, + "408": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Request Timeout" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Content Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unprocessable Content" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "HomeAssistantIngress": [] + } + ], + "summary": "Original" + } + }, + "/api/v1/automation/drafts/{rule_id}": { + "get": { + "operationId": "reopen_api_v1_automation_drafts__rule_id__get", + "parameters": [ + { + "in": "path", + "name": "rule_id", + "required": true, + "schema": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Rule Id", + "type": "string" + } + }, + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AutomationDraftDetail" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Method Not Allowed" + }, + "408": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Request Timeout" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Content Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unprocessable Content" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "HomeAssistantIngress": [] + } + ], + "summary": "Reopen" + } + }, "/api/v1/automation/preview": { "post": { "operationId": "preview_api_v1_automation_preview_post", diff --git a/docs/evidence/automation-draft-qualification.md b/docs/evidence/automation-draft-qualification.md new file mode 100644 index 00000000..6e09eb13 --- /dev/null +++ b/docs/evidence/automation-draft-qualification.md @@ -0,0 +1,16 @@ +# Automation draft qualification + +[Domus #118](https://github.com/vypdev/domus/issues/118) adds inactive drafts to +the [manual automation preview](automation-preview-qualification.md). The +[automation specification](../../specs/household-automation.md) owns the +requirements `automation-drafts-R01` through `automation-drafts-R04`. + +| Case | Verification | +| --- | --- | +| `automation-drafts-C01` | The native and standalone HTTP tests save, list and reopen the exact version-one task proposal and condition, including the maximum condition depth. | +| `automation-drafts-C02` | The HTTP tests exercise current membership and task grants, scoped references and validation that preserves the last saved revision. | +| `automation-drafts-C03` | The HTTP tests exercise concurrent writers, immutable revision history, identical replay and conflicting key reuse. | +| `automation-drafts-C04` | The HTTP tests compare task and inventory data and the pending outbox before and after save and preview. The save records an audit envelope acknowledged in its own transaction for receipt restoration. | +| `automation-drafts-C05` | The [compiled browser journeys](../../frontend/tests/e2e/workspace-navigation.spec.ts) cover English desktop keyboard and Spanish narrow touch, with screenshots in both themes. They reopen a saved stock condition after reload, lose a committed response and recover its receipt, then compare the competing revision and save the preserved input. A failed comparison leaves the review action available, blocks another stale save and keeps the edits. A delayed open and a failed, then delayed, initial list keep the editor locked until the saved definition or pending request is known. | +| `automation-drafts-C06` | The SQLite tests exercise byte-identical migration rollback, restart, checkpoint restoration and rollback for the [schema 20 fixture](../../tests/fixtures/sqlite/v20-inventory-history-source.sql) and [schema 31 fixture](../../tests/fixtures/sqlite/v31-automation-drafts-source.sql). Edge.32 at `43bace9576b9468f789fe9975a3dd5fe427d83ae` produced the schema 31 fixture with a named purchase session and its original receipt. | +| `automation-drafts-C07` | The compiled browser journeys run through Ingress and standalone. The contributing pull request records the image and installed Edge qualification and cleanup. | diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json index 3e2d2d01..a1a5589e 100644 --- a/docs/evidence/task-navigation-integration.json +++ b/docs/evidence/task-navigation-integration.json @@ -3,12 +3,12 @@ "historicalTaskHead": "8c0a36c0b9804bdaf33a301a4dc85ae3dc12ee21", "developParent": "5b7bdcdee3a9e98d6669bfd34ce750ae30a8c775", "command": "pnpm build:frontend", - "scope": "Compiled household workspace with a protected manual task automation preview, upcoming maintenance, due today, overdue, assigned and unclaimed task summaries, products below their replenishment minimum, outstanding shopping items, weekly Family participation, optional task base points, native deadline sensor integration, protected Pantry, shared Shopping, purchase sessions with an optional store, receipt corrections, physical returns, stock locations, transfers and original operation recovery in English and Spanish.", + "scope": "Compiled household workspace with a protected manual task automation preview and inactive saved revisions, upcoming maintenance, due today, overdue, assigned and unclaimed task summaries, products below their replenishment minimum, outstanding shopping items, weekly Family participation, optional task base points, native deadline sensor integration, protected Pantry, shared Shopping, purchase sessions with an optional store, receipt corrections, physical returns, stock locations, transfers and original operation recovery in English and Spanish.", "actualProductFiles": { - ".vite/manifest.json": "8157d0110594f50f64ef9eaf26ccde2b9762d2ec1d9a65788015cef05d51be1e", - "assets/index-CK0b1_ig.js": "62063f545d4cd9609d9cc807e8eea8cf89587e904803de7ec44ef6fcc7dc3543", + ".vite/manifest.json": "fafa17b6976362a2a437ce99e0b87d6afb465acf1ae0ae634d29bb24b050297e", + "assets/index-CJX6CQDY.js": "ceb1aa767bf164682dababadfb0f60d3217988372995b365cf38f3b26546f02f", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "005c1c8afae3913690ee9e83248d4d23cc5775b2f14d14718e544ba696037616" + "index.html": "9704bae64d589f1512faec3f59e963c8a6363804d57dece08f77832f96b95c87" }, "localValidation": { "commit": "9a10d8114869be754962953903e773fe8e12c723", @@ -250,5 +250,16 @@ "assets/index-dNVoGxPS.js": "e45db999a44ae5c37e304cddec83956b3ad5cc658661fb45ab9553154b204347", "index.html": "75559774732a85108416c5bfc6f4a855f144ebeffbc87f641f6ccea7cb13791e" } + }, + "automationDrafts": { + "sourceCommit": "63890ace59d55ec76e0b9c3c7c832598eeeab7a1", + "actualProductFiles": { + ".vite/manifest.json": "fafa17b6976362a2a437ce99e0b87d6afb465acf1ae0ae634d29bb24b050297e", + "assets/index-CJX6CQDY.js": "ceb1aa767bf164682dababadfb0f60d3217988372995b365cf38f3b26546f02f", + "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", + "index.html": "9704bae64d589f1512faec3f59e963c8a6363804d57dece08f77832f96b95c87" + }, + "requirements": "automation-drafts-R01 through automation-drafts-R04", + "evidence": "automation-draft-qualification.md" } } diff --git a/docs/installation-home-assistant.md b/docs/installation-home-assistant.md index bdd517da..02cc9511 100644 --- a/docs/installation-home-assistant.md +++ b/docs/installation-home-assistant.md @@ -17,11 +17,22 @@ The Ingress walkthrough verified the Overview stock summary and replenishment in English and Spanish. The test app, its data and its temporary repository source were removed after verification. [Installed acceptance](https://github.com/vypdev/domus/pull/103#issuecomment-6797153928) -The preview uses SQLite schema 31, introduced by Edge.13. Keep a compatible image and +The current Edge preview uses SQLite schema 32. Keep a compatible image and cold data backup before updating from an earlier schema. An additional Supervisor source creates an independent app and data directory. Use the [installation steps](#installation-journey) for the selected source and check the installed version before opening it. +Edge.37 keeps conflict review available when the latest draft revision fails to load. + +Edge.36 keeps the automation editor locked while opening a draft or checking an interrupted save. + +Edge.35 shows the latest saved condition when you review a conflicting draft revision. + +Edge.34 makes the draft API contract use the exact signed 64-bit revision range. + +Edge.33 [saves and reopens inactive automation drafts](evidence/automation-draft-qualification.md). +Edits append revisions. An original-save receipt allows recovery after a lost response. + Edge.32 adds the [Overview shopping summary](user-guide.md#shared-shopping-list). Open any displayed item to focus it in Inventory. The preview uses the current shared-list permissions and SQLite schema 31. diff --git a/docs/roadmap.md b/docs/roadmap.md index 196dd5d6..825bad33 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -53,8 +53,9 @@ acceptance of the installed recurrence experience remain open. archiving, lot and package management, barcodes and optional online lookup remain open. - M4 starts with the [manual automation preview](evidence/automation-preview-qualification.md) and includes the native Home Assistant calendar and [task deadline sensors](evidence/ha-deadline-sensors-qualification.md). - Household settings can simulate one task proposal against current stock. Durable rule storage, - enabling and execution, the advanced editor, a shared automation engine and additional Domus-owned + Household settings can simulate one task proposal against current stock and + [save and reopen inactive drafts with immutable revisions](evidence/automation-draft-qualification.md). + Enabling and execution, the advanced editor, a shared automation engine and additional Domus-owned HA entities and services remain open. The existing gateway is already integrated. - M5 includes the [assigned and unclaimed task summaries on Overview](evidence/overview-task-qualification.md) and the [due today and overdue summaries](evidence/overview-deadlines-qualification.md). diff --git a/docs/user-guide.md b/docs/user-guide.md index 8b77a62c..f571a5c8 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -373,8 +373,15 @@ If the product list fails to load, you can preview without a stock condition or choose **Try again** to reload the list with your title intact. Your current household grants control access to the form. +Choose **Save draft** under **Automation drafts** to keep the rule inactive. +Choose **Open** beside a draft to load its latest revision. Saving edits appends a +revision. **Review latest revision** shows a conflicting edit so you can decide +whether to keep your own changes on the new revision. If the save could not be +confirmed, choose **Check original save** to recover the operation without +creating a duplicate. Grouped conditions are available to read and preview. + The [automation specification](../specs/household-automation.md) describes the planned -rule editors, enabling, execution history and Home Assistant operations. +advanced editor, enabling, execution history and Home Assistant operations. ## Channels and privacy diff --git a/frontend/src/adapters/automation-draft-http.ts b/frontend/src/adapters/automation-draft-http.ts new file mode 100644 index 00000000..80f6ae2b --- /dev/null +++ b/frontend/src/adapters/automation-draft-http.ts @@ -0,0 +1,128 @@ +/** Validate protected draft responses and correlate receipts to their original request. */ +import type {AutomationDraftServer, DraftCondition, DraftOutcome, DraftRequest, DraftScope, DraftSummary, SavedAutomationDraft} from '../application/automation-drafts'; +import {revisionValue} from '../domain/administration'; +import {taskText} from '../domain/tasks'; +import {manualRule} from './automation-preview-http'; +import {BoundedHTTP, readFailure} from './http-transport'; +import type {FetchTransport} from './http-transport'; +import {csrf, failure} from './http-values'; +import type {EntryEndpoint} from './http-values'; +import {boolean, check, choice, fields, identifier, integer, text} from './json-values'; +import type {Fields} from './json-values'; + +const BASE = 'automation/drafts'; +const STATUS = ['rule_id', 'revision', 'state', 'enabled'] as const; + +function errorCode(value: unknown): string { + failure(value); + return (value as {code: string}).code; +} + +function inactive(row: Fields) { + check(row.state === 'draft' && row.enabled === false); + return {id: identifier(row.rule_id), revision: revisionValue(row.revision)}; +} + +function summary(value: unknown): DraftSummary { + const row = fields(value, [...STATUS, 'title'], []); + return {...inactive(row), title: taskText(row.title, 160, true)}; +} + +function condition(value: unknown): DraftCondition { + const row = fields(value, ['kind'], ['child', 'children', 'product_id']); + switch (choice(row.kind, ['stock_below_minimum', 'not', 'all', 'any'] as const)) { + case 'stock_below_minimum': + return {kind: 'stock_below_minimum', product_id: identifier(fields(row, ['kind', 'product_id'], []).product_id)}; + case 'not': + return {kind: 'not', child: condition(fields(row, ['kind', 'child'], []).child)}; + case 'all': + case 'any': { + const {children} = fields(row, ['kind', 'children'], []); + check(Array.isArray(children) && children.length > 0 && children.length <= 62); + return {kind: row.kind as 'all' | 'any', children: children.map(condition)}; + } + } +} + +function receipt(value: unknown, scope: DraftScope, request: DraftRequest): DraftOutcome { + const row = fields(value, ['state', 'archived_by', 'operation_id', 'created_at', 'result', 'message', 'action_required'], []); + const kind = choice(row.state, ['committed', 'historical'] as const); + if (kind === 'historical' || row.archived_by !== null) identifier(row.archived_by); + integer(row.created_at, 0); + text(row.message, 2048); + text(row.action_required, 4096); + const result = fields(row.result, [...STATUS, 'member_id'], []); + const fact = inactive(result); + check(result.member_id === scope.memberId + && (request.ruleId === null || request.ruleId === fact.id) + && BigInt(fact.revision) === BigInt(request.revision) + 1n); + return {...fact, kind, operationId: identifier(row.operation_id)}; +} + +export class HttpAutomationDrafts implements AutomationDraftServer { + private readonly network: BoundedHTTP; + constructor(target: EntryEndpoint, transport: FetchTransport) {this.network = new BoundedHTTP(target, transport);} + + list(scope: DraftScope, after: string | null) { + return this.network.owned(async signal => { + const route = after === null ? BASE : BASE + '?cursor=' + encodeURIComponent(after); + const page = fields(await this.network.get(route, scope.context, signal), ['drafts', 'next_cursor'], []); + check(Array.isArray(page.drafts) && page.drafts.length <= 25); + const drafts = page.drafts.map(summary); + check(new Set(drafts.map(draft => draft.id)).size === drafts.length); + return {drafts, next: page.next_cursor === null ? null : text(page.next_cursor, 512)}; + }); + } + + reopen(scope: DraftScope, id: string) { + return this.network.owned(async signal => { + const row = fields(await this.network.get(BASE + '/' + identifier(id), scope.context, signal), + [...STATUS, 'version', 'trigger', 'condition', 'action'], []); + const fact = inactive(row); + const trigger = fields(row.trigger, ['kind'], []); + const action = fields(row.action, ['kind', 'title'], []); + check(fact.id === id && integer(row.version, 1) === 1 + && trigger.kind === 'manual' && action.kind === 'task.create'); + return {...fact, title: taskText(action.title, 160, true), + condition: row.condition === null ? null : condition(row.condition)}; + }); + } + + send(scope: DraftScope, request: DraftRequest) { + return this.network.owned(async signal => { + const token = csrf(await this.network.get('auth/csrf', scope.context, signal)); + const body = JSON.stringify({...manualRule(request.rule), + rule_id: request.ruleId, expected_revision: request.revision}); + const reply = await this.network.request(BASE, 'POST', scope.context, body, identifier(request.key), token, signal); + if (reply.status === 200) return receipt(reply.value, scope, request); + if ([404, 409, 422].includes(reply.status)) { + const code = errorCode(reply.value); + return {kind: code === 'revision_conflict' ? 'conflict' : 'rejected'}; + } + return readFailure(reply.status, reply.value); + }); + } + + previewSaved(scope: DraftScope, draft: SavedAutomationDraft) { + return this.network.owned(async signal => { + const token = csrf(await this.network.get('auth/csrf', scope.context, signal)); + const body = JSON.stringify({...manualRule({title: draft.title, productId: null}), condition: draft.condition}); + const reply = await this.network.request('automation/preview', 'POST', scope.context, body, null, token, signal); + if (reply.status !== 200) return readFailure(reply.status, reply.value); + const result = fields(reply.value, ['version', 'trigger', 'task_title', 'would_create', 'conditions'], []); + check(integer(result.version, 1) === 1 && result.trigger === 'manual' && result.task_title === draft.title + && Array.isArray(result.conditions) && result.conditions.length <= 62); + return boolean(result.would_create); + }); + } + + original(scope: DraftScope, request: DraftRequest) { + return this.network.owned(async signal => { + const reply = await this.network.request(BASE + '/requests/' + identifier(request.key), + 'GET', scope.context, null, null, null, signal); + if (reply.status === 200) return receipt(reply.value, scope, request); + if (reply.status === 404 && errorCode(reply.value) === 'operation_missing') return {kind: 'missing'}; + return readFailure(reply.status, reply.value); + }); + } +} diff --git a/frontend/src/adapters/automation-draft-journal.ts b/frontend/src/adapters/automation-draft-journal.ts new file mode 100644 index 00000000..29bb0f5f --- /dev/null +++ b/frontend/src/adapters/automation-draft-journal.ts @@ -0,0 +1,25 @@ +import type {AutomationDraftJournal, DraftRequest} from '../application/automation-drafts'; +import {revisionValue} from '../domain/administration'; +import {taskText} from '../domain/tasks'; +import {check, fields, identifier, text} from './json-values'; +import {ScopedCommandJournal} from './scoped-command-journal'; +import type {OwnedStorage} from './session-journal'; + +export const AUTOMATION_DRAFT_JOURNAL_KEY = 'domus.automation-draft.v1'; + +function decode(raw: string): DraftRequest { + check(raw.length <= 4096); + const row = fields(JSON.parse(raw), ['key', 'scope', 'ruleId', 'revision', 'rule'], []); + const rule = fields(row.rule, ['title', 'productId'], []); + const ruleId = row.ruleId === null ? null : identifier(row.ruleId); + const revision = ruleId === null && row.revision === '0' ? '0' : revisionValue(row.revision); + check((ruleId === null) === (revision === '0')); + const request: DraftRequest = {key: identifier(row.key), scope: text(row.scope, 1024), ruleId, revision, + rule: {title: taskText(rule.title, 160, true), productId: rule.productId === null ? null : identifier(rule.productId)}}; + check(JSON.stringify(request) === raw); + return request; +} + +export class AutomationDraftSessionJournal extends ScopedCommandJournal implements AutomationDraftJournal { + constructor(storage: OwnedStorage) {super(storage, AUTOMATION_DRAFT_JOURNAL_KEY, decode);} +} diff --git a/frontend/src/adapters/automation-preview-http.ts b/frontend/src/adapters/automation-preview-http.ts index d113f8a0..31c1221e 100644 --- a/frontend/src/adapters/automation-preview-http.ts +++ b/frontend/src/adapters/automation-preview-http.ts @@ -6,6 +6,12 @@ import {csrf} from './http-values'; import type {EntryEndpoint} from './http-values'; import {boolean, check, fields, integer} from './json-values'; +export function manualRule(draft: AutomationPreviewDraft) { + return {version: 1, trigger: {kind: 'manual'}, + condition: draft.productId === null ? null : {kind: 'stock_below_minimum', product_id: draft.productId}, + action: {kind: 'task.create', title: draft.title}}; +} + function proposed(value: unknown, draft: AutomationPreviewDraft): boolean { const result = fields(value, ['version', 'trigger', 'task_title', 'would_create', 'conditions'], []); check(integer(result.version, 1) === 1 && result.trigger === 'manual' && result.task_title === draft.title); @@ -35,9 +41,7 @@ export class HttpAutomationPreview implements AutomationPreviewServer { preview(context: JournalContext, draft: AutomationPreviewDraft) { return this.network.owned(async signal => { const token = csrf(await this.network.get('auth/csrf', context, signal)); - const body = JSON.stringify({version: 1, trigger: {kind: 'manual'}, - condition: draft.productId === null ? null : {kind: 'stock_below_minimum', product_id: draft.productId}, - action: {kind: 'task.create', title: draft.title}}); + const body = JSON.stringify(manualRule(draft)); const reply = await this.network.request('automation/preview', 'POST', context, body, null, token, signal); if (reply.status !== 200) readFailure(reply.status, reply.value); return proposed(reply.value, draft); diff --git a/frontend/src/application/automation-drafts.ts b/frontend/src/application/automation-drafts.ts new file mode 100644 index 00000000..2c66c9d9 --- /dev/null +++ b/frontend/src/application/automation-drafts.ts @@ -0,0 +1,248 @@ +import type {Revision} from '../domain/administration'; +import type {JournalContext} from '../domain/journal'; +import {taskText} from '../domain/tasks'; +import type {AutomationPreviewDraft} from './automation-preview'; +import {EntryReadError} from './ports'; +import type {EntryEntropy, EntryRead} from './ports'; + +export interface DraftScope { + readonly key: string; + readonly context: JournalContext; + readonly memberId: string; + readonly readOnly: boolean; +} +export interface DraftSummary { + readonly id: string; + readonly revision: Revision; + readonly title: string; +} +export type DraftCondition = Readonly<{kind: 'stock_below_minimum'; product_id: string}> + | Readonly<{kind: 'not'; child: DraftCondition}> + | Readonly<{kind: 'all' | 'any'; children: readonly DraftCondition[]}>; +export interface SavedAutomationDraft extends DraftSummary { + readonly condition: DraftCondition | null; +} +export interface DraftPage { + readonly drafts: readonly DraftSummary[]; + readonly next: string | null; +} +export interface DraftRequest { + readonly key: string; + readonly scope: string; + readonly ruleId: string | null; + readonly revision: Revision | '0'; + readonly rule: AutomationPreviewDraft; +} +export type DraftOutcome = Readonly<{kind: 'committed' | 'historical'; id: string; revision: Revision; operationId: string}> + | Readonly<{kind: 'conflict' | 'rejected' | 'missing'}>; +export interface AutomationDraftServer { + list(scope: DraftScope, after: string | null): EntryRead; + reopen(scope: DraftScope, id: string): EntryRead; + previewSaved(scope: DraftScope, draft: SavedAutomationDraft): EntryRead; + send(scope: DraftScope, request: DraftRequest): EntryRead; + original(scope: DraftScope, request: DraftRequest): EntryRead; +} +export interface AutomationDraftJournal { + open(scope: string): DraftRequest | null; + save(request: DraftRequest): void; + clear(request: DraftRequest): void; +} + +type Notice = 'unavailable' | 'invalid_title' | 'uncertain' | 'rejected' | 'conflict' | 'saved' | 'historical'; +interface ReadyDrafts { + readonly state: 'ready'; + readonly page: DraftPage; + readonly after: string | null; + readonly selected: Readonly<{id: string; revision: Revision}> | null; + readonly locked: SavedAutomationDraft | null; + readonly competing: SavedAutomationDraft | null; + readonly conflict: boolean; // A read failure can replace the notice while saving stays blocked. + readonly operationId: string | null; + readonly preview: boolean | null; + readonly busy: boolean; + readonly pending: boolean; + readonly readOnly: boolean; + readonly notice: Notice | null; +} +export type AutomationDraftView = ReadyDrafts | Readonly<{state: 'loading' | 'denied' | 'unavailable'}>; +export type AutomationDraftIntent = Readonly<{type: 'open'; id: string}> + | Readonly<{type: 'retry' | 'next' | 'first' | 'new' | 'save' | 'recover' | 'review' | 'rebase' | 'preview_saved'}>; + +function editable(draft: SavedAutomationDraft): AutomationPreviewDraft | null { + if (draft.condition === null) return {title: draft.title, productId: null}; + return draft.condition.kind === 'stock_below_minimum' + ? {title: draft.title, productId: draft.condition.product_id} : null; +} + +export class AutomationDraftController { + private scope: DraftScope | null = null; + private visible = false; + private ready: ReadyDrafts | null = null; + private owned: EntryRead | null = null; + private pending: DraftRequest | null = null; + + constructor(private readonly server: AutomationDraftServer, private readonly journal: AutomationDraftJournal, + private readonly entropy: EntryEntropy, private readonly edit: (rule: AutomationPreviewDraft) => void, + private readonly publish: (view: AutomationDraftView | null) => void) {} + + bind(scope: DraftScope | null, visible = false): void { + const prior = this.scope; + visible = scope !== null && visible; + const same = prior?.key === scope?.key; + this.scope = scope; + if (same && this.visible === visible) { + if (this.ready !== null && scope !== null && prior?.readOnly !== scope.readOnly) this.set({readOnly: scope.readOnly}); + return; + } + this.cancel(); + if (!same) { + this.ready = null; + this.pending = null; + } + this.visible = visible; + if (visible && scope !== null) void this.list(scope, this.ready?.after ?? null); + else this.publish(null); + } + + private cancel(): void { + this.owned?.cancel(); + this.owned = null; + } + + private set(patch: Partial): void { + if (this.ready === null) return; + this.ready = {...this.ready, ...patch}; + this.publish(this.ready); + } + + private retire(scope: DraftScope): void { + this.ready = null; + this.pending = null; + try { + const saved = this.journal.open(scope.key); + if (saved !== null) this.journal.clear(saved); + } catch {/* Failure to remove local bytes never grants access to them. */} + this.edit({title: '', productId: null}); + this.publish({state: 'denied'}); + } + + private async run(scope: DraftScope, request: EntryRead, use: (value: T) => void, fail: () => void): Promise { + this.owned = request; + this.set({busy: true}); + try { + const value = await request.result; + if (this.owned === request) use(value); + } catch (error) { + if (this.owned !== request) return; + if (error instanceof EntryReadError && (error.code === 'forbidden' || error.code === 'authentication_required')) { + this.retire(scope); + } else fail(); + } finally { + if (this.owned === request) {this.owned = null; this.set({busy: false});} + } + } + + private async list(scope: DraftScope, after: string | null): Promise { + if (this.ready === null) this.publish({state: 'loading'}); + await this.run(scope, this.server.list(scope, after), page => { + if (this.ready === null) { + this.pending = this.journal.open(scope.key); + const recover = this.pending; + this.ready = {state: 'ready', page, after, selected: recover?.ruleId == null ? null + : {id: recover.ruleId, revision: recover.revision as Revision}, locked: null, + competing: null, conflict: false, operationId: null, preview: null, busy: true, pending: recover !== null, + readOnly: this.scope!.readOnly, notice: recover === null ? null : 'uncertain'}; + if (recover !== null) this.edit(recover.rule); + } + this.set({page, after}); + }, () => { + if (this.ready === null) this.publish({state: 'unavailable'}); + else this.set({notice: 'unavailable'}); + }); + } + + async handle(intent: AutomationDraftIntent | undefined, input: AutomationPreviewDraft | null): Promise { + const scope = this.scope, ready = this.ready; + if (intent === undefined || scope === null || !this.visible || this.owned !== null) return; + if (intent.type === 'retry') {await this.list(scope, ready?.after ?? null); return;} + if (ready === null) return; + if (intent.type === 'recover') {await this.recover(scope); return;} + if (intent.type === 'first' && ready.after !== null) {await this.list(scope, null); return;} + if (intent.type === 'next' && ready.page.next !== null) {await this.list(scope, ready.page.next); return;} + if (this.pending !== null) return; + if (intent.type === 'new') { + this.edit({title: '', productId: null}); + this.set({selected: null, locked: null, competing: null, conflict: false, + notice: null, preview: null, operationId: null}); + } else if (intent.type === 'open' && ready.page.drafts.some(draft => draft.id === intent.id)) { + await this.open(scope, intent.id, false); + } else if (intent.type === 'review' && ready.conflict && ready.selected !== null) { + this.set({competing: null, notice: 'conflict'}); + await this.open(scope, ready.selected.id, true); + } else if (intent.type === 'rebase' && ready.competing !== null && !scope.readOnly) { + const competing = ready.competing; + if (editable(competing) !== null) this.set({selected: competing, competing: null, conflict: false, notice: null}); + } else if (intent.type === 'preview_saved' && ready.locked !== null) { + this.set({notice: null, preview: null}); + await this.run(scope, this.server.previewSaved(scope, ready.locked), preview => this.set({preview}), + () => this.set({notice: 'unavailable'})); + } else if (intent.type === 'save' && input !== null && !scope.readOnly + && ready.locked === null && !ready.conflict) { + await this.save(scope, ready, input); + } + } + + private async open(scope: DraftScope, id: string, review: boolean): Promise { + await this.run(scope, this.server.reopen(scope, id), draft => { + if (review) {this.set({competing: draft}); return;} + const rule = editable(draft); + this.edit(rule ?? {title: draft.title, productId: null}); + this.set({selected: draft, locked: rule === null ? draft : null, competing: null, conflict: false, + notice: null, preview: null, operationId: null}); + }, () => this.set({notice: 'unavailable'})); + } + + private async save(scope: DraftScope, ready: ReadyDrafts, input: AutomationPreviewDraft): Promise { + let title: string; + try {title = taskText(input.title, 160, true);} + catch {this.set({notice: 'invalid_title'}); return;} + let request: DraftRequest; + try { + request = {key: this.entropy.requestKey(), scope: scope.key, ruleId: ready.selected?.id ?? null, + revision: ready.selected?.revision ?? '0', rule: {title, productId: input.productId}}; + this.journal.save(request); + } catch {this.set({notice: 'unavailable'}); return;} + this.pending = request; + this.set({pending: true, notice: null, operationId: null}); + await this.send(scope, request, this.server.send(scope, request)); + } + + private async recover(scope: DraftScope): Promise { + const request = this.pending; + if (request === null) return; + const original = await this.send(scope, request, this.server.original(scope, request)); + if (original && this.pending === request && !this.scope?.readOnly) { + await this.send(scope, request, this.server.send(scope, request)); + } + } + + private async send(scope: DraftScope, request: DraftRequest, owned: EntryRead): Promise { + let retry = false; + let refresh = false; + await this.run(scope, owned, outcome => { + if (outcome.kind === 'missing') {retry = true; return;} + this.journal.clear(request); + this.pending = null; + if (outcome.kind === 'committed') { + this.set({pending: false, selected: {id: outcome.id, revision: outcome.revision}, notice: 'saved', + operationId: outcome.operationId, competing: null}); + refresh = true; + } else if (outcome.kind === 'historical') { + this.set({pending: false, selected: null, notice: 'historical', operationId: outcome.operationId}); + refresh = true; + } else this.set({pending: false, conflict: outcome.kind === 'conflict', notice: outcome.kind}); + }, () => this.set({notice: 'uncertain'})); + if (refresh && this.visible && this.scope?.key === scope.key) await this.list(scope, null); + return retry; + } +} diff --git a/frontend/src/application/automation-preview.ts b/frontend/src/application/automation-preview.ts index fbd89c5b..0fa7bbc0 100644 --- a/frontend/src/application/automation-preview.ts +++ b/frontend/src/application/automation-preview.ts @@ -47,6 +47,7 @@ export class AutomationPreviewController { private ready: ReadyPreview | null = null; private pending: EntryRead | null = null; private granted = false; + private replacement: AutomationPreviewDraft | null = null; constructor(private readonly server: AutomationPreviewServer, private readonly inventory: Pick, private readonly publish: (view: AutomationPreviewView | null) => void) {} @@ -57,7 +58,7 @@ export class AutomationPreviewController { if (same && this.visible === visible) return; this.pending?.cancel(); this.pending = null; - if (!same) this.ready = null; + if (!same) {this.ready = null; this.replacement = null;} this.scope = scope; this.visible = visible; this.granted = false; @@ -65,6 +66,17 @@ export class AutomationPreviewController { else this.publish(null); } + draft(): AutomationPreviewDraft | null { + const ready = this.ready; + return this.visible && this.granted && ready?.busy === null + ? {title: ready.title, productId: ready.selected?.id ?? null} : null; + } + + replaceDraft(draft: AutomationPreviewDraft): void { + this.replacement = draft; + if (this.ready !== null && this.pending === null) this.update(this.ready); + } + async handle(intent: AutomationPreviewIntent | undefined): Promise { if (intent?.type === 'retry') { await this.refresh(); @@ -89,6 +101,14 @@ export class AutomationPreviewController { } private update(view: ReadyPreview): void { + const draft = this.replacement; + if (draft !== null && view.busy === null) { + const selected = draft.productId === null ? null + : view.catalog.products.find(product => product.id === draft.productId) + ?? {id: draft.productId, name: draft.productId}; + view = {...view, title: draft.title, selected, result: null, issue: null}; + this.replacement = null; + } this.ready = view; this.publish(view); } @@ -104,6 +124,7 @@ export class AutomationPreviewController { if (error instanceof EntryReadError && (error.code === 'forbidden' || error.code === 'authentication_required')) { this.granted = false; this.ready = null; + this.replacement = null; this.publish({state: 'denied'}); } else failure(); return; @@ -133,7 +154,8 @@ export class AutomationPreviewController { this.update({...current, catalogUnavailable: false, busy: 'products', issue: null}); await this.settle(this.inventory.read(this.scope!, after), report => { const products = report.products.map(({id, name}) => ({id, name})); - this.update({...current, catalog: {products, after, next: report.cursor}, catalogUnavailable: false, issue: null}); + const selected = products.find(product => product.id === current.selected?.id) ?? current.selected; + this.update({...current, selected, catalog: {products, after, next: report.cursor}, catalogUnavailable: false, issue: null}); }, () => this.update({...current, catalogUnavailable: true, issue: null})); } diff --git a/frontend/src/composition/entry-page.ts b/frontend/src/composition/entry-page.ts index 2a5f15a2..4a99ccc6 100644 --- a/frontend/src/composition/entry-page.ts +++ b/frontend/src/composition/entry-page.ts @@ -4,6 +4,10 @@ import type {TaskOverview} from '../application/task-overview'; import {HttpAutomationPreview} from '../adapters/automation-preview-http'; import {AutomationPreviewController} from '../application/automation-preview'; import type {AutomationPreviewIntent} from '../application/automation-preview'; +import {HttpAutomationDrafts} from '../adapters/automation-draft-http'; +import {AUTOMATION_DRAFT_JOURNAL_KEY, AutomationDraftSessionJournal} from '../adapters/automation-draft-journal'; +import {AutomationDraftController} from '../application/automation-drafts'; +import type {AutomationDraftIntent} from '../application/automation-drafts'; import type {StockAttention} from '../application/stock-attention'; import type {ShoppingAttention} from '../application/shopping-attention'; import {HttpInventoryServer} from '../adapters/inventory-http'; @@ -217,6 +221,7 @@ export function mountEntry(page: EntryPage): PageMount { let inventory: InventoryController | null = null; let taskOverview: OverviewReadController | null = null; let automationPreview: AutomationPreviewController | null = null; + let automationDrafts: AutomationDraftController | null = null; let stockAttention: OverviewReadController | null = null; let shoppingAttention: OverviewReadController | null = null; let familyOverview: OverviewReadController | null = null; @@ -226,7 +231,7 @@ export function mountEntry(page: EntryPage): PageMount { let localeOwner:string|null=null,preferenceIdentity:string|null=null,hadPreference=false,temporaryLanguage=false,temporaryContext:string|null=null; const dispose = () => { if (stopped) return; - stopped = true; widget.abort(); lifetime.abort(); runtime?.dispose(); calendar?.bind(null); family?.bind(null); rewards?.bind(null); inventory?.bind(null); allocation?.bind(null); calendarPreference?.bind(null); review?.bind(null); taskOverview?.bind(null); automationPreview?.bind(null); error?.remove(); + stopped = true; widget.abort(); lifetime.abort(); runtime?.dispose(); calendar?.bind(null); family?.bind(null); rewards?.bind(null); inventory?.bind(null); allocation?.bind(null); calendarPreference?.bind(null); review?.bind(null); taskOverview?.bind(null); automationPreview?.bind(null); automationDrafts?.bind(null); error?.remove(); stockAttention?.bind(null); shoppingAttention?.bind(null); familyOverview?.bind(null); if (mounts.get(doc) === dispose) mounts.delete(doc); }; @@ -236,7 +241,7 @@ export function mountEntry(page: EntryPage): PageMount { }, {signal: lifetime.signal}); const fail = () => { if (stopped || error !== null) return; - widget.abort(); runtime?.dispose(); calendar?.bind(null); family?.bind(null); rewards?.bind(null); inventory?.bind(null); allocation?.bind(null); calendarPreference?.bind(null); review?.bind(null); taskOverview?.bind(null); automationPreview?.bind(null); app?.remove(); + widget.abort(); runtime?.dispose(); calendar?.bind(null); family?.bind(null); rewards?.bind(null); inventory?.bind(null); allocation?.bind(null); calendarPreference?.bind(null); review?.bind(null); taskOverview?.bind(null); automationPreview?.bind(null); automationDrafts?.bind(null); app?.remove(); stockAttention?.bind(null); shoppingAttention?.bind(null); familyOverview?.bind(null); const locale = language(null, page.navigator.language); doc.documentElement.lang = locale; error = doc.createElement('main'); error.id = 'domus-entry-error'; @@ -494,20 +499,30 @@ export function mountEntry(page: EntryPage): PageMount { const automation = new AutomationPreviewController(new HttpAutomationPreview(source.target, browser.transport), inventoryServer, view => {element.automationPreview = view;}); automationPreview = automation; + const drafts = new AutomationDraftController(new HttpAutomationDrafts(source.target, browser.transport), + new AutomationDraftSessionJournal({getItem:key => browser.storage().getItem(key), + setItem:(key,value) => browser.storage().setItem(key,value), removeItem:key => browser.storage().removeItem(key)}), + new BrowserEntropy(browser.random), rule => automation.replaceDraft(rule), view => {element.automationDrafts = view;}); + automationDrafts = drafts; const syncAutomation = () => { const entry = element.view, member = element.administration?.access?.member; if (entry?.phase === 'ready' && entry.notice !== 'context_changed' && entry.decision?.householdReadable && entry.session && entry.household && member) { const {context} = entry.session, {householdId} = entry.household; const key = JSON.stringify([context.installationId, context.channel, context.subject, householdId, member.memberId]); - automation.bind({key, context, householdId, readOnly: entry.decision.readOnly}, - element.workspaceDestination === 'household'); - } else automation.bind(null); + const visible = element.workspaceDestination === 'household', readOnly = entry.decision.readOnly; + automation.bind({key, context, householdId, readOnly}, visible); + drafts.bind({key, context, memberId: member.memberId, readOnly}, visible); + } else {automation.bind(null); drafts.bind(null);} }; element.addEventListener('domus-automation-preview-intent', event => { if (event.target !== element) return; void automation.handle((event as CustomEvent).detail); }, {signal: widget.signal}); + element.addEventListener('domus-automation-draft-intent', event => { + if (event.target !== element) return; + void drafts.handle((event as CustomEvent).detail, automation.draft()); + }, {signal: widget.signal}); const syncWorkspace = () => { const fragment = new URL(page.location.href).hash; element.shoppingTarget = /^#inventory-shopping\/((?:product|extra):[A-Za-z0-9][A-Za-z0-9_.:-]{0,127})$/u.exec(fragment)?.[1] ?? null; @@ -573,6 +588,7 @@ export function mountEntry(page: EntryPage): PageMount { storage.removeItem(INVENTORY_JOURNAL_KEY); storage.removeItem(CALENDAR_JOURNAL_KEY); storage.removeItem(RECURRENCE_JOURNAL_KEY); + storage.removeItem(AUTOMATION_DRAFT_JOURNAL_KEY); await signOut; break; } diff --git a/frontend/src/presentation/domus-app.ts b/frontend/src/presentation/domus-app.ts index d511fa8b..0045fa4a 100644 --- a/frontend/src/presentation/domus-app.ts +++ b/frontend/src/presentation/domus-app.ts @@ -12,6 +12,8 @@ import './domus-task-overview'; import type {TaskOverviewView} from '../application/task-overview'; import './domus-automation-preview'; import type {AutomationPreviewView} from '../application/automation-preview'; +import './domus-automation-drafts'; +import type {AutomationDraftView} from '../application/automation-drafts'; import './domus-stock-attention'; import type {StockAttentionView} from '../application/stock-attention'; import './domus-shopping-attention'; @@ -51,7 +53,7 @@ export type EntryIntent = Readonly<{type: 'refresh' | 'request_membership' | 'lo /** Owned rendering only; intents cross a semantic boundary and never grant command authority. */ export class DomusApp extends LitElement { static properties = {inventory: {attribute:false}, rewards: {attribute:false}, allocation: {attribute:false}, family: {attribute:false}, familyScopeKey: {attribute:false}, familyToday: {attribute:false}, recurrenceReview: {attribute:false}, calendar: {attribute:false}, calendarPreference: {attribute:false}, calendarScopeKey: {attribute:false}, calendarToday: {attribute:false}, tasks: {attribute: false}, view: {attribute: false}, administration: {attribute:false}, deployment: {attribute: false}, language: {attribute: false}, - taskOverview: {attribute: false}, automationPreview: {attribute: false}, stockAttention: {attribute: false}, shoppingAttention: {attribute: false}, familyOverview: {attribute: false}, + taskOverview: {attribute: false}, automationPreview: {attribute: false}, automationDrafts: {attribute: false}, stockAttention: {attribute: false}, shoppingAttention: {attribute: false}, familyOverview: {attribute: false}, workspaceDestination: {attribute: false}, nameDraft: {state: true}, zoneDraft: {state: true}}; static styles = styles; declare view: EntryView | null; @@ -59,6 +61,7 @@ export class DomusApp extends LitElement { declare tasks: TaskView | null; declare taskOverview: TaskOverviewView | null; declare automationPreview: AutomationPreviewView | null; + declare automationDrafts: AutomationDraftView | null; declare stockAttention: StockAttentionView | null; declare shoppingAttention: ShoppingAttentionView | null; declare familyOverview: FamilyOverviewView | null; @@ -86,6 +89,7 @@ export class DomusApp extends LitElement { this.recurrenceReview = null; this.calendar = null; this.calendarPreference = null; this.calendarScopeKey = null; this.calendarToday = DATE_MIN; this.family = null; this.rewards = null; this.inventory = null; this.allocation = null; this.familyScopeKey = null; this.familyToday = DATE_MIN; this.workspaceDestination = null; this.taskOverview = null; this.automationPreview = null; this.nameDraft = ''; this.zoneDraft = ''; + this.automationDrafts = null; this.stockAttention = null; this.shoppingAttention = null; this.familyOverview = null; } disconnectedCallback(): void {super.disconnectedCallback(); this.dispatchEvent(new Event('domus-detached'));} @@ -194,6 +198,10 @@ export class DomusApp extends LitElement { } protected render() { const view = this.view, closed = view?.phase === 'closed'; + const drafts = this.automationDrafts; + // An initial list can restore an uncertain save, including after retrying a failed load. + const draftEditorLocked = drafts?.state === 'loading' || drafts?.state === 'unavailable' + || (drafts?.state === 'ready' && (drafts.busy || drafts.pending || drafts.locked !== null)); const loading = view === null || view.phase === 'idle' || view.phase === 'loading' || view.phase === 'sending'; const workspace = this.hasWorkspace(); const decision = view?.decision, state = decision?.state ?? 'unavailable'; @@ -267,7 +275,10 @@ export class DomusApp extends LitElement {
- + + diff --git a/frontend/src/presentation/domus-automation-drafts.ts b/frontend/src/presentation/domus-automation-drafts.ts new file mode 100644 index 00000000..fa62ba36 --- /dev/null +++ b/frontend/src/presentation/domus-automation-drafts.ts @@ -0,0 +1,157 @@ +import {LitElement, css, html, nothing} from 'lit'; +import type {TemplateResult} from 'lit'; +import {registerButton} from '@vypdev/ha-ui/button'; +import {buttonState} from '@vypdev/ha-ui/button-contracts'; +import {registerCard} from '@vypdev/ha-ui/card'; +import {cardState} from '@vypdev/ha-ui/card-contracts'; +import {registerFeedback} from '@vypdev/ha-ui/feedback'; +import {feedbackState} from '@vypdev/ha-ui/feedback-contracts'; +import type {AutomationDraftIntent, AutomationDraftView, DraftCondition} from '../application/automation-drafts'; +import type {Language} from './messages'; + +const COPY = { + en: { + heading: 'Automation drafts', loading: 'Loading automation drafts…', + empty: 'Enter a task title above and save your first draft.', + first: 'First drafts', next: 'Next drafts', retry: 'Try again', open: 'Open', + save: 'Save draft', new: 'New draft', revision: 'Revision', inactive: 'Inactive', + denied: 'Your current household permissions do not allow access to automation drafts.', + unavailable: 'Automation drafts are unavailable. Try again.', + invalid_title: 'Enter a task title of 1 to 160 characters.', + uncertain: 'The save result is uncertain. Check the original request to recover it.', + rejected: 'The draft could not be saved. Check its title and selected product and try again.', + conflict: 'Another save changed this draft. Review its latest revision before saving your edits.', + saved: 'Draft saved.', historical: 'This save was processed before restoration. Review the current draft list.', + recover: 'Check original save', review: 'Review latest revision', rebase: 'Keep edits on latest revision', + current: 'Current draft', operation: 'Operation ID', busy: 'Checking automation drafts…', + noCondition: 'No stock condition', + complex: 'This draft uses grouped conditions. You can open and preview the saved rule here.', + product: 'Stock below minimum', all: 'All conditions', any: 'Any condition', not: 'Negated condition', + preview_saved: 'Preview saved rule', wouldCreate: 'Would create this task', noAction: 'No task would be created', + readOnly: 'Saving drafts is unavailable in the current read-only session.', + }, + es: { + heading: 'Borradores de automatización', loading: 'Cargando borradores de automatización…', + empty: 'Introduce un título de tarea arriba y guarda tu primer borrador.', + first: 'Primeros borradores', next: 'Siguientes borradores', retry: 'Volver a intentar', open: 'Abrir', + save: 'Guardar borrador', new: 'Nuevo borrador', revision: 'Revisión', inactive: 'Inactivo', + denied: 'Tus permisos actuales del hogar no permiten acceder a los borradores de automatización.', + unavailable: 'Los borradores de automatización no están disponibles. Vuelve a intentarlo.', + invalid_title: 'Introduce un título de tarea de 1 a 160 caracteres.', + uncertain: 'No se pudo confirmar el guardado. Consulta la solicitud original para recuperarlo.', + rejected: 'No se pudo guardar el borrador. Revisa el título y el producto seleccionado y vuelve a intentarlo.', + conflict: 'Otro guardado cambió este borrador. Revisa la última revisión antes de guardar tus cambios.', + saved: 'Borrador guardado.', historical: 'El guardado se procesó antes de la restauración. Revisa la lista actual de borradores.', + recover: 'Consultar guardado original', review: 'Revisar la última revisión', rebase: 'Mantener mis cambios sobre la última revisión', + current: 'Borrador actual', operation: 'Identificador de operación', busy: 'Consultando borradores…', + noCondition: 'Sin condición de existencias', + complex: 'Este borrador usa condiciones agrupadas. Aquí puedes abrir y previsualizar la regla guardada.', + product: 'Existencias por debajo del mínimo', all: 'Todas las condiciones', any: 'Cualquier condición', not: 'Negación de la condición', + preview_saved: 'Previsualizar regla guardada', wouldCreate: 'Se crearía esta tarea', noAction: 'No se crearía ninguna tarea', + readOnly: 'El guardado de borradores no está disponible en esta sesión de solo lectura.', + }, +} as const; + +type CopyKey = keyof typeof COPY.en; +type Ready = Extract; + +export class DomusAutomationDrafts extends LitElement { + static properties = {view: {attribute: false}, language: {attribute: false}, canEdit: {attribute: false}}; + static styles = css` + :host {display:block;--vyp-ha-surface:var(--surface);--vyp-ha-surface-raised:var(--surface);--vyp-ha-text:var(--text); + --vyp-ha-text-secondary:var(--muted);--vyp-ha-border:var(--line);--vyp-ha-primary:var(--accent); + --vyp-ha-on-accent:var(--surface);--vyp-ha-focus-ring:3px solid var(--accent)} + vyp-ha-card {margin-block-end:16px} + .content, .drafts {display:grid;gap:10px} + .actions, .draft {display:flex;align-items:center;flex-wrap:wrap;gap:8px} + .draft {justify-content:space-between;border-block-start:1px solid var(--line);padding-block-start:8px} + .draft p {flex:1 1 17rem} + p,ul {margin:0;overflow-wrap:anywhere} + .drafts {list-style:none;padding:0} + `; + + declare view: AutomationDraftView | null; + declare language: Language; + declare canEdit: boolean; + + constructor() {super(); this.view = null; this.language = 'en'; this.canEdit = false;} + + private text(key: CopyKey): string {return COPY[this.language][key];} + + private button(key: CopyKey, intent: AutomationDraftIntent, disabled: boolean, title?: string) { + const label = title === undefined ? this.text(key) : this.text(key) + ' ' + title.replace(/[\u007f-\u009f]/gu, '�'); + return html` this.dispatchEvent(new CustomEvent( + 'domus-automation-draft-intent', {detail: intent, bubbles: true, composed: true}))}>`; + } + + private feedback(key: CopyKey, loading = false) { + return html``; + } + + private describe(condition: DraftCondition): TemplateResult { + switch (condition.kind) { + case 'stock_below_minimum': + return html`
  • ${this.text('product')} · ${condition.product_id}
  • `; + case 'not': + return html`
  • ${this.text('not')}
      ${this.describe(condition.child)}
  • `; + default: + return html`
  • ${this.text(condition.kind)}
      ${condition.children.map(value => this.describe(value))}
  • `; + } + } + + private controls(view: Ready) { + const busy = view.busy || view.pending; + return html`
    + ${this.button('save', {type: 'save'}, busy || view.readOnly || !this.canEdit || view.locked !== null || view.conflict)} + ${view.selected === null ? nothing : this.button('new', {type: 'new'}, busy || !this.canEdit)} + ${view.pending ? this.button('recover', {type: 'recover'}, view.busy) : nothing} +
    + ${view.selected === null ? nothing : html`

    ${this.text('current')} · + ${this.text('revision')} ${view.selected.revision} · ${this.text('inactive')}

    `} + ${view.readOnly ? html`

    ${this.text('readOnly')}

    ` : nothing} + ${view.busy ? this.feedback('busy', true) : nothing} + ${view.notice === null ? nothing : this.feedback(view.notice)} + ${view.operationId === null ? nothing : html`

    ${this.text('operation')} ${view.operationId}

    `} + ${view.conflict ? this.button('review', {type: 'review'}, busy) : nothing} + ${view.competing === null ? nothing : html`
    +

    ${view.competing.title} · ${this.text('revision')} ${view.competing.revision}

    + ${view.competing.condition === null ? html`

    ${this.text('noCondition')}

    ` + : html`
      ${this.describe(view.competing.condition)}
    `} +
    ${this.button('rebase', {type: 'rebase'}, busy || view.readOnly || !this.canEdit + || (view.competing.condition !== null && view.competing.condition.kind !== 'stock_below_minimum'))}
    +
    `} + ${view.locked === null ? nothing : html`

    ${view.locked.title}

    +

    ${this.text('complex')}

    +
      ${view.locked.condition === null ? nothing : this.describe(view.locked.condition)}
    +
    ${this.button('preview_saved', {type: 'preview_saved'}, busy || !this.canEdit)}
    + ${view.preview === null ? nothing : html`

    ${this.text(view.preview ? 'wouldCreate' : 'noAction')}

    `}`} + ${view.page.drafts.length === 0 ? html`

    ${this.text('empty')}

    ` : html`
      + ${view.page.drafts.map(draft => html`
    • +

      ${draft.title} · ${this.text('revision')} ${draft.revision} · ${this.text('inactive')}

      + ${this.button('open', {type: 'open', id: draft.id}, busy, draft.title)} +
    • `)} +
    `} + ${view.after !== null || view.page.next !== null ? html`
    + ${view.after === null ? nothing : this.button('first', {type: 'first'}, view.busy)} + ${view.page.next === null ? nothing : this.button('next', {type: 'next'}, view.busy)} +
    ` : nothing}`; + } + + protected render() { + const view = this.view; + if (view === null) return nothing; + return html` +
    ${view.state === 'ready' ? this.controls(view) + : this.feedback(view.state, view.state === 'loading')} + ${view.state === 'unavailable' ? this.button('retry', {type: 'retry'}, false) : nothing}
    +
    `; + } +} + +registerButton(); registerCard(); registerFeedback(); +customElements.define('domus-automation-drafts', DomusAutomationDrafts); +declare global {interface HTMLElementTagNameMap {'domus-automation-drafts': DomusAutomationDrafts;}} diff --git a/frontend/src/presentation/domus-automation-preview.ts b/frontend/src/presentation/domus-automation-preview.ts index e4a594c0..2ffacb5e 100644 --- a/frontend/src/presentation/domus-automation-preview.ts +++ b/frontend/src/presentation/domus-automation-preview.ts @@ -75,7 +75,7 @@ const COPY = { type CopyKey = keyof typeof COPY.en; export class DomusAutomationPreview extends LitElement { - static properties = {view: {attribute: false}, language: {attribute: false}}; + static properties = {view: {attribute: false}, language: {attribute: false}, locked: {attribute: false}}; static styles = css` :host {display:block;--vyp-ha-surface:var(--surface);--vyp-ha-surface-raised:var(--surface);--vyp-ha-text:var(--text); --vyp-ha-text-secondary:var(--muted);--vyp-ha-border:var(--line);--vyp-ha-primary:var(--accent); @@ -91,8 +91,9 @@ export class DomusAutomationPreview extends LitElement { declare view: AutomationPreviewView | null; declare language: Language; + declare locked: boolean; - constructor() {super(); this.view = null; this.language = 'en';} + constructor() {super(); this.view = null; this.language = 'en'; this.locked = false;} private text(key: CopyKey): string {return COPY[this.language][key];} @@ -119,7 +120,7 @@ export class DomusAutomationPreview extends LitElement { } private form(view: Extract) { - const blocked = view.busy !== null; + const blocked = view.busy !== null || this.locked; const products = new Map(view.catalog.products.map(product => [product.id, product])); if (view.selected !== null) products.set(view.selected.id, view.selected); const options = Array.from(products.values(), product => ({ diff --git a/frontend/tests/automation-drafts.test.ts b/frontend/tests/automation-drafts.test.ts new file mode 100644 index 00000000..44494c86 --- /dev/null +++ b/frontend/tests/automation-drafts.test.ts @@ -0,0 +1,360 @@ +import {afterEach, expect, test, vi} from 'vitest'; +import {HttpAutomationDrafts} from '../src/adapters/automation-draft-http'; +import {AUTOMATION_DRAFT_JOURNAL_KEY, AutomationDraftSessionJournal} from '../src/adapters/automation-draft-journal'; +import {AutomationDraftController} from '../src/application/automation-drafts'; +import type {AutomationDraftServer, AutomationDraftView, DraftCondition, DraftOutcome, DraftPage, DraftRequest, SavedAutomationDraft} from '../src/application/automation-drafts'; +import {EntryReadError} from '../src/application/ports'; +import {revisionValue} from '../src/domain/administration'; +import '../src/presentation/domus-automation-drafts'; + +const context = {installationId: '01234567-89ab-cdef-0123-456789abcdef', channel: 'edge' as const, subject: 'a'.repeat(32)}; +const scope = {key: 'private-scope', context, memberId: 'member', readOnly: false}; +const idea = {title: 'Buy tea', productId: 'tea'}; +const first = {id: 'draft-1', title: 'Buy tea', revision: revisionValue('1')}; +const second = {...first, revision: revisionValue('2'), title: 'Prepare tea'}; +const request: DraftRequest = {key: 'exact-request', scope: scope.key, ruleId: null, revision: '0', rule: idea}; +const grouped: DraftCondition = {kind: 'all', children: [{kind: 'not', child: {kind: 'stock_below_minimum', product_id: 'milk'}}, + {kind: 'any', children: [{kind: 'stock_below_minimum', product_id: 'tea'}]}]}; +const settled = (value: T) => ({result: Promise.resolve(value), cancel: vi.fn()}); +const failed = (error = new Error('network')) => ({result: Promise.reject(error), cancel: vi.fn()}); +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + const result = new Promise((done, fail) => {resolve = done; reject = fail;}); + return {result, resolve, reject, cancel: vi.fn()}; +} +function setup() { + const storage = new Map(); + const journal = new AutomationDraftSessionJournal({ + getItem: key => storage.get(key) ?? null, + setItem: (key, value) => {storage.set(key, value);}, + removeItem: key => {storage.delete(key);}, + }); + const page: DraftPage = {drafts: [first], next: 'more'}; + const server = { + list: vi.fn(() => settled(page)), + reopen: vi.fn(() => settled({...first, condition: null})), + previewSaved: vi.fn(() => settled(true)), + send: vi.fn(() => settled({kind: 'rejected'})), + original: vi.fn(() => settled({kind: 'missing'})), + }; + const edit = vi.fn(), publish = vi.fn(), counter = {value: 0}; + const controller = () => new AutomationDraftController(server, journal, + {requestKey: () => 'req-' + ++counter.value}, edit, publish); + return {storage, journal, page, server, edit, publish, controller}; +} + +test('open, page, edit and resolve conflicts while preserving entered values', async () => { + const {server, controller, edit, publish} = setup(); + const drafts = controller(); + await drafts.handle({type: 'save'}, idea); + drafts.bind(scope, true); + await vi.waitFor(() => expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({state: 'ready', busy: false}))); + await drafts.handle({type: 'first'}, null); + await drafts.handle({type: 'next'}, null); + expect(server.list).toHaveBeenLastCalledWith(scope, 'more'); + await drafts.handle({type: 'first'}, null); + expect(server.list).toHaveBeenLastCalledWith(scope, null); + await drafts.handle({type: 'open', id: 'outside-page'}, null); + expect(server.reopen).not.toHaveBeenCalled(); + await drafts.handle({type: 'open', id: first.id}, null); + expect(edit).toHaveBeenLastCalledWith({title: first.title, productId: null}); + await drafts.handle({type: 'save'}, {title: ' ', productId: null}); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({notice: 'invalid_title'})); + const dirty = {...idea, title: 'My revision'}; + server.send.mockReturnValueOnce(settled({kind: 'conflict'})); + await drafts.handle({type: 'save'}, dirty); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({notice: 'conflict'})); + await drafts.handle({type: 'save'}, dirty); + expect(server.send).toHaveBeenCalledOnce(); + server.reopen.mockReturnValueOnce(failed()); + await drafts.handle({type: 'review'}, null); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({notice: 'unavailable', conflict: true, competing: null})); + await drafts.handle({type: 'save'}, dirty); + expect(server.send).toHaveBeenCalledOnce(); + server.reopen.mockReturnValueOnce(settled({...second, condition: grouped})); + await drafts.handle({type: 'review'}, null); + await drafts.handle({type: 'rebase'}, null); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({notice: 'conflict'})); + server.reopen.mockReturnValueOnce(settled({...second, condition: null})); + await drafts.handle({type: 'review'}, null); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({competing: {...second, condition: null}})); + drafts.bind({...scope, readOnly: true}, true); + await drafts.handle({type: 'rebase'}, null); + expect(edit).toHaveBeenCalledOnce(); + drafts.bind(scope, true); + await drafts.handle({type: 'rebase'}, null); + await drafts.handle({type: 'save'}, dirty); + expect(server.send).toHaveBeenLastCalledWith(scope, expect.objectContaining({rule: dirty, revision: '2'})); + expect(edit).toHaveBeenCalledOnce(); + await drafts.handle({type: 'new'}, null); + expect(edit).toHaveBeenLastCalledWith({title: '', productId: null}); + server.reopen.mockReturnValueOnce(failed()); + await drafts.handle({type: 'open', id: first.id}, null); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({notice: 'unavailable'})); +}); + +test('recover an uncertain save after reload with its exact key and retire denied details', async () => { + const {server, controller, journal, edit, publish} = setup(); + const drafting = controller(); + drafting.bind(scope, true); + await vi.waitFor(() => expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({busy: false}))); + server.send.mockReturnValueOnce(failed()); + await drafting.handle({type: 'save'}, idea); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({pending: true, notice: 'uncertain'})); + const original = journal.open(scope.key); + drafting.bind(null); + const reloaded = controller(); + reloaded.bind(scope, true); + await vi.waitFor(() => expect(edit).toHaveBeenLastCalledWith(idea)); + await reloaded.handle({type: 'new'}, null); + expect(edit).toHaveBeenCalledOnce(); + reloaded.bind({...scope, readOnly: true}, true); + await reloaded.handle({type: 'recover'}, null); + expect(server.send).toHaveBeenCalledOnce(); + reloaded.bind(scope, true); + server.send.mockReturnValueOnce(settled({kind: 'committed', id: first.id, revision: first.revision, operationId: 'operation'})); + await reloaded.handle({type: 'recover'}, null); + expect(server.original).toHaveBeenLastCalledWith(scope, original); + expect(server.send).toHaveBeenLastCalledWith(scope, original); + expect(journal.open(scope.key)).toBeNull(); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({pending: false, notice: 'saved', operationId: 'operation'})); + + server.send.mockReturnValueOnce(failed()); + await reloaded.handle({type: 'save'}, idea); + server.original.mockReturnValueOnce(settled({kind: 'historical', id: first.id, revision: second.revision, + operationId: 'before-restore'})); + await reloaded.handle({type: 'recover'}, null); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({selected: null, notice: 'historical'})); + server.send.mockReturnValueOnce(failed()); + await reloaded.handle({type: 'save'}, idea); + server.original.mockReturnValueOnce(failed(new EntryReadError('forbidden'))); + await reloaded.handle({type: 'recover'}, null); + expect(publish).toHaveBeenLastCalledWith({state: 'denied'}); + expect(edit).toHaveBeenLastCalledWith({title: '', productId: null}); + expect(journal.open(scope.key)).toBeNull(); +}); + +test('retain the saved grouped condition and preview it without allowing replacement', async () => { + const {controller, server, publish} = setup(); + const drafts = controller(); + const saved = {...first, condition: grouped}; + server.reopen.mockReturnValue(settled(saved)); + drafts.bind(scope, true); + await vi.waitFor(() => expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({busy: false}))); + await drafts.handle({type: 'open', id: first.id}, null); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({locked: saved})); + await drafts.handle({type: 'save'}, idea); + expect(server.send).not.toHaveBeenCalled(); + server.previewSaved.mockReturnValueOnce(failed()); + await drafts.handle({type: 'preview_saved'}, null); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({notice: 'unavailable'})); + await drafts.handle({type: 'preview_saved'}, null); + expect(server.previewSaved).toHaveBeenLastCalledWith(scope, saved); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({preview: true})); +}); + +test('ignore navigation-cancelled reads and fail closed on storage or request errors', async () => { + const {controller, server, storage, publish} = setup(); + const drafts = controller(), obsolete = deferred(); + server.list.mockReturnValueOnce(obsolete); + drafts.bind(scope, true); + drafts.bind(scope, false); + expect(obsolete.cancel).toHaveBeenCalledOnce(); + obsolete.reject(new Error('obsolete')); + await Promise.resolve(); + expect(publish).toHaveBeenLastCalledWith(null); + storage.set(AUTOMATION_DRAFT_JOURNAL_KEY, '{}'); + drafts.bind(scope, true); + await vi.waitFor(() => expect(publish).toHaveBeenLastCalledWith({state: 'unavailable'})); + storage.delete(AUTOMATION_DRAFT_JOURNAL_KEY); + await drafts.handle({type: 'retry'}, null); + const late = deferred(); + server.send.mockReturnValueOnce(late); + const outgoing = drafts.handle({type: 'save'}, idea); + drafts.bind(null); + late.resolve({kind: 'rejected'}); + await outgoing; + expect(publish).toHaveBeenLastCalledWith(null); + expect(storage.get(AUTOMATION_DRAFT_JOURNAL_KEY)).toContain('req-1'); +}); + +const target = {origin: 'https://domus.test', deployment: 'standalone' as const, applicationBase: '/'}; +const status = {rule_id: first.id, revision: '1', state: 'draft', enabled: false}; +const wire = {...status, version: 1, trigger: {kind: 'manual'}, condition: grouped, action: {kind: 'task.create', title: first.title}}; +const receipt = {state: 'committed', archived_by: null, operation_id: 'operation', created_at: 100, + result: {...status, member_id: scope.memberId}, message: 'Saved.', action_required: 'Retain original.'}; +const blocked = (code: string) => ({state: 'blocked', code, message: 'Blocked.', action_required: 'Review details.', correlation_id: 'cor_issue'}); +function response(path: string, value: unknown, status = 200): Response { + const reply = new Response(JSON.stringify(value), {status, + headers: {'Content-Type': 'application/json', 'Cache-Control': 'no-store'}}); + Object.defineProperty(reply, 'url', {value: target.origin + path}); + return reply; +} + +test('HTTP binds list, exact saves, complex reads and original recovery to the current context', async () => { + const transport = vi.fn(async (path: string, init: RequestInit) => { + const headers = init.headers as Headers; + expect(headers.get('X-Domus-Context')).toBe('v1:' + context.installationId + ':edge:' + context.subject); + if (path.endsWith('/csrf')) return response(path, {csrf_token: 'c'.repeat(64)}); + if (path.endsWith('?cursor=opaque%3D')) return response(path, {drafts: [{...status, title: first.title}], next_cursor: 'next'}); + if (path.endsWith(first.id)) return response(path, wire); + if (path.endsWith('/preview')) { + expect(JSON.parse(String(init.body)).condition).toEqual(grouped); + expect(headers.get('Idempotency-Key')).toBeNull(); + return response(path, {version: 1, trigger: 'manual', task_title: first.title, would_create: false, conditions: []}); + } + if (path.endsWith('/requests/' + request.key)) { + return response(path, {...receipt, state: 'historical', archived_by: 'backup'}); + } + expect(init.method).toBe('POST'); + expect(headers.get('Idempotency-Key')).toBe(request.key); + expect(headers.get('X-CSRF-Token')).toBe('c'.repeat(64)); + expect(JSON.parse(String(init.body))).toEqual({version: 1, trigger: wire.trigger, action: wire.action, + condition: {kind: 'stock_below_minimum', product_id: 'tea'}, rule_id: null, expected_revision: '0'}); + return response(path, receipt); + }); + const server = new HttpAutomationDrafts(target, transport); + await expect(server.list(scope, 'opaque=').result).resolves.toEqual({drafts: [first], next: 'next'}); + const draft: SavedAutomationDraft = await server.reopen(scope, first.id).result; + expect(draft).toEqual({...first, condition: grouped}); + await expect(server.previewSaved(scope, draft).result).resolves.toBe(false); + await expect(server.send(scope, request).result).resolves.toMatchObject({kind: 'committed', ...statusFact()}); + await expect(server.original(scope, request).result).resolves.toMatchObject({kind: 'historical', ...statusFact()}); + function statusFact() {return {id: first.id, revision: first.revision, operationId: 'operation'};} +}); + +test.each([ + [409, 'revision_conflict', 'conflict'], + [409, 'idempotency_conflict', 'rejected'], + [404, 'inventory_product_missing', 'rejected'], + [422, 'invalid_request', 'rejected'], +])('HTTP recognizes definite save failure %s %s', async (status, code, kind) => { + const server = new HttpAutomationDrafts(target, async path => path.endsWith('/csrf') + ? response(path, {csrf_token: 'c'.repeat(64)}) : response(path, blocked(code), status)); + await expect(server.send(scope, request).result).resolves.toEqual({kind}); +}); + +test('HTTP treats only a scoped operation 404 as missing and rejects mismatched receipts', async () => { + const server = new HttpAutomationDrafts(target, async path => response(path, blocked('operation_missing'), 404)); + await expect(server.original(scope, request).result).resolves.toEqual({kind: 'missing'}); + const denied = new HttpAutomationDrafts(target, async path => path.endsWith('/csrf') + ? response(path, {csrf_token: 'c'.repeat(64)}) : response(path, blocked('permission_denied'), 403)); + await expect(denied.send(scope, request).result).rejects.toMatchObject({code: 'forbidden'}); + await expect(denied.original(scope, request).result).rejects.toMatchObject({code: 'forbidden'}); + await expect(denied.previewSaved(scope, {...first, condition: null}).result).rejects.toMatchObject({code: 'forbidden'}); + const wrong = new HttpAutomationDrafts(target, async path => response(path, {...receipt, result: {...receipt.result, member_id: 'other'}})); + await expect(wrong.original(scope, request).result).rejects.toMatchObject({code: 'invalid_response'}); +}); + +test('session journal keeps canonical request bytes and retires another scope', () => { + const {journal, storage} = setup(); + journal.save(request); + expect(journal.open(scope.key)).toEqual(request); + expect(() => journal.save(request)).toThrow(); + expect(journal.open('other-scope')).toBeNull(); + const editRequest: DraftRequest = {...request, ruleId: first.id, revision: first.revision, rule: {...idea, productId: null}}; + journal.save(editRequest); + expect(journal.open(scope.key)).toEqual(editRequest); + storage.set(AUTOMATION_DRAFT_JOURNAL_KEY, JSON.stringify({...editRequest, ruleId: null})); + expect(() => journal.open(scope.key)).toThrow(); +}); + +test('load and recover an existing revision and handle temporary local failures', async () => { + const {controller, server, storage, journal, edit, publish} = setup(); + const amendment: DraftRequest = {...request, ruleId: first.id, revision: first.revision}; + journal.save(amendment); + const drafts = controller(); + drafts.bind(scope, true); + await drafts.handle({type: 'save'}, null); + await vi.waitFor(() => expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({selected: firstIdentity()}))); + server.original.mockReturnValueOnce(settled({kind: 'rejected'})); + await drafts.handle({type: 'recover'}, null); + await drafts.handle({type: 'recover'}, null); + expect(server.original).toHaveBeenCalledOnce(); + server.reopen.mockReturnValueOnce(settled({...first, condition: {kind: 'stock_below_minimum', product_id: 'tea'}})); + await drafts.handle({type: 'open', id: first.id}, null); + expect(edit).toHaveBeenLastCalledWith(idea); + storage.set(AUTOMATION_DRAFT_JOURNAL_KEY, '{}'); + await drafts.handle({type: 'save'}, idea); + expect(server.send).not.toHaveBeenCalled(); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({notice: 'unavailable'})); + server.list.mockReturnValueOnce(failed()); + await drafts.handle({type: 'retry'}, null); + expect(publish).toHaveBeenLastCalledWith(expect.objectContaining({state: 'ready', notice: 'unavailable'})); + storage.delete(AUTOMATION_DRAFT_JOURNAL_KEY); + server.list.mockReturnValueOnce(failed(new EntryReadError('forbidden'))); + await drafts.handle({type: 'retry'}, null); + expect(publish).toHaveBeenLastCalledWith({state: 'denied'}); + await drafts.handle({type: 'open', id: first.id}, null); + expect(server.reopen).toHaveBeenCalledOnce(); + function firstIdentity() {return {id: first.id, revision: first.revision};} +}); + +test('HTTP reopens a simple rule and checks the revision on an edit receipt', async () => { + const server = new HttpAutomationDrafts(target, async path => { + if (path.endsWith(first.id)) return response(path, {...wire, condition: null}); + if (path.endsWith('/drafts')) return response(path, {drafts: [], next_cursor: null}); + return response(path, {...receipt, archived_by: 'rollback', result: {...receipt.result, revision: '2'}}); + }); + await expect(server.list(scope, null).result).resolves.toEqual({drafts: [], next: null}); + await expect(server.reopen(scope, first.id).result).resolves.toEqual({...first, condition: null}); + await expect(server.original(scope, {...request, ruleId: first.id, revision: first.revision}).result) + .resolves.toMatchObject({kind: 'committed', revision: second.revision, id: first.id}); +}); + +afterEach(() => document.querySelectorAll('domus-automation-drafts').forEach(element => element.remove())); + +test('draft interface exposes localized inactive revisions, recovery and explicit review', async () => { + const element = document.createElement('domus-automation-drafts'); + document.body.append(element); + const event = vi.fn(); + element.addEventListener('domus-automation-draft-intent', event); + await element.updateComplete; + expect(element.shadowRoot!.textContent!.trim()).toBe(''); + const ready: Extract = {state: 'ready', page: {drafts: [first], next: 'next'}, + after: null, selected: first, locked: null, competing: secondWithGroup(), operationId: 'operation', preview: null, + busy: false, pending: false, conflict: true, readOnly: false, notice: 'conflict'}; + element.view = ready; + element.canEdit = true; + await element.updateComplete; + const root = element.shadowRoot!; + expect(root.textContent).toContain('Inactive'); + expect(root.textContent).toContain('operation'); + expect(root.textContent).toContain('Any condition'); + expect(root.textContent).toContain('Stock below minimum · milk'); + const buttons = [...root.querySelectorAll('vyp-ha-button')]; + expect(buttons[0].disabled).toBe(true); + buttons.find(button => button.state?.label === 'Review latest revision')! + .dispatchEvent(new CustomEvent('ha-press-request')); + expect(event.mock.lastCall?.[0].detail).toEqual({type: 'review'}); + element.language = 'es'; + element.view = {...ready, readOnly: true, busy: true, pending: true, notice: 'uncertain', + locked: secondWithGroup(), preview: false, after: 'previous'}; + await element.updateComplete; + expect(root.textContent).toContain('Cualquier condición'); + expect(root.textContent).toContain('No se crearía ninguna tarea'); + expect(root.textContent).toContain('sesión de solo lectura'); + for (const state of ['loading', 'denied', 'unavailable'] as const) { + element.view = {state}; + await element.updateComplete; + expect(root.querySelectorAll('vyp-ha-feedback')).toHaveLength(1); + } + element.view = {...ready, page: {drafts: [], next: null}, after: 'previous', notice: 'saved', competing: null}; + await element.updateComplete; + expect(root.textContent).toContain('guarda tu primer borrador'); + element.view = {...ready, selected: null, notice: null, operationId: null, competing: null, + after: null, page: {drafts: [], next: null}}; + await element.updateComplete; + expect(root.textContent).not.toContain('Borrador actual'); + element.view = {...ready, locked: {...first, condition: null}, notice: null, preview: null}; + await element.updateComplete; + expect(root.textContent).toContain('condiciones agrupadas'); + element.view = {...ready, locked: secondWithGroup(), preview: true}; + await element.updateComplete; + expect(root.textContent).toContain('Se crearía esta tarea'); + element.view = {...ready, competing: {...second, condition: null}}; + await element.updateComplete; + expect(root.textContent).toContain('Sin condición de existencias'); + function secondWithGroup(): SavedAutomationDraft {return {...second, condition: grouped};} +}); diff --git a/frontend/tests/automation-preview.test.ts b/frontend/tests/automation-preview.test.ts index 583506ac..3b25e192 100644 --- a/frontend/tests/automation-preview.test.ts +++ b/frontend/tests/automation-preview.test.ts @@ -20,6 +20,30 @@ const ready = (overrides: Partial { + const catalog = deferred(); + const read = vi.fn().mockReturnValueOnce(catalog).mockImplementationOnce(() => settled(page([coffee], null))); + const publish = vi.fn(); + const controller = new AutomationPreviewController({access: () => settled(undefined), + preview: () => settled(true)}, {read}, publish); + expect(controller.draft()).toBeNull(); + controller.bind(scope, true); + await vi.waitFor(() => expect(read).toHaveBeenCalledOnce()); + controller.replaceDraft({title: 'Reopened', productId: 'coffee'}); + expect(controller.draft()).toBeNull(); + catalog.resolve(page([tea], 'next')); + await vi.waitFor(() => expect(controller.draft()).toEqual({title: 'Reopened', productId: 'coffee'})); + expect(publish.mock.lastCall?.[0].selected).toEqual({id: 'coffee', name: 'coffee'}); + await controller.handle({type: 'next'}); + expect(publish.mock.lastCall?.[0].selected).toEqual(coffee); + controller.replaceDraft({title: 'Another draft', productId: 'coffee'}); + expect(publish.mock.lastCall?.[0].selected).toEqual(coffee); + controller.replaceDraft({title: '', productId: null}); + expect(controller.draft()).toEqual({title: '', productId: null}); + controller.bind(null); + expect(controller.draft()).toBeNull(); +}); + function deferred() { let resolve!: (value: T) => void; let reject!: (error: unknown) => void; diff --git a/frontend/tests/component.test.ts b/frontend/tests/component.test.ts index d7295848..42d9b9b5 100644 --- a/frontend/tests/component.test.ts +++ b/frontend/tests/component.test.ts @@ -1,3 +1,4 @@ +import type {AutomationDraftView} from '../src/application/automation-drafts'; import type {TaskView} from '../src/application/task-controller'; import {revisionValue} from '../src/domain/administration'; import {afterEach, expect, test} from 'vitest'; @@ -79,6 +80,24 @@ test('a labeled setup form preserves exact draft values and emits only an explic expect(f.root.querySelector('#name')!.value).toBe(' Family 🏠 '); expect(f.root.querySelector('#time_zone')!.value).toBe('Europe/Madrid'); }); +test('automation editor waits for draft restoration and only unlocks when editing can resume', async () => { + const {element, root} = await mount(view('active')); + const preview = root.querySelector('domus-automation-preview')!; + const ready = {state: 'ready', page: {drafts: [], next: null}, after: null, selected: null, + locked: null, competing: null, conflict: false, operationId: null, preview: null, busy: false, pending: false, + readOnly: false, notice: null} satisfies AutomationDraftView; + const states: [AutomationDraftView | null, boolean][] = [ + [null, false], [{state: 'loading'}, true], [{state: 'unavailable'}, true], + [{state: 'denied'}, false], [ready, false], [{...ready, busy: true}, true], + [{...ready, pending: true}, true], + [{...ready, locked: {id: 'draft', revision: revisionValue('1'), title: 'Restock', condition: null}}, true], + ]; + for (const [drafts, locked] of states) { + element.automationDrafts = drafts; + await element.updateComplete; + expect(preview.locked).toBe(locked); + } +}); test('validation focuses the associated first error, without focusing a hidden form in another state', async () => { const f = await mount(view()); f.element.view = view('unconfigured', {fields: ['name', 'time_zone']}); await f.element.updateComplete; diff --git a/frontend/tests/e2e/administration.spec.ts b/frontend/tests/e2e/administration.spec.ts index e66234c9..3ef67de7 100644 --- a/frontend/tests/e2e/administration.spec.ts +++ b/frontend/tests/e2e/administration.spec.ts @@ -96,6 +96,7 @@ for(const mode of ['native','standalone'] as const)test.describe('administration let release!:()=>void,arrived!:()=>void,count=0; const gate=new Promise(resolve=>{release=resolve;}),ready=new Promise(resolve=>{arrived=resolve;}); const writes:{index:number;key:string;body:string|null;status:number;code:string|null}[]=[],lookups:string[]=[]; + const unavailableAuthorization=new Set(); const pages=[page,other],names=['Independent house A','Independent house B'],horizons=[14,31]; const folds=['second_instant','first_instant']; try{ @@ -110,6 +111,12 @@ for(const mode of ['native','standalone'] as const)test.describe('administration const before=await statistics(request,mode); for(const [index,candidate]of pages.entries()){ candidate.on('request',item=>{if(item.url().includes('/administration/requests/')||item.url().includes('/operations/'))lookups.push(item.url());}); + candidate.on('response',async response=>{ + if(response.url()===base(mode)+'/api/v1/authorization'&&response.status()===503){ + const body=await response.json(); + if(body.code==='storage_busy')unavailableAuthorization.add(index); + } + }); await candidate.route(base(mode)+'/api/v1/household',async route=>{ if(route.request().method()!=='PUT')return route.continue(); const original={index,key:route.request().headers()['idempotency-key'],body:route.request().postData()}; @@ -138,13 +145,18 @@ for(const mode of ['native','standalone'] as const)test.describe('administration const unavailable=widgets[loser.index].getByRole('status') .filter({has:pages[loser.index].getByRole('heading',{name:'Household administration',level:2,exact:true})}) .getByText('The requested information is unavailable. Refresh or check the original request again.',{exact:true}); - await expect(rejected.or(unavailable)).toBeVisible(); + const householdUnavailable=pages[loser.index].getByRole('region',{name:'Household status unavailable',exact:true}); + await expect(rejected.or(unavailable).or(householdUnavailable)).toBeVisible(); const losingRecord=await pages[loser.index].evaluate( ({storage,key})=>JSON.parse(sessionStorage.getItem(storage)!).records.find((record:{key:string})=>record.key===key), {storage:journalKey,key:loser.key}); expect(losingRecord).toMatchObject({key:loser.key,stage:'rejected',operationId:null}); - if(await unavailable.isVisible()){ - // A follow-up authorization read can also contend with the winning transaction. + if(await householdUnavailable.isVisible()){ + // The entry workspace also refreshes authorization after the rejected write. + await expect.poll(()=>unavailableAuthorization.has(loser.index)).toBe(true); + await householdUnavailable.getByRole('button',{name:'Refresh status',exact:true}).click(); + await expect(widgets[loser.index].getByRole('button',{name:'Edit household',exact:true})).toBeEnabled(); + }else if(await unavailable.isVisible()){ await widgets[loser.index].getByRole('button',{name:'Refresh administration',exact:true}).click(); await expect(widgets[loser.index].getByRole('button',{name:'Edit household',exact:true})).toBeEnabled(); } diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index 6af45429..e62c3624 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -302,10 +302,14 @@ for (const mode of ['native', 'standalone'] as const) { }); const ledger = async () => { const result = await page.request.get(firstFamily.url(), {headers: {'X-Domus-Context': contextHeader}}); + if (result.status() === 503) { + expect((await result.json()).code).toBe('storage_busy'); + return null; + } expect(result.ok(), await result.text()).toBe(true); return result.json(); }; - await expect.poll(async () => (await ledger()).available_minor, {timeout: 15_000}).toBe(225); + await expect.poll(async () => (await ledger())?.available_minor, {timeout: 15_000}).toBe(225); const participation = overviewRegion.locator('domus-family-overview'); await page.setViewportSize({width:390,height:844}); await page.emulateMedia({colorScheme:'dark'}); @@ -345,7 +349,7 @@ for (const mode of ['native', 'standalone'] as const) { await post('occurrences/' + seeded.occurrence_id + '/reopen', 'family-reopened', { expected_revision: done.revision, cycle_id: done.cycle.cycle_id, reason: 'Check the original work', }); - await expect.poll(async () => (await ledger()).history.length, {timeout: 15_000}).toBe(2); + await expect.poll(async () => (await ledger())?.history.length, {timeout: 15_000}).toBe(2); await familyRegion.getByRole('button', {name: 'Actualizar', exact: true}).click(); await expect(familyRegion.getByText('Reversión −2,25', {exact: true})).toBeVisible(); await expect(familyRegion.getByText('Premio original', {exact: true})).toBeVisible(); @@ -373,7 +377,7 @@ for (const mode of ['native', 'standalone'] as const) { await expect(points.getByText('Actual total', {exact: true})).toBeVisible(); await expect(points.getByText('2.25', {exact: true})).toBeVisible(); await tasksRegion.getByRole('button', {name: 'Mark done now', exact: true}).click(); - await expect.poll(async () => (await ledger()).available_minor, {timeout: 15_000}).toBe(300); + await expect.poll(async () => (await ledger())?.available_minor, {timeout: 15_000}).toBe(300); await family.click(); const details = familyRegion.locator('ol li').first().locator('summary'); await details.click(); @@ -401,13 +405,13 @@ for (const mode of ['native', 'standalone'] as const) { await rewards.getByRole('textbox', {name: 'Código de solicitud', exact: true}).fill(code!); await rewards.getByRole('button', {name: 'Aprobar solicitud'}).click(); await expect(rewards.locator('li').filter({hasText: 'Aprobada para entrega'})).toBeVisible(); - await expect.poll(async () => (await ledger()).reserved_minor).toBe(200); + await expect.poll(async () => (await ledger())?.reserved_minor).toBe(200); const latest = await (await page.request.get(base + 'api/v1/tasks/occurrences/' + seeded.occurrence_id, {headers: {'X-Domus-Context': contextHeader}})).json(); await post('occurrences/' + seeded.occurrence_id + '/reopen', 'family-reward-hold', { expected_revision: latest.work.revision, cycle_id: latest.cycle.cycle_id, reason: 'Check the reward funding', }); - await expect.poll(async () => (await ledger()).available_minor, {timeout: 15_000}).toBe(-200); + await expect.poll(async () => (await ledger())?.available_minor, {timeout: 15_000}).toBe(-200); await rewards.getByRole('button', {name: 'Actualizar recompensas'}).click(); await expect(rewards.getByText('Puntos necesarios para cubrir las reservas activas 2,00')).toBeVisible(); await page.getByLabel('Idioma', {exact: true}).selectOption('en'); @@ -422,10 +426,10 @@ for (const mode of ['native', 'standalone'] as const) { const earned = await post('occurrences/' + newCredit.occurrence_id + '/complete', 'family-reward-completed', { expected_revision: newCredit.revision, performer_ids: [member], performed_at: Date.now() - 500, }); - await expect.poll(async () => (await ledger()).available_minor, {timeout: 15_000}).toBe(100); + await expect.poll(async () => (await ledger())?.available_minor, {timeout: 15_000}).toBe(100); await rewards.getByRole('button', {name: 'Refresh rewards'}).click(); await expect(rewards.locator('li').filter({hasText: 'Approved for delivery'})).toBeVisible(); - expect((await ledger()).spending_count).toBe(0); + await expect.poll(async () => (await ledger())?.spending_count).toBe(0); await rewards.getByRole('checkbox', {name: 'I delivered this reward'}).check(); await rewards.getByRole('button', {name: 'Record delivery'}).click(); await expect(rewards.locator('li').filter({hasText: 'Spending recorded'})).toBeVisible(); @@ -433,7 +437,7 @@ for (const mode of ['native', 'standalone'] as const) { await post('occurrences/' + newCredit.occurrence_id + '/reopen', 'family-reward-negative', { expected_revision: earned.revision, cycle_id: earned.cycle.cycle_id, reason: 'Check the original work', }); - await expect.poll(async () => (await ledger()).posted_minor, {timeout: 15_000}).toBe(-200); + await expect.poll(async () => (await ledger())?.posted_minor, {timeout: 15_000}).toBe(-200); await familyRegion.getByRole('button', {name: 'Refresh', exact: true}).click(); await expect(familyRegion.getByText(/Task reversals can leave a negative posted balance/u)).toBeVisible(); await page.getByLabel('Language', {exact: true}).selectOption('es'); @@ -1160,6 +1164,126 @@ for (const mode of ['native', 'standalone'] as const) { expect(writes.slice(writeOffset)).toEqual(Array(5).fill('POST ' + previewAPI)); expect(await definitions()).toEqual(beforePreview); + const drafts = page.locator('domus-automation-drafts'); + const draftsAPI = base + 'api/v1/automation/drafts'; + await page.getByLabel('Idioma',{exact:true}).selectOption('en'); + await page.setViewportSize({width:1100,height:760}); + await page.emulateMedia({colorScheme:'light'}); + await expect(drafts.getByText('Enter a task title above and save your first draft.')).toBeVisible(); + const saving = page.waitForResponse(response => response.url() === draftsAPI && response.request().method() === 'POST'); + await drafts.getByRole('button',{name:'Save draft',exact:true}).press('Enter'); + const firstDraftSave = await saving; + expect(firstDraftSave.status()).toBe(200); + const openDraft = drafts.getByRole('button',{name:'Open Check the tea supplies',exact:true}); + await expect(openDraft).toBeEnabled(); + const firstDraftKey = firstDraftSave.request().headers()['idempotency-key']; + const firstDraftReceipt = await page.request.get(draftsAPI + '/requests/' + firstDraftKey, { + headers: {'X-Domus-Context':contextHeader}, + }); + expect(firstDraftReceipt.ok(), await firstDraftReceipt.text()).toBe(true); + const {result:savedRule} = await firstDraftReceipt.json(); + expect(savedRule).toMatchObject({revision:'1',state:'draft',enabled:false}); + await expect(drafts.getByRole('article',{name:'Automation drafts'})).toHaveCSS('background-color','rgb(255, 255, 255)'); + await drafts.screenshot({path:info.outputPath('automation-drafts-en-wide.png')}); + await page.reload(); + await expect(page).toHaveURL(base + '#household'); + await page.getByRole('combobox',{name:/^(Language|Idioma)$/u}).selectOption('en'); + const draftURL = draftsAPI + '/' + savedRule.rule_id; + const releaseOpen = Promise.withResolvers(); + await page.route(draftURL, async route => { + await releaseOpen.promise; + await route.continue(); + }, {times:1}); + await expect(title).toBeEditable(); + await openDraft.press('Enter'); + try { + await expect(title).toBeDisabled(); + await expect(stockCondition).toBeDisabled(); + } finally { + releaseOpen.resolve(); + } + await expect(title).toHaveValue('Check the tea supplies'); + await expect(title).toBeEditable(); + await expect(stockCondition).toContainText('Tea filters for preview'); + + await page.getByLabel('Language',{exact:true}).selectOption('es'); + await page.setViewportSize({width:390,height:844}); + await page.emulateMedia({colorScheme:'dark'}); + const spanishTitle = rule.getByRole('textbox',{name:'Título de la tarea propuesta',exact:true}); + const saveRuleEs = drafts.getByRole('button',{name:'Guardar borrador',exact:true}); + await spanishTitle.fill('Preparar las provisiones de té'); + let lostKey = ''; + const loseResponse = async (route: import('@playwright/test').Route) => { + if (route.request().method() !== 'POST') {await route.continue(); return;} + lostKey = (await route.request().allHeaders())['idempotency-key']; + const committed = await route.fetch(); + expect(committed.ok(), await committed.text()).toBe(true); + await route.abort('failed'); + }; + await page.route(draftsAPI, loseResponse); + await saveRuleEs.tap(); + const recoverDraft = drafts.getByRole('button',{name:/^(Check original save|Consultar guardado original)$/u}); + await expect(recoverDraft).toBeEnabled(); + expect(lostKey).toMatch(/^req_[a-f0-9]{32}$/u); + await page.unroute(draftsAPI, loseResponse); + await page.route(draftsAPI, route => route.abort('failed'), {times:1}); + await page.reload(); + await expect(drafts.getByText(/Automation drafts are unavailable|Los borradores de automatización no están disponibles/u)).toBeVisible(); + await page.getByRole('combobox',{name:/^(Language|Idioma)$/u}).selectOption('es'); + await expect(spanishTitle).toBeDisabled(); + const releaseList = Promise.withResolvers(); + await page.route(draftsAPI, async route => { + await releaseList.promise; + await route.continue(); + }, {times:1}); + await drafts.getByRole('button',{name:'Volver a intentar',exact:true}).tap(); + try { + await expect(drafts.getByText('Cargando borradores de automatización…')).toBeVisible(); + await expect(spanishTitle).toBeDisabled(); + } finally { + releaseList.resolve(); + } + await expect(recoverDraft).toBeEnabled(); + await expect(spanishTitle).toBeDisabled(); + await expect(spanishTitle).toHaveValue('Preparar las provisiones de té'); + const receiptLookup = page.waitForResponse(draftsAPI + '/requests/' + lostKey); + await recoverDraft.tap(); + expect((await receiptLookup).ok()).toBe(true); + await expect(drafts.getByRole('status').filter({hasText:'Borrador actual'})).toHaveText(/Revisión 2/u); + await expect(spanishTitle).toBeEditable(); + + const draftToken = await page.request.get(base + 'api/v1/auth/csrf', {headers:{'X-Domus-Context':contextHeader}}); + const competing = await page.request.post(draftsAPI, {headers:{ + Origin:origin, 'X-Domus-Context':contextHeader, 'X-CSRF-Token':(await draftToken.json()).csrf_token, + 'Idempotency-Key':'competing-draft-edit', + }, data:{rule_id:savedRule.rule_id,expected_revision:'2',version:1,trigger:{kind:'manual'}, + condition:null, + action:{kind:'task.create',title:'Revisar las compras de té'}}}); + expect(competing.ok(), await competing.text()).toBe(true); + await spanishTitle.fill('Comprar té para el hogar'); + await saveRuleEs.tap(); + await expect(drafts.getByText(/Otro guardado cambió este borrador/u)).toBeVisible(); + await expect(spanishTitle).toHaveValue('Comprar té para el hogar'); + const reviewRevisionEs = drafts.getByRole('button',{name:'Revisar la última revisión',exact:true}); + await page.route(draftURL, route => route.abort('failed'), {times:1}); + await reviewRevisionEs.tap(); + await expect(drafts.getByText(/Los borradores de automatización no están disponibles/u)).toBeVisible(); + await expect(reviewRevisionEs).toBeEnabled(); + await expect(saveRuleEs).toBeDisabled(); + await expect(spanishTitle).toHaveValue('Comprar té para el hogar'); + await reviewRevisionEs.tap(); + await expect(drafts.getByText('Revisar las compras de té · Revisión 3')).toBeVisible(); + await expect(drafts.getByText('Sin condición de existencias',{exact:true})).toBeVisible(); + await drafts.getByRole('button',{name:'Mantener mis cambios sobre la última revisión',exact:true}).tap(); + await expect(spanishTitle).toHaveValue('Comprar té para el hogar'); + await expect(rule.getByRole('combobox',{name:'Existencias por debajo del mínimo (opcional)'})) + .toContainText('Tea filters for preview'); + await saveRuleEs.tap(); + await expect(drafts.getByRole('status').filter({hasText:'Borrador actual'})).toHaveText(/Revisión 4/u); + await expect(drafts.getByRole('article',{name:'Borradores de automatización'})).toHaveCSS('background-color','rgb(24, 36, 47)'); + await drafts.screenshot({path:info.outputPath('automation-drafts-es-narrow.png')}); + expect(await definitions()).toEqual(beforePreview); + const restock = await inventoryWrite('overview-restock-product', { action:'inventory.register-product', name:'Filters for the Overview', base_unit:'piece', }); diff --git a/frontend/tests/page.test.ts b/frontend/tests/page.test.ts index e0ae0814..fcb1cffc 100644 --- a/frontend/tests/page.test.ts +++ b/frontend/tests/page.test.ts @@ -34,6 +34,8 @@ function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'e let phase = 'unconfigured', postRequests = 0, putRequests = 0; let taskOverviewDenied = false; let shoppingItemPresent = false; + let automationTitle: string | null = null; + const automationDraft = {rule_id:'saved-draft',revision:'1',state:'draft',enabled:false}; const shoppingItem = {product_id:'product',extra_id:null,name:'Salt',base_unit:'gram',total:'1.000001'}; const originalAccess=JSON.parse(wire.active); let preferenceReceipt:Record|null=null; @@ -50,6 +52,18 @@ function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'e : phase === 'eligible' ? wire.eligible : phase === 'pending' ? wire.pending : wire.unconfigured; else if (route === 'auth/csrf') raw = JSON.stringify({csrf_token: 'c'.repeat(64)}); else if (route === 'automation/preview-access') raw = JSON.stringify({household_id: 'home'}); + else if (route === 'automation/drafts' && init.method === 'POST') { + automationTitle = JSON.parse(String(init.body)).action.title; + raw = JSON.stringify({state:'committed', archived_by:null, operation_id:'saved-automation', created_at:100, + result:{...automationDraft,member_id:memberId}, message:'Saved.',action_required:'Review.'}); + } + else if (route === 'automation/drafts') raw = JSON.stringify({ + drafts: automationTitle === null ? [] : [{...automationDraft,title:automationTitle}], next_cursor:null, + }); + else if (route === 'automation/drafts/saved-draft') raw = JSON.stringify({ + ...automationDraft, version:1, trigger:{kind:'manual'}, condition:null, + action:{kind:'task.create',title:automationTitle}, + }); else if (route === 'automation/preview') raw = JSON.stringify({version:1, trigger:'manual', task_title:JSON.parse(String(init.body)).action.title, would_create:true, conditions:[]}); else if (route === 'auth/logout') raw = JSON.stringify({state: 'logged_out', upstream_revoked: true, @@ -798,6 +812,8 @@ test('Household automation binds the verified member and retires requests outsid const emit = (target: EventTarget, detail: unknown) => target.dispatchEvent(new CustomEvent('domus-automation-preview-intent', {detail, bubbles:true, composed:true})); const requests = () => f.fetch.mock.calls.filter(([path]) => path.endsWith('/automation/preview')); + const saveDraft = (target: EventTarget) => target.dispatchEvent( + new CustomEvent('domus-automation-draft-intent', {detail:{type:'save'}, bubbles:true, composed:true})); expect(app.automationPreview).toBeNull(); navigate('#household'); await vi.waitFor(() => expect(app.automationPreview?.state).toBe('ready')); @@ -812,6 +828,21 @@ test('Household automation binds the verified member and retires requests outsid emit(widget, {type:'preview'}); await vi.waitFor(() => expect(app.automationPreview).toMatchObject({title:'Check lights',result:true})); expect(requests()).toHaveLength(1); + await vi.waitFor(() => expect(app.automationDrafts).toMatchObject({state:'ready',busy:false,pending:false})); + const drafts = app.shadowRoot!.querySelector('domus-automation-drafts')!; + saveDraft(unrelated); + expect(f.fetch.mock.calls.filter(([path, init]) => path.endsWith('/automation/drafts') && init.method === 'POST')) + .toHaveLength(0); + saveDraft(drafts); + await vi.waitFor(() => expect(app.automationDrafts).toMatchObject({notice:'saved',operationId:'saved-automation'})); + expect(f.fetch.mock.calls.filter(([path, init]) => path.endsWith('/automation/drafts') && init.method === 'POST')) + .toHaveLength(1); + await vi.waitFor(() => expect(app.automationDrafts).toMatchObject({busy:false,page:{drafts:[{id:'saved-draft'}]}})); + emit(widget, {type:'title',value:'Discard this edit'}); + drafts.dispatchEvent(new CustomEvent('domus-automation-draft-intent', { + detail:{type:'open',id:'saved-draft'}, bubbles:true, composed:true, + })); + await vi.waitFor(() => expect(app.automationPreview).toMatchObject({title:'Check lights',result:null})); navigate('#overview'); expect(app.automationPreview).toBeNull(); emit(widget, {type:'preview'}); diff --git a/specs/CATALOG.md b/specs/CATALOG.md index c20f9684..430f61a8 100644 --- a/specs/CATALOG.md +++ b/specs/CATALOG.md @@ -15,12 +15,12 @@ debt or convert unknown historic intent into a design decision. | `household-tasks` | Proposed | Members create and perform household responsibilities with explicit assignments, actual performers and history. A recurring definition survives completion of each individual occurrence. | [Task definitions, occurrences and household execution](./household-tasks.md) + 2 companion | 53 paths · 2026-11-11 | | `recurrence-calendar` | Proposed | A bounded scheduler turns task definitions into stable occurrences and a family calendar distinguishes planned start, deadline and actual completion. Original recurrence outcomes bind receipt status, action, result and source-cycle identity before replay and snapshot acceptance. | [Recurrence engine and family calendar](./recurrence-calendar.md) + 3 companion | 37 paths · 2026-11-09 | | `points-rewards` | Proposed | Task completion produces auditable point entries. Household-configurable collaboration policies determine each share and the actual award total; corrections preserve history and optional rewards never control basic participation. | [Auditable points, participation and optional rewards](./points-rewards.md) | 54 paths · 2026-11-11 | -| `shopping-management` | Proposed | Shopping combines manual intent, replenishment and task materials without losing provenance. Buying an item and physically receiving it are separate recorded facts. | [Shared shopping demand, purchases and receipt](./shopping-management.md) | 48 paths · 2026-11-17 | +| `shopping-management` | Proposed | Shopping combines manual intent, replenishment and task materials without losing provenance. Buying an item and physically receiving it are separate recorded facts. | [Shared shopping demand, purchases and receipt](./shopping-management.md) | 47 paths · 2026-11-17 | | `household-inventory` | Proposed | The household knows what is available, where it is stored and what needs replenishment through a local product catalog and an immutable stock movement ledger. | [Product catalog, pantry stock and replenishment](./household-inventory.md) | 29 paths · 2026-11-11 | | `home-assistant-surface` | Proposed | Domus exposes its household capabilities as native Home Assistant entities, services and events. The already integrated HA MCP consumes these surfaces; no gateway work or second MCP is included. | [Home Assistant entities, services and integration](./home-assistant-surface.md) + 2 companion | 17 paths · 2026-10-29 | | `application-experience` | Proposed | A complete household interface serves all six domains from the first release with fast daily actions, responsive navigation and clear operation results, independently of entity dashboards and AI.; combined native/standalone browser CI uses a bounded complete-suite deadline with protected candidate workflow qualification | [Responsive application, household dashboard and navigation](./application-experience.md) + 1 companion | 37 paths · 2026-11-08 | | `delivery-quality` | Proposed | Every implemented capability starts with meaningful tests and enforced architecture boundaries. A CI Check workflow validates each PR update, and both deployment targets ship isolated experimental and production channels. | [Clean Architecture, CI Check and isolated Stable and Edge channels](./delivery-quality.md) | 27 paths · 2026-10-31 | -| `household-automation` | Proposed | Simple/default and optional advanced editors share one durable declarative automation engine in the first release, invoking authorized household commands with replay-safe execution and visible traces. | [Household automation engine and simple/advanced rule editors](./household-automation.md) | 21 paths · 2026-11-11 | +| `household-automation` | Proposed | Simple/default and optional advanced editors share one durable declarative automation engine in the first release, invoking authorized household commands with replay-safe execution and visible traces. | [Household automation engine and simple/advanced rule editors](./household-automation.md) | 31 paths · 2026-11-11 | ## Evidence map @@ -141,9 +141,9 @@ debt or convert unknown historic intent into a design decision. - Specifications: [`specs/household-automation.md`](./household-automation.md) - Workflows: Not applicable for this capability. - Entrypoints: [`backend/src/domus/entrypoints/automation_http.py`](../backend/src/domus/entrypoints/automation_http.py) · [`frontend/src/composition/entry-page.ts`](../frontend/src/composition/entry-page.ts) · [`frontend/src/presentation/domus-app.ts`](../frontend/src/presentation/domus-app.ts) -- Core code: [`backend/src/domus/domain/automation.py`](../backend/src/domus/domain/automation.py) · [`backend/src/domus/application/automation_preview.py`](../backend/src/domus/application/automation_preview.py) · [`frontend/src/application/automation-preview.ts`](../frontend/src/application/automation-preview.ts) · [`frontend/src/adapters/automation-preview-http.ts`](../frontend/src/adapters/automation-preview-http.ts) · [`frontend/src/presentation/domus-automation-preview.ts`](../frontend/src/presentation/domus-automation-preview.ts) -- Tests: [`tests/backend/test_automation_preview.py`](../tests/backend/test_automation_preview.py) · [`frontend/tests/automation-preview.test.ts`](../frontend/tests/automation-preview.test.ts) · [`frontend/tests/page.test.ts`](../frontend/tests/page.test.ts) · [`frontend/tests/e2e/workspace-navigation.spec.ts`](../frontend/tests/e2e/workspace-navigation.spec.ts) -- User documentation: [`docs/product-vision.md`](../docs/product-vision.md) · [`docs/architecture.md`](../docs/architecture.md) · [`docs/operations.md`](../docs/operations.md) · [`docs/user-guide.md`](../docs/user-guide.md) · [`docs/contracts/home-assistant.md`](../docs/contracts/home-assistant.md) · [`docs/roadmap.md`](../docs/roadmap.md) · [`docs/evidence/automation-preview-qualification.md`](../docs/evidence/automation-preview-qualification.md) · [`docs/contracts/household-api.openapi.json`](../docs/contracts/household-api.openapi.json) · [`docs/contracts/native-household-api.openapi.json`](../docs/contracts/native-household-api.openapi.json) +- Core code: [`backend/src/domus/domain/automation.py`](../backend/src/domus/domain/automation.py) · [`backend/src/domus/application/automation_preview.py`](../backend/src/domus/application/automation_preview.py) · [`backend/src/domus/application/automation_drafts.py`](../backend/src/domus/application/automation_drafts.py) · [`backend/src/domus/infrastructure/sqlite_automation_drafts.py`](../backend/src/domus/infrastructure/sqlite_automation_drafts.py) · [`frontend/src/application/automation-preview.ts`](../frontend/src/application/automation-preview.ts) · [`frontend/src/application/automation-drafts.ts`](../frontend/src/application/automation-drafts.ts) · [`frontend/src/adapters/automation-preview-http.ts`](../frontend/src/adapters/automation-preview-http.ts) · [`frontend/src/adapters/automation-draft-http.ts`](../frontend/src/adapters/automation-draft-http.ts) · [`frontend/src/adapters/automation-draft-journal.ts`](../frontend/src/adapters/automation-draft-journal.ts) · [`frontend/src/presentation/domus-automation-preview.ts`](../frontend/src/presentation/domus-automation-preview.ts) · [`frontend/src/presentation/domus-automation-drafts.ts`](../frontend/src/presentation/domus-automation-drafts.ts) +- Tests: [`tests/backend/test_automation_preview.py`](../tests/backend/test_automation_preview.py) · [`tests/backend/test_automation_drafts.py`](../tests/backend/test_automation_drafts.py) · [`tests/backend/test_automation_draft_storage.py`](../tests/backend/test_automation_draft_storage.py) · [`frontend/tests/automation-preview.test.ts`](../frontend/tests/automation-preview.test.ts) · [`frontend/tests/automation-drafts.test.ts`](../frontend/tests/automation-drafts.test.ts) · [`frontend/tests/page.test.ts`](../frontend/tests/page.test.ts) · [`frontend/tests/e2e/workspace-navigation.spec.ts`](../frontend/tests/e2e/workspace-navigation.spec.ts) +- User documentation: [`docs/product-vision.md`](../docs/product-vision.md) · [`docs/architecture.md`](../docs/architecture.md) · [`docs/operations.md`](../docs/operations.md) · [`docs/user-guide.md`](../docs/user-guide.md) · [`docs/contracts/home-assistant.md`](../docs/contracts/home-assistant.md) · [`docs/roadmap.md`](../docs/roadmap.md) · [`docs/evidence/automation-preview-qualification.md`](../docs/evidence/automation-preview-qualification.md) · [`docs/evidence/automation-draft-qualification.md`](../docs/evidence/automation-draft-qualification.md) · [`docs/contracts/household-api.openapi.json`](../docs/contracts/household-api.openapi.json) · [`docs/contracts/native-household-api.openapi.json`](../docs/contracts/native-household-api.openapi.json) ## Maintenance contract diff --git a/specs/catalog.json b/specs/catalog.json index 6d827b64..35c6ee6b 100644 --- a/specs/catalog.json +++ b/specs/catalog.json @@ -1010,13 +1010,22 @@ "code": [ "backend/src/domus/domain/automation.py", "backend/src/domus/application/automation_preview.py", + "backend/src/domus/application/automation_drafts.py", + "backend/src/domus/infrastructure/sqlite_automation_drafts.py", "frontend/src/application/automation-preview.ts", + "frontend/src/application/automation-drafts.ts", "frontend/src/adapters/automation-preview-http.ts", - "frontend/src/presentation/domus-automation-preview.ts" + "frontend/src/adapters/automation-draft-http.ts", + "frontend/src/adapters/automation-draft-journal.ts", + "frontend/src/presentation/domus-automation-preview.ts", + "frontend/src/presentation/domus-automation-drafts.ts" ], "tests": [ "tests/backend/test_automation_preview.py", + "tests/backend/test_automation_drafts.py", + "tests/backend/test_automation_draft_storage.py", "frontend/tests/automation-preview.test.ts", + "frontend/tests/automation-drafts.test.ts", "frontend/tests/page.test.ts", "frontend/tests/e2e/workspace-navigation.spec.ts" ], @@ -1028,12 +1037,13 @@ "docs/contracts/home-assistant.md", "docs/roadmap.md", "docs/evidence/automation-preview-qualification.md", + "docs/evidence/automation-draft-qualification.md", "docs/contracts/household-api.openapi.json", "docs/contracts/native-household-api.openapi.json" ], "readiness": { "state": "draft", - "implementationEvidence": "partial: protected versioned manual task preview with optional current stock condition, typed validation and English/Spanish simple form", + "implementationEvidence": "partial: protected manual task preview and inactive drafts with immutable revisions, original-save recovery, current stock conditions and an English/Spanish editor", "blockingDecisions": "Detailed DSL/action catalog, numeric resource limits, external-effect receipts and supported HA/browser evidence. The owner confirmed both editors, one engine and disablement that stops new runs/later steps while retaining already-started atomic commands and effects.", "copilotChangesAllowed": false } diff --git a/specs/household-automation.md b/specs/household-automation.md index 2fc5a668..46538a37 100644 --- a/specs/household-automation.md +++ b/specs/household-automation.md @@ -466,3 +466,223 @@ and installed Edge evidence with scoped cleanup. ADR 0005 and household-automation-R1, R2 and R7 define one typed model and simulation without effects. Reuse the current automation configuration and task creation permissions and Inventory replenishment semantics. + +## Save and reopen household automation drafts + +- Status: Draft +- Date: 2026-11-18 +- Catalog capability ID: household-automation +- Owners: Domus maintainers +- Scope: Durable inactive drafts for the existing manual task rule editor +- Related issue: [Domus #118](https://github.com/vypdev/domus/issues/118) +- Required review gates: product UX, architecture, testing, documentation, security/operations +- Open decisions blocking readiness: none within the supported manual rule scope + +### 1. Executive summary + +A household administrator can save the manual rule they already preview, leave +Household settings and reopen the saved definition with its exact values. +An explicit edit adds a revision under the same rule identity. A saved draft +cannot admit a run. + +### 2. Problem, current behavior, and evidence + +The manual preview delivered by [issue #98](https://github.com/vypdev/domus/issues/98) +uses the current authorized stock facts. The current editor holds the draft in +browser memory, which is lost after reload. The product roadmap requires a +durable versioned definition before activation and execution can pin a revision. + +The selected base preserves the preview qualifier in +`docs/evidence/automation-preview-qualification.md`, the closed rule model in +`backend/src/domus/domain/automation.py`, and the UI state in +`frontend/src/application/automation-preview.ts`. This is a prospective delta. + +### 3. Actors, surfaces, and terminology + +| Actor | Goal | Entry point | Visible surfaces | +| --- | --- | --- | --- | +| Household administrator with current configuration and task creation grants | Save, reopen, edit and preview the supported manual rule | Household settings | Draft list, editor and save status | +| Household member without current grants | Use only permitted household views | Household settings | Permission feedback without rule details | + +A rule ID identifies the draft within one installation, channel and household. +A revision is the immutable typed definition saved at a particular point. +An original save receipt identifies the result of one scoped request. +An inactive draft has no execution authority. + +### 4. Goals, non-goals, and fixed invariants + +| Requirement | Behavior | +| --- | --- | +| automation-drafts-R01 | Let a currently authorized household administrator save and reopen the exact validated manual rule under a stable identity. Saving and previewing leave execution inactive. | +| automation-drafts-R02 | Keep immutable revisions, require the expected revision on replacement and recover the result of the original save without duplicating a draft or a revision. | +| automation-drafts-R03 | Provide protected draft listing, editing and recoverable errors with English and Spanish keyboard and touch navigation. | +| automation-drafts-R04 | Preserve existing data through migration and verify draft revisions and receipts through restart and restoration in the supported deployments. | + +Activation, live triggers, runs, advanced editing, external effects and +distribution have separate acceptance. The server owns scope, resulting +revision and status. No draft input grants permission or starts an effect. + +### 5. Current versus proposed product journey + +| Stage | Current | Proposed | User effect | +| --- | --- | --- | --- | +| Edit | Manual task rule exists only in the editor | Reuse the same editor and form values | The task title and optional stock predicate stay recognizable | +| Save | Refresh loses the editor draft | Explicit save returns a revision | The notice identifies what was saved | +| Reopen | Start over after leaving the view | Select a current draft in Household settings | Reopen the exact recorded data | +| Edit again | Existing data is ephemeral | Save against the reopened revision | Preserve the old revision and show conflicts clearly | + +Text equivalent: edit and preview as needed, save the inactive rule, reopen it +from the list, then explicitly save later changes as a new revision. + +### 6. Functional behavior and state model + +The first save records one stable identity and revision one. Reopening a saved +item loads its latest authorized revision in the same editor. An edit uses +the expected revision and appends one immutable revision. Creation and edit +produce exactly one original-operation receipt. An identical replay returns +the recorded result. Reusing a request identity for different input fails +without writing. Conflicting edits preserve the draft and both users' results. + +The version-one definition carries one explicit manual trigger, one task +proposal and the existing supported optional stock predicate. Save validation +uses the existing typed rule and closed-schema policy. Older or unsupported +content cannot be silently replaced by the simple form. Preview evaluates the +loaded definition against current stock and remains available before saving. + +### 7. User-facing configuration + +The existing manual task title limit and product selection apply. The stock +predicate is optional. Scope and enabled state come from the server. +There is no new installation configuration. The draft list is bounded and a +member can request the next page when more authorized drafts exist. + +### 8. Clean Architecture design + +The domain owns typed validation and immutable rule data. The application uses +the existing household authorization and transaction boundaries to admit a +save, validate owned product references, persist the revision and record the +original result atomically. Protected read queries return only the current +member's allowed drafts. SQLite implements storage and snapshot verification. +The existing HTTP compositions map the same validated DTOs and safe outcomes. +The browser owns the draft editor, localized view and exact original-request +recovery. Keep storage and transport dependencies outside domain and +application policy. + +### 9. UI/UX and content contract + +Show the draft list next to the existing editor in Household settings. An +empty list invites the administrator to save the first draft. Saving shows a +pending state and the resulting revision when confirmed. Treat a lost +response as a recoverable original save. A revision conflict explains how +to review the newer version and preserves unsaved input. A permission loss +retires the user's saved data and editor. Localize list, states and recovery +copy in English and Spanish. Provide visible focus, accessible controls and +a readable narrow layout in light and dark modes. + +### 10. Failure, recovery, and cleanup + +Invalid input preserves the last valid revision. A failed or conflicting +operation preserves the form and explains the next step. An uncertain save +recovers through its original request identity. Revocation blocks recovery +disclosure. Removing a disposable test installation removes only its own +data and temporary repository source. + +### 11. Security, permissions, and privacy + +Resolve trusted installation, channel, household and member on the server. +Apply current household read and automation configuration authority to list +and reopen. Apply current write and relevant task permissions to saves. +Reject foreign products without disclosing their data. A draft carries +declarative data, with no raw command, URL, credential or principal override. +Stable and Edge storage remain isolated. + +### 12. Observability and operational UX + +Show authoritative empty, pending, saved, conflict, denied and unavailable +states. An operation reference supports original-save recovery. Diagnostics +use safe codes and correlation identifiers without private rule data. +Application and UI render exact saved revision and inactivity. + +### 13. Compatibility, migration, rollout, and rollback + +The storage change upgrades representative schema 31 and schema 20 data. +Verify that existing household records, original-operation receipts and +authorization remain consistent after migration. Verify restart and +snapshot restoration of a saved rule and its immutable revisions. Preserve +the earlier compatible image and data backup for rollback. Exercise Ingress, +standalone, both architectures and a separately installed Edge candidate. + +### 14. Testing strategy and numeric budget + +| Area | Minimum distinct cases | Behaviors/risks covered | +| --- | --- | --- | +| Managing drafts | 2 | Exact round trip, revision conflicts and original replay | +| Permission boundary | 1 | Current grants and owned references | +| Preview | 1 | Current facts and inactive saves | +| Interaction | 1 | Localized editor and recoverable conflicts | +| Storage lifecycle | 1 | Migration, restart and restoration | +| Deployment evidence | 1 | Both compositions and architectures plus installed Edge | +| Total | 7 | Independently observable cases | + +| Case ID | Area | Requirements | Scenario | +| --- | --- | --- | --- | +| automation-drafts-C01 | Managing drafts | automation-drafts-R01 | Save the current manual rule, reload the workspace, reopen the recorded rule and compare the exact task proposal and stock predicate to the original input. The draft is inactive. | +| automation-drafts-C02 | Permission boundary | automation-drafts-R01 | A revoked member or foreign household cannot list, read or save the draft. A malformed rule or foreign stock reference cannot replace a prior revision. | +| automation-drafts-C03 | Managing drafts | automation-drafts-R02 | Two saves with the same expected revision yield one new revision and a conflict. Replaying an original request after a lost response returns its recorded result. Both immutable revisions remain available to storage verification. | +| automation-drafts-C04 | Preview | automation-drafts-R01 | Preview a reopened draft using the current stock facts. Compare task, inventory, notification and outbox state before and after save and preview. | +| automation-drafts-C05 | Interaction | automation-drafts-R03 | Use English desktop keyboard and Spanish narrow touch controls to save and reopen. A conflict or recoverable failure keeps the unsaved input and identifies the next action. | +| automation-drafts-C06 | Storage lifecycle | automation-drafts-R04 | Upgrade representative schema 31 and 20 data, then verify a saved draft, exact revisions and its original receipt after restart and snapshot restoration. | +| automation-drafts-C07 | Deployment evidence | automation-drafts-R03, automation-drafts-R04 | Prove the browser journey in Ingress and standalone, CI images for both architectures and an installed Edge candidate. Clean the disposable installation and data. | + +### 15. Documentation and discoverability + +| Path | Change | +| --- | --- | +| specs/household-automation.md | update | +| docs/roadmap.md | update | +| docs/user-guide.md | update | +| docs/contracts/household-api.openapi.json | update | +| docs/contracts/native-household-api.openapi.json | update | +| docs/evidence/automation-preview-qualification.md | reference | + +Keep the catalog under the existing household-automation capability and +record exact validation evidence in the contributing PR. + +### 16. Acceptance scenarios + +The seven scenarios in the section 14 inventory define acceptance for this +increment. Existing automation engine and preview cases retain their scope. +Validate the protected reads and same-key write recovery through both HTTP +compositions. Run the browser cases in both languages and verify installed +Edge behavior and scoped cleanup before merge. + +### 17. Requirements traceability + +| Requirement | Cases | +| --- | --- | +| automation-drafts-R01 | automation-drafts-C01, automation-drafts-C02, automation-drafts-C04 | +| automation-drafts-R02 | automation-drafts-C03 | +| automation-drafts-R03 | automation-drafts-C05, automation-drafts-C07 | +| automation-drafts-R04 | automation-drafts-C06, automation-drafts-C07 | + +### 18. Implementation sequence + +Reuse the typed rule and protected access boundary. Add durable rule identity, +immutable revisions and the original save receipt. Connect the existing +editor and draft list. Exercise the storage migrations, original save +recovery, browser journey and installed Edge candidate. Update the catalog +and the user guide with verified evidence. + +### 19. Definition of Done + +- [ ] The seven acceptance cases pass. +- [ ] Existing records, access and read-only preview behavior pass regression checks. +- [ ] Authored runtime files retain complete coverage and architecture checks. +- [ ] Both compositions and architectures pass and the installed Edge test is recorded with scoped cleanup. +- [ ] Requirements, case mappings and catalog agree with the implemented increment. + +### 20. References and decisions + +[Domus #118](https://github.com/vypdev/domus/issues/118) defines the draft +increment. The existing capability owns the rule model and later execution. +The selected base is `d18391736d425fb7c6a80e44e30371fe12124ad1`. diff --git a/tests/backend/test_activation_compatibility.py b/tests/backend/test_activation_compatibility.py index ef42e56f..94e83895 100644 --- a/tests/backend/test_activation_compatibility.py +++ b/tests/backend/test_activation_compatibility.py @@ -79,7 +79,7 @@ def test_real_activation_upgrades_only_target_from_frozen_source_and_checkpoint( selected = open_storage(root, "edge") try: with selected.database._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 32 assert connection.execute("SELECT COUNT(*) FROM retained_operations").fetchone()[0] == ( 2 if version == 4 else 1 ) diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py index d502fc52..b3809276 100644 --- a/tests/backend/test_app_package.py +++ b/tests/backend/test_app_package.py @@ -15,7 +15,7 @@ def test_repository_and_edge_manifest_offer_native_ha_entry_without_user_credent manifest = yaml.safe_load((ROOT / "addon-edge/config.yaml").read_text()) assert repository["url"] == "https://github.com/vypdev/domus" assert manifest["slug"] == "domus_edge" and manifest["stage"] == "experimental" - assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.32" + assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.37" assert manifest["ingress"] is True and manifest["ingress_port"] == 8099 assert manifest["panel_admin"] is False and manifest["homeassistant_api"] is True assert manifest["options"] == {"public_origins": []} @@ -31,6 +31,7 @@ def test_repository_and_edge_manifest_offer_native_ha_entry_without_user_credent "0.0.0-edge.6", "0.0.0-edge.10", "0.0.0-edge.13", + "0.0.0-edge.33", ] assert set(manifest["arch"]) == {"amd64", "aarch64"} @@ -58,15 +59,15 @@ def test_build_pins_source_checksum_bases_lock_and_nonroot_native_entrypoint() - commits = re.findall(r"^ARG DOMUS_SOURCE_COMMIT=(\w+)$", source, re.MULTILINE) assert len(commits) == 2 and len(set(commits)) == 1 assert re.fullmatch(r"[a-f0-9]{40}", commits[0]) - assert commits[0] == "43bace9576b9468f789fe9975a3dd5fe427d83ae" + assert commits[0] == "63890ace59d55ec76e0b9c3c7c832598eeeab7a1" assert ( - "DOMUS_SOURCE_SHA256=7ad1c19b3452f2be9f8385be113c7d5a1f7f1a74ee094c11ad99c2513732d0d4" + "DOMUS_SOURCE_SHA256=683f22b93d1e26d6145f51d005d8cfca1324f7d27425786050d1f54fc4cb9b9b" in source ) - assert "ARG BUILD_VERSION=0.0.0-edge.32" in source + assert "ARG BUILD_VERSION=0.0.0-edge.37" in source candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text()) assert candidate["sourceCommit"] == commits[0] - assert candidate["version"] == "0.0.0-edge.32" + assert candidate["version"] == "0.0.0-edge.37" assert "DOMUS_SOURCE_SHA256=" + candidate["sourceArchiveSHA256"] in source assert re.search(r"^ARG DOMUS_SOURCE_SHA256=[a-f0-9]{64}$", source, re.MULTILINE) assert "sha256sum --check" in source @@ -140,12 +141,12 @@ def test_edge_artifact_declares_exact_reviewed_runtime_without_rebinding_histori "pythonFiles", "uiFiles", } - assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.32" - assert artifact["sourceCommit"] == "43bace9576b9468f789fe9975a3dd5fe427d83ae" - assert artifact["storageSchema"] == 31 + assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.37" + assert artifact["sourceCommit"] == "63890ace59d55ec76e0b9c3c7c832598eeeab7a1" + assert artifact["storageSchema"] == 32 for field in ["sourceArchiveSHA256", "wheelSHA256"]: assert re.fullmatch("[a-f0-9]{64}", artifact[field]) - assert len(artifact["pythonFiles"]) == 221 and len(artifact["uiFiles"]) == 4 + assert len(artifact["pythonFiles"]) == 223 and len(artifact["uiFiles"]) == 4 for name, digest in artifact["pythonFiles"].items(): assert re.fullmatch(r"domus/(?:[A-Za-z0-9_]+/)*[A-Za-z0-9_]+\.py", name) assert re.fullmatch("[a-f0-9]{64}", digest) diff --git a/tests/backend/test_automation_draft_storage.py b/tests/backend/test_automation_draft_storage.py new file mode 100644 index 00000000..04650811 --- /dev/null +++ b/tests/backend/test_automation_draft_storage.py @@ -0,0 +1,177 @@ +"""Verify exact drafts and replay through SQLite migration, activation and rollback.""" + +import sqlite3 +from contextlib import closing +from dataclasses import replace +from pathlib import Path + +import pytest +from test_activation_compatibility import identity_at +from test_automation_drafts import DRAFTS, read, save +from test_automation_preview import USER +from test_household_commands import Actor +from test_sqlite_snapshots import Clock +from test_task_runtime import api as api + +from domus.application.automation_drafts import SAVE_DRAFT, AutomationDrafts, SaveDraft +from domus.application.fixed_materialization import MaintenanceScope +from domus.domain.automation import AutomationRule, StockCondition +from domus.domain.errors import DatabaseRejected, Forbidden, InvalidInput, StorageFailure +from domus.domain.storage import CommandKey, Installation +from domus.domain.task_values import TaskContent +from domus.infrastructure import sqlite as storage +from domus.infrastructure.application_runtime import SecureIdentifiers +from domus.infrastructure.owned_storage import open_storage +from domus.infrastructure.sqlite import SQLiteDatabase +from domus.infrastructure.sqlite_activation import SQLiteActivation +from domus.infrastructure.sqlite_restoration import SQLiteRestorations +from domus.infrastructure.sqlite_snapshots import SQLiteSnapshots, _verify_database +from domus.infrastructure.task_cursor import TaskCursor + + +def service(store): + actor, clock = Actor(), Clock() + return AutomationDrafts( + store, + MaintenanceScope(store.installation, "home"), + actor, + actor.current, + clock, + SecureIdentifiers(), + TaskCursor(clock, b"d" * 32), + ) + + +@pytest.mark.parametrize( + ("version", "filename"), + [ + (20, "v20-inventory-history-source.sql"), + (31, "v31-automation-drafts-source.sql"), + ], +) +def test_migration_restoration_and_rollback_keep_exact_drafts_and_receipts( + tmp_path, monkeypatch, version, filename +): + root = tmp_path / "source" + root.mkdir(mode=0o700) + path = root / "domus.sqlite3" + fixture = Path(__file__).parents[1] / "fixtures/sqlite" / filename + with closing(sqlite3.connect(path, autocommit=True)) as db: + db.executescript(fixture.read_text()) + identity = db.execute("SELECT instance_id,channel FROM installation").fetchone() + installation = Installation(*identity) + product = db.execute("SELECT product_id FROM inventory_products").fetchone()[0] + tables = ("households", "members", "receipts", "inventory_materials", "task_occurrences") + if version == 31: + tables += ("shopping_sessions",) + prior = {name: db.execute("SELECT * FROM " + name).fetchall() for name in tables} + path.chmod(0o600) + identity_at(root, installation) + store = SQLiteDatabase(path, installation) + with closing(sqlite3.connect(path)) as db: + db.row_factory = sqlite3.Row + assert _verify_database(db, store, previous=True) == version + original = path.read_bytes() + with monkeypatch.context() as patch: + patch.setattr(storage, "AUTOMATION_DRAFT_STATEMENT", "invalid SQL") + with pytest.raises(StorageFailure): + store.initialize(require_existing=True) + assert path.read_bytes() == original + store.initialize(require_existing=True) + + with closing(sqlite3.connect(path)) as db: + assert db.execute("PRAGMA user_version").fetchone() == (32,) + assert db.execute("PRAGMA foreign_key_check").fetchall() == [] + assert {name: db.execute("SELECT * FROM " + name).fetchall() for name in tables} == prior + rule = AutomationRule(1, "manual", StockCondition(product), TaskContent("Buy oil")) + drafts = service(store) + first = drafts.save("initial", SaveDraft(None, 0, rule)) + rule_id = first.result.decode()["rule_id"] + archive, target = tmp_path / "checkpoint", tmp_path / "prepared" + snapshotter = SQLiteSnapshots(store, archive, installation, Clock()) + checkpoint = snapshotter.create("first-draft") + assert checkpoint.schema_version == 32 and snapshotter.inspect() == checkpoint + edit = SaveDraft(rule_id, 1, replace(rule, task=TaskContent("Review the pantry"))) + second = drafts.save("edit", edit) + restarted = service(SQLiteDatabase(path, installation)) + assert restarted.reopen(rule_id).rule == edit.rule + assert restarted.original("initial") == first + assert restarted.original("edit") == second + + SQLiteRestorations(store, archive, target, installation, Clock(), checkpoint).prepare( + "restore-draft" + ) + result = SQLiteActivation(root, installation, Clock(), target).activate() + assert result.state == "active" + selected = open_storage(root, "edge") + try: + restored = service(selected.database) + draft = restored.reopen(rule_id) + assert (draft.revision, draft.rule) == (1, rule) + evidence = restored.original("initial") + assert not evidence.historical and evidence.operation_id == first.operation_id + historical = restored.save("edit", edit) + assert historical == restored.original("edit") + assert historical.historical and historical.operation_id == second.operation_id + assert restored.reopen(rule_id) == draft + with selected.database.read() as unit: + assert unit.outbox.delivered(first.operation_id) + assert all(event.event_id != second.operation_id for event in unit.outbox.pending()) + + rollback_target = tmp_path / "rollback" + SQLiteRestorations( + selected.database, + root / "activations/restore-draft/source-checkpoint", + rollback_target, + installation, + Clock(), + result.record.rollback_snapshot, + ).prepare("rollback-draft") + finally: + selected.close() + rollback = SQLiteActivation(root, installation, Clock(), rollback_target).activate() + assert rollback.state == "active" + reopened = open_storage(root, "edge") + try: + restored = service(reopened.database) + draft = restored.reopen(rule_id) + assert (draft.revision, draft.rule) == (2, edit.rule) + restored_second = restored.original("edit") + assert not restored_second.historical + assert restored_second.operation_id == second.operation_id + finally: + reopened.close() + + +@pytest.mark.parametrize( + "corruption", + ["revision=3", "definition='{}'", "definition=' ' || definition"], +) +def test_snapshot_rejects_invalid_draft_storage(api, corruption): + api.user(USER, True) + assert save(api, "single").status_code == 200 + with closing(sqlite3.connect(api.store.path, autocommit=True)) as connection: + connection.execute(f"UPDATE automation_draft_revisions SET {corruption}") + connection.row_factory = sqlite3.Row + with pytest.raises(DatabaseRejected, match="invalid_snapshot_records"): + _verify_database(connection, api.store, previous=False) + + +def test_authority_binds_the_original_to_the_current_member(api): + api.user(USER, True) + assert save(api, "single").status_code == 200 + drafts = service(api.store) + with pytest.raises(InvalidInput, match="invalid_page_size"): + drafts.list(limit=0, cursor=None) + actor = Actor() + with api.store.read() as unit, pytest.raises(Forbidden, match="permission_denied"): + authority = drafts._authority(actor.current(), "single") + authority.require(CommandKey("home", actor.human.ha_user_id, SAVE_DRAFT, "other"), unit) + with closing(sqlite3.connect(api.store.path, autocommit=True)) as connection: + connection.execute( + "UPDATE receipts SET result=json_set(result,'$.member_id','previous-member') " + "WHERE action=?", + (SAVE_DRAFT,), + ) + response = read(api, f"{DRAFTS}/requests/single") + assert (response.status_code, response.json()["code"]) == (403, "permission_denied") diff --git a/tests/backend/test_automation_drafts.py b/tests/backend/test_automation_drafts.py new file mode 100644 index 00000000..c0642ba1 --- /dev/null +++ b/tests/backend/test_automation_drafts.py @@ -0,0 +1,279 @@ +"""Qualify typed drafts and durable command recovery in both HTTP compositions.""" + +import re +import sqlite3 +from concurrent.futures import ThreadPoolExecutor +from contextlib import closing +from dataclasses import replace +from threading import Barrier + +import pytest +from test_automation_preview import ACTION, CONTEXT, RULE, USER, leaf, preview +from test_inventory_catalog_http import post, register +from test_task_runtime import api as api + +from domus.domain.automation import ( + MAX_CONDITION_DEPTH, + AutomationRule, + Condition, + ConditionGroup, + NegatedCondition, + StockCondition, +) +from domus.domain.errors import InvalidInput +from domus.domain.identity import MAX_REVISION, MemberStatus, Permission, PermissionRule +from domus.domain.storage import JsonDocument +from domus.domain.task_values import TaskContent + +DRAFTS = "/api/v1/automation/drafts" + + +@pytest.mark.parametrize( + "condition", + [ + None, + StockCondition("tea"), + ConditionGroup( + "all", + ( + ConditionGroup("any", (StockCondition("coffee"),)), + NegatedCondition(StockCondition("tea")), + ), + ), + ], +) +def test_draft_rule_document_round_trips_the_exact_version_one_definition( + condition: Condition | None, +) -> None: + rule = AutomationRule(1, "manual", condition, TaskContent("Reponer té")) + document = rule.document() + assert document.decode()["action"] == {"kind": "task.create", "title": "Reponer té"} + assert AutomationRule.from_document(document) == rule + assert AutomationRule.from_document(document).document() == document + + +def test_draft_rule_document_preserves_a_condition_at_the_maximum_depth() -> None: + condition: Condition = StockCondition("tea") + for _ in range(MAX_CONDITION_DEPTH - 1): + condition = ConditionGroup("all", (condition,)) + rule = AutomationRule(1, "manual", condition, TaskContent("Buy tea")) + assert AutomationRule.from_document(rule.document()) == rule + + +@pytest.mark.parametrize( + ("changes", "reason"), + [ + ({"household_id": "elsewhere"}, "invalid_automation_rule"), + ({"version": True}, "invalid_automation_rule"), + ({"version": 2}, "invalid_automation_rule"), + ({"trigger": {"kind": "manual", "schedule": "daily"}}, "invalid_automation_rule"), + ({"action": {"kind": "notification", "title": "Buy tea"}}, "invalid_automation_rule"), + ({"condition": {"kind": "not", "child": None}}, "invalid_automation_condition"), + ({"condition": {"kind": "any", "children": []}}, "invalid_automation_condition"), + ( + {"condition": {"kind": "stock_below_minimum", "product_id": "tea", "code": ""}}, + "invalid_automation_condition", + ), + ], +) +def test_draft_rule_document_rejects_invalid_records( + changes: dict[str, object], reason: str +) -> None: + baseline = AutomationRule(1, "manual", None, TaskContent("Buy tea")).document() + with pytest.raises(InvalidInput, match=reason): + AutomationRule.from_document(JsonDocument.from_value(baseline.decode() | changes)) + + +def test_draft_rule_document_rejects_task_fields_the_format_cannot_preserve() -> None: + rule = AutomationRule(1, "manual", None, TaskContent("Buy tea", description="Loose leaf")) + with pytest.raises(InvalidInput, match="invalid_automation_rule"): + rule.document() + + +def save(api, key, *, rule_id=None, revision="0", **rule): + return api.client.post( + DRAFTS, + json=RULE | rule | {"rule_id": rule_id, "expected_revision": revision}, + headers=api.headers(key) | CONTEXT, + ) + + +def read(api, path=DRAFTS, **kwargs): + return api.client.get(path, headers=CONTEXT, **kwargs) + + +def effects(api): + tables = ( + "task_definitions", + "task_occurrences", + "inventory_movements", + "inventory_effects", + "points_task_receipts", + ) + with closing(sqlite3.connect(api.store.path)) as connection, api.store.read() as unit: + rows = tuple(connection.execute(f"SELECT * FROM {table}").fetchall() for table in tables) + return rows, unit.outbox.pending() + + +def test_draft_round_trip_pagination_and_preview_leave_no_pending_effect(api): + api.user(USER, True) + assert read(api).json() == {"drafts": [], "next_cursor": None} + product = register(api, "tea", "Tea", "piece") + assert ( + post( + api, + "configure-tea", + "configure-replenishment", + product_id=product, + minimum="2", + target="4", + expected_revision="0", + ).status_code + == 200 + ) + before = effects(api) + rule = {"action": ACTION | {"title": "Reponer té"}, "condition": leaf(product)} + saved = save(api, "save-tea", **rule) + assert saved.status_code == 200, saved.text + receipt = saved.json() + rule_id = receipt["result"]["rule_id"] + state = {"rule_id": rule_id, "revision": "1", "state": "draft", "enabled": False} + assert receipt["result"] == state | {"member_id": receipt["result"]["member_id"]} + reopened = read(api, f"{DRAFTS}/{rule_id}") + assert reopened.json() == RULE | rule | state + assert read(api).json() == { + "drafts": [state | {"title": rule["action"]["title"]}], + "next_cursor": None, + } + assert preview(api, api.headers() | CONTEXT, **rule).json()["would_create"] is True + assert effects(api) == before + assert post(api, "stock-tea", "intake", product_id=product, quantity="2").status_code == 200 + updated = effects(api) + assert preview(api, api.headers() | CONTEXT, **rule).json()["would_create"] is False + assert effects(api) == updated + + tallest = leaf(product) + for _ in range(MAX_CONDITION_DEPTH - 1): + tallest = {"kind": "all", "children": [tallest]} + second = save(api, "second-draft", condition=tallest) + assert second.status_code == 200, second.text + second_id = second.json()["result"]["rule_id"] + assert read(api, f"{DRAFTS}/{second_id}").json()["condition"] == tallest + first_page = read(api, params={"limit": 1}).json() + assert len(first_page["drafts"]) == 1 and first_page["next_cursor"] + cursor = first_page["next_cursor"] + next_page = read(api, params={"limit": 1, "cursor": cursor}).json() + assert [item["rule_id"] for item in first_page["drafts"] + next_page["drafts"]] == sorted( + (rule_id, second_id) + ) + assert next_page["next_cursor"] is None + wrong_limit = read(api, params={"limit": 2, "cursor": cursor}) + assert (wrong_limit.status_code, wrong_limit.json()["code"]) == (422, "invalid_task_cursor") + + +def test_draft_denies_revoked_grants_and_preserves_the_last_valid_revision(api): + api.user(USER, True) + created = save(api, "first") + assert created.status_code == 200, created.text + rule_id = created.json()["result"]["rule_id"] + path = f"{DRAFTS}/{rule_id}" + before = read(api, path).json() + for changes, expected in ( + ({"enabled": True}, (422, "invalid_request")), + ({"condition": leaf("other-household-product")}, (404, "inventory_product_missing")), + ): + rejected = save(api, "edit", rule_id=rule_id, revision="1", **changes) + assert (rejected.status_code, rejected.json()["code"]) == expected + bad_revision = save(api, "edit", rule_id=rule_id) + assert (bad_revision.status_code, bad_revision.json()["code"]) == (422, "invalid_revision") + bad_creation = save(api, "edit", revision="1") + assert (bad_creation.status_code, bad_creation.json()["code"]) == (422, "invalid_revision") + too_large = save(api, "edit", rule_id=rule_id, revision=str(MAX_REVISION + 1)) + assert (too_large.status_code, too_large.json()["code"]) == (422, "invalid_request") + missing = read(api, f"{DRAFTS}/elsewhere") + assert (missing.status_code, missing.json()["code"]) == (404, "automation_draft_missing") + assert read(api, path).json() == before + + original = f"{DRAFTS}/requests/first" + with api.store.write() as unit: + member = unit.members.by_user("home", USER) + restricted = replace( + member, + exceptions=(PermissionRule(Permission.TASKS_CREATE, False),), + revision=member.revision + 1, + ) + unit.members.save(restricted, member.revision) + assert read(api, path).json() == before + assert read(api, original).status_code == 403 + assert save(api, "first").status_code == 403 + with api.store.write() as unit: + unit.members.save( + replace(restricted, status=MemberStatus.SUSPENDED, revision=restricted.revision + 1), + restricted.revision, + ) + assert all(read(api, route).status_code == 403 for route in (DRAFTS, path, original)) + assert save(api, "edit", rule_id=rule_id, revision="1").status_code == 403 + + +def test_openapi_draft_revision_pattern_matches_the_exact_signed_range(api): + schema = api.client.get("/api/v1/openapi.json").json()["components"]["schemas"] + pattern = schema["AutomationDraftBody"]["properties"]["expected_revision"]["pattern"] + assert all(re.fullmatch(pattern, value) is None for value in ("-1", "01", "1.0", "+1")) + for exponent in range(19): + boundary = (MAX_REVISION // 10**exponent) * 10**exponent + for revision in (10**exponent, boundary - 1, boundary, boundary + 1): + assert bool(re.fullmatch(pattern, str(revision))) == (0 <= revision <= MAX_REVISION) + assert re.fullmatch(pattern, "0") + assert re.fullmatch(pattern, str(10**19)) is None + + +def test_concurrent_draft_edits_and_original_request_replay(api): + api.user(USER, True) + first = save(api, "initial").json() + rule_id = first["result"]["rule_id"] + assert save(api, "initial").json() == first + assert read(api, f"{DRAFTS}/requests/initial").json() == first + missing = read(api, f"{DRAFTS}/requests/unknown") + assert (missing.status_code, missing.json()["code"]) == (404, "operation_missing") + + contenders = [ + ( + key, + api.headers(key) | CONTEXT, + RULE + | {"rule_id": rule_id, "expected_revision": "1", "action": ACTION | {"title": key}}, + ) + for key in ("first-edit", "second-edit") + ] + start = Barrier(2) + + def edit(item): + key, headers, body = item + start.wait(timeout=10) + return key, api.client.post(DRAFTS, headers=headers, json=body) + + with ThreadPoolExecutor(max_workers=2) as pool: + results = sorted(pool.map(edit, contenders), key=lambda item: item[1].status_code) + (winner, accepted), (_, rejected) = results + assert accepted.status_code == 200 and accepted.json()["result"]["revision"] == "2" + assert (rejected.status_code, rejected.json()["code"]) == (409, "revision_conflict") + assert read(api, f"{DRAFTS}/requests/{winner}").json() == accepted.json() + wrong_payload = save(api, winner, rule_id=rule_id, revision="1") + assert (wrong_payload.status_code, wrong_payload.json()["code"]) == ( + 409, + "idempotency_conflict", + ) + latest = read(api, f"{DRAFTS}/{rule_id}").json() + assert latest["revision"] == "2" and latest["action"]["title"] == winner + assert read(api, f"{DRAFTS}/requests/initial").json() == first + with closing(sqlite3.connect(api.store.path)) as connection: + rows = connection.execute( + "SELECT revision,definition FROM automation_draft_revisions " + "WHERE household_id='home' AND rule_id=? ORDER BY revision", + (rule_id,), + ).fetchall() + assert [revision for revision, _ in rows] == [1, 2] + assert [ + AutomationRule.from_document(JsonDocument(definition)).task.title + for _, definition in rows + ] == [ACTION["title"], winner] diff --git a/tests/backend/test_inventory_catalog_storage.py b/tests/backend/test_inventory_catalog_storage.py index dd628531..a9b46fab 100644 --- a/tests/backend/test_inventory_catalog_storage.py +++ b/tests/backend/test_inventory_catalog_storage.py @@ -156,7 +156,7 @@ def test_schema19_upgrade_preserves_legacy_stock_and_rewards(tmp_path, monkeypat assert path.read_bytes() == baseline store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert [row[:-2] for row in db.execute("SELECT * FROM inventory_movements")] == previous with store.read() as unit: assert unit.inventory.products("home", "", 25) == () diff --git a/tests/backend/test_inventory_movements.py b/tests/backend/test_inventory_movements.py index fa305ffa..1b903bc3 100644 --- a/tests/backend/test_inventory_movements.py +++ b/tests/backend/test_inventory_movements.py @@ -102,7 +102,7 @@ def legacy(root, monkeypatch): assert path.read_bytes() == original store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] assert [ row[:-2] for row in db.execute("SELECT * FROM inventory_movements ORDER BY position") diff --git a/tests/backend/test_inventory_recurrence.py b/tests/backend/test_inventory_recurrence.py index 64ded009..e334fba5 100644 --- a/tests/backend/test_inventory_recurrence.py +++ b/tests/backend/test_inventory_recurrence.py @@ -459,7 +459,7 @@ def test_genuine_schema_16_inventory_migration_preserves_points_and_is_atomic( connection.execute("SELECT * FROM points_task_receipts ORDER BY position").fetchall() == before ) - assert connection.execute("PRAGMA user_version").fetchone() == (31,) + assert connection.execute("PRAGMA user_version").fetchone() == (32,) def test_real_task_material_posts_in_both_compositions_and_keeps_shortage_pending(api): diff --git a/tests/backend/test_pantry_replenishment.py b/tests/backend/test_pantry_replenishment.py index 09f4797e..fefd39d4 100644 --- a/tests/backend/test_pantry_replenishment.py +++ b/tests/backend/test_pantry_replenishment.py @@ -195,7 +195,7 @@ def test_upgrade_and_activated_restore_preserve_stock_and_policy_receipts(tmp_pa assert path.read_bytes() == baseline store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] for table, rows in existing.items(): actual = db.execute("SELECT * FROM " + table).fetchall() @@ -267,7 +267,7 @@ def test_snapshot_rejects_fractional_piece_threshold(tmp_path, minimum, target): configure(commands, "policy", product, "1", "2") archive = tmp_path / "archive" snapshots = SQLiteSnapshots(store, archive, store.installation, Clock()) - assert snapshots.create("valid").schema_version == 31 + assert snapshots.create("valid").schema_version == 32 with closing(sqlite3.connect(store.path, autocommit=True)) as db: db.execute("UPDATE inventory_replenishment SET minimum=?,target=?", (minimum, target)) with pytest.raises(DatabaseRejected, match="invalid_snapshot_records"): diff --git a/tests/backend/test_physical_receipt_return.py b/tests/backend/test_physical_receipt_return.py index 810013f3..e2d58ab3 100644 --- a/tests/backend/test_physical_receipt_return.py +++ b/tests/backend/test_physical_receipt_return.py @@ -404,7 +404,7 @@ def test_schema_28_migration_returns_and_activated_restore(tmp_path, monkeypatch assert path.read_bytes() == before store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] for table, rows in old.items(): actual = db.execute("SELECT * FROM " + table).fetchall() diff --git a/tests/backend/test_physical_receipt_void.py b/tests/backend/test_physical_receipt_void.py index 5841295e..f7c1cf96 100644 --- a/tests/backend/test_physical_receipt_void.py +++ b/tests/backend/test_physical_receipt_void.py @@ -348,7 +348,7 @@ def test_schema_26_upgrade_restart_and_activated_restore(tmp_path, monkeypatch): assert path.read_bytes() == original_bytes store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] for table, rows in existing.items(): actual = db.execute("SELECT * FROM " + table).fetchall() diff --git a/tests/backend/test_point_allocation_storage.py b/tests/backend/test_point_allocation_storage.py index 2791229a..1f5ba9cd 100644 --- a/tests/backend/test_point_allocation_storage.py +++ b/tests/backend/test_point_allocation_storage.py @@ -53,7 +53,7 @@ def test_real_schema17_migrates_without_rewriting_pending_or_posted_awards(tmp_p assert path.read_bytes() == before store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as connection: - assert connection.execute("PRAGMA user_version").fetchone() == (31,) + assert connection.execute("PRAGMA user_version").fetchone() == (32,) assert ( connection.execute("SELECT * FROM points_task_receipts ORDER BY position").fetchall() == original @@ -76,7 +76,7 @@ def report(user, admin=False): checkpoint = SQLiteSnapshots(store, tmp_path / "checkpoint", installation, Clock()).create( "legacy" ) - assert checkpoint.schema_version == 31 + assert checkpoint.schema_version == 32 def test_concurrent_replay_freezes_once_and_reopened_pending_work_uses_fresh_policy(tmp_path): diff --git a/tests/backend/test_posted_receipt_correction.py b/tests/backend/test_posted_receipt_correction.py index 9fd51ac4..473ac97b 100644 --- a/tests/backend/test_posted_receipt_correction.py +++ b/tests/backend/test_posted_receipt_correction.py @@ -433,7 +433,7 @@ def test_schema_27_migration_legacy_history_and_activated_restore(tmp_path, monk assert path.read_bytes() == before store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] for table, rows in old.items(): actual = db.execute("SELECT * FROM " + table).fetchall() diff --git a/tests/backend/test_purchase_balance.py b/tests/backend/test_purchase_balance.py index a31818e5..4a4afb0c 100644 --- a/tests/backend/test_purchase_balance.py +++ b/tests/backend/test_purchase_balance.py @@ -305,7 +305,7 @@ def test_v25_migration_and_activated_restore_of_cancelled_balances(tmp_path, mon assert path.read_bytes() == baseline store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] for table, rows in existing.items(): actual = db.execute("SELECT * FROM " + table).fetchall() diff --git a/tests/backend/test_purchase_sessions.py b/tests/backend/test_purchase_sessions.py index 89c94562..46624260 100644 --- a/tests/backend/test_purchase_sessions.py +++ b/tests/backend/test_purchase_sessions.py @@ -344,7 +344,7 @@ def test_schema_24_upgrade_and_restore_of_sessions_and_original_receipts(tmp_pat assert path.read_bytes() == baseline store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] for table, rows in existing.items(): expected = [(*row, 0) for row in rows] if table == "shopping_purchases" else rows @@ -473,7 +473,7 @@ def test_store_migration_keeps_historical_data_and_unnamed_originals( database.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] for table, rows in original.items(): migrated = db.execute("SELECT * FROM " + table).fetchall() diff --git a/tests/backend/test_recurrence_frontier.py b/tests/backend/test_recurrence_frontier.py index 6a3f0416..921295df 100644 --- a/tests/backend/test_recurrence_frontier.py +++ b/tests/backend/test_recurrence_frontier.py @@ -61,7 +61,7 @@ def test_frontier_commits_reopens_and_never_creates_task_or_business_evidence(tm SQLiteSnapshots(store, tmp_path / "checkpoint", store.installation, Clock()) .create("frontier") .schema_version - == 31 + == 32 ) diff --git a/tests/backend/test_recurrence_lifecycle_migration.py b/tests/backend/test_recurrence_lifecycle_migration.py index 221e251e..9f06876b 100644 --- a/tests/backend/test_recurrence_lifecycle_migration.py +++ b/tests/backend/test_recurrence_lifecycle_migration.py @@ -57,7 +57,7 @@ def test_supported_schema9_keeps_fixed_work_pristine_relative_progress_and_priva assert private.routine_participation_summaries is False and private.revision == 2 assert facts(store.path, tables) == original with restarted._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 32 with restarted.read() as unit: assert unit.recurrence.relative_inbox_after("home") == 0 @@ -81,7 +81,7 @@ def test_independent_snapshot_inspection_after_migration_preserves_every_origina store, archive, store.installation, SimpleNamespace(now=lambda: 1800000000000) ) checkpoint = snapshots.create("source-nine") - assert checkpoint.schema_version == 31 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 32 and snapshots.inspect() == checkpoint assert facts(archive / "domus.sqlite3", tables) == original assert store.path.read_bytes() == before @@ -136,7 +136,7 @@ def test_genuine_schema11_horizon_migration_preserves_private_preferences_and_hi preference = unit.calendar_preferences.get("home", member.member_id) assert preference.week_start is WeekStart.SUNDAY and preference.revision == 2 with restarted._connection() as connection: - assert _verify_database(connection, restarted, previous=False) == 31 + assert _verify_database(connection, restarted, previous=False) == 32 assert facts(store.path, tables) == before diff --git a/tests/backend/test_restore_source.py b/tests/backend/test_restore_source.py index 5b0c6492..77359972 100644 --- a/tests/backend/test_restore_source.py +++ b/tests/backend/test_restore_source.py @@ -19,7 +19,7 @@ def test_bare_source_and_managed_generation_source_are_explicit_and_roundtrip(tm bare_root.mkdir(mode=0o700) adapter, store, _, _ = restoration_fixture(bare_root) result = adapter.prepare("restore-bare") - assert result.source == RestoreSource(store.installation, 31, None, None) + assert result.source == RestoreSource(store.installation, 32, None, None) assert result.document().decode()["format_version"] == 2 assert PreparedRestoration.from_value(result.document().decode()) == result root, slot, selection = generation_fixture(tmp_path) @@ -39,7 +39,7 @@ def test_bare_source_and_managed_generation_source_are_explicit_and_roundtrip(tm ).prepare("restore-generation") assert prepared.source.generation_id == selection.generation_id assert prepared.source.identity_sha256 == selection.document().fingerprint - assert prepared.source.schema_version == 31 + assert prepared.source.schema_version == 32 assert PreparedRestoration.from_value(prepared.document().decode()) == prepared finally: storage.close() diff --git a/tests/backend/test_rewards_storage.py b/tests/backend/test_rewards_storage.py index 2bcfc381..65683361 100644 --- a/tests/backend/test_rewards_storage.py +++ b/tests/backend/test_rewards_storage.py @@ -204,7 +204,7 @@ def test_real_schema18_migrates_without_creating_reservations(tmp_path, monkeypa assert path.read_bytes() == baseline store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as connection: - assert connection.execute("PRAGMA user_version").fetchone() == (31,) + assert connection.execute("PRAGMA user_version").fetchone() == (32,) assert ( connection.execute("SELECT * FROM points_task_receipts ORDER BY position").fetchall() == prior diff --git a/tests/backend/test_shared_shopping.py b/tests/backend/test_shared_shopping.py index f68bf37c..0e275d7d 100644 --- a/tests/backend/test_shared_shopping.py +++ b/tests/backend/test_shared_shopping.py @@ -454,7 +454,7 @@ def test_v23_migration_and_activated_restore_of_extra_receipts(tmp_path, monkeyp assert path.read_bytes() == baseline store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] for table, rows in existing.items(): expected = [(*row, 0) for row in rows] if table == "shopping_purchases" else rows diff --git a/tests/backend/test_shopping_storage.py b/tests/backend/test_shopping_storage.py index f2d9331f..90e1ebbf 100644 --- a/tests/backend/test_shopping_storage.py +++ b/tests/backend/test_shopping_storage.py @@ -144,7 +144,7 @@ def test_upgrade_v22_preserves_pantry_and_restore_recovers_pending_and_posted( assert path.read_bytes() == baseline store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (31,) + assert db.execute("PRAGMA user_version").fetchone() == (32,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] for table, rows in existing.items(): actual = db.execute("SELECT * FROM " + table).fetchall() diff --git a/tests/backend/test_sqlite_history.py b/tests/backend/test_sqlite_history.py index f4048958..08f9ea39 100644 --- a/tests/backend/test_sqlite_history.py +++ b/tests/backend/test_sqlite_history.py @@ -81,7 +81,7 @@ def test_frozen_old_schema_migrates_without_losing_existing_evidence(tmp_path, v store = SQLiteDatabase(path, Installation("047cc6fb-dfb0-4fa4-b3c3-e0fe54d116b6", "edge")) store.initialize() with store._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 32 assert connection.execute("SELECT count(*) FROM retained_operations").fetchone()[0] == len( before.get("retained_operations", []) ) diff --git a/tests/backend/test_sqlite_identity.py b/tests/backend/test_sqlite_identity.py index 96accd50..df7fb5ed 100644 --- a/tests/backend/test_sqlite_identity.py +++ b/tests/backend/test_sqlite_identity.py @@ -177,7 +177,7 @@ def test_v1_upgrade_preserves_household_receipts_audit_and_pending_outbox(tmp_pa unit.members.save(member(), 0) unit.policies.save(policy(), 0) with closing(sqlite3.connect(path)) as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 32 assert connection.execute("PRAGMA foreign_key_check").fetchall() == [] diff --git a/tests/backend/test_sqlite_member_profiles.py b/tests/backend/test_sqlite_member_profiles.py index 0c90bb5f..4d86caa5 100644 --- a/tests/backend/test_sqlite_member_profiles.py +++ b/tests/backend/test_sqlite_member_profiles.py @@ -302,7 +302,7 @@ def test_real_historical_input_upgrade_preserves_every_original_table_and_adds_d current.household_id, current.member_id ) == MemberPreferences(current.member_id, current.household_id) with store._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 32 assert connection.execute("PRAGMA foreign_key_check").fetchall() == [] @@ -350,7 +350,7 @@ def test_snapshot_independently_preserves_both_profiles_without_changing_member_ archive = tmp_path / "snapshot" snapshots = SQLiteSnapshots(store, archive, store.installation, Clock()) checkpoint = snapshots.create("original") - assert checkpoint.schema_version == 31 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 32 and snapshots.inspect() == checkpoint with SQLiteDatabase(archive / "domus.sqlite3", store.installation).read() as unit: assert unit.presentations.get("home", "member_1") == public assert unit.preferences.get("home", "member_1") == private diff --git a/tests/backend/test_sqlite_recovery.py b/tests/backend/test_sqlite_recovery.py index 827e4053..aebac1e2 100644 --- a/tests/backend/test_sqlite_recovery.py +++ b/tests/backend/test_sqlite_recovery.py @@ -160,7 +160,7 @@ def test_compatible_migration_preserves_identity_history_and_adds_empty_recovery assert unit.outbox.pending()[0].event_id == "old-operation" assert unit.recoveries.pending("home", 3000) == () with closing(sqlite3.connect(path)) as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 32 def test_failed_v2_upgrade_rolls_back_all_new_schema_and_replay_data( diff --git a/tests/backend/test_sqlite_recurrence.py b/tests/backend/test_sqlite_recurrence.py index affb5d4c..ee46fc54 100644 --- a/tests/backend/test_sqlite_recurrence.py +++ b/tests/backend/test_sqlite_recurrence.py @@ -233,7 +233,7 @@ def test_normal_transactions_refuse_schema7_until_explicit_atomic_upgrade(tmp_pa with store.read() as unit: assert unit.recurrence.schedules("home") == () with store._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 32 assert tuple(connection.execute("SELECT * FROM receipts ORDER BY operation_id")) == original assert connection.execute("PRAGMA foreign_key_check").fetchall() == [] diff --git a/tests/backend/test_sqlite_recurrence_integrity.py b/tests/backend/test_sqlite_recurrence_integrity.py index 3001cce9..75db98cf 100644 --- a/tests/backend/test_sqlite_recurrence_integrity.py +++ b/tests/backend/test_sqlite_recurrence_integrity.py @@ -37,7 +37,7 @@ def test_checkpoint_verifies_and_reopens_real_rule_progress_slot_and_original_re snapshots = SQLiteSnapshots(store, tmp_path / "snapshot", store.installation, Clock()) before = store.path.read_bytes() checkpoint = snapshots.create("recurrence") - assert checkpoint.schema_version == 31 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 32 and snapshots.inspect() == checkpoint assert store.path.read_bytes() == before reopened = SQLiteDatabase(tmp_path / "snapshot/domus.sqlite3", store.installation) with reopened.read() as unit: @@ -264,7 +264,7 @@ def test_pattern_edit_requires_matching_progress_and_preserves_existing_slot_sna SQLiteSnapshots(store, tmp_path / "edited", store.installation, Clock()) .create("edited") .schema_version - == 31 + == 32 ) diff --git a/tests/backend/test_sqlite_snapshots.py b/tests/backend/test_sqlite_snapshots.py index be638b6a..f32ecc0a 100644 --- a/tests/backend/test_sqlite_snapshots.py +++ b/tests/backend/test_sqlite_snapshots.py @@ -37,7 +37,7 @@ def test_snapshot_contains_verified_private_identity_checkpoint_and_all_atomic_r before = store.path.read_bytes() result = snapshots.create("snapshot-1") assert ( - result.schema_version == 31 + result.schema_version == 32 and result.captured_at == 2000 and result.last_committed_at == 100 ) diff --git a/tests/backend/test_sqlite_task_integrity.py b/tests/backend/test_sqlite_task_integrity.py index 90cc7b5d..27ef4c79 100644 --- a/tests/backend/test_sqlite_task_integrity.py +++ b/tests/backend/test_sqlite_task_integrity.py @@ -158,7 +158,7 @@ def test_actual_unit_snapshot_and_reopen_keep_task_cycles_and_one_atomic_receipt before = store.path.read_bytes() snapshots = SQLiteSnapshots(store, tmp_path / "snapshot", store.installation, Clock()) checkpoint = snapshots.create("tasks") - assert checkpoint.schema_version == 31 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 32 and snapshots.inspect() == checkpoint assert store.path.read_bytes() == before copy = SQLiteDatabase(tmp_path / "snapshot/domus.sqlite3", store.installation) with copy.read() as unit: @@ -433,5 +433,5 @@ def test_schema4_upgrade_failure_preserves_the_exact_old_database_and_history( assert unit.tasks.policy("home") is None and unit.tasks.definitions("home") == () assert unit.receipts.get_operation("home", "human", "operation-a").historical with store._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 32 assert connection.execute("SELECT count(*) FROM retained_operations").fetchone()[0] == 2 diff --git a/tests/backend/test_sqlite_task_materials.py b/tests/backend/test_sqlite_task_materials.py index d3aec601..825c5401 100644 --- a/tests/backend/test_sqlite_task_materials.py +++ b/tests/backend/test_sqlite_task_materials.py @@ -58,7 +58,7 @@ def test_original_schema5_migration_preserves_history_and_legacy_request_fingerp store = SQLiteDatabase(path, Installation("047cc6fb-dfb0-4fa4-b3c3-e0fe54d116b6", "edge")) store.initialize(require_existing=True) with store._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 32 for table, rows in before.items(): assert [tuple(row) for row in connection.execute(f"SELECT * FROM {table}")] == rows with store.read() as unit: @@ -134,7 +134,7 @@ def test_real_file_material_cas_preserves_source_pending_and_confirmed_totals(tm checkpoint = SQLiteSnapshots(store, tmp_path / "snapshot", store.installation, Clock()).create( "materials" ) - assert checkpoint.schema_version == 31 + assert checkpoint.schema_version == 32 copy = SQLiteDatabase(tmp_path / "snapshot/domus.sqlite3", store.installation) with copy.read() as unit: assert unit.task_materials.get("home", "intent") == final @@ -441,7 +441,7 @@ def test_schema5_real_offline_activation_upgrades_only_target_and_keeps_original SQLiteSnapshots(selected.database, tmp_path / "new-snapshot", installation, Clock()) .create("new") .schema_version - == 31 + == 32 ) finally: selected.close() diff --git a/tests/backend/test_sqlite_task_reviews.py b/tests/backend/test_sqlite_task_reviews.py index ec82dad2..a3c30d2f 100644 --- a/tests/backend/test_sqlite_task_reviews.py +++ b/tests/backend/test_sqlite_task_reviews.py @@ -80,6 +80,7 @@ def test_original_schema6_migration_preserves_rows_and_projects_existing_cause(t "shopping_receipt_returns", "inventory_locations", "inventory_transfers", + "automation_draft_revisions", } assert set(upgraded) == set(original) | added | { "member_presentations", @@ -93,7 +94,7 @@ def test_original_schema6_migration_preserves_rows_and_projects_existing_cause(t upgraded[table] == values for table, values in original.items() if table != "households" ) assert all(upgraded[table] == [] for table in added) - assert connection.execute("PRAGMA user_version").fetchone()[0] == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 32 service = queries(store, HumanIdentity("ha_admin", True, True, False)) detail = service.occurrence("identity-15") assert detail.dependency_review_required and len(detail.dependency_reviews.items) == 1 @@ -363,7 +364,7 @@ def test_original_schema6_checkpoint_activation_migrates_only_the_prepared_targe SQLiteSnapshots(selected.database, tmp_path / "new-checkpoint", INSTALLATION, Clock()) .create("new") .schema_version - == 31 + == 32 ) finally: selected.close() diff --git a/tests/backend/test_task_categories.py b/tests/backend/test_task_categories.py index ee661775..7c627529 100644 --- a/tests/backend/test_task_categories.py +++ b/tests/backend/test_task_categories.py @@ -57,7 +57,7 @@ def test_schema14_category_ddl_rolls_back_to_the_exact_original_bytes(tmp_path, assert definition.content.tags == ("Garden",) assert definition.content.category_id is None and definition.category_label is None with closing(sqlite3.connect(path)) as connection: - assert connection.execute("PRAGMA user_version").fetchone() == (31,) + assert connection.execute("PRAGMA user_version").fetchone() == (32,) def test_protected_category_commands_preserve_exact_history_and_calendar_counts(api): diff --git a/tests/backend/test_task_restoration.py b/tests/backend/test_task_restoration.py index 587f94e5..3bd817f3 100644 --- a/tests/backend/test_task_restoration.py +++ b/tests/backend/test_task_restoration.py @@ -32,7 +32,7 @@ def test_restore_keeps_original_task_state_and_retains_later_completion_as_proce ) adapter = SQLiteRestorations(store, archive, target, store.installation, Clock(), checkpoint) prepared = adapter.prepare("restore-tasks") - assert prepared.source.schema_version == checkpoint.schema_version == 31 + assert prepared.source.schema_version == checkpoint.schema_version == 32 assert prepared.operation_count == 3 and prepared.current_operations == 2 assert adapter.inspect() == prepared and store.path.read_bytes() == source_bytes assert (archive / "domus.sqlite3").read_bytes() == checkpoint_bytes diff --git a/tests/containers/administration_rollback_fixture.py b/tests/containers/administration_rollback_fixture.py index 404b23f3..76815d32 100644 --- a/tests/containers/administration_rollback_fixture.py +++ b/tests/containers/administration_rollback_fixture.py @@ -111,7 +111,7 @@ def main(): assert phase in ("initialize", "later", "refuse", "restored", "rollback") assert mode in ("native", "standalone") and delivery in ("pending", "acknowledged") assert os.getuid() == os.getgid() == 65532 - assert SCHEMA_VERSION == (31 if phase in ("later", "restored") else 9) + assert SCHEMA_VERSION == (32 if phase in ("later", "restored") else 9) if phase == "refuse": saved = json.loads(RECORD.read_text()) selected = ROOT / "generations" / saved["selected_generation"] / "domus.sqlite3" diff --git a/tests/containers/restore_fixture.py b/tests/containers/restore_fixture.py index d72d1bc5..8a0d7b19 100644 --- a/tests/containers/restore_fixture.py +++ b/tests/containers/restore_fixture.py @@ -109,7 +109,7 @@ def terminate(source, target, **kwargs): else: raise AssertionError("Unknown fixture operation") with storage.database._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 31 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 32 private_layout() print( json.dumps( diff --git a/tests/containers/test_administration_image.py b/tests/containers/test_administration_image.py index 0ca0e93a..c4313513 100644 --- a/tests/containers/test_administration_image.py +++ b/tests/containers/test_administration_image.py @@ -42,7 +42,7 @@ def test_current_image_persists_independent_profiles_in_owned_runtime(image, mod from domus.infrastructure.sqlite import SQLiteDatabase, SCHEMA_VERSION from domus.infrastructure.sqlite_snapshots import SQLiteSnapshots -assert SCHEMA_VERSION == 31 +assert SCHEMA_VERSION == 32 class Human: user_id = 'fictional_profile_ha_user' def current(self): @@ -110,7 +110,7 @@ def factory(): unit.preferences.save(private, 1) checkpoint = SQLiteSnapshots(store, Path(directory) / 'snapshot', storage.installation, clock).create('profile-checkpoint') - assert checkpoint.schema_version == 31 + assert checkpoint.schema_version == 32 assert len(tuple((Path(directory) / 'snapshot').iterdir())) == 3 finally: runtime.close() @@ -363,7 +363,7 @@ def test_actual_compatible_application_data_and_generation_rollback( assert restored["ui"] == later["ui"] assert restored["generation_id"] == later["selected_generation"] assert restored["state"] == before["state"] - assert restored["schema"] == refusal["refused_schema"] == 31 + assert restored["schema"] == refusal["refused_schema"] == 32 assert restored["original_operations_preserved"] is True assert rolled_back["ui"] == before["ui"] assert rolled_back["state"] == before["state"] @@ -427,7 +427,7 @@ def runtime(): raise AssertionError('Old application accepted an unsupported schema') assert path.read_bytes() == original else: - assert SCHEMA_VERSION == (14 if phase == 'old' else 31) + assert SCHEMA_VERSION == (14 if phase == 'old' else 32) active = runtime() try: assert active.storage is not None diff --git a/tests/containers/test_app_compatibility.py b/tests/containers/test_app_compatibility.py index c1b4d8d7..89072cdc 100644 --- a/tests/containers/test_app_compatibility.py +++ b/tests/containers/test_app_compatibility.py @@ -127,7 +127,7 @@ def test_actual_older_image_refuses_selected_generation_without_changing_any_fil indirect=["previous_image"], ) def test_real_older_image_upgrades_replays_and_restores_its_pre_upgrade_snapshot( - image, previous_image, data_volume, old_schema, expected_schema=31 + image, previous_image, data_volume, old_schema, expected_schema=32 ): old = "domus-upgrade-old-" + uuid.uuid4().hex new = "domus-upgrade-new-" + uuid.uuid4().hex diff --git a/tests/containers/test_app_image.py b/tests/containers/test_app_image.py index d6a2e9c2..231cee45 100644 --- a/tests/containers/test_app_image.py +++ b/tests/containers/test_app_image.py @@ -129,7 +129,7 @@ def data_volume(image: str): def test_real_nonroot_listener_rejects_forgery_and_retains_storage_and_replay_on_restart( image: str, data_volume: str, - expected_schema: int = 31, + expected_schema: int = 32, ) -> None: name = "domus-persistent-test-" + uuid.uuid4().hex try: @@ -535,7 +535,7 @@ def test_packaged_console_restore_restart_and_latest_history_rollback( ) ) assert activated["state"] == "active" - assert activated["activation"]["rollback_snapshot"]["schema_version"] == 31 + assert activated["activation"]["rollback_snapshot"]["schema_version"] == 32 assert docker("start", name).returncode == 0 ready(name, standalone=mode == "standalone") active = successful(packaged_fixture(image, volume, "active", delivery)) diff --git a/tests/containers/test_recurrence_image.py b/tests/containers/test_recurrence_image.py index 9eacd6a3..c52c88d9 100644 --- a/tests/containers/test_recurrence_image.py +++ b/tests/containers/test_recurrence_image.py @@ -56,7 +56,7 @@ def test_current_image_executes_recurrence_creation_planning_and_closed_record_c schedule_document, read_schedule, progress_document, read_progress, slot_document, read_slot, frontier_document, read_frontier, ) -assert SCHEMA_VERSION == 31 +assert SCHEMA_VERSION == 32 policy = TimePolicy('Europe/Madrid', TIMEZONE_DATA_IDENTITY) pattern = parse_fixed_pattern('FREQ=DAILY;COUNT=2', NominalTime(datetime(2026, 3, 29, 2, 30))) times = PinnedRecurrenceTime() diff --git a/tests/containers/test_relative_recurrence_image.py b/tests/containers/test_relative_recurrence_image.py index de393deb..97bc48b0 100644 --- a/tests/containers/test_relative_recurrence_image.py +++ b/tests/containers/test_relative_recurrence_image.py @@ -43,7 +43,7 @@ def test_packaged_owned_worker_restarts_and_materializes_a_relative_successor(im MODE = sys.argv[1] ORIGIN = 'https://domus.fixture' -assert SCHEMA_VERSION == 31 +assert SCHEMA_VERSION == 32 class FixtureHuman: def current(self): diff --git a/tests/fixtures/sqlite/v31-automation-drafts-source.sql b/tests/fixtures/sqlite/v31-automation-drafts-source.sql new file mode 100644 index 00000000..09d46d79 --- /dev/null +++ b/tests/fixtures/sqlite/v31-automation-drafts-source.sql @@ -0,0 +1,302 @@ +-- Exported by Edge.32 at 43bace9576b9468f789fe9975a3dd5fe427d83ae. +PRAGMA application_id=1146047829; +PRAGMA user_version=31; +BEGIN TRANSACTION; +CREATE TABLE audit(operation_id TEXT PRIMARY KEY, household_id TEXT NOT NULL REFERENCES households(household_id), actor_id TEXT NOT NULL, action TEXT NOT NULL, command_key TEXT NOT NULL, detail TEXT NOT NULL, created_at INTEGER NOT NULL); +INSERT INTO "audit" VALUES('identity-2','home','ha_admin','household.setup','setup','{"administrator_member_id":"identity-1","mapping_mode":"all_ha_administrators","transition":"household.configured"}',100); +INSERT INTO "audit" VALUES('identity-5','home','ha_admin','inventory.register-product','new','{"base_unit":"millilitre","name":"Oil"}',100); +INSERT INTO "audit" VALUES('identity-7','home','ha_admin','inventory.intake','intake-v20','{"product_id":"identity-3","quantity":"4.250001"}',100); +INSERT INTO "audit" VALUES('identity-11','home','ha_admin','task.create','task-v20','{"request":{"content":{"description":"","priority":"normal","tags":[],"title":"Refill the dispenser"},"expected_revision":0,"materials":[{"planned_quantity":"2","reference_id":"identity-4"}],"overrides":{"adult_performer_may_approve":null,"claim_allowed":null,"dependency_gate":null,"eligible_roles":null,"material_recording":null,"point_value_minor":null,"task_scoped_material_consumption":null,"verification":null},"state":"active"},"result":{"assignee_ids":[],"definition_id":"identity-9","definition_revision":1,"occurrence_id":"identity-10","prerequisite_ids":[],"required_subtask_ids":[],"revision":1,"state":"available","state_reason":""},"transition":"task.created"}',100); +INSERT INTO "audit" VALUES('identity-13','home','ha_admin','inventory.commit-effect','reserve-v20','{"kind":"reservation","occurrence_id":"identity-10","quantity":"2","reference_id":"identity-4"}',100); +INSERT INTO "audit" VALUES('identity-18','home','ha_admin','task.complete','complete-v20','{"request":{"expected_revision":1,"material_usages":[{"line_id":"identity-8","quantity":"1.125"}],"occurrence_id":"identity-10","performed_at":95,"performer_ids":["identity-1"]},"result":{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-14","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-10","performed_at":95,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":0,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-9","definition_revision":1,"materials":[{"action_required":null,"cycle_id":"identity-14","effect_revision":1,"intent_id":"identity-15","line_id":"identity-8","message":"Inventory confirmed this material consumption.","movement_id":"identity-17","pending_reason":null,"quantity":"1.125","revision":2,"state":"posted","submitted_quantity":"1.125"}],"occurrence_id":"identity-10","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":""},"transition":"task.completed"}',100); +INSERT INTO "audit" VALUES('identity-21','home','ha_admin','task.material.settle','task-correct-v20','{"request":{"action":"correct","cycle_id":"identity-14","expected_revision":2,"intent_id":"identity-15","occurrence_id":"identity-10","quantity":"1","reason":"Actual use"},"result":{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-14","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-10","performed_at":95,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":0,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-9","definition_revision":1,"material":{"action_required":null,"confirmed_effect_revision":2,"confirmed_quantity":"1","cycle_id":"identity-14","effect_revision":2,"intent_id":"identity-15","line_id":"identity-8","message":"Inventory confirmed the corrected total.","movement_id":"identity-20","pending_reason":null,"posted_at":100,"quantity":"1","revision":4,"state":"corrected","submitted_quantity":"1.125"},"material_action":"correct","material_source":{"cycle_id":"identity-14","definition_revision":1,"household_id":"home","intent_id":"identity-15","line_id":"identity-8","occurrence_id":"identity-10","performer_ids":["identity-1"]},"occurrence_id":"identity-10","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":""},"transition":"task.material.settled"}',100); +INSERT INTO "audit" VALUES('domus_GpP8fpUm2fz7CZq_DVZWCyty-HjUD5F2','home','ha_admin','inventory.register-product','replenishment-v21-product','{"base_unit":"gram","name":"Oats"}',100); +INSERT INTO "audit" VALUES('domus_5M2TxM_QPWHHasJ32kAB1u-iwkU0UbKo','home','ha_admin','inventory.intake','replenishment-v21-intake','{"product_id":"domus_eFvAbbTLuCtrtEJ6KTUG1tbCwMVBVvhr","quantity":"1.125"}',100); +INSERT INTO "audit" VALUES('domus_LgNq0sL9tNZAQlYM5bW1lfH9nJhwqQkn','home','ha_admin','inventory.correct-intake','replenishment-v21-correction','{"movement_id":"domus_h8MiNTHX876pXMCj0hHOVrqRRfqTAeup","product_id":"domus_eFvAbbTLuCtrtEJ6KTUG1tbCwMVBVvhr","reason":"Duplicate intake"}',100); +INSERT INTO "audit" VALUES('domus_uZBk2wqcsgcRwf2AK2z6u7Lvswbn89-q','home','ha_admin','inventory.configure-replenishment','policy-v22','{"expected_revision":"0","minimum":"3","product_id":"identity-3","target":"5"}',1794318537054); +INSERT INTO "audit" VALUES('domus_wcbzJQaTFNzjQNlu6utgWWB-NWbHrHqe','home','ha_admin','shopping.purchase','buy-v23','{"name":null,"product_id":"identity-3","quantity":"2"}',1794321336330); +INSERT INTO "audit" VALUES('domus_yKfFr-rfKW_77yhBlfk9Pmtt3cSCrVnS','home','ha_admin','shopping.receive','arrival-v23','{"expected_revision":"1","purchase_id":"domus_7DadKyZ9oOozqAgfBT4tHLtCE-g-evi7","quantity":"0.25"}',1794321336332); +INSERT INTO "audit" VALUES('domus_HlimXSAwLqyeExfVIdDvg-WR1Ip59Lny','home','ha_admin','shopping.receive','pending-v23','{"expected_revision":"2","purchase_id":"domus_7DadKyZ9oOozqAgfBT4tHLtCE-g-evi7","quantity":"0.5"}',1794321336335); +INSERT INTO "audit" VALUES('domus_fNMB0nHFvIQUSSNeBmKY9Zf3T_4SFMS8','home','ha_admin','shopping.post-receipt','posted-v23','{"purchase_id":"domus_7DadKyZ9oOozqAgfBT4tHLtCE-g-evi7","receipt_id":"domus_HYnlK7j7ShiTOsPacjrNxt2m6voRSJML"}',1794321336338); +INSERT INTO "audit" VALUES('domus_rrgvH6kGMqVqilsxdvzDwmdFDXSWaQlk','home','ha_admin','shopping.add-extra','session-tracked-v24','{"name":null,"product_id":"identity-3","quantity":"0.000002"}',100); +INSERT INTO "audit" VALUES('domus_reoKWG7jjwtJVqevLEuFNg2vHTTN2q9N','home','ha_admin','shopping.add-extra','session-active-v24','{"name":"Lemons","product_id":null,"quantity":"2"}',100); +INSERT INTO "audit" VALUES('domus_eF7j-7jnJvaKFNk97Wwbuele0gdsJKTT','home','ha_admin','shopping.add-extra','session-cleared-v24','{"name":"Spare","product_id":null,"quantity":"1"}',100); +INSERT INTO "audit" VALUES('domus_qiHduFuVEJhQhK4eDn4pc1xsrNce7q4O','home','ha_admin','shopping.clear-extra','session-clear-v24','{"extra_id":"domus_Ap0512Et0SZig2QOnumOz9QSuzevCz4s"}',100); +INSERT INTO "audit" VALUES('domus_CFlY82YE213UJhxqF0Shskgnqq6wYU-B','home','ha_admin','inventory.register-product','v25-flour','{"base_unit":"gram","name":"Session flour"}',100); +INSERT INTO "audit" VALUES('domus_PZu_-tulSZVrB5CpkKc2BM3iMTKEqDge','home','ha_admin','shopping.record-session','v25-trip','{"items":[{"extra_id":null,"product_id":"domus_CwE03pjDXqGzQ66BG_IqfYYfBEYDclIW","quantity":"6.000001"},{"extra_id":"domus_slB4XXU5cp1xyt5rCQ5T4onfz3og3EVE","product_id":null,"quantity":"2"}]}',100); +INSERT INTO "audit" VALUES('domus_lopknBIm4eFcX5dA8BLVlhgs63IH_nUL','home','ha_admin','shopping.receive','v25-arrival','{"expected_revision":"1","purchase_id":"domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","quantity":"4.000001"}',100); +INSERT INTO "audit" VALUES('domus_3_MQ5SJb-uNRoJIr3QLE3X7-ZcVyDzOR','home','ha_admin','shopping.cancel-balance','pre-void-balance-cancel','{"expected_revision":"1","purchase_id":"domus_GzvhyL40lw4ua72YuqdG_SI2z_wDFJBG","reason":"Supplier cancelled the loose item"}',100); +INSERT INTO "audit" VALUES('domus_lnWji8oXPfIKByutGtp1CVtNNe8xwksU','home','ha_admin','inventory.correct-intake','legacy-posted-reversal','{"movement_id":"domus_8r5jVraFc6n3P4vEWEuUo_dcqQjQaYv3","product_id":"identity-3","reason":"Legacy inventory reversal"}',100); +INSERT INTO "audit" VALUES('domus_8Uve_ckROgMCYfkW_fZNOpEIuShUlJrw','home','ha_admin','shopping.receive','legacy-mistaken-arrival','{"expected_revision":"2","purchase_id":"domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","quantity":"0.5"}',100); +INSERT INTO "audit" VALUES('domus_zywqs3EM5sH0rgG79mCCe7ZN73XARtux','home','ha_admin','shopping.void-receipt','legacy-pending-void','{"expected_revision":"3","purchase_id":"domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","reason":"Legacy pending void","receipt_id":"domus_Cjq3pfqXcLk4s1HoYi8hSMli8bEv_OGG"}',100); +INSERT INTO "audit" VALUES('domus_I6TKHbOO_Et0UdEjnWLWK4-2X1-xQP0V','home','ha_admin','shopping.post-receipt','legacy-post-flour','{"purchase_id":"domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","receipt_id":"domus_IjDCb68yPYGTfC5861ai_1ooEAz7_1q-"}',100); +INSERT INTO "audit" VALUES('domus_HM6TO1rj2Gc7B5-zz_opOQogFVw2rjvw','home','ha_admin','inventory.register-product','legacy-pear-product','{"base_unit":"piece","name":"Pears"}',100); +INSERT INTO "audit" VALUES('domus_-LN_fSE03EvM8IsFKE-WWEoDqDGiCxM8','home','ha_admin','shopping.purchase','legacy-buy-pears','{"name":null,"product_id":"domus_Od8wq1rVNYDvVPOjwTdTCJyssAb7N7OP","quantity":"2"}',100); +INSERT INTO "audit" VALUES('domus_lAXE4xVY5JQwF0xaNjvus7pr-bqIUQgR','home','ha_admin','shopping.receive','legacy-receive-pears','{"expected_revision":"1","purchase_id":"domus_xMK8jzLSbWb-4cIDquBA1M4CzrXnYFl0","quantity":"2"}',100); +INSERT INTO "audit" VALUES('domus_X0cTH1TJ9YlAl_94GXQybWh3rIPFUCkG','home','ha_admin','shopping.post-receipt','legacy-post-pears','{"purchase_id":"domus_xMK8jzLSbWb-4cIDquBA1M4CzrXnYFl0","receipt_id":"domus_AE07stExzOh2XLuwGIkzwRc3zyhaZ7O6"}',100); +INSERT INTO "audit" VALUES('domus_NDNzBAbLKwtsLp4gi9XiQXrW6dgVL94T','home','ha_admin','shopping.correct-posted-receipt','fixture-linked-correction','{"expected_revision":"5","purchase_id":"domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","reason":"Fixture posting corrected","receipt_id":"domus_IjDCb68yPYGTfC5861ai_1ooEAz7_1q-"}',100); +INSERT INTO "audit" VALUES('domus_A3ptVt1BhuSF_urBC-kRtjGtX81dejus','home','ha_admin','inventory.register-product','fixture-rice-product','{"base_unit":"gram","name":"Rice"}',100); +INSERT INTO "audit" VALUES('domus_6XTPAuRfOdJa4j7J_o6Ygk6MH4iF1VAH','home','ha_admin','shopping.purchase','fixture-buy-rice','{"name":null,"product_id":"domus_OtrCetg8XPQkMtK8crfCzq5l_pxex86C","quantity":"4.000001"}',100); +INSERT INTO "audit" VALUES('domus_r31CEr5al59kFNPy1hiJov89wuZ-DuGM','home','ha_admin','shopping.receive','fixture-receive-rice','{"expected_revision":"1","purchase_id":"domus_owkz3twLY8GPCTLqKmlCnN-YIvqlTc5G","quantity":"4.000001"}',100); +INSERT INTO "audit" VALUES('domus_KuRGLk9EQ82AcK6c0hsSwwbn-Cq6Bxuu','home','ha_admin','shopping.post-receipt','fixture-post-rice','{"purchase_id":"domus_owkz3twLY8GPCTLqKmlCnN-YIvqlTc5G","receipt_id":"domus_3AWQO2_g6TTpKkxd2JjHIYvz29kQ-q5m"}',100); +INSERT INTO "audit" VALUES('domus_6itD9iLhWZlbBjPkIjtk3Gv_2wR6x4Ul','home','ha_admin','shopping.return-receipt','schema-29-return-rice','{"expected_revision":"3","purchase_id":"domus_owkz3twLY8GPCTLqKmlCnN-YIvqlTc5G","reason":"Representative supplier return","receipt_id":"domus_3AWQO2_g6TTpKkxd2JjHIYvz29kQ-q5m"}',100); +INSERT INTO "audit" VALUES('domus_knTyoPNUcQZm3R_vsaId5xSy1aoHofF8','home','ha_admin','inventory.add-location','v30-fixture-location','{"name":"Dry cupboard"}',100); +INSERT INTO "audit" VALUES('domus_vDdzUwhFlvHt5klffEsN8xsha9SIXnLy','home','ha_admin','inventory.transfer','v30-fixture-transfer','{"destination_location":"domus_UON265oSFoFshuKs38X-Ba836nECOLGa","product_id":"identity-3","quantity":"0.25","source_location":"pantry"}',100); +INSERT INTO "audit" VALUES('fixture-v31-2','home','ha_admin','shopping.add-extra','brush-v31','{"name":"Dish brush","product_id":null,"quantity":"1"}',250); +INSERT INTO "audit" VALUES('fixture-v31-4','home','ha_admin','shopping.add-extra','soap-v31','{"name":"Dish soap","product_id":null,"quantity":"1"}',250); +INSERT INTO "audit" VALUES('fixture-v31-8','home','ha_admin','shopping.record-session','named-trip-v31','{"items":[{"extra_id":"fixture-v31-1","product_id":null,"quantity":"1"},{"extra_id":"fixture-v31-3","product_id":null,"quantity":"1"}],"store_name":"North Market"}',250); +CREATE TABLE calendar_preferences(household_id TEXT NOT NULL, member_id TEXT NOT NULL, week_start TEXT NOT NULL DEFAULT 'monday' CHECK(week_start IN ('monday','sunday')), revision INTEGER NOT NULL DEFAULT 1 CHECK(typeof(revision)='integer' AND revision>=1), PRIMARY KEY(household_id,member_id), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)); +INSERT INTO "calendar_preferences" VALUES('home','identity-1','monday',1); +INSERT INTO "calendar_preferences" VALUES('home','child','monday',1); +INSERT INTO "calendar_preferences" VALUES('home','other','monday',1); +CREATE TABLE household_policy(household_id TEXT PRIMARY KEY REFERENCES households(household_id), mapping_mode TEXT NOT NULL, target_ha_user_id TEXT, revision INTEGER NOT NULL CHECK(revision>=1), adjustments TEXT NOT NULL, CHECK((mapping_mode='all_ha_administrators' AND target_ha_user_id IS NULL) OR (mapping_mode IN ('setup_administrator','selected_ha_user') AND target_ha_user_id IS NOT NULL))); +INSERT INTO "household_policy" VALUES('home','all_ha_administrators',NULL,1,'{"rules":[]}'); +CREATE TABLE households(household_id TEXT PRIMARY KEY, singleton INTEGER NOT NULL DEFAULT 1 UNIQUE CHECK(singleton=1), name TEXT NOT NULL, time_zone TEXT NOT NULL, revision INTEGER NOT NULL CHECK(revision>=1), materialization_horizon_days INTEGER NOT NULL DEFAULT 60 CHECK(typeof(materialization_horizon_days)='integer' AND materialization_horizon_days BETWEEN 7 AND 366), repeated_time TEXT NOT NULL DEFAULT 'first_instant' CHECK(repeated_time IN ('first_instant','second_instant'))); +INSERT INTO "households" VALUES('home',1,'Home','UTC',1,60,'first_instant'); +CREATE TABLE installation(singleton INTEGER PRIMARY KEY CHECK(singleton=1), instance_id TEXT NOT NULL, channel TEXT NOT NULL CHECK(channel IN ('stable','edge'))); +INSERT INTO "installation" VALUES(1,'047cc6fb-dfb0-4fa4-b3c3-e0fe54d116b6','edge'); +CREATE TABLE inventory_effects(household_id TEXT NOT NULL, effect_id TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('reservation','demand')), reference_id TEXT NOT NULL, origin_id TEXT, occurrence_id TEXT, line_id TEXT, remaining INTEGER NOT NULL CHECK(remaining BETWEEN 0 AND 999999999999999999), revision INTEGER NOT NULL CHECK(revision>=1), PRIMARY KEY(household_id,effect_id), UNIQUE(household_id,occurrence_id,reference_id,kind), CHECK((origin_id IS NOT NULL AND occurrence_id IS NOT NULL AND line_id IS NOT NULL) OR (kind='demand' AND origin_id IS NULL AND occurrence_id IS NULL AND line_id IS NULL)), FOREIGN KEY(household_id,reference_id) REFERENCES inventory_materials(household_id,reference_id), FOREIGN KEY(household_id,origin_id) REFERENCES task_occurrences(household_id,occurrence_id), FOREIGN KEY(household_id,occurrence_id) REFERENCES task_occurrences(household_id,occurrence_id)) STRICT; +INSERT INTO "inventory_effects" VALUES('home','identity-12','reservation','identity-4','identity-10','identity-10','identity-8',875000,2); +CREATE TABLE inventory_locations(household_id TEXT NOT NULL REFERENCES households(household_id), location_id TEXT NOT NULL CHECK(location_id!='pantry'), name TEXT NOT NULL, name_key TEXT NOT NULL, PRIMARY KEY(household_id,location_id), UNIQUE(household_id,name_key)) STRICT; +INSERT INTO "inventory_locations" VALUES('home','domus_UON265oSFoFshuKs38X-Ba836nECOLGa','Dry cupboard','dry cupboard'); +CREATE TABLE inventory_materials(household_id TEXT NOT NULL REFERENCES households(household_id), reference_id TEXT NOT NULL, product_id TEXT NOT NULL, unit_id TEXT NOT NULL, location_id TEXT NOT NULL, revision INTEGER NOT NULL CHECK(revision=1), precision INTEGER NOT NULL CHECK(precision BETWEEN 0 AND 6), label TEXT NOT NULL, balance INTEGER NOT NULL CHECK(balance BETWEEN 0 AND 999999999999999999), PRIMARY KEY(household_id,reference_id), UNIQUE(household_id,product_id,location_id)) STRICT; +INSERT INTO "inventory_materials" VALUES('home','identity-4','identity-3','millilitre','pantry',1,6,'Oil',3000001); +INSERT INTO "inventory_materials" VALUES('home','domus_Qd7OZkiYNGO0PB-yNGqfm75n1ISKIcIG','domus_eFvAbbTLuCtrtEJ6KTUG1tbCwMVBVvhr','gram','pantry',1,6,'Oats',0); +INSERT INTO "inventory_materials" VALUES('home','domus_9jkFE56V0qqPENrgjwbNKOBFgWxAruvj','domus_CwE03pjDXqGzQ66BG_IqfYYfBEYDclIW','gram','pantry',1,6,'Session flour',0); +INSERT INTO "inventory_materials" VALUES('home','domus_BDleJnOo7irYzqxD9ad3AzOGZ_zdv3m_','domus_Od8wq1rVNYDvVPOjwTdTCJyssAb7N7OP','piece','pantry',1,0,'Pears',2000000); +INSERT INTO "inventory_materials" VALUES('home','domus_I9JHy7_RfZ_wQfkMQB-IkCpXgc_Vxp19','domus_OtrCetg8XPQkMtK8crfCzq5l_pxex86C','gram','pantry',1,6,'Rice',0); +INSERT INTO "inventory_materials" VALUES('home','domus_DnpSXZoJ9QuyrB94-Sft9TsK4r51W4_k','identity-3','millilitre','domus_UON265oSFoFshuKs38X-Ba836nECOLGa',1,6,'Oil',250000); +CREATE TABLE inventory_movements(position INTEGER PRIMARY KEY, household_id TEXT NOT NULL, reference_id TEXT NOT NULL, movement_id TEXT NOT NULL, source_key TEXT NOT NULL, member_id TEXT NOT NULL, delta INTEGER NOT NULL CHECK(delta BETWEEN -999999999999999999 AND 999999999999999999 AND delta!=0), created_at INTEGER NOT NULL CHECK(created_at>=0), reason TEXT NOT NULL, posting TEXT, corrects TEXT, kind TEXT NOT NULL, transfer_id TEXT CHECK(transfer_id IS NULL OR (kind='adjustment' AND posting IS NULL AND corrects IS NULL)), UNIQUE(household_id,movement_id), UNIQUE(household_id,source_key), UNIQUE(household_id,reference_id,movement_id), UNIQUE(household_id,corrects), CHECK((kind='intake' AND posting IS NULL AND corrects IS NULL AND delta>0) OR (kind='adjustment' AND posting IS NULL AND corrects IS NULL) OR (kind='intake_correction' AND posting IS NULL AND corrects IS NOT NULL AND delta<0) OR (kind='task_consumption' AND posting IS NOT NULL AND corrects IS NULL AND delta<0) OR (kind='task_correction' AND posting IS NOT NULL AND corrects IS NOT NULL)), FOREIGN KEY(household_id,reference_id) REFERENCES inventory_materials(household_id,reference_id), FOREIGN KEY(household_id,reference_id,corrects) REFERENCES inventory_movements(household_id,reference_id,movement_id), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)) STRICT; +INSERT INTO "inventory_movements" VALUES(1,'home','identity-4','identity-6','fad1a4be58f0c7897bfd593650d21f3f1d10c8d5ec5b97818d78a6b5edc6690c','identity-1',4250001,100,'receipt',NULL,NULL,'intake',NULL); +INSERT INTO "inventory_movements" VALUES(2,'home','identity-4','identity-17','task-material:e2196b2e2afb5ee8c736f61bfada2e1f51dee29b4a66bdb6b2e2cae92ff446d5','identity-1',-1125000,100,'','{"binding_revision":1,"cycle_id":"identity-14","effect_revision":1,"household_id":"home","intent_id":"identity-15","intent_revision":1,"inventory_operation_id":"identity-16","line_id":"identity-8","movement_id":"identity-17","occurrence_id":"identity-10","posted_at":100,"quantity":"1.125","reference_id":"identity-4"}',NULL,'task_consumption',NULL); +INSERT INTO "inventory_movements" VALUES(3,'home','identity-4','identity-20','task-material:3651caa603062899e4d08a171cac2509c6c0ff7d1bc3de941cac1e97d181835b','identity-1',125000,100,'Actual use','{"binding_revision":1,"cycle_id":"identity-14","effect_revision":2,"household_id":"home","intent_id":"identity-15","intent_revision":3,"inventory_operation_id":"identity-19","line_id":"identity-8","movement_id":"identity-20","occurrence_id":"identity-10","posted_at":100,"quantity":"1","reference_id":"identity-4"}','identity-17','task_correction',NULL); +INSERT INTO "inventory_movements" VALUES(4,'home','domus_Qd7OZkiYNGO0PB-yNGqfm75n1ISKIcIG','domus_h8MiNTHX876pXMCj0hHOVrqRRfqTAeup','d0ee7b06829c35ee68a874d097d02ed34de0c4a6420e81c5746f2687c16907c7','identity-1',1125000,100,'receipt',NULL,NULL,'intake',NULL); +INSERT INTO "inventory_movements" VALUES(5,'home','domus_Qd7OZkiYNGO0PB-yNGqfm75n1ISKIcIG','domus_RYCCVDaLdHmlBxaJx_ohli4K1GRNrx2i','2856fc9574f5443f0f47b42a753f43d3b84df5d9df5818f2eb08ed1fb2250d94','identity-1',-1125000,100,'Duplicate intake',NULL,'domus_h8MiNTHX876pXMCj0hHOVrqRRfqTAeup','intake_correction',NULL); +INSERT INTO "inventory_movements" VALUES(6,'home','identity-4','domus_8r5jVraFc6n3P4vEWEuUo_dcqQjQaYv3','f4540e2cbbf5c0cdcf43720d4eafd387d66367f89a694d5086114ab04532ba72','identity-1',250000,1794321336338,'receipt',NULL,NULL,'intake',NULL); +INSERT INTO "inventory_movements" VALUES(7,'home','identity-4','domus_G6icpezyFnst6F-7PeToBUy0ezRwfC4f','dfc5616e66955dcfd2b4e83ac0dc2c13d73fa76657af26b6eef3025cd0af0767','identity-1',-250000,100,'Legacy inventory reversal',NULL,'domus_8r5jVraFc6n3P4vEWEuUo_dcqQjQaYv3','intake_correction',NULL); +INSERT INTO "inventory_movements" VALUES(8,'home','domus_9jkFE56V0qqPENrgjwbNKOBFgWxAruvj','domus_hOtKVv7KF08db_-AQBuN543KXuz-ljAa','4d6c4111e6c72c0d2976a45126d112926d82e95e05f755dd4bdc8d81f5c39cde','identity-1',4000001,100,'receipt',NULL,NULL,'intake',NULL); +INSERT INTO "inventory_movements" VALUES(9,'home','domus_BDleJnOo7irYzqxD9ad3AzOGZ_zdv3m_','domus_lYZd1XThXhORS9rwD4ihNxgPRmzjFISR','7c97ea1083cba0a6fc5ab7030cf7a6c6cdaaef4bd42f04b0f02568a1d74193ab','identity-1',2000000,100,'receipt',NULL,NULL,'intake',NULL); +INSERT INTO "inventory_movements" VALUES(10,'home','domus_9jkFE56V0qqPENrgjwbNKOBFgWxAruvj','domus_wxbaFm36s1M-4Wn_vJHnJJkeENhSaO7N','29f552d54426998791d1a0655e48d4becfcebd7cdebb65d8862071657f7bc561','identity-1',-4000001,100,'Fixture posting corrected',NULL,'domus_hOtKVv7KF08db_-AQBuN543KXuz-ljAa','intake_correction',NULL); +INSERT INTO "inventory_movements" VALUES(11,'home','domus_I9JHy7_RfZ_wQfkMQB-IkCpXgc_Vxp19','domus_MzGllJGdOQlQ6O2hayc1xX8deFFf0ZCy','e1e7f3dfcfee8725de6500cd397184b122a83c7b1d72903515e5782b5395fbcc','identity-1',4000001,100,'receipt',NULL,NULL,'intake',NULL); +INSERT INTO "inventory_movements" VALUES(12,'home','domus_I9JHy7_RfZ_wQfkMQB-IkCpXgc_Vxp19','domus_eccslYHn5WGuE0ODDpfrT8Y-EXexYglj','f49fad2ba565ad6ca594862ddc94a4b1599144e9ada107ffae31dd1a538d6e71','identity-1',-4000001,100,'Representative supplier return',NULL,NULL,'adjustment',NULL); +INSERT INTO "inventory_movements" VALUES(13,'home','identity-4','domus_4o_Fpo4i0WrxRRiA4HvHbCW5B3oT-Vsq','aa041c736451d4ff70465ed49a20ec71b061befa9a40af15c081e5cd8bd10f6d:out','identity-1',-250000,100,'',NULL,NULL,'adjustment','domus_ertdgHH4Uqa1CMm0Yqq9Oy-c5Bj7F9jc'); +INSERT INTO "inventory_movements" VALUES(14,'home','domus_DnpSXZoJ9QuyrB94-Sft9TsK4r51W4_k','domus_qEk8GHm3A6h2QrF7dMEYdRkrPOqOt5Vs','aa041c736451d4ff70465ed49a20ec71b061befa9a40af15c081e5cd8bd10f6d:in','identity-1',250000,100,'',NULL,NULL,'adjustment','domus_ertdgHH4Uqa1CMm0Yqq9Oy-c5Bj7F9jc'); +CREATE TABLE inventory_products(household_id TEXT NOT NULL, product_id TEXT NOT NULL, reference_id TEXT NOT NULL, name TEXT NOT NULL, base_unit TEXT NOT NULL CHECK(base_unit IN ('piece','gram','millilitre')), PRIMARY KEY(household_id,product_id), UNIQUE(household_id,reference_id), FOREIGN KEY(household_id,reference_id) REFERENCES inventory_materials(household_id,reference_id)) STRICT; +INSERT INTO "inventory_products" VALUES('home','identity-3','identity-4','Oil','millilitre'); +INSERT INTO "inventory_products" VALUES('home','domus_eFvAbbTLuCtrtEJ6KTUG1tbCwMVBVvhr','domus_Qd7OZkiYNGO0PB-yNGqfm75n1ISKIcIG','Oats','gram'); +INSERT INTO "inventory_products" VALUES('home','domus_CwE03pjDXqGzQ66BG_IqfYYfBEYDclIW','domus_9jkFE56V0qqPENrgjwbNKOBFgWxAruvj','Session flour','gram'); +INSERT INTO "inventory_products" VALUES('home','domus_Od8wq1rVNYDvVPOjwTdTCJyssAb7N7OP','domus_BDleJnOo7irYzqxD9ad3AzOGZ_zdv3m_','Pears','piece'); +INSERT INTO "inventory_products" VALUES('home','domus_OtrCetg8XPQkMtK8crfCzq5l_pxex86C','domus_I9JHy7_RfZ_wQfkMQB-IkCpXgc_Vxp19','Rice','gram'); +CREATE TABLE inventory_replenishment(household_id TEXT NOT NULL, product_id TEXT NOT NULL, minimum INTEGER NOT NULL CHECK(minimum BETWEEN 0 AND 999999999999999999), target INTEGER NOT NULL CHECK(target BETWEEN minimum AND 999999999999999999), revision INTEGER NOT NULL CHECK(revision>0), PRIMARY KEY(household_id,product_id), FOREIGN KEY(household_id,product_id) REFERENCES inventory_products(household_id,product_id)) STRICT; +INSERT INTO "inventory_replenishment" VALUES('home','identity-3',3000000,5000000,1); +CREATE TABLE inventory_transfers(household_id TEXT NOT NULL, transfer_id TEXT NOT NULL, product_id TEXT NOT NULL, source_location TEXT NOT NULL, destination_location TEXT NOT NULL, withdrawal_id TEXT NOT NULL, deposit_id TEXT NOT NULL, PRIMARY KEY(household_id,transfer_id), UNIQUE(household_id,withdrawal_id), UNIQUE(household_id,deposit_id), CHECK(source_location!=destination_location), FOREIGN KEY(household_id,product_id) REFERENCES inventory_products(household_id,product_id), FOREIGN KEY(household_id,withdrawal_id) REFERENCES inventory_movements(household_id,movement_id), FOREIGN KEY(household_id,deposit_id) REFERENCES inventory_movements(household_id,movement_id)) STRICT; +INSERT INTO "inventory_transfers" VALUES('home','domus_ertdgHH4Uqa1CMm0Yqq9Oy-c5Bj7F9jc','identity-3','pantry','domus_UON265oSFoFshuKs38X-Ba836nECOLGa','domus_4o_Fpo4i0WrxRRiA4HvHbCW5B3oT-Vsq','domus_qEk8GHm3A6h2QrF7dMEYdRkrPOqOt5Vs'); +CREATE TABLE member_preferences(member_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL, locale TEXT CHECK(locale IS NULL OR locale IN ('en','es')), routine_participation_summaries INTEGER NOT NULL CHECK(typeof(routine_participation_summaries)='integer' AND routine_participation_summaries IN (0,1)), revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)); +INSERT INTO "member_preferences" VALUES('identity-1','home',NULL,1,1); +INSERT INTO "member_preferences" VALUES('child','home',NULL,1,1); +INSERT INTO "member_preferences" VALUES('other','home',NULL,1,1); +CREATE TABLE member_presentations(member_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL, alias TEXT, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id), CHECK(alias IS NULL OR (typeof(alias)='text' AND length(alias) BETWEEN 1 AND 80))); +INSERT INTO "member_presentations" VALUES('identity-1','home',NULL,1); +INSERT INTO "member_presentations" VALUES('child','home',NULL,1); +INSERT INTO "member_presentations" VALUES('other','home',NULL,1); +CREATE TABLE members(member_id TEXT PRIMARY KEY, household_id TEXT NOT NULL REFERENCES households(household_id), ha_user_id TEXT NOT NULL, role TEXT NOT NULL CHECK(role IN ('administrator','adult','restricted','viewer')), status TEXT NOT NULL CHECK(status IN ('pending','active','suspended','archived')), revision INTEGER NOT NULL CHECK(revision>=1), exceptions TEXT NOT NULL, UNIQUE(household_id,ha_user_id)); +INSERT INTO "members" VALUES('identity-1','home','ha_admin','viewer','active',1,'{"rules":[]}'); +INSERT INTO "members" VALUES('child','home','ha_child','restricted','active',1,'{"rules":[]}'); +INSERT INTO "members" VALUES('other','home','ha_other','restricted','active',1,'{"rules":[]}'); +CREATE TABLE outbox(position INTEGER PRIMARY KEY AUTOINCREMENT, event_id TEXT NOT NULL UNIQUE, household_id TEXT NOT NULL REFERENCES households(household_id), event_type TEXT NOT NULL, payload TEXT NOT NULL, created_at INTEGER NOT NULL, delivered INTEGER NOT NULL DEFAULT 0 CHECK(delivered IN (0,1))); +INSERT INTO "outbox" VALUES(1,'identity-2','home','household.setup','{"household_id":"home","revision":1}',100,0); +INSERT INTO "outbox" VALUES(2,'identity-5','home','inventory.register-product','{"kind":"inventory.register-product","version":1}',100,0); +INSERT INTO "outbox" VALUES(3,'identity-7','home','inventory.intake','{"kind":"inventory.intake","version":1}',100,0); +INSERT INTO "outbox" VALUES(4,'identity-11','home','task.create','{"assignee_ids":[],"definition_id":"identity-9","definition_revision":1,"kind":"task.created","occurrence_id":"identity-10","prerequisite_ids":[],"required_subtask_ids":[],"revision":1,"state":"available","state_reason":"","version":1}',100,0); +INSERT INTO "outbox" VALUES(5,'identity-13','home','inventory.commit-effect','{"kind":"inventory.commit-effect","version":1}',100,0); +INSERT INTO "outbox" VALUES(6,'identity-18','home','task.complete','{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-14","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-10","performed_at":95,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":0,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-9","definition_revision":1,"kind":"task.completed","materials":[{"action_required":null,"cycle_id":"identity-14","effect_revision":1,"intent_id":"identity-15","line_id":"identity-8","message":"Inventory confirmed this material consumption.","movement_id":"identity-17","pending_reason":null,"quantity":"1.125","revision":2,"state":"posted","submitted_quantity":"1.125"}],"occurrence_id":"identity-10","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":"","version":1}',100,0); +INSERT INTO "outbox" VALUES(7,'identity-21','home','task.material.settle','{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-14","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-10","performed_at":95,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":0,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-9","definition_revision":1,"kind":"task.material.settled","material":{"action_required":null,"confirmed_effect_revision":2,"confirmed_quantity":"1","cycle_id":"identity-14","effect_revision":2,"intent_id":"identity-15","line_id":"identity-8","message":"Inventory confirmed the corrected total.","movement_id":"identity-20","pending_reason":null,"posted_at":100,"quantity":"1","revision":4,"state":"corrected","submitted_quantity":"1.125"},"material_action":"correct","material_source":{"cycle_id":"identity-14","definition_revision":1,"household_id":"home","intent_id":"identity-15","line_id":"identity-8","occurrence_id":"identity-10","performer_ids":["identity-1"]},"occurrence_id":"identity-10","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":"","version":1}',100,0); +INSERT INTO "outbox" VALUES(8,'domus_GpP8fpUm2fz7CZq_DVZWCyty-HjUD5F2','home','inventory.register-product','{"kind":"inventory.register-product","version":1}',100,0); +INSERT INTO "outbox" VALUES(9,'domus_5M2TxM_QPWHHasJ32kAB1u-iwkU0UbKo','home','inventory.intake','{"kind":"inventory.intake","version":1}',100,0); +INSERT INTO "outbox" VALUES(10,'domus_LgNq0sL9tNZAQlYM5bW1lfH9nJhwqQkn','home','inventory.correct-intake','{"kind":"inventory.correct-intake","version":1}',100,0); +INSERT INTO "outbox" VALUES(11,'domus_uZBk2wqcsgcRwf2AK2z6u7Lvswbn89-q','home','inventory.configure-replenishment','{"kind":"inventory.configure-replenishment","version":1}',1794318537054,0); +INSERT INTO "outbox" VALUES(12,'domus_wcbzJQaTFNzjQNlu6utgWWB-NWbHrHqe','home','shopping.purchase','{"kind":"shopping.purchase","version":1}',1794321336330,0); +INSERT INTO "outbox" VALUES(13,'domus_yKfFr-rfKW_77yhBlfk9Pmtt3cSCrVnS','home','shopping.receive','{"kind":"shopping.receive","version":1}',1794321336332,0); +INSERT INTO "outbox" VALUES(14,'domus_HlimXSAwLqyeExfVIdDvg-WR1Ip59Lny','home','shopping.receive','{"kind":"shopping.receive","version":1}',1794321336335,0); +INSERT INTO "outbox" VALUES(15,'domus_fNMB0nHFvIQUSSNeBmKY9Zf3T_4SFMS8','home','shopping.post-receipt','{"kind":"shopping.post-receipt","version":1}',1794321336338,0); +INSERT INTO "outbox" VALUES(16,'domus_rrgvH6kGMqVqilsxdvzDwmdFDXSWaQlk','home','shopping.add-extra','{"kind":"shopping.add-extra","version":1}',100,0); +INSERT INTO "outbox" VALUES(17,'domus_reoKWG7jjwtJVqevLEuFNg2vHTTN2q9N','home','shopping.add-extra','{"kind":"shopping.add-extra","version":1}',100,0); +INSERT INTO "outbox" VALUES(18,'domus_eF7j-7jnJvaKFNk97Wwbuele0gdsJKTT','home','shopping.add-extra','{"kind":"shopping.add-extra","version":1}',100,0); +INSERT INTO "outbox" VALUES(19,'domus_qiHduFuVEJhQhK4eDn4pc1xsrNce7q4O','home','shopping.clear-extra','{"kind":"shopping.clear-extra","version":1}',100,0); +INSERT INTO "outbox" VALUES(20,'domus_CFlY82YE213UJhxqF0Shskgnqq6wYU-B','home','inventory.register-product','{"kind":"inventory.register-product","version":1}',100,0); +INSERT INTO "outbox" VALUES(21,'domus_PZu_-tulSZVrB5CpkKc2BM3iMTKEqDge','home','shopping.record-session','{"kind":"shopping.record-session","version":1}',100,0); +INSERT INTO "outbox" VALUES(22,'domus_lopknBIm4eFcX5dA8BLVlhgs63IH_nUL','home','shopping.receive','{"kind":"shopping.receive","version":1}',100,0); +INSERT INTO "outbox" VALUES(23,'domus_3_MQ5SJb-uNRoJIr3QLE3X7-ZcVyDzOR','home','shopping.cancel-balance','{"kind":"shopping.cancel-balance","version":1}',100,0); +INSERT INTO "outbox" VALUES(24,'domus_lnWji8oXPfIKByutGtp1CVtNNe8xwksU','home','inventory.correct-intake','{"kind":"inventory.correct-intake","version":1}',100,0); +INSERT INTO "outbox" VALUES(25,'domus_8Uve_ckROgMCYfkW_fZNOpEIuShUlJrw','home','shopping.receive','{"kind":"shopping.receive","version":1}',100,0); +INSERT INTO "outbox" VALUES(26,'domus_zywqs3EM5sH0rgG79mCCe7ZN73XARtux','home','shopping.void-receipt','{"kind":"shopping.void-receipt","version":1}',100,0); +INSERT INTO "outbox" VALUES(27,'domus_I6TKHbOO_Et0UdEjnWLWK4-2X1-xQP0V','home','shopping.post-receipt','{"kind":"shopping.post-receipt","version":1}',100,0); +INSERT INTO "outbox" VALUES(28,'domus_HM6TO1rj2Gc7B5-zz_opOQogFVw2rjvw','home','inventory.register-product','{"kind":"inventory.register-product","version":1}',100,0); +INSERT INTO "outbox" VALUES(29,'domus_-LN_fSE03EvM8IsFKE-WWEoDqDGiCxM8','home','shopping.purchase','{"kind":"shopping.purchase","version":1}',100,0); +INSERT INTO "outbox" VALUES(30,'domus_lAXE4xVY5JQwF0xaNjvus7pr-bqIUQgR','home','shopping.receive','{"kind":"shopping.receive","version":1}',100,0); +INSERT INTO "outbox" VALUES(31,'domus_X0cTH1TJ9YlAl_94GXQybWh3rIPFUCkG','home','shopping.post-receipt','{"kind":"shopping.post-receipt","version":1}',100,0); +INSERT INTO "outbox" VALUES(32,'domus_NDNzBAbLKwtsLp4gi9XiQXrW6dgVL94T','home','shopping.correct-posted-receipt','{"kind":"shopping.correct-posted-receipt","version":1}',100,0); +INSERT INTO "outbox" VALUES(33,'domus_A3ptVt1BhuSF_urBC-kRtjGtX81dejus','home','inventory.register-product','{"kind":"inventory.register-product","version":1}',100,0); +INSERT INTO "outbox" VALUES(34,'domus_6XTPAuRfOdJa4j7J_o6Ygk6MH4iF1VAH','home','shopping.purchase','{"kind":"shopping.purchase","version":1}',100,0); +INSERT INTO "outbox" VALUES(35,'domus_r31CEr5al59kFNPy1hiJov89wuZ-DuGM','home','shopping.receive','{"kind":"shopping.receive","version":1}',100,0); +INSERT INTO "outbox" VALUES(36,'domus_KuRGLk9EQ82AcK6c0hsSwwbn-Cq6Bxuu','home','shopping.post-receipt','{"kind":"shopping.post-receipt","version":1}',100,0); +INSERT INTO "outbox" VALUES(37,'domus_6itD9iLhWZlbBjPkIjtk3Gv_2wR6x4Ul','home','shopping.return-receipt','{"kind":"shopping.return-receipt","version":1}',100,0); +INSERT INTO "outbox" VALUES(38,'domus_knTyoPNUcQZm3R_vsaId5xSy1aoHofF8','home','inventory.add-location','{"kind":"inventory.add-location","version":1}',100,0); +INSERT INTO "outbox" VALUES(39,'domus_vDdzUwhFlvHt5klffEsN8xsha9SIXnLy','home','inventory.transfer','{"kind":"inventory.transfer","version":1}',100,0); +INSERT INTO "outbox" VALUES(40,'fixture-v31-2','home','shopping.add-extra','{"kind":"shopping.add-extra","version":1}',250,0); +INSERT INTO "outbox" VALUES(41,'fixture-v31-4','home','shopping.add-extra','{"kind":"shopping.add-extra","version":1}',250,0); +INSERT INTO "outbox" VALUES(42,'fixture-v31-8','home','shopping.record-session','{"kind":"shopping.record-session","version":1}',250,0); +CREATE TABLE point_allocation_settings(household_id TEXT NOT NULL REFERENCES households,scope TEXT NOT NULL, definition_id TEXT, revision INTEGER NOT NULL CHECK(revision>=1),document TEXT CHECK(document IS NULL OR json_valid(document)),CHECK((definition_id IS NULL AND scope='household' AND document IS NOT NULL) OR (definition_id IS NOT NULL AND scope='task:'||definition_id)),PRIMARY KEY(household_id,scope), FOREIGN KEY(household_id,definition_id) REFERENCES task_definitions(household_id,definition_id)); +CREATE TABLE point_completion_allocations(position INTEGER PRIMARY KEY AUTOINCREMENT,household_id TEXT NOT NULL REFERENCES households, cycle_id TEXT NOT NULL REFERENCES task_cycles, definition_id TEXT NOT NULL, document TEXT NOT NULL CHECK(json_valid(document)),UNIQUE(household_id,cycle_id), FOREIGN KEY(household_id,definition_id) REFERENCES task_definitions(household_id,definition_id)); +INSERT INTO "point_completion_allocations" VALUES(1,'home','identity-14','identity-9','{"allocation":{"next_recipient":null,"shares":[["identity-1",0]]},"base":0,"override_definition_id":null,"policy":{"mode":"conserve_total","precision":0,"rounding":null},"policy_revision":0,"previous_recipient":null}'); +CREATE TABLE points_task_receipts(household_id TEXT NOT NULL REFERENCES households,event_id TEXT NOT NULL REFERENCES receipts(operation_id), position INTEGER NOT NULL REFERENCES outbox(position), cycle_id TEXT NOT NULL REFERENCES task_cycles, definition_id TEXT NOT NULL, fingerprint TEXT NOT NULL CHECK(length(fingerprint)=64 AND fingerprint NOT GLOB '*[^0-9a-f]*'), effect INTEGER NOT NULL CHECK(effect IN (0,1,2)), document TEXT, PRIMARY KEY(household_id,event_id), UNIQUE(household_id,position), CHECK((effect=0 AND document IS NULL) OR (effect>0 AND document IS NOT NULL AND json_valid(document))), FOREIGN KEY(household_id,definition_id) REFERENCES task_definitions(household_id,definition_id)); +CREATE TABLE receipts(household_id TEXT NOT NULL REFERENCES households(household_id), actor_id TEXT NOT NULL, action TEXT NOT NULL, command_key TEXT NOT NULL, payload_fingerprint TEXT NOT NULL, operation_id TEXT NOT NULL UNIQUE, result TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY(household_id,actor_id,action,command_key)); +INSERT INTO "receipts" VALUES('home','ha_admin','household.setup','setup','fd81d9a903eff49c605ff960bfae80f61f684b2f1f12ff15fb363cd7bdea3c51','identity-2','{"administrator_member_id":"identity-1","household_id":"home","mapping_mode":"all_ha_administrators","member_id":"identity-1","policy_revision":1,"revision":1,"state":"configured"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.register-product','new','18d12712e7e98c8b8f431c68c6bb0c8dd26f683476aa272184eeee033b927cc6','identity-5','{"base_unit":"millilitre","name":"Oil","product_id":"identity-3"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.intake','intake-v20','fcec2adebbddc8fcd264808d3a893110ce1499f913c0b7a5bfe308fb4b49be62','identity-7','{"base_unit":"millilitre","movement_id":"identity-6","product_id":"identity-3","quantity":"4.250001"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','task.create','task-v20','4ccfb618c929e5ea95ad04ba0da1b34359d0d254da0686f10c4d804d896f0b01','identity-11','{"assignee_ids":[],"definition_id":"identity-9","definition_revision":1,"occurrence_id":"identity-10","prerequisite_ids":[],"required_subtask_ids":[],"revision":1,"state":"available","state_reason":""}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.commit-effect','reserve-v20','b6164b17211826c39c48e893da952f063f43b3d8cd102c873008b09da26d3656','identity-13','{"effect_id":"identity-12"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','task.complete','complete-v20','8f070b7bf5adeb3b5175f95c6b781f4149b0c2383429e85d0362f19891e9bfa4','identity-18','{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-14","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-10","performed_at":95,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":0,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-9","definition_revision":1,"materials":[{"action_required":null,"cycle_id":"identity-14","effect_revision":1,"intent_id":"identity-15","line_id":"identity-8","message":"Inventory confirmed this material consumption.","movement_id":"identity-17","pending_reason":null,"quantity":"1.125","revision":2,"state":"posted","submitted_quantity":"1.125"}],"occurrence_id":"identity-10","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":""}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','task.material.settle','task-correct-v20','cd2efe84cd485d0fd5991f932faee2184541408f1fece2cb3b06281685c7a841','identity-21','{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-14","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-10","performed_at":95,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":0,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-9","definition_revision":1,"material":{"action_required":null,"confirmed_effect_revision":2,"confirmed_quantity":"1","cycle_id":"identity-14","effect_revision":2,"intent_id":"identity-15","line_id":"identity-8","message":"Inventory confirmed the corrected total.","movement_id":"identity-20","pending_reason":null,"posted_at":100,"quantity":"1","revision":4,"state":"corrected","submitted_quantity":"1.125"},"material_action":"correct","material_source":{"cycle_id":"identity-14","definition_revision":1,"household_id":"home","intent_id":"identity-15","line_id":"identity-8","occurrence_id":"identity-10","performer_ids":["identity-1"]},"occurrence_id":"identity-10","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":""}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.register-product','replenishment-v21-product','a768800b21e7859dff6968b21e2a0a694fa20d5be3bc91c10b3f3f414223cb91','domus_GpP8fpUm2fz7CZq_DVZWCyty-HjUD5F2','{"base_unit":"gram","name":"Oats","product_id":"domus_eFvAbbTLuCtrtEJ6KTUG1tbCwMVBVvhr"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.intake','replenishment-v21-intake','8fc1c513c2787b511c7e5ef04a9d78ef0ef58fbcd90d8dd9d3b92d6f0a35ec3f','domus_5M2TxM_QPWHHasJ32kAB1u-iwkU0UbKo','{"base_unit":"gram","movement_id":"domus_h8MiNTHX876pXMCj0hHOVrqRRfqTAeup","product_id":"domus_eFvAbbTLuCtrtEJ6KTUG1tbCwMVBVvhr","quantity":"1.125"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.correct-intake','replenishment-v21-correction','c10a0fa4671ebfeb700d97ae3b3eaabb8ae7757c3860446add00956a1bc5b6a0','domus_LgNq0sL9tNZAQlYM5bW1lfH9nJhwqQkn','{"base_unit":"gram","corrects":"domus_h8MiNTHX876pXMCj0hHOVrqRRfqTAeup","movement_id":"domus_RYCCVDaLdHmlBxaJx_ohli4K1GRNrx2i","product_id":"domus_eFvAbbTLuCtrtEJ6KTUG1tbCwMVBVvhr","quantity":"-1.125"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.configure-replenishment','policy-v22','56ef75eb70b75754697a3bfaf1d485eba3c4d44670bb2f0895fee84d71ee97a6','domus_uZBk2wqcsgcRwf2AK2z6u7Lvswbn89-q','{"minimum":"3","product_id":"identity-3","revision":"1","target":"5"}',1794318537054); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.purchase','buy-v23','700d349ee7254940f8725ee95404412845ed4041d4a07601ff0f19954e163744','domus_wcbzJQaTFNzjQNlu6utgWWB-NWbHrHqe','{"purchase_id":"domus_7DadKyZ9oOozqAgfBT4tHLtCE-g-evi7"}',1794321336330); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.receive','arrival-v23','b0967a2ae5dcc5317f74db8929d433830b74dc90a7fa12e5b333a0e29f5c5175','domus_yKfFr-rfKW_77yhBlfk9Pmtt3cSCrVnS','{"purchase_id":"domus_7DadKyZ9oOozqAgfBT4tHLtCE-g-evi7","receipt_id":"domus_HYnlK7j7ShiTOsPacjrNxt2m6voRSJML"}',1794321336332); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.receive','pending-v23','664594776a538cc9e9a34875ff7ddaace84a66f90a95472e1cfd528d70cd575a','domus_HlimXSAwLqyeExfVIdDvg-WR1Ip59Lny','{"purchase_id":"domus_7DadKyZ9oOozqAgfBT4tHLtCE-g-evi7","receipt_id":"domus_1M6yX8BB9moGlcKlR6kgxJgQGp331Tvm"}',1794321336335); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.post-receipt','posted-v23','9bd179e404c1c265b78a64a200046479692525711d270e324f1dbe5dbc447c5a','domus_fNMB0nHFvIQUSSNeBmKY9Zf3T_4SFMS8','{"movement_id":"domus_8r5jVraFc6n3P4vEWEuUo_dcqQjQaYv3","purchase_id":"domus_7DadKyZ9oOozqAgfBT4tHLtCE-g-evi7","receipt_id":"domus_HYnlK7j7ShiTOsPacjrNxt2m6voRSJML"}',1794321336338); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.add-extra','session-tracked-v24','994c5582ba062ecd0e6464b8e881e3dde7e1f8a6021c5b225033dc3b9e8f6be7','domus_rrgvH6kGMqVqilsxdvzDwmdFDXSWaQlk','{"extra_id":"domus_d0671QKGtp7jSNkNLRo9DX9wUs-bwror"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.add-extra','session-active-v24','168500146c75e6196c4c9631fb9fe3a810fe46901efaf901844f74bacedd85aa','domus_reoKWG7jjwtJVqevLEuFNg2vHTTN2q9N','{"extra_id":"domus_slB4XXU5cp1xyt5rCQ5T4onfz3og3EVE"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.add-extra','session-cleared-v24','432cac2da963ae0689af1e717f45338a15b6a7fd785f54618662cd213fe05576','domus_eF7j-7jnJvaKFNk97Wwbuele0gdsJKTT','{"extra_id":"domus_Ap0512Et0SZig2QOnumOz9QSuzevCz4s"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.clear-extra','session-clear-v24','2de4622917410dcb3b6ab8bc63249bbcbbc1ea4dfd81e9aff811ff373dc46e95','domus_qiHduFuVEJhQhK4eDn4pc1xsrNce7q4O','{"extra_id":"domus_Ap0512Et0SZig2QOnumOz9QSuzevCz4s"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.register-product','v25-flour','f8cff5a6bb9eabf7c19de69fe564997d65c2df1ea5cc4e84330a456e43c14309','domus_CFlY82YE213UJhxqF0Shskgnqq6wYU-B','{"base_unit":"gram","name":"Session flour","product_id":"domus_CwE03pjDXqGzQ66BG_IqfYYfBEYDclIW"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.record-session','v25-trip','118a4924d02731b97618cce8c6822e2e1bd83307d96660740879d8c79dceef81','domus_PZu_-tulSZVrB5CpkKc2BM3iMTKEqDge','{"purchase_ids":["domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","domus_GzvhyL40lw4ua72YuqdG_SI2z_wDFJBG"],"session_id":"domus_g2c2XVpWA6EkWYFy_ko12rhnhz4IDZGV"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.receive','v25-arrival','f0930bafe5ce5a813dea6661482e5e4254cbba07c306d8feb97c4642b71c2132','domus_lopknBIm4eFcX5dA8BLVlhgs63IH_nUL','{"purchase_id":"domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","receipt_id":"domus_IjDCb68yPYGTfC5861ai_1ooEAz7_1q-"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.cancel-balance','pre-void-balance-cancel','5530e4bf22041863314878ceec015855ca9508abf11f451f2c39f8a07bf1ff19','domus_3_MQ5SJb-uNRoJIr3QLE3X7-ZcVyDzOR','{"cancelled":"2","purchase_id":"domus_GzvhyL40lw4ua72YuqdG_SI2z_wDFJBG","revision":"2"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.correct-intake','legacy-posted-reversal','819c5de339672470dd36d0446077735894f63a5b25d12311064c5fc1005286b4','domus_lnWji8oXPfIKByutGtp1CVtNNe8xwksU','{"base_unit":"millilitre","corrects":"domus_8r5jVraFc6n3P4vEWEuUo_dcqQjQaYv3","movement_id":"domus_G6icpezyFnst6F-7PeToBUy0ezRwfC4f","product_id":"identity-3","quantity":"-0.25"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.receive','legacy-mistaken-arrival','27338cd11f3f1ef920748b6eb5d22a5b0878dd375940f80a9af4cedd7913a07b','domus_8Uve_ckROgMCYfkW_fZNOpEIuShUlJrw','{"purchase_id":"domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","receipt_id":"domus_Cjq3pfqXcLk4s1HoYi8hSMli8bEv_OGG"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.void-receipt','legacy-pending-void','0c4ac4c09c3d1bc3243b40e55e0aa9d2c65503f77d8b72f47f0161f152949deb','domus_zywqs3EM5sH0rgG79mCCe7ZN73XARtux','{"purchase_id":"domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","quantity":"0.5","receipt_id":"domus_Cjq3pfqXcLk4s1HoYi8hSMli8bEv_OGG","revision":"4"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.post-receipt','legacy-post-flour','42a223f751b808f8402c425ccea467d2f0da67d2e327d651b22be3efb23c48f2','domus_I6TKHbOO_Et0UdEjnWLWK4-2X1-xQP0V','{"movement_id":"domus_hOtKVv7KF08db_-AQBuN543KXuz-ljAa","purchase_id":"domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","receipt_id":"domus_IjDCb68yPYGTfC5861ai_1ooEAz7_1q-"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.register-product','legacy-pear-product','0549afe38e177409b7fca667ed2a21faa99a7eff20d820e317526f75e9db0e49','domus_HM6TO1rj2Gc7B5-zz_opOQogFVw2rjvw','{"base_unit":"piece","name":"Pears","product_id":"domus_Od8wq1rVNYDvVPOjwTdTCJyssAb7N7OP"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.purchase','legacy-buy-pears','79aa5be3f249fbdc75d417a36a6a05ed4a0a0883c385109594f90b127cc49205','domus_-LN_fSE03EvM8IsFKE-WWEoDqDGiCxM8','{"purchase_id":"domus_xMK8jzLSbWb-4cIDquBA1M4CzrXnYFl0"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.receive','legacy-receive-pears','4a2bdcca2caf1fe1b9683aa496e918a09d279ad691a5445a849bc4d8e3aebbb4','domus_lAXE4xVY5JQwF0xaNjvus7pr-bqIUQgR','{"purchase_id":"domus_xMK8jzLSbWb-4cIDquBA1M4CzrXnYFl0","receipt_id":"domus_AE07stExzOh2XLuwGIkzwRc3zyhaZ7O6"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.post-receipt','legacy-post-pears','40cb47faa53871255964b90e66e644a9ef007b6e5bdfb53cf345d0c36030a7fc','domus_X0cTH1TJ9YlAl_94GXQybWh3rIPFUCkG','{"movement_id":"domus_lYZd1XThXhORS9rwD4ihNxgPRmzjFISR","purchase_id":"domus_xMK8jzLSbWb-4cIDquBA1M4CzrXnYFl0","receipt_id":"domus_AE07stExzOh2XLuwGIkzwRc3zyhaZ7O6"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.correct-posted-receipt','fixture-linked-correction','a5a28defbcbeb01dfabf4ca608cee4a79bf4c14fe985c9654d17cc5955bfb72c','domus_NDNzBAbLKwtsLp4gi9XiQXrW6dgVL94T','{"movement_id":"domus_wxbaFm36s1M-4Wn_vJHnJJkeENhSaO7N","purchase_id":"domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ","quantity":"4.000001","receipt_id":"domus_IjDCb68yPYGTfC5861ai_1ooEAz7_1q-","revision":"6"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.register-product','fixture-rice-product','f3affb1256a518150bef00ddf5b50932cfd31545dc359a0a61dfe82dd6e8cb09','domus_A3ptVt1BhuSF_urBC-kRtjGtX81dejus','{"base_unit":"gram","name":"Rice","product_id":"domus_OtrCetg8XPQkMtK8crfCzq5l_pxex86C"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.purchase','fixture-buy-rice','7a3613144fb748913048482a1ed09ece6bb2626247dee5132eccfb03ef8515fe','domus_6XTPAuRfOdJa4j7J_o6Ygk6MH4iF1VAH','{"purchase_id":"domus_owkz3twLY8GPCTLqKmlCnN-YIvqlTc5G"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.receive','fixture-receive-rice','84e82b3751e473f3b934664093e6771613bc5f943de18259900ad4a542d15e14','domus_r31CEr5al59kFNPy1hiJov89wuZ-DuGM','{"purchase_id":"domus_owkz3twLY8GPCTLqKmlCnN-YIvqlTc5G","receipt_id":"domus_3AWQO2_g6TTpKkxd2JjHIYvz29kQ-q5m"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.post-receipt','fixture-post-rice','3065a48bcf4c874f6bd0487d802f32cbce42f4dd2fae61778ad950707acefc78','domus_KuRGLk9EQ82AcK6c0hsSwwbn-Cq6Bxuu','{"movement_id":"domus_MzGllJGdOQlQ6O2hayc1xX8deFFf0ZCy","purchase_id":"domus_owkz3twLY8GPCTLqKmlCnN-YIvqlTc5G","receipt_id":"domus_3AWQO2_g6TTpKkxd2JjHIYvz29kQ-q5m"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.return-receipt','schema-29-return-rice','ab91e5f0352967616a917eabf1c20bf10d5af159a42d159e1fa578bade159d8c','domus_6itD9iLhWZlbBjPkIjtk3Gv_2wR6x4Ul','{"movement_id":"domus_eccslYHn5WGuE0ODDpfrT8Y-EXexYglj","purchase_id":"domus_owkz3twLY8GPCTLqKmlCnN-YIvqlTc5G","quantity":"4.000001","receipt_id":"domus_3AWQO2_g6TTpKkxd2JjHIYvz29kQ-q5m","revision":"4"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.add-location','v30-fixture-location','37277b78b68ea5bcf07da4616411ef46ab35017ce0f54d476b24537698e96305','domus_knTyoPNUcQZm3R_vsaId5xSy1aoHofF8','{"location_id":"domus_UON265oSFoFshuKs38X-Ba836nECOLGa","name":"Dry cupboard"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','inventory.transfer','v30-fixture-transfer','768261ff21f8cd30d8b287a9e4600ec24f95536ead2a40a5838f06107b2089e8','domus_vDdzUwhFlvHt5klffEsN8xsha9SIXnLy','{"base_unit":"millilitre","deposit_id":"domus_qEk8GHm3A6h2QrF7dMEYdRkrPOqOt5Vs","destination_location":"domus_UON265oSFoFshuKs38X-Ba836nECOLGa","product_id":"identity-3","quantity":"0.25","source_location":"pantry","transfer_id":"domus_ertdgHH4Uqa1CMm0Yqq9Oy-c5Bj7F9jc","withdrawal_id":"domus_4o_Fpo4i0WrxRRiA4HvHbCW5B3oT-Vsq"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.add-extra','brush-v31','a3afed0d22dc290f67d71ee9673e4401dd93c3814c5f19fef06f0dd94eae5064','fixture-v31-2','{"extra_id":"fixture-v31-1"}',250); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.add-extra','soap-v31','367b82bbda1592e27a22856d21935b5bfbdbae9096f7ceaf9c6dce9f4e127089','fixture-v31-4','{"extra_id":"fixture-v31-3"}',250); +INSERT INTO "receipts" VALUES('home','ha_admin','shopping.record-session','named-trip-v31','4a2c9635d52e333d14408939cfebb44e42efe7eca02dc2d7108901c1bfa7e79b','fixture-v31-8','{"purchase_ids":["fixture-v31-6","fixture-v31-7"],"session_id":"fixture-v31-5","store_name":"North Market"}',250); +CREATE TABLE recovery_requests(request_id TEXT PRIMARY KEY, household_id TEXT NOT NULL REFERENCES households(household_id), target_ha_user_id TEXT NOT NULL, revision INTEGER NOT NULL CHECK(revision>=1), state TEXT NOT NULL CHECK(state IN ('pending','approved','consumed','canceled')), created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, detail TEXT NOT NULL); +CREATE TABLE recurrence_frontiers(household_id TEXT PRIMARY KEY NOT NULL REFERENCES households(household_id), after_schedule_id TEXT, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), selected_at INTEGER NOT NULL CHECK(typeof(selected_at)='integer' AND selected_at>=0), document TEXT NOT NULL); +CREATE TABLE recurrence_progress(schedule_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL, pattern_revision INTEGER NOT NULL CHECK(typeof(pattern_revision)='integer' AND pattern_revision>=1), revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), timing_kind TEXT NOT NULL CHECK(timing_kind IN ('fixed_calendar','completion_relative')), document TEXT NOT NULL, UNIQUE(household_id,schedule_id,pattern_revision,timing_kind), FOREIGN KEY(household_id,schedule_id,pattern_revision,timing_kind) REFERENCES recurrence_rules(household_id,schedule_id,pattern_revision,timing_kind) DEFERRABLE INITIALLY DEFERRED); +CREATE TABLE recurrence_progress_evidence(household_id TEXT NOT NULL, schedule_id TEXT NOT NULL, progress_revision INTEGER NOT NULL CHECK(typeof(progress_revision)='integer' AND progress_revision>=1), operation_id TEXT NOT NULL, evidence_fingerprint TEXT NOT NULL, PRIMARY KEY(household_id,schedule_id), FOREIGN KEY(household_id,schedule_id,progress_revision) REFERENCES recurrence_progress(household_id,schedule_id,revision) DEFERRABLE INITIALLY DEFERRED); +CREATE TABLE recurrence_relative_closures(household_id TEXT NOT NULL, closure_key TEXT NOT NULL, operation_id TEXT NOT NULL UNIQUE, document TEXT NOT NULL, PRIMARY KEY(household_id,closure_key)); +CREATE TABLE recurrence_relative_inbox(household_id TEXT NOT NULL REFERENCES households(household_id), position INTEGER NOT NULL CHECK(typeof(position)='integer' AND position>=1), event_key TEXT NOT NULL, operation_id TEXT NOT NULL UNIQUE, actor_id TEXT NOT NULL, cycle_key TEXT NOT NULL, source_schedule_id TEXT, source_terminal INTEGER NOT NULL CHECK(typeof(source_terminal)='integer' AND source_terminal IN (0,1)), outcome_status TEXT, outcome_schedule_id TEXT, outcome_operation_id TEXT, outcome_occurrence_id TEXT, CHECK((outcome_status IS NULL)=(outcome_schedule_id IS NULL) AND (outcome_status IS NOT NULL OR (outcome_operation_id IS NULL AND outcome_occurrence_id IS NULL))), PRIMARY KEY(household_id,position), UNIQUE(household_id,event_key), FOREIGN KEY(household_id,source_schedule_id) REFERENCES recurrence_rules(household_id,schedule_id)); +CREATE TABLE recurrence_relative_slots(household_id TEXT NOT NULL, slot_key TEXT NOT NULL, schedule_id TEXT NOT NULL, definition_id TEXT NOT NULL, pattern_revision INTEGER NOT NULL CHECK(typeof(pattern_revision)='integer' AND pattern_revision>=1), occurrence_id TEXT NOT NULL, source_occurrence_id TEXT, source_cycle_id TEXT, created_at INTEGER NOT NULL CHECK(typeof(created_at)='integer' AND created_at>=0), receipt_actor TEXT NOT NULL CHECK(receipt_actor='system:recurrence'), receipt_action TEXT NOT NULL CHECK(receipt_action='recurrence.materialize'), timing_kind TEXT NOT NULL CHECK(timing_kind='completion_relative'), document TEXT NOT NULL, PRIMARY KEY(household_id,slot_key), UNIQUE(household_id,occurrence_id), CHECK((source_occurrence_id IS NULL)=(source_cycle_id IS NULL)), FOREIGN KEY(household_id,schedule_id,definition_id,timing_kind) REFERENCES recurrence_rules(household_id,schedule_id,definition_id,timing_kind), FOREIGN KEY(household_id,definition_id,occurrence_id) REFERENCES task_occurrences(household_id,definition_id,occurrence_id), FOREIGN KEY(household_id,source_occurrence_id,source_cycle_id) REFERENCES task_cycles(household_id,occurrence_id,cycle_id), FOREIGN KEY(household_id,receipt_actor,receipt_action,slot_key) REFERENCES receipts(household_id,actor_id,action,command_key) DEFERRABLE INITIALLY DEFERRED); +CREATE TABLE recurrence_rules(schedule_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL, definition_id TEXT NOT NULL, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), pattern_revision INTEGER NOT NULL CHECK(typeof(pattern_revision)='integer' AND pattern_revision>=1 AND pattern_revision<=revision), state TEXT NOT NULL CHECK(state IN ('active','paused','retired')), timing_kind TEXT NOT NULL CHECK(timing_kind IN ('fixed_calendar','completion_relative')), document TEXT NOT NULL, UNIQUE(household_id,schedule_id), UNIQUE(household_id,schedule_id,definition_id), UNIQUE(household_id,schedule_id,pattern_revision,timing_kind), UNIQUE(household_id,schedule_id,definition_id,timing_kind), FOREIGN KEY(household_id,definition_id) REFERENCES task_definitions(household_id,definition_id), FOREIGN KEY(household_id,schedule_id,pattern_revision,timing_kind) REFERENCES recurrence_progress(household_id,schedule_id,pattern_revision,timing_kind) DEFERRABLE INITIALLY DEFERRED); +CREATE TABLE recurrence_slots(household_id TEXT NOT NULL, slot_key TEXT NOT NULL, schedule_id TEXT NOT NULL, definition_id TEXT NOT NULL, pattern_revision INTEGER NOT NULL CHECK(typeof(pattern_revision)='integer' AND pattern_revision>=1), occurrence_id TEXT NOT NULL, nominal_kind TEXT NOT NULL CHECK(nominal_kind IN ('date','time')), nominal_value TEXT NOT NULL, resolved_at INTEGER, created_at INTEGER NOT NULL CHECK(typeof(created_at)='integer' AND created_at>=0), receipt_actor TEXT NOT NULL CHECK(receipt_actor='system:recurrence'), receipt_action TEXT NOT NULL CHECK(receipt_action='recurrence.materialize'), timing_kind TEXT NOT NULL CHECK(timing_kind='fixed_calendar'), document TEXT NOT NULL, PRIMARY KEY(household_id,slot_key), UNIQUE(household_id,occurrence_id), CHECK((nominal_kind='date' AND resolved_at IS NULL) OR (nominal_kind='time' AND typeof(resolved_at)='integer' AND resolved_at>=0)), FOREIGN KEY(household_id,schedule_id,definition_id,timing_kind) REFERENCES recurrence_rules(household_id,schedule_id,definition_id,timing_kind), FOREIGN KEY(household_id,definition_id,occurrence_id) REFERENCES task_occurrences(household_id,definition_id,occurrence_id), FOREIGN KEY(household_id,receipt_actor,receipt_action,slot_key) REFERENCES receipts(household_id,actor_id,action,command_key) DEFERRABLE INITIALLY DEFERRED); +CREATE TABLE retained_operations(household_id TEXT NOT NULL, actor_id TEXT NOT NULL, action TEXT NOT NULL, command_key TEXT NOT NULL, operation_id TEXT NOT NULL UNIQUE, position INTEGER NOT NULL UNIQUE CHECK(position>=1), current INTEGER NOT NULL CHECK(current IN (0,1)), archived_by TEXT, document TEXT NOT NULL, closed_recovery_id TEXT, PRIMARY KEY(household_id,actor_id,action,command_key)); +CREATE TABLE reward_funding_changes(household_id TEXT NOT NULL, redemption_id TEXT NOT NULL,revision INTEGER NOT NULL CHECK(revision>1), source TEXT NOT NULL CHECK(source IN ('points','cancellation')),source_id TEXT NOT NULL, stage TEXT NOT NULL CHECK(stage IN ('approved','funding_hold')),occurred_at INTEGER NOT NULL CHECK(occurred_at>=0), PRIMARY KEY(household_id,redemption_id,revision),UNIQUE(household_id,redemption_id,source,source_id),FOREIGN KEY(household_id,redemption_id) REFERENCES reward_redemptions(household_id,redemption_id)); +CREATE TABLE reward_offers(household_id TEXT NOT NULL REFERENCES households,offer_id TEXT NOT NULL, document TEXT NOT NULL CHECK(json_valid(document)),PRIMARY KEY(household_id,offer_id)); +CREATE TABLE reward_redemptions(position INTEGER PRIMARY KEY AUTOINCREMENT,household_id TEXT NOT NULL REFERENCES households, redemption_id TEXT NOT NULL,member_id TEXT NOT NULL, offer_id TEXT NOT NULL, cost_minor INTEGER NOT NULL CHECK(cost_minor>0),stage TEXT NOT NULL CHECK(stage IN ('requested','approved','funding_hold','delivered','cancelled')),document TEXT NOT NULL CHECK(json_valid(document)), UNIQUE(household_id,redemption_id),FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id),FOREIGN KEY(household_id,offer_id) REFERENCES reward_offers(household_id,offer_id)); +CREATE TABLE reward_settings(household_id TEXT PRIMARY KEY REFERENCES households,enabled INTEGER NOT NULL CHECK(enabled IN (0,1)), revision INTEGER NOT NULL CHECK(revision>=1)); +CREATE TABLE reward_spends(household_id TEXT NOT NULL, redemption_id TEXT NOT NULL,member_id TEXT NOT NULL, cost_minor INTEGER NOT NULL CHECK(cost_minor>0),posted_at INTEGER NOT NULL CHECK(posted_at>=0), title TEXT NOT NULL,PRIMARY KEY(household_id,redemption_id),FOREIGN KEY(household_id,redemption_id) REFERENCES reward_redemptions(household_id,redemption_id),FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)); +CREATE TABLE shopping_cancellations(household_id TEXT NOT NULL, purchase_id TEXT NOT NULL, quantity INTEGER NOT NULL CHECK(quantity BETWEEN 1 AND 999999999999999999), reason TEXT NOT NULL, member_id TEXT NOT NULL, created_at INTEGER NOT NULL CHECK(created_at>=0), PRIMARY KEY(household_id,purchase_id), FOREIGN KEY(household_id,purchase_id) REFERENCES shopping_purchases(household_id,purchase_id), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)) STRICT; +INSERT INTO "shopping_cancellations" VALUES('home','domus_GzvhyL40lw4ua72YuqdG_SI2z_wDFJBG',2000000,'Supplier cancelled the loose item','identity-1',100); +CREATE TABLE shopping_extras(position INTEGER PRIMARY KEY, household_id TEXT NOT NULL, extra_id TEXT NOT NULL, product_id TEXT, name TEXT NOT NULL, base_unit TEXT NOT NULL CHECK(base_unit IN ('piece','gram','millilitre')), quantity INTEGER NOT NULL CHECK(quantity BETWEEN 1 AND 999999999999999999), member_id TEXT NOT NULL, created_at INTEGER NOT NULL CHECK(created_at>=0), cleared_by TEXT, cleared_at INTEGER CHECK(cleared_at>=0), CHECK((cleared_by IS NULL) = (cleared_at IS NULL)), CHECK(product_id IS NOT NULL OR base_unit='piece'), UNIQUE(household_id,extra_id), FOREIGN KEY(household_id,product_id) REFERENCES inventory_products(household_id,product_id), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id), FOREIGN KEY(household_id,cleared_by) REFERENCES members(household_id,member_id)) STRICT; +INSERT INTO "shopping_extras" VALUES(1,'home','domus_d0671QKGtp7jSNkNLRo9DX9wUs-bwror','identity-3','Oil','millilitre',2,'identity-1',100,NULL,NULL); +INSERT INTO "shopping_extras" VALUES(2,'home','domus_slB4XXU5cp1xyt5rCQ5T4onfz3og3EVE',NULL,'Lemons','piece',2000000,'identity-1',100,NULL,NULL); +INSERT INTO "shopping_extras" VALUES(3,'home','domus_Ap0512Et0SZig2QOnumOz9QSuzevCz4s',NULL,'Spare','piece',1000000,'identity-1',100,'identity-1',100); +INSERT INTO "shopping_extras" VALUES(4,'home','fixture-v31-1',NULL,'Dish brush','piece',1000000,'identity-1',250,NULL,NULL); +INSERT INTO "shopping_extras" VALUES(5,'home','fixture-v31-3',NULL,'Dish soap','piece',1000000,'identity-1',250,NULL,NULL); +CREATE TABLE shopping_purchases(position INTEGER PRIMARY KEY, household_id TEXT NOT NULL, purchase_id TEXT NOT NULL, product_id TEXT, name TEXT NOT NULL, base_unit TEXT NOT NULL CHECK(base_unit IN ('piece','gram','millilitre')), purchased INTEGER NOT NULL CHECK(purchased BETWEEN 1 AND 999999999999999999), received INTEGER NOT NULL CHECK(received BETWEEN 0 AND purchased), settled INTEGER NOT NULL CHECK(settled BETWEEN 0 AND received), revision INTEGER NOT NULL CHECK(revision>0), member_id TEXT NOT NULL, created_at INTEGER NOT NULL CHECK(created_at>=0), cancelled INTEGER NOT NULL DEFAULT 0 CHECK(cancelled>=0 AND (cancelled=0 OR cancelled=purchased-received)), UNIQUE(household_id,purchase_id), CHECK(product_id IS NOT NULL OR (base_unit='piece' AND settled=received)), FOREIGN KEY(household_id,product_id) REFERENCES inventory_products(household_id,product_id), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)) STRICT; +INSERT INTO "shopping_purchases" VALUES(1,'home','domus_7DadKyZ9oOozqAgfBT4tHLtCE-g-evi7','identity-3','Oil','millilitre',2000000,750000,250000,4,'identity-1',1794321336329,0); +INSERT INTO "shopping_purchases" VALUES(2,'home','domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ','domus_CwE03pjDXqGzQ66BG_IqfYYfBEYDclIW','Session flour','gram',6000001,0,0,6,'identity-1',100,0); +INSERT INTO "shopping_purchases" VALUES(3,'home','domus_GzvhyL40lw4ua72YuqdG_SI2z_wDFJBG',NULL,'Lemons','piece',2000000,0,0,2,'identity-1',100,2000000); +INSERT INTO "shopping_purchases" VALUES(4,'home','domus_xMK8jzLSbWb-4cIDquBA1M4CzrXnYFl0','domus_Od8wq1rVNYDvVPOjwTdTCJyssAb7N7OP','Pears','piece',2000000,2000000,2000000,3,'identity-1',100,0); +INSERT INTO "shopping_purchases" VALUES(5,'home','domus_owkz3twLY8GPCTLqKmlCnN-YIvqlTc5G','domus_OtrCetg8XPQkMtK8crfCzq5l_pxex86C','Rice','gram',4000001,4000001,4000001,4,'identity-1',100,0); +INSERT INTO "shopping_purchases" VALUES(6,'home','fixture-v31-6',NULL,'Dish brush','piece',1000000,0,0,1,'identity-1',250,0); +INSERT INTO "shopping_purchases" VALUES(7,'home','fixture-v31-7',NULL,'Dish soap','piece',1000000,0,0,1,'identity-1',250,0); +CREATE TABLE shopping_receipt_corrections(household_id TEXT NOT NULL, receipt_id TEXT NOT NULL, movement_id TEXT NOT NULL, PRIMARY KEY(household_id,receipt_id), UNIQUE(household_id,movement_id), FOREIGN KEY(household_id,receipt_id) REFERENCES shopping_receipts(household_id,receipt_id), FOREIGN KEY(household_id,movement_id) REFERENCES inventory_movements(household_id,movement_id)) STRICT; +INSERT INTO "shopping_receipt_corrections" VALUES('home','domus_IjDCb68yPYGTfC5861ai_1ooEAz7_1q-','domus_wxbaFm36s1M-4Wn_vJHnJJkeENhSaO7N'); +CREATE TABLE shopping_receipt_returns(household_id TEXT NOT NULL, receipt_id TEXT NOT NULL, movement_id TEXT NOT NULL, PRIMARY KEY(household_id,receipt_id), UNIQUE(household_id,movement_id), FOREIGN KEY(household_id,receipt_id) REFERENCES shopping_receipts(household_id,receipt_id), FOREIGN KEY(household_id,movement_id) REFERENCES inventory_movements(household_id,movement_id)) STRICT; +INSERT INTO "shopping_receipt_returns" VALUES('home','domus_3AWQO2_g6TTpKkxd2JjHIYvz29kQ-q5m','domus_eccslYHn5WGuE0ODDpfrT8Y-EXexYglj'); +CREATE TABLE shopping_receipt_voids(household_id TEXT NOT NULL, receipt_id TEXT NOT NULL, reason TEXT NOT NULL, member_id TEXT NOT NULL, created_at INTEGER NOT NULL CHECK(created_at>=0), PRIMARY KEY(household_id,receipt_id), FOREIGN KEY(household_id,receipt_id) REFERENCES shopping_receipts(household_id,receipt_id), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)) STRICT; +INSERT INTO "shopping_receipt_voids" VALUES('home','domus_Cjq3pfqXcLk4s1HoYi8hSMli8bEv_OGG','Legacy pending void','identity-1',100); +CREATE TABLE shopping_receipts(position INTEGER PRIMARY KEY, household_id TEXT NOT NULL, receipt_id TEXT NOT NULL, purchase_id TEXT NOT NULL, quantity INTEGER NOT NULL CHECK(quantity BETWEEN 1 AND 999999999999999999), member_id TEXT NOT NULL, created_at INTEGER NOT NULL CHECK(created_at>=0), movement_id TEXT, UNIQUE(household_id,receipt_id), UNIQUE(household_id,movement_id), FOREIGN KEY(household_id,purchase_id) REFERENCES shopping_purchases(household_id,purchase_id), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id), FOREIGN KEY(household_id,movement_id) REFERENCES inventory_movements(household_id,movement_id)) STRICT; +INSERT INTO "shopping_receipts" VALUES(1,'home','domus_HYnlK7j7ShiTOsPacjrNxt2m6voRSJML','domus_7DadKyZ9oOozqAgfBT4tHLtCE-g-evi7',250000,'identity-1',1794321336332,'domus_8r5jVraFc6n3P4vEWEuUo_dcqQjQaYv3'); +INSERT INTO "shopping_receipts" VALUES(2,'home','domus_1M6yX8BB9moGlcKlR6kgxJgQGp331Tvm','domus_7DadKyZ9oOozqAgfBT4tHLtCE-g-evi7',500000,'identity-1',1794321336335,NULL); +INSERT INTO "shopping_receipts" VALUES(3,'home','domus_IjDCb68yPYGTfC5861ai_1ooEAz7_1q-','domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ',4000001,'identity-1',100,'domus_hOtKVv7KF08db_-AQBuN543KXuz-ljAa'); +INSERT INTO "shopping_receipts" VALUES(4,'home','domus_Cjq3pfqXcLk4s1HoYi8hSMli8bEv_OGG','domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ',500000,'identity-1',100,NULL); +INSERT INTO "shopping_receipts" VALUES(5,'home','domus_AE07stExzOh2XLuwGIkzwRc3zyhaZ7O6','domus_xMK8jzLSbWb-4cIDquBA1M4CzrXnYFl0',2000000,'identity-1',100,'domus_lYZd1XThXhORS9rwD4ihNxgPRmzjFISR'); +INSERT INTO "shopping_receipts" VALUES(6,'home','domus_3AWQO2_g6TTpKkxd2JjHIYvz29kQ-q5m','domus_owkz3twLY8GPCTLqKmlCnN-YIvqlTc5G',4000001,'identity-1',100,'domus_MzGllJGdOQlQ6O2hayc1xX8deFFf0ZCy'); +CREATE TABLE shopping_session_items(household_id TEXT NOT NULL, session_id TEXT NOT NULL, ordinal INTEGER NOT NULL CHECK(ordinal>=0 AND ordinal<16), purchase_id TEXT NOT NULL, PRIMARY KEY(household_id,session_id,ordinal), UNIQUE(household_id,purchase_id), FOREIGN KEY(household_id,session_id) REFERENCES shopping_sessions(household_id,session_id), FOREIGN KEY(household_id,purchase_id) REFERENCES shopping_purchases(household_id,purchase_id)) STRICT; +INSERT INTO "shopping_session_items" VALUES('home','domus_g2c2XVpWA6EkWYFy_ko12rhnhz4IDZGV',0,'domus_mKrjXkpWMSAyTuiePJgkyFxHawhsawsJ'); +INSERT INTO "shopping_session_items" VALUES('home','domus_g2c2XVpWA6EkWYFy_ko12rhnhz4IDZGV',1,'domus_GzvhyL40lw4ua72YuqdG_SI2z_wDFJBG'); +INSERT INTO "shopping_session_items" VALUES('home','fixture-v31-5',0,'fixture-v31-6'); +INSERT INTO "shopping_session_items" VALUES('home','fixture-v31-5',1,'fixture-v31-7'); +CREATE TABLE shopping_sessions(position INTEGER PRIMARY KEY, household_id TEXT NOT NULL, session_id TEXT NOT NULL, member_id TEXT NOT NULL, created_at INTEGER NOT NULL CHECK(created_at>=0), store_name TEXT CHECK(store_name IS NULL OR length(store_name) BETWEEN 1 AND 160), UNIQUE(household_id,session_id), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)) STRICT; +INSERT INTO "shopping_sessions" VALUES(1,'home','domus_g2c2XVpWA6EkWYFy_ko12rhnhz4IDZGV','identity-1',100,NULL); +INSERT INTO "shopping_sessions" VALUES(2,'home','fixture-v31-5','identity-1',250,'North Market'); +CREATE TABLE task_categories(category_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL REFERENCES households(household_id), label TEXT NOT NULL, label_key TEXT NOT NULL, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), archived INTEGER NOT NULL CHECK(archived IN (0,1))); +CREATE TABLE task_cycles(cycle_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL REFERENCES households(household_id), occurrence_id TEXT NOT NULL, active_occurrence_id TEXT, recorded_by TEXT NOT NULL, verified_by TEXT, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), closed_at INTEGER CHECK(closed_at IS NULL OR (typeof(closed_at)='integer' AND closed_at>=0)), document TEXT NOT NULL, UNIQUE(household_id,active_occurrence_id,cycle_id,revision), CHECK((closed_at IS NULL AND active_occurrence_id IS occurrence_id) OR (closed_at IS NOT NULL AND active_occurrence_id IS NULL)), FOREIGN KEY(household_id,occurrence_id) REFERENCES task_occurrences(household_id,occurrence_id) DEFERRABLE INITIALLY DEFERRED, FOREIGN KEY(household_id,recorded_by) REFERENCES members(household_id,member_id), FOREIGN KEY(household_id,verified_by) REFERENCES members(household_id,member_id), FOREIGN KEY(household_id,active_occurrence_id,cycle_id,revision) REFERENCES task_occurrences(household_id,occurrence_id,current_cycle_id,current_cycle_revision) DEFERRABLE INITIALLY DEFERRED); +INSERT INTO "task_cycles" VALUES('identity-14','home','identity-10','identity-10','identity-1',NULL,1,NULL,'{"closed_at":null,"cycle_id":"identity-14","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-10","performed_at":95,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":0,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null,"version":1}'); +CREATE TABLE task_definitions(definition_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL REFERENCES task_policy(household_id), revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), state TEXT NOT NULL CHECK(state IN ('draft','active','paused','archived')), document TEXT NOT NULL, UNIQUE(household_id,definition_id)); +INSERT INTO "task_definitions" VALUES('identity-9','home',1,'active','{"content":{"description":"","priority":"normal","tags":[],"title":"Refill the dispenser"},"created_at":100,"definition_id":"identity-9","household_id":"home","materials":[{"binding":{"household_id":"home","label":"Oil","location_id":"pantry","precision":6,"product_id":"identity-3","reference_id":"identity-4","revision":1,"unit_id":"millilitre"},"line_id":"identity-8","planned_quantity":"2"}],"overrides":{"adult_performer_may_approve":null,"claim_allowed":null,"dependency_gate":null,"eligible_roles":null,"material_recording":null,"point_value_minor":null,"task_scoped_material_consumption":null,"verification":null},"revision":1,"state":"active","version":2}'); +CREATE TABLE task_material_intents(intent_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL, occurrence_id TEXT NOT NULL, cycle_id TEXT NOT NULL, line_id TEXT NOT NULL, recorded_by TEXT NOT NULL, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), state TEXT NOT NULL CHECK(state IN ('pending_recording','pending_authorization','pending_regularization','pending_processing','not_used','posted','corrected','dismissed')), document TEXT NOT NULL, UNIQUE(household_id,cycle_id,line_id), FOREIGN KEY(household_id,occurrence_id,cycle_id) REFERENCES task_cycles(household_id,occurrence_id,cycle_id), FOREIGN KEY(household_id,recorded_by) REFERENCES members(household_id,member_id)); +INSERT INTO "task_material_intents" VALUES('identity-15','home','identity-10','identity-14','identity-8','identity-1',4,'corrected','{"authorized_at_recording":true,"created_at":100,"cycle_id":"identity-14","effect_revision":2,"household_id":"home","intent_id":"identity-15","line":{"binding":{"household_id":"home","label":"Oil","location_id":"pantry","precision":6,"product_id":"identity-3","reference_id":"identity-4","revision":1,"unit_id":"millilitre"},"line_id":"identity-8","planned_quantity":"2"},"occurrence_id":"identity-10","pending_reason":null,"performed_at":95,"posting":{"binding_revision":1,"cycle_id":"identity-14","effect_revision":2,"household_id":"home","intent_id":"identity-15","intent_revision":3,"inventory_operation_id":"identity-19","line_id":"identity-8","movement_id":"identity-20","occurrence_id":"identity-10","posted_at":100,"quantity":"1","reference_id":"identity-4"},"quantity":"1","reason":"Actual use","recorded_by":"identity-1","recording_mode":"review_on_completion","revision":4,"state":"corrected","submitted_quantity":"1.125","updated_at":100,"version":1}'); +CREATE TABLE task_missed_occurrence_settings(household_id TEXT NOT NULL, definition_id TEXT NOT NULL, policy TEXT NOT NULL CHECK(policy IN ('keep_visible','skip_after_review')), revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), PRIMARY KEY(household_id,definition_id), FOREIGN KEY(household_id,definition_id) REFERENCES task_definitions(household_id,definition_id)); +CREATE TABLE task_occurrences(occurrence_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL REFERENCES households(household_id), definition_id TEXT NOT NULL, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), state TEXT NOT NULL CHECK(state IN ('draft','available','assigned','in_progress','blocked','completed','cancelled','skipped')), current_cycle_id TEXT, current_cycle_revision INTEGER CHECK(current_cycle_revision IS NULL OR (typeof(current_cycle_revision)='integer' AND current_cycle_revision>=1)), document TEXT NOT NULL, UNIQUE(household_id,occurrence_id), UNIQUE(household_id,occurrence_id,current_cycle_id,current_cycle_revision), CHECK((state='completed' AND current_cycle_id IS NOT NULL AND current_cycle_revision IS NOT NULL) OR (state!='completed' AND current_cycle_id IS NULL AND current_cycle_revision IS NULL)), FOREIGN KEY(household_id,definition_id) REFERENCES task_definitions(household_id,definition_id), FOREIGN KEY(household_id,occurrence_id,current_cycle_id,current_cycle_revision) REFERENCES task_cycles(household_id,active_occurrence_id,cycle_id,revision) DEFERRABLE INITIALLY DEFERRED); +INSERT INTO "task_occurrences" VALUES('identity-10','home','identity-9',2,'completed','identity-14',1,'{"assignee_ids":[],"created_at":100,"current_cycle_id":"identity-14","current_cycle_revision":1,"definition_snapshot":{"content":{"description":"","priority":"normal","tags":[],"title":"Refill the dispenser"},"created_at":100,"definition_id":"identity-9","household_id":"home","materials":[{"binding":{"household_id":"home","label":"Oil","location_id":"pantry","precision":6,"product_id":"identity-3","reference_id":"identity-4","revision":1,"unit_id":"millilitre"},"line_id":"identity-8","planned_quantity":"2"}],"overrides":{"adult_performer_may_approve":null,"claim_allowed":null,"dependency_gate":null,"eligible_roles":null,"material_recording":null,"point_value_minor":null,"task_scoped_material_consumption":null,"verification":null},"revision":1,"state":"active","version":2},"due_at":null,"household_id":"home","occurrence_id":"identity-10","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":"","version":2}'); +CREATE TABLE task_policy(household_id TEXT PRIMARY KEY NOT NULL REFERENCES households(household_id), revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), document TEXT NOT NULL); +INSERT INTO "task_policy" VALUES('home',1,'{"household_id":"home","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":0,"task_scoped_material_consumption":true,"verification":"role_default"},"version":1}'); +CREATE INDEX outbox_pending ON outbox(delivered,position); +CREATE INDEX recovery_pending ON recovery_requests(household_id,state,expires_at); +CREATE INDEX retained_recovery ON retained_operations(household_id,closed_recovery_id) WHERE current=0 AND closed_recovery_id IS NOT NULL; +CREATE UNIQUE INDEX task_member_scope ON members(household_id,member_id); +CREATE INDEX task_definitions_page ON task_definitions(household_id,state,definition_id); +CREATE INDEX task_occurrences_page ON task_occurrences(household_id,state,occurrence_id); +CREATE INDEX task_occurrences_definition ON task_occurrences(household_id,definition_id,occurrence_id); +CREATE INDEX task_cycles_page ON task_cycles(household_id,occurrence_id,cycle_id); +CREATE UNIQUE INDEX task_one_open_cycle ON task_cycles(household_id,occurrence_id) WHERE closed_at IS NULL; +CREATE UNIQUE INDEX task_cycle_material_scope ON task_cycles(household_id,occurrence_id,cycle_id); +CREATE INDEX task_material_cycle_page ON task_material_intents(household_id,cycle_id,intent_id); +CREATE INDEX task_cycle_event_page ON outbox(json_extract(payload,'$.cycle.cycle_id'),position); +CREATE INDEX task_occurrence_event_page ON outbox(json_extract(payload,'$.occurrence_id'),position); +CREATE INDEX task_dependency_ack_page ON outbox(json_extract(payload,'$.review.cause.dependent_cycle_id'),json_extract(payload,'$.review.cause.source_operation_id'),position); +CREATE UNIQUE INDEX recurrence_occurrence_scope ON task_occurrences(household_id,definition_id,occurrence_id); +CREATE UNIQUE INDEX recurrence_cycle_scope ON task_cycles(household_id,occurrence_id,cycle_id); +CREATE UNIQUE INDEX recurrence_progress_revision ON recurrence_progress(household_id,schedule_id,revision); +CREATE UNIQUE INDEX recurrence_current_definition ON recurrence_rules(household_id,definition_id) WHERE state!='retired'; +CREATE INDEX recurrence_rules_page ON recurrence_rules(household_id,state,schedule_id); +CREATE INDEX recurrence_slots_page ON recurrence_slots(household_id,schedule_id,slot_key); +CREATE INDEX recurrence_relative_slots_page ON recurrence_relative_slots(household_id,schedule_id,slot_key); +CREATE INDEX recurrence_relative_pending ON recurrence_relative_inbox(household_id,position) WHERE outcome_status IS NULL; +CREATE INDEX recurrence_relative_pending_rule ON recurrence_relative_inbox(household_id,source_schedule_id,source_terminal DESC,position) WHERE outcome_status IS NULL; +CREATE UNIQUE INDEX task_categories_active_label ON task_categories(household_id,label_key) WHERE archived=0; +CREATE UNIQUE INDEX points_one_effect_per_cycle ON points_task_receipts(household_id,cycle_id,effect) WHERE effect>0; +CREATE INDEX points_definition_rotation ON points_task_receipts(household_id,definition_id,position) WHERE effect=1; +CREATE INDEX points_restored_award_closure ON retained_operations(household_id,json_extract(document,'$.event_payload.cycle.cycle_id'),position) WHERE current=0 AND (action='task.reopen' OR (action='task.verify' AND json_extract(document,'$.event_payload.cycle.verification')='rejected')); +CREATE INDEX inventory_reservations ON inventory_effects(household_id,reference_id) WHERE kind='reservation' AND remaining>0; +CREATE INDEX point_allocation_rotation ON point_completion_allocations(household_id,definition_id,position) WHERE json_extract(document,'$.policy.mode')='conserve_total'; +CREATE INDEX reward_member_requests ON reward_redemptions(household_id,member_id,position); +CREATE INDEX reward_member_reservations ON reward_redemptions(household_id,member_id,stage) WHERE stage IN ('requested','approved','funding_hold'); +CREATE INDEX reward_member_spending ON reward_spends(household_id,member_id,posted_at); +CREATE INDEX inventory_history ON inventory_movements(household_id,reference_id,position); +CREATE INDEX shopping_history ON shopping_purchases(household_id,position); +CREATE INDEX shopping_receipt_history ON shopping_receipts(household_id,purchase_id,position); +CREATE INDEX shopping_active_extras ON shopping_extras(household_id,product_id,position) WHERE cleared_at IS NULL; +CREATE INDEX shopping_session_history ON shopping_sessions(household_id,position); +CREATE UNIQUE INDEX shopping_open_pantry ON shopping_purchases(household_id,product_id) WHERE product_id IS NOT NULL AND settled+cancelled