diff --git a/apps/website/CHANGELOG.md b/apps/website/CHANGELOG.md index e4fa961..67c7a38 100644 --- a/apps/website/CHANGELOG.md +++ b/apps/website/CHANGELOG.md @@ -79,6 +79,23 @@ skipped, and the last good copy kept when a fetch fails. Admin → **Linked products**: Connect, Disconnect, Show events from, Publish my events, Check now. Accounts' signed `church.changed` now fetches the church profile again at once. +- **Church details** (§2, decision 10): the church's name, colours, fonts and corners, logo, + service times, contact and social links, saved through Accounts' `church.update` as the signed-in + admin; live at once on all the church's sites (not drafts), refused when someone changed them in + between. +- **Settings** (§10): Google Search Console and Bing verification codes (shown on the home page), + the Coming soon line, and the menu's order. **Audit log** for Owners and Admins; **recent edits** + on the dashboard. +- **Search engines** (§11): a share image made from the church's colours and name for pages without + their own; `Event` structured data on the Website's own event pages, `VideoObject` / + `PodcastEpisode` for messages, `BreadcrumbList` on every page but home; a page's old address + sends people on to the new one (permanent redirect) once published. +- **Two editors at once** (§4): a save that someone else's save overtook is refused, saying who, and + nothing is overwritten. **A Ministry leader's events**: an event can belong to a ministry; its + Ministry leader adds and changes it, an Editor publishes it. **Choose your template** with the + church's own content: each template can be previewed on the real site before it's chosen. +- A simple event with an outside link still has its own page here, with a "More information" + button (its address in the event feed). - The admin page signs people in and out; `/auth/problem` explains a refused sign-in. - **The church's export** (`scripts/export-church.ts`): `export.json` in `crosscode.church-export/1` with its `website` part, for `crosscode export` and uninstall. diff --git a/apps/website/backend/prisma/migrations/20261125000000_init/migration.sql b/apps/website/backend/prisma/migrations/20261125000000_init/migration.sql index c37daa8..5e3f040 100644 --- a/apps/website/backend/prisma/migrations/20261125000000_init/migration.sql +++ b/apps/website/backend/prisma/migrations/20261125000000_init/migration.sql @@ -1,4 +1,4 @@ --- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §8, §10). +-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §6, §8, §10). -- CreateSchema CREATE SCHEMA IF NOT EXISTS "public"; @@ -137,6 +137,7 @@ CREATE TABLE "SimpleEvent" ( "description" TEXT, "imageId" TEXT, "link" TEXT, + "ministryId" TEXT, "cancelled" BOOLEAN NOT NULL DEFAULT false, "publishedAt" TIMESTAMP(3), "updatedAt" TIMESTAMP(3) NOT NULL, @@ -195,6 +196,15 @@ CREATE TABLE "SiteVersion" ( CONSTRAINT "SiteVersion_pkey" PRIMARY KEY ("id") ); +-- CreateTable +CREATE TABLE "SlugHistory" ( + "slug" TEXT NOT NULL, + "pageId" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "SlugHistory_pkey" PRIMARY KEY ("slug") +); + -- CreateTable CREATE TABLE "PreviewLink" ( "id" TEXT NOT NULL, diff --git a/apps/website/backend/prisma/schema.prisma b/apps/website/backend/prisma/schema.prisma index ab520e8..2e00961 100644 --- a/apps/website/backend/prisma/schema.prisma +++ b/apps/website/backend/prisma/schema.prisma @@ -171,6 +171,8 @@ model SimpleEvent { description String? imageId String? link String? + /// A ministry's event: its Ministry leader can add and edit it; an Editor publishes it (§10). + ministryId String? cancelled Boolean @default(false) publishedAt DateTime? updatedAt DateTime @updatedAt @@ -230,6 +232,14 @@ model SiteVersion { publishedAt DateTime @default(now()) } +/// A page's earlier address (§6: "Slug changes get a 301 to the new slug"). Published versions +/// send it to wherever the page is now. +model SlugHistory { + slug String @id + pageId String + createdAt DateTime @default(now()) +} + /// A shared preview link (§4): the token is stored hashed, expires after 7 days or when revoked. model PreviewLink { id String @id @default(uuid()) diff --git a/apps/website/backend/src/admin/church.ts b/apps/website/backend/src/admin/church.ts new file mode 100644 index 0000000..3356776 --- /dev/null +++ b/apps/website/backend/src/admin/church.ts @@ -0,0 +1,52 @@ +/** + * The church's shared details from the Website's admin (WEBSITE-1.0-PLAN §2, decision 10): name, + * colours, brand style (fonts, corners), logo, service times, contact and social links. Accounts + * owns them; the Website saves them through Accounts' `church.update` with the admin as `actor`. + * They aren't drafts: they go live at once on every one of the church's sites, and the screens + * say so. `ifUpdatedAt` refuses a save when someone changed the profile in between. + */ +import { churchEditableSchema, type Church } from '@crosscode/contracts'; +import type { Ctx } from '../context.js'; +import { accounts } from '../auth/accounts.js'; +import { churchChanged, churchProfile } from '../church/profile.js'; +import { ApiError } from '../http.js'; +import { audit } from '../lib/audit.js'; + +type Who = { id: string; role: string }; + +const patchSchema = churchEditableSchema.extend({ branding: churchEditableSchema.shape.branding.partial() }).partial(); + +export async function getChurch(ctx: Ctx) { + churchChanged(ctx); + const church = await churchProfile(ctx); + const linked = !!(await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })); + return { church, linked }; +} + +export async function saveChurch(ctx: Ctx, body: unknown, by: Who): Promise { + const b = (body ?? {}) as { church?: unknown; ifUpdatedAt?: unknown }; + const parsed = patchSchema.safeParse(b.church); + if (!parsed.success) { + const fields: Record = {}; + for (const i of parsed.error.issues) fields[i.path.join('.') || '_'] ??= i.message; + throw new ApiError(400, 'VALIDATION', 'Some details need another look.', fields); + } + if (!Object.keys(parsed.data).length) throw new ApiError(400, 'VALIDATION', 'Nothing to change.'); + type Reply = { church: Church }; + let reply: Reply; + try { + reply = await (await accounts(ctx)).request({ + type: 'church.update', actor: by.id, church: parsed.data as never, + ...(typeof b.ifUpdatedAt === 'string' ? { ifUpdatedAt: b.ifUpdatedAt } : {}), + }); + } catch (e) { + const err = e as { code?: string; message?: string; status?: number }; + if (err.code === 'PROFILE_CHANGED') throw new ApiError(409, 'PROFILE_CHANGED', 'Someone changed your church\'s details while you were editing. Your changes weren\'t saved: reload to see theirs, then make yours again.'); + if (err.code === 'NOT_ALLOWED') throw new ApiError(403, 'NOT_ALLOWED', 'Accounts doesn\'t know you as someone who signs in to this website yet. Sign out and in again, then try once more.'); + if (err instanceof ApiError) throw err; + throw new ApiError(err.status && err.status < 500 ? 400 : 502, err.code ?? 'ACCOUNTS_ERROR', err.message ?? 'Accounts didn\'t take the change.'); + } + churchChanged(ctx); + await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'church_details_changed', targetType: 'church', targetId: null, metadata: { fields: Object.keys(parsed.data) } }); + return reply.church; +} diff --git a/apps/website/backend/src/admin/content.ts b/apps/website/backend/src/admin/content.ts index f60650b..560550f 100644 --- a/apps/website/backend/src/admin/content.ts +++ b/apps/website/backend/src/admin/content.ts @@ -29,6 +29,19 @@ function check(schema: z.ZodType, body: unknown): T { return r.data; } +/** + * Two editors at once (§4): a save says when its form was loaded (`ifUpdatedAt`). If someone else + * saved the same thing since, nothing is overwritten and the editor is told who. + */ +export async function notChangedSince(ctx: Ctx, row: { updatedAt: Date; updatedBy: string | null }, body: unknown, by: Who) { + const given = (body as { ifUpdatedAt?: unknown } | null)?.ifUpdatedAt; + if (typeof given !== 'string') return; + const since = new Date(given); + if (!Number.isFinite(since.getTime()) || row.updatedAt.getTime() <= since.getTime() || row.updatedBy === by.id) return; + const other = row.updatedBy ? await ctx.db.websiteUser.findUnique({ where: { id: row.updatedBy } }) : null; + throw new ApiError(409, 'CHANGED_SINCE', `${other?.name ?? 'Someone else'} changed this while you were editing, so your changes weren't saved. Reload to see theirs, then make yours again.`); +} + // ─── Design ─────────────────────────────────────────────────────────────────── export async function getDesign(ctx: Ctx) { @@ -114,8 +127,14 @@ async function slugFree(ctx: Ctx, slug: string, except?: string) { export async function savePage(ctx: Ctx, id: string, body: unknown, by: Who) { const page = await getPage(ctx, id); const patch = check(pagePatch, body); + await notChangedSince(ctx, page, body, by); if (page.kind === 'home') delete patch.slug; - if (patch.slug && patch.slug !== page.slug) await slugFree(ctx, patch.slug, id); + if (patch.slug && patch.slug !== page.slug) { + await slugFree(ctx, patch.slug, id); + // The old address keeps working: it sends people on to the new one once published. + await ctx.db.slugHistory.upsert({ where: { slug: page.slug }, create: { slug: page.slug, pageId: id }, update: { pageId: id } }); + await ctx.db.slugHistory.deleteMany({ where: { slug: patch.slug } }); + } await ctx.db.page.update({ where: { id }, data: { ...patch, updatedBy: by.id } }); return getPage(ctx, id); } @@ -152,6 +171,7 @@ export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, bo 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 notChangedSince(ctx, existing, body, by); 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 } }); @@ -177,6 +197,7 @@ export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, bod 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); + await notChangedSince(ctx, s, body, by); 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 } }); @@ -236,6 +257,7 @@ export async function saveMinistry(ctx: Ctx, id: string | null, body: unknown, b 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.'); + await notChangedSince(ctx, row, body, by); return ctx.db.ministry.update({ where: { id }, data }); } const last = await ctx.db.ministry.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } }); @@ -256,6 +278,7 @@ export async function saveLeader(ctx: Ctx, id: string | null, body: unknown, by: 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.'); + await notChangedSince(ctx, row, body, by); return ctx.db.leader.update({ where: { id }, data }); } const last = await ctx.db.leader.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } }); diff --git a/apps/website/backend/src/admin/happenings.ts b/apps/website/backend/src/admin/happenings.ts index a542b4f..50dd277 100644 --- a/apps/website/backend/src/admin/happenings.ts +++ b/apps/website/backend/src/admin/happenings.ts @@ -12,6 +12,7 @@ import { youtubeId, spotifyEmbed } from '../site/content.js'; import { mediaUrl } from '../site/snapshot.js'; import { getSource, setSource, syncYoutube, uniqueSlug } from '../site/youtube.js'; import { markRemoved, notifyLinks } from '../feed/feed.js'; +import { notChangedSince } from './content.js'; type Who = { id: string; role: string }; @@ -120,6 +121,7 @@ const eventSchema = z.object({ location: optional(500), description: optional(8000), imageId: z.string().uuid().nullable().default(null), + ministryId: z.string().uuid().nullable().default(null), link: z.string().trim().max(500).nullable().default(null).refine((v) => !v || /^https:\/\//.test(v), 'An https:// address').transform((v) => v || null), }).refine((e) => !e.endsAt || new Date(e.endsAt) >= new Date(e.startsAt), { message: 'It ends before it starts', path: ['endsAt'] }); @@ -128,15 +130,27 @@ export async function listEvents(ctx: Ctx) { const urls = new Map(media.map((m) => [m.id, mediaUrl(m.filename)])); return rows.map((e) => ({ id: e.id, slug: e.slug, title: e.title, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null, allDay: e.allDay, location: e.location, - description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, link: e.link, cancelled: e.cancelled, published: e.publishedAt !== null, + description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, link: e.link, ministryId: e.ministryId, + cancelled: e.cancelled, published: e.publishedAt !== null, updatedAt: e.updatedAt.toISOString(), })); } +const OWN_ONLY = "You can add and change your own ministry's events only."; + export async function saveEvent(ctx: Ctx, id: string | null, body: unknown, by: Who) { const e = check(eventSchema, body); - const data = { title: e.title, startsAt: new Date(e.startsAt), endsAt: e.endsAt ? new Date(e.endsAt) : null, allDay: e.allDay, location: e.location, description: e.description, imageId: e.imageId, link: e.link, timezone: ctx.config.timezone, updatedBy: by.id }; + // A Ministry leader's events are their ministry's (§10); an Editor publishes them. + const leader = by.role === 'ministry_leader' ? await ctx.db.websiteUser.findUnique({ where: { id: by.id } }) : null; + if (leader && (!leader.ministryId || e.ministryId !== leader.ministryId)) throw new ApiError(403, 'FORBIDDEN', OWN_ONLY); + const data = { + title: e.title, startsAt: new Date(e.startsAt), endsAt: e.endsAt ? new Date(e.endsAt) : null, allDay: e.allDay, location: e.location, description: e.description, + imageId: e.imageId, link: e.link, ministryId: e.ministryId, timezone: ctx.config.timezone, updatedBy: by.id, + }; if (id) { - if (!(await ctx.db.simpleEvent.findUnique({ where: { id } }))) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.'); + const row = await ctx.db.simpleEvent.findUnique({ where: { id } }); + if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.'); + if (leader && row.ministryId !== leader.ministryId) throw new ApiError(403, 'FORBIDDEN', OWN_ONLY); + await notChangedSince(ctx, row, body, by); const saved = await ctx.db.simpleEvent.update({ where: { id }, data }); // A live event changed: the church's other sites fetch it now. if (saved.publishedAt) void notifyLinks(ctx, [id]).catch(() => {}); diff --git a/apps/website/backend/src/admin/routes.ts b/apps/website/backend/src/admin/routes.ts index 8106b26..7e6f8f5 100644 --- a/apps/website/backend/src/admin/routes.ts +++ b/apps/website/backend/src/admin/routes.ts @@ -15,6 +15,8 @@ import { TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_VARIANTS } from '../sit import { changes, discard, restore } from '../site/workingCopy.js'; import * as content from './content.js'; import * as people from './people.js'; +import * as church from './church.js'; +import * as settings from './settings.js'; import * as happenings from './happenings.js'; import { syncYoutube } from '../site/youtube.js'; import { publishOn, syncLink } from '../feed/feed.js'; @@ -37,19 +39,21 @@ export function adminRouter(ctx: Ctx) { /** 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([ + const [pending, last, s, profile, design, pages, ministries, recent] = 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), + ctx.db.siteDesign.findUnique({ where: { id: 1 } }), content.listPages(ctx), content.listMinistries(ctx), settings.auditLog(ctx, { take: 12 }), ]); - const palette = church ? buildPalette(church.branding.colours.primary, church.branding.colours.accent) : null; + const palette = profile ? buildPalette(profile.branding.colours.primary, profile.branding.colours.accent) : null; return { pending: pending.length, + /** Recent edits (§10): the audit log without sign-ins. */ + recent: recent.filter((e) => !/^(Signed|Was refused)/.test(e.action)).slice(0, 5), 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: 'profile', label: 'Add your service times and address', done: !!profile && profile.serviceTimes.length > 0 && !!profile.contact.address, href: '/admin/church' }, { 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' }, @@ -112,8 +116,10 @@ export function adminRouter(ctx: Ctx) { r.put('/messages-youtube', editor, json, handle((req) => happenings.saveYoutube(ctx, req.body, who(req)))); r.post('/messages-youtube/sync', editor, handle(() => syncYoutube(ctx))); r.get('/events', handle(() => happenings.listEvents(ctx))); - r.post('/events', editor, json, handle((req) => happenings.saveEvent(ctx, null, req.body, who(req)))); - r.put('/events/:id', editor, json, handle((req) => happenings.saveEvent(ctx, param(req, 'id'), req.body, who(req)))); + // An Editor, or a Ministry leader for their own ministry's events (checked in saveEvent). + const eventWriter = requireRole(ctx, 'ministry_leader'); + r.post('/events', eventWriter, json, handle((req) => happenings.saveEvent(ctx, null, req.body, who(req)))); + r.put('/events/:id', eventWriter, json, handle((req) => happenings.saveEvent(ctx, param(req, 'id'), req.body, who(req)))); r.post('/events/:id/state', editor, json, handle(async (req) => { const b = req.body ?? {}; await happenings.setEventState(ctx, param(req, 'id'), { ...(typeof b.published === 'boolean' ? { published: b.published } : {}), ...(typeof b.cancelled === 'boolean' ? { cancelled: b.cancelled } : {}) }, who(req)); @@ -121,6 +127,14 @@ export function adminRouter(ctx: Ctx) { })); r.delete('/events/:id', editor, handle(async (req) => { await happenings.deleteEvent(ctx, param(req, 'id'), who(req)); return { ok: true }; })); + // ─── The church's shared details (through Accounts, live at once), settings, audit log ─── + r.get('/church', handle(() => church.getChurch(ctx))); + r.put('/church', editor, json, handle((req) => church.saveChurch(ctx, req.body, who(req)))); + r.get('/settings', handle(() => settings.getSettings(ctx))); + r.put('/settings', editor, json, handle((req) => settings.saveSettings(ctx, req.body, who(req)))); + r.put('/pages-order', editor, json, handle((req) => settings.orderPages(ctx, req.body, who(req)))); + r.get('/audit', requireRole(ctx, 'admin'), handle((req) => settings.auditLog(ctx, { before: typeof req.query.before === 'string' ? req.query.before : undefined }))); + // ─── Linked products and the event feed (§8, §9) ─── r.get('/links', handle(async () => { const [listed, links, publishing] = await Promise.all([linkedProducts(ctx), ctx.db.productLink.findMany(), publishOn(ctx)]); diff --git a/apps/website/backend/src/admin/settings.ts b/apps/website/backend/src/admin/settings.ts new file mode 100644 index 0000000..055c644 --- /dev/null +++ b/apps/website/backend/src/admin/settings.ts @@ -0,0 +1,93 @@ +/** + * The site's own settings (WEBSITE-1.0-PLAN §10, "Settings"), live at once (they aren't the site's + * design): the Coming soon line (§5), and the search engines' verification codes (ROADMAP-v3 §11: + * Google Search Console and Bing Webmaster Tools), shown as `` tags on the home page. Also the + * menu's order, and the audit log. + */ +import { z } from 'zod'; +import type { Ctx } from '../context.js'; +import { ApiError } from '../http.js'; +import { audit } from '../lib/audit.js'; + +/** What the search engines give: the content of their meta tag, or the whole tag pasted in. */ +const code = z.string().trim().max(300) + .transform((v) => (/content="([^"]+)"/.exec(v)?.[1] ?? v).trim()) + .refine((v) => v === '' || /^[\w-]{6,100}$/.test(v), 'The code from the search engine (letters, numbers, - and _)'); + +const schema = z.object({ + comingSoonText: z.string().trim().max(300).optional(), + googleVerification: code.optional(), + bingVerification: code.optional(), +}); + +export type SiteSettings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null }; + +export async function getSettings(ctx: Ctx): Promise { + const [coming, google, bing] = await Promise.all([ctx.settings.get('coming_soon_text'), ctx.settings.get('google_verification'), ctx.settings.get('bing_verification')]); + return { comingSoonText: coming || 'Our new website is on its way.', googleVerification: google || null, bingVerification: bing || null }; +} + +export async function saveSettings(ctx: Ctx, body: unknown, by: { id: string; role: string }) { + const r = schema.safeParse(body); + if (!r.success) { + const fields: Record = {}; + for (const i of r.error.issues) fields[i.path.join('.') || '_'] ??= i.message; + throw new ApiError(400, 'VALIDATION', 'Some settings need another look.', fields); + } + const s = r.data; + await ctx.settings.setMany({ + ...(s.comingSoonText !== undefined ? { coming_soon_text: s.comingSoonText || null } : {}), + ...(s.googleVerification !== undefined ? { google_verification: s.googleVerification || null } : {}), + ...(s.bingVerification !== undefined ? { bing_verification: s.bingVerification || null } : {}), + }); + await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'settings_changed', targetType: 'settings', targetId: null, metadata: { fields: Object.keys(s) } }); + return getSettings(ctx); +} + +/** The menu's order: pages in the order given (§10, "Navigation"). A draft, like any page change. */ +export async function orderPages(ctx: Ctx, body: unknown, by: { id: string }) { + const ids = z.array(z.string().uuid()).max(200).safeParse((body as { ids?: unknown } | null)?.ids); + if (!ids.success) throw new ApiError(400, 'VALIDATION', 'Give the pages in order.'); + const pages = await ctx.db.page.findMany({ where: { archivedAt: null } }); + const known = new Set(pages.map((p) => p.id)); + if (ids.data.some((id) => !known.has(id))) throw new ApiError(400, 'VALIDATION', "That isn't one of the site's pages."); + for (const [n, id] of ids.data.entries()) { + const p = pages.find((x) => x.id === id)!; + if (p.position !== n + 1) await ctx.db.page.update({ where: { id }, data: { position: n + 1, updatedBy: by.id } }); + } + return { ok: true }; +} + +const ACTIONS: Record = { + site_published: 'Published the site', change_discarded: 'Discarded a change', version_restored: 'Restored a version', + preview_link_created: 'Made a preview link', preview_link_revoked: 'Stopped a preview link', + first_owner_signed_in: 'Signed in as the first Owner', admin_signed_in: 'Signed in', admin_signed_out: 'Signed out', + admin_sign_in_refused: 'Was refused sign-in (no role here)', website_user_added: 'Gave someone access', + website_user_role_changed: "Changed someone's role", website_user_removed: "Removed someone's access", + website_user_deleted: 'An account was deleted in Accounts', message_published: 'Published a message', + message_unpublished: 'Took a message off the site', message_deleted: 'Removed a message', + youtube_source_set: 'Set the YouTube channel or playlist', event_changed: 'Changed an event', event_deleted: 'Removed an event', + church_details_changed: "Changed the church's details", settings_changed: 'Changed the settings', + product_link_connected: 'Connected a product', product_link_disconnected: 'Disconnected a product', storage_requested: 'Asked for more storage', +}; + +const ROLE_ACTORS: Record = { system: 'The site itself', linked_product: 'A linked product', accounts: 'Accounts' }; + +/** The audit log (§4: "an audit log of who changed what"), newest first. */ +export async function auditLog(ctx: Ctx, opts: { before?: string; take?: number } = {}) { + const take = Math.min(200, Math.max(1, opts.take ?? 100)); + const before = opts.before ? new Date(opts.before) : null; + const where = before && Number.isFinite(before.getTime()) ? { createdAt: { lt: before } } : {}; + const rows = await ctx.db.auditLog.findMany({ where, orderBy: { createdAt: 'desc' }, take }); + const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name])); + return rows.map((r) => { + const meta = (r.metadata ?? {}) as Record; + const detail = [meta.title, meta.label, meta.note].find((x) => typeof x === 'string') as string | undefined; + return { + at: r.createdAt.toISOString(), + who: (r.actorId && names.get(r.actorId)) || ROLE_ACTORS[r.actorRole] || 'Someone', + action: ACTIONS[r.action] ?? r.action.replace(/_/g, ' '), + detail: detail ?? null, + }; + }); +} diff --git a/apps/website/backend/src/app.ts b/apps/website/backend/src/app.ts index 275ea28..012d740 100644 --- a/apps/website/backend/src/app.ts +++ b/apps/website/backend/src/app.ts @@ -14,6 +14,7 @@ */ import path from 'node:path'; import express from 'express'; +import { websiteTemplateSchema } from '@crosscode/contracts'; import type { Ctx } from './context.js'; import { authRouter } from './auth/routes.js'; import { adminRouter } from './admin/routes.js'; @@ -53,7 +54,10 @@ export function createApp(ctx: Ctx) { if (!signed && !(await previewTokenValid(ctx, req.get('x-preview-token')))) throw new ApiError(401, 'NO_PREVIEW', 'This preview has ended, or you need to sign in.'); res.set('Cache-Control', 'no-store'); res.set('X-Robots-Tag', 'noindex, nofollow'); - return { ...(await previewContent(ctx)), preview: { by: signed ? 'admin' : 'link', canPublish: !!signed && atLeast(signed.user.role, 'editor') } }; + // An admin trying a template on (Template and style): the content in it, nothing saved. + const t = websiteTemplateSchema.safeParse(req.get('x-preview-template')); + const asTemplate = signed && t.success ? t.data : undefined; + return { ...(await previewContent(ctx, { asTemplate })), preview: { by: signed ? 'admin' : 'link', canPublish: !!signed && atLeast(signed.user.role, 'editor') && !asTemplate, template: asTemplate ?? null } }; })); site.get('/content', handle(async (_req, res) => { // Short: Publish shows within a minute even where a proxy caches. diff --git a/apps/website/backend/src/site/content.ts b/apps/website/backend/src/site/content.ts index 38b8778..dad4f49 100644 --- a/apps/website/backend/src/site/content.ts +++ b/apps/website/backend/src/site/content.ts @@ -21,6 +21,10 @@ export type SiteEvent = { image: Image | null; /** The event's page: on this site, or at its origin (Cross Events, for registering). */ url: string; + /** The Website's own events: their page here is /events/ (`url` may be their outside link). */ + slug: string | null; + /** An outside link for more information or signing up (the Website's own events). */ + link: string | null; from: 'website' | 'events' | 'app'; registration: { status: string; priceFromCents: number | null } | null; }; @@ -44,6 +48,8 @@ type Common = { palette: Palette; /** The shared brand style, else what the template suggests (§3). */ style: { fontPairing: string; corners: string }; + /** Search engines' verification codes, for the home page's meta tags (§11). */ + verification: { google: string | null; bing: string | null }; }; export type SiteContent = @@ -116,14 +122,14 @@ async function liveEvents(ctx: Ctx): Promise { }; const own: SiteEvent[] = simple.map((e) => ({ title: e.title, summary: e.description ? e.description.slice(0, 200) : null, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null, - allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, from: 'website', registration: null, + allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, slug: e.slug, link: e.link, from: 'website', registration: null, })); const copies: SiteEvent[] = imported.flatMap((row) => { const e = row.data as unknown as CrosscodeEvent; if (!e?.title || (e.endsAt ? new Date(e.endsAt) < now : new Date(e.startsAt) < now)) return []; return [{ title: e.title, summary: e.summary ?? null, startsAt: e.startsAt, endsAt: e.endsAt ?? null, allDay: !!e.allDay, location: e.location?.name ?? null, - image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, from: e.origin.product, + image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, slug: null, link: null, from: e.origin.product, registration: e.registration ? { status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null, } satisfies SiteEvent]; }); @@ -137,17 +143,19 @@ export async function siteContent(ctx: Ctx): Promise { } /** The preview (§4): the working copy as it would look published, whatever was published before. */ -export async function previewContent(ctx: Ctx): Promise { - const [church, snapshot] = await Promise.all([churchProfile(ctx), buildSnapshot(ctx)]); +export async function previewContent(ctx: Ctx, opts: { asTemplate?: WebsiteTemplate } = {}): Promise { + const [church, snapshot] = await Promise.all([churchProfile(ctx), buildSnapshot(ctx, opts)]); return contentFrom(ctx, church, { number: 0, publishedAt: ctx.now(), snapshot }); } async function contentFrom(ctx: Ctx, church: Church | null, published: { number: number; publishedAt: Date; snapshot: Snapshot } | null): Promise { + const [google, bing] = await Promise.all([ctx.settings.get('google_verification'), ctx.settings.get('bing_verification')]); + const verification = { google: google || null, bing: bing || null }; if (!published) { const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } }); const template = (design?.template ?? 'heritage') as WebsiteTemplate; return { - mode: 'coming-soon', template, church, ...brandFor(church, template), + mode: 'coming-soon', template, church, ...brandFor(church, template), verification, comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.', }; } @@ -158,5 +166,5 @@ async function contentFrom(ctx: Ctx, church: Church | null, published: { number: return [p.path, headerIsTransparent(template, snapshot.design.style.header, hero)]; })); const [messages, events] = await Promise.all([liveMessages(ctx), liveEvents(ctx)]); - return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), messages, events }; + return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), verification, messages, events }; } diff --git a/apps/website/backend/src/site/snapshot.ts b/apps/website/backend/src/site/snapshot.ts index b6f169f..8349b34 100644 --- a/apps/website/backend/src/site/snapshot.ts +++ b/apps/website/backend/src/site/snapshot.ts @@ -11,7 +11,7 @@ import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts'; import type { Ctx } from '../context.js'; import { audit } from '../lib/audit.js'; import { parseSectionData } from './sections.js'; -import { defaultDesign, isVariant, SECTION_TYPES, type SectionType, type SiteDesign } from './variants.js'; +import { defaultDesign, isVariant, SECTION_TYPES, switchTemplate, type SectionType, type SiteDesign } from './variants.js'; export const SNAPSHOT_VERSION = 1; @@ -44,6 +44,8 @@ export type Snapshot = { leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[]; /** Every image the sections refer to, by media id. */ media: Record; + /** Earlier page addresses (without the /) and the path each page has now: a permanent redirect. */ + redirects: Record; /** The working copy's rows at publish time: Restore and Discard copy from here (§4). */ source: Source; }; @@ -117,9 +119,20 @@ export function toSource(w: Awaited>): Source } /** The working copy as a snapshot (what Publish saves, and what the preview shows). */ -export async function buildSnapshot(ctx: Ctx): Promise { - const [w, media] = await Promise.all([readWorkingCopy(ctx), ctx.db.mediaAsset.findMany()]); - return snapshotFrom(toSource(w), media); +export async function buildSnapshot(ctx: Ctx, opts: { asTemplate?: WebsiteTemplate } = {}): Promise { + const [w, media, history] = await Promise.all([readWorkingCopy(ctx), ctx.db.mediaAsset.findMany(), ctx.db.slugHistory.findMany()]); + const source = toSource(w); + // "Choose your template" (ROADMAP-v3 §6): the church's own content in another template, as a + // switch would make it, without saving anything. + if (opts.asTemplate) source.design = switchTemplate(cleanDesign(source.design), opts.asTemplate).design; + const snap = snapshotFrom(source, media); + const pathOf = new Map(w.pages.map((p) => [p.id, p.kind === 'home' ? '/' : `/${p.slug}`])); + const live = new Set(w.pages.map((p) => p.slug)); + for (const h of history) { + const to = pathOf.get(h.pageId); + if (to && !live.has(h.slug)) snap.redirects[h.slug] = to; + } + return snap; } export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot { @@ -169,6 +182,7 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot { ministries: source.ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })), leaders: source.leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })), media: used, + redirects: {}, source, }; } diff --git a/apps/website/backend/tests/editing.test.ts b/apps/website/backend/tests/editing.test.ts new file mode 100644 index 0000000..c4d3e8e --- /dev/null +++ b/apps/website/backend/tests/editing.test.ts @@ -0,0 +1,87 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import request from 'supertest'; +import { hashToken } from '../src/lib/crypto.js'; +import { previewContent, siteContent } from '../src/site/content.js'; +import { publish } from '../src/site/snapshot.js'; +import { harness, SITE } from './support/harness.js'; + +async function site() { + const h = await harness({ linked: false }); + const people = { ann: '00000000-0000-4000-8000-00000000000a', ben: '00000000-0000-4000-8000-00000000000b', lee: '00000000-0000-4000-8000-00000000000c' }; + const kids = await h.db.ministry.create({ data: { slug: 'kids', name: 'Kids' } }); + const youth = await h.db.ministry.create({ data: { slug: 'youth', name: 'Youth' } }); + await h.db.websiteUser.create({ data: { id: people.ann, name: 'Ann', email: 'ann@hope.test', role: 'editor' } }); + await h.db.websiteUser.create({ data: { id: people.ben, name: 'Ben', email: 'ben@hope.test', role: 'editor' } }); + await h.db.websiteUser.create({ data: { id: people.lee, name: 'Lee', email: 'lee@hope.test', role: 'ministry_leader', ministryId: kids.id } }); + for (const [k, id] of Object.entries(people)) await h.db.session.create({ data: { tokenHash: hashToken(k), userId: id, expiresAt: new Date(Date.now() + 864e5) } }); + const as = (who: keyof typeof people) => (m: 'get' | 'post' | 'put', p: string, b?: object) => { + const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', `ccw_session=${who}`).set('Origin', SITE); + return b ? r.send(b) : r; + }; + return { ...h, as, kids, youth }; +} + +describe('two editors at once (§4)', () => { + it("doesn't overwrite someone else's save, and says who", async () => { + const { as, db } = await site(); + const page = await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About' } }); + const loaded = (await as('ann')('get', `/pages/${page.id}`)).body.updatedAt; + await new Promise((r) => setTimeout(r, 5)); + assert.equal((await as('ben')('put', `/pages/${page.id}`, { title: "Ben's title", ifUpdatedAt: loaded })).status, 200); + const ann = await as('ann')('put', `/pages/${page.id}`, { title: "Ann's title", ifUpdatedAt: loaded }); + assert.equal(ann.status, 409); + assert.match(ann.body.error.message, /^Ben changed this/); + assert.equal((await as('ann')('get', `/pages/${page.id}`)).body.title, "Ben's title"); + // Her own earlier save never blocks her. + const fresh = (await as('ann')('get', `/pages/${page.id}`)).body.updatedAt; + assert.equal((await as('ann')('put', `/pages/${page.id}`, { title: 'One', ifUpdatedAt: fresh })).status, 200); + assert.equal((await as('ann')('put', `/pages/${page.id}`, { title: 'Two', ifUpdatedAt: fresh })).status, 200); + }); +}); + +describe("a Ministry leader's events (§10)", () => { + it('adds and changes their own ministry\'s events only, and an Editor publishes them', async () => { + const { as, kids, youth } = await site(); + const startsAt = new Date(Date.now() + 864e5).toISOString(); + assert.equal((await as('lee')('post', '/events', { title: 'Youth night', startsAt, ministryId: youth.id })).status, 403); + assert.equal((await as('lee')('post', '/events', { title: 'No ministry', startsAt })).status, 403); + const mine = await as('lee')('post', '/events', { title: 'Kids party', startsAt, ministryId: kids.id }); + assert.equal(mine.status, 200); + assert.equal((await as('lee')('put', `/events/${mine.body.id}`, { title: 'Kids party!', startsAt, ministryId: kids.id })).status, 200); + assert.equal((await as('lee')('post', `/events/${mine.body.id}/state`, { published: true })).status, 403); + const other = await as('ann')('post', '/events', { title: 'Picnic', startsAt }); + assert.equal((await as('lee')('put', `/events/${other.body.id}`, { title: 'Mine now', startsAt, ministryId: kids.id })).status, 403); + assert.equal((await as('ann')('post', `/events/${mine.body.id}/state`, { published: true })).status, 200); + }); +}); + +describe('choosing a template with the church\'s own content', () => { + it('previews the content in another template without saving anything', async () => { + const { ctx, db, as, app } = await site(); + await db.siteDesign.create({ data: { id: 1, template: 'heritage', variants: {}, home: [], style: {} } }); + const c = await previewContent(ctx, { asTemplate: 'bold' }); + assert.equal(c.mode === 'published' && c.snapshot.design.template, 'bold'); + assert.equal((await as('ann')('get', '/design')).body.design.template, 'heritage', 'nothing saved'); + const viaHeader = await request(app).get('/api/v1/site/preview').set('Cookie', 'ccw_session=ann').set('x-preview-template', 'clean'); + assert.equal(viaHeader.body.snapshot.design.template, 'clean'); + assert.equal(viaHeader.body.preview.canPublish, false, 'no publishing from a try-on'); + }); +}); + +describe('an address that changed (§6)', () => { + it('sends the old address on to the new one once published', async () => { + const { ctx, db, as } = await site(); + const page = await db.page.create({ data: { kind: 'custom', slug: 'youth-camp', title: 'Youth camp' } }); + await as('ann')('put', `/pages/${page.id}`, { slug: 'camp' }); + await as('ann')('put', `/pages/${page.id}`, { slug: 'summer-camp' }); + await publish(ctx, { id: 'x', role: 'system' }); + const c = await siteContent(ctx); + assert.deepEqual(c.mode === 'published' && c.snapshot.redirects, { 'youth-camp': '/summer-camp', camp: '/summer-camp' }); + // A new page taking an old address wins over its redirect. + await db.page.create({ data: { kind: 'custom', slug: 'camp', title: 'Camp info' } }); + await publish(ctx, { id: 'x', role: 'system' }); + const after = await siteContent(ctx); + assert.deepEqual(after.mode === 'published' && after.snapshot.redirects, { 'youth-camp': '/summer-camp' }); + }); +}); diff --git a/apps/website/backend/tests/settings.test.ts b/apps/website/backend/tests/settings.test.ts new file mode 100644 index 0000000..f68c3d0 --- /dev/null +++ b/apps/website/backend/tests/settings.test.ts @@ -0,0 +1,70 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import request from 'supertest'; +import { hashToken } from '../src/lib/crypto.js'; +import { siteContent } from '../src/site/content.js'; +import { harness, SITE } from './support/harness.js'; + +async function site(role: 'owner' | 'editor' | 'viewer' = 'owner') { + const h = await harness(); + const id = '00000000-0000-4000-8000-000000000001'; + await h.db.websiteUser.create({ data: { id, name: 'Sam', email: 'sam@hope.test', role } }); + await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: id, expiresAt: new Date(Date.now() + 864e5) } }); + const go = (m: 'get' | 'post' | 'put', p: string, b?: object) => { + const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE); + return b ? r.send(b) : r; + }; + return { ...h, go, id }; +} + +describe("the church's shared details, saved through Accounts (decision 10)", () => { + it('sends only what changed, as the signed-in admin', async () => { + const { go, fake, id } = await site(); + const r = await go('put', '/church', { church: { serviceTimes: [{ day: 'sunday', time: '09:30', label: 'Morning', campus: null, note: null }] }, ifUpdatedAt: '2026-11-25T08:00:00.000Z' }); + assert.equal(r.status, 200); + const sent = fake.requests.at(-1)!; + assert.equal(sent.type, 'church.update'); + assert.equal(sent.actor, id); + assert.deepEqual(Object.keys(sent.church!), ['serviceTimes']); + }); + + it('says so when someone changed the profile in between, and checks the fields first', async () => { + const { go } = await site(); + const stale = await go('put', '/church', { church: { name: 'Hope' }, ifUpdatedAt: '2000-01-01T00:00:00.000Z' }); + assert.equal(stale.body.error.code, 'PROFILE_CHANGED'); + const bad = await go('put', '/church', { church: { contact: { email: null, phone: '012 345', whatsapp: null, address: null } } }); + assert.equal(bad.status, 400); + assert.ok(bad.body.error.fields['contact.phone']); + }); + + it("is an Editor's job, not a Viewer's", async () => { + const { go } = await site('viewer'); + assert.equal((await go('put', '/church', { church: { name: 'X' } })).status, 403); + }); +}); + +describe('settings, the menu and the audit log', () => { + it('takes a verification code, or the whole meta tag, and the site shows it', async () => { + const { go, ctx } = await site(); + const r = await go('put', '/settings', { googleVerification: '', bingVerification: 'B1NGcode99', comingSoonText: 'Opening at Easter.' }); + assert.equal(r.status, 200); + assert.equal(r.body.googleVerification, 'abc123XYZ_-'); + const c = await siteContent(ctx); + assert.deepEqual(c.verification, { google: 'abc123XYZ_-', bing: 'B1NGcode99' }); + assert.equal(c.mode === 'coming-soon' && c.comingSoonText, 'Opening at Easter.'); + assert.equal((await go('put', '/settings', { googleVerification: '