feat(website): the admin, with drafts, preview, publish and restore

Admin API and screens: dashboard and setup checklist, template and
style, pages and blocks, ministries, leadership, media library with
the storage limit, publish and history. Pending changes with who and
when, discard one, one Publish, restore any version (each version
keeps the working copy's rows, never sent to visitors). Preview on
the site's own addresses with a bar (widths, back, publish); shared
preview links for 7 days or until revoked. Roles checked, same-origin
changes only. Publish refreshes the public pages at once
(WEBSITE_CONTENT_CACHE_SECONDS). E2E on a production build: the
admin's flows and axe on every screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 12:30:29 +02:00
co-authored by Claude Opus 5.5
parent 3caa1d1e1a
commit 84c5b0c08e
44 changed files with 2404 additions and 65 deletions
+267
View File
@@ -0,0 +1,267 @@
/**
* Editing the working copy (WEBSITE-1.0-PLAN §4, §10): the site's design (template, section
* variants, homepage order, style), pages and their sections or blocks, ministries and leaders.
* Every change is a draft until Publish; each row records who changed it last (`updatedBy`).
*
* Shared facts (name, logo, colours, service times, contact) aren't here: they're the church
* profile's, saved through Accounts (§2), and go live at once.
*/
import { z } from 'zod';
import { websiteTemplateSchema } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { BLOCK_SCHEMAS, isBlockType, SECTION_SCHEMAS } from '../site/sections.js';
import { cleanDesign } from '../site/snapshot.js';
import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js';
type Who = { id: string; role: string };
/** zod issues as `{ field: message }`, for the form. */
function fieldsOf(e: z.ZodError): Record<string, string> {
const out: Record<string, string> = {};
for (const i of e.issues) out[i.path.join('.') || '_'] ??= i.message;
return out;
}
function check<T>(schema: z.ZodType<T>, body: unknown): T {
const r = schema.safeParse(body);
if (!r.success) throw new ApiError(400, 'VALIDATION', 'Some fields need another look.', fieldsOf(r.error));
return r.data;
}
// ─── Design ───────────────────────────────────────────────────────────────────
export async function getDesign(ctx: Ctx) {
return cleanDesign(await ctx.db.siteDesign.findUnique({ where: { id: 1 } }));
}
const designPatch = z.object({
template: websiteTemplateSchema.optional(),
variants: z.record(z.string(), z.string()).optional(),
home: z.array(z.object({ section: sectionTypeSchema, hidden: z.boolean() })).max(SECTION_TYPES.length).optional(),
style: z.object({
sectionColour: z.enum(SECTION_COLOURS).optional(),
spacing: z.enum(SPACINGS).optional(),
buttons: z.enum(BUTTONS).optional(),
images: z.enum(IMAGE_TREATMENTS).optional(),
header: z.string().max(40).optional(),
}).optional(),
});
/**
* Changes the design. A template switch first moves everything still on the old template's
* defaults to the new one's and keeps the church's own choices (§3); the rest of the patch then
* applies. Returns what the switch moved, for the screen.
*/
export async function saveDesign(ctx: Ctx, body: unknown, by: Who) {
const patch = check(designPatch, body);
let design = await getDesign(ctx);
let moved: { what: string; from: string; to: string }[] = [];
if (patch.template && patch.template !== design.template) ({ design, changes: moved } = switchTemplate(design, patch.template));
for (const [section, variant] of Object.entries(patch.variants ?? {})) {
if (!SECTION_TYPES.includes(section as SectionType) || !isVariant(section as SectionType, variant)) throw new ApiError(400, 'VALIDATION', `"${variant}" isn't a layout for ${section}.`);
(design.variants as Record<string, string>)[section] = variant;
}
if (patch.home) {
if (new Set(patch.home.map((e) => e.section)).size !== patch.home.length) throw new ApiError(400, 'VALIDATION', 'Each homepage section can be listed once.');
design.home = [...patch.home, ...design.home.filter((e) => !patch.home!.some((p) => p.section === e.section)).map((e) => ({ ...e, hidden: true }))];
}
if (patch.style) {
const { header, ...rest } = patch.style;
if (header && !(TEMPLATE_HEADERS[design.template] as readonly string[]).includes(header)) throw new ApiError(400, 'VALIDATION', `"${header}" isn't a header for ${design.template}.`);
design.style = { ...design.style, ...rest, ...(header ? { header } : {}) };
}
const data = { template: design.template, variants: design.variants as never, home: design.home as never, style: design.style as never, updatedBy: by.id };
await ctx.db.siteDesign.upsert({ where: { id: 1 }, create: { id: 1, ...data }, update: data });
return { design, moved };
}
// ─── Pages and sections ─────────────────────────────────────────────────────────
const slugSchema = z.string().trim().toLowerCase().regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Lower-case letters, numbers and dashes').max(80);
const RESERVED = new Set(['admin', 'api', 'auth', 'preview', 'events', 'home', 'sitemap.xml', 'robots.txt', 'uploads']);
const pagePatch = z.object({
title: z.string().trim().min(1).max(120).optional(),
slug: slugSchema.optional(),
seoTitle: z.string().trim().max(70).nullable().optional(),
description: z.string().trim().max(300).nullable().optional(),
navLabel: z.string().trim().max(40).nullable().optional(),
inNav: z.boolean().optional(),
position: z.int().min(0).max(1000).optional(),
imageId: z.string().uuid().nullable().optional(),
});
export async function listPages(ctx: Ctx) {
const pages = await ctx.db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }] });
return pages.map((p) => ({ id: p.id, kind: p.kind, slug: p.slug, title: p.title, inNav: p.inNav, position: p.position, path: p.kind === 'home' ? '/' : `/${p.slug}` }));
}
export async function getPage(ctx: Ctx, id: string) {
const page = await ctx.db.page.findUnique({ where: { id } });
if (!page || page.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That page doesn\'t exist.');
const sections = await ctx.db.section.findMany({ where: { pageId: id }, orderBy: { position: 'asc' } });
return { ...page, sections };
}
async function slugFree(ctx: Ctx, slug: string, except?: string) {
if (RESERVED.has(slug)) throw new ApiError(400, 'VALIDATION', `"${slug}" is used by the site itself. Choose another address.`, { slug: 'Used by the site itself' });
const other = await ctx.db.page.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } });
if (other && !other.archivedAt) throw new ApiError(409, 'SLUG_TAKEN', 'Another page already has that address.', { slug: 'Another page has it' });
if (other) await ctx.db.page.update({ where: { id: other.id }, data: { slug: `${other.slug}-${other.id.slice(0, 6)}` } });
}
export async function savePage(ctx: Ctx, id: string, body: unknown, by: Who) {
const page = await getPage(ctx, id);
const patch = check(pagePatch, body);
if (page.kind === 'home') delete patch.slug;
if (patch.slug && patch.slug !== page.slug) await slugFree(ctx, patch.slug, id);
await ctx.db.page.update({ where: { id }, data: { ...patch, updatedBy: by.id } });
return getPage(ctx, id);
}
/** A custom page (§3, "Pages from blocks"), starting with one text block. */
export async function createPage(ctx: Ctx, body: unknown, by: Who) {
const p = check(z.object({ title: z.string().trim().min(1).max(120), slug: slugSchema }), body);
await slugFree(ctx, p.slug);
const last = await ctx.db.page.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
const page = await ctx.db.page.create({ data: { kind: 'custom', slug: p.slug, title: p.title, position: (last?.position ?? 0) + 1, updatedBy: by.id } });
await ctx.db.section.create({ data: { pageId: page.id, type: 'text', position: 0, data: { heading: null, body: '' }, updatedBy: by.id } });
return getPage(ctx, page.id);
}
/** Archive, never delete (§4): restored by Discard or by restoring a version. The home page stays. */
export async function archivePage(ctx: Ctx, id: string, by: Who) {
const page = await getPage(ctx, id);
if (page.kind === 'home') throw new ApiError(400, 'HOME', 'The home page can\'t be removed.');
await ctx.db.page.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
}
function schemaFor(type: string): z.ZodType {
const s = (SECTION_SCHEMAS as Record<string, z.ZodType>)[type] ?? (BLOCK_SCHEMAS as Record<string, z.ZodType>)[type];
if (!s) throw new ApiError(400, 'VALIDATION', `"${type}" isn't a section or block.`);
return s;
}
/**
* The home page's section of `type` (one each; its layout is the design's, §3), created the first
* time it's saved.
*/
export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, body: unknown, by: Who) {
const page = await getPage(ctx, pageId);
if (page.kind !== 'home' || !SECTION_TYPES.includes(type as SectionType)) throw new ApiError(400, 'VALIDATION', 'That isn\'t a homepage section.');
const data = check(schemaFor(type), (body as { data?: unknown })?.data);
const existing = page.sections.find((s) => s.type === type);
if (existing) await ctx.db.section.update({ where: { id: existing.id }, data: { data: data as never, updatedBy: by.id } });
else await ctx.db.section.create({ data: { pageId, type, position: SECTION_TYPES.indexOf(type as SectionType), data: data as never, updatedBy: by.id } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId);
}
const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional() });
/** The blocks of any other page: add, change, move, remove. */
export async function addBlock(ctx: Ctx, pageId: string, body: unknown, by: Who) {
const page = await getPage(ctx, pageId);
if (page.kind === 'home') throw new ApiError(400, 'VALIDATION', 'The home page has its sections; blocks are for the other pages.');
const { type } = check(z.object({ type: z.string() }), body);
if (!isBlockType(type)) throw new ApiError(400, 'VALIDATION', `"${type}" isn't a block.`);
const data = check(schemaFor(type), type === 'quote' ? { quote: 'Your quote here' } : type === 'cta' ? { heading: 'Your heading here' } : {});
await ctx.db.section.create({ data: { pageId, type, position: page.sections.length, data: data as never, updatedBy: by.id } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId);
}
export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, body: unknown, by: Who) {
const page = await getPage(ctx, pageId);
const s = page.sections.find((x) => x.id === sectionId);
if (!s) throw new ApiError(404, 'NOT_FOUND', 'That block doesn\'t exist.');
const patch = check(blockPatch, body);
const data = patch.data === undefined ? undefined : check(schemaFor(s.type), patch.data);
await ctx.db.section.update({ where: { id: sectionId }, data: { ...(data !== undefined ? { data: data as never } : {}), ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), ...(patch.variant !== undefined ? { variant: patch.variant } : {}), updatedBy: by.id } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId);
}
export async function moveBlock(ctx: Ctx, pageId: string, sectionId: string, direction: 'up' | 'down', by: Who) {
const page = await getPage(ctx, pageId);
const list = [...page.sections];
const i = list.findIndex((x) => x.id === sectionId);
const j = direction === 'up' ? i - 1 : i + 1;
if (i < 0 || j < 0 || j >= list.length) return page;
[list[i], list[j]] = [list[j]!, list[i]!];
for (const [n, s] of list.entries()) await ctx.db.section.update({ where: { id: s.id }, data: { position: n, updatedBy: by.id } });
return getPage(ctx, pageId);
}
export async function removeBlock(ctx: Ctx, pageId: string, sectionId: string, by: Who) {
const page = await getPage(ctx, pageId);
if (!page.sections.some((x) => x.id === sectionId)) throw new ApiError(404, 'NOT_FOUND', 'That block doesn\'t exist.');
await ctx.db.section.delete({ where: { id: sectionId } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId);
}
// ─── Ministries and leaders ─────────────────────────────────────────────────────
const ministrySchema = z.object({
name: z.string().trim().min(1).max(120),
slug: slugSchema.optional(),
summary: z.string().trim().max(300).nullable().default(null),
body: z.string().trim().max(8000).nullable().default(null),
imageId: z.string().uuid().nullable().default(null),
position: z.int().min(0).max(1000).optional(),
});
const leaderSchema = z.object({
name: z.string().trim().min(1).max(120),
role: z.string().trim().max(120).nullable().default(null),
bio: z.string().trim().max(4000).nullable().default(null),
photoId: z.string().uuid().nullable().default(null),
position: z.int().min(0).max(1000).optional(),
});
const slugify = (s: string) => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'ministry';
export async function listMinistries(ctx: Ctx) {
return ctx.db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] });
}
export async function saveMinistry(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const m = check(ministrySchema, body);
const slug = m.slug ?? slugify(m.name);
const clash = await ctx.db.ministry.findFirst({ where: { slug, ...(id ? { NOT: { id } } : {}) } });
if (clash) throw new ApiError(409, 'SLUG_TAKEN', 'Another ministry already has that name.', { name: 'Another ministry has it' });
const data = { name: m.name, slug, summary: m.summary, body: m.body, imageId: m.imageId, ...(m.position !== undefined ? { position: m.position } : {}), updatedBy: by.id };
if (id) {
const row = await ctx.db.ministry.findUnique({ where: { id } });
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That ministry doesn\'t exist.');
return ctx.db.ministry.update({ where: { id }, data });
}
const last = await ctx.db.ministry.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
return ctx.db.ministry.create({ data: { ...data, position: m.position ?? (last?.position ?? -1) + 1 } });
}
export async function archiveMinistry(ctx: Ctx, id: string, by: Who) {
await ctx.db.ministry.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
}
export async function listLeaders(ctx: Ctx) {
return ctx.db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] });
}
export async function saveLeader(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const l = check(leaderSchema, body);
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...(l.position !== undefined ? { position: l.position } : {}), updatedBy: by.id };
if (id) {
const row = await ctx.db.leader.findUnique({ where: { id } });
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That person isn\'t on the team.');
return ctx.db.leader.update({ where: { id }, data });
}
const last = await ctx.db.leader.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
return ctx.db.leader.create({ data: { ...data, position: l.position ?? (last?.position ?? -1) + 1 } });
}
export async function archiveLeader(ctx: Ctx, id: string, by: Who) {
await ctx.db.leader.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
}
+92
View File
@@ -0,0 +1,92 @@
/**
* The media library and storage (WEBSITE-1.0-PLAN §10, ROADMAP-v3 §10): uploads of photos (JPEG,
* PNG, WebP), checked by their bytes, not their name. 5 GB included; the licence's
* `limits.storageBytes` says more once extra storage is bought. **When it's full, uploads stop**
* (decision 12) until more is bought; what's already uploaded keeps showing.
*
* Responsive sizes (WebP and JPEG per width) come next; for now the file is served as uploaded.
*/
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import type { Ctx } from '../context.js';
import { defaultUploadDir } from '../demo/demoChurch.js';
import { INCLUDED_STORAGE_BYTES } from '../hub/client.js';
import { hubPublicKey, verifyToken } from '../hub/licence.js';
import { ApiError } from '../http.js';
import { mediaUrl } from '../site/snapshot.js';
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
type Kind = { ext: string; mime: string };
/** What the bytes are, whatever the name says. */
export function sniff(b: Buffer): Kind | null {
if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' };
if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' };
if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' };
return null;
}
/** Width and height from the file's header (PNG, JPEG, WebP), or nulls. */
export function dimensions(b: Buffer, kind: Kind): { width: number | null; height: number | null } {
try {
if (kind.ext === 'png') return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
if (kind.ext === 'webp') {
const chunk = b.toString('ascii', 12, 16);
if (chunk === 'VP8X') return { width: 1 + b.readUIntLE(24, 3), height: 1 + b.readUIntLE(27, 3) };
if (chunk === 'VP8 ') return { width: b.readUInt16LE(26) & 0x3fff, height: b.readUInt16LE(28) & 0x3fff };
if (chunk === 'VP8L') {
const bits = b.readUInt32LE(21);
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
}
}
if (kind.ext === 'jpg') {
let i = 2;
while (i < b.length) {
if (b[i] !== 0xff) break;
const marker = b[i + 1]!;
const len = b.readUInt16BE(i + 2);
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { height: b.readUInt16BE(i + 5), width: b.readUInt16BE(i + 7) };
i += 2 + len;
}
}
} catch {
// A header we can't read: no dimensions, the image still shows.
}
return { width: null, height: null };
}
export async function storage(ctx: Ctx): Promise<{ usedBytes: number; limitBytes: number; full: boolean; percent: number }> {
const [sum, token, installId] = await Promise.all([
ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }),
ctx.settings.get('hub_licence'),
ctx.settings.get('hub_install_id'),
]);
const claims = verifyToken(token, hubPublicKey(ctx)) as { installId?: string; limits?: { storageBytes?: number } } | null;
const fromLicence = claims && claims.installId === installId ? claims.limits?.storageBytes : undefined;
const limitBytes = typeof fromLicence === 'number' ? fromLicence : INCLUDED_STORAGE_BYTES;
const usedBytes = sum._sum.bytes ?? 0;
return { usedBytes, limitBytes, full: usedBytes >= limitBytes, percent: limitBytes ? Math.min(100, Math.round((usedBytes / limitBytes) * 100)) : 100 };
}
export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defaultUploadDir());
export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.');
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.');
const kind = sniff(body);
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.');
const s = await storage(ctx);
if (s.usedBytes + body.length > s.limitBytes) {
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. To get more (5 GB at a time), contact Cross Code; everything already uploaded keeps showing.');
}
const now = ctx.now();
const rel = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.${kind.ext}`;
const file = path.join(uploadDir(ctx), rel);
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(file, body, { mode: 0o644 });
const { width, height } = dimensions(body, kind);
const row = await ctx.db.mediaAsset.create({ data: { filename: rel, mime: kind.mime, bytes: body.length, width, height, alt: alt.trim().slice(0, 500), uploadedBy: by } });
return { ...row, url: mediaUrl(row.filename) };
}
@@ -0,0 +1,42 @@
/**
* Shared previews (WEBSITE-1.0-PLAN §4): a link for someone without an account (the pastor), that
* shows the working copy as it is when opened, for 7 days or until revoked. It can't edit or
* publish, and its pages are `noindex`. Only the token's hash is stored; the link is shown once.
*/
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { hashToken, randomToken } from '../lib/crypto.js';
export const PREVIEW_DAYS = 7;
export async function createPreviewLink(ctx: Ctx, by: { id: string; role: string }) {
const token = randomToken();
const now = ctx.now();
const row = await ctx.db.previewLink.create({ data: { tokenHash: hashToken(token), createdBy: by.id, createdAt: now, expiresAt: new Date(now.getTime() + PREVIEW_DAYS * 864e5) } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'preview_link_created', targetType: 'preview_link', targetId: row.id });
return { id: row.id, url: `${ctx.config.publicUrl}/preview/${token}`, expiresAt: row.expiresAt.toISOString() };
}
export async function listPreviewLinks(ctx: Ctx) {
const now = ctx.now();
const rows = await ctx.db.previewLink.findMany({ orderBy: { createdAt: 'desc' } });
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
return rows.map((r) => ({
id: r.id, createdAt: r.createdAt.toISOString(), expiresAt: r.expiresAt.toISOString(), by: names.get(r.createdBy) ?? null,
active: !r.revokedAt && r.expiresAt > now, revokedAt: r.revokedAt?.toISOString() ?? null,
}));
}
export async function revokePreviewLink(ctx: Ctx, id: string, by: { id: string; role: string }) {
const row = await ctx.db.previewLink.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That preview link doesn\'t exist.');
await ctx.db.previewLink.update({ where: { id }, data: { revokedAt: ctx.now() } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'preview_link_revoked', targetType: 'preview_link', targetId: id });
}
export async function previewTokenValid(ctx: Ctx, token: string | undefined): Promise<boolean> {
if (!token || token.length > 200) return false;
const row = await ctx.db.previewLink.findUnique({ where: { tokenHash: hashToken(token) } });
return !!row && !row.revokedAt && row.expiresAt > ctx.now();
}
+122
View File
@@ -0,0 +1,122 @@
/**
* The admin API (WEBSITE-1.0-PLAN §4, §10), under /api/v1/admin, signed in through Accounts.
* Roles: a Viewer reads; an Editor (and Admin, Owner) changes anything, publishes and shares
* previews; a Ministry leader changes only their own ministry, and their changes wait for an
* Editor or above to publish (decision 11). Every change comes from the site itself (sameOrigin).
*/
import express, { type Request } from 'express';
import type { Ctx } from '../context.js';
import { atLeast, requireRole } from '../auth/sessions.js';
import { churchProfile } from '../church/profile.js';
import { ApiError, handle, sameOrigin } from '../http.js';
import { buildPalette } from '../site/palette.js';
import { mediaUrl, publish } from '../site/snapshot.js';
import { TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_VARIANTS } from '../site/variants.js';
import { changes, discard, restore } from '../site/workingCopy.js';
import * as content from './content.js';
import { MAX_UPLOAD_BYTES, storage, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
const who = (req: Request) => ({ id: req.signed!.user.id, role: req.signed!.user.role });
const param = (req: Request, name: string) => String(req.params[name] ?? '');
export function adminRouter(ctx: Ctx) {
const r = express.Router();
r.use(sameOrigin(ctx.config.publicUrl, ctx.config.production));
r.use(requireRole(ctx, 'viewer'));
const json = express.json({ limit: '256kb' });
const editor = requireRole(ctx, 'editor');
r.get('/me', handle((req) => ({ user: req.signed!.user, mfa: req.signed!.mfa })));
/** The dashboard: pending changes, the last publish, storage, and the setup checklist (§10). */
r.get('/overview', handle(async () => {
const [pending, last, s, church, design, pages, ministries] = await Promise.all([
changes(ctx), ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' } }), storage(ctx), churchProfile(ctx),
ctx.db.siteDesign.findUnique({ where: { id: 1 } }), content.listPages(ctx), content.listMinistries(ctx),
]);
const palette = church ? buildPalette(church.branding.colours.primary, church.branding.colours.accent) : null;
return {
pending: pending.length,
lastPublished: last ? { number: last.number, at: last.publishedAt.toISOString() } : null,
storage: s,
colourNotes: palette?.notes ?? [],
checklist: [
{ key: 'template', label: 'Choose your template', done: !!design, href: '/admin/template' },
{ key: 'profile', label: 'Add your service times and address (your church profile in Accounts)', done: !!church && church.serviceTimes.length > 0 && !!church.contact.address, href: null },
{ key: 'pages', label: 'Write your home page and Plan your visit', done: pages.some((p) => p.kind === 'visit'), href: '/admin/pages' },
{ key: 'ministries', label: 'Add your ministries', done: ministries.length > 0, href: '/admin/ministries' },
{ key: 'publish', label: 'Preview and publish', done: !!last, href: '/admin/publish' },
],
};
}));
// ─── Design ───
r.get('/design', handle(async () => ({ design: await content.getDesign(ctx), options: { variants: TEMPLATE_VARIANTS, headers: TEMPLATE_HEADERS, home: TEMPLATE_HOME_ORDER } })));
r.put('/design', editor, json, handle((req) => content.saveDesign(ctx, req.body, who(req))));
// ─── Pages ───
r.get('/pages', handle(() => content.listPages(ctx)));
r.post('/pages', editor, json, handle((req) => content.createPage(ctx, req.body, who(req))));
r.get('/pages/:id', handle((req) => content.getPage(ctx, param(req, 'id'))));
r.put('/pages/:id', editor, json, handle((req) => content.savePage(ctx, param(req, 'id'), req.body, who(req))));
r.delete('/pages/:id', editor, handle(async (req) => { await content.archivePage(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
r.put('/pages/:id/home/:type', editor, json, handle((req) => content.saveHomeSection(ctx, param(req, 'id'), param(req, 'type'), req.body, who(req))));
r.post('/pages/:id/blocks', editor, json, handle((req) => content.addBlock(ctx, param(req, 'id'), req.body, who(req))));
r.put('/pages/:id/blocks/:sid', editor, json, handle((req) => content.saveBlock(ctx, param(req, 'id'), param(req, 'sid'), req.body, who(req))));
r.post('/pages/:id/blocks/:sid/move', editor, json, handle((req) => content.moveBlock(ctx, param(req, 'id'), param(req, 'sid'), req.body?.direction === 'up' ? 'up' : 'down', who(req))));
r.delete('/pages/:id/blocks/:sid', editor, handle((req) => content.removeBlock(ctx, param(req, 'id'), param(req, 'sid'), who(req))));
// ─── Ministries (a Ministry leader: their own only) and leaders ───
r.get('/ministries', handle(() => content.listMinistries(ctx)));
r.post('/ministries', editor, json, handle((req) => content.saveMinistry(ctx, null, req.body, who(req))));
r.put('/ministries/:id', json, handle((req) => {
const s = req.signed!;
if (!atLeast(s.user.role, 'editor') && !(s.user.role === 'ministry_leader' && s.user.ministryId === param(req, 'id'))) {
throw new ApiError(403, 'FORBIDDEN', 'You can change your own ministry only.');
}
return content.saveMinistry(ctx, param(req, 'id'), req.body, who(req));
}));
r.delete('/ministries/:id', editor, handle(async (req) => { await content.archiveMinistry(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
r.get('/leaders', handle(() => content.listLeaders(ctx)));
r.post('/leaders', editor, json, handle((req) => content.saveLeader(ctx, null, req.body, who(req))));
r.put('/leaders/:id', editor, json, handle((req) => content.saveLeader(ctx, param(req, 'id'), req.body, who(req))));
r.delete('/leaders/:id', editor, handle(async (req) => { await content.archiveLeader(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
// ─── Media library and storage ───
r.get('/media', handle(async () => {
const rows = await ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } });
return { storage: await storage(ctx), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes })) };
}));
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle((req) =>
upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), String(req.query.alt ?? ''), who(req).id)));
r.put('/media/:id', editor, json, handle(async (req) => {
const alt = String(req.body?.alt ?? '').trim().slice(0, 500);
const m = await ctx.db.mediaAsset.update({ where: { id: param(req, 'id') }, data: { alt } }).catch(() => null);
if (!m) throw new ApiError(404, 'NOT_FOUND', 'That image doesn\'t exist.');
return { id: m.id, alt: m.alt };
}));
// ─── Publish, discard, restore, versions, shared previews (§4) ───
r.get('/changes', handle(() => changes(ctx)));
r.post('/publish', editor, json, handle(async (req) => {
const pending = await changes(ctx);
const first = !(await ctx.db.siteVersion.findFirst());
if (!pending.length && !first) throw new ApiError(409, 'NOTHING_TO_PUBLISH', 'There are no changes to publish.');
const note = typeof req.body?.note === 'string' && req.body.note.trim() ? req.body.note.trim().slice(0, 500) : null;
const v = await publish(ctx, who(req), note);
return { number: v.number, publishedAt: v.publishedAt.toISOString(), changes: pending.length };
}));
r.post('/discard', editor, json, handle((req) => discard(ctx, String(req.body?.key ?? ''), who(req))));
r.get('/versions', handle(async () => {
const rows = await ctx.db.siteVersion.findMany({ orderBy: { number: 'desc' }, take: 100, select: { number: true, publishedAt: true, publishedBy: true, note: true } });
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
return rows.map((v) => ({ number: v.number, publishedAt: v.publishedAt.toISOString(), by: names.get(v.publishedBy) ?? null, note: v.note }));
}));
r.post('/versions/:n/restore', editor, handle((req) => restore(ctx, Number(param(req, 'n')), who(req))));
r.get('/preview-links', editor, handle(() => listPreviewLinks(ctx)));
r.post('/preview-links', editor, handle((req) => createPreviewLink(ctx, who(req))));
r.delete('/preview-links/:id', editor, handle(async (req) => { await revokePreviewLink(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
return r;
}