feat(website): church details, settings, audit log, search engine data, safer editing
Church details saved through Accounts' church.update (live at once). Settings: Search Console and Bing codes, Coming soon line, menu order. Audit log and recent edits. A made share image, Event / VideoObject / PodcastEpisode / BreadcrumbList structured data, permanent redirects from old page addresses. Saves refused when someone else saved in between; Ministry leaders' events; templates previewed with the church's own content before choosing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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<Church> {
|
||||
const b = (body ?? {}) as { church?: unknown; ifUpdatedAt?: unknown };
|
||||
const parsed = patchSchema.safeParse(b.church);
|
||||
if (!parsed.success) {
|
||||
const fields: Record<string, string> = {};
|
||||
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<Reply>({
|
||||
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;
|
||||
}
|
||||
@@ -29,6 +29,19 @@ function check<T>(schema: z.ZodType<T>, 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' } });
|
||||
|
||||
@@ -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(() => {});
|
||||
|
||||
@@ -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)]);
|
||||
|
||||
@@ -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 `<meta>` 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<SiteSettings> {
|
||||
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<string, string> = {};
|
||||
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<string, string> = {
|
||||
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<string, string> = { 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<string, unknown>;
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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/<slug> (`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<SiteEvent[]> {
|
||||
};
|
||||
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<SiteContent> {
|
||||
}
|
||||
|
||||
/** The preview (§4): the working copy as it would look published, whatever was published before. */
|
||||
export async function previewContent(ctx: Ctx): Promise<SiteContent> {
|
||||
const [church, snapshot] = await Promise.all([churchProfile(ctx), buildSnapshot(ctx)]);
|
||||
export async function previewContent(ctx: Ctx, opts: { asTemplate?: WebsiteTemplate } = {}): Promise<SiteContent> {
|
||||
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<SiteContent> {
|
||||
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 };
|
||||
}
|
||||
|
||||
@@ -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<string, Image>;
|
||||
/** Earlier page addresses (without the /) and the path each page has now: a permanent redirect. */
|
||||
redirects: Record<string, string>;
|
||||
/** 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<ReturnType<typeof readWorkingCopy>>): Source
|
||||
}
|
||||
|
||||
/** The working copy as a snapshot (what Publish saves, and what the preview shows). */
|
||||
export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
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<Snapshot> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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' });
|
||||
});
|
||||
});
|
||||
@@ -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: '<meta name="google-site-verification" content="abc123XYZ_-" />', 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: '<script>' })).status, 400);
|
||||
});
|
||||
|
||||
it('orders the menu, and the audit log says who did what', async () => {
|
||||
const { go, db } = await site();
|
||||
const a = await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About', position: 1 } });
|
||||
const b = await db.page.create({ data: { kind: 'give', slug: 'give', title: 'Give', position: 2 } });
|
||||
assert.equal((await go('put', '/pages-order', { ids: [b.id, a.id] })).status, 200);
|
||||
assert.deepEqual((await go('get', '/pages')).body.map((p: { slug: string }) => p.slug), ['give', 'about']);
|
||||
await go('put', '/settings', { comingSoonText: 'Soon.' });
|
||||
const log = (await go('get', '/audit')).body;
|
||||
assert.deepEqual([log[0].who, log[0].action], ['Sam', 'Changed the settings']);
|
||||
const overview = (await go('get', '/overview')).body;
|
||||
assert.equal(overview.recent[0].action, 'Changed the settings');
|
||||
});
|
||||
});
|
||||
@@ -21,7 +21,7 @@ export type FakeAccounts = {
|
||||
next: Partial<IdentityClaims> & { sub: string };
|
||||
started: { returnTo: string; requireTwoFactor: boolean }[];
|
||||
/** Requests to Accounts (people.ensure, …). */
|
||||
requests: { type: string; email?: string; actor?: string | null }[];
|
||||
requests: { type: string; email?: string; actor?: string | null; church?: Record<string, unknown> }[];
|
||||
};
|
||||
|
||||
export function claims(over: Partial<IdentityClaims> & { sub: string }): IdentityClaims {
|
||||
@@ -66,8 +66,13 @@ function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
|
||||
}
|
||||
},
|
||||
/** people.ensure: the same sub for the same email; "new@…" is a new account. */
|
||||
request: async (input: { type: string; email?: string; actor?: string | null }) => {
|
||||
request: async (input: { type: string; email?: string; actor?: string | null; church?: Record<string, unknown>; ifUpdatedAt?: string }) => {
|
||||
fake.requests.push(input);
|
||||
if (input.type === 'church.update') {
|
||||
// An old ifUpdatedAt: someone saved in between.
|
||||
if (input.ifUpdatedAt === '2000-01-01T00:00:00.000Z') throw Object.assign(new Error('changed'), { code: 'PROFILE_CHANGED', status: 409 });
|
||||
return { schema: 'crosscode.identity-request/1', church: { name: 'Hope', ...input.church } };
|
||||
}
|
||||
if (input.type !== 'people.ensure') throw new Error(`not faked: ${input.type}`);
|
||||
const hex = Buffer.from(input.email ?? '').toString('hex').padEnd(12, '0').slice(0, 12);
|
||||
return { schema: 'crosscode.identity-request/1', sub: `22222222-2222-4222-8222-${hex}`, created: input.email?.startsWith('new@') ?? false, emailSent: true };
|
||||
|
||||
Reference in New Issue
Block a user