diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md index e71d8e2..a714718 100644 --- a/addon-edge/CHANGELOG.md +++ b/addon-edge/CHANGELOG.md @@ -1,11 +1,25 @@ # Changelog +## 0.0.0-edge.28 + +- Refresh the Family summary when the household week changes while Overview is open. + +## 0.0.0-edge.27 + +- Show completed tasks and posted earned points for the current Family week on Overview. +- Open Family from the localized summary to review the full report and pending values. + ## 0.0.0-edge.26 - Let people with task configuration permission set optional base points when creating a task. - Keep the household default for title-only creation and accept localized decimal input. - Explain how to correct a fractional amount when the current allocation requires whole base points. +## 0.0.0-edge.22 + +- Show completed tasks and posted earned points for the current Family week on Overview in English and Spanish. +- Open Family from the summary to review pending work and the full report. + ## 0.0.0-edge.21 - Use singular units when reviewing an intake of exactly one item in English and Spanish. diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md index 2c0d16a..1079d47 100644 --- a/addon-edge/DOCS.md +++ b/addon-edge/DOCS.md @@ -1,11 +1,12 @@ # Installation and operation -Edge 0.0.0-edge.26 packages the immutable runtime declared in -[artifact.json](artifact.json). People with task configuration permission can set -optional base points when creating a task. Leaving the field empty uses the -household default. Home Assistant can read the same due-today and -overdue task counts shown on Overview through a dedicated installation grant. -Enable the [native deadline sensors](../docs/tasks/ha-deadline-sensors.md) using +Edge 0.0.0-edge.28 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. +People with task configuration permission can set optional base points when creating a task. +Leaving the field empty uses the household default. Home Assistant can read +the due-today and overdue task counts shown on Overview through a dedicated installation +grant. Enable the [native deadline sensors](../docs/tasks/ha-deadline-sensors.md) using the optional `ha_deadline_digest` setting. The calendar uses its own `ha_calendar_digest` setting. Both share the private app port `8100` when enabled. This preview retains SQLite schema 31. Edge.13 introduced that schema and diff --git a/addon-edge/Dockerfile b/addon-edge/Dockerfile index 793b9ec..a9ec093 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=691496c299ff371763e445acb9d36b9623a81404 -ARG DOMUS_SOURCE_SHA256=535c0b95a2db96fe3ebc927596f4e74f6eaadb7b641f2a674c23e672489f0d3b +ARG DOMUS_SOURCE_COMMIT=b2718e41793d274d22f6f6532da894ed3f158557 +ARG DOMUS_SOURCE_SHA256=e89f738343769db5d24ae5306c11d4c33ed2a4c3885eff46b64a6acbeed94a1a 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.26 +ARG BUILD_VERSION=0.0.0-edge.28 ARG BUILD_ARCH -ARG DOMUS_SOURCE_COMMIT=691496c299ff371763e445acb9d36b9623a81404 +ARG DOMUS_SOURCE_COMMIT=b2718e41793d274d22f6f6532da894ed3f158557 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 890997a..9a53a20 100644 --- a/addon-edge/README.md +++ b/addon-edge/README.md @@ -3,9 +3,8 @@ Development preview of Domus installed as a Home Assistant app. Open it through HA's Open Web UI using your existing Home Assistant session. -This preview lets people with task configuration permission set optional base -points when creating a task. It also includes Home Assistant sensors for the same due-today and -overdue task counts shown on Overview. +This Edge.28 preview shows the current Family week's completed tasks and posted +earned points on Overview. Open Family from the summary to see the full report. This candidate uses SQLite schema 31. Keep a compatible image and cold data backup before upgrading a previous preview. diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json index e3da5f0..64f2ad3 100644 --- a/addon-edge/artifact.json +++ b/addon-edge/artifact.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, - "version": "0.0.0-edge.26", - "sourceCommit": "691496c299ff371763e445acb9d36b9623a81404", - "sourceArchiveSHA256": "535c0b95a2db96fe3ebc927596f4e74f6eaadb7b641f2a674c23e672489f0d3b", + "version": "0.0.0-edge.28", + "sourceCommit": "b2718e41793d274d22f6f6532da894ed3f158557", + "sourceArchiveSHA256": "e89f738343769db5d24ae5306c11d4c33ed2a4c3885eff46b64a6acbeed94a1a", "storageSchema": 31, - "wheelSHA256": "5bb060c69c0b2caf9b9f8d99ecff0b56e44a3096f6339582816f5dd52c5bf089", + "wheelSHA256": "7a675fc84a4ae9ae839d5f08aeb44cb15033be251d4973b9ef7ec231fec6c1ab", "pythonFiles": { "domus/__init__.py": "7182c88b92234b4328f94497f4e70222d4390d8093e4b62893dfa78ac5530ac6", "domus/application/__init__.py": "1e8c0c87bf2a8ca947112543070583c0cc55d9d40b56eab0d86ed59a4ec1e82c", @@ -18,7 +18,7 @@ "domus/application/commands.py": "6d1d735b4a725086b0d37f6895dd4201f3944e132763f6825142e038f7635354", "domus/application/fair_recurrence.py": "ce4a9bbe48ed4762e0456669c21e1b6d573b3b9b7b53912a960bab797f7ad610", "domus/application/family_ports.py": "f2d089eb617b311b305f1ff696437bc5075b9092750b06a1189e4e51e93c5b16", - "domus/application/family_queries.py": "5d3b4f4db4beab3209c7097774b55fdfc73376af614a045e9d3022baaae40274", + "domus/application/family_queries.py": "2945045adada3c7bacba211a565ef2c19de3227a3dc6c0ab934dbea9fc93568f", "domus/application/fixed_batch_review.py": "ed4e8860c22dc2c0af3abd109eb2df0ad5d8d652ed76d770b043343e8b570f08", "domus/application/fixed_exception_review.py": "d05039b1752f158c690011b0bab06c2b6bad53854f45ee9d067ea490bcd426aa", "domus/application/fixed_materialization.py": "5f57bbbd92ed86caaa7751ab978ead0b95a9bf3c564065b2a2a25310be4f8289", @@ -97,7 +97,7 @@ "domus/composition/recurrence.py": "62adda116cec8667e9142b03f422a138818575cf5814a79e219a65999dbed1e6", "domus/composition/restore.py": "fe4f5040a99db1404938e402eefa54fc93139055a5bc92abdfb7bf35d0c87297", "domus/composition/server.py": "f857338e254477cd7b1d452fc85434e75fd7a25781ed237bb0d5658ac13ad719", - "domus/composition/tasks.py": "c35704cbeb496dd929b89e541d2856f94edf10b57766c239089f4c9dcae8a522", + "domus/composition/tasks.py": "6ac7d47cb443b8fd955edd3d9d0b04df407792e910c161e500b0f84b8ca40974", "domus/domain/__init__.py": "0aac8a2ba41471d7a174ef7baca6073c95009a9db96df3e032392aa4f80bd079", "domus/domain/activation.py": "fcb2e47e939127d5e254e2136fb7f1459b40fa8c8561100579fced49666ad0fe", "domus/domain/calendar_values.py": "5a0f3821391f10fbab05c00f775133683203e7f4b7c5861718bef1f98dedc219", @@ -144,18 +144,18 @@ "domus/entrypoints/calendar_http.py": "5a7359ac2a876296a13bfe4bc63ac69bd36aec48e55c536a20470a789a6fef13", "domus/entrypoints/console_recovery.py": "854a3f8d7a2e74f301ac5bd4b54682e409e2669a3bb7e05546e479c113c09026", "domus/entrypoints/entry_context.py": "c3c8b64c603dd4de8330f9e336754c190f793e245d0a8e0455ac06e110919f78", - "domus/entrypoints/family_http.py": "2a4030193a4c6b9d98353127f7a225cacf62a5aa55d5a2305c6ca1c8211c99e8", + "domus/entrypoints/family_http.py": "2a82211898be9d5cf69fbb0fc67f706e47dfeca93c1307e498e700056085b4b7", "domus/entrypoints/ha_calendar_http.py": "25f5d83257c5cf4ead15ad1232ee826be042387c01d609ecabc660ff4fbcf42e", "domus/entrypoints/ha_deadline_http.py": "c01085af95c101e8837dd2a077822ae399af7adaf7be7dbf24507fe30c8c3e77", "domus/entrypoints/ha_projection_http.py": "a061762e5088727351e8cdaefcaa909836d3a3c9c9e01dd64fe766acff5b5ea9", "domus/entrypoints/household_http.py": "37e948848115bfa8714c9cccc50058389114f2e665cad965a66964b0dcd098c8", - "domus/entrypoints/http.py": "d6e318bad8731c4edcba4da3bc15a762b7aa17610cd8a4d04c71bfd370b5ac96", + "domus/entrypoints/http.py": "e330d600a9397cf057e9843b33ed989d2c57737da1065df126256c7e44119e83", "domus/entrypoints/http_contract.py": "613be310d4ff6a6c7e2a699c20f1c4a142d0b34073629884e58e973c4b040039", "domus/entrypoints/http_errors.py": "7d838b6a0169de57b79b80efb8aec455560aa96bbd956334bcb5479f95e934f9", "domus/entrypoints/ingress_boundary.py": "1aa1d684b8625464b5d36d272f71d94b4cd32b84819ff8765a821c9a722f8f28", "domus/entrypoints/ingress_http.py": "f6557eb5481d132131f66ad7691e30c223c63a66a6f0ae5754c9fba3bc7f3626", "domus/entrypoints/inventory_http.py": "a62ee56429988b15e9ac5903cc78dfa7ea38884e3c1aaa5efc2c6722829d0437", - "domus/entrypoints/native_http.py": "067770c688cd044e2169a144ae4e53bd33586f948deac3239c2c601bbbd19088", + "domus/entrypoints/native_http.py": "38cf774fcf46c90ea12852ca87c50b7b4e7bb153f6b7b36c0ea227171ea0eff4", "domus/entrypoints/openapi.py": "01a3fab9e5890ebcc1fb9c70bce9ced43d45b9190afd134db7dd45e0c5eb28f1", "domus/entrypoints/point_allocation_http.py": "7339c88c083206c0778885b55793c80af219b15af7004c5a51d34dbc28f4da5c", "domus/entrypoints/recurrence_dto.py": "094e6f64e1f963bfb053e830b214eed1189258e4f0eb8ff15ddba1f059649a1a", @@ -164,7 +164,7 @@ "domus/entrypoints/schedule_creation_http.py": "2a3c3ea682f978eb2767dc8808a218c312861f31079cc2c76dbc3847ddec3197", "domus/entrypoints/task_category_http.py": "e5443015f5e5cb2684eb6807e0a3bac5116703b5611508281afd7d1addee9672", "domus/entrypoints/task_dto.py": "10657d1df0180bf05e71d1f38ac3214d2cea34c8822f50ea25ab331b9c014049", - "domus/entrypoints/task_http.py": "5189ade4f7ab546ba84d0b88a82b02bf7e53cc436bf312920ed6839761aa0810", + "domus/entrypoints/task_http.py": "e9a533d615be77f4b420f78aa5ac61212d0afd1ac1300add3e0cc22c02986e93", "domus/entrypoints/task_response.py": "d2f4c0795aee429fc318b32495601031c559fa38af1d7da63b4735f7e6eb5d13", "domus/entrypoints/ui_bundle.py": "beae3d4a7a57375ee195cca81efccdbc899d9db4286029d53eabaf30de6e14f7", "domus/entrypoints/ui_http.py": "b6c47baa742f3862173a93e4121dc9914fd972eb6287ffffb9ffccecbf2ebe4a", @@ -226,9 +226,9 @@ "domus/infrastructure/task_materials.py": "d5d2934e36f290c7bf44b473392f014eab8749f1f3b3d26a3402079e65d2818f" }, "uiFiles": { - ".vite/manifest.json": "734a1f5ba77da03257115ade8cb5f680b19febd79c853f95a3fa51993e0f2cdb", + ".vite/manifest.json": "ff8264fde84e7207e3ba230fdb7935716ce36902a765fa71523e22bb5ff1195f", + "assets/index-CX10IRLI.js": "838cb6fdacbd2f7f6e27b302c231c4fb6d5d49cd50e1cb3685ea7e4722c45e7a", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "assets/index-CrrA8YHS.js": "c32342fbb48c4d5e7266a3a6272e77d6a4479290440c4e801887750470b99bb2", - "index.html": "1198c1ad6b3475ec0c03041f145522f4454e7782aec020a2779204a4bea2f399" + "index.html": "c709edea7d9a6607c1064bd52bb500a25dc22e18e2852c76ff42394bb5516d04" } } diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml index bd2582e..0b284bc 100644 --- a/addon-edge/config.yaml +++ b/addon-edge/config.yaml @@ -1,5 +1,5 @@ name: Domus Edge -version: "0.0.0-edge.26" +version: "0.0.0-edge.28" slug: domus_edge description: Development preview of the local Domus household application url: https://github.com/vypdev/domus diff --git a/backend/src/domus/application/family_queries.py b/backend/src/domus/application/family_queries.py index b1b3224..8c4eaff 100644 --- a/backend/src/domus/application/family_queries.py +++ b/backend/src/domus/application/family_queries.py @@ -1,23 +1,24 @@ """Project private ledger and work facts from one authorized read transaction.""" from dataclasses import dataclass +from datetime import date, timedelta from typing import Literal from domus.application.authorization import HouseholdAccess from domus.application.calendar_queries import calendar_boundary from domus.application.family_ports import FamilyAllocationEvidence, FamilyLedgerEntry from domus.application.fixed_materialization import MaintenanceScope -from domus.application.ports import Transactions +from domus.application.ports import Clock, Transactions, UnitOfWork from domus.application.recurrence_ports import RecurrenceTimes from domus.application.reward_funding import reward_balance -from domus.application.task_authorization import TaskAccess +from domus.application.task_authorization import TaskAccess, TaskActor from domus.application.task_ports import TaskCursors from domus.domain.calendar_values import CalendarRange from domus.domain.identity import HumanIdentity, Permission from domus.domain.points import conserved_shares from domus.domain.recurrence_time import TimePolicy from domus.domain.rewards import RewardSpend -from domus.domain.storage import JsonDocument +from domus.domain.storage import Household, JsonDocument from domus.domain.task_values import VerificationState PENDING_LIMIT = 4 @@ -54,6 +55,13 @@ class FamilyReport: next_cursor: str | None +@dataclass(frozen=True, slots=True) +class FamilyWeek: + period: CalendarRange + earned_minor: int + completed_count: int + + @dataclass(frozen=True, slots=True) class FamilyQueries: transactions: Transactions @@ -62,12 +70,30 @@ class FamilyQueries: cursors: TaskCursors times: RecurrenceTimes + def _access(self, unit: UnitOfWork) -> tuple[Household, TaskActor]: + home = self.scope.require(unit) + HouseholdAccess(self.human).require(unit, home.household_id, Permission.HOUSEHOLD_READ) + actor = TaskAccess(self.human).require(unit, home.household_id, Permission.TASKS_READ) + return home, actor + + def overview(self, clock: Clock) -> FamilyWeek: + with self.transactions.read() as unit: + home, actor = self._access(unit) + policy = TimePolicy(home.time_zone, self.times.data_identity) + today = self.times.local_at(clock.now(), policy).local.date() + monday = today - timedelta(days=today.weekday()) + period = CalendarRange(max(date(1970, 1, 1), monday), monday + timedelta(days=7)) + start = calendar_boundary(period.start, self.times, policy) + end = calendar_boundary(period.end, self.times, policy) + household_id, member_id = home.household_id, actor.member.member_id + _, earned = unit.points.member_totals(household_id, member_id, start, end) + completed = sum(1 for _ in unit.points.member_work(household_id, member_id, start, end)) + return FamilyWeek(period, earned, completed) + def report(self, period: CalendarRange, *, limit: int, cursor: str | None) -> FamilyReport: with self.transactions.read() as unit: - home = self.scope.require(unit) + home, actor = self._access(unit) household_id = home.household_id - HouseholdAccess(self.human).require(unit, household_id, Permission.HOUSEHOLD_READ) - actor = TaskAccess(self.human).require(unit, household_id, Permission.TASKS_READ) member_id = actor.member.member_id policy = TimePolicy(home.time_zone, self.times.data_identity) start = calendar_boundary(period.start, self.times, policy) diff --git a/backend/src/domus/composition/tasks.py b/backend/src/domus/composition/tasks.py index aa41cb8..3071740 100644 --- a/backend/src/domus/composition/tasks.py +++ b/backend/src/domus/composition/tasks.py @@ -66,6 +66,9 @@ def queries() -> TaskQueries: schedule_data_identity=planner.times.data_identity, ) + def family() -> FamilyQueries: + return FamilyQueries(store, scope, actor.read(), cursors, planner.times) + return TaskHTTPContext( queries, lambda: queries().overview(clock, planner.times), @@ -92,7 +95,8 @@ def queries() -> TaskQueries: bind_household_policy=True, ), TaskCategoryCommands(store, actor, actor.read, clock, identifiers), - lambda: FamilyQueries(store, scope, actor.read(), cursors, planner.times), + family, + lambda: family().overview(clock), lambda: AllocationQueries(store, actor.read()), AllocationCommands(store, actor, clock, identifiers), lambda: RewardQueries(store, scope, actor.read(), cursors), diff --git a/backend/src/domus/entrypoints/family_http.py b/backend/src/domus/entrypoints/family_http.py index 0f2a4dd..17906cd 100644 --- a/backend/src/domus/entrypoints/family_http.py +++ b/backend/src/domus/entrypoints/family_http.py @@ -7,13 +7,14 @@ from fastapi import APIRouter, Query, Request from fastapi.params import Depends -from domus.application.family_queries import FamilyQueries, FamilyReport +from domus.application.family_queries import FamilyReport, FamilyWeek from domus.domain.calendar_values import CalendarRange from domus.domain.errors import InvalidInput from domus.entrypoints.calendar_http import LocalDate -from domus.entrypoints.household_http import _JSONRoute +from domus.entrypoints.household_http import _EmptyQuery, _JSONRoute from domus.entrypoints.recurrence_http import _require_context from domus.entrypoints.task_dto import PageQuery +from domus.entrypoints.task_http import TaskHTTPContext class FamilyQuery(PageQuery): @@ -28,12 +29,18 @@ def period(self) -> CalendarRange: def create_family_router( - context: Callable[[Request], FamilyQueries], *, security: Depends + context: Callable[[Request], TaskHTTPContext], *, security: Depends ) -> APIRouter: router = APIRouter(dependencies=[security, Depends(_require_context)], route_class=_JSONRoute) @router.get("/api/v1/family", response_model=FamilyReport) def family(request: Request, query: Annotated[FamilyQuery, Query()]) -> FamilyReport: - return context(request).report(query.period(), limit=query.limit, cursor=query.cursor) + return ( + context(request).family().report(query.period(), limit=query.limit, cursor=query.cursor) + ) + + @router.get("/api/v1/family/overview", response_model=FamilyWeek) + def overview(request: Request, query: Annotated[_EmptyQuery, Query()]) -> FamilyWeek: + return context(request).family_overview() return router diff --git a/backend/src/domus/entrypoints/http.py b/backend/src/domus/entrypoints/http.py index 2192e50..df201b8 100644 --- a/backend/src/domus/entrypoints/http.py +++ b/backend/src/domus/entrypoints/http.py @@ -440,8 +440,6 @@ def tasks(request: Request) -> TaskHTTPContext: app.include_router(create_point_allocation_router(tasks, security=session_security)) app.include_router(create_reward_router(tasks, security=session_security)) app.include_router(create_inventory_router(tasks, security=session_security)) - app.include_router( - create_family_router(lambda request: tasks(request).family(), security=session_security) - ) + app.include_router(create_family_router(tasks, security=session_security)) attach_ui(app, ui_bundle, "standalone", lambda request: None) return app diff --git a/backend/src/domus/entrypoints/native_http.py b/backend/src/domus/entrypoints/native_http.py index a685c73..01b78ed 100644 --- a/backend/src/domus/entrypoints/native_http.py +++ b/backend/src/domus/entrypoints/native_http.py @@ -255,11 +255,7 @@ def health() -> dict[str, str]: app.include_router(create_point_allocation_router(task_context, security=Depends(security))) app.include_router(create_reward_router(task_context, security=Depends(security))) app.include_router(create_inventory_router(task_context, security=Depends(security))) - app.include_router( - create_family_router( - lambda request: task_context(request).family(), security=Depends(security) - ) - ) + app.include_router(create_family_router(task_context, security=Depends(security))) if administration_context is not None: app.include_router( create_administration_router(administration_context, security=Depends(security)) diff --git a/backend/src/domus/entrypoints/task_http.py b/backend/src/domus/entrypoints/task_http.py index 908f146..d637efd 100644 --- a/backend/src/domus/entrypoints/task_http.py +++ b/backend/src/domus/entrypoints/task_http.py @@ -9,7 +9,7 @@ from domus.application.calendar_commands import CalendarCommands from domus.application.calendar_queries import CalendarQueries -from domus.application.family_queries import FamilyQueries +from domus.application.family_queries import FamilyQueries, FamilyWeek from domus.application.inventory import CatalogAction, InventoryCommands from domus.application.inventory_queries import InventoryQueries from domus.application.point_allocations import AllocationCommands, AllocationQueries @@ -113,6 +113,7 @@ class TaskHTTPContext: relative_creation: RelativeRecurrenceCommands category_commands: TaskCategoryCommands family: Callable[[], FamilyQueries] + family_overview: Callable[[], FamilyWeek] allocation: Callable[[], AllocationQueries] allocation_commands: AllocationCommands rewards: Callable[[], RewardQueries] diff --git a/docs/contracts/household-api.openapi.json b/docs/contracts/household-api.openapi.json index 4793ee1..3b74018 100644 --- a/docs/contracts/household-api.openapi.json +++ b/docs/contracts/household-api.openapi.json @@ -2357,6 +2357,28 @@ "title": "FamilyReport", "type": "object" }, + "FamilyWeek": { + "properties": { + "completed_count": { + "title": "Completed Count", + "type": "integer" + }, + "earned_minor": { + "title": "Earned Minor", + "type": "integer" + }, + "period": { + "$ref": "#/components/schemas/CalendarRange" + } + }, + "required": [ + "period", + "earned_minor", + "completed_count" + ], + "title": "FamilyWeek", + "type": "object" + }, "FixedExceptionBody": { "additionalProperties": false, "properties": { @@ -12428,6 +12450,150 @@ "summary": "Original" } }, + "/api/v1/family/overview": { + "get": { + "operationId": "overview_api_v1_family_overview_get", + "parameters": [ + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FamilyWeek" + } + } + }, + "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": "Overview" + } + }, "/api/v1/family/rewards": { "get": { "operationId": "rewards_api_v1_family_rewards_get", diff --git a/docs/contracts/native-household-api.openapi.json b/docs/contracts/native-household-api.openapi.json index fc356ea..89aa039 100644 --- a/docs/contracts/native-household-api.openapi.json +++ b/docs/contracts/native-household-api.openapi.json @@ -2351,6 +2351,28 @@ "title": "FamilyReport", "type": "object" }, + "FamilyWeek": { + "properties": { + "completed_count": { + "title": "Completed Count", + "type": "integer" + }, + "earned_minor": { + "title": "Earned Minor", + "type": "integer" + }, + "period": { + "$ref": "#/components/schemas/CalendarRange" + } + }, + "required": [ + "period", + "earned_minor", + "completed_count" + ], + "title": "FamilyWeek", + "type": "object" + }, "FixedExceptionBody": { "additionalProperties": false, "properties": { @@ -11916,6 +11938,150 @@ "summary": "Original" } }, + "/api/v1/family/overview": { + "get": { + "operationId": "overview_api_v1_family_overview_get", + "parameters": [ + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FamilyWeek" + } + } + }, + "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": "Overview" + } + }, "/api/v1/family/rewards": { "get": { "operationId": "rewards_api_v1_family_rewards_get", diff --git a/docs/evidence/overview-family-participation-qualification.md b/docs/evidence/overview-family-participation-qualification.md new file mode 100644 index 0000000..6911bee --- /dev/null +++ b/docs/evidence/overview-family-participation-qualification.md @@ -0,0 +1,34 @@ +# Overview Family participation qualification + +The protected summary shows completed tasks and posted earned points for the +verified member's current Family week. The backend derives the Monday boundary +from a server observation in the household time zone. [Issue #105](https://github.com/vypdev/domus/issues/105) + +| Published case | Executable evidence | +| --- | --- | +| `overview-participation-C01` | The [Family Overview HTTP tests](../../tests/backend/test_family_overview.py) create real tasks and ledger awards. The summary matches the current Family report in Ingress and standalone. | +| `overview-participation-C02` | Sunday work approved and posted on Monday remains in the prior household week. A server observation on each side of local midnight verifies the boundary. | +| `overview-participation-C03` | A posted award from the next household week is excluded from the current read and appears in the next week. | +| `overview-participation-C04` | Work awaiting verification contributes to the completed count. Its expected points appear in Family's pending-verification value. | +| `overview-participation-C05` | Approved work awaiting ledger posting contributes to the completed count. Its expected points appear in Family's pending-posting value. | +| `overview-participation-C06` | The same HTTP tests switch verified members and confirm each receives their own totals. Forged context, caller-selected member and revoked Household or Tasks access return no participation facts. | + +The HTTP suite collects C01 through C06 independently in both Ingress and standalone. + +The [browser tests](../../frontend/tests/e2e/workspace-navigation.spec.ts) use +real posted points, recover a failed read and open Family from Overview using +English desktop keyboard and narrow Spanish touch in both compositions. CI +runs these journeys on amd64 and ARM64. + +On 2026-11-11, the [pinned Edge.22 artifact](https://github.com/vypdev/domus/blob/36b6532541890f4af3ff9a50b77ca17bca278521/addon-edge/artifact.json) +was installed in a disposable Supervisor app with a UTC household. A posted +2.25-point award appeared with one completed task in English desktop and at +390 px in Spanish as 2,25. Opening Family focused its heading. Reopening the +task retained its historical completion and brought earned points back to +0,00 with a linked reversal in Family. The disposable app, its data and its +repository source were removed after verification. + +A mounted-page test advances the server-anchored clock across the household's +Monday boundary while Overview stays open. It checks that the new period replaces +the prior totals with one read, without renewing the current session. If the +monotonic clock fails, the old summary is retired. diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json index 3243a6e..9443974 100644 --- a/docs/evidence/task-navigation-integration.json +++ b/docs/evidence/task-navigation-integration.json @@ -3,22 +3,12 @@ "historicalTaskHead": "8c0a36c0b9804bdaf33a301a4dc85ae3dc12ee21", "developParent": "5b7bdcdee3a9e98d6669bfd34ce750ae30a8c775", "command": "pnpm build:frontend", - "scope": "Compiled household workspace with the existing task, Pantry, and Shopping journeys and optional base points during task creation, including localized decimal entry and original operation recovery in English and Spanish.", + "scope": "Compiled household workspace with upcoming maintenance, due today, overdue, assigned and unclaimed task summaries, products below their replenishment minimum, weekly Family participation, optional task base points, native deadline sensor integration, protected Pantry, shared Shopping, purchase sessions with an optional store, receipt corrections, physical returns, stock locations, transfers and original operation recovery in English and Spanish.", "actualProductFiles": { - ".vite/manifest.json": "734a1f5ba77da03257115ade8cb5f680b19febd79c853f95a3fa51993e0f2cdb", + ".vite/manifest.json": "ff8264fde84e7207e3ba230fdb7935716ce36902a765fa71523e22bb5ff1195f", + "assets/index-CX10IRLI.js": "838cb6fdacbd2f7f6e27b302c231c4fb6d5d49cd50e1cb3685ea7e4722c45e7a", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "assets/index-CrrA8YHS.js": "c32342fbb48c4d5e7266a3a6272e77d6a4479290440c4e801887750470b99bb2", - "index.html": "1198c1ad6b3475ec0c03041f145522f4454e7782aec020a2779204a4bea2f399" - }, - "preTaskBasePoints": { - "sourceCommit": "ff6b64fec87bab3d156a0c64952387c7a33ceff1", - "scope": "Compiled household workspace before optional task base points, with task and stock summaries, protected Pantry, shared Shopping, purchase sessions with an optional store, receipt corrections, physical returns, stock locations, transfers and original operation recovery in English and Spanish.", - "actualProductFiles": { - ".vite/manifest.json": "d3e5d88e254b44f115434200d7c06e3786503ddd3dcc54159b12cfa478a0e8d3", - "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "assets/index-DOfU-Xei.js": "58c0a0583f61ddb56f7990abdb08988801cb12ab8cd261424507f6a1d6489a84", - "index.html": "640506dad66475ec8db78b827e96c250a8ce3fbacbc4c2f77aa1173266c51f7d" - } + "index.html": "c709edea7d9a6607c1064bd52bb500a25dc22e18e2852c76ff42394bb5516d04" }, "localValidation": { "commit": "9a10d8114869be754962953903e773fe8e12c723", @@ -232,5 +222,24 @@ "assets/index-Dx8HsQnC.js": "eeef7579c8591ebe2ed679c5edf3d12e14c42f2316a3dee552f07759001f4eb2", "index.html": "df5fca477aea9e4719d6a0cfb28dbc11ac5eb4d4694bddb5a8a64457c5e4c361" } + }, + "preTaskBasePoints": { + "sourceCommit": "ff6b64fec87bab3d156a0c64952387c7a33ceff1", + "scope": "Compiled household workspace before optional task base points, with task and stock summaries, protected Pantry, shared Shopping, purchase sessions with an optional store, receipt corrections, physical returns, stock locations, transfers and original operation recovery in English and Spanish.", + "actualProductFiles": { + ".vite/manifest.json": "d3e5d88e254b44f115434200d7c06e3786503ddd3dcc54159b12cfa478a0e8d3", + "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", + "assets/index-DOfU-Xei.js": "58c0a0583f61ddb56f7990abdb08988801cb12ab8cd261424507f6a1d6489a84", + "index.html": "640506dad66475ec8db78b827e96c250a8ce3fbacbc4c2f77aa1173266c51f7d" + } + }, + "taskBasePointsIntegration": { + "scope": "Compiled household workspace with the existing task, Pantry, and Shopping journeys and optional base points during task creation, including localized decimal entry and original operation recovery in English and Spanish.", + "actualProductFiles": { + ".vite/manifest.json": "734a1f5ba77da03257115ade8cb5f680b19febd79c853f95a3fa51993e0f2cdb", + "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", + "assets/index-CrrA8YHS.js": "c32342fbb48c4d5e7266a3a6272e77d6a4479290440c4e801887750470b99bb2", + "index.html": "1198c1ad6b3475ec0c03041f145522f4454e7782aec020a2779204a4bea2f399" + } } } diff --git a/docs/roadmap.md b/docs/roadmap.md index da1fdb4..883a2fc 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -57,7 +57,9 @@ acceptance of the installed recurrence experience remain open. [Upcoming maintenance](evidence/overview-maintenance-qualification.md) shows open scheduled tasks for the next seven days. [Products below minimum](evidence/overview-stock-attention-qualification.md) shows where available stock after reservations falls below the household's replenishment minimums. - Shopping and Family summaries, full integrated acceptance and Stable release acceptance remain open. + [Weekly Family participation](evidence/overview-family-participation-qualification.md) shows the + member's completed tasks and posted earned points for the current household week. + The Shopping summary, full integrated acceptance and Stable release acceptance remain open. ## Shared components, Domus-owned experience diff --git a/docs/user-guide.md b/docs/user-guide.md index f794f1b..3d50181 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -295,6 +295,11 @@ Scan a barcode with the camera or enter it manually. Domus searches local produc ## Participation +**Your participation this week** on Overview shows your completed tasks and posted earned points +for the current Family week. The week starts on Monday in the household time zone. Select +**Open Family** for the full report, including work awaiting verification and approved points +awaiting posting. + Open Family to see your balance, point history and recorded work. Select a week or month using a date in that period. The household time zone determines where the work belongs. Sunday work stays in Sunday's week if it is approved on Monday. diff --git a/frontend/src/adapters/family-http.ts b/frontend/src/adapters/family-http.ts index 08dfb6f..f0cc009 100644 --- a/frontend/src/adapters/family-http.ts +++ b/frontend/src/adapters/family-http.ts @@ -1,5 +1,6 @@ /** Family reports use the same context assertion and bounded JSON decoder as other private reads. */ -import type {FamilyEntry, FamilyPendingEntry, FamilyReport, FamilyServer, FamilySpending} from '../application/family-controller'; +import type {FamilyEntry, FamilyPendingEntry, FamilyReport, FamilyServer, FamilySpending, FamilyWeek} from '../application/family-controller'; +import {calendarPeriod, civilDate} from '../domain/calendar'; import type {CalendarPeriod} from '../domain/calendar'; import {rewardCost} from '../domain/rewards'; import type {JournalContext} from '../domain/journal'; @@ -44,6 +45,16 @@ function spendingEntry(value: unknown): FamilySpending { cost: rewardCost(integer(row.cost_minor, 1)), postedAt: timestamp(row.posted_at)}; } +function week(value: unknown): FamilyWeek { + const row = fields(value, ['period','earned_minor','completed_count'], []); + const range = fields(row.period, ['start','end'], []); + check(civilDate(range.start)); + const period = calendarPeriod('week', range.start); + check(range.start === period.start && range.end === period.end); + return {period, earned:integer(row.earned_minor, -Number.MAX_SAFE_INTEGER), + completed:integer(row.completed_count, 0)}; +} + function report(value: unknown, expected: CalendarPeriod): FamilyReport { const row = fields(value, ['period','time_zone','posted_minor','available_minor','reserved_minor', 'spent_in_period_minor','spending_count','spending','earned_minor', @@ -80,6 +91,9 @@ function report(value: unknown, expected: CalendarPeriod): FamilyReport { export class HttpFamilyServer implements FamilyServer { private readonly network: BoundedHTTP; constructor(target: EntryEndpoint, transport: FetchTransport) {this.network = new BoundedHTTP(target, transport);} + overview(context: JournalContext) { + return this.network.owned(async signal => week(await this.network.get('family/overview', context, signal))); + } read(context: JournalContext, period: CalendarPeriod, cursor: string | null) { return this.network.owned(async signal => { const query = new URLSearchParams({start: period.start, end: period.end, limit: '8'}); diff --git a/frontend/src/application/family-controller.ts b/frontend/src/application/family-controller.ts index 7ff33c0..707f87f 100644 --- a/frontend/src/application/family-controller.ts +++ b/frontend/src/application/family-controller.ts @@ -3,10 +3,17 @@ import {calendarPeriod} from '../domain/calendar'; import type {CalendarPeriod} from '../domain/calendar'; import type {AllocationEvidence} from '../domain/point-allocation'; import type {JournalContext} from '../domain/journal'; +import type {OverviewView} from './overview-read'; import {EntryReadError} from './ports'; import type {EntryRead} from './ports'; export type FamilyPeriod = 'week' | 'month'; +export interface FamilyWeek { + readonly period: CalendarPeriod; + readonly earned: number; + readonly completed: number; +} +export type FamilyOverviewView = OverviewView; export interface FamilyEntry { readonly id: string; readonly title: string; diff --git a/frontend/src/composition/entry-page.ts b/frontend/src/composition/entry-page.ts index d625909..ef38422 100644 --- a/frontend/src/composition/entry-page.ts +++ b/frontend/src/composition/entry-page.ts @@ -21,6 +21,7 @@ import type {AllocationInput, ReviewedAllocation} from '../domain/point-allocati import type {AllocationSettingsIntent} from '../presentation/domus-allocation-settings'; import {HttpFamilyServer} from '../adapters/family-http'; import {FamilyController} from '../application/family-controller'; +import type {FamilyWeek} from '../application/family-controller'; import {civilDate} from '../domain/calendar'; import type {FamilyIntent} from '../presentation/domus-family'; import {HttpRecurrenceServer} from '../adapters/recurrence-http'; @@ -34,7 +35,7 @@ import {CALENDAR_JOURNAL_KEY, CalendarSessionJournal} from '../adapters/calendar import {CalendarPreferenceController} from '../application/calendar-preferences'; import {HttpCalendarServer} from '../adapters/calendar-http'; import {CalendarController} from '../application/calendar-controller'; -import {calendarQuery, calendarToday, WEEK_STARTS} from '../domain/calendar'; +import {calendarPeriod, calendarQuery, calendarToday, WEEK_STARTS} from '../domain/calendar'; import type {CalendarIntent} from '../presentation/domus-calendar'; import {bootstrap} from '../adapters/bootstrap'; import {check, fields, identifier} from '../adapters/http-values'; @@ -212,6 +213,7 @@ export function mountEntry(page: EntryPage): PageMount { let inventory: InventoryController | null = null; let taskOverview: OverviewReadController | null = null; let stockAttention: OverviewReadController | null = null; + let familyOverview: OverviewReadController | null = null; let allocation: AllocationController | null = null; let calendar: CalendarController | null = null, review: RecurrenceReviewController | null = null; let stopped = false, runtime: EntryRuntime | null = null, app: DomusApp | null = null, error: HTMLElement | null = null; @@ -219,7 +221,7 @@ export function mountEntry(page: EntryPage): PageMount { const dispose = () => { if (stopped) return; stopped = true; widget.abort(); lifetime.abort(); runtime?.dispose(); calendar?.bind(null); family?.bind(null); rewards?.bind(null); inventory?.bind(null); allocation?.bind(null); calendarPreference?.bind(null); review?.bind(null); taskOverview?.bind(null); error?.remove(); - stockAttention?.bind(null); + stockAttention?.bind(null); familyOverview?.bind(null); if (mounts.get(doc) === dispose) mounts.delete(doc); }; mounts.set(doc, dispose); @@ -229,7 +231,7 @@ export function mountEntry(page: EntryPage): PageMount { const fail = () => { if (stopped || error !== null) return; widget.abort(); runtime?.dispose(); calendar?.bind(null); family?.bind(null); rewards?.bind(null); inventory?.bind(null); allocation?.bind(null); calendarPreference?.bind(null); review?.bind(null); taskOverview?.bind(null); app?.remove(); - stockAttention?.bind(null); + stockAttention?.bind(null); familyOverview?.bind(null); const locale = language(null, page.navigator.language); doc.documentElement.lang = locale; error = doc.createElement('main'); error.id = 'domus-entry-error'; const heading = doc.createElement('h1'), body = doc.createElement('p'), action = doc.createElement('p'), reload = doc.createElement('button'); @@ -274,7 +276,8 @@ export function mountEntry(page: EntryPage): PageMount { calendarController.bind(null); preferences.bind(null); element.calendarScopeKey = null; } }; - const familyController = new FamilyController(new HttpFamilyServer(source.target, browser.transport), + const familyServer = new HttpFamilyServer(source.target, browser.transport); + const familyController = new FamilyController(familyServer, view => {element.family = view;}); family = familyController; const rewardsController = new RewardsController(new HttpRewardsServer(source.target, browser.transport), @@ -448,16 +451,35 @@ export function mountEntry(page: EntryPage): PageMount { element.addEventListener('domus-stock-attention-retry', event => { if (event.target === element) void stockController.refresh(); }, {signal: widget.signal}); + const familySummary = new OverviewReadController(context => familyServer.overview(context), + view => {element.familyOverview = view;}); + familyOverview = familySummary; + const syncFamilyOverview = () => { + const entry = element.view, tasks = element.tasks, destination = element.workspaceDestination; + if ((destination === null || destination === 'overview') && entry?.phase === 'ready' + && entry.notice !== 'context_changed' && entry.decision?.householdReadable && entry.household + && tasks?.phase === 'ready' && tasks.session && tasks.scopeKey) { + let day: string; + try {day = calendarToday(runtime!.serverTime, entry.household.timeZone);} + catch {familySummary.bind(null); return;} + const start = calendarPeriod('week', day).start; + const key = JSON.stringify([tasks.scopeKey, entry.household.revision, start]); + familySummary.bind({key, context:tasks.session.context}); + } else familySummary.bind(null); + }; + element.addEventListener('domus-family-overview-retry', event => { + if (event.target === element) void familySummary.refresh(); + }, {signal: widget.signal}); const syncWorkspace = () => { const fragment = new URL(page.location.href).hash; element.workspaceDestination = fragment === '#overview' ? 'overview' : fragment === '#household' ? 'household' : fragment === '#tasks' ? 'tasks' : fragment === '#calendar' ? 'calendar' : fragment === '#family' ? 'family' : fragment === '#inventory' ? 'inventory' : null; - syncCalendar(); syncReview(); syncFamily(); syncAllocation(); syncInventory(); syncOverview(); syncStockAttention(); + syncCalendar(); syncReview(); syncFamily(); syncAllocation(); syncInventory(); syncOverview(); syncStockAttention(); syncFamilyOverview(); }; syncWorkspace(); page.addEventListener('hashchange', syncWorkspace, {signal: widget.signal}); const active = new EntryRuntime(source.target, browser, (view,administration,tasks) => { - element.view=view;element.administration=administration;element.tasks=tasks;syncCalendar();syncReview();syncFamily();syncAllocation();syncInventory();syncOverview();syncStockAttention(); + element.view=view;element.administration=administration;element.tasks=tasks;syncCalendar();syncReview();syncFamily();syncAllocation();syncInventory();syncOverview();syncStockAttention();syncFamilyOverview(); const context=administration?.session?.context,member=administration?.access?.member; const contextKey=context?JSON.stringify([context.installationId,context.channel,context.subject]):null; const owner=contextKey!==null&&administration?.access?.state==='active'&&member?JSON.stringify([contextKey,member.memberId]):null; diff --git a/frontend/src/composition/entry-runtime.ts b/frontend/src/composition/entry-runtime.ts index f259ee1..6de9147 100644 --- a/frontend/src/composition/entry-runtime.ts +++ b/frontend/src/composition/entry-runtime.ts @@ -63,6 +63,7 @@ export class EntryRuntime { get view(): EntryView {return this.current.controller.view;} get administration(): AdministrationView | null {return this.current.controller.administration;} get tasks(): TaskView | null {return this.current.controller.tasks;} + get serverTime(): number {return this.current.clock.now();} taskWork(work: (controller: TaskController) => Promise): Promise {return this.perform(controller => controller.taskWork(work));} private publish(): void { try {this.changed(this.view, this.administration, this.tasks);} catch {/* A renderer failure cannot change authority or interrupt resource cleanup. */} diff --git a/frontend/src/presentation/domus-app.ts b/frontend/src/presentation/domus-app.ts index 202d83a..8c38350 100644 --- a/frontend/src/presentation/domus-app.ts +++ b/frontend/src/presentation/domus-app.ts @@ -14,6 +14,7 @@ import './domus-stock-attention'; import type {StockAttentionView} from '../application/stock-attention'; import './domus-calendar'; import './domus-family'; +import './domus-family-overview'; import './domus-rewards'; import './domus-inventory'; import type {InventoryState} from '../application/inventory-controller'; @@ -22,7 +23,7 @@ import './domus-allocation-settings'; import type {AllocationView} from '../application/allocation-controller'; import type {ParticipantName} from './allocation-details'; import {familyMessage} from './family-messages'; -import type {FamilyView} from '../application/family-controller'; +import type {FamilyOverviewView, FamilyView} from '../application/family-controller'; import type {CalendarPreferenceView} from '../application/calendar-preferences'; import './domus-recurrence-review'; import type {ReviewView} from '../application/recurrence-review-controller'; @@ -46,7 +47,7 @@ export type EntryIntent = Readonly<{type: 'refresh' | 'request_membership' | 'lo /** Owned rendering only; intents cross a semantic boundary and never grant command authority. */ export class DomusApp extends LitElement { static properties = {inventory: {attribute:false}, rewards: {attribute:false}, allocation: {attribute:false}, family: {attribute:false}, familyScopeKey: {attribute:false}, familyToday: {attribute:false}, recurrenceReview: {attribute:false}, calendar: {attribute:false}, calendarPreference: {attribute:false}, calendarScopeKey: {attribute:false}, calendarToday: {attribute:false}, tasks: {attribute: false}, view: {attribute: false}, administration: {attribute:false}, deployment: {attribute: false}, language: {attribute: false}, - taskOverview: {attribute: false}, stockAttention: {attribute: false}, + taskOverview: {attribute: false}, stockAttention: {attribute: false}, familyOverview: {attribute: false}, workspaceDestination: {attribute: false}, nameDraft: {state: true}, zoneDraft: {state: true}}; static styles = styles; declare view: EntryView | null; @@ -54,6 +55,7 @@ export class DomusApp extends LitElement { declare tasks: TaskView | null; declare taskOverview: TaskOverviewView | null; declare stockAttention: StockAttentionView | null; + declare familyOverview: FamilyOverviewView | null; declare calendar: CalendarView | null; declare family: FamilyView | null; declare rewards: RewardsView | null; @@ -77,7 +79,7 @@ export class DomusApp extends LitElement { this.recurrenceReview = null; this.calendar = null; this.calendarPreference = null; this.calendarScopeKey = null; this.calendarToday = DATE_MIN; this.family = null; this.rewards = null; this.inventory = null; this.allocation = null; this.familyScopeKey = null; this.familyToday = DATE_MIN; this.workspaceDestination = null; this.taskOverview = null; this.nameDraft = ''; this.zoneDraft = ''; - this.stockAttention = null; + this.stockAttention = null; this.familyOverview = null; } disconnectedCallback(): void {super.disconnectedCallback(); this.dispatchEvent(new Event('domus-detached'));} private text(key: MessageKey): string {return message(key, this.language);} @@ -225,6 +227,7 @@ export class DomusApp extends LitElement { ${!closed && view?.busy ? html`

