add shared login pin mechansim
This commit is contained in:
@@ -19,14 +19,14 @@
|
|||||||
|
|
||||||
## Auth
|
## Auth
|
||||||
|
|
||||||
| Role | Auth | Session | Record in |
|
| Role | Auth | Session | Record in |
|
||||||
| -------------- | --------------------------------------------- | -------------------------- | ------------------------- |
|
| -------------- | ----------------------------------------------- | ------------------------------------------------ | ----------------------- |
|
||||||
| Admin (parent) | PB email+pass | 24hr JWT `pb_token` cookie | `users` (role `parent`) |
|
| Admin (parent) | PB email+pass | 24hr JWT `pb_token` cookie | `users` (role `parent`) |
|
||||||
| Member (child) | Invite OTP + server-derived password | httpOnly `pb_token` cookie | `users` (role `child`) |
|
| Member (child) | Invite OTP + server-derived password | Shared-device: `pb_token_<userId>` + `pb_active` | `users` (role `child`) |
|
||||||
| Superuser | PB `_superusers` (server-side only, `pb-admin`) | — | — |
|
| Superuser | PB `_superusers` (server-side only, `pb-admin`) | — | — |
|
||||||
|
|
||||||
- **Admins** (parents) are `users` records (role `parent`). They authenticate via email/password login, get an httpOnly `pb_token` cookie with `{ id, name, username, role: "parent", famId, color }`.
|
- **Admins** (parents) are `users` records (role `parent`). They authenticate via email/password login, get an httpOnly `pb_token` cookie with `{ id, name, username, role: "parent", famId, color }`.
|
||||||
- **Members** (children) are `users` records (role `child`); PB `username` = `{famSlug}:{handle}` (globally-unique auth identity; `handle` = whitespace-free lowercase name), URL segment = `handleOf(username)`, `name` = display name. Their PB password is **derived** server-side (`MEMBER_SECRET + famSlug + handle`); access is gated by a 20-min OTP in `otp`, then `authWithPassword`. They get the same httpOnly `pb_token` cookie. There is **no `members` collection**.
|
- **Members** (children) are `users` records (role `child`); PB `username` = `{famSlug}:{handle}` (globally-unique auth identity; `handle` = whitespace-free lowercase name), URL segment = `handleOf(username)`, `name` = display name. Their PB password is **derived** server-side (`MEMBER_SECRET + famSlug + handle`); access is gated by a 20-min OTP in `otp`, then `authWithPassword`. **Shared-computer sessions:** children keep ONE httpOnly cookie per account (`pb_token_<userId>`, set at join) + a `pb_active` cookie naming the current session; a 3-digit PIN _selects_ among those device sessions (see `shared-device.md`) — it is NOT a login and mints nothing on a fresh device. Parents stay on the single `pb_token`. Resolution order in hooks: `pb_active` → `pb_token`. There is **no `members` collection**.
|
||||||
- **Platform superuser** (`_superusers`) used only server-side by `pb-admin.ts` for cross-family queries (e.g. `/admin` stats dashboard) and OTP/signup writes. Not an app role.
|
- **Platform superuser** (`_superusers`) used only server-side by `pb-admin.ts` for cross-family queries (e.g. `/admin` stats dashboard) and OTP/signup writes. Not an app role.
|
||||||
- The layout (`[fam]/+layout.server.ts`) derives `isParent` and `role` centrally from the session — child pages use `page.data.isParent` or `page.data.role` from `$app/state`.
|
- The layout (`[fam]/+layout.server.ts`) derives `isParent` and `role` centrally from the session — child pages use `page.data.isParent` or `page.data.role` from `$app/state`.
|
||||||
- Because `pb_token` is httpOnly, the browser PB SDK is seeded from `page.data.pbToken` via `initPb(token)` in the layout `onMount` (not `document.cookie`).
|
- Because `pb_token` is httpOnly, the browser PB SDK is seeded from `page.data.pbToken` via `initPb(token)` in the layout `onMount` (not `document.cookie`).
|
||||||
@@ -35,6 +35,7 @@
|
|||||||
|
|
||||||
- `users` — auth collection; famId, role (`parent`|`child`), username (`{famSlug}:{handle}`), name, color, email (admin only)
|
- `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 lives on `users.color`)
|
- `otp` — famId, userId, otp, updatedAt (OTP gate for child join; display colour lives on `users.color`)
|
||||||
|
- `pins` — famId, userId, pin (superuser-only shared-device PINs, plaintext so parents can read them out; all access via server endpoints)
|
||||||
- `accesscodes` — value (unique), name, duration, expiry, active, createdAt (superuser-only; platform access codes)
|
- `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`; toggle via `/admin` Platform Flags card. The `debug` flag gates dev-only CTAs (e.g. settings "Revoke code").
|
- `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`; toggle via `/admin` Platform Flags card. The `debug` flag gates dev-only CTAs (e.g. settings "Revoke code").
|
||||||
- `fams` — name, slug, stripeCustomerId, paymentMode (`none|code|sub|canceled`), active, accessCodeId, accessCodeEnteredAt
|
- `fams` — name, slug, stripeCustomerId, paymentMode (`none|code|sub|canceled`), active, accessCodeId, accessCodeEnteredAt
|
||||||
@@ -46,7 +47,7 @@
|
|||||||
- `monthly_bonuses` — famId, month, prizeType, prizeValue, winnerUserId
|
- `monthly_bonuses` — famId, month, prizeType, prizeValue, winnerUserId
|
||||||
- `settings` — famId, pointsThreshold, weeklyBonus, webhookUrl
|
- `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` only **bootstraps** a fresh/wiped PB (idempotent, skips if `fams` exists) — it has no incremental history. The native `users` auth fields/rules and the superuser-only `otp` collection are applied in `migrate.ts` (`ensureUsers`/`ensureOtp`), not `SCHEMA_PLAN`. Data is disposable (app not live), so a 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` only **bootstraps** a fresh/wiped PB (idempotent, skips if `fams` exists) — it has no incremental history. The native `users` auth fields/rules and the superuser-only `otp`/`pins` collections are applied in `migrate.ts` (`ensureUsers`/`ensureOtp`/`ensurePins`), not `SCHEMA_PLAN`. Data is disposable (app not live), so a schema change = update `SCHEMA_PLAN` + wipe PB + reboot.
|
||||||
|
|
||||||
## Routes
|
## Routes
|
||||||
|
|
||||||
@@ -56,6 +57,7 @@
|
|||||||
/login · /logout Parent email/password login / logout
|
/login · /logout Parent email/password login / logout
|
||||||
/signup Parent + family signup (wizard: fam → child → code → plan)
|
/signup Parent + family signup (wizard: fam → child → code → plan)
|
||||||
/{fam}/join/{username} Member invite (OTP join), auto-fills from ?code=
|
/{fam}/join/{username} Member invite (OTP join), auto-fills from ?code=
|
||||||
|
/{fam}/switch Shared-device profile picker (standalone landing when child sessions exist but none active)
|
||||||
/{fam} Fam dashboard
|
/{fam} Fam dashboard
|
||||||
/{fam}/{username} Parent → admin overview, Child → member kanban (role from session)
|
/{fam}/{username} Parent → admin overview, Child → member kanban (role from session)
|
||||||
/{fam}/{username}/chores Chore templates & assignment grid
|
/{fam}/{username}/chores Chore templates & assignment grid
|
||||||
@@ -157,10 +159,10 @@ let configs = $derived(
|
|||||||
|
|
||||||
Two patterns based on who's acting:
|
Two patterns based on who's acting:
|
||||||
|
|
||||||
| Pattern | Who | Frequency | Sensitivity | Optimistic? | Auth |
|
| Pattern | Who | Frequency | Sensitivity | Optimistic? | Auth |
|
||||||
| ---------------------------- | ------ | -------------------- | ------------------------ | --------------------------------------------- | ------------------------- |
|
| ---------------------------- | ------ | -------------------- | ------------------------ | --------------------------------------------- | ---------------------------------- |
|
||||||
| Direct `fetch` + `memberApi` | Member | High (chore toggles) | None | Yes (instant UI, reconcile on response) | `Authorization: Bearer <pb_token>` |
|
| Direct `fetch` + `memberApi` | Member | High (chore toggles) | None | Yes (instant UI, reconcile on response) | `Authorization: Bearer <pb_token>` |
|
||||||
| Form action | Admin | Low (CRUD) | High (settings, members) | No — form is server-side, wait for round trip | httpOnly `pb_token` cookie |
|
| Form action | Admin | Low (CRUD) | High (settings, members) | No — form is server-side, wait for round trip | httpOnly `pb_token` cookie |
|
||||||
|
|
||||||
**Member direct fetch** — optimistic UI via local state mutation, reconciled on response:
|
**Member direct fetch** — optimistic UI via local state mutation, reconciled on response:
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
## UI Component Architecture (Jul 2026)
|
## UI Component Architecture (Jul 2026)
|
||||||
|
|
||||||
### Layout Hierarchy
|
### Layout Hierarchy
|
||||||
|
|
||||||
```
|
```
|
||||||
+layout.svelte ← global styles, meta, favicon
|
+layout.svelte ← global styles, meta, favicon
|
||||||
├── /login, /signup, /join/* ← auth pages (no shell)
|
├── /login, /signup, /join/* ← auth pages (no shell)
|
||||||
@@ -34,6 +35,7 @@
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Sidebar (collapsible to mini-mode)
|
### Sidebar (collapsible to mini-mode)
|
||||||
|
|
||||||
- Header: app name (FamDone)
|
- Header: app name (FamDone)
|
||||||
- Admin CTAs: Dashboard, Chores, Rewards (badge count), Bonuses
|
- Admin CTAs: Dashboard, Chores, Rewards (badge count), Bonuses
|
||||||
- Member CTAs: Dashboard, Preferences
|
- Member CTAs: Dashboard, Preferences
|
||||||
@@ -41,10 +43,12 @@
|
|||||||
- Role-aware: items differ based on admin vs member route
|
- Role-aware: items differ based on admin vs member route
|
||||||
|
|
||||||
### TopNav
|
### TopNav
|
||||||
|
|
||||||
- Slot `announcement` (center) — system/family messages
|
- Slot `announcement` (center) — system/family messages
|
||||||
- Slot `actions` (right) — user status, claim/message
|
- Slot `actions` (right) — user status, claim/message
|
||||||
|
|
||||||
### Page Content
|
### Page Content
|
||||||
|
|
||||||
- `ViewHeader` — title + subtitle + tool bar (tabs, weeknav, sort)
|
- `ViewHeader` — title + subtitle + tool bar (tabs, weeknav, sort)
|
||||||
- `CardGrid` — 3-column grid, Cards span columns via `cols` prop
|
- `CardGrid` — 3-column grid, Cards span columns via `cols` prop
|
||||||
- `Card` — 1/2/3 col span, micro-layout per page
|
- `Card` — 1/2/3 col span, micro-layout per page
|
||||||
@@ -52,6 +56,7 @@
|
|||||||
- `Button` — consistent CTAs with `variant` (primary/secondary/ghost/danger) and `size` (sm/md/lg)
|
- `Button` — consistent CTAs with `variant` (primary/secondary/ghost/danger) and `size` (sm/md/lg)
|
||||||
|
|
||||||
### Components (frontend/src/lib/components/)
|
### Components (frontend/src/lib/components/)
|
||||||
|
|
||||||
- `Sidebar.svelte`, `TopNav.svelte`, `Footer.svelte`
|
- `Sidebar.svelte`, `TopNav.svelte`, `Footer.svelte`
|
||||||
- `ViewHeader.svelte`, `Card.svelte`, `CardGrid.svelte`
|
- `ViewHeader.svelte`, `Card.svelte`, `CardGrid.svelte`
|
||||||
- `Button.svelte`, `Accordion.svelte`
|
- `Button.svelte`, `Accordion.svelte`
|
||||||
@@ -177,14 +182,12 @@
|
|||||||
- **Admin dashboard stat tiles**: added 4 gradient tiles (members / points / cash / chores done) reusing the child `.tiles`/`.tile` pattern + new `.tile-members`/`.tile-chores` colors, from a new `adminTiles` derived summing `summary.summaries`. Also fixed admin subtitle `Week of {YYYY-MM-DD}` → `Week of {DDMMYY}`.
|
- **Admin dashboard stat tiles**: added 4 gradient tiles (members / points / cash / chores done) reusing the child `.tiles`/`.tile` pattern + new `.tile-members`/`.tile-chores` colors, from a new `adminTiles` derived summing `summary.summaries`. Also fixed admin subtitle `Week of {YYYY-MM-DD}` → `Week of {DDMMYY}`.
|
||||||
- **Check**: frontend `svelte-check` stays at 12 baseline errors. Note: frontend dev server on :2080 was not running when verified (proxy :3456 up).
|
- **Check**: frontend `svelte-check` stays at 12 baseline errors. Note: frontend dev server on :2080 was not running when verified (proxy :3456 up).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### 2026-08-06 — Env Consolidation: `SERVER_IP`, `PROXY_URL`, and SvelteKit env only
|
### 2026-08-06 — Env Consolidation: `SERVER_IP`, `PROXY_URL`, and SvelteKit env only
|
||||||
|
|
||||||
- **`config.ts` is proxy-only.** It now holds just the three ports (`FRONTEND_PORT`/`PROXY_PORT`/`PB_PORT` = `2080`/`3456`/`8090`). SvelteKit **never imports `config.ts`** — SvelteKit env vars are declared in `frontend/src/env.ts` and read via `$app/env/*`. Deleted the stale `config.js/.d.ts/.map` artifacts.
|
- **`config.ts` is proxy-only.** It now holds just the three ports (`FRONTEND_PORT`/`PROXY_PORT`/`PB_PORT` = `2080`/`3456`/`8090`). SvelteKit **never imports `config.ts`** — SvelteKit env vars are declared in `frontend/src/env.ts` and read via `$app/env/*`. Deleted the stale `config.js/.d.ts/.map` artifacts.
|
||||||
- **`frontend/src/env.ts`** declares: `PROXY_URL` (public, default `http://127.0.0.1:3456`), `SERVER_IP` (public, default `192.168.1.225`), `PB_EMAIL`/`PB_PASSWORD` (private, defaults). `PUBLIC_PB_URL` removed (was the source of a startup crash when unset).
|
- **`frontend/src/env.ts`** declares: `PROXY_URL` (public, default `http://127.0.0.1:3456`), `SERVER_IP` (public, default `192.168.1.225`), `PB_EMAIL`/`PB_PASSWORD` (private, defaults). `PUBLIC_PB_URL` removed (was the source of a startup crash when unset).
|
||||||
- **Deleted `frontend/src/lib/server/env.ts`** (untracked). All server modules now `import { PROXY_URL } from '$app/env/public'` (`hono.ts`, `auth.ts`, `+layout.server.ts`, `+page.server.ts`, `preferences`, `join/[code]/[member]`). `admin/+page.server.ts` imports creds from `$app/env/private`.
|
- **Deleted `frontend/src/lib/server/env.ts`** (untracked). All server modules now `import { PROXY_URL } from '$app/env/public'` (`hono.ts`, `auth.ts`, `+layout.server.ts`, `+page.server.ts`, `preferences`, `join/[code]/[member]`). `admin/+page.server.ts` imports creds from `$app/env/private`.
|
||||||
- **`frontend/src/lib/pocketbase.ts` (browser) + `pb-admin.ts`**: `PB_ENDPOINT = import.meta.env.PROD ? '/pb' : \`http://${SERVER_IP}:8090\``. (Fixed a bug where `pocketbase.ts` used `import.meta.env.SERVER_IP` → undefined.)
|
- **`frontend/src/lib/pocketbase.ts` (browser) + `pb-admin.ts`**: `PB_ENDPOINT = import.meta.env.PROD ? '/pb' : \`http://${SERVER_IP}:8090\``. (Fixed a bug where `pocketbase.ts`used`import.meta.env.SERVER_IP` → undefined.)
|
||||||
- **`proxy/src/env.ts`** (new): `PB_ENDPOINT = SERVER_IP ? \`http://${SERVER_IP}:8090\` : \`http://127.0.0.1:8090\``. Dev env is loaded by the proxy's `dev`/`seed` scripts via `tsx --env-file-if-exists=../.env` (pnpm has no `--env-file`; `NODE_OPTIONS='--env-file=…'` is rejected by Node). No `loadEnvFile` hack in code.
|
- **`proxy/src/env.ts`** (new): `PB_ENDPOINT = SERVER_IP ? \`http://${SERVER_IP}:8090\` : \`http://127.0.0.1:8090\``. Dev env is loaded by the proxy's `dev`/`seed` scripts via `tsx --env-file-if-exists=../.env` (pnpm has no `--env-file`; `NODE_OPTIONS='--env-file=…'` is rejected by Node). No `loadEnvFile` hack in code.
|
||||||
- **Docker**: removed dead `ENV PB_ENDPOINT` from `Dockerfile`; `EXPOSE 3001` (was `3005 8090`); compose public port is `${PORT:-3001}:3001`, creds default to the code fallback, redundant `FRONTEND_PORT`/`PROXY_PORT` passthrough dropped; `entrypoint.sh` simplified (`PB_DATA=/app/pb_data`, `PORT=$FRONTEND_PORT`, no `:-` fallbacks).
|
- **Docker**: removed dead `ENV PB_ENDPOINT` from `Dockerfile`; `EXPOSE 3001` (was `3005 8090`); compose public port is `${PORT:-3001}:3001`, creds default to the code fallback, redundant `FRONTEND_PORT`/`PROXY_PORT` passthrough dropped; `entrypoint.sh` simplified (`PB_DATA=/app/pb_data`, `PORT=$FRONTEND_PORT`, no `:-` fallbacks).
|
||||||
- **Frontend deps added** (were missing imports): `chart.js`, `qrcode`, `@hiseb/confetti`.
|
- **Frontend deps added** (were missing imports): `chart.js`, `qrcode`, `@hiseb/confetti`.
|
||||||
@@ -198,12 +201,14 @@
|
|||||||
- **Watch-out**: a careless `docker run` with a **fresh volume** (my first attempt, aborted in time) would have wiped the permanent PB data. Restore command is in RULES.md. Two containers (`pb-dev` :8090 and the docker app's internal PB :8091) currently **share the same host `./pb_data`** — be careful with both.
|
- **Watch-out**: a careless `docker run` with a **fresh volume** (my first attempt, aborted in time) would have wiped the permanent PB data. Restore command is in RULES.md. Two containers (`pb-dev` :8090 and the docker app's internal PB :8091) currently **share the same host `./pb_data`** — be careful with both.
|
||||||
|
|
||||||
### 2026-08-06 — Added root `shared/` for cross-package code
|
### 2026-08-06 — Added root `shared/` for cross-package code
|
||||||
|
|
||||||
- Created `shared/timezone.ts` (moved from root `timezone.ts`). Imported by `frontend/src/routes/[fam]/[username]/+page.svelte`, `.../settings/+page.svelte`, and `proxy/src/index.ts`. Deleted the root `timezone.ts`.
|
- Created `shared/timezone.ts` (moved from root `timezone.ts`). Imported by `frontend/src/routes/[fam]/[username]/+page.svelte`, `.../settings/+page.svelte`, and `proxy/src/index.ts`. Deleted the root `timezone.ts`.
|
||||||
- Created `shared/pb/schema.ts` — single source of truth for the PocketBase schema + field builders (`SCHEMA_PLAN` ordered collection plan + `text/select/rel/...` helpers). Both `proxy/src/migrate.ts` (`ensureSchema`) and `proxy/scripts/seed.ts` now iterate `SCHEMA_PLAN`; kills the previous duplicated schema/field-helper definitions in both files.
|
- Created `shared/pb/schema.ts` — single source of truth for the PocketBase schema + field builders (`SCHEMA_PLAN` ordered collection plan + `text/select/rel/...` helpers). Both `proxy/src/migrate.ts` (`ensureSchema`) and `proxy/scripts/seed.ts` now iterate `SCHEMA_PLAN`; kills the previous duplicated schema/field-helper definitions in both files.
|
||||||
- Reason: `timezone.ts` and the PB schema are consumed by more than one package; `shared/` is the root location both can reach. Rule added to RULES.md: shared code lives in `shared/`, never inside `frontend/` or `proxy/`.
|
- Reason: `timezone.ts` and the PB schema are consumed by more than one package; `shared/` is the root location both can reach. Rule added to RULES.md: shared code lives in `shared/`, never inside `frontend/` or `proxy/`.
|
||||||
- Note: proxy `tsc --noEmit` already errors on `.ts`-extension imports (`allowImportingTsExtensions` unset) — pre-existing, not from this change. Runtime uses esbuild (build) + tsx (dev), both of which bundle the `shared/` imports correctly. Verified `pnpm build` clean for both packages.
|
- Note: proxy `tsc --noEmit` already errors on `.ts`-extension imports (`allowImportingTsExtensions` unset) — pre-existing, not from this change. Runtime uses esbuild (build) + tsx (dev), both of which bundle the `shared/` imports correctly. Verified `pnpm build` clean for both packages.
|
||||||
|
|
||||||
### 2026-08-07 — `@shared/*` import alias (path alias, not a pnpm package)
|
### 2026-08-07 — `@shared/*` import alias (path alias, not a pnpm package)
|
||||||
|
|
||||||
- Moved `config.ts` → `shared/config.ts`. All `shared/` code is now imported as `@shared/*` instead of relative `../../shared/...`.
|
- Moved `config.ts` → `shared/config.ts`. All `shared/` code is now imported as `@shared/*` instead of relative `../../shared/...`.
|
||||||
- This is a **path alias**, not a pnpm workspace package (`@shared` alone isn't a valid npm package name; a real package would need `@scope/name`).
|
- This is a **path alias**, not a pnpm workspace package (`@shared` alone isn't a valid npm package name; a real package would need `@scope/name`).
|
||||||
- Proxy: `tsconfig.json` sets `paths: { "@shared/*": ["../shared/*"] }`; esbuild build adds `--alias:@shared=../shared`; tsx resolves via tsconfig paths. Proxy keeps `.ts` extensions (`@shared/config.ts`).
|
- Proxy: `tsconfig.json` sets `paths: { "@shared/*": ["../shared/*"] }`; esbuild build adds `--alias:@shared=../shared`; tsx resolves via tsconfig paths. Proxy keeps `.ts` extensions (`@shared/config.ts`).
|
||||||
@@ -212,6 +217,7 @@
|
|||||||
- Docker note: runtime image only copies `frontend/build` + `proxy/dist` (both already bundle `shared/`), so `shared/` needn't be copied into the image.
|
- Docker note: runtime image only copies `frontend/build` + `proxy/dist` (both already bundle `shared/`), so `shared/` needn't be copied into the image.
|
||||||
|
|
||||||
### 2026-08-10 — Dev runtime cleanup (PB instances / containers)
|
### 2026-08-10 — Dev runtime cleanup (PB instances / containers)
|
||||||
|
|
||||||
- **Removed** test container `31e74178b3f0` (`famdone-service-app-1`, host :3010 + :8092). It ran **PB 0.39.10** and bound the **same host `pb_data`** as pb-dev → two PBs (v0.25 + v0.39) writing one SQLite DB = corruption/lock risk (likely source of dev instability/login lag).
|
- **Removed** test container `31e74178b3f0` (`famdone-service-app-1`, host :3010 + :8092). It ran **PB 0.39.10** and bound the **same host `pb_data`** as pb-dev → two PBs (v0.25 + v0.39) writing one SQLite DB = corruption/lock risk (likely source of dev instability/login lag).
|
||||||
- **Killed** 7 stale host `tsx watch` dev-proxy processes (Jul 28–Aug 5) + my throwaway 0.39 PBs.
|
- **Killed** 7 stale host `tsx watch` dev-proxy processes (Jul 28–Aug 5) + my throwaway 0.39 PBs.
|
||||||
- **Reset pb_data**: stopped pb-dev, wiped `/home/threejjjs/development/famchamp/pb_data`, **recreated** pb-dev container (fresh v0.25 store) with `--automigrate=false`, recreated dev superuser `debug@famchamp.dev`/`debug123`.
|
- **Reset pb_data**: stopped pb-dev, wiped `/home/threejjjs/development/famchamp/pb_data`, **recreated** pb-dev container (fresh v0.25 store) with `--automigrate=false`, recreated dev superuser `debug@famchamp.dev`/`debug123`.
|
||||||
@@ -219,6 +225,7 @@
|
|||||||
- **Desired end state (confirmed)**: `8090` = pb-dev (v0.25, single instance, automigrate off); `3001`+`8091` = PROD app `cffd636cc772` (kept, not live); PROD pb_data at `/data/coolify/.../pb_data` (separate from dev).
|
- **Desired end state (confirmed)**: `8090` = pb-dev (v0.25, single instance, automigrate off); `3001`+`8091` = PROD app `cffd636cc772` (kept, not live); PROD pb_data at `/data/coolify/.../pb_data` (separate from dev).
|
||||||
|
|
||||||
### 2026-08-10 — PB 0.25 → 0.39 migration (branch `feature/migrate-pocketbase`)
|
### 2026-08-10 — PB 0.25 → 0.39 migration (branch `feature/migrate-pocketbase`)
|
||||||
|
|
||||||
- **Decision**: keep our own `migrate.ts` schema-as-code (API-driven, does data migrations + rule locking), NOT PocketBase's built-in automigrate (schema-only, generates version-specific migration files, and generates conflicting snapshots on upgraded stores). Disable PB automigrate in the runtime.
|
- **Decision**: keep our own `migrate.ts` schema-as-code (API-driven, does data migrations + rule locking), NOT PocketBase's built-in automigrate (schema-only, generates version-specific migration files, and generates conflicting snapshots on upgraded stores). Disable PB automigrate in the runtime.
|
||||||
- **Verified against 0.39.10** (throwaway binaries on `127.0.0.1:8098/8099`, temp data dirs):
|
- **Verified against 0.39.10** (throwaway binaries on `127.0.0.1:8098/8099`, temp data dirs):
|
||||||
1. Fresh store: `migrate()` bootstraps all 14 `SCHEMA_PLAN` collections + every field migration cleanly (schema field builders are 0.39-compatible).
|
1. Fresh store: `migrate()` bootstraps all 14 `SCHEMA_PLAN` collections + every field migration cleanly (schema field builders are 0.39-compatible).
|
||||||
@@ -228,7 +235,7 @@
|
|||||||
- `docker/Dockerfile` `POCKETBASE_VERSION` → `0.39.10`.
|
- `docker/Dockerfile` `POCKETBASE_VERSION` → `0.39.10`.
|
||||||
- `docker/Dockerfile.dev` → `0.39.10` + `CMD ... --automigrate=false`.
|
- `docker/Dockerfile.dev` → `0.39.10` + `CMD ... --automigrate=false`.
|
||||||
- `docker/entrypoint.sh` → `pocketbase serve ... --automigrate=false`.
|
- `docker/entrypoint.sh` → `pocketbase serve ... --automigrate=false`.
|
||||||
- `proxy/src/env.ts` → added non-breaking `PB_ENDPOINT` env override (used to point migrate at a throwaway PB on another port; default dev/prod split unchanged).
|
- `proxy/src/env.ts` → added non-breaking `PB_ENDPOINT` env override (used to point migrate at a throwaway PB on another port; default dev/prod split unchanged).
|
||||||
- **⚠️ 0.39 schema breaking change**: PB 0.39 does **NOT** auto-add `createdAt`/`updatedAt` to **API-created** collections (0.25 did). The chat store filters/sorts on a custom `messages.createdAt`, so a fresh 0.39 store is missing it → raw PB 400. Fixed two ways:
|
- **⚠️ 0.39 schema breaking change**: PB 0.39 does **NOT** auto-add `createdAt`/`updatedAt` to **API-created** collections (0.25 did). The chat store filters/sorts on a custom `messages.createdAt`, so a fresh 0.39 store is missing it → raw PB 400. Fixed two ways:
|
||||||
- `shared/pb/schema.ts`: `messages` now declares `date("createdAt")` explicitly (source of truth → `ensureSchema`).
|
- `shared/pb/schema.ts`: `messages` now declares `date("createdAt")` explicitly (source of truth → `ensureSchema`).
|
||||||
- `proxy/src/migrate.ts`: the "messages already exists" branch now adds `createdAt` if missing (idempotent hardening for drifted/upgraded stores).
|
- `proxy/src/migrate.ts`: the "messages already exists" branch now adds `createdAt` if missing (idempotent hardening for drifted/upgraded stores).
|
||||||
@@ -236,6 +243,7 @@
|
|||||||
- **Prod upgrade steps**: backup `pb_data` → run the 0.39 image (automigrate off) → run `migrate()` → verify no drift (`messages.createdAt`, `id.autogeneratePattern`).
|
- **Prod upgrade steps**: backup `pb_data` → run the 0.39 image (automigrate off) → run `migrate()` → verify no drift (`messages.createdAt`, `id.autogeneratePattern`).
|
||||||
|
|
||||||
### 2026-08-10 — Revert PB to 0.25.8 (backtrack from 0.39)
|
### 2026-08-10 — Revert PB to 0.25.8 (backtrack from 0.39)
|
||||||
|
|
||||||
- **Decision**: backtrack off the PocketBase 0.39 bump (introduced in commit `3725c54` via `ARG POCKETBASE_VERSION=0.39.10`) and work from a **0.25.8 baseline** in BOTH dev and prod, then migrate to 0.39 deliberately later.
|
- **Decision**: backtrack off the PocketBase 0.39 bump (introduced in commit `3725c54` via `ARG POCKETBASE_VERSION=0.39.10`) and work from a **0.25.8 baseline** in BOTH dev and prod, then migrate to 0.39 deliberately later.
|
||||||
- Reverted `docker/Dockerfile` `POCKETBASE_VERSION` back to `0.25.8` (matches `docker/Dockerfile.dev`). Dev `pb-dev` and the docker app internal PB `:8091` share host `./pb_data`.
|
- Reverted `docker/Dockerfile` `POCKETBASE_VERSION` back to `0.25.8` (matches `docker/Dockerfile.dev`). Dev `pb-dev` and the docker app internal PB `:8091` share host `./pb_data`.
|
||||||
- **Migration schema scripts (DO NOT FORGET)**: the schema single source of truth is `shared/pb/schema.ts` (`SCHEMA_PLAN`), iterated by `proxy/src/migrate.ts` (`ensureSchema`) and `proxy/scripts/seed.ts`. The chat `messages` / `chat_typing` collections are defined there **without** an explicit `createdAt` — they rely on PB auto-adding it on first create.
|
- **Migration schema scripts (DO NOT FORGET)**: the schema single source of truth is `shared/pb/schema.ts` (`SCHEMA_PLAN`), iterated by `proxy/src/migrate.ts` (`ensureSchema`) and `proxy/scripts/seed.ts`. The chat `messages` / `chat_typing` collections are defined there **without** an explicit `createdAt` — they rely on PB auto-adding it on first create.
|
||||||
@@ -332,7 +340,7 @@
|
|||||||
|
|
||||||
### 2026-08-31 — Bonus progress window: `completeBy` + `startDate` implemented
|
### 2026-08-31 — Bonus progress window: `completeBy` + `startDate` implemented
|
||||||
|
|
||||||
- **Problem**: a standalone cash bonus (core reward with a points threshold) displayed progress differently on the child dashboard (current week → "0/500") vs the admin dashboard (cumulative since records began). Both were "correct" because `bonus_configs` had no way to scope tracking — with no `period` set, progress()/evaluateFam totalled *all* completions, and the child dashboard forced `cfg.period || 'weekly'`.
|
- **Problem**: a standalone cash bonus (core reward with a points threshold) displayed progress differently on the child dashboard (current week → "0/500") vs the admin dashboard (cumulative since records began). Both were "correct" because `bonus_configs` had no way to scope tracking — with no `period` set, progress()/evaluateFam totalled _all_ completions, and the child dashboard forced `cfg.period || 'weekly'`.
|
||||||
- **Fix**: added to `bonus_configs` (schema + `ensureBonusFields` idempotent field-add in migrate.ts, so existing installs upgrade without wiping): `completeBy` (select `unlimited|week|custom`), `startDate` (text), `completeByDate` (text). New shared helpers in `shared/timezone.ts`: `bonusWindow(cfg, payday, tz)` + `completionInWindow(c, {from,to})` ('' = unbounded side).
|
- **Fix**: added to `bonus_configs` (schema + `ensureBonusFields` idempotent field-add in migrate.ts, so existing installs upgrade without wiping): `completeBy` (select `unlimited|week|custom`), `startDate` (text), `completeByDate` (text). New shared helpers in `shared/timezone.ts`: `bonusWindow(cfg, payday, tz)` + `completionInWindow(c, {from,to})` ('' = unbounded side).
|
||||||
- **Window semantics** (unified across server `progress()`/`evaluateFam()` and the child `thresholdGoals`): recurring configs (period set) keep their period window; standalone configs use `completeBy`:
|
- **Window semantics** (unified across server `progress()`/`evaluateFam()` and the child `thresholdGoals`): recurring configs (period set) keep their period window; standalone configs use `completeBy`:
|
||||||
- `unlimited` (default) → `[startDate, ∞]` cumulative
|
- `unlimited` (default) → `[startDate, ∞]` cumulative
|
||||||
@@ -367,3 +375,17 @@
|
|||||||
|
|
||||||
- **Feature:** Count-type rewards now support pinning to a single assigned chore (`bonus_configs.targetChoreId`). On the fam-admin Rewards modal (Step 2), when Type = "Count - (chores)" a **Target Chore** dropdown appears after the Target Value field — options are the selected member's assigned (non-todo) chores, default "All Chores". Evaluation (`bonuses.evaluateFam`) + display (`bonuses.progress`, dashboard `thresholdGoals`) now filter Count progress to only that chore's completions when set. Platform-level template form only needed the relabeled "Count - (chores)" — no target chore at template level. Pocket-money checkbox removed from the platform template form (only the auto-created per-child droplet needs it).
|
- **Feature:** Count-type rewards now support pinning to a single assigned chore (`bonus_configs.targetChoreId`). On the fam-admin Rewards modal (Step 2), when Type = "Count - (chores)" a **Target Chore** dropdown appears after the Target Value field — options are the selected member's assigned (non-todo) chores, default "All Chores". Evaluation (`bonuses.evaluateFam`) + display (`bonuses.progress`, dashboard `thresholdGoals`) now filter Count progress to only that chore's completions when set. Platform-level template form only needed the relabeled "Count - (chores)" — no target chore at template level. Pocket-money checkbox removed from the platform template form (only the auto-created per-child droplet needs it).
|
||||||
- **TODO (logic, not yet fixed):** Count rewards with a `period` (e.g. weekly) reset + re-earn each period like a points/cash threshold. Once a Count reward is pinned to a target (or all chores), the intended semantics are ambiguous: should it be **continuous** (unlimited, measured once since startDate until reached) or **limited to the period window** (re-earn each week)? Currently it follows the periodic-reset behavior. Decide whether Count rewards should ignore `period` (behave as standalone/unlimited since startDate) and adjust `bonusWindow`/evaluation accordingly. Not attempted in this change.
|
- **TODO (logic, not yet fixed):** Count rewards with a `period` (e.g. weekly) reset + re-earn each period like a points/cash threshold. Once a Count reward is pinned to a target (or all chores), the intended semantics are ambiguous: should it be **continuous** (unlimited, measured once since startDate until reached) or **limited to the period window** (re-earn each week)? Currently it follows the periodic-reset behavior. Decide whether Count rewards should ignore `period` (behave as standalone/unlimited since startDate) and adjust `bonusWindow`/evaluation accordingly. Not attempted in this change.
|
||||||
|
|
||||||
|
### 2026-09-11 — Shared-device PIN switching (a computer shared by siblings)
|
||||||
|
|
||||||
|
- **Problem:** a single `pb_token` cookie meant joining kid B on the family computer silently logged out kid A; every hand-off needed a fresh parent-issued OTP. Design note: `shared-device.md` (decisions + flows).
|
||||||
|
- **Model — the PIN is NOT a login:** it _selects_ among sessions that already exist on the device (`pb_token_<childId>` per child + `pb_active` naming the current one). PIN alone mints nothing on a fresh device; a stolen cookie alone selects nothing. Threat model = sibling mischief; devtools-level bypass explicitly accepted (data is family-scoped, toggles reversible).
|
||||||
|
- **Sessions (`session.ts` + `hooks.server.ts`):** children store one httpOnly cookie per account (`pb_token_<id>`, 5d TTL) + `pb_active`. Resolution order: `pb_active` first, then legacy `pb_token` (parents + pre-feature children). Parent login/join clears `pb_active` → supersedes kid mode; kid switches shadow (don't delete) a parent session; `/logout` clears everything. Per-profile removal = picker ✕ → `POST /api/device/remove` (device-local cookie surgery, no session required).
|
||||||
|
- **`pins` collection** (superuser-only rules like `otp`): plaintext 3-digit PIN, deliberately parent-recoverable (Q1: View). All access server-side with session-role checks — kids can never read siblings' pins via PB rules. Created on boot via `ensurePins({})` in the always-run migrate path (existing installs — no DB wipe), plus `settings.lockMins` via `SCHEMA_PLAN` + `ensureSettingsFields`.
|
||||||
|
- **Endpoints:** `POST /api/switch-user {userId, pin}` — cookie-presence gate, superuser PIN verify, in-memory rate limit (5 fails → 30s), **self-healing**: expired device tokens re-mint via the derived password (server-only) instead of forcing a re-join. `POST /api/pins` — `set` (first-time), `change` (needs current), `ensure` (set-if-missing, used by the join wizard so joining a _second_ shared device doesn't clash with an existing PIN).
|
||||||
|
- **Picker (`SharedPicker` component)** — one UI everywhere: top-nav colour-dot (any session), idle-lock overlay, and standalone `/{fam}/switch` landing (fam layout redirects there when kid cookies exist but none is active; join pages excluded from the redirect; `+page.server.ts` sends active sessions home). PIN required on every pick incl. "resume" (deliberate-select property). Standalone footer links: join with a code + parent login.
|
||||||
|
- **Join wizard (`JoinPinFlow`):** after OTP redeem → "shared with siblings?" → PIN setup (skipped on "no"), **forced when the device already has other kid sessions**; then straight to the kid's dashboard. All three child join routes updated (root `/join`, `/{fam}/join`, `/{fam}/join/{username}`); parents keep the single-session flow.
|
||||||
|
- **Idle lock (client, `lib/client/lock.ts`):** `localStorage[fam_last_active]` written on click/key/touch (throttled 10s) + force-written on `pagehide` → survives browser close/sleep/restart (next launch compares elapsed; live 15s interval mid-session). Default **10 min** (user-set: default 10, not 2-3); parent-adjustable `Off / 2 / 10` in Settings → Family → **Shared computer**. Children only; tab-switches don't lock; two tabs share the timestamp so the active tab arbitrates.
|
||||||
|
- **Parent/child PIN UI:** Settings → Invites → All members → **PIN** per member (reveal + give-a-new-PIN modal); child Preferences → **My PIN** (set, or change with current PIN; "forgot? parent can read it out").
|
||||||
|
- **Typecheck/build:** `svelte-check` still 4 pre-existing canary errors only (chores RewardType/Frequency ×3, qrcode decl — files untouched by this change); prettier run over touched files. Migration applies on next dev-server boot (migrateOnBoot) — no DB wipe; hooks changes need the dev server restart (auto).
|
||||||
|
- **Caveats:** legacy single-cookie child sessions work but don't appear in the picker until re-join; multi-tab concurrency accepted (single-tab-norm on family desktops); `shared-device.md` records the settled open questions (view-not-reset, optional-at-join, no parent switcher, straight-to-dashboard, no cross-family).
|
||||||
|
|||||||
@@ -2,8 +2,12 @@ import type { Handle } from '@sveltejs/kit';
|
|||||||
import { createPbClient } from '$lib/server/pocketbase';
|
import { createPbClient } from '$lib/server/pocketbase';
|
||||||
import {
|
import {
|
||||||
SESSION_COOKIE,
|
SESSION_COOKIE,
|
||||||
|
ACTIVE_COOKIE,
|
||||||
|
childSessionCookie,
|
||||||
setSessionCookie,
|
setSessionCookie,
|
||||||
clearSessionCookie,
|
clearSessionCookie,
|
||||||
|
setChildSessionCookie,
|
||||||
|
clearActiveChild,
|
||||||
PLATFORM_SESSION_COOKIE,
|
PLATFORM_SESSION_COOKIE,
|
||||||
clearPlatformSession
|
clearPlatformSession
|
||||||
} from '$lib/server/session';
|
} from '$lib/server/session';
|
||||||
@@ -14,6 +18,21 @@ import { migrateOnBoot } from '$lib/server/migrate-boot';
|
|||||||
// Run the PB schema migration once at server boot (idempotent).
|
// Run the PB schema migration once at server boot (idempotent).
|
||||||
void migrateOnBoot();
|
void migrateOnBoot();
|
||||||
|
|
||||||
|
function sessionFrom(record: any, freshToken: string) {
|
||||||
|
return {
|
||||||
|
id: record.id,
|
||||||
|
name: record.name || record.username || '',
|
||||||
|
username: handleOf(record.username || ''),
|
||||||
|
role: record.role || 'parent',
|
||||||
|
famId: record.famId,
|
||||||
|
color: record.color || '',
|
||||||
|
pattern: record.pattern || '',
|
||||||
|
themeSize: record.themeSize || '',
|
||||||
|
themeOpacity: record.themeOpacity || '',
|
||||||
|
token: freshToken
|
||||||
|
} satisfies SessionUser & { token: string };
|
||||||
|
}
|
||||||
|
|
||||||
export const handle: Handle = async ({ event, resolve }) => {
|
export const handle: Handle = async ({ event, resolve }) => {
|
||||||
event.locals.user = null;
|
event.locals.user = null;
|
||||||
event.locals.pbToken = null;
|
event.locals.pbToken = null;
|
||||||
@@ -36,32 +55,50 @@ export const handle: Handle = async ({ event, resolve }) => {
|
|||||||
return resolve(event);
|
return resolve(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fam-user session: pb_token JWT → authRefresh → locals.user.
|
// Shared-device sessions: `pb_active` names the child whose cookie is the
|
||||||
|
// current session. Resolved FIRST so a kid switch on a family computer
|
||||||
|
// supersedes any shadowed single pb_token (parent) session.
|
||||||
|
const activeId = event.cookies.get(ACTIVE_COOKIE);
|
||||||
|
if (activeId) {
|
||||||
|
const childToken = event.cookies.get(childSessionCookie(activeId));
|
||||||
|
if (!childToken) {
|
||||||
|
// Stale active pointer (cookie removed) — clean it up and fall through.
|
||||||
|
clearActiveChild(event.cookies);
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const pb = createPbClient(childToken);
|
||||||
|
// authRefresh() does two jobs in one call:
|
||||||
|
// 1. Verifies the token (PB JWTs can't be checked offline — the
|
||||||
|
// signing secret is per-record and never leaves PB).
|
||||||
|
// 2. Returns the current record — the only way to get
|
||||||
|
// name/role/famId, since PB doesn't embed custom fields.
|
||||||
|
const { record, token: freshToken } = await pb.collection('users').authRefresh();
|
||||||
|
if (record.role === 'child') {
|
||||||
|
const session = sessionFrom(record, freshToken);
|
||||||
|
event.locals.user = session;
|
||||||
|
event.locals.pbToken = session.token;
|
||||||
|
if (freshToken !== childToken) {
|
||||||
|
setChildSessionCookie(event.cookies, activeId, freshToken);
|
||||||
|
}
|
||||||
|
return resolve(event);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Expired/revoked/malformed — leave the cookie; the picker switch
|
||||||
|
// re-mints it server-side. Fall through to the single session.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Single session: pb_token JWT (parents, or children from before the
|
||||||
|
// multi-session scheme) → authRefresh → locals.user.
|
||||||
const token = event.cookies.get(SESSION_COOKIE);
|
const token = event.cookies.get(SESSION_COOKIE);
|
||||||
if (token) {
|
if (token) {
|
||||||
const pb = createPbClient(token);
|
const pb = createPbClient(token);
|
||||||
try {
|
try {
|
||||||
// authRefresh() does two jobs in one call:
|
|
||||||
// 1. Verifies the token (PB JWTs can't be checked offline — the
|
|
||||||
// signing secret is per-record and never leaves PB), so this
|
|
||||||
// round trip IS the verification step.
|
|
||||||
// 2. Returns the current record — the only way to get
|
|
||||||
// name/role/famId, since PB doesn't embed custom fields in the
|
|
||||||
// token itself.
|
|
||||||
const { record, token: freshToken } = await pb.collection('users').authRefresh();
|
const { record, token: freshToken } = await pb.collection('users').authRefresh();
|
||||||
event.locals.user = {
|
const session = sessionFrom(record, freshToken);
|
||||||
id: record.id,
|
event.locals.user = session;
|
||||||
name: record.name || record.username || '',
|
event.locals.pbToken = session.token;
|
||||||
username: handleOf(record.username || ''),
|
|
||||||
role: record.role || 'parent',
|
|
||||||
famId: record.famId,
|
|
||||||
color: record.color || '',
|
|
||||||
pattern: record.pattern || '',
|
|
||||||
themeSize: record.themeSize || '',
|
|
||||||
themeOpacity: record.themeOpacity || ''
|
|
||||||
} satisfies SessionUser;
|
|
||||||
event.locals.pbToken = freshToken;
|
|
||||||
|
|
||||||
if (freshToken !== token) {
|
if (freshToken !== token) {
|
||||||
setSessionCookie(event.cookies, freshToken);
|
setSessionCookie(event.cookies, freshToken);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,3 +14,6 @@ export { default as NoticeDialog } from './NoticeDialog.svelte';
|
|||||||
export { default as PricingPlans } from './PricingPlans.svelte';
|
export { default as PricingPlans } from './PricingPlans.svelte';
|
||||||
export { default as CheckboxGrid } from './CheckboxGrid.svelte';
|
export { default as CheckboxGrid } from './CheckboxGrid.svelte';
|
||||||
export { default as PatternPicker } from './PatternPicker.svelte';
|
export { default as PatternPicker } from './PatternPicker.svelte';
|
||||||
|
export { default as PinPad } from './PinPad.svelte';
|
||||||
|
export { default as SharedPicker } from './SharedPicker.svelte';
|
||||||
|
export { default as JoinPinFlow } from './JoinPinFlow.svelte';
|
||||||
|
|||||||
@@ -235,8 +235,8 @@ export async function redeemOtp(opts: { famSlug: string; username: string; otp:
|
|||||||
if (!issued || Date.now() - issued > OTP_TTL_MS) throw new Error('Code expired');
|
if (!issued || Date.now() - issued > OTP_TTL_MS) throw new Error('Code expired');
|
||||||
|
|
||||||
const authPb = createPbClient();
|
const authPb = createPbClient();
|
||||||
await authPb
|
const { record } = await authPb
|
||||||
.collection('users')
|
.collection('users')
|
||||||
.authWithPassword(fullUsername, derivePassword(famSlug, handleName));
|
.authWithPassword(fullUsername, derivePassword(famSlug, handleName));
|
||||||
return authPb.authStore.token;
|
return { token: authPb.authStore.token, userId: record.id };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -262,6 +262,54 @@ async function ensureOtp(ids: Record<string, string>): Promise<void> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Child shared-device PINs. Superuser-only rules (like `otp`) — all access
|
||||||
|
// goes through server endpoints with session-role checks, so children can
|
||||||
|
// never read siblings' pins via PB rules.
|
||||||
|
async function ensurePins(ids: Record<string, string>): Promise<void> {
|
||||||
|
if (await getCollection('pins')) return;
|
||||||
|
const famsId = ids.fams || (await getCollection('fams'))?.id;
|
||||||
|
const usersId = ids.users || (await getCollection('users'))?.id;
|
||||||
|
if (!famsId || !usersId) throw new Error('fams/users collection not found');
|
||||||
|
await createCollection({
|
||||||
|
name: 'pins',
|
||||||
|
type: 'base',
|
||||||
|
listRule: null,
|
||||||
|
viewRule: null,
|
||||||
|
createRule: null,
|
||||||
|
updateRule: null,
|
||||||
|
deleteRule: null,
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: 'famId',
|
||||||
|
type: 'relation',
|
||||||
|
required: true,
|
||||||
|
collectionId: famsId,
|
||||||
|
maxSelect: 1,
|
||||||
|
cascadeDelete: false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'userId',
|
||||||
|
type: 'relation',
|
||||||
|
required: true,
|
||||||
|
collectionId: usersId,
|
||||||
|
maxSelect: 1,
|
||||||
|
cascadeDelete: false
|
||||||
|
},
|
||||||
|
{ name: 'pin', type: 'text', required: false }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idempotent field-add for the shared-device idle lock (0 = off, else mins).
|
||||||
|
async function ensureSettingsFields(): Promise<void> {
|
||||||
|
const settingsCol = await getCollection('settings');
|
||||||
|
if (!settingsCol) return;
|
||||||
|
const has = (n: string) => settingsCol.fields.some((f: any) => f.name === n);
|
||||||
|
if (has('lockMins')) return;
|
||||||
|
settingsCol.fields.push({ name: 'lockMins', type: 'number', required: false });
|
||||||
|
await updateCollection(settingsCol.id, { fields: settingsCol.fields });
|
||||||
|
}
|
||||||
|
|
||||||
// Platform access codes — the codes that enable access to the platform. They're
|
// Platform access codes — the codes that enable access to the platform. They're
|
||||||
// global (not fam-scoped) and managed via the platform admin page (superuser
|
// global (not fam-scoped) and managed via the platform admin page (superuser
|
||||||
// only), so all rules are null like `otp`. A code grants a family a subscription
|
// only), so all rules are null like `otp`. A code grants a family a subscription
|
||||||
@@ -404,6 +452,7 @@ async function ensureSchema(): Promise<void> {
|
|||||||
|
|
||||||
await ensureUsers(ids);
|
await ensureUsers(ids);
|
||||||
await ensureOtp(ids);
|
await ensureOtp(ids);
|
||||||
|
await ensurePins(ids);
|
||||||
console.log('[migrate] Schema bootstrapped.');
|
console.log('[migrate] Schema bootstrapped.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -473,11 +522,16 @@ export async function migrate(): Promise<void> {
|
|||||||
// return) so new platform collections/fields/seed land on existing installs.
|
// return) so new platform collections/fields/seed land on existing installs.
|
||||||
await ensureUserFields();
|
await ensureUserFields();
|
||||||
await ensureFamFields();
|
await ensureFamFields();
|
||||||
|
await ensureSettingsFields();
|
||||||
await ensureBonusFields();
|
await ensureBonusFields();
|
||||||
await ensureTemplateFields();
|
await ensureTemplateFields();
|
||||||
await ensureAssignedChoreFields();
|
await ensureAssignedChoreFields();
|
||||||
await ensureAccessCodes();
|
await ensureAccessCodes();
|
||||||
await ensurePlatform();
|
await ensurePlatform();
|
||||||
|
// Superuser-only collections also land on EXISTING installs (ensureSchema's
|
||||||
|
// early return skips them). Like ensureOtp before it, ensurePins no-ops when
|
||||||
|
// the collection already exists.
|
||||||
|
await ensurePins({});
|
||||||
await ensureDefaultSeasons();
|
await ensureDefaultSeasons();
|
||||||
if (await isDemo()) {
|
if (await isDemo()) {
|
||||||
await seedDemoFamily();
|
await seedDemoFamily();
|
||||||
|
|||||||
@@ -1,22 +1,66 @@
|
|||||||
import type { Cookies } from '@sveltejs/kit';
|
import type { Cookies } from '@sveltejs/kit';
|
||||||
|
|
||||||
// The PocketBase JWT lives in a single cookie shared by:
|
// PocketBase JWTs live in cookies shared by:
|
||||||
// - the server hooks (authRefresh -> locals.user)
|
// - the server hooks (authRefresh -> locals.user)
|
||||||
// - the client SDK (seeded from page.data.pbToken -> authenticated famStore reads/subscribe)
|
// - the client SDK (seeded from page.data.pbToken -> authenticated famStore reads/subscribe)
|
||||||
// httpOnly keeps the token out of reach of browser JS/XSS; the client receives
|
// httpOnly keeps tokens out of reach of browser JS/XSS; the client receives
|
||||||
// the token server-side via the layout load (pbToken) and seeds pb.authStore.
|
// the token server-side via the layout load (pbToken) and seeds pb.authStore.
|
||||||
// Secure flag is set in prod so it's only sent over HTTPS.
|
// Secure flag is set in prod so it's only sent over HTTPS.
|
||||||
export const SESSION_COOKIE = 'pb_token';
|
export const SESSION_COOKIE = 'pb_token';
|
||||||
|
// Shared-device multi-session: children hold ONE cookie per account
|
||||||
|
// (`pb_token_<userId>`); `pb_active` names which one is the current session.
|
||||||
|
// Parents stay on the single `pb_token`.
|
||||||
|
export const CHILD_COOKIE_PREFIX = 'pb_token_';
|
||||||
|
export const ACTIVE_COOKIE = 'pb_active';
|
||||||
const MAX_AGE = 60 * 60 * 24 * 5; // 5 days — matches the PB users auth token duration
|
const MAX_AGE = 60 * 60 * 24 * 5; // 5 days — matches the PB users auth token duration
|
||||||
|
|
||||||
export function setSessionCookie(cookies: Cookies, token: string) {
|
function cookieOpts() {
|
||||||
cookies.set(SESSION_COOKIE, token, {
|
return {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
sameSite: 'lax',
|
sameSite: 'lax' as const,
|
||||||
path: '/',
|
path: '/',
|
||||||
maxAge: MAX_AGE,
|
maxAge: MAX_AGE,
|
||||||
secure: import.meta.env.PROD
|
secure: import.meta.env.PROD
|
||||||
});
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setSessionCookie(cookies: Cookies, token: string) {
|
||||||
|
cookies.set(SESSION_COOKIE, token, cookieOpts());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function childSessionCookie(userId: string) {
|
||||||
|
return `${CHILD_COOKIE_PREFIX}${userId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setChildSessionCookie(cookies: Cookies, userId: string, token: string) {
|
||||||
|
cookies.set(childSessionCookie(userId), token, cookieOpts());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearChildSession(cookies: Cookies, userId: string) {
|
||||||
|
cookies.delete(childSessionCookie(userId), { path: '/' });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setActiveChild(cookies: Cookies, userId: string) {
|
||||||
|
cookies.set(ACTIVE_COOKIE, userId, cookieOpts());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearActiveChild(cookies: Cookies) {
|
||||||
|
cookies.delete(ACTIVE_COOKIE, { path: '/' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ids of every child that has a session cookie on this device.
|
||||||
|
export function scanChildSessions(cookies: Cookies): string[] {
|
||||||
|
return cookies
|
||||||
|
.getAll()
|
||||||
|
.filter((c) => c.name.startsWith(CHILD_COOKIE_PREFIX))
|
||||||
|
.map((c) => c.name.slice(CHILD_COOKIE_PREFIX.length))
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove every child session on this device (logout-all).
|
||||||
|
export function clearDeviceSessions(cookies: Cookies) {
|
||||||
|
for (const id of scanChildSessions(cookies)) clearChildSession(cookies, id);
|
||||||
|
clearActiveChild(cookies);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearSessionCookie(cookies: Cookies) {
|
export function clearSessionCookie(cookies: Cookies) {
|
||||||
@@ -50,4 +94,4 @@ export function setPlatformSession(cookies: Cookies, token: string) {
|
|||||||
|
|
||||||
export function clearPlatformSession(cookies: Cookies) {
|
export function clearPlatformSession(cookies: Cookies) {
|
||||||
cookies.delete(PLATFORM_SESSION_COOKIE, { path: '/' });
|
cookies.delete(PLATFORM_SESSION_COOKIE, { path: '/' });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
import type { LayoutServerLoad } from './$types';
|
import type { LayoutServerLoad } from './$types';
|
||||||
import { getPlatformFlags } from '$lib/server/platform';
|
import { getPlatformFlags } from '$lib/server/platform';
|
||||||
|
import { scanChildSessions } from '$lib/server/session';
|
||||||
|
|
||||||
// Platform settings are public (read-only): feature flags ride along with
|
// Platform settings are public (read-only): feature flags ride along with
|
||||||
// every page's data so any component can deduce them via page.data.platformFlags.
|
// every page's data so any component can deduce them via page.data.platformFlags.
|
||||||
export const load: LayoutServerLoad = async () => {
|
export const load: LayoutServerLoad = async (event) => {
|
||||||
return { platformFlags: await getPlatformFlags() };
|
return {
|
||||||
|
platformFlags: await getPlatformFlags(),
|
||||||
|
// Children with session cookies on THIS device (shared-computer picker).
|
||||||
|
deviceChildIds: scanChildSessions(event.cookies)
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { redirect } from '@sveltejs/kit';
|
import { redirect } from '@sveltejs/kit';
|
||||||
import { createPbClient } from '$lib/server/pocketbase';
|
import { createPbClient, createSuperClient } from '$lib/server/pocketbase';
|
||||||
import { createServices, type ChatActor } from '$lib/server/services';
|
import { createServices, type ChatActor } from '$lib/server/services';
|
||||||
import { ensureFamAccess } from '$lib/server/access';
|
import { ensureFamAccess } from '$lib/server/access';
|
||||||
import { seedDemoCompletions } from '$lib/server/migrate';
|
import { seedDemoCompletions } from '$lib/server/migrate';
|
||||||
import { getPlatformFlags } from '$lib/server/platform';
|
import { getPlatformFlags } from '$lib/server/platform';
|
||||||
|
import { scanChildSessions } from '$lib/server/session';
|
||||||
|
|
||||||
async function paydayCheck(famId: string, pbToken: string) {
|
async function paydayCheck(famId: string, pbToken: string) {
|
||||||
try {
|
try {
|
||||||
@@ -56,7 +57,62 @@ export async function load(event) {
|
|||||||
const session = event.locals.user;
|
const session = event.locals.user;
|
||||||
const role = session?.role || 'child';
|
const role = session?.role || 'child';
|
||||||
const isParent = role === 'parent';
|
const isParent = role === 'parent';
|
||||||
const pbToken = event.cookies.get('pb_token') || '';
|
const pbToken = event.locals.pbToken || '';
|
||||||
|
const deviceChildIds = scanChildSessions(event.cookies);
|
||||||
|
|
||||||
|
// ── Shared-device picker mode ──
|
||||||
|
// The device holds child sessions but none is active (per-profile logout).
|
||||||
|
// Anything except the join flow lands on the standalone picker.
|
||||||
|
const paramFam = event.params.fam;
|
||||||
|
const isJoinPage = (event.url.pathname || '').split('/').includes('join');
|
||||||
|
if (!session && deviceChildIds.length > 0 && !isJoinPage) {
|
||||||
|
if (!(event.url.pathname || '').endsWith('/switch')) {
|
||||||
|
throw redirect(303, `/${encodeURIComponent(paramFam)}/switch`);
|
||||||
|
}
|
||||||
|
let pickerFamName = paramFam || '';
|
||||||
|
let pickerChildren: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
color: string;
|
||||||
|
username: string;
|
||||||
|
}[] = [];
|
||||||
|
try {
|
||||||
|
const pb = await createSuperClient();
|
||||||
|
const fam = await pb
|
||||||
|
.collection('fams')
|
||||||
|
.getFirstListItem(`slug='${paramFam}'`)
|
||||||
|
.catch(() => null);
|
||||||
|
if (fam) {
|
||||||
|
pickerFamName = fam.name || fam.slug;
|
||||||
|
const users = await pb.collection('users').getFullList({
|
||||||
|
filter: `id in ('${deviceChildIds.join("','")}') && role='child'`
|
||||||
|
});
|
||||||
|
pickerChildren = (users || []).map((u: any) => ({
|
||||||
|
id: u.id,
|
||||||
|
name: u.name || u.username || '',
|
||||||
|
color: u.color || '#6366f1',
|
||||||
|
username: u.username || ''
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
return {
|
||||||
|
famSlug: paramFam || '',
|
||||||
|
session: null,
|
||||||
|
isParent,
|
||||||
|
role,
|
||||||
|
famId: '',
|
||||||
|
chat: null,
|
||||||
|
pbToken: '',
|
||||||
|
fam: null,
|
||||||
|
famAccess: { disabled: false, mode: 'none', reason: '' },
|
||||||
|
demoMode: (await getPlatformFlags()).demo,
|
||||||
|
picker: true,
|
||||||
|
pickerFamName,
|
||||||
|
pickerChildren,
|
||||||
|
deviceChildIds,
|
||||||
|
lockMins: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
let famId = '';
|
let famId = '';
|
||||||
let chat: {
|
let chat: {
|
||||||
@@ -70,6 +126,7 @@ export async function load(event) {
|
|||||||
mode: 'none' as 'none' | 'code' | 'sub' | 'canceled',
|
mode: 'none' as 'none' | 'code' | 'sub' | 'canceled',
|
||||||
reason: ''
|
reason: ''
|
||||||
};
|
};
|
||||||
|
let lockMins = 0;
|
||||||
|
|
||||||
if (session && pbToken) {
|
if (session && pbToken) {
|
||||||
famId = session.famId;
|
famId = session.famId;
|
||||||
@@ -82,11 +139,22 @@ export async function load(event) {
|
|||||||
fam = res.fam;
|
fam = res.fam;
|
||||||
famAccess = res.access;
|
famAccess = res.access;
|
||||||
}
|
}
|
||||||
|
// Shared-device idle lock setting (0 = off; missing row defaults to 10
|
||||||
|
// min). Superuser read — the settings rules are parent-oriented and
|
||||||
|
// children must see it too.
|
||||||
|
try {
|
||||||
|
const pb = await createSuperClient();
|
||||||
|
const settings = await pb
|
||||||
|
.collection('settings')
|
||||||
|
.getFullList({ filter: `famId='${famId}'` })
|
||||||
|
.catch(() => []);
|
||||||
|
const row = (settings as any[])?.[0];
|
||||||
|
lockMins = row && row.lockMins != null ? Number(row.lockMins) : 10;
|
||||||
|
} catch {}
|
||||||
// Canonical URL: the [fam] segment must be the family SLUG, never the PB
|
// Canonical URL: the [fam] segment must be the family SLUG, never the PB
|
||||||
// id. If someone lands on /{famId}/... (a stale shortcut, bookmark, or a
|
// id. If someone lands on /{famId}/... (a stale shortcut, bookmark, or a
|
||||||
// login that fell back to the id), rewrite the first path segment to the
|
// login that fell back to the id), rewrite the first path segment to the
|
||||||
// slug so the id is replaced everywhere it'd otherwise persist.
|
// slug so the id is replaced everywhere it'd otherwise persist.
|
||||||
const paramFam = event.params.fam;
|
|
||||||
const canonicalSlug = fam?.slug;
|
const canonicalSlug = fam?.slug;
|
||||||
if (canonicalSlug && paramFam && paramFam !== canonicalSlug) {
|
if (canonicalSlug && paramFam && paramFam !== canonicalSlug) {
|
||||||
const rest = event.url.pathname.replace(`/${paramFam}`, '') || '/';
|
const rest = event.url.pathname.replace(`/${paramFam}`, '') || '/';
|
||||||
@@ -100,7 +168,7 @@ export async function load(event) {
|
|||||||
return {
|
return {
|
||||||
// Canonical fam slug — from the URL param ([fam] routes). Client code
|
// Canonical fam slug — from the URL param ([fam] routes). Client code
|
||||||
// reads page.data.famSlug; never copy it into local $state.
|
// reads page.data.famSlug; never copy it into local $state.
|
||||||
famSlug: event.params.fam || '',
|
famSlug: paramFam || '',
|
||||||
session: session
|
session: session
|
||||||
? {
|
? {
|
||||||
famId: session.famId,
|
famId: session.famId,
|
||||||
@@ -121,6 +189,11 @@ export async function load(event) {
|
|||||||
pbToken,
|
pbToken,
|
||||||
fam,
|
fam,
|
||||||
famAccess,
|
famAccess,
|
||||||
demoMode
|
demoMode,
|
||||||
|
picker: false,
|
||||||
|
pickerFamName: '',
|
||||||
|
pickerChildren: [],
|
||||||
|
deviceChildIds,
|
||||||
|
lockMins
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,9 +6,10 @@
|
|||||||
import { famStore } from '$lib/stores/fam.svelte';
|
import { famStore } from '$lib/stores/fam.svelte';
|
||||||
import { chatStore } from '$lib/stores/chat.svelte';
|
import { chatStore } from '$lib/stores/chat.svelte';
|
||||||
import { notices } from '$lib/stores/notices.svelte';
|
import { notices } from '$lib/stores/notices.svelte';
|
||||||
import { Sidebar, TopNav, Footer, Chat } from '$lib/components';
|
import { Sidebar, TopNav, Footer, Chat, SharedPicker } from '$lib/components';
|
||||||
import { chatIcon } from '$lib/components/icons';
|
import { chatIcon } from '$lib/components/icons';
|
||||||
import { recordShortcut } from '$lib/shortcut';
|
import { recordShortcut } from '$lib/shortcut';
|
||||||
|
import { installLockTracking, lockDue } from '$lib/client/lock';
|
||||||
import { themeShades } from '$lib/theme';
|
import { themeShades } from '$lib/theme';
|
||||||
import '$lib/theme-patterns.css';
|
import '$lib/theme-patterns.css';
|
||||||
import { themeDraft } from '$lib/stores/theme.svelte';
|
import { themeDraft } from '$lib/stores/theme.svelte';
|
||||||
@@ -29,6 +30,41 @@
|
|||||||
// Pattern size in vw units ('' = untouched → pattern class default).
|
// Pattern size in vw units ('' = untouched → pattern class default).
|
||||||
let bgSize = $derived(themeDraft.size ?? (data.session?.memberThemeSize || ''));
|
let bgSize = $derived(themeDraft.size ?? (data.session?.memberThemeSize || ''));
|
||||||
let bgSizeVw = $derived(Number(bgSize) > 0 ? bgSize : '');
|
let bgSizeVw = $derived(Number(bgSize) > 0 ? bgSize : '');
|
||||||
|
// Shared-device picker: standalone when the device has child sessions but
|
||||||
|
// none is active (layout load redirects here); overlay when the idle lock
|
||||||
|
// fires or the top-nav switcher is opened.
|
||||||
|
const pickerMode = $derived(!!data.picker);
|
||||||
|
let pickerOpen = $state(false);
|
||||||
|
let lockTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let deviceProfiles = $derived(
|
||||||
|
(data.deviceChildIds || [])
|
||||||
|
.map((id) => famStore.members.find((m) => m.id === id))
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((m: any) => ({ id: m.id, name: m.name, color: m.color, username: m.username }))
|
||||||
|
);
|
||||||
|
|
||||||
|
// Idle lock (children only): return to the picker after `lockMins` of no
|
||||||
|
// interaction. localStorage-backed (see lib/client/lock.ts) so a closed
|
||||||
|
// browser still trips the lock on next launch.
|
||||||
|
$effect(() => {
|
||||||
|
const isChild = data.session?.role === 'child';
|
||||||
|
const lockMins = Number(data.lockMins) || 0;
|
||||||
|
if (!isChild || lockMins <= 0 || data.picker) return;
|
||||||
|
installLockTracking();
|
||||||
|
if (lockDue(lockMins)) pickerOpen = true;
|
||||||
|
if (!lockTimer) {
|
||||||
|
lockTimer = setInterval(() => {
|
||||||
|
if (lockDue(lockMins)) pickerOpen = true;
|
||||||
|
}, 15_000);
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
if (lockTimer) {
|
||||||
|
clearInterval(lockTimer);
|
||||||
|
lockTimer = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
let session = $state<Session | null>(data.session);
|
let session = $state<Session | null>(data.session);
|
||||||
let isParent = $state(data.isParent);
|
let isParent = $state(data.isParent);
|
||||||
let role = $state(data.role);
|
let role = $state(data.role);
|
||||||
@@ -194,66 +230,97 @@
|
|||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="layout-stage" class:chat-open={chatStore.open} class:has-pattern={!!bgPattern}>
|
<!-- layout.svelte picker-mode branch -->
|
||||||
<div
|
{#if pickerMode}
|
||||||
class="app-shell {bgPattern ? `pattern-${bgPattern}` : ''}"
|
<main class="picker-stage">
|
||||||
style={`${bgSizeVw ? `--s:calc(${bgSizeVw} * 1vw);` : ''}--c1:${bgShades.c1};--c2:${bgShades.c2};--c3:${bgShades.c3};--c4:${bgShades.c4}`}
|
<SharedPicker
|
||||||
>
|
standalone
|
||||||
<Sidebar {famName} session={data.session} {isParent} {role} {isDemo} />
|
famSlug={data.famSlug}
|
||||||
<TopNav
|
famName={data.pickerFamName}
|
||||||
role={data.session ? role : ''}
|
profiles={data.pickerChildren || []}
|
||||||
seasons={famStore.seasons.filter((s) => s.active !== false)}
|
/>
|
||||||
announcement={disabled && !activating ? accessMessage(accessReason, isParent) : ''}
|
</main>
|
||||||
|
{:else}
|
||||||
|
<div class="layout-stage" class:chat-open={chatStore.open} class:has-pattern={!!bgPattern}>
|
||||||
|
<div
|
||||||
|
class="app-shell {bgPattern ? `pattern-${bgPattern}` : ''}"
|
||||||
|
style={`${bgSizeVw ? `--s:calc(${bgSizeVw} * 1vw);` : ''}--c1:${bgShades.c1};--c2:${bgShades.c2};--c3:${bgShades.c3};--c4:${bgShades.c4}`}
|
||||||
>
|
>
|
||||||
<button class="chat-toggle" onclick={() => chatStore.toggle()} aria-label="Open chat">
|
<Sidebar {famName} session={data.session} {isParent} {role} {isDemo} />
|
||||||
{@html chatIcon}
|
<TopNav
|
||||||
{#if chatStore.unread > 0}
|
role={data.session ? role : ''}
|
||||||
<span class="chat-badge">{chatStore.unread > 9 ? '9+' : chatStore.unread}</span>
|
seasons={famStore.seasons.filter((s) => s.active !== false)}
|
||||||
{/if}
|
announcement={disabled && !activating ? accessMessage(accessReason, isParent) : ''}
|
||||||
</button>
|
|
||||||
</TopNav>
|
|
||||||
<main class="app-main" class:join-page={page.url.pathname.split('/')[2] === 'join'}>
|
|
||||||
<div class="page-wrap">
|
|
||||||
<div class="page-content" class:locked>{@render children()}</div>
|
|
||||||
|
|
||||||
{#if locked}
|
|
||||||
<div class="disabled-overlay">
|
|
||||||
<div class="disabled-card">
|
|
||||||
{#if !hasAuth}
|
|
||||||
<h2>You need to be logged in to view this page</h2>
|
|
||||||
{:else if activating}
|
|
||||||
<div class="spinner" aria-hidden="true"></div>
|
|
||||||
<strong>Activating your subscription…</strong>
|
|
||||||
<span>Payment received — this usually only takes a few seconds.</span>
|
|
||||||
{:else}
|
|
||||||
<strong>Access paused</strong>
|
|
||||||
<span>
|
|
||||||
{isParent
|
|
||||||
? 'Add an access code or resume your subscription to keep using FamDone.'
|
|
||||||
: 'Your family access is paused.'}
|
|
||||||
</span>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{#if claimToast}
|
|
||||||
<a
|
|
||||||
class="claim-toast"
|
|
||||||
href={`/${page.params.fam}/${data.session?.username || page.params.username || ''}`}
|
|
||||||
>
|
>
|
||||||
{claimToast} — view dashboard →
|
<button class="chat-toggle" onclick={() => chatStore.toggle()} aria-label="Open chat">
|
||||||
</a>
|
{@html chatIcon}
|
||||||
|
{#if chatStore.unread > 0}
|
||||||
|
<span class="chat-badge">{chatStore.unread > 9 ? '9+' : chatStore.unread}</span>
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
{#if data.session && (data.deviceChildIds?.length || 0) > 0}
|
||||||
|
<button
|
||||||
|
class="kid-switch"
|
||||||
|
onclick={() => (pickerOpen = true)}
|
||||||
|
aria-label="Switch user (shared device)"
|
||||||
|
title="Switch user"
|
||||||
|
>
|
||||||
|
<span class="kid-switch-dot" style="background:{data.session.memberColor || '#6366f1'}"
|
||||||
|
></span>
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</TopNav>
|
||||||
|
<main class="app-main" class:join-page={page.url.pathname.split('/')[2] === 'join'}>
|
||||||
|
<div class="page-wrap">
|
||||||
|
<div class="page-content" class:locked>{@render children()}</div>
|
||||||
|
|
||||||
|
{#if locked}
|
||||||
|
<div class="disabled-overlay">
|
||||||
|
<div class="disabled-card">
|
||||||
|
{#if !hasAuth}
|
||||||
|
<h2>You need to be logged in to view this page</h2>
|
||||||
|
{:else if activating}
|
||||||
|
<div class="spinner" aria-hidden="true"></div>
|
||||||
|
<strong>Activating your subscription…</strong>
|
||||||
|
<span>Payment received — this usually only takes a few seconds.</span>
|
||||||
|
{:else}
|
||||||
|
<strong>Access paused</strong>
|
||||||
|
<span>
|
||||||
|
{isParent
|
||||||
|
? 'Add an access code or resume your subscription to keep using FamDone.'
|
||||||
|
: 'Your family access is paused.'}
|
||||||
|
</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
{#if claimToast}
|
||||||
|
<a
|
||||||
|
class="claim-toast"
|
||||||
|
href={`/${page.params.fam}/${data.session?.username || page.params.username || ''}`}
|
||||||
|
>
|
||||||
|
{claimToast} — view dashboard →
|
||||||
|
</a>
|
||||||
|
{/if}
|
||||||
|
<Footer sidebar />
|
||||||
|
</div>
|
||||||
|
{#if chatStore.open}
|
||||||
|
<button class="chat-backdrop" onclick={() => chatStore.closeChat()} aria-label="Close chat"
|
||||||
|
></button>
|
||||||
|
{/if}
|
||||||
|
<Chat {role} />
|
||||||
|
{#if pickerOpen && deviceProfiles.length > 0}
|
||||||
|
<SharedPicker
|
||||||
|
profiles={deviceProfiles}
|
||||||
|
activeId={data.session?.userId}
|
||||||
|
famSlug={data.famSlug}
|
||||||
|
oncancel={() => (pickerOpen = false)}
|
||||||
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
<Footer sidebar />
|
|
||||||
</div>
|
</div>
|
||||||
{#if chatStore.open}
|
{/if}
|
||||||
<button class="chat-backdrop" onclick={() => chatStore.closeChat()} aria-label="Close chat"
|
|
||||||
></button>
|
|
||||||
{/if}
|
|
||||||
<Chat {role} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.claim-toast {
|
.claim-toast {
|
||||||
@@ -402,6 +469,33 @@
|
|||||||
justify-content: center;
|
justify-content: center;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
.kid-switch {
|
||||||
|
position: relative;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: #f3f4f6;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.kid-switch:hover {
|
||||||
|
background: #e5e7eb;
|
||||||
|
}
|
||||||
|
.kid-switch-dot {
|
||||||
|
width: 22px;
|
||||||
|
height: 22px;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 2px solid #fff;
|
||||||
|
box-shadow: 0 0 0 1px #e2e8f0;
|
||||||
|
}
|
||||||
|
.picker-stage {
|
||||||
|
min-height: 100vh;
|
||||||
|
width: 100%;
|
||||||
|
background: whitesmoke;
|
||||||
|
}
|
||||||
.chat-toggle:hover {
|
.chat-toggle:hover {
|
||||||
background: #e5e7eb;
|
background: #e5e7eb;
|
||||||
color: #4338ca;
|
color: #4338ca;
|
||||||
|
|||||||
@@ -70,12 +70,13 @@ export async function load(event) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const pbToken = event.cookies.get('pb_token') || '';
|
const pbToken = event.locals.pbToken || '';
|
||||||
const famId = session?.famId || '';
|
const famId = session?.famId || '';
|
||||||
// When a demo parent visits a child's route, session.id is the parent's PB
|
// When a demo parent visits a child's route, session.id is the parent's PB
|
||||||
// record. Look up the actual child user by username so chores load correctly.
|
// record. Look up the actual child user by username so chores load correctly.
|
||||||
const childId = demoParentVisitingChild
|
const childId = demoParentVisitingChild
|
||||||
? (await pbAdmin.getList('users', `famId='${famId}' && username='${famSlug}:${username}'`))?.[0]?.id || ''
|
? (await pbAdmin.getList('users', `famId='${famId}' && username='${famSlug}:${username}'`))?.[0]
|
||||||
|
?.id || ''
|
||||||
: session?.id || '';
|
: session?.id || '';
|
||||||
|
|
||||||
const empty = {
|
const empty = {
|
||||||
@@ -183,4 +184,4 @@ export const actions = {
|
|||||||
return { error: e instanceof Error ? e.message : 'Failed to trigger' };
|
return { error: e instanceof Error ? e.message : 'Failed to trigger' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { redirect } from '@sveltejs/kit';
|
import { redirect } from '@sveltejs/kit';
|
||||||
import { servicesFor } from '$lib/server/servicesFor';
|
import { servicesFor } from '$lib/server/servicesFor';
|
||||||
import { getPlatformFlags } from '$lib/server/platform';
|
import { getPlatformFlags } from '$lib/server/platform';
|
||||||
|
import { hasPin } from '$lib/server/pins';
|
||||||
|
|
||||||
async function isDemoMode(): Promise<boolean> {
|
async function isDemoMode(): Promise<boolean> {
|
||||||
return (await getPlatformFlags()).demo;
|
return (await getPlatformFlags()).demo;
|
||||||
@@ -8,7 +9,20 @@ async function isDemoMode(): Promise<boolean> {
|
|||||||
|
|
||||||
export async function load(event) {
|
export async function load(event) {
|
||||||
if (await isDemoMode()) {
|
if (await isDemoMode()) {
|
||||||
return { verified: false, role: '', token: '', memberId: '', famId: '', memberName: '', memberColor: '', pattern: '', themeSize: '', themeOpacity: '', email: '', demoMode: true };
|
return {
|
||||||
|
verified: false,
|
||||||
|
role: '',
|
||||||
|
token: '',
|
||||||
|
memberId: '',
|
||||||
|
famId: '',
|
||||||
|
memberName: '',
|
||||||
|
memberColor: '',
|
||||||
|
pattern: '',
|
||||||
|
themeSize: '',
|
||||||
|
themeOpacity: '',
|
||||||
|
email: '',
|
||||||
|
demoMode: true
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const session = event.locals.user;
|
const session = event.locals.user;
|
||||||
@@ -50,6 +64,7 @@ export async function load(event) {
|
|||||||
themeSize: me.themeSize || '',
|
themeSize: me.themeSize || '',
|
||||||
themeOpacity: me.themeOpacity || '',
|
themeOpacity: me.themeOpacity || '',
|
||||||
email: me.email || '',
|
email: me.email || '',
|
||||||
|
hasPin: false,
|
||||||
session: true
|
session: true
|
||||||
};
|
};
|
||||||
} catch {
|
} catch {
|
||||||
@@ -61,7 +76,8 @@ export async function load(event) {
|
|||||||
famId: '',
|
famId: '',
|
||||||
memberName: '',
|
memberName: '',
|
||||||
memberColor: '',
|
memberColor: '',
|
||||||
email: ''
|
email: '',
|
||||||
|
hasPin: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -70,7 +86,7 @@ export async function load(event) {
|
|||||||
return {
|
return {
|
||||||
verified: true,
|
verified: true,
|
||||||
role: 'child',
|
role: 'child',
|
||||||
token: event.cookies.get('pb_token') || '',
|
token: event.locals.pbToken || '',
|
||||||
memberId: session.id,
|
memberId: session.id,
|
||||||
famId,
|
famId,
|
||||||
memberName: session.name || '',
|
memberName: session.name || '',
|
||||||
@@ -79,6 +95,7 @@ export async function load(event) {
|
|||||||
themeSize: session.themeSize || '',
|
themeSize: session.themeSize || '',
|
||||||
themeOpacity: session.themeOpacity || '',
|
themeOpacity: session.themeOpacity || '',
|
||||||
email: '',
|
email: '',
|
||||||
|
hasPin: await hasPin(session.id).catch(() => false),
|
||||||
session: true
|
session: true
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,50 @@
|
|||||||
|
|
||||||
let { data, form } = $props();
|
let { data, form } = $props();
|
||||||
|
|
||||||
|
let pinMsg = $state('');
|
||||||
|
|
||||||
|
async function pinRequest(action: 'set' | 'change', pin: string, currentPin = '') {
|
||||||
|
pinMsg = '';
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/pins', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ action, pin, currentPin })
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(data.error || 'Could not save PIN');
|
||||||
|
pinMsg = 'Saved — try it on the shared computer!';
|
||||||
|
await invalidateAll();
|
||||||
|
} catch (e) {
|
||||||
|
pinMsg = e instanceof Error ? e.message : 'Could not save PIN';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPin(e: SubmitEvent) {
|
||||||
|
const fd = new FormData(e.currentTarget as HTMLFormElement);
|
||||||
|
const pin = String(fd.get('pin') || '').trim();
|
||||||
|
const confirm = String(fd.get('confirm') || '').trim();
|
||||||
|
e.preventDefault();
|
||||||
|
if (pin !== confirm) {
|
||||||
|
pinMsg = 'PINs do not match';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pinRequest('set', pin);
|
||||||
|
}
|
||||||
|
|
||||||
|
function changePin(e: SubmitEvent) {
|
||||||
|
const fd = new FormData(e.currentTarget as HTMLFormElement);
|
||||||
|
const current = String(fd.get('current') || '').trim();
|
||||||
|
const pin = String(fd.get('pin') || '').trim();
|
||||||
|
const confirm = String(fd.get('confirm') || '').trim();
|
||||||
|
e.preventDefault();
|
||||||
|
if (pin !== confirm) {
|
||||||
|
pinMsg = 'PINs do not match';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pinRequest('change', pin, current);
|
||||||
|
}
|
||||||
|
|
||||||
let memberName = $state(data.memberName || '');
|
let memberName = $state(data.memberName || '');
|
||||||
let memberColor = $state(data.memberColor || '#6366f1');
|
let memberColor = $state(data.memberColor || '#6366f1');
|
||||||
let memberEmail = $state(data.email || '');
|
let memberEmail = $state(data.email || '');
|
||||||
@@ -160,6 +204,70 @@
|
|||||||
</Card>
|
</Card>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
{#if data.role === 'child'}
|
||||||
|
<Card cols={1} title="My PIN">
|
||||||
|
{#if data.hasPin}
|
||||||
|
<p class="theme-hint">
|
||||||
|
Your 3-digit PIN switches you back to your chores on a shared computer. Forgot it? Your
|
||||||
|
parent can read it out — Settings → Invites → PIN.
|
||||||
|
</p>
|
||||||
|
<form class="pin-form" onsubmit={changePin}>
|
||||||
|
<input
|
||||||
|
name="current"
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="3"
|
||||||
|
required
|
||||||
|
placeholder="Current PIN"
|
||||||
|
class="pin-input"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
name="pin"
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="3"
|
||||||
|
required
|
||||||
|
placeholder="New PIN"
|
||||||
|
class="pin-input"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
name="confirm"
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="3"
|
||||||
|
required
|
||||||
|
placeholder="Confirm"
|
||||||
|
class="pin-input"
|
||||||
|
/>
|
||||||
|
<Button type="submit" size="sm">Change PIN</Button>
|
||||||
|
</form>
|
||||||
|
{:else}
|
||||||
|
<p class="theme-hint">
|
||||||
|
Set a 3-digit PIN so you can switch back to your chores quickly on a shared computer.
|
||||||
|
</p>
|
||||||
|
<form class="pin-form" onsubmit={setPin}>
|
||||||
|
<input
|
||||||
|
name="pin"
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="3"
|
||||||
|
required
|
||||||
|
placeholder="Your PIN"
|
||||||
|
class="pin-input"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
name="confirm"
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="3"
|
||||||
|
required
|
||||||
|
placeholder="Confirm"
|
||||||
|
class="pin-input"
|
||||||
|
/>
|
||||||
|
<Button type="submit" size="sm">Set PIN</Button>
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
{#if pinMsg}
|
||||||
|
<p class="pin-msg">{pinMsg}</p>
|
||||||
|
{/if}
|
||||||
|
</Card>
|
||||||
|
{/if}
|
||||||
|
|
||||||
<Card cols={1} title="Account">
|
<Card cols={1} title="Account">
|
||||||
<p style="font-size:0.85rem;color:#6b7280">
|
<p style="font-size:0.85rem;color:#6b7280">
|
||||||
To change your device or sign in on a new device, use your invite link.
|
To change your device or sign in on a new device, use your invite link.
|
||||||
@@ -182,4 +290,25 @@
|
|||||||
color: #6b7280;
|
color: #6b7280;
|
||||||
margin: 0 0 0.75rem;
|
margin: 0 0 0.75rem;
|
||||||
}
|
}
|
||||||
|
.pin-form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
.pin-input {
|
||||||
|
padding: 0.5rem;
|
||||||
|
border: 1px solid #d1d5db;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
width: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
|
text-align: center;
|
||||||
|
letter-spacing: 0.3em;
|
||||||
|
}
|
||||||
|
.pin-msg {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #059669;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { sendParentInviteEmail } from '$lib/server/email';
|
|||||||
import { slugify, handle, famUsername } from '@shared/slugify';
|
import { slugify, handle, famUsername } from '@shared/slugify';
|
||||||
import { applyAccessCode } from '$lib/server/access';
|
import { applyAccessCode } from '$lib/server/access';
|
||||||
import { getPlatformFlags } from '$lib/server/platform';
|
import { getPlatformFlags } from '$lib/server/platform';
|
||||||
|
import { getPin, resetPin as resetChildPin } from '$lib/server/pins';
|
||||||
import {
|
import {
|
||||||
createBillingPortalSession,
|
createBillingPortalSession,
|
||||||
cancelSubscriptionAtPeriodEnd,
|
cancelSubscriptionAtPeriodEnd,
|
||||||
@@ -26,7 +27,15 @@ async function isDemoMode(): Promise<boolean> {
|
|||||||
|
|
||||||
export async function load(event: RequestEvent) {
|
export async function load(event: RequestEvent) {
|
||||||
if (await isDemoMode()) {
|
if (await isDemoMode()) {
|
||||||
return { members: [], fam: null, seasons: [], accessCode: null, subStatus: null, demoMode: true };
|
return {
|
||||||
|
members: [],
|
||||||
|
fam: null,
|
||||||
|
seasons: [],
|
||||||
|
accessCode: null,
|
||||||
|
subStatus: null,
|
||||||
|
demoMode: true,
|
||||||
|
lockMins: 10
|
||||||
|
};
|
||||||
}
|
}
|
||||||
const famId = famIdOf(event);
|
const famId = famIdOf(event);
|
||||||
const pb = pbUser(event);
|
const pb = pbUser(event);
|
||||||
@@ -48,7 +57,13 @@ export async function load(event: RequestEvent) {
|
|||||||
if (fam?.paymentMode === 'sub' && fam?.stripeCustomerId) {
|
if (fam?.paymentMode === 'sub' && fam?.stripeCustomerId) {
|
||||||
subStatus = await getSubscriptionStatus(fam.stripeCustomerId).catch(() => null);
|
subStatus = await getSubscriptionStatus(fam.stripeCustomerId).catch(() => null);
|
||||||
}
|
}
|
||||||
return { members, fam, seasons, accessCode, subStatus };
|
// Shared-device idle lock (0 = off). Missing row → default 10 min.
|
||||||
|
const settingsRow = await pbAdmin
|
||||||
|
.getList('settings', `famId='${famId}'`)
|
||||||
|
.then((rows: any[]) => rows?.[0] || null)
|
||||||
|
.catch(() => null);
|
||||||
|
const lockMins = settingsRow && settingsRow.lockMins != null ? Number(settingsRow.lockMins) : 10;
|
||||||
|
return { members, fam, seasons, accessCode, subStatus, lockMins };
|
||||||
}
|
}
|
||||||
|
|
||||||
export const actions = {
|
export const actions = {
|
||||||
@@ -159,6 +174,59 @@ export const actions = {
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Parent reads a child's shared-device PIN (children forget theirs often).
|
||||||
|
revealPin: async (event: RequestEvent) => {
|
||||||
|
const famId = famIdOf(event);
|
||||||
|
const fd = await event.request.formData();
|
||||||
|
const id = (fd.get('id') || '').toString();
|
||||||
|
if (!id) return { error: 'Member ID required' };
|
||||||
|
try {
|
||||||
|
const member = await pbAdmin.getOne('users', id).catch(() => null);
|
||||||
|
if (!member || member.famId !== famId) return { error: 'No such member' };
|
||||||
|
const pin = await getPin(id);
|
||||||
|
if (!pin) return { ok: true, pin: '', name: member.name || '', unset: true };
|
||||||
|
return { ok: true, pin, name: member.name || '' };
|
||||||
|
} catch (e) {
|
||||||
|
return { error: e instanceof Error ? e.message : 'Failed to reveal PIN' };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// Parent hands out a fresh PIN when a child forgets theirs.
|
||||||
|
resetPin: async (event: RequestEvent) => {
|
||||||
|
const famId = famIdOf(event);
|
||||||
|
const fd = await event.request.formData();
|
||||||
|
const id = (fd.get('id') || '').toString();
|
||||||
|
if (!id) return { error: 'Member ID required' };
|
||||||
|
try {
|
||||||
|
const member = await pbAdmin.getOne('users', id).catch(() => null);
|
||||||
|
if (!member || member.famId !== famId) return { error: 'No such member' };
|
||||||
|
const pin = await resetChildPin(famId, id);
|
||||||
|
return { ok: true, pin, name: member.name || '' };
|
||||||
|
} catch (e) {
|
||||||
|
return { error: e instanceof Error ? e.message : 'Failed to reset PIN' };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// Shared-computer idle lock: off / 2 / 10 minutes before returning to the
|
||||||
|
// profile picker (children only). Missing settings row → created.
|
||||||
|
updateLock: async (event: RequestEvent) => {
|
||||||
|
const famId = famIdOf(event);
|
||||||
|
const fd = await event.request.formData();
|
||||||
|
const mins = parseInt((fd.get('mins') || '').toString(), 10);
|
||||||
|
if (![0, 2, 10].includes(mins)) return { error: 'Invalid value' };
|
||||||
|
const pb = await createSuperClient();
|
||||||
|
let row = await pb
|
||||||
|
.collection('settings')
|
||||||
|
.getFirstListItem(`famId='${famId}'`)
|
||||||
|
.catch(() => null);
|
||||||
|
if (row) {
|
||||||
|
await pb.collection('settings').update(row.id, { lockMins: mins });
|
||||||
|
} else {
|
||||||
|
await pb.collection('settings').create({ famId, lockMins: mins });
|
||||||
|
}
|
||||||
|
return { ok: true, lockMins: mins };
|
||||||
|
},
|
||||||
|
|
||||||
updatePayday: async (event: RequestEvent) => {
|
updatePayday: async (event: RequestEvent) => {
|
||||||
const famId = famIdOf(event);
|
const famId = famIdOf(event);
|
||||||
const fd = await event.request.formData();
|
const fd = await event.request.formData();
|
||||||
|
|||||||
@@ -89,6 +89,8 @@
|
|||||||
let members = $derived(famStore.initialized ? famStore.members : data.members || []);
|
let members = $derived(famStore.initialized ? famStore.members : data.members || []);
|
||||||
let deletingSeason = $state<any>(null);
|
let deletingSeason = $state<any>(null);
|
||||||
let issueModal = $state<{ otp: string; joinUrl: string; name: string } | null>(null);
|
let issueModal = $state<{ otp: string; joinUrl: string; name: string } | null>(null);
|
||||||
|
let pinModal = $state<{ id: string; name: string; pin: string; unset?: boolean } | null>(null);
|
||||||
|
let lockMins = $state(String(data.lockMins ?? 10));
|
||||||
let seasonColor = $state('#6366f1');
|
let seasonColor = $state('#6366f1');
|
||||||
const seasonColors = [
|
const seasonColors = [
|
||||||
'#6366f1',
|
'#6366f1',
|
||||||
@@ -363,6 +365,32 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
<Card title="Shared computer" cols={1}>
|
||||||
|
<p class="hint">
|
||||||
|
If kids share this computer, FamDone returns to the profile picker after a break so nobody
|
||||||
|
lands on the wrong chores. Children pick a 3-digit PIN when they join.
|
||||||
|
</p>
|
||||||
|
<form
|
||||||
|
method="POST"
|
||||||
|
action="?/updateLock"
|
||||||
|
use:enhance={() => {
|
||||||
|
return async ({ result }) => {
|
||||||
|
if (result.type !== 'success') return;
|
||||||
|
const d = result.data as any;
|
||||||
|
if (d?.ok) lockMins = String(d.lockMins);
|
||||||
|
else if (d?.error) alert(d.error);
|
||||||
|
};
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<select name="mins" bind:value={lockMins}>
|
||||||
|
<option value="0">Off — keep the last profile</option>
|
||||||
|
<option value="2">After 2 minutes of no use</option>
|
||||||
|
<option value="10">After 10 minutes of no use</option>
|
||||||
|
</select>
|
||||||
|
<Button type="submit" size="sm">Save</Button>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
</CardGrid>
|
</CardGrid>
|
||||||
</AccordionItem>
|
</AccordionItem>
|
||||||
|
|
||||||
@@ -478,6 +506,32 @@
|
|||||||
<span class="member-handle">/{famSlug}/{handleOf(m.username)}</span>
|
<span class="member-handle">/{famSlug}/{handleOf(m.username)}</span>
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
|
<form
|
||||||
|
method="POST"
|
||||||
|
action="?/revealPin"
|
||||||
|
use:enhance={() => {
|
||||||
|
return async ({ formData, result }) => {
|
||||||
|
if (result.type !== 'success') return;
|
||||||
|
const d = result.data as any;
|
||||||
|
if (d?.ok) {
|
||||||
|
pinModal = {
|
||||||
|
id: String(formData.get('id') || ''),
|
||||||
|
name: d.name || m.name,
|
||||||
|
pin: d.pin || '',
|
||||||
|
unset: !!d.unset
|
||||||
|
};
|
||||||
|
} else if (d?.error) {
|
||||||
|
alert(d.error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}}
|
||||||
|
class="inline"
|
||||||
|
>
|
||||||
|
<input type="hidden" name="id" value={m.id} />
|
||||||
|
<Button type="submit" variant="ghost" size="sm" title="Shared-computer PIN"
|
||||||
|
>PIN</Button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
<form method="POST" action="?/deleteMember" use:enhance class="inline">
|
<form method="POST" action="?/deleteMember" use:enhance class="inline">
|
||||||
<input type="hidden" name="id" value={m.id} />
|
<input type="hidden" name="id" value={m.id} />
|
||||||
<Button
|
<Button
|
||||||
@@ -492,6 +546,58 @@
|
|||||||
</ul>
|
</ul>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{#if pinModal}
|
||||||
|
<div class="overlay" onclick={() => (pinModal = null)} role="presentation">
|
||||||
|
<div class="modal" onclick={(e) => e.stopPropagation()} role="dialog">
|
||||||
|
<h3>{pinModal.name}'s PIN</h3>
|
||||||
|
{#if pinModal.unset}
|
||||||
|
<p class="hint">
|
||||||
|
No PIN set yet. Set one so {pinModal.name} can pick their profile on a shared computer.
|
||||||
|
</p>
|
||||||
|
<form
|
||||||
|
method="POST"
|
||||||
|
action="?/resetPin"
|
||||||
|
use:enhance={() => {
|
||||||
|
return async ({ result }) => {
|
||||||
|
if (result.type !== 'success') return;
|
||||||
|
const d = result.data as any;
|
||||||
|
if (d?.ok) pinModal = { ...pinModal!, pin: d.pin, unset: false };
|
||||||
|
else if (d?.error) alert(d.error);
|
||||||
|
};
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input type="hidden" name="id" value={pinModal.id} />
|
||||||
|
<Button type="submit" size="sm" variant="primary">Set a new PIN</Button>
|
||||||
|
</form>
|
||||||
|
{:else}
|
||||||
|
<p class="code-display">{pinModal.pin}</p>
|
||||||
|
<p class="hint">
|
||||||
|
Read it out if they've forgotten. They can change it themselves in Preferences.
|
||||||
|
</p>
|
||||||
|
<form
|
||||||
|
method="POST"
|
||||||
|
action="?/resetPin"
|
||||||
|
use:enhance={() => {
|
||||||
|
return async ({ result }) => {
|
||||||
|
if (result.type !== 'success') return;
|
||||||
|
const d = result.data as any;
|
||||||
|
if (d?.ok) pinModal = { ...pinModal!, pin: d.pin, unset: false };
|
||||||
|
else if (d?.error) alert(d.error);
|
||||||
|
};
|
||||||
|
}}
|
||||||
|
class="inline"
|
||||||
|
>
|
||||||
|
<input type="hidden" name="id" value={pinModal.id} />
|
||||||
|
<Button type="submit" size="sm" variant="secondary">Give a new PIN</Button>
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button type="button" onclick={() => (pinModal = null)}>Close</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
<Card title="Invite Parent" cols={1}>
|
<Card title="Invite Parent" cols={1}>
|
||||||
<p class="hint">Send an email invitation for another parent to join as an admin.</p>
|
<p class="hint">Send an email invitation for another parent to join as an admin.</p>
|
||||||
<form
|
<form
|
||||||
@@ -1162,6 +1268,8 @@
|
|||||||
margin-top: 0.5rem;
|
margin-top: 0.5rem;
|
||||||
}
|
}
|
||||||
@media (max-width: 639px) {
|
@media (max-width: 639px) {
|
||||||
.code-display { font-size: 1.5em; }
|
.code-display {
|
||||||
|
font-size: 1.5em;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import { fail, redirect } from '@sveltejs/kit';
|
import { fail } from '@sveltejs/kit';
|
||||||
import { redeemOtp } from '$lib/server/member-otp';
|
import { redeemOtp } from '$lib/server/member-otp';
|
||||||
import { handle } from '@shared/slugify';
|
import { handle } from '@shared/slugify';
|
||||||
import { setSessionCookie, clearLegacyCookies } from '$lib/server/session';
|
import {
|
||||||
|
clearLegacyCookies,
|
||||||
|
setChildSessionCookie,
|
||||||
|
setActiveChild,
|
||||||
|
scanChildSessions
|
||||||
|
} from '$lib/server/session';
|
||||||
|
|
||||||
export const actions = {
|
export const actions = {
|
||||||
default: async (event) => {
|
default: async (event) => {
|
||||||
@@ -14,11 +19,14 @@ export const actions = {
|
|||||||
if (!otp) return fail(400, { error: 'Enter the code shown by your parent.', name, otp });
|
if (!otp) return fail(400, { error: 'Enter the code shown by your parent.', name, otp });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// redeemOtp derives the username from the handle internally; pass the
|
// Children join onto a shared-device session (pb_token_<id> +
|
||||||
// raw name so it resolves the same {famSlug}:{handle} identity.
|
// pb_active) so siblings' sessions on this computer survive.
|
||||||
const token = await redeemOtp({ famSlug: fam, username: name, otp });
|
const { token, userId } = await redeemOtp({ famSlug: fam, username: name, otp });
|
||||||
clearLegacyCookies(event.cookies);
|
clearLegacyCookies(event.cookies);
|
||||||
setSessionCookie(event.cookies, token);
|
setChildSessionCookie(event.cookies, userId, token);
|
||||||
|
setActiveChild(event.cookies, userId);
|
||||||
|
const hasOtherKids = scanChildSessions(event.cookies).length > 1;
|
||||||
|
return { joined: true, famSlug: fam, username: handle(name), hasOtherKids };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return fail(400, {
|
return fail(400, {
|
||||||
error: e instanceof Error ? e.message : 'Join failed',
|
error: e instanceof Error ? e.message : 'Join failed',
|
||||||
@@ -26,8 +34,5 @@ export const actions = {
|
|||||||
otp
|
otp
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleName = handle(name);
|
|
||||||
throw redirect(303, `/${fam}/${encodeURIComponent(handleName)}`);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
import { enhance } from '$app/forms';
|
import { enhance } from '$app/forms';
|
||||||
import { Button } from '$lib/components';
|
import { Button, JoinPinFlow } from '$lib/components';
|
||||||
import { homeIcon } from '$lib/components/icons';
|
import { homeIcon } from '$lib/components/icons';
|
||||||
|
|
||||||
const famSlug = page.params.fam;
|
const famSlug = page.params.fam;
|
||||||
let name = $state('');
|
let name = $state('');
|
||||||
let otp = $state(page.url.searchParams.get('code') || '');
|
let otp = $state(page.url.searchParams.get('code') || '');
|
||||||
|
let joined = $state<{ username: string; hasOtherKids: boolean } | null>(null);
|
||||||
let { form } = $props();
|
let { form } = $props();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -19,51 +20,66 @@
|
|||||||
>
|
>
|
||||||
<span class="home-badge">{@html homeIcon}</span>
|
<span class="home-badge">{@html homeIcon}</span>
|
||||||
</div>
|
</div>
|
||||||
<h1 class="text-xl font-bold text-slate-900">Join {famSlug}</h1>
|
|
||||||
<p class="mt-1 text-sm text-slate-500">
|
|
||||||
Enter your name and the code your parent gave you to get started.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<form
|
{#if joined}
|
||||||
class="mt-6 flex flex-col gap-3"
|
<JoinPinFlow
|
||||||
method="POST"
|
targetUrl={`/${famSlug}/${encodeURIComponent(joined.username)}`}
|
||||||
use:enhance={() => {
|
force={joined.hasOtherKids}
|
||||||
return async ({ result, update }) => {
|
|
||||||
if (result.type === 'failure') {
|
|
||||||
name = (result.data as any)?.name || '';
|
|
||||||
otp = (result.data as any)?.otp || '';
|
|
||||||
}
|
|
||||||
await update();
|
|
||||||
};
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
name="name"
|
|
||||||
bind:value={name}
|
|
||||||
placeholder="Your name"
|
|
||||||
autocomplete="name"
|
|
||||||
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-lg text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
|
||||||
/>
|
/>
|
||||||
<input
|
{:else}
|
||||||
type="text"
|
<h1 class="text-xl font-bold text-slate-900">Join {famSlug}</h1>
|
||||||
name="otp"
|
<p class="mt-1 text-sm text-slate-500">
|
||||||
bind:value={otp}
|
Enter your name and the code your parent gave you to get started.
|
||||||
inputmode="numeric"
|
</p>
|
||||||
maxlength="6"
|
|
||||||
placeholder="6-digit code"
|
|
||||||
autocomplete="one-time-code"
|
|
||||||
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-lg tracking-[0.5em] text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
|
||||||
/>
|
|
||||||
{#if form?.error}
|
|
||||||
<p class="text-sm font-medium text-rose-600">{form.error}</p>
|
|
||||||
{/if}
|
|
||||||
<Button type="submit" variant="primary" size="lg">Join</Button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<p class="mt-6 text-xs text-slate-400">
|
<form
|
||||||
Code is valid for 20 minutes. Ask your parent for a new one if it expires.
|
class="mt-6 flex flex-col gap-3"
|
||||||
</p>
|
method="POST"
|
||||||
|
use:enhance={() => {
|
||||||
|
return async ({ result, update }) => {
|
||||||
|
if (result.type === 'failure') {
|
||||||
|
name = (result.data as any)?.name || '';
|
||||||
|
otp = (result.data as any)?.otp || '';
|
||||||
|
await update();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const d = (result as any).data;
|
||||||
|
if (d?.joined) {
|
||||||
|
joined = { username: d.username, hasOtherKids: !!d.hasOtherKids };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await update();
|
||||||
|
};
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="name"
|
||||||
|
bind:value={name}
|
||||||
|
placeholder="Your name"
|
||||||
|
autocomplete="name"
|
||||||
|
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-lg text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="otp"
|
||||||
|
bind:value={otp}
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="6"
|
||||||
|
placeholder="6-digit code"
|
||||||
|
autocomplete="one-time-code"
|
||||||
|
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-lg tracking-[0.5em] text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
||||||
|
/>
|
||||||
|
{#if form?.error}
|
||||||
|
<p class="text-sm font-medium text-rose-600">{form.error}</p>
|
||||||
|
{/if}
|
||||||
|
<Button type="submit" variant="primary" size="lg">Join</Button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="mt-6 text-xs text-slate-400">
|
||||||
|
Code is valid for 20 minutes. Ask your parent for a new one if it expires.
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
import { fail, redirect } from '@sveltejs/kit';
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
import { redeemOtp, redeemParentOtp } from '$lib/server/member-otp';
|
import { redeemOtp, redeemParentOtp } from '$lib/server/member-otp';
|
||||||
import { createSuperClient } from '$lib/server/pocketbase';
|
import { createSuperClient } from '$lib/server/pocketbase';
|
||||||
import { setSessionCookie, clearLegacyCookies } from '$lib/server/session';
|
import {
|
||||||
|
setSessionCookie,
|
||||||
|
clearLegacyCookies,
|
||||||
|
setChildSessionCookie,
|
||||||
|
setActiveChild,
|
||||||
|
scanChildSessions,
|
||||||
|
clearActiveChild
|
||||||
|
} from '$lib/server/session';
|
||||||
import { famUsername, handle } from '@shared/slugify';
|
import { famUsername, handle } from '@shared/slugify';
|
||||||
|
|
||||||
export async function load(event) {
|
export async function load(event) {
|
||||||
@@ -58,15 +65,25 @@ export const actions = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = isParent
|
if (isParent) {
|
||||||
? await redeemParentOtp({ famSlug: fam, username, otp, password })
|
const token = await redeemParentOtp({ famSlug: fam, username, otp, password });
|
||||||
: await redeemOtp({ famSlug: fam, username, otp });
|
clearLegacyCookies(event.cookies);
|
||||||
|
setSessionCookie(event.cookies, token);
|
||||||
|
// A parent join supersedes kid mode on a shared device.
|
||||||
|
clearActiveChild(event.cookies);
|
||||||
|
throw redirect(303, `/${fam}/${encodeURIComponent(username)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Child: shared-device session (pb_token_<id> + pb_active) so
|
||||||
|
// siblings' sessions on this computer survive.
|
||||||
|
const { token, userId } = await redeemOtp({ famSlug: fam, username, otp });
|
||||||
clearLegacyCookies(event.cookies);
|
clearLegacyCookies(event.cookies);
|
||||||
setSessionCookie(event.cookies, token);
|
setChildSessionCookie(event.cookies, userId, token);
|
||||||
|
setActiveChild(event.cookies, userId);
|
||||||
|
const hasOtherKids = scanChildSessions(event.cookies).length > 1;
|
||||||
|
return { joined: true, famSlug: fam, username, hasOtherKids };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return fail(400, { error: e instanceof Error ? e.message : 'Join failed' });
|
return fail(400, { error: e instanceof Error ? e.message : 'Join failed' });
|
||||||
}
|
}
|
||||||
|
|
||||||
throw redirect(303, `/${fam}/${encodeURIComponent(username)}`);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
import { enhance } from '$app/forms';
|
import { enhance } from '$app/forms';
|
||||||
import { Button } from '$lib/components';
|
import { Button, JoinPinFlow } from '$lib/components';
|
||||||
import { homeIcon } from '$lib/components/icons';
|
import { homeIcon } from '$lib/components/icons';
|
||||||
|
|
||||||
const famSlug = page.params.fam;
|
const famSlug = page.params.fam;
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
let otp = $state(page.url.searchParams.get('code') || '');
|
let otp = $state(page.url.searchParams.get('code') || '');
|
||||||
let password = $state('');
|
let password = $state('');
|
||||||
let confirmPassword = $state('');
|
let confirmPassword = $state('');
|
||||||
|
let joined = $state<{ hasOtherKids: boolean } | null>(null);
|
||||||
let { data, form } = $props();
|
let { data, form } = $props();
|
||||||
|
|
||||||
const isParent = $derived(data?.isParent);
|
const isParent = $derived(data?.isParent);
|
||||||
@@ -24,73 +25,88 @@
|
|||||||
>
|
>
|
||||||
<span class="home-badge">{@html homeIcon}</span>
|
<span class="home-badge">{@html homeIcon}</span>
|
||||||
</div>
|
</div>
|
||||||
{#if isParent}
|
{#if joined}
|
||||||
<h1 class="text-xl font-bold text-slate-900">Join {famSlug}</h1>
|
<JoinPinFlow
|
||||||
<p class="mt-1 text-sm text-slate-500">
|
targetUrl={`/${famSlug}/${encodeURIComponent(username || '')}`}
|
||||||
Hi <span class="font-semibold text-slate-700">{username}</span> — enter the code from your
|
force={joined.hasOtherKids}
|
||||||
email and create a password to join <strong>{famName}</strong> as a parent.
|
/>
|
||||||
</p>
|
|
||||||
{:else}
|
{:else}
|
||||||
<h1 class="text-xl font-bold text-slate-900">Welcome to {famSlug}!</h1>
|
{#if isParent}
|
||||||
<p class="mt-1 text-sm text-slate-500">
|
<h1 class="text-xl font-bold text-slate-900">Join {famSlug}</h1>
|
||||||
Hi <span class="font-semibold text-slate-700">{username}</span> — enter the code your parent gave
|
<p class="mt-1 text-sm text-slate-500">
|
||||||
you to get started.
|
Hi <span class="font-semibold text-slate-700">{username}</span> — enter the code from your
|
||||||
|
email and create a password to join <strong>{famName}</strong> as a parent.
|
||||||
|
</p>
|
||||||
|
{:else}
|
||||||
|
<h1 class="text-xl font-bold text-slate-900">Welcome to {famSlug}!</h1>
|
||||||
|
<p class="mt-1 text-sm text-slate-500">
|
||||||
|
Hi <span class="font-semibold text-slate-700">{username}</span> — enter the code your parent
|
||||||
|
gave you to get started.
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<form
|
||||||
|
class="mt-6 flex flex-col gap-3"
|
||||||
|
method="POST"
|
||||||
|
use:enhance={() => {
|
||||||
|
return async ({ result, update }) => {
|
||||||
|
if (result.type === 'failure') {
|
||||||
|
otp = (result as any).data?.otp || '';
|
||||||
|
await update();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const d = (result as any).data;
|
||||||
|
if (d?.joined) {
|
||||||
|
joined = { hasOtherKids: !!d.hasOtherKids };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Parent joins redirect server-side (303) — nothing to do here.
|
||||||
|
await update();
|
||||||
|
};
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="otp"
|
||||||
|
bind:value={otp}
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="6"
|
||||||
|
placeholder="6-digit code"
|
||||||
|
autocomplete="one-time-code"
|
||||||
|
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-lg tracking-[0.5em] text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
||||||
|
/>
|
||||||
|
{#if isParent}
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
name="password"
|
||||||
|
bind:value={password}
|
||||||
|
placeholder="Create a password"
|
||||||
|
autocomplete="new-password"
|
||||||
|
minlength="10"
|
||||||
|
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
name="confirmPassword"
|
||||||
|
bind:value={confirmPassword}
|
||||||
|
placeholder="Confirm password"
|
||||||
|
autocomplete="new-password"
|
||||||
|
minlength="10"
|
||||||
|
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
||||||
|
/>
|
||||||
|
{/if}
|
||||||
|
{#if form?.error}
|
||||||
|
<p class="text-sm font-medium text-rose-600">{form.error}</p>
|
||||||
|
{/if}
|
||||||
|
<Button type="submit" variant="primary" size="lg"
|
||||||
|
>{isParent ? 'Set up my account' : 'Join'}</Button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="mt-6 text-xs text-slate-400">
|
||||||
|
Code is valid for 20 minutes. Ask your parent for a new one if it expires.
|
||||||
</p>
|
</p>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<form
|
|
||||||
class="mt-6 flex flex-col gap-3"
|
|
||||||
method="POST"
|
|
||||||
use:enhance={() => {
|
|
||||||
return async ({ result, update }) => {
|
|
||||||
if (result.type === 'failure') {
|
|
||||||
otp = (result.data as any)?.otp || '';
|
|
||||||
}
|
|
||||||
await update();
|
|
||||||
};
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
name="otp"
|
|
||||||
bind:value={otp}
|
|
||||||
inputmode="numeric"
|
|
||||||
maxlength="6"
|
|
||||||
placeholder="6-digit code"
|
|
||||||
autocomplete="one-time-code"
|
|
||||||
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-lg tracking-[0.5em] text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
|
||||||
/>
|
|
||||||
{#if isParent}
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
name="password"
|
|
||||||
bind:value={password}
|
|
||||||
placeholder="Create a password"
|
|
||||||
autocomplete="new-password"
|
|
||||||
minlength="10"
|
|
||||||
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
name="confirmPassword"
|
|
||||||
bind:value={confirmPassword}
|
|
||||||
placeholder="Confirm password"
|
|
||||||
autocomplete="new-password"
|
|
||||||
minlength="10"
|
|
||||||
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
|
||||||
/>
|
|
||||||
{/if}
|
|
||||||
{#if form?.error}
|
|
||||||
<p class="text-sm font-medium text-rose-600">{form.error}</p>
|
|
||||||
{/if}
|
|
||||||
<Button type="submit" variant="primary" size="lg"
|
|
||||||
>{isParent ? 'Set up my account' : 'Join'}</Button
|
|
||||||
>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<p class="mt-6 text-xs text-slate-400">
|
|
||||||
Code is valid for 20 minutes. Ask your parent for a new one if it expires.
|
|
||||||
</p>
|
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import { fail, redirect } from '@sveltejs/kit';
|
import { fail } from '@sveltejs/kit';
|
||||||
import { redeemOtp } from '$lib/server/member-otp';
|
import { redeemOtp } from '$lib/server/member-otp';
|
||||||
import { slugify, handle } from '@shared/slugify';
|
import { slugify, handle } from '@shared/slugify';
|
||||||
import { setSessionCookie, clearLegacyCookies } from '$lib/server/session';
|
import {
|
||||||
|
clearLegacyCookies,
|
||||||
|
setChildSessionCookie,
|
||||||
|
setActiveChild,
|
||||||
|
scanChildSessions
|
||||||
|
} from '$lib/server/session';
|
||||||
|
|
||||||
export const actions = {
|
export const actions = {
|
||||||
default: async (event) => {
|
default: async (event) => {
|
||||||
@@ -12,13 +17,19 @@ export const actions = {
|
|||||||
|
|
||||||
if (!famName) return fail(400, { error: 'Enter your family name.', famName, name, otp });
|
if (!famName) return fail(400, { error: 'Enter your family name.', famName, name, otp });
|
||||||
if (!name) return fail(400, { error: 'Enter your name.', famName, name, otp });
|
if (!name) return fail(400, { error: 'Enter your name.', famName, name, otp });
|
||||||
if (!otp) return fail(400, { error: 'Enter the code shown by your parent.', famName, name, otp });
|
if (!otp)
|
||||||
|
return fail(400, { error: 'Enter the code shown by your parent.', famName, name, otp });
|
||||||
|
|
||||||
const famSlug = slugify(famName);
|
const famSlug = slugify(famName);
|
||||||
try {
|
try {
|
||||||
const token = await redeemOtp({ famSlug, username: name, otp });
|
// Children join onto a shared-device session (pb_token_<id> +
|
||||||
|
// pb_active) so siblings' sessions on this computer survive.
|
||||||
|
const { token, userId } = await redeemOtp({ famSlug, username: name, otp });
|
||||||
clearLegacyCookies(event.cookies);
|
clearLegacyCookies(event.cookies);
|
||||||
setSessionCookie(event.cookies, token);
|
setChildSessionCookie(event.cookies, userId, token);
|
||||||
|
setActiveChild(event.cookies, userId);
|
||||||
|
const hasOtherKids = scanChildSessions(event.cookies).length > 1;
|
||||||
|
return { joined: true, famSlug, username: handle(name), hasOtherKids };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return fail(400, {
|
return fail(400, {
|
||||||
error: e instanceof Error ? e.message : 'Join failed',
|
error: e instanceof Error ? e.message : 'Join failed',
|
||||||
@@ -27,8 +38,5 @@ export const actions = {
|
|||||||
otp
|
otp
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleName = handle(name);
|
|
||||||
throw redirect(303, `/${famSlug}/${encodeURIComponent(handleName)}`);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { enhance } from '$app/forms';
|
import { enhance } from '$app/forms';
|
||||||
import { Button } from '$lib/components';
|
import { Button, JoinPinFlow } from '$lib/components';
|
||||||
import { homeIcon } from '$lib/components/icons';
|
import { homeIcon } from '$lib/components/icons';
|
||||||
|
|
||||||
let name = $state('');
|
let name = $state('');
|
||||||
let family = $state('');
|
let family = $state('');
|
||||||
let otp = $state('');
|
let otp = $state('');
|
||||||
|
let joined = $state<{ famSlug: string; username: string; hasOtherKids: boolean } | null>(null);
|
||||||
let { form } = $props();
|
let { form } = $props();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -13,63 +14,84 @@
|
|||||||
|
|
||||||
<main class="mx-auto flex min-h-screen max-w-md flex-col items-center justify-center px-6">
|
<main class="mx-auto flex min-h-screen max-w-md flex-col items-center justify-center px-6">
|
||||||
<section class="w-full rounded-2xl border border-slate-200 bg-white p-8 text-center shadow-sm">
|
<section class="w-full rounded-2xl border border-slate-200 bg-white p-8 text-center shadow-sm">
|
||||||
<div class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-indigo-100 text-2xl">
|
<div
|
||||||
|
class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-indigo-100 text-2xl"
|
||||||
|
>
|
||||||
<span class="home-badge">{@html homeIcon}</span>
|
<span class="home-badge">{@html homeIcon}</span>
|
||||||
</div>
|
</div>
|
||||||
<h1 class="text-xl font-bold text-slate-900">Join the family</h1>
|
|
||||||
<p class="mt-1 text-sm text-slate-500">
|
|
||||||
Enter your family name and the code your parent gave you to get started.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<form
|
{#if joined}
|
||||||
class="mt-6 flex flex-col gap-3"
|
<JoinPinFlow
|
||||||
method="POST"
|
targetUrl={`/${joined.famSlug}/${encodeURIComponent(joined.username)}`}
|
||||||
use:enhance={() => {
|
force={joined.hasOtherKids}
|
||||||
return async ({ result, update }) => {
|
|
||||||
if (result.type === 'failure') {
|
|
||||||
family = (result.data as any)?.family || '';
|
|
||||||
name = (result.data as any)?.name || '';
|
|
||||||
otp = (result.data as any)?.otp || '';
|
|
||||||
}
|
|
||||||
await update();
|
|
||||||
};
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
name="family"
|
|
||||||
bind:value={family}
|
|
||||||
placeholder="Family name"
|
|
||||||
autocomplete="organization"
|
|
||||||
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-lg text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
|
||||||
/>
|
/>
|
||||||
<input
|
{:else}
|
||||||
type="text"
|
<h1 class="text-xl font-bold text-slate-900">Join the family</h1>
|
||||||
name="name"
|
<p class="mt-1 text-sm text-slate-500">
|
||||||
bind:value={name}
|
Enter your family name and the code your parent gave you to get started.
|
||||||
placeholder="Your name"
|
</p>
|
||||||
autocomplete="name"
|
|
||||||
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-lg text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
name="otp"
|
|
||||||
bind:value={otp}
|
|
||||||
inputmode="numeric"
|
|
||||||
maxlength="6"
|
|
||||||
placeholder="6-digit code"
|
|
||||||
autocomplete="one-time-code"
|
|
||||||
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-2xl tracking-[0.5em] text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
|
||||||
/>
|
|
||||||
{#if form?.error}
|
|
||||||
<p class="text-sm font-medium text-rose-600">{form.error}</p>
|
|
||||||
{/if}
|
|
||||||
<Button type="submit" variant="primary" size="lg">Join</Button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<p class="mt-6 text-xs text-slate-400">
|
<form
|
||||||
Code is valid for 20 minutes. Ask your parent for a new one if it expires.
|
class="mt-6 flex flex-col gap-3"
|
||||||
</p>
|
method="POST"
|
||||||
|
use:enhance={() => {
|
||||||
|
return async ({ result, update }) => {
|
||||||
|
if (result.type === 'failure') {
|
||||||
|
family = (result.data as any)?.family || '';
|
||||||
|
name = (result.data as any)?.name || '';
|
||||||
|
otp = (result.data as any)?.otp || '';
|
||||||
|
await update();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const d = (result as any).data;
|
||||||
|
if (d?.joined) {
|
||||||
|
joined = {
|
||||||
|
famSlug: d.famSlug,
|
||||||
|
username: d.username,
|
||||||
|
hasOtherKids: !!d.hasOtherKids
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await update();
|
||||||
|
};
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="family"
|
||||||
|
bind:value={family}
|
||||||
|
placeholder="Family name"
|
||||||
|
autocomplete="organization"
|
||||||
|
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-lg text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="name"
|
||||||
|
bind:value={name}
|
||||||
|
placeholder="Your name"
|
||||||
|
autocomplete="name"
|
||||||
|
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-lg text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="otp"
|
||||||
|
bind:value={otp}
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="6"
|
||||||
|
placeholder="6-digit code"
|
||||||
|
autocomplete="one-time-code"
|
||||||
|
class="w-full rounded-lg border border-slate-300 px-4 py-3 text-center text-2xl tracking-[0.5em] text-slate-900 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
|
||||||
|
/>
|
||||||
|
{#if form?.error}
|
||||||
|
<p class="text-sm font-medium text-rose-600">{form.error}</p>
|
||||||
|
{/if}
|
||||||
|
<Button type="submit" variant="primary" size="lg">Join</Button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="mt-6 text-xs text-slate-400">
|
||||||
|
Code is valid for 20 minutes. Ask your parent for a new one if it expires.
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { fail, redirect } from '@sveltejs/kit';
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
import { createPbClient } from '$lib/server/pocketbase';
|
import { createPbClient } from '$lib/server/pocketbase';
|
||||||
import { setSessionCookie } from '$lib/server/session';
|
import { setSessionCookie, clearActiveChild } from '$lib/server/session';
|
||||||
import { pbAdmin } from '$lib/server/pocketbase';
|
import { pbAdmin } from '$lib/server/pocketbase';
|
||||||
import { handleOf } from '@shared/slugify';
|
import { handleOf } from '@shared/slugify';
|
||||||
|
|
||||||
@@ -27,6 +27,8 @@ export const actions = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setSessionCookie(event.cookies, authResult.token);
|
setSessionCookie(event.cookies, authResult.token);
|
||||||
|
// An explicit email/password login supersedes kid mode on a shared device.
|
||||||
|
clearActiveChild(event.cookies);
|
||||||
|
|
||||||
const fam = await pbAdmin.getOne('fams', user.famId).catch(() => null);
|
const fam = await pbAdmin.getOne('fams', user.famId).catch(() => null);
|
||||||
const famSlug = fam?.slug || user.famId;
|
const famSlug = fam?.slug || user.famId;
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { redirect } from '@sveltejs/kit';
|
import { redirect } from '@sveltejs/kit';
|
||||||
import { clearSessionCookie, clearLegacyCookies } from '$lib/server/session';
|
import { clearSessionCookie, clearLegacyCookies, clearDeviceSessions } from '$lib/server/session';
|
||||||
|
|
||||||
function signOut(event: { cookies: any }) {
|
function signOut(event: { cookies: any }) {
|
||||||
clearSessionCookie(event.cookies);
|
clearSessionCookie(event.cookies);
|
||||||
clearLegacyCookies(event.cookies);
|
clearLegacyCookies(event.cookies);
|
||||||
|
// Shared device: also drop every child session + the active pointer.
|
||||||
|
clearDeviceSessions(event.cookies);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const actions = {
|
export const actions = {
|
||||||
|
|||||||
+252
-188
@@ -61,11 +61,19 @@ export function jsonField(name: string): FieldDef {
|
|||||||
return { name, type: "json" };
|
return { name, type: "json" };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function select(name: string, values: string[], required = false): FieldDef {
|
export function select(
|
||||||
|
name: string,
|
||||||
|
values: string[],
|
||||||
|
required = false,
|
||||||
|
): FieldDef {
|
||||||
return { name, type: "select", required, values, maxSelect: 1 };
|
return { name, type: "select", required, values, maxSelect: 1 };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function rel(name: string, collectionId: string, required = false): FieldDef {
|
export function rel(
|
||||||
|
name: string,
|
||||||
|
collectionId: string,
|
||||||
|
required = false,
|
||||||
|
): FieldDef {
|
||||||
return {
|
return {
|
||||||
name,
|
name,
|
||||||
type: "relation",
|
type: "relation",
|
||||||
@@ -151,236 +159,292 @@ export const SCHEMA_PLAN: CollectionPlanEntry[] = [
|
|||||||
text("accessCodeId"),
|
text("accessCodeId"),
|
||||||
date("accessCodeEnteredAt"),
|
date("accessCodeEnteredAt"),
|
||||||
],
|
],
|
||||||
{ listRule: RULE_OWN_FAM, viewRule: RULE_OWN_FAM, updateRule: RULE_OWN_FAM },
|
{
|
||||||
|
listRule: RULE_OWN_FAM,
|
||||||
|
viewRule: RULE_OWN_FAM,
|
||||||
|
updateRule: RULE_OWN_FAM,
|
||||||
|
},
|
||||||
)(ids),
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "bonus_templates",
|
name: "bonus_templates",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("bonus_templates", [
|
col(
|
||||||
rel("famId", ids.fams, false),
|
"bonus_templates",
|
||||||
text("name", true),
|
[
|
||||||
text("description"),
|
rel("famId", ids.fams, false),
|
||||||
select("target", ["individual", "competitive", "collaborative"], true),
|
text("name", true),
|
||||||
select("type", ["threshold", "count", "manual"], true),
|
text("description"),
|
||||||
select("thresholdType", ["points", "percent"], false),
|
select(
|
||||||
select("occurrence", ["recurring", "once"], true),
|
"target",
|
||||||
select("rewardType", ["points", "cash", "prize"], true),
|
["individual", "competitive", "collaborative"],
|
||||||
text("rewardValue", false),
|
true,
|
||||||
number("criteriaValue"),
|
),
|
||||||
select("period", ["schedule", "daily", "weekly", "monthly"]),
|
select("type", ["threshold", "count", "manual"], true),
|
||||||
bool("isPocketMoney"),
|
select("thresholdType", ["points", "percent"], false),
|
||||||
bool("global"),
|
select("occurrence", ["recurring", "once"], true),
|
||||||
text("icon"),
|
select("rewardType", ["points", "cash", "prize"], true),
|
||||||
text("color"),
|
text("rewardValue", false),
|
||||||
], {
|
number("criteriaValue"),
|
||||||
listRule: "global = true || famId = @request.auth.famId",
|
select("period", ["schedule", "daily", "weekly", "monthly"]),
|
||||||
viewRule: "global = true || famId = @request.auth.famId",
|
bool("isPocketMoney"),
|
||||||
createRule: RULE_PARENT_WRITE,
|
bool("global"),
|
||||||
updateRule: RULE_PARENT_SCOPED,
|
text("icon"),
|
||||||
deleteRule: RULE_PARENT_SCOPED,
|
text("color"),
|
||||||
})(ids),
|
],
|
||||||
|
{
|
||||||
|
listRule: "global = true || famId = @request.auth.famId",
|
||||||
|
viewRule: "global = true || famId = @request.auth.famId",
|
||||||
|
createRule: RULE_PARENT_WRITE,
|
||||||
|
updateRule: RULE_PARENT_SCOPED,
|
||||||
|
deleteRule: RULE_PARENT_SCOPED,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "settings",
|
name: "settings",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("settings", [rel("famId", ids.fams, true), text("webhookUrl")], {
|
col(
|
||||||
createRule: RULE_PARENT_WRITE,
|
"settings",
|
||||||
updateRule: RULE_PARENT_SCOPED,
|
[rel("famId", ids.fams, true), text("webhookUrl"), number("lockMins")],
|
||||||
deleteRule: RULE_PARENT_SCOPED,
|
{
|
||||||
})(ids),
|
createRule: RULE_PARENT_WRITE,
|
||||||
|
updateRule: RULE_PARENT_SCOPED,
|
||||||
|
deleteRule: RULE_PARENT_SCOPED,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "chore_templates",
|
name: "chore_templates",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("chore_templates", [
|
col(
|
||||||
rel("famId", ids.fams, false),
|
"chore_templates",
|
||||||
text("name", true),
|
[
|
||||||
text("description"),
|
rel("famId", ids.fams, false),
|
||||||
select("defaultFrequency", ["daily", "weekly"], true),
|
text("name", true),
|
||||||
select("defaultType", ["points", "money"], true),
|
text("description"),
|
||||||
number("defaultValue", true),
|
select("defaultFrequency", ["daily", "weekly"], true),
|
||||||
bool("global"),
|
select("defaultType", ["points", "money"], true),
|
||||||
text("icon"),
|
number("defaultValue", true),
|
||||||
text("color"),
|
bool("global"),
|
||||||
], {
|
text("icon"),
|
||||||
listRule: "global = true || famId = @request.auth.famId",
|
text("color"),
|
||||||
viewRule: "global = true || famId = @request.auth.famId",
|
],
|
||||||
createRule: RULE_PARENT_WRITE,
|
{
|
||||||
updateRule: RULE_PARENT_SCOPED,
|
listRule: "global = true || famId = @request.auth.famId",
|
||||||
deleteRule: RULE_PARENT_SCOPED,
|
viewRule: "global = true || famId = @request.auth.famId",
|
||||||
})(ids),
|
createRule: RULE_PARENT_WRITE,
|
||||||
|
updateRule: RULE_PARENT_SCOPED,
|
||||||
|
deleteRule: RULE_PARENT_SCOPED,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "bonus_configs",
|
name: "bonus_configs",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("bonus_configs", [
|
col(
|
||||||
rel("famId", ids.fams, true),
|
"bonus_configs",
|
||||||
text("name", true),
|
[
|
||||||
text("description"),
|
rel("famId", ids.fams, true),
|
||||||
select("target", ["individual", "competitive", "collaborative"], true),
|
text("name", true),
|
||||||
select("type", ["threshold", "count", "manual"], true),
|
text("description"),
|
||||||
select("thresholdType", ["points", "percent"], false),
|
select(
|
||||||
select("occurrence", ["recurring", "once"], true),
|
"target",
|
||||||
select("rewardType", ["points", "cash", "prize"], true),
|
["individual", "competitive", "collaborative"],
|
||||||
text("rewardValue", false),
|
true,
|
||||||
number("criteriaValue"),
|
),
|
||||||
rel("memberId", ids.users),
|
select("type", ["threshold", "count", "manual"], true),
|
||||||
select("period", ["schedule", "daily", "weekly", "monthly"]),
|
select("thresholdType", ["points", "percent"], false),
|
||||||
select("status", ["active", "completed"], true),
|
select("occurrence", ["recurring", "once"], true),
|
||||||
text("targetChoreId"),
|
select("rewardType", ["points", "cash", "prize"], true),
|
||||||
jsonField("targetChoreIds"),
|
text("rewardValue", false),
|
||||||
bool("isPocketMoney"),
|
number("criteriaValue"),
|
||||||
// Standalone/one-off reward progress window. `period` stays empty for
|
rel("memberId", ids.users),
|
||||||
// these (they're measured once, not per-cycle). `completeBy` bounds how
|
select("period", ["schedule", "daily", "weekly", "monthly"]),
|
||||||
// far progress counts: `unlimited` (cumulative since startDate),
|
select("status", ["active", "completed"], true),
|
||||||
// `week` (end of current week), or `custom` (a specific completeByDate).
|
text("targetChoreId"),
|
||||||
// `startDate` is when tracking begins — without it "unlimited" would
|
jsonField("targetChoreIds"),
|
||||||
// count points earned before the reward existed.
|
bool("isPocketMoney"),
|
||||||
select("completeBy", ["unlimited", "week", "custom"]),
|
// Standalone/one-off reward progress window. `period` stays empty for
|
||||||
text("startDate"),
|
// these (they're measured once, not per-cycle). `completeBy` bounds how
|
||||||
text("completeByDate"),
|
// far progress counts: `unlimited` (cumulative since startDate),
|
||||||
], {
|
// `week` (end of current week), or `custom` (a specific completeByDate).
|
||||||
createRule: RULE_PARENT_WRITE,
|
// `startDate` is when tracking begins — without it "unlimited" would
|
||||||
updateRule: RULE_PARENT_SCOPED,
|
// count points earned before the reward existed.
|
||||||
deleteRule: RULE_PARENT_SCOPED,
|
select("completeBy", ["unlimited", "week", "custom"]),
|
||||||
})(ids),
|
text("startDate"),
|
||||||
|
text("completeByDate"),
|
||||||
|
],
|
||||||
|
{
|
||||||
|
createRule: RULE_PARENT_WRITE,
|
||||||
|
updateRule: RULE_PARENT_SCOPED,
|
||||||
|
deleteRule: RULE_PARENT_SCOPED,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "weekly_history",
|
name: "weekly_history",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("weekly_history", [
|
col(
|
||||||
rel("famId", ids.fams, true),
|
"weekly_history",
|
||||||
rel("memberId", ids.users, true),
|
[
|
||||||
date("weekStart"),
|
rel("famId", ids.fams, true),
|
||||||
number("pointsEarned"),
|
rel("memberId", ids.users, true),
|
||||||
number("moneyEarned"),
|
date("weekStart"),
|
||||||
number("choresCompleted"),
|
number("pointsEarned"),
|
||||||
number("bonusEarned"),
|
number("moneyEarned"),
|
||||||
], {
|
number("choresCompleted"),
|
||||||
createRule: RULE_PARENT_WRITE,
|
number("bonusEarned"),
|
||||||
updateRule: RULE_PARENT_SCOPED,
|
],
|
||||||
deleteRule: RULE_PARENT_SCOPED,
|
{
|
||||||
})(ids),
|
createRule: RULE_PARENT_WRITE,
|
||||||
|
updateRule: RULE_PARENT_SCOPED,
|
||||||
|
deleteRule: RULE_PARENT_SCOPED,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "seasons",
|
name: "seasons",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("seasons", [
|
col(
|
||||||
rel("famId", ids.fams, true),
|
"seasons",
|
||||||
text("name", true),
|
[
|
||||||
text("color"),
|
rel("famId", ids.fams, true),
|
||||||
bool("active"),
|
text("name", true),
|
||||||
date("autoDisable"),
|
text("color"),
|
||||||
date("autoStart"),
|
bool("active"),
|
||||||
], {
|
date("autoDisable"),
|
||||||
createRule: RULE_PARENT_WRITE,
|
date("autoStart"),
|
||||||
updateRule: RULE_PARENT_SCOPED,
|
],
|
||||||
deleteRule: RULE_PARENT_SCOPED,
|
{
|
||||||
})(ids),
|
createRule: RULE_PARENT_WRITE,
|
||||||
|
updateRule: RULE_PARENT_SCOPED,
|
||||||
|
deleteRule: RULE_PARENT_SCOPED,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "messages",
|
name: "messages",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("messages", [
|
col(
|
||||||
rel("famId", ids.fams, true),
|
"messages",
|
||||||
select("authorType", ["admin", "member"], true),
|
[
|
||||||
text("authorId", true),
|
rel("famId", ids.fams, true),
|
||||||
text("authorName", true),
|
select("authorType", ["admin", "member"], true),
|
||||||
text("authorColor"),
|
text("authorId", true),
|
||||||
text("content", true),
|
text("authorName", true),
|
||||||
// Explicit createdAt: PB 0.39 does NOT auto-add createdAt to
|
text("authorColor"),
|
||||||
// API-created collections (0.25 did). Chat filters/sorts on it.
|
text("content", true),
|
||||||
date("createdAt"),
|
// Explicit createdAt: PB 0.39 does NOT auto-add createdAt to
|
||||||
text("clientId"),
|
// API-created collections (0.25 did). Chat filters/sorts on it.
|
||||||
], {
|
date("createdAt"),
|
||||||
createRule: RULE_FAM_WRITE,
|
text("clientId"),
|
||||||
updateRule: RULE_FAM_SCOPED,
|
],
|
||||||
deleteRule: RULE_FAM_SCOPED,
|
{
|
||||||
listRule: RULE_FAM_READ,
|
createRule: RULE_FAM_WRITE,
|
||||||
viewRule: RULE_FAM_READ,
|
updateRule: RULE_FAM_SCOPED,
|
||||||
})(ids),
|
deleteRule: RULE_FAM_SCOPED,
|
||||||
|
listRule: RULE_FAM_READ,
|
||||||
|
viewRule: RULE_FAM_READ,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "chat_typing",
|
name: "chat_typing",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("chat_typing", [
|
col(
|
||||||
rel("famId", ids.fams, true),
|
"chat_typing",
|
||||||
text("actorId", true),
|
[
|
||||||
select("actorType", ["admin", "member"], true),
|
rel("famId", ids.fams, true),
|
||||||
text("authorName", true),
|
text("actorId", true),
|
||||||
text("authorColor"),
|
select("actorType", ["admin", "member"], true),
|
||||||
bool("typing"),
|
text("authorName", true),
|
||||||
], {
|
text("authorColor"),
|
||||||
createRule: RULE_FAM_WRITE,
|
bool("typing"),
|
||||||
updateRule: RULE_FAM_SCOPED,
|
],
|
||||||
deleteRule: RULE_FAM_SCOPED,
|
{
|
||||||
listRule: RULE_FAM_READ,
|
createRule: RULE_FAM_WRITE,
|
||||||
viewRule: RULE_FAM_READ,
|
updateRule: RULE_FAM_SCOPED,
|
||||||
})(ids),
|
deleteRule: RULE_FAM_SCOPED,
|
||||||
|
listRule: RULE_FAM_READ,
|
||||||
|
viewRule: RULE_FAM_READ,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "rewards",
|
name: "rewards",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("rewards", [
|
col(
|
||||||
rel("famId", ids.fams, true),
|
"rewards",
|
||||||
rel("memberId", ids.users, true),
|
[
|
||||||
rel("bonusConfigId", ids.bonus_configs),
|
rel("famId", ids.fams, true),
|
||||||
text("label", true),
|
rel("memberId", ids.users, true),
|
||||||
number("value", true),
|
rel("bonusConfigId", ids.bonus_configs),
|
||||||
select("rewardType", ["cash", "prize", "points"], true),
|
text("label", true),
|
||||||
select("status", ["unclaimed", "requested", "claimed"], true),
|
number("value", true),
|
||||||
select("claimable", ["immediate", "payday"], false),
|
select("rewardType", ["cash", "prize", "points"], true),
|
||||||
text("settleDate"),
|
select("status", ["unclaimed", "requested", "claimed"], true),
|
||||||
date("claimedAt"),
|
select("claimable", ["immediate", "payday"], false),
|
||||||
date("requestedAt"),
|
text("settleDate"),
|
||||||
text("date"),
|
date("claimedAt"),
|
||||||
], {
|
date("requestedAt"),
|
||||||
createRule: RULE_FAM_WRITE,
|
text("date"),
|
||||||
updateRule: RULE_FAM_SCOPED,
|
],
|
||||||
deleteRule: RULE_FAM_SCOPED,
|
{
|
||||||
})(ids),
|
createRule: RULE_FAM_WRITE,
|
||||||
|
updateRule: RULE_FAM_SCOPED,
|
||||||
|
deleteRule: RULE_FAM_SCOPED,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "assigned_chores",
|
name: "assigned_chores",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("assigned_chores", [
|
col(
|
||||||
rel("famId", ids.fams, true),
|
"assigned_chores",
|
||||||
rel("memberId", ids.users, false), // null = shared with all members
|
[
|
||||||
bool("shared"), // true = initially shared (tracked for revoke)
|
rel("famId", ids.fams, true),
|
||||||
rel("templateId", ids.chore_templates),
|
rel("memberId", ids.users, false), // null = shared with all members
|
||||||
select("frequency", ["daily", "weekly"], true),
|
bool("shared"), // true = initially shared (tracked for revoke)
|
||||||
select("type", ["points", "money", "emoji"], true),
|
rel("templateId", ids.chore_templates),
|
||||||
number("value", false),
|
select("frequency", ["daily", "weekly"], true),
|
||||||
text("customName"),
|
select("type", ["points", "money", "emoji"], true),
|
||||||
text("description"),
|
number("value", false),
|
||||||
text("icon"),
|
text("customName"),
|
||||||
text("color"),
|
text("description"),
|
||||||
text("emoji"),
|
text("icon"),
|
||||||
jsonField("seasonIds"),
|
text("color"),
|
||||||
bool("isTodo"),
|
text("emoji"),
|
||||||
text("startDate"),
|
jsonField("seasonIds"),
|
||||||
text("completeBy"),
|
bool("isTodo"),
|
||||||
], {
|
text("startDate"),
|
||||||
createRule: RULE_PARENT_WRITE,
|
text("completeBy"),
|
||||||
updateRule: RULE_PARENT_SCOPED,
|
],
|
||||||
deleteRule: RULE_PARENT_SCOPED,
|
{
|
||||||
})(ids),
|
createRule: RULE_PARENT_WRITE,
|
||||||
|
updateRule: RULE_PARENT_SCOPED,
|
||||||
|
deleteRule: RULE_PARENT_SCOPED,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "completions",
|
name: "completions",
|
||||||
build: (ids) =>
|
build: (ids) =>
|
||||||
col("completions", [
|
col(
|
||||||
rel("famId", ids.fams, true),
|
"completions",
|
||||||
rel("memberId", ids.users, true),
|
[
|
||||||
rel("assignedChoreId", ids.assigned_chores, true),
|
rel("famId", ids.fams, true),
|
||||||
date("date"),
|
rel("memberId", ids.users, true),
|
||||||
date("completedAt"),
|
rel("assignedChoreId", ids.assigned_chores, true),
|
||||||
text("rewardId"),
|
date("date"),
|
||||||
], {
|
date("completedAt"),
|
||||||
createRule: RULE_FAM_WRITE,
|
text("rewardId"),
|
||||||
updateRule: RULE_FAM_SCOPED,
|
],
|
||||||
deleteRule: RULE_FAM_SCOPED,
|
{
|
||||||
})(ids),
|
createRule: RULE_FAM_WRITE,
|
||||||
|
updateRule: RULE_FAM_SCOPED,
|
||||||
|
deleteRule: RULE_FAM_SCOPED,
|
||||||
|
},
|
||||||
|
)(ids),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
Reference in New Issue
Block a user