make major bonus updates
This commit is contained in:
@@ -18,10 +18,10 @@
|
|||||||
|
|
||||||
## Auth
|
## Auth
|
||||||
|
|
||||||
| Role | Auth | Session | Record in |
|
| Role | Auth | Session | Record in |
|
||||||
| ---------------- | -------------------------- | --------------------------- | -------------------- |
|
| -------------- | -------------------------- | -------------------------- | ------------ |
|
||||||
| Admin (parent) | PB email+pass | 24hr JWT | `fam_admins` |
|
| Admin (parent) | PB email+pass | 24hr JWT | `fam_admins` |
|
||||||
| Member (child) | Invite code + device token | `device_token` cookie only | `members` |
|
| Member (child) | Invite code + device token | `device_token` cookie only | `members` |
|
||||||
|
|
||||||
- **Admins** (parents) have a PB auth record + `fam_admins` record. They authenticate via email/password login, get a session cookie (`session`) with `{ famId, userId, famSlug, memberName, role: "parent" }`.
|
- **Admins** (parents) have a PB auth record + `fam_admins` record. They authenticate via email/password login, get a session cookie (`session`) with `{ famId, userId, famSlug, memberName, role: "parent" }`.
|
||||||
- **Members** (children) exist only in the `members` collection. They authenticate via invite code + device token (SHA-256 hashed). The `device_token` cookie is set on join; no session cookie.
|
- **Members** (children) exist only in the `members` collection. They authenticate via invite code + device token (SHA-256 hashed). The `device_token` cookie is set on join; no session cookie.
|
||||||
@@ -61,11 +61,13 @@
|
|||||||
## Data Flow
|
## Data Flow
|
||||||
|
|
||||||
### Reads (both roles)
|
### Reads (both roles)
|
||||||
|
|
||||||
- **Parent (admin):** `famStore.init()` fetches all collections via PB SDK (authenticated via `pb_token` cookie).
|
- **Parent (admin):** `famStore.init()` fetches all collections via PB SDK (authenticated via `pb_token` cookie).
|
||||||
- **Child (member):** `famStore.init()` fetches all collections via PB SDK — **unauthenticated/anonymous**. All family-scoped collections have public `listRule` / `viewRule` (empty string = allow all), so reads work without any auth. PB SDK `.subscribe()` also works anonymously for public collections.
|
- **Child (member):** `famStore.init()` fetches all collections via PB SDK — **unauthenticated/anonymous**. All family-scoped collections have public `listRule` / `viewRule` (empty string = allow all), so reads work without any auth. PB SDK `.subscribe()` also works anonymously for public collections.
|
||||||
- **TopNav season pills:** Read from `famStore.seasons` — reactive, no extra fetches needed.
|
- **TopNav season pills:** Read from `famStore.seasons` — reactive, no extra fetches needed.
|
||||||
|
|
||||||
### Writes (both roles go through Hono proxy)
|
### Writes (both roles go through Hono proxy)
|
||||||
|
|
||||||
- **Chore toggle:** Browser → Hono proxy → PB (auth via device token or admin JWT)
|
- **Chore toggle:** Browser → Hono proxy → PB (auth via device token or admin JWT)
|
||||||
- **Admin CRUD:** Form actions → Hono proxy → PB (admin JWT via `sessionHeaders`)
|
- **Admin CRUD:** Form actions → Hono proxy → PB (admin JWT via `sessionHeaders`)
|
||||||
- **Member updates:** Browser → Hono proxy → PB (auth via `x-device-token` + `x-device-famid`)
|
- **Member updates:** Browser → Hono proxy → PB (auth via `x-device-token` + `x-device-famid`)
|
||||||
@@ -75,6 +77,7 @@
|
|||||||
- **WhatsApp:** Deferred — Hono CRON handler has pluggable notification interface
|
- **WhatsApp:** Deferred — Hono CRON handler has pluggable notification interface
|
||||||
|
|
||||||
### UI reactivity
|
### UI reactivity
|
||||||
|
|
||||||
- Svelte `$state` / `$derived` / `$effect`
|
- Svelte `$state` / `$derived` / `$effect`
|
||||||
- PB SDK `.subscribe()` for realtime multi-user sync (public reads → works for both roles)
|
- PB SDK `.subscribe()` for realtime multi-user sync (public reads → works for both roles)
|
||||||
- `famStore.applyRecord()` for instant optimistic UI feedback from form actions
|
- `famStore.applyRecord()` for instant optimistic UI feedback from form actions
|
||||||
@@ -84,15 +87,16 @@
|
|||||||
Env vars must be declared in `frontend/src/env.ts` using `defineEnvVars` from `@sveltejs/kit/hooks`:
|
Env vars must be declared in `frontend/src/env.ts` using `defineEnvVars` from `@sveltejs/kit/hooks`:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { defineEnvVars } from '@sveltejs/kit/hooks';
|
import { defineEnvVars } from "@sveltejs/kit/hooks";
|
||||||
export const variables = defineEnvVars({
|
export const variables = defineEnvVars({
|
||||||
DEBUG_RECORD_ID: {},
|
DEBUG_RECORD_ID: {},
|
||||||
SERVER_IP: {public: true},
|
SERVER_IP: { public: true },
|
||||||
PB_PORT: {public: true}
|
PB_PORT: { public: true },
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
Only vars with `{public: true}` are exposed to client-side code via `$app/env/public`. If you need a new client-side env var (e.g., `PUBLIC_PB_URL`), you must:
|
Only vars with `{public: true}` are exposed to client-side code via `$app/env/public`. If you need a new client-side env var (e.g., `PUBLIC_PB_URL`), you must:
|
||||||
|
|
||||||
1. Add it to `.env` with `PUBLIC_` prefix
|
1. Add it to `.env` with `PUBLIC_` prefix
|
||||||
2. Add it to `frontend/src/env.ts` with `{public: true}`
|
2. Add it to `frontend/src/env.ts` with `{public: true}`
|
||||||
|
|
||||||
@@ -101,6 +105,7 @@ The actual values come from `.env` (symlinked from project root at `frontend/.en
|
|||||||
## ⚠️ CRITICAL: Reactivity Pattern (NEVER use `$effect` to sync from famStore)
|
## ⚠️ CRITICAL: Reactivity Pattern (NEVER use `$effect` to sync from famStore)
|
||||||
|
|
||||||
**Do NOT do this:**
|
**Do NOT do this:**
|
||||||
|
|
||||||
```svelte
|
```svelte
|
||||||
<!-- ❌ WRONG: $effect syncing local state from famStore fights Svelte reactivity -->
|
<!-- ❌ WRONG: $effect syncing local state from famStore fights Svelte reactivity -->
|
||||||
let items = $state(data.items);
|
let items = $state(data.items);
|
||||||
@@ -111,21 +116,45 @@ $effect(() => {
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Do this instead:**
|
**Do this instead:**
|
||||||
|
|
||||||
```svelte
|
```svelte
|
||||||
<!-- ✅ RIGHT: Initialize from famStore, mutate via applyRecord in callbacks -->
|
<!-- ✅ RIGHT: Initialize from famStore, mutate via applyRecord in callbacks -->
|
||||||
let items = $state(famStore.initialized ? famStore.items : (data.items || []));
|
let items = $state(famStore.initialized ? famStore.items : (data.items || []));
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### ⚠️ CRITICAL: `$state` vs `$derived` for famStore collections
|
||||||
|
|
||||||
|
**When a page reads data that should update via SSE (realtime from other users/actions), you MUST use `$derived` — NOT `$state`.**
|
||||||
|
|
||||||
|
This is the most commonly missed rule. Agents repeatedly initialize collections from `famStore` with `$state`, which captures a **frozen snapshot** at init time. When PocketBase pushes a record via SSE → `famStore.applyRecord()`, the `$state` variable never reacts — the UI stays stale until a page refresh.
|
||||||
|
|
||||||
|
**Rule: if the data should update without a refresh, use `$derived`.**
|
||||||
|
|
||||||
|
```svelte
|
||||||
|
// ❌ WRONG — frozen snapshot, won't react to SSE updates
|
||||||
|
let configs = $state(famStore.initialized ? famStore.bonusConfigs : data.configs);
|
||||||
|
|
||||||
|
// ✅ RIGHT — reactive, updates when famStore changes via SSE
|
||||||
|
let configs = $derived(
|
||||||
|
famStore.initialized ? famStore.bonusConfigs : (data.configs || [])
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
**The only exception:** high-frequency member actions (like chore toggles) that need **optimistic UI** before the server responds. Those use `$state` + `famStore.applyRecord()` for instant feedback, then reconcile on the server response. See `applyRecord` pattern below.
|
||||||
|
|
||||||
|
**All other pages (admin CRUD, bonuses, rewards, settings, etc.) must use `$derived`** so that SSE updates flow through `famStore` → `$derived` → UI automatically.
|
||||||
|
|
||||||
## Update Patterns
|
## Update Patterns
|
||||||
|
|
||||||
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) | `x-device-token` header |
|
| Direct `fetch` + `memberApi` | Member | High (chore toggles) | None | Yes (instant UI, reconcile on response) | `x-device-token` header |
|
||||||
| Form action | Admin | Low (CRUD) | High (settings, members) | No — form is server-side, wait for round trip | httpOnly `session` cookie |
|
| Form action | Admin | Low (CRUD) | High (settings, members) | No — form is server-side, wait for round trip | httpOnly `session` 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:
|
||||||
|
|
||||||
```svelte
|
```svelte
|
||||||
let completions = $state(data.completions)
|
let completions = $state(data.completions)
|
||||||
async function toggle(chore) {
|
async function toggle(chore) {
|
||||||
|
|||||||
Vendored
+2
@@ -1,4 +1,5 @@
|
|||||||
import { PocketBase } from 'pocketbase';
|
import { PocketBase } from 'pocketbase';
|
||||||
|
import type { Session } from './lib/types';
|
||||||
|
|
||||||
// See https://svelte.dev/docs/kit/types#app.d.ts
|
// See https://svelte.dev/docs/kit/types#app.d.ts
|
||||||
// for information about these interfaces
|
// for information about these interfaces
|
||||||
@@ -8,6 +9,7 @@ declare global {
|
|||||||
// interface Error {}
|
// interface Error {}
|
||||||
interface Locals {
|
interface Locals {
|
||||||
pb: PocketBase;
|
pb: PocketBase;
|
||||||
|
session?: Session | null;
|
||||||
}
|
}
|
||||||
// interface PageData {}
|
// interface PageData {}
|
||||||
// interface PageState {}
|
// interface PageState {}
|
||||||
|
|||||||
+126
-25
@@ -9,15 +9,20 @@ function sessionHeaders(event: RequestEvent): Record<string, string> {
|
|||||||
return {
|
return {
|
||||||
'x-session-famid': s.famId,
|
'x-session-famid': s.famId,
|
||||||
'x-session-userid': s.userId,
|
'x-session-userid': s.userId,
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function request(method: string, path: string, body?: unknown, headers?: Record<string, string>) {
|
async function request(
|
||||||
|
method: string,
|
||||||
|
path: string,
|
||||||
|
body?: unknown,
|
||||||
|
headers?: Record<string, string>
|
||||||
|
) {
|
||||||
const res = await fetch(`${HONO_URL}${path}`, {
|
const res = await fetch(`${HONO_URL}${path}`, {
|
||||||
method,
|
method,
|
||||||
headers: headers || { 'Content-Type': 'application/json' },
|
headers: headers || { 'Content-Type': 'application/json' },
|
||||||
body: body ? JSON.stringify(body) : undefined,
|
body: body ? JSON.stringify(body) : undefined
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) throw new Error(data.error || `${method} ${path} failed`);
|
if (!res.ok) throw new Error(data.error || `${method} ${path} failed`);
|
||||||
@@ -29,14 +34,30 @@ export const hono = {
|
|||||||
async list(event: RequestEvent, resource: string, famId: string) {
|
async list(event: RequestEvent, resource: string, famId: string) {
|
||||||
return request('GET', `/api/admin/${famId}/${resource}`, undefined, sessionHeaders(event));
|
return request('GET', `/api/admin/${famId}/${resource}`, undefined, sessionHeaders(event));
|
||||||
},
|
},
|
||||||
async create(event: RequestEvent, resource: string, famId: string, data: Record<string, unknown>) {
|
async create(
|
||||||
|
event: RequestEvent,
|
||||||
|
resource: string,
|
||||||
|
famId: string,
|
||||||
|
data: Record<string, unknown>
|
||||||
|
) {
|
||||||
return request('POST', `/api/admin/${famId}/${resource}`, data, sessionHeaders(event));
|
return request('POST', `/api/admin/${famId}/${resource}`, data, sessionHeaders(event));
|
||||||
},
|
},
|
||||||
async update(event: RequestEvent, resource: string, famId: string, id: string, data: Record<string, unknown>) {
|
async update(
|
||||||
|
event: RequestEvent,
|
||||||
|
resource: string,
|
||||||
|
famId: string,
|
||||||
|
id: string,
|
||||||
|
data: Record<string, unknown>
|
||||||
|
) {
|
||||||
return request('PATCH', `/api/admin/${famId}/${resource}/${id}`, data, sessionHeaders(event));
|
return request('PATCH', `/api/admin/${famId}/${resource}/${id}`, data, sessionHeaders(event));
|
||||||
},
|
},
|
||||||
async remove(event: RequestEvent, resource: string, famId: string, id: string) {
|
async remove(event: RequestEvent, resource: string, famId: string, id: string) {
|
||||||
return request('DELETE', `/api/admin/${famId}/${resource}/${id}`, undefined, sessionHeaders(event));
|
return request(
|
||||||
|
'DELETE',
|
||||||
|
`/api/admin/${famId}/${resource}/${id}`,
|
||||||
|
undefined,
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async renameFam(event: RequestEvent, famId: string, name: string) {
|
async renameFam(event: RequestEvent, famId: string, name: string) {
|
||||||
return request('PATCH', `/api/admin/${famId}/fam`, { name }, sessionHeaders(event));
|
return request('PATCH', `/api/admin/${famId}/fam`, { name }, sessionHeaders(event));
|
||||||
@@ -63,46 +84,126 @@ export const hono = {
|
|||||||
return request('GET', `/api/admin/${famId}/rewards`, undefined, sessionHeaders(event));
|
return request('GET', `/api/admin/${famId}/rewards`, undefined, sessionHeaders(event));
|
||||||
},
|
},
|
||||||
async claimReward(event: RequestEvent, famId: string, rewardId: string) {
|
async claimReward(event: RequestEvent, famId: string, rewardId: string) {
|
||||||
return request('POST', `/api/admin/${famId}/rewards/${rewardId}/claim`, undefined, sessionHeaders(event));
|
return request(
|
||||||
|
'POST',
|
||||||
|
`/api/admin/${famId}/rewards/${rewardId}/claim`,
|
||||||
|
undefined,
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async issueAllRewards(event: RequestEvent, famId: string, memberId: string, message?: string) {
|
async issueAllRewards(event: RequestEvent, famId: string, memberId: string, message?: string) {
|
||||||
return request('POST', `/api/admin/${famId}/rewards/issue-all`, { memberId, message }, sessionHeaders(event));
|
return request(
|
||||||
|
'POST',
|
||||||
|
`/api/admin/${famId}/rewards/issue-all`,
|
||||||
|
{ memberId, message },
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async bonusConfigs(event: RequestEvent, famId: string) {
|
async bonusConfigs(event: RequestEvent, famId: string) {
|
||||||
return request('GET', `/api/admin/${famId}/bonus-configs`, undefined, sessionHeaders(event));
|
return request('GET', `/api/admin/${famId}/bonus-configs`, undefined, sessionHeaders(event));
|
||||||
},
|
},
|
||||||
async bonusConfigProgress(event: RequestEvent, famId: string) {
|
async bonusConfigProgress(event: RequestEvent, famId: string) {
|
||||||
return request('GET', `/api/admin/${famId}/bonus-configs/progress`, undefined, sessionHeaders(event));
|
return request(
|
||||||
|
'GET',
|
||||||
|
`/api/admin/${famId}/bonus-configs/progress`,
|
||||||
|
undefined,
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async evaluateBonusConfig(event: RequestEvent, famId: string, configId?: string) {
|
async evaluateBonusConfig(event: RequestEvent, famId: string, configId?: string) {
|
||||||
return request('POST', `/api/admin/${famId}/bonus-configs/evaluate`, { configId }, sessionHeaders(event));
|
return request(
|
||||||
|
'POST',
|
||||||
|
`/api/admin/${famId}/bonus-configs/evaluate`,
|
||||||
|
{ configId },
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async triggerBonusConfig(event: RequestEvent, famId: string, configId: string, memberId?: string) {
|
async triggerBonusConfig(
|
||||||
return request('POST', `/api/admin/${famId}/bonus-configs/${configId}/trigger`, { memberId }, sessionHeaders(event));
|
event: RequestEvent,
|
||||||
|
famId: string,
|
||||||
|
configId: string,
|
||||||
|
memberId?: string
|
||||||
|
) {
|
||||||
|
return request(
|
||||||
|
'POST',
|
||||||
|
`/api/admin/${famId}/bonus-configs/${configId}/trigger`,
|
||||||
|
{ memberId },
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async assignBonusConfig(event: RequestEvent, famId: string, configId: string, data: Record<string, unknown>) {
|
async assignBonusConfig(
|
||||||
return request('POST', `/api/admin/${famId}/bonus-configs/${configId}/assign`, data, sessionHeaders(event));
|
event: RequestEvent,
|
||||||
|
famId: string,
|
||||||
|
configId: string,
|
||||||
|
data: Record<string, unknown>
|
||||||
|
) {
|
||||||
|
return request(
|
||||||
|
'POST',
|
||||||
|
`/api/admin/${famId}/bonus-configs/${configId}/assign`,
|
||||||
|
data,
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async completeBonusConfig(event: RequestEvent, famId: string, configId: string, phase?: string) {
|
async completeBonusConfig(event: RequestEvent, famId: string, configId: string) {
|
||||||
return request('POST', `/api/admin/${famId}/bonus-configs/${configId}/complete`, { phase }, sessionHeaders(event));
|
return request(
|
||||||
|
'POST',
|
||||||
|
`/api/admin/${famId}/bonus-configs/${configId}/complete`,
|
||||||
|
undefined,
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async destroyBonusConfig(event: RequestEvent, famId: string, configId: string) {
|
async destroyBonusConfig(event: RequestEvent, famId: string, configId: string) {
|
||||||
return request('POST', `/api/admin/${famId}/bonus-configs/${configId}/destroy`, undefined, sessionHeaders(event));
|
return request(
|
||||||
|
'POST',
|
||||||
|
`/api/admin/${famId}/bonus-configs/${configId}/destroy`,
|
||||||
|
undefined,
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async bonusConfigTallies(event: RequestEvent, famId: string) {
|
async bonusConfigTallies(event: RequestEvent, famId: string) {
|
||||||
return request('GET', `/api/admin/${famId}/bonus-configs/tallies`, undefined, sessionHeaders(event));
|
return request(
|
||||||
|
'GET',
|
||||||
|
`/api/admin/${famId}/bonus-configs/tallies`,
|
||||||
|
undefined,
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async revokeCompletion(event: RequestEvent, famId: string, completionId: string) {
|
async revokeCompletion(event: RequestEvent, famId: string, completionId: string) {
|
||||||
return request('POST', `/api/admin/${famId}/completions/${completionId}/revoke`, undefined, sessionHeaders(event));
|
return request(
|
||||||
|
'POST',
|
||||||
|
`/api/admin/${famId}/completions/${completionId}/revoke`,
|
||||||
|
undefined,
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async sendMessage(event: RequestEvent, famId: string, memberId: string, message: string) {
|
async sendMessage(event: RequestEvent, famId: string, memberId: string, message: string) {
|
||||||
return request('POST', `/api/admin/${famId}/send-message`, { memberId, message }, sessionHeaders(event));
|
return request(
|
||||||
|
'POST',
|
||||||
|
`/api/admin/${famId}/send-message`,
|
||||||
|
{ memberId, message },
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async memberChores(event: RequestEvent, famId: string, memberId: string) {
|
async memberChores(event: RequestEvent, famId: string, memberId: string) {
|
||||||
return request('GET', `/api/admin/${famId}/members/${memberId}/chores`, undefined, sessionHeaders(event));
|
return request(
|
||||||
|
'GET',
|
||||||
|
`/api/admin/${famId}/members/${memberId}/chores`,
|
||||||
|
undefined,
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async updateMember(event: RequestEvent, famId: string, memberId: string, data: Record<string, unknown>) {
|
async updateMember(
|
||||||
return request('PATCH', `/api/admin/${famId}/members/${memberId}`, data, sessionHeaders(event));
|
event: RequestEvent,
|
||||||
|
famId: string,
|
||||||
|
memberId: string,
|
||||||
|
data: Record<string, unknown>
|
||||||
|
) {
|
||||||
|
return request(
|
||||||
|
'PATCH',
|
||||||
|
`/api/admin/${famId}/members/${memberId}`,
|
||||||
|
data,
|
||||||
|
sessionHeaders(event)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
async getProfile(event: RequestEvent, famId: string) {
|
async getProfile(event: RequestEvent, famId: string) {
|
||||||
return request('GET', `/api/admin/${famId}/profile`, undefined, sessionHeaders(event));
|
return request('GET', `/api/admin/${famId}/profile`, undefined, sessionHeaders(event));
|
||||||
@@ -115,6 +216,6 @@ export const hono = {
|
|||||||
},
|
},
|
||||||
async request(event: RequestEvent, method: string, path: string, body?: unknown) {
|
async request(event: RequestEvent, method: string, path: string, body?: unknown) {
|
||||||
return request(method, path, body, sessionHeaders(event));
|
return request(method, path, body, sessionHeaders(event));
|
||||||
},
|
}
|
||||||
},
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,99 +1,145 @@
|
|||||||
import { pb } from '$lib/pocketbase';
|
import { pb } from '$lib/pocketbase';
|
||||||
import type {
|
import type {
|
||||||
Member, ChoreTemplate, AssignedChore, Completion,
|
Member,
|
||||||
WeeklyHistory, Reward, BonusConfig, Fam, Season,
|
ChoreTemplate,
|
||||||
|
AssignedChore,
|
||||||
|
Completion,
|
||||||
|
WeeklyHistory,
|
||||||
|
Reward,
|
||||||
|
BonusConfig,
|
||||||
|
BonusTemplate,
|
||||||
|
Fam,
|
||||||
|
Season
|
||||||
} from '$lib/types';
|
} from '$lib/types';
|
||||||
|
|
||||||
type CollectionName = 'members' | 'chore_templates' | 'assigned_chores' | 'completions' | 'bonus_configs' | 'rewards' | 'seasons';
|
type CollectionName =
|
||||||
|
| 'members'
|
||||||
|
| 'chore_templates'
|
||||||
|
| 'assigned_chores'
|
||||||
|
| 'completions'
|
||||||
|
| 'bonus_configs'
|
||||||
|
| 'bonus_templates'
|
||||||
|
| 'rewards'
|
||||||
|
| 'seasons';
|
||||||
|
|
||||||
class FamStore {
|
class FamStore {
|
||||||
fam = $state<Fam | null>(null)
|
fam = $state<Fam | null>(null);
|
||||||
members = $state<Member[]>([])
|
members = $state<Member[]>([]);
|
||||||
templates = $state<ChoreTemplate[]>([])
|
templates = $state<ChoreTemplate[]>([]);
|
||||||
assigned = $state<AssignedChore[]>([])
|
assigned = $state<AssignedChore[]>([]);
|
||||||
completions = $state<Completion[]>([])
|
completions = $state<Completion[]>([]);
|
||||||
history = $state<WeeklyHistory[]>([])
|
history = $state<WeeklyHistory[]>([]);
|
||||||
rewards = $state<Reward[]>([])
|
rewards = $state<Reward[]>([]);
|
||||||
bonusConfigs = $state<BonusConfig[]>([])
|
bonusConfigs = $state<BonusConfig[]>([]);
|
||||||
seasons = $state<Season[]>([])
|
bonusTemplates = $state<BonusTemplate[]>([]);
|
||||||
initialized = $state(false)
|
seasons = $state<Season[]>([]);
|
||||||
famId = $state('')
|
initialized = $state(false);
|
||||||
|
famId = $state('');
|
||||||
|
|
||||||
private unsubs: (() => void)[] = []
|
private unsubs: (() => void)[] = [];
|
||||||
private destroyed = false
|
private destroyed = false;
|
||||||
|
|
||||||
memberMap(): Map<string, Member> {
|
memberMap(): Map<string, Member> {
|
||||||
return new Map(this.members.map((m) => [m.id, m]))
|
return new Map(this.members.map((m) => [m.id, m]));
|
||||||
}
|
}
|
||||||
|
|
||||||
templateMap(): Map<string, ChoreTemplate> {
|
templateMap(): Map<string, ChoreTemplate> {
|
||||||
return new Map(this.templates.map((t) => [t.id, t]))
|
return new Map(this.templates.map((t) => [t.id, t]));
|
||||||
}
|
}
|
||||||
|
|
||||||
bonusConfigMap(): Map<string, BonusConfig> {
|
bonusConfigMap(): Map<string, BonusConfig> {
|
||||||
return new Map(this.bonusConfigs.map((b) => [b.id, b]))
|
return new Map(this.bonusConfigs.map((b) => [b.id, b]));
|
||||||
}
|
}
|
||||||
|
|
||||||
assignedForMember(memberId: string): AssignedChore[] {
|
assignedForMember(memberId: string): AssignedChore[] {
|
||||||
return this.assigned.filter((a) => a.memberId === memberId)
|
return this.assigned.filter((a) => a.memberId === memberId);
|
||||||
}
|
}
|
||||||
|
|
||||||
completionsForDate(date: string): Completion[] {
|
completionsForDate(date: string): Completion[] {
|
||||||
return this.completions.filter((c) => (c.date?.slice(0, 10) || c.date) === date)
|
return this.completions.filter((c) => (c.date?.slice(0, 10) || c.date) === date);
|
||||||
}
|
}
|
||||||
|
|
||||||
isCompleted(assignedChoreId: string, date: string): boolean {
|
isCompleted(assignedChoreId: string, date: string): boolean {
|
||||||
return this.completions.some((c) => c.assignedChoreId === assignedChoreId && (c.date?.slice(0, 10) || c.date) === date)
|
return this.completions.some(
|
||||||
|
(c) => c.assignedChoreId === assignedChoreId && (c.date?.slice(0, 10) || c.date) === date
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private initPromise: Promise<void> | null = null
|
private initPromise: Promise<void> | null = null;
|
||||||
|
|
||||||
async init(famId: string) {
|
async init(famId: string) {
|
||||||
if (this.initialized && this.famId === famId) return
|
if (this.initialized && this.famId === famId) return;
|
||||||
|
|
||||||
// Wait for any in-flight init to finish first
|
// Wait for any in-flight init to finish first
|
||||||
if (this.initPromise) {
|
if (this.initPromise) {
|
||||||
await this.initPromise
|
await this.initPromise;
|
||||||
if (this.initialized && this.famId === famId) return
|
if (this.initialized && this.famId === famId) return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.cleanup()
|
this.cleanup();
|
||||||
this.destroyed = false
|
this.destroyed = false;
|
||||||
this.famId = famId
|
this.famId = famId;
|
||||||
|
|
||||||
this.initPromise = (async () => {
|
this.initPromise = (async () => {
|
||||||
try {
|
try {
|
||||||
const [famRes, membersRes, templatesRes, assignedRes, completionsRes, bonusConfigsRes, rewardsRes, seasonsRes] =
|
const [
|
||||||
await Promise.all([
|
famRes,
|
||||||
pb.collection('fams').getOne(famId) as Promise<Fam>,
|
membersRes,
|
||||||
pb.collection('members').getFullList({ filter: `famId = '${famId}'` }) as Promise<Member[]>,
|
templatesRes,
|
||||||
pb.collection('chore_templates').getFullList({ filter: `famId = '${famId}'` }) as Promise<ChoreTemplate[]>,
|
assignedRes,
|
||||||
pb.collection('assigned_chores').getFullList({ filter: `famId = '${famId}'` }) as Promise<AssignedChore[]>,
|
completionsRes,
|
||||||
pb.collection('completions').getFullList({ filter: `famId = '${famId}'` }) as Promise<Completion[]>,
|
bonusConfigsRes,
|
||||||
pb.collection('bonus_configs').getFullList({ filter: `famId = '${famId}'` }) as Promise<BonusConfig[]>,
|
bonusTemplatesRes,
|
||||||
pb.collection('rewards').getFullList({ filter: `famId = '${famId}'` }) as Promise<Reward[]>,
|
rewardsRes,
|
||||||
pb.collection('seasons').getFullList({ filter: `famId = '${famId}'` }) as Promise<Season[]>,
|
seasonsRes
|
||||||
])
|
] = await Promise.all([
|
||||||
this.fam = famRes
|
pb.collection('fams').getOne(famId) as Promise<Fam>,
|
||||||
this.members = membersRes
|
pb.collection('members').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||||
this.templates = templatesRes
|
Member[]
|
||||||
this.assigned = assignedRes
|
>,
|
||||||
this.completions = completionsRes
|
pb.collection('chore_templates').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||||
this.bonusConfigs = bonusConfigsRes
|
ChoreTemplate[]
|
||||||
this.rewards = rewardsRes
|
>,
|
||||||
this.seasons = seasonsRes
|
pb.collection('assigned_chores').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||||
this.initialized = true
|
AssignedChore[]
|
||||||
|
>,
|
||||||
|
pb.collection('completions').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||||
|
Completion[]
|
||||||
|
>,
|
||||||
|
pb.collection('bonus_configs').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||||
|
BonusConfig[]
|
||||||
|
>,
|
||||||
|
pb.collection('bonus_templates').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||||
|
BonusTemplate[]
|
||||||
|
>,
|
||||||
|
pb.collection('rewards').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||||
|
Reward[]
|
||||||
|
>,
|
||||||
|
pb.collection('seasons').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||||
|
Season[]
|
||||||
|
>
|
||||||
|
]);
|
||||||
|
this.fam = famRes;
|
||||||
|
this.members = membersRes;
|
||||||
|
this.templates = templatesRes;
|
||||||
|
this.assigned = assignedRes;
|
||||||
|
this.completions = completionsRes;
|
||||||
|
this.bonusConfigs = bonusConfigsRes;
|
||||||
|
this.bonusTemplates = bonusTemplatesRes;
|
||||||
|
this.rewards = rewardsRes;
|
||||||
|
this.seasons = seasonsRes;
|
||||||
|
this.initialized = true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('FamStore.init failed:', e)
|
console.error('FamStore.init failed:', e);
|
||||||
this.initPromise = null
|
this.initPromise = null;
|
||||||
throw e
|
throw e;
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.subscribe()
|
await this.subscribe();
|
||||||
this.initPromise = null
|
this.initPromise = null;
|
||||||
})()
|
})();
|
||||||
|
|
||||||
return this.initPromise!
|
return this.initPromise!;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async subscribe() {
|
private async subscribe() {
|
||||||
@@ -103,58 +149,92 @@ class FamStore {
|
|||||||
{ collection: 'assigned_chores', filter: this.famId },
|
{ collection: 'assigned_chores', filter: this.famId },
|
||||||
{ collection: 'completions', filter: this.famId },
|
{ collection: 'completions', filter: this.famId },
|
||||||
{ collection: 'bonus_configs', filter: this.famId },
|
{ collection: 'bonus_configs', filter: this.famId },
|
||||||
|
{ collection: 'bonus_templates', filter: this.famId },
|
||||||
{ collection: 'rewards', filter: this.famId },
|
{ collection: 'rewards', filter: this.famId },
|
||||||
{ collection: 'seasons', filter: this.famId },
|
{ collection: 'seasons', filter: this.famId }
|
||||||
]
|
];
|
||||||
|
|
||||||
const promises = subs.map(({ collection, filter }) => {
|
const promises = subs.map(({ collection, filter }) => {
|
||||||
const filterStr = filter ? `famId = '${filter}'` : ''
|
const filterStr = filter ? `famId = '${filter}'` : '';
|
||||||
return pb.collection(collection).subscribe('*', (data: any) => {
|
return pb
|
||||||
if (this.destroyed) return
|
.collection(collection)
|
||||||
this.handleRealtime(collection, data.action, data.record)
|
.subscribe(
|
||||||
}, { filter: filterStr || undefined }).then((unsub) => {
|
'*',
|
||||||
if (this.destroyed) { unsub(); return }
|
(data: any) => {
|
||||||
this.unsubs.push(unsub)
|
if (this.destroyed) return;
|
||||||
}).catch((err: Error) => {
|
this.handleRealtime(collection, data.action, data.record);
|
||||||
console.error(`[famStore] subscribe failed for ${collection}:`, err)
|
},
|
||||||
})
|
{ filter: filterStr || undefined }
|
||||||
})
|
)
|
||||||
|
.then((unsub) => {
|
||||||
|
if (this.destroyed) {
|
||||||
|
unsub();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.unsubs.push(unsub);
|
||||||
|
})
|
||||||
|
.catch((err: Error) => {
|
||||||
|
console.error(`[famStore] subscribe failed for ${collection}:`, err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
await Promise.allSettled(promises)
|
await Promise.allSettled(promises);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Called from form action callbacks for instant UI feedback,
|
// Called from form action callbacks for instant UI feedback,
|
||||||
// and from PB subscribe SSE for multi-user realtime.
|
// and from PB subscribe SSE for multi-user realtime.
|
||||||
applyRecord(collection: CollectionName, record: any, action: 'create' | 'update' | 'delete') {
|
applyRecord(collection: CollectionName, record: any, action: 'create' | 'update' | 'delete') {
|
||||||
const apply = <T extends { id: string }>(list: T[]): T[] => {
|
const apply = <T extends { id: string }>(list: T[]): T[] => {
|
||||||
if (action === 'create') return [record, ...list]
|
if (action === 'create') return [record, ...list];
|
||||||
if (action === 'update') return list.map((x) => (x.id === record.id ? { ...x, ...record } : x))
|
if (action === 'update')
|
||||||
if (action === 'delete') return list.filter((x) => x.id !== record.id)
|
return list.map((x) => (x.id === record.id ? { ...x, ...record } : x));
|
||||||
return list
|
if (action === 'delete') return list.filter((x) => x.id !== record.id);
|
||||||
}
|
return list;
|
||||||
|
};
|
||||||
|
|
||||||
switch (collection) {
|
switch (collection) {
|
||||||
case 'members': this.members = apply(this.members); break
|
case 'members':
|
||||||
case 'chore_templates': this.templates = apply(this.templates); break
|
this.members = apply(this.members);
|
||||||
case 'assigned_chores': this.assigned = apply(this.assigned); break
|
break;
|
||||||
case 'completions': this.completions = apply(this.completions); break
|
case 'chore_templates':
|
||||||
case 'bonus_configs': this.bonusConfigs = apply(this.bonusConfigs); break
|
this.templates = apply(this.templates);
|
||||||
case 'rewards': this.rewards = apply(this.rewards); break
|
break;
|
||||||
case 'seasons': this.seasons = apply(this.seasons); break
|
case 'assigned_chores':
|
||||||
|
this.assigned = apply(this.assigned);
|
||||||
|
break;
|
||||||
|
case 'completions':
|
||||||
|
this.completions = apply(this.completions);
|
||||||
|
break;
|
||||||
|
case 'bonus_configs':
|
||||||
|
this.bonusConfigs = apply(this.bonusConfigs);
|
||||||
|
break;
|
||||||
|
case 'bonus_templates':
|
||||||
|
this.bonusTemplates = apply(this.bonusTemplates);
|
||||||
|
break;
|
||||||
|
case 'rewards':
|
||||||
|
this.rewards = apply(this.rewards);
|
||||||
|
break;
|
||||||
|
case 'seasons':
|
||||||
|
this.seasons = apply(this.seasons);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleRealtime(collection: string, action: string, record: any) {
|
private handleRealtime(collection: string, action: string, record: any) {
|
||||||
this.applyRecord(collection as CollectionName, record, action as 'create' | 'update' | 'delete')
|
this.applyRecord(
|
||||||
|
collection as CollectionName,
|
||||||
|
record,
|
||||||
|
action as 'create' | 'update' | 'delete'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
cleanup() {
|
cleanup() {
|
||||||
// TODO - we need to properly unsubscribe from pocketbase
|
// TODO - we need to properly unsubscribe from pocketbase
|
||||||
this.destroyed = true
|
this.destroyed = true;
|
||||||
for (const unsub of this.unsubs) unsub()
|
for (const unsub of this.unsubs) unsub();
|
||||||
this.unsubs = []
|
this.unsubs = [];
|
||||||
this.initialized = false
|
this.initialized = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const famStore = new FamStore()
|
export const famStore = new FamStore();
|
||||||
|
|||||||
+132
-117
@@ -1,156 +1,171 @@
|
|||||||
export type Frequency = 'daily' | 'weekly'
|
export type Frequency = 'daily' | 'weekly';
|
||||||
export type RewardType = 'points' | 'money'
|
export type RewardType = 'points' | 'money';
|
||||||
export type BonusTarget = 'individual' | 'competitive' | 'collaborative'
|
export type BonusTarget = 'individual' | 'competitive' | 'collaborative';
|
||||||
export type BonusType = 'threshold' | 'count' | 'manual'
|
export type BonusType = 'threshold' | 'count' | 'manual';
|
||||||
export type BonusOccurrence = 'recurring' | 'once'
|
export type BonusOccurrence = 'recurring' | 'once';
|
||||||
export type BonusRewardType = 'points' | 'cash' | 'prize'
|
export type BonusRewardType = 'points' | 'cash' | 'prize';
|
||||||
export type BonusPeriod = 'weekly' | 'monthly'
|
export type BonusPeriod = 'weekly' | 'monthly' | 'daily';
|
||||||
export type BonusStatus = 'active' | 'archived'
|
export type BonusStatus = 'active' | 'completed' | 'disabled';
|
||||||
export type BonusState = 'pending' | 'unclaimed' | 'claimed'
|
export type BonusState = 'pending' | 'unclaimed' | 'claimed';
|
||||||
|
|
||||||
|
export interface BonusTemplate {
|
||||||
|
id: string;
|
||||||
|
famId: string;
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
target: BonusTarget;
|
||||||
|
type: BonusType;
|
||||||
|
occurrence: BonusOccurrence;
|
||||||
|
rewardType: BonusRewardType;
|
||||||
|
rewardValue: string;
|
||||||
|
criteriaValue?: number;
|
||||||
|
period?: BonusPeriod;
|
||||||
|
created: string;
|
||||||
|
updated: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Season {
|
export interface Season {
|
||||||
id: string
|
id: string;
|
||||||
famId: string
|
famId: string;
|
||||||
name: string
|
name: string;
|
||||||
color: string
|
color: string;
|
||||||
active: boolean
|
active: boolean;
|
||||||
autoDisable?: string
|
autoDisable?: string;
|
||||||
autoStart?: string
|
autoStart?: string;
|
||||||
created: string
|
created: string;
|
||||||
updated: string
|
updated: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Fam {
|
export interface Fam {
|
||||||
id: string
|
id: string;
|
||||||
name: string
|
name: string;
|
||||||
slug: string
|
slug: string;
|
||||||
inviteCode: string
|
inviteCode: string;
|
||||||
stripeCustomerId?: string
|
stripeCustomerId?: string;
|
||||||
featureFlags: Record<string, boolean>
|
featureFlags: Record<string, boolean>;
|
||||||
created: string
|
created: string;
|
||||||
updated: string
|
updated: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Member {
|
export interface Member {
|
||||||
id: string
|
id: string;
|
||||||
famId: string
|
famId: string;
|
||||||
name: string
|
name: string;
|
||||||
color: string
|
color: string;
|
||||||
deviceToken: string
|
deviceToken: string;
|
||||||
deviceTokenHint: string
|
deviceTokenHint: string;
|
||||||
created: string
|
created: string;
|
||||||
updated: string
|
updated: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ChoreTemplate {
|
export interface ChoreTemplate {
|
||||||
id: string
|
id: string;
|
||||||
famId: string
|
famId: string;
|
||||||
name: string
|
name: string;
|
||||||
description?: string
|
description?: string;
|
||||||
defaultFrequency: Frequency
|
defaultFrequency: Frequency;
|
||||||
defaultType: RewardType
|
defaultType: RewardType;
|
||||||
defaultValue: number
|
defaultValue: number;
|
||||||
created: string
|
created: string;
|
||||||
updated: string
|
updated: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AssignedChore {
|
export interface AssignedChore {
|
||||||
id: string
|
id: string;
|
||||||
famId: string
|
famId: string;
|
||||||
memberId: string
|
memberId: string;
|
||||||
templateId: string
|
templateId: string;
|
||||||
frequency: Frequency
|
frequency: Frequency;
|
||||||
type: RewardType
|
type: RewardType;
|
||||||
value: number
|
value: number;
|
||||||
customName?: string
|
customName?: string;
|
||||||
seasonIds?: string[]
|
seasonIds?: string[];
|
||||||
created: string
|
created: string;
|
||||||
updated: string
|
updated: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Completion {
|
export interface Completion {
|
||||||
id: string
|
id: string;
|
||||||
famId: string
|
famId: string;
|
||||||
memberId: string
|
memberId: string;
|
||||||
assignedChoreId: string
|
assignedChoreId: string;
|
||||||
date: string
|
date: string;
|
||||||
completedAt: string
|
completedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WeeklyHistory {
|
export interface WeeklyHistory {
|
||||||
id: string
|
id: string;
|
||||||
famId: string
|
famId: string;
|
||||||
memberId: string
|
memberId: string;
|
||||||
weekStart: string
|
weekStart: string;
|
||||||
pointsEarned: number
|
pointsEarned: number;
|
||||||
moneyEarned: number
|
moneyEarned: number;
|
||||||
choresCompleted: number
|
choresCompleted: number;
|
||||||
bonusEarned: number
|
bonusEarned: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BonusConfig {
|
export interface BonusConfig {
|
||||||
id: string
|
id: string;
|
||||||
famId: string
|
famId: string;
|
||||||
name: string
|
name: string;
|
||||||
description?: string
|
description?: string;
|
||||||
target: BonusTarget
|
target: BonusTarget;
|
||||||
memberId?: string
|
memberId?: string;
|
||||||
type: BonusType
|
type: BonusType;
|
||||||
occurrence: BonusOccurrence
|
occurrence: BonusOccurrence;
|
||||||
rewardType: BonusRewardType
|
rewardType: BonusRewardType;
|
||||||
rewardValue: string
|
rewardValue: string;
|
||||||
criteriaValue?: number
|
criteriaValue?: number;
|
||||||
period?: BonusPeriod
|
period?: BonusPeriod;
|
||||||
status: BonusStatus
|
status: BonusStatus;
|
||||||
phase?: 'template' | 'ready' | 'active' | 'completed'
|
created: string;
|
||||||
created: string
|
updated: string;
|
||||||
updated: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Reward {
|
export interface Reward {
|
||||||
id: string
|
id: string;
|
||||||
famId: string
|
famId: string;
|
||||||
memberId: string
|
memberId: string;
|
||||||
bonusConfigId?: string
|
bonusConfigId?: string;
|
||||||
label: string
|
label: string;
|
||||||
value: number
|
value: number;
|
||||||
rewardType: BonusRewardType
|
rewardType: BonusRewardType;
|
||||||
status: 'unclaimed' | 'requested' | 'claimed'
|
status: 'unclaimed' | 'requested' | 'claimed';
|
||||||
claimedAt?: string
|
claimedAt?: string;
|
||||||
requestedAt?: string
|
requestedAt?: string;
|
||||||
date: string
|
date: string;
|
||||||
created: string
|
created: string;
|
||||||
updated: string
|
updated: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BonusProgress {
|
export interface BonusProgress {
|
||||||
memberId: string
|
memberId: string;
|
||||||
memberName: string
|
memberName: string;
|
||||||
memberColor: string
|
memberColor: string;
|
||||||
current: number
|
current: number;
|
||||||
criteriaValue: number
|
criteriaValue: number;
|
||||||
reward: { id: string; status: string } | null
|
reward: { id: string; status: string } | null;
|
||||||
state: BonusState
|
state: BonusState;
|
||||||
achieved: boolean
|
achieved: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BonusConfigWithProgress {
|
export interface BonusConfigWithProgress {
|
||||||
config: BonusConfig
|
config: BonusConfig;
|
||||||
progress: BonusProgress[]
|
progress: BonusProgress[];
|
||||||
periodStart: string
|
periodStart: string;
|
||||||
periodEnd: string
|
periodEnd: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Settings {
|
export interface Settings {
|
||||||
id: string
|
id: string;
|
||||||
famId: string
|
famId: string;
|
||||||
webhookUrl?: string
|
webhookUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Session {
|
export interface Session {
|
||||||
famId: string
|
famId: string;
|
||||||
userId: string
|
userId: string;
|
||||||
famSlug: string
|
famSlug: string;
|
||||||
memberName?: string
|
memberName?: string;
|
||||||
role?: string
|
role?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -118,16 +118,22 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function rewardLabel(r: any): string {
|
function rewardLabel(r: any): string {
|
||||||
if (r.rewardType === 'cash') return `£${(Number(r.value) / 100).toFixed(2)}`;
|
if (r.rewardType === 'cash') return `£${Number(r.value).toFixed(2)}`;
|
||||||
if (r.rewardType === 'points') return `${r.value} pts`;
|
if (r.rewardType === 'points') return `${r.value} pts`;
|
||||||
return r.label;
|
return r.label;
|
||||||
}
|
}
|
||||||
|
|
||||||
function manualConfigs() {
|
function manualConfigs() {
|
||||||
return parentBonusConfigs.filter(
|
return parentBonusConfigs.filter((b: any) => {
|
||||||
(b: any) =>
|
if (!(b.status === 'active' && b.type === 'manual')) return false;
|
||||||
(b.phase === 'active' || (!b.phase && b.status === 'active')) && b.type === 'manual'
|
if (b.occurrence === 'once') {
|
||||||
);
|
const hasReward = parentRewards.some(
|
||||||
|
(r: any) => r.bonusConfigId === b.id && (!b.memberId || r.memberId === b.memberId)
|
||||||
|
);
|
||||||
|
if (hasReward) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Child View (kanban) ───
|
// ─── Child View (kanban) ───
|
||||||
@@ -140,11 +146,29 @@
|
|||||||
let nameInput = $state('');
|
let nameInput = $state('');
|
||||||
let showColorPicker = $state(false);
|
let showColorPicker = $state(false);
|
||||||
|
|
||||||
let templates = $derived(famStore.initialized ? (famStore.templates as ChoreTemplate[]) : (data.templates as ChoreTemplate[]));
|
let templates = $derived(
|
||||||
let assigned = $derived(famStore.initialized ? (famStore.assigned as AssignedChore[]) : (data.assigned as AssignedChore[]));
|
famStore.initialized
|
||||||
let completions = $derived(famStore.initialized ? (famStore.completions as Completion[]) : (data.completions as Completion[]));
|
? (famStore.templates as ChoreTemplate[])
|
||||||
let rewards = $derived(famStore.initialized ? (famStore.rewards as Reward[]) : (data.rewards as Reward[]));
|
: (data.templates as ChoreTemplate[])
|
||||||
let bonusConfigs = $derived(famStore.initialized ? (famStore.bonusConfigs as BonusConfig[]) : (data.bonusConfigs as BonusConfig[]));
|
);
|
||||||
|
let assigned = $derived(
|
||||||
|
famStore.initialized
|
||||||
|
? (famStore.assigned as AssignedChore[])
|
||||||
|
: (data.assigned as AssignedChore[])
|
||||||
|
);
|
||||||
|
let completions = $derived(
|
||||||
|
famStore.initialized
|
||||||
|
? (famStore.completions as Completion[])
|
||||||
|
: (data.completions as Completion[])
|
||||||
|
);
|
||||||
|
let rewards = $derived(
|
||||||
|
famStore.initialized ? (famStore.rewards as Reward[]) : (data.rewards as Reward[])
|
||||||
|
);
|
||||||
|
let bonusConfigs = $derived(
|
||||||
|
famStore.initialized
|
||||||
|
? (famStore.bonusConfigs as BonusConfig[])
|
||||||
|
: (data.bonusConfigs as BonusConfig[])
|
||||||
|
);
|
||||||
|
|
||||||
let loading = $state(true);
|
let loading = $state(true);
|
||||||
let error = $state('');
|
let error = $state('');
|
||||||
@@ -187,8 +211,12 @@
|
|||||||
let completedToday = $derived(
|
let completedToday = $derived(
|
||||||
completions.filter((c) => c.memberId === memberId && c.date?.slice(0, 10) === todayChild)
|
completions.filter((c) => c.memberId === memberId && c.date?.slice(0, 10) === todayChild)
|
||||||
);
|
);
|
||||||
let claimableRewardsChild = $derived(rewards.filter((r) => r.memberId === memberId && r.status === 'unclaimed'));
|
let claimableRewardsChild = $derived(
|
||||||
let requestedRewardsChild = $derived(rewards.filter((r) => r.memberId === memberId && r.status === 'requested'));
|
rewards.filter((r) => r.memberId === memberId && r.status === 'unclaimed')
|
||||||
|
);
|
||||||
|
let requestedRewardsChild = $derived(
|
||||||
|
rewards.filter((r) => r.memberId === memberId && r.status === 'requested')
|
||||||
|
);
|
||||||
|
|
||||||
let weeklyTotal = $derived.by(() => {
|
let weeklyTotal = $derived.by(() => {
|
||||||
const dailyChores = memberChores.filter((a) => a.frequency === 'daily');
|
const dailyChores = memberChores.filter((a) => a.frequency === 'daily');
|
||||||
@@ -211,9 +239,7 @@
|
|||||||
const chore = assigned.find((a) => a.id === c.assignedChoreId);
|
const chore = assigned.find((a) => a.id === c.assignedChoreId);
|
||||||
return sum + (chore?.type === 'money' ? Number(chore.value) : 0);
|
return sum + (chore?.type === 'money' ? Number(chore.value) : 0);
|
||||||
}, 0) +
|
}, 0) +
|
||||||
myRewards
|
myRewards.filter((r) => r.rewardType === 'cash').reduce((sum, r) => sum + Number(r.value), 0)
|
||||||
.filter((r) => r.rewardType === 'cash')
|
|
||||||
.reduce((sum, r) => sum + Number(r.value), 0)
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -248,13 +274,12 @@
|
|||||||
const myCompletions = completions.filter((c) => c.memberId === memberId);
|
const myCompletions = completions.filter((c) => c.memberId === memberId);
|
||||||
const activeConfigs = bonusConfigs.filter(
|
const activeConfigs = bonusConfigs.filter(
|
||||||
(b: BonusConfig) =>
|
(b: BonusConfig) =>
|
||||||
(b.phase === 'active' || (!b.phase && b.status === 'active')) &&
|
b.status === 'active' &&
|
||||||
b.target === 'individual' &&
|
b.target === 'individual' &&
|
||||||
(!b.memberId || b.memberId === memberId)
|
(!b.memberId || b.memberId === memberId)
|
||||||
);
|
);
|
||||||
return activeConfigs.map((cfg) => {
|
return activeConfigs.map((cfg) => {
|
||||||
const pStart =
|
const pStart = cfg.period === 'weekly' ? ws : cfg.period === 'monthly' ? monthStartStr() : '';
|
||||||
cfg.period === 'weekly' ? ws : cfg.period === 'monthly' ? monthStartStr() : '';
|
|
||||||
const pEnd = pStart
|
const pEnd = pStart
|
||||||
? (() => {
|
? (() => {
|
||||||
if (cfg.period === 'weekly') {
|
if (cfg.period === 'weekly') {
|
||||||
@@ -274,8 +299,7 @@
|
|||||||
const periodCompletions = pStart
|
const periodCompletions = pStart
|
||||||
? myCompletions.filter(
|
? myCompletions.filter(
|
||||||
(c) =>
|
(c) =>
|
||||||
(c.date?.slice(0, 10) || c.date) >= pStart &&
|
(c.date?.slice(0, 10) || c.date) >= pStart && (c.date?.slice(0, 10) || c.date) <= pEnd
|
||||||
(c.date?.slice(0, 10) || c.date) <= pEnd
|
|
||||||
)
|
)
|
||||||
: myCompletions;
|
: myCompletions;
|
||||||
|
|
||||||
@@ -374,14 +398,18 @@
|
|||||||
famStore.applyRecord('completions', existing, 'delete');
|
famStore.applyRecord('completions', existing, 'delete');
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
famStore.applyRecord('completions', {
|
famStore.applyRecord(
|
||||||
id: 'optimistic-' + chore.id,
|
'completions',
|
||||||
famId,
|
{
|
||||||
memberId,
|
id: 'optimistic-' + chore.id,
|
||||||
assignedChoreId: chore.id,
|
famId,
|
||||||
date: todayChild,
|
memberId,
|
||||||
completedAt: new Date().toISOString()
|
assignedChoreId: chore.id,
|
||||||
} as Completion, 'create');
|
date: todayChild,
|
||||||
|
completedAt: new Date().toISOString()
|
||||||
|
} as Completion,
|
||||||
|
'create'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -392,14 +420,18 @@
|
|||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (wasCompleted) {
|
if (wasCompleted) {
|
||||||
famStore.applyRecord('completions', {
|
famStore.applyRecord(
|
||||||
id: 'revert-' + chore.id + '-' + Date.now(),
|
'completions',
|
||||||
famId,
|
{
|
||||||
memberId,
|
id: 'revert-' + chore.id + '-' + Date.now(),
|
||||||
assignedChoreId: chore.id,
|
famId,
|
||||||
date: todayChild,
|
memberId,
|
||||||
completedAt: new Date().toISOString()
|
assignedChoreId: chore.id,
|
||||||
} as Completion, 'create');
|
date: todayChild,
|
||||||
|
completedAt: new Date().toISOString()
|
||||||
|
} as Completion,
|
||||||
|
'create'
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
const optimistic = completions.find((c) => c.id === 'optimistic-' + chore.id);
|
const optimistic = completions.find((c) => c.id === 'optimistic-' + chore.id);
|
||||||
if (optimistic) {
|
if (optimistic) {
|
||||||
@@ -421,7 +453,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function rewardLabelChild(r: Reward): string {
|
function rewardLabelChild(r: Reward): string {
|
||||||
if (r.rewardType === 'cash') return `£${(Number(r.value) / 100).toFixed(2)}`;
|
if (r.rewardType === 'cash') return `£${Number(r.value).toFixed(2)}`;
|
||||||
if (r.rewardType === 'points') return `${r.value} pts`;
|
if (r.rewardType === 'points') return `${r.value} pts`;
|
||||||
return r.label;
|
return r.label;
|
||||||
}
|
}
|
||||||
@@ -468,7 +500,14 @@
|
|||||||
{#each todays as c}
|
{#each todays as c}
|
||||||
<li>
|
<li>
|
||||||
✅ {choreNameFor(c.assignedChoreId)}
|
✅ {choreNameFor(c.assignedChoreId)}
|
||||||
<form method="POST" action="?/revoke" use:enhance={() => { return async (args) => handleResult(args); }} class="revoke-form">
|
<form
|
||||||
|
method="POST"
|
||||||
|
action="?/revoke"
|
||||||
|
use:enhance={() => {
|
||||||
|
return async (args) => handleResult(args);
|
||||||
|
}}
|
||||||
|
class="revoke-form"
|
||||||
|
>
|
||||||
<input type="hidden" name="id" value={c.id} />
|
<input type="hidden" name="id" value={c.id} />
|
||||||
<button type="submit" class="revoke-btn" title="Revoke">↩</button>
|
<button type="submit" class="revoke-btn" title="Revoke">↩</button>
|
||||||
</form>
|
</form>
|
||||||
@@ -487,7 +526,7 @@
|
|||||||
{#each manualConfigs() as bc}
|
{#each manualConfigs() as bc}
|
||||||
{@const val =
|
{@const val =
|
||||||
bc.rewardType === 'cash'
|
bc.rewardType === 'cash'
|
||||||
? `£${(Number(bc.rewardValue) / 100).toFixed(2)}`
|
? `£${Number(bc.rewardValue).toFixed(2)}`
|
||||||
: bc.rewardType === 'points'
|
: bc.rewardType === 'points'
|
||||||
? `${bc.rewardValue} pts`
|
? `${bc.rewardValue} pts`
|
||||||
: bc.rewardValue}
|
: bc.rewardValue}
|
||||||
@@ -500,7 +539,13 @@
|
|||||||
<span class="trigger-value">{val}</span>
|
<span class="trigger-value">{val}</span>
|
||||||
</div>
|
</div>
|
||||||
{#if targeted}
|
{#if targeted}
|
||||||
<form method="POST" action="?/trigger" use:enhance={() => { return async (args: any) => handleResult(args); }}>
|
<form
|
||||||
|
method="POST"
|
||||||
|
action="?/trigger"
|
||||||
|
use:enhance={() => {
|
||||||
|
return async (args: any) => handleResult(args);
|
||||||
|
}}
|
||||||
|
>
|
||||||
<input type="hidden" name="configId" value={bc.id} />
|
<input type="hidden" name="configId" value={bc.id} />
|
||||||
<input type="hidden" name="memberId" value={targeted.id} />
|
<input type="hidden" name="memberId" value={targeted.id} />
|
||||||
<div class="trigger-row">
|
<div class="trigger-row">
|
||||||
@@ -511,7 +556,13 @@
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{:else}
|
{:else}
|
||||||
<form method="POST" action="?/trigger" use:enhance={() => { return async (args: any) => handleResult(args); }}>
|
<form
|
||||||
|
method="POST"
|
||||||
|
action="?/trigger"
|
||||||
|
use:enhance={() => {
|
||||||
|
return async (args: any) => handleResult(args);
|
||||||
|
}}
|
||||||
|
>
|
||||||
<input type="hidden" name="configId" value={bc.id} />
|
<input type="hidden" name="configId" value={bc.id} />
|
||||||
<div class="trigger-row">
|
<div class="trigger-row">
|
||||||
<select name="memberId" class="trigger-select">
|
<select name="memberId" class="trigger-select">
|
||||||
@@ -561,6 +612,7 @@
|
|||||||
<div class="payment-right">
|
<div class="payment-right">
|
||||||
<span class="value">{rewardLabel(r)}</span>
|
<span class="value">{rewardLabel(r)}</span>
|
||||||
<Button type="submit" size="sm" variant="primary">Issue</Button>
|
<Button type="submit" size="sm" variant="primary">Issue</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{/each}
|
{/each}
|
||||||
@@ -569,13 +621,14 @@
|
|||||||
method="POST"
|
method="POST"
|
||||||
action="?/issueAll"
|
action="?/issueAll"
|
||||||
use:enhance={() => {
|
use:enhance={() => {
|
||||||
return async (args: any) =>
|
return async (args: any) => handleResult(args);
|
||||||
handleResult(args);
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<input type="hidden" name="memberId" value={m.id} />
|
<input type="hidden" name="memberId" value={m.id} />
|
||||||
<input type="hidden" name="message" value={selectedMessage[m.id] || ''} />
|
<input type="hidden" name="message" value={selectedMessage[m.id] || ''} />
|
||||||
<Button type="submit" size="sm" variant="secondary">Issue All ({requested.length})</Button>
|
<Button type="submit" size="sm" variant="secondary"
|
||||||
|
>Issue All ({requested.length})</Button
|
||||||
|
>
|
||||||
</form>
|
</form>
|
||||||
{/if}
|
{/if}
|
||||||
{/if}
|
{/if}
|
||||||
@@ -746,11 +799,11 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="badge-card cash">
|
<div class="badge-card cash">
|
||||||
<span class="badge-label">Total Cash</span>
|
<span class="badge-label">Total Cash</span>
|
||||||
<span class="badge-value">£{(totalCash / 100).toFixed(2)}</span>
|
<span class="badge-value">£{totalCash.toFixed(2)}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="badge-card pending">
|
<div class="badge-card pending">
|
||||||
<span class="badge-label">Pending Cash</span>
|
<span class="badge-label">Pending Cash</span>
|
||||||
<span class="badge-value">£{(pendingCash / 100).toFixed(2)}</span>
|
<span class="badge-value">£{pendingCash.toFixed(2)}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="badge-card points">
|
<div class="badge-card points">
|
||||||
<span class="badge-label">Total Points</span>
|
<span class="badge-label">Total Points</span>
|
||||||
@@ -1440,9 +1493,16 @@
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.request-all-btn:hover { background: #1d4ed8; }
|
.request-all-btn:hover {
|
||||||
.request-col { border-color: #93c5fd; background: #eff6ff; }
|
background: #1d4ed8;
|
||||||
.claim-card.requested { opacity: 0.7; }
|
}
|
||||||
|
.request-col {
|
||||||
|
border-color: #93c5fd;
|
||||||
|
background: #eff6ff;
|
||||||
|
}
|
||||||
|
.claim-card.requested {
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
.requested-badge {
|
.requested-badge {
|
||||||
font-size: 0.7rem;
|
font-size: 0.7rem;
|
||||||
padding: 2px 8px;
|
padding: 2px 8px;
|
||||||
@@ -1465,7 +1525,9 @@
|
|||||||
color: #2563eb;
|
color: #2563eb;
|
||||||
margin: 0 0 0.25rem;
|
margin: 0 0 0.25rem;
|
||||||
}
|
}
|
||||||
.payment-row.outstanding { opacity: 0.6; }
|
.payment-row.outstanding {
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
h1 {
|
h1 {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -4,21 +4,95 @@ import { hono } from '$lib/server/hono';
|
|||||||
export async function load(event) {
|
export async function load(event) {
|
||||||
if (!event.locals.session) throw redirect(303, '/login');
|
if (!event.locals.session) throw redirect(303, '/login');
|
||||||
const famId = event.locals.session.famId;
|
const famId = event.locals.session.famId;
|
||||||
const [configs, members, progress, rewards] = await Promise.all([
|
const [configs, templates, members, progress, rewards] = await Promise.all([
|
||||||
hono.admin.bonusConfigs(event, famId),
|
hono.admin.bonusConfigs(event, famId),
|
||||||
|
hono.admin.list(event, 'bonus-templates', famId),
|
||||||
hono.admin.list(event, 'members', famId),
|
hono.admin.list(event, 'members', famId),
|
||||||
hono.admin.bonusConfigProgress(event, famId),
|
hono.admin.bonusConfigProgress(event, famId),
|
||||||
hono.admin.rewards(event, famId),
|
hono.admin.rewards(event, famId)
|
||||||
]);
|
]);
|
||||||
return { configs, members, progress, rewards };
|
return { configs, templates, members, progress, rewards };
|
||||||
}
|
}
|
||||||
|
|
||||||
export const actions = {
|
export const actions = {
|
||||||
|
createTemplate: async (event) => {
|
||||||
|
if (!event.locals.session) throw redirect(303, '/login');
|
||||||
|
const famId = event.locals.session.famId;
|
||||||
|
const fd = await event.request.formData();
|
||||||
|
const data: Record<string, unknown> = {
|
||||||
|
name: fd.get('name'),
|
||||||
|
description: fd.get('description') || '',
|
||||||
|
target: fd.get('target'),
|
||||||
|
type: fd.get('type'),
|
||||||
|
occurrence: fd.get('occurrence'),
|
||||||
|
rewardType: fd.get('rewardType'),
|
||||||
|
rewardValue: fd.get('rewardValue')
|
||||||
|
};
|
||||||
|
const criteriaValue = fd.get('criteriaValue');
|
||||||
|
if (criteriaValue) data.criteriaValue = parseInt(criteriaValue as string, 10) || 0;
|
||||||
|
const period = fd.get('period');
|
||||||
|
if (period !== null) data.period = period;
|
||||||
|
if (data.occurrence === 'once') data.period = '';
|
||||||
|
try {
|
||||||
|
const record = await hono.admin.create(event, 'bonus-templates', famId, data);
|
||||||
|
return { record };
|
||||||
|
} catch (e) {
|
||||||
|
return fail(400, { error: e instanceof Error ? e.message : 'Failed to create template' });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
updateTemplate: async (event) => {
|
||||||
|
if (!event.locals.session) throw redirect(303, '/login');
|
||||||
|
const famId = event.locals.session.famId;
|
||||||
|
const fd = await event.request.formData();
|
||||||
|
const id = fd.get('id') as string;
|
||||||
|
const data: Record<string, unknown> = {};
|
||||||
|
const name = fd.get('name');
|
||||||
|
if (name) data.name = name;
|
||||||
|
const target = fd.get('target');
|
||||||
|
if (target) data.target = target;
|
||||||
|
const type = fd.get('type');
|
||||||
|
if (type) data.type = type;
|
||||||
|
const occurrence = fd.get('occurrence');
|
||||||
|
if (occurrence) data.occurrence = occurrence;
|
||||||
|
const rewardType = fd.get('rewardType');
|
||||||
|
if (rewardType) data.rewardType = rewardType;
|
||||||
|
const rewardValue = fd.get('rewardValue');
|
||||||
|
if (rewardValue) data.rewardValue = rewardValue;
|
||||||
|
const criteriaValue = fd.get('criteriaValue');
|
||||||
|
if (criteriaValue) data.criteriaValue = parseInt(criteriaValue as string, 10) || 0;
|
||||||
|
const period = fd.get('period');
|
||||||
|
if (period !== null) data.period = period;
|
||||||
|
if (occurrence === 'once') data.period = '';
|
||||||
|
const description = fd.get('description');
|
||||||
|
if (description) data.description = description;
|
||||||
|
try {
|
||||||
|
const record = await hono.admin.update(event, 'bonus-templates', famId, id, data);
|
||||||
|
return { record };
|
||||||
|
} catch (e) {
|
||||||
|
return fail(400, { error: e instanceof Error ? e.message : 'Failed to update template' });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
deleteTemplate: async (event) => {
|
||||||
|
if (!event.locals.session) throw redirect(303, '/login');
|
||||||
|
const famId = event.locals.session.famId;
|
||||||
|
const fd = await event.request.formData();
|
||||||
|
const id = fd.get('id') as string;
|
||||||
|
try {
|
||||||
|
await hono.admin.remove(event, 'bonus-templates', famId, id);
|
||||||
|
return { deleted: true };
|
||||||
|
} catch (e) {
|
||||||
|
return fail(400, { error: e instanceof Error ? e.message : 'Failed to delete template' });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
createConfig: async (event) => {
|
createConfig: async (event) => {
|
||||||
if (!event.locals.session) throw redirect(303, '/login');
|
if (!event.locals.session) throw redirect(303, '/login');
|
||||||
const famId = event.locals.session.famId;
|
const famId = event.locals.session.famId;
|
||||||
const fd = await event.request.formData();
|
const fd = await event.request.formData();
|
||||||
const phase = fd.get('phase') as string;
|
const startMode = fd.get('startMode') as string;
|
||||||
|
const status = startMode === 'disabled' ? 'disabled' : 'active';
|
||||||
const data: Record<string, unknown> = {
|
const data: Record<string, unknown> = {
|
||||||
name: fd.get('name'),
|
name: fd.get('name'),
|
||||||
target: fd.get('target'),
|
target: fd.get('target'),
|
||||||
@@ -26,12 +100,13 @@ export const actions = {
|
|||||||
occurrence: fd.get('occurrence'),
|
occurrence: fd.get('occurrence'),
|
||||||
rewardType: fd.get('rewardType'),
|
rewardType: fd.get('rewardType'),
|
||||||
rewardValue: fd.get('rewardValue'),
|
rewardValue: fd.get('rewardValue'),
|
||||||
phase: phase || 'ready',
|
status
|
||||||
};
|
};
|
||||||
const criteriaValue = fd.get('criteriaValue');
|
const criteriaValue = fd.get('criteriaValue');
|
||||||
if (criteriaValue) data.criteriaValue = parseInt(criteriaValue as string, 10) || 0;
|
if (criteriaValue) data.criteriaValue = parseInt(criteriaValue as string, 10) || 0;
|
||||||
const period = fd.get('period');
|
const period = fd.get('period');
|
||||||
if (period !== null) data.period = period;
|
if (period !== null) data.period = period;
|
||||||
|
if (data.occurrence === 'once') data.period = '';
|
||||||
const description = fd.get('description');
|
const description = fd.get('description');
|
||||||
if (description) data.description = description;
|
if (description) data.description = description;
|
||||||
const memberId = fd.get('memberId');
|
const memberId = fd.get('memberId');
|
||||||
@@ -66,6 +141,7 @@ export const actions = {
|
|||||||
if (criteriaValue) data.criteriaValue = parseInt(criteriaValue as string, 10) || 0;
|
if (criteriaValue) data.criteriaValue = parseInt(criteriaValue as string, 10) || 0;
|
||||||
const period = fd.get('period');
|
const period = fd.get('period');
|
||||||
if (period !== null) data.period = period;
|
if (period !== null) data.period = period;
|
||||||
|
if (occurrence === 'once') data.period = '';
|
||||||
const description = fd.get('description');
|
const description = fd.get('description');
|
||||||
if (description) data.description = description;
|
if (description) data.description = description;
|
||||||
const memberId = fd.get('memberId');
|
const memberId = fd.get('memberId');
|
||||||
@@ -87,7 +163,7 @@ export const actions = {
|
|||||||
await hono.admin.remove(event, 'bonus-configs', famId, id);
|
await hono.admin.remove(event, 'bonus-configs', famId, id);
|
||||||
return { deleted: true };
|
return { deleted: true };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return fail(400, { error: e instanceof Error ? e.message : 'Failed to archive config' });
|
return fail(400, { error: e instanceof Error ? e.message : 'Failed to delete config' });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -95,6 +171,8 @@ export const actions = {
|
|||||||
if (!event.locals.session) throw redirect(303, '/login');
|
if (!event.locals.session) throw redirect(303, '/login');
|
||||||
const famId = event.locals.session.famId;
|
const famId = event.locals.session.famId;
|
||||||
const fd = await event.request.formData();
|
const fd = await event.request.formData();
|
||||||
|
const startMode = fd.get('startMode') as string;
|
||||||
|
const status = startMode === 'disabled' ? 'disabled' : 'active';
|
||||||
const data: Record<string, unknown> = {
|
const data: Record<string, unknown> = {
|
||||||
name: fd.get('name'),
|
name: fd.get('name'),
|
||||||
description: fd.get('description') || '',
|
description: fd.get('description') || '',
|
||||||
@@ -106,13 +184,16 @@ export const actions = {
|
|||||||
criteriaValue: parseInt(fd.get('criteriaValue') as string, 10) || 0,
|
criteriaValue: parseInt(fd.get('criteriaValue') as string, 10) || 0,
|
||||||
period: fd.get('period') || '',
|
period: fd.get('period') || '',
|
||||||
memberId: fd.get('memberId') || '',
|
memberId: fd.get('memberId') || '',
|
||||||
phase: 'active',
|
status
|
||||||
};
|
};
|
||||||
|
if (data.occurrence === 'once') data.period = '';
|
||||||
try {
|
try {
|
||||||
const record = await hono.admin.create(event, 'bonus-configs', famId, data);
|
const record = await hono.admin.create(event, 'bonus-configs', famId, data);
|
||||||
return { record };
|
return { record };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return fail(400, { error: e instanceof Error ? e.message : 'Failed to create bonus from template' });
|
return fail(400, {
|
||||||
|
error: e instanceof Error ? e.message : 'Failed to create bonus from template'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -124,7 +205,10 @@ export const actions = {
|
|||||||
const target = fd.get('target') as string;
|
const target = fd.get('target') as string;
|
||||||
const memberId = fd.get('memberId') as string;
|
const memberId = fd.get('memberId') as string;
|
||||||
try {
|
try {
|
||||||
const record = await hono.admin.assignBonusConfig(event, famId, id, { target, memberId: memberId || null });
|
const record = await hono.admin.assignBonusConfig(event, famId, id, {
|
||||||
|
target,
|
||||||
|
memberId: memberId || null
|
||||||
|
});
|
||||||
return { record };
|
return { record };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return fail(400, { error: e instanceof Error ? e.message : 'Failed to assign bonus' });
|
return fail(400, { error: e instanceof Error ? e.message : 'Failed to assign bonus' });
|
||||||
@@ -136,12 +220,11 @@ export const actions = {
|
|||||||
const famId = event.locals.session.famId;
|
const famId = event.locals.session.famId;
|
||||||
const fd = await event.request.formData();
|
const fd = await event.request.formData();
|
||||||
const id = fd.get('id') as string;
|
const id = fd.get('id') as string;
|
||||||
const phase = fd.get('phase') as string;
|
|
||||||
try {
|
try {
|
||||||
const record = await hono.admin.completeBonusConfig(event, famId, id, phase || 'completed');
|
const record = await hono.admin.completeBonusConfig(event, famId, id);
|
||||||
return { record };
|
return { record };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return fail(400, { error: e instanceof Error ? e.message : 'Failed to update bonus phase' });
|
return fail(400, { error: e instanceof Error ? e.message : 'Failed to complete bonus' });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -158,6 +241,23 @@ export const actions = {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
toggleConfig: async (event) => {
|
||||||
|
if (!event.locals.session) throw redirect(303, '/login');
|
||||||
|
const famId = event.locals.session.famId;
|
||||||
|
const fd = await event.request.formData();
|
||||||
|
const id = fd.get('id') as string;
|
||||||
|
const currentStatus = fd.get('currentStatus') as string;
|
||||||
|
const newStatus = currentStatus === 'disabled' ? 'active' : 'disabled';
|
||||||
|
try {
|
||||||
|
const record = await hono.admin.update(event, 'bonus-configs', famId, id, {
|
||||||
|
status: newStatus
|
||||||
|
});
|
||||||
|
return { record };
|
||||||
|
} catch (e) {
|
||||||
|
return fail(400, { error: e instanceof Error ? e.message : 'Failed to toggle bonus' });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
claimReward: async (event) => {
|
claimReward: async (event) => {
|
||||||
if (!event.locals.session) throw redirect(303, '/login');
|
if (!event.locals.session) throw redirect(303, '/login');
|
||||||
const famId = event.locals.session.famId;
|
const famId = event.locals.session.famId;
|
||||||
@@ -178,5 +278,5 @@ export const actions = {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
return { error: e instanceof Error ? e.message : 'Failed to evaluate' };
|
return { error: e instanceof Error ? e.message : 'Failed to evaluate' };
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -17,7 +17,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function rewardAmount(r: any): string {
|
function rewardAmount(r: any): string {
|
||||||
if (r.rewardType === 'cash') return `£${(Number(r.value) / 100).toFixed(2)}`;
|
if (r.rewardType === 'cash') return `£${Number(r.value).toFixed(2)}`;
|
||||||
if (r.rewardType === 'points') return `${r.value} pts`;
|
if (r.rewardType === 'points') return `${r.value} pts`;
|
||||||
return r.label;
|
return r.label;
|
||||||
}
|
}
|
||||||
@@ -112,7 +112,7 @@
|
|||||||
<td></td>
|
<td></td>
|
||||||
<td></td>
|
<td></td>
|
||||||
<td class="num"><strong>Outstanding cash</strong></td>
|
<td class="num"><strong>Outstanding cash</strong></td>
|
||||||
<td class="num"><strong>£{(totalOutstanding / 100).toFixed(2)}</strong></td>
|
<td class="num"><strong>£{totalOutstanding.toFixed(2)}</strong></td>
|
||||||
<td></td>
|
<td></td>
|
||||||
<td></td>
|
<td></td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
+293
-272
@@ -3,333 +3,354 @@ import { SERVER_IP, PB_PORT, PB_EMAIL, PB_PASSWORD } from "../../config.ts";
|
|||||||
const PB_ENDPOINT = `http://${SERVER_IP}:${PB_PORT}`;
|
const PB_ENDPOINT = `http://${SERVER_IP}:${PB_PORT}`;
|
||||||
|
|
||||||
interface FieldDef {
|
interface FieldDef {
|
||||||
name: string
|
name: string;
|
||||||
type: string
|
type: string;
|
||||||
required?: boolean
|
required?: boolean;
|
||||||
unique?: boolean
|
unique?: boolean;
|
||||||
max?: number
|
max?: number;
|
||||||
min?: number
|
min?: number;
|
||||||
values?: string[]
|
values?: string[];
|
||||||
maxSelect?: number
|
maxSelect?: number;
|
||||||
collectionId?: string
|
collectionId?: string;
|
||||||
cascadeDelete?: boolean
|
cascadeDelete?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CollectionDef {
|
interface CollectionDef {
|
||||||
name: string
|
name: string;
|
||||||
type: string
|
type: string;
|
||||||
fields: FieldDef[]
|
fields: FieldDef[];
|
||||||
listRule?: string | null
|
listRule?: string | null;
|
||||||
viewRule?: string | null
|
viewRule?: string | null;
|
||||||
createRule?: string | null
|
createRule?: string | null;
|
||||||
updateRule?: string | null
|
updateRule?: string | null;
|
||||||
deleteRule?: string | null
|
deleteRule?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getSuperadminToken(): Promise<string> {
|
async function getSuperadminToken(): Promise<string> {
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
`${PB_ENDPOINT}/api/collections/_superusers/auth-with-password`,
|
`${PB_ENDPOINT}/api/collections/_superusers/auth-with-password`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ identity: PB_EMAIL, password: PB_PASSWORD }),
|
body: JSON.stringify({ identity: PB_EMAIL, password: PB_PASSWORD }),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) throw new Error(`Auth failed: ${JSON.stringify(data)}`);
|
if (!res.ok) throw new Error(`Auth failed: ${JSON.stringify(data)}`);
|
||||||
return data.token;
|
return data.token;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createCollection(
|
async function createCollection(
|
||||||
token: string,
|
token: string,
|
||||||
col: CollectionDef,
|
col: CollectionDef,
|
||||||
): Promise<string | null> {
|
): Promise<string | null> {
|
||||||
const existing = await fetch(
|
const existing = await fetch(
|
||||||
`${PB_ENDPOINT}/api/collections?filter=name='${col.name}'`,
|
`${PB_ENDPOINT}/api/collections?filter=name='${col.name}'`,
|
||||||
{ headers: { Authorization: `Bearer ${token}` } },
|
{ headers: { Authorization: `Bearer ${token}` } },
|
||||||
);
|
);
|
||||||
const existingData = await existing.json();
|
const existingData = await existing.json();
|
||||||
if (existingData?.items?.length > 0) {
|
if (existingData?.items?.length > 0) {
|
||||||
console.log(` ↳ Already exists: ${col.name}`);
|
console.log(` ↳ Already exists: ${col.name}`);
|
||||||
return existingData.items[0].id;
|
return existingData.items[0].id;
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await fetch(`${PB_ENDPOINT}/api/collections`, {
|
const res = await fetch(`${PB_ENDPOINT}/api/collections`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify(col),
|
body: JSON.stringify(col),
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) throw new Error(`Create ${col.name} failed: ${JSON.stringify(data)}`);
|
if (!res.ok)
|
||||||
console.log(` ✓ Created: ${col.name}`);
|
throw new Error(`Create ${col.name} failed: ${JSON.stringify(data)}`);
|
||||||
return data.id;
|
console.log(` ✓ Created: ${col.name}`);
|
||||||
|
return data.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
function text(name: string, required = false): FieldDef {
|
function text(name: string, required = false): FieldDef {
|
||||||
return { name, type: "text", required };
|
return { name, type: "text", required };
|
||||||
}
|
}
|
||||||
|
|
||||||
function uniqueText(name: string): FieldDef {
|
function uniqueText(name: string): FieldDef {
|
||||||
return { name, type: "text", required: true, unique: true };
|
return { name, type: "text", required: true, unique: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
function number(name: string, required = false): FieldDef {
|
function number(name: string, required = false): FieldDef {
|
||||||
return { name, type: "number", required };
|
return { name, type: "number", required };
|
||||||
}
|
}
|
||||||
|
|
||||||
function bool(name: string): FieldDef {
|
function bool(name: string): FieldDef {
|
||||||
return { name, type: "bool" };
|
return { name, type: "bool" };
|
||||||
}
|
}
|
||||||
|
|
||||||
function date(name: string): FieldDef {
|
function date(name: string): FieldDef {
|
||||||
return { name, type: "date" };
|
return { name, type: "date" };
|
||||||
}
|
}
|
||||||
|
|
||||||
function jsonField(name: string): FieldDef {
|
function jsonField(name: string): FieldDef {
|
||||||
return { name, type: "json" };
|
return { name, type: "json" };
|
||||||
}
|
}
|
||||||
|
|
||||||
function select(name: string, values: string[], required = false): FieldDef {
|
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 };
|
||||||
}
|
}
|
||||||
|
|
||||||
function rel(name: string, collectionId: string, required = false): FieldDef {
|
function rel(name: string, collectionId: string, required = false): FieldDef {
|
||||||
return {
|
return {
|
||||||
name,
|
name,
|
||||||
type: "relation",
|
type: "relation",
|
||||||
required,
|
required,
|
||||||
collectionId,
|
collectionId,
|
||||||
maxSelect: 1,
|
maxSelect: 1,
|
||||||
cascadeDelete: false,
|
cascadeDelete: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
console.log("Connecting to PB at", PB_ENDPOINT);
|
console.log("Connecting to PB at", PB_ENDPOINT);
|
||||||
const token = await getSuperadminToken();
|
const token = await getSuperadminToken();
|
||||||
console.log("Authenticated as superadmin\n");
|
console.log("Authenticated as superadmin\n");
|
||||||
|
|
||||||
const ids: Record<string, string> = {};
|
const ids: Record<string, string> = {};
|
||||||
|
|
||||||
// ── Pass 1: Independent collections ──
|
// ── Pass 1: Independent collections ──
|
||||||
console.log("--- Pass 1: Independent collections ---");
|
console.log("--- Pass 1: Independent collections ---");
|
||||||
|
|
||||||
ids.fams = await createCollection(token, {
|
ids.fams = await createCollection(token, {
|
||||||
name: "fams",
|
name: "fams",
|
||||||
type: "base",
|
type: "base",
|
||||||
listRule: "",
|
listRule: "",
|
||||||
viewRule: "",
|
viewRule: "",
|
||||||
createRule: null,
|
createRule: null,
|
||||||
updateRule: null,
|
updateRule: null,
|
||||||
deleteRule: null,
|
deleteRule: null,
|
||||||
fields: [
|
fields: [
|
||||||
text("name", true),
|
text("name", true),
|
||||||
uniqueText("slug"),
|
uniqueText("slug"),
|
||||||
text("inviteCode"),
|
text("inviteCode"),
|
||||||
text("stripeCustomerId"),
|
text("stripeCustomerId"),
|
||||||
jsonField("featureFlags"),
|
jsonField("featureFlags"),
|
||||||
jsonField("seasons"),
|
jsonField("seasons"),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Pass 2: Collections that reference fams ──
|
// ── Pass 2: Collections that reference fams ──
|
||||||
console.log("\n--- Pass 2: fam-scoped collections ---");
|
console.log("\n--- Pass 2: fam-scoped collections ---");
|
||||||
|
|
||||||
ids.settings = await createCollection(token, {
|
ids.settings = await createCollection(token, {
|
||||||
name: "settings",
|
name: "settings",
|
||||||
type: "base",
|
type: "base",
|
||||||
listRule: "",
|
listRule: "",
|
||||||
viewRule: "",
|
viewRule: "",
|
||||||
createRule: null,
|
createRule: null,
|
||||||
updateRule: null,
|
updateRule: null,
|
||||||
deleteRule: null,
|
deleteRule: null,
|
||||||
fields: [
|
fields: [rel("famId", ids.fams!, true), text("webhookUrl")],
|
||||||
rel("famId", ids.fams!, true),
|
});
|
||||||
text("webhookUrl"),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
ids.members = await createCollection(token, {
|
ids.members = await createCollection(token, {
|
||||||
name: "members",
|
name: "members",
|
||||||
type: "base",
|
type: "base",
|
||||||
listRule: "",
|
listRule: "",
|
||||||
viewRule: "",
|
viewRule: "",
|
||||||
createRule: null,
|
createRule: null,
|
||||||
updateRule: null,
|
updateRule: null,
|
||||||
deleteRule: null,
|
deleteRule: null,
|
||||||
fields: [
|
fields: [
|
||||||
rel("famId", ids.fams!, true),
|
rel("famId", ids.fams!, true),
|
||||||
text("name", true),
|
text("name", true),
|
||||||
text("color"),
|
text("color"),
|
||||||
text("deviceToken"),
|
text("deviceToken"),
|
||||||
text("deviceTokenHint"),
|
text("deviceTokenHint"),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
ids.chore_templates = await createCollection(token, {
|
ids.chore_templates = await createCollection(token, {
|
||||||
name: "chore_templates",
|
name: "chore_templates",
|
||||||
type: "base",
|
type: "base",
|
||||||
listRule: "",
|
listRule: "",
|
||||||
viewRule: "",
|
viewRule: "",
|
||||||
createRule: null,
|
createRule: null,
|
||||||
updateRule: null,
|
updateRule: null,
|
||||||
deleteRule: null,
|
deleteRule: null,
|
||||||
fields: [
|
fields: [
|
||||||
rel("famId", ids.fams!, true),
|
rel("famId", ids.fams!, true),
|
||||||
text("name", true),
|
text("name", true),
|
||||||
text("description"),
|
text("description"),
|
||||||
select("defaultFrequency", ["daily", "weekly"], true),
|
select("defaultFrequency", ["daily", "weekly"], true),
|
||||||
select("defaultType", ["points", "money"], true),
|
select("defaultType", ["points", "money"], true),
|
||||||
number("defaultValue", true),
|
number("defaultValue", true),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
ids.fam_admins = await createCollection(token, {
|
ids.fam_admins = await createCollection(token, {
|
||||||
name: "fam_admins",
|
name: "fam_admins",
|
||||||
type: "base",
|
type: "base",
|
||||||
listRule: "",
|
listRule: "",
|
||||||
viewRule: "",
|
viewRule: "",
|
||||||
createRule: null,
|
createRule: null,
|
||||||
updateRule: null,
|
updateRule: null,
|
||||||
deleteRule: null,
|
deleteRule: null,
|
||||||
fields: [
|
fields: [
|
||||||
rel("famId", ids.fams!, true),
|
rel("famId", ids.fams!, true),
|
||||||
text("userId", true),
|
text("userId", true),
|
||||||
text("email", true),
|
text("email", true),
|
||||||
text("name"),
|
text("name"),
|
||||||
text("color"),
|
text("color"),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
ids.bonus_configs = await createCollection(token, {
|
ids.bonus_configs = await createCollection(token, {
|
||||||
name: "bonus_configs",
|
name: "bonus_configs",
|
||||||
type: "base",
|
type: "base",
|
||||||
listRule: "",
|
listRule: "",
|
||||||
viewRule: "",
|
viewRule: "",
|
||||||
createRule: null,
|
createRule: null,
|
||||||
updateRule: null,
|
updateRule: null,
|
||||||
deleteRule: null,
|
deleteRule: null,
|
||||||
fields: [
|
fields: [
|
||||||
rel("famId", ids.fams!, true),
|
rel("famId", ids.fams!, true),
|
||||||
text("name", true),
|
text("name", true),
|
||||||
text("description"),
|
text("description"),
|
||||||
select("target", ["individual", "competitive"], true),
|
select("target", ["individual", "competitive", "collaborative"], true),
|
||||||
select("type", ["threshold", "count", "manual"], true),
|
select("type", ["threshold", "count", "manual"], true),
|
||||||
select("occurrence", ["recurring", "once"], true),
|
select("occurrence", ["recurring", "once"], true),
|
||||||
select("rewardType", ["points", "cash", "prize"], true),
|
select("rewardType", ["points", "cash", "prize"], true),
|
||||||
text("rewardValue", true),
|
text("rewardValue", true),
|
||||||
number("criteriaValue"),
|
number("criteriaValue"),
|
||||||
select("period", ["weekly", "monthly"]),
|
rel("memberId", ids.members!),
|
||||||
select("status", ["active", "archived"], true),
|
select("period", ["schedule", "daily", "weekly", "monthly"]),
|
||||||
],
|
select("status", ["active", "completed"], true),
|
||||||
});
|
],
|
||||||
|
});
|
||||||
|
|
||||||
// ── Pass 3: Collections with member/template deps ──
|
ids.bonus_templates = await createCollection(token, {
|
||||||
console.log("\n--- Pass 3: Nested collections ---");
|
name: "bonus_templates",
|
||||||
|
type: "base",
|
||||||
|
listRule: "",
|
||||||
|
viewRule: "",
|
||||||
|
createRule: null,
|
||||||
|
updateRule: null,
|
||||||
|
deleteRule: null,
|
||||||
|
fields: [
|
||||||
|
rel("famId", ids.fams!, true),
|
||||||
|
text("name", true),
|
||||||
|
text("description"),
|
||||||
|
select("target", ["individual", "competitive", "collaborative"], true),
|
||||||
|
select("type", ["threshold", "count", "manual"], true),
|
||||||
|
select("occurrence", ["recurring", "once"], true),
|
||||||
|
select("rewardType", ["points", "cash", "prize"], true),
|
||||||
|
text("rewardValue", true),
|
||||||
|
number("criteriaValue"),
|
||||||
|
select("period", ["schedule", "daily", "weekly", "monthly"]),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
ids.weekly_history = await createCollection(token, {
|
// ── Pass 3: Collections with member/template deps ──
|
||||||
name: "weekly_history",
|
console.log("\n--- Pass 3: Nested collections ---");
|
||||||
type: "base",
|
|
||||||
listRule: "",
|
|
||||||
viewRule: "",
|
|
||||||
createRule: null,
|
|
||||||
updateRule: null,
|
|
||||||
deleteRule: null,
|
|
||||||
fields: [
|
|
||||||
rel("famId", ids.fams!, true),
|
|
||||||
rel("memberId", ids.members!, true),
|
|
||||||
date("weekStart"),
|
|
||||||
number("pointsEarned"),
|
|
||||||
number("moneyEarned"),
|
|
||||||
number("choresCompleted"),
|
|
||||||
number("bonusEarned"),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
ids.rewards = await createCollection(token, {
|
ids.weekly_history = await createCollection(token, {
|
||||||
name: "rewards",
|
name: "weekly_history",
|
||||||
type: "base",
|
type: "base",
|
||||||
listRule: "",
|
listRule: "",
|
||||||
viewRule: "",
|
viewRule: "",
|
||||||
createRule: null,
|
createRule: null,
|
||||||
updateRule: null,
|
updateRule: null,
|
||||||
deleteRule: null,
|
deleteRule: null,
|
||||||
fields: [
|
fields: [
|
||||||
rel("famId", ids.fams!, true),
|
rel("famId", ids.fams!, true),
|
||||||
rel("memberId", ids.members!, true),
|
rel("memberId", ids.members!, true),
|
||||||
rel("bonusConfigId", ids.bonus_configs!),
|
date("weekStart"),
|
||||||
text("label", true),
|
number("pointsEarned"),
|
||||||
number("value", true),
|
number("moneyEarned"),
|
||||||
select("rewardType", ["cash", "prize", "points"], true),
|
number("choresCompleted"),
|
||||||
select("status", ["unclaimed", "requested", "claimed"], true),
|
number("bonusEarned"),
|
||||||
date("claimedAt"),
|
],
|
||||||
date("requestedAt"),
|
});
|
||||||
text("date"),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
ids.assigned_chores = await createCollection(token, {
|
ids.rewards = await createCollection(token, {
|
||||||
name: "assigned_chores",
|
name: "rewards",
|
||||||
type: "base",
|
type: "base",
|
||||||
listRule: "",
|
listRule: "",
|
||||||
viewRule: "",
|
viewRule: "",
|
||||||
createRule: null,
|
createRule: null,
|
||||||
updateRule: null,
|
updateRule: null,
|
||||||
deleteRule: null,
|
deleteRule: null,
|
||||||
fields: [
|
fields: [
|
||||||
rel("famId", ids.fams!, true),
|
rel("famId", ids.fams!, true),
|
||||||
rel("memberId", ids.members!, true),
|
rel("memberId", ids.members!, true),
|
||||||
rel("templateId", ids.chore_templates!, true),
|
rel("bonusConfigId", ids.bonus_configs!),
|
||||||
select("frequency", ["daily", "weekly"], true),
|
text("label", true),
|
||||||
select("type", ["points", "money"], true),
|
number("value", true),
|
||||||
number("value", true),
|
select("rewardType", ["cash", "prize", "points"], true),
|
||||||
text("customName"),
|
select("status", ["unclaimed", "requested", "claimed"], true),
|
||||||
jsonField("seasonIds"),
|
date("claimedAt"),
|
||||||
],
|
date("requestedAt"),
|
||||||
});
|
text("date"),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
ids.seasons = await createCollection(token, {
|
ids.assigned_chores = await createCollection(token, {
|
||||||
name: "seasons",
|
name: "assigned_chores",
|
||||||
type: "base",
|
type: "base",
|
||||||
listRule: "",
|
listRule: "",
|
||||||
viewRule: "",
|
viewRule: "",
|
||||||
createRule: null,
|
createRule: null,
|
||||||
updateRule: null,
|
updateRule: null,
|
||||||
deleteRule: null,
|
deleteRule: null,
|
||||||
fields: [
|
fields: [
|
||||||
rel("famId", ids.fams!, true),
|
rel("famId", ids.fams!, true),
|
||||||
text("name", true),
|
rel("memberId", ids.members!, true),
|
||||||
text("color"),
|
rel("templateId", ids.chore_templates!, true),
|
||||||
bool("active"),
|
select("frequency", ["daily", "weekly"], true),
|
||||||
date("autoDisable"),
|
select("type", ["points", "money"], true),
|
||||||
date("autoStart"),
|
number("value", true),
|
||||||
],
|
text("customName"),
|
||||||
});
|
jsonField("seasonIds"),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
ids.completions = await createCollection(token, {
|
ids.seasons = await createCollection(token, {
|
||||||
name: "completions",
|
name: "seasons",
|
||||||
type: "base",
|
type: "base",
|
||||||
listRule: "",
|
listRule: "",
|
||||||
viewRule: "",
|
viewRule: "",
|
||||||
createRule: null,
|
createRule: null,
|
||||||
updateRule: null,
|
updateRule: null,
|
||||||
deleteRule: null,
|
deleteRule: null,
|
||||||
fields: [
|
fields: [
|
||||||
rel("famId", ids.fams!, true),
|
rel("famId", ids.fams!, true),
|
||||||
rel("memberId", ids.members!, true),
|
text("name", true),
|
||||||
rel("assignedChoreId", ids.assigned_chores!, true),
|
text("color"),
|
||||||
date("date"),
|
bool("active"),
|
||||||
],
|
date("autoDisable"),
|
||||||
});
|
date("autoStart"),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
console.log("\n✅ All collections created successfully");
|
ids.completions = await createCollection(token, {
|
||||||
console.log("Collection IDs:", ids);
|
name: "completions",
|
||||||
|
type: "base",
|
||||||
|
listRule: "",
|
||||||
|
viewRule: "",
|
||||||
|
createRule: null,
|
||||||
|
updateRule: null,
|
||||||
|
deleteRule: null,
|
||||||
|
fields: [
|
||||||
|
rel("famId", ids.fams!, true),
|
||||||
|
rel("memberId", ids.members!, true),
|
||||||
|
rel("assignedChoreId", ids.assigned_chores!, true),
|
||||||
|
date("date"),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("\n✅ All collections created successfully");
|
||||||
|
console.log("Collection IDs:", ids);
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch((err) => {
|
main().catch((err) => {
|
||||||
console.error("Seed failed:", err);
|
console.error("Seed failed:", err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|||||||
+1561
-1025
File diff suppressed because it is too large
Load Diff
+1113
-696
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user