feat(website): the admin, with drafts, preview, publish and restore
Admin API and screens: dashboard and setup checklist, template and style, pages and blocks, ministries, leadership, media library with the storage limit, publish and history. Pending changes with who and when, discard one, one Publish, restore any version (each version keeps the working copy's rows, never sent to visitors). Preview on the site's own addresses with a bar (widths, back, publish); shared preview links for 7 days or until revoked. Roles checked, same-origin changes only. Publish refreshes the public pages at once (WEBSITE_CONTENT_CACHE_SECONDS). E2E on a production build: the admin's flows and axe on every screen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -8,7 +8,7 @@ import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteT
|
||||
import type { Ctx } from '../context.js';
|
||||
import { churchProfile } from '../church/profile.js';
|
||||
import { buildPalette, type Palette } from './palette.js';
|
||||
import { mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
|
||||
import { buildSnapshot, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
|
||||
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
|
||||
|
||||
export type SiteEvent = {
|
||||
@@ -51,7 +51,8 @@ export type SiteContent =
|
||||
| (Common & {
|
||||
mode: 'published';
|
||||
version: number;
|
||||
snapshot: Snapshot;
|
||||
/** Without its `source` (the working copy's rows): visitors never get internal ids or hidden sections. */
|
||||
snapshot: Omit<Snapshot, 'source'>;
|
||||
/** Per page path: whether the header sits over the hero (Bold's transparent header, §3). */
|
||||
transparentHeader: Record<string, boolean>;
|
||||
messages: SiteMessage[];
|
||||
@@ -129,8 +130,19 @@ async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
|
||||
return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt));
|
||||
}
|
||||
|
||||
/** What visitors see: the latest published version, else Coming soon. */
|
||||
export async function siteContent(ctx: Ctx): Promise<SiteContent> {
|
||||
const [church, published] = await Promise.all([churchProfile(ctx), publishedSnapshot(ctx)]);
|
||||
return contentFrom(ctx, church, published);
|
||||
}
|
||||
|
||||
/** 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)]);
|
||||
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> {
|
||||
if (!published) {
|
||||
const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } });
|
||||
const template = (design?.template ?? 'heritage') as WebsiteTemplate;
|
||||
@@ -139,7 +151,7 @@ export async function siteContent(ctx: Ctx): Promise<SiteContent> {
|
||||
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
|
||||
};
|
||||
}
|
||||
const { snapshot } = published;
|
||||
const { source: _source, ...snapshot } = published.snapshot;
|
||||
const template = snapshot.design.template;
|
||||
const transparentHeader = Object.fromEntries(snapshot.pages.map((p) => {
|
||||
const hero = p.sections[0]?.type === 'hero' ? (p.sections[0].variant as Variant<'hero'>) : null;
|
||||
|
||||
@@ -41,6 +41,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>;
|
||||
/** The working copy's rows at publish time: Restore and Discard copy from here (§4). */
|
||||
source: Source;
|
||||
};
|
||||
|
||||
export const mediaUrl = (filename: string) => `/api/uploads/${filename.split('/').map(encodeURIComponent).join('/')}`;
|
||||
@@ -62,16 +64,50 @@ export function cleanDesign(saved: { template: string; variants: unknown; home:
|
||||
return { template, variants: variants as SiteDesign['variants'], home: home.filter((e, i) => home.findIndex((x) => x.section === e.section) === i), style };
|
||||
}
|
||||
|
||||
/** The working copy as a snapshot. */
|
||||
export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
/** The working copy's rows, as saved (the source of a snapshot, so a version can be restored, §4). */
|
||||
export type Source = {
|
||||
design: { template: string; variants: unknown; home: unknown; style: unknown } | null;
|
||||
pages: {
|
||||
id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null;
|
||||
inNav: boolean; position: number; imageId: string | null;
|
||||
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[];
|
||||
}[];
|
||||
ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; position: number }[];
|
||||
leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; position: number }[];
|
||||
};
|
||||
|
||||
/** Every page, section, ministry and leader that isn't archived, with who last changed it. */
|
||||
export async function readWorkingCopy(ctx: Ctx) {
|
||||
const db = ctx.db;
|
||||
const [design, pages, ministries, leaders, media] = await Promise.all([
|
||||
const [design, pages, ministries, leaders] = await Promise.all([
|
||||
db.siteDesign.findUnique({ where: { id: 1 } }),
|
||||
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
|
||||
db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
|
||||
db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
|
||||
db.mediaAsset.findMany(),
|
||||
]);
|
||||
return { design, pages, ministries, leaders };
|
||||
}
|
||||
|
||||
export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source {
|
||||
return {
|
||||
design: w.design ? { template: w.design.template, variants: w.design.variants, home: w.design.home, style: w.design.style } : null,
|
||||
pages: w.pages.map((p) => ({
|
||||
id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav,
|
||||
position: p.position, imageId: p.imageId,
|
||||
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })),
|
||||
})),
|
||||
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position })),
|
||||
leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position })),
|
||||
};
|
||||
}
|
||||
|
||||
/** 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 function snapshotFrom(source: Source, media: { id: string; filename: string; alt: string; width: number | null; height: number | null }[]): Snapshot {
|
||||
const images = new Map(media.map((m) => [m.id, { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } satisfies Image]));
|
||||
const image = (id: string | null | undefined) => (id ? images.get(id) ?? null : null);
|
||||
const used: Record<string, Image> = {};
|
||||
@@ -84,12 +120,12 @@ export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
};
|
||||
walk(data);
|
||||
};
|
||||
const d = cleanDesign(design);
|
||||
const snapshotPages: SnapshotPage[] = pages.map((p) => {
|
||||
const d = cleanDesign(source.design);
|
||||
const snapshotPages: SnapshotPage[] = source.pages.map((p) => {
|
||||
const sections: SnapshotSection[] = [];
|
||||
if (p.kind === 'home') {
|
||||
// The homepage: the design's order and variants, each section's data from the page.
|
||||
const byType = new Map(p.sections.map((s) => [s.type, s]));
|
||||
const byType = new Map(p.sections.map((x) => [x.type, x]));
|
||||
for (const entry of d.home) {
|
||||
if (entry.hidden) continue;
|
||||
const data = parseSectionData(entry.section, byType.get(entry.section)?.data);
|
||||
@@ -98,12 +134,12 @@ export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
sections.push({ type: entry.section, variant: d.variants[entry.section], data });
|
||||
}
|
||||
} else {
|
||||
for (const s of p.sections) {
|
||||
if (s.hidden) continue;
|
||||
const data = parseSectionData(s.type, s.data);
|
||||
for (const x of p.sections) {
|
||||
if (x.hidden) continue;
|
||||
const data = parseSectionData(x.type, x.data);
|
||||
if (!data) continue;
|
||||
collect(data);
|
||||
sections.push({ type: s.type, variant: s.variant, data });
|
||||
sections.push({ type: x.type, variant: x.variant, data });
|
||||
}
|
||||
}
|
||||
return {
|
||||
@@ -115,9 +151,10 @@ export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
v: SNAPSHOT_VERSION,
|
||||
design: d,
|
||||
pages: snapshotPages,
|
||||
ministries: ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
|
||||
leaders: leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
|
||||
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,
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Pending changes, Discard and Restore (WEBSITE-1.0-PLAN §4). The working copy is compared with
|
||||
* the latest published version's `source`, item by item: the site's design, each page (with its
|
||||
* sections), each ministry and each leader.
|
||||
*
|
||||
* changes(ctx) what Publish would put live: added, changed or removed, who and when
|
||||
* discard(ctx, key) one item back to its published state (an added one is archived)
|
||||
* restore(ctx, n) a whole version back into the working copy (then previewed and published
|
||||
* like any other change; nothing is lost)
|
||||
*
|
||||
* Archive instead of delete: a removed page, ministry or leader keeps its row (`archivedAt`).
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { publishedSnapshot, readWorkingCopy, toSource, type Source } from './snapshot.js';
|
||||
|
||||
export type ChangeKind = 'added' | 'changed' | 'removed';
|
||||
export type Change = { key: string; kind: ChangeKind; what: 'design' | 'page' | 'ministry' | 'leader'; label: string; by: string | null; at: string | null };
|
||||
|
||||
type Item = { key: string; what: Change['what']; label: string; value: unknown };
|
||||
|
||||
function items(s: Source | null): Map<string, Item> {
|
||||
const m = new Map<string, Item>();
|
||||
if (!s) return m;
|
||||
if (s.design) m.set('design', { key: 'design', what: 'design', label: 'Template and style', value: s.design });
|
||||
for (const p of s.pages) m.set(`page:${p.id}`, { key: `page:${p.id}`, what: 'page', label: p.title, value: p });
|
||||
for (const x of s.ministries) m.set(`ministry:${x.id}`, { key: `ministry:${x.id}`, what: 'ministry', label: x.name, value: x });
|
||||
for (const x of s.leaders) m.set(`leader:${x.id}`, { key: `leader:${x.id}`, what: 'leader', label: x.name, value: x });
|
||||
return m;
|
||||
}
|
||||
|
||||
/** JSON with sorted keys, so two copies of the same thing compare equal. */
|
||||
function stable(v: unknown): string {
|
||||
if (Array.isArray(v)) return `[${v.map(stable).join(',')}]`;
|
||||
if (v && typeof v === 'object') return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable((v as Record<string, unknown>)[k])}`).join(',')}}`;
|
||||
return JSON.stringify(v ?? null);
|
||||
}
|
||||
|
||||
async function publishedSource(ctx: Ctx): Promise<Source | null> {
|
||||
return (await publishedSnapshot(ctx))?.snapshot.source ?? null;
|
||||
}
|
||||
|
||||
export async function changes(ctx: Ctx): Promise<Change[]> {
|
||||
const w = await readWorkingCopy(ctx);
|
||||
const now = items(toSource(w));
|
||||
const then = items(await publishedSource(ctx));
|
||||
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
|
||||
// Who changed it last, and when: the row's own, or (for a page) its latest section's.
|
||||
const who = new Map<string, { by: string | null; at: Date | null }>();
|
||||
if (w.design) who.set('design', { by: w.design.updatedBy, at: w.design.updatedAt });
|
||||
for (const p of w.pages) {
|
||||
const latest = [p, ...p.sections].sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0]!;
|
||||
who.set(`page:${p.id}`, { by: latest.updatedBy, at: latest.updatedAt });
|
||||
}
|
||||
for (const x of w.ministries) who.set(`ministry:${x.id}`, { by: x.updatedBy, at: x.updatedAt });
|
||||
for (const x of w.leaders) who.set(`leader:${x.id}`, { by: x.updatedBy, at: x.updatedAt });
|
||||
|
||||
const out: Change[] = [];
|
||||
const meta = (key: string) => {
|
||||
const h = who.get(key);
|
||||
return { by: h?.by ? names.get(h.by) ?? null : null, at: h?.at?.toISOString() ?? null };
|
||||
};
|
||||
for (const [key, item] of now) {
|
||||
const before = then.get(key);
|
||||
if (!before) out.push({ key, kind: 'added', what: item.what, label: item.label, ...meta(key) });
|
||||
else if (stable(before.value) !== stable(item.value)) out.push({ key, kind: 'changed', what: item.what, label: item.label, ...meta(key) });
|
||||
}
|
||||
for (const [key, item] of then) if (!now.has(key)) out.push({ key, kind: 'removed', what: item.what, label: item.label, by: null, at: null });
|
||||
return out;
|
||||
}
|
||||
|
||||
type Who = { id: string; role: string };
|
||||
|
||||
/** Puts one item of `source` into the working copy as it is there (or archives it when absent). */
|
||||
async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) {
|
||||
const db = ctx.db;
|
||||
const [what, id] = key.split(':') as [string, string | undefined];
|
||||
const stamp = { updatedBy: by.id };
|
||||
if (what === 'design') {
|
||||
if (!source?.design) throw new ApiError(409, 'NOTHING_PUBLISHED', 'The design has never been published, so there\'s nothing to go back to.');
|
||||
const d = source.design;
|
||||
const data = { template: d.template, variants: d.variants as never, home: d.home as never, style: d.style as never, ...stamp };
|
||||
await db.siteDesign.upsert({ where: { id: 1 }, create: { id: 1, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
if (!id) throw new ApiError(400, 'BAD_KEY', 'That isn\'t a change.');
|
||||
if (what === 'page') {
|
||||
const p = source?.pages.find((x) => x.id === id);
|
||||
if (!p) {
|
||||
await db.page.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } });
|
||||
return;
|
||||
}
|
||||
// A page that was added since takes the slug: move it aside first.
|
||||
const clash = await db.page.findFirst({ where: { slug: p.slug, NOT: { id } } });
|
||||
if (clash) await db.page.update({ where: { id: clash.id }, data: { slug: `${clash.slug}-${clash.id.slice(0, 6)}` } });
|
||||
const data = { kind: p.kind as never, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, archivedAt: null, ...stamp };
|
||||
await db.page.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
await db.section.deleteMany({ where: { pageId: id } });
|
||||
for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data as never, ...stamp } });
|
||||
return;
|
||||
}
|
||||
if (what === 'ministry') {
|
||||
const m = source?.ministries.find((x) => x.id === id);
|
||||
if (!m) return void (await db.ministry.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
|
||||
const data = { slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position, archivedAt: null, ...stamp };
|
||||
await db.ministry.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
if (what === 'leader') {
|
||||
const l = source?.leaders.find((x) => x.id === id);
|
||||
if (!l) return void (await db.leader.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
|
||||
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position, archivedAt: null, ...stamp };
|
||||
await db.leader.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
throw new ApiError(400, 'BAD_KEY', 'That isn\'t a change.');
|
||||
}
|
||||
|
||||
/** Discard (§4): one pending change goes back to its published value. */
|
||||
export async function discard(ctx: Ctx, key: string, by: Who) {
|
||||
const pending = (await changes(ctx)).find((c) => c.key === key);
|
||||
if (!pending) throw new ApiError(404, 'NO_SUCH_CHANGE', 'That change isn\'t pending any more.');
|
||||
await apply(ctx, key, await publishedSource(ctx), by);
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'change_discarded', targetType: pending.what, targetId: key, metadata: { label: pending.label, kind: pending.kind } });
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Restore (§4): version `number` back into the working copy, to preview and publish. */
|
||||
export async function restore(ctx: Ctx, number: number, by: Who) {
|
||||
const v = await ctx.db.siteVersion.findUnique({ where: { number } });
|
||||
const source = (v?.snapshot as { source?: Source } | null)?.source;
|
||||
if (!v || !source) throw new ApiError(404, 'NO_SUCH_VERSION', 'That version can\'t be restored.');
|
||||
const keys = new Set([...items(toSource(await readWorkingCopy(ctx))).keys(), ...items(source).keys()]);
|
||||
for (const key of keys) {
|
||||
if (key === 'design' && !source.design) continue;
|
||||
await apply(ctx, key, source, by);
|
||||
}
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'version_restored', targetType: 'site_version', targetId: String(number) });
|
||||
return { restored: number, pending: (await changes(ctx)).length };
|
||||
}
|
||||
Reference in New Issue
Block a user