Shopping Module — Standalone Product Extraction Analysis
Version: 1.0
Last Updated: 2026-08-06 10:26:31
Status: Exploratory analysis — no code changed. Companion to debt D4 (“Shopping as separate product”) in 32-KNOWN-DEBTS-REGISTER.md.
Related: 06-SHOPPING-MODULE.md (behavioural spec) · 01-ARCHITECTURE.md · packages/clinical-anatomy (precedent for an extracted, independently-versioned package inside this repo)
1. Verdict
Section titled “1. Verdict”Feasible, but not “copy-paste” today. The module is well-layered (Router → Service → Repository, zero SQL in the router, tenant-scoped throughout) and the database schema was already designed for a tenant-only “standalone mode” (shopping_lists.patient_id is nullable, tenant_shopping_settings.standalone_mode exists). That intent, however, was never implemented — every route, every frontend call, and every UI component assumes a LynCareOS patient exists. Selling this as its own product means either:
- (A) Fork it — copy the code into a new repo/app and strip the patient concept out, or
- (B) Finish “Mode B” and extract as a package — implement the tenant-level routes the spec already describes, then lift the module into an internal package (mirroring
packages/clinical-anatomy) that both LynCareOS and a new thin “Shopping” app import.
Recommendation: (B). It costs more up front (finish Mode B: ~1–2 weeks) but avoids maintaining two divergent copies of ~1,400 lines of repository SQL, the 750-line router, and — most valuable of all — the 300+ item / 200-icon catalog that took a full phase to build. Section 6 gives the phased breakdown either way you choose.
2. What exists today (inventory)
Section titled “2. What exists today (inventory)”| Layer | File(s) | Size | Notes |
|---|---|---|---|
| Router | backend/routers/shopping.py | ~750 lines | All patient-scoped: /api/patients/{patient_id}/shopping/.... Catalog reads are tenant-scoped (/api/shopping/catalog/...). |
| Router (admin) | backend/routers/admin_shopping.py | ~155 lines | Super-admin catalog moderation (approve/reject/merge suggestions, CRUD global catalog items). |
| Service | backend/services/shopping_service.py | ~570 lines | Business rules, SSE broadcast, locale resolution, recurring-item reset job. |
| Repository | backend/repositories/shopping.py | ~1,400 lines | Pure SQL. Every query already includes tenant_id. |
| Repository (admin) | backend/repositories/admin_shopping.py | ~145 lines | Global (non-tenant) catalog CRUD — explicitly excluded from the tenant-isolation lint scan (PLATFORM_REPOS). |
| Alerts glue | backend/services/alert_shopping_sync.py, alert_shopping_helpers.py | ~100 lines | Consolidated “N items to collect” alert — calls the generic alert_service/alert_registry. |
| Care Start glue | backend/services/care_start_bootstrap.py (§ ensure_pack_shopping_lists) | ~30 lines used | Seeds themed lists when a Care Profile / condition pack is applied. Optional convenience, not a hard dependency. |
| Schema | backend/migrations/archive/pre-v1/V012__shopping_module.sql (+ icon/badge migrations V019–V027) | ~190 + ~6 small migrations | 9 tables: catalog_categories, catalog_subcategories, catalog_items, catalog_item_aliases, catalog_category_translations, catalog_subcategory_translations, catalog_suggestions, shopping_lists, shopping_list_items, tenant_shopping_settings, shopping_patient_catalog_badge_overrides. |
| Seed data | backend/scripts/seed_shopping_catalog.py | 591 lines | Idempotent seeder for the full catalog (categories/subcategories/~300 items/aliases). This is the highest-value, most portable asset in the whole module. |
| Icon assets | frontend/public/catalog-icons/** | 200 files | SVG illustrations per the Phase-7 style guide. |
| Frontend page | frontend/src/pages/Shopping.tsx | 640 lines | Orchestrates lists/items/SSE/catalog for one patient. |
| Frontend components | frontend/src/components/shopping/*.tsx (16 files) | ~130 KB | ActiveItemList, AddItemsSheet, AddCustomProductSheet, CatalogItemTile, CategoryBrowser, IconResolver, NewListModal, PurchasedSection/PurchasedTile, ShoppingListRow/Tabs, ShoppingDashboardWidget, ShoppingShiftWidget, CropImageSheet, CatalogItemEditModal, DeleteCardConfirmDialog. |
| Frontend lib | frontend/src/lib/shoppingSummary.ts, shoppingBadgeOverrides.ts, shoppingListTypeTileSchemes.ts | small | Pure helper functions — trivially portable. |
| Frontend hook | frontend/src/hooks/useShoppingSync.ts | 72 lines | SSE client (ticket + EventSource + reconnect back-off). |
| Admin UI | frontend/src/pages/admin/ShoppingCatalogAdmin.tsx | — | Super-admin catalog moderation screen. |
| Tests | backend/tests/test_shopping.py (784 lines), frontend/src/test/components/Shopping.test.tsx, frontend/src/test/lib/shoppingSummary.test.ts, frontend/e2e/shopping.spec.ts (228 lines) | — | Solid coverage — a real asset when forking/extracting, not just the app code. |
Total: ~9 backend files, ~20 frontend files, 11 DB tables, 1 seed script, 4 test files. This is a genuinely self-contained feature domain — it does not reach into medications, prescriptions, or care shifts for its core loop (the one shift_id column on shopping_list_items is unused dead weight — see §4.4).
3. Dependency map
Section titled “3. Dependency map”4. Dependency-by-dependency breakdown
Section titled “4. Dependency-by-dependency breakdown”4.1 Hard dependencies (must be replaced or reimplemented in a standalone product)
Section titled “4.1 Hard dependencies (must be replaced or reimplemented in a standalone product)”| Dependency | Where | Why it’s coupled | Decoupling effort |
|---|---|---|---|
| Patient concept | Every router path (/api/patients/{patient_id}/shopping/...), require_patient_access, frontend/src/context/PatientContext.tsx, Shopping.tsx (activePatient?.id) | The entire request path is keyed off patient_id, not just tenant_id. A standalone household product has no “patient” — it has a household/tenant. | High — this is the core rewrite. See §5. |
| Auth / tenancy core | backend/auth.py (require_tenant_member, require_carer_role, require_tenant_admin, require_super_admin, RLS app.current_tenant_id GUC), tenants/users tables | Shopping tables FK to tenants(id) and users(id). The whole request pipeline assumes LynCareOS’s user/tenant/membership/RLS model. | High if forking to a new codebase (must rebuild a minimal auth+tenant shell). None if extracted as a package inside this backend (the shell already exists). |
| Subscription gating | backend/billing/tiers.json (shopping is bundled only in Complete, $99+/mo — never sold alone), require_module("shopping") in main.py | REQ-SHOP-* and the module spec (§3) both say shopping should be independently purchasable, but the pricing config never exposes it as an à-la-carte or standalone tier. | Medium — this is a pricing/Stripe config change, not a code rewrite (stripe_seed_tiers reads tiers.json). A standalone product needs its own Stripe account/product line regardless. |
| Calm Care design system | cc-* Tailwind classes, tailwind.config.js, index.css tokens used throughout every shopping component | Purely visual — components are portable as long as the target app ships the same token set (or you fork/rename the tokens). | Low — copy the token subset, not a rewrite. |
| i18next scaffold | frontend/src/lib/i18n.ts, locales/en-AU/common.json (shopping.* namespace) | Every string goes through t(). | Low — the string keys already form a clean, extractable bundle. |
4.2 Soft platform services (generic — reuse, don’t rewrite)
Section titled “4.2 Soft platform services (generic — reuse, don’t rewrite)”These are not shopping-specific. They’re small, well-scoped services other modules also use. If you fork, copy them verbatim; if you extract in-place, no work needed at all.
services/redis_client.py— plain Redis client wrapper. SSE pub/sub channel naming (shopping:{tenant_id}:{patient_id}) is the only shopping-specific bit, and it already degrades to a tenant-wide channel (shopping:{tenant_id}:*) whenpatient_idisNone— i.e. the SSE layer already works in a patient-less world (services/shopping_service.py:44-53).services/images.py— tenant-scoped EXIF-stripped WebP upload service, no shopping-specific logic at all.services/alert_service.py/alert_registry.py— generic consolidated-alert framework;alert_shopping_sync.py/alert_shopping_helpers.pyare thin (~100 lines) adapters on top of it. Fully optional for a standalone product (no alerts needed if there’s no multi-carer coordination story) or trivially reimplementable.
4.3 The catalog — the actual crown jewel
Section titled “4.3 The catalog — the actual crown jewel”catalog_categories / catalog_subcategories / catalog_items / catalog_item_aliases / catalog_category_translations / catalog_subcategory_translations / catalog_suggestions have zero tenant or patient columns — they are platform-global by design (see backend/migrations/archive/pre-v1/V012__shopping_module.sql:1-111, and backend/repositories/admin_shopping.py docstring: “Platform-wide product catalog… Excluded from clinical tenant_id isolation scans”). Combined with backend/scripts/seed_shopping_catalog.py (591 lines) and 200 SVG icons, this is a fully portable, tenant-agnostic dataset — the single biggest reason a fork is cheap on the data side and expensive only on the request-routing side.
4.4 Dead/vestigial coupling (ignore or delete)
Section titled “4.4 Dead/vestigial coupling (ignore or delete)”shopping_list_items.shift_id— plainINTEGER, no FK constraint, not read or written anywhere except being selected in bulk byfind_recurring_to_reset(repositories/shopping.py:1153). It’s a leftover placeholder for the “not started” shift widget integration (roadmap doc 04 §9: “Shopping widget on shift/calendar view — Not started”). Safe to drop in a standalone schema.care_start_bootstrap.ensure_pack_shopping_lists— a convenience that seeds themed lists when a Care Profile is applied. Callsrepositories.shopping.create_list/create_itemdirectly; nice-to-have, not required for shopping to function. Drop it for a standalone product (no “Care Profiles” concept there).standalone_modecolumn ontenant_shopping_settings— exists in schema and inshopping_service.get_settings()’s default dict, but no router or service code ever branches on it. It’s aspirational scaffolding from the original spec that was never wired up (see §5).
5. The gap: “Mode B” is documented, not built
Section titled “5. The gap: “Mode B” is documented, not built”06-SHOPPING-MODULE.md §2 explicitly describes two tenanting modes:
- Mode A (Integrated) — lists are patient-scoped. This is 100% of what’s implemented.
- Mode B (Standalone) — lists are tenant-scoped,
patient_idisNULLon every row, URLs move from/api/patients/{id}/shopping/...to/api/shopping/...at the tenant level, and “no other code changes are required.”
That last claim is only true for the repository layer (every repositories/shopping.py function already accepts patient_id: int | None and branches correctly — e.g. list_lists, get_list, create_item). It is not true for:
routers/shopping.py— every route haspatient_id: intas a required path parameter and depends onrequire_patient_access, which 403s without a valid patient row.frontend/src/pages/Shopping.tsx— hard-gates the entire page behindactivePatient?.id(if (!patientId) { return <...select a patient...> }), and everyapi.shopping.*call infrontend/src/lib/api.tstakes a mandatorypatientId.frontend/src/context/PatientContext.tsx— assumes every tenant member is choosing among clinical patients, not managing their own household list.
This is the real blocker, not tenant isolation or data model. The good news: because the repository layer was built patient-agnostic from day one, finishing Mode B is a router + service + frontend routing change, not a schema migration.
6. Two extraction strategies
Section titled “6. Two extraction strategies”Option A — Fork into a new standalone codebase
Section titled “Option A — Fork into a new standalone codebase”Copy the 9 backend files + schema + seed data + 20 frontend files into a new repo. Strip patient_id everywhere, build a minimal auth/tenant/user shell (or reuse a generic starter), stand up its own Postgres, its own Stripe product, its own deploy pipeline.
- Pros: Fastest to a shippable v1 if you want it live in weeks and don’t mind a from-scratch billing/auth stack; total independence from LynCareOS release cadence; can strip anything LynCareOS-specific (audit trail rigor, PHI handling, RLS) that a grocery-list SaaS doesn’t need.
- Cons: You now own two copies of the SQL, the SSE logic, the catalog seed data, and the icon set. Every future catalog improvement (new items, new locales, new icons) has to be back-ported by hand or you fork the data too and it drifts. You also rebuild — from nothing — auth, tenancy, billing, RLS, session/2FA, GDPR/PHI-adjacent plumbing that this repo already has hardened over multiple releases.
- Effort: Backend shell (auth+tenant+billing+DB) 2–4 weeks; port shopping module 1 week; new frontend shell (routing/auth/design system) 1–2 weeks. ~4–7 weeks to parity with what exists today, before any new standalone-specific polish.
Option B — Finish Mode B, extract as an internal package (recommended)
Section titled “Option B — Finish Mode B, extract as an internal package (recommended)”- Finish Mode B in-place (still inside LynCareOS): add tenant-level routes (
/api/shopping/listsetc.) alongside the existing patient-scoped ones, branchrequire_tenant_membervsrequire_patient_accessontenant_shopping_settings.standalone_mode, and give the frontend a “household mode” that doesn’t requirePatientContext. This is additive — it does not touch Mode A’s existing behaviour or tests. - Extract into
packages/shopping-*the same waypackages/clinical-anatomywas extracted (ownpackage.json,tsconfig.json,README.md, versioned independently): catalog data + icons aspackages/shopping-catalog, UI components aspackages/shopping-ui(importable by any React shell that ships the Calm Care token subset), backend module unchanged in place (it’s already isolated behind Router→Service→Repository — no code motion needed there, just a clean public contract). - Stand up a thin “Shopping” shell app — its own minimal FastAPI app (or a slimmed profile of the existing
main.py) that mounts the samerouters/shopping.py/admin_shopping.py, points at its own Postgres (or a schema-isolated slice of the same one), and has its own Stripe product line for direct sale. Because tenancy is already enforced bytenant_ideverywhere and the catalog tables have no tenant scoping at all, this shell can literally point at the same database in early days (cheapest to validate demand) and be split to its own DB later without a data model change. - Pricing: update
backend/billing/tiers.jsonto also exposeshoppingas an à-la-carte add-on for existing LynCareOS tenants (closes the REQ-SHOP gap from doc 31 §2.39 at the same time), and mint a separate Stripe product for the standalone shell.
- Pros: One source of truth for the catalog, the SQL, and the SSE logic — LynCareOS and the new product both improve when either improves. Reuses a hardened auth/tenant/RLS/billing stack instead of rebuilding one. Directly resolves the documented-but-unbuilt Mode B gap, which is useful to LynCareOS regardless of the standalone decision (e.g. a future household-only pricing tier).
- Cons: Slower to first sale — Mode B has to be finished before the standalone shell is worth building. Two apps sharing one backend means a shopping-only outage/bug is a LynCareOS outage too until/unless you split databases.
- Effort: Mode B (router + service branch + frontend household mode) 1–2 weeks. Package extraction (mechanical — move files, add package.json/tsconfig, no logic changes) 2–3 days. Thin shell app (new FastAPI app mounting existing routers + new minimal frontend shell) 1–2 weeks. ~3–5 weeks total, and LynCareOS itself gains the Mode B capability as a side effect.
7. Recommended phased plan (Option B)
Section titled “7. Recommended phased plan (Option B)”| Phase | Work | Files touched | Effort |
|---|---|---|---|
| 1 | Add tenant_id-only shopping routes (no patient_id) to routers/shopping.py, gated on tenant_shopping_settings.standalone_mode | routers/shopping.py, services/shopping_service.py (already patient-agnostic) | 3–4 days |
| 2 | Frontend “household mode”: a Shopping.tsx variant (or a prop/flag) that skips PatientContext and calls the new tenant-level endpoints | pages/Shopping.tsx, lib/api.ts (api.shopping.* optional patientId) | 3–4 days |
| 3 | Tests for Mode B (mirror test_shopping.py patient-scoped cases with tenant-scoped equivalents) | backend/tests/test_shopping.py, frontend/e2e/shopping.spec.ts | 2–3 days |
| 4 | Extract packages/shopping-catalog (seed data + icons) and packages/shopping-ui (components + lib helpers), mechanical move + new package.json/tsconfig.json/README.md per packages/clinical-anatomy precedent | new packages/shopping-* dirs | 2–3 days |
| 5 | Stand up thin shell app (new FastAPI entry mounting shopping/admin_shopping routers + a minimal React shell) pointed at the same Postgres initially | new app scaffold (outside this repo’s scope until you decide on a name/domain) | 1–2 weeks |
| 6 | à-la-carte pricing: add shopping as an add-on module in tiers.json for existing tenants; separate Stripe product for the standalone shell | backend/billing/tiers.json, Stripe dashboard/stripe_seed_tiers | 2–3 days |
| 7 | Decide on data split (shared DB vs dedicated DB for the standalone product) once there’s real usage/revenue signal | infra decision, no code change day 1 | — |
Total before first paid standalone user: roughly 3–5 weeks, most of it Phase 1–2 (finishing what the spec already promised) plus Phase 5 (a genuinely new, thin app).
8. Open questions this analysis surfaced
Section titled “8. Open questions this analysis surfaced”- Should Mode B ship for existing LynCareOS households too (an à-la-carte “just groceries” tier), or only as internal plumbing for the spin-off?
- Does the standalone product need multi-carer real-time sync (the SSE/Redis machinery) on day one, or is a single-household MVP acceptable without it initially?
- Catalog IP: is the 300-item/200-icon catalog something you’re comfortable sharing verbatim between LynCareOS and the new product, or does the standalone product need its own diverged catalog/branding (e.g. no “pharmacy/medical” list type if it’s a pure grocery-coordination app)?
- Same Postgres instance to start (cheap, fast, some blast-radius risk) vs. a dedicated database from day one (slower, cleaner, costs more before you have revenue)?