Files
crosscode-platform/apps/accounts/backend/src/church/profile.ts
T
joshuaandClaude Opus 5.5 a3e3921b4f packages/auth-client: the product side of signing in through Accounts
Start a sign-in with the return path (state, nonce, PKCE), finish it,
sign-out address, back-channel logout tokens and Accounts' signed
user.* calls. Tested against the real provider. Root lint covers
Accounts' backend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:45:39 +02:00

98 lines
4.2 KiB
TypeScript

/**
* 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<typeof profileInputSchema>;
type Stored = Partial<Omit<Church, 'schema' | 'customerId' | 'links'>> & { updatedAt?: string };
const DEFAULTS = (ctx: Ctx): Omit<Church, 'schema' | 'customerId' | 'links' | 'updatedAt'> => ({
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<Stored> {
return ctx.settings.json<Stored>('church_profile', {});
}
/** Whether `/setup` has given the church its name yet. */
export async function profileSet(ctx: Ctx): Promise<boolean> {
return !!(await storedProfile(ctx)).name;
}
export async function church(ctx: Ctx): Promise<Church> {
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<string, string>) {
super(message);
}
}
/** Saves an admin's changes (merged onto what's there), and tells the linked products. */
export async function updateProfile(ctx: Ctx, input: unknown): Promise<Church> {
const current = await storedProfile(ctx);
const next = { ...DEFAULTS(ctx), ...current, ...(input && typeof input === 'object' ? 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,
signupEnabled: await ctx.settings.bool('signup_enabled', true),
};
}