Files
crosscode-platform/apps/accounts/backend/src/church/profile.ts
T

126 lines
5.6 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);
}
}
/** 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<string, unknown> => !!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<string, unknown>, input: unknown): Record<string, unknown> {
if (!isObject(input)) return { ...base };
const next: Record<string, unknown> = { ...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<Church> {
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),
};
}