${this.text('busy')}

` : nothing} +
diff --git a/frontend/src/presentation/domus-family-overview.ts b/frontend/src/presentation/domus-family-overview.ts new file mode 100644 index 0000000..16a6297 --- /dev/null +++ b/frontend/src/presentation/domus-family-overview.ts @@ -0,0 +1,83 @@ +import {LitElement, css, html, nothing} from 'lit'; +import {registerButton} from '@vypdev/ha-ui/button'; +import {buttonState} from '@vypdev/ha-ui/button-contracts'; +import {registerCard} from '@vypdev/ha-ui/card'; +import {cardState} from '@vypdev/ha-ui/card-contracts'; +import {registerFeedback} from '@vypdev/ha-ui/feedback'; +import {feedbackState} from '@vypdev/ha-ui/feedback-contracts'; +import type {FamilyOverviewView} from '../application/family-controller'; +import {displayPoints} from '../domain/point-allocation'; +import type {Language} from './messages'; + +const COPY = { + en: { + title: 'Your participation this week', + earned: 'Earned points', + completed: 'Completed tasks', + loading: 'Loading weekly participation…', + denied: 'Your current household access does not allow viewing participation.', + unavailable: 'Weekly participation could not be loaded.', + retry: 'Retry participation summary', + open: 'Open Family', + }, + es: { + title: 'Tu participación esta semana', + earned: 'Puntos ganados', + completed: 'Tareas completadas', + loading: 'Cargando la participación semanal…', + denied: 'Tu acceso actual al hogar no permite ver la participación.', + unavailable: 'No se pudo cargar la participación semanal.', + retry: 'Volver a cargar la participación', + open: 'Abrir Familia', + }, +} as const; + +export class DomusFamilyOverview extends LitElement { + static properties = {view: {attribute: false}, language: {attribute: false}}; + static styles = css` + :host {display:block;--vyp-ha-surface:var(--surface);--vyp-ha-surface-raised:var(--surface); + --vyp-ha-text:var(--text);--vyp-ha-text-secondary:var(--muted);--vyp-ha-border:var(--line); + --vyp-ha-primary:var(--accent);--vyp-ha-focus-ring:3px solid var(--accent)} + vyp-ha-card {margin-block-start:16px} + vyp-ha-card::part(heading) {text-wrap:balance} + p {margin:0 0 12px;color:var(--muted)} + dl {display:grid;grid-template-columns:minmax(0,1fr) auto;gap:8px 16px;margin:0} + dd {margin:0;font-weight:650;font-variant-numeric:tabular-nums} + a {display:inline-flex;align-items:center;min-height:44px;margin-block-start:8px;color:var(--accent)} + a:focus-visible {outline:3px solid var(--accent);outline-offset:3px} + vyp-ha-feedback + vyp-ha-button {margin-block-start:8px} + `; + + declare view: FamilyOverviewView | null; + declare language: Language; + + constructor() {super(); this.view = null; this.language = 'en';} + + protected render() { + const view = this.view; + if (view === null) return nothing; + const copy = COPY[this.language]; + return html` + ${view.state === 'ready' ? html` +

${new Intl.DateTimeFormat(this.language, {timeZone:'UTC', dateStyle:'medium'}).formatRange( + Date.parse(view.data.period.start), Date.parse(view.data.period.end) - 86_400_000)}

+
+
${copy.completed}
${new Intl.NumberFormat(this.language).format(view.data.completed)}
+
${copy.earned}
${displayPoints(view.data.earned, this.language, 2)}
+
+ ${copy.open}` : html` + + ${view.state === 'unavailable' ? html` this.dispatchEvent(new Event('domus-family-overview-retry', { + bubbles:true, composed:true, + }))}>` : nothing}`} +
`; + } +} + +registerButton(); registerCard(); registerFeedback(); +customElements.define('domus-family-overview', DomusFamilyOverview); +declare global {interface HTMLElementTagNameMap {'domus-family-overview': DomusFamilyOverview;}} diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index 2587065..f67db77 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -306,8 +306,33 @@ for (const mode of ['native', 'standalone'] as const) { return result.json(); }; await expect.poll(async () => (await ledger()).available_minor, {timeout: 15_000}).toBe(225); - const familia = tabs.getByRole('link', {name: 'Familia', exact: true}); - await familia.click(); + const participation = overviewRegion.locator('domus-family-overview'); + await page.setViewportSize({width:390,height:844}); + await page.emulateMedia({colorScheme:'dark'}); + await tabs.getByRole('link',{name:'Inicio',exact:true}).tap(); + await expect(participation.getByRole('heading',{name:'Tu participación esta semana',exact:true})).toBeVisible(); + await expect(participation.locator('dd')).toHaveText(['1','2,25']); + await expect(participation.getByRole('article')).toHaveCSS('background-color','rgb(24, 36, 47)'); + await participation.screenshot({path:info.outputPath('family-overview-es-narrow.png')}); + await participation.getByRole('link',{name:'Abrir Familia',exact:true}).tap(); + await expect(familyRegion).toBeFocused(); + await page.getByLabel('Idioma',{exact:true}).selectOption('en'); + await page.setViewportSize({width:1100,height:760}); + await page.emulateMedia({colorScheme:'light'}); + await page.route(base + 'api/v1/family/overview', route => route.abort('failed'), {times:1}); + await overview.press('Enter'); + await expect(page).toHaveURL(base + '#overview'); + await expect(participation.getByText('Weekly participation could not be loaded.',{exact:true})).toBeVisible(); + await expect(overviewRegion.getByRole('heading',{name:/^Products below minimum ·/u})).toBeVisible(); + await participation.getByRole('button',{name:'Retry participation summary',exact:true}).press('Enter'); + await expect(participation.locator('dd')).toHaveText(['1','2.25']); + await expect(participation.getByRole('article')).toHaveCSS('background-color','rgb(255, 255, 255)'); + await participation.screenshot({path:info.outputPath('family-overview-en-wide.png')}); + await participation.getByRole('link',{name:'Open Family',exact:true}).press('Enter'); + await expect(familyRegion).toBeFocused(); + await page.getByLabel('Language',{exact:true}).selectOption('es'); + await page.setViewportSize({width:320,height:720}); + await page.emulateMedia({colorScheme:'dark',reducedMotion:'reduce'}); await expect(familyRegion.getByText('Saldo disponible', {exact: true})).toBeVisible(); await expect(familyRegion.getByText('Premio 2,25', {exact: true})).toBeVisible(); await expect(familyRegion.getByText('Puntos estimados pendientes de verificación')).toBeVisible(); diff --git a/frontend/tests/family.test.ts b/frontend/tests/family.test.ts index e3fff77..89d5014 100644 --- a/frontend/tests/family.test.ts +++ b/frontend/tests/family.test.ts @@ -4,6 +4,7 @@ import type {FamilyReport} from '../src/application/family-controller'; import {EntryReadError} from '../src/application/ports'; import {HttpFamilyServer} from '../src/adapters/family-http'; import '../src/presentation/domus-family'; +import '../src/presentation/domus-family-overview'; import corpus from './fixtures/entry-wire.json'; const period = {start: '2026-05-25', end: '2026-06-01'}; @@ -22,6 +23,7 @@ const wire = {period, time_zone: 'Europe/Madrid', posted_minor: 0, available_min ], history: [reversal, award], next_cursor: 'next'}; const endpoint = {...corpus.standalone.endpoint, deployment: 'standalone' as const}; const context = {installationId: '047cc6fb-dfb0-4fa4-b3c3-e0fe54d116b6', channel: 'edge' as const, subject: 'a'.repeat(32)}; +const wireWeek = {period, earned_minor:125, completed_count:3}; function server(payload: unknown, status = 200) { const transport = vi.fn(async (path: string, _init: RequestInit) => { @@ -31,6 +33,27 @@ function server(payload: unknown, status = 200) { return {http: new HttpFamilyServer(endpoint, transport), transport}; } +test('the Family summary reads the protected current week without caller scope', async () => { + const {http, transport} = server(wireWeek); + expect(await http.overview(context).result).toEqual({period, earned:125, completed:3}); + expect(transport.mock.calls[0][0]).toBe('/api/v1/family/overview'); + expect(new Headers(transport.mock.calls[0][1].headers).get('X-Domus-Context')).toContain(context.subject); + const first = {start:'1970-01-01',end:'1970-01-05'}; + expect(await server({period:first,earned_minor:0,completed_count:0}).http.overview(context).result) + .toEqual({period:first,earned:0,completed:0}); +}); + +test.each([ + {...wireWeek, period: {start:'2026-05-99',end:period.end}}, + {...wireWeek, period: {start:'2026-05-26',end:period.end}}, + {...wireWeek, period: {start:period.start,end:'2026-06-02'}}, + {...wireWeek, earned_minor:1.5}, + {...wireWeek, completed_count:-1}, + {...wireWeek, pending_posting_minor:325}, +])('the Family summary rejects invalid or excessive facts %#', async payload => { + await expect(server(payload).http.overview(context).result).rejects.toMatchObject({code:'invalid_response'}); +}); + test('the private Family adapter preserves signed postings, dates and exact scoped pagination', async () => { const {http, transport} = server(wire); const report = await http.read(context, period, 'cursor').result; @@ -109,7 +132,36 @@ test('Family refreshes, pages, retains a transient stale view and clears it on s expect(publish).toHaveBeenLastCalledWith(null); }); -afterEach(() => {document.querySelector('domus-family')?.remove();}); +afterEach(() => { + document.querySelector('domus-family')?.remove(); + document.querySelector('domus-family-overview')?.remove(); +}); + +test('weekly participation distinguishes an actual zero, read failures and localized earned values', async () => { + const node = document.createElement('domus-family-overview'); + document.body.append(node); await node.updateComplete; + const root = node.shadowRoot!; + expect(root.querySelector('vyp-ha-card')).toBeNull(); + const view = async (state: 'loading' | 'denied' | 'unavailable') => { + node.view = {state}; await node.updateComplete; + expect(root.querySelector('dl')).toBeNull(); + return root.querySelector('vyp-ha-feedback')?.state?.message; + }; + expect(await view('loading')).toBe('Loading weekly participation…'); + expect(await view('denied')).toContain('does not allow viewing participation'); + expect(await view('unavailable')).toBe('Weekly participation could not be loaded.'); + const retry = vi.fn(); node.addEventListener('domus-family-overview-retry',retry); + root.querySelector('vyp-ha-button')!.dispatchEvent(new Event('ha-press-request')); + expect(retry).toHaveBeenCalledOnce(); + node.view = {state:'ready', data:{period,earned:0,completed:0}}; await node.updateComplete; + expect([...root.querySelectorAll('dd')].map(item=>item.textContent)).toEqual(['0','0.00']); + expect(root.querySelector('a')?.getAttribute('href')).toBe('#family'); + expect(root.querySelector('p')?.textContent).toContain('2026'); + node.language = 'es'; node.view = {state:'ready',data:{period,earned:125,completed:3}}; + await node.updateComplete; + expect([...root.querySelectorAll('dd')].map(item=>item.textContent)).toEqual(['3','1,25']); + expect(root.querySelector('a')?.textContent).toBe('Abrir Familia'); +}); test('Family shows distinct pending values, contribution, localized signed history and a safe empty state', async () => { const node = document.createElement('domus-family'); document.body.append(node); await node.updateComplete; diff --git a/frontend/tests/page.test.ts b/frontend/tests/page.test.ts index f5542db..74f454d 100644 --- a/frontend/tests/page.test.ts +++ b/frontend/tests/page.test.ts @@ -20,8 +20,13 @@ afterEach(() => { for (const node of nodes.splice(0)) node.remove(); document.querySelector('#domus-entry-error')?.remove(); }); -function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'en', canReview = false, canManagePoints = false) { +function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'en', canReview = false, canManagePoints = false, + timing?: {serverTime: number; timeZone: string; elapsed: () => number; overview: () => unknown}) { const wire = corpus[deployment], values = new Map(), navigation: string[] = []; + const session = JSON.parse(wire.session); + const sessionBody = timing ? JSON.stringify({...session, context: {...session.context, + server_time: timing.serverTime, expires_at: timing.serverTime + 3_600_000}}) : wire.session; + const household = timing ? JSON.stringify({...JSON.parse(wire.household), time_zone: timing.timeZone}) : wire.household; const root = document.createElement('div'); root.id = 'domus-entry'; document.body.append(root); nodes.push(root); const data = document.createElement('script'); data.id = 'domus-bootstrap'; data.type = 'application/json'; data.textContent = JSON.stringify({version: 1, deployment, application_base: wire.endpoint.applicationBase, style_nonce: 'a'.repeat(32)}); @@ -37,7 +42,7 @@ function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'e const fetch = vi.fn(async (path: string, init: RequestInit) => { const route = path.slice(wire.endpoint.applicationBase.length + 'api/v1/'.length); let raw: string, status = 200; - if (route === 'session') raw = phase === 'eligible' || phase === 'pending' ? wire.participantSession : wire.session; + if (route === 'session') raw = phase === 'eligible' || phase === 'pending' ? wire.participantSession : sessionBody; else if (route === 'authorization') raw = phase === 'active' ? JSON.stringify({...originalAccess,member:{...originalAccess.member,member_id:memberId}, permissions:originalAccess.permissions.filter((permission:string)=>preferencesReadable||permission!=='preferences.read')}) : phase === 'eligible' ? wire.eligible : phase === 'pending' ? wire.pending : wire.unconfigured; @@ -84,6 +89,8 @@ function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'e }); } else if (route === 'inventory/stock-attention') raw = JSON.stringify({total:0,items:[]}); + else if (route === 'family/overview') raw = JSON.stringify(timing ? timing.overview() : { + period:{start:'2026-05-25',end:'2026-06-01'}, earned_minor:125,completed_count:3}); else if (route==='tasks/access') raw=JSON.stringify({household_id:'home',member_id:memberId,can_create:true,can_review_schedule:canReview, can_manage_points:canManagePoints,can_record_for_others:canManagePoints}); else if (route === 'family/allocation' || route.startsWith('family/allocation?')) raw = JSON.stringify({household:null,override:null}); @@ -152,14 +159,14 @@ function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'e else if (route==='administration/members/'+memberId+'/presentation') raw=JSON.stringify(presentation()); else if (route==='policy') raw=JSON.stringify({household_id:'home',revision:1,mapping:{mode:'all_ha_administrators',target_ha_user_id:null},adjustments:[]}); else if (init.method === 'POST') {postRequests++; phase = route === 'household' ? 'active' : 'pending'; raw = route === 'household' ? wire.setup : wire.enrollment;} - else raw = wire.household; + else raw = household; const response = new Response(raw, {status, headers: {'Content-Type': 'application/json', 'Cache-Control': 'no-store'}}); Object.defineProperty(response, 'url', {value: wire.endpoint.origin + path}); return response; }); const events = new EventTarget(); const page: EntryPage = {document, location: {href: wire.endpoint.origin + wire.endpoint.applicationBase, assign: url => {navigation.push(String(url));}, reload: vi.fn()}, navigator: {language: locale}, - crypto, performance, fetch, sessionStorage: {getItem: key => values.get(key) ?? null, + crypto, performance: timing ? {now: timing.elapsed} : performance, fetch, sessionStorage: {getItem: key => values.get(key) ?? null, setItem: (key, value) => {values.set(key, value);}, removeItem: key => {values.delete(key);}}, addEventListener: events.addEventListener.bind(events), removeEventListener: events.removeEventListener.bind(events), dispatchEvent: events.dispatchEvent.bind(events), setTimeout: window.setTimeout.bind(window), clearTimeout: window.clearTimeout.bind(window)}; @@ -796,3 +803,54 @@ test('Overview stock is independently available and retires with the verified ho f.events.dispatchEvent(new Event('hashchange')); expect(app.stockAttention).toBeNull(); }); + +test('the weekly Family summary retries its own read and retires on member and workspace changes', async () => { + const f = fixture(); f.phase('active'); + const {app} = await f.open(); + const expected = {state:'ready',data:{period:{start:'2026-05-25',end:'2026-06-01'},earned:125,completed:3}}; + await vi.waitFor(() => expect(app.familyOverview).toEqual(expected)); + const summary = app.shadowRoot!.querySelector('domus-family-overview')!; + await summary.updateComplete; + expect(summary.view).toBe(app.familyOverview); + const readCount = () => f.fetch.mock.calls.filter(([path]) => path.endsWith('/family/overview')).length; + const before = readCount(); + const retry = () => new Event('domus-family-overview-retry',{bubbles:true,composed:true}); + const unrelated = document.createElement('div'); app.append(unrelated); unrelated.dispatchEvent(retry()); + expect(readCount()).toBe(before); + summary.dispatchEvent(retry()); + await vi.waitFor(() => expect(app.familyOverview).toEqual(expected)); + expect(readCount()).toBe(before+1); + f.member('replacement'); administrationIntent(app,{type:'refresh'}); + await vi.waitFor(() => expect(readCount()).toBeGreaterThan(before+1)); + f.page.location.href += '#family'; f.events.dispatchEvent(new Event('hashchange')); + expect(app.familyOverview).toBeNull(); +}); + +test('the weekly summary refreshes at household Monday while Overview stays open', async () => { + let elapsed = 0, tick!: () => void; + const f = fixture('standalone', 'en', false, false, { + serverTime: Date.parse('2026-05-31T21:59:59Z'), timeZone: 'Europe/Madrid', elapsed: () => elapsed, + overview: () => elapsed < 1000 + ? {period:{start:'2026-05-25',end:'2026-06-01'}, earned_minor:125, completed_count:3} + : {period:{start:'2026-06-01',end:'2026-06-08'}, earned_minor:0, completed_count:0}, + }); + f.phase('active'); + f.page.setTimeout = callback => {tick = callback; return 1;}; + f.page.clearTimeout = () => {}; + const {app} = await f.open(); + const reads = (route: string) => f.fetch.mock.calls.filter(([path]) => path.endsWith(route)).length; + await vi.waitFor(() => expect(app.familyOverview).toMatchObject({state:'ready', data:{earned:125}})); + const sessions = reads('/session'); + elapsed = 999; tick(); + expect(reads('/family/overview')).toBe(1); + elapsed = 1000; tick(); + await vi.waitFor(() => expect(app.familyOverview).toEqual({state:'ready', data:{ + period:{start:'2026-06-01',end:'2026-06-08'}, earned:0, completed:0, + }})); + elapsed = 2000; tick(); + expect(reads('/family/overview')).toBe(2); + expect(reads('/session')).toBe(sessions); + elapsed = Number.NaN; + f.events.dispatchEvent(new Event('hashchange')); + expect(app.familyOverview).toBeNull(); +}); diff --git a/specs/CATALOG.md b/specs/CATALOG.md index 1a23379..161faaa 100644 --- a/specs/CATALOG.md +++ b/specs/CATALOG.md @@ -14,7 +14,7 @@ debt or convert unknown historic intent into a design decision. | `household-identity` | Proposed | Each participating person uses their own Home Assistant account. Domus associates that verified user with one household member and applies explicit backend permissions independently of an optional person entity. | [Household members, Home Assistant identity and permissions](./household-identity.md) + 4 companion | 222 paths · 2026-11-02 | | `household-tasks` | Proposed | Members create and perform household responsibilities with explicit assignments, actual performers and history. A recurring definition survives completion of each individual occurrence. | [Task definitions, occurrences and household execution](./household-tasks.md) + 2 companion | 53 paths · 2026-11-11 | | `recurrence-calendar` | Proposed | A bounded scheduler turns task definitions into stable occurrences and a family calendar distinguishes planned start, deadline and actual completion. Original recurrence outcomes bind receipt status, action, result and source-cycle identity before replay and snapshot acceptance. | [Recurrence engine and family calendar](./recurrence-calendar.md) + 3 companion | 37 paths · 2026-11-09 | -| `points-rewards` | Proposed | Task completion produces auditable point entries. Household-configurable collaboration policies determine each share and the actual award total; corrections preserve history and optional rewards never control basic participation. | [Auditable points, participation and optional rewards](./points-rewards.md) | 51 paths · 2026-11-10 | +| `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) | 40 paths · 2026-11-10 | | `household-inventory` | Proposed | The household knows what is available, where it is stored and what needs replenishment through a local product catalog and an immutable stock movement ledger. | [Product catalog, pantry stock and replenishment](./household-inventory.md) | 29 paths · 2026-11-11 | | `home-assistant-surface` | Proposed | Domus exposes its household capabilities as native Home Assistant entities, services and events. The already integrated HA MCP consumes these surfaces; no gateway work or second MCP is included. | [Home Assistant entities, services and integration](./home-assistant-surface.md) + 2 companion | 17 paths · 2026-10-29 | @@ -71,13 +71,13 @@ debt or convert unknown historic intent into a design decision. ### `points-rewards` — Auditable points, participation and optional rewards - Owner: Domus maintainers (review assignment pending) -- Last verified: 2026-11-10 +- Last verified: 2026-11-11 - Specifications: [`specs/points-rewards.md`](./points-rewards.md) - Workflows: [`.github/workflows/ci_check.yml`](../.github/workflows/ci_check.yml) - Entrypoints: [`backend/src/domus/composition/ingress.py`](../backend/src/domus/composition/ingress.py) · [`backend/src/domus/composition/server.py`](../backend/src/domus/composition/server.py) · [`backend/src/domus/entrypoints/family_http.py`](../backend/src/domus/entrypoints/family_http.py) · [`backend/src/domus/entrypoints/point_allocation_http.py`](../backend/src/domus/entrypoints/point_allocation_http.py) · [`backend/src/domus/entrypoints/reward_http.py`](../backend/src/domus/entrypoints/reward_http.py) -- Core code: [`backend/src/domus/domain/points.py`](../backend/src/domus/domain/points.py) · [`backend/src/domus/application/points.py`](../backend/src/domus/application/points.py) · [`backend/src/domus/application/points_ports.py`](../backend/src/domus/application/points_ports.py) · [`backend/src/domus/infrastructure/sqlite_points.py`](../backend/src/domus/infrastructure/sqlite_points.py) · [`backend/src/domus/application/family_queries.py`](../backend/src/domus/application/family_queries.py) · [`backend/src/domus/application/family_ports.py`](../backend/src/domus/application/family_ports.py) · [`frontend/src/application/family-controller.ts`](../frontend/src/application/family-controller.ts) · [`frontend/src/adapters/family-http.ts`](../frontend/src/adapters/family-http.ts) · [`frontend/src/presentation/domus-family.ts`](../frontend/src/presentation/domus-family.ts) · [`frontend/src/presentation/family-messages.ts`](../frontend/src/presentation/family-messages.ts) · [`backend/src/domus/domain/point_allocation.py`](../backend/src/domus/domain/point_allocation.py) · [`backend/src/domus/application/point_allocations.py`](../backend/src/domus/application/point_allocations.py) · [`backend/src/domus/application/point_allocation_ports.py`](../backend/src/domus/application/point_allocation_ports.py) · [`backend/src/domus/infrastructure/sqlite_point_allocations.py`](../backend/src/domus/infrastructure/sqlite_point_allocations.py) · [`frontend/src/application/allocation-controller.ts`](../frontend/src/application/allocation-controller.ts) · [`frontend/src/adapters/allocation-http.ts`](../frontend/src/adapters/allocation-http.ts) · [`frontend/src/presentation/domus-allocation-settings.ts`](../frontend/src/presentation/domus-allocation-settings.ts) · [`frontend/src/presentation/domus-allocation-preview.ts`](../frontend/src/presentation/domus-allocation-preview.ts) · [`backend/src/domus/domain/rewards.py`](../backend/src/domus/domain/rewards.py) · [`backend/src/domus/application/reward_commands.py`](../backend/src/domus/application/reward_commands.py) · [`backend/src/domus/application/reward_funding.py`](../backend/src/domus/application/reward_funding.py) · [`backend/src/domus/application/reward_queries.py`](../backend/src/domus/application/reward_queries.py) · [`backend/src/domus/infrastructure/sqlite_rewards.py`](../backend/src/domus/infrastructure/sqlite_rewards.py) · [`frontend/src/application/rewards-controller.ts`](../frontend/src/application/rewards-controller.ts) · [`frontend/src/adapters/reward-http.ts`](../frontend/src/adapters/reward-http.ts) · [`frontend/src/presentation/domus-rewards.ts`](../frontend/src/presentation/domus-rewards.ts) -- Tests: [`tests/backend/test_points_consumer.py`](../tests/backend/test_points_consumer.py) · [`tests/backend/test_family_http.py`](../tests/backend/test_family_http.py) · [`frontend/tests/family.test.ts`](../frontend/tests/family.test.ts) · [`frontend/tests/e2e/workspace-navigation.spec.ts`](../frontend/tests/e2e/workspace-navigation.spec.ts) · [`tests/backend/test_point_allocation.py`](../tests/backend/test_point_allocation.py) · [`tests/backend/test_point_allocation_http.py`](../tests/backend/test_point_allocation_http.py) · [`tests/backend/test_point_allocation_storage.py`](../tests/backend/test_point_allocation_storage.py) · [`frontend/tests/allocation.test.ts`](../frontend/tests/allocation.test.ts) · [`tests/backend/test_rewards.py`](../tests/backend/test_rewards.py) · [`tests/backend/test_rewards_http.py`](../tests/backend/test_rewards_http.py) · [`tests/backend/test_rewards_storage.py`](../tests/backend/test_rewards_storage.py) · [`frontend/tests/rewards.test.ts`](../frontend/tests/rewards.test.ts) -- User documentation: [`docs/product-vision.md`](../docs/product-vision.md) · [`docs/architecture.md`](../docs/architecture.md) · [`docs/operations.md`](../docs/operations.md) · [`docs/user-guide.md`](../docs/user-guide.md) · [`docs/contracts/home-assistant.md`](../docs/contracts/home-assistant.md) · [`docs/tasks/points-consumer.md`](../docs/tasks/points-consumer.md) · [`docs/evidence/family-qualification.md`](../docs/evidence/family-qualification.md) +- Core code: [`backend/src/domus/domain/points.py`](../backend/src/domus/domain/points.py) · [`backend/src/domus/application/points.py`](../backend/src/domus/application/points.py) · [`backend/src/domus/application/points_ports.py`](../backend/src/domus/application/points_ports.py) · [`backend/src/domus/infrastructure/sqlite_points.py`](../backend/src/domus/infrastructure/sqlite_points.py) · [`backend/src/domus/application/family_queries.py`](../backend/src/domus/application/family_queries.py) · [`backend/src/domus/application/family_ports.py`](../backend/src/domus/application/family_ports.py) · [`frontend/src/application/family-controller.ts`](../frontend/src/application/family-controller.ts) · [`frontend/src/adapters/family-http.ts`](../frontend/src/adapters/family-http.ts) · [`frontend/src/presentation/domus-family.ts`](../frontend/src/presentation/domus-family.ts) · [`frontend/src/presentation/domus-family-overview.ts`](../frontend/src/presentation/domus-family-overview.ts) · [`frontend/src/presentation/family-messages.ts`](../frontend/src/presentation/family-messages.ts) · [`backend/src/domus/domain/point_allocation.py`](../backend/src/domus/domain/point_allocation.py) · [`backend/src/domus/application/point_allocations.py`](../backend/src/domus/application/point_allocations.py) · [`backend/src/domus/application/point_allocation_ports.py`](../backend/src/domus/application/point_allocation_ports.py) · [`backend/src/domus/infrastructure/sqlite_point_allocations.py`](../backend/src/domus/infrastructure/sqlite_point_allocations.py) · [`frontend/src/application/allocation-controller.ts`](../frontend/src/application/allocation-controller.ts) · [`frontend/src/adapters/allocation-http.ts`](../frontend/src/adapters/allocation-http.ts) · [`frontend/src/presentation/domus-allocation-settings.ts`](../frontend/src/presentation/domus-allocation-settings.ts) · [`frontend/src/presentation/domus-allocation-preview.ts`](../frontend/src/presentation/domus-allocation-preview.ts) · [`backend/src/domus/domain/rewards.py`](../backend/src/domus/domain/rewards.py) · [`backend/src/domus/application/reward_commands.py`](../backend/src/domus/application/reward_commands.py) · [`backend/src/domus/application/reward_funding.py`](../backend/src/domus/application/reward_funding.py) · [`backend/src/domus/application/reward_queries.py`](../backend/src/domus/application/reward_queries.py) · [`backend/src/domus/infrastructure/sqlite_rewards.py`](../backend/src/domus/infrastructure/sqlite_rewards.py) · [`frontend/src/application/rewards-controller.ts`](../frontend/src/application/rewards-controller.ts) · [`frontend/src/adapters/reward-http.ts`](../frontend/src/adapters/reward-http.ts) · [`frontend/src/presentation/domus-rewards.ts`](../frontend/src/presentation/domus-rewards.ts) +- Tests: [`tests/backend/test_points_consumer.py`](../tests/backend/test_points_consumer.py) · [`tests/backend/test_family_http.py`](../tests/backend/test_family_http.py) · [`tests/backend/test_family_overview.py`](../tests/backend/test_family_overview.py) · [`frontend/tests/family.test.ts`](../frontend/tests/family.test.ts) · [`frontend/tests/e2e/workspace-navigation.spec.ts`](../frontend/tests/e2e/workspace-navigation.spec.ts) · [`tests/backend/test_point_allocation.py`](../tests/backend/test_point_allocation.py) · [`tests/backend/test_point_allocation_http.py`](../tests/backend/test_point_allocation_http.py) · [`tests/backend/test_point_allocation_storage.py`](../tests/backend/test_point_allocation_storage.py) · [`frontend/tests/allocation.test.ts`](../frontend/tests/allocation.test.ts) · [`tests/backend/test_rewards.py`](../tests/backend/test_rewards.py) · [`tests/backend/test_rewards_http.py`](../tests/backend/test_rewards_http.py) · [`tests/backend/test_rewards_storage.py`](../tests/backend/test_rewards_storage.py) · [`frontend/tests/rewards.test.ts`](../frontend/tests/rewards.test.ts) +- User documentation: [`docs/product-vision.md`](../docs/product-vision.md) · [`docs/architecture.md`](../docs/architecture.md) · [`docs/operations.md`](../docs/operations.md) · [`docs/user-guide.md`](../docs/user-guide.md) · [`docs/contracts/home-assistant.md`](../docs/contracts/home-assistant.md) · [`docs/tasks/points-consumer.md`](../docs/tasks/points-consumer.md) · [`docs/evidence/family-qualification.md`](../docs/evidence/family-qualification.md) · [`docs/evidence/overview-family-participation-qualification.md`](../docs/evidence/overview-family-participation-qualification.md) ### `shopping-management` — Shared shopping demand, purchases and receipt diff --git a/specs/catalog.json b/specs/catalog.json index fb80a09..773ba82 100644 --- a/specs/catalog.json +++ b/specs/catalog.json @@ -624,7 +624,7 @@ "status": "proposed", "scope": "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.", "owner": "Domus maintainers (review assignment pending)", - "lastVerified": "2026-11-10", + "lastVerified": "2026-11-11", "specs": [ "specs/points-rewards.md" ], @@ -648,6 +648,7 @@ "frontend/src/application/family-controller.ts", "frontend/src/adapters/family-http.ts", "frontend/src/presentation/domus-family.ts", + "frontend/src/presentation/domus-family-overview.ts", "frontend/src/presentation/family-messages.ts", "backend/src/domus/domain/point_allocation.py", "backend/src/domus/application/point_allocations.py", @@ -669,6 +670,7 @@ "tests": [ "tests/backend/test_points_consumer.py", "tests/backend/test_family_http.py", + "tests/backend/test_family_overview.py", "frontend/tests/family.test.ts", "frontend/tests/e2e/workspace-navigation.spec.ts", "tests/backend/test_point_allocation.py", @@ -687,11 +689,12 @@ "docs/user-guide.md", "docs/contracts/home-assistant.md", "docs/tasks/points-consumer.md", - "docs/evidence/family-qualification.md" + "docs/evidence/family-qualification.md", + "docs/evidence/overview-family-participation-qualification.md" ], "readiness": { "state": "draft", - "implementationEvidence": "PR #63 covers scoped Family participation and Points history. PR #66 covers exact configurable allocation, saved policies, and migration. The Family qualification maps the reward command, lifecycle, restoration, and bilingual browser evidence to issue #65 and the retained owner cases.", + "implementationEvidence": "PR #63 covers scoped Family participation and Points history. PR #66 covers exact configurable allocation, saved policies, and migration. The Family qualification maps the reward command, lifecycle, restoration, and bilingual browser evidence to issue #65 and the retained owner cases. Issue #105 covers the protected current-week Overview projection and Family navigation.", "blockingDecisions": "Family qualification records the M2 gate. Publication follows the separate release workflow.", "copilotChangesAllowed": false } diff --git a/specs/points-rewards.md b/specs/points-rewards.md index f739a57..f83a06e 100644 --- a/specs/points-rewards.md +++ b/specs/points-rewards.md @@ -1243,3 +1243,143 @@ Completion requires the concrete behaviors represented by the retained owner cas ### 20. References and decisions Issue: https://github.com/vypdev/domus/issues/65. This delta applies to the immutable selected source revision `2e660f3fba255315316f6835a4b30cd6ee793629` and updates the registered owner `specs/points-rewards.md`; its retained contracts and cases remain authoritative. The issue specifies use of the Action-managed branch from `develop` after #64 merges and excludes Gateway, deployments, releases, and M3. No additional repository verification invocation is asserted here; any concrete invocation or prerequisite remains unverified. + +## Proposed change: Show this week's Family participation on Overview + +- Status: Draft +- Catalog capability: points-rewards + +### 1. Executive summary + +This delta adds a compact Overview summary of the verified member’s completed-task count and earned points for the current Family week, plus one action to open Family for the full report. The Overview points figure includes only that member’s posted earned points for the current week. Points pending verification or pending posting remain visible in the full Family report. The existing points, participation, and rewards contract and cases remain authoritative in `specs/points-rewards.md`; this delta does not change ledger ownership or award behavior. + +### 2. Problem, current behavior, and evidence + +Members can currently see participation and points after opening Family, while the Overview specification calls for weekly points and participation. This delta brings a bounded weekly summary to the initial workspace and links to Family for details. It relies on the retained owner’s rules: work is attributed by actual `completed_at` under household calendar boundaries; approval and posting are distinct; pending points are not spendable credit. The existing Family proposal defines protected, member-scoped reads and separates pending verification, pending posting, and posted credit. These are documented contracts, not evidence that the proposed surfaces are implemented. Evidence: `specs/points-rewards.md` sections 6, 8, 9, and 19; `specs/points-rewards.md` section “Proposed change: Show protected Family points, history and participation”; `specs/application-experience.md` section “Dashboard and navigation”; issue #105 at https://github.com/vypdev/domus/issues/105. The supplied source establishes the Overview’s weekly-summary expectation and existing Family report context; implementation details for the Overview projection and its integration remain to be established. + +### 3. Actors, surfaces, and terminology + +The reader is the verified household member. The Overview is the initial workspace surface; Family remains the destination for the full participation report, including pending values. Use the retained owner’s identity, read-permission, ledger, and Family terminology. “Current Family week” means the current period under the household calendar policy, not the browser’s local week. “Posted earned points” means credit already recorded for the verified member. Completed-task count is based on completed work in that same period; it does not imply that pending points are posted. The single Overview action opens Family. + +### 4. Goals, non-goals, and fixed invariants + +This delta has one product goal: show only the verified member’s posted earned points for the current Family week on Overview, while keeping pending verification and pending posting in the full Family report. The Overview summary also shows that week’s completed-task count and offers one action to open Family. Acceptance includes exclusion of points from earlier and future Family weeks, exclusion of pending verification and pending posting from Overview while retaining each in Family, and member scoping so another member’s points do not appear. Existing Points and Family case IDs remain references to baseline coverage; the six new Overview participation cases are defined in the host inventory. + +This delta does not change the ledger, attribution, read permissions, Family’s role as the full report, or the household calendar policy. It does not expose another member’s data or treat pending points as spendable credit. The specification satisfies the required format; internal and cross-document consistency is checked; reciprocal catalog ownership, paths, and evidence agree with the generated view. The concrete invocation and prerequisites for those publication checks remain unverified in the selected source; no execution or passing result is claimed. + +| Requirement | Behavior | +| --- | --- | +| SDD-I105-U3-R1 | The Overview shows only posted earned points for the verified member's current Family week; pending verification and pending posting remain in the full Family report. | + +### 5. Current versus proposed product journey + +This delta adds a small participation summary to the verified member’s Overview, with one action to open Family. Family remains the full report; this change does not move ledger ownership or alter the retained Points and Family contracts (`specs/points-rewards.md`, sections 5–6). + +| Stage | Current | Proposed | User effect | +|---|---|---|---| +| Open Overview | Weekly points and participation are specified in the retained contract, but this Overview summary is not specified here. | Show the verified member’s completed-task count and earned points for the current Family week. | The member can see this week’s participation from the initial workspace. | +| Read totals | Family provides the full report. | Include only that member’s posted earned points for the current Family week. | The summary has a clear, bounded meaning. | +| See pending work | Pending verification and pending posting remain in the full Family report. | Exclude both from the Overview summary. | Pending values are not mistaken for posted points. | +| Continue | Open Family for the full report. | Provide one accessible action to open Family. | The member can inspect the full report for pending values and other details. | + +The summary MUST exclude points attributed to earlier or future Family weeks and MUST be scoped to the currently verified member. In text: open Overview → read this week’s completed-task count and posted earned points → open Family for the full report. + +### 6. Functional behavior and state model + +The Overview MUST show the verified member’s completed-task count and earned points for the current Family week. Its points total includes only posted earned points attributed to that Family week. Points attributed to earlier or future Family weeks are excluded. Points pending verification and approved points pending posting are excluded from Overview and remain visible in the full Family report. Do not infer posting from completion or approval alone. + +The Overview read MUST use the existing Family week definition, read permissions, and ledger attribution. It MUST scope the result to the verified member and recheck current household authority at the read boundary, consistent with the retained Family read contract (`specs/points-rewards.md`, sections 4 and 6). The summary is read-only and does not create, alter, or erase ledger entries. Family remains the destination for the full report. + +Acceptance is observable across the current-week, earlier-week, future-week, pending-verification, pending-posting, and member-scope situations: only the verified member’s posted earned points for the current Family week appear in that member’s Overview; pending values remain visible in Family. These are covered by the six Overview participation cases in the inventory. + +### 7. User-facing configuration + +No new user-facing configuration is introduced. The summary uses the existing verified member, Family week, read permissions, and ledger attribution. Its scope and inclusion rules are fixed: configuration cannot include another member’s entries, a different week, pending verification, or pending posting. Family remains the full-report destination. + +### 8. Clean Architecture design + +The Overview should consume a member-scoped, read-only participation projection using the existing Points and Family contracts. Keep authorization and current household authority checks at the read boundary; derive member scope from verified context rather than caller-supplied identifiers. Reuse the existing Family week and ledger attribution rules so Overview does not introduce a competing calendar or posting policy. + +Presentation code renders the completed-task count and posted earned-points total and provides the Family action. It must not calculate a separate ledger balance, expose pending values as posted, or mutate ledger state. Preserve the Clean Architecture boundaries and verification expectations of the immutable owning specification (`specs/points-rewards.md`, sections 6 and 8); concrete implementation boundaries remain to be established during design. + +### 9. UI/UX and content contract + +Overview adds a concise participation summary for the verified member: completed-task count and earned points for the current Family week, plus one clear action that opens Family for the full report. Show only posted earned points. Keep points awaiting verification or posting out of this summary and visible in the full Family report. The summary must distinguish zero activity from unavailable data and use accessible labels that identify both the week and the measures. English and Spanish content must fit the existing application experience and remain understandable to assistive technology. The retained owner defines the baseline; this issue adds only the bounded Overview delta. The selected source must be checked for the exact retained UI contract before implementation. + +### 10. Failure, recovery, and cleanup + +If the current-week participation summary cannot load, keep the Overview usable, show an accessible unavailable state, and provide a retry path or the existing route to Family. Do not show stale-week or unverified values as current. Opening Family remains the recovery path to the full report, including pending verification and pending posting. Retry behavior must not duplicate ledger activity or alter earned points. + +### 11. Security, permissions, and privacy + +Use existing Family week boundaries, read permissions, and ledger attribution. The summary is scoped to the verified member and must not expose another member's participation or points. Include only that member's posted earned points in the current Family week; pending verification and pending posting remain confined to the full Family report. Do not change ledger ownership, permissions, or the existing Family report's access rules. Confirm the exact authorization and attribution rules against the immutable owner before implementation. + +### 12. Observability and operational UX + +The Overview must make the selected Family week and the completed-task and posted-points measures understandable without exposing ledger history or pending values. Loading and unavailable states must be accessible and must not imply that missing data is zero. The Family action must give a clear route to the full report. Validate the displayed week, member scope, posted-only total, pending-value exclusion, and English and Spanish presentation against the observable scenarios in the approved inventory. No new telemetry or operational instrumentation is specified by this delta. + +### 13. Compatibility, migration, rollout, and rollback + +This is an additive Overview change. Preserve the existing Family report, week definition, read permissions, ledger attribution, and the retained owning contract and cases in `specs/points-rewards.md` at immutable revision `da5dd58efc90ecf94dd65cf814cc3f4ddd573017`. Use the application's existing localization and navigation conventions where confirmed in the selected source. The source declarations for the relevant presentation, localization, and navigation entry points have not been inspected here, so their exact names and any migration, rollout, or rollback mechanism remain unverified. Do not alter stored data or introduce a migration as part of this delta. + +### 14. Testing strategy and numeric budget + +The retained owner budget is 44 distinct cases. This delta adds six distinct Overview participation cases, bringing the minimum to 50. The six added cases exercise the same requirement through current-week inclusion, exclusion of earlier and future weeks, pending-verification and pending-posting visibility in the full Family report, and member-specific attribution. They are separate observable assertions; the total is a floor, not evidence that tests have run or that coverage is complete. Allocate the six additional cases to presentation and accessibility behavior, with underlying period and attribution rules covered by the existing domain, adapter, and integration budget where applicable. Preserve the retained owner’s deterministic clocks, fakes, coverage expectations, and human UX evidence. The concrete verification invocation and prerequisites for this delta remain unverified. + +| Area | Minimum distinct cases | Behaviors/risks covered | +|---|---:|---| +| Overview participation | 6 | Observable scenarios in the case inventory. | +| Total | 6 | Distinct inventory cases; repeated executions do not add cases. | + +| Case ID | Area | Requirements | Scenario | +| --- | --- | --- | --- | +| overview-participation-C01 | Overview participation | SDD-I105-U3-R1 | The verified member's Overview shows only posted earned points from the current Family week. | +| overview-participation-C02 | Overview participation | SDD-I105-U3-R1 | Points earned in an earlier Family week are excluded from the verified member's Overview. | +| overview-participation-C03 | Overview participation | SDD-I105-U3-R1 | Points earned in a future Family week are excluded from the verified member's Overview. | +| overview-participation-C04 | Overview participation | SDD-I105-U3-R1 | Points pending verification are excluded from the Overview and remain visible in the full Family report. | +| overview-participation-C05 | Overview participation | SDD-I105-U3-R1 | Points pending posting are excluded from the Overview and remain visible in the full Family report. | +| overview-participation-C06 | Overview participation | SDD-I105-U3-R1 | Only the verified member's posted earned points for the current Family week appear in that member's Overview. | + +### 15. Documentation and discoverability + +This update adds the Overview participation contract to the existing points and Family reporting documentation. The member-facing explanation must describe the current Family week, completed-task count, posted earned points, and the action to open Family for the full report. Explain that pending verification and pending posting remain visible in the full Family report and are excluded from Overview. Present this behavior in English and Spanish, consistent with the issue’s stated audience. The selected source does not establish a concrete documentation update destination or invocation for validating this delta; those remain unverified. Publication requires the specification to satisfy the required format, internal and cross-document consistency to be checked, and reciprocal catalog ownership, paths, and evidence to agree with the generated view. + +| Path | Change | +| --- | --- | +| specs/points-rewards.md | update | + +[specs/points-rewards.md](points-rewards.md) + +### 16. Acceptance scenarios + +Acceptance requires observable evidence that the verified member’s Overview includes only posted earned points and completed-task participation for the current Family week. Work attributed to an earlier or future Family week does not appear. Points pending verification and points pending posting do not appear on Overview and remain visible in the full Family report. Attribution is scoped to the verified member, so another member’s points do not appear in that member’s Overview. Provide the single Family action to reach the full report. These scenarios refine the six new inventory assertions; no acceptance result is inferred from their declaration. The existing owning contract and cases remain in force. + +### 17. Requirements traceability + +The new requirement, SDD-I105-U3-R1, is exercised by overview-participation-C01 for current-week posted points; overview-participation-C02 and overview-participation-C03 for earlier- and future-week exclusion; overview-participation-C04 and overview-participation-C05 for pending-state exclusion from Overview with retention in the full Family report; and overview-participation-C06 for verified-member attribution. These are the supplied concrete assertions, not a claim of semantic completeness or executed acceptance. Existing points and Family case identities remain references through the retained owner; they are not redefined by this delta. + +| Requirement | Cases | +|---|---| +| SDD-I105-U3-R1 | overview-participation-C01, overview-participation-C02, overview-participation-C03, overview-participation-C04, overview-participation-C05, overview-participation-C06 | + +### 18. Implementation sequence + +1. Extend the retained Points and Family contract in `specs/points-rewards.md` with a member-scoped Overview summary for the current Family week, preserving the existing owner requirements and case definitions. The six supplied Overview cases are new definitions; existing Points and Family cases remain references. +2. Define the Overview projection from the existing Family-week attribution and read permissions. Show the verified member’s completed-task count and posted earned points for the current Family week only. Keep pending verification and pending posting visible in the full Family report, and provide one action to open Family. +3. Implement the accessible English and Spanish Overview content using the existing Family and Overview surfaces. Do not make the Overview a new ledger or change ledger attribution, balances, or posting behavior. +4. Cover current-week inclusion, earlier- and future-week exclusion, pending-state visibility in Family, and verified-member scoping with the six supplied observable cases. Complete applicable localization, accessibility, permission, and integration acceptance before publication. + +### 19. Definition of Done + +- [ ] The verified member’s Overview shows only that member’s posted earned points and completed-task count for the current Family week; earlier and future Family weeks are excluded. +- [ ] Points pending verification and points pending posting are excluded from Overview and remain visible in the full Family report. The Overview offers one action to open Family. +- [ ] English and Spanish content is accessible and consistent with the existing Overview and Family surfaces and their read permissions. No change to ledger ownership, attribution, balance, or posting semantics is introduced. +- [ ] Each retained owner requirement and each of the six supplied Overview cases has observable acceptance coverage. Every requirement maps to cases that exercise it, and each case lists only requirements it exercises. Structural counts and reciprocal mappings do not establish semantic completeness or executed acceptance. +- [ ] The specification satisfies the required format; internal and cross-document consistency is checked; reciprocal catalog ownership, paths, and evidence agree with the generated view. These are observable publication outcomes. `specs/README.md` names `pnpm run validate:specifications` and `pnpm run generate:specifications`, but the selected root `package.json` does not declare those scripts; concrete invocation and prerequisites for specification validation and generated-view consistency verification remain unverified. Do not treat a declaration as execution, a passing check, or acceptance. +- [ ] Product acceptance verifies current-week boundaries, member scoping, pending verification and posting behavior, localization, and accessible navigation. A source review or structural inventory count alone does not satisfy these outcomes. + +### 20. References and decisions + +This delta updates the immutable retained owner `specs/points-rewards.md` at selected source revision `da5dd58efc90ecf94dd65cf814cc3f4ddd573017` for [issue #105](https://github.com/vypdev/domus/issues/105). The owner’s existing Family contract attributes participation to actual work dates under household calendar boundaries; approval and posting remain distinct, and pending points are not spendable credit. The retained contract also establishes member-scoped Family reads and English and Spanish presentation. This delta adds only the Overview summary and Family navigation action. + +`docs/roadmap.md` identifies household participation as an Overview destination concern and requires authoritative, permission-scoped projections. `specs/application-experience.md` describes Overview as a shared localized surface. The selected root `package.json` declares pnpm 10.34.0 and Node 24.20.x but has no specification-validation or generation script; the README’s named invocations and their prerequisites therefore remain unverified in this selected project. diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py index e2604a6..6c7e8e4 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.26" + assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.28" 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": []} @@ -58,15 +58,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] == "691496c299ff371763e445acb9d36b9623a81404" + assert commits[0] == "b2718e41793d274d22f6f6532da894ed3f158557" assert ( - "DOMUS_SOURCE_SHA256=535c0b95a2db96fe3ebc927596f4e74f6eaadb7b641f2a674c23e672489f0d3b" + "DOMUS_SOURCE_SHA256=e89f738343769db5d24ae5306c11d4c33ed2a4c3885eff46b64a6acbeed94a1a" in source ) - assert "ARG BUILD_VERSION=0.0.0-edge.26" in source + assert "ARG BUILD_VERSION=0.0.0-edge.28" in source candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text()) assert candidate["sourceCommit"] == commits[0] - assert candidate["version"] == "0.0.0-edge.26" + assert candidate["version"] == "0.0.0-edge.28" assert "DOMUS_SOURCE_SHA256=" + candidate["sourceArchiveSHA256"] in source assert re.search(r"^ARG DOMUS_SOURCE_SHA256=[a-f0-9]{64}$", source, re.MULTILINE) assert "sha256sum --check" in source @@ -140,8 +140,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.26" - assert artifact["sourceCommit"] == "691496c299ff371763e445acb9d36b9623a81404" + assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.28" + assert artifact["sourceCommit"] == "b2718e41793d274d22f6f6532da894ed3f158557" assert artifact["storageSchema"] == 31 for field in ["sourceArchiveSHA256", "wheelSHA256"]: assert re.fullmatch("[a-f0-9]{64}", artifact[field]) diff --git a/tests/backend/test_family_overview.py b/tests/backend/test_family_overview.py new file mode 100644 index 0000000..adbd01e --- /dev/null +++ b/tests/backend/test_family_overview.py @@ -0,0 +1,189 @@ +"""Read only the verified member's posted work-period points in both compositions.""" + +from dataclasses import replace +from types import SimpleNamespace + +import pytest +from test_family_http import CHILD_CONTEXT, CHILD_USER, NEXT_WEEK, WEEK, timestamp +from test_recurrence_http import CONTEXT, USER +from test_task_commands import counts, resource +from test_task_runtime import api as api + +from domus.application.points import PointsConsumer +from domus.application.task_commands import TaskCommands +from domus.application.task_requests import CompleteTask, CreateTask, VerifyTask +from domus.domain.identity import ( + HumanIdentity, + Member, + MemberStatus, + Permission, + PermissionRule, + Role, +) +from domus.domain.task_values import TaskContent, TaskOverrides, VerificationState +from domus.infrastructure.application_runtime import SecureIdentifiers, SystemClock + +ROUTE = "/api/v1/family/overview" + + +def record(commands, clock, key, member, at, points): + clock.value = at - 60_000 + _, occurrence = resource( + commands.create( + key + "-create", + CreateTask( + TaskContent(key.replace("-", " ").capitalize()), + overrides=TaskOverrides(point_value_minor=points), + ), + ) + ) + clock.value = at + result = commands.complete(key, CompleteTask(occurrence, 1, (member,), at)).result.decode() + return occurrence, result["revision"], result["cycle"]["cycle_id"] + + +def approve(commands, clock, key, work, at): + clock.value = at + occurrence, revision, cycle = work + commands.verify(key, VerifyTask(occurrence, revision, cycle, VerificationState.APPROVED)) + + +@pytest.fixture +def participation(api, monkeypatch): + api.user(USER, True) + with api.store.write() as unit: + home = unit.households.current() + unit.households.save(replace(home, time_zone="Europe/Madrid", revision=2), 1) + owner = unit.members.by_user("home", USER).member_id + unit.members.save( + Member("child", "home", CHILD_USER, Role.RESTRICTED, MemberStatus.ACTIVE, 1), 0 + ) + observation = SimpleNamespace(value=timestamp(4, 10)) + monkeypatch.setattr(SystemClock, "now", lambda self: observation.value) + clock = SimpleNamespace(value=0) + clock.now = lambda: clock.value + actor = SimpleNamespace(current=lambda: HumanIdentity(USER, True, True, False)) + commands = TaskCommands(api.store, actor, clock, SecureIdentifiers()) + worker = PointsConsumer(api.store, api.store.installation, clock) + return SimpleNamespace( + commands=commands, clock=clock, worker=worker, observation=observation, owner=owner + ) + + +def overview(api, headers=CHILD_CONTEXT): + result = api.client.get(ROUTE, headers=headers) + assert result.status_code == 200, result.text + assert result.headers["cache-control"] == "no-store" + return result.json() + + +def family_report(api): + response = api.client.get("/api/v1/family", headers=CHILD_CONTEXT, params=NEXT_WEEK) + assert response.status_code == 200, response.text + return response.json() + + +def test_overview_participation_c01_reports_current_week_posted_points_without_writes( + api, participation +): + scenario = participation + api.user(CHILD_USER) + assert overview(api) == {"period": NEXT_WEEK, "earned_minor": 0, "completed_count": 0} + work = record(scenario.commands, scenario.clock, "current-work", "child", timestamp(2, 10), 175) + approve(scenario.commands, scenario.clock, "current-approval", work, timestamp(2, 10, 30)) + scenario.worker.tick(lambda: True) + original = counts(api.store) + expected = {"period": NEXT_WEEK, "earned_minor": 175, "completed_count": 1} + assert overview(api) == expected + assert overview(api) == expected + report = family_report(api) + assert report["earned_minor"] == expected["earned_minor"] + assert report["completed_count"] == expected["completed_count"] + assert counts(api.store) == original + + +def test_overview_participation_c02_excludes_sunday_work_posted_on_monday(api, participation): + scenario = participation + work = record( + scenario.commands, scenario.clock, "sunday-work", "child", timestamp(31, 21, 50), 125 + ) + approve(scenario.commands, scenario.clock, "late-approval", work, timestamp(31, 22, 5)) + scenario.worker.tick(lambda: True) + api.user(CHILD_USER) + scenario.observation.value = timestamp(31, 21, 59) + assert overview(api) == {"period": WEEK, "earned_minor": 125, "completed_count": 1} + scenario.observation.value = timestamp(31, 22) + assert overview(api) == {"period": NEXT_WEEK, "earned_minor": 0, "completed_count": 0} + + +def test_overview_participation_c03_excludes_future_week_points(api, participation): + scenario = participation + work = record(scenario.commands, scenario.clock, "future-work", "child", timestamp(8, 10), 500) + approve(scenario.commands, scenario.clock, "future-approval", work, timestamp(8, 10, 30)) + scenario.worker.tick(lambda: True) + api.user(CHILD_USER) + assert overview(api) == {"period": NEXT_WEEK, "earned_minor": 0, "completed_count": 0} + scenario.observation.value = timestamp(7, 22) + assert overview(api) == { + "period": {"start": "2026-06-08", "end": "2026-06-15"}, + "earned_minor": 500, + "completed_count": 1, + } + + +def test_overview_participation_c04_excludes_points_pending_verification(api, participation): + scenario = participation + record( + scenario.commands, scenario.clock, "awaiting-verification", "child", timestamp(3, 9), 225 + ) + scenario.worker.tick(lambda: True) + api.user(CHILD_USER) + assert overview(api) == {"period": NEXT_WEEK, "earned_minor": 0, "completed_count": 1} + assert family_report(api)["pending_verification_minor"] == 225 + + +def test_overview_participation_c05_excludes_points_pending_posting(api, participation): + scenario = participation + work = record( + scenario.commands, scenario.clock, "awaiting-posting", "child", timestamp(3, 10), 325 + ) + approve(scenario.commands, scenario.clock, "queued-award", work, timestamp(3, 10, 30)) + api.user(CHILD_USER) + assert overview(api) == {"period": NEXT_WEEK, "earned_minor": 0, "completed_count": 1} + assert family_report(api)["pending_posting_minor"] == 325 + + +def test_overview_participation_c06_scopes_posted_points_to_the_verified_member(api, participation): + scenario = participation + work = record(scenario.commands, scenario.clock, "child-work", "child", timestamp(2, 10), 175) + approve(scenario.commands, scenario.clock, "child-approval", work, timestamp(2, 10, 30)) + record(scenario.commands, scenario.clock, "owner-work", scenario.owner, timestamp(2, 11), 900) + scenario.worker.tick(lambda: True) + assert overview(api, CONTEXT) == { + "period": NEXT_WEEK, + "earned_minor": 900, + "completed_count": 1, + } + api.user(CHILD_USER) + assert overview(api) == {"period": NEXT_WEEK, "earned_minor": 175, "completed_count": 1} + + +def test_family_overview_rejects_unverified_or_revoked_scope(api): + api.user(USER, True) + assert api.client.get(ROUTE).status_code == 422 + assert api.client.get(ROUTE, headers={"X-Domus-Context": "v1:forged"}).status_code == 403 + assert api.client.get(ROUTE, headers=CONTEXT, params={"member_id": "other"}).status_code == 422 + with api.store.write() as unit: + viewer = Member("child", "home", CHILD_USER, Role.RESTRICTED, MemberStatus.ACTIVE, 1) + unit.members.save(viewer, 0) + api.user(CHILD_USER) + assert api.client.get(ROUTE, headers=CHILD_CONTEXT).status_code == 200 + for revision, permission in enumerate((Permission.TASKS_READ, Permission.HOUSEHOLD_READ), 2): + with api.store.write() as unit: + unit.members.save( + replace(viewer, revision=revision, exceptions=(PermissionRule(permission, False),)), + revision - 1, + ) + denied = api.client.get(ROUTE, headers=CHILD_CONTEXT) + assert denied.status_code == 403 + assert not {"period", "earned_minor", "completed_count"} & denied.json().keys()