feature plus ux rearrangements

This commit is contained in:
JCEEE
2026-08-22 19:49:46 +01:00
parent f14f4e2ac1
commit 42b9a27ce6
44 changed files with 2020 additions and 538 deletions
+97 -55
View File
@@ -12,23 +12,22 @@ Multi-tenant chore tracking SaaS. Families ("fams") are isolated tenant groups.
| Component | Role | Deploy | Port |
|---|---|---|---|
| SvelteKit | SSR frontend, all UI + Stripe server routes | Coolify Docker (nginx) | :2080 internal, :3001 external |
| Hono proxy | data layer (`/api/*`); CRON | Same container, proxied via nginx `/api/*` | :3456 internal |
| SvelteKit | SSR frontend + all services + Stripe server routes (`/api/*`) | Coolify Docker (nginx) | :2080 internal, :3001 external |
| PocketBase | DB, auth, realtime, storage, Admin UI | Coolify service (pb.chores.app.com) | :8090 |
| Stripe | subscriptions (in SvelteKit, NOT Hono) | — | — |
| Stripe | subscriptions (SvelteKit server routes) | — | — |
### Deployment Topology
```
chores.app.com ────┬──► nginx (:3001)
│ ├── /* ──► SvelteKit (:2080)
│ └── /api/* ──► Hono proxy (:3456)
│ └── /api/* ──► SvelteKit (:2080)
│
pb.chores.app.com ──► PocketBase (:8090)
│ Admin UI at /_
│ Volume: /pb_data (persistence + backups)
│
stripe.com ─────────► SvelteKit /account/webhook
stripe.com ─────────► SvelteKit /api/webhooks/stripe
```
---
@@ -60,7 +59,9 @@ Every tenant-scoped collection has `famId` and enforces `famId = @request.auth.f
- `users` — auth collection; famId, role (`parent`|`child`), username (`{famSlug}:{handle}`), name, color, email (admin only)
- `otp` — famId, userId, otp, updatedAt (OTP gate for child join; display colour on `users.color`)
- `fams` — name, slug, stripeCustomerId, featureFlags
- `accesscodes` — value (unique), name, duration, expiry, active, createdAt (superuser-only; platform access codes)
- `platform` — label (`global` singleton), flags (json) — platform feature flags; public read (empty list/view rules), superuser-only writes. Loaded on every page via root `+layout.server.ts` as `page.data.platformFlags`; toggled from the `/admin` Platform Flags card (`debug` gates dev-only CTAs like settings "Revoke code"). Replaces the deprecated per-fam `fams.featureFlags`.
- `fams` — name, slug, stripeCustomerId, paymentMode (`none`|`code`|`sub`|`canceled`), active, accessCodeId, accessCodeEnteredAt
- `chore_templates` — famId, name, defaultValue, defaultFrequency
- `assigned_chores` — famId, userId, templateId, frequency, value
- `completions` — famId, userId, assignedChoreId, date
@@ -69,7 +70,7 @@ Every tenant-scoped collection has `famId` and enforces `famId = @request.auth.f
- `monthly_bonuses` — famId, month, prizeType, prizeValue, winnerUserId
- `settings` — famId, pointsThreshold, weeklyBonus, webhookUrl
> **Schema/migrations:** `shared/pb/schema.ts` (`SCHEMA_PLAN`) is the single source of truth for base collections. `frontend/src/lib/server/migrate.ts` bootstraps a fresh/wiped PB (idempotent). The native `users` auth fields/rules + superuser-only `otp` are applied in `migrate.ts` (`ensureUsers`/`ensureOtp`). Data is disposable — schema change = update `SCHEMA_PLAN` + wipe PB + reboot.
> **Schema/migrations:** `shared/pb/schema.ts` (`SCHEMA_PLAN`) is the single source of truth for base collections. `frontend/src/lib/server/migrate.ts` bootstraps a fresh/wiped PB (idempotent). The native `users` auth fields/rules + the superuser-only `otp`/`accesscodes` and public-read `platform` collections are applied in `migrate.ts` (`ensureUsers`/`ensureOtp`/`ensureAccessCodes`/`ensurePlatform`); `ensureFamFields()` hardens existing installs with newer `fams` fields. Data is disposable — schema change = update `SCHEMA_PLAN` + wipe PB + reboot.
---
@@ -81,8 +82,8 @@ Every tenant-scoped collection has `famId` and enforces `famId = @request.auth.f
/ Landing page (SaaS marketing)
/admin Platform super-admin stats dashboard
/login · /logout Parent login / logout
/signup Parent + family signup
/{famSlug}/join/{username} Member invite (OTP join), auto-fills from ?code=
/signup Parent + family signup (wizard: fam → child → code → plan)
/{fam}/join/{username} Member invite (OTP join), auto-fills from ?code=
/{fam} Fam dashboard
/{fam}/{username} Parent → admin overview, Child → member kanban
/{fam}/{username}/chores Chore templates & assignment grid
@@ -90,10 +91,10 @@ Every tenant-scoped collection has `famId` and enforces `famId = @request.auth.f
/{fam}/{username}/bonuses Bonus configs & evaluation
/{fam}/{username}/preferences User preferences
/{fam}/{username}/settings Family admin settings (parent only) — Stripe connect/manage + pause
/account Account/billing — payment setup & subscription management
/subscriptions 3-tier plan page (trial | monthly | yearly), access via settings
/account/webhook Stripe webhook handler (server route)
/api/* Hono proxy (data layer; CRON not implemented)
/settings (Billing group) Subscription status, change plan, open billing portal
/pricing 3-tier public plan page (trial | monthly | yearly), entry via settings or logged-out
/api/webhooks/stripe Stripe webhook handler (server route)
/api/* SvelteKit API endpoints (data layer; CRON not implemented)
```
---
@@ -107,30 +108,36 @@ Every tenant-scoped collection has `famId` and enforces `famId = @request.auth.f
### 5.2 Writes
- **Chore toggle:** Browser → Hono proxy → PB (member auth via `Authorization: Bearer <pb_token>`).
- **Admin CRUD:** Form actions / `hono.admin.*` → Hono proxy → PB (admin JWT via `sessionHeaders`).
- **Member updates:** Browser → Hono proxy → PB (`Bearer <pb_token>`).
- **Reward creation:** after completion toggle, Hono proxy creates reward if threshold met.
- **Chore toggle:** Browser → SvelteKit `/api/completions/toggle` → PB (session cookie auth).
- **Admin CRUD:** Form actions / `/api/admin/*` endpoints → PB via services; PB collection rules are the security boundary.
- **Member updates:** Browser → SvelteKit `/api/*` routes → PB.
- **Reward creation:** after completion toggle, service layer creates reward if threshold met.
- **Weekly settlement:** NOT via CRON — manual `complete-week` action or `simulateEow` preview in settings. `/api/weekly-cron` (Coolify) not implemented.
- **Stripe:** SvelteKit server routes `/account` + `/account/webhook` (frontend app, NOT Hono).
- **Stripe:** SvelteKit server routes `/pricing` + settings Billing actions + `/api/webhooks/stripe`.
- **WhatsApp:** not implemented.
### 5.3 Stripe Subscription (embedded Checkout)
```
Parent picks a tier on /subscriptions (trial | monthly | yearly)
→ SvelteKit server action (subscriptions) creates Embedded Checkout Session
createEmbeddedCheckoutSession() → ui_mode: "embedded" → client_secret
→ returns { clientSecret } to the browser
→ @stripe/stripe-js createEmbeddedCheckoutPage({ clientSecret }) mounts in-page
→ Parent completes payment inside the embedded Stripe page
→ Stripe sends checkout.session.completed → SvelteKit /account/webhook
handleStripeEvent() → pbAdmin.update fams.stripeCustomerId + active = true
→ Subsequent customer.subscription.* webhooks keep fams.active in sync
→ Parent returns to /account?checkout=return
PUBLIC PRICING SIGNUP WIZARD AFTER
───────────── ───────────── ─────
/pricing ── logged out ──► /signup?plan=X
└─ logged in ──► embedded checkout (existing behavior)
1. fam create family + parent
2. child add child / skip
3. code "Have an access code?"
├─ apply valid ──► 5. done (fam active)
└─ skip ─────────► 4. plan
4. plan PricingPlans component
├─ ?plan=X pre-highlights that tier
├─ pick tier ──► embedded checkout mounts INLINE
└─ trial tier hidden (codes live at step 3)
5. done "Go to dashboard"
webhook sets paymentMode=sub → overlay lifts
```
Pause/stop via Stripe Customer Portal (from `/account`) or the pause toggle (writes `fams.active` directly).
Webhook events (`/api/webhooks/stripe`) update `fams.stripeCustomerId`, `fams.active`, `fams.paymentMode` from subscription lifecycle.
### 5.3.1 Payments architecture
@@ -138,26 +145,27 @@ Pause/stop via Stripe Customer Portal (from `/account`) or the pause toggle (wri
┌────────────────────────────────────────── SVELTEKIT APP ──────────────────────────────────────────┐
│ │
│ Browser │
│ ┌──────────────────────────────┐ POST ?/checkout ┌─────────────────────────────────────────┐ │
│ │ /subscriptions (+page.svelte)│ ───────────────────► │ subscriptions/+page.server.ts (action) │ │
│ │ • tier cards │ │ • resolves famId + parent email (PB) │ │
│ │ • createEmbeddedCheckoutPage│ ◄─── clientSecret ─── │ • createEmbeddedCheckoutSession() │ │
│ │ • mounts embedded Stripe UI │ └───────────────┬─────────────────────────┘ │
│ ┌──────────────────────────────┐ POST ?/choose ┌─────────────────────────────────────────┐ │
│ │ /pricing (+page.svelte) │ ───────────────────► │ pricing/+page.server.ts (action) │ │
│ │ • PricingPlans component │ │ • logged-out: redirect /signup?plan=X │ │
│ │ • createEmbeddedCheckoutPage │ ◄─── clientSecret ─── │ • logged-in: createEmbeddedCheckout... │ │
│ │ • mounts embedded Stripe UI │ └───────────────┬─────────────────────────┘ │
│ └──────────────┬───────────────┘ │ stripe SDK (secret) │
│ │ createEmbeddedCheckoutPage(clientSecret) ▼ │
│ ▼ ┌─────────────────────────────┐ │
│ ┌──────────────────────────────┐ │ STRIPE API │ │
│ │ Embedded Checkout (Stripe │ card + pay │ checkout.sessions.create │ │
│ │ hosted iframe, in-page) │ ───────────────────► │ (ui_mode: embedded) │ │
│ │ hosted iframe, in-page) │ ───────────────────► │ (ui_mode: embedded_page) │ │
│ └──────────────────────────────┘ └──────────────┬──────────────┘ │
│ │ webhook events │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────────────────────────────────────────┐ │
│ │ /account/webhook (+server.ts) │ │
│ │ /api/webhooks/stripe (+server.ts) │ │
│ │ • verify stripe-signature (CLI secret in dev, dashboard in prod) │ │
│ │ • handleStripeEvent() → stripe-events.ts │ │
│ │ └ checkout.session.completed → fams.stripeCustomerId + active = true │ │
│ │ └ customer.subscription.* → fams.active (sync by customer id) │ │
│ │ └ checkout.session.completed → fams.stripeCustomerId + active + paymentMode='sub' │ │
│ │ └ customer.subscription.* → fams.active + paymentMode (sync by customer id) │ │
│ │ └ customer.subscription.deleted → active=false + paymentMode='canceled' │ │
│ └──────────────────────────────────────────────────────┬─────────────────────────────────────┘ │
│ │ pbAdmin (superuser) │
└─────────────────────────────────────────────────────────┼─────────────────────────────────────────┘
@@ -166,25 +174,60 @@ Pause/stop via Stripe Customer Portal (from `/account`) or the pause toggle (wri
│ POCKETBASE │
│ fams.stripeCustomerId │
│ fams.active (bool) │
│ fams.paymentMode │
└────────────────────┘
SIGNUP WIZARD (inline checkout at step 4):
/signup?plan=X
1. fam create family + parent (no code field)
2. child add child / skip
3. code "Have an access code?" → apply or skip
4. plan PricingPlans component (hideTrial), selecting a plan
→ ?/choose action → createEmbeddedCheckoutSession → mount embedded inline
5. done "Go to dashboard" — webhook flips paymentMode=sub, overlay lifts
Management:
/account (+page.server.ts)
• billing action → createBillingPortalSession(customerId) → Stripe Customer Portal
(update card, cancel / reactivate subscription)
• togglePause action → pbAdmin.update fams.active (hard pause, independent of Stripe)
Settings → Billing group (+page.server.ts ?/billingPortal)
• createBillingPortalSession(customerId) → Stripe Customer Portal
(update card, cancel / reactivate subscription; returns to /{fam}?checkout=return)
Gating derives from fams.paymentMode alone (none = gated). No local pause flag.
Dev-only:
stripe CLI: stripe listen -e ... --forward-to http://127.0.0.1:2080/account/webhook
(sets STRIPE_CLI_WEBHOOK_SECRET for local signature verification)
pnpm stripe:listen (root script)
= stripe listen -e customer.subscription.updated,customer.subscription.deleted,checkout.session.completed
--forward-to http://127.0.0.1:2080/api/webhooks/stripe
(sets STRIPE_CLI_WEBHOOK_SECRET for local signature verification)
Embedded Checkout needs a secure context (HTTPS or localhost). Over Tailscale/LAN HTTP the
checkout iframe hangs silently — port-forward instead: ssh -L 2080:localhost:2080
```
**Key decisions**
- **Payments live in SvelteKit, not Hono** — the app already owns SSR + server actions; Hono stays a pure data layer. Stripe secret never reaches the client.
- **`fams.active`** is the single app-level gate: webhooks (subscription lifecycle) and the pause toggle both write it. It disables interactions + payments when `false`.
- **Embedded Checkout** (in-page, no redirect) via `createEmbeddedCheckoutPage` — needs a same-origin `return_url`; subscriptions require a `customer` (created with `customer_creation: 'always'` + `customer_email` if the fam has none yet).
- **Trial** is app-side: a code maps to `trial_period_days` on the subscription; the trial Stripe price is a `$0` plan. Real-world codes should move to a PB collection.
- **Webhook secrets** — `STRIPE_CLI_WEBHOOK_SECRET` (dev) overrides `STRIPE_WEBHOOK_SECRET` (prod/dashboard); `verifyStripeEvent` picks the CLI one when set. Dev testing uses the Stripe CLI (`stripe listen --forward-to http://127.0.0.1:2080/account/webhook`) which forwards real signed events; a real checkout carries the `famId` and drives the DB write end-to-end.
- **Payments live in SvelteKit server routes** — the app owns SSR + server actions end-to-end. Stripe secret never reaches the client.
- **`fams.paymentMode` + `fams.active`** gate the platform (see 5.3.2). Webhooks write `paymentMode`; `ensureFamAccess()` recomputes and persists `active` on every `[fam]` layout load.
- **Embedded Checkout** (in-page, no redirect) via `createEmbeddedCheckoutPage` with `ui_mode: 'embedded_page'` (`'embedded'` is deprecated) — needs a same-origin `return_url`. No `customer_creation` (subscription mode only; Stripe auto-creates the customer from `customer_email`).
- **Access codes are a real PB collection** (`accesscodes`, superuser-only) — entered at signup or via settings; replaces the earlier app-side trial-code idea.
- **Webhook secrets** — `STRIPE_CLI_WEBHOOK_SECRET` (dev) overrides `STRIPE_WEBHOOK_SECRET` (prod/dashboard); `verifyStripeEvent` picks the CLI one when set. Dev testing uses the Stripe CLI (`pnpm stripe:listen`) which forwards real signed events; a real checkout carries the `famId` and drives the DB write end-to-end.
### 5.3.2 Access gating (`fams.paymentMode` / `accesscodes`)
```
computeFamAccess(fam, code?) → { disabled, reason } lib/server/access.ts
none → disabled ("no_access") fresh signup, no code/sub
code → valid while accesscodes.active && !expired && !durationExhausted
(duration/expiry 0 = continuous/never; months measured from
fam.accessCodeEnteredAt / code.createdAt)
sub → follows webhook-maintained fams.active
canceled → disabled ("canceled")
ensureFamAccess(famId): reads fam+code, persists drifted fams.active, returns {fam, access}
applyAccessCode(famId, value): validates + sets paymentMode='code' + entry stamp
```
- Exposed to all fam pages as `data.famAccess` from `[fam]/+layout.server.ts`.
- Disabled UX: layout blurs page content behind an overlay card + admin TopNav announcement (`/settings` is exempt so admins can apply a code / manage billing); member kanban renders empty locked columns and `toggle()` early-returns (frontend-only by decision).
- Entry points: optional code field at signup, Access card in settings (`?/applyCode`). Webhooks flip `paymentMode` to `sub`/`canceled`.
- Debug revoke: with the platform `debug` flag ON, settings shows a "Revoke code" CTA (`?/revokeCode`) that clears the applied code (back to `none`/gated). Server-side flag check is the boundary.
- Seeded dev code: `dev123` (developer, duration 0, expiry 0).
### 5.4 UI reactivity
@@ -202,11 +245,10 @@ Dev-only:
/shared/pb/schema.ts SCHEMA_PLAN — source of truth for base collections
/frontend SvelteKit app (:2080)
/src/env.ts declareEnvVars — client/server env
/src/lib/server pb-admin, migrate.ts, services, hono.ts (sessionHeaders)
/src/lib/server pocketbase.ts (pbAdmin), migrate.ts, access.ts, platform.ts, services/
/src/lib/client api.ts (memberApi), stores (famStore)
/src/lib/components UI components (re-exported from index.ts)
/src/routes SvelteKit file-based routing (incl /account, /subscriptions)
/proxy Hono proxy (:3456)
/src/routes SvelteKit file-based routing (incl /pricing, /signup wizard, /api/webhooks/stripe)
/docker Dockerfile (prod multi-stage + nginx), Dockerfile.dev (PB)
/config.ts dev/build-time shared config (ports)
/MEMORY.md decisions log
@@ -234,8 +276,8 @@ Values come from root `.env` (symlinked at `frontend/.env -> ../.env`). `.env.ex
## 8. Key Conventions
- **`famId` on every query** — PB auth rules enforce `famId = @request.auth.famId`; superuser bypasses.
- **Member → Proxy (server/browser):** `memberApi.*` in `$lib/client/api.ts`; `BASE_URL` resolves to Hono port on server, empty in browser (Vite proxies `/api/*`).
- **Admin → Proxy:** `hono.admin.*` in `$lib/server/hono.ts` — `sessionHeaders(event)` (server-only, requires `RequestEvent`).
- **Server data access:** `servicesFor(event)` / `createServices(pb)` in `$lib/server/services/`; superuser ops via `pbAdmin` facade.
- **Browser data access:** same-origin fetch to `/api/*` SvelteKit endpoints; httpOnly `pb_token` cookie is the auth.
- **Child passwords derived** — `MEMBER_SECRET + famSlug + username`; join gate is a transient OTP. Never log raw tokens/secrets.
- **`$page`** — from `$app/state` (not `$app/stores`); no `$` prefix.
- **Dates** — user-facing via `formatDDMMYY()` (compact `040826`); human-readable due dates use `formatShortDate()`. Never render raw `YYYY-MM-DD`.
@@ -248,5 +290,5 @@ Values come from root `.env` (symlinked at `frontend/.env -> ../.env`). `.env.ex
## 9. Open / Deferred
- **WhatsApp notifications** — `NotificationService` plugin for the weekly CRON handler. Deferred.
- **Stripe payments** — flow not yet implemented. Only `fams.stripeCustomerId` + `settings.webhookUrl` exist. Building in SvelteKit `/account` + `/account/webhook`. Trial via codes (app-side validation + `trial_period_days`) — TBD.
- **Stripe payments** — implemented in SvelteKit (`/pricing` public picker + inline signup checkout, settings Billing group with billing portal, `/api/webhooks/stripe` → `stripe-events.ts`; `?checkout=return` lands on the fam dashboard with a welcome notice). Remaining: platform-admin UI for managing `accesscodes`, prod webhook secret wiring, optional Stripe-level pause (see TODO.md).
- **Weekly CRON** (`/api/weekly-cron`, Coolify) — not implemented; settlement is manual via `complete-week`/`simulateEow`.