/** * The church profile (`crosscode.church/1`), owned by Accounts (docs/ACCOUNTS-1.0-PLAN.md ยง7, * decision 1). Admins edit it; it brands the sign-in pages; `GET /api/church/v1` serves it to the * church's products; a change sends `church.changed` to each linked product. * * Stored as `church_profile` (the editable fields). `customerId` comes from the licence, `links` * from the linked products, so neither can be typed in wrong. */ import { churchObjectSchema, churchSchema, CHURCH_SCHEMA, type Church } from '@crosscode/contracts'; import type { z } from 'zod'; import type { Ctx } from '../context.js'; import { customerId } from '../hub/licence.js'; import { queueCall } from '../links/deliveries.js'; /** Before the Hub has given a customer id (a site not connected yet). */ export const NO_CUSTOMER = '00000000-0000-4000-8000-000000000000'; /** The fields an admin edits: the contract minus what Accounts fills in itself. */ export const profileInputSchema = churchObjectSchema.omit({ schema: true, customerId: true, updatedAt: true, links: true }).partial({ shortName: true, campuses: true, serviceTimes: true, social: true, }); export type ProfileInput = z.input; type Stored = Partial> & { updatedAt?: string }; const DEFAULTS = (ctx: Ctx): Omit => ({ name: 'Our church', shortName: null, timezone: ctx.config.timezone, locale: 'en-ZA', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#1f4e79', accent: '#f2a900' } }, campuses: [], serviceTimes: [], contact: { email: null, phone: null, whatsapp: null, address: null }, social: [], } as never); export async function storedProfile(ctx: Ctx): Promise { return ctx.settings.json('church_profile', {}); } /** Whether `/setup` has given the church its name yet. */ export async function profileSet(ctx: Ctx): Promise { return !!(await storedProfile(ctx)).name; } export async function church(ctx: Ctx): Promise { const stored = await storedProfile(ctx); const links = await ctx.db.productLink.findMany(); const url = (product: string) => links.find((l) => l.product === product)?.url ?? null; const merged = { ...DEFAULTS(ctx), ...stored, schema: CHURCH_SCHEMA, customerId: (await customerId(ctx)) ?? NO_CUSTOMER, updatedAt: stored.updatedAt ?? new Date(0).toISOString(), links: { website: url('website'), events: url('events'), app: url('app'), accounts: ctx.config.publicUrl }, }; const parsed = churchSchema.safeParse(merged); // Never serve something the contract refuses: fall back to the name and defaults. return parsed.success ? parsed.data : churchSchema.parse({ ...DEFAULTS(ctx), name: stored.name || 'Our church', schema: CHURCH_SCHEMA, customerId: merged.customerId, updatedAt: merged.updatedAt, links: merged.links }); } export class ProfileError extends Error { status = 400; code = 'VALIDATION'; constructor(message: string, public fields: Record) { super(message); } } /** The profile changed since the editor loaded it (`church.update` with `ifUpdatedAt`). */ export class ProfileChangedError extends Error { constructor(public updatedAt: string) { super('The church profile was changed by someone else since you opened it.'); } } const isObject = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); /** * The fields given replace what's there; `branding` is merged field by field (1.7.0), so a form * that doesn't know `branding.style` (or sends only the style) never drops the rest. */ export function mergeProfile(base: Record, input: unknown): Record { if (!isObject(input)) return { ...base }; const next: Record = { ...base, ...input }; if (isObject(input.branding)) next.branding = { ...(isObject(base.branding) ? base.branding : {}), ...input.branding }; return next; } /** * Saves changes (merged onto what's there) from an admin here or a product (`church.update`), * and tells the linked products. With `ifUpdatedAt`, refuses if someone saved since. */ export async function updateProfile(ctx: Ctx, input: unknown, opts: { ifUpdatedAt?: string } = {}): Promise { const current = await storedProfile(ctx); if (opts.ifUpdatedAt) { const now = current.updatedAt ?? new Date(0).toISOString(); if (new Date(now).getTime() !== new Date(opts.ifUpdatedAt).getTime()) throw new ProfileChangedError(now); } const next = mergeProfile({ ...DEFAULTS(ctx), ...current }, input); const check = profileInputSchema.safeParse(next); if (!check.success) { const fields = Object.fromEntries(check.error.issues.map((i) => [i.path.join('.'), i.message])); throw new ProfileError('Some details need fixing.', fields); } const updatedAt = ctx.now().toISOString(); await ctx.settings.set('church_profile', JSON.stringify({ ...check.data, updatedAt })); await queueCall(ctx, 'church.changed', () => ({ schema: CHURCH_SCHEMA, type: 'church.changed', occurredAt: updatedAt, updatedAt })); return church(ctx); } /** What the sign-in pages need to look like the church's own (public). */ export async function branding(ctx: Ctx) { const c = await church(ctx); return { name: c.name, shortName: c.shortName, logoUrl: c.branding.logoUrl, colours: c.branding.colours, style: { fontPairing: c.branding.style?.fontPairing ?? null, corners: c.branding.style?.corners ?? null }, signupEnabled: await ctx.settings.bool('signup_enabled', true), }; }