From 5728f074bb4f0f8e1906cac96ff1c97e77570746 Mon Sep 17 00:00:00 2001 From: "copilot-action[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:49:07 +0100 Subject: [PATCH 01/16] docs(sdd): specify issue contract in specs/stock-local-barcode.md --- specs/CATALOG.md | 4 +- specs/catalog.json | 3 +- specs/stock-local-barcode.md | 180 +++++++++++++++++++++++++++++++++++ 3 files changed, 184 insertions(+), 3 deletions(-) create mode 100644 specs/stock-local-barcode.md diff --git a/specs/CATALOG.md b/specs/CATALOG.md index 8e51b56..e6d8652 100644 --- a/specs/CATALOG.md +++ b/specs/CATALOG.md @@ -16,7 +16,7 @@ debt or convert unknown historic intent into a design decision. | `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) | 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 | +| `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) + 1 companion | 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) + 3 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 | @@ -94,7 +94,7 @@ debt or convert unknown historic intent into a design decision. - Owner: Domus maintainers (review assignment pending) - Last verified: 2026-11-11 -- Specifications: [`specs/household-inventory.md`](./household-inventory.md) +- Specifications: [`specs/household-inventory.md`](./household-inventory.md) · [`specs/stock-local-barcode.md`](./stock-local-barcode.md) - Workflows: Not applicable for this capability. - Entrypoints: [`backend/src/domus/entrypoints/inventory_http.py`](../backend/src/domus/entrypoints/inventory_http.py) - Core code: [`backend/src/domus/domain/inventory.py`](../backend/src/domus/domain/inventory.py) · [`backend/src/domus/application/inventory.py`](../backend/src/domus/application/inventory.py) · [`backend/src/domus/infrastructure/sqlite_inventory.py`](../backend/src/domus/infrastructure/sqlite_inventory.py) · [`backend/src/domus/application/inventory_queries.py`](../backend/src/domus/application/inventory_queries.py) · [`frontend/src/presentation/domus-inventory.ts`](../frontend/src/presentation/domus-inventory.ts) · [`frontend/src/presentation/domus-stock-attention.ts`](../frontend/src/presentation/domus-stock-attention.ts) diff --git a/specs/catalog.json b/specs/catalog.json index 0287c3f..04876ce 100644 --- a/specs/catalog.json +++ b/specs/catalog.json @@ -791,7 +791,8 @@ "owner": "Domus maintainers (review assignment pending)", "lastVerified": "2026-11-11", "specs": [ - "specs/household-inventory.md" + "specs/household-inventory.md", + "specs/stock-local-barcode.md" ], "workflows": [], "entrypoints": [ diff --git a/specs/stock-local-barcode.md b/specs/stock-local-barcode.md new file mode 100644 index 0000000..b43c348 --- /dev/null +++ b/specs/stock-local-barcode.md @@ -0,0 +1,180 @@ +# Find household products by manually entered barcode + +- Status: Draft +- Owners: Domus maintainers and Inventory +- Scope: Manual GTIN validation, local catalog search and barcode associations +- Open decisions blocking readiness: none + +## 1. Executive summary + +Enter the number printed under a retail barcode and find the corresponding +product in the household catalog. Inventory managers can associate a validated +number with an existing catalog product and correct an erroneous association. + +## 2. Problem, current behavior, and evidence + +Inventory supports product registration and stock workflows. Its catalog +has no local barcode associations or lookup. The owner confirmed manual +entry and local matching in the existing Inventory specification. + +## 3. Actors, surfaces, and terminology + +A household reader can search Inventory. A member with current inventory +management authority can maintain the association. A GTIN is the retail +trade item number printed alongside a barcode. The local association points +to the stable product identity. + +## 4. Goals, non-goals, and fixed invariants + +| Requirement | Behavior | +|---|---| +| stock-local-barcode-R01 | Accept manually entered GS1 GTIN-8, GTIN-12, GTIN-13 and GTIN-14 text, validate the check digit and use the zero-padded 14-character identity for matching. | +| stock-local-barcode-R02 | A current household reader can find at most one catalog product by a valid barcode. Distinguish invalid input, an unlinked barcode and an unavailable lookup. Keep requests within Domus. | +| stock-local-barcode-R03 | An inventory manager can link or explicitly remove a barcode association in the current household. Concurrent updates preserve uniqueness. Original operations can be recovered. Product identity, quantities and existing ledger history are preserved. | +| stock-local-barcode-R04 | Migrate and restore the local association index safely. Preserve representative older inventory and its receipts. | +| stock-local-barcode-R05 | Support an accessible manual workflow in English and Spanish through both deployment compositions and the installed Edge candidate. | + +The manual workflow forms the local lookup shared by future camera and +configured provider adapters. Package quantities follow the owning conversion +contract. + +## 5. Current versus proposed product journey + +Open Inventory, type or paste a GTIN, and search. If a product matches, see +its name and open its existing stock detail. When there is no association, +a manager can attach the code to an existing product. Ordinary product +registration remains available. + +## 6. Functional behavior and state model + +Validate ASCII digits, the supported lengths and the GS1 check digit before +deriving the canonical string. Preserve leading zeroes. Apply the same +canonical identity to every lookup and association. Equivalent forms +resolve the same link. A code belongs to at most one product in a household. +Remove a link only when it is still the association the manager reviewed. +Link changes and their original command receipts commit atomically. + +## 7. User-facing configuration + +Use the existing household locale and inventory grants. The lookup reads +the current household database and uses existing Inventory navigation. + +## 8. Clean Architecture design + +A pure domain value validates the GTIN. Application services own grants, +association commands and exact queries. SQLite enforces the household key +and the product reference. The HTTP entry point validates transport input. +The browser uses published ha-ui field, button and feedback components. + +## 9. UI/UX and content contract + +Label the field for the printed barcode digits, preserve zeroes when +pasting and use a numeric keyboard hint. Give an example of the supported +lengths. State whether the code is invalid, unlinked, found or temporarily +unavailable and offer the relevant next action. Show the product name before +the manager submits a link or removal. Preserve a correctable draft. + +## 10. Failure, recovery, and cleanup + +A duplicate association displays the conflict while retaining the entered +code. An unavailable query offers retry. A lost successful reply recovers the +original result. A stale removal leaves a newer association intact. + +## 11. Security, permissions, and privacy + +Authorize exact reads under the verified current household. Recheck +inventory management authority for writes and original receipt access. +Validate before querying and resolve products within the current household. +Keep lookup data within the Domus installation. + +## 12. Observability and operational UX + +Operation receipts record association changes. Product history continues to +report its existing movement identities and quantities. + +## 13. Compatibility, migration, rollout, and rollback + +Initialize an empty barcode index for existing households. Test +representative data from the current previous schema 34, schema 30 and schema 20. Verify restart and activated +compatible restore of a barcode link and its receipt. Qualify the installed +candidate with its exact version and a compatible rollback checkpoint. + +## 14. Testing strategy and numeric budget + +Minimum eight distinct cases. + +| Area | Minimum distinct cases | Behaviors/risks covered | +|---|---:|---| +| Barcode identity | 1 | Observable scenarios in the case inventory. | +| Local catalog | 1 | Observable scenarios in the case inventory. | +| Authorization | 1 | Observable scenarios in the case inventory. | +| State and concurrency | 1 | Observable scenarios in the case inventory. | +| State and recovery | 1 | Observable scenarios in the case inventory. | +| Upgrade and restoration | 1 | Observable scenarios in the case inventory. | +| Browser acceptance | 1 | Observable scenarios in the case inventory. | +| Installed acceptance | 1 | Observable scenarios in the case inventory. | +| Total | 8 | Distinct inventory cases; repeated executions do not add cases. | + +| Case ID | Area | Requirements | Scenario | +|---|---|---|---| +| stock-local-barcode-C01 | Barcode identity | stock-local-barcode-R01 | Validate GS1 check digits for all four supported lengths. Leading zeroes survive and equivalent strings resolve one canonical key. Reject malformed, wrong-length and check-digit-invalid input. | +| stock-local-barcode-C02 | Local catalog | stock-local-barcode-R02 | Find a linked product and distinguish a valid unlinked code. Exercise local lookup with external connectivity absent and observe only installation-local requests. | +| stock-local-barcode-C03 | Authorization | stock-local-barcode-R02, stock-local-barcode-R03 | A current household reader can find an own product. A foreign association is invisible. A reader without management access cannot modify a link or recover its original write. | +| stock-local-barcode-C04 | State and concurrency | stock-local-barcode-R03 | Race two products for equivalent forms of one code. Exactly one link wins. Explicitly remove it and verify a stale removal cannot delete a later association. | +| stock-local-barcode-C05 | State and recovery | stock-local-barcode-R03 | Recover the original receipt after a lost reply, reject a different command under the same key and roll back the association on a late failure. | +| stock-local-barcode-C06 | Upgrade and restoration | stock-local-barcode-R04 | Preserve representative schema 34, schema 30 and schema 20 data during migration. Restart and activate a compatible backup containing a link and its original operation. | +| stock-local-barcode-C07 | Browser acceptance | stock-local-barcode-R05 | Enter a code, see invalid and unlinked states, link to the selected product and find it again. Verify desktop keyboard and narrow touch use in English and Spanish through Ingress and standalone. | +| stock-local-barcode-C08 | Installed acceptance | stock-local-barcode-R05 | Verify the installed Edge version, exercise the manual lookup with disposable data and qualify both architecture images. | + +## 15. Documentation and discoverability + +[specs/stock-local-barcode.md](stock-local-barcode.md) · [docs/roadmap.md](../docs/roadmap.md) · [docs/household-api.md](../docs/household-api.md) · [backend/src/domus/domain/inventory.py](../backend/src/domus/domain/inventory.py) · [backend/src/domus/application/inventory.py](../backend/src/domus/application/inventory.py) · [backend/src/domus/application/inventory\_queries.py](../backend/src/domus/application/inventory_queries.py) · [backend/src/domus/infrastructure/sqlite\_inventory.py](../backend/src/domus/infrastructure/sqlite_inventory.py) · [backend/src/domus/entrypoints/inventory\_http.py](../backend/src/domus/entrypoints/inventory_http.py) · [frontend/src/presentation/domus-inventory.ts](../frontend/src/presentation/domus-inventory.ts) · [frontend/src/presentation/inventory-messages.ts](../frontend/src/presentation/inventory-messages.ts) + +| Path | Change | +|---|---| +| specs/stock-local-barcode.md | create | +| docs/roadmap.md | update | +| docs/household-api.md | update | +| backend/src/domus/domain/inventory.py | update | +| backend/src/domus/application/inventory.py | update | +| backend/src/domus/application/inventory_queries.py | update | +| backend/src/domus/infrastructure/sqlite_inventory.py | update | +| backend/src/domus/entrypoints/inventory_http.py | update | +| frontend/src/presentation/domus-inventory.ts | update | +| frontend/src/presentation/inventory-messages.ts | update | + +## 16. Acceptance scenarios + +Enter a valid UPC, link it to an existing product, and look it up using its +zero-padded representation. Observe the product's stable identity and exact +stock. Correct the association through the manager flow. + +## 17. Requirements traceability + +| Requirement | Cases | +|---|---| +| stock-local-barcode-R01 | stock-local-barcode-C01 | +| stock-local-barcode-R02 | stock-local-barcode-C02, stock-local-barcode-C03 | +| stock-local-barcode-R03 | stock-local-barcode-C03, stock-local-barcode-C04, stock-local-barcode-C05 | +| stock-local-barcode-R04 | stock-local-barcode-C06 | +| stock-local-barcode-R05 | stock-local-barcode-C07, stock-local-barcode-C08 | + +## 18. Implementation sequence + +Validate and normalize GTINs. Add protected exact lookup, association +commands and durable storage. Integrate the manual Inventory experience +and qualify the package on both deployment targets. + +## 19. Definition of Done + +Verify the eight cases, global and per-file coverage, both architecture +images, deployed Edge version and scoped test cleanup. + +## 20. References and decisions + +The owner's decision A14 and household-inventory-R7 accept manual entry +and local catalog search. GS1 defines the supported GTIN lengths, check +digit and the 14-character zero-padded representation. + +https://support.gs1.org/support/solutions/articles/43000734355-what-is-the-required-format-of-gtin-in-gs1-edi-standards- +https://ref.gs1.org/guidelines/2d-in-retail/1.1.0/ From 3751c4e1650f5de5433bcbefe228260c0b07753b Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 16:55:30 +0100 Subject: [PATCH 02/16] feat(inventory): find products by local barcode and review associations --- .github/workflows/ci_check.yml | 4 +- backend/src/domus/application/inventory.py | 32 ++ .../src/domus/application/inventory_ports.py | 4 + .../domus/application/inventory_queries.py | 22 ++ backend/src/domus/domain/inventory.py | 31 ++ backend/src/domus/entrypoints/http_errors.py | 3 + .../src/domus/entrypoints/inventory_http.py | 33 ++ backend/src/domus/entrypoints/native_http.py | 1 + backend/src/domus/infrastructure/sqlite.py | 12 +- .../domus/infrastructure/sqlite_inventory.py | 40 +++ .../domus/infrastructure/sqlite_snapshots.py | 3 + docs/contracts/household-api.openapi.json | 320 +++++++++++++++++ .../native-household-api.openapi.json | 320 +++++++++++++++++ docs/evidence/local-barcode-qualification.md | 46 +++ .../evidence/task-navigation-integration.json | 8 +- docs/household-api.md | 67 +++- docs/user-guide.md | 22 ++ frontend/package.json | 2 +- frontend/src/adapters/inventory-http.ts | 38 +- .../src/application/inventory-controller.ts | 29 +- frontend/src/composition/entry-page.ts | 6 +- frontend/src/domain/inventory.ts | 30 ++ frontend/src/presentation/domus-inventory.ts | 132 ++++++- .../src/presentation/inventory-messages.ts | 42 +++ .../tests/e2e/workspace-navigation.spec.ts | 128 +++++++ frontend/tests/inventory.test.ts | 333 +++++++++++++++++- frontend/tests/page.test.ts | 9 + pnpm-lock.yaml | 10 +- .../backend/test_activation_compatibility.py | 2 +- .../backend/test_automation_draft_storage.py | 4 +- .../test_automation_execution_storage.py | 4 +- tests/backend/test_daily_automation_drafts.py | 7 +- tests/backend/test_inventory_barcode_http.py | 110 ++++++ tests/backend/test_inventory_barcodes.py | 261 ++++++++++++++ .../backend/test_inventory_catalog_storage.py | 2 +- tests/backend/test_inventory_movements.py | 2 +- tests/backend/test_inventory_recurrence.py | 2 +- tests/backend/test_pantry_replenishment.py | 4 +- tests/backend/test_physical_receipt_return.py | 2 +- tests/backend/test_physical_receipt_void.py | 2 +- .../backend/test_point_allocation_storage.py | 4 +- .../backend/test_posted_receipt_correction.py | 2 +- tests/backend/test_purchase_balance.py | 2 +- tests/backend/test_purchase_sessions.py | 4 +- tests/backend/test_recurrence_frontier.py | 2 +- .../test_recurrence_lifecycle_migration.py | 6 +- tests/backend/test_restore_source.py | 4 +- tests/backend/test_rewards_storage.py | 2 +- tests/backend/test_shared_shopping.py | 2 +- tests/backend/test_shopping_storage.py | 2 +- tests/backend/test_sqlite_history.py | 2 +- tests/backend/test_sqlite_identity.py | 2 +- tests/backend/test_sqlite_member_profiles.py | 4 +- tests/backend/test_sqlite_recovery.py | 2 +- tests/backend/test_sqlite_recurrence.py | 2 +- .../test_sqlite_recurrence_integrity.py | 4 +- tests/backend/test_sqlite_snapshots.py | 2 +- tests/backend/test_sqlite_task_integrity.py | 4 +- tests/backend/test_sqlite_task_materials.py | 6 +- tests/backend/test_sqlite_task_reviews.py | 5 +- tests/backend/test_task_categories.py | 2 +- tests/backend/test_task_restoration.py | 2 +- tests/python/test_ci_contract.py | 4 +- 63 files changed, 2114 insertions(+), 86 deletions(-) create mode 100644 docs/evidence/local-barcode-qualification.md create mode 100644 tests/backend/test_inventory_barcode_http.py create mode 100644 tests/backend/test_inventory_barcodes.py diff --git a/.github/workflows/ci_check.yml b/.github/workflows/ci_check.yml index 92f39b1..2dce4eb 100644 --- a/.github/workflows/ci_check.yml +++ b/.github/workflows/ci_check.yml @@ -401,11 +401,11 @@ jobs: run: >- lockf -k -t 600 /tmp/domus-ci-entry-browser.lock pnpm --filter @domus/frontend exec playwright test -c playwright.entry.config.ts tests/e2e/administration.spec.ts tests/e2e/tasks.spec.ts tests/e2e/workspace-navigation.spec.ts - - name: Require all sixty-four actual-image household journeys + - name: Require all sixty-six actual-image household journeys run: >- uv run python -c "import json; from pathlib import Path; result=json.loads(Path('frontend/test-results/entry-results.json').read_text()); - assert result['stats']['expected']==64 and result['stats']['unexpected']==0 + assert result['stats']['expected']==66 and result['stats']['unexpected']==0 and result['stats']['skipped']==0 and result['stats']['flaky']==0" - name: Retain actual-image browser evidence diff --git a/backend/src/domus/application/inventory.py b/backend/src/domus/application/inventory.py index bf01e84..d687b98 100644 --- a/backend/src/domus/application/inventory.py +++ b/backend/src/domus/application/inventory.py @@ -17,6 +17,7 @@ MAX_NAMED_LOCATIONS, MAX_STOCK_UNITS, PANTRY, + BarcodeAssociation, BaseUnit, CatalogProduct, EffectKind, @@ -26,6 +27,7 @@ StockMovement, StockTransfer, StorageLocation, + canonical_gtin, stock_quantity, stock_units, validate_location_name, @@ -141,6 +143,8 @@ def settle(self, request: MaterialPostingRequest) -> InventoryMaterialResult: class CatalogAction(StrEnum): REGISTER = "inventory.register-product" + LINK_BARCODE = "inventory.link-barcode" + REMOVE_BARCODE = "inventory.remove-barcode" ADD_LOCATION = "inventory.add-location" TRANSFER = "inventory.transfer" INTAKE = "inventory.intake" @@ -328,6 +332,34 @@ def apply(unit: UnitOfWork, member: str, command: CommandKey) -> JsonDocument: return self._execute(CatalogAction.ADD_LOCATION.value, key, payload, apply) + def link_barcode(self, key: str, barcode: str, product_id: str) -> Receipt: + canonical = canonical_gtin(barcode) + validate_identifier(product_id) + payload = JsonDocument.from_value({"barcode": canonical, "product_id": product_id}) + + def apply(unit: UnitOfWork, member: str, command: CommandKey) -> JsonDocument: + stock = unit.inventory + self._product(stock, product_id) + if stock.barcode(self.household_id, canonical) is not None: + raise Conflict("inventory_barcode_linked") + association = BarcodeAssociation(canonical, self.identifiers.new(), product_id) + stock.link_barcode(self.household_id, association) + return JsonDocument.from_value(asdict(association)) + + return self._execute(CatalogAction.LINK_BARCODE.value, key, payload, apply) + + def remove_barcode( + self, key: str, barcode: str, product_id: str, association_id: str + ) -> Receipt: + association = BarcodeAssociation(canonical_gtin(barcode), association_id, product_id) + payload = JsonDocument.from_value(asdict(association)) + + def apply(unit: UnitOfWork, member: str, command: CommandKey) -> JsonDocument: + unit.inventory.remove_barcode(self.household_id, association) + return payload + + return self._execute(CatalogAction.REMOVE_BARCODE.value, key, payload, apply) + def transfer( self, key: str, product_id: str, source: str, destination: str, quantity: MaterialQuantity ) -> Receipt: diff --git a/backend/src/domus/application/inventory_ports.py b/backend/src/domus/application/inventory_ports.py index 4aa9246..a6ebac4 100644 --- a/backend/src/domus/application/inventory_ports.py +++ b/backend/src/domus/application/inventory_ports.py @@ -4,6 +4,7 @@ from typing import Protocol from domus.domain.inventory import ( + BarcodeAssociation, CatalogProduct, InventoryEffect, ReplenishmentPolicy, @@ -23,6 +24,9 @@ class LedgerEntry: class InventoryRecords(Protocol): + def barcode(self, home: str, barcode: str) -> BarcodeAssociation | None: ... + def link_barcode(self, home: str, value: BarcodeAssociation) -> None: ... + def remove_barcode(self, home: str, value: BarcodeAssociation) -> None: ... def add_product(self, home: str, product: CatalogProduct) -> None: ... def product(self, home: str, product_id: str) -> CatalogProduct | None: ... def products(self, home: str, after: str, limit: int) -> tuple[CatalogProduct, ...]: ... diff --git a/backend/src/domus/application/inventory_queries.py b/backend/src/domus/application/inventory_queries.py index af712de..5387a4f 100644 --- a/backend/src/domus/application/inventory_queries.py +++ b/backend/src/domus/application/inventory_queries.py @@ -23,11 +23,13 @@ from domus.domain.identity import HumanIdentity, Permission, allows, effective_role from domus.domain.inventory import ( PANTRY, + BarcodeAssociation, BaseUnit, CatalogProduct, MovementKind, StockTransfer, StorageLocation, + canonical_gtin, stock_quantity, ) from domus.domain.shopping import Purchase, PurchaseReceipt, PurchaseSession @@ -90,6 +92,14 @@ class LowStockCount: low_stock_products: int +@dataclass(frozen=True, slots=True) +class BarcodeLookup: + barcode: str + may_manage: bool + association: BarcodeAssociation | None + product: CatalogProduct | None + + @dataclass(frozen=True, slots=True) class InstallationLowStock: transactions: Transactions @@ -369,6 +379,18 @@ class InventoryQueries: human: HumanIdentity cursors: TaskCursors + def barcode(self, value: str) -> BarcodeLookup: + canonical = canonical_gtin(value) + with self.store.read() as unit: + home, grants, _ = self._access(unit, "inventory-barcode-v1", 1, None) + association = unit.inventory.barcode(home, canonical) + product = ( + None + if association is None + else unit.inventory.product(home, association.product_id) + ) + return BarcodeLookup(canonical, grants.manage, association, product) + def _access( self, unit: UnitOfWork, query: str, limit: int, product_id: str | None ) -> tuple[str, _InventoryGrants, JsonDocument]: diff --git a/backend/src/domus/domain/inventory.py b/backend/src/domus/domain/inventory.py index abb8d14..f8f01ba 100644 --- a/backend/src/domus/domain/inventory.py +++ b/backend/src/domus/domain/inventory.py @@ -17,6 +17,37 @@ MAX_NAMED_LOCATIONS = 32 +def canonical_gtin(value: str) -> str: + """Validate the printed GS1 identity before deriving its fourteen-digit key.""" + if ( + not isinstance(value, str) + or len(value) not in (8, 12, 13, 14) + or not value.isascii() + or not value.isdigit() + ): + raise InvalidInput("invalid_inventory_barcode") + weighted = sum( + int(digit) * (3 if index % 2 == 0 else 1) + for index, digit in enumerate(reversed(value[:-1])) + ) + if (weighted + int(value[-1])) % 10: + raise InvalidInput("invalid_inventory_barcode") + return value.zfill(14) + + +@dataclass(frozen=True, slots=True) +class BarcodeAssociation: + barcode: str + association_id: str + product_id: str + + def __post_init__(self) -> None: + if canonical_gtin(self.barcode) != self.barcode: + raise InvalidInput("invalid_inventory_barcode") + validate_identifier(self.association_id) + validate_identifier(self.product_id) + + class BaseUnit(StrEnum): PIECE = "piece" GRAM = "gram" diff --git a/backend/src/domus/entrypoints/http_errors.py b/backend/src/domus/entrypoints/http_errors.py index 9ea14eb..83ee564 100644 --- a/backend/src/domus/entrypoints/http_errors.py +++ b/backend/src/domus/entrypoints/http_errors.py @@ -174,6 +174,9 @@ "invalid_replenishment_bounds", "invalid_inventory_receipt", "inventory_product_missing", + "invalid_inventory_barcode", + "inventory_barcode_linked", + "inventory_barcode_changed", "inventory_stock_capacity", "invalid_inventory_location_name", "inventory_location_exists", diff --git a/backend/src/domus/entrypoints/inventory_http.py b/backend/src/domus/entrypoints/inventory_http.py index ab96b9f..550456f 100644 --- a/backend/src/domus/entrypoints/inventory_http.py +++ b/backend/src/domus/entrypoints/inventory_http.py @@ -9,6 +9,7 @@ from domus.application.inventory import CatalogAction from domus.application.inventory_queries import ( + BarcodeLookup, InventoryView, MovementHistory, PhysicalReceiptsView, @@ -50,6 +51,26 @@ class LocationBody(StrictModel): name: str = Field(min_length=1, max_length=MAX_LOCATION_NAME) +Barcode = Annotated[str, Field(min_length=8, max_length=14, pattern=r"^[0-9]+$")] + + +class BarcodeQuery(StrictModel): + barcode: Barcode + + +class LinkBarcodeBody(StrictModel): + action: Literal["inventory.link-barcode"] + barcode: Barcode + product_id: Identifier + + +class RemoveBarcodeBody(StrictModel): + action: Literal["inventory.remove-barcode"] + barcode: Barcode + product_id: Identifier + association_id: Identifier + + class TransferBody(StrictModel): action: Literal["inventory.transfer"] product_id: Identifier @@ -170,6 +191,8 @@ class ReturnReceiptBody(ReceiptCorrectionBody): CatalogBody = Annotated[ ProductBody + | LinkBarcodeBody + | RemoveBarcodeBody | LocationBody | TransferBody | IntakeBody @@ -203,6 +226,10 @@ def create_inventory_router( def catalog(request: Request, query: Annotated[PageQuery, Query()]) -> InventoryView: return context(request).inventory().report(limit=query.limit, cursor=query.cursor) + @router.get("/barcode", response_model=BarcodeLookup) + def barcode(request: Request, query: Annotated[BarcodeQuery, Query()]) -> BarcodeLookup: + return context(request).inventory().barcode(query.barcode) + @router.get("/stock-attention", response_model=StockAttention) def stock_attention(request: Request, query: Annotated[_EmptyQuery, Query()]) -> StockAttention: return context(request).inventory().stock_attention() @@ -279,6 +306,12 @@ def command( inventory, key = context(request).inventory_commands, _key(request) if isinstance(body, ProductBody): receipt = inventory.register(key, body.name, body.base_unit) + elif isinstance(body, LinkBarcodeBody): + receipt = inventory.link_barcode(key, body.barcode, body.product_id) + elif isinstance(body, RemoveBarcodeBody): + receipt = inventory.remove_barcode( + key, body.barcode, body.product_id, body.association_id + ) elif isinstance(body, LocationBody): receipt = inventory.add_location(key, body.name) elif isinstance(body, TransferBody): diff --git a/backend/src/domus/entrypoints/native_http.py b/backend/src/domus/entrypoints/native_http.py index df18f44..bbde4d5 100644 --- a/backend/src/domus/entrypoints/native_http.py +++ b/backend/src/domus/entrypoints/native_http.py @@ -125,6 +125,7 @@ def _allowed(self, scope: Scope) -> None: "/api/v1/family/allocation", "/api/v1/family/rewards", "/api/v1/inventory", + "/api/v1/inventory/barcode", "/api/v1/inventory/purchases", "/api/v1/inventory/purchase-sessions", "/api/v1/inventory/shopping-list", diff --git a/backend/src/domus/infrastructure/sqlite.py b/backend/src/domus/infrastructure/sqlite.py index 571bee0..2c166ae 100644 --- a/backend/src/domus/infrastructure/sqlite.py +++ b/backend/src/domus/infrastructure/sqlite.py @@ -48,6 +48,8 @@ from domus.infrastructure.sqlite_history import HISTORY_STATEMENTS, SQLiteHistory from domus.infrastructure.sqlite_identity import SQLiteMembers, SQLitePolicies from domus.infrastructure.sqlite_inventory import ( + BARCODE_STATEMENT, + BARCODE_TABLE, CATALOG_STATEMENTS, CATALOG_TABLES, INVENTORY_STATEMENTS, @@ -113,7 +115,7 @@ ) from domus.infrastructure.sqlite_tasks import SQLiteTasks -SCHEMA_VERSION = 34 +SCHEMA_VERSION = 35 APPLICATION_ID = 0x444F4D55 BASE_STATEMENTS = ( "CREATE TABLE installation(singleton INTEGER PRIMARY KEY CHECK(singleton=1), " @@ -203,6 +205,7 @@ SHOPPING_SESSION_STORE_STATEMENT, AUTOMATION_DRAFT_STATEMENT, AUTOMATION_CONTROL_STATEMENT, + BARCODE_STATEMENT, ) BASE_TABLES = {"installation", "households", "receipts", "audit", "outbox"} IDENTITY_TABLES = BASE_TABLES | {"members", "household_policy"} @@ -231,7 +234,8 @@ RETURN_SCHEMA_TABLES = CORRECTION_SCHEMA_TABLES | {SHOPPING_RECEIPT_RETURN_TABLE} LOCATION_SCHEMA_TABLES = RETURN_SCHEMA_TABLES | LOCATION_TABLES DRAFT_SCHEMA_TABLES = LOCATION_SCHEMA_TABLES | {AUTOMATION_DRAFT_TABLE} -TABLES = DRAFT_SCHEMA_TABLES | {AUTOMATION_CONTROL_TABLE} +CONTROL_SCHEMA_TABLES = DRAFT_SCHEMA_TABLES | {AUTOMATION_CONTROL_TABLE} +TABLES = CONTROL_SCHEMA_TABLES | {BARCODE_TABLE} def _schema(connection: sqlite3.Connection) -> tuple[tuple[str, str], ...]: @@ -280,6 +284,7 @@ def _expected_schema(version: int) -> tuple[tuple[str, str], ...]: *((SHOPPING_SESSION_STORE_STATEMENT,) if version >= 31 else ()), *((AUTOMATION_DRAFT_STATEMENT,) if version >= 32 else ()), *((AUTOMATION_CONTROL_STATEMENT,) if version >= 33 else ()), + *((BARCODE_STATEMENT,) if version >= 35 else ()), ) for statement in statements: connection.execute(statement) @@ -564,6 +569,8 @@ def _inspect( 30: LOCATION_SCHEMA_TABLES, 31: LOCATION_SCHEMA_TABLES, 32: DRAFT_SCHEMA_TABLES, + 33: CONTROL_SCHEMA_TABLES, + 34: CONTROL_SCHEMA_TABLES, }.get(version, TABLES) if application_id != APPLICATION_ID or objects != expected_tables: raise DatabaseRejected("unrelated_database") @@ -643,6 +650,7 @@ def initialize(self, *, require_existing: bool = False) -> None: *((SHOPPING_SESSION_STORE_STATEMENT,) if version < 31 else ()), *((AUTOMATION_DRAFT_STATEMENT,) if version < 32 else ()), *((AUTOMATION_CONTROL_STATEMENT,) if version < 33 else ()), + *((BARCODE_STATEMENT,) if version < 35 else ()), ) for statement in migration: connection.execute(statement) diff --git a/backend/src/domus/infrastructure/sqlite_inventory.py b/backend/src/domus/infrastructure/sqlite_inventory.py index fc36aa2..a35e529 100644 --- a/backend/src/domus/infrastructure/sqlite_inventory.py +++ b/backend/src/domus/infrastructure/sqlite_inventory.py @@ -10,6 +10,7 @@ MAX_NAMED_LOCATIONS, MAX_STOCK_UNITS, PANTRY, + BarcodeAssociation, BaseUnit, CatalogProduct, EffectKind, @@ -101,6 +102,16 @@ "REFERENCES inventory_materials(household_id,reference_id)) STRICT", ) +BARCODE_TABLE = "inventory_barcodes" +BARCODE_STATEMENT = ( + "CREATE TABLE inventory_barcodes(household_id TEXT NOT NULL, barcode TEXT NOT NULL " + "CHECK(length(barcode)=14 AND barcode NOT GLOB '*[^0-9]*'), " + "association_id TEXT NOT NULL, product_id TEXT NOT NULL, " + "PRIMARY KEY(household_id,barcode), UNIQUE(household_id,association_id), " + "FOREIGN KEY(household_id,product_id) " + "REFERENCES inventory_products(household_id,product_id)) STRICT" +) + REPLENISHMENT_STATEMENT = ( "CREATE TABLE inventory_replenishment(household_id TEXT NOT NULL, product_id TEXT NOT NULL, " f"minimum INTEGER NOT NULL CHECK(minimum BETWEEN 0 AND {MAX_STOCK_UNITS}), " @@ -198,6 +209,28 @@ def _movement(row: sqlite3.Row) -> StockMovement: class SQLiteInventory: connection: sqlite3.Connection + def barcode(self, home: str, barcode: str) -> BarcodeAssociation | None: + row = self.connection.execute( + "SELECT barcode,association_id,product_id FROM inventory_barcodes " + "WHERE household_id=? AND barcode=?", + (home, barcode), + ).fetchone() + return None if row is None else BarcodeAssociation(*row) + + def link_barcode(self, home: str, value: BarcodeAssociation) -> None: + self.connection.execute( + "INSERT INTO inventory_barcodes VALUES (?,?,?,?)", (home, *astuple(value)) + ) + + def remove_barcode(self, home: str, value: BarcodeAssociation) -> None: + removed = self.connection.execute( + "DELETE FROM inventory_barcodes WHERE household_id=? AND barcode=? " + "AND association_id=? AND product_id=?", + (home, *astuple(value)), + ) + if removed.rowcount != 1: + raise Conflict("inventory_barcode_changed") + def add_product(self, home: str, product: CatalogProduct) -> None: self.connection.execute( "INSERT INTO inventory_products VALUES (?,?,?,?,?)", (home, *astuple(product)) @@ -506,6 +539,13 @@ def verify_inventory_catalog(connection: sqlite3.Connection) -> None: raise StorageFailure("invalid_inventory_catalog_binding") +def verify_inventory_barcodes(connection: sqlite3.Connection) -> None: + for row in connection.execute( + "SELECT barcode,association_id,product_id FROM inventory_barcodes" + ): + BarcodeAssociation(*row) + + def verify_replenishment(connection: sqlite3.Connection) -> None: for minimum, target in connection.execute( "SELECT r.minimum,r.target FROM inventory_replenishment AS r " diff --git a/backend/src/domus/infrastructure/sqlite_snapshots.py b/backend/src/domus/infrastructure/sqlite_snapshots.py index ed20932..8ac28f3 100644 --- a/backend/src/domus/infrastructure/sqlite_snapshots.py +++ b/backend/src/domus/infrastructure/sqlite_snapshots.py @@ -44,6 +44,7 @@ verify_history, ) from domus.infrastructure.sqlite_inventory import ( + verify_inventory_barcodes, verify_inventory_catalog, verify_inventory_locations, verify_inventory_records, @@ -232,6 +233,8 @@ def _records(connection: sqlite3.Connection, version: int, installation: Install verify_automation_drafts(connection, allow_daily=version >= 34) if version >= 33: verify_automation_controls(connection) + if version >= 35: + verify_inventory_barcodes(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 907fc92..1e2bbce 100644 --- a/docs/contracts/household-api.openapi.json +++ b/docs/contracts/household-api.openapi.json @@ -1066,6 +1066,69 @@ "title": "AutomationSimulation", "type": "object" }, + "BarcodeAssociation": { + "properties": { + "association_id": { + "title": "Association Id", + "type": "string" + }, + "barcode": { + "title": "Barcode", + "type": "string" + }, + "product_id": { + "title": "Product Id", + "type": "string" + } + }, + "required": [ + "barcode", + "association_id", + "product_id" + ], + "title": "BarcodeAssociation", + "type": "object" + }, + "BarcodeLookup": { + "properties": { + "association": { + "anyOf": [ + { + "$ref": "#/components/schemas/BarcodeAssociation" + }, + { + "type": "null" + } + ] + }, + "barcode": { + "title": "Barcode", + "type": "string" + }, + "may_manage": { + "title": "May Manage", + "type": "boolean" + }, + "product": { + "anyOf": [ + { + "$ref": "#/components/schemas/CatalogProduct" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "barcode", + "may_manage", + "association", + "product" + ], + "title": "BarcodeLookup", + "type": "object" + }, "BaseUnit": { "enum": [ "piece", @@ -1438,6 +1501,8 @@ "CatalogAction": { "enum": [ "inventory.register-product", + "inventory.link-barcode", + "inventory.remove-barcode", "inventory.add-location", "inventory.transfer", "inventory.intake", @@ -1458,6 +1523,33 @@ "title": "CatalogAction", "type": "string" }, + "CatalogProduct": { + "properties": { + "base_unit": { + "$ref": "#/components/schemas/BaseUnit" + }, + "name": { + "title": "Name", + "type": "string" + }, + "product_id": { + "title": "Product Id", + "type": "string" + }, + "reference_id": { + "title": "Reference Id", + "type": "string" + } + }, + "required": [ + "product_id", + "reference_id", + "name", + "base_unit" + ], + "title": "CatalogProduct", + "type": "object" + }, "CatalogReward": { "properties": { "eligible": { @@ -3849,6 +3941,35 @@ } ] }, + "LinkBarcodeBody": { + "additionalProperties": false, + "properties": { + "action": { + "const": "inventory.link-barcode", + "title": "Action", + "type": "string" + }, + "barcode": { + "maxLength": 14, + "minLength": 8, + "pattern": "^[0-9]+$", + "title": "Barcode", + "type": "string" + }, + "product_id": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Product Id", + "type": "string" + } + }, + "required": [ + "action", + "barcode", + "product_id" + ], + "title": "LinkBarcodeBody", + "type": "object" + }, "LocationBody": { "additionalProperties": false, "properties": { @@ -6539,6 +6660,41 @@ "title": "RelativeTaskBody", "type": "object" }, + "RemoveBarcodeBody": { + "additionalProperties": false, + "properties": { + "action": { + "const": "inventory.remove-barcode", + "title": "Action", + "type": "string" + }, + "association_id": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Association Id", + "type": "string" + }, + "barcode": { + "maxLength": 14, + "minLength": 8, + "pattern": "^[0-9]+$", + "title": "Barcode", + "type": "string" + }, + "product_id": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Product Id", + "type": "string" + } + }, + "required": [ + "action", + "barcode", + "product_id", + "association_id" + ], + "title": "RemoveBarcodeBody", + "type": "object" + }, "RenameCategoryBody": { "additionalProperties": false, "properties": { @@ -16830,6 +16986,162 @@ "summary": "Catalog" } }, + "/api/v1/inventory/barcode": { + "get": { + "operationId": "barcode_api_v1_inventory_barcode_get", + "parameters": [ + { + "in": "query", + "name": "barcode", + "required": true, + "schema": { + "maxLength": 14, + "minLength": 8, + "pattern": "^[0-9]+$", + "title": "Barcode", + "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/BarcodeLookup" + } + } + }, + "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": "Barcode" + } + }, "/api/v1/inventory/commands": { "post": { "operationId": "command_api_v1_inventory_commands_post", @@ -16879,7 +17191,9 @@ "inventory.configure-replenishment": "#/components/schemas/ReplenishmentBody", "inventory.correct-intake": "#/components/schemas/IntakeCorrectionBody", "inventory.intake": "#/components/schemas/IntakeBody", + "inventory.link-barcode": "#/components/schemas/LinkBarcodeBody", "inventory.register-product": "#/components/schemas/ProductBody", + "inventory.remove-barcode": "#/components/schemas/RemoveBarcodeBody", "inventory.transfer": "#/components/schemas/TransferBody", "shopping.add-extra": "#/components/schemas/AddExtraBody", "shopping.cancel-balance": "#/components/schemas/CancelPurchaseBalanceBody", @@ -16898,6 +17212,12 @@ { "$ref": "#/components/schemas/ProductBody" }, + { + "$ref": "#/components/schemas/LinkBarcodeBody" + }, + { + "$ref": "#/components/schemas/RemoveBarcodeBody" + }, { "$ref": "#/components/schemas/LocationBody" }, diff --git a/docs/contracts/native-household-api.openapi.json b/docs/contracts/native-household-api.openapi.json index 7ad5661..6e7f85d 100644 --- a/docs/contracts/native-household-api.openapi.json +++ b/docs/contracts/native-household-api.openapi.json @@ -1066,6 +1066,69 @@ "title": "AutomationSimulation", "type": "object" }, + "BarcodeAssociation": { + "properties": { + "association_id": { + "title": "Association Id", + "type": "string" + }, + "barcode": { + "title": "Barcode", + "type": "string" + }, + "product_id": { + "title": "Product Id", + "type": "string" + } + }, + "required": [ + "barcode", + "association_id", + "product_id" + ], + "title": "BarcodeAssociation", + "type": "object" + }, + "BarcodeLookup": { + "properties": { + "association": { + "anyOf": [ + { + "$ref": "#/components/schemas/BarcodeAssociation" + }, + { + "type": "null" + } + ] + }, + "barcode": { + "title": "Barcode", + "type": "string" + }, + "may_manage": { + "title": "May Manage", + "type": "boolean" + }, + "product": { + "anyOf": [ + { + "$ref": "#/components/schemas/CatalogProduct" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "barcode", + "may_manage", + "association", + "product" + ], + "title": "BarcodeLookup", + "type": "object" + }, "BaseUnit": { "enum": [ "piece", @@ -1438,6 +1501,8 @@ "CatalogAction": { "enum": [ "inventory.register-product", + "inventory.link-barcode", + "inventory.remove-barcode", "inventory.add-location", "inventory.transfer", "inventory.intake", @@ -1458,6 +1523,33 @@ "title": "CatalogAction", "type": "string" }, + "CatalogProduct": { + "properties": { + "base_unit": { + "$ref": "#/components/schemas/BaseUnit" + }, + "name": { + "title": "Name", + "type": "string" + }, + "product_id": { + "title": "Product Id", + "type": "string" + }, + "reference_id": { + "title": "Reference Id", + "type": "string" + } + }, + "required": [ + "product_id", + "reference_id", + "name", + "base_unit" + ], + "title": "CatalogProduct", + "type": "object" + }, "CatalogReward": { "properties": { "eligible": { @@ -3843,6 +3935,35 @@ } ] }, + "LinkBarcodeBody": { + "additionalProperties": false, + "properties": { + "action": { + "const": "inventory.link-barcode", + "title": "Action", + "type": "string" + }, + "barcode": { + "maxLength": 14, + "minLength": 8, + "pattern": "^[0-9]+$", + "title": "Barcode", + "type": "string" + }, + "product_id": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Product Id", + "type": "string" + } + }, + "required": [ + "action", + "barcode", + "product_id" + ], + "title": "LinkBarcodeBody", + "type": "object" + }, "LocationBody": { "additionalProperties": false, "properties": { @@ -6560,6 +6681,41 @@ "title": "RelativeTaskBody", "type": "object" }, + "RemoveBarcodeBody": { + "additionalProperties": false, + "properties": { + "action": { + "const": "inventory.remove-barcode", + "title": "Action", + "type": "string" + }, + "association_id": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Association Id", + "type": "string" + }, + "barcode": { + "maxLength": 14, + "minLength": 8, + "pattern": "^[0-9]+$", + "title": "Barcode", + "type": "string" + }, + "product_id": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Product Id", + "type": "string" + } + }, + "required": [ + "action", + "barcode", + "product_id", + "association_id" + ], + "title": "RemoveBarcodeBody", + "type": "object" + }, "RenameCategoryBody": { "additionalProperties": false, "properties": { @@ -16318,6 +16474,162 @@ "summary": "Catalog" } }, + "/api/v1/inventory/barcode": { + "get": { + "operationId": "barcode_api_v1_inventory_barcode_get", + "parameters": [ + { + "in": "query", + "name": "barcode", + "required": true, + "schema": { + "maxLength": 14, + "minLength": 8, + "pattern": "^[0-9]+$", + "title": "Barcode", + "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/BarcodeLookup" + } + } + }, + "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": "Barcode" + } + }, "/api/v1/inventory/commands": { "post": { "operationId": "command_api_v1_inventory_commands_post", @@ -16367,7 +16679,9 @@ "inventory.configure-replenishment": "#/components/schemas/ReplenishmentBody", "inventory.correct-intake": "#/components/schemas/IntakeCorrectionBody", "inventory.intake": "#/components/schemas/IntakeBody", + "inventory.link-barcode": "#/components/schemas/LinkBarcodeBody", "inventory.register-product": "#/components/schemas/ProductBody", + "inventory.remove-barcode": "#/components/schemas/RemoveBarcodeBody", "inventory.transfer": "#/components/schemas/TransferBody", "shopping.add-extra": "#/components/schemas/AddExtraBody", "shopping.cancel-balance": "#/components/schemas/CancelPurchaseBalanceBody", @@ -16386,6 +16700,12 @@ { "$ref": "#/components/schemas/ProductBody" }, + { + "$ref": "#/components/schemas/LinkBarcodeBody" + }, + { + "$ref": "#/components/schemas/RemoveBarcodeBody" + }, { "$ref": "#/components/schemas/LocationBody" }, diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md new file mode 100644 index 0000000..c7cb271 --- /dev/null +++ b/docs/evidence/local-barcode-qualification.md @@ -0,0 +1,46 @@ +# Local barcode qualification + +Issue #91 adds manual product lookup and reviewed local associations in Inventory. +The selected companion defines five requirements and eight acceptance cases. +[Local barcode specification](../../specs/stock-local-barcode.md) + +Printed ASCII GTIN-8, GTIN-12, GTIN-13 and GTIN-14 values retain leading zeroes. +Validation checks the original length and GS1 check digit before zero-padding the +identity to 14 characters. The household and canonical code identify one current +association. Every link receives a fresh association ID. Removal matches that +reviewed identity, including when a later link selects the same product. + +Inventory uses the shared ha-ui numeric text field, cards, buttons and feedback +from the exact published version `0.1.0-next.3`. +The field preserves malformed input for correction. An unlinked result leads to +the existing paginated Pantry cards. A manager chooses a product, reviews its name +and code, then separately confirms. A found product opens its existing stock +detail. An unavailable read retains the draft and offers an explicit retry. + +Association writes use the existing atomic commands, journal, original receipts, +current grants, CSRF and origin checks. A lost successful response recovers its +original operation. Rejected stale removal refreshes the current match and retires +the old confirmation. Scope changes retire private facts and drafts. + +| Published case | Executable evidence | +| --- | --- | +| stock-local-barcode-C01 | Domain and client tests validate all four lengths, original shape, check digits and equivalent canonical forms. [Backend cases](../../tests/backend/test_inventory_barcodes.py), [client cases](../../frontend/tests/inventory.test.ts) | +| stock-local-barcode-C02 | Exact current-household queries distinguish found and unlinked codes. Compiled journeys abort external requests and complete both local flows. [HTTP cases](../../tests/backend/test_inventory_barcode_http.py), [compiled journeys](../../frontend/tests/e2e/workspace-navigation.spec.ts) | +| stock-local-barcode-C03 | Both HTTP compositions check current readers, management grants, foreign households and original receipt authority. Component tests retire management controls after current grants change. [HTTP cases](../../tests/backend/test_inventory_barcode_http.py), [component cases](../../frontend/tests/inventory.test.ts) | +| stock-local-barcode-C04 | Two real SQLite writers race equivalent forms for different products. One wins. Stale removal preserves a replacement association, including a new link to the same product. Two browser tabs verify conflict recovery after reassignment to another product. [SQLite cases](../../tests/backend/test_inventory_barcodes.py), [compiled journeys](../../frontend/tests/e2e/workspace-navigation.spec.ts) | +| stock-local-barcode-C05 | Original replay preserves the operation and rejects a changed payload. Late receipt failure rolls back association changes. Compiled journeys commit a link, lose its response, reload and recover the same original request. [SQLite cases](../../tests/backend/test_inventory_barcodes.py), [compiled journeys](../../frontend/tests/e2e/workspace-navigation.spec.ts) | +| stock-local-barcode-C06 | Schema 34, 30 and 20 data survive migration to 35. Invalid migration SQL leaves source bytes unchanged. Checkpoint activation preserves the link and its original receipt. Snapshot validation rejects corrupted barcode and association identities. [Migration and restoration cases](../../tests/backend/test_inventory_barcodes.py) | +| stock-local-barcode-C07 | Ingress and standalone journeys exercise English desktop keyboard, Spanish 390 px touch, light and dark themes, focus, malformed input, selection, confirmation, current conflicts and explicit read retry. [Compiled journeys](../../frontend/tests/e2e/workspace-navigation.spec.ts) | +| stock-local-barcode-C08 | The immutable Edge candidate requires both CPU image campaigns and installed-owner acceptance. The increment's pull request records their measured source identities and outcomes. | + +The complete backend campaign passes 5,569 tests with 100% statement and branch +coverage globally and across all 231 authored modules. An independent source +coverage audit accepts the report. The complete frontend campaign passes 1,927 +tests with all four metrics at 100% globally and per authored runtime file. +All 121 compiled source journeys and 45 rebuilt catalog journeys pass, with zero +skipped, unexpected or flaky results. The CPU image gate requires all 66 household +journeys on each architecture, including the two new barcode journeys. + +SQLite schema 35 adds the local association index. Keep the previous compatible +image together with its cold schema-34 state for rollback. Compatible schema-35 +restoration retains current associations and original historical evidence. diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json index 5e8a8fd..d1c4029 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 protected manual automation preview, saved revisions, explicit runs and scoped run history, daily schedule previews and inactive daily drafts, 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. Points-allocation cards inherit the shared raised surface in both color schemes. The Tasks workspace supports planned task assignment, state-permitted release, retained conflict selections and original assignment-request recovery. The Tasks workspace also confirms Start, Block and Unblock, retains a bounded blocking reason through explicit current-task review and recovers the original progress request.", + "scope": "Compiled household workspace with protected manual automation preview, saved revisions, explicit runs and scoped run history, daily schedule previews and inactive daily drafts, 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. Points-allocation cards inherit the shared raised surface in both color schemes. The Tasks workspace supports planned task assignment, state-permitted release, retained conflict selections and original assignment-request recovery. The Tasks workspace also confirms Start, Block and Unblock, retains a bounded blocking reason through explicit current-task review and recovers the original progress request. Inventory supports manually entered local GTIN lookup, explicit product association and removal review, stale-association recovery and retained original barcode requests.", "actualProductFiles": { - ".vite/manifest.json": "5cc6cb5d72390640c8e281eba20c9ff8c782c7f5c6e103ff39a6257fde28b74b", + ".vite/manifest.json": "20fb5f3930922339ac18f422befcad26d39a3e48168ae034bdd075c858d933a8", + "assets/index-CNI5WB-O.js": "b394b8038910cc30dfc0b92a864641bad49d25edaa8392273fc0a91951950c28", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "assets/index-lAPOs-kN.js": "1696cc56f023da1760f9147d175e64caa65baa08be89024a85761776b88b38ff", - "index.html": "c9110bf2ef5b3294a64e67513f27b7f5baee3a999344590d479c5b15ff95ac33" + "index.html": "d4bd63a737c246f3511c31685acdd1e1ec0e012ed82f3c1ac42878d52159c7ef" }, "localValidation": { "commit": "9a10d8114869be754962953903e773fe8e12c723", diff --git a/docs/household-api.md b/docs/household-api.md index 071d607..7d888d5 100644 --- a/docs/household-api.md +++ b/docs/household-api.md @@ -142,8 +142,7 @@ authority in the same read transaction; an old service instance is not a permiss Every write requires one `Origin` matching the configured public origin, one session-bound `X-CSRF-Token`, and one `Idempotency-Key`. Obtain CSRF from `/api/v1/auth/csrf`. Keys are 1–128 characters, start with an ASCII letter/digit and otherwise use letters/digits, underscore, dot, -colon or hyphen. Missing, duplicate and malformed keys are rejected. Every body includes the expected -revision. Invalid types, unknown fields and protected permission overrides are rejected. +colon or hyphen. Missing, duplicate and malformed keys are rejected. Revisioned commands include their reviewed concurrency precondition. Invalid types, unknown fields and protected permission overrides are rejected. Bodies must be UTF-8 JSON objects with `application/json` (optionally `charset=utf-8`). Duplicate JSON keys, nonfinite values, malformed encoding and excessive nesting cannot be silently normalized into a @@ -177,6 +176,70 @@ both synthetic fixtures and real offline activations in both HTTP compositions. console exposes restore preparation/activation/resume; local Edge.3 image cases pass. Complete deployment and live acceptance remain pending. +## Manual local barcode lookup + +Inventory accepts manually entered ASCII GTIN-8, GTIN-12, GTIN-13 and GTIN-14 +numbers under the [local barcode companion](../specs/stock-local-barcode.md). +Validate the original length and GS1 check digit before padding the identity to +14 characters. Preserve leading zeroes. GTIN-8 uses its printed GS1 identity. +Queries and association commands resolve that canonical key within the verified +current household. + +| Route or action | Result | Current authority | +|---|---|---| +| `GET /api/v1/inventory/barcode?barcode=036000291452` | Canonical barcode, management hint and nullable association/product | Household read | +| `inventory.link-barcode` through `POST /api/v1/inventory/commands` | Canonical barcode, association ID and product ID | Inventory management | +| `inventory.remove-barcode` through the same command route | Original removed association | Inventory management | +| `GET /api/v1/inventory/requests/{action}/{key}` | Original own command receipt | Original action's current authority | + +A valid unlinked query succeeds with both `association` and `product` set to +`null`. A found result includes the stable catalog product ID, reference ID, +name and base unit, together with the association's own ID. Invalid text returns +422. A service, storage or reachability failure is an unavailable read. The +browser retains the entered text, retires previous match facts and offers an +explicit read retry. Requests remain installation-local, including when external +internet connectivity is absent. + +A link body contains `action`, `barcode` and `product_id`. Its product must belong +to the current household. One canonical code can identify one product in that +household. Competing links serialize through the existing atomic writer and +household/code uniqueness constraint. An occupied code returns +`inventory_barcode_linked`. The manager reviews and removes its current +association before linking the code again. + +A removal body additionally contains `association_id` from the reviewed lookup. +The write matches the household, canonical code, product and exact association +ID. Every successful link receives a fresh association ID, including a link back +to the same product. A stale removal returns `inventory_barcode_changed` and +preserves the later association. The browser refreshes the current match for +another deliberate review. + +Both writes use the existing origin, CSRF, idempotency, audit and outbox boundary. +The canonical command payload binds the barcode and product, plus the reviewed +association ID for removal. An equivalent printed form uses the same canonical +payload. A lost successful reply can recover the original receipt. Current +management authority is checked again for receipt access. Association changes +and their receipts commit atomically, and a late failure rolls back both. +Product IDs, quantities, reservations and movement history retain their domain +identities. + +SQLite schema 35 adds an initially empty local association index. Upgrade +qualification includes representative schema 34, 30 and 20 inventory. Compatible +checkpoint activation preserves the index and its original receipts. Historical +receipts retain the existing restoration warning, and current queries establish +the association visible after restoration. + +The regression inventory maps `stock-local-barcode-C01` through +`stock-local-barcode-C06` to the domain, HTTP and real SQLite migration, +contention, rollback and activation cases in +[`test_inventory_barcodes.py`](../tests/backend/test_inventory_barcodes.py) and +[`test_inventory_barcode_http.py`](../tests/backend/test_inventory_barcode_http.py). +Client command validation, protected response binding, journal replay, read retry +and scope retirement are covered in +[`inventory.test.ts`](../frontend/tests/inventory.test.ts) and the normal +[`page composition`](../frontend/tests/page.test.ts). Browser and installed +acceptance follow `stock-local-barcode-C07` and `stock-local-barcode-C08`. + ## HA availability and remaining deployment work Reads may use the original unexpired lease during a bounded HA availability failure; current local diff --git a/docs/user-guide.md b/docs/user-guide.md index 5139c6a..8e25dc6 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -132,6 +132,28 @@ key prevents a second stock entry, including after reload. A historical receipt can be viewed after restoring a backup. Check the current recorded stock before making another request. +### Find a product by its printed barcode + +In **Inventory**, enter the digits below the barcode and choose **Find product**. +Keep leading zeroes. Supported numbers have 8, 12, 13 or 14 digits and a valid +check digit. A match offers **Open product stock**. The lookup uses your current +household's local catalog and works with external internet access unavailable. + +For an unlinked code, an inventory manager chooses a product from the Pantry +cards below. Use **Show more products** as needed. Choose **Associate barcode +with** that product, review its name and barcode, then choose **Confirm barcode +association**. Register the product first if it is absent from the catalog. + +To change an association, choose **Remove barcode association**, review and +confirm the removal, then choose the replacement product. If someone changes +the association first, review the refreshed match before confirming again. +Use **Retry barcode lookup** after an unavailable read. The entered digits stay +in the field. A lost write response offers **Recover original request**, including +after reloading the same tab. + +In Spanish, the main controls are **Buscar producto**, **Asociar código a**, +**Confirmar asociación del código** and **Reintentar búsqueda del código**. + ### Movement history and corrections Choose **Show movement history** on a product. Each entry shows its signed diff --git a/frontend/package.json b/frontend/package.json index 88d214c..a54899c 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -13,7 +13,7 @@ "browser:entry": "playwright test -c playwright.entry.config.ts" }, "dependencies": { - "@vypdev/ha-ui": "0.1.0-next.2", + "@vypdev/ha-ui": "0.1.0-next.3", "lit": "3.3.3" }, "devDependencies": { diff --git a/frontend/src/adapters/inventory-http.ts b/frontend/src/adapters/inventory-http.ts index 5222edd..50fcf81 100644 --- a/frontend/src/adapters/inventory-http.ts +++ b/frontend/src/adapters/inventory-http.ts @@ -3,8 +3,8 @@ import {INVENTORY_ERRORS} from '../application/inventory-controller'; import type {InventoryError, InventoryRequest, InventoryResult, InventoryScope, InventoryServer} from '../application/inventory-controller'; import type {ShoppingAttention} from '../application/shopping-attention'; import type {StockAttention} from '../application/stock-attention'; -import {BASE_UNITS, MAX_LOCATION_NAME, MAX_NAMED_LOCATIONS, MAX_SESSION_ITEMS, MIN_SESSION_ITEMS, MOVEMENT_KINDS, SHOPPING_SOURCE_KINDS, STOCK_REASON_LIMIT, inventoryCommand, positiveQuantity, purchaseStoreName, replenishmentRevision, shoppingItemKey, signedQuantity, stockUnits} from '../domain/inventory'; -import type {BaseUnit, InventoryCommand, InventoryReport, LocationStock, MovementHistory, ProductStock, Purchase, PurchaseCancellation, Purchases, PurchaseReceipts, PurchaseSession, PurchaseSessionDetail, PurchaseSessions, Replenishment, ShoppingItem, ShoppingList, ShoppingSource, ShoppingSources, StockMovement, StockTotals, StockTransfer, StorageLocation} from '../domain/inventory'; +import {BASE_UNITS, MAX_LOCATION_NAME, MAX_NAMED_LOCATIONS, MAX_SESSION_ITEMS, MIN_SESSION_ITEMS, MOVEMENT_KINDS, SHOPPING_SOURCE_KINDS, STOCK_REASON_LIMIT, canonicalGtin, inventoryCommand, positiveQuantity, purchaseStoreName, replenishmentRevision, shoppingItemKey, signedQuantity, stockUnits} from '../domain/inventory'; +import type {BarcodeLookup, BaseUnit, InventoryCommand, InventoryReport, LocationStock, MovementHistory, ProductStock, Purchase, PurchaseCancellation, Purchases, PurchaseReceipts, PurchaseSession, PurchaseSessionDetail, PurchaseSessions, Replenishment, ShoppingItem, ShoppingList, ShoppingSource, ShoppingSources, StockMovement, StockTotals, StockTransfer, StorageLocation} from '../domain/inventory'; import type {JournalContext} from '../domain/journal'; import {revisionValue} from '../domain/administration'; import {taskQuantity, taskTime} from '../domain/tasks'; @@ -16,6 +16,24 @@ import {boolean, check, choice, fields, identifier, integer, text} from './json- const BASE = 'inventory'; +function barcodeLookup(value: unknown, barcode: string): BarcodeLookup { + const row = fields(value, ['barcode', 'may_manage', 'association', 'product'], []); + check(row.barcode === barcode); + const mayManage = boolean(row.may_manage); + if (row.association === null) { + check(row.product === null); + return {barcode, mayManage, product: null}; + } + const association = fields(row.association, ['barcode', 'association_id', 'product_id'], []); + const product = fields(row.product, ['product_id', 'reference_id', 'name', 'base_unit'], []); + check(association.barcode === barcode && product.product_id === association.product_id); + return {barcode, mayManage, product: { + id: identifier(product.product_id), referenceId: identifier(product.reference_id), + associationId: identifier(association.association_id), name: text(product.name, 160), + unit: choice(product.base_unit, BASE_UNITS), + }}; +} + function replenishment(value: unknown, id: string, unit: ProductStock['unit'], available: string): Replenishment { const row = fields(value, ['source_id','minimum','target','revision','needed'], []); const minimum = taskQuantity(row.minimum), target = taskQuantity(row.target), needed = taskQuantity(row.needed); @@ -326,6 +344,14 @@ function receipt(value: unknown, command: InventoryCommand): InventoryResult { if (row.archived_by !== null || kind === 'historical') identifier(row.archived_by); const operationId = identifier(row.operation_id); integer(row.created_at, 0); + if (command.action === 'inventory.link-barcode' || command.action === 'inventory.remove-barcode') { + const result = fields(row.result, ['barcode', 'association_id', 'product_id'], []); + const associationId = identifier(result.association_id); + check(result.barcode === command.barcode && result.product_id === command.product_id); + if (command.action === 'inventory.remove-barcode') check(associationId === command.association_id); + return {kind, operationId, productId: command.product_id, movement: null, + barcodeSaved: {barcode: command.barcode, linked: command.action === 'inventory.link-barcode'}}; + } if (command.action === 'inventory.register-product') { const result = fields(row.result, ['product_id','name','base_unit'], []); check(result.name === command.name && result.base_unit === command.base_unit); @@ -427,6 +453,14 @@ export class HttpInventoryServer implements InventoryServer { private readonly network: BoundedHTTP; constructor(target: EntryEndpoint, transport: FetchTransport) {this.network = new BoundedHTTP(target, transport);} + barcode(scope: InventoryScope, value: string) { + const barcode = canonicalGtin(value); + return this.network.owned(async signal => { + const query = new URLSearchParams({barcode}); + return barcodeLookup(await this.network.get(BASE + '/barcode?' + query, scope.context, signal), barcode); + }); + } + stockAttention(context: JournalContext) { return this.network.owned(async signal => stockAttention(await this.network.get(BASE + '/stock-attention', context, signal))); } diff --git a/frontend/src/application/inventory-controller.ts b/frontend/src/application/inventory-controller.ts index f5a033f..e2c250d 100644 --- a/frontend/src/application/inventory-controller.ts +++ b/frontend/src/application/inventory-controller.ts @@ -1,10 +1,11 @@ /** Manage only current household scope and the original unresolved stock command. */ -import {inventoryCommand, shoppingItemKey} from '../domain/inventory'; -import type {BaseUnit, InventoryCommand, InventoryReport, MovementHistory, PurchaseReceipts, Purchases, PurchaseSessionDetail, PurchaseSessions, ShoppingAction, ShoppingList, ShoppingSources} from '../domain/inventory'; +import {canonicalGtin, inventoryCommand, shoppingItemKey} from '../domain/inventory'; +import type {BarcodeLookup, BaseUnit, InventoryCommand, InventoryReport, MovementHistory, PurchaseReceipts, Purchases, PurchaseSessionDetail, PurchaseSessions, ShoppingAction, ShoppingList, ShoppingSources} from '../domain/inventory'; import type {JournalContext} from '../domain/journal'; import type {EntryEntropy, EntryRead} from './ports'; export const INVENTORY_ERRORS = ['permission_denied', 'idempotency_conflict', 'invalid_request', + 'invalid_inventory_barcode', 'inventory_barcode_linked', 'inventory_barcode_changed', 'invalid_inventory_location_name', 'inventory_location_exists', 'inventory_location_limit', 'inventory_location_missing', 'inventory_same_location', 'invalid_task_text', 'invalid_inventory_unit', 'invalid_inventory_receipt', 'invalid_material_quantity', @@ -31,12 +32,14 @@ export type InventoryResult = Readonly<{ kind: 'committed' | 'historical'; operationId: string; productId: string | null; replenishmentSaved?: true; locationSaved?: true; + barcodeSaved?: Readonly<{barcode: string; linked: boolean}>; shoppingAction?: ShoppingAction; sessionId?: string; movement: Readonly<{movementId: string; quantity: string; unit: BaseUnit; action: 'inventory.intake' | 'inventory.adjust' | 'inventory.correct-intake' | 'inventory.transfer'}> | null; }> | Readonly<{kind: 'rejected'; reason: InventoryError; command: InventoryCommand}>; export interface InventoryServer { + barcode(scope: InventoryScope, value: string): EntryRead; read(scope: InventoryScope, cursor: string | null): EntryRead; history(scope: InventoryScope, productId: string, cursor: string | null): EntryRead; purchases(scope: InventoryScope, cursor: string | null): EntryRead; @@ -57,6 +60,7 @@ export interface InventoryState { readonly scope: InventoryScope; readonly report: InventoryReport | null; readonly history: MovementHistory | null; + readonly barcode?: Readonly<{code: string; lookup: BarcodeLookup | null; unavailable: boolean}> | null; readonly purchases?: Purchases | null; readonly purchaseReceipts?: PurchaseReceipts | null; readonly purchaseSessions?: PurchaseSessions | null; @@ -123,6 +127,21 @@ export class InventoryController { } if (state?.shoppingSources && this.view?.scope === state.scope && this.view.shoppingSources) await this.showShoppingSources(state.shoppingSources.item.productId!); + if (state?.barcode && this.view?.scope === state.scope && this.view.report) + await this.showBarcode(state.barcode.code); + } + + async showBarcode(value: string): Promise { + const state = this.view; + if (state === null || state.report === null || this.owned !== null) return; + let code: string; + try {code = canonicalGtin(value);} catch {return;} + this.set({barcode: {code, lookup: null, unavailable: false}}); + const loaded = await this.run(this.server.barcode(state.scope, code), lookup => { + this.set({barcode: {code, lookup, unavailable: false}}); + }, state.pending ? state.notice : null); + if (!loaded && this.view?.scope === state.scope) + this.set({barcode: {code, lookup: null, unavailable: true}}); } async showHistory(productId: string): Promise {await this.loadHistory(productId, null);} @@ -278,7 +297,7 @@ export class InventoryController { }, 'unavailable'); if (!loaded && this.view?.scope === state.scope) this.set({report:null, history:null, purchases:null, purchaseReceipts:null, - shoppingList:null, shoppingSources:null, purchaseSessions:null, purchaseSession:null}); + shoppingList:null, shoppingSources:null, purchaseSessions:null, purchaseSession:null, barcode:null}); } private async loadPurchases(cursor: string | null): Promise { @@ -320,10 +339,12 @@ export class InventoryController { this.journal.clear(request); this.request = null; this.set({pending: false, notice: null, result}); + if ('barcode' in request.command) + this.set({barcode: {code: request.command.barcode, lookup: null, unavailable: false}}); } private async run(owned: EntryRead, use: (value: T) => void, - notice: 'unavailable' | 'uncertain'): Promise { + notice: 'unavailable' | 'uncertain' | null): Promise { this.owned = owned; this.set({busy: true}); try { diff --git a/frontend/src/composition/entry-page.ts b/frontend/src/composition/entry-page.ts index 266bab8..5e48e0f 100644 --- a/frontend/src/composition/entry-page.ts +++ b/frontend/src/composition/entry-page.ts @@ -23,7 +23,7 @@ import type {ShoppingAttention} from '../application/shopping-attention'; import {HttpInventoryServer} from '../adapters/inventory-http'; import {INVENTORY_JOURNAL_KEY, InventorySessionJournal} from '../adapters/inventory-journal'; import {InventoryController} from '../application/inventory-controller'; -import {inventoryCommand} from '../domain/inventory'; +import {canonicalGtin, inventoryCommand} from '../domain/inventory'; import type {InventoryIntent} from '../presentation/domus-inventory'; import {HttpRewardsServer} from '../adapters/reward-http'; import {REWARD_JOURNAL_KEY, RewardsSessionJournal} from '../adapters/reward-journal'; @@ -219,7 +219,8 @@ export function decodeReviewIntent(value: unknown): ReviewIntent | null { export function decodeInventoryIntent(value: unknown): InventoryIntent | null { try { - const {type} = fields(value, ['type'], ['command', 'productId', 'purchaseId', 'sessionId']); + const {type} = fields(value, ['type'], ['command', 'productId', 'purchaseId', 'sessionId', 'barcode']); + if (type === 'barcode') return {type, barcode:canonicalGtin(fields(value, ['type','barcode'], []).barcode)}; if (type === 'submit') return {type, command: inventoryCommand(fields(value, ['type','command'], []).command)}; if (type === 'history' || type === 'shopping-sources') return {type, productId: identifier(fields(value, ['type','productId'], []).productId)}; if (type === 'purchase-receipts') return {type, purchaseId: identifier(fields(value, ['type','purchaseId'], []).purchaseId)}; @@ -445,6 +446,7 @@ export function mountEntry(page: EntryPage): PageMount { if (intent?.type === 'refresh') await inventoryController.refresh(); if (intent?.type === 'more') await inventoryController.more(); if (intent?.type === 'recover') await inventoryController.recover(); + if (intent?.type === 'barcode') await inventoryController.showBarcode(intent.barcode); if (intent?.type === 'history') await inventoryController.showHistory(intent.productId); if (intent?.type === 'more-history') await inventoryController.moreHistory(); if (intent?.type === 'close-history') inventoryController.closeHistory(); diff --git a/frontend/src/domain/inventory.ts b/frontend/src/domain/inventory.ts index ad2774d..c99c7b8 100644 --- a/frontend/src/domain/inventory.ts +++ b/frontend/src/domain/inventory.ts @@ -15,6 +15,28 @@ export const MAX_PURCHASE_STORE_NAME = 160; export const MAX_LOCATION_NAME = 80; export const MAX_NAMED_LOCATIONS = 32; +export function canonicalGtin(value: unknown): string { + if (typeof value !== 'string' || ![8, 12, 13, 14].includes(value.length) || /[^0-9]/u.test(value)) + throw new Error('invalid_inventory_barcode'); + let total = Number(value[value.length - 1]); + for (const [index, digit] of [...value.slice(0, -1)].reverse().entries()) + total += Number(digit) * (index % 2 === 0 ? 3 : 1); + if (total % 10 !== 0) throw new Error('invalid_inventory_barcode'); + return value.padStart(14, '0'); +} + +export interface BarcodeLookup { + readonly barcode: string; + readonly mayManage: boolean; + readonly product: Readonly<{ + id: string; + referenceId: string; + associationId: string; + name: string; + unit: BaseUnit; + }> | null; +} + export interface SessionSelection { readonly product_id: string | null; readonly extra_id: string | null; @@ -23,6 +45,8 @@ export interface SessionSelection { export type InventoryCommand = | Readonly<{action: 'inventory.register-product'; name: string; base_unit: BaseUnit}> + | Readonly<{action: 'inventory.link-barcode'; barcode: string; product_id: string}> + | Readonly<{action: 'inventory.remove-barcode'; barcode: string; product_id: string; association_id: string}> | Readonly<{action: 'inventory.add-location'; name: string}> | Readonly<{action: 'inventory.transfer'; product_id: string; source_location: string; destination_location: string; quantity: string}> @@ -288,6 +312,12 @@ export function inventoryCommand(value: unknown): InventoryCommand { throw new Error('invalid_inventory_command'); const record = value as Record; const {action} = record; + if (action === 'inventory.link-barcode' && hasFields(record, ['action', 'barcode', 'product_id'])) + return {action, barcode: canonicalGtin(record.barcode), product_id: taskIdentifier(record.product_id)}; + if (action === 'inventory.remove-barcode' + && hasFields(record, ['action', 'barcode', 'product_id', 'association_id'])) + return {action, barcode: canonicalGtin(record.barcode), product_id: taskIdentifier(record.product_id), + association_id: taskIdentifier(record.association_id)}; if (action === 'inventory.add-location' && hasFields(record, ['action', 'name'])) return {action, name: locationName(record.name)}; if (action === 'inventory.transfer' diff --git a/frontend/src/presentation/domus-inventory.ts b/frontend/src/presentation/domus-inventory.ts index 90abf44..fb34dc6 100644 --- a/frontend/src/presentation/domus-inventory.ts +++ b/frontend/src/presentation/domus-inventory.ts @@ -14,7 +14,7 @@ import {selectState} from '@vypdev/ha-ui/select-contracts'; import {registerFeedback} from '@vypdev/ha-ui/feedback'; import {feedbackState} from '@vypdev/ha-ui/feedback-contracts'; import type {InventoryError, InventoryState} from '../application/inventory-controller'; -import {BASE_UNITS, MAX_LOCATION_NAME, STOCK_REASON_LIMIT, adjustmentQuantity, intakeQuantity, locationName, policyQuantity, stockUnits} from '../domain/inventory'; +import {BASE_UNITS, MAX_LOCATION_NAME, STOCK_REASON_LIMIT, adjustmentQuantity, canonicalGtin, intakeQuantity, locationName, policyQuantity, stockUnits} from '../domain/inventory'; import type {BaseUnit, MovementHistory, ProductStock, ReplenishmentRevision, StockMovement, StockTotals, StorageLocation} from '../domain/inventory'; import {taskText} from '../domain/tasks'; import {inventoryMessage, inventoryUnitMessage} from './inventory-messages'; @@ -26,6 +26,7 @@ import {instant} from './messages'; import type {Language} from './messages'; export type InventoryIntent = {readonly type: 'refresh' | 'more' | 'recover' | 'more-history' | 'close-history'} + | {readonly type: 'barcode'; readonly barcode: string} | {readonly type: 'history'; readonly productId: string} | ShoppingIntent | ShoppingListIntent; @@ -70,12 +71,20 @@ interface PolicyEditor { readonly error: 'invalidQuantity' | 'invalid_replenishment_bounds' | null; } +interface BarcodeReview { + readonly barcode: string; + readonly productId: string; + readonly productName: string; + readonly associationId: string | null; +} + export class DomusInventory extends LitElement { static properties = { view: {attribute:false}, language: {attribute:false}, nameDraft: {state:true}, unit: {state:true}, selected: {state:true}, amount: {state:true}, review: {state:true}, invalid: {state:true}, editor: {state:true}, reason: {state:true}, adjustment: {state:true}, policyEditor: {state:true}, locationDraft: {state:true}, locationInvalid: {state:true}, transferDraft: {state:true}, + barcodeDraft: {state:true}, barcodeSubmitted: {state:true}, barcodeInvalid: {state:true}, barcodeReview: {state:true}, }; static styles = css` @@ -94,6 +103,8 @@ export class DomusInventory extends LitElement { li {overflow-wrap:anywhere;border-block-start:1px solid var(--line);padding-block-start:12px} .history {scroll-margin-block-start:68px} .history-content, .location-content, .location-balances {display:grid;gap:12px} + .barcode-content, .barcode-review {display:grid;gap:12px;min-width:0} + .barcode-review {scroll-margin-block-start:68px} .location-balances {grid-template-columns:repeat(auto-fit,minmax(min(100%,170px),1fr))} .location-stock {border:1px solid var(--line);border-radius:8px;padding:12px;overflow-wrap:anywhere} .location-stock h5 {font-size:inherit;margin:0 0 8px} @@ -117,6 +128,10 @@ export class DomusInventory extends LitElement { private declare locationDraft: string; private declare locationInvalid: boolean; private declare transferDraft: TransferDraft | null; + private declare barcodeDraft: string; + private declare barcodeSubmitted: string | null; + private declare barcodeInvalid: boolean; + private declare barcodeReview: BarcodeReview | null; constructor() { super(); @@ -135,6 +150,10 @@ export class DomusInventory extends LitElement { this.locationDraft = ''; this.locationInvalid = false; this.transferDraft = null; + this.barcodeDraft = ''; + this.barcodeSubmitted = null; + this.barcodeInvalid = false; + this.barcodeReview = null; } protected willUpdate(changed: PropertyValues): void { @@ -149,7 +168,13 @@ export class DomusInventory extends LitElement { this.locationDraft = ''; this.locationInvalid = false; this.transferDraft = null; + this.barcodeDraft = ''; + this.barcodeSubmitted = null; + this.barcodeInvalid = false; + this.barcodeReview = null; } + if (previous?.barcode?.lookup !== current?.barcode?.lookup || current?.report?.mayManage !== true) + this.barcodeReview = null; if (previous?.history?.productId !== current?.history?.productId) { this.editor = null; if (current?.history && current.history.productId !== this.transferDraft?.productId) this.transferDraft = null; @@ -159,6 +184,11 @@ export class DomusInventory extends LitElement { if (result.kind === 'rejected') { if (result.command.action === 'inventory.configure-replenishment' && result.reason === 'revision_conflict') this.policyEditor = null; + if ('barcode' in result.command) this.barcodeReview = null; + } else if (result.barcodeSaved) { + this.barcodeReview = null; + this.barcodeSubmitted = result.barcodeSaved.barcode; + if (this.barcodeDraft === '') this.barcodeDraft = result.barcodeSaved.barcode; } else if (result.locationSaved) this.locationDraft = ''; else if (result.replenishmentSaved) this.policyEditor = null; else if (result.movement === null) { @@ -212,10 +242,98 @@ export class DomusInventory extends LitElement { return html``; } + private barcodeState() { + const search = this.view?.barcode; + return search && search.code === this.barcodeSubmitted ? search : null; + } + + private beginBarcodeReview(productId: string, productName: string, associationId: string | null): void { + const lookup = this.barcodeState()?.lookup; + if (!lookup?.mayManage || this.view?.report?.mayManage !== true || this.view.scope.readOnly) return; + this.barcodeReview = {barcode: lookup.barcode, productId, productName, associationId}; + void this.updateComplete.then(() => this.renderRoot.querySelector('.barcode-review')?.focus()); + } + + private barcodeSearch(manage: boolean, busy: boolean, blocked: boolean) { + const search = this.barcodeState(); + const lookup = search?.lookup; + const product = lookup?.product; + const review = this.barcodeReview; + const firstProduct = this.view!.report!.products[0]; + return html` +
+
{ + event.preventDefault(); + if (busy || this.view!.pending) return; + try { + this.barcodeSubmitted = canonicalGtin(this.barcodeDraft); + } catch { + this.barcodeInvalid = true; + this.barcodeSubmitted = null; + void this.updateComplete.then(() => this.renderRoot.querySelector('.barcode-content vyp-ha-field')?.focus()); + return; + } + this.barcodeInvalid = false; + this.barcodeReview = null; + this.intent({type: 'barcode', barcode: this.barcodeSubmitted}); + }}> + { + this.barcodeDraft = event.detail.value; + this.barcodeSubmitted = null; + this.barcodeInvalid = false; + this.barcodeReview = null; + }}> + ${this.submitButton(search?.unavailable ? 'barcodeRetry' : 'barcodeSearch', busy || this.view!.pending)} + + ${search && lookup === null && !search.unavailable ? html`` : nothing} + ${search?.unavailable ? html`` : nothing} + ${lookup && product === null ? html`

${this.text('barcodeUnlinked')}

+ ${manage && lookup.mayManage ? firstProduct ? html` { + event.preventDefault(); + this.renderRoot.querySelector('article[id="product-' + firstProduct.id + '"]')?.focus(); + }}>${this.text('barcodeChooseProduct')}` : html`

${this.text('barcodeRegisterProduct')}

` : nothing}` : nothing} + ${lookup && (!manage || !lookup.mayManage) ? html`

${this.text('barcodeManagerRequired')}

` : nothing} + ${product ? html`

${this.text('barcodeFound')} ${product.name}

+
+ ${this.button('barcodeViewStock', () => this.intent({type: 'history', productId: product.id}), busy)} + ${manage && lookup!.mayManage && review === null + ? this.button('barcodeRemove', () => this.beginBarcodeReview(product.id, product.name, product.associationId), blocked) : nothing} +
` : nothing} + ${review ? html`
{ + event.preventDefault(); + if (blocked) return; + this.intent({type: 'submit', command: review.associationId === null + ? {action: 'inventory.link-barcode', barcode: review.barcode, product_id: review.productId} + : {action: 'inventory.remove-barcode', barcode: review.barcode, + product_id: review.productId, association_id: review.associationId}}); + }}> +

${review.productName} · ${review.barcode}

+

${this.text(review.associationId === null ? 'barcodeLinkReview' : 'barcodeRemoveReview')}

+
+ ${this.submitButton(review.associationId === null ? 'barcodeConfirmLink' : 'barcodeConfirmRemove', blocked)} + ${this.button('cancel', () => { + this.barcodeReview = null; + void this.updateComplete.then(() => this.renderRoot.querySelector('.barcode-content vyp-ha-field')?.focus()); + }, blocked)} +
+
` : nothing} +
+
`; + } + private registration(blocked: boolean) { const invalid = this.invalid === 'name'; return html` -
{ + { event.preventDefault(); if (blocked) return; try {taskText(this.nameDraft, 160, true);} catch {this.invalid = 'name'; return;} @@ -503,6 +621,7 @@ export class DomusInventory extends LitElement { private product(product: ProductStock, manage: boolean, busy: boolean, blocked: boolean) { const policy = product.replenishment, editor = this.policyEditor; + const barcode = this.barcodeState()?.lookup; return html`

${product.name}

${this.text('unit')} · ${this.text(product.unit)}

@@ -517,6 +636,9 @@ export class DomusInventory extends LitElement {

${this.text('outstandingPurchase')} · ${this.quantity(product.outstandingPurchase)} ${this.text(product.unit)}

${this.text('shoppingNeeded')} · ${this.quantity(product.shoppingNeeded)} ${this.text(product.unit)}

`}
+ ${manage && barcode?.mayManage && barcode.product === null ? html` this.beginBarcodeReview(product.id, product.name, null)}>` : nothing} ${this.button('showHistory', () => this.intent({type:'history', productId:product.id}), busy)} ${manage && this.view!.report!.locations.length > 0 ? this.button('moveStock', () => this.beginTransfer(product.id), blocked) : nothing} @@ -545,7 +667,10 @@ export class DomusInventory extends LitElement { .state=${feedbackState({kind:'notice', tone:'warning', message:this.text(message)})}>`} ${saved === null ? nothing : html`

${this.text(saved.kind === 'historical' ? 'historical' : movement ? MOVEMENT_SAVED[movement.action] : saved.shoppingAction - ? SHOPPING_SAVED[saved.shoppingAction] : saved.replenishmentSaved ? 'replenishmentSaved' : saved.locationSaved ? 'locationSaved' : 'registered')} + ? SHOPPING_SAVED[saved.shoppingAction] : saved.barcodeSaved + ? saved.barcodeSaved.linked ? 'barcodeLinkedSaved' : 'barcodeRemovedSaved' + : saved.replenishmentSaved ? 'replenishmentSaved' : saved.locationSaved ? 'locationSaved' : 'registered')} + ${saved.barcodeSaved ? html`${saved.barcodeSaved.barcode}` : nothing} ${movement ? html`${this.quantity(movement.quantity)} ${this.unitLabel(movement.unit, movement.quantity)}` : nothing}

${report?.products.some(product => product.id === saved.productId) ? html` { @@ -560,6 +685,7 @@ export class DomusInventory extends LitElement { ${pending ? this.button('recover', () => this.intent({type:'recover'}), busy) : nothing}
${busy && report === null ? html`

${this.text('loading')}

` : nothing} ${report === null ? nothing : html` + ${this.barcodeSearch(manage, busy, blocked)} ${manage ? this.registration(blocked) : nothing} ${this.locations(report.locations, manage, blocked)} diff --git a/frontend/src/presentation/inventory-messages.ts b/frontend/src/presentation/inventory-messages.ts index bc6713c..f23cc7f 100644 --- a/frontend/src/presentation/inventory-messages.ts +++ b/frontend/src/presentation/inventory-messages.ts @@ -4,6 +4,24 @@ import type {Language} from './messages'; const SINGULAR_UNIT = {piece:'singularPiece', gram:'singularGram', millilitre:'singularMillilitre'} as const; const EN = { + barcodeTitle: 'Find product by barcode', + barcodeNumber: 'Digits below the barcode', + barcodeHelp: 'Enter 8, 12, 13 or 14 digits. For example, 036000291452. Keep leading zeroes.', + barcodeRequired: 'Enter the barcode number.', + barcodeSearch: 'Find product', barcodeRetry: 'Retry barcode lookup', + barcodeLoading: 'Looking up the barcode.', + barcodeUnavailable: 'Local barcode lookup is unavailable. Retry the lookup or refresh Inventory.', + barcodeUnlinked: 'Unlinked barcode in this household.', + barcodeChooseProduct: 'Choose a product in Pantry below.', + barcodeRegisterProduct: 'Register a product below to associate this barcode.', + barcodeManagerRequired: 'An inventory manager can change barcode associations.', + barcodeFound: 'Product found', barcodeViewStock: 'Open product stock', + barcodeLink: 'Associate barcode with', barcodeRemove: 'Remove barcode association', + barcodeReviewLink: 'Review barcode association', barcodeReviewRemove: 'Review barcode removal', + barcodeLinkReview: 'This barcode will identify the selected product.', + barcodeRemoveReview: 'Remove this association before linking the barcode to another product.', + barcodeConfirmLink: 'Confirm barcode association', barcodeConfirmRemove: 'Confirm barcode removal', + barcodeLinkedSaved: 'Barcode associated.', barcodeRemovedSaved: 'Barcode association removed.', title: 'Inventory', pantry: 'Pantry', empty: 'There are no registered products.', loading: 'Loading inventory.', refresh: 'Refresh inventory', more: 'Show more products', recover: 'Recover original request', productName: 'Product name', unit: 'Base unit', permanent: 'The base unit cannot change after registration.', @@ -29,6 +47,9 @@ const EN = { invalid_material_quantity: 'Stock was not changed. Check the quantity.', invalid_material_precision: 'Stock was not changed. Check the allowed decimal places.', inventory_product_missing: 'The product is unavailable. Refresh the catalog.', + invalid_inventory_barcode: 'Enter 8, 12, 13 or 14 printed digits with a valid check digit.', + inventory_barcode_linked: 'This barcode is already linked. Review the current product before changing its association.', + inventory_barcode_changed: 'The association changed. Review the current product before confirming again.', inventory_stock_capacity: 'Stock was not changed. Compare the recorded quantity with the limit and enter a smaller amount.', history: 'Movement history', showHistory: 'Show movement history', closeHistory: 'Close movement history', moreHistory: 'Show older movements', emptyHistory: 'There are no movements for this product.', @@ -133,6 +154,24 @@ const EN = { } as const; const ES: Record = { + barcodeTitle: 'Buscar producto por código de barras', + barcodeNumber: 'Dígitos bajo el código de barras', + barcodeHelp: 'Introduce 8, 12, 13 o 14 dígitos. Por ejemplo, 036000291452. Conserva los ceros iniciales.', + barcodeRequired: 'Introduce el número del código de barras.', + barcodeSearch: 'Buscar producto', barcodeRetry: 'Reintentar búsqueda del código', + barcodeLoading: 'Buscando el código de barras.', + barcodeUnavailable: 'La búsqueda local del código no está disponible. Reintenta la búsqueda o actualiza Inventario.', + barcodeUnlinked: 'Código sin asociación en este hogar.', + barcodeChooseProduct: 'Elige un producto en la despensa de abajo.', + barcodeRegisterProduct: 'Registra un producto abajo para asociar este código.', + barcodeManagerRequired: 'Un miembro con permiso para gestionar el inventario puede cambiar las asociaciones.', + barcodeFound: 'Producto encontrado', barcodeViewStock: 'Abrir stock del producto', + barcodeLink: 'Asociar código a', barcodeRemove: 'Eliminar asociación del código', + barcodeReviewLink: 'Revisar asociación del código', barcodeReviewRemove: 'Revisar retirada del código', + barcodeLinkReview: 'Este código identificará el producto elegido.', + barcodeRemoveReview: 'Retira esta asociación antes de vincular el código a otro producto.', + barcodeConfirmLink: 'Confirmar asociación del código', barcodeConfirmRemove: 'Confirmar retirada del código', + barcodeLinkedSaved: 'Código asociado.', barcodeRemovedSaved: 'Asociación del código retirada.', title: 'Inventario', pantry: 'Despensa', empty: 'No hay productos registrados.', loading: 'Cargando el inventario.', refresh: 'Actualizar inventario', more: 'Mostrar más productos', recover: 'Recuperar la solicitud original', productName: 'Nombre del producto', unit: 'Unidad base', permanent: 'La unidad base no se puede cambiar después del registro.', @@ -158,6 +197,9 @@ const ES: Record = { invalid_material_quantity: 'El stock no ha cambiado. Revisa la cantidad.', invalid_material_precision: 'El stock no ha cambiado. Revisa los decimales permitidos.', inventory_product_missing: 'El producto no está disponible. Actualiza el catálogo.', + invalid_inventory_barcode: 'Introduce 8, 12, 13 o 14 dígitos impresos con un dígito de control válido.', + inventory_barcode_linked: 'Este código ya está vinculado. Revisa el producto actual antes de cambiar la asociación.', + inventory_barcode_changed: 'La asociación ha cambiado. Revisa el producto actual antes de volver a confirmar.', inventory_stock_capacity: 'El stock no ha cambiado. Compara la cantidad registrada con el límite e introduce una cantidad menor.', history: 'Historial de movimientos', showHistory: 'Mostrar historial de movimientos', closeHistory: 'Cerrar historial de movimientos', moreHistory: 'Mostrar movimientos anteriores', emptyHistory: 'Este producto no tiene movimientos.', diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index 3f4394e..525764d 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -4,6 +4,134 @@ test.use({hasTouch: true}); const ingress = '/api/hassio_ingress/fixture_domus_supervisor_1234567890'; +for (const mode of ['native', 'standalone'] as const) { + test(`local barcode lookup and reviewed association recovery in ${mode}`, async ({page, context, request}, info) => { + test.setTimeout(50_000); + const origin = `http://127.0.0.1:${mode === 'native' ? 56174 : 56175}`; + const base = origin + (mode === 'native' ? ingress : '') + '/'; + const barcode = '00036000291452'; + const commands = base + 'api/v1/inventory/commands'; + const lookup = base + 'api/v1/inventory/barcode?barcode=' + barcode; + const external: string[] = []; + await context.route('**/*', route => { + if (new URL(route.request().url()).origin === origin) return route.continue(); + external.push(route.request().url()); + return route.abort('internetdisconnected'); + }); + if (process.env.DOMUS_BROWSER_IMAGE) { + const image = await request.get(origin + '/__fixture__/image'); + expect(image.ok()).toBe(true); + expect(await image.json()).toEqual({source_commit:process.env.DOMUS_TEST_SOURCE_COMMIT, + architecture:process.env.DOMUS_TEST_ARCH, image_id:expect.stringMatching(/^sha256:[a-f0-9]{64}$/u), mode}); + } + expect((await request.post(origin + '/__fixture__/reset')).ok()).toBe(true); + if (mode === 'native') await context.addCookies([{name:'ingress_session', value:'f'.repeat(128), + domain:'127.0.0.1', path:'/', httpOnly:true, sameSite:'Strict'}]); + await page.goto(base + '#household'); + if (mode === 'standalone') { + await page.getByRole('button', {name:'Sign in with Home Assistant', exact:true}).press('Enter'); + await page.getByRole('link', {name:'Continue as fixture user', exact:true}).press('Enter'); + } + await page.getByRole('textbox', {name:'Household name', exact:true}).fill('Barcode QA household'); + await page.getByRole('textbox', {name:'Timezone', exact:true}).fill('UTC'); + await page.getByRole('button', {name:'Create household', exact:true}).press('Enter'); + await page.locator('vyp-ha-tabs').getByRole('link', {name:'Inventory', exact:true}).press('Enter'); + const stock = page.locator('domus-inventory'); + for (const name of ['QA barcode soap', 'QA barcode tea']) { + await stock.getByRole('textbox', {name:'Product name', exact:true}).fill(name); + await stock.getByRole('button', {name:'Register product', exact:true}).press('Enter'); + await expect(stock.getByRole('article', {name, exact:true})).toBeVisible(); + } + const digits = stock.getByRole('textbox', {name:'Digits below the barcode', exact:true}); + await expect(digits).toHaveAttribute('type', 'text'); + await expect(digits).toHaveAttribute('inputmode', 'numeric'); + await digits.fill(barcode + '0'); + await digits.press('Enter'); + await expect(digits).toHaveValue(barcode + '0'); + await expect(digits).toBeFocused(); + await expect(stock.getByText('Enter 8, 12, 13 or 14 printed digits with a valid check digit.')).toBeVisible(); + await digits.fill('036000291452'); + await digits.press('Enter'); + await expect(stock.getByText('Unlinked barcode in this household.', {exact:true})).toBeVisible(); + const firstProduct = stock.locator('.products > article').first(); + await stock.getByRole('link', {name:'Choose a product in Pantry below.', exact:true}).press('Enter'); + await expect(firstProduct).toBeFocused(); + await stock.getByRole('button', {name:'Associate barcode with QA barcode soap', exact:true}).press('Enter'); + const review = stock.getByRole('form', {name:'Review barcode association', exact:true}); + await expect(review).toBeFocused(); + await expect(review).toContainText(barcode); + let originalKey = ''; + let associationId = ''; + await page.route(commands, async route => { + expect(route.request().postDataJSON()).toMatchObject({action:'inventory.link-barcode', barcode}); + originalKey = route.request().headers()['idempotency-key']; + const committed = await route.fetch({maxRetries:0, maxRedirects:0}); + expect(committed.ok()).toBe(true); + associationId = (await committed.json()).result.association_id; + await route.abort('connectionclosed'); + }); + await review.getByRole('button', {name:'Confirm barcode association', exact:true}).press('Enter'); + await expect(stock.getByRole('button', {name:'Recover original request', exact:true})).toBeEnabled(); + await page.unroute(commands); + await page.reload(); + const original = page.waitForResponse(base + 'api/v1/inventory/requests/inventory.link-barcode/' + originalKey); + await stock.getByRole('button', {name:'Recover original request', exact:true}).press('Enter'); + expect((await original).ok()).toBe(true); + await expect(stock.getByText('Barcode associated.', {exact:false})).toBeVisible(); + await expect(stock.getByText('Product found QA barcode soap', {exact:true})).toBeVisible(); + await expect(digits).toHaveValue(barcode); + await expect(stock.getByRole('article', {name:'QA barcode soap', exact:true}).locator('dd')).toHaveText(['0', '0', '0']); + await stock.getByRole('button', {name:'Open product stock', exact:true}).press('Enter'); + await expect(stock.getByRole('region', {name:'Movement history · QA barcode soap', exact:true})).toBeFocused(); + await stock.getByRole('button', {name:'Remove barcode association', exact:true}).press('Enter'); + const oldReview = stock.getByRole('form', {name:'Review barcode removal', exact:true}); + await expect(oldReview).toBeFocused(); + + const peer = await context.newPage(); + await peer.goto(base + '#inventory'); + const other = peer.locator('domus-inventory'); + await other.getByRole('textbox', {name:'Digits below the barcode', exact:true}).fill('036000291452'); + await other.getByRole('button', {name:'Find product', exact:true}).press('Enter'); + await other.getByRole('button', {name:'Remove barcode association', exact:true}).press('Enter'); + await other.getByRole('button', {name:'Confirm barcode removal', exact:true}).press('Enter'); + await expect(other.getByText('Unlinked barcode in this household.', {exact:true})).toBeVisible(); + await other.getByRole('button', {name:'Associate barcode with QA barcode tea', exact:true}).press('Enter'); + await other.getByRole('button', {name:'Confirm barcode association', exact:true}).press('Enter'); + await expect(other.getByText('Product found QA barcode tea', {exact:true})).toBeVisible(); + const stale = page.waitForRequest(item => item.url() === commands && item.method() === 'POST'); + await oldReview.getByRole('button', {name:'Confirm barcode removal', exact:true}).press('Enter'); + expect((await stale).postDataJSON()).toMatchObject({action:'inventory.remove-barcode', barcode, association_id:associationId}); + await expect(stock.getByText('The association changed. Review the current product before confirming again.', {exact:true})).toBeVisible(); + await expect(stock.getByText('Product found QA barcode tea', {exact:true})).toBeVisible(); + await expect(oldReview).toHaveCount(0); + await stock.screenshot({path:info.outputPath('barcode-en-keyboard.png')}); + await peer.close(); + + await page.setViewportSize({width:390, height:844}); + await page.emulateMedia({colorScheme:'dark', reducedMotion:'reduce'}); + await page.getByRole('combobox', {name:'Language', exact:true}).selectOption('es'); + const spanish = stock.getByRole('textbox', {name:'Dígitos bajo el código de barras', exact:true}); + const searchCard = stock.getByRole('article', {name:'Buscar producto por código de barras', exact:true}); + await expect(searchCard).toHaveCSS('background-color', 'rgb(24, 36, 47)'); + await expect(searchCard).toHaveCSS('color', 'rgb(237, 244, 250)'); + await expect(stock.getByRole('button', {name:'Buscar producto', exact:true})).toHaveCSS('color', 'rgb(24, 36, 47)'); + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390); + await spanish.fill('036000291452'); + await page.route(lookup, route => route.abort('failed'), {times:1}); + await stock.getByRole('button', {name:'Buscar producto', exact:true}).tap(); + await expect(stock.getByText('La búsqueda local del código no está disponible. Reintenta la búsqueda o actualiza Inventario.', {exact:true})).toBeVisible(); + await expect(spanish).toHaveValue('036000291452'); + await stock.getByRole('button', {name:'Reintentar búsqueda del código', exact:true}).tap(); + await expect(stock.getByText('Producto encontrado QA barcode tea', {exact:true})).toBeVisible(); + await stock.getByRole('button', {name:'Eliminar asociación del código', exact:true}).tap(); + await stock.getByRole('button', {name:'Confirmar retirada del código', exact:true}).tap(); + await expect(stock.getByText('Código sin asociación en este hogar.', {exact:true})).toBeVisible(); + await expect(spanish).toHaveValue('036000291452'); + await stock.screenshot({path:info.outputPath('barcode-es-touch.png')}); + expect(external).toEqual([]); + }); +} + for (const mode of ['native', 'standalone'] as const) { test(`shared workspace navigation in ${mode}`, async ({page, context, request}, info) => { test.setTimeout(75_000); diff --git a/frontend/tests/inventory.test.ts b/frontend/tests/inventory.test.ts index e29131e..bed7f47 100644 --- a/frontend/tests/inventory.test.ts +++ b/frontend/tests/inventory.test.ts @@ -1,12 +1,13 @@ import {afterEach, expect, test, vi} from 'vitest'; +import type {HaTextField} from '@vypdev/ha-ui/field'; import {HttpInventoryServer} from '../src/adapters/inventory-http'; import {INVENTORY_JOURNAL_KEY, InventorySessionJournal} from '../src/adapters/inventory-journal'; import {InventoryController} from '../src/application/inventory-controller'; import type {InventoryRequest, InventoryResult, InventoryScope, InventoryState} from '../src/application/inventory-controller'; import type {EntryRead} from '../src/application/ports'; -import {adjustmentQuantity, intakeQuantity, inventoryCommand} from '../src/domain/inventory'; +import {adjustmentQuantity, canonicalGtin, intakeQuantity, inventoryCommand} from '../src/domain/inventory'; import {revisionValue} from '../src/domain/administration'; -import type {InventoryReport, MovementHistory, Purchase, PurchaseReceipts, Purchases, PurchaseSessions, PurchaseSessionDetail} from '../src/domain/inventory'; +import type {BarcodeLookup, InventoryReport, MovementHistory, Purchase, PurchaseReceipts, Purchases, PurchaseSessions, PurchaseSessionDetail} from '../src/domain/inventory'; import '../src/presentation/domus-inventory'; import corpus from './fixtures/entry-wire.json'; @@ -282,14 +283,16 @@ function controller() { const load = vi.fn((): EntryRead => read(report)); const send = vi.fn((_scope: InventoryScope, _request: InventoryRequest): EntryRead => read(committed)); const original = vi.fn((_scope: InventoryScope, _request: InventoryRequest): EntryRead => read(null)); + const barcodes = vi.fn((_scope: InventoryScope, _code: string): EntryRead => + read({barcode:'00036000291452',mayManage:true,product:null})); const movements = vi.fn((_scope: InventoryScope, _product: string, _cursor: string|null): EntryRead => read(history)); const buys = vi.fn((_scope: InventoryScope, _cursor: string|null): EntryRead => read(purchases)); const arrivals = vi.fn((_scope: InventoryScope, _id:string, _cursor: string|null): EntryRead => read(purchaseReceipts)); - const controller = new InventoryController({read:load,history:movements,purchases:buys,purchaseReceipts:arrivals, + const controller = new InventoryController({barcode:barcodes,read:load,history:movements,purchases:buys,purchaseReceipts:arrivals, purchaseSessions:() => lost(),purchaseSession:() => lost(),shoppingList:() => lost(),shoppingSources:() => lost(),send,original}, local.journal,{requestKey:() => request.key},publish); const current = () => publish.mock.lastCall?.[0]; - return {...local, controller, load, movements, buys, arrivals, send, original, current}; + return {...local, controller, load, barcodes, movements, buys, arrivals, send, original, current}; } test('shopping reads and writes stay within the current authorized session and use original recovery', async () => { @@ -627,14 +630,14 @@ test('inventory exposes scoped empty, read-only and failure states with accessib node.view = {...initial,report:{...report,mayManage:false,products:[],cursor:null}}; await node.updateComplete; expect(root.textContent).toContain('There are no registered products.'); - expect(root.querySelector('form')).toBeNull(); + expect(root.querySelector('.registration-form')).toBeNull(); node.view = {...initial,scope:{...scope,readOnly:true},report}; await node.updateComplete; - expect(root.querySelector('form')).toBeNull(); + expect(root.querySelector('.registration-form')).toBeNull(); node.view = {...initial,report}; await node.updateComplete; press('Show more products'); - const registration = root.querySelector('form')!; + const registration = root.querySelector('.registration-form')!; submit(registration); await node.updateComplete; expect(registration.querySelector('[role=alert]')?.textContent).toContain('Enter a product name'); @@ -949,7 +952,7 @@ test('shared Shopping loads pages only in scope and recovers requests with their const sources = vi.fn((_scope:InventoryScope,_id:string,_cursor:string|null) => read(pages.shoppingSources)); const send = vi.fn((_scope:InventoryScope,_request:InventoryRequest):EntryRead => lost()); const original = vi.fn((_scope:InventoryScope,_request:InventoryRequest):EntryRead => read(null)); - const app = new InventoryController({read:load,history:() => lost(),purchases:() => lost(), + const app = new InventoryController({barcode:() => lost(),read:load,history:() => lost(),purchases:() => lost(), purchaseReceipts:() => lost(),purchaseSessions:() => lost(),purchaseSession:() => lost(), shoppingList:list,shoppingSources:sources,send,original}, local.journal,{requestKey:() => 'extra-operation'},publish); @@ -1010,7 +1013,7 @@ test('opening a shopping item retires incomplete pages, rejects cursor loops and const pages = await shoppingPages(); const publish = vi.fn<(state:InventoryState|null) => void>(); const list = vi.fn((_scope:InventoryScope,_cursor:string|null) => read(pages.shoppingList)); - const app = new InventoryController({read:() => read(report),history:() => lost(),purchases:() => lost(), + const app = new InventoryController({barcode:() => lost(),read:() => read(report),history:() => lost(),purchases:() => lost(), purchaseReceipts:() => lost(),purchaseSessions:() => lost(),purchaseSession:() => lost(), shoppingList:list,shoppingSources:() => lost(),send:() => lost(),original:() => lost()}, journal().journal,{requestKey:() => 'request'},publish); @@ -1195,7 +1198,7 @@ test('session history stays in scope and opens independent per-item receipts aft const arrivals = vi.fn((_scope:InventoryScope,_id:string,_cursor:string|null) => read(purchaseReceipts)); const send = vi.fn((_scope:InventoryScope,_request:InventoryRequest):EntryRead => lost()); const original = vi.fn((_scope:InventoryScope,_request:InventoryRequest) => read(sessionSaved)); - const app = new InventoryController({read:load,history:() => lost(),purchases:() => lost(), + const app = new InventoryController({barcode:() => lost(),read:load,history:() => lost(),purchases:() => lost(), purchaseReceipts:arrivals,purchaseSessions:sessions,purchaseSession:session,shoppingList:() => lost(), shoppingSources:() => lost(),send,original},local.journal,{requestKey:() => 'session-operation'},publish); const state = () => publish.mock.lastCall?.[0]; @@ -1973,3 +1976,313 @@ test('the shared location and transfer controls retain drafts through rejection press('Cerrar historial de movimientos'); expect(events.mock.lastCall?.[0].detail).toEqual({type:'close-history'}); }); + + +test('printed GTINs validate before padding and keep exact canonical command identities', () => { + for (const value of ['96385074', '036000291452', '0036000291452', '00036000291452']) { + expect(canonicalGtin(value)).toBe(value.padStart(14, '0')); + const wrongDigit = value.slice(0, -1) + String((Number(value.at(-1)) + 1) % 10); + expect(() => canonicalGtin(wrongDigit)).toThrow('invalid_inventory_barcode'); + } + for (const value of [null, undefined, 36000291452, {}, [], '', '1234567', '0'.repeat(9), + '0'.repeat(10), '0'.repeat(11), '0'.repeat(15), ' 96385074', '96385074 ', '96385074\n', '96385074', '9638507x']) + expect(() => canonicalGtin(value)).toThrow('invalid_inventory_barcode'); + const link = inventoryCommand({action: 'inventory.link-barcode', barcode: '036000291452', product_id: 'product'}); + const remove = inventoryCommand({action: 'inventory.remove-barcode', barcode: '0036000291452', product_id: 'product', association_id: 'link'}); + expect(link).toEqual({action: 'inventory.link-barcode', barcode: '00036000291452', product_id: 'product'}); + expect(remove).toEqual({...link, action: 'inventory.remove-barcode', association_id: 'link'}); + const local = journal().journal; + for (const command of [link, remove, intake]) { + const operation = {...request, command}; + local.save(operation); + expect(local.open(scope.key)).toEqual(operation); + local.clear(operation); + } + for (const command of [{...link, extra: true}, {...remove, association_id: ''}, + {action: 'inventory.remove-barcode', barcode: '00036000291452', product_id: 'product'}]) + expect(() => inventoryCommand(command)).toThrow(); +}); + +test.each(['native', 'standalone'] as const)('barcode reads bind canonical identity and product in %s', async deployment => { + const barcode = '00036000291452'; + const association = {barcode, association_id: 'link', product_id: 'product'}; + const product = {product_id: 'product', reference_id: 'reference', name: 'Soap', base_unit: 'piece'}; + const found = {barcode, may_manage: true, association, product}; + const absent = {...found, may_manage: false, association: null, product: null}; + const {server, fetch} = http([[200, found], [200, absent]], deployment); + expect(await server.barcode(scope, '036000291452').result).toEqual({barcode, mayManage: true, + product: {id: 'product', referenceId: 'reference', associationId: 'link', name: 'Soap', unit: 'piece'}}); + expect(await server.barcode(scope, barcode).result).toEqual({barcode, mayManage: false, product: null}); + expect(fetch.mock.calls[0][0]).toContain('inventory/barcode?barcode=00036000291452'); + for (const invalid of [null, {...found, barcode: '96385074'}, {...found, may_manage: 'true'}, + {...found, association: null}, {...found, product: null}, + {...found, association: {...association, barcode: '96385074'}}, + {...found, association: {...association, product_id: 'foreign'}}, + {...found, product: {...product, reference_id: ''}}, {...found, product: {...product, base_unit: 'litre'}}]) + await expect(http([[200, invalid]], deployment).server.barcode(scope, barcode).result).rejects.toMatchObject({code: 'invalid_response'}); + expect(() => server.barcode(scope, '96385075')).toThrow('invalid_inventory_barcode'); +}); + +test('barcode original receipts match the exact frozen association command', async () => { + const barcode = '00036000291452'; + const saved = {barcode, association_id: 'link', product_id: 'product'}; + for (const action of ['inventory.link-barcode', 'inventory.remove-barcode'] as const) { + const command = inventoryCommand(action === 'inventory.link-barcode' + ? {action, barcode, product_id: 'product'} : {action, ...saved}); + const operation = {...request, command}; + const {server} = http([[200, receipt(saved)], [200, receipt(saved, 'historical')]]); + expect(await server.original(scope, operation).result).toMatchObject({kind: 'committed', + productId: 'product', movement: null, barcodeSaved: {barcode, linked: action === 'inventory.link-barcode'}}); + expect(await server.original(scope, operation).result).toMatchObject({kind: 'historical'}); + for (const invalid of [{...saved, barcode: '96385074'}, {...saved, product_id: 'other'}, {...saved, association_id: ''}]) + await expect(http([[200, receipt(invalid)]]).server.original(scope, operation).result).rejects.toMatchObject({code: 'invalid_response'}); + if (action === 'inventory.remove-barcode') + await expect(http([[200, receipt({...saved, association_id: 'new-link'})]]).server.original(scope, operation).result).rejects.toMatchObject({code: 'invalid_response'}); + } +}); + + +test('barcode query failure retires old facts and supports an explicit read retry', async () => { + const f = controller(), app = f.controller; + await app.showBarcode('036000291452'); + app.bind(scope); + await app.showBarcode('036000291452'); + await vi.waitFor(() => expect(f.current()?.busy).toBe(false)); + await app.showBarcode('96385075'); + expect(f.barcodes).not.toHaveBeenCalled(); + await app.showBarcode('036000291452'); + expect(f.current()?.barcode).toEqual({code:'00036000291452',lookup:{barcode:'00036000291452',mayManage:true,product:null},unavailable:false}); + f.barcodes.mockReturnValueOnce(lost()); + await app.showBarcode('036000291452'); + expect(f.current()?.barcode).toEqual({code:'00036000291452',lookup:null,unavailable:true}); + await app.showBarcode('036000291452'); + expect(f.current()?.barcode?.unavailable).toBe(false); + expect(f.current()?.barcode?.lookup?.barcode).toBe('00036000291452'); + f.load.mockReturnValueOnce(lost()); + await app.refresh(); + expect(f.current()?.barcode).toBeNull(); + expect(f.current()?.report).toBeNull(); +}); + +test('retired barcode reads cannot populate another household scope', async () => { + const f = controller(), app = f.controller; + app.bind(scope); + await vi.waitFor(() => expect(f.current()?.busy).toBe(false)); + let resolve!: (value: BarcodeLookup) => void; + const cancel = vi.fn(); + f.barcodes.mockReturnValueOnce({result:new Promise(done => {resolve=done;}),cancel}); + const reading = app.showBarcode('036000291452'); + await app.showBarcode('036000291452'); + expect(f.barcodes).toHaveBeenCalledOnce(); + app.bind({...scope,key:'different-home'}); + await vi.waitFor(() => expect(f.current()?.busy).toBe(false)); + resolve({barcode:'00036000291452',mayManage:true,product:null}); + await reading; + expect(cancel).toHaveBeenCalledOnce(); + expect(f.current()?.barcode).toBeUndefined(); +}); + +test('lost barcode writes recover their original receipt and refresh current association facts', async () => { + const f = controller(), app = f.controller; + const barcode = '00036000291452'; + const link = {action:'inventory.link-barcode',barcode,product_id:'product'} as const; + const found: BarcodeLookup = {barcode,mayManage:true, + product:{id:'product',referenceId:'reference',associationId:'link',name:'Soap',unit:'piece'}}; + app.bind(scope); + await vi.waitFor(() => expect(f.current()?.busy).toBe(false)); + await app.showBarcode(barcode); + f.send.mockReturnValueOnce(lost()); + await app.submit(link); + expect(f.current()).toMatchObject({pending:true,notice:'uncertain'}); + f.barcodes.mockReturnValueOnce(lost()); + await app.showBarcode(barcode); + expect(f.current()).toMatchObject({pending:true,notice:'uncertain',barcode:{code:barcode,lookup:null,unavailable:true}}); + f.original.mockReturnValueOnce(read({kind:'committed',operationId:'original-link',productId:'product', + movement:null,barcodeSaved:{barcode,linked:true}})); + f.barcodes.mockReturnValueOnce(read(found)); + await app.recover(); + expect(f.current()).toMatchObject({pending:false,notice:null,barcode:{code:barcode,lookup:found,unavailable:false}}); + expect(f.journal.open(scope.key)).toBeNull(); + f.send.mockReturnValueOnce(read({kind:'rejected',reason:'inventory_barcode_changed', + command:{action:'inventory.remove-barcode',barcode,product_id:'product',association_id:'link'}})); + f.barcodes.mockReturnValueOnce(read({...found,product:{...found.product!,associationId:'new-link'}})); + await app.submit({action:'inventory.remove-barcode',barcode,product_id:'product',association_id:'link'}); + expect(f.current()?.result?.kind).toBe('rejected'); + expect(f.current()?.barcode?.lookup?.product?.associationId).toBe('new-link'); +}); + + +const barcodeCode = '00036000291452'; +const barcodeUnlinked: BarcodeLookup = {barcode: barcodeCode, mayManage: true, product: null}; +const barcodeFound: BarcodeLookup = {barcode: barcodeCode, mayManage: true, product: { + id: 'product', referenceId: 'reference', name: 'Olive oil', unit: 'millilitre', associationId: 'barcode-link', +}}; +const barcodeView: InventoryState = {...initial, report, + barcode: {code: barcodeCode, lookup: barcodeUnlinked, unavailable: false}}; + +async function barcodeComponent(language: 'en' | 'es' = 'en') { + const f = component(); + const field = () => f.root.querySelector('.barcode-content vyp-ha-field'); + const search = () => f.root.querySelector('.barcode-search-form'); + const assign = async (view: InventoryState | null) => { + f.node.view = view; + await f.node.updateComplete; + await field()?.updateComplete; + }; + const enter = async (value: string) => { + const control = field()!; + await control.updateComplete; + const input = control.shadowRoot!.querySelector('input')!; + input.value = value; + input.dispatchEvent(new InputEvent('input', {bubbles: true, composed: true})); + await f.node.updateComplete; + await control.updateComplete; + }; + f.node.language = language; + await assign({...initial, report}); + return {...f, field, search, assign, enter}; +} + +test('barcode lookup selects an existing paginated product and reviews each association write', async () => { + const f = await barcodeComponent(); + const registration = f.root.querySelector('.registration-form')!; + f.input(registration, 'Preserved product draft'); + await f.enter('036000291452'); + expect(f.field()!.state.inputMode).toBe('numeric'); + expect(f.field()!.shadowRoot!.querySelector('input')!.type).toBe('text'); + f.submit(f.search()!); + expect(f.events.mock.lastCall?.[0].detail).toEqual({type: 'barcode', barcode: barcodeCode}); + await f.assign(barcodeView); + expect(f.root.textContent).toContain('Unlinked barcode in this household.'); + f.root.querySelector('.barcode-content a')!.click(); + expect((f.root.activeElement as HTMLElement).id).toBe('product-product'); + f.press('Associate barcode with Olive oil'); + await f.node.updateComplete; + const review = () => f.root.querySelector('.barcode-review'); + expect(review()!.textContent).toContain('Olive oil'); + expect(review()!.textContent).toContain(barcodeCode); + expect(review()!.getAttribute('aria-label')).toBe('Review barcode association'); + expect(f.root.activeElement).toBe(review()); + f.submit(review()!); + expect(f.events.mock.lastCall?.[0].detail).toEqual({type: 'submit', command: { + action: 'inventory.link-barcode', barcode: barcodeCode, product_id: 'product', + }}); + const linked: InventoryResult = {kind: 'committed', operationId: 'linked', productId: 'product', + movement: null, barcodeSaved: {barcode: barcodeCode, linked: true}}; + const found: InventoryState = {...barcodeView, result: linked, + barcode: {code: barcodeCode, lookup: barcodeFound, unavailable: false}}; + await f.assign(found); + expect(f.root.textContent).toContain('Barcode associated.'); + expect(f.root.querySelector('.registration-form input')!.value).toBe('Preserved product draft'); + expect(f.field()!.value).toBe('036000291452'); + f.press('Open product stock'); + expect(f.events.mock.lastCall?.[0].detail).toEqual({type: 'history', productId: 'product'}); + f.press('Remove barcode association'); + await f.node.updateComplete; + expect(review()!.getAttribute('aria-label')).toBe('Review barcode removal'); + f.submit(review()!); + expect(f.events.mock.lastCall?.[0].detail).toEqual({type: 'submit', command: { + action: 'inventory.remove-barcode', barcode: barcodeCode, product_id: 'product', association_id: 'barcode-link', + }}); + await f.assign({...barcodeView, result: {...linked, operationId: 'removed', barcodeSaved: {barcode: barcodeCode, linked: false}}}); + expect(f.root.textContent).toContain('Barcode association removed.'); + expect(review()).toBeNull(); + await f.enter(''); + await f.assign({...found, result: {...linked, operationId: 'recovered'}}); + expect(f.field()!.value).toBe(barcodeCode); + await f.assign({...found, result: {...linked, kind: 'historical'}}); + expect(f.root.textContent).toContain('before restoration'); +}); + +test('barcode drafts retain malformed input and retire unavailable or obsolete match facts', async () => { + const f = await barcodeComponent('es'); + const invalid = barcodeCode + '0'; + await f.enter(invalid); + f.submit(f.search()!); + await f.node.updateComplete; + await f.field()!.updateComplete; + expect(f.events).not.toHaveBeenCalled(); + expect(f.field()!.value).toBe(invalid); + expect(f.field()!.state.error).toContain('dígito de control'); + expect(f.field()!.shadowRoot!.activeElement).toBe(f.field()!.shadowRoot!.querySelector('input')); + await f.enter('036000291452'); + f.submit(f.search()!); + const loading = {...barcodeView, barcode: {code: barcodeCode, lookup: null, unavailable: false}}; + await f.assign(loading); + expect(f.root.querySelector('vyp-ha-feedback')!.state!.kind).toBe('loading'); + await f.assign({...loading, barcode: {code: barcodeCode, lookup: null, unavailable: true}}); + expect(f.root.querySelector('vyp-ha-feedback')!.state!.message).toContain('búsqueda local'); + expect(f.field()!.value).toBe('036000291452'); + expect([...f.root.querySelectorAll('vyp-ha-button')].map(button => button.state.label)).toContain('Reintentar búsqueda del código'); + f.submit(f.search()!); + expect(f.events.mock.lastCall?.[0].detail).toEqual({type: 'barcode', barcode: barcodeCode}); + await f.assign({...barcodeView, report: {...report, products: []}}); + expect(f.root.textContent).toContain('Registra un producto abajo'); + await f.assign(barcodeView); + f.press('Asociar código a Olive oil'); + await f.node.updateComplete; + f.press('Cancelar'); + await f.node.updateComplete; + expect(f.root.querySelector('.barcode-review')).toBeNull(); + expect(f.field()!.shadowRoot!.activeElement).toBe(f.field()!.shadowRoot!.querySelector('input')); + await f.enter('96385074'); + expect(f.root.textContent).not.toContain('Código sin asociación'); + await f.assign({...barcodeView, scope: {...scope, key: 'another-household'}}); + expect(f.field()!.value).toBe(''); + const orphan = [...f.root.querySelectorAll('vyp-ha-button')].find(button => button.state.label === 'Asociar código a Olive oil'); + expect(orphan).toBeUndefined(); + await f.assign(null); + expect(f.root.textContent).toBe(''); +}); + +test('barcode controls honor current grants, pending work and changed association identities', async () => { + const f = await barcodeComponent(); + await f.enter('036000291452'); + f.submit(f.search()!); + await f.assign(barcodeView); + const retired = [...f.root.querySelectorAll('vyp-ha-button')].find(button => button.state.label === 'Associate barcode with Olive oil')!; + for (const partial of [{busy: true}, {pending: true}]) { + await f.assign({...barcodeView, ...partial}); + const before = f.events.mock.calls.length; + f.submit(f.search()!); + expect(f.events).toHaveBeenCalledTimes(before); + expect(f.field()!.disabled).toBe(true); + } + await f.assign(barcodeView); + f.press('Associate barcode with Olive oil'); + await f.node.updateComplete; + await f.assign({...barcodeView, pending: true}); + const before = f.events.mock.calls.length; + f.submit(f.root.querySelector('.barcode-review')!); + expect(f.events).toHaveBeenCalledTimes(before); + await f.assign({...barcodeView, result: {kind: 'rejected', reason: 'inventory_barcode_linked', + command: {action: 'inventory.link-barcode', barcode: barcodeCode, product_id: 'product'}}}); + expect(f.root.querySelector('.barcode-review')).toBeNull(); + for (const grant of [ + {...barcodeView, report: {...report, mayManage: false}}, + {...barcodeView, barcode: {code: barcodeCode, lookup: {...barcodeUnlinked, mayManage: false}, unavailable: false}}, + {...barcodeView, scope: {...scope, readOnly: true}}, + ]) { + await f.assign(grant); + retired.dispatchEvent(new Event('ha-press-request')); + await f.node.updateComplete; + expect(f.root.querySelector('.barcode-review')).toBeNull(); + expect(f.root.textContent).toContain('An inventory manager can change barcode associations.'); + expect([...f.root.querySelectorAll('vyp-ha-button')].some(button => button.state.label.startsWith('Associate barcode with'))).toBe(false); + } + await f.assign({...barcodeView, barcode: {code: barcodeCode, lookup: barcodeFound, unavailable: false}}); + f.press('Remove barcode association'); + await f.node.updateComplete; + await f.assign({...barcodeView, result: {kind: 'rejected', reason: 'inventory_barcode_changed', command: { + action: 'inventory.remove-barcode', barcode: barcodeCode, product_id: 'product', association_id: 'barcode-link', + }}, barcode: {code: barcodeCode, lookup: {...barcodeFound, product: {...barcodeFound.product!, associationId: 'new-link'}}, unavailable: false}}); + expect(f.root.querySelector('.barcode-review')).toBeNull(); + f.press('Remove barcode association'); + await f.node.updateComplete; + f.submit(f.root.querySelector('.barcode-review')!); + expect(f.events.mock.lastCall?.[0].detail.command.association_id).toBe('new-link'); + await f.assign({...initial, report}); + retired.dispatchEvent(new Event('ha-press-request')); + await f.node.updateComplete; + expect(f.root.querySelector('.barcode-review')).toBeNull(); +}); diff --git a/frontend/tests/page.test.ts b/frontend/tests/page.test.ts index 896de6e..e47ff87 100644 --- a/frontend/tests/page.test.ts +++ b/frontend/tests/page.test.ts @@ -142,6 +142,9 @@ function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'e upcoming_maintenance: {total: 0, items: []}, }); } + else if (route === 'inventory/barcode?barcode=00036000291452') raw = JSON.stringify({ + barcode:'00036000291452',may_manage:true,association:null,product:null, + }); else if (route === 'inventory/stock-attention') raw = JSON.stringify({total:0,items:[]}); else if (route === 'inventory/shopping-attention') raw = JSON.stringify(shoppingItemPresent ? {total:1,items:[shoppingItem]} : {total:0,items:[]}); @@ -836,6 +839,12 @@ test('Inventory owns the current protected destination and accepts only closed u expect(decodeInventoryIntent({type:'purchase-session',sessionId:'../outside'})).toBeNull(); expect(decodeInventoryIntent({type:'purchase-receipts',purchaseId:'../outside'})).toBeNull(); expect(decodeInventoryIntent({type:'submit',command:{action:'inventory.intake',product_id:'product',quantity:'1',location:'foreign'}})).toBeNull(); + expect(decodeInventoryIntent({type:'barcode',barcode:'036000291452'})).toEqual({type:'barcode',barcode:'00036000291452'}); + expect(decodeInventoryIntent({type:'barcode',barcode:'96385075'})).toBeNull(); + expect(decodeInventoryIntent({type:'barcode',barcode:'036000291452',household:'foreign'})).toBeNull(); + emit({type:'barcode',barcode:'036000291452'}); + await vi.waitFor(() => expect(app.inventory?.barcode?.lookup?.barcode).toBe('00036000291452')); + expect(app.inventory?.barcode?.lookup?.product).toBeNull(); navigate('#tasks'); expect(app.inventory).toBeNull(); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1baac5b..63d2c69 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -27,8 +27,8 @@ importers: frontend: dependencies: '@vypdev/ha-ui': - specifier: 0.1.0-next.2 - version: 0.1.0-next.2 + specifier: 0.1.0-next.3 + version: 0.1.0-next.3 lit: specifier: 3.3.3 version: 3.3.3 @@ -813,8 +813,8 @@ packages: '@vitest/utils@5.0.5': resolution: {integrity: sha512-/rBu7gzLDQI/SC79Tn98b5DwOgaHU/Gt4I9OVeP3YofzNaYtbImRCOJQmT1S6vOJg9gEIlWC+r3QxKkjuSa1nQ==} - '@vypdev/ha-ui@0.1.0-next.2': - resolution: {integrity: sha512-dB1RWDDDcdrcohBEi/TSWR89kXPbm/0/yE1Gz1WQ3bSE0nZOeuMveSPeSNaPv2n7sm97K25MG1c1GjywZchbrA==} + '@vypdev/ha-ui@0.1.0-next.3': + resolution: {integrity: sha512-DgUrjC7MOGQ0JMSfEO2DpnagEYpik+9zB6LeGggZGVZO6X+2hYywed0uYFnnvNS7byqhV1N/SAoIAnx/LZ+yjQ==} '@webcontainer/env@1.1.1': resolution: {integrity: sha512-6aN99yL695Hi9SuIk1oC88l9o0gmxL1nGWWQ/kNy81HigJ0FoaoTXpytCj6ItzgyCEwA9kF1wixsTuv5cjsgng==} @@ -2041,7 +2041,7 @@ snapshots: convert-source-map: 2.0.0 tinyrainbow: 3.2.0 - '@vypdev/ha-ui@0.1.0-next.2': + '@vypdev/ha-ui@0.1.0-next.3': dependencies: lit: 3.3.3 diff --git a/tests/backend/test_activation_compatibility.py b/tests/backend/test_activation_compatibility.py index 0264442..a62fbab 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] == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 35 assert connection.execute("SELECT COUNT(*) FROM retained_operations").fetchone()[0] == ( 2 if version == 4 else 1 ) diff --git a/tests/backend/test_automation_draft_storage.py b/tests/backend/test_automation_draft_storage.py index 11318bc..2ffb1c7 100644 --- a/tests/backend/test_automation_draft_storage.py +++ b/tests/backend/test_automation_draft_storage.py @@ -80,7 +80,7 @@ def test_migration_restoration_and_rollback_keep_exact_drafts_and_receipts( store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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")) @@ -90,7 +90,7 @@ def test_migration_restoration_and_rollback_keep_exact_drafts_and_receipts( archive, target = tmp_path / "checkpoint", tmp_path / "prepared" snapshotter = SQLiteSnapshots(store, archive, installation, Clock()) checkpoint = snapshotter.create("first-draft") - assert checkpoint.schema_version == 34 and snapshotter.inspect() == checkpoint + assert checkpoint.schema_version == 35 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)) diff --git a/tests/backend/test_automation_execution_storage.py b/tests/backend/test_automation_execution_storage.py index 269a10c..f8ddcba 100644 --- a/tests/backend/test_automation_execution_storage.py +++ b/tests/backend/test_automation_execution_storage.py @@ -89,7 +89,7 @@ def test_runtime_migration_restoration_and_rollback_preserve_exact_outcomes( assert path.read_bytes() == original store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: - assert db.execute("PRAGMA user_version").fetchone() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) assert db.execute("PRAGMA foreign_key_check").fetchall() == [] assert { table: db.execute(f"SELECT * FROM {table}").fetchall() for table in tables @@ -121,7 +121,7 @@ def test_runtime_migration_restoration_and_rollback_preserve_exact_outcomes( archive, target = tmp_path / "checkpoint", tmp_path / "prepared" snapshotter = SQLiteSnapshots(store, archive, installation, Clock()) checkpoint = snapshotter.create("before-run") - assert checkpoint.schema_version == 34 and snapshotter.inspect() == checkpoint + assert checkpoint.schema_version == 35 and snapshotter.inspect() == checkpoint complete = execution.run("record-run", request) occurrence_id = complete.result.decode()["task_occurrence_id"] restarted = execution_service(SQLiteDatabase(path, installation)) diff --git a/tests/backend/test_daily_automation_drafts.py b/tests/backend/test_daily_automation_drafts.py index 8f07ff5..44ff418 100644 --- a/tests/backend/test_daily_automation_drafts.py +++ b/tests/backend/test_daily_automation_drafts.py @@ -223,9 +223,12 @@ def test_daily_definition_after_migration_restart_and_restore( legacy_manual = None if version == 33: + # Construct the historical control-table migration before running its commands. + with closing(sqlite3.connect(path, autocommit=True)) as db: + db.execute(storage.AUTOMATION_CONTROL_STATEMENT) + db.execute("PRAGMA user_version=33") with monkeypatch.context() as previous: previous.setattr(storage, "SCHEMA_VERSION", 33) - store.initialize(require_existing=True) legacy_manual = draft_service(store).save( "legacy-manual", SaveDraft(None, 0, AutomationRule(1, "manual", None, TaskContent("Legacy manual"))), @@ -244,7 +247,7 @@ def test_daily_definition_after_migration_restart_and_restore( store.initialize(require_existing=True) with closing(sqlite3.connect(path)) as db: db.row_factory = sqlite3.Row - assert _verify_database(db, store, previous=False) == 34 + assert _verify_database(db, store, previous=False) == 35 assert ( db.execute("SELECT * FROM inventory_products ORDER BY product_id").fetchall() == original_products diff --git a/tests/backend/test_inventory_barcode_http.py b/tests/backend/test_inventory_barcode_http.py new file mode 100644 index 0000000..1702ac9 --- /dev/null +++ b/tests/backend/test_inventory_barcode_http.py @@ -0,0 +1,110 @@ +"""Barcode admission uses both protected production HTTP compositions.""" + +import pytest +from test_inventory_catalog_http import INVENTORY, VIEWER, post, register +from test_recurrence_http import USER +from test_rewards_http import member_context +from test_task_runtime import api as api + +from domus.domain.errors import StorageFailure +from domus.domain.identity import Member, MemberStatus, Role +from domus.infrastructure.sqlite_inventory import SQLiteInventory + + +def lookup(api, barcode="036000291452", *, user=USER, **params): + return api.client.get( + INVENTORY + "/barcode", + params={"barcode": barcode, **params}, + headers=member_context(user), + ) + + +def test_reader_can_lookup_but_only_current_manager_can_change_or_recover(api): + api.user(USER, True) + product = register(api, "product", "Soap", "piece") + result = lookup(api) + assert result.status_code == 200, result.text + assert result.json() == { + "barcode": "00036000291452", + "may_manage": True, + "association": None, + "product": None, + } + response = post(api, "link", "link-barcode", barcode="036000291452", product_id=product) + assert response.status_code == 200, response.text + receipt = response.json() + association = receipt["result"] + found = lookup(api, "0036000291452").json() + assert found["association"] == association + assert found["product"]["product_id"] == product and found["product"]["name"] == "Soap" + with api.store.write() as unit: + unit.members.save(Member("viewer", "home", VIEWER, Role.VIEWER, MemberStatus.ACTIVE, 1), 0) + api.user(VIEWER) + assert lookup(api, user=VIEWER).json() == {**found, "may_manage": False} + for action in ("link-barcode", "remove-barcode"): + payload = {"barcode": "036000291452", "product_id": product} + if action == "remove-barcode": + payload["association_id"] = association["association_id"] + assert post(api, "forbidden", action, user=VIEWER, **payload).status_code == 403 + assert ( + api.client.get( + INVENTORY + "/requests/inventory." + action + "/link", + headers=member_context(VIEWER), + ).status_code + == 403 + ) + api.user(USER, True) + assert ( + post(api, "replay", "link-barcode", barcode="036000291452", product_id=product).json()[ + "code" + ] + == "inventory_barcode_linked" + ) + assert ( + api.client.get( + INVENTORY + "/requests/inventory.link-barcode/link", headers=member_context(USER) + ).json() + == receipt + ) + assert post(api, "remove", "remove-barcode", **association).status_code == 200 + assert lookup(api).json()["product"] is None + assert ( + post( + api, "missing", "link-barcode", barcode="036000291452", product_id="missing" + ).status_code + == 404 + ) + + +@pytest.mark.parametrize( + "barcode", ["96385075", "000000000", "036000291452 ", "96385074", 36000291452] +) +def test_invalid_code_never_queries_or_writes_a_link(api, monkeypatch, barcode): + api.user(USER, True) + product = register(api, "product", "Soap", "piece") + + def unexpected(*_): + raise AssertionError("An invalid barcode reached storage") + + monkeypatch.setattr(SQLiteInventory, "barcode", unexpected) + if isinstance(barcode, str): + assert lookup(api, barcode).status_code == 422 + assert ( + post(api, "invalid", "link-barcode", barcode=barcode, product_id=product).status_code == 422 + ) + + +def test_lookup_unavailability_is_distinct_and_read_retry_retains_the_same_key(api, monkeypatch): + api.user(USER, True) + + def fail(*_): + raise StorageFailure("synthetic_barcode_storage") + + with monkeypatch.context() as patch: + patch.setattr(SQLiteInventory, "barcode", fail) + unavailable = lookup(api) + assert unavailable.status_code == 500 + assert unavailable.json()["code"] == "internal_error" + assert lookup(api).json()["product"] is None + assert lookup(api, household_id="foreign").status_code == 422 + assert api.client.get(INVENTORY + "/barcode", headers=member_context(USER)).status_code == 422 diff --git a/tests/backend/test_inventory_barcodes.py b/tests/backend/test_inventory_barcodes.py new file mode 100644 index 0000000..31a4c9f --- /dev/null +++ b/tests/backend/test_inventory_barcodes.py @@ -0,0 +1,261 @@ +"""The barcode companion uses real protected commands, SQLite writers and activation.""" + +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_household_commands import Clock +from test_inventory_catalog_storage import register, setup +from test_rewards_storage import race + +from domus.application.fixed_materialization import MaintenanceScope +from domus.application.inventory import CatalogAction +from domus.application.inventory_queries import InventoryQueries +from domus.domain.errors import Conflict, DatabaseRejected, InvalidInput, StorageFailure +from domus.domain.inventory import BarcodeAssociation, BaseUnit, canonical_gtin +from domus.domain.storage import Installation +from domus.infrastructure import sqlite as storage +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_receipts import SQLiteReceipts +from domus.infrastructure.sqlite_restoration import SQLiteRestorations +from domus.infrastructure.sqlite_snapshots import SQLiteSnapshots +from domus.infrastructure.task_cursor import TaskCursor + + +def queries(store, commands): + return InventoryQueries( + store, + MaintenanceScope(store.installation, "home"), + commands.actor.current(), + TaskCursor(Clock(), b"b" * 32), + ) + + +@pytest.mark.parametrize("barcode", ["96385074", "036000291452", "0036000291452", "00036000291452"]) +def test_each_supported_printed_length_keeps_zeroes_and_validates_its_digit(barcode): + canonical = canonical_gtin(barcode) + assert canonical == barcode.zfill(14) + assert canonical_gtin(canonical) == canonical + invalid = barcode[:-1] + str((int(barcode[-1]) + 1) % 10) + with pytest.raises(InvalidInput, match="invalid_inventory_barcode"): + canonical_gtin(invalid) + + +@pytest.mark.parametrize( + "barcode", + [ + None, + 36000291452, + "", + "1234567", + "123456789", + "1234567890", + "12345678901", + "0" * 15, + " 96385074", + "96385074 ", + "96385074", + "9638507x", + "9638507\n", + ], +) +def test_reject_original_shape_before_any_canonical_padding(barcode): + with pytest.raises(InvalidInput, match="invalid_inventory_barcode"): + canonical_gtin(barcode) + + +def test_association_requires_the_canonical_key_and_valid_stable_identifiers(): + with pytest.raises(InvalidInput, match="invalid_inventory_barcode"): + BarcodeAssociation("036000291452", "link", "product") + for association, product in (("", "product"), ("link", "")): + with pytest.raises(InvalidInput): + BarcodeAssociation("00036000291452", association, product) + + +def test_equivalent_lookup_and_original_replay_preserve_product_and_stock(tmp_path): + _, store, commands = setup(tmp_path) + product = register(commands) + service = queries(store, commands) + assert service.barcode("036000291452").product is None + first = commands.link_barcode("link", "036000291452", product) + assert commands.link_barcode("link", "00036000291452", product) == first + assert commands.original(CatalogAction.LINK_BARCODE, "link", commands.actor.current()) == first + result = service.barcode("0036000291452") + assert result.barcode == "00036000291452" and result.may_manage + assert result.product.product_id == product and result.product.name == "Oil" + assert result.association.association_id == first.result.decode()["association_id"] + assert ( + replace(commands, transactions=SQLiteDatabase(store.path, store.installation)).original( + CatalogAction.LINK_BARCODE, "link", commands.actor.current() + ) + == first + ) + with store.read() as unit: + assert unit.inventory.barcode("other", result.barcode) is None + assert unit.inventory.balance("home", result.product.reference_id) == 0 + other = commands.register("other", "Other product", BaseUnit.PIECE).result.decode()[ + "product_id" + ] + with pytest.raises(Conflict, match="idempotency_conflict"): + commands.link_barcode("link", result.barcode, other) + + +def test_two_equivalent_writers_have_one_winner_and_stale_removal_preserves_relink(tmp_path): + _, store, commands = setup(tmp_path) + products = [ + register(commands), + commands.register("second", "Tea", BaseUnit.GRAM).result.decode()["product_id"], + ] + other = replace(commands, transactions=SQLiteDatabase(store.path, store.installation)) + + def attempt(service, key, code, product): + try: + return service.link_barcode(key, code, product) + except Conflict as error: + return error.code + + results = race( + lambda: attempt(commands, "one", "036000291452", products[0]), + lambda: attempt(other, "two", "00036000291452", products[1]), + ) + assert sum(result == "inventory_barcode_linked" for result in results) == 1 + winner = next(result for result in results if result != "inventory_barcode_linked") + association = winner.result.decode() + removed = commands.remove_barcode("remove", **association) + assert commands.remove_barcode("remove", **association) == removed + replacement = commands.link_barcode( + "replacement", association["barcode"], association["product_id"] + ) + assert replacement.result.decode()["association_id"] != association["association_id"] + with pytest.raises(Conflict, match="inventory_barcode_changed"): + commands.remove_barcode("stale", **association) + assert ( + queries(store, commands).barcode(association["barcode"]).association.association_id + == replacement.result.decode()["association_id"] + ) + with pytest.raises(Conflict, match="inventory_barcode_changed"): + commands.remove_barcode( + "wrong-product", + association["barcode"], + "missing", + replacement.result.decode()["association_id"], + ) + + +def test_late_receipt_failure_rolls_back_the_link_and_removal(tmp_path, monkeypatch): + _, store, commands = setup(tmp_path) + product = register(commands) + + def fail(*_): + raise StorageFailure("synthetic_receipt_failure") + + with monkeypatch.context() as patch: + patch.setattr(SQLiteReceipts, "add", fail) + with pytest.raises(StorageFailure, match="synthetic_receipt_failure"): + commands.link_barcode("link", "036000291452", product) + assert queries(store, commands).barcode("036000291452").association is None + receipt = commands.link_barcode("link", "036000291452", product) + with monkeypatch.context() as patch: + patch.setattr(SQLiteReceipts, "add", fail) + with pytest.raises(StorageFailure, match="synthetic_receipt_failure"): + commands.remove_barcode("remove", **receipt.result.decode()) + assert queries(store, commands).barcode("036000291452").association is not None + assert commands.remove_barcode("remove", **receipt.result.decode()).result == receipt.result + + +@pytest.mark.parametrize("version", [20, 30, 34]) +def test_upgrade_atomicity_and_compatible_activation_keep_links_and_originals( + tmp_path, monkeypatch, version +): + root = tmp_path / "source" + root.mkdir(mode=0o700) + if version == 34: + _, store, commands = setup(root) + register(commands) + with closing(sqlite3.connect(store.path, autocommit=True)) as db: + db.execute("DROP TABLE inventory_barcodes") + db.execute("PRAGMA user_version=34") + else: + source = ( + "v20-inventory-history-source.sql" if version == 20 else "v30-purchase-store-source.sql" + ) + path = root / "domus.sqlite3" + with closing(sqlite3.connect(path, autocommit=True)) as db: + db.executescript((Path(__file__).parents[1] / "fixtures/sqlite" / source).read_text()) + installation = Installation( + *db.execute("SELECT instance_id,channel FROM installation").fetchone() + ) + path.chmod(0o600) + store = SQLiteDatabase(path, installation) + identity_at(root, store.installation) + with closing(sqlite3.connect(store.path)) as db: + before = { + table: db.execute("SELECT * FROM " + table).fetchall() + for table in ( + "inventory_products", + "inventory_materials", + "inventory_movements", + "receipts", + ) + } + original = store.path.read_bytes() + with monkeypatch.context() as patch: + patch.setattr(storage, "BARCODE_STATEMENT", "invalid SQL") + with pytest.raises(StorageFailure): + store.initialize(require_existing=True) + assert store.path.read_bytes() == original + store.initialize(require_existing=True) + with closing(sqlite3.connect(store.path)) as db: + assert db.execute("PRAGMA user_version").fetchone() == (35,) + assert db.execute("PRAGMA foreign_key_check").fetchall() == [] + for table, rows in before.items(): + current = db.execute("SELECT * FROM " + table).fetchall() + if rows: + assert [row[: len(rows[0])] for row in current] == rows + else: + assert current == [] + if version != 34: + return + product = before["inventory_products"][0][1] + receipt = commands.link_barcode("link", "036000291452", product) + archive, target = tmp_path / "archive", tmp_path / "prepared" + snapshotter = SQLiteSnapshots(store, archive, store.installation, Clock()) + checkpoint = snapshotter.create("barcode") + commands.remove_barcode("remove", **receipt.result.decode()) + SQLiteRestorations(store, archive, target, store.installation, Clock(), checkpoint).prepare( + "restore" + ) + assert SQLiteActivation(root, store.installation, Clock(), target).activate().state == "active" + restored = open_storage(root, "edge") + try: + recovered = replace(commands, transactions=restored.database) + assert ( + recovered.original( + CatalogAction.LINK_BARCODE, "link", recovered.actor.current() + ).operation_id + == receipt.operation_id + ) + assert ( + queries(restored.database, recovered).barcode("036000291452").product.product_id + == product + ) + finally: + restored.close() + + +@pytest.mark.parametrize( + "column,value", [("barcode", "00036000291453"), ("association_id", "invalid id")] +) +def test_snapshot_rejects_malformed_association_records(tmp_path, column, value): + _, store, commands = setup(tmp_path) + product = register(commands) + commands.link_barcode("link", "036000291452", product) + with closing(sqlite3.connect(store.path, autocommit=True)) as db: + db.execute("UPDATE inventory_barcodes SET " + column + "=?", (value,)) + with pytest.raises(DatabaseRejected, match="invalid_snapshot_records"): + SQLiteSnapshots(store, tmp_path / "archive", store.installation, Clock()).create("corrupt") diff --git a/tests/backend/test_inventory_catalog_storage.py b/tests/backend/test_inventory_catalog_storage.py index d85b4e6..840612b 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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 b938fca..41ee861 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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 1091fe6..803e0b8 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() == (34,) + assert connection.execute("PRAGMA user_version").fetchone() == (35,) 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 57d59db..717cc34 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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 == 34 + assert snapshots.create("valid").schema_version == 35 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 e04b8cd..7465ae1 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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 c10043d..8f3d494 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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 7d4c9fb..bb63e3d 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() == (34,) + assert connection.execute("PRAGMA user_version").fetchone() == (35,) 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 == 34 + assert checkpoint.schema_version == 35 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 6e168f4..7699a21 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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 ba2ac82..efd1142 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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 ae241a3..22e1501 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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 387e736..43e9531 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 - == 34 + == 35 ) diff --git a/tests/backend/test_recurrence_lifecycle_migration.py b/tests/backend/test_recurrence_lifecycle_migration.py index 0486046..cd354d4 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] == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 35 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 == 34 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 35 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) == 34 + assert _verify_database(connection, restarted, previous=False) == 35 assert facts(store.path, tables) == before diff --git a/tests/backend/test_restore_source.py b/tests/backend/test_restore_source.py index 105894f..16d88ec 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, 34, None, None) + assert result.source == RestoreSource(store.installation, 35, 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 == 34 + assert prepared.source.schema_version == 35 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 b72d216..26b7860 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() == (34,) + assert connection.execute("PRAGMA user_version").fetchone() == (35,) 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 addf9ef..e0e3cc3 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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 d2ab2e6..895c1da 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() == (34,) + assert db.execute("PRAGMA user_version").fetchone() == (35,) 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 b387c51..3f5163e 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 == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 35 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 6cb8cda..bb647db 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] == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 35 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 444fc9c..2f929ae 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] == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 35 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 == 34 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 35 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 4ca5368..2108bee 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 == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 35 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 1727d9f..cc4152a 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] == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 35 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 13431f8..57727f9 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 == 34 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 35 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 - == 34 + == 35 ) diff --git a/tests/backend/test_sqlite_snapshots.py b/tests/backend/test_sqlite_snapshots.py index 51b89a2..47eed9e 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 == 34 + result.schema_version == 35 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 e331d8a..b91b1ca 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 == 34 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 35 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] == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 35 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 67a826a..25a1993 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 == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 35 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 == 34 + assert checkpoint.schema_version == 35 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 - == 34 + == 35 ) finally: selected.close() diff --git a/tests/backend/test_sqlite_task_reviews.py b/tests/backend/test_sqlite_task_reviews.py index 4ff9574..e06e722 100644 --- a/tests/backend/test_sqlite_task_reviews.py +++ b/tests/backend/test_sqlite_task_reviews.py @@ -68,6 +68,7 @@ def test_original_schema6_migration_preserves_rows_and_projects_existing_cause(t "inventory_effects", "inventory_movements", "inventory_products", + "inventory_barcodes", "inventory_replenishment", "shopping_purchases", "shopping_receipts", @@ -95,7 +96,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] == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 35 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 @@ -365,7 +366,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 - == 34 + == 35 ) finally: selected.close() diff --git a/tests/backend/test_task_categories.py b/tests/backend/test_task_categories.py index f7bd2d0..b93cf43 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() == (34,) + assert connection.execute("PRAGMA user_version").fetchone() == (35,) 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 3d14061..b4dfd8b 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 == 34 + assert prepared.source.schema_version == checkpoint.schema_version == 35 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/python/test_ci_contract.py b/tests/python/test_ci_contract.py index 28bb0cf..f84f03d 100644 --- a/tests/python/test_ci_contract.py +++ b/tests/python/test_ci_contract.py @@ -373,10 +373,10 @@ def test_both_cpu_images_run_all_actual_household_browser_journeys() -> None: audit = next( step for step in steps - if step.get("name") == "Require all sixty-four actual-image household journeys" + if step.get("name") == "Require all sixty-six actual-image household journeys" ) assert all(field in audit["run"] for field in ["expected", "unexpected", "skipped", "flaky"]) - assert "expected']==64" in audit["run"] + assert "expected']==66" in audit["run"] cleanup = next( step for step in steps if step.get("name") == "Require no surviving image browser fixtures" ) From 96252c93587e4e68838d9adea96d42d6351f309f Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 17:00:33 +0100 Subject: [PATCH 03/16] chore(edge): pin manual barcode candidate Edge.52 --- addon-edge/CHANGELOG.md | 7 ++++ addon-edge/DOCS.md | 13 ++++++- addon-edge/Dockerfile | 8 ++--- addon-edge/README.md | 6 +++- addon-edge/artifact.json | 36 ++++++++++---------- addon-edge/config.yaml | 3 +- docs/evidence/local-barcode-qualification.md | 15 ++++++++ docs/installation-home-assistant.md | 8 ++++- tests/backend/test_app_package.py | 17 ++++----- 9 files changed, 79 insertions(+), 34 deletions(-) diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md index 5f20554..d9ceaf7 100644 --- a/addon-edge/CHANGELOG.md +++ b/addon-edge/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 0.0.0-edge.52 + +- Find a local household product from its printed GTIN barcode digits. +- Review a product association or removal before confirming, with current conflict recovery. +- Retain entered digits through failed reads and recover original writes after interruption. +- Migrate inventory from supported earlier schemas to schema 35. Keep the previous compatible image and cold data checkpoint for rollback. + ## 0.0.0-edge.51 - Refresh the task list and selected detail together after a competing progress update. diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md index fb0649e..942bfca 100644 --- a/addon-edge/DOCS.md +++ b/addon-edge/DOCS.md @@ -1,6 +1,6 @@ # Installation and operation -Edge 0.0.0-edge.51 packages the immutable runtime declared in +Edge 0.0.0-edge.52 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 @@ -38,6 +38,17 @@ A competing update retains your proposal for **Review current task** and a separate save. The list and selected detail refresh together after a competing progress update. **Check saved request** recovers an interrupted progress change. +In Inventory, enter the digits below a barcode and choose **Find product**. +Keep leading zeroes. Supported GTIN values have 8, 12, 13 or 14 digits with a +valid check digit. A match offers **Open product stock**. An inventory manager +can choose a Pantry product, review its code and confirm the association. +Review and remove the current association before choosing a replacement. +Use **Retry barcode lookup** after an unavailable read or **Recover original +request** after an unconfirmed write. + +Edge.52 uses SQLite schema 35 and is listed in `breaking_versions`. +Keep a compatible image together with its cold schema-34 data for rollback. + Edge.47 completes explicit runtime cleanup when Home Assistant requests Stop. Workers finish before identity disposal and installation-lease release. Standalone shutdown reports its bounded delegated-grant cleanup result in the server log. diff --git a/addon-edge/Dockerfile b/addon-edge/Dockerfile index b48cd43..648920e 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=4f79b75d65835037a51b51e3742cd372bc45edfe -ARG DOMUS_SOURCE_SHA256=b57247ac5e62686f8ff42b1ac71cbcde5e47ea54ff873b543077db0102e865dc +ARG DOMUS_SOURCE_COMMIT=3751c4e1650f5de5433bcbefe228260c0b07753b +ARG DOMUS_SOURCE_SHA256=db5d9e29761e7ab22e79bd04c51e6d4e26eac73a303eeb8c64cdaa330b0fcb9d 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.51 +ARG BUILD_VERSION=0.0.0-edge.52 ARG BUILD_ARCH -ARG DOMUS_SOURCE_COMMIT=4f79b75d65835037a51b51e3742cd372bc45edfe +ARG DOMUS_SOURCE_COMMIT=3751c4e1650f5de5433bcbefe228260c0b07753b 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 ea2e0d9..3a2ad0d 100644 --- a/addon-edge/README.md +++ b/addon-edge/README.md @@ -28,7 +28,11 @@ explicit conflict review and recovery of the original progress request. Edge.51 refreshes both the list and detail after a competing progress update and keeps the mobile task layout within the available width. -This candidate uses SQLite schema 34. Keep a +Edge.52 finds household products from manually entered barcode digits. Inventory +managers review a local product association or its removal before confirming. +Original-request recovery and current conflict review retain the entered code. + +This candidate uses SQLite schema 35. Keep a compatible image and cold data backup before upgrading a previous preview. See [installation and operation](https://github.com/vypdev/domus/blob/ac843a9a5c23d411ff11dcbd83d32256af2f5daa/addon-edge/DOCS.md) for the source pin and rollback instructions. diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json index 7bb84af..157d4ec 100644 --- a/addon-edge/artifact.json +++ b/addon-edge/artifact.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, - "version": "0.0.0-edge.51", - "sourceCommit": "4f79b75d65835037a51b51e3742cd372bc45edfe", - "sourceArchiveSHA256": "b57247ac5e62686f8ff42b1ac71cbcde5e47ea54ff873b543077db0102e865dc", - "storageSchema": 34, - "wheelSHA256": "3fe64c5c5d4d21d6c65538f276bf18805c44d04d084db57d964599b36d48ff0f", + "version": "0.0.0-edge.52", + "sourceCommit": "3751c4e1650f5de5433bcbefe228260c0b07753b", + "sourceArchiveSHA256": "db5d9e29761e7ab22e79bd04c51e6d4e26eac73a303eeb8c64cdaa330b0fcb9d", + "storageSchema": 35, + "wheelSHA256": "2038b6218c8b2f5371e4cd5797a03af1274b9de8c17b698a69e3d59bb5969975", "pythonFiles": { "domus/__init__.py": "7182c88b92234b4328f94497f4e70222d4390d8093e4b62893dfa78ac5530ac6", "domus/application/__init__.py": "1e8c0c87bf2a8ca947112543070583c0cc55d9d40b56eab0d86ed59a4ec1e82c", @@ -38,9 +38,9 @@ "domus/application/household_queries.py": "d68db5e792eaeaac07bb1dcb232f84ee573be42c071ae2e3567b32482bb4e27d", "domus/application/household_roster.py": "32ff065c1aa94086aa0390b5c4f3834a5a2e5319f2c26bd8f20af887bf051928", "domus/application/identity_ports.py": "aebf50fc433fa1c77bacf2bb9e35fdde8c746069b567154de01eaf9980c49075", - "domus/application/inventory.py": "0723c4697ca7668b1d3a66b33aa2fba65c0bf5179faee918b5f4a073ddfe5dc1", - "domus/application/inventory_ports.py": "b0a04487925b2714702ce2737051b334949d7df09baa1e2ae29931b4c7df3d68", - "domus/application/inventory_queries.py": "016ebd6b8d4e6db7ec2cdf478d7e71cfdc575608f4fabe7393ddc695742a2b99", + "domus/application/inventory.py": "de20d26996c091f19f96ec4b306c3395a5a4f853820b8866902c8ef8016e8c3b", + "domus/application/inventory_ports.py": "504917eaa74987f880b20402bc549832b55c440767d581e36e829390a0e3f208", + "domus/application/inventory_queries.py": "6af01b6860c1a73176bae59817b3d9e50cb9e8f6b980f6cdc8818cfae60a2ae8", "domus/application/member_commands.py": "d3e93982d2e42d9a57771269ec0ccd4692fcd196189922bb09e7b0398b924649", "domus/application/member_profile_access.py": "c3af66244b9b10a43848e2422f9d662390f4ffd557440d9eae0e0a45d6e4b8a4", "domus/application/member_profile_commands.py": "cee8b699d2774056fe8620c22befb369193c2e3acec7fe861c4555540ffdbcc8", @@ -112,7 +112,7 @@ "domus/domain/fold_policy.py": "fb938ee4cfae747b569a074d2be4e29ed3024012e09ef7645909a7f86122b2c4", "domus/domain/generations.py": "bd8d665c7b6e832f881784c07475d2b8911c08d0894cf8e125681a9f27e1ba97", "domus/domain/identity.py": "3f30a61e1de77a7457f131e8e8371b86ac2ccd3e589060429d091624ee1e75ed", - "domus/domain/inventory.py": "d2e559cfc75fbe2557b0112cd7e2b75b05ac8b8b54dff8bbea7131d7d0b98c0c", + "domus/domain/inventory.py": "2413be298a6c6d0c4413f73cf3e9fc27bc6c6a79711d352742fcd47fd36b3a8c", "domus/domain/member_profiles.py": "2790ca55a7b37a390d006165a44520085e1ff513783b9cf1a7b681435b8ae4d2", "domus/domain/member_sources.py": "b5e9d19d501d3d5dd5caf5b4ce945d4c3ff71b1967e92bd8933f26661a416c01", "domus/domain/nominal_recurrence.py": "2c3678f220a311b8b08e6cad0d146a1a68135b5fd2a5c0d8ab9ed809fe47d8c1", @@ -162,11 +162,11 @@ "domus/entrypoints/household_http.py": "37e948848115bfa8714c9cccc50058389114f2e665cad965a66964b0dcd098c8", "domus/entrypoints/http.py": "5fe33029b7ca04aae3f41fde9e8e7c517f48cff65d3cc3ac5dcb08b25a26a42b", "domus/entrypoints/http_contract.py": "613be310d4ff6a6c7e2a699c20f1c4a142d0b34073629884e58e973c4b040039", - "domus/entrypoints/http_errors.py": "76c3905115553a1702eb7cd911a5f8ca0b2ed1c8a7b42b6ba0420ca96752e36f", + "domus/entrypoints/http_errors.py": "c4f3d19889750bca29a13aee7528299883782e50a5ae3378e691d79e8faf7ded", "domus/entrypoints/ingress_boundary.py": "1aa1d684b8625464b5d36d272f71d94b4cd32b84819ff8765a821c9a722f8f28", "domus/entrypoints/ingress_http.py": "f6557eb5481d132131f66ad7691e30c223c63a66a6f0ae5754c9fba3bc7f3626", - "domus/entrypoints/inventory_http.py": "a58e114de6ff684f6d7d1a93f7f4cb316b8ffa60b0c662733df2c1fd70c2ab6e", - "domus/entrypoints/native_http.py": "75a7d8c15afaa9ce82e627daa561a76e216546f627319563e032a770dc8d7fdc", + "domus/entrypoints/inventory_http.py": "507873935dc9ed813c189b47a7ddc581802ceae854f555533e1e94a4046bb34d", + "domus/entrypoints/native_http.py": "6c4471c6468b64d9f38e1c74e0338fae9eaf0dbbf73ba8b93a9f868317a220fc", "domus/entrypoints/openapi.py": "01a3fab9e5890ebcc1fb9c70bce9ced43d45b9190afd134db7dd45e0c5eb28f1", "domus/entrypoints/point_allocation_http.py": "7339c88c083206c0778885b55793c80af219b15af7004c5a51d34dbc28f4da5c", "domus/entrypoints/recurrence_dto.py": "094e6f64e1f963bfb053e830b214eed1189258e4f0eb8ff15ddba1f059649a1a", @@ -197,7 +197,7 @@ "domus/infrastructure/recurrence_worker.py": "23f76be62ed3ce5ddd557338d7e553d818001f1b3083e6e2f17b1e53723297b0", "domus/infrastructure/restore_source.py": "71917a2db52f5f6794504fd8caa7fd23b0732e8328760c728ea3f082acd2d203", "domus/infrastructure/session_access.py": "1e8bc8d44b60d985da7b44d7bb75fd21bb05f3a45ec38dc7031eff1a2709197d", - "domus/infrastructure/sqlite.py": "25b78ac319fc05f089b87a2484120a57cfc9aaff227a35557895bd9db6893729", + "domus/infrastructure/sqlite.py": "fe8fc5fb8bf95bf11940302b91ed314e622c9e0ba60c2f8806403f43af6ebc1e", "domus/infrastructure/sqlite_activation.py": "eabd490e86eab9dec76104d7d65c687133b8768a0ec8679e6cca97ba8616ded2", "domus/infrastructure/sqlite_automation_controls.py": "8f783d8475a1a16d470ad7c15cb3576e1b60e2176724ecba68634bee8e68366c", "domus/infrastructure/sqlite_automation_drafts.py": "5d56d727bc1653110944946a5159b72ea6310ad993427fbe6667667ec71d3986", @@ -205,7 +205,7 @@ "domus/infrastructure/sqlite_calendar_preferences.py": "0e10804e9571a885518868b5bcbb69ad4eb1d006cafc33bf8b563e7067e69a4e", "domus/infrastructure/sqlite_history.py": "e7f8d4f2b79aed851a4056364f67d1c7806c52d011b46c597968bea86dd1d144", "domus/infrastructure/sqlite_identity.py": "2c07453984455a45f0ef6cd7bac775e1ad3673b8e8a3e450d419df5591f2beeb", - "domus/infrastructure/sqlite_inventory.py": "ca2166eb4c8f5cdf6c0ffbf2a3dd2518af2df2842299355fadefe25b172d6fbe", + "domus/infrastructure/sqlite_inventory.py": "df5f764b7fbcb4ee4f5e6742a8b34e1207063e1003418daf696abf14876a7fe3", "domus/infrastructure/sqlite_member_profile_schema.py": "88ed7ea8572f3e625d1ca8f114a750fbea02fc4ffe165fe12bc4d68307f7764c", "domus/infrastructure/sqlite_member_profiles.py": "db7be5e4209d408f2fd780f684ba3a0a76267347fd2cbc0521a33c06e5453ec5", "domus/infrastructure/sqlite_point_allocations.py": "e1aa5075544bf5faf16dac92fc0655c82fc65a3b5495fc916dc33769168c8bd5", @@ -223,7 +223,7 @@ "domus/infrastructure/sqlite_restoration.py": "2f28207974082bdee48d72afdca08956e077b957377b1a2894b3eb6f4e6c224a", "domus/infrastructure/sqlite_rewards.py": "91a9d549198d523d5cd12beefa31cc2d947dc9fe55af245c8cb12017ff1cad5d", "domus/infrastructure/sqlite_shopping.py": "521e335ae6419f6cd1ee8286c3c6689932ae06330ef370a666581ec915b29688", - "domus/infrastructure/sqlite_snapshots.py": "f500fd2566010fc52168a5482fd9c496ffe758e75e7f4a953bb4bef11d91eedf", + "domus/infrastructure/sqlite_snapshots.py": "54c0499faa5bef6d2230c26760e1a8e09a7c9ab75fe50370ff28b23d0f049eda", "domus/infrastructure/sqlite_task_categories.py": "88adfacc0cbb4408ae902f0dceb4db8cf138073e98314a92fb85d881184e2e3d", "domus/infrastructure/sqlite_task_history.py": "d701c2ce24f8116976b524130dfd6406f0419144b9b68fed7341f18929f77aaf", "domus/infrastructure/sqlite_task_integrity.py": "982435ff6b6742506c98204292893744aff7b1d64645762eba131e7951e4d09c", @@ -239,9 +239,9 @@ "domus/infrastructure/task_materials.py": "d5d2934e36f290c7bf44b473392f014eab8749f1f3b3d26a3402079e65d2818f" }, "uiFiles": { - ".vite/manifest.json": "5cc6cb5d72390640c8e281eba20c9ff8c782c7f5c6e103ff39a6257fde28b74b", + ".vite/manifest.json": "20fb5f3930922339ac18f422befcad26d39a3e48168ae034bdd075c858d933a8", + "assets/index-CNI5WB-O.js": "b394b8038910cc30dfc0b92a864641bad49d25edaa8392273fc0a91951950c28", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "assets/index-lAPOs-kN.js": "1696cc56f023da1760f9147d175e64caa65baa08be89024a85761776b88b38ff", - "index.html": "c9110bf2ef5b3294a64e67513f27b7f5baee3a999344590d479c5b15ff95ac33" + "index.html": "d4bd63a737c246f3511c31685acdd1e1ec0e012ed82f3c1ac42878d52159c7ef" } } diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml index 70d57f3..74cd7c9 100644 --- a/addon-edge/config.yaml +++ b/addon-edge/config.yaml @@ -1,5 +1,5 @@ name: Domus Edge -version: "0.0.0-edge.51" +version: "0.0.0-edge.52" slug: domus_edge description: Development preview of the local Domus household application url: https://github.com/vypdev/domus @@ -19,6 +19,7 @@ breaking_versions: - "0.0.0-edge.33" - "0.0.0-edge.38" - "0.0.0-edge.42" + - "0.0.0-edge.52" init: true timeout: 30 backup: cold diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index c7cb271..c78b62f 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -44,3 +44,18 @@ journeys on each architecture, including the two new barcode journeys. SQLite schema 35 adds the local association index. Keep the previous compatible image together with its cold schema-34 state for rollback. Compatible schema-35 restoration retains current associations and original historical evidence. + +## Immutable candidate + +Edge.52 packages runtime source `3751c4e1650f5de5433bcbefe228260c0b07753b`. +The source archive SHA-256 is +`db5d9e29761e7ab22e79bd04c51e6d4e26eac73a303eeb8c64cdaa330b0fcb9d`. +The independently measured Linux wheel SHA-256 is +`2038b6218c8b2f5371e4cd5797a03af1274b9de8c17b698a69e3d59bb5969975`. +All 231 Python modules match Git, the wheel and the installed Linux builder. +The four compiled UI files match the local and Linux builds, and the normal +local wheel matches the Linux wheel exactly. The artifact declaration records +those measured bytes. [Edge artifact](../../addon-edge/artifact.json) + +Both CPU image campaigns, installed-owner acceptance and final same-head CI +and review are tracked in the increment's pull request. [PR #145](https://github.com/vypdev/domus/pull/145) diff --git a/docs/installation-home-assistant.md b/docs/installation-home-assistant.md index 8bb0cef..f5b2351 100644 --- a/docs/installation-home-assistant.md +++ b/docs/installation-home-assistant.md @@ -7,6 +7,12 @@ Install Domus Edge through the durable Supervisor repository source offered by Supervisor to the artifact declaration. It records the preview version, source commit, source archive and installed file hashes. [Edge artifact](../addon-edge/artifact.json) +Edge.52 finds products from manually entered barcode digits in Inventory. +Managers review the chosen product and code before confirming an association +or removal. A failed read offers a retry with the draft retained, and original +request recovery handles an unconfirmed write. +[Qualification](evidence/local-barcode-qualification.md) + Edge.51 lets members start, block and unblock eligible work from Tasks. It keeps the blocking reason through conflict review and original-request recovery. A competing progress update refreshes both the list and selected detail. @@ -39,7 +45,7 @@ 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 current Edge preview uses SQLite schema 34. Keep a compatible image and +The current Edge preview uses SQLite schema 35. 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. diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py index 97d3081..3de8069 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.51" + assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.52" 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": []} @@ -37,6 +37,7 @@ def test_repository_and_edge_manifest_offer_native_ha_entry_without_user_credent "0.0.0-edge.33", "0.0.0-edge.38", "0.0.0-edge.42", + "0.0.0-edge.52", ] assert set(manifest["arch"]) == {"amd64", "aarch64"} @@ -64,15 +65,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] == "4f79b75d65835037a51b51e3742cd372bc45edfe" + assert commits[0] == "3751c4e1650f5de5433bcbefe228260c0b07753b" assert ( - "DOMUS_SOURCE_SHA256=b57247ac5e62686f8ff42b1ac71cbcde5e47ea54ff873b543077db0102e865dc" + "DOMUS_SOURCE_SHA256=db5d9e29761e7ab22e79bd04c51e6d4e26eac73a303eeb8c64cdaa330b0fcb9d" in source ) - assert "ARG BUILD_VERSION=0.0.0-edge.51" in source + assert "ARG BUILD_VERSION=0.0.0-edge.52" in source candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text()) assert candidate["sourceCommit"] == commits[0] - assert candidate["version"] == "0.0.0-edge.51" + assert candidate["version"] == "0.0.0-edge.52" 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 @@ -149,9 +150,9 @@ def test_edge_artifact_declares_exact_reviewed_runtime_without_rebinding_histori "pythonFiles", "uiFiles", } - assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.51" - assert artifact["sourceCommit"] == "4f79b75d65835037a51b51e3742cd372bc45edfe" - assert artifact["storageSchema"] == 34 + assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.52" + assert artifact["sourceCommit"] == "3751c4e1650f5de5433bcbefe228260c0b07753b" + assert artifact["storageSchema"] == 35 for field in ["sourceArchiveSHA256", "wheelSHA256"]: assert re.fullmatch("[a-f0-9]{64}", artifact[field]) assert len(artifact["pythonFiles"]) == 231 and len(artifact["uiFiles"]) == 4 From 74e607fa68a171055ec1a401d650469235dd9562 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 17:18:20 +0100 Subject: [PATCH 04/16] test(ci): align current image schema and capture authorization bodies before navigation --- frontend/tests/e2e/administration.spec.ts | 10 +++++----- tests/containers/administration_rollback_fixture.py | 2 +- tests/containers/restore_fixture.py | 2 +- tests/containers/test_administration_image.py | 8 ++++---- tests/containers/test_app_compatibility.py | 2 +- tests/containers/test_app_image.py | 4 ++-- tests/containers/test_recurrence_image.py | 2 +- tests/containers/test_relative_recurrence_image.py | 2 +- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/frontend/tests/e2e/administration.spec.ts b/frontend/tests/e2e/administration.spec.ts index 3ef67de..ce90411 100644 --- a/frontend/tests/e2e/administration.spec.ts +++ b/frontend/tests/e2e/administration.spec.ts @@ -111,11 +111,11 @@ 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/authorization',async route=>{ + const upstream=await route.fetch({maxRetries:0,maxRedirects:0}),body=await upstream.body(); + if(upstream.status()===503&&JSON.parse(body.toString('utf8')).code==='storage_busy') + unavailableAuthorization.add(index); + await route.fulfill({response:upstream,body}); }); await candidate.route(base(mode)+'/api/v1/household',async route=>{ if(route.request().method()!=='PUT')return route.continue(); diff --git a/tests/containers/administration_rollback_fixture.py b/tests/containers/administration_rollback_fixture.py index 2de389d..bbd3b73 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 == (34 if phase in ("later", "restored") else 9) + assert SCHEMA_VERSION == (35 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 894d022..5850d4e 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] == 34 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 35 private_layout() print( json.dumps( diff --git a/tests/containers/test_administration_image.py b/tests/containers/test_administration_image.py index c922a01..d8bdb4e 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 == 34 +assert SCHEMA_VERSION == 35 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 == 34 + assert checkpoint.schema_version == 35 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"] == 34 + assert restored["schema"] == refusal["refused_schema"] == 35 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 34) + assert SCHEMA_VERSION == (14 if phase == 'old' else 35) 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 9e731a9..7d39958 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=34 + image, previous_image, data_volume, old_schema, expected_schema=35 ): 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 3d215c9..baaf9ee 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 = 34, + expected_schema: int = 35, ) -> 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"] == 34 + assert activated["activation"]["rollback_snapshot"]["schema_version"] == 35 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 fefb91a..aec20de 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 == 34 +assert SCHEMA_VERSION == 35 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 f3fd8fc..77846d5 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 == 34 +assert SCHEMA_VERSION == 35 class FixtureHuman: def current(self): From 465f780ee37275471a32238fafe7dfb5866dd478 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 17:58:53 +0100 Subject: [PATCH 05/16] fix(inventory): continue barcode search keyboard focus --- docs/evidence/local-barcode-qualification.md | 14 ++++- .../evidence/task-navigation-integration.json | 6 +- frontend/src/presentation/domus-inventory.ts | 23 +++++++- .../tests/e2e/workspace-navigation.spec.ts | 7 ++- frontend/tests/inventory.test.ts | 59 +++++++++++++++++++ 5 files changed, 101 insertions(+), 8 deletions(-) diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index c78b62f..26bf5e9 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -16,6 +16,9 @@ The field preserves malformed input for correction. An unlinked result leads to the existing paginated Pantry cards. A manager chooses a product, reviews its name and code, then separately confirms. A found product opens its existing stock detail. An unavailable read retains the draft and offers an explicit retry. +A submitted search continues keyboard focus to its result or retry control once +the read finishes. A current view owns that continuation and preserves focus +that the user has moved elsewhere. Association writes use the existing atomic commands, journal, original receipts, current grants, CSRF and origin checks. A lost successful response recovers its @@ -35,7 +38,7 @@ the old confirmation. Scope changes retire private facts and drafts. The complete backend campaign passes 5,569 tests with 100% statement and branch coverage globally and across all 231 authored modules. An independent source -coverage audit accepts the report. The complete frontend campaign passes 1,927 +coverage audit accepts the report. The complete frontend campaign passes 1,928 tests with all four metrics at 100% globally and per authored runtime file. All 121 compiled source journeys and 45 rebuilt catalog journeys pass, with zero skipped, unexpected or flaky results. The CPU image gate requires all 66 household @@ -59,3 +62,12 @@ those measured bytes. [Edge artifact](../../addon-edge/artifact.json) Both CPU image campaigns, installed-owner acceptance and final same-head CI and review are tracked in the increment's pull request. [PR #145](https://github.com/vypdev/domus/pull/145) + +## Installed keyboard correction + +The installed Edge.52 candidate reproduced loss of keyboard focus after a +successful lookup. Its disabled input relinquished focus to the document body. +Edge.53 will carry the correction and repeat installed acceptance. The regression +checks found and unlinked results, unavailable retry, retained input, moved focus, +background documents and retired view ownership. Both compiled barcode journeys +require result focus and use the real next Tab to reach product selection. diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json index d1c4029..1332ce3 100644 --- a/docs/evidence/task-navigation-integration.json +++ b/docs/evidence/task-navigation-integration.json @@ -5,10 +5,10 @@ "command": "pnpm build:frontend", "scope": "Compiled household workspace with protected manual automation preview, saved revisions, explicit runs and scoped run history, daily schedule previews and inactive daily drafts, 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. Points-allocation cards inherit the shared raised surface in both color schemes. The Tasks workspace supports planned task assignment, state-permitted release, retained conflict selections and original assignment-request recovery. The Tasks workspace also confirms Start, Block and Unblock, retains a bounded blocking reason through explicit current-task review and recovers the original progress request. Inventory supports manually entered local GTIN lookup, explicit product association and removal review, stale-association recovery and retained original barcode requests.", "actualProductFiles": { - ".vite/manifest.json": "20fb5f3930922339ac18f422befcad26d39a3e48168ae034bdd075c858d933a8", - "assets/index-CNI5WB-O.js": "b394b8038910cc30dfc0b92a864641bad49d25edaa8392273fc0a91951950c28", + ".vite/manifest.json": "9954a8b26e1ed88f36de286a7b1184d5d6f92efe076221a9b8395684e77c2955", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "d4bd63a737c246f3511c31685acdd1e1ec0e012ed82f3c1ac42878d52159c7ef" + "assets/index-g4W3QIWH.js": "57539f4a01ab4e0162da779f058a4d9206a9309cd82c9b123499f6981ff7c48c", + "index.html": "9ac902d7ffb0a2dde0b9e66ce277bd837f388e6355af52cd01367e363e52e10c" }, "localValidation": { "commit": "9a10d8114869be754962953903e773fe8e12c723", diff --git a/frontend/src/presentation/domus-inventory.ts b/frontend/src/presentation/domus-inventory.ts index fb34dc6..97d7fe8 100644 --- a/frontend/src/presentation/domus-inventory.ts +++ b/frontend/src/presentation/domus-inventory.ts @@ -104,7 +104,7 @@ export class DomusInventory extends LitElement { .history {scroll-margin-block-start:68px} .history-content, .location-content, .location-balances {display:grid;gap:12px} .barcode-content, .barcode-review {display:grid;gap:12px;min-width:0} - .barcode-review {scroll-margin-block-start:68px} + .barcode-review, .barcode-result {scroll-margin-block-start:68px} .location-balances {grid-template-columns:repeat(auto-fit,minmax(min(100%,170px),1fr))} .location-stock {border:1px solid var(--line);border-radius:8px;padding:12px;overflow-wrap:anywhere} .location-stock h5 {font-size:inherit;margin:0 0 8px} @@ -132,6 +132,7 @@ export class DomusInventory extends LitElement { private declare barcodeSubmitted: string | null; private declare barcodeInvalid: boolean; private declare barcodeReview: BarcodeReview | null; + private barcodeFocusPending = false; constructor() { super(); @@ -172,6 +173,7 @@ export class DomusInventory extends LitElement { this.barcodeSubmitted = null; this.barcodeInvalid = false; this.barcodeReview = null; + this.barcodeFocusPending = false; } if (previous?.barcode?.lookup !== current?.barcode?.lookup || current?.report?.mayManage !== true) this.barcodeReview = null; @@ -202,6 +204,18 @@ export class DomusInventory extends LitElement { protected updated(changed: PropertyValues): void { if (!changed.has('view')) return; + if (this.barcodeFocusPending && !this.view!.busy) { + const owner = this.view; + const target = this.renderRoot.querySelector(this.barcodeState()?.unavailable + ? '.barcode-search-form vyp-ha-button' : '.barcode-result'); + if (target) { + this.barcodeFocusPending = false; + void this.updateComplete.then(() => { + if (this.view === owner && this.ownerDocument.hasFocus() + && this.ownerDocument.activeElement === this.ownerDocument.body) target.focus(); + }); + } + } const product = this.view?.history?.productId; if (product && product !== changed.get('view')?.history?.productId) this.renderRoot.querySelector('.history')?.focus(); @@ -270,11 +284,13 @@ export class DomusInventory extends LitElement { } catch { this.barcodeInvalid = true; this.barcodeSubmitted = null; + this.barcodeFocusPending = false; void this.updateComplete.then(() => this.renderRoot.querySelector('.barcode-content vyp-ha-field')?.focus()); return; } this.barcodeInvalid = false; this.barcodeReview = null; + this.barcodeFocusPending = true; this.intent({type: 'barcode', barcode: this.barcodeSubmitted}); }}> ${this.submitButton(search?.unavailable ? 'barcodeRetry' : 'barcodeSearch', busy || this.view!.pending)} @@ -293,14 +310,14 @@ export class DomusInventory extends LitElement { .state=${feedbackState({kind: 'loading', message: this.text('barcodeLoading')})}>` : nothing} ${search?.unavailable ? html`` : nothing} - ${lookup && product === null ? html`

${this.text('barcodeUnlinked')}

+ ${lookup && product === null ? html`

${this.text('barcodeUnlinked')}

${manage && lookup.mayManage ? firstProduct ? html`
{ event.preventDefault(); this.renderRoot.querySelector('article[id="product-' + firstProduct.id + '"]')?.focus(); }}>${this.text('barcodeChooseProduct')}` : html`

${this.text('barcodeRegisterProduct')}

` : nothing}` : nothing} ${lookup && (!manage || !lookup.mayManage) ? html`

${this.text('barcodeManagerRequired')}

` : nothing} - ${product ? html`

${this.text('barcodeFound')} ${product.name}

+ ${product ? html`

${this.text('barcodeFound')} ${product.name}

${this.button('barcodeViewStock', () => this.intent({type: 'history', productId: product.id}), busy)} ${manage && lookup!.mayManage && review === null diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index 525764d..6b72909 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -53,8 +53,11 @@ for (const mode of ['native', 'standalone'] as const) { await digits.fill('036000291452'); await digits.press('Enter'); await expect(stock.getByText('Unlinked barcode in this household.', {exact:true})).toBeVisible(); + await expect(stock.locator('.barcode-result')).toBeFocused(); const firstProduct = stock.locator('.products > article').first(); - await stock.getByRole('link', {name:'Choose a product in Pantry below.', exact:true}).press('Enter'); + await page.keyboard.press('Tab'); + await expect(stock.getByRole('link', {name:'Choose a product in Pantry below.', exact:true})).toBeFocused(); + await page.keyboard.press('Enter'); await expect(firstProduct).toBeFocused(); await stock.getByRole('button', {name:'Associate barcode with QA barcode soap', exact:true}).press('Enter'); const review = stock.getByRole('form', {name:'Review barcode association', exact:true}); @@ -121,8 +124,10 @@ for (const mode of ['native', 'standalone'] as const) { await stock.getByRole('button', {name:'Buscar producto', exact:true}).tap(); await expect(stock.getByText('La búsqueda local del código no está disponible. Reintenta la búsqueda o actualiza Inventario.', {exact:true})).toBeVisible(); await expect(spanish).toHaveValue('036000291452'); + await expect(stock.getByRole('button', {name:'Reintentar búsqueda del código', exact:true})).toBeFocused(); await stock.getByRole('button', {name:'Reintentar búsqueda del código', exact:true}).tap(); await expect(stock.getByText('Producto encontrado QA barcode tea', {exact:true})).toBeVisible(); + await expect(stock.locator('.barcode-result')).toBeFocused(); await stock.getByRole('button', {name:'Eliminar asociación del código', exact:true}).tap(); await stock.getByRole('button', {name:'Confirmar retirada del código', exact:true}).tap(); await expect(stock.getByText('Código sin asociación en este hogar.', {exact:true})).toBeVisible(); diff --git a/frontend/tests/inventory.test.ts b/frontend/tests/inventory.test.ts index bed7f47..8d49486 100644 --- a/frontend/tests/inventory.test.ts +++ b/frontend/tests/inventory.test.ts @@ -2143,6 +2143,65 @@ async function barcodeComponent(language: 'en' | 'es' = 'en') { return {...f, field, search, assign, enter}; } +test('a submitted barcode search continues to its result or retry without reclaiming moved focus', async () => { + const foreground = vi.spyOn(document, 'hasFocus').mockReturnValue(true); + const f = await barcodeComponent(); + const loading: InventoryState = {...barcodeView, busy: true, + barcode: {code: barcodeCode, lookup: null, unavailable: false}}; + const begin = async () => { + await f.enter('036000291452'); + f.field()!.focus(); + f.submit(f.search()!); + await f.assign(loading); + expect(document.activeElement).toBe(document.body); + }; + try { + for (const lookup of [barcodeUnlinked, barcodeFound]) { + await begin(); + await f.assign({...barcodeView, barcode: {code: barcodeCode, lookup, unavailable: false}}); + const result = f.root.querySelector('.barcode-result'); + expect(result).not.toBeNull(); + expect(f.root.activeElement).toBe(result); + expect(f.field()!.value).toBe('036000291452'); + } + await begin(); + await f.assign({...loading, busy: false}); + expect(document.activeElement).toBe(document.body); + await f.assign({...loading, busy: false, barcode: {code: barcodeCode, lookup: null, unavailable: true}}); + const retry = f.search()!.querySelector('vyp-ha-button')!; + await retry.updateComplete; + expect(f.root.activeElement).toBe(retry); + expect(retry.shadowRoot!.activeElement).toBe(retry.shadowRoot!.querySelector('button')); + + await begin(); + const moved = document.createElement('button'); + moved.textContent = 'Another workspace action'; + document.body.append(moved); + mounted.push(moved); + moved.focus(); + await f.assign(barcodeView); + expect(document.activeElement).toBe(moved); + + await begin(); + foreground.mockReturnValue(false); + await f.assign(barcodeView); + expect(document.activeElement).toBe(document.body); + foreground.mockReturnValue(true); + await f.assign({...barcodeView}); + expect(document.activeElement).toBe(document.body); + + await begin(); + f.node.view = barcodeView; + await f.node.updateComplete; + f.node.view = {...barcodeView, scope: {...scope, key: 'retired-household'}}; + await f.node.updateComplete; + expect(document.activeElement).toBe(document.body); + expect(f.field()!.value).toBe(''); + } finally { + foreground.mockRestore(); + } +}); + test('barcode lookup selects an existing paginated product and reviews each association write', async () => { const f = await barcodeComponent(); const registration = f.root.querySelector('.registration-form')!; From 3335814472b0e3f14fc9d0eaf0555f12620af25f Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 18:02:22 +0100 Subject: [PATCH 06/16] build(edge): pin verified barcode focus preview 53 --- addon-edge/CHANGELOG.md | 5 +++++ addon-edge/DOCS.md | 5 +++-- addon-edge/Dockerfile | 8 ++++---- addon-edge/README.md | 3 +++ addon-edge/artifact.json | 14 +++++++------- addon-edge/config.yaml | 2 +- docs/evidence/local-barcode-qualification.md | 17 +++++++++++++++-- docs/installation-home-assistant.md | 2 ++ tests/backend/test_app_package.py | 14 +++++++------- 9 files changed, 47 insertions(+), 23 deletions(-) diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md index d9ceaf7..752668c 100644 --- a/addon-edge/CHANGELOG.md +++ b/addon-edge/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 0.0.0-edge.53 + +- Continue keyboard focus to the barcode result or retry control after a submitted search. +- Preserve focus that has moved to another control while the lookup is running. + ## 0.0.0-edge.52 - Find a local household product from its printed GTIN barcode digits. diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md index 942bfca..9c46d74 100644 --- a/addon-edge/DOCS.md +++ b/addon-edge/DOCS.md @@ -1,6 +1,6 @@ # Installation and operation -Edge 0.0.0-edge.52 packages the immutable runtime declared in +Edge 0.0.0-edge.53 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 @@ -44,7 +44,8 @@ valid check digit. A match offers **Open product stock**. An inventory manager can choose a Pantry product, review its code and confirm the association. Review and remove the current association before choosing a replacement. Use **Retry barcode lookup** after an unavailable read or **Recover original -request** after an unconfirmed write. +request** after an unconfirmed write. A submitted search continues keyboard +focus to its result or retry control when the read finishes. Edge.52 uses SQLite schema 35 and is listed in `breaking_versions`. Keep a compatible image together with its cold schema-34 data for rollback. diff --git a/addon-edge/Dockerfile b/addon-edge/Dockerfile index 648920e..8293ab9 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=3751c4e1650f5de5433bcbefe228260c0b07753b -ARG DOMUS_SOURCE_SHA256=db5d9e29761e7ab22e79bd04c51e6d4e26eac73a303eeb8c64cdaa330b0fcb9d +ARG DOMUS_SOURCE_COMMIT=465f780ee37275471a32238fafe7dfb5866dd478 +ARG DOMUS_SOURCE_SHA256=7d9bc569a0cdb962ad205037eea159cc7bbe3317aa03a00454b83bf00c4839e4 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.52 +ARG BUILD_VERSION=0.0.0-edge.53 ARG BUILD_ARCH -ARG DOMUS_SOURCE_COMMIT=3751c4e1650f5de5433bcbefe228260c0b07753b +ARG DOMUS_SOURCE_COMMIT=465f780ee37275471a32238fafe7dfb5866dd478 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 3a2ad0d..00acb58 100644 --- a/addon-edge/README.md +++ b/addon-edge/README.md @@ -32,6 +32,9 @@ Edge.52 finds household products from manually entered barcode digits. Inventory managers review a local product association or its removal before confirming. Original-request recovery and current conflict review retain the entered code. +Edge.53 continues keyboard focus to the barcode result or retry control after a +submitted search. + This candidate uses SQLite schema 35. Keep a compatible image and cold data backup before upgrading a previous preview. See [installation and operation](https://github.com/vypdev/domus/blob/ac843a9a5c23d411ff11dcbd83d32256af2f5daa/addon-edge/DOCS.md) for the source pin and rollback diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json index 157d4ec..6757616 100644 --- a/addon-edge/artifact.json +++ b/addon-edge/artifact.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, - "version": "0.0.0-edge.52", - "sourceCommit": "3751c4e1650f5de5433bcbefe228260c0b07753b", - "sourceArchiveSHA256": "db5d9e29761e7ab22e79bd04c51e6d4e26eac73a303eeb8c64cdaa330b0fcb9d", + "version": "0.0.0-edge.53", + "sourceCommit": "465f780ee37275471a32238fafe7dfb5866dd478", + "sourceArchiveSHA256": "7d9bc569a0cdb962ad205037eea159cc7bbe3317aa03a00454b83bf00c4839e4", "storageSchema": 35, - "wheelSHA256": "2038b6218c8b2f5371e4cd5797a03af1274b9de8c17b698a69e3d59bb5969975", + "wheelSHA256": "7a47e346cc62887c02b501ce93a0f0c94e01e2c627e3bd838aaac02e0bddbae2", "pythonFiles": { "domus/__init__.py": "7182c88b92234b4328f94497f4e70222d4390d8093e4b62893dfa78ac5530ac6", "domus/application/__init__.py": "1e8c0c87bf2a8ca947112543070583c0cc55d9d40b56eab0d86ed59a4ec1e82c", @@ -239,9 +239,9 @@ "domus/infrastructure/task_materials.py": "d5d2934e36f290c7bf44b473392f014eab8749f1f3b3d26a3402079e65d2818f" }, "uiFiles": { - ".vite/manifest.json": "20fb5f3930922339ac18f422befcad26d39a3e48168ae034bdd075c858d933a8", - "assets/index-CNI5WB-O.js": "b394b8038910cc30dfc0b92a864641bad49d25edaa8392273fc0a91951950c28", + ".vite/manifest.json": "9954a8b26e1ed88f36de286a7b1184d5d6f92efe076221a9b8395684e77c2955", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "d4bd63a737c246f3511c31685acdd1e1ec0e012ed82f3c1ac42878d52159c7ef" + "assets/index-g4W3QIWH.js": "57539f4a01ab4e0162da779f058a4d9206a9309cd82c9b123499f6981ff7c48c", + "index.html": "9ac902d7ffb0a2dde0b9e66ce277bd837f388e6355af52cd01367e363e52e10c" } } diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml index 74cd7c9..55812d2 100644 --- a/addon-edge/config.yaml +++ b/addon-edge/config.yaml @@ -1,5 +1,5 @@ name: Domus Edge -version: "0.0.0-edge.52" +version: "0.0.0-edge.53" slug: domus_edge description: Development preview of the local Domus household application url: https://github.com/vypdev/domus diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index 26bf5e9..8eb80ac 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -48,7 +48,7 @@ SQLite schema 35 adds the local association index. Keep the previous compatible image together with its cold schema-34 state for rollback. Compatible schema-35 restoration retains current associations and original historical evidence. -## Immutable candidate +## Edge.52 observation Edge.52 packages runtime source `3751c4e1650f5de5433bcbefe228260c0b07753b`. The source archive SHA-256 is @@ -67,7 +67,20 @@ and review are tracked in the increment's pull request. [PR #145](https://github The installed Edge.52 candidate reproduced loss of keyboard focus after a successful lookup. Its disabled input relinquished focus to the document body. -Edge.53 will carry the correction and repeat installed acceptance. The regression +Edge.53 carries the correction and requires repeated installed acceptance. The regression checks found and unlinked results, unavailable retry, retained input, moved focus, background documents and retired view ownership. Both compiled barcode journeys require result focus and use the real next Tab to reach product selection. + +## Immutable Edge.53 candidate + +Edge.53 packages runtime source `465f780ee37275471a32238fafe7dfb5866dd478`. +The source archive SHA-256 is +`7d9bc569a0cdb962ad205037eea159cc7bbe3317aa03a00454b83bf00c4839e4`. +The independently measured Linux wheel SHA-256 is +`7a47e346cc62887c02b501ce93a0f0c94e01e2c627e3bd838aaac02e0bddbae2`. +All 231 Python modules match Git, the wheel and the installed Linux builder. +The four compiled UI files match the local and Linux builds. The normal local +wheel matches the Linux wheel exactly. Schema 35 is retained. +The actual-owner update, both CPU image campaigns and final same-head CI and +review are tracked in the increment's pull request. diff --git a/docs/installation-home-assistant.md b/docs/installation-home-assistant.md index f5b2351..c880a5d 100644 --- a/docs/installation-home-assistant.md +++ b/docs/installation-home-assistant.md @@ -11,6 +11,8 @@ Edge.52 finds products from manually entered barcode digits in Inventory. Managers review the chosen product and code before confirming an association or removal. A failed read offers a retry with the draft retained, and original request recovery handles an unconfirmed write. +Edge.53 continues keyboard focus to the result or retry control after a submitted +search. [Qualification](evidence/local-barcode-qualification.md) Edge.51 lets members start, block and unblock eligible work from Tasks. It keeps diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py index 3de8069..dfbc247 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.52" + assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.53" 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": []} @@ -65,15 +65,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] == "3751c4e1650f5de5433bcbefe228260c0b07753b" + assert commits[0] == "465f780ee37275471a32238fafe7dfb5866dd478" assert ( - "DOMUS_SOURCE_SHA256=db5d9e29761e7ab22e79bd04c51e6d4e26eac73a303eeb8c64cdaa330b0fcb9d" + "DOMUS_SOURCE_SHA256=7d9bc569a0cdb962ad205037eea159cc7bbe3317aa03a00454b83bf00c4839e4" in source ) - assert "ARG BUILD_VERSION=0.0.0-edge.52" in source + assert "ARG BUILD_VERSION=0.0.0-edge.53" in source candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text()) assert candidate["sourceCommit"] == commits[0] - assert candidate["version"] == "0.0.0-edge.52" + assert candidate["version"] == "0.0.0-edge.53" 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 @@ -150,8 +150,8 @@ def test_edge_artifact_declares_exact_reviewed_runtime_without_rebinding_histori "pythonFiles", "uiFiles", } - assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.52" - assert artifact["sourceCommit"] == "3751c4e1650f5de5433bcbefe228260c0b07753b" + assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.53" + assert artifact["sourceCommit"] == "465f780ee37275471a32238fafe7dfb5866dd478" assert artifact["storageSchema"] == 35 for field in ["sourceArchiveSHA256", "wheelSHA256"]: assert re.fullmatch("[a-f0-9]{64}", artifact[field]) From c505aba5844cec04aca5501963afd61ad72cf748 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 18:31:44 +0100 Subject: [PATCH 07/16] fix(inventory): continue barcode confirmations and recovery focus --- addon-edge/README.md | 2 +- docs/evidence/local-barcode-qualification.md | 24 +++++++- .../evidence/task-navigation-integration.json | 6 +- frontend/src/presentation/domus-inventory.ts | 22 ++++--- .../tests/e2e/workspace-navigation.spec.ts | 10 +++- frontend/tests/inventory.test.ts | 57 +++++++++++++++++++ 6 files changed, 107 insertions(+), 14 deletions(-) diff --git a/addon-edge/README.md b/addon-edge/README.md index 00acb58..d62e7b5 100644 --- a/addon-edge/README.md +++ b/addon-edge/README.md @@ -37,5 +37,5 @@ submitted search. This candidate uses SQLite schema 35. Keep a compatible image and cold data backup before upgrading a previous preview. -See [installation and operation](https://github.com/vypdev/domus/blob/ac843a9a5c23d411ff11dcbd83d32256af2f5daa/addon-edge/DOCS.md) for the source pin and rollback +See [installation and operation](https://github.com/vypdev/domus/blob/develop/addon-edge/DOCS.md) for the source pin and rollback instructions. diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index 8eb80ac..792d677 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -38,7 +38,7 @@ the old confirmation. Scope changes retire private facts and drafts. The complete backend campaign passes 5,569 tests with 100% statement and branch coverage globally and across all 231 authored modules. An independent source -coverage audit accepts the report. The complete frontend campaign passes 1,928 +coverage audit accepts the report. The complete frontend campaign passes 1,929 tests with all four metrics at 100% globally and per authored runtime file. All 121 compiled source journeys and 45 rebuilt catalog journeys pass, with zero skipped, unexpected or flaky results. The CPU image gate requires all 66 household @@ -84,3 +84,25 @@ The four compiled UI files match the local and Linux builds. The normal local wheel matches the Linux wheel exactly. Schema 35 is retained. The actual-owner update, both CPU image campaigns and final same-head CI and review are tracked in the increment's pull request. + +## Confirmed write continuation + +Installed Edge.53 retains the household, products and association from Edge.52. +English keyboard query continuation, real Tab navigation, cancelled review, +two-tab stale removal and Spanish 390 px touch passed. A temporary offline read +focused its explicit retry and retained all entered digits. Returning that tab +to the network and retrying restored the current match. + +A confirmed removal then relinquished focus to the document body. Edge.54 will +also continue focus after confirmed association writes and rejected stale removal, +waiting for the refreshed current result. An unconfirmed barcode write continues +to its original-request recovery control. Its regression covers accepted links, +accepted removals and an intermediate obsolete view during conflict refresh. + +The Edge.53 package-head frontend campaign also exposed an unrelated fixture +ordering race. Opening the selected automation draft read its execution state +while the test immediately seeded stock and history through independent writes. +The preserved trace reports a 503 `storage_busy` for that execution read and the +interface offers its explicit retry. The test now waits for the current rule +control before seeding later history. The existing write-concurrency and +unavailable-read acceptance cases retain their original assertions. diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json index 1332ce3..45ac496 100644 --- a/docs/evidence/task-navigation-integration.json +++ b/docs/evidence/task-navigation-integration.json @@ -5,10 +5,10 @@ "command": "pnpm build:frontend", "scope": "Compiled household workspace with protected manual automation preview, saved revisions, explicit runs and scoped run history, daily schedule previews and inactive daily drafts, 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. Points-allocation cards inherit the shared raised surface in both color schemes. The Tasks workspace supports planned task assignment, state-permitted release, retained conflict selections and original assignment-request recovery. The Tasks workspace also confirms Start, Block and Unblock, retains a bounded blocking reason through explicit current-task review and recovers the original progress request. Inventory supports manually entered local GTIN lookup, explicit product association and removal review, stale-association recovery and retained original barcode requests.", "actualProductFiles": { - ".vite/manifest.json": "9954a8b26e1ed88f36de286a7b1184d5d6f92efe076221a9b8395684e77c2955", + ".vite/manifest.json": "d0c30babfcbb32c3d008981d04c56745d8be171fdfff8724137a3bed98732ba8", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "assets/index-g4W3QIWH.js": "57539f4a01ab4e0162da779f058a4d9206a9309cd82c9b123499f6981ff7c48c", - "index.html": "9ac902d7ffb0a2dde0b9e66ce277bd837f388e6355af52cd01367e363e52e10c" + "assets/index-DOg1mB8K.js": "d6231483e8ba95c3eecfd923c04c8abafadcd7c15ce146cbb50bdcadcededfd6", + "index.html": "9a0eb467ea4afb8ab10d3df9ffcf4d2b31b188c6ec6e5d3c20206d86224ee9b7" }, "localValidation": { "commit": "9a10d8114869be754962953903e773fe8e12c723", diff --git a/frontend/src/presentation/domus-inventory.ts b/frontend/src/presentation/domus-inventory.ts index 97d7fe8..03daa24 100644 --- a/frontend/src/presentation/domus-inventory.ts +++ b/frontend/src/presentation/domus-inventory.ts @@ -186,9 +186,13 @@ export class DomusInventory extends LitElement { if (result.kind === 'rejected') { if (result.command.action === 'inventory.configure-replenishment' && result.reason === 'revision_conflict') this.policyEditor = null; - if ('barcode' in result.command) this.barcodeReview = null; + if ('barcode' in result.command) { + this.barcodeReview = null; + this.barcodeFocusPending = true; + } } else if (result.barcodeSaved) { this.barcodeReview = null; + this.barcodeFocusPending = true; this.barcodeSubmitted = result.barcodeSaved.barcode; if (this.barcodeDraft === '') this.barcodeDraft = result.barcodeSaved.barcode; } else if (result.locationSaved) this.locationDraft = ''; @@ -205,14 +209,15 @@ export class DomusInventory extends LitElement { protected updated(changed: PropertyValues): void { if (!changed.has('view')) return; if (this.barcodeFocusPending && !this.view!.busy) { - const owner = this.view; - const target = this.renderRoot.querySelector(this.barcodeState()?.unavailable - ? '.barcode-search-form vyp-ha-button' : '.barcode-result'); + const owner = this.view!; + const target = this.renderRoot.querySelector(owner.pending + ? '.inventory-actions vyp-ha-button:last-child' + : this.barcodeState()?.unavailable ? '.barcode-search-form vyp-ha-button' : '.barcode-result'); if (target) { - this.barcodeFocusPending = false; void this.updateComplete.then(() => { - if (this.view === owner && this.ownerDocument.hasFocus() - && this.ownerDocument.activeElement === this.ownerDocument.body) target.focus(); + if (this.view !== owner) return; + this.barcodeFocusPending = false; + if (this.ownerDocument.hasFocus() && this.ownerDocument.activeElement === this.ownerDocument.body) target.focus(); }); } } @@ -328,6 +333,7 @@ export class DomusInventory extends LitElement { @submit=${(event: SubmitEvent) => { event.preventDefault(); if (blocked) return; + this.barcodeFocusPending = true; this.intent({type: 'submit', command: review.associationId === null ? {action: 'inventory.link-barcode', barcode: review.barcode, product_id: review.productId} : {action: 'inventory.remove-barcode', barcode: review.barcode, @@ -698,7 +704,7 @@ export class DomusInventory extends LitElement {

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

${movement ? html`

${this.text('movement')} ${movement.movementId}

` : nothing} `} -
${this.button('refresh', () => this.intent({type:'refresh'}), busy)} +
${this.button('refresh', () => this.intent({type:'refresh'}), busy)} ${pending ? this.button('recover', () => this.intent({type:'recover'}), busy) : nothing}
${busy && report === null ? html`

${this.text('loading')}

` : nothing} ${report === null ? nothing : html` diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index 6b72909..2f0ce9a 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -75,6 +75,7 @@ for (const mode of ['native', 'standalone'] as const) { }); await review.getByRole('button', {name:'Confirm barcode association', exact:true}).press('Enter'); await expect(stock.getByRole('button', {name:'Recover original request', exact:true})).toBeEnabled(); + await expect(stock.getByRole('button', {name:'Recover original request', exact:true})).toBeFocused(); await page.unroute(commands); await page.reload(); const original = page.waitForResponse(base + 'api/v1/inventory/requests/inventory.link-barcode/' + originalKey); @@ -82,6 +83,7 @@ for (const mode of ['native', 'standalone'] as const) { expect((await original).ok()).toBe(true); await expect(stock.getByText('Barcode associated.', {exact:false})).toBeVisible(); await expect(stock.getByText('Product found QA barcode soap', {exact:true})).toBeVisible(); + await expect(stock.locator('.barcode-result')).toBeFocused(); await expect(digits).toHaveValue(barcode); await expect(stock.getByRole('article', {name:'QA barcode soap', exact:true}).locator('dd')).toHaveText(['0', '0', '0']); await stock.getByRole('button', {name:'Open product stock', exact:true}).press('Enter'); @@ -98,14 +100,18 @@ for (const mode of ['native', 'standalone'] as const) { await other.getByRole('button', {name:'Remove barcode association', exact:true}).press('Enter'); await other.getByRole('button', {name:'Confirm barcode removal', exact:true}).press('Enter'); await expect(other.getByText('Unlinked barcode in this household.', {exact:true})).toBeVisible(); + await expect(other.locator('.barcode-result')).toBeFocused(); await other.getByRole('button', {name:'Associate barcode with QA barcode tea', exact:true}).press('Enter'); await other.getByRole('button', {name:'Confirm barcode association', exact:true}).press('Enter'); await expect(other.getByText('Product found QA barcode tea', {exact:true})).toBeVisible(); + await expect(other.locator('.barcode-result')).toBeFocused(); const stale = page.waitForRequest(item => item.url() === commands && item.method() === 'POST'); + await page.bringToFront(); await oldReview.getByRole('button', {name:'Confirm barcode removal', exact:true}).press('Enter'); expect((await stale).postDataJSON()).toMatchObject({action:'inventory.remove-barcode', barcode, association_id:associationId}); await expect(stock.getByText('The association changed. Review the current product before confirming again.', {exact:true})).toBeVisible(); await expect(stock.getByText('Product found QA barcode tea', {exact:true})).toBeVisible(); + await expect(stock.locator('.barcode-result')).toBeFocused(); await expect(oldReview).toHaveCount(0); await stock.screenshot({path:info.outputPath('barcode-en-keyboard.png')}); await peer.close(); @@ -131,6 +137,7 @@ for (const mode of ['native', 'standalone'] as const) { await stock.getByRole('button', {name:'Eliminar asociación del código', exact:true}).tap(); await stock.getByRole('button', {name:'Confirmar retirada del código', exact:true}).tap(); await expect(stock.getByText('Código sin asociación en este hogar.', {exact:true})).toBeVisible(); + await expect(stock.locator('.barcode-result')).toBeFocused(); await expect(spanish).toHaveValue('036000291452'); await stock.screenshot({path:info.outputPath('barcode-es-touch.png')}); expect(external).toEqual([]); @@ -1702,6 +1709,8 @@ for (const mode of ['native', 'standalone'] as const) { await tabs.getByRole('link',{name:'Hogar',exact:true}).tap(); await drafts.getByRole('button',{name:'Abrir ' + draftTitle,exact:true}).tap(); + const disable = execution.getByRole('button',{name:'Deshabilitar futuras ejecuciones',exact:true}); + await expect(disable).toBeEnabled(); await stockWrite('refill-for-later-no-task-runs',{action:'inventory.adjust',product_id:product, quantity:'2',reason:'Replenished for history test'}); const token = await page.request.get(base + 'api/v1/auth/csrf', {headers:{'X-Domus-Context':contextHeader}}); @@ -1720,7 +1729,6 @@ for (const mode of ['native', 'standalone'] as const) { expect((await newer.json()).result.condition_matched).toBe(false); } - const disable = execution.getByRole('button',{name:'Deshabilitar futuras ejecuciones',exact:true}); await disable.tap(); await execution.getByRole('region',{name:'Confirmar acción de automatización',exact:true}) .getByRole('button',{name:'Deshabilitar futuras ejecuciones',exact:true}).tap(); diff --git a/frontend/tests/inventory.test.ts b/frontend/tests/inventory.test.ts index 8d49486..3ed92da 100644 --- a/frontend/tests/inventory.test.ts +++ b/frontend/tests/inventory.test.ts @@ -2202,6 +2202,63 @@ test('a submitted barcode search continues to its result or retry without reclai } }); +test('confirmed barcode writes and stale removal continue to the refreshed current result', async () => { + const foreground = vi.spyOn(document, 'hasFocus').mockReturnValue(true); + const f = await barcodeComponent(); + const loading: InventoryState = {...barcodeView, busy: true, + barcode: {code: barcodeCode, lookup: null, unavailable: false}}; + const saved: InventoryResult = {kind: 'committed', operationId: 'barcode-saved', productId: 'product', + movement: null, barcodeSaved: {barcode: barcodeCode, linked: true}}; + try { + await f.enter('036000291452'); + f.submit(f.search()!); + await f.assign(barcodeView); + f.press('Associate barcode with Olive oil'); + await f.node.updateComplete; + f.submit(f.root.querySelector('.barcode-review')!); + await f.assign(loading); + await f.assign({...barcodeView, pending: true, notice: 'uncertain'}); + const recover = [...f.root.querySelectorAll('vyp-ha-button')] + .find(button => button.state.label === 'Recover original request'); + expect(recover).toBeDefined(); + expect(f.root.activeElement).toBe(recover); + await f.assign({...loading, result: saved}); + await f.assign({...barcodeView, result: saved, + barcode: {code: barcodeCode, lookup: barcodeFound, unavailable: false}}); + expect(f.root.activeElement).toBe(f.root.querySelector('.barcode-result')); + + f.press('Remove barcode association'); + await f.node.updateComplete; + f.submit(f.root.querySelector('.barcode-review')!); + await f.assign({...f.node.view!, busy: true}); + const rejected: InventoryState = {...barcodeView, + barcode: {code: barcodeCode, lookup: barcodeFound, unavailable: false}, + result: {kind: 'rejected', reason: 'inventory_barcode_changed', command: { + action: 'inventory.remove-barcode', barcode: barcodeCode, product_id: 'product', association_id: 'barcode-link', + }}}; + f.node.view = rejected; + await f.node.updateComplete; + await f.assign({...loading, result: rejected.result}); + await f.assign({...rejected, barcode: {code: barcodeCode, unavailable: false, + lookup: {...barcodeFound, product: {...barcodeFound.product!, name: 'Replacement', associationId: 'replacement'}}}}); + expect(f.root.querySelector('.barcode-review')).toBeNull(); + expect(f.root.activeElement).toBe(f.root.querySelector('.barcode-result')); + expect(f.root.activeElement!.textContent).toContain('Replacement'); + + f.press('Remove barcode association'); + await f.node.updateComplete; + f.submit(f.root.querySelector('.barcode-review')!); + await f.assign(loading); + const removed = {...saved, operationId: 'barcode-removed', barcodeSaved: {barcode: barcodeCode, linked: false}}; + await f.assign({...loading, result: removed}); + await f.assign({...barcodeView, result: removed}); + expect(f.root.activeElement).toBe(f.root.querySelector('.barcode-result')); + expect(f.root.activeElement!.textContent).toContain('Unlinked barcode'); + } finally { + foreground.mockRestore(); + } +}); + test('barcode lookup selects an existing paginated product and reviews each association write', async () => { const f = await barcodeComponent(); const registration = f.root.querySelector('.registration-form')!; From b2f9f48994d523e28c4584f583e1c929ecbc61b1 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 19:08:43 +0100 Subject: [PATCH 08/16] test(browser): wait for restored workspace readiness --- docs/evidence/local-barcode-qualification.md | 15 +++++++++++++++ frontend/playwright.config.ts | 2 +- frontend/playwright.entry.config.ts | 2 +- frontend/tests/e2e/tasks.spec.ts | 5 ++++- frontend/tests/e2e/workspace-navigation.spec.ts | 5 ++++- 5 files changed, 25 insertions(+), 4 deletions(-) diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index 792d677..4529f39 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -106,3 +106,18 @@ The preserved trace reports a 503 `storage_busy` for that execution read and the interface offers its explicit retry. The test now waits for the current rule control before seeding later history. The existing write-concurrency and unavailable-read acceptance cases retain their original assertions. + +A complete local campaign reached its 600-second suite deadline after 113 passing +cases. Its assignment fixture also chose Spanish before reloaded preferences +finished hydrating, then waited for a Spanish recovery control while the interface +was in English. The fixture now waits for the loaded Tasks heading before choosing +the locale. Assignment journeys use the existing progress journey's 75-second +bound, and the complete 121-case suite has a 900-second bound for shared runners. +All case assertions and the zero-retry policy remain applicable. + +The static catalog server uses HTTP/1.1 persistent connections. Two earlier local +catalog campaigns lost JavaScript resource connections before their stories +loaded. Their original traces are retained. With HTTP/1.1, all 45 cases pass in +two consecutive zero-retry campaigns. Barcode recovery now waits for the restored +product projection and a valid captured original request key before reading the +receipt. Both deployment journeys pass twice with the recovery focus assertion. diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index dd41ef1..0a9c6ad 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -5,6 +5,6 @@ export default defineConfig({ outputDir: 'test-results/catalog-artifacts', reporter: [['list'], ['json', {outputFile: 'test-results/catalog-results.json'}]], use: {headless: true, screenshot: 'only-on-failure', trace: 'retain-on-failure'}, - webServer: {command: 'python3 -m http.server 56173 --bind 127.0.0.1 --directory storybook-static', + webServer: {command: 'python3 -m http.server 56173 --bind 127.0.0.1 --protocol HTTP/1.1 --directory storybook-static', url: 'http://127.0.0.1:56173', reuseExistingServer: false, timeout: 10_000}, }); diff --git a/frontend/playwright.entry.config.ts b/frontend/playwright.entry.config.ts index a54a1d3..59bbcea 100644 --- a/frontend/playwright.entry.config.ts +++ b/frontend/playwright.entry.config.ts @@ -3,7 +3,7 @@ import {defineConfig} from '@playwright/test'; export default defineConfig({ testDir: 'tests/e2e', testMatch: ['entry.spec.ts','administration.spec.ts','tasks.spec.ts','workspace-navigation.spec.ts'], forbidOnly: true, retries: 0, workers: 1, // Include both workspace journeys, fixture startup and cleanup on slower self-hosted runners. - globalTimeout: 600_000, outputDir: 'test-results/entry-artifacts', + globalTimeout: 900_000, outputDir: 'test-results/entry-artifacts', reporter: [['list'], ['json', {outputFile: 'test-results/entry-results.json'}]], // Playwright normally disables BFCache. Exercise the real production page lifecycle instead. use: {headless: true, launchOptions: {ignoreDefaultArgs: ['--disable-back-forward-cache']}, diff --git a/frontend/tests/e2e/tasks.spec.ts b/frontend/tests/e2e/tasks.spec.ts index 7dd3d5b..4fe09c3 100644 --- a/frontend/tests/e2e/tasks.spec.ts +++ b/frontend/tests/e2e/tasks.spec.ts @@ -490,6 +490,7 @@ for (const mode of ['native', 'standalone'] as const) { for (const mode of ['native', 'standalone'] as const) { for (const locale of ['en', 'es'] as const) { test(`assignment review, recovery and restart in ${mode} ${locale}`, async ({browser, request}, info) => { + test.setTimeout(75_000); expect((await request.post(origin(mode) + '/__fixture__/reset')).ok()).toBe(true); const owner = await browser.newContext({viewport: {width: locale === 'es' ? 390 : 1280, height: 844}, hasTouch: locale === 'es'}); const peer = await browser.newContext(); @@ -506,8 +507,9 @@ for (const mode of ['native', 'standalone'] as const) { await page.getByRole('link', {name: 'Continue as fixture user', exact: true}).click(); } await expect(page.getByRole('link', {name: 'Tasks', exact: true})).toBeVisible(); + await page.getByRole('link', {name: 'Tasks', exact: true}).click(); + await expect(page.locator('domus-tasks').getByRole('heading', {name: /^(Household tasks|Tareas del hogar)$/u})).toBeVisible(); await page.getByRole('combobox', {name: /^(Language|Idioma)$/u}).selectOption(locale); - await page.getByRole('link', {name: t('Tasks', 'Tareas'), exact: true}).click(); }; try { const tasks = await open(page, owner, mode); @@ -609,6 +611,7 @@ for (const mode of ['native', 'standalone'] as const) { await expect(save).toBeDisabled(); expect(writes).toHaveLength(3); const released = writes[2]; expect(JSON.parse(released.body)).toEqual({expected_revision: 4, assignee_ids: []}); await page.unroute(endpoint + '/assignment'); await page.reload(); + await expect(tasks.getByRole('heading', {name: 'Household tasks', exact: true})).toBeVisible(); await page.getByRole('combobox', {name: 'Language', exact: true}).selectOption(locale); await activate(tasks.getByRole('button', {name: t('Check saved request', 'Comprobar solicitud guardada'), exact: true}).first()); await expect(tasks.getByRole('heading', {name: t('Assignment saved', 'Asignación guardada'), exact: true})).toBeVisible(); diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index 2f0ce9a..4518421 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -67,7 +67,7 @@ for (const mode of ['native', 'standalone'] as const) { let associationId = ''; await page.route(commands, async route => { expect(route.request().postDataJSON()).toMatchObject({action:'inventory.link-barcode', barcode}); - originalKey = route.request().headers()['idempotency-key']; + originalKey = (await route.request().allHeaders())['idempotency-key']; const committed = await route.fetch({maxRetries:0, maxRedirects:0}); expect(committed.ok()).toBe(true); associationId = (await committed.json()).result.association_id; @@ -76,8 +76,11 @@ for (const mode of ['native', 'standalone'] as const) { await review.getByRole('button', {name:'Confirm barcode association', exact:true}).press('Enter'); await expect(stock.getByRole('button', {name:'Recover original request', exact:true})).toBeEnabled(); await expect(stock.getByRole('button', {name:'Recover original request', exact:true})).toBeFocused(); + expect(originalKey).toMatch(/^req_[a-f0-9]{32}$/u); await page.unroute(commands); await page.reload(); + await expect(stock.getByRole('article', {name:'QA barcode soap', exact:true})).toBeVisible(); + await expect(stock.getByRole('button', {name:'Recover original request', exact:true})).toBeEnabled(); const original = page.waitForResponse(base + 'api/v1/inventory/requests/inventory.link-barcode/' + originalKey); await stock.getByRole('button', {name:'Recover original request', exact:true}).press('Enter'); expect((await original).ok()).toBe(true); From 5797b5b4cd18ed63748fe2ddbfa8dddd3b3a405d Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 19:12:47 +0100 Subject: [PATCH 09/16] build(edge): pin verified barcode recovery preview 54 --- addon-edge/CHANGELOG.md | 5 +++++ addon-edge/DOCS.md | 6 ++++-- addon-edge/Dockerfile | 8 ++++---- addon-edge/README.md | 3 +++ addon-edge/artifact.json | 14 +++++++------- addon-edge/config.yaml | 2 +- docs/evidence/local-barcode-qualification.md | 19 ++++++++++++++++--- docs/installation-home-assistant.md | 2 ++ tests/backend/test_app_package.py | 14 +++++++------- 9 files changed, 49 insertions(+), 24 deletions(-) diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md index 752668c..18e3214 100644 --- a/addon-edge/CHANGELOG.md +++ b/addon-edge/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 0.0.0-edge.54 + +- Continue keyboard focus to the current barcode result after confirmed changes and stale-removal review. +- Focus original-request recovery when an association write has an unconfirmed response. + ## 0.0.0-edge.53 - Continue keyboard focus to the barcode result or retry control after a submitted search. diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md index 9c46d74..48f226f 100644 --- a/addon-edge/DOCS.md +++ b/addon-edge/DOCS.md @@ -1,6 +1,6 @@ # Installation and operation -Edge 0.0.0-edge.53 packages the immutable runtime declared in +Edge 0.0.0-edge.54 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 @@ -45,7 +45,9 @@ can choose a Pantry product, review its code and confirm the association. Review and remove the current association before choosing a replacement. Use **Retry barcode lookup** after an unavailable read or **Recover original request** after an unconfirmed write. A submitted search continues keyboard -focus to its result or retry control when the read finishes. +focus to its result or retry control when the read finishes. After a confirmed +change, focus continues to the current result. If a write reply is unconfirmed, +focus continues to **Recover original request**. Edge.52 uses SQLite schema 35 and is listed in `breaking_versions`. Keep a compatible image together with its cold schema-34 data for rollback. diff --git a/addon-edge/Dockerfile b/addon-edge/Dockerfile index 8293ab9..aa04f9a 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=465f780ee37275471a32238fafe7dfb5866dd478 -ARG DOMUS_SOURCE_SHA256=7d9bc569a0cdb962ad205037eea159cc7bbe3317aa03a00454b83bf00c4839e4 +ARG DOMUS_SOURCE_COMMIT=b2f9f48994d523e28c4584f583e1c929ecbc61b1 +ARG DOMUS_SOURCE_SHA256=23c9240e137ed578ee6e52b68e4318b3e0153ca2ad32940088f20635931c2918 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.53 +ARG BUILD_VERSION=0.0.0-edge.54 ARG BUILD_ARCH -ARG DOMUS_SOURCE_COMMIT=465f780ee37275471a32238fafe7dfb5866dd478 +ARG DOMUS_SOURCE_COMMIT=b2f9f48994d523e28c4584f583e1c929ecbc61b1 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 d62e7b5..c4dc8ad 100644 --- a/addon-edge/README.md +++ b/addon-edge/README.md @@ -35,6 +35,9 @@ Original-request recovery and current conflict review retain the entered code. Edge.53 continues keyboard focus to the barcode result or retry control after a submitted search. +Edge.54 continues keyboard focus after confirmed barcode changes and moves it to +original-request recovery when a write response is unconfirmed. + This candidate uses SQLite schema 35. Keep a compatible image and cold data backup before upgrading a previous preview. See [installation and operation](https://github.com/vypdev/domus/blob/develop/addon-edge/DOCS.md) for the source pin and rollback diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json index 6757616..d45a2f1 100644 --- a/addon-edge/artifact.json +++ b/addon-edge/artifact.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, - "version": "0.0.0-edge.53", - "sourceCommit": "465f780ee37275471a32238fafe7dfb5866dd478", - "sourceArchiveSHA256": "7d9bc569a0cdb962ad205037eea159cc7bbe3317aa03a00454b83bf00c4839e4", + "version": "0.0.0-edge.54", + "sourceCommit": "b2f9f48994d523e28c4584f583e1c929ecbc61b1", + "sourceArchiveSHA256": "23c9240e137ed578ee6e52b68e4318b3e0153ca2ad32940088f20635931c2918", "storageSchema": 35, - "wheelSHA256": "7a47e346cc62887c02b501ce93a0f0c94e01e2c627e3bd838aaac02e0bddbae2", + "wheelSHA256": "b9e3fd518a611d7ef9cef215d23355e2bdce91e7a7b9a5ecdbf7653753eb2a07", "pythonFiles": { "domus/__init__.py": "7182c88b92234b4328f94497f4e70222d4390d8093e4b62893dfa78ac5530ac6", "domus/application/__init__.py": "1e8c0c87bf2a8ca947112543070583c0cc55d9d40b56eab0d86ed59a4ec1e82c", @@ -239,9 +239,9 @@ "domus/infrastructure/task_materials.py": "d5d2934e36f290c7bf44b473392f014eab8749f1f3b3d26a3402079e65d2818f" }, "uiFiles": { - ".vite/manifest.json": "9954a8b26e1ed88f36de286a7b1184d5d6f92efe076221a9b8395684e77c2955", + ".vite/manifest.json": "d0c30babfcbb32c3d008981d04c56745d8be171fdfff8724137a3bed98732ba8", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "assets/index-g4W3QIWH.js": "57539f4a01ab4e0162da779f058a4d9206a9309cd82c9b123499f6981ff7c48c", - "index.html": "9ac902d7ffb0a2dde0b9e66ce277bd837f388e6355af52cd01367e363e52e10c" + "assets/index-DOg1mB8K.js": "d6231483e8ba95c3eecfd923c04c8abafadcd7c15ce146cbb50bdcadcededfd6", + "index.html": "9a0eb467ea4afb8ab10d3df9ffcf4d2b31b188c6ec6e5d3c20206d86224ee9b7" } } diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml index 55812d2..43873a9 100644 --- a/addon-edge/config.yaml +++ b/addon-edge/config.yaml @@ -1,5 +1,5 @@ name: Domus Edge -version: "0.0.0-edge.53" +version: "0.0.0-edge.54" slug: domus_edge description: Development preview of the local Domus household application url: https://github.com/vypdev/domus diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index 4529f39..88da6a9 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -72,7 +72,7 @@ checks found and unlinked results, unavailable retry, retained input, moved focu background documents and retired view ownership. Both compiled barcode journeys require result focus and use the real next Tab to reach product selection. -## Immutable Edge.53 candidate +## Edge.53 candidate observation Edge.53 packages runtime source `465f780ee37275471a32238fafe7dfb5866dd478`. The source archive SHA-256 is @@ -93,8 +93,7 @@ two-tab stale removal and Spanish 390 px touch passed. A temporary offline read focused its explicit retry and retained all entered digits. Returning that tab to the network and retrying restored the current match. -A confirmed removal then relinquished focus to the document body. Edge.54 will -also continue focus after confirmed association writes and rejected stale removal, +A confirmed removal then relinquished focus to the document body. Edge.54 also continues focus after confirmed association writes and rejected stale removal, waiting for the refreshed current result. An unconfirmed barcode write continues to its original-request recovery control. Its regression covers accepted links, accepted removals and an intermediate obsolete view during conflict refresh. @@ -121,3 +120,17 @@ loaded. Their original traces are retained. With HTTP/1.1, all 45 cases pass in two consecutive zero-retry campaigns. Barcode recovery now waits for the restored product projection and a valid captured original request key before reading the receipt. Both deployment journeys pass twice with the recovery focus assertion. + +## Immutable Edge.54 candidate + +Edge.54 packages runtime source `b2f9f48994d523e28c4584f583e1c929ecbc61b1`. +The source archive SHA-256 is +`23c9240e137ed578ee6e52b68e4318b3e0153ca2ad32940088f20635931c2918`. +The independently measured Linux wheel SHA-256 is +`b9e3fd518a611d7ef9cef215d23355e2bdce91e7a7b9a5ecdbf7653753eb2a07`. +All 231 Python modules match Git, the wheel and the installed Linux builder. +The four compiled UI files match the local and Linux builds. The normal local +wheel matches the Linux wheel exactly. Schema 35 is retained. +All 121 compiled source journeys pass in a complete zero-retry campaign. +Installed-owner acceptance, both CPU image campaigns and final same-head CI and +review are tracked in the increment's pull request. diff --git a/docs/installation-home-assistant.md b/docs/installation-home-assistant.md index c880a5d..ad2e56d 100644 --- a/docs/installation-home-assistant.md +++ b/docs/installation-home-assistant.md @@ -13,6 +13,8 @@ or removal. A failed read offers a retry with the draft retained, and original request recovery handles an unconfirmed write. Edge.53 continues keyboard focus to the result or retry control after a submitted search. +Edge.54 continues focus after confirmed barcode changes and moves it to original +request recovery when a write response is unconfirmed. [Qualification](evidence/local-barcode-qualification.md) Edge.51 lets members start, block and unblock eligible work from Tasks. It keeps diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py index dfbc247..494ffba 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.53" + assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.54" 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": []} @@ -65,15 +65,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] == "465f780ee37275471a32238fafe7dfb5866dd478" + assert commits[0] == "b2f9f48994d523e28c4584f583e1c929ecbc61b1" assert ( - "DOMUS_SOURCE_SHA256=7d9bc569a0cdb962ad205037eea159cc7bbe3317aa03a00454b83bf00c4839e4" + "DOMUS_SOURCE_SHA256=23c9240e137ed578ee6e52b68e4318b3e0153ca2ad32940088f20635931c2918" in source ) - assert "ARG BUILD_VERSION=0.0.0-edge.53" in source + assert "ARG BUILD_VERSION=0.0.0-edge.54" in source candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text()) assert candidate["sourceCommit"] == commits[0] - assert candidate["version"] == "0.0.0-edge.53" + assert candidate["version"] == "0.0.0-edge.54" 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 @@ -150,8 +150,8 @@ def test_edge_artifact_declares_exact_reviewed_runtime_without_rebinding_histori "pythonFiles", "uiFiles", } - assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.53" - assert artifact["sourceCommit"] == "465f780ee37275471a32238fafe7dfb5866dd478" + assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.54" + assert artifact["sourceCommit"] == "b2f9f48994d523e28c4584f583e1c929ecbc61b1" assert artifact["storageSchema"] == 35 for field in ["sourceArchiveSHA256", "wheelSHA256"]: assert re.fullmatch("[a-f0-9]{64}", artifact[field]) From bd3e6263d6212b3371171d3b50ab8751cef6dace Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 19:44:37 +0100 Subject: [PATCH 10/16] docs: record the delivered local barcode workflow --- docs/roadmap.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 28baebf..1e906b4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -53,8 +53,10 @@ assignees, replacement and release with explicit conflict review and original-re return](evidence/physical-receipt-return-qualification.md) records the withdrawal of a received item from a closed purchase. The [storage locations and transfers increment](evidence/stock-location-transfer-qualification.md) shows the stock at each location and - records a move as two linked ledger entries. Multiple lists, prices, refunds, location editing and - archiving, lot and package management, barcodes and optional online lookup remain open. + records a move as two linked ledger entries. [Manual local barcode + lookup](evidence/local-barcode-qualification.md) finds a household product from printed digits + and lets managers review its association or removal. Multiple lists, prices, refunds, location + editing and archiving, lot and package management 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, [task deadline sensors](evidence/ha-deadline-sensors-qualification.md), From e8e93fe892babc0263808848c3bd24c8aea9d2c2 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 20:36:16 +0100 Subject: [PATCH 11/16] fix: align barcode schema and qualify inherited long-name wrapping --- .../src/domus/entrypoints/inventory_http.py | 2 +- docs/contracts/household-api.openapi.json | 6 ++--- .../native-household-api.openapi.json | 6 ++--- docs/evidence/local-barcode-qualification.md | 19 ++++++++++++++++ .../tests/e2e/workspace-navigation.spec.ts | 22 ++++++++++++++++++- tests/backend/test_inventory_barcode_http.py | 21 ++++++++++++++++++ 6 files changed, 68 insertions(+), 8 deletions(-) diff --git a/backend/src/domus/entrypoints/inventory_http.py b/backend/src/domus/entrypoints/inventory_http.py index 550456f..25b68bb 100644 --- a/backend/src/domus/entrypoints/inventory_http.py +++ b/backend/src/domus/entrypoints/inventory_http.py @@ -51,7 +51,7 @@ class LocationBody(StrictModel): name: str = Field(min_length=1, max_length=MAX_LOCATION_NAME) -Barcode = Annotated[str, Field(min_length=8, max_length=14, pattern=r"^[0-9]+$")] +Barcode = Annotated[str, Field(min_length=8, max_length=14, pattern=r"^(?:[0-9]{8}|[0-9]{12,14})$")] class BarcodeQuery(StrictModel): diff --git a/docs/contracts/household-api.openapi.json b/docs/contracts/household-api.openapi.json index 1e2bbce..8f0322f 100644 --- a/docs/contracts/household-api.openapi.json +++ b/docs/contracts/household-api.openapi.json @@ -3952,7 +3952,7 @@ "barcode": { "maxLength": 14, "minLength": 8, - "pattern": "^[0-9]+$", + "pattern": "^(?:[0-9]{8}|[0-9]{12,14})$", "title": "Barcode", "type": "string" }, @@ -6676,7 +6676,7 @@ "barcode": { "maxLength": 14, "minLength": 8, - "pattern": "^[0-9]+$", + "pattern": "^(?:[0-9]{8}|[0-9]{12,14})$", "title": "Barcode", "type": "string" }, @@ -16997,7 +16997,7 @@ "schema": { "maxLength": 14, "minLength": 8, - "pattern": "^[0-9]+$", + "pattern": "^(?:[0-9]{8}|[0-9]{12,14})$", "title": "Barcode", "type": "string" } diff --git a/docs/contracts/native-household-api.openapi.json b/docs/contracts/native-household-api.openapi.json index 6e7f85d..8fe6bf5 100644 --- a/docs/contracts/native-household-api.openapi.json +++ b/docs/contracts/native-household-api.openapi.json @@ -3946,7 +3946,7 @@ "barcode": { "maxLength": 14, "minLength": 8, - "pattern": "^[0-9]+$", + "pattern": "^(?:[0-9]{8}|[0-9]{12,14})$", "title": "Barcode", "type": "string" }, @@ -6697,7 +6697,7 @@ "barcode": { "maxLength": 14, "minLength": 8, - "pattern": "^[0-9]+$", + "pattern": "^(?:[0-9]{8}|[0-9]{12,14})$", "title": "Barcode", "type": "string" }, @@ -16485,7 +16485,7 @@ "schema": { "maxLength": 14, "minLength": 8, - "pattern": "^[0-9]+$", + "pattern": "^(?:[0-9]{8}|[0-9]{12,14})$", "title": "Barcode", "type": "string" } diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index 88da6a9..ab27be2 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -134,3 +134,22 @@ wheel matches the Linux wheel exactly. Schema 35 is retained. All 121 compiled source journeys pass in a complete zero-retry campaign. Installed-owner acceptance, both CPU image campaigns and final same-head CI and review are tracked in the increment's pull request. + +## Published shape and long-name review + +The HTTP annotation and both composed OpenAPI snapshots now restrict the +printed shape to exactly 8, 12, 13 or 14 ASCII digits. The domain still checks +the GS1 digit before canonicalization. A contract regression compares all three +published barcode shapes with actual lookup admission in both deployments. +The previous pattern reproduced six mismatches for 9-, 10- and 11-digit inputs. +After the correction, all 30 focused HTTP and composed-snapshot cases pass. + +The long-name review finding was a false positive. The exact published ha-ui +card already supplies inherited `overflow-wrap:anywhere`. Both compiled barcode +journeys now register an unbroken 160-character product name and exercise its +Spanish narrow-screen review and found result. Each has a client and scroll +width of 324 px inside the 390 px viewport, with inherited wrapping retained. +Both journeys pass without a Domus CSS change. Original screenshots and measured +layout attachments are retained. The first diagnostic passed the layout checks +but failed a new test expectation for light text color; the expectation was +corrected to the existing `#172b3a` without changing application colors. diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index 4518421..8fd0cdb 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -10,6 +10,7 @@ for (const mode of ['native', 'standalone'] as const) { const origin = `http://127.0.0.1:${mode === 'native' ? 56174 : 56175}`; const base = origin + (mode === 'native' ? ingress : '') + '/'; const barcode = '00036000291452'; + const longName = 'QA91' + 'X'.repeat(156); const commands = base + 'api/v1/inventory/commands'; const lookup = base + 'api/v1/inventory/barcode?barcode=' + barcode; const external: string[] = []; @@ -37,7 +38,7 @@ for (const mode of ['native', 'standalone'] as const) { await page.getByRole('button', {name:'Create household', exact:true}).press('Enter'); await page.locator('vyp-ha-tabs').getByRole('link', {name:'Inventory', exact:true}).press('Enter'); const stock = page.locator('domus-inventory'); - for (const name of ['QA barcode soap', 'QA barcode tea']) { + for (const name of ['QA barcode soap', 'QA barcode tea', longName]) { await stock.getByRole('textbox', {name:'Product name', exact:true}).fill(name); await stock.getByRole('button', {name:'Register product', exact:true}).press('Enter'); await expect(stock.getByRole('article', {name, exact:true})).toBeVisible(); @@ -143,6 +144,25 @@ for (const mode of ['native', 'standalone'] as const) { await expect(stock.locator('.barcode-result')).toBeFocused(); await expect(spanish).toHaveValue('036000291452'); await stock.screenshot({path:info.outputPath('barcode-es-touch.png')}); + await stock.getByRole('button', {name:'Asociar código a ' + longName, exact:true}).tap(); + const longReview = stock.getByRole('form', {name:'Revisar asociación del código', exact:true}); + await expect(longReview).toContainText(longName); + await stock.screenshot({path:info.outputPath('barcode-long-name-review-es.png')}); + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390); + const reviewLayout = await longReview.evaluate(element => ({clientWidth:element.clientWidth, + scrollWidth:element.scrollWidth, overflowWrap:getComputedStyle(element).overflowWrap})); + await longReview.getByRole('button', {name:'Confirmar asociación del código', exact:true}).tap(); + await expect(stock.locator('.barcode-result')).toContainText(longName); + await expect(stock.locator('.barcode-result')).toBeFocused(); + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390); + const resultLayout = await stock.locator('.barcode-result').evaluate(element => ({clientWidth:element.clientWidth, + scrollWidth:element.scrollWidth, overflowWrap:getComputedStyle(element).overflowWrap})); + await info.attach('barcode-long-name-layout', {body:JSON.stringify({length:longName.length, + viewport:390, review:reviewLayout, result:resultLayout}), contentType:'application/json'}); + await page.emulateMedia({colorScheme:'light', reducedMotion:'reduce'}); + await expect(searchCard).toHaveCSS('background-color', 'rgb(255, 255, 255)'); + await expect(searchCard).toHaveCSS('color', 'rgb(23, 43, 58)'); + await stock.screenshot({path:info.outputPath('barcode-long-name-result-es.png')}); expect(external).toEqual([]); }); } diff --git a/tests/backend/test_inventory_barcode_http.py b/tests/backend/test_inventory_barcode_http.py index 1702ac9..fe9fdb5 100644 --- a/tests/backend/test_inventory_barcode_http.py +++ b/tests/backend/test_inventory_barcode_http.py @@ -1,5 +1,7 @@ """Barcode admission uses both protected production HTTP compositions.""" +import re + import pytest from test_inventory_catalog_http import INVENTORY, VIEWER, post, register from test_recurrence_http import USER @@ -94,6 +96,25 @@ def unexpected(*_): ) +@pytest.mark.parametrize( + "barcode", + ["96385074", "036000291452", "0036000291452", "00036000291452", "0" * 9, "0" * 10, "0" * 11], +) +def test_published_barcode_shapes_match_runtime_accepted_lengths(api, barcode): + api.user(USER, True) + document = api.client.get("/api/v1/openapi.json").json() + parameters = document["paths"][INVENTORY + "/barcode"]["get"]["parameters"] + schemas = [next(item["schema"] for item in parameters if item["name"] == "barcode")] + schemas.extend( + document["components"]["schemas"][name]["properties"]["barcode"] + for name in ("LinkBarcodeBody", "RemoveBarcodeBody") + ) + accepted = len(barcode) in (8, 12, 13, 14) + for schema in schemas: + assert bool(re.fullmatch(schema["pattern"], barcode)) is accepted + assert lookup(api, barcode).status_code == (200 if accepted else 422) + + def test_lookup_unavailability_is_distinct_and_read_retry_retains_the_same_key(api, monkeypatch): api.user(USER, True) From 1c5ae42a87becadb247125a5c63f35034c8ba7af Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 20:52:30 +0100 Subject: [PATCH 12/16] build: pin Edge.55 barcode contract qualification --- addon-edge/CHANGELOG.md | 4 ++++ addon-edge/DOCS.md | 5 ++++- addon-edge/Dockerfile | 8 ++++---- addon-edge/README.md | 3 +++ addon-edge/artifact.json | 10 +++++----- addon-edge/config.yaml | 2 +- docs/evidence/local-barcode-qualification.md | 20 +++++++++++++++++++- docs/installation-home-assistant.md | 2 ++ tests/backend/test_app_package.py | 14 +++++++------- 9 files changed, 49 insertions(+), 19 deletions(-) diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md index 18e3214..c441ad4 100644 --- a/addon-edge/CHANGELOG.md +++ b/addon-edge/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.0.0-edge.55 + +- Align barcode HTTP validation and published API schemas with the supported printed GTIN lengths. + ## 0.0.0-edge.54 - Continue keyboard focus to the current barcode result after confirmed changes and stale-removal review. diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md index 48f226f..222a1ff 100644 --- a/addon-edge/DOCS.md +++ b/addon-edge/DOCS.md @@ -1,6 +1,6 @@ # Installation and operation -Edge 0.0.0-edge.54 packages the immutable runtime declared in +Edge 0.0.0-edge.55 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 @@ -49,6 +49,9 @@ focus to its result or retry control when the read finishes. After a confirmed change, focus continues to the current result. If a write reply is unconfirmed, focus continues to **Recover original request**. +Edge.55 aligns HTTP validation and the published API shapes with the supported +printed barcode lengths. It retains schema 35 and the compatible Edge.54 data. + Edge.52 uses SQLite schema 35 and is listed in `breaking_versions`. Keep a compatible image together with its cold schema-34 data for rollback. diff --git a/addon-edge/Dockerfile b/addon-edge/Dockerfile index aa04f9a..bbf5ed1 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=b2f9f48994d523e28c4584f583e1c929ecbc61b1 -ARG DOMUS_SOURCE_SHA256=23c9240e137ed578ee6e52b68e4318b3e0153ca2ad32940088f20635931c2918 +ARG DOMUS_SOURCE_COMMIT=e8e93fe892babc0263808848c3bd24c8aea9d2c2 +ARG DOMUS_SOURCE_SHA256=eca392d17f93d6eb25006b78a5690f25680b09f8c625feb0ec8093dbb7bbc4a5 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.54 +ARG BUILD_VERSION=0.0.0-edge.55 ARG BUILD_ARCH -ARG DOMUS_SOURCE_COMMIT=b2f9f48994d523e28c4584f583e1c929ecbc61b1 +ARG DOMUS_SOURCE_COMMIT=e8e93fe892babc0263808848c3bd24c8aea9d2c2 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 c4dc8ad..0057a95 100644 --- a/addon-edge/README.md +++ b/addon-edge/README.md @@ -38,6 +38,9 @@ submitted search. Edge.54 continues keyboard focus after confirmed barcode changes and moves it to original-request recovery when a write response is unconfirmed. +Edge.55 aligns barcode HTTP validation and published API schemas with the same +supported printed lengths. + This candidate uses SQLite schema 35. Keep a compatible image and cold data backup before upgrading a previous preview. See [installation and operation](https://github.com/vypdev/domus/blob/develop/addon-edge/DOCS.md) for the source pin and rollback diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json index d45a2f1..e1f9ffb 100644 --- a/addon-edge/artifact.json +++ b/addon-edge/artifact.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, - "version": "0.0.0-edge.54", - "sourceCommit": "b2f9f48994d523e28c4584f583e1c929ecbc61b1", - "sourceArchiveSHA256": "23c9240e137ed578ee6e52b68e4318b3e0153ca2ad32940088f20635931c2918", + "version": "0.0.0-edge.55", + "sourceCommit": "e8e93fe892babc0263808848c3bd24c8aea9d2c2", + "sourceArchiveSHA256": "eca392d17f93d6eb25006b78a5690f25680b09f8c625feb0ec8093dbb7bbc4a5", "storageSchema": 35, - "wheelSHA256": "b9e3fd518a611d7ef9cef215d23355e2bdce91e7a7b9a5ecdbf7653753eb2a07", + "wheelSHA256": "35262f4448e6ddeee76882e6096b5f8fb666a1cbd043bdce1068f24574d284fb", "pythonFiles": { "domus/__init__.py": "7182c88b92234b4328f94497f4e70222d4390d8093e4b62893dfa78ac5530ac6", "domus/application/__init__.py": "1e8c0c87bf2a8ca947112543070583c0cc55d9d40b56eab0d86ed59a4ec1e82c", @@ -165,7 +165,7 @@ "domus/entrypoints/http_errors.py": "c4f3d19889750bca29a13aee7528299883782e50a5ae3378e691d79e8faf7ded", "domus/entrypoints/ingress_boundary.py": "1aa1d684b8625464b5d36d272f71d94b4cd32b84819ff8765a821c9a722f8f28", "domus/entrypoints/ingress_http.py": "f6557eb5481d132131f66ad7691e30c223c63a66a6f0ae5754c9fba3bc7f3626", - "domus/entrypoints/inventory_http.py": "507873935dc9ed813c189b47a7ddc581802ceae854f555533e1e94a4046bb34d", + "domus/entrypoints/inventory_http.py": "719e2c3a0d70a42cb4b3c42f8941841ea8e87ca5745c3fba94657226390142b3", "domus/entrypoints/native_http.py": "6c4471c6468b64d9f38e1c74e0338fae9eaf0dbbf73ba8b93a9f868317a220fc", "domus/entrypoints/openapi.py": "01a3fab9e5890ebcc1fb9c70bce9ced43d45b9190afd134db7dd45e0c5eb28f1", "domus/entrypoints/point_allocation_http.py": "7339c88c083206c0778885b55793c80af219b15af7004c5a51d34dbc28f4da5c", diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml index 43873a9..2b2fcfc 100644 --- a/addon-edge/config.yaml +++ b/addon-edge/config.yaml @@ -1,5 +1,5 @@ name: Domus Edge -version: "0.0.0-edge.54" +version: "0.0.0-edge.55" slug: domus_edge description: Development preview of the local Domus household application url: https://github.com/vypdev/domus diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index ab27be2..b998e6e 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -36,7 +36,7 @@ the old confirmation. Scope changes retire private facts and drafts. | stock-local-barcode-C07 | Ingress and standalone journeys exercise English desktop keyboard, Spanish 390 px touch, light and dark themes, focus, malformed input, selection, confirmation, current conflicts and explicit read retry. [Compiled journeys](../../frontend/tests/e2e/workspace-navigation.spec.ts) | | stock-local-barcode-C08 | The immutable Edge candidate requires both CPU image campaigns and installed-owner acceptance. The increment's pull request records their measured source identities and outcomes. | -The complete backend campaign passes 5,569 tests with 100% statement and branch +The complete backend campaign passes 5,583 tests with 100% statement and branch coverage globally and across all 231 authored modules. An independent source coverage audit accepts the report. The complete frontend campaign passes 1,929 tests with all four metrics at 100% globally and per authored runtime file. @@ -153,3 +153,21 @@ Both journeys pass without a Domus CSS change. Original screenshots and measured layout attachments are retained. The first diagnostic passed the layout checks but failed a new test expectation for light text color; the expectation was corrected to the existing `#172b3a` without changing application colors. + +## Immutable Edge.55 candidate + +Edge.55 packages the reviewed HTTP contract refinement from runtime source +`e8e93fe892babc0263808848c3bd24c8aea9d2c2`. Its source archive SHA-256 is +`eca392d17f93d6eb25006b78a5690f25680b09f8c625feb0ec8093dbb7bbc4a5`. +The normal and independently measured Linux wheels share SHA-256 +`35262f4448e6ddeee76882e6096b5f8fb666a1cbd043bdce1068f24574d284fb`. +All 231 Python modules match Git, the wheel, installed Linux builder and final +image. All four UI files match the accepted Edge.54 bytes. Only the HTTP barcode +annotation changes between those runtime sources. Schema 35 is retained. + +The measured local ARM64 image is +`sha256:e0cb412274443805bef5b8f72150c8c4c9c2d0b1b3c1399f31eebb5cfe081fb0`. +Installed Home Assistant observations remain a separate acceptance record; this +local image ID is not an assertion about the Supervisor image. Both exact CPU +campaigns, installed acceptance and final same-head review are tracked in the +increment's pull request. diff --git a/docs/installation-home-assistant.md b/docs/installation-home-assistant.md index ad2e56d..f5ba43b 100644 --- a/docs/installation-home-assistant.md +++ b/docs/installation-home-assistant.md @@ -15,6 +15,8 @@ Edge.53 continues keyboard focus to the result or retry control after a submitte search. Edge.54 continues focus after confirmed barcode changes and moves it to original request recovery when a write response is unconfirmed. +Edge.55 aligns barcode HTTP validation and published API schemas with the same +supported printed lengths. [Qualification](evidence/local-barcode-qualification.md) Edge.51 lets members start, block and unblock eligible work from Tasks. It keeps diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py index 494ffba..ac45672 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.54" + assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.55" 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": []} @@ -65,15 +65,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] == "b2f9f48994d523e28c4584f583e1c929ecbc61b1" + assert commits[0] == "e8e93fe892babc0263808848c3bd24c8aea9d2c2" assert ( - "DOMUS_SOURCE_SHA256=23c9240e137ed578ee6e52b68e4318b3e0153ca2ad32940088f20635931c2918" + "DOMUS_SOURCE_SHA256=eca392d17f93d6eb25006b78a5690f25680b09f8c625feb0ec8093dbb7bbc4a5" in source ) - assert "ARG BUILD_VERSION=0.0.0-edge.54" in source + assert "ARG BUILD_VERSION=0.0.0-edge.55" in source candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text()) assert candidate["sourceCommit"] == commits[0] - assert candidate["version"] == "0.0.0-edge.54" + assert candidate["version"] == "0.0.0-edge.55" 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 @@ -150,8 +150,8 @@ def test_edge_artifact_declares_exact_reviewed_runtime_without_rebinding_histori "pythonFiles", "uiFiles", } - assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.54" - assert artifact["sourceCommit"] == "b2f9f48994d523e28c4584f583e1c929ecbc61b1" + assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.55" + assert artifact["sourceCommit"] == "e8e93fe892babc0263808848c3bd24c8aea9d2c2" assert artifact["storageSchema"] == 35 for field in ["sourceArchiveSHA256", "wheelSHA256"]: assert re.fullmatch("[a-f0-9]{64}", artifact[field]) From 4556aa1612e4eea6cefb3acba4e5371a4475b990 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 21:55:45 +0100 Subject: [PATCH 13/16] test: coordinate task creation and bound complete workspace journeys --- docs/evidence/local-barcode-qualification.md | 21 +++++++++++++++++++ frontend/tests/e2e/tasks.spec.ts | 4 ++++ .../tests/e2e/workspace-navigation.spec.ts | 3 ++- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index b998e6e..4709ee6 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -171,3 +171,24 @@ Installed Home Assistant observations remain a separate acceptance record; this local image ID is not an assertion about the Supervisor image. Both exact CPU campaigns, installed acceptance and final same-head review are tracked in the increment's pull request. + +## Final package CI diagnostics + +The initial Edge.55 package campaign passed both 66-case actual-image suites, +while its source frontend campaign passed 119 cases and failed two time bounds. +The progress case checked its heading after five seconds while the original +creation POST was still pending. It now explicitly requires that same POST to +return HTTP 200 within the existing 15-second transport bound before checking +the projection. The complete standalone workspace journey exhausted its +75-second case budget during a preview retry, after earlier task creation alone +took 8.87 seconds. Its case budget is now 120 seconds; the suite remains bounded +at 900 seconds with zero retries and every existing assertion retained. + +Both unchanged failing cases passed in an isolated 63.87-second diagnostic +before these harness refinements. That repeat does not establish the cause of +the slower server responses. The original CI log, report, two traces and failure +screenshots remain retained. These changes affect test coordination and its +documented time budget; the Edge.55 runtime and immutable package pins remain +unchanged. The complete local campaign after the refinement passes all 121 +cases with no skipped, unexpected or flaky results and zero retries. Final +same-head qualification is recorded in the pull request. diff --git a/frontend/tests/e2e/tasks.spec.ts b/frontend/tests/e2e/tasks.spec.ts index 4fe09c3..2736db8 100644 --- a/frontend/tests/e2e/tasks.spec.ts +++ b/frontend/tests/e2e/tasks.spec.ts @@ -694,7 +694,11 @@ for (const mode of ['native', 'standalone'] as const) { await page.getByRole('combobox', {name: 'Language', exact: true}).selectOption(locale); const title = 'Progress 🧰'; await tasks.getByLabel(t('Title', 'Título'), {exact: true}).fill(title); + // Await this transaction within the existing HTTP bound before checking its projection. + const creation = page.waitForResponse(response => response.request().method() === 'POST' + && response.url() === base(mode) + '/api/v1/tasks/definitions', {timeout: 15_000}); await activate(tasks.getByRole('button', {name: t('Create task', 'Crear tarea'), exact: true})); + expect((await creation).status()).toBe(200); await expect(tasks.getByRole('heading', {name: title, exact: true})).toBeVisible(); const list = await (await page.request.get(base(mode) + '/api/v1/tasks/occurrences')).json(); const id = list.items.find((item: {title: string}) => item.title === title).occurrence_id; diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index 8fd0cdb..94b5b14 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -169,7 +169,8 @@ for (const mode of ['native', 'standalone'] as const) { for (const mode of ['native', 'standalone'] as const) { test(`shared workspace navigation in ${mode}`, async ({page, context, request}, info) => { - test.setTimeout(75_000); + // This complete workspace journey includes several domains and retained screenshots. + test.setTimeout(120_000); const origin = `http://127.0.0.1:${mode === 'native' ? 56174 : 56175}`; const base = origin + (mode === 'native' ? ingress : '') + '/'; if (process.env.DOMUS_BROWSER_IMAGE) { From 52ab6e15e05f25ef6893f610f0e29cda3203b1a0 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Fri, 20 Nov 2026 00:51:43 +0100 Subject: [PATCH 14/16] test: await real projection and access reconciliation in workspace fixtures --- docs/evidence/local-barcode-qualification.md | 20 +++++++++++++++++ .../tests/e2e/workspace-navigation.spec.ts | 13 +++++++++++ tests/browser/entry_server.py | 22 ++++++++++++++++++- 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index 4709ee6..7dc8474 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -192,3 +192,23 @@ documented time budget; the Edge.55 runtime and immutable package pins remain unchanged. The complete local campaign after the refinement passes all 121 cases with no skipped, unexpected or flaky results and zero retries. Final same-head qualification is recorded in the pull request. + +The subsequent source campaign passed 120 cases, then an Overview-to-Tasks +navigation lost its household projection after two authorization reads returned +503 `storage_busy`. Its original trace, error response bodies, screenshot and +report remain retained. The unchanged standalone journey passed an isolated +repeat in 51.7 seconds. The calendar fixture prepares completed and approved +past work as well as the future occurrence used by this navigation. + +The fixture now exposes a read-only projection-readiness observation. Before +the navigation assertions, both composed journeys wait until the actual Points +consumer has processed the seeded lifecycle events and its worker is still +running. They also await the owning household's access reconciliation rather +than treating the first successful task-detail response as its completion. +This neither advances a fake consumer nor pauses a production worker; +all task states, authorization checks, normal unavailable-state behavior and +existing journey assertions remain. The trace establishes storage contention, +but does not independently identify which transaction owned the writer. +Both complete workspace journeys pass after this preparation change, with no +skipped, unexpected or flaky results and zero retries. Final same-head CI still +repeats the full source, catalog and actual-image qualification. diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index 94b5b14..ee52279 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -1212,9 +1212,20 @@ for (const mode of ['native', 'standalone'] as const) { expect((await dueDetail).ok()).toBe(true); await expect(tasksRegion.getByRole('heading',{name:'Read the water meter',exact:true})).toBeFocused(); + // A detail response precedes the owning household's final access reconciliation. + const settledHousehold = page.getByRole('button', { + name:/^(Close this view|Cerrar esta vista|Sign out of Domus|Cerrar sesión en Domus)$/u, + }); + await expect(settledHousehold).toBeEnabled({timeout:15_000}); const scheduled = await request.post(origin + '/__fixture__/calendar-review'); expect(scheduled.ok()).toBe(true); const {title:maintenanceTitle, future:maintenanceId, new_date:maintenanceDay} = await scheduled.json(); + // Preparation also completes and approves past work. Await its real asynchronous projection. + await expect.poll(async () => { + const ready = await request.get(origin + '/__fixture__/points-ready'); + expect(ready.ok()).toBe(true); + return ready.json(); + }, {timeout:15_000}).toEqual({ready:true, worker_running:true}); const maintenanceURL = base + 'api/v1/tasks/occurrences/' + maintenanceId; const label = (locale: 'en' | 'es', state: string) => { const deadline = new Intl.DateTimeFormat(locale, @@ -1236,6 +1247,7 @@ for (const mode of ['native', 'standalone'] as const) { expect((await keyboardDetail).ok()).toBe(true); await expect(tasksRegion).toBeFocused(); await expect(tasksRegion.getByRole('heading',{name:maintenanceTitle,exact:true})).toBeVisible(); + await expect(settledHousehold).toBeEnabled({timeout:15_000}); await page.getByLabel('Language',{exact:true}).selectOption('es'); await page.setViewportSize({width:390,height:844}); @@ -1249,6 +1261,7 @@ for (const mode of ['native', 'standalone'] as const) { expect((await touchDetail).ok()).toBe(true); await expect(tasksRegion).toBeFocused(); await expect(tasksRegion.getByRole('heading',{name:maintenanceTitle,exact:true})).toBeVisible(); + await expect(settledHousehold).toBeEnabled({timeout:15_000}); await tabs.getByRole('link',{name:'Inicio',exact:true}).tap(); await unclaimedItem.tap(); diff --git a/tests/browser/entry_server.py b/tests/browser/entry_server.py index 9475577..5be3b95 100644 --- a/tests/browser/entry_server.py +++ b/tests/browser/entry_server.py @@ -38,7 +38,7 @@ VerifyTask, ) from domus.composition import admin, ingress, server -from domus.domain.errors import Forbidden, IdentityRejected, IdentityUnavailable +from domus.domain.errors import Forbidden, IdentityRejected, IdentityUnavailable, StorageBusy from domus.domain.identity import HumanIdentity from domus.domain.nominal_recurrence import CalendarNominalExpansion from domus.domain.recurrence_rule_text import parse_fixed_pattern @@ -319,6 +319,24 @@ def seed_calendar_review(self) -> dict: "new_date": final.date().isoformat(), } + def points_ready(self) -> dict: + """Observe real projection progress without advancing or pausing its worker.""" + worker = self.runtime.points_worker + assert worker is not None and self.runtime.storage is not None + ready = False + try: + with self.runtime.storage.database.read() as unit: + home = unit.households.current() + if home is not None: + ready = not unit.tasks.lifecycle_events( + home.household_id, + limit=1, + after=unit.points.position(home.household_id), + ) + except StorageBusy: + pass # A live projection can temporarily own the writer during fixture preparation. + return {"ready": ready, "worker_running": worker.is_running} + def stats(self) -> dict: with sqlite3.connect(f"file:{self.database}?mode=ro", uri=True) as connection: counts = { @@ -359,6 +377,8 @@ async def __call__(self, scope, receive, send) -> None: response = JSONResponse(self.stats()) elif path == "/__fixture__/calendar-review" and request.method == "POST": response = JSONResponse(self.seed_calendar_review()) + elif path == "/__fixture__/points-ready" and request.method == "GET": + response = JSONResponse(self.points_ready()) elif path == "/__fixture__/operator" and request.method == "POST": values = await request.json() assert set(values) == {"action"} From 1c7b3f0b52ff25a29b9fa884ad4912fd576f98e7 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Fri, 20 Nov 2026 01:31:22 +0100 Subject: [PATCH 15/16] fix(inventory): retire private views after rejected access --- docs/evidence/local-barcode-qualification.md | 37 +++++++++++ .../evidence/task-navigation-integration.json | 17 ++++- .../src/application/inventory-controller.ts | 13 +++- frontend/src/presentation/domus-inventory.ts | 3 +- .../tests/e2e/workspace-navigation.spec.ts | 18 ++++++ frontend/tests/inventory.test.ts | 62 +++++++++++++++++++ 6 files changed, 143 insertions(+), 7 deletions(-) diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index 7dc8474..4e2ebbd 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -212,3 +212,40 @@ but does not independently identify which transaction owned the writer. Both complete workspace journeys pass after this preparation change, with no skipped, unexpected or flaky results and zero retries. Final same-head CI still repeats the full source, catalog and actual-image qualification. + + +## Rejected-access review correction + +The final `52ab6e1` review found that a barcode HTTP 401 or 403 retired the +lookup result but retained the previously loaded catalog. The Inventory adapter +correctly distinguished rejected access from unavailable transport; its controller +had erased that distinction. Four new regressions reproduced the retained private +report across both HTTP compositions. The two corresponding HTTP 503 controls +passed with the existing retry behavior. + +The shared Inventory read boundary now retires loaded product, history, shopping, +association and receipt facts after current authentication or authorization is +rejected. Management controls disappear, and another barcode query or write cannot +use the old report. A current explicit refresh must authorize a new report. +An unresolved original command stays in its journal without another POST. +Transient unavailable reads retain the input and their normal explicit retry. + +A submitted barcode lookup that loses its report continues focus to Refresh +inventory. Both full barcode journeys exercise 401 and 403, verify removal of +private product/history and management views, then refresh current authorized +state and reuse the entered digits. Original screenshots distinguish each status. +Both compositions pass these complete journeys without retries; all eight native +specification cases and their identities remain unchanged. A new immutable Edge +candidate, exact CPU campaigns and installed acceptance are required for this UI +change; the previously accepted Edge.55 remains historical evidence and rollback. + +The corrected interface passes 1,936 unit cases, with all four coverage metrics +at 100% globally and per authored file and the independent audit passing. +The first normal-wheel check correctly rejected the previous Edge.55 bundle +fingerprints. The integration receipt now records the newly measured four-file +bundle and retains the previous bytes as its accepted historical input. + +The final corrected source campaign passes all 121 journeys in 364.896745 +seconds, with zero skipped, unexpected or flaky results. The rebuilt catalog +passes all 45 cases in 29.439194 seconds under the same zero-retry policy. +The normal wheel contract passes with the current bundle fingerprints. diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json index 45ac496..11b228d 100644 --- a/docs/evidence/task-navigation-integration.json +++ b/docs/evidence/task-navigation-integration.json @@ -5,10 +5,10 @@ "command": "pnpm build:frontend", "scope": "Compiled household workspace with protected manual automation preview, saved revisions, explicit runs and scoped run history, daily schedule previews and inactive daily drafts, 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. Points-allocation cards inherit the shared raised surface in both color schemes. The Tasks workspace supports planned task assignment, state-permitted release, retained conflict selections and original assignment-request recovery. The Tasks workspace also confirms Start, Block and Unblock, retains a bounded blocking reason through explicit current-task review and recovers the original progress request. Inventory supports manually entered local GTIN lookup, explicit product association and removal review, stale-association recovery and retained original barcode requests.", "actualProductFiles": { - ".vite/manifest.json": "d0c30babfcbb32c3d008981d04c56745d8be171fdfff8724137a3bed98732ba8", + ".vite/manifest.json": "4cbe45655f8d01448745d65ff235df5645464430192d5b95059f8ffa108525f2", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "assets/index-DOg1mB8K.js": "d6231483e8ba95c3eecfd923c04c8abafadcd7c15ce146cbb50bdcadcededfd6", - "index.html": "9a0eb467ea4afb8ab10d3df9ffcf4d2b31b188c6ec6e5d3c20206d86224ee9b7" + "assets/index-_Wife6Ef.js": "159d5ad4f52250dc9a68aafcbf2ee418b97ad7504684869a36fdeec751ee2fb6", + "index.html": "6534890312bfa5f4c7a2b8a9b5705eba0be7cd5d38982544dfe743ca99e66dd2" }, "localValidation": { "commit": "9a10d8114869be754962953903e773fe8e12c723", @@ -317,5 +317,16 @@ "scope": "Compiled task workspace with readable household and task points-allocation cards during open-task list qualification.", "requirements": "ha-open-tasks-C07", "evidence": "ha-open-tasks-qualification.md" + }, + "barcodeBeforeRejectedAccessReview": { + "sourceCommit": "e8e93fe892babc0263808848c3bd24c8aea9d2c2", + "actualProductFiles": { + ".vite/manifest.json": "d0c30babfcbb32c3d008981d04c56745d8be171fdfff8724137a3bed98732ba8", + "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", + "assets/index-DOg1mB8K.js": "d6231483e8ba95c3eecfd923c04c8abafadcd7c15ce146cbb50bdcadcededfd6", + "index.html": "9a0eb467ea4afb8ab10d3df9ffcf4d2b31b188c6ec6e5d3c20206d86224ee9b7" + }, + "scope": "Accepted Edge.55 runtime before retiring retained Inventory facts after current access rejection.", + "evidence": "local-barcode-qualification.md" } } diff --git a/frontend/src/application/inventory-controller.ts b/frontend/src/application/inventory-controller.ts index e2c250d..21f3ac5 100644 --- a/frontend/src/application/inventory-controller.ts +++ b/frontend/src/application/inventory-controller.ts @@ -3,6 +3,7 @@ import {canonicalGtin, inventoryCommand, shoppingItemKey} from '../domain/invent import type {BarcodeLookup, BaseUnit, InventoryCommand, InventoryReport, MovementHistory, PurchaseReceipts, Purchases, PurchaseSessionDetail, PurchaseSessions, ShoppingAction, ShoppingList, ShoppingSources} from '../domain/inventory'; import type {JournalContext} from '../domain/journal'; import type {EntryEntropy, EntryRead} from './ports'; +import {EntryReadError} from './ports'; export const INVENTORY_ERRORS = ['permission_denied', 'idempotency_conflict', 'invalid_request', 'invalid_inventory_barcode', 'inventory_barcode_linked', 'inventory_barcode_changed', @@ -140,7 +141,7 @@ export class InventoryController { const loaded = await this.run(this.server.barcode(state.scope, code), lookup => { this.set({barcode: {code, lookup, unavailable: false}}); }, state.pending ? state.notice : null); - if (!loaded && this.view?.scope === state.scope) + if (!loaded && this.view?.scope === state.scope && this.view.report !== null) this.set({barcode: {code, lookup: null, unavailable: true}}); } @@ -352,8 +353,14 @@ export class InventoryController { if (this.owned !== owned) return false; use(value); return true; - } catch { - if (this.owned === owned) this.set({notice}); + } catch (error) { + if (this.owned === owned) { + if (error instanceof EntryReadError && (error.code === 'authentication_required' || error.code === 'forbidden')) + this.set({report:null, history:null, purchases:null, purchaseReceipts:null, + shoppingList:null, shoppingSources:null, purchaseSessions:null, purchaseSession:null, + shoppingFocus:undefined, barcode:null, result:null, notice:this.view!.pending ? 'uncertain' : 'unavailable'}); + else this.set({notice}); + } return false; } finally { if (this.owned === owned) { diff --git a/frontend/src/presentation/domus-inventory.ts b/frontend/src/presentation/domus-inventory.ts index 03daa24..885043a 100644 --- a/frontend/src/presentation/domus-inventory.ts +++ b/frontend/src/presentation/domus-inventory.ts @@ -212,7 +212,8 @@ export class DomusInventory extends LitElement { const owner = this.view!; const target = this.renderRoot.querySelector(owner.pending ? '.inventory-actions vyp-ha-button:last-child' - : this.barcodeState()?.unavailable ? '.barcode-search-form vyp-ha-button' : '.barcode-result'); + : owner.report === null ? '.inventory-actions vyp-ha-button:first-child' + : this.barcodeState()?.unavailable ? '.barcode-search-form vyp-ha-button' : '.barcode-result'); if (target) { void this.updateComplete.then(() => { if (this.view !== owner) return; diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index ee52279..58ae6cf 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -163,6 +163,24 @@ for (const mode of ['native', 'standalone'] as const) { await expect(searchCard).toHaveCSS('background-color', 'rgb(255, 255, 255)'); await expect(searchCard).toHaveCSS('color', 'rgb(23, 43, 58)'); await stock.screenshot({path:info.outputPath('barcode-long-name-result-es.png')}); + for (const status of [401, 403]) { + await page.route(lookup, route => route.fulfill({status, contentType:'application/json', + headers:{'Cache-Control':'no-store'}, body:JSON.stringify({state:'blocked', + code:status === 401 ? 'authentication_required' : 'permission_denied', + message:'Access rejected.', action_required:'Review current access.', correlation_id:'cor_barcode_access'})}), {times:1}); + await stock.getByRole('button', {name:'Buscar producto', exact:true}).tap(); + await expect(stock.getByText('El inventario no está disponible. Actualiza para consultar el stock.', {exact:true})).toBeVisible(); + await expect(stock.getByRole('article', {name:'QA barcode soap', exact:true})).toHaveCount(0); + await expect(stock.locator('.registration-form, .barcode-search-form, .barcode-review, .history')).toHaveCount(0); + const refresh = stock.getByRole('button', {name:'Actualizar inventario', exact:true}); + await expect(refresh).toBeFocused(); + await stock.screenshot({path:info.outputPath('barcode-access-' + status + '-es.png')}); + await refresh.tap(); + await expect(spanish).toHaveValue('036000291452'); + await expect(stock.getByRole('article', {name:'QA barcode soap', exact:true})).toBeVisible(); + await stock.getByRole('button', {name:'Buscar producto', exact:true}).tap(); + await expect(stock.locator('.barcode-result')).toContainText(longName); + } expect(external).toEqual([]); }); } diff --git a/frontend/tests/inventory.test.ts b/frontend/tests/inventory.test.ts index 3ed92da..e480f42 100644 --- a/frontend/tests/inventory.test.ts +++ b/frontend/tests/inventory.test.ts @@ -2064,6 +2064,42 @@ test('barcode query failure retires old facts and supports an explicit read retr expect(f.current()?.report).toBeNull(); }); +test.each((['native', 'standalone'] as const).flatMap(mode => + [401, 403, 503].map(status => ({mode, status}))))( + 'barcode HTTP $status in $mode retires rejected access but preserves recoverable unavailable reads', async ({mode, status}) => { + const f = controller(), app = f.controller; + app.bind(scope); + await vi.waitFor(() => expect(f.current()?.busy).toBe(false)); + await app.showHistory('product'); + await app.showPurchases(); + await app.showPurchaseReceipts('purchase'); + const server = http([[status, failure('permission_denied')]], mode).server; + f.barcodes.mockImplementationOnce((current, value) => server.barcode(current, value)); + await app.showBarcode('036000291452'); + const {node, root} = component(); + node.view = f.current()!; + await node.updateComplete; + if (status === 503) { + expect(f.current()?.report).toEqual(report); + expect(f.current()?.barcode).toMatchObject({lookup: null, unavailable: true}); + expect(root.textContent).toContain(register.name); + } else { + expect(f.current()).toMatchObject({report: null, history: null, purchases: null, + purchaseReceipts: null, barcode: null, result: null, notice: 'unavailable'}); + expect(root.textContent).not.toContain(register.name); + expect(root.querySelector('.registration-form')).toBeNull(); + expect(root.querySelector('.barcode-search-form')).toBeNull(); + await app.submit(register); + expect(f.send).not.toHaveBeenCalled(); + await app.showBarcode('036000291452'); + expect(f.barcodes).toHaveBeenCalledOnce(); + } + await app.refresh(); + expect(f.current()?.report).toEqual(report); + await app.showBarcode('036000291452'); + expect(f.current()?.barcode?.lookup?.barcode).toBe('00036000291452'); +}); + test('retired barcode reads cannot populate another household scope', async () => { const f = controller(), app = f.controller; app.bind(scope); @@ -2082,6 +2118,24 @@ test('retired barcode reads cannot populate another household scope', async () = expect(f.current()?.barcode).toBeUndefined(); }); +test('barcode access rejection preserves an unresolved original command without retaining private facts', async () => { + const f = controller(), app = f.controller; + app.bind(scope); + await vi.waitFor(() => expect(f.current()?.busy).toBe(false)); + const command = {action:'inventory.link-barcode',barcode:'00036000291452',product_id:'product'} as const; + f.send.mockReturnValueOnce(lost()); + await app.submit(command); + const original = f.journal.open(scope.key); + f.barcodes.mockImplementationOnce((current, value) => + http([[403, failure('permission_denied')]]).server.barcode(current, value)); + await app.showBarcode(command.barcode); + expect(f.current()).toMatchObject({report:null, barcode:null, pending:true, notice:'uncertain'}); + expect(f.journal.open(scope.key)).toEqual(original); + expect(f.send).toHaveBeenCalledOnce(); + await app.refresh(); + expect(f.current()).toMatchObject({report, pending:true, notice:'uncertain'}); +}); + test('lost barcode writes recover their original receipt and refresh current association facts', async () => { const f = controller(), app = f.controller; const barcode = '00036000291452'; @@ -2173,6 +2227,14 @@ test('a submitted barcode search continues to its result or retry without reclai expect(f.root.activeElement).toBe(retry); expect(retry.shadowRoot!.activeElement).toBe(retry.shadowRoot!.querySelector('button')); + await begin(); + await f.assign({...initial, notice: 'unavailable'}); + const refresh = f.root.querySelector('.inventory-actions vyp-ha-button')!; + await refresh.updateComplete; + expect(f.root.activeElement).toBe(refresh); + await f.assign(barcodeView); + expect(f.field()!.value).toBe('036000291452'); + await begin(); const moved = document.createElement('button'); moved.textContent = 'Another workspace action'; From d799da63ec0496b43f54d3ff7d91546addd78eb2 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Fri, 20 Nov 2026 01:36:38 +0100 Subject: [PATCH 16/16] build(edge): pin rejected-access correction in Edge.56 --- addon-edge/CHANGELOG.md | 5 ++++ addon-edge/DOCS.md | 7 +++++- addon-edge/Dockerfile | 8 +++--- addon-edge/README.md | 2 +- addon-edge/artifact.json | 14 +++++------ addon-edge/config.yaml | 2 +- docs/evidence/local-barcode-qualification.md | 26 ++++++++++++++++++++ frontend/tests/inventory.test.ts | 2 +- tests/backend/test_app_package.py | 14 +++++------ 9 files changed, 58 insertions(+), 22 deletions(-) diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md index c441ad4..a9a0a4f 100644 --- a/addon-edge/CHANGELOG.md +++ b/addon-edge/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 0.0.0-edge.56 + +- Retire loaded Inventory data and management controls when current access is rejected. +- Continue a rejected barcode search to Refresh inventory, preserving the input for an authorized retry. + ## 0.0.0-edge.55 - Align barcode HTTP validation and published API schemas with the supported printed GTIN lengths. diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md index 222a1ff..23db1bf 100644 --- a/addon-edge/DOCS.md +++ b/addon-edge/DOCS.md @@ -1,6 +1,6 @@ # Installation and operation -Edge 0.0.0-edge.55 packages the immutable runtime declared in +Edge 0.0.0-edge.56 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 @@ -52,6 +52,11 @@ focus continues to **Recover original request**. Edge.55 aligns HTTP validation and the published API shapes with the supported printed barcode lengths. It retains schema 35 and the compatible Edge.54 data. +Edge.56 hides the loaded catalog, history and management controls when current +access is rejected. The submitted barcode search focuses **Refresh inventory**. +Refresh checks current access before showing stock again and retains the entered +digits. An unresolved original write remains available for recovery. + Edge.52 uses SQLite schema 35 and is listed in `breaking_versions`. Keep a compatible image together with its cold schema-34 data for rollback. diff --git a/addon-edge/Dockerfile b/addon-edge/Dockerfile index bbf5ed1..0eb76cc 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=e8e93fe892babc0263808848c3bd24c8aea9d2c2 -ARG DOMUS_SOURCE_SHA256=eca392d17f93d6eb25006b78a5690f25680b09f8c625feb0ec8093dbb7bbc4a5 +ARG DOMUS_SOURCE_COMMIT=1c7b3f0b52ff25a29b9fa884ad4912fd576f98e7 +ARG DOMUS_SOURCE_SHA256=3a805018aea499f703cbe84b5576be1a9b0b50cd2d666bf7adacfaba04b35e54 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.55 +ARG BUILD_VERSION=0.0.0-edge.56 ARG BUILD_ARCH -ARG DOMUS_SOURCE_COMMIT=e8e93fe892babc0263808848c3bd24c8aea9d2c2 +ARG DOMUS_SOURCE_COMMIT=1c7b3f0b52ff25a29b9fa884ad4912fd576f98e7 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 0057a95..fca737f 100644 --- a/addon-edge/README.md +++ b/addon-edge/README.md @@ -41,7 +41,7 @@ original-request recovery when a write response is unconfirmed. Edge.55 aligns barcode HTTP validation and published API schemas with the same supported printed lengths. -This candidate uses SQLite schema 35. Keep a +Edge.56 retires loaded Inventory data when current access is rejected and focuses Refresh inventory. An authorized refresh preserves the entered barcode digits. This candidate uses SQLite schema 35. Keep a compatible image and cold data backup before upgrading a previous preview. See [installation and operation](https://github.com/vypdev/domus/blob/develop/addon-edge/DOCS.md) for the source pin and rollback instructions. diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json index e1f9ffb..9d07668 100644 --- a/addon-edge/artifact.json +++ b/addon-edge/artifact.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, - "version": "0.0.0-edge.55", - "sourceCommit": "e8e93fe892babc0263808848c3bd24c8aea9d2c2", - "sourceArchiveSHA256": "eca392d17f93d6eb25006b78a5690f25680b09f8c625feb0ec8093dbb7bbc4a5", + "version": "0.0.0-edge.56", + "sourceCommit": "1c7b3f0b52ff25a29b9fa884ad4912fd576f98e7", + "sourceArchiveSHA256": "3a805018aea499f703cbe84b5576be1a9b0b50cd2d666bf7adacfaba04b35e54", "storageSchema": 35, - "wheelSHA256": "35262f4448e6ddeee76882e6096b5f8fb666a1cbd043bdce1068f24574d284fb", + "wheelSHA256": "3a37f907e928c6a0ada988cfc27db0460d153a182ab8d95a2be753afb8ae742d", "pythonFiles": { "domus/__init__.py": "7182c88b92234b4328f94497f4e70222d4390d8093e4b62893dfa78ac5530ac6", "domus/application/__init__.py": "1e8c0c87bf2a8ca947112543070583c0cc55d9d40b56eab0d86ed59a4ec1e82c", @@ -239,9 +239,9 @@ "domus/infrastructure/task_materials.py": "d5d2934e36f290c7bf44b473392f014eab8749f1f3b3d26a3402079e65d2818f" }, "uiFiles": { - ".vite/manifest.json": "d0c30babfcbb32c3d008981d04c56745d8be171fdfff8724137a3bed98732ba8", + ".vite/manifest.json": "4cbe45655f8d01448745d65ff235df5645464430192d5b95059f8ffa108525f2", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "assets/index-DOg1mB8K.js": "d6231483e8ba95c3eecfd923c04c8abafadcd7c15ce146cbb50bdcadcededfd6", - "index.html": "9a0eb467ea4afb8ab10d3df9ffcf4d2b31b188c6ec6e5d3c20206d86224ee9b7" + "assets/index-_Wife6Ef.js": "159d5ad4f52250dc9a68aafcbf2ee418b97ad7504684869a36fdeec751ee2fb6", + "index.html": "6534890312bfa5f4c7a2b8a9b5705eba0be7cd5d38982544dfe743ca99e66dd2" } } diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml index 2b2fcfc..6575b3d 100644 --- a/addon-edge/config.yaml +++ b/addon-edge/config.yaml @@ -1,5 +1,5 @@ name: Domus Edge -version: "0.0.0-edge.55" +version: "0.0.0-edge.56" slug: domus_edge description: Development preview of the local Domus household application url: https://github.com/vypdev/domus diff --git a/docs/evidence/local-barcode-qualification.md b/docs/evidence/local-barcode-qualification.md index 4e2ebbd..da12745 100644 --- a/docs/evidence/local-barcode-qualification.md +++ b/docs/evidence/local-barcode-qualification.md @@ -249,3 +249,29 @@ The final corrected source campaign passes all 121 journeys in 364.896745 seconds, with zero skipped, unexpected or flaky results. The rebuilt catalog passes all 45 cases in 29.439194 seconds under the same zero-retry policy. The normal wheel contract passes with the current bundle fingerprints. + +## Immutable Edge.56 candidate + +Edge.56 packages the rejected-access correction from runtime source +`1c7b3f0b52ff25a29b9fa884ad4912fd576f98e7`. Its source archive SHA-256 is +`3a805018aea499f703cbe84b5576be1a9b0b50cd2d666bf7adacfaba04b35e54`. +The normal and independently measured Linux wheels share SHA-256 +`3a37f907e928c6a0ada988cfc27db0460d153a182ab8d95a2be753afb8ae742d`. +All 231 Python modules remain identical to Edge.55 and match Git/archive, +wheel and installed Linux builder. All four compiled UI files match the +current integration receipt and both wheel builds. Schema 35 and its +compatibility boundary remain unchanged. Exact final-image measurements, +installed Home Assistant acceptance and same-head CI/review remain separate +required observations in the increment pull request. + +The locally measured final ARM64 image is +`sha256:444a5e58a0bae3d34276679f866cfea2442d3958fd8e0c9641a4248269773950`. Its 231 Python and four UI files match the +source archive, wheel and installed builder. This local ID does not claim +the separately built Supervisor image has the same Docker identity. + +The source-commit CI rejected an untyped generic Element in the new focus +assertion. The local command had continued after its strict type-check failure; +the original local and CI logs are retained. Selecting the registered button +through its literal tag preserves its element type without changing the +assertion or runtime. The package-head validation uses checked subprocesses, +so any prerequisite failure stops the remaining pipeline. diff --git a/frontend/tests/inventory.test.ts b/frontend/tests/inventory.test.ts index e480f42..9039a91 100644 --- a/frontend/tests/inventory.test.ts +++ b/frontend/tests/inventory.test.ts @@ -2229,7 +2229,7 @@ test('a submitted barcode search continues to its result or retry without reclai await begin(); await f.assign({...initial, notice: 'unavailable'}); - const refresh = f.root.querySelector('.inventory-actions vyp-ha-button')!; + const refresh = f.root.querySelector('.inventory-actions')!.querySelector('vyp-ha-button')!; await refresh.updateComplete; expect(f.root.activeElement).toBe(refresh); await f.assign(barcodeView); diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py index ac45672..43fd469 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.55" + assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.56" 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": []} @@ -65,15 +65,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] == "e8e93fe892babc0263808848c3bd24c8aea9d2c2" + assert commits[0] == "1c7b3f0b52ff25a29b9fa884ad4912fd576f98e7" assert ( - "DOMUS_SOURCE_SHA256=eca392d17f93d6eb25006b78a5690f25680b09f8c625feb0ec8093dbb7bbc4a5" + "DOMUS_SOURCE_SHA256=3a805018aea499f703cbe84b5576be1a9b0b50cd2d666bf7adacfaba04b35e54" in source ) - assert "ARG BUILD_VERSION=0.0.0-edge.55" in source + assert "ARG BUILD_VERSION=0.0.0-edge.56" in source candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text()) assert candidate["sourceCommit"] == commits[0] - assert candidate["version"] == "0.0.0-edge.55" + assert candidate["version"] == "0.0.0-edge.56" 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 @@ -150,8 +150,8 @@ def test_edge_artifact_declares_exact_reviewed_runtime_without_rebinding_histori "pythonFiles", "uiFiles", } - assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.55" - assert artifact["sourceCommit"] == "e8e93fe892babc0263808848c3bd24c8aea9d2c2" + assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.56" + assert artifact["sourceCommit"] == "1c7b3f0b52ff25a29b9fa884ad4912fd576f98e7" assert artifact["storageSchema"] == 35 for field in ["sourceArchiveSHA256", "wheelSHA256"]: assert re.fullmatch("[a-f0-9]{64}", artifact[field])