/** * 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; }