1.7.0 had Move and zoom in page sections only. Ministries, Leadership
and Events now have it on their photo, in the frame the site uses for
the current template and layouts. Saved with the row as `framing`
({ x, y, zoom }, null for centred; cleared when the photo changes).
Ministries and leaders are drafts until Publish (snapshot, Discard and
Restore carry it); an event's shows once the event is published.
Versions published before this compare unchanged.
One migration: a nullable JSONB `framing` column on Ministry, Leader
and SimpleEvent.
Also: the 1.7.0 e2e test waits for the media library to load before
counting it (it could count an empty list).
Checked: Website backend tests (136) and typecheck, frontend typecheck
and lint, production build, admin e2e suite in Chromium (12).
Lighthouse not run.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
143 lines
8.2 KiB
TypeScript
143 lines
8.2 KiB
TypeScript
/**
|
|
* 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 { Prisma } from '../generated/prisma/client.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, framing: (m.framing ?? Prisma.DbNull) as never, 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, framing: (l.framing ?? Prisma.DbNull) as never, 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 };
|
|
}
|