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>
186 lines
11 KiB
TypeScript
186 lines
11 KiB
TypeScript
/**
|
|
* Messages and simple events in the admin (WEBSITE-1.0-PLAN §7, §8). They're things that happen
|
|
* rather than the site's design, so each has its own Publish (decision 9) and doesn't wait for the
|
|
* site's. Registrations and payments are only Cross Events' (roadmap decision 4): a simple event has
|
|
* at most a link.
|
|
*/
|
|
import { z } from 'zod';
|
|
import type { Ctx } from '../context.js';
|
|
import { ApiError } from '../http.js';
|
|
import { audit } from '../lib/audit.js';
|
|
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 };
|
|
|
|
function check<T>(schema: z.ZodType<T>, body: unknown): T {
|
|
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 fields need another look.', fields);
|
|
}
|
|
return r.data;
|
|
}
|
|
|
|
const optional = (max: number) => z.string().trim().max(max).nullable().default(null).transform((v) => v || null);
|
|
|
|
// ─── Messages ──────────────────────────────────────────────────────────────────
|
|
|
|
const messageSchema = z.object({
|
|
title: z.string().trim().min(1).max(500),
|
|
date: z.iso.date().or(z.iso.datetime()),
|
|
mediaUrl: z.string().trim().max(500).refine((u) => !!youtubeId(u) || !!spotifyEmbed(u), 'A YouTube video or Spotify episode link'),
|
|
speaker: optional(300),
|
|
passage: optional(300),
|
|
notes: optional(8000),
|
|
series: optional(300),
|
|
hidden: z.boolean().default(false),
|
|
});
|
|
|
|
async function seriesId(ctx: Ctx, title: string | null) {
|
|
if (!title) return null;
|
|
const found = await ctx.db.messageSeries.findFirst({ where: { title } });
|
|
if (found) return found.id;
|
|
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'series';
|
|
return (await ctx.db.messageSeries.create({ data: { title, slug: `${slug}-${Date.now().toString(36)}` } })).id;
|
|
}
|
|
|
|
export async function listMessages(ctx: Ctx) {
|
|
const [rows, source, lastSync, lastError] = await Promise.all([
|
|
ctx.db.message.findMany({ orderBy: { date: 'desc' }, take: 200, include: { series: true } }),
|
|
getSource(ctx), ctx.settings.get('youtube_last_sync_at'), ctx.settings.get('youtube_last_error'),
|
|
]);
|
|
return {
|
|
youtube: { source, lastSync, lastError },
|
|
items: rows.map((m) => ({
|
|
id: m.id, title: m.title, date: m.date.toISOString(), mediaUrl: m.mediaUrl, source: m.source, speaker: m.speaker, passage: m.passage, notes: m.notes,
|
|
series: m.series?.title ?? null, hidden: m.hidden, published: m.publishedAt !== null, thumbnail: m.thumbnailUrl,
|
|
})),
|
|
};
|
|
}
|
|
|
|
export async function saveMessage(ctx: Ctx, id: string | null, body: unknown, by: Who) {
|
|
const m = check(messageSchema, body);
|
|
const yt = youtubeId(m.mediaUrl);
|
|
const externalId = yt ?? /\/episode\/([A-Za-z0-9]+)/.exec(m.mediaUrl)?.[1] ?? null;
|
|
if (externalId) {
|
|
const dup = await ctx.db.message.findFirst({ where: { externalId, ...(id ? { NOT: { id } } : {}) } });
|
|
if (dup) throw new ApiError(409, 'DUPLICATE', `That video is already a message (“${dup.title}”).`, { mediaUrl: 'Already a message' });
|
|
}
|
|
const data = {
|
|
title: m.title, date: new Date(m.date), mediaUrl: m.mediaUrl, externalId, speaker: m.speaker, passage: m.passage, notes: m.notes,
|
|
seriesId: await seriesId(ctx, m.series), hidden: m.hidden, updatedBy: by.id,
|
|
};
|
|
if (id) {
|
|
const row = await ctx.db.message.findUnique({ where: { id } });
|
|
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
|
|
// A video from the feed keeps its address and source; its details can be filled in.
|
|
const keep = row.source === 'youtube_feed' ? { mediaUrl: row.mediaUrl, externalId: row.externalId } : {};
|
|
return ctx.db.message.update({ where: { id }, data: { ...data, ...keep } });
|
|
}
|
|
return ctx.db.message.create({
|
|
data: { ...data, slug: await uniqueSlug(ctx, m.title, 'message'), source: yt ? 'youtube' : 'spotify', thumbnailUrl: yt ? `https://i.ytimg.com/vi/${yt}/hqdefault.jpg` : null },
|
|
});
|
|
}
|
|
|
|
/** A message's own Publish (decision 9): live, or back off the site. */
|
|
export async function publishMessage(ctx: Ctx, id: string, live: boolean, by: Who) {
|
|
const row = await ctx.db.message.findUnique({ where: { id } });
|
|
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
|
|
await ctx.db.message.update({ where: { id }, data: { publishedAt: live ? ctx.now() : null, updatedBy: by.id } });
|
|
await audit(ctx, { actorId: by.id, actorRole: by.role, action: live ? 'message_published' : 'message_unpublished', targetType: 'message', targetId: id, metadata: { title: row.title } });
|
|
}
|
|
|
|
export async function deleteMessage(ctx: Ctx, id: string, by: Who) {
|
|
const row = await ctx.db.message.findUnique({ where: { id } });
|
|
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
|
|
// One from the feed would just come back at the next sync: hide it instead.
|
|
if (row.source === 'youtube_feed') throw new ApiError(400, 'FROM_FEED', 'That one comes from YouTube and would come back: hide it instead.');
|
|
await ctx.db.message.delete({ where: { id } });
|
|
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'message_deleted', targetType: 'message', targetId: id, metadata: { title: row.title } });
|
|
}
|
|
|
|
export async function saveYoutube(ctx: Ctx, body: unknown, by: Who) {
|
|
const { youtube } = check(z.object({ youtube: z.string().max(300).nullable() }), body);
|
|
const source = await setSource(ctx, youtube);
|
|
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'youtube_source_set', targetType: 'setting', targetId: 'youtube_source', metadata: { source } });
|
|
return { source, sync: source ? await syncYoutube(ctx) : null };
|
|
}
|
|
|
|
// ─── Simple events ─────────────────────────────────────────────────────────────
|
|
|
|
const eventSchema = z.object({
|
|
title: z.string().trim().min(1).max(300),
|
|
startsAt: z.iso.datetime({ offset: true }),
|
|
endsAt: z.iso.datetime({ offset: true }).nullable().default(null),
|
|
allDay: z.boolean().default(false),
|
|
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'] });
|
|
|
|
export async function listEvents(ctx: Ctx) {
|
|
const [rows, media] = await Promise.all([ctx.db.simpleEvent.findMany({ orderBy: { startsAt: 'desc' }, take: 300 }), ctx.db.mediaAsset.findMany()]);
|
|
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, 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);
|
|
// 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) {
|
|
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(() => {});
|
|
return saved;
|
|
}
|
|
return ctx.db.simpleEvent.create({ data: { ...data, slug: await uniqueSlug(ctx, e.title, 'simpleEvent') } });
|
|
}
|
|
|
|
export async function setEventState(ctx: Ctx, id: string, change: { published?: boolean; cancelled?: boolean }, by: Who) {
|
|
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
|
|
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
|
|
await ctx.db.simpleEvent.update({ where: { id }, data: {
|
|
...(change.published !== undefined ? { publishedAt: change.published ? ctx.now() : null } : {}),
|
|
...(change.cancelled !== undefined ? { cancelled: change.cancelled } : {}),
|
|
updatedBy: by.id,
|
|
} });
|
|
// In or out of the feed (ROADMAP-v3 §4: an unpublished event goes in `deleted`), and siblings told.
|
|
if (change.published !== undefined) await markRemoved(ctx, id, !change.published);
|
|
if (row.publishedAt || change.published) void notifyLinks(ctx, [id]).catch(() => {});
|
|
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_changed', targetType: 'simple_event', targetId: id, metadata: { title: row.title, ...change } });
|
|
}
|
|
|
|
export async function deleteEvent(ctx: Ctx, id: string, by: Who) {
|
|
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
|
|
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
|
|
await ctx.db.simpleEvent.delete({ where: { id } });
|
|
if (row.publishedAt) {
|
|
await markRemoved(ctx, id, true);
|
|
void notifyLinks(ctx, [id]).catch(() => {});
|
|
}
|
|
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_deleted', targetType: 'simple_event', targetId: id, metadata: { title: row.title } });
|
|
}
|