migrate from hono
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
// Client-only. All /api calls go same-origin (vite proxy in dev, nginx in
|
||||
// prod). Server-side (SSR) calls use PROXY_URL from $app/env/public instead.
|
||||
// Client-only. All /api calls go same-origin (SvelteKit in dev and prod).
|
||||
const BASE_URL = '';
|
||||
|
||||
async function memberFetch<T = unknown>(
|
||||
@@ -27,16 +26,10 @@ export const memberApi = {
|
||||
async toggleCompletion(token: string, famId: string, assignedChoreId: string, date: string) {
|
||||
return memberFetch('POST', '/api/completions/toggle', token, famId, { assignedChoreId, date });
|
||||
},
|
||||
async myChores(token: string, famId: string) {
|
||||
return memberFetch('POST', '/api/members/my-chores', token, famId);
|
||||
},
|
||||
async claimReward(token: string, famId: string, rewardId: string) {
|
||||
return memberFetch('POST', `/api/members/rewards/${rewardId}/claim`, token, famId);
|
||||
},
|
||||
async requestAllRewards(token: string, famId: string) {
|
||||
return memberFetch<{ count: number }>('POST', '/api/members/rewards/request-all', token, famId);
|
||||
},
|
||||
async payday(token: string, famId: string) {
|
||||
return memberFetch('POST', `/api/fam/${famId}/payday`, token, famId);
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -1,246 +0,0 @@
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
import { PROXY_URL } from '$app/env/public';
|
||||
|
||||
function sessionHeaders(event: RequestEvent): Record<string, string> {
|
||||
const u = event.locals.user;
|
||||
if (!u) return {};
|
||||
return {
|
||||
'x-session-famid': u.famId,
|
||||
'x-session-userid': u.id,
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
}
|
||||
|
||||
async function request(
|
||||
method: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
headers?: Record<string, string>
|
||||
) {
|
||||
const res = await fetch(`${PROXY_URL}${path}`, {
|
||||
method,
|
||||
headers: headers || { 'Content-Type': 'application/json' },
|
||||
body: body ? JSON.stringify(body) : undefined
|
||||
});
|
||||
const text = await res.text();
|
||||
let data: any = {};
|
||||
try {
|
||||
data = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
data = { raw: text };
|
||||
}
|
||||
if (!res.ok) {
|
||||
const msg = data?.error || data?.message || `${method} ${path} failed (HTTP ${res.status})`;
|
||||
throw new Error(msg);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
export const hono = {
|
||||
admin: {
|
||||
async list(event: RequestEvent, resource: string, famId: string) {
|
||||
return request('GET', `/api/admin/${famId}/${resource}`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async create(
|
||||
event: RequestEvent,
|
||||
resource: string,
|
||||
famId: string,
|
||||
data: Record<string, unknown>
|
||||
) {
|
||||
return request('POST', `/api/admin/${famId}/${resource}`, data, sessionHeaders(event));
|
||||
},
|
||||
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));
|
||||
},
|
||||
async remove(event: RequestEvent, resource: string, famId: string, id: string) {
|
||||
return request(
|
||||
'DELETE',
|
||||
`/api/admin/${famId}/${resource}/${id}`,
|
||||
undefined,
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async renameFam(event: RequestEvent, famId: string, name: string) {
|
||||
return request('PATCH', `/api/admin/${famId}/fam`, { name }, sessionHeaders(event));
|
||||
},
|
||||
async updatePayday(
|
||||
event: RequestEvent,
|
||||
famId: string,
|
||||
payday: number,
|
||||
paydayTime?: string,
|
||||
timezone?: string
|
||||
) {
|
||||
return request(
|
||||
'PATCH',
|
||||
`/api/admin/${famId}/fam`,
|
||||
{
|
||||
payday,
|
||||
...(paydayTime !== undefined ? { paydayTime } : {}),
|
||||
...(timezone !== undefined ? { timezone } : {})
|
||||
},
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async fam(event: RequestEvent, famId: string) {
|
||||
return request('GET', `/api/admin/${famId}/fam`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async verify(event: RequestEvent, famId: string) {
|
||||
return request('GET', `/api/admin/${famId}/verify`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async weeklySummary(event: RequestEvent, famId: string) {
|
||||
return request('GET', `/api/admin/${famId}/weekly-summary`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async completions(event: RequestEvent, famId: string) {
|
||||
return request('GET', `/api/admin/${famId}/completions`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async rewards(event: RequestEvent, famId: string) {
|
||||
return request('GET', `/api/admin/${famId}/rewards`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async claimReward(event: RequestEvent, famId: string, rewardId: string) {
|
||||
return request(
|
||||
'POST',
|
||||
`/api/admin/${famId}/rewards/${rewardId}/claim`,
|
||||
undefined,
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async issueAllRewards(event: RequestEvent, famId: string, memberId: string) {
|
||||
return request(
|
||||
'POST',
|
||||
`/api/admin/${famId}/rewards/issue-all`,
|
||||
{ memberId },
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async bonusConfigs(event: RequestEvent, famId: string) {
|
||||
return request('GET', `/api/admin/${famId}/bonus-configs`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async bonusConfigProgress(event: RequestEvent, famId: string) {
|
||||
return request(
|
||||
'GET',
|
||||
`/api/admin/${famId}/bonus-configs/progress`,
|
||||
undefined,
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async evaluateBonusConfig(event: RequestEvent, famId: string, configId?: string) {
|
||||
return request(
|
||||
'POST',
|
||||
`/api/admin/${famId}/bonus-configs/evaluate`,
|
||||
{ configId },
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async triggerBonusConfig(
|
||||
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>
|
||||
) {
|
||||
return request(
|
||||
'POST',
|
||||
`/api/admin/${famId}/bonus-configs/${configId}/assign`,
|
||||
data,
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async completeBonusConfig(event: RequestEvent, famId: string, configId: string) {
|
||||
return request(
|
||||
'POST',
|
||||
`/api/admin/${famId}/bonus-configs/${configId}/complete`,
|
||||
undefined,
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async destroyBonusConfig(event: RequestEvent, famId: string, configId: string) {
|
||||
return request(
|
||||
'POST',
|
||||
`/api/admin/${famId}/bonus-configs/${configId}/destroy`,
|
||||
undefined,
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async bonusConfigTallies(event: RequestEvent, famId: string) {
|
||||
return request(
|
||||
'GET',
|
||||
`/api/admin/${famId}/bonus-configs/tallies`,
|
||||
undefined,
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async revokeCompletion(event: RequestEvent, famId: string, completionId: string) {
|
||||
return request(
|
||||
'POST',
|
||||
`/api/admin/${famId}/completions/${completionId}/revoke`,
|
||||
undefined,
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async memberChores(event: RequestEvent, famId: string, memberId: string) {
|
||||
return request(
|
||||
'GET',
|
||||
`/api/admin/${famId}/members/${memberId}/chores`,
|
||||
undefined,
|
||||
sessionHeaders(event)
|
||||
);
|
||||
},
|
||||
async updateMember(
|
||||
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) {
|
||||
return request('GET', `/api/admin/${famId}/profile`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async updateProfile(event: RequestEvent, famId: string, data: Record<string, unknown>) {
|
||||
return request('PATCH', `/api/admin/${famId}/profile`, data, sessionHeaders(event));
|
||||
},
|
||||
async updateFam(event: RequestEvent, famId: string, data: Record<string, unknown>) {
|
||||
return request('PATCH', `/api/admin/${famId}/fam`, data, sessionHeaders(event));
|
||||
},
|
||||
async request(event: RequestEvent, method: string, path: string, body?: unknown) {
|
||||
return request(method, path, body, sessionHeaders(event));
|
||||
},
|
||||
async settings(event: RequestEvent, famId: string) {
|
||||
return request('GET', `/api/admin/${famId}/settings`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async updateSettings(event: RequestEvent, famId: string, data: Record<string, unknown>) {
|
||||
return request('PATCH', `/api/admin/${famId}/settings`, data, sessionHeaders(event));
|
||||
},
|
||||
async eowPreview(event: RequestEvent, famId: string) {
|
||||
return request(
|
||||
'GET',
|
||||
`/api/admin/${famId}/debug/eow-preview`,
|
||||
undefined,
|
||||
sessionHeaders(event)
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import { migrate } from './migrate';
|
||||
|
||||
// Runs the PocketBase schema migration once per server process, at boot.
|
||||
// Idempotent (migrate() diffs against existing collections), so re-running on
|
||||
// dev HMR or restarts is a cheap no-op. Errors are logged, not thrown, so a
|
||||
// migration hiccup never takes the server down.
|
||||
let done: Promise<void> | null = null;
|
||||
|
||||
export function migrateOnBoot(): Promise<void> {
|
||||
if (!done) {
|
||||
done = migrate().catch((e) => {
|
||||
console.error('[migrate] failed:', e);
|
||||
});
|
||||
}
|
||||
return done;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -36,9 +36,8 @@ export async function createSuperClient() {
|
||||
return pb;
|
||||
}
|
||||
|
||||
// Superuser CRUD facade, built on the memoized SDK superuser client. Replaces
|
||||
// the old raw-fetch `pb-admin.ts`/`ensureToken` path so all server PB access
|
||||
// (authenticated user + superuser) lives in this one module.
|
||||
// Superuser CRUD facade, built on the memoized SDK superuser client. All
|
||||
// server PB access (authenticated user + superuser) lives in this one module.
|
||||
export const pbAdmin = {
|
||||
async getList(collection: string, filter = '') {
|
||||
const pb = await createSuperClient();
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { error } from '@sveltejs/kit';
|
||||
import { createPbClient } from '$lib/server/pocketbase';
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
|
||||
// Resolve the acting user's PB client from a request: prefer the Authorization
|
||||
// Bearer token (sent by the browser member API), else the httpOnly session
|
||||
// cookie. Identity comes from the verified session. Used by the in-app /api/*
|
||||
// routes that replaced the Hono member endpoints.
|
||||
export function actingClient(event: RequestEvent) {
|
||||
const token =
|
||||
event.request.headers.get('authorization')?.replace(/^Bearer\s+/i, '') ||
|
||||
event.locals.pbToken ||
|
||||
'';
|
||||
const u = event.locals.user;
|
||||
if (!u || !token) throw error(401, 'Unauthorized');
|
||||
return {
|
||||
pb: createPbClient(token),
|
||||
famId: u.famId,
|
||||
userId: u.id,
|
||||
role: u.role,
|
||||
name: u.name || '',
|
||||
color: u.color || '#6366f1'
|
||||
};
|
||||
}
|
||||
|
||||
export function err(e: unknown) {
|
||||
return error(500, e instanceof Error ? e.message : 'Internal error');
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
import {
|
||||
todayInTz,
|
||||
resolveTz,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
nextPaydayAfter,
|
||||
weekStart
|
||||
} from '@shared/timezone';
|
||||
import { famMeta } from './fam';
|
||||
|
||||
function resolveServerTz(tz?: string): string {
|
||||
return resolveTz(tz || 'auto');
|
||||
}
|
||||
|
||||
function claimableStamp(cfg: any, payday: number, tz: string) {
|
||||
if (cfg.period !== 'weekly' && cfg.period !== 'monthly') {
|
||||
return { claimable: 'immediate', settleDate: '' };
|
||||
}
|
||||
const now = todayInTz(resolveServerTz(tz));
|
||||
const start = cfg.period === 'monthly' ? `${now.slice(0, 7)}-01` : weekStart(payday, tz);
|
||||
const end = periodEnd(cfg.period, start);
|
||||
return { claimable: 'payday', settleDate: nextPaydayAfter(end, payday, tz) };
|
||||
}
|
||||
|
||||
export async function evaluateFam(pb: any, famId: string) {
|
||||
let configs: any[] = [];
|
||||
try {
|
||||
configs = await pb
|
||||
.collection('bonus_configs')
|
||||
.getFullList({ filter: `famId = '${famId}' && status = 'active' && type != 'manual'` });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!configs.length) return;
|
||||
|
||||
const [allMembers, allAssigned, allCompletions] = await Promise.all([
|
||||
pb.collection('users').getFullList({ filter: `famId = '${famId}' && role = 'child'` }),
|
||||
pb.collection('assigned_chores').getFullList({ filter: `famId = '${famId}'` }),
|
||||
pb.collection('completions').getFullList({ filter: `famId = '${famId}'` })
|
||||
]);
|
||||
let allRewards: any[] = [];
|
||||
try {
|
||||
allRewards = await pb.collection('rewards').getFullList({ filter: `famId = '${famId}'` });
|
||||
} catch {}
|
||||
const { payday: paydayEval, tz: tzEval } = await famMeta(pb, famId);
|
||||
|
||||
for (const cfg of configs) {
|
||||
const pStart2 = cfg.period ? periodStart(cfg.period, paydayEval, tzEval) : '';
|
||||
const pEnd = cfg.period ? periodEnd(cfg.period, pStart2) : '';
|
||||
const periodCompletions = cfg.period
|
||||
? allCompletions.filter(
|
||||
(c: any) => (c.date || '').slice(0, 10) >= pStart2 && (c.date || '').slice(0, 10) <= pEnd
|
||||
)
|
||||
: allCompletions;
|
||||
|
||||
const existingRewards = allRewards.filter((r: any) => r.bonusConfigId === cfg.id);
|
||||
let createdReward = false;
|
||||
|
||||
const rewardData = (memberId: string) => {
|
||||
const label =
|
||||
cfg.rewardType === 'cash'
|
||||
? `${cfg.name} – £${Number(cfg.rewardValue).toFixed(2)}`
|
||||
: `${cfg.name} – ${cfg.rewardValue}`;
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
famId,
|
||||
memberId,
|
||||
bonusConfigId: cfg.id,
|
||||
label,
|
||||
value: Number(cfg.rewardValue) || 0,
|
||||
rewardType: cfg.rewardType,
|
||||
status: cfg.rewardType === 'points' ? 'claimed' : 'unclaimed',
|
||||
claimedAt: cfg.rewardType === 'points' ? now : null,
|
||||
date: now.slice(0, 10),
|
||||
...claimableStamp(cfg, paydayEval, tzEval)
|
||||
};
|
||||
};
|
||||
|
||||
if (cfg.target === 'individual') {
|
||||
const targetMembers = cfg.memberId ? allMembers.filter((m: any) => m.id === cfg.memberId) : allMembers;
|
||||
for (const m of targetMembers) {
|
||||
const memberCompletions = periodCompletions.filter((c: any) => c.memberId === m.id);
|
||||
let current = 0;
|
||||
if (cfg.type === 'threshold') {
|
||||
current = memberCompletions.reduce((sum: number, c: any) => {
|
||||
const chore = allAssigned.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (chore?.type === 'points' ? Number(chore.value) : 0);
|
||||
}, 0);
|
||||
} else if (cfg.type === 'count') {
|
||||
current = memberCompletions.length;
|
||||
}
|
||||
const achieved = cfg.criteriaValue > 0 && current >= Number(cfg.criteriaValue);
|
||||
|
||||
const memberReward = existingRewards.find((r: any) => r.memberId === m.id);
|
||||
|
||||
if (memberReward && !achieved) {
|
||||
if (memberReward.status !== 'claimed') {
|
||||
try {
|
||||
await pb.collection('rewards').delete(memberReward.id);
|
||||
} catch {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (memberReward) continue;
|
||||
|
||||
if (achieved) {
|
||||
await pb.collection('rewards').create(rewardData(m.id));
|
||||
createdReward = true;
|
||||
}
|
||||
}
|
||||
} else if (cfg.target === 'collaborative') {
|
||||
const allMemberIds = allMembers.map((m: any) => m.id);
|
||||
const teamCompletions = periodCompletions.filter((c: any) => allMemberIds.includes(c.memberId));
|
||||
let total = 0;
|
||||
if (cfg.type === 'threshold') {
|
||||
total = teamCompletions.reduce((sum: number, c: any) => {
|
||||
const chore = allAssigned.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (chore?.type === 'points' ? Number(chore.value) : 0);
|
||||
}, 0);
|
||||
} else if (cfg.type === 'count') {
|
||||
total = teamCompletions.length;
|
||||
}
|
||||
const achieved = cfg.criteriaValue > 0 && total >= Number(cfg.criteriaValue);
|
||||
|
||||
if (!achieved && existingRewards.length > 0) {
|
||||
for (const r of existingRewards) {
|
||||
if (r.status !== 'claimed') {
|
||||
try {
|
||||
await pb.collection('rewards').delete(r.id);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (achieved && existingRewards.length === 0) {
|
||||
for (const m of allMembers) {
|
||||
await pb.collection('rewards').create(rewardData(m.id));
|
||||
createdReward = true;
|
||||
}
|
||||
}
|
||||
} else if (cfg.target === 'competitive') {
|
||||
const scored = allMembers.map((m: any) => {
|
||||
const memberCompletions = periodCompletions.filter((c: any) => c.memberId === m.id);
|
||||
let current = 0;
|
||||
if (cfg.type === 'threshold') {
|
||||
current = memberCompletions.reduce((sum: number, c: any) => {
|
||||
const chore = allAssigned.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (chore?.type === 'points' ? Number(chore.value) : 0);
|
||||
}, 0);
|
||||
} else if (cfg.type === 'count') {
|
||||
current = memberCompletions.length;
|
||||
}
|
||||
return { memberId: m.id, name: m.name, current };
|
||||
});
|
||||
const qualified = scored.filter((s: any) => cfg.criteriaValue > 0 && s.current >= Number(cfg.criteriaValue));
|
||||
const eligible = qualified.length > 0 ? qualified : scored.filter((s: any) => s.current > 0);
|
||||
const winner = eligible.sort((a: any, b: any) => b.current - a.current)[0];
|
||||
|
||||
if (existingRewards.length > 0) {
|
||||
const existing = existingRewards[0];
|
||||
const stillValid = winner && existing.memberId === winner.memberId && winner.current > 0;
|
||||
if (!stillValid && existing.status !== 'claimed') {
|
||||
try {
|
||||
await pb.collection('rewards').delete(existing.id);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
if (winner && existingRewards.length === 0) {
|
||||
await pb.collection('rewards').create(rewardData(winner.memberId));
|
||||
createdReward = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (cfg.occurrence === 'once' && (existingRewards.length > 0 || createdReward)) {
|
||||
try {
|
||||
await pb.collection('bonus_configs').update(cfg.id, { status: 'completed' });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function evaluateAll(pb: any, famId: string) {
|
||||
await evaluateFam(pb, famId);
|
||||
return { evaluated: true };
|
||||
}
|
||||
|
||||
export async function progress(pb: any, famId: string) {
|
||||
const { payday, tz } = await famMeta(pb, famId);
|
||||
let configsData: any[] = [];
|
||||
try {
|
||||
configsData = await pb
|
||||
.collection('bonus_configs')
|
||||
.getFullList({ filter: `famId = '${famId}' && status = 'active'` });
|
||||
} catch {}
|
||||
const [members, assigned, completions] = await Promise.all([
|
||||
pb.collection('users').getFullList({ filter: `famId = '${famId}' && role = 'child'` }),
|
||||
pb.collection('assigned_chores').getFullList({ filter: `famId = '${famId}'` }),
|
||||
pb.collection('completions').getFullList({ filter: `famId = '${famId}'` })
|
||||
]);
|
||||
|
||||
const assignedList = assigned;
|
||||
const completionsList = completions;
|
||||
let allRewards: any[] = [];
|
||||
try {
|
||||
allRewards = await pb.collection('rewards').getFullList({ filter: `famId = '${famId}'` });
|
||||
} catch {}
|
||||
|
||||
const result: any[] = [];
|
||||
|
||||
for (const cfg of configsData) {
|
||||
const cfgRewards = allRewards.filter((r: any) => r.bonusConfigId === cfg.id);
|
||||
const pStart = cfg.period ? periodStart(cfg.period, payday, tz) : '';
|
||||
const pEnd = cfg.period ? periodEnd(cfg.period, pStart) : '';
|
||||
const periodCompletions = cfg.period
|
||||
? completionsList.filter((c: any) => c.date >= pStart && c.date <= pEnd)
|
||||
: completionsList;
|
||||
|
||||
const progressRows: any[] = [];
|
||||
|
||||
if (cfg.target === 'collaborative') {
|
||||
const teamCompletions = periodCompletions.filter((c: any) =>
|
||||
members.some((m: any) => m.id === c.memberId)
|
||||
);
|
||||
let teamCurrent = 0;
|
||||
if (cfg.type === 'threshold') {
|
||||
teamCurrent = teamCompletions.reduce((sum: number, c: any) => {
|
||||
const chore = assignedList.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (chore?.type === 'points' ? Number(chore.value) : 0);
|
||||
}, 0);
|
||||
} else if (cfg.type === 'count') {
|
||||
teamCurrent = teamCompletions.length;
|
||||
}
|
||||
const teamReward = cfgRewards[0];
|
||||
progressRows.push({
|
||||
memberId: '__team__',
|
||||
memberName: 'Team Total',
|
||||
memberColor: '#8b5cf6',
|
||||
current: teamCurrent,
|
||||
criteriaValue: cfg.criteriaValue || 0,
|
||||
reward: teamReward ? { id: teamReward.id, status: teamReward.status } : null,
|
||||
state: teamReward ? teamReward.status : 'pending',
|
||||
achieved: teamReward ? true : false
|
||||
});
|
||||
}
|
||||
|
||||
if (cfg.target !== 'collaborative') {
|
||||
const progressMembers =
|
||||
cfg.target === 'individual' && cfg.memberId
|
||||
? members.filter((m: any) => m.id === cfg.memberId)
|
||||
: members;
|
||||
for (const m of progressMembers) {
|
||||
const memberCompletions = periodCompletions.filter((c: any) => c.memberId === m.id);
|
||||
const memberReward = cfgRewards.find((r: any) => r.memberId === m.id);
|
||||
|
||||
let current = 0;
|
||||
if (cfg.type === 'threshold') {
|
||||
current = memberCompletions.reduce((sum: number, c: any) => {
|
||||
const chore = assignedList.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (chore?.type === 'points' ? Number(chore.value) : 0);
|
||||
}, 0);
|
||||
} else if (cfg.type === 'count') {
|
||||
current = memberCompletions.length;
|
||||
} else if (cfg.type === 'manual') {
|
||||
current = 0;
|
||||
}
|
||||
|
||||
progressRows.push({
|
||||
memberId: m.id,
|
||||
memberName: m.name,
|
||||
memberColor: m.color,
|
||||
current,
|
||||
criteriaValue: cfg.criteriaValue || 0,
|
||||
reward: memberReward ? { id: memberReward.id, status: memberReward.status } : null,
|
||||
state: memberReward ? memberReward.status : 'pending',
|
||||
achieved: memberReward ? true : false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
result.push({ config: cfg, progress: progressRows, periodStart: pStart, periodEnd: pEnd });
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function trigger(pb: any, famId: string, configId: string, memberId?: string) {
|
||||
const configs = await pb
|
||||
.collection('bonus_configs')
|
||||
.getFullList({ filter: `famId = '${famId}' && id = '${configId}' && status = 'active'` });
|
||||
const cfg = configs?.[0];
|
||||
if (!cfg) throw new Error('Bonus config not found');
|
||||
if (cfg.type !== 'manual') throw new Error('Only manual-type configs can be triggered');
|
||||
|
||||
const existingRewards = await pb.collection('rewards').getFullList({
|
||||
filter: `famId = '${famId}' && bonusConfigId = '${cfg.id}'`
|
||||
});
|
||||
|
||||
const members = await pb
|
||||
.collection('users')
|
||||
.getFullList({ filter: `famId = '${famId}' && role = 'child'` });
|
||||
|
||||
const targetMembers: any[] = [];
|
||||
if (cfg.target === 'competitive' || cfg.target === 'collaborative') {
|
||||
for (const m of members) targetMembers.push(m);
|
||||
} else if (cfg.target === 'individual') {
|
||||
const targetId = cfg.memberId || memberId;
|
||||
if (!targetId) throw new Error('memberId required for individual trigger');
|
||||
const member = members.find((m: any) => m.id === targetId);
|
||||
if (!member) throw new Error('Member not found');
|
||||
targetMembers.push(member);
|
||||
}
|
||||
|
||||
for (const m of targetMembers) {
|
||||
const memberRewards = existingRewards.filter((r: any) => r.memberId === m.id);
|
||||
if (cfg.occurrence === 'once' && memberRewards.some((r: any) => r.status === 'unclaimed')) {
|
||||
throw new Error(`Already issued and pending for ${m.name}`);
|
||||
}
|
||||
if (cfg.occurrence === 'recurring' && cfg.period) {
|
||||
const { payday, tz } = await famMeta(pb, famId);
|
||||
const pStart = periodStart(cfg.period, payday, tz);
|
||||
const pEnd = periodEnd(cfg.period, pStart);
|
||||
const periodRewards = memberRewards.filter((r: any) => r.date >= pStart && r.date <= pEnd);
|
||||
if (periodRewards.length > 0) {
|
||||
throw new Error(
|
||||
`Already issued ${periodRewards.length}x this ${cfg.period} to ${m.name}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const created: any[] = [];
|
||||
for (const m of targetMembers) {
|
||||
const label =
|
||||
cfg.rewardType === 'cash'
|
||||
? `${cfg.name} – £${Number(cfg.rewardValue).toFixed(2)}`
|
||||
: `${cfg.name} – ${cfg.rewardValue}`;
|
||||
const now = new Date().toISOString();
|
||||
const record = await pb.collection('rewards').create({
|
||||
famId,
|
||||
memberId: m.id,
|
||||
bonusConfigId: cfg.id,
|
||||
label,
|
||||
value: Number(cfg.rewardValue) || 0,
|
||||
rewardType: cfg.rewardType,
|
||||
status: cfg.rewardType === 'points' ? 'claimed' : 'unclaimed',
|
||||
claimedAt: cfg.rewardType === 'points' ? now : null,
|
||||
date: now.slice(0, 10),
|
||||
claimable: 'immediate',
|
||||
settleDate: ''
|
||||
});
|
||||
created.push(record);
|
||||
}
|
||||
|
||||
if (cfg.occurrence === 'once') {
|
||||
await pb.collection('bonus_configs').update(cfg.id, { status: 'completed' });
|
||||
}
|
||||
|
||||
return { triggered: true, created: created.length, records: created };
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
export type ChatActor = {
|
||||
id: string;
|
||||
type: 'admin' | 'member';
|
||||
name: string;
|
||||
color: string;
|
||||
};
|
||||
|
||||
export async function chatMe(pb: any, famId: string, actor: ChatActor) {
|
||||
return { famId, actor };
|
||||
}
|
||||
|
||||
export async function send(
|
||||
pb: any,
|
||||
famId: string,
|
||||
actor: ChatActor,
|
||||
body: { content?: string; clientId?: string }
|
||||
) {
|
||||
const content = (body.content || '').trim();
|
||||
if (!content) throw new Error('content required');
|
||||
return pb.collection('messages').create({
|
||||
famId,
|
||||
authorType: actor.type,
|
||||
authorId: actor.id,
|
||||
authorName: actor.name,
|
||||
authorColor: actor.color,
|
||||
content,
|
||||
createdAt: new Date().toISOString(),
|
||||
clientId: body.clientId ? String(body.clientId).slice(0, 64) : ''
|
||||
});
|
||||
}
|
||||
|
||||
export async function typing(
|
||||
pb: any,
|
||||
famId: string,
|
||||
actor: ChatActor,
|
||||
body: { typing?: boolean }
|
||||
) {
|
||||
const existing = await pb.collection('chat_typing').getFullList({
|
||||
filter: `famId = '${famId}' && actorId = '${actor.id}' && actorType = '${actor.type}'`
|
||||
});
|
||||
const row = {
|
||||
famId,
|
||||
actorId: actor.id,
|
||||
actorType: actor.type,
|
||||
authorName: actor.name,
|
||||
authorColor: actor.color,
|
||||
typing: !!body.typing
|
||||
};
|
||||
if (existing?.length) {
|
||||
await pb.collection('chat_typing').update(existing[0].id, row);
|
||||
} else {
|
||||
await pb.collection('chat_typing').create(row);
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { famMeta } from './fam';
|
||||
|
||||
// Aggregated kanban payload for a single member (child session).
|
||||
export async function myChores(pb: any, famId: string, memberId: string) {
|
||||
const [templates, assigned, completions, rewards, bonusConfigs] = await Promise.all([
|
||||
pb.collection('chore_templates').getFullList({ filter: `famId = '${famId}'` }),
|
||||
pb.collection('assigned_chores').getFullList({ filter: `famId = '${famId}' && memberId = '${memberId}'` }),
|
||||
pb.collection('completions').getFullList({ filter: `famId = '${famId}' && memberId = '${memberId}'` }),
|
||||
pb.collection('rewards').getFullList({ filter: `famId = '${famId}' && memberId = '${memberId}'` }),
|
||||
pb.collection('bonus_configs').getFullList({ filter: `famId = '${famId}' && status = 'active'` })
|
||||
]);
|
||||
const { payday, paydayTime, tz } = await famMeta(pb, famId);
|
||||
let settings: any = {};
|
||||
try {
|
||||
const s = await pb
|
||||
.collection('settings')
|
||||
.getFullList({ filter: `famId = '${famId}'` });
|
||||
settings = s?.[0] || {};
|
||||
} catch {}
|
||||
return {
|
||||
templates,
|
||||
assigned,
|
||||
completions,
|
||||
rewards,
|
||||
bonusConfigs,
|
||||
payday,
|
||||
paydayTime,
|
||||
timezone: tz,
|
||||
simulateEow: !!settings.simulateEow
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { periodWindow } from '@shared/timezone';
|
||||
import { famMeta } from './fam';
|
||||
import { evaluateFam } from './bonuses';
|
||||
|
||||
export async function myChores(pb: any, famId: string, memberId: string) {
|
||||
const [templates, assigned, completions, rewards, bonusConfigs] = await Promise.all([
|
||||
pb.collection('chore_templates').getFullList({ filter: `famId = '${famId}'` }),
|
||||
pb.collection('assigned_chores').getFullList({ filter: `famId = '${famId}' && memberId = '${memberId}'` }),
|
||||
pb.collection('completions').getFullList({ filter: `famId = '${famId}' && memberId = '${memberId}'` }),
|
||||
pb.collection('rewards').getFullList({ filter: `famId = '${famId}' && memberId = '${memberId}'` }),
|
||||
pb.collection('bonus_configs').getFullList({ filter: `famId = '${famId}' && status = 'active'` })
|
||||
]);
|
||||
const { payday, paydayTime, tz } = await famMeta(pb, famId);
|
||||
let settings: any = {};
|
||||
try {
|
||||
const s = await pb
|
||||
.collection('settings')
|
||||
.getFullList({ filter: `famId = '${famId}'` });
|
||||
settings = s?.[0] || {};
|
||||
} catch {}
|
||||
return {
|
||||
templates,
|
||||
assigned,
|
||||
completions,
|
||||
rewards,
|
||||
bonusConfigs,
|
||||
payday,
|
||||
paydayTime,
|
||||
timezone: tz,
|
||||
simulateEow: !!settings.simulateEow
|
||||
};
|
||||
}
|
||||
|
||||
export async function toggle(pb: any, famId: string, memberId: string, body: { assignedChoreId: string; date: string }) {
|
||||
const { assignedChoreId, date } = body;
|
||||
if (!assignedChoreId || !date) throw new Error('assignedChoreId and date required');
|
||||
|
||||
const choreList = await pb
|
||||
.collection('assigned_chores')
|
||||
.getFullList({ filter: `famId = '${famId}' && id = '${assignedChoreId}'` });
|
||||
const chore = choreList?.[0];
|
||||
const isTodo = chore?.isTodo;
|
||||
let filter: string;
|
||||
if (isTodo) {
|
||||
filter = `assignedChoreId = '${assignedChoreId}' && memberId = '${memberId}'`;
|
||||
} else {
|
||||
const { payday, tz } = await famMeta(pb, famId);
|
||||
const { from, to } = periodWindow(chore?.frequency, payday, tz);
|
||||
filter = `assignedChoreId = '${assignedChoreId}' && memberId = '${memberId}' && date >= '${from}' && date < '${to}'`;
|
||||
}
|
||||
const existing = await pb
|
||||
.collection('completions')
|
||||
.getFullList({ filter });
|
||||
if (existing?.length > 0) {
|
||||
await pb.collection('completions').delete(existing[0].id);
|
||||
evaluateFam(pb, famId).catch(() => {});
|
||||
return { completed: false };
|
||||
}
|
||||
const record = await pb.collection('completions').create({
|
||||
famId,
|
||||
memberId,
|
||||
assignedChoreId,
|
||||
date,
|
||||
completedAt: new Date().toISOString()
|
||||
});
|
||||
evaluateFam(pb, famId).catch(() => {});
|
||||
return { completed: true, record };
|
||||
}
|
||||
|
||||
export async function revoke(pb: any, famId: string, completionId: string) {
|
||||
const completions = await pb
|
||||
.collection('completions')
|
||||
.getFullList({ filter: `famId = '${famId}' && id = '${completionId}'` });
|
||||
if (!completions?.length) throw new Error('Completion not found');
|
||||
await pb.collection('completions').delete(completionId);
|
||||
evaluateFam(pb, famId).catch(() => {});
|
||||
return { revoked: true };
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Generic per-resource CRUD, mirroring the old proxy's /api/admin/:famId/<resource>.
|
||||
// Kept generic because many pages (chore templates, bonus templates, members,
|
||||
// assigned-chores, seasons) only need plain list/create/update/delete.
|
||||
|
||||
const RESOURCES: Record<
|
||||
string,
|
||||
{ col: string; listFilter: (famId: string) => string; bonus?: 'config' | 'template' }
|
||||
> = {
|
||||
'chore-templates': { col: 'chore_templates', listFilter: (f) => `famId = '${f}'` },
|
||||
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-configs': { col: 'bonus_configs', listFilter: (f) => `famId = '${f}'`, bonus: 'config' },
|
||||
completions: { col: 'completions', listFilter: (f) => `famId = '${f}'` },
|
||||
rewards: { col: 'rewards', listFilter: (f) => `famId = '${f}'` },
|
||||
seasons: { col: 'seasons', listFilter: (f) => `famId = '${f}'` }
|
||||
};
|
||||
|
||||
function res(resource: string) {
|
||||
const r = RESOURCES[resource];
|
||||
if (!r) throw new Error(`Unknown resource: ${resource}`);
|
||||
return r;
|
||||
}
|
||||
|
||||
function bonusBody(c: { bonus?: 'config' | 'template' }, data: Record<string, unknown>) {
|
||||
const body: Record<string, unknown> = { ...data };
|
||||
if (body.occurrence === 'once') body.period = '';
|
||||
if (c.bonus === 'config') body.status = 'active';
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function list(pb: any, resource: string, famId: string) {
|
||||
const c = res(resource);
|
||||
return pb.collection(c.col).getFullList({ filter: c.listFilter(famId) });
|
||||
}
|
||||
|
||||
export async function create(
|
||||
pb: any,
|
||||
resource: string,
|
||||
famId: string,
|
||||
data: Record<string, unknown>
|
||||
) {
|
||||
const c = res(resource);
|
||||
return pb.collection(c.col).create({ famId, ...bonusBody(c, data) });
|
||||
}
|
||||
|
||||
export async function update(
|
||||
pb: any,
|
||||
resource: string,
|
||||
famId: string,
|
||||
id: string,
|
||||
data: Record<string, unknown>
|
||||
) {
|
||||
const c = res(resource);
|
||||
return pb.collection(c.col).update(id, bonusBody(c, data));
|
||||
}
|
||||
|
||||
export async function remove(pb: any, resource: string, famId: string, id: string) {
|
||||
const c = res(resource);
|
||||
return pb.collection(c.col).delete(id);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Dev/test helper (settings debugMode) — random completions for a range of days.
|
||||
|
||||
export async function generateData(pb: any, famId: string, days = 7) {
|
||||
const [members, templates] = await Promise.all([
|
||||
pb.collection('users').getFullList({ filter: `famId = '${famId}' && role = 'child'` }),
|
||||
pb.collection('chore_templates').getFullList({ filter: `famId = '${famId}'` })
|
||||
]);
|
||||
|
||||
if (!members.length) return { error: 'No members found' };
|
||||
if (!templates.length) return { error: 'No templates found' };
|
||||
|
||||
let completionsCreated = 0;
|
||||
const today = new Date();
|
||||
|
||||
for (let d = 0; d < days; d++) {
|
||||
const date = new Date(today);
|
||||
date.setDate(date.getDate() - d);
|
||||
const dateStr = date.toISOString().slice(0, 10);
|
||||
|
||||
for (const m of members) {
|
||||
const completionRate = 0.5 + Math.random() * 0.5;
|
||||
for (const t of templates) {
|
||||
if (Math.random() > completionRate) continue;
|
||||
|
||||
let assigned = await pb.collection('assigned_chores').getFullList({
|
||||
filter: `famId = '${famId}' && memberId = '${m.id}' && templateId = '${t.id}'`
|
||||
});
|
||||
let assignedId;
|
||||
if (assigned?.length > 0) {
|
||||
assignedId = assigned[0].id;
|
||||
} else {
|
||||
const record = await pb.collection('assigned_chores').create({
|
||||
famId,
|
||||
memberId: m.id,
|
||||
templateId: t.id,
|
||||
frequency: t.defaultFrequency || 'daily',
|
||||
type: t.defaultType || 'points',
|
||||
value: t.defaultValue || 10
|
||||
});
|
||||
assignedId = record.id;
|
||||
}
|
||||
|
||||
const existing = await pb.collection('completions').getFullList({
|
||||
filter: `famId = '${famId}' && memberId = '${m.id}' && assignedChoreId = '${assignedId}' && date = '${dateStr}'`
|
||||
});
|
||||
if (existing?.length > 0) continue;
|
||||
|
||||
await pb.collection('completions').create({
|
||||
famId,
|
||||
memberId: m.id,
|
||||
assignedChoreId: assignedId,
|
||||
date: dateStr
|
||||
});
|
||||
completionsCreated++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { completionsCreated, days };
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
import {
|
||||
weekStart,
|
||||
addDaysStr,
|
||||
resolveTz,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
wallClockToUtc
|
||||
} from '@shared/timezone';
|
||||
import { slugify } from '@shared/slugify';
|
||||
import { evaluateFam } from './bonuses';
|
||||
|
||||
function resolveServerTz(tz?: string): string {
|
||||
return resolveTz(tz || 'auto');
|
||||
}
|
||||
|
||||
export async function famMeta(pb: any, famId: string) {
|
||||
const fam = await pb.collection('fams').getOne(famId);
|
||||
return {
|
||||
payday: fam.payday !== undefined && fam.payday !== null ? Number(fam.payday) : 1,
|
||||
paydayTime: fam.paydayTime || '18:00',
|
||||
tz: resolveServerTz(fam.timezone)
|
||||
};
|
||||
}
|
||||
|
||||
export async function getFam(pb: any, famId: string) {
|
||||
const fam = await pb.collection('fams').getOne(famId);
|
||||
return {
|
||||
name: fam.name,
|
||||
slug: fam.slug,
|
||||
payday: fam.payday,
|
||||
paydayTime: fam.paydayTime || '18:00',
|
||||
timezone: fam.timezone || 'auto'
|
||||
};
|
||||
}
|
||||
|
||||
export async function patchFam(pb: any, famId: string, body: Record<string, unknown>) {
|
||||
if (body.name !== undefined) {
|
||||
const name = body.name as string;
|
||||
if (!name) throw new Error('name required');
|
||||
const slug = slugify(name);
|
||||
const record = await pb.collection('fams').update(famId, { name, slug });
|
||||
return { name: record.name, slug: record.slug, payday: record.payday };
|
||||
}
|
||||
if (body.payday !== undefined || body.paydayTime !== undefined || body.timezone !== undefined) {
|
||||
const patch: Record<string, string | number> = {};
|
||||
if (body.payday !== undefined) {
|
||||
const payday = Number(body.payday);
|
||||
if (payday < 0 || payday > 6 || !Number.isInteger(payday))
|
||||
throw new Error('payday must be 0-6');
|
||||
patch.payday = payday;
|
||||
}
|
||||
if (body.paydayTime !== undefined) {
|
||||
const paydayTime = String(body.paydayTime);
|
||||
if (!/^\d{2}:\d{2}$/.test(paydayTime)) throw new Error('paydayTime must be HH:MM');
|
||||
patch.paydayTime = paydayTime;
|
||||
}
|
||||
if (body.timezone !== undefined) {
|
||||
const timezone = String(body.timezone);
|
||||
if (timezone !== 'auto' && !/^[A-Za-z_+-]+\/[A-Za-z_+-]+$/.test(timezone))
|
||||
throw new Error("timezone must be an IANA name or 'auto'");
|
||||
patch.timezone = timezone;
|
||||
}
|
||||
const record = await pb.collection('fams').update(famId, patch);
|
||||
return { payday: record.payday, paydayTime: record.paydayTime, timezone: record.timezone };
|
||||
}
|
||||
throw new Error('no valid fields');
|
||||
}
|
||||
|
||||
export async function getProfile(pb: any, famId: string, userId: string) {
|
||||
const rec = await pb.collection('users').getOne(userId);
|
||||
return { id: rec.id, name: rec.name || '', color: rec.color || '#6366f1', email: rec.email || '' };
|
||||
}
|
||||
|
||||
export async function updateProfile(
|
||||
pb: any,
|
||||
famId: string,
|
||||
userId: string,
|
||||
data: Record<string, unknown>
|
||||
) {
|
||||
const patch: Record<string, unknown> = {};
|
||||
if (data.name) patch.name = data.name;
|
||||
if (data.color) patch.color = data.color;
|
||||
if (data.email !== undefined) patch.email = data.email;
|
||||
const rec = await pb.collection('users').update(userId, patch);
|
||||
return { id: rec.id, name: rec.name || '', color: rec.color || '#6366f1', email: rec.email || '' };
|
||||
}
|
||||
|
||||
export async function weeklySummary(pb: any, famId: string) {
|
||||
const { payday, tz } = await famMeta(pb, famId);
|
||||
const ws = weekStart(payday, tz);
|
||||
const [members, assigned, completions] = await Promise.all([
|
||||
pb.collection('users').getFullList({ filter: `famId = '${famId}' && role = 'child'` }),
|
||||
pb.collection('assigned_chores').getFullList({ filter: `famId = '${famId}'` }),
|
||||
pb.collection('completions').getFullList({ filter: `famId = '${famId}' && date >= '${ws}'` })
|
||||
]);
|
||||
|
||||
let rewardPointsList: any[] = [];
|
||||
try {
|
||||
rewardPointsList = await pb.collection('rewards').getFullList({
|
||||
filter: `famId = '${famId}' && rewardType = 'points' && status = 'claimed' && date >= '${ws}'`
|
||||
});
|
||||
} catch {}
|
||||
|
||||
const assignedList = assigned;
|
||||
const completionsList = completions;
|
||||
|
||||
const daysInWeek: string[] = [];
|
||||
{
|
||||
const d = new Date(ws + 'T00:00:00Z');
|
||||
for (let i = 0; i < 7; i++) {
|
||||
daysInWeek.push(d.toISOString().slice(0, 10));
|
||||
d.setDate(d.getDate() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const summaries = await Promise.all(
|
||||
members.map(async (m: any) => {
|
||||
const memberAssignments = assignedList.filter((a: any) => a.memberId === m.id);
|
||||
const memberCompletions = completionsList.filter((c: any) => c.memberId === m.id);
|
||||
|
||||
const weekPoints = memberCompletions.reduce((sum: number, c: any) => {
|
||||
const chore = assignedList.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (chore?.type === 'points' ? Number(chore.value) : 0);
|
||||
}, 0);
|
||||
|
||||
const dayPoints: Record<string, number> = {};
|
||||
const dayCompletions: Record<string, number> = {};
|
||||
for (const day of daysInWeek) {
|
||||
dayPoints[day] = 0;
|
||||
dayCompletions[day] = 0;
|
||||
}
|
||||
for (const c of memberCompletions) {
|
||||
const day = (c.date || '').slice(0, 10);
|
||||
if (dayPoints[day] !== undefined) {
|
||||
const chore = assignedList.find((a: any) => a.id === c.assignedChoreId);
|
||||
dayPoints[day] += chore?.type === 'points' ? Number(chore.value) : 0;
|
||||
dayCompletions[day]++;
|
||||
}
|
||||
}
|
||||
|
||||
const bonusPoints = rewardPointsList
|
||||
.filter((r: any) => r.memberId === m.id)
|
||||
.reduce((sum: number, r: any) => sum + Number(r.value), 0);
|
||||
|
||||
const weekMoney = memberCompletions.reduce((sum: number, c: any) => {
|
||||
const chore = assignedList.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (chore?.type === 'money' ? Number(chore.value) : 0);
|
||||
}, 0);
|
||||
|
||||
let bonusMoney = 0;
|
||||
try {
|
||||
const cashRewards = await pb.collection('rewards').getFullList({
|
||||
filter: `famId = '${famId}' && memberId = '${m.id}' && rewardType = 'cash' && status = 'claimed' && date >= '${ws}'`
|
||||
});
|
||||
bonusMoney = cashRewards.reduce((sum: number, r: any) => sum + Number(r.value), 0);
|
||||
} catch {}
|
||||
|
||||
return {
|
||||
memberId: m.id,
|
||||
memberName: m.name,
|
||||
memberColor: m.color,
|
||||
pointsEarned: weekPoints + bonusPoints,
|
||||
moneyEarned: weekMoney + bonusMoney,
|
||||
choresCompleted: memberCompletions.length,
|
||||
totalChores: memberAssignments.length,
|
||||
dayPoints,
|
||||
dayCompletions
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return { weekStart: ws, daysInWeek, summaries };
|
||||
}
|
||||
|
||||
export async function eowPreview(pb: any, famId: string) {
|
||||
const { payday, tz } = await famMeta(pb, famId);
|
||||
const ws = weekStart(payday, tz);
|
||||
const we = periodEnd('weekly', ws);
|
||||
|
||||
const [members, assigned, completions, configs, rewards] = await Promise.all([
|
||||
pb.collection('users').getFullList({ filter: `famId = '${famId}' && role = 'child'` }),
|
||||
pb.collection('assigned_chores').getFullList({ filter: `famId = '${famId}'` }),
|
||||
pb.collection('completions').getFullList({ filter: `famId = '${famId}' && date >= '${ws}'` }),
|
||||
pb
|
||||
.collection('bonus_configs')
|
||||
.getFullList({ filter: `famId = '${famId}' && status = 'active'` })
|
||||
.catch(() => []),
|
||||
pb.collection('rewards').getFullList({ filter: `famId = '${famId}'` }).catch(() => [])
|
||||
]);
|
||||
|
||||
let rewardPointsList: any[] = [];
|
||||
let rewardCashList: any[] = [];
|
||||
try {
|
||||
[rewardPointsList, rewardCashList] = await Promise.all([
|
||||
pb.collection('rewards').getFullList({
|
||||
filter: `famId = '${famId}' && rewardType = 'points' && status = 'claimed' && date >= '${ws}'`
|
||||
}),
|
||||
pb.collection('rewards').getFullList({
|
||||
filter: `famId = '${famId}' && rewardType = 'cash' && status = 'claimed' && date >= '${ws}'`
|
||||
})
|
||||
]);
|
||||
} catch {}
|
||||
|
||||
const assignedList = assigned;
|
||||
const completionsList = completions;
|
||||
|
||||
const summaries = members.map((m: any) => {
|
||||
const mc = completionsList.filter((c: any) => c.memberId === m.id);
|
||||
const weekPoints = mc.reduce((sum: number, c: any) => {
|
||||
const ch = assignedList.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (ch?.type === 'points' ? Number(ch.value) : 0);
|
||||
}, 0);
|
||||
const weekMoney = mc.reduce((sum: number, c: any) => {
|
||||
const ch = assignedList.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (ch?.type === 'money' ? Number(ch.value) : 0);
|
||||
}, 0);
|
||||
const bonusPoints = rewardPointsList
|
||||
.filter((r: any) => r.memberId === m.id)
|
||||
.reduce((sum: number, r: any) => sum + Number(r.value), 0);
|
||||
const bonusMoney = rewardCashList
|
||||
.filter((r: any) => r.memberId === m.id)
|
||||
.reduce((sum: number, r: any) => sum + Number(r.value), 0);
|
||||
return {
|
||||
memberId: m.id,
|
||||
memberName: m.name || m.username || m.id.slice(0, 6),
|
||||
memberColor: m.color,
|
||||
pointsEarned: weekPoints + bonusPoints,
|
||||
moneyEarned: weekMoney + bonusMoney,
|
||||
choresCompleted: mc.length,
|
||||
bonusEarned: bonusPoints
|
||||
};
|
||||
});
|
||||
|
||||
const predictedRewards: any[] = [];
|
||||
const existingRewards = rewards;
|
||||
for (const cfg of configs) {
|
||||
if (cfg.type === 'manual') continue;
|
||||
const pStart = cfg.period ? periodStart(cfg.period, payday, tz) : '';
|
||||
const pEnd = cfg.period ? periodEnd(cfg.period, pStart) : '';
|
||||
const periodCompletions = cfg.period
|
||||
? completionsList.filter(
|
||||
(c: any) => (c.date || '').slice(0, 10) >= pStart && (c.date || '').slice(0, 10) <= pEnd
|
||||
)
|
||||
: completionsList;
|
||||
const cfgRewards = existingRewards.filter((r: any) => r.bonusConfigId === cfg.id);
|
||||
|
||||
const tryEval = (sourceComps: any[]) => {
|
||||
if (cfg.type === 'threshold')
|
||||
return sourceComps.reduce((sum: number, c: any) => {
|
||||
const ch = assignedList.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (ch?.type === 'points' ? Number(ch.value) : 0);
|
||||
}, 0);
|
||||
if (cfg.type === 'count') return sourceComps.length;
|
||||
return 0;
|
||||
};
|
||||
|
||||
if (cfg.target === 'individual') {
|
||||
const targets = cfg.memberId ? members.filter((m: any) => m.id === cfg.memberId) : members;
|
||||
for (const m of targets) {
|
||||
if (cfgRewards.some((r: any) => r.memberId === m.id)) continue;
|
||||
const current = tryEval(periodCompletions.filter((c: any) => c.memberId === m.id));
|
||||
if (cfg.criteriaValue > 0 && current >= Number(cfg.criteriaValue))
|
||||
predictedRewards.push({
|
||||
config: cfg.name,
|
||||
memberName: m.name || m.id.slice(0, 6),
|
||||
type: cfg.rewardType,
|
||||
value: Number(cfg.rewardValue) || 0,
|
||||
detail: `${cfg.type} ${current}/${cfg.criteriaValue}`
|
||||
});
|
||||
}
|
||||
} else if (cfg.target === 'collaborative') {
|
||||
if (cfgRewards.length) continue;
|
||||
const allIds = members.map((m: any) => m.id);
|
||||
const teamComps = periodCompletions.filter((c: any) => allIds.includes(c.memberId));
|
||||
const current = tryEval(teamComps);
|
||||
if (cfg.criteriaValue > 0 && current >= Number(cfg.criteriaValue))
|
||||
predictedRewards.push({
|
||||
config: cfg.name,
|
||||
memberName: 'Everyone',
|
||||
type: cfg.rewardType,
|
||||
value: Number(cfg.rewardValue) || 0,
|
||||
detail: `${cfg.type} ${current}/${cfg.criteriaValue}`
|
||||
});
|
||||
} else if (cfg.target === 'competitive') {
|
||||
if (cfgRewards.length) continue;
|
||||
const scored = members.map((m: any) => ({
|
||||
memberId: m.id,
|
||||
name: m.name,
|
||||
current: tryEval(periodCompletions.filter((c: any) => c.memberId === m.id))
|
||||
}));
|
||||
const qualified = scored.filter((st: any) => st.current >= Number(cfg.criteriaValue));
|
||||
const eligible = qualified.length ? qualified : scored.filter((st: any) => st.current > 0);
|
||||
const winner = eligible.sort((aa: any, bb: any) => bb.current - aa.current)[0];
|
||||
if (winner)
|
||||
predictedRewards.push({
|
||||
config: cfg.name,
|
||||
memberName: winner.name,
|
||||
type: cfg.rewardType,
|
||||
value: Number(cfg.rewardValue) || 0,
|
||||
detail: `winner ${winner.current} pts`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const nextWeekStart = addDaysStr(ws, 7);
|
||||
|
||||
return {
|
||||
simulateEow: true,
|
||||
weekStart: ws,
|
||||
weekEnd: we,
|
||||
nextWeekStart,
|
||||
summaries,
|
||||
predictedRewards,
|
||||
completionsThisWeek: completionsList.length
|
||||
};
|
||||
}
|
||||
|
||||
export async function releaseWeek(pb: any, famId: string) {
|
||||
const { payday, paydayTime, tz } = await famMeta(pb, famId);
|
||||
const fams = await pb.collection('fams').getFullList({ filter: `id = '${famId}'` });
|
||||
const fam = fams?.[0];
|
||||
if (!fam) throw new Error('Fam not found');
|
||||
|
||||
const wsToday = weekStart(payday, tz);
|
||||
const target = new Date(wallClockToUtc(wsToday, paydayTime || '18:00', tz));
|
||||
if (Date.now() < target.getTime()) {
|
||||
return {
|
||||
settled: false,
|
||||
notYet: true,
|
||||
weekStart: wsToday,
|
||||
target: target.toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
if (fam.lastIssued === wsToday) return { settled: false, weekStart: wsToday };
|
||||
|
||||
const members = await pb
|
||||
.collection('users')
|
||||
.getFullList({ filter: `famId = '${famId}' && role = 'child'` });
|
||||
let cashRewards: any[] = [];
|
||||
try {
|
||||
cashRewards = await pb.collection('rewards').getFullList({
|
||||
filter: `famId = '${famId}' && rewardType = 'cash' && (status = 'unclaimed' || status = 'requested')`
|
||||
});
|
||||
} catch {}
|
||||
|
||||
const breakdown: any[] = [];
|
||||
const now = new Date().toISOString();
|
||||
const today = now.slice(0, 10);
|
||||
|
||||
for (const m of members) {
|
||||
const unpaid = cashRewards.filter((r: any) => r.memberId === m.id && r.status !== 'claimed');
|
||||
const total = unpaid.reduce((sum: number, r: any) => sum + Number(r.value), 0);
|
||||
if (total > 0) {
|
||||
for (const r of unpaid) {
|
||||
if (r.status !== 'requested') {
|
||||
await pb.collection('rewards').update(r.id, {
|
||||
status: 'requested',
|
||||
claimedAt: null,
|
||||
date: (r.date || '').slice(0, 10) || today
|
||||
});
|
||||
}
|
||||
}
|
||||
breakdown.push({
|
||||
memberId: m.id,
|
||||
name: m.name,
|
||||
total,
|
||||
rewards: unpaid.map((r: any) => ({ id: r.id, label: r.label, value: Number(r.value) }))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await pb.collection('fams').update(famId, { lastIssued: wsToday });
|
||||
return { settled: true, weekStart: wsToday, breakdown };
|
||||
}
|
||||
|
||||
export async function completeWeek(pb: any, famId: string) {
|
||||
const { payday, tz } = await famMeta(pb, famId);
|
||||
const ws = weekStart(payday, tz);
|
||||
|
||||
await evaluateFam(pb, famId);
|
||||
|
||||
const [members, assigned, completions] = await Promise.all([
|
||||
pb.collection('users').getFullList({ filter: `famId = '${famId}' && role = 'child'` }),
|
||||
pb.collection('assigned_chores').getFullList({ filter: `famId = '${famId}'` }),
|
||||
pb.collection('completions').getFullList({ filter: `famId = '${famId}' && date >= '${ws}'` })
|
||||
]);
|
||||
|
||||
let rewardPointsList: any[] = [];
|
||||
let rewardCashList: any[] = [];
|
||||
try {
|
||||
[rewardPointsList, rewardCashList] = await Promise.all([
|
||||
pb.collection('rewards').getFullList({
|
||||
filter: `famId = '${famId}' && rewardType = 'points' && status = 'claimed' && date >= '${ws}'`
|
||||
}),
|
||||
pb.collection('rewards').getFullList({
|
||||
filter: `famId = '${famId}' && rewardType = 'cash' && status = 'claimed' && date >= '${ws}'`
|
||||
})
|
||||
]);
|
||||
} catch {}
|
||||
|
||||
const assignedList = assigned;
|
||||
const historyRecords: any[] = [];
|
||||
|
||||
for (const m of members) {
|
||||
const memberCompletions = completions.filter((c: any) => c.memberId === m.id);
|
||||
|
||||
const weekPoints = memberCompletions.reduce((sum: number, c: any) => {
|
||||
const chore = assignedList.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (chore?.type === 'points' ? Number(chore.value) : 0);
|
||||
}, 0);
|
||||
|
||||
const weekMoney = memberCompletions.reduce((sum: number, c: any) => {
|
||||
const chore = assignedList.find((a: any) => a.id === c.assignedChoreId);
|
||||
return sum + (chore?.type === 'money' ? Number(chore.value) : 0);
|
||||
}, 0);
|
||||
|
||||
const bonusPoints = rewardPointsList
|
||||
.filter((r: any) => r.memberId === m.id)
|
||||
.reduce((sum: number, r: any) => sum + Number(r.value), 0);
|
||||
|
||||
const bonusMoney = rewardCashList
|
||||
.filter((r: any) => r.memberId === m.id)
|
||||
.reduce((sum: number, r: any) => sum + Number(r.value), 0);
|
||||
|
||||
const existing = await pb
|
||||
.collection('weekly_history')
|
||||
.getFullList({ filter: `famId = '${famId}' && memberId = '${m.id}' && weekStart = '${ws}'` });
|
||||
const recordData = {
|
||||
famId,
|
||||
memberId: m.id,
|
||||
weekStart: ws,
|
||||
pointsEarned: weekPoints + bonusPoints,
|
||||
moneyEarned: weekMoney + bonusMoney,
|
||||
choresCompleted: memberCompletions.length,
|
||||
bonusEarned: bonusPoints
|
||||
};
|
||||
|
||||
if (existing.length > 0) {
|
||||
await pb.collection('weekly_history').update(existing[0].id, recordData);
|
||||
} else {
|
||||
const record = await pb.collection('weekly_history').create(recordData);
|
||||
historyRecords.push(record);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
weekStart: ws,
|
||||
historyRecords,
|
||||
memberCount: members.length
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import * as famSvc from './fam';
|
||||
import * as choresSvc from './chores';
|
||||
import * as completionsSvc from './completions';
|
||||
import * as rewardsSvc from './rewards';
|
||||
import * as bonusesSvc from './bonuses';
|
||||
import * as chatSvc from './chat';
|
||||
import * as settingsSvc from './settings';
|
||||
import * as crudSvc from './crud';
|
||||
import * as debugSvc from './debug';
|
||||
|
||||
export * from './chat';
|
||||
export { famMeta } from './fam';
|
||||
export { assertPaydayUnlocked } from './rewards';
|
||||
|
||||
// Per-feature service binder. `pb` is the acting user's own PocketBase client
|
||||
// (child or parent token), so PB collection rules enforce famId + role scoping;
|
||||
// this layer is purely in-process logic grouped by app area for readability.
|
||||
// `user` supplies the acting user's id/role so member-scoped ops default to it.
|
||||
export function createServices(
|
||||
pb: any,
|
||||
user?: { id?: string; role?: string; name?: string; color?: string }
|
||||
) {
|
||||
const uid = user?.id || '';
|
||||
|
||||
return {
|
||||
fam: {
|
||||
meta: (famId: string) => famSvc.famMeta(pb, famId),
|
||||
get: (famId: string) => famSvc.getFam(pb, famId),
|
||||
update: (famId: string, body: Record<string, unknown>) => famSvc.patchFam(pb, famId, body),
|
||||
rename: (famId: string, name: string) => famSvc.patchFam(pb, famId, { name }),
|
||||
updatePayday: (famId: string, payday: number, paydayTime?: string, timezone?: string) =>
|
||||
famSvc.patchFam(pb, famId, {
|
||||
payday,
|
||||
...(paydayTime !== undefined ? { paydayTime } : {}),
|
||||
...(timezone !== undefined ? { timezone } : {})
|
||||
}),
|
||||
weeklySummary: (famId: string) => famSvc.weeklySummary(pb, famId),
|
||||
eowPreview: (famId: string) => famSvc.eowPreview(pb, famId),
|
||||
payday: (famId: string) => famSvc.releaseWeek(pb, famId),
|
||||
completeWeek: (famId: string) => famSvc.completeWeek(pb, famId),
|
||||
getProfile: (famId: string) => famSvc.getProfile(pb, famId, uid),
|
||||
updateProfile: (famId: string, data: Record<string, unknown>) =>
|
||||
famSvc.updateProfile(pb, famId, uid, data)
|
||||
},
|
||||
crud: {
|
||||
list: (resource: string, famId: string) => crudSvc.list(pb, resource, famId),
|
||||
create: (resource: string, famId: string, data: Record<string, unknown>) =>
|
||||
crudSvc.create(pb, resource, famId, data),
|
||||
update: (resource: string, famId: string, id: string, data: Record<string, unknown>) =>
|
||||
crudSvc.update(pb, resource, famId, id, data),
|
||||
remove: (resource: string, famId: string, id: string) => crudSvc.remove(pb, resource, famId, id)
|
||||
},
|
||||
chores: {
|
||||
myChores: (famId: string) => choresSvc.myChores(pb, famId, uid)
|
||||
},
|
||||
completions: {
|
||||
toggle: (famId: string, body: { assignedChoreId: string; date: string }) =>
|
||||
completionsSvc.toggle(pb, famId, uid, body),
|
||||
revoke: (famId: string, completionId: string) => completionsSvc.revoke(pb, famId, completionId)
|
||||
},
|
||||
rewards: {
|
||||
claim: (famId: string, id: string) => rewardsSvc.claim(pb, famId, id),
|
||||
approve: (famId: string, id: string) => rewardsSvc.approve(pb, famId, id),
|
||||
requestAll: (famId: string) => rewardsSvc.requestAll(pb, famId, uid),
|
||||
issueAll: (famId: string, memberId: string) => rewardsSvc.issueAll(pb, famId, memberId)
|
||||
},
|
||||
bonuses: {
|
||||
progress: (famId: string) => bonusesSvc.progress(pb, famId),
|
||||
evaluate: (famId: string) => bonusesSvc.evaluateAll(pb, famId),
|
||||
trigger: (famId: string, configId: string, memberId?: string) =>
|
||||
bonusesSvc.trigger(pb, famId, configId, memberId),
|
||||
assign: (famId: string, configId: string, data: Record<string, unknown>) => {
|
||||
const updates: Record<string, unknown> = { status: 'active' };
|
||||
if (data.target) updates.target = data.target;
|
||||
if (data.memberId !== undefined) updates.memberId = data.memberId || null;
|
||||
return pb.collection('bonus_configs').update(configId, updates);
|
||||
},
|
||||
complete: (famId: string, configId: string) =>
|
||||
pb.collection('bonus_configs').update(configId, { status: 'completed' }),
|
||||
destroy: (famId: string, configId: string) =>
|
||||
pb.collection('bonus_configs').delete(configId)
|
||||
},
|
||||
settings: {
|
||||
get: (famId: string) => settingsSvc.getSettings(pb, famId),
|
||||
update: (famId: string, data: Record<string, unknown>) =>
|
||||
settingsSvc.updateSettings(pb, famId, data)
|
||||
},
|
||||
chat: {
|
||||
me: (famId: string, actor: chatSvc.ChatActor) => chatSvc.chatMe(pb, famId, actor),
|
||||
send: (famId: string, actor: chatSvc.ChatActor, body: { content?: string; clientId?: string }) =>
|
||||
chatSvc.send(pb, famId, actor, body),
|
||||
typing: (famId: string, actor: chatSvc.ChatActor, body: { typing?: boolean }) =>
|
||||
chatSvc.typing(pb, famId, actor, body)
|
||||
},
|
||||
debug: {
|
||||
generateData: (famId: string, days?: number) => debugSvc.generateData(pb, famId, days)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export type Services = ReturnType<typeof createServices>;
|
||||
@@ -0,0 +1,68 @@
|
||||
import { todayInTz, resolveTz } from '@shared/timezone';
|
||||
import { famMeta } from './fam';
|
||||
|
||||
function resolveServerTz(tz?: string): string {
|
||||
return resolveTz(tz || 'auto');
|
||||
}
|
||||
|
||||
export function assertPaydayUnlocked(reward: any, tz?: string) {
|
||||
if (!reward || reward.claimable !== 'payday' || !reward.settleDate) return;
|
||||
const today = todayInTz(resolveServerTz(tz));
|
||||
if (today < reward.settleDate) {
|
||||
throw new Error(`This bonus pays out on payday (${reward.settleDate}) — hang tight!`);
|
||||
}
|
||||
}
|
||||
|
||||
// Member claim → status 'requested' (pending parent approval).
|
||||
export async function claim(pb: any, famId: string, id: string) {
|
||||
const now = new Date().toISOString();
|
||||
const { tz } = await famMeta(pb, famId);
|
||||
const found = await pb
|
||||
.collection('rewards')
|
||||
.getFullList({ filter: `famId = '${famId}' && id = '${id}'` });
|
||||
const reward = found?.[0];
|
||||
if (!reward) throw new Error('Reward not found');
|
||||
assertPaydayUnlocked(reward, tz);
|
||||
return pb.collection('rewards').update(id, { status: 'requested', requestedAt: now });
|
||||
}
|
||||
|
||||
// Admin approval → status 'claimed'.
|
||||
export async function approve(pb: any, famId: string, id: string) {
|
||||
return pb.collection('rewards').update(id, {
|
||||
status: 'claimed',
|
||||
claimedAt: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
export async function requestAll(pb: any, famId: string, memberId: string) {
|
||||
const now = new Date().toISOString();
|
||||
const { tz } = await famMeta(pb, famId);
|
||||
const rewards = await pb.collection('rewards').getFullList({
|
||||
filter: `famId = '${famId}' && memberId = '${memberId}' && status = 'unclaimed'`
|
||||
});
|
||||
let count = 0;
|
||||
for (const r of rewards) {
|
||||
try {
|
||||
assertPaydayUnlocked(r, tz);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
await pb.collection('rewards').update(r.id, { status: 'requested', requestedAt: now });
|
||||
count++;
|
||||
}
|
||||
return { count };
|
||||
}
|
||||
|
||||
export async function issueAll(pb: any, famId: string, memberId: string) {
|
||||
if (!memberId) throw new Error('memberId required');
|
||||
const now = new Date().toISOString();
|
||||
const rewards = await pb.collection('rewards').getFullList({
|
||||
filter: `famId = '${famId}' && memberId = '${memberId}' && rewardType = 'cash' && (status = 'unclaimed' || status = 'requested')`
|
||||
});
|
||||
let count = 0;
|
||||
for (const r of rewards) {
|
||||
await pb.collection('rewards').update(r.id, { status: 'claimed', claimedAt: now });
|
||||
count++;
|
||||
}
|
||||
return { count };
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { todayInTz, resolveTz } from '@shared/timezone';
|
||||
import { famMeta } from './fam';
|
||||
|
||||
function resolveServerTz(tz?: string): string {
|
||||
return resolveTz(tz || 'auto');
|
||||
}
|
||||
|
||||
export async function getSettings(pb: any, famId: string) {
|
||||
const list = await pb.collection('settings').getFullList({ filter: `famId = '${famId}'` });
|
||||
const s = list?.[0] || {};
|
||||
return { simulateEow: !!s.simulateEow, webhookUrl: s.webhookUrl || '' };
|
||||
}
|
||||
|
||||
export async function updateSettings(pb: any, famId: string, data: Record<string, unknown>) {
|
||||
const list = await pb.collection('settings').getFullList({ filter: `famId = '${famId}'` });
|
||||
const existing = list?.[0];
|
||||
const patch: Record<string, unknown> = {};
|
||||
if (data.simulateEow !== undefined) patch.simulateEow = !!data.simulateEow;
|
||||
if (data.webhookUrl !== undefined) patch.webhookUrl = String(data.webhookUrl);
|
||||
let s;
|
||||
if (existing) {
|
||||
s = Object.keys(patch).length ? await pb.collection('settings').update(existing.id, patch) : existing;
|
||||
} else {
|
||||
s = await pb.collection('settings').create({ famId, ...patch });
|
||||
}
|
||||
return { simulateEow: !!s.simulateEow, webhookUrl: s.webhookUrl || '' };
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { pbUser } from '$lib/server/pocketbase';
|
||||
import { createServices, type Services } from '$lib/server/services';
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
|
||||
// Build the per-feature service binder for a server request, running as the
|
||||
// authenticated user's own PB client (session cookie). Shorthand for the
|
||||
// common `createServices(pbUser(event), event.locals.user)` call used in loads
|
||||
// and form actions.
|
||||
export function servicesFor(event: RequestEvent): Services {
|
||||
return createServices(pbUser(event), event.locals.user || undefined);
|
||||
}
|
||||
@@ -180,7 +180,7 @@ class ChatStore {
|
||||
// ── Writes via SvelteKit server (forwards session/device auth) ──
|
||||
|
||||
private async serverChat(payload: Record<string, unknown>) {
|
||||
const res = await fetch('/chat', {
|
||||
const res = await fetch('/api/chat', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
|
||||
Reference in New Issue
Block a user