Shopping Mode B (Household/Tenant-Only Routes) + Package Extraction Implementation Plan
⚠️ SUPERSEDED — DO NOT EXECUTE (2026-08-06 12:38). The product owner clarified the standalone shopping product — now named GetQwikShop (www.getqwik.shop) — “cannot in any way, shape, or form be attached to LynCareOS,” which rules out this plan’s core approach (adding routes to
backend/routers/shopping.pyand creatingpackages/shopping-catalog/packages/shopping-uiinside this repository). See the current revision of docs/superpowers/specs/2026-08-06-shopping-standalone-product-design.md §0, §0a, and §8 for the corrected approach: zero footprint in this repo, App Store/Play Store billing only, everything built fresh in a new, separate repository once the product owner provides its disk location. This file is kept for historical reference only.
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Add tenant-only (“household”) shopping list/item/SSE routes alongside the existing patient-scoped ones (finishing “Mode B” from 06-SHOPPING-MODULE.md §2), then mechanically extract the catalog data and UI components into standalone packages/ directories so a future standalone product repo has a clean, patient-free starting point to fork.
Architecture: Additive-only backend change — new routes in backend/routers/shopping.py call the existing services/shopping_service.py functions with patient_id=None, which the repository layer already supports. No existing patient-scoped route, test, or frontend behaviour changes. Package extraction is a file copy (not a move, not a live import rewire) into packages/shopping-catalog and packages/shopping-ui, mirroring the existing packages/clinical-anatomy precedent (standalone package.json, not wired into frontend/’s build).
Tech Stack: Python 3 / FastAPI / psycopg (AsyncConnection) / pytest (backend); TypeScript / React 19 / Vite (packages, no new runtime deps needed).
Global Constraints
Section titled “Global Constraints”- Every new route must go through
require_tenant_memberorrequire_tenant_admin— neverrequire_patient_access(there is no patient in this mode). - Every new route passes
patient_id=Noneexplicitly to the service layer — never omit it or infer it. - Permission model for household lists (explicit design decision — the spec text does not enumerate this for Mode B): any active tenant member (
tenant_rolememberoradmin) may add/edit/purchase/unpurchase/remove items and view lists; onlyadmin(orsuper_admin) may create, rename, or delete a list, and onlyadminmay clear purchased items — mirrors the existing Mode A carer-vs-admin split (require_carer_role/require_tenant_admin) without inventing a new role. - Explicitly out of scope for this plan (YAGNI — file a follow-up if the standalone product needs them before Sub-project 3): item photo upload/serve endpoints, catalog badge overrides,
care_start_bootstrapintegration. None of these are required to prove Mode B works; all remain patient-scoped-only after this plan. - No LynCareOS frontend UI is added in this plan. LynCareOS’s own users always have a patient — the new routes exist purely as the hardened reference implementation that the (separate, future) standalone product’s backend will copy. Do not add a
PatientContext-free variant ofShopping.tsx. - Package extraction copies files; it must not delete or modify the originals under
backend/orfrontend/src/, and must not change any existing import path. The live LynCareOS app continues to work exactly as it does today. - Every
docs/Markdown file touched must have its Version and Last Updated stamped withGet-Date -Format "yyyy-MM-dd HH:mm:ss".
Task 1: Household-scoped shopping list routes
Section titled “Task 1: Household-scoped shopping list routes”Files:
- Modify:
backend/routers/shopping.py(insert new section) - Modify:
backend/services/shopping_service.py:203-224,190-201(fixpatient_idtype hints — see Step 1) - Test:
backend/tests/test_shopping.py(append new test class)
Interfaces:
-
Consumes:
svc.get_lists(db, tenant_id, patient_id),svc.create_list(db, tenant_id=, patient_id=, name=, list_type=, grouping_mode=, created_by=),svc.update_list(db, tenant_id, list_id, patient_id, **kwargs),svc.delete_list(db, tenant_id, list_id, patient_id)— all already exist inservices/shopping_service.py. -
Consumes:
auth.require_tenant_member,auth.require_tenant_admin— both already exist inbackend/auth.py. -
Produces: routes
GET/POST /api/shopping/lists,PATCH/DELETE /api/shopping/lists/{list_id}— consumed by Task 2 and Task 3 (which extend the same file section) and, later, by the standalone product’s ported router. -
Step 1: Fix
patient_idtype hints that already supportNonebut claim not to
services/shopping_service.py currently declares patient_id: int (required) on update_list and delete_list, even though both simply forward to repository functions (repo.update_list, repo.archive_list) that already default patient_id: int | None = None and skip the AND patient_id = %s clause when it’s None. This is a pre-existing type-hint inaccuracy, not a runtime bug — fix it so the household routes in this task are honest about what they pass.
Change:
async def update_list( db: AsyncConnection, tenant_id: int, list_id: int, patient_id: int, **kwargs,) -> dict:to:
async def update_list( db: AsyncConnection, tenant_id: int, list_id: int, patient_id: int | None, **kwargs,) -> dict:And change:
async def delete_list( db: AsyncConnection, tenant_id: int, list_id: int, patient_id: int,) -> None:to:
async def delete_list( db: AsyncConnection, tenant_id: int, list_id: int, patient_id: int | None,) -> None:- Step 2: Write the failing tests
Append to backend/tests/test_shopping.py (new top-level class, after TestShoppingLists):
# ── Household-scoped lists (Mode B — no patient) ──────────────────────────────
@requires_dbclass TestHouseholdShoppingLists: @pytest.mark.regression async def test_admin_can_create_household_list(self, client, db): _, token, _tenant_id = await create_user_and_login( db, client, "hh_admin1", "hh_admin1@test.com", membership_role="admin", ) resp = await client.post( "/api/shopping/lists", json={"name": "Weekly Groceries", "list_type": "grocery", "grouping_mode": "by_category"}, headers={"Authorization": f"Bearer {token}"}, ) assert resp.status_code == 201, resp.text data = resp.json() assert data["name"] == "Weekly Groceries" assert data["patient_id"] is None
async def test_member_cannot_create_household_list(self, client, db): _, admin_token, tenant_id = await create_user_and_login( db, client, "hh_admin2", "hh_admin2@test.com", membership_role="admin", ) _, member_token = await create_member_in_tenant( db, "hh_member2", "hh_member2@test.com", tenant_id, membership_role="member", ) resp = await client.post( "/api/shopping/lists", json={"name": "Cleaning Supplies", "list_type": "household", "grouping_mode": "by_category"}, headers={"Authorization": f"Bearer {member_token}"}, ) assert resp.status_code == 403
async def test_member_can_view_household_lists(self, client, db): _, admin_token, tenant_id = await create_user_and_login( db, client, "hh_admin3", "hh_admin3@test.com", membership_role="admin", ) _, member_token = await create_member_in_tenant( db, "hh_member3", "hh_member3@test.com", tenant_id, membership_role="member", ) await client.post( "/api/shopping/lists", json={"name": "Fortnightly Shop", "list_type": "grocery", "grouping_mode": "by_category"}, headers={"Authorization": f"Bearer {admin_token}"}, ) resp = await client.get( "/api/shopping/lists", headers={"Authorization": f"Bearer {member_token}"}, ) assert resp.status_code == 200 names = [lst["name"] for lst in resp.json()] assert "Fortnightly Shop" in names
async def test_rename_household_list(self, client, db): _, token, _ = await create_user_and_login( db, client, "hh_admin4", "hh_admin4@test.com", membership_role="admin", ) create_resp = await client.post( "/api/shopping/lists", json={"name": "Old Name", "list_type": "general", "grouping_mode": "flat"}, headers={"Authorization": f"Bearer {token}"}, ) list_id = create_resp.json()["id"] resp = await client.patch( f"/api/shopping/lists/{list_id}", json={"name": "New Name"}, headers={"Authorization": f"Bearer {token}"}, ) assert resp.status_code == 200 assert resp.json()["name"] == "New Name"
async def test_delete_household_list(self, client, db): _, token, _ = await create_user_and_login( db, client, "hh_admin5", "hh_admin5@test.com", membership_role="admin", ) create_resp = await client.post( "/api/shopping/lists", json={"name": "Temp List", "list_type": "general", "grouping_mode": "flat"}, headers={"Authorization": f"Bearer {token}"}, ) list_id = create_resp.json()["id"] resp = await client.delete( f"/api/shopping/lists/{list_id}", headers={"Authorization": f"Bearer {token}"}, ) assert resp.status_code == 204 list_resp = await client.get( "/api/shopping/lists", headers={"Authorization": f"Bearer {token}"}, ) assert list_id not in [lst["id"] for lst in list_resp.json()]
async def test_household_lists_do_not_leak_across_tenants(self, client, db): _, token_a, _ = await create_user_and_login( db, client, "hh_tenantA", "hh_tenantA@test.com", membership_role="admin", ) _, token_b, _ = await create_user_and_login( db, client, "hh_tenantB", "hh_tenantB@test.com", membership_role="admin", ) await client.post( "/api/shopping/lists", json={"name": "Tenant A List", "list_type": "general", "grouping_mode": "flat"}, headers={"Authorization": f"Bearer {token_a}"}, ) resp = await client.get( "/api/shopping/lists", headers={"Authorization": f"Bearer {token_b}"}, ) assert resp.status_code == 200 assert resp.json() == []- Step 3: Run tests to verify they fail
Run: cd backend && python -m pytest tests/test_shopping.py::TestHouseholdShoppingLists -v
Expected: FAIL — 404 Not Found on every request (routes don’t exist yet).
- Step 4: Implement the routes
In backend/routers/shopping.py, insert the following new section immediately before the # ─── Catalog — read endpoints (all authenticated users) ─── comment line:
# ─── Household-scoped shopping (Mode B — tenant only, no patient) ────────────# See docs/01 - BUSINESS REQUIRMENTS/06-SHOPPING-MODULE.md §2 "Deployment Modes".# These routes always pass patient_id=None. They exist alongside the# patient-scoped routes above (Mode A) without changing that behaviour.# Permission model: any active member may view/add/edit/purchase/remove# items; only an admin may create/rename/delete a list or clear purchased.
@router.get("/shopping/lists")async def list_household_shopping_lists( ctx: dict = Depends(require_tenant_member), db: AsyncConnection = Depends(get_db),): return await _map_domain(svc.get_lists(db, ctx["tenant_id"], None))
@router.post("/shopping/lists", status_code=201)async def create_household_shopping_list( body: ShoppingListCreate, ctx: dict = Depends(require_tenant_admin), db: AsyncConnection = Depends(get_db),): if body.list_type not in ( "grocery", "pharmacy", "personal_care", "household", "services", "equipment", "general" ): raise HTTPException(422, f"Invalid list_type: {body.list_type}") return await _map_domain(svc.create_list( db, tenant_id=ctx["tenant_id"], patient_id=None, name=body.name, list_type=body.list_type, grouping_mode=body.grouping_mode, created_by=ctx["id"], ))
@router.patch("/shopping/lists/{list_id}")async def update_household_shopping_list( list_id: int, body: ShoppingListUpdate, ctx: dict = Depends(require_tenant_admin), db: AsyncConnection = Depends(get_db),): updates = body.model_dump(exclude_none=True) return await _map_domain(svc.update_list(db, ctx["tenant_id"], list_id, None, **updates))
@router.delete("/shopping/lists/{list_id}", status_code=204)async def delete_household_shopping_list( list_id: int, ctx: dict = Depends(require_tenant_admin), db: AsyncConnection = Depends(get_db),): await _map_domain(svc.delete_list(db, ctx["tenant_id"], list_id, None))
# ─── Catalog — read endpoints (all authenticated users) ───────────────────────(Note the duplicated final comment line — replace the original # ─── Catalog — read endpoints (all authenticated users) ─── line with the whole block above, which ends by restoring that same comment line.)
- Step 5: Run tests to verify they pass
Run: cd backend && python -m pytest tests/test_shopping.py::TestHouseholdShoppingLists -v
Expected: PASS — all 6 tests green.
- Step 6: Run the full shopping test file to confirm no regression
Run: cd backend && python -m pytest tests/test_shopping.py -v
Expected: PASS — all existing TestShoppingLists/TestShoppingItems/etc. tests still pass unchanged.
- Step 7: Commit
git add backend/routers/shopping.py backend/services/shopping_service.py backend/tests/test_shopping.pygit commit -m "feat(shopping): add household-scoped (Mode B) list routes"Task 2: Household-scoped shopping item routes
Section titled “Task 2: Household-scoped shopping item routes”Files:
- Modify:
backend/routers/shopping.py(extend the section added in Task 1) - Test:
backend/tests/test_shopping.py(append new test class)
Interfaces:
-
Consumes:
svc.get_items(db, list_id, tenant_id, patient_id, status),svc.add_item(db, list_id=, tenant_id=, patient_id=, added_by=, added_by_name=, **fields),svc.update_item(db, list_id, item_id, tenant_id, patient_id, user_name=, **fields),svc.mark_purchased(db, list_id=, item_id=, tenant_id=, patient_id=, purchased_by=, purchased_by_name=),svc.undo_purchase(db, list_id=, item_id=, tenant_id=, patient_id=, user_name=),svc.remove_item(db, list_id=, item_id=, tenant_id=, patient_id=, removed_by=, removed_by_name=),svc.clear_purchased(db, list_id=, tenant_id=, patient_id=, user_name=)— all already exist. -
Produces: routes under
/api/shopping/lists/{list_id}/items...— no other task depends on these directly, but Task 3’s used-before/SSE routes live in the same file section. -
Step 1: Fix
get_items’spatient_idtype hint
In services/shopping_service.py, change:
async def get_items( db: AsyncConnection, list_id: int, tenant_id: int, patient_id: int, status: str = "active",) -> list[dict]:to:
async def get_items( db: AsyncConnection, list_id: int, tenant_id: int, patient_id: int | None, status: str = "active",) -> list[dict]:(Same rationale as Task 1 Step 1 — repo.get_list already handles patient_id=None correctly.)
- Step 2: Write the failing tests
Append to backend/tests/test_shopping.py, after TestHouseholdShoppingLists:
# ── Household-scoped items (Mode B — no patient) ──────────────────────────────
async def _create_household_list(client, token, name="Weekly Shop", list_type="grocery"): resp = await client.post( "/api/shopping/lists", json={"name": name, "list_type": list_type, "grouping_mode": "by_category"}, headers={"Authorization": f"Bearer {token}"}, ) assert resp.status_code == 201, resp.text return resp.json()["id"]
@requires_dbclass TestHouseholdShoppingItems: @pytest.mark.regression async def test_member_can_add_and_view_item(self, client, db): _, admin_token, tenant_id = await create_user_and_login( db, client, "hh_item_admin1", "hh_item_admin1@test.com", membership_role="admin", ) _, member_token = await create_member_in_tenant( db, "hh_item_member1", "hh_item_member1@test.com", tenant_id, membership_role="member", ) list_id = await _create_household_list(client, admin_token) add_resp = await client.post( f"/api/shopping/lists/{list_id}/items", json={"name": "Milk", "quantity": 2.0, "unit": "L"}, headers={"Authorization": f"Bearer {member_token}"}, ) assert add_resp.status_code == 201, add_resp.text item = add_resp.json() assert item["name"] == "Milk" assert item["patient_id"] is None
list_resp = await client.get( f"/api/shopping/lists/{list_id}/items?status=active", headers={"Authorization": f"Bearer {admin_token}"}, ) assert list_resp.status_code == 200 assert any(i["id"] == item["id"] for i in list_resp.json())
async def test_member_can_purchase_and_undo(self, client, db): _, token, _ = await create_user_and_login( db, client, "hh_item_admin2", "hh_item_admin2@test.com", membership_role="admin", ) list_id = await _create_household_list(client, token) add_resp = await client.post( f"/api/shopping/lists/{list_id}/items", json={"name": "Bread", "quantity": 1.0, "unit": "loaf"}, headers={"Authorization": f"Bearer {token}"}, ) item_id = add_resp.json()["id"]
purchase_resp = await client.post( f"/api/shopping/lists/{list_id}/items/{item_id}/purchase", headers={"Authorization": f"Bearer {token}"}, ) assert purchase_resp.status_code == 200 assert purchase_resp.json()["status"] == "purchased"
undo_resp = await client.post( f"/api/shopping/lists/{list_id}/items/{item_id}/unpurchase", headers={"Authorization": f"Bearer {token}"}, ) assert undo_resp.status_code == 200 assert undo_resp.json()["status"] == "active"
async def test_member_can_remove_item(self, client, db): _, token, _ = await create_user_and_login( db, client, "hh_item_admin3", "hh_item_admin3@test.com", membership_role="admin", ) list_id = await _create_household_list(client, token) add_resp = await client.post( f"/api/shopping/lists/{list_id}/items", json={"name": "Eggs", "quantity": 12, "unit": "pack"}, headers={"Authorization": f"Bearer {token}"}, ) item_id = add_resp.json()["id"] del_resp = await client.delete( f"/api/shopping/lists/{list_id}/items/{item_id}", headers={"Authorization": f"Bearer {token}"}, ) assert del_resp.status_code == 204 list_resp = await client.get( f"/api/shopping/lists/{list_id}/items?status=active", headers={"Authorization": f"Bearer {token}"}, ) assert item_id not in [i["id"] for i in list_resp.json()]
async def test_member_cannot_clear_purchased_only_admin_can(self, client, db): _, admin_token, tenant_id = await create_user_and_login( db, client, "hh_item_admin4", "hh_item_admin4@test.com", membership_role="admin", ) _, member_token = await create_member_in_tenant( db, "hh_item_member4", "hh_item_member4@test.com", tenant_id, membership_role="member", ) list_id = await _create_household_list(client, admin_token) add_resp = await client.post( f"/api/shopping/lists/{list_id}/items", json={"name": "Butter", "quantity": 1.0, "unit": "tub"}, headers={"Authorization": f"Bearer {admin_token}"}, ) item_id = add_resp.json()["id"] await client.post( f"/api/shopping/lists/{list_id}/items/{item_id}/purchase", headers={"Authorization": f"Bearer {admin_token}"}, )
member_clear = await client.post( f"/api/shopping/lists/{list_id}/clear-purchased", headers={"Authorization": f"Bearer {member_token}"}, ) assert member_clear.status_code == 403
admin_clear = await client.post( f"/api/shopping/lists/{list_id}/clear-purchased", headers={"Authorization": f"Bearer {admin_token}"}, ) assert admin_clear.status_code == 200 assert admin_clear.json()["archived_count"] == 1- Step 3: Run tests to verify they fail
Run: cd backend && python -m pytest tests/test_shopping.py::TestHouseholdShoppingItems -v
Expected: FAIL — 404 Not Found (routes don’t exist yet).
- Step 4: Implement the routes
In backend/routers/shopping.py, extend the “Household-scoped shopping” section added in Task 1 — insert the following immediately after delete_household_shopping_list and before the restored # ─── Catalog — read endpoints ─── line:
@router.get("/shopping/lists/{list_id}/items")async def list_household_shopping_items( list_id: int, status: str = Query("active", description="active|purchased|removed|all"), ctx: dict = Depends(require_tenant_member), db: AsyncConnection = Depends(get_db),): if status not in ("active", "purchased", "removed", "all"): raise HTTPException(422, "status must be active|purchased|removed|all") return await _map_domain(svc.get_items(db, list_id, ctx["tenant_id"], None, status))
@router.post("/shopping/lists/{list_id}/items", status_code=201)async def add_household_shopping_item( list_id: int, body: ShoppingItemCreate, ctx: dict = Depends(require_tenant_member), db: AsyncConnection = Depends(get_db),): fields = body.model_dump(exclude_none=True) item = await _map_domain(svc.add_item( db, list_id=list_id, tenant_id=ctx["tenant_id"], patient_id=None, added_by=ctx["id"], added_by_name=ctx.get("username"), **fields, ))
if not body.catalog_item_id and body.name: try: await svc.submit_suggestion( db, tenant_id=ctx["tenant_id"], suggested_name=body.name, suggested_category_id=body.category_id, suggested_subcategory_id=body.subcategory_id, item_type=body.item_type, created_by_user_id=ctx["id"], ) except Exception: logger.warning("Catalog suggestion submission failed — non-critical", exc_info=True)
return item
@router.patch("/shopping/lists/{list_id}/items/{item_id}")async def update_household_shopping_item( list_id: int, item_id: int, body: ShoppingItemUpdate, ctx: dict = Depends(require_tenant_member), db: AsyncConnection = Depends(get_db),): fields = body.model_dump(exclude_none=True) return await _map_domain(svc.update_item( db, list_id, item_id, ctx["tenant_id"], None, user_name=ctx.get("username"), **fields ))
@router.post("/shopping/lists/{list_id}/items/{item_id}/purchase")async def purchase_household_shopping_item( list_id: int, item_id: int, ctx: dict = Depends(require_tenant_member), db: AsyncConnection = Depends(get_db),): return await _map_domain(svc.mark_purchased( db, list_id=list_id, item_id=item_id, tenant_id=ctx["tenant_id"], patient_id=None, purchased_by=ctx["id"], purchased_by_name=ctx.get("username"), ))
@router.post("/shopping/lists/{list_id}/items/{item_id}/unpurchase")async def unpurchase_household_shopping_item( list_id: int, item_id: int, ctx: dict = Depends(require_tenant_member), db: AsyncConnection = Depends(get_db),): return await _map_domain(svc.undo_purchase( db, list_id=list_id, item_id=item_id, tenant_id=ctx["tenant_id"], patient_id=None, user_name=ctx.get("username"), ))
@router.delete("/shopping/lists/{list_id}/items/{item_id}", status_code=204)async def remove_household_shopping_item( list_id: int, item_id: int, ctx: dict = Depends(require_tenant_member), db: AsyncConnection = Depends(get_db),): await _map_domain(svc.remove_item( db, list_id=list_id, item_id=item_id, tenant_id=ctx["tenant_id"], patient_id=None, removed_by=ctx["id"], removed_by_name=ctx.get("username"), ))
@router.post("/shopping/lists/{list_id}/clear-purchased")async def clear_household_purchased_items( list_id: int, ctx: dict = Depends(require_tenant_admin), db: AsyncConnection = Depends(get_db),): count = await _map_domain(svc.clear_purchased( db, list_id=list_id, tenant_id=ctx["tenant_id"], patient_id=None, user_name=ctx.get("username"), )) return {"archived_count": count}- Step 5: Run tests to verify they pass
Run: cd backend && python -m pytest tests/test_shopping.py::TestHouseholdShoppingItems -v
Expected: PASS — all 4 tests green.
- Step 6: Run the full shopping test file to confirm no regression
Run: cd backend && python -m pytest tests/test_shopping.py -v
Expected: PASS — all existing and Task 1 tests still pass.
- Step 7: Commit
git add backend/routers/shopping.py backend/services/shopping_service.py backend/tests/test_shopping.pygit commit -m "feat(shopping): add household-scoped (Mode B) item routes"Task 3: Household-scoped “used before” and SSE events routes
Section titled “Task 3: Household-scoped “used before” and SSE events routes”Files:
- Modify:
backend/routers/shopping.py(extend the section added in Tasks 1–2) - Test:
backend/tests/test_shopping.py(append new test class)
Interfaces:
-
Consumes:
svc.get_settings(db, tenant_id),svc.get_used_before(db, tenant_id, patient_id, limit, days_window),svc.sse_stream(tenant_id, patient_id)— all already exist. -
Produces:
GET /api/shopping/used-before,GET /api/shopping/events— terminal routes for this plan; the future standalone product’s frontend calls these directly (via a porteduseShoppingSync-style hook), no other task in this plan depends on them. -
Step 1: Write the failing test
Append to backend/tests/test_shopping.py, after TestHouseholdShoppingItems:
# ── Household-scoped used-before (Mode B — no patient) ────────────────────────
@requires_dbclass TestHouseholdUsedBefore: @pytest.mark.regression async def test_purchased_item_appears_in_household_used_before(self, client, db): _, token, _ = await create_user_and_login( db, client, "hh_ub_admin1", "hh_ub_admin1@test.com", membership_role="admin", ) list_id = await _create_household_list(client, token) add_resp = await client.post( f"/api/shopping/lists/{list_id}/items", json={"name": "Oat Milk", "quantity": 1.0, "unit": "L"}, headers={"Authorization": f"Bearer {token}"}, ) item_id = add_resp.json()["id"] await client.post( f"/api/shopping/lists/{list_id}/items/{item_id}/purchase", headers={"Authorization": f"Bearer {token}"}, )
resp = await client.get( "/api/shopping/used-before", headers={"Authorization": f"Bearer {token}"}, ) assert resp.status_code == 200 names = [row["name"] for row in resp.json()] assert "Oat Milk" in names
async def test_used_before_does_not_leak_across_tenants(self, client, db): _, token_a, _ = await create_user_and_login( db, client, "hh_ub_tenantA", "hh_ub_tenantA@test.com", membership_role="admin", ) _, token_b, _ = await create_user_and_login( db, client, "hh_ub_tenantB", "hh_ub_tenantB@test.com", membership_role="admin", ) list_id = await _create_household_list(client, token_a) add_resp = await client.post( f"/api/shopping/lists/{list_id}/items", json={"name": "Tenant A Only Item", "quantity": 1.0}, headers={"Authorization": f"Bearer {token_a}"}, ) item_id = add_resp.json()["id"] await client.post( f"/api/shopping/lists/{list_id}/items/{item_id}/purchase", headers={"Authorization": f"Bearer {token_a}"}, )
resp = await client.get( "/api/shopping/used-before", headers={"Authorization": f"Bearer {token_b}"}, ) assert resp.status_code == 200 assert resp.json() == []- Step 2: Run test to verify it fails
Run: cd backend && python -m pytest tests/test_shopping.py::TestHouseholdUsedBefore -v
Expected: FAIL — 404 Not Found.
- Step 3: Implement the routes
In backend/routers/shopping.py, insert the following immediately after the last route added in Task 2 (clear_household_purchased_items) and before the restored # ─── Catalog — read endpoints ─── line:
@router.get("/shopping/used-before")async def get_household_used_before( limit: int = Query(30, ge=1, le=100), ctx: dict = Depends(require_tenant_member), db: AsyncConnection = Depends(get_db),): settings = await svc.get_settings(db, ctx["tenant_id"]) days_window = settings.get("used_before_days_window", 90) return await svc.get_used_before(db, ctx["tenant_id"], None, limit, days_window)
@router.get("/shopping/events")async def household_shopping_events( ctx: dict = Depends(require_tenant_member),): """Server-Sent Events stream for real-time household shopping list updates.""" async def generate(): async for chunk in svc.sse_stream(ctx["tenant_id"], None): yield chunk
return StreamingResponse( generate(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "X-Accel-Buffering": "no", }, )Note: household_shopping_events is not covered by an automated test in this task — StreamingResponse/SSE generators are awkward to assert against with the synchronous test client used elsewhere in this file, and svc.sse_stream’s Redis pub/sub plumbing is already covered by the existing patient-scoped SSE tests (if any) plus Task 2’s coverage of broadcast() being called on every mutation. Manually verify with curl -N http://localhost:8021/api/shopping/events -H "Authorization: Bearer <token>" after Step 4, in a second terminal, while purchasing an item via Task 2’s routes in a first terminal — confirm an event: shopping_list_updated line appears.
- Step 4: Run test to verify it passes
Run: cd backend && python -m pytest tests/test_shopping.py::TestHouseholdUsedBefore -v
Expected: PASS — both tests green.
- Step 5: Run the full shopping test file to confirm no regression
Run: cd backend && python -m pytest tests/test_shopping.py -v
Expected: PASS — every test in the file (existing + Tasks 1–3) is green.
- Step 6: Commit
git add backend/routers/shopping.py backend/tests/test_shopping.pygit commit -m "feat(shopping): add household-scoped (Mode B) used-before and SSE routes"Task 4: Update the module spec doc
Section titled “Task 4: Update the module spec doc”Files:
- Modify:
docs/01 - BUSINESS REQUIRMENTS/06-SHOPPING-MODULE.md
Interfaces:
-
Consumes: nothing (documentation-only task).
-
Produces: an accurate implementation-status record for the next engineer or the standalone product’s team — no code depends on this.
-
Step 1: Get the current timestamp
Run: Get-Date -Format "yyyy-MM-dd HH:mm:ss"
- Step 2: Update the version header
In docs/01 - BUSINESS REQUIRMENTS/06-SHOPPING-MODULE.md, replace:
**Version:** 1.14**Last Updated:** 2026-06-03 12:00:00with (substituting the real timestamp from Step 1):
**Version:** 1.15**Last Updated:** <timestamp from Step 1>- Step 3: Add a Mode B implementation-status row
In the “Implementation notes (code vs original spec)” table near the top of the file, add a new row directly after the existing “Core lists + catalog + SSE” row:
| Mode B — household/tenant-only routes | **Backend done** (2026-08) — `GET/POST /api/shopping/lists`, `PATCH/DELETE /api/shopping/lists/{id}`, item CRUD, `used-before`, `events` all accept `patient_id=None`. **Not exposed in LynCareOS's own frontend** — these routes exist as the reference implementation for the standalone product spin-off analysis; see [docs/plans/2026-08-06-shopping-module-standalone-product-extraction.md](/internal/plans/2026-08-06-shopping-module-standalone-product-extraction/). |- Step 4: Commit
git add "docs/01 - BUSINESS REQUIRMENTS/06-SHOPPING-MODULE.md"git commit -m "docs(shopping): record Mode B backend routes as implemented"Task 5: Extract packages/shopping-catalog
Section titled “Task 5: Extract packages/shopping-catalog”Files:
- Create:
packages/shopping-catalog/package.json - Create:
packages/shopping-catalog/README.md - Create:
packages/shopping-catalog/seed_shopping_catalog.py(copy ofbackend/scripts/seed_shopping_catalog.py) - Create:
packages/shopping-catalog/icons/(copy offrontend/public/catalog-icons/)
Interfaces:
-
Consumes: nothing from the live app (this is a copy, not a live dependency).
-
Produces: a versioned, portable catalog dataset for the standalone product’s future repo to fork from (Sub-project 3/4 in the design spec) — no other task in this plan depends on it.
-
Step 1: Create the package directory and copy the seed script
Run (PowerShell, from repo root):
New-Item -ItemType Directory -Force -Path "packages\shopping-catalog\icons" | Out-NullCopy-Item "backend\scripts\seed_shopping_catalog.py" "packages\shopping-catalog\seed_shopping_catalog.py"Copy-Item "frontend\public\catalog-icons\*" "packages\shopping-catalog\icons\" -Recurse- Step 2: Verify the copy is complete
Run: (Get-ChildItem -Recurse "packages\shopping-catalog\icons" -File).Count
Expected: 200 (matches the source count — see the companion analysis doc §2).
- Step 3: Write
packages/shopping-catalog/package.json
{ "name": "@lyncareos/shopping-catalog", "version": "0.1.0", "private": true, "description": "Portable grocery/household/pharmacy/services catalog data (categories, subcategories, ~300 items, aliases) and icon set, extracted from LynCareOS's Shopping module as a fork point for the standalone family-shopping product.", "files": [ "seed_shopping_catalog.py", "icons/**" ]}- Step 4: Write
packages/shopping-catalog/README.md
# @lyncareos/shopping-catalog
A snapshot of LynCareOS's Shopping module catalog data — 6 categories, ~55subcategories, ~300 items with locale-tagged aliases, and 200 SVG icons —extracted as a fork point for the standalone family-shopping product designin docs/superpowers/specs/2026-08-06-shopping-standalone-product-design.md.
## What this is
- `seed_shopping_catalog.py` — an idempotent seeder (`ON CONFLICT DO NOTHING`) that populates `catalog_categories` / `catalog_subcategories` / `catalog_items` / `catalog_item_aliases` from hardcoded Python data. It currently connects via `psycopg` using LynCareOS's `backend/config.py` (`DATABASE_URL` env var) — **when forking into the standalone product's own repo, replace the `import config` / connection-string line with that repo's own database config.** No other change is required; the SQL and data are already tenant-agnostic (the catalog tables have no `tenant_id` column at all).- `icons/` — the 200 SVG illustrations referenced by `icon_type='svg'` rows, copied from `frontend/public/catalog-icons/`.
## What this is not
- **Not a live dependency of the LynCareOS app.** This is a point-in-time copy for the standalone product to fork and diverge from (rebrand icons, drop the pharmacy/medical list type, etc. — see the design spec's "diverge" decision). Future catalog improvements in LynCareOS are **not** automatically reflected here; re-copy if you want to pull newer data before diverging further.- Not wired into any build (`npm install`able but nothing currently imports it) — same pattern as the existing `packages/clinical-anatomy` package in this repo.
## Schema this data targets
See `backend/migrations/archive/pre-v1/V012__shopping_module.sql` in the mainLynCareOS repo for the original table definitions this seed script expects(`catalog_categories`, `catalog_subcategories`, `catalog_items`,`catalog_item_aliases`, `catalog_category_translations`,`catalog_subcategory_translations`).- Step 5: Verify the originals are untouched
Run: git status backend/scripts/seed_shopping_catalog.py frontend/public/catalog-icons/ (if using git) or manually confirm file timestamps/sizes on backend/scripts/seed_shopping_catalog.py are unchanged from before Step 1.
Expected: no modifications reported on the original files — only new files under packages/shopping-catalog/.
- Step 6: Commit
git add packages/shopping-cataloggit commit -m "chore(shopping): extract packages/shopping-catalog as a fork point"Task 6: Extract packages/shopping-ui
Section titled “Task 6: Extract packages/shopping-ui”Files:
- Create:
packages/shopping-ui/package.json - Create:
packages/shopping-ui/README.md - Create:
packages/shopping-ui/tsconfig.json - Create:
packages/shopping-ui/src/components/(copy offrontend/src/components/shopping/*.tsx) - Create:
packages/shopping-ui/src/lib/(copy offrontend/src/lib/shoppingSummary.ts,shoppingBadgeOverrides.ts,shoppingListTypeTileSchemes.ts) - Create:
packages/shopping-ui/src/hooks/(copy offrontend/src/hooks/useShoppingSync.ts)
Interfaces:
-
Consumes: nothing from the live app (this is a copy).
-
Produces: a versioned, portable UI component set for the standalone product’s future frontend (Sub-project 4 in the design spec) — no other task in this plan depends on it.
-
Step 1: Create the package directory structure and copy files
Run (PowerShell, from repo root):
New-Item -ItemType Directory -Force -Path "packages\shopping-ui\src\components" | Out-NullNew-Item -ItemType Directory -Force -Path "packages\shopping-ui\src\lib" | Out-NullNew-Item -ItemType Directory -Force -Path "packages\shopping-ui\src\hooks" | Out-Null
Copy-Item "frontend\src\components\shopping\*.tsx" "packages\shopping-ui\src\components\"Copy-Item "frontend\src\lib\shoppingSummary.ts" "packages\shopping-ui\src\lib\"Copy-Item "frontend\src\lib\shoppingBadgeOverrides.ts" "packages\shopping-ui\src\lib\"Copy-Item "frontend\src\lib\shoppingListTypeTileSchemes.ts" "packages\shopping-ui\src\lib\"Copy-Item "frontend\src\hooks\useShoppingSync.ts" "packages\shopping-ui\src\hooks\"- Step 2: Verify the copy is complete
Run: (Get-ChildItem "packages\shopping-ui\src\components" -File).Count
Expected: 16 (matches the component inventory in the companion analysis doc §2).
- Step 3: Write
packages/shopping-ui/package.json
{ "name": "@lyncareos/shopping-ui", "version": "0.1.0", "private": true, "description": "React/Calm Care UI components for shopping lists, catalog browsing, and used-before, extracted from LynCareOS's Shopping module as a fork point for the standalone family-shopping product.", "type": "module", "peerDependencies": { "react": "^19.2.4", "react-dom": "^19.2.4", "react-i18next": "^16.2.0", "lucide-react": "^0.548.0" }, "devDependencies": { "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "typescript": "~5.9.3" }}(Check frontend/package.json for the exact installed react-i18next and lucide-react version ranges before finalizing this file — copy the real values rather than guessing, since a mismatch would mislead whoever forks this package next.)
- Step 4: Write
packages/shopping-ui/tsconfig.json
{ "compilerOptions": { "target": "ES2022", "lib": ["ES2022", "DOM"], "module": "ESNext", "moduleResolution": "bundler", "jsx": "react-jsx", "strict": true, "skipLibCheck": true, "esModuleInterop": true, "declaration": true, "outDir": "dist" }, "include": ["src"]}- Step 5: Write
packages/shopping-ui/README.md
# @lyncareos/shopping-ui
React components for shopping lists, the catalog Add panel, and the Purchasedsection — extracted from LynCareOS's `frontend/src/components/shopping/` as afork point for the standalone family-shopping product design indocs/superpowers/specs/2026-08-06-shopping-standalone-product-design.md.
## What this is
16 components (`ActiveItemList`, `AddItemsSheet`, `AddCustomProductSheet`,`CatalogItemTile`, `CategoryBrowser`, `IconResolver`, `NewListModal`,`PurchasedSection`/`PurchasedTile`, `ShoppingListRow`/`Tabs`,`ShoppingDashboardWidget`, `ShoppingShiftWidget`, `CropImageSheet`,`CatalogItemEditModal`, `DeleteCardConfirmDialog`) plus three pure-functionhelper modules (`shoppingSummary.ts`, `shoppingBadgeOverrides.ts`,`shoppingListTypeTileSchemes.ts`) and the SSE sync hook (`useShoppingSync.ts`).
## Before forking further
These components currently:- Use Calm Care `cc-*` Tailwind classes and design tokens (`tailwind.config.js` / `index.css` in the main LynCareOS `frontend/`) — the standalone product needs to ship an equivalent token set (its own brand) or these components will render unstyled.- Call `t()` from `react-i18next` for all copy — port the `shopping.*` key bundle from `frontend/src/locales/en-AU/common.json` alongside this package, or replace with the standalone product's own i18n setup.- Some components (`ShoppingDashboardWidget`, `ShoppingShiftWidget`) call `useModule('shopping')` from LynCareOS's `ModuleContext` — the standalone product has no module-gating concept and should drop these two components or replace the hook with a no-op.- `useShoppingSync.ts` calls `api.auth.sseTicket()` for an anti-replay SSE ticket — port that endpoint's pattern or adapt the hook to the standalone product's own auth token scheme.
## What this is not
Not wired into any build — copied for the standalone product to fork andre-skin, matching the existing `packages/clinical-anatomy` pattern in thisrepo. Not a live dependency of `frontend/`.- Step 6: Verify the originals are untouched
Confirm frontend/src/components/shopping/*.tsx, frontend/src/lib/shoppingSummary.ts, and frontend/src/hooks/useShoppingSync.ts are byte-identical to before Step 1 (unchanged timestamps/sizes, or git status shows no modifications if using git).
- Step 7: Run the existing frontend shopping tests to confirm no regression
Run: cd frontend && npm run test -- Shopping shoppingSummary
Expected: PASS — Shopping.test.tsx and shoppingSummary.test.ts both still pass unchanged (they import from frontend/src/..., not from the new package).
- Step 8: Commit
git add packages/shopping-uigit commit -m "chore(shopping): extract packages/shopping-ui as a fork point"Self-Review
Section titled “Self-Review”- Spec coverage: Task 1–3 implement §7 Sub-project 1 (Mode B backend) from the design spec; Task 5–6 implement §7 Sub-project 2 (package extraction). Sub-projects 3–5 (new repo, native track) are explicitly out of scope for this plan per the design spec’s own sequencing and will get their own plan once that repo exists.
- Placeholder scan: none found — every step has complete, real code or an exact command.
- Type consistency:
patient_idisNone(Python) / omitted-and-defaulted consistently across every new route and service call in Tasks 1–3;ctx["tenant_id"]/ctx["id"]/ctx.get("username")match the exact dict shape returned byauth.require_tenant_member/require_tenant_admin(verified againstbackend/auth.py:389-407). - Ambiguity check resolved inline: the household list-management permission split (member vs. admin) is stated explicitly in Global Constraints rather than left to the implementer’s judgement, since the source spec doesn’t enumerate it for Mode B.