varierty of implementstions based on platform droplet issuance
This commit is contained in:
@@ -322,15 +322,47 @@ async function ensureFamFields(): Promise<void> {
|
||||
}
|
||||
|
||||
export async function migrate(): Promise<void> {
|
||||
console.log("[migrate] Checking PB collection schemas...");
|
||||
await ensureSchema();
|
||||
// Runs even when the schema already exists (unlike ensureSchema's early
|
||||
// return) so new platform collections/fields/seed land on existing installs.
|
||||
await ensureFamFields();
|
||||
await ensureBonusFields();
|
||||
await ensureAccessCodes();
|
||||
await ensurePlatform();
|
||||
console.log("[migrate] Done");
|
||||
console.log("[migrate] Checking PB collection schemas...");
|
||||
await ensureSchema();
|
||||
// Runs even when the schema already exists (unlike ensureSchema's early
|
||||
// return) so new platform collections/fields/seed land on existing installs.
|
||||
await ensureFamFields();
|
||||
await ensureBonusFields();
|
||||
await ensureTemplateFields();
|
||||
await ensureAssignedChoreFields();
|
||||
await ensureAccessCodes();
|
||||
await ensurePlatform();
|
||||
console.log("[migrate] Done");
|
||||
}
|
||||
|
||||
// Add colour / icon / description to `assigned_chores` on existing installs so
|
||||
// family-admins can override a template's look per assignment. Idempotent.
|
||||
async function ensureAssignedChoreFields(): Promise<void> {
|
||||
const col = await getCollection("assigned_chores");
|
||||
if (!col) return;
|
||||
const has = (n: string) => col.fields.some((f: any) => f.name === n);
|
||||
const needed: any[] = [];
|
||||
if (!has("description")) needed.push({ name: "description", type: "text", required: false });
|
||||
if (!has("icon")) needed.push({ name: "icon", type: "text", required: false });
|
||||
if (!has("color")) needed.push({ name: "color", type: "text", required: false });
|
||||
if (!has("emoji")) needed.push({ name: "emoji", type: "text", required: false });
|
||||
// Todos can be celebration-only (emoji) as well as points/money.
|
||||
let changed = !!needed.length;
|
||||
const typeField = col.fields.find((f: any) => f.name === "type");
|
||||
if (typeField && Array.isArray(typeField.values) && !typeField.values.includes("emoji")) {
|
||||
typeField.values = [...typeField.values, "emoji"];
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
await updateCollection(col.id, { ...col, fields: [...col.fields] });
|
||||
}
|
||||
const comp = await getCollection("completions");
|
||||
if (comp && !comp.fields.some((f: any) => f.name === "rewardId")) {
|
||||
await updateCollection(comp.id, {
|
||||
...comp,
|
||||
fields: [...comp.fields, { name: "rewardId", type: "text", required: false }],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Add the pocket-money fields to bonus collections on existing installs, and
|
||||
@@ -367,6 +399,21 @@ async function ensureBonusFields(): Promise<void> {
|
||||
|
||||
async function backfillPocketMoney(): Promise<void> {
|
||||
const t = await auth();
|
||||
// Flag legacy pocket-money configs that predate the isPocketMoney field so
|
||||
// the dashboard recognises them (and we don't create duplicates below).
|
||||
const legacyRes = await fetch(
|
||||
`${PB_ENDPOINT}/api/collections/bonus_configs/records?filter=${encodeURIComponent(
|
||||
"isPocketMoney!=true && name~'pocket' && thresholdType='percent'"
|
||||
)}&perPage=500`,
|
||||
{ headers: { Authorization: `Bearer ${t}` } }
|
||||
);
|
||||
for (const rec of (await legacyRes.json())?.items || []) {
|
||||
await fetch(`${PB_ENDPOINT}/api/collections/bonus_configs/records/${rec.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${t}` },
|
||||
body: JSON.stringify({ isPocketMoney: true }),
|
||||
}).catch(() => {});
|
||||
}
|
||||
const childrenRes = await fetch(
|
||||
`${PB_ENDPOINT}/api/collections/users/records?filter=role='child'&perPage=500`,
|
||||
{ headers: { Authorization: `Bearer ${t}` } }
|
||||
@@ -399,4 +446,143 @@ async function backfillPocketMoney(): Promise<void> {
|
||||
}).catch(() => {});
|
||||
}
|
||||
console.log("[migrate] Pocket-money droplets ensured.");
|
||||
}
|
||||
}
|
||||
|
||||
// Promote chore_templates / bonus_templates to platform-owned: add global/icon/
|
||||
// color fields, make famId optional, and relax read rules so any family can see
|
||||
// global (platform) templates as assignable droplets. Idempotent. Seeds a
|
||||
// starter set of global templates on first run for out-of-the-box usage.
|
||||
async function ensureTemplateFields(): Promise<void> {
|
||||
const readRule = "global = true || famId = @request.auth.famId";
|
||||
for (const name of ["chore_templates", "bonus_templates"]) {
|
||||
const col = await getCollection(name);
|
||||
if (!col) continue;
|
||||
const has = (n: string) => col.fields.some((f: any) => f.name === n);
|
||||
let changed = false;
|
||||
const fields = [...col.fields];
|
||||
for (const f of [
|
||||
{ name: "global", type: "bool", required: false },
|
||||
{ name: "icon", type: "text", required: false },
|
||||
{ name: "color", type: "text", required: false },
|
||||
]) {
|
||||
if (!has(f.name)) {
|
||||
fields.push(f);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const famId = fields.find((f: any) => f.name === "famId");
|
||||
if (famId && famId.required) {
|
||||
famId.required = false;
|
||||
changed = true;
|
||||
}
|
||||
if (col.listRule !== readRule || col.viewRule !== readRule) {
|
||||
col.listRule = readRule;
|
||||
col.viewRule = readRule;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) await updateCollection(col.id, { ...col, fields });
|
||||
}
|
||||
await seedGlobalTemplates();
|
||||
}
|
||||
|
||||
const GLOBAL_TEMPLATE_ICONS = [
|
||||
"Bed",
|
||||
"Sparkles",
|
||||
"BookOpen",
|
||||
"Utensils",
|
||||
"Wallet",
|
||||
"Trophy",
|
||||
"Star",
|
||||
"Moon",
|
||||
"Sun",
|
||||
"Apple",
|
||||
"Car",
|
||||
"Gamepad2",
|
||||
"Music",
|
||||
"Shirt",
|
||||
"Leaf",
|
||||
"Heart",
|
||||
"Gift",
|
||||
"Timer",
|
||||
];
|
||||
|
||||
async function seedGlobalTemplates(): Promise<void> {
|
||||
const t = await auth();
|
||||
const countGlobal = async (name: string) => {
|
||||
const res = await fetch(
|
||||
`${PB_ENDPOINT}/api/collections/${name}/records?filter=global=true&perPage=1`,
|
||||
{ headers: { Authorization: `Bearer ${t}` } }
|
||||
);
|
||||
return ((await res.json())?.items?.length) || 0;
|
||||
};
|
||||
if ((await countGlobal("chore_templates")) > 0 || (await countGlobal("bonus_templates")) > 0) {
|
||||
console.log("[migrate] Global templates already present — skipping seed.");
|
||||
return;
|
||||
}
|
||||
|
||||
const choreSeeds = [
|
||||
{ name: "Make Bed", defaultFrequency: "daily", defaultType: "points", defaultValue: 2, icon: "Bed", color: "#6366f1" },
|
||||
{ name: "Tidy Room", defaultFrequency: "weekly", defaultType: "points", defaultValue: 10, icon: "Sparkles", color: "#8b5cf6" },
|
||||
{ name: "Homework", defaultFrequency: "daily", defaultType: "points", defaultValue: 5, icon: "BookOpen", color: "#0ea5e9" },
|
||||
{ name: "Set Table", defaultFrequency: "daily", defaultType: "money", defaultValue: 1, icon: "Utensils", color: "#10b981" },
|
||||
];
|
||||
const bonusSeeds = [
|
||||
{
|
||||
name: "Pocket Money",
|
||||
target: "individual",
|
||||
type: "threshold",
|
||||
thresholdType: "percent",
|
||||
occurrence: "recurring",
|
||||
rewardType: "cash",
|
||||
rewardValue: "",
|
||||
criteriaValue: 50,
|
||||
period: "weekly",
|
||||
isPocketMoney: true,
|
||||
icon: "Wallet",
|
||||
color: "#22c55e",
|
||||
},
|
||||
{
|
||||
name: "Reading Bonus",
|
||||
target: "individual",
|
||||
type: "count",
|
||||
occurrence: "recurring",
|
||||
rewardType: "points",
|
||||
rewardValue: "50",
|
||||
criteriaValue: 5,
|
||||
period: "weekly",
|
||||
icon: "BookOpen",
|
||||
color: "#f59e0b",
|
||||
},
|
||||
{
|
||||
name: "Star of the Week",
|
||||
target: "competitive",
|
||||
type: "threshold",
|
||||
thresholdType: "points",
|
||||
occurrence: "weekly",
|
||||
rewardType: "prize",
|
||||
rewardValue: "Treat",
|
||||
criteriaValue: 100,
|
||||
period: "weekly",
|
||||
icon: "Trophy",
|
||||
color: "#ef4444",
|
||||
},
|
||||
];
|
||||
|
||||
for (const s of choreSeeds) {
|
||||
await fetch(`${PB_ENDPOINT}/api/collections/chore_templates/records`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${t}` },
|
||||
body: JSON.stringify({ ...s, global: true }),
|
||||
}).catch(() => {});
|
||||
}
|
||||
for (const s of bonusSeeds) {
|
||||
await fetch(`${PB_ENDPOINT}/api/collections/bonus_templates/records`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${t}` },
|
||||
body: JSON.stringify({ ...s, global: true }),
|
||||
}).catch(() => {});
|
||||
}
|
||||
console.log("[migrate] Seeded global templates.");
|
||||
}
|
||||
|
||||
export { GLOBAL_TEMPLATE_ICONS };
|
||||
@@ -53,15 +53,33 @@ export async function toggle(pb: any, famId: string, memberId: string, body: { a
|
||||
.getFullList({ filter });
|
||||
if (existing?.length > 0) {
|
||||
await pb.collection('completions').delete(existing[0].id);
|
||||
// Un-completing a cash todo removes its one-time reward.
|
||||
if (isTodo && existing[0].rewardId) {
|
||||
await pb.collection('rewards').delete(existing[0].rewardId).catch(() => {});
|
||||
}
|
||||
evaluateFam(pb, famId).catch(() => {});
|
||||
return { completed: false };
|
||||
}
|
||||
let rewardId: string | undefined;
|
||||
if (isTodo && chore?.type === 'money' && Number(chore.value) > 0) {
|
||||
const reward = await pb.collection('rewards').create({
|
||||
famId,
|
||||
memberId,
|
||||
label: chore.customName || 'Cash todo',
|
||||
value: Number(chore.value),
|
||||
rewardType: 'cash',
|
||||
status: 'unclaimed',
|
||||
date
|
||||
});
|
||||
rewardId = reward.id;
|
||||
}
|
||||
const record = await pb.collection('completions').create({
|
||||
famId,
|
||||
memberId,
|
||||
assignedChoreId,
|
||||
date,
|
||||
completedAt: new Date().toISOString()
|
||||
completedAt: new Date().toISOString(),
|
||||
...(rewardId ? { rewardId } : {})
|
||||
});
|
||||
evaluateFam(pb, famId).catch(() => {});
|
||||
return { completed: true, record };
|
||||
|
||||
@@ -6,10 +6,10 @@ const RESOURCES: Record<
|
||||
string,
|
||||
{ col: string; listFilter: (famId: string) => string; bonus?: 'config' | 'template' }
|
||||
> = {
|
||||
'chore-templates': { col: 'chore_templates', listFilter: (f) => `famId = '${f}'` },
|
||||
'chore-templates': { col: 'chore_templates', listFilter: (f) => `(famId = '${f}' || global = true)` },
|
||||
members: { col: 'users', listFilter: (f) => `famId = '${f}' && role = 'child'` },
|
||||
'assigned-chores': { col: 'assigned_chores', listFilter: (f) => `famId = '${f}'` },
|
||||
'bonus-templates': { col: 'bonus_templates', listFilter: (f) => `famId = '${f}'`, bonus: 'template' },
|
||||
'bonus-templates': { col: 'bonus_templates', listFilter: (f) => `(famId = '${f}' || global = true)`, bonus: 'template' },
|
||||
'bonus-configs': { col: 'bonus_configs', listFilter: (f) => `famId = '${f}'`, bonus: 'config' },
|
||||
completions: { col: 'completions', listFilter: (f) => `famId = '${f}'` },
|
||||
rewards: { col: 'rewards', listFilter: (f) => `famId = '${f}'` },
|
||||
|
||||
@@ -99,7 +99,7 @@ class FamStore {
|
||||
pb.collection('users').getFullList({
|
||||
filter: `famId = '${famId}' && role = 'child'`
|
||||
}) as Promise<Member[]>,
|
||||
pb.collection('chore_templates').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||
pb.collection('chore_templates').getFullList({ filter: `(famId = '${famId}' || global = true)` }) as Promise<
|
||||
ChoreTemplate[]
|
||||
>,
|
||||
pb.collection('assigned_chores').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||
@@ -111,7 +111,7 @@ class FamStore {
|
||||
pb.collection('bonus_configs').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||
BonusConfig[]
|
||||
>,
|
||||
pb.collection('bonus_templates').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||
pb.collection('bonus_templates').getFullList({ filter: `(famId = '${famId}' || global = true)` }) as Promise<
|
||||
BonusTemplate[]
|
||||
>,
|
||||
pb.collection('rewards').getFullList({ filter: `famId = '${famId}'` }) as Promise<
|
||||
@@ -146,11 +146,11 @@ class FamStore {
|
||||
private async subscribe() {
|
||||
const subs: { collection: CollectionName; filter: string }[] = [
|
||||
{ collection: 'users', filter: `famId = '${this.famId}' && role = 'child'` },
|
||||
{ collection: 'chore_templates', filter: `famId = '${this.famId}'` },
|
||||
{ collection: 'chore_templates', filter: `(famId = '${this.famId}' || global = true)` },
|
||||
{ collection: 'assigned_chores', filter: `famId = '${this.famId}'` },
|
||||
{ collection: 'completions', filter: `famId = '${this.famId}'` },
|
||||
{ collection: 'bonus_configs', filter: `famId = '${this.famId}'` },
|
||||
{ collection: 'bonus_templates', filter: `famId = '${this.famId}'` },
|
||||
{ collection: 'bonus_templates', filter: `(famId = '${this.famId}' || global = true)` },
|
||||
{ collection: 'rewards', filter: `famId = '${this.famId}'` },
|
||||
{ collection: 'seasons', filter: `famId = '${this.famId}'` }
|
||||
];
|
||||
|
||||
@@ -23,6 +23,9 @@ export interface BonusTemplate {
|
||||
criteriaValue?: number;
|
||||
period?: BonusPeriod;
|
||||
isPocketMoney?: boolean;
|
||||
global?: boolean;
|
||||
icon?: string;
|
||||
color?: string;
|
||||
created: string;
|
||||
updated: string;
|
||||
}
|
||||
@@ -71,6 +74,9 @@ export interface ChoreTemplate {
|
||||
defaultFrequency: Frequency;
|
||||
defaultType: RewardType;
|
||||
defaultValue: number;
|
||||
global?: boolean;
|
||||
icon?: string;
|
||||
color?: string;
|
||||
created: string;
|
||||
updated: string;
|
||||
}
|
||||
@@ -84,6 +90,10 @@ export interface AssignedChore {
|
||||
type: RewardType;
|
||||
value: number;
|
||||
customName?: string;
|
||||
description?: string;
|
||||
icon?: string;
|
||||
color?: string;
|
||||
emoji?: string;
|
||||
seasonIds?: string[];
|
||||
isTodo?: boolean;
|
||||
startDate?: string;
|
||||
|
||||
@@ -124,7 +124,7 @@
|
||||
setTimeout(() => (toast = ''), 4000);
|
||||
}
|
||||
|
||||
function handleResult({ result }, onSuccess = null) {
|
||||
function handleResult({ result }: any, onSuccess: ((d: any) => void) | null = null) {
|
||||
const d = result.data || {};
|
||||
if (d.error) showToast(d.error);
|
||||
else if (result.type === 'success') {
|
||||
@@ -273,6 +273,38 @@
|
||||
})
|
||||
);
|
||||
|
||||
// Celebration badge — completed todos from the last 24h, dismissed per-device
|
||||
// via localStorage (no PB storage; auto-expires after 24h).
|
||||
let celebrateDismissed = $state<string[]>([]);
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
celebrateDismissed = JSON.parse(localStorage.getItem('celebrateDismissed') || '[]');
|
||||
}
|
||||
function dismissCelebrate(id: string) {
|
||||
if (!celebrateDismissed.includes(id)) {
|
||||
celebrateDismissed = [...celebrateDismissed, id];
|
||||
try {
|
||||
localStorage.setItem('celebrateDismissed', JSON.stringify(celebrateDismissed));
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
let celebrations = $derived.by(() => {
|
||||
const cutoff = Date.now() - 24 * 3600 * 1000;
|
||||
return completions
|
||||
.filter((c: Completion) => {
|
||||
if (c.id.startsWith('optimistic-')) return false;
|
||||
const at = c.completedAt ? new Date(c.completedAt).getTime() : 0;
|
||||
if (!at || at < cutoff) return false;
|
||||
const chore = assigned.find((a) => a.id === c.assignedChoreId);
|
||||
return !!chore?.isTodo && !celebrateDismissed.includes(c.id);
|
||||
})
|
||||
.map((c: Completion) => {
|
||||
const chore = assigned.find((a) => a.id === c.assignedChoreId);
|
||||
const emoji =
|
||||
chore?.type === 'emoji' ? chore.emoji || '🎉' : chore?.type === 'money' ? '💸' : '⭐';
|
||||
return { id: c.id, emoji, name: chore?.customName || 'Todo' };
|
||||
});
|
||||
});
|
||||
|
||||
let dailyPending = $derived(
|
||||
memberChores.filter((a) => a.frequency === 'daily' && !isCompleted(a.id, todayChild))
|
||||
);
|
||||
@@ -640,11 +672,13 @@
|
||||
<div class="card-header">
|
||||
<span class="dot" style="background:{m.color}"></span>
|
||||
<span class="member-name">{m.name}</span>
|
||||
<Button
|
||||
href="/{famSlug}/{username}/bonuses?s=pocketmoney"
|
||||
variant="secondary"
|
||||
size="sm">Pocket money</Button
|
||||
>
|
||||
{#if !(pm && pm.rewardValue)}
|
||||
<Button
|
||||
href="/{famSlug}/{username}/bonuses?s=pocketmoney"
|
||||
variant="secondary"
|
||||
size="sm">Pocket money</Button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="stats">
|
||||
<span>Points: {s?.pointsEarned ?? 0}</span>
|
||||
@@ -1163,6 +1197,17 @@ const res = await fetch('/api/members', {
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
{#if celebrations.length > 0}
|
||||
<div class="celebrations">
|
||||
{#each celebrations as cel}
|
||||
<div class="celebrate-card">
|
||||
<span class="celebrate-emoji">{cel.emoji}</span>
|
||||
<span class="celebrate-text"><strong>{cel.name}</strong> complete — amazing work!</span>
|
||||
<button class="celebrate-close" onclick={() => dismissCelebrate(cel.id)}>✕</button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="kanban">
|
||||
<div class="column col-daily">
|
||||
<h2>🎯 Daily ({dailyPending.length})</h2>
|
||||
@@ -1206,7 +1251,7 @@ const res = await fetch('/api/members', {
|
||||
<span class="checkbox">📋</span>
|
||||
<span class="chore-name">{todo.customName || 'Todo'}</span>
|
||||
<span class="todo-label">todo</span>
|
||||
<span class="chore-value">🎯</span>
|
||||
<span class="chore-value">{todo.emoji || '🎯'}</span>
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
@@ -1222,7 +1267,11 @@ const res = await fetch('/api/members', {
|
||||
<span class="checkbox">📋</span>
|
||||
<span class="chore-name">{todo.customName || 'Todo'}</span>
|
||||
<span class="todo-label">todo</span>
|
||||
<span class="chore-value">{todo.value} {todo.type}</span>
|
||||
<span class="chore-value">
|
||||
{todo.type === 'money'
|
||||
? `£${Number(todo.value).toFixed(2)}`
|
||||
: `${todo.value} pts`}
|
||||
</span>
|
||||
</button>
|
||||
{/if}
|
||||
{/each}
|
||||
@@ -1879,6 +1928,48 @@ const res = await fetch('/api/members', {
|
||||
}
|
||||
|
||||
/* ── Kanban ── */
|
||||
.celebrations {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.celebrate-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
background: linear-gradient(90deg, #fef3c7, #fce7f3);
|
||||
border: 1px solid #fcd34d;
|
||||
border-radius: 12px;
|
||||
padding: 0.55rem 0.85rem;
|
||||
animation: celebrate-pop 0.35s ease-out;
|
||||
}
|
||||
@keyframes celebrate-pop {
|
||||
from {
|
||||
transform: scale(0.9);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
.celebrate-emoji {
|
||||
font-size: 1.6rem;
|
||||
}
|
||||
.celebrate-text {
|
||||
flex: 1;
|
||||
font-size: 0.85rem;
|
||||
color: #78350f;
|
||||
}
|
||||
.celebrate-close {
|
||||
background: none;
|
||||
border: none;
|
||||
color: #92400e;
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.15rem;
|
||||
}
|
||||
.kanban {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
|
||||
@@ -198,7 +198,8 @@ export const actions = {
|
||||
criteriaValue: parseInt(fd.get('criteriaValue') as string, 10) || 0,
|
||||
period: fd.get('period') || '',
|
||||
memberId: fd.get('memberId') || '',
|
||||
status
|
||||
status,
|
||||
isPocketMoney: !!fd.get('isPocketMoney')
|
||||
};
|
||||
if (data.occurrence === 'once') data.period = '';
|
||||
try {
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
import { enhance } from '$app/forms';
|
||||
import { famStore } from '$lib/stores/fam.svelte';
|
||||
import { ViewHeader, CardGrid, Card, Button } from '$lib/components';
|
||||
import TemplateIcon from '$lib/components/TemplateIcon.svelte';
|
||||
import Clock from '@lucide/svelte/icons/clock';
|
||||
import type {
|
||||
BonusConfig,
|
||||
BonusTemplate,
|
||||
@@ -15,10 +17,8 @@
|
||||
|
||||
let { data }: { data: PageData } = $props();
|
||||
|
||||
let showCreateModal = $state(false);
|
||||
let showEditModal = $state(false);
|
||||
let editingConfig = $state<BonusConfig | null>(null);
|
||||
let editingTemplate = $state<BonusTemplate | null>(null);
|
||||
let creatingFromTemplate = $state<BonusTemplate | null>(null);
|
||||
|
||||
let createVals = $state({
|
||||
@@ -74,7 +74,7 @@
|
||||
let createIsPercent = $derived(createVals.type === 'threshold' && createVals.thresholdType === 'percent');
|
||||
let editIsPercent = $derived(editVals.type === 'threshold' && editVals.thresholdType === 'percent');
|
||||
|
||||
let templateConfigs = $derived(templates as BonusTemplate[]);
|
||||
let templateConfigs = $derived((templates as BonusTemplate[]).filter((t) => t.global));
|
||||
let allBonusConfigs = $derived(
|
||||
configs.filter((c: BonusConfig) => c.status !== 'completed') as BonusConfig[]
|
||||
);
|
||||
@@ -137,7 +137,6 @@
|
||||
if (!tpl) return;
|
||||
creatingFromTemplate = tpl;
|
||||
editingConfig = null;
|
||||
editingTemplate = null;
|
||||
editVals = {
|
||||
name: tpl.name,
|
||||
description: tpl.description || '',
|
||||
@@ -173,26 +172,18 @@
|
||||
if (raw) openCreateFromTemplate(raw, 'collaborative');
|
||||
}
|
||||
|
||||
function handleCreate() {
|
||||
return async ({ result }: any) => {
|
||||
if (result.type === 'success') showCreateModal = false;
|
||||
};
|
||||
}
|
||||
|
||||
function handleUpdate() {
|
||||
return async ({ result }: any) => {
|
||||
if (result.type === 'success') {
|
||||
showEditModal = false;
|
||||
creatingFromTemplate = null;
|
||||
editingConfig = null;
|
||||
editingTemplate = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function openEditConfig(cfg: BonusConfig) {
|
||||
editingConfig = cfg;
|
||||
editingTemplate = null;
|
||||
creatingFromTemplate = null;
|
||||
editVals = {
|
||||
name: cfg.name,
|
||||
@@ -245,58 +236,32 @@
|
||||
<div class="template-section">
|
||||
<h3>Templates — Drag to assign</h3>
|
||||
<div class="template-list">
|
||||
{#each templateConfigs as cfg}
|
||||
<div class="template-card" draggable="true" ondragstart={(e) => handleDragStart(e, cfg)}>
|
||||
<div class="card-head">
|
||||
<strong>{cfg.name}</strong>
|
||||
</div>
|
||||
<div class="badges">
|
||||
<span class="badge {badgeClass(cfg)}">{cfg.target}</span>
|
||||
<span class="badge">{cfg.type}</span>
|
||||
<span class="badge">{cfg.occurrence}</span>
|
||||
{#if cfg.period}
|
||||
<span class="badge period">{cfg.period}</span>
|
||||
{/if}
|
||||
{#if cfg.isPocketMoney}
|
||||
<span class="badge pocket">Pocket Money</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="reward-preview">
|
||||
{formatReward(cfg.rewardType, cfg.rewardValue)}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onclick={() => {
|
||||
editingTemplate = cfg;
|
||||
editingConfig = null;
|
||||
creatingFromTemplate = null;
|
||||
editVals = {
|
||||
name: cfg.name,
|
||||
description: cfg.description || '',
|
||||
target: cfg.target,
|
||||
memberId: '',
|
||||
type: cfg.type,
|
||||
thresholdType: cfg.thresholdType || 'points',
|
||||
occurrence: cfg.occurrence,
|
||||
rewardType: cfg.rewardType,
|
||||
rewardValue: cfg.rewardValue,
|
||||
criteriaValue: cfg.criteriaValue || 10,
|
||||
period: cfg.occurrence === 'once' ? '' : cfg.period || '',
|
||||
startMode: 'today'
|
||||
};
|
||||
showEditModal = true;
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</Button>
|
||||
{#each templateConfigs as cfg}
|
||||
<div class="template-card" draggable="true" ondragstart={(e) => handleDragStart(e, cfg)} style="border-left-color:{cfg.color}">
|
||||
<div class="card-head">
|
||||
<TemplateIcon name={cfg.icon} size={18} color={cfg.color} />
|
||||
<strong>{cfg.name}</strong>
|
||||
</div>
|
||||
{/each}
|
||||
<div class="badges">
|
||||
<span class="badge {badgeClass(cfg)}">{cfg.target}</span>
|
||||
<span class="badge">{cfg.type}</span>
|
||||
<span class="badge">{cfg.occurrence}</span>
|
||||
{#if cfg.period}
|
||||
<span class="badge period">{cfg.period}</span>
|
||||
{/if}
|
||||
{#if cfg.isPocketMoney}
|
||||
<span class="badge pocket">Pocket Money</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="reward-preview">
|
||||
{formatReward(cfg.rewardType, cfg.rewardValue)}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{#if templateConfigs.length === 0}
|
||||
<p class="empty">No templates yet</p>
|
||||
{/if}
|
||||
</div>
|
||||
<Button onclick={() => (showCreateModal = true)}>New Template</Button>
|
||||
</div>
|
||||
</Card>
|
||||
<Card cols={3} scrollX>
|
||||
@@ -305,7 +270,14 @@
|
||||
<div class="column member-col" ondragover={handleDragOver} ondrop={handleDropToMember}>
|
||||
<h3>Member</h3>
|
||||
{#each allBonusConfigs.filter((c) => c.target === 'individual' && !doneConfigs.includes(c)) as cfg}
|
||||
<div class="col-card" class:disabled={disabledIds.has(cfg.id)}>
|
||||
<div
|
||||
class="col-card"
|
||||
class:disabled={disabledIds.has(cfg.id)}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
onclick={() => openEditConfig(cfg)}
|
||||
onkeydown={(e) => e.key === 'Enter' && openEditConfig(cfg)}
|
||||
>
|
||||
<div class="col-card-head">
|
||||
<strong>{cfg.name}</strong>
|
||||
<div class="badges">
|
||||
@@ -316,6 +288,9 @@
|
||||
<span class="badge pocket">Pocket Money</span>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="reward-total {cfg.rewardType}">
|
||||
{cfg.rewardType === 'cash' ? `£${Number(cfg.rewardValue).toFixed(2)}` : `${cfg.rewardValue} pts`}
|
||||
</span>
|
||||
</div>
|
||||
{#each members as m}
|
||||
{#if !cfg.memberId || cfg.memberId === m.id}
|
||||
@@ -344,16 +319,14 @@
|
||||
</div>
|
||||
{/if}
|
||||
<span class="stat {p?.state ?? 'pending'}">
|
||||
{p ? p.state : 'Pending'}
|
||||
{#if !p || p.state === 'pending'}<Clock size={13} />{:else}{p.state}{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{/each}
|
||||
<div class="col-card-foot">
|
||||
<Button variant="secondary" size="sm" onclick={() => openEditConfig(cfg)}>
|
||||
Edit
|
||||
</Button>
|
||||
<span class="click-edit">Click to edit</span>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
@@ -367,7 +340,14 @@
|
||||
<h3>Competition</h3>
|
||||
{#each allBonusConfigs.filter((c) => c.target === 'competitive' && !doneConfigs.includes(c)) as cfg}
|
||||
{@const prog = progressByConfigId.get(cfg.id)}
|
||||
<div class="col-card" class:disabled={disabledIds.has(cfg.id)}>
|
||||
<div
|
||||
class="col-card"
|
||||
class:disabled={disabledIds.has(cfg.id)}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
onclick={() => openEditConfig(cfg)}
|
||||
onkeydown={(e) => e.key === 'Enter' && openEditConfig(cfg)}
|
||||
>
|
||||
<div class="col-card-head">
|
||||
<strong>{cfg.name}</strong>
|
||||
<div class="badges">
|
||||
@@ -375,6 +355,9 @@
|
||||
<span class="badge">{cfg.type}</span>
|
||||
<span class="badge">{cfg.occurrence}</span>
|
||||
</div>
|
||||
<span class="reward-total {cfg.rewardType}">
|
||||
{cfg.rewardType === 'cash' ? `£${Number(cfg.rewardValue).toFixed(2)}` : `${cfg.rewardValue} pts`}
|
||||
</span>
|
||||
</div>
|
||||
{#if prog}
|
||||
<div class="leaderboard">
|
||||
@@ -397,16 +380,14 @@
|
||||
</div>
|
||||
{/if}
|
||||
<span class="stat {p.state}">
|
||||
{p.state}
|
||||
{#if p.state === 'pending'}<Clock size={13} />{:else}{p.state}{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="col-card-foot">
|
||||
<Button variant="secondary" size="sm" onclick={() => openEditConfig(cfg)}>
|
||||
Edit
|
||||
</Button>
|
||||
<span class="click-edit">Click to edit</span>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
@@ -420,7 +401,14 @@
|
||||
<h3>Collaboration</h3>
|
||||
{#each allBonusConfigs.filter((c) => c.target === 'collaborative') as cfg}
|
||||
{@const prog = progressByConfigId.get(cfg.id)}
|
||||
<div class="col-card" class:disabled={disabledIds.has(cfg.id)}>
|
||||
<div
|
||||
class="col-card"
|
||||
class:disabled={disabledIds.has(cfg.id)}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
onclick={() => openEditConfig(cfg)}
|
||||
onkeydown={(e) => e.key === 'Enter' && openEditConfig(cfg)}
|
||||
>
|
||||
<div class="col-card-head">
|
||||
<strong>{cfg.name}</strong>
|
||||
<div class="badges">
|
||||
@@ -428,6 +416,9 @@
|
||||
<span class="badge">{cfg.type}</span>
|
||||
<span class="badge">{cfg.occurrence}</span>
|
||||
</div>
|
||||
<span class="reward-total {cfg.rewardType}">
|
||||
{cfg.rewardType === 'cash' ? `£${Number(cfg.rewardValue).toFixed(2)}` : `${cfg.rewardValue} pts`}
|
||||
</span>
|
||||
</div>
|
||||
{#if prog}
|
||||
{@const team = prog.progress[0]}
|
||||
@@ -453,15 +444,13 @@
|
||||
{cfg.type === 'threshold' ? 'pts' : 'chores'}</span
|
||||
>
|
||||
<span class="stat {team.state}">
|
||||
{team.state}
|
||||
{#if team.state === 'pending'}<Clock size={13} />{:else}{team.state}{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
<div class="col-card-foot">
|
||||
<Button variant="secondary" size="sm" onclick={() => openEditConfig(cfg)}>
|
||||
Edit
|
||||
</Button>
|
||||
<span class="click-edit">Click to edit</span>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
@@ -471,146 +460,32 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showCreateModal}
|
||||
<div class="overlay" onclick={() => (showCreateModal = false)} role="presentation">
|
||||
<div class="modal" onclick={(e) => e.stopPropagation()} role="dialog">
|
||||
<h3>New Bonus Template</h3>
|
||||
<form method="POST" action="?/createTemplate" use:enhance={handleCreate}>
|
||||
<label>Name <input name="name" bind:value={createVals.name} required /></label>
|
||||
<label
|
||||
>Description <input name="description" bind:value={createVals.description} /></label
|
||||
>
|
||||
<label
|
||||
>Target
|
||||
<select name="target" bind:value={createVals.target}>
|
||||
<option value="individual">Individual</option>
|
||||
<option value="competitive">Competition</option>
|
||||
<option value="collaborative">Collaborative</option>
|
||||
</select>
|
||||
</label>
|
||||
<label
|
||||
>Type
|
||||
<select name="type" bind:value={createVals.type}>
|
||||
<option value="threshold">Threshold</option>
|
||||
<option value="count">Count</option>
|
||||
<option value="manual">Manual</option>
|
||||
</select>
|
||||
</label>
|
||||
{#if createVals.type === 'threshold'}
|
||||
<label
|
||||
>Threshold by
|
||||
<select name="thresholdType" bind:value={createVals.thresholdType}>
|
||||
<option value="points">Points</option>
|
||||
<option value="percent">% of chores done</option>
|
||||
</select>
|
||||
</label>
|
||||
{/if}
|
||||
{#if showCriteriaForCreate}
|
||||
{#if createIsPercent}
|
||||
<label
|
||||
>Chores completed (%)
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="100"
|
||||
name="criteriaValue"
|
||||
bind:value={createVals.criteriaValue}
|
||||
/>
|
||||
<span class="hint">{createVals.criteriaValue}% of chores this week</span>
|
||||
</label>
|
||||
{:else}
|
||||
<label
|
||||
>Target Value
|
||||
<input
|
||||
type="number"
|
||||
name="criteriaValue"
|
||||
bind:value={createVals.criteriaValue}
|
||||
required
|
||||
/>
|
||||
<span class="hint"
|
||||
>{createVals.type === 'threshold' ? 'Points to reach' : 'Number of chores'}</span
|
||||
>
|
||||
</label>
|
||||
{/if}
|
||||
{/if}
|
||||
<label
|
||||
>Occurrence
|
||||
<select name="occurrence" bind:value={createVals.occurrence}>
|
||||
<option value="recurring">Recurring</option>
|
||||
<option value="once">Once</option>
|
||||
</select>
|
||||
</label>
|
||||
{#if showPeriodForCreate}
|
||||
<label
|
||||
>Period
|
||||
<select name="period" bind:value={createVals.period}>
|
||||
<option value="">None</option>
|
||||
<option value="daily">Daily</option>
|
||||
<option value="weekly">Weekly</option>
|
||||
<option value="monthly">Monthly</option>
|
||||
</select>
|
||||
</label>
|
||||
{/if}
|
||||
<label
|
||||
>Reward Type
|
||||
<select name="rewardType" bind:value={createVals.rewardType}>
|
||||
<option value="points">Points</option>
|
||||
<option value="cash">Cash</option>
|
||||
<option value="prize">Prize</option>
|
||||
</select>
|
||||
</label>
|
||||
<label
|
||||
>Reward Value
|
||||
<input name="rewardValue" bind:value={createVals.rewardValue} required />
|
||||
<span class="hint"
|
||||
>{createVals.rewardType === 'cash'
|
||||
? 'Amount in £ (e.g. 2.00 = £2.00)'
|
||||
: createVals.rewardType === 'points'
|
||||
? 'Points to award'
|
||||
: 'Prize description'}</span
|
||||
>
|
||||
</label>
|
||||
<div class="modal-actions">
|
||||
<button type="button" onclick={() => (showCreateModal = false)}>Cancel</button>
|
||||
<button type="submit">Create</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Edit / Create-from-Template Modal -->
|
||||
{#if showEditModal && (editingConfig || editingTemplate || creatingFromTemplate)}
|
||||
{@const targetCfg = creatingFromTemplate || editingConfig || editingTemplate!}
|
||||
{#if showEditModal && (editingConfig || creatingFromTemplate)}
|
||||
{@const targetCfg = creatingFromTemplate || editingConfig!}
|
||||
<div
|
||||
class="overlay"
|
||||
onclick={() => {
|
||||
showEditModal = false;
|
||||
creatingFromTemplate = null;
|
||||
editingConfig = null;
|
||||
editingTemplate = null;
|
||||
}}
|
||||
role="presentation"
|
||||
>
|
||||
<div class="modal" onclick={(e) => e.stopPropagation()} role="dialog">
|
||||
<h3>
|
||||
{creatingFromTemplate
|
||||
? 'Create from: '
|
||||
: editingTemplate
|
||||
? 'Edit Template: '
|
||||
: 'Edit: '}{targetCfg.name}
|
||||
{creatingFromTemplate ? 'Create from: ' : 'Edit: '}{targetCfg.name}
|
||||
</h3>
|
||||
<form
|
||||
method="POST"
|
||||
action={editingTemplate
|
||||
? '?/updateTemplate'
|
||||
: creatingFromTemplate
|
||||
? '?/createFromTemplate'
|
||||
: '?/updateConfig'}
|
||||
action={creatingFromTemplate ? '?/createFromTemplate' : '?/updateConfig'}
|
||||
use:enhance={handleUpdate}
|
||||
>
|
||||
{#if editingConfig || editingTemplate}
|
||||
<input type="hidden" name="id" value={editingConfig?.id || editingTemplate!.id} />
|
||||
{#if editingConfig}
|
||||
<input type="hidden" name="id" value={editingConfig?.id} />
|
||||
{/if}
|
||||
{#if creatingFromTemplate}
|
||||
<input type="hidden" name="isPocketMoney" value={creatingFromTemplate.isPocketMoney ? '1' : ''} />
|
||||
{/if}
|
||||
<label>Name <input name="name" bind:value={editVals.name} required /></label>
|
||||
<label>Description <input name="description" bind:value={editVals.description} /></label
|
||||
@@ -804,7 +679,7 @@
|
||||
Delete
|
||||
</button>
|
||||
{/if}
|
||||
<button type="submit">{creatingFromTemplate ? 'Confirm' : 'Save'}</button>
|
||||
<button type="submit">{creatingFromTemplate ? 'Assign' : 'Save'}</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -822,22 +697,14 @@
|
||||
font-size: 1rem;
|
||||
}
|
||||
.template-list {
|
||||
display: grid;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.75rem;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
@media (max-width: 1100px) {
|
||||
.template-list {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.template-list {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
.template-card {
|
||||
flex: 0 1 auto;
|
||||
min-width: 160px;
|
||||
background: white;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-left: 4px solid #8b5cf6;
|
||||
@@ -877,8 +744,9 @@
|
||||
}
|
||||
.card-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
justify-content: flex-start;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
.card-head strong {
|
||||
@@ -957,6 +825,7 @@
|
||||
border-radius: 10px;
|
||||
padding: 0.65rem 0.85rem;
|
||||
margin-bottom: 0.6rem;
|
||||
cursor: pointer;
|
||||
transition: transform 0.15s, box-shadow 0.15s, border-color 0.15s;
|
||||
}
|
||||
.col-card:hover {
|
||||
@@ -964,6 +833,27 @@
|
||||
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
|
||||
border-color: #c7d2fe;
|
||||
}
|
||||
.col-card:focus-visible {
|
||||
outline: 2px solid #6366f1;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.reward-total {
|
||||
margin-left: auto;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.reward-total.cash {
|
||||
color: #16a34a;
|
||||
}
|
||||
.reward-total.points {
|
||||
color: #9333ea;
|
||||
}
|
||||
.click-edit {
|
||||
margin-left: auto;
|
||||
font-size: 0.68rem;
|
||||
color: #9ca3af;
|
||||
}
|
||||
.col-card.done {
|
||||
opacity: 0.75;
|
||||
}
|
||||
@@ -986,6 +876,7 @@
|
||||
.col-card-foot {
|
||||
margin-top: 0.5rem;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
.member-progress {
|
||||
@@ -1027,6 +918,9 @@
|
||||
padding: 0.1rem 0.25rem;
|
||||
border-radius: 0.25rem;
|
||||
background: #e5e7eb;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.15rem;
|
||||
}
|
||||
.stat.pending {
|
||||
background: #e5e7eb;
|
||||
|
||||
@@ -7,7 +7,7 @@ export async function load(event) {
|
||||
const famId = event.locals.user.famId;
|
||||
const pb = pbUser(event);
|
||||
const [templates, members, assigned, seasons, completions] = await Promise.all([
|
||||
pb.collection('chore_templates').getFullList({ filter: `famId = '${famId}'` }),
|
||||
pb.collection('chore_templates').getFullList({ filter: `(famId = '${famId}' || global = true)` }),
|
||||
pb.collection('users').getFullList({
|
||||
filter: `famId = '${famId}' && role = 'child'`
|
||||
}),
|
||||
@@ -111,8 +111,10 @@ export const actions = {
|
||||
const completeBy = fd.get('completeBy') as string;
|
||||
const startDate = fd.get('startDate') as string;
|
||||
if (type) data.type = type;
|
||||
if (type === 'emoji') data.value = 0;
|
||||
else if (fd.get('value')) data.value = parseFloat(fd.get('value') as string) || 0;
|
||||
if (type === 'emoji') {
|
||||
data.value = 0;
|
||||
data.emoji = (fd.get('emoji') as string) || '🎉';
|
||||
} else if (fd.get('value')) data.value = parseFloat(fd.get('value') as string) || 0;
|
||||
data.customName = customName || undefined;
|
||||
if (completeBy) data.completeBy = completeBy;
|
||||
if (startDate) data.startDate = startDate;
|
||||
@@ -146,6 +148,7 @@ export const actions = {
|
||||
const name = fd.get('name') as string;
|
||||
const type = fd.get('type') as string;
|
||||
const value = type === 'emoji' ? 0 : (parseFloat(fd.get('value') as string) || 0);
|
||||
const emoji = type === 'emoji' ? ((fd.get('emoji') as string) || '🎉') : '';
|
||||
const todoStart = fd.get('todoStart') as string;
|
||||
const todoCompleteBy = fd.get('todoCompleteBy') as string;
|
||||
const customDate = fd.get('customDate') as string;
|
||||
@@ -181,6 +184,7 @@ export const actions = {
|
||||
value,
|
||||
customName: name,
|
||||
isTodo: true,
|
||||
emoji,
|
||||
startDate,
|
||||
completeBy
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { page } from '$app/state';
|
||||
import { famStore } from '$lib/stores/fam.svelte';
|
||||
import { ViewHeader, CardGrid, Card } from '$lib/components';
|
||||
import TemplateIcon from '$lib/components/TemplateIcon.svelte';
|
||||
import { formatHumanDate } from '$lib/format';
|
||||
import type { ChoreTemplate, AssignedChore, Member, Season, Completion } from '$lib/types';
|
||||
|
||||
@@ -14,48 +15,53 @@
|
||||
|
||||
let { data, form } = $props();
|
||||
|
||||
let showCreateModal = $state(false);
|
||||
let showEditModal = $state(false);
|
||||
let showEditTemplateModal = $state(false);
|
||||
let showTodoModal = $state(false);
|
||||
let editingAssignment = $state<AssignedChore | null>(null);
|
||||
let editingTemplate = $state<ChoreTemplate | null>(null);
|
||||
let editMemberId = $state('');
|
||||
let draggedTemplateId = $state<string | null>(null);
|
||||
let todoMemberId = $state('');
|
||||
|
||||
let createName = $state('');
|
||||
let createFreq = $state('daily');
|
||||
let createType = $state('points');
|
||||
let createValue = $state(10);
|
||||
// Assign-from-template modal (platform templates are copied into the family
|
||||
// as assigned chores; the fam admin amends before saving).
|
||||
let assignModal = $state<{ t: ChoreTemplate; memberId: string } | null>(null);
|
||||
let assignFreq = $state('daily');
|
||||
let assignType = $state('points');
|
||||
let assignValue = $state(10);
|
||||
let assignSeasonIds = $state<string[]>([]);
|
||||
|
||||
// Todo form state
|
||||
let todoName = $state('');
|
||||
let todoType = $state<'points' | 'emoji'>('points');
|
||||
let todoType = $state<'points' | 'money' | 'emoji'>('points');
|
||||
let todoValue = $state(10);
|
||||
let todoEmoji = $state('🎉');
|
||||
let showTodoEmojiPicker = $state(false);
|
||||
let todoStart = $state<'now' | 'next-week'>('now');
|
||||
let todoCompleteBy = $state<'next-week' | 'custom'>('next-week');
|
||||
let todoCustomDate = $state('');
|
||||
|
||||
// Curated celebration emojis for todos
|
||||
const EMOJI_CHOICES = [
|
||||
'🎉', '⭐', '🏆', '💪', '🧹', '📚', '🦸', '✨', '🌟', '🥇',
|
||||
'🎯', '💚', '🚀', '🦄', '🌈', '🍀', '🎨', '🎸', '⚽', '🍰'
|
||||
];
|
||||
|
||||
let editFreq = $state('daily');
|
||||
let editType = $state('points');
|
||||
let editValue = $state(10);
|
||||
let editCustomName = $state('');
|
||||
let editEmoji = $state('🎉');
|
||||
let editTodoCompleteBy = $state('');
|
||||
let editTodoStartDate = $state('');
|
||||
|
||||
let editTplName = $state('');
|
||||
let editTplFreq = $state('daily');
|
||||
let editTplType = $state('points');
|
||||
let editTplValue = $state(10);
|
||||
|
||||
let seasonFilter = $state('all');
|
||||
let editSeasonIds = $state<string[]>([]);
|
||||
|
||||
let templates = $state(
|
||||
famStore.initialized
|
||||
? (famStore.templates as ChoreTemplate[])
|
||||
: (data.templates as ChoreTemplate[]) || []
|
||||
// Platform-owned templates only — families assign these, they don't create.
|
||||
let templates = $derived(
|
||||
((famStore.initialized ? (famStore.templates as ChoreTemplate[]) : (data.templates as ChoreTemplate[])) || []).filter(
|
||||
(t: ChoreTemplate) => t.global
|
||||
)
|
||||
);
|
||||
let members = $state(
|
||||
famStore.initialized ? (famStore.members as Member[]) : (data.members as Member[]) || []
|
||||
@@ -122,20 +128,29 @@
|
||||
async function handleDrop(e: DragEvent, memberId: string) {
|
||||
e.preventDefault();
|
||||
const tid = e.dataTransfer?.getData('text/plain') || draggedTemplateId;
|
||||
if (!tid) return;
|
||||
draggedTemplateId = null;
|
||||
if (!tid) return;
|
||||
const t = templates.find((x) => x.id === tid);
|
||||
if (!t) return;
|
||||
assignModal = { t, memberId };
|
||||
assignFreq = t.defaultFrequency;
|
||||
assignType = t.defaultType;
|
||||
assignValue = t.defaultValue;
|
||||
assignSeasonIds = seasonFilter !== 'all' ? [seasonFilter] : [];
|
||||
}
|
||||
|
||||
async function assignChore() {
|
||||
if (!assignModal) return;
|
||||
const s = page.data.session as any;
|
||||
if (!s) return;
|
||||
const def = getDefault(tid);
|
||||
const body: Record<string, unknown> = {
|
||||
memberId,
|
||||
templateId: tid,
|
||||
frequency: def.frequency,
|
||||
type: def.type,
|
||||
value: def.value
|
||||
memberId: assignModal.memberId,
|
||||
templateId: assignModal.t.id,
|
||||
frequency: assignFreq,
|
||||
type: assignType,
|
||||
value: assignValue
|
||||
};
|
||||
if (seasonFilter !== 'all') body.seasonIds = [seasonFilter];
|
||||
if (assignSeasonIds.length) body.seasonIds = assignSeasonIds;
|
||||
await fetch(`/api/admin/${s.famId}/assigned-chores`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -145,6 +160,7 @@
|
||||
},
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
assignModal = null;
|
||||
}
|
||||
|
||||
// Accordion state per member: which section is open
|
||||
@@ -160,6 +176,8 @@
|
||||
todoName = '';
|
||||
todoType = 'points';
|
||||
todoValue = 10;
|
||||
todoEmoji = '🎉';
|
||||
showTodoEmojiPicker = false;
|
||||
todoStart = 'now';
|
||||
todoCompleteBy = 'custom';
|
||||
todoCustomDate = defaultCompleteByDate();
|
||||
@@ -209,6 +227,7 @@
|
||||
editType = a.type;
|
||||
editValue = a.value;
|
||||
editCustomName = a.customName || '';
|
||||
editEmoji = a.emoji || '🎉';
|
||||
editSeasonIds = a.seasonIds ? [...a.seasonIds] : [];
|
||||
editTodoCompleteBy = a.completeBy || '';
|
||||
editTodoStartDate = a.startDate || '';
|
||||
@@ -220,32 +239,6 @@
|
||||
editingAssignment = null;
|
||||
}
|
||||
|
||||
function openEditTemplate(t: ChoreTemplate) {
|
||||
editingTemplate = t;
|
||||
editTplName = t.name;
|
||||
editTplFreq = t.defaultFrequency;
|
||||
editTplType = t.defaultType;
|
||||
editTplValue = t.defaultValue;
|
||||
showEditTemplateModal = true;
|
||||
}
|
||||
|
||||
function closeEditTemplate() {
|
||||
showEditTemplateModal = false;
|
||||
editingTemplate = null;
|
||||
}
|
||||
|
||||
function enhanceCreate() {
|
||||
return async ({ result }: any) => {
|
||||
if (result.type === 'success') {
|
||||
showCreateModal = false;
|
||||
const rec = result.data?.record;
|
||||
if (rec) {
|
||||
templates = [rec as ChoreTemplate, ...templates];
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function enhanceUpdateAssigned() {
|
||||
return async ({ result }: any) => {
|
||||
if (result.type === 'success' && editingAssignment) {
|
||||
@@ -256,7 +249,8 @@
|
||||
};
|
||||
if (editingAssignment.isTodo) {
|
||||
updates.type = editType;
|
||||
updates.value = editValue;
|
||||
updates.value = editType === 'emoji' ? 0 : editValue;
|
||||
updates.emoji = editType === 'emoji' ? editEmoji : undefined;
|
||||
updates.completeBy = editTodoCompleteBy;
|
||||
updates.startDate = editTodoStartDate;
|
||||
} else {
|
||||
@@ -271,30 +265,6 @@
|
||||
closeEdit();
|
||||
};
|
||||
}
|
||||
|
||||
function enhanceUpdateTemplate() {
|
||||
return async ({ result, formData }: any) => {
|
||||
if (result.type === 'success' && editingTemplate) {
|
||||
const tid = editingTemplate!.id;
|
||||
const idx = templates.findIndex((t: any) => t.id === tid);
|
||||
if (idx !== -1) {
|
||||
templates[idx] = {
|
||||
...templates[idx],
|
||||
name: editTplName,
|
||||
defaultFrequency: editTplFreq,
|
||||
defaultType: editTplType,
|
||||
defaultValue: editTplValue
|
||||
} as ChoreTemplate;
|
||||
assigned = assigned.map((a: any) =>
|
||||
a.templateId === tid
|
||||
? { ...a, frequency: editTplFreq, type: editTplType, value: editTplValue }
|
||||
: a
|
||||
) as AssignedChore[];
|
||||
closeEditTemplate();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
<ViewHeader title="Chore Assignment" hero />
|
||||
@@ -321,8 +291,9 @@
|
||||
</div>
|
||||
<div class="template-list">
|
||||
{#each templates as t}
|
||||
<div class="card template" draggable="true" ondragstart={(e) => handleDragStart(e, t.id)}>
|
||||
<div class="card-body" onclick={() => openEditTemplate(t)} role="button" tabindex="0">
|
||||
<div class="card template" draggable="true" ondragstart={(e) => handleDragStart(e, t.id)} style="border-left-color:{t.color}">
|
||||
<div class="card-body">
|
||||
<TemplateIcon name={t.icon} size={18} color={t.color} />
|
||||
<strong>{t.name}</strong>
|
||||
<span class="badge">{t.defaultFrequency}</span>
|
||||
<span class="badge type">{t.defaultType}</span>
|
||||
@@ -330,18 +301,12 @@
|
||||
<div class="card-value">
|
||||
{t.defaultType === 'money' ? `£${Number(t.defaultValue).toFixed(2)}` : t.defaultValue}
|
||||
</div>
|
||||
<div class="card-actions">
|
||||
<button onclick={() => openEditTemplate(t)} class="edit-btn" title="Edit template"
|
||||
>✎</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{#if templates.length === 0}
|
||||
<p class="empty">No templates yet</p>
|
||||
{/if}
|
||||
</div>
|
||||
<button class="add-inline" onclick={() => (showCreateModal = true)}>+ New template</button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
@@ -389,7 +354,9 @@
|
||||
<strong class="todo-admin-name">{a.customName || 'Todo'}</strong>
|
||||
<div class="todo-admin-meta">
|
||||
{#if a.type === 'emoji'}
|
||||
<span class="todo-admin-type">🎯 emoji</span>
|
||||
<span class="todo-admin-type">{a.emoji || '🎉'} celebration</span>
|
||||
{:else if a.type === 'money'}
|
||||
<span class="todo-admin-type">£{Number(a.value).toFixed(2)} cash</span>
|
||||
{:else}
|
||||
<span class="todo-admin-type"
|
||||
><span class="badge badge-pts">{a.value} pts</span></span
|
||||
@@ -484,101 +451,36 @@
|
||||
</Card>
|
||||
</CardGrid>
|
||||
|
||||
<!-- Create Template Modal -->
|
||||
{#if showCreateModal}
|
||||
<div class="overlay" onclick={() => (showCreateModal = false)} role="presentation">
|
||||
<!-- Assign from Template Modal -->
|
||||
{#if assignModal}
|
||||
<div class="overlay" onclick={() => (assignModal = null)} role="presentation">
|
||||
<div class="modal" onclick={(e) => e.stopPropagation()} role="dialog">
|
||||
<h3>New Chore Template</h3>
|
||||
<form method="POST" action="?/createTemplate" use:enhance={enhanceCreate}>
|
||||
<label>
|
||||
Name
|
||||
<input name="name" bind:value={createName} required />
|
||||
</label>
|
||||
<label>
|
||||
Frequency
|
||||
<select name="defaultFrequency" bind:value={createFreq}>
|
||||
<option value="daily">Daily</option>
|
||||
<option value="weekly">Weekly</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Type
|
||||
<select name="defaultType" bind:value={createType}>
|
||||
<option value="points">Points</option>
|
||||
<option value="money">Money</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Default Value
|
||||
<input name="defaultValue" type="number" step="any" bind:value={createValue} required />
|
||||
</label>
|
||||
<div class="modal-actions">
|
||||
<button type="button" onclick={() => (showCreateModal = false)}>Cancel</button>
|
||||
<button type="submit">Create</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Edit Template Modal -->
|
||||
{#if showEditTemplateModal && editingTemplate}
|
||||
<div class="overlay" onclick={closeEditTemplate} role="presentation">
|
||||
<div class="modal" onclick={(e) => e.stopPropagation()} role="dialog">
|
||||
<h3>Edit Template: {editingTemplate.name}</h3>
|
||||
<p class="hint">Changes will also update all existing assigned chores using this template.</p>
|
||||
<form id="updateTplForm" method="POST" action="?/updateTemplate" use:enhance={enhanceUpdateTemplate}>
|
||||
<input name="id" type="hidden" value={editingTemplate.id} />
|
||||
<label>
|
||||
Name
|
||||
<input name="name" bind:value={editTplName} required />
|
||||
</label>
|
||||
<label>
|
||||
Frequency
|
||||
<select name="defaultFrequency" bind:value={editTplFreq}>
|
||||
<option value="daily">Daily</option>
|
||||
<option value="weekly">Weekly</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Type
|
||||
<select name="defaultType" bind:value={editTplType}>
|
||||
<option value="points">Points</option>
|
||||
<option value="money">Money</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Default Value
|
||||
<input name="defaultValue" type="number" step="any" bind:value={editTplValue} required />
|
||||
</label>
|
||||
</form>
|
||||
<h3>Assign: {assignModal.t.name}</h3>
|
||||
<p class="hint">
|
||||
Copies this platform template into {members.find((m) => m.id === assignModal?.memberId)?.name}'s
|
||||
chores. Amend, then Assign.
|
||||
</p>
|
||||
<label>
|
||||
Frequency
|
||||
<select bind:value={assignFreq}>
|
||||
<option value="daily">Daily</option>
|
||||
<option value="weekly">Weekly</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Type
|
||||
<select bind:value={assignType}>
|
||||
<option value="points">Points</option>
|
||||
<option value="money">Money</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Value
|
||||
<input type="number" step="any" bind:value={assignValue} />
|
||||
</label>
|
||||
<div class="modal-actions">
|
||||
<button type="button" onclick={closeEditTemplate}>Cancel</button>
|
||||
<form
|
||||
method="POST"
|
||||
action="?/deleteTemplate"
|
||||
use:enhance={() => {
|
||||
return async ({ result, formData }) => {
|
||||
if (result.type === 'success') {
|
||||
const id = formData.get('id');
|
||||
templates = templates.filter((t) => t.id !== id) as ChoreTemplate[];
|
||||
closeEditTemplate();
|
||||
}
|
||||
};
|
||||
}}
|
||||
>
|
||||
<input type="hidden" name="id" value={editingTemplate.id} />
|
||||
<button
|
||||
type="submit"
|
||||
class="delete-btn"
|
||||
onclick={(e) => {
|
||||
if (!confirm('Delete this template? This cannot be undone.')) {
|
||||
e.preventDefault();
|
||||
}
|
||||
}}>Delete</button
|
||||
>
|
||||
</form>
|
||||
<button type="submit" form="updateTplForm">Save</button>
|
||||
<button type="button" onclick={() => (assignModal = null)}>Cancel</button>
|
||||
<button type="button" onclick={assignChore}>Assign</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -608,7 +510,8 @@
|
||||
Type
|
||||
<select name="type" bind:value={editType}>
|
||||
<option value="points">Points</option>
|
||||
<option value="emoji">Emoji</option>
|
||||
<option value="money">Cash</option>
|
||||
<option value="emoji">Celebration</option>
|
||||
</select>
|
||||
</label>
|
||||
{#if editType === 'points'}
|
||||
@@ -616,6 +519,37 @@
|
||||
Points value
|
||||
<input name="value" type="number" bind:value={editValue} required />
|
||||
</label>
|
||||
{:else if editType === 'money'}
|
||||
<label>
|
||||
Cash amount (£)
|
||||
<input name="value" type="number" step="0.01" min="0.01" bind:value={editValue} required />
|
||||
</label>
|
||||
{:else}
|
||||
<input type="hidden" name="emoji" value={editEmoji} />
|
||||
<div class="emoji-field">
|
||||
<span class="emoji-preview">{editEmoji}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="link-btn"
|
||||
onclick={() => (showTodoEmojiPicker = !showTodoEmojiPicker)}>
|
||||
{showTodoEmojiPicker ? 'Hide' : 'Choose'}
|
||||
</button>
|
||||
</div>
|
||||
{#if showTodoEmojiPicker}
|
||||
<div class="emoji-grid">
|
||||
{#each EMOJI_CHOICES as e}
|
||||
<button
|
||||
type="button"
|
||||
class="emoji-opt"
|
||||
class:selected={e === editEmoji}
|
||||
onclick={() => {
|
||||
editEmoji = e;
|
||||
showTodoEmojiPicker = false;
|
||||
}}>{e}</button
|
||||
>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
<label>
|
||||
Start date
|
||||
@@ -721,7 +655,8 @@
|
||||
Type
|
||||
<select name="type" bind:value={todoType}>
|
||||
<option value="points">Points</option>
|
||||
<option value="emoji">Emoji</option>
|
||||
<option value="money">Cash</option>
|
||||
<option value="emoji">Celebration</option>
|
||||
</select>
|
||||
</label>
|
||||
{#if todoType === 'points'}
|
||||
@@ -729,6 +664,34 @@
|
||||
Points value
|
||||
<input name="value" type="number" bind:value={todoValue} required />
|
||||
</label>
|
||||
{:else if todoType === 'money'}
|
||||
<label>
|
||||
Cash amount (£)
|
||||
<input name="value" type="number" step="0.01" min="0.01" bind:value={todoValue} required />
|
||||
</label>
|
||||
{:else}
|
||||
<input type="hidden" name="emoji" value={todoEmoji} />
|
||||
<div class="emoji-field">
|
||||
<span class="emoji-preview">{todoEmoji}</span>
|
||||
<button type="button" class="link-btn" onclick={() => (showTodoEmojiPicker = !showTodoEmojiPicker)}>
|
||||
{showTodoEmojiPicker ? 'Hide' : 'Choose'}
|
||||
</button>
|
||||
</div>
|
||||
{#if showTodoEmojiPicker}
|
||||
<div class="emoji-grid">
|
||||
{#each EMOJI_CHOICES as e}
|
||||
<button
|
||||
type="button"
|
||||
class="emoji-opt"
|
||||
class:selected={e === todoEmoji}
|
||||
onclick={() => {
|
||||
todoEmoji = e;
|
||||
showTodoEmojiPicker = false;
|
||||
}}>{e}</button
|
||||
>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
<label>
|
||||
Starts
|
||||
@@ -786,20 +749,20 @@
|
||||
font-weight: 700;
|
||||
}
|
||||
.template-list {
|
||||
display: grid;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.75rem;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
@media (max-width: 1100px) {
|
||||
.template-list {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
.template-list .card.template {
|
||||
flex: 0 1 auto;
|
||||
min-width: 150px;
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.template-list {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.template-list .card.template .card-body {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
/* ── Kanban (3 columns, scrolls via Card scrollX) ── */
|
||||
@@ -877,6 +840,7 @@
|
||||
.card {
|
||||
background: white;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-left: 4px solid #8b5cf6;
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
margin-bottom: 0.4rem;
|
||||
@@ -896,9 +860,11 @@
|
||||
.card-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.card-body strong {
|
||||
display: block;
|
||||
font-size: 0.85rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
@@ -1192,6 +1158,38 @@
|
||||
font-size: 0.7rem;
|
||||
margin-top: 0.15rem;
|
||||
}
|
||||
.emoji-field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.emoji-preview {
|
||||
font-size: 1.4rem;
|
||||
}
|
||||
.emoji-grid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.25rem;
|
||||
padding: 0.4rem;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.emoji-opt {
|
||||
font-size: 1.2rem;
|
||||
background: none;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 6px;
|
||||
padding: 0.15rem 0.3rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.emoji-opt:hover {
|
||||
background: #f3f4f6;
|
||||
}
|
||||
.emoji-opt.selected {
|
||||
border-color: #6366f1;
|
||||
background: #eef2ff;
|
||||
}
|
||||
.todo-admin-type {
|
||||
color: #6b7280;
|
||||
font-weight: 600;
|
||||
|
||||
@@ -23,6 +23,8 @@ export const load: PageServerLoad = async (event) => {
|
||||
authenticated: false,
|
||||
fams: [],
|
||||
codes: [],
|
||||
choreTemplates: [],
|
||||
bonusTemplates: [],
|
||||
platformFlags: {},
|
||||
totalFams: 0,
|
||||
totalMembers: 0,
|
||||
@@ -82,10 +84,17 @@ export const load: PageServerLoad = async (event) => {
|
||||
usedBy: usage[c.id] || []
|
||||
}));
|
||||
|
||||
const [choreTemplates, bonusTemplates] = await Promise.all([
|
||||
pbAdmin.getList('chore_templates', 'global = true'),
|
||||
pbAdmin.getList('bonus_templates', 'global = true')
|
||||
]);
|
||||
|
||||
return {
|
||||
authenticated: true,
|
||||
fams: famsWithStats,
|
||||
codes: codeList,
|
||||
choreTemplates: choreTemplates as any[],
|
||||
bonusTemplates: bonusTemplates as any[],
|
||||
totalFams: fams.length,
|
||||
totalMembers: famsWithStats.reduce((s, f) => s + f.memberCount, 0),
|
||||
totalRewards: famsWithStats.reduce((s, f) => s + f.totalRewards, 0),
|
||||
@@ -110,6 +119,8 @@ export const load: PageServerLoad = async (event) => {
|
||||
subCount: 0,
|
||||
gatedCount: 0,
|
||||
codeCount: 0,
|
||||
choreTemplates: [],
|
||||
bonusTemplates: [],
|
||||
loadError: e instanceof Error ? e.message : 'Failed to load platform data'
|
||||
};
|
||||
}
|
||||
@@ -225,5 +236,113 @@ export const actions: Actions = {
|
||||
} catch (e) {
|
||||
return fail(500, { error: e instanceof Error ? e.message : 'Failed to delete code' });
|
||||
}
|
||||
},
|
||||
|
||||
// Platform-owned chore/reward templates. `type` selects the target
|
||||
// collection (chore_templates | bonus_templates); the droplet is always
|
||||
// global (visible to every family as an assignable source).
|
||||
createTemplate: async (event) => {
|
||||
requirePlatform(event);
|
||||
const fd = await event.request.formData();
|
||||
const type = fd.get('type') as string;
|
||||
const name = (fd.get('name') as string || '').trim();
|
||||
const description = (fd.get('description') as string) || '';
|
||||
const icon = (fd.get('icon') as string) || '';
|
||||
const color = (fd.get('color') as string) || '#6366f1';
|
||||
if (!name) return fail(400, { error: 'Name required' });
|
||||
|
||||
try {
|
||||
if (type === 'chore') {
|
||||
await pbAdmin.create('chore_templates', {
|
||||
name,
|
||||
description,
|
||||
icon,
|
||||
color,
|
||||
global: true,
|
||||
defaultFrequency: (fd.get('defaultFrequency') as string) || 'daily',
|
||||
defaultType: (fd.get('defaultType') as string) || 'points',
|
||||
defaultValue: Number(fd.get('defaultValue') || 0)
|
||||
});
|
||||
} else {
|
||||
await pbAdmin.create('bonus_templates', {
|
||||
name,
|
||||
description,
|
||||
icon,
|
||||
color,
|
||||
global: true,
|
||||
target: (fd.get('target') as string) || 'individual',
|
||||
type: (fd.get('bonusType') as string) || 'threshold',
|
||||
thresholdType: (fd.get('thresholdType') as string) || 'points',
|
||||
occurrence: (fd.get('occurrence') as string) || 'recurring',
|
||||
rewardType: (fd.get('rewardType') as string) || 'points',
|
||||
rewardValue: (fd.get('rewardValue') as string) || '',
|
||||
criteriaValue: Number(fd.get('criteriaValue') || 0),
|
||||
period: (fd.get('period') as string) || 'weekly',
|
||||
isPocketMoney: fd.get('isPocketMoney') === 'true'
|
||||
});
|
||||
}
|
||||
return { success: true };
|
||||
} catch (e) {
|
||||
return fail(500, { error: e instanceof Error ? e.message : 'Failed to create template' });
|
||||
}
|
||||
},
|
||||
|
||||
updateTemplate: async (event) => {
|
||||
requirePlatform(event);
|
||||
const fd = await event.request.formData();
|
||||
const kind = fd.get('kind') as string; // chore | reward
|
||||
const id = fd.get('id') as string;
|
||||
if (!id) return fail(400, { error: 'Missing id' });
|
||||
const name = (fd.get('name') as string || '').trim();
|
||||
const description = (fd.get('description') as string) || '';
|
||||
const icon = (fd.get('icon') as string) || '';
|
||||
const color = (fd.get('color') as string) || '#6366f1';
|
||||
|
||||
try {
|
||||
if (kind === 'chore') {
|
||||
await pbAdmin.update('chore_templates', id, {
|
||||
name,
|
||||
description,
|
||||
icon,
|
||||
color,
|
||||
defaultFrequency: (fd.get('defaultFrequency') as string) || 'daily',
|
||||
defaultType: (fd.get('defaultType') as string) || 'points',
|
||||
defaultValue: Number(fd.get('defaultValue') || 0)
|
||||
});
|
||||
} else {
|
||||
await pbAdmin.update('bonus_templates', id, {
|
||||
name,
|
||||
description,
|
||||
icon,
|
||||
color,
|
||||
target: (fd.get('target') as string) || 'individual',
|
||||
type: (fd.get('bonusType') as string) || 'threshold',
|
||||
thresholdType: (fd.get('thresholdType') as string) || 'points',
|
||||
occurrence: (fd.get('occurrence') as string) || 'recurring',
|
||||
rewardType: (fd.get('rewardType') as string) || 'points',
|
||||
rewardValue: (fd.get('rewardValue') as string) || '',
|
||||
criteriaValue: Number(fd.get('criteriaValue') || 0),
|
||||
period: (fd.get('period') as string) || 'weekly',
|
||||
isPocketMoney: fd.get('isPocketMoney') === 'true'
|
||||
});
|
||||
}
|
||||
return { success: true };
|
||||
} catch (e) {
|
||||
return fail(500, { error: e instanceof Error ? e.message : 'Failed to update template' });
|
||||
}
|
||||
},
|
||||
|
||||
deleteTemplate: async (event) => {
|
||||
requirePlatform(event);
|
||||
const fd = await event.request.formData();
|
||||
const kind = fd.get('kind') as string;
|
||||
const id = fd.get('id') as string;
|
||||
if (!id) return fail(400, { error: 'Missing id' });
|
||||
try {
|
||||
await pbAdmin.remove(kind === 'chore' ? 'chore_templates' : 'bonus_templates', id);
|
||||
return { success: true };
|
||||
} catch (e) {
|
||||
return fail(500, { error: e instanceof Error ? e.message : 'Failed to delete template' });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import { goto, invalidateAll } from '$app/navigation';
|
||||
import { page } from '$app/state';
|
||||
import { ViewHeader, CardGrid, Card, Button } from '$lib/components';
|
||||
import TemplateIcon from '$lib/components/TemplateIcon.svelte';
|
||||
import { ICON_NAMES } from '$lib/templateIcons';
|
||||
import Footer from '$lib/components/Footer.svelte';
|
||||
|
||||
let { data, form } = $props();
|
||||
@@ -20,6 +22,65 @@
|
||||
canceled: 'Canceled',
|
||||
none: 'None'
|
||||
};
|
||||
|
||||
// ── Platform template management ──
|
||||
type TplKind = 'chore' | 'reward';
|
||||
let showTplModal = $state(false);
|
||||
let editingTpl = $state<{ kind: TplKind; id: string } | null>(null);
|
||||
let tplType = $state<TplKind>('chore');
|
||||
const blankTpl = {
|
||||
name: '',
|
||||
description: '',
|
||||
icon: 'Star',
|
||||
color: '#6366f1',
|
||||
defaultFrequency: 'daily',
|
||||
defaultType: 'points',
|
||||
defaultValue: 0,
|
||||
target: 'individual',
|
||||
bonusType: 'threshold',
|
||||
thresholdType: 'points',
|
||||
occurrence: 'recurring',
|
||||
rewardType: 'points',
|
||||
rewardValue: '',
|
||||
criteriaValue: 0,
|
||||
period: 'weekly',
|
||||
isPocketMoney: false
|
||||
};
|
||||
let tplVals = $state({ ...blankTpl });
|
||||
|
||||
function openNewTpl(kind: TplKind) {
|
||||
editingTpl = null;
|
||||
tplType = kind;
|
||||
tplVals = { ...blankTpl };
|
||||
showTplModal = true;
|
||||
}
|
||||
function openEditTpl(kind: TplKind, rec: any) {
|
||||
editingTpl = { kind, id: rec.id };
|
||||
tplType = kind;
|
||||
tplVals = {
|
||||
name: rec.name || '',
|
||||
description: rec.description || '',
|
||||
icon: rec.icon || 'Star',
|
||||
color: rec.color || '#6366f1',
|
||||
defaultFrequency: rec.defaultFrequency || 'daily',
|
||||
defaultType: rec.defaultType || 'points',
|
||||
defaultValue: rec.defaultValue ?? 0,
|
||||
target: rec.target || 'individual',
|
||||
bonusType: rec.type || 'threshold',
|
||||
thresholdType: rec.thresholdType || 'points',
|
||||
occurrence: rec.occurrence || 'recurring',
|
||||
rewardType: rec.rewardType || 'points',
|
||||
rewardValue: rec.rewardValue ?? '',
|
||||
criteriaValue: rec.criteriaValue ?? 0,
|
||||
period: rec.period || 'weekly',
|
||||
isPocketMoney: !!rec.isPocketMoney
|
||||
};
|
||||
showTplModal = true;
|
||||
}
|
||||
const allTemplates = $derived([
|
||||
...(data.choreTemplates || []).map((t: any) => ({ ...t, kind: 'chore' as TplKind })),
|
||||
...(data.bonusTemplates || []).map((t: any) => ({ ...t, kind: 'reward' as TplKind }))
|
||||
]);
|
||||
</script>
|
||||
|
||||
<div class="shell">
|
||||
@@ -258,6 +319,184 @@
|
||||
</Card>
|
||||
</CardGrid>
|
||||
|
||||
<CardGrid>
|
||||
<Card cols={3} title="Templates" accent="#8b5cf6">
|
||||
<p class="muted">
|
||||
Platform-owned chore & reward droplets. Families assign these as read-only sources — they
|
||||
can't create their own.
|
||||
</p>
|
||||
<div class="tpl-grid">
|
||||
{#each allTemplates as t}
|
||||
<div class="tpl-card" style="border-left-color:{t.color}">
|
||||
<div class="tpl-head">
|
||||
<TemplateIcon name={t.icon} size={20} color={t.color} />
|
||||
<strong>{t.name}</strong>
|
||||
</div>
|
||||
<div class="tpl-meta">
|
||||
<span class="badge">{t.kind}</span>
|
||||
{#if t.isPocketMoney}<span class="badge pocket">Pocket Money</span>{/if}
|
||||
</div>
|
||||
<div class="tpl-actions">
|
||||
<button class="link-btn" onclick={() => openEditTpl(t.kind, t)}>Edit</button>
|
||||
<form
|
||||
method="POST"
|
||||
action="?/deleteTemplate"
|
||||
use:enhance={() => {
|
||||
return async ({ result, update }) => {
|
||||
update();
|
||||
};
|
||||
}}
|
||||
>
|
||||
<input type="hidden" name="kind" value={t.kind} />
|
||||
<input type="hidden" name="id" value={t.id} />
|
||||
<button
|
||||
type="submit"
|
||||
class="link-btn danger"
|
||||
onclick={(e) => {
|
||||
if (!confirm('Delete this template?')) e.preventDefault();
|
||||
}}>Delete</button
|
||||
>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{#if allTemplates.length === 0}
|
||||
<p class="muted">No templates yet.</p>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="tpl-new">
|
||||
<Button onclick={() => openNewTpl('chore')}>+ Chore template</Button>
|
||||
<Button onclick={() => openNewTpl('reward')}>+ Reward template</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</CardGrid>
|
||||
|
||||
{#if showTplModal}
|
||||
<div class="overlay" onclick={() => (showTplModal = false)} role="presentation">
|
||||
<div class="modal" onclick={(e) => e.stopPropagation()} role="dialog">
|
||||
<h3>{editingTpl ? 'Edit' : 'New'} {tplType} template</h3>
|
||||
<form
|
||||
method="POST"
|
||||
action={editingTpl ? '?/updateTemplate' : '?/createTemplate'}
|
||||
use:enhance={() => {
|
||||
return async ({ result, update }) => {
|
||||
if (result.type === 'success') showTplModal = false;
|
||||
update();
|
||||
};
|
||||
}}
|
||||
>
|
||||
{#if editingTpl}
|
||||
<input type="hidden" name="kind" value={editingTpl.kind} />
|
||||
<input type="hidden" name="id" value={editingTpl.id} />
|
||||
{/if}
|
||||
<input type="hidden" name="type" value={tplType} />
|
||||
<label>Name <input name="name" bind:value={tplVals.name} required /></label>
|
||||
<label>Description <input name="description" bind:value={tplVals.description} /></label>
|
||||
<div class="row">
|
||||
<label>
|
||||
Icon
|
||||
<select name="icon" bind:value={tplVals.icon}>
|
||||
{#each ICON_NAMES as n}<option value={n}>{n}</option>{/each}
|
||||
</select>
|
||||
</label>
|
||||
<span class="icon-preview"><TemplateIcon name={tplVals.icon} size={22} color={tplVals.color} /></span>
|
||||
<label>
|
||||
Colour
|
||||
<input type="color" name="color" bind:value={tplVals.color} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{#if tplType === 'chore'}
|
||||
<label>
|
||||
Frequency
|
||||
<select name="defaultFrequency" bind:value={tplVals.defaultFrequency}>
|
||||
<option value="daily">Daily</option>
|
||||
<option value="weekly">Weekly</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Type
|
||||
<select name="defaultType" bind:value={tplVals.defaultType}>
|
||||
<option value="points">Points</option>
|
||||
<option value="money">Money</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Default Value
|
||||
<input type="number" step="any" name="defaultValue" bind:value={tplVals.defaultValue} />
|
||||
</label>
|
||||
{:else}
|
||||
<label>
|
||||
Target
|
||||
<select name="target" bind:value={tplVals.target}>
|
||||
<option value="individual">Individual</option>
|
||||
<option value="competitive">Competition</option>
|
||||
<option value="collaborative">Collaborative</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Type
|
||||
<select name="bonusType" bind:value={tplVals.bonusType}>
|
||||
<option value="threshold">Threshold</option>
|
||||
<option value="count">Count</option>
|
||||
<option value="manual">Manual</option>
|
||||
</select>
|
||||
</label>
|
||||
{#if tplVals.bonusType === 'threshold'}
|
||||
<label>
|
||||
Threshold by
|
||||
<select name="thresholdType" bind:value={tplVals.thresholdType}>
|
||||
<option value="points">Points</option>
|
||||
<option value="percent">% of chores done</option>
|
||||
</select>
|
||||
</label>
|
||||
{/if}
|
||||
<label>
|
||||
Occurrence
|
||||
<select name="occurrence" bind:value={tplVals.occurrence}>
|
||||
<option value="recurring">Recurring</option>
|
||||
<option value="once">Once</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Reward Type
|
||||
<select name="rewardType" bind:value={tplVals.rewardType}>
|
||||
<option value="points">Points</option>
|
||||
<option value="cash">Cash</option>
|
||||
<option value="prize">Prize</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Reward Value
|
||||
<input name="rewardValue" bind:value={tplVals.rewardValue} />
|
||||
</label>
|
||||
<label>
|
||||
Target Value
|
||||
<input type="number" name="criteriaValue" bind:value={tplVals.criteriaValue} />
|
||||
</label>
|
||||
<label>
|
||||
Period
|
||||
<select name="period" bind:value={tplVals.period}>
|
||||
<option value="daily">Daily</option>
|
||||
<option value="weekly">Weekly</option>
|
||||
<option value="monthly">Monthly</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="check">
|
||||
<input type="checkbox" name="isPocketMoney" value="true" bind:checked={tplVals.isPocketMoney} />
|
||||
Pocket Money
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
<div class="modal-actions">
|
||||
<button type="button" onclick={() => (showTplModal = false)}>Cancel</button>
|
||||
<button type="submit">{editingTpl ? 'Save' : 'Create'}</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
@@ -669,4 +908,97 @@
|
||||
border-bottom: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Template management ── */
|
||||
.tpl-grid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.6rem;
|
||||
margin: 0.75rem 0;
|
||||
}
|
||||
.tpl-card {
|
||||
flex: 0 1 auto;
|
||||
min-width: 180px;
|
||||
background: #fff;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-left: 4px solid #8b5cf6;
|
||||
border-radius: 10px;
|
||||
padding: 0.6rem 0.75rem;
|
||||
}
|
||||
.tpl-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
.tpl-head strong { font-size: 0.9rem; }
|
||||
.tpl-meta { display: flex; gap: 0.3rem; flex-wrap: wrap; margin-bottom: 0.4rem; }
|
||||
.tpl-actions { display: flex; gap: 0.75rem; }
|
||||
.tpl-new { display: flex; gap: 0.6rem; margin-top: 0.5rem; }
|
||||
.row { display: flex; align-items: flex-end; gap: 0.75rem; flex-wrap: wrap; }
|
||||
.icon-preview {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.badge.pocket { background: #dcfce7; color: #166534; }
|
||||
.check { display: flex; align-items: center; gap: 0.4rem; }
|
||||
|
||||
/* ── Modal (shared) ── */
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(15, 23, 42, 0.45);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1rem;
|
||||
z-index: 50;
|
||||
}
|
||||
.modal {
|
||||
background: #fff;
|
||||
border-radius: 14px;
|
||||
padding: 1.25rem 1.5rem;
|
||||
width: min(440px, 100%);
|
||||
max-height: 88vh;
|
||||
overflow: auto;
|
||||
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
.modal h3 { margin: 0 0 0.75rem; }
|
||||
.modal label {
|
||||
display: block;
|
||||
margin-bottom: 0.6rem;
|
||||
font-size: 0.85rem;
|
||||
color: #374151;
|
||||
}
|
||||
.modal input,
|
||||
.modal select {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin-top: 0.25rem;
|
||||
padding: 0.5rem;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 6px;
|
||||
font-size: 0.9rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
justify-content: flex-end;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
.modal-actions button {
|
||||
padding: 0.5rem 1rem;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.modal-actions button[type='button'] { background: #e5e7eb; color: #374151; }
|
||||
.modal-actions button[type='submit'] { background: #6366f1; color: #fff; }
|
||||
</style>
|
||||
|
||||
@@ -54,24 +54,9 @@ export const actions = {
|
||||
role: 'parent'
|
||||
});
|
||||
await pbAdmin.create('settings', { famId: fam.id });
|
||||
// Seed the family-level POCKET MONEY bonus template (the teaching
|
||||
// droplet). Per-child instances are created when each child joins.
|
||||
await pbAdmin
|
||||
.create('bonus_templates', {
|
||||
famId: fam.id,
|
||||
name: 'POCKET MONEY',
|
||||
description: 'Weekly pocket money for children',
|
||||
target: 'individual',
|
||||
type: 'threshold',
|
||||
thresholdType: 'percent',
|
||||
occurrence: 'recurring',
|
||||
rewardType: 'cash',
|
||||
rewardValue: '',
|
||||
criteriaValue: 50,
|
||||
period: 'weekly',
|
||||
isPocketMoney: true
|
||||
})
|
||||
.catch(() => null);
|
||||
// Pocket money is a platform-owned global template (seeded by migrate)
|
||||
// and per-child instances are created when each child joins — no
|
||||
// family-level template needed here.
|
||||
} catch (e) {
|
||||
throw new SignupError(
|
||||
`Could not create account — ${e instanceof Error ? e.message : 'please try again'}`
|
||||
|
||||
Reference in New Issue
Block a user