diff --git a/apps/app/backend/prisma/migrations/20261204000000_content/migration.sql b/apps/app/backend/prisma/migrations/20261204000000_content/migration.sql new file mode 100644 index 0000000..73e9711 --- /dev/null +++ b/apps/app/backend/prisma/migrations/20261204000000_content/migration.sql @@ -0,0 +1,128 @@ +-- Church App 1.0.0: announcements, devotionals and events (docs/APP-1.0-PLAN.md §5-§7): announcements, +-- Cross Code's and the church's own devotionals, simple events, the feed's copies and removals. +-- CreateEnum +CREATE TYPE "AnnouncementAudience" AS ENUM ('everyone', 'members'); + +-- CreateEnum +CREATE TYPE "DevotionalSource" AS ENUM ('crosscode', 'church'); + +-- CreateTable +CREATE TABLE "Announcement" ( + "id" TEXT NOT NULL, + "slug" TEXT NOT NULL, + "title" TEXT NOT NULL, + "body" TEXT NOT NULL, + "imageUrl" TEXT, + "buttonLabel" TEXT, + "buttonUrl" TEXT, + "campus" TEXT, + "audience" "AnnouncementAudience" NOT NULL DEFAULT 'everyone', + "pinned" BOOLEAN NOT NULL DEFAULT false, + "publishAt" TIMESTAMP(3), + "endsAt" TIMESTAMP(3), + "sendEmail" BOOLEAN NOT NULL DEFAULT false, + "sendWhatsApp" BOOLEAN NOT NULL DEFAULT false, + "sentAt" TIMESTAMP(3), + "createdById" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Announcement_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Devotional" ( + "id" TEXT NOT NULL, + "source" "DevotionalSource" NOT NULL, + "originId" TEXT, + "date" TEXT NOT NULL, + "title" TEXT NOT NULL, + "reference" TEXT NOT NULL, + "location" JSONB NOT NULL, + "translation" TEXT NOT NULL, + "passageText" TEXT NOT NULL, + "body" TEXT NOT NULL, + "prayer" TEXT, + "author" TEXT, + "membersOnly" BOOLEAN NOT NULL DEFAULT false, + "createdById" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Devotional_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "SimpleEvent" ( + "id" TEXT NOT NULL, + "slug" TEXT NOT NULL, + "title" TEXT NOT NULL, + "startsAt" TIMESTAMP(3) NOT NULL, + "endsAt" TIMESTAMP(3), + "allDay" BOOLEAN NOT NULL DEFAULT false, + "timezone" TEXT NOT NULL DEFAULT 'Africa/Johannesburg', + "location" TEXT, + "description" TEXT, + "imageUrl" TEXT, + "link" TEXT, + "cancelled" BOOLEAN NOT NULL DEFAULT false, + "publishedAt" TIMESTAMP(3), + "updatedBy" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "SimpleEvent_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "ImportedEvent" ( + "id" TEXT NOT NULL, + "linkId" TEXT NOT NULL, + "originProduct" TEXT NOT NULL, + "originId" TEXT NOT NULL, + "startsAt" TIMESTAMP(3) NOT NULL, + "endsAt" TIMESTAMP(3) NOT NULL, + "data" JSONB NOT NULL, + "syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "ImportedEvent_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "FeedRemoval" ( + "eventId" TEXT NOT NULL, + "removedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "FeedRemoval_pkey" PRIMARY KEY ("eventId") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Announcement_slug_key" ON "Announcement"("slug"); + +-- CreateIndex +CREATE INDEX "Announcement_publishAt_idx" ON "Announcement"("publishAt"); + +-- CreateIndex +CREATE INDEX "Devotional_date_idx" ON "Devotional"("date"); + +-- CreateIndex +CREATE UNIQUE INDEX "Devotional_source_date_key" ON "Devotional"("source", "date"); + +-- CreateIndex +CREATE UNIQUE INDEX "SimpleEvent_slug_key" ON "SimpleEvent"("slug"); + +-- CreateIndex +CREATE INDEX "SimpleEvent_startsAt_idx" ON "SimpleEvent"("startsAt"); + +-- CreateIndex +CREATE INDEX "ImportedEvent_startsAt_idx" ON "ImportedEvent"("startsAt"); + +-- CreateIndex +CREATE INDEX "ImportedEvent_linkId_idx" ON "ImportedEvent"("linkId"); + +-- CreateIndex +CREATE UNIQUE INDEX "ImportedEvent_originProduct_originId_key" ON "ImportedEvent"("originProduct", "originId"); + +-- AddForeignKey +ALTER TABLE "ImportedEvent" ADD CONSTRAINT "ImportedEvent_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE; + diff --git a/apps/app/backend/prisma/schema.prisma b/apps/app/backend/prisma/schema.prisma index 9a24d24..9650e16 100644 --- a/apps/app/backend/prisma/schema.prisma +++ b/apps/app/backend/prisma/schema.prisma @@ -80,19 +80,20 @@ model Session { /// the shared email and WhatsApp settings, and Events / the Website for the event feed (§7, §8). /// The secret is encrypted. model ProductLink { - installId String @id - product String - url String - publicKey String - secret String - connectedAt DateTime @default(now()) - connectedById String? + installId String @id + product String + url String + publicKey String + secret String + connectedAt DateTime @default(now()) + connectedById String? /// Show this sibling's events in the App (the event feed, §7). Accounts has none. - showEvents Boolean @default(true) - lastSyncAt DateTime? - lastGoodAt DateTime? - lastSyncError String? - updatedAt DateTime @updatedAt + showEvents Boolean @default(true) + lastSyncAt DateTime? + lastGoodAt DateTime? + lastSyncError String? + updatedAt DateTime @updatedAt + importedEvents ImportedEvent[] } /// Nonces of link messages seen in the last hour (replays are refused). @@ -366,3 +367,123 @@ model RequestPrayer { @@unique([requestId, memberId]) } + +// ── Announcements (§5) ─────────────────────────────────────────────────────────────────────── + +enum AnnouncementAudience { + everyone + members +} + +/// News from the church: public ones are pages of their own (SEO, §11); members-only ones are noindex. +model Announcement { + id String @id @default(uuid()) + slug String @unique + title String + /// Markdown, shown sanitised (no HTML). + body String + imageUrl String? + buttonLabel String? + buttonUrl String? + /// A campus's slug from the church profile, or null for every campus. + campus String? + audience AnnouncementAudience @default(everyone) + pinned Boolean @default(false) + /// Shown from then (now or later); a draft has none. + publishAt DateTime? + /// Hidden after this, if set. + endsAt DateTime? + /// Also send it at the publish time (to members who chose announcements, §8). + sendEmail Boolean @default(false) + sendWhatsApp Boolean @default(false) + /// When the sends were queued (once). + sentAt DateTime? + createdById String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([publishAt]) +} + +// ── Devotionals (§6) ───────────────────────────────────────────────────────────────────────── +// `crosscode.devotional/1`: Cross Code's (from the Hub, the next 2 weeks each night) and the +// church's own, side by side; Settings → Devotionals (AppSetting `devotionals_source`) picks which +// one shows. One per day per source. + +enum DevotionalSource { + crosscode + church +} + +model Devotional { + id String @id @default(uuid()) + source DevotionalSource + /// The Hub's id for Cross Code's (`crosscode.devotional/1` `id`). + originId String? + /// The local day it's for (YYYY-MM-DD, the church's timezone). + date String + title String + reference String + /// `passageLocationSchema`: book, chapter and verses (for the YouVersion link). + location Json + translation String + passageText String + /// Markdown, shown sanitised. + body String + prayer String? + author String? + /// Only for signed-in members (noindex); public by default (§6). + membersOnly Boolean @default(false) + createdById String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([source, date]) + @@index([date]) +} + +// ── Events (§7) ────────────────────────────────────────────────────────────────────────────── +// As the Website's: simple events made in the App, read-only copies of the siblings' events (the +// feed), and removals listed for 90 days. + +model SimpleEvent { + id String @id @default(uuid()) + slug String @unique + title String + startsAt DateTime + endsAt DateTime? + allDay Boolean @default(false) + timezone String @default("Africa/Johannesburg") + location String? + description String? + imageUrl String? + link String? + cancelled Boolean @default(false) + publishedAt DateTime? + updatedBy String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([startsAt]) +} + +model ImportedEvent { + id String @id @default(uuid()) + linkId String + link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade) + originProduct String + originId String + startsAt DateTime + endsAt DateTime + data Json + syncedAt DateTime @default(now()) + + @@unique([originProduct, originId]) + @@index([startsAt]) + @@index([linkId]) +} + +model FeedRemoval { + eventId String @id + removedAt DateTime @default(now()) +} diff --git a/apps/app/backend/src/app.ts b/apps/app/backend/src/app.ts index 54ac601..f8cd08b 100644 --- a/apps/app/backend/src/app.ts +++ b/apps/app/backend/src/app.ts @@ -17,7 +17,8 @@ * /api/v1/requests, /api/v1/me/requests, /api/v1/admin/requests * prayer requests: shared, a member's own, the prayer team's (requests/) * - * To come with the modules (§1): the rest of the public content and member API, and the event feed. + * /api/v1/announcements, /devotionals, /events and their admin content (content/routes.ts) + * /api/feed/v1/… the event feed, both ways (events/feed.ts) */ import express from 'express'; import type { Ctx } from './context.js'; @@ -31,6 +32,7 @@ import { appInfo } from './public/app.js'; import { prayerAdminRouter } from './prayer/admin.js'; import { prayerRouter } from './prayer/routes.js'; import { requestsAdminRouter, requestsRouter } from './requests/routes.js'; +import { contentAdminRouter, contentRouter } from './content/routes.js'; export function createApp(ctx: Ctx) { const app = express(); @@ -60,8 +62,10 @@ export function createApp(ctx: Ctx) { app.use('/api', linksRouter(ctx)); app.use('/api', prayerRouter(ctx)); app.use('/api', requestsRouter(ctx)); + app.use('/api', contentRouter(ctx)); app.use('/api/v1/admin/prayer', prayerAdminRouter(ctx)); app.use('/api/v1/admin/requests', requestsAdminRouter(ctx)); + app.use('/api/v1/admin', contentAdminRouter(ctx)); app.use('/api/v1/admin', adminRouter(ctx)); app.use('/api', (_req, res) => { diff --git a/apps/app/backend/src/content/announcements.ts b/apps/app/backend/src/content/announcements.ts new file mode 100644 index 0000000..e861175 --- /dev/null +++ b/apps/app/backend/src/content/announcements.ts @@ -0,0 +1,107 @@ +/** + * Announcements (APP-1.0-PLAN §5): title, text (markdown, shown without HTML), image, an optional + * button, a campus (or all), who sees it (everyone, or signed-in members only), pinned to the top, + * a publish time and an end date. Public ones are pages of their own; members-only ones are noindex + * and not in the sitemap. "Also send it" by email and/or WhatsApp is queued once at the publish time + * by the messaging slice (§8), for members who chose announcements. + */ +import { z } from 'zod'; +import type { Ctx } from '../context.js'; +import type { Announcement, Prisma } from '../generated/prisma/client.js'; +import { ApiError } from '../http.js'; +import { churchProfile } from '../church/profile.js'; +import { slugify, uniqueSlug } from '../lib/slug.js'; + +const DAY = 864e5; + +export const announcementBody = z.object({ + title: z.string().trim().min(2).max(160), + body: z.string().trim().min(1).max(20_000), + imageUrl: z.string().trim().url().max(500).nullable().optional(), + buttonLabel: z.string().trim().max(40).nullable().optional(), + buttonUrl: z.string().trim().url().max(500).nullable().optional(), + campus: z.string().trim().max(60).nullable().optional(), + audience: z.enum(['everyone', 'members']).default('everyone'), + pinned: z.boolean().default(false), + /** null: a draft; omitted or a past time: now. */ + publishAt: z.string().datetime({ offset: true }).nullable().optional(), + endsAt: z.string().datetime({ offset: true }).nullable().optional(), + sendEmail: z.boolean().default(false), + sendWhatsApp: z.boolean().default(false), +}).strict() + .refine((a) => !a.buttonUrl === !a.buttonLabel, { path: ['buttonLabel'], message: 'A button needs both its words and its link.' }) + .refine((a) => !a.endsAt || !a.publishAt || a.endsAt > a.publishAt, { path: ['endsAt'], message: 'The end is before it\'s published.' }); +export type AnnouncementInput = z.infer; + +/** Shown now: published, not ended. Members-only ones only for a signed-in member. */ +export function visibleWhere(now: Date, signedIn: boolean): Prisma.AnnouncementWhereInput { + return { + publishAt: { not: null, lte: now }, + OR: [{ endsAt: null }, { endsAt: { gt: now } }], + ...(signedIn ? {} : { audience: 'everyone' }), + }; +} + +export function view(a: Announcement) { + return { + slug: a.slug, title: a.title, body: a.body, imageUrl: a.imageUrl, + button: a.buttonLabel && a.buttonUrl ? { label: a.buttonLabel, url: a.buttonUrl } : null, + campus: a.campus, membersOnly: a.audience === 'members', pinned: a.pinned, + publishedAt: a.publishAt!.toISOString(), updatedAt: a.updatedAt.toISOString(), + }; +} + +/** What's shown, pinned first, then newest; `campus` keeps that campus's and everyone's. */ +export async function currentAnnouncements(ctx: Ctx, signedIn: boolean, opts: { campus?: string | null; take?: number } = {}) { + const rows = await ctx.db.announcement.findMany({ + where: opts.campus ? { AND: [visibleWhere(ctx.now(), signedIn), { OR: [{ campus: opts.campus }, { campus: null }] }] } : visibleWhere(ctx.now(), signedIn), + orderBy: [{ pinned: 'desc' }, { publishAt: 'desc' }], + take: opts.take ?? 50, + }); + return rows.map(view); +} + +/** One announcement by its address: null when it isn't shown; `SIGNED_OUT` for a members-only one. */ +export async function announcementBySlug(ctx: Ctx, slug: string, signedIn: boolean) { + const a = await ctx.db.announcement.findFirst({ where: { slug, ...visibleWhere(ctx.now(), true) } }); + if (!a) return null; + if (a.audience === 'members' && !signedIn) throw new ApiError(401, 'SIGNED_OUT', 'Sign in to read this announcement.'); + return view(a); +} + +export async function saveAnnouncement(ctx: Ctx, byId: string, input: AnnouncementInput, id?: string) { + if (input.campus) { + const church = await churchProfile(ctx); + if (!church?.campuses.some((c) => c.slug === input.campus)) throw new ApiError(400, 'VALIDATION', 'There\'s no such campus.', { campus: 'There\'s no such campus in the church profile.' }); + } + const now = ctx.now(); + const publishAt = input.publishAt === null ? null : input.publishAt ? new Date(Math.max(new Date(input.publishAt).getTime(), now.getTime() - 60e3)) : now; + const data = { + title: input.title, body: input.body, imageUrl: input.imageUrl || null, buttonLabel: input.buttonLabel || null, buttonUrl: input.buttonUrl || null, + campus: input.campus || null, audience: input.audience, pinned: input.pinned, publishAt, endsAt: input.endsAt ? new Date(input.endsAt) : null, + sendEmail: input.sendEmail, sendWhatsApp: input.sendWhatsApp, + }; + if (id) { + const before = await ctx.db.announcement.findUnique({ where: { id } }); + if (!before) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such announcement.'); + // Once sent, it stays sent: changing it never sends it again. + return ctx.db.announcement.update({ where: { id }, data: before.sentAt ? { ...data, sendEmail: before.sendEmail, sendWhatsApp: before.sendWhatsApp } : data }); + } + const slug = await uniqueSlug(slugify(input.title), async (s) => !!(await ctx.db.announcement.findUnique({ where: { slug: s } }))); + return ctx.db.announcement.create({ data: { ...data, slug, createdById: byId } }); +} + +export async function adminAnnouncements(ctx: Ctx) { + const rows = await ctx.db.announcement.findMany({ orderBy: [{ createdAt: 'desc' }], take: 300 }); + const now = ctx.now(); + return rows.map((a) => ({ + id: a.id, slug: a.slug, title: a.title, body: a.body, imageUrl: a.imageUrl, buttonLabel: a.buttonLabel, buttonUrl: a.buttonUrl, campus: a.campus, + audience: a.audience, pinned: a.pinned, publishAt: a.publishAt?.toISOString() ?? null, endsAt: a.endsAt?.toISOString() ?? null, + sendEmail: a.sendEmail, sendWhatsApp: a.sendWhatsApp, sentAt: a.sentAt?.toISOString() ?? null, + state: !a.publishAt ? 'draft' : a.publishAt > now ? 'scheduled' : a.endsAt && a.endsAt <= now ? 'ended' : 'live', + })); +} + +/** The heartbeat's count (hub.appStatsSchema `announcements.last30d`). */ +export const announcementsLast30d = (ctx: Ctx) => + ctx.db.announcement.count({ where: { publishAt: { gte: new Date(ctx.now().getTime() - 30 * DAY), lte: ctx.now() } } }); diff --git a/apps/app/backend/src/content/devotionals.ts b/apps/app/backend/src/content/devotionals.ts new file mode 100644 index 0000000..0e95e99 --- /dev/null +++ b/apps/app/backend/src/content/devotionals.ts @@ -0,0 +1,240 @@ +/** + * Devotionals (APP-1.0-PLAN §6, decisions 1, 5, 14, 15): two sources, chosen in Settings → + * Devotionals (AppSetting `devotionals_source`, Cross Code's by default): + * + * 1. **From Cross Code:** fetched from the Hub each night (`GET /api/v2/devotionals?from=`, the next 2 weeks, today included) and on **Sync now**. The App + * replaces its copy of exactly those days and keeps the rest, so a Hub outage under 2 weeks + * changes nothing (ROADMAP-v3 §1, rule 2). + * 2. **Our own:** written by the church's Devotional writers, or imported from the same CSV as the + * Hub's (`checkDevotionalCsv`). + * + * Only the free translations (KJV, BSB; `FREE_BIBLE_TRANSLATION_IDS`). The passage is shown in full + * with its translation's copyright line (and the Bible Society's disclaimer, for when one is + * cleared) and **Read in YouVersion**. No AI on Bible text, ever. + */ +import { z } from 'zod'; +import { + bibleTranslation, CROSSCODE_DEVOTIONALS_FETCH_DAYS, checkDevotionalCsv, DEVOTIONAL_LIMITS, devotionalsReplySchema, FREE_BIBLE_TRANSLATION_IDS, hub, + PASSAGE_WARN_VERSES, parseBibleReference, passageVerseCount, youVersionUrl, type BibleTranslationId, type DevotionalContent, type PassageLocation, +} from '@crosscode/contracts'; +import type { Ctx } from '../context.js'; +import type { Devotional } from '../generated/prisma/client.js'; +import { ApiError } from '../http.js'; +import { churchTimezone } from '../church/profile.js'; +import { addDays, isDate, localDate } from '../lib/zoned.js'; +import { enabledModules } from '../modules.js'; + +const SOURCE_KEY = 'devotionals_source'; +const TIMEOUT_MS = 15_000; + +export type Source = 'crosscode' | 'church'; + +export async function devotionalSource(ctx: Ctx): Promise { + return (await ctx.settings.get(SOURCE_KEY)) === 'church' ? 'church' : 'crosscode'; +} + +export async function setDevotionalSource(ctx: Ctx, source: Source) { + await ctx.settings.set(SOURCE_KEY, source); +} + +/** What every screen, email and WhatsApp shows of one devotional. */ +export function view(d: Devotional) { + const translation = bibleTranslation(d.translation as BibleTranslationId); + return { + id: d.id, date: d.date, source: d.source, title: d.title, + passage: { + reference: d.reference, text: d.passageText, translation: translation.id, translationName: translation.name, + copyright: translation.copyright, disclaimer: translation.disclaimer, + youVersionUrl: youVersionUrl(d.location as PassageLocation, translation.id), + }, + body: d.body, prayer: d.prayer, author: d.author, membersOnly: d.membersOnly, updatedAt: d.updatedAt.toISOString(), + }; +} + +/** Today's (or the most recent before it, §6) from the chosen source; members-only ones need a sign-in. */ +export async function todaysDevotional(ctx: Ctx, signedIn: boolean) { + const [source, tz] = await Promise.all([devotionalSource(ctx), churchTimezone(ctx)]); + const today = localDate(ctx.now(), tz); + const d = await ctx.db.devotional.findFirst({ where: { source, date: { lte: today }, ...(signedIn ? {} : { membersOnly: false }) }, orderBy: { date: 'desc' } }); + return d ? { ...view(d), today: d.date === today } : null; +} + +/** One day's, from the chosen source; never a day after today. */ +export async function devotionalOn(ctx: Ctx, date: string, signedIn: boolean) { + const [source, tz] = await Promise.all([devotionalSource(ctx), churchTimezone(ctx)]); + if (date > localDate(ctx.now(), tz)) return null; + const d = await ctx.db.devotional.findUnique({ where: { source_date: { source, date } } }); + if (!d) return null; + if (d.membersOnly && !signedIn) throw new ApiError(401, 'SIGNED_OUT', 'Sign in to read this devotional.'); + return view(d); +} + +/** The archive by month (§6): titles and passages of the days up to today. */ +export async function archive(ctx: Ctx, month: string, signedIn: boolean) { + const [source, tz] = await Promise.all([devotionalSource(ctx), churchTimezone(ctx)]); + const today = localDate(ctx.now(), tz); + const rows = await ctx.db.devotional.findMany({ + where: { source, date: { gte: `${month}-01`, lte: `${month}-31` < today ? `${month}-31` : today }, ...(signedIn ? {} : { membersOnly: false }) }, + orderBy: { date: 'desc' }, + }); + return rows.map((d) => ({ date: d.date, title: d.title, reference: d.reference, membersOnly: d.membersOnly })); +} + +/** Every translation the App's devotionals quote, with its full notice (the Acknowledgements page). */ +export async function acknowledgements(ctx: Ctx) { + const used = new Set((await ctx.db.devotional.findMany({ select: { translation: true } })).map((d) => d.translation)); + return [...used].sort().map((id) => { + const t = bibleTranslation(id as BibleTranslationId); + return { id: t.id, name: t.name, acknowledgement: t.acknowledgement, disclaimer: t.disclaimer }; + }); +} + +// ── From Cross Code (the Hub) ── + +export class SyncError extends Error {} + +/** + * Fetches Cross Code's next 2 weeks from the Hub and replaces the App's copy of exactly those days + * (a day missing from the answer was removed in the Hub). Earlier days stay, for the archive. + */ +export async function syncCrosscode(ctx: Ctx): Promise<{ from: string; to: string; saved: number; removed: number }> { + const licence = await ctx.settings.get('hub_licence'); + if (!licence) throw new SyncError('The App isn\'t registered with the Hub yet.'); + const from = localDate(ctx.now(), await churchTimezone(ctx)); + let body: unknown; + try { + const res = await fetch(`${ctx.config.hubUrl}${hub.DEVOTIONALS_PATH}?from=${from}`, { headers: { Authorization: `Bearer ${licence}`, Accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) }); + body = await res.json().catch(() => null); + if (!res.ok) { + const code = (body as { error?: { code?: string } } | null)?.error?.code; + throw new SyncError(code === 'LICENCE_INACTIVE' ? 'The App\'s licence isn\'t active, so the Hub sends no devotionals.' : `The Hub answered ${res.status}${code ? ` (${code})` : ''}.`); + } + } catch (e) { + await ctx.settings.set('devotionals_sync_error', (e as Error).message.slice(0, 300)); + if (e instanceof SyncError) throw e; + throw new SyncError(`The Hub can't be reached: ${(e as Error).message}`); + } + const parsed = devotionalsReplySchema.safeParse(body); + if (!parsed.success) { + await ctx.settings.set('devotionals_sync_error', 'The Hub\'s answer isn\'t crosscode.devotional/1.'); + throw new SyncError('The Hub\'s answer isn\'t crosscode.devotional/1.'); + } + const reply = parsed.data; + // Never more than the fetch window, whatever an older Hub sends. + const to = reply.to < addDays(reply.from, CROSSCODE_DEVOTIONALS_FETCH_DAYS - 1) ? reply.to : addDays(reply.from, CROSSCODE_DEVOTIONALS_FETCH_DAYS - 1); + const days = reply.devotionals.filter((d) => d.date >= reply.from && d.date <= to && FREE_BIBLE_TRANSLATION_IDS.includes(d.passage.translation)); + for (const d of days) { + const data = { + originId: d.id, title: d.title, reference: d.passage.reference, location: d.passage.location as never, translation: d.passage.translation, + passageText: d.passage.text, body: d.body, prayer: d.prayer, author: d.author, + }; + await ctx.db.devotional.upsert({ where: { source_date: { source: 'crosscode', date: d.date } }, create: { ...data, source: 'crosscode', date: d.date }, update: data }); + } + const removed = await ctx.db.devotional.deleteMany({ where: { source: 'crosscode', date: { gte: reply.from, lte: to, notIn: days.map((d) => d.date) } } }); + await ctx.settings.setMany({ devotionals_synced_at: ctx.now().toISOString(), devotionals_sync_error: null }); + return { from: reply.from, to, saved: days.length, removed: removed.count }; +} + +/** The nightly job: only while the module is on and the church shows Cross Code's. */ +export async function nightlySync(ctx: Ctx) { + if (!(await enabledModules(ctx)).includes('devotionals')) return { skipped: 'Devotionals are switched off.' }; + if ((await devotionalSource(ctx)) !== 'crosscode') return { skipped: 'The church shows its own devotionals.' }; + return syncCrosscode(ctx); +} + +// ── The church's own ── + +export const devotionalBody = z.object({ + date: z.string().refine(isDate, 'A date as YYYY-MM-DD.'), + title: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.title), + reference: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.reference), + translation: z.string(), + passageText: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.passageText), + body: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.body), + prayer: z.string().trim().max(DEVOTIONAL_LIMITS.prayer).nullable().optional(), + author: z.string().trim().max(DEVOTIONAL_LIMITS.author).nullable().optional(), + membersOnly: z.boolean().default(false), +}).strict(); +export type DevotionalInput = z.infer; + +/** Reads the reference and checks the translation; answers the location and any warning. */ +function passageOf(input: Pick): { location: PassageLocation; translation: BibleTranslationId; warnings: string[] } { + if (!FREE_BIBLE_TRANSLATION_IDS.includes(input.translation as BibleTranslationId)) { + throw new ApiError(400, 'VALIDATION', 'Only the free translations can be used.', { translation: `Use ${FREE_BIBLE_TRANSLATION_IDS.join(' or ')}: the others need their publisher's permission.` }); + } + const parsed = parseBibleReference(input.reference); + if (!parsed.ok) throw new ApiError(400, 'VALIDATION', 'That passage can\'t be read.', { reference: parsed.error }); + const verses = passageVerseCount(parsed.passage); + const warnings = verses !== null && verses > PASSAGE_WARN_VERSES ? [`The passage is ${verses} verses long: quote the passage the devotional is about, not whole chapters.`] : []; + return { location: parsed.passage, translation: input.translation as BibleTranslationId, warnings }; +} + +export async function saveOwn(ctx: Ctx, byId: string, input: DevotionalInput, id?: string) { + const { location, translation, warnings } = passageOf(input); + const data = { + date: input.date, title: input.title, reference: input.reference, location: location as never, translation, passageText: input.passageText, + body: input.body, prayer: input.prayer || null, author: input.author || null, membersOnly: input.membersOnly, + }; + const clash = await ctx.db.devotional.findUnique({ where: { source_date: { source: 'church', date: input.date } } }); + if (clash && clash.id !== id) throw new ApiError(409, 'DATE_TAKEN', `${input.date} already has a devotional.`, { date: 'That day already has one.' }); + if (id) { + const before = await ctx.db.devotional.findUnique({ where: { id } }); + if (!before || before.source !== 'church') throw new ApiError(404, 'NOT_FOUND', 'There\'s no such devotional.'); + return { devotional: view(await ctx.db.devotional.update({ where: { id }, data })), warnings }; + } + return { devotional: view(await ctx.db.devotional.create({ data: { ...data, source: 'church', createdById: byId } })), warnings }; +} + +export async function deleteOwn(ctx: Ctx, id: string) { + const { count } = await ctx.db.devotional.deleteMany({ where: { id, source: 'church' } }); + if (!count) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such devotional.'); +} + +/** The admin's list: a month of either source (Cross Code's read-only), every day of it. */ +export async function adminMonth(ctx: Ctx, month: string, source: Source) { + const rows = await ctx.db.devotional.findMany({ where: { source, date: { gte: `${month}-01`, lte: `${month}-31` } }, orderBy: { date: 'asc' } }); + return rows.map((d) => ({ ...view(d), location: d.location, reference: d.reference })); +} + +/** + * The CSV import (§6): `preview` checks every row (as the Hub does) and changes nothing; otherwise + * the valid rows are saved, days already filled replaced or skipped (`taken`). + */ +export async function importCsv(ctx: Ctx, byId: string, text: string, opts: { preview: boolean; taken: 'replace' | 'skip' }) { + const existing = await ctx.db.devotional.findMany({ where: { source: 'church' }, select: { date: true } }); + const result = checkDevotionalCsv(text, { taken: existing.map((d) => d.date), translations: FREE_BIBLE_TRANSLATION_IDS }); + const summary = { + fileError: result.fileError, + rows: result.rows.map((r) => ({ line: r.line, date: r.devotional?.date ?? null, title: r.devotional?.title ?? null, errors: r.errors, warnings: r.warnings, taken: r.taken })), + valid: result.rows.filter((r) => r.devotional).length, + imported: 0, + replaced: 0, + skipped: 0, + }; + if (opts.preview || result.fileError) return summary; + for (const r of result.rows) { + const d = r.devotional as DevotionalContent | null; + if (!d) continue; + if (r.taken && opts.taken === 'skip') { summary.skipped++; continue; } + const data = { + title: d.title, reference: d.passage.reference, location: d.passage.location as never, translation: d.passage.translation, passageText: d.passage.text, + body: d.body, prayer: d.prayer, author: d.author, + }; + await ctx.db.devotional.upsert({ where: { source_date: { source: 'church', date: d.date } }, create: { ...data, source: 'church', date: d.date, createdById: byId }, update: data }); + if (r.taken) summary.replaced++; + else summary.imported++; + } + return summary; +} + +/** Settings → Devotionals: the source, and how Cross Code's are doing. */ +export async function devotionalStatus(ctx: Ctx) { + const tz = await churchTimezone(ctx); + const today = localDate(ctx.now(), tz); + const [source, syncedAt, error, ahead] = await Promise.all([ + devotionalSource(ctx), ctx.settings.get('devotionals_synced_at'), ctx.settings.get('devotionals_sync_error'), + ctx.db.devotional.findMany({ where: { source: 'crosscode', date: { gte: today } }, select: { date: true }, orderBy: { date: 'desc' }, take: 1 }), + ]); + return { source, crosscode: { syncedAt, error, lastDay: ahead[0]?.date ?? null }, translations: FREE_BIBLE_TRANSLATION_IDS.map((id) => ({ id, name: bibleTranslation(id).name })) }; +} diff --git a/apps/app/backend/src/content/routes.ts b/apps/app/backend/src/content/routes.ts new file mode 100644 index 0000000..0d09d30 --- /dev/null +++ b/apps/app/backend/src/content/routes.ts @@ -0,0 +1,243 @@ +/** + * Announcements, devotionals and events (APP-1.0-PLAN §5–§7). Each module answers 404 `MODULE_OFF` + * while it's switched off. + * + * Public (signed in, members-only items too): + * GET /api/v1/announcements[?campus=] pinned first, then newest + * GET /api/v1/announcements/:slug + * GET /api/v1/devotionals/today today's, or the most recent (§6) + * GET /api/v1/devotionals?month=YYYY-MM the archive + * GET /api/v1/devotionals/acknowledgements every quoted translation's notice + * GET /api/v1/devotionals/:date + * GET /api/v1/events upcoming: the App's own and the siblings' + * GET /api/v1/events/:key + * + * The admin (with 2FA): + * /api/v1/admin/announcements GET, POST, PUT /:id, DELETE /:id (Content admin) + * /api/v1/admin/events GET, POST, PUT /:id, DELETE /:id, GET|PUT /feed, POST /feed/sync (Content admin) + * /api/v1/admin/devotionals GET ?month=&source=, POST, PUT /:id, DELETE /:id, POST /import, + * GET /template, GET|PUT /settings, POST /sync (Devotional writer) + */ +import express, { type Request, type RequestHandler } from 'express'; +import { z } from 'zod'; +import { DEVOTIONAL_CSV_MAX_BYTES, DEVOTIONAL_CSV_TEMPLATE, type AppModule } from '@crosscode/contracts'; +import type { Ctx } from '../context.js'; +import { ApiError, handle, parse, sameOrigin } from '../http.js'; +import { audit, clientIp } from '../lib/audit.js'; +import { isDate } from '../lib/zoned.js'; +import { currentSession, requireRole } from '../auth/sessions.js'; +import { enabledModules } from '../modules.js'; +import { publishOn, syncAll } from '../events/feed.js'; +import { adminEvents, deleteEvent, eventBody, eventByKey, saveEvent, upcoming } from '../events/service.js'; +import { adminAnnouncements, announcementBody, announcementBySlug, currentAnnouncements, saveAnnouncement } from './announcements.js'; +import { + acknowledgements, adminMonth, archive, deleteOwn, devotionalBody, devotionalOn, devotionalStatus, importCsv, saveOwn, setDevotionalSource, SyncError, + syncCrosscode, todaysDevotional, +} from './devotionals.js'; + +const NAMES: Record = { announcements: 'Announcements', devotionals: 'Devotionals', events: 'Events' }; + +function requireModule(ctx: Ctx, module: AppModule): RequestHandler { + return (_req, _res, next) => { + enabledModules(ctx).then((on) => next(on.includes(module) ? undefined : new ApiError(404, 'MODULE_OFF', `${NAMES[module]} are switched off.`))).catch(next); + }; +} + +const signedIn = async (ctx: Ctx, req: Request) => !!(await currentSession(ctx, req)); + +/** Public, briefly cached; private and uncached when the answer depends on being signed in. */ +const cacheFor = (res: express.Response, signed: boolean, seconds = 60) => res.set('Cache-Control', signed ? 'private, no-store' : `public, max-age=${seconds}`); + +const month = z.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/, 'A month as YYYY-MM.'); +const actor = (req: Request) => ({ actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), ip: clientIp(req) }); +const idOf = (v: unknown, what: string) => { + if (typeof v !== 'string' || !/^[0-9a-f-]{36}$/.test(v)) throw new ApiError(404, 'NOT_FOUND', `There's no such ${what}.`); + return v; +}; + +export function contentRouter(ctx: Ctx) { + const r = express.Router(); + + r.use('/v1/announcements', requireModule(ctx, 'announcements')); + r.get('/v1/announcements', handle(async (req, res) => { + const signed = await signedIn(ctx, req); + cacheFor(res, signed); + const campus = typeof req.query.campus === 'string' && /^[a-z0-9-]{1,60}$/.test(req.query.campus) ? req.query.campus : null; + return { announcements: await currentAnnouncements(ctx, signed, { campus }) }; + })); + r.get('/v1/announcements/:slug', handle(async (req, res) => { + const signed = await signedIn(ctx, req); + const a = await announcementBySlug(ctx, String(req.params.slug), signed); + if (!a) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such announcement.'); + cacheFor(res, signed || a.membersOnly); + return { announcement: a }; + })); + + r.use('/v1/devotionals', requireModule(ctx, 'devotionals')); + r.get('/v1/devotionals/today', handle(async (req, res) => { + const signed = await signedIn(ctx, req); + cacheFor(res, signed, 300); + return { devotional: await todaysDevotional(ctx, signed) }; + })); + r.get('/v1/devotionals/acknowledgements', handle(async (_req, res) => { + res.set('Cache-Control', 'public, max-age=3600'); + return { translations: await acknowledgements(ctx) }; + })); + r.get('/v1/devotionals', handle(async (req, res) => { + const m = parse(month, req.query.month); + const signed = await signedIn(ctx, req); + cacheFor(res, signed, 300); + return { month: m, days: await archive(ctx, m, signed) }; + })); + r.get('/v1/devotionals/:date', handle(async (req, res) => { + const d = String(req.params.date); + if (!isDate(d)) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such devotional.'); + const signed = await signedIn(ctx, req); + const devotional = await devotionalOn(ctx, d, signed); + if (!devotional) throw new ApiError(404, 'NOT_FOUND', 'There\'s no devotional for that day.'); + cacheFor(res, signed || devotional.membersOnly, 300); + return { devotional }; + })); + + r.use('/v1/events', requireModule(ctx, 'events')); + r.get('/v1/events', handle(async (_req, res) => { + res.set('Cache-Control', 'public, max-age=60'); + return { events: await upcoming(ctx) }; + })); + r.get('/v1/events/:key', handle(async (req, res) => { + const e = await eventByKey(ctx, String(req.params.key).slice(0, 120)); + if (!e) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such event.'); + res.set('Cache-Control', 'public, max-age=60'); + return { event: e }; + })); + + return r; +} + +const noStore: RequestHandler = (_req, res, next) => { + res.set('Cache-Control', 'no-store'); + next(); +}; + +export function contentAdminRouter(ctx: Ctx) { + const r = express.Router(); + const common = (module: AppModule, roles: Parameters[1]) => [requireModule(ctx, module), sameOrigin(ctx.config.publicUrl, ctx.config.production), requireRole(ctx, roles), noStore]; + const json = express.json({ limit: '64kb' }); + + // ── Announcements ── + r.use('/announcements', ...common('announcements', ['content_admin']), json); + r.get('/announcements', handle(async () => ({ announcements: await adminAnnouncements(ctx) }))); + r.post('/announcements', handle(async (req, res) => { + const a = await saveAnnouncement(ctx, req.signed!.member.id, parse(announcementBody, req.body)); + await audit(ctx, { ...actor(req), action: 'announcement_created', targetType: 'announcement', targetId: a.id }); + res.status(201); + return { id: a.id, slug: a.slug }; + })); + r.put('/announcements/:id', handle(async (req) => { + const id = idOf(req.params.id, 'announcement'); + const a = await saveAnnouncement(ctx, req.signed!.member.id, parse(announcementBody, req.body), id); + await audit(ctx, { ...actor(req), action: 'announcement_changed', targetType: 'announcement', targetId: id }); + return { id: a.id, slug: a.slug }; + })); + r.delete('/announcements/:id', handle(async (req) => { + const id = idOf(req.params.id, 'announcement'); + const { count } = await ctx.db.announcement.deleteMany({ where: { id } }); + if (!count) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such announcement.'); + await audit(ctx, { ...actor(req), action: 'announcement_deleted', targetType: 'announcement', targetId: id }); + return { deleted: true }; + })); + + // ── Events ── + r.use('/events', ...common('events', ['content_admin']), json); + r.get('/events', handle(async () => ({ events: await adminEvents(ctx) }))); + r.post('/events', handle(async (req, res) => { + const e = await saveEvent(ctx, req.signed!.member.id, parse(eventBody, req.body)); + await audit(ctx, { ...actor(req), action: 'event_created', targetType: 'event', targetId: e.id }); + res.status(201); + return { id: e.id, slug: e.slug }; + })); + r.get('/events/feed', handle(async () => { + const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } }, orderBy: { connectedAt: 'asc' } }); + return { + publish: await publishOn(ctx), + links: links.map((l) => ({ installId: l.installId, product: l.product, url: l.url, showEvents: l.showEvents, lastSyncAt: l.lastSyncAt, lastGoodAt: l.lastGoodAt, lastSyncError: l.lastSyncError })), + }; + })); + r.put('/events/feed', handle(async (req) => { + const body = parse(z.object({ publish: z.boolean().optional(), showEvents: z.record(z.string(), z.boolean()).optional() }).strict(), req.body); + if (body.publish !== undefined) await ctx.settings.set('feed_publish', String(body.publish)); + for (const [installId, on] of Object.entries(body.showEvents ?? {})) { + await ctx.db.productLink.updateMany({ where: { installId, product: { not: 'accounts' } }, data: { showEvents: on } }); + } + await audit(ctx, { ...actor(req), action: 'event_feed_changed', targetType: 'settings', targetId: 'feed', metadata: body }); + return { ok: true, sync: await syncAll(ctx) }; + })); + r.post('/events/feed/sync', handle(async () => syncAll(ctx))); + r.put('/events/:id', handle(async (req) => { + const id = idOf(req.params.id, 'event'); + const e = await saveEvent(ctx, req.signed!.member.id, parse(eventBody, req.body), id); + await audit(ctx, { ...actor(req), action: 'event_changed', targetType: 'event', targetId: id }); + return { id: e.id, slug: e.slug }; + })); + r.delete('/events/:id', handle(async (req) => { + const id = idOf(req.params.id, 'event'); + await deleteEvent(ctx, id); + await audit(ctx, { ...actor(req), action: 'event_deleted', targetType: 'event', targetId: id }); + return { deleted: true }; + })); + + // ── Devotionals ── + r.use('/devotionals', ...common('devotionals', ['devotional_writer'])); + r.get('/devotionals/template', (_req, res) => { + res.set({ 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': 'attachment; filename="devotionals-template.csv"' }).send(DEVOTIONAL_CSV_TEMPLATE); + }); + r.post('/devotionals/import', express.text({ type: () => true, limit: DEVOTIONAL_CSV_MAX_BYTES + 1024 }), handle(async (req) => { + const preview = req.query.preview !== 'false'; + const taken = req.query.taken === 'replace' ? 'replace' : 'skip'; + const out = await importCsv(ctx, req.signed!.member.id, typeof req.body === 'string' ? req.body : '', { preview, taken }); + if (!preview && !out.fileError) await audit(ctx, { ...actor(req), action: 'devotionals_imported', targetType: 'devotional', metadata: { imported: out.imported, replaced: out.replaced, skipped: out.skipped } }); + return out; + })); + r.use('/devotionals', json); + r.get('/devotionals/settings', handle(async () => devotionalStatus(ctx))); + r.put('/devotionals/settings', handle(async (req) => { + const { source } = parse(z.object({ source: z.enum(['crosscode', 'church']) }).strict(), req.body); + await setDevotionalSource(ctx, source); + await audit(ctx, { ...actor(req), action: 'devotionals_source_changed', targetType: 'settings', targetId: 'devotionals_source', metadata: { source } }); + if (source === 'crosscode') await syncCrosscode(ctx).catch(() => null); + return devotionalStatus(ctx); + })); + r.post('/devotionals/sync', handle(async () => { + try { + return await syncCrosscode(ctx); + } catch (e) { + if (e instanceof SyncError) throw new ApiError(502, 'SYNC_FAILED', e.message); + throw e; + } + })); + r.get('/devotionals', handle(async (req) => { + const m = parse(month, req.query.month); + const source = req.query.source === 'crosscode' ? 'crosscode' : 'church'; + return { month: m, source, devotionals: await adminMonth(ctx, m, source) }; + })); + r.post('/devotionals', handle(async (req, res) => { + const out = await saveOwn(ctx, req.signed!.member.id, parse(devotionalBody, req.body)); + await audit(ctx, { ...actor(req), action: 'devotional_created', targetType: 'devotional', targetId: out.devotional.id }); + res.status(201); + return out; + })); + r.put('/devotionals/:id', handle(async (req) => { + const id = idOf(req.params.id, 'devotional'); + const out = await saveOwn(ctx, req.signed!.member.id, parse(devotionalBody, req.body), id); + await audit(ctx, { ...actor(req), action: 'devotional_changed', targetType: 'devotional', targetId: id }); + return out; + })); + r.delete('/devotionals/:id', handle(async (req) => { + const id = idOf(req.params.id, 'devotional'); + await deleteOwn(ctx, id); + await audit(ctx, { ...actor(req), action: 'devotional_deleted', targetType: 'devotional', targetId: id }); + return { deleted: true }; + })); + + return r; +} diff --git a/apps/app/backend/src/events/feed.ts b/apps/app/backend/src/events/feed.ts new file mode 100644 index 0000000..0827d54 --- /dev/null +++ b/apps/app/backend/src/events/feed.ts @@ -0,0 +1,164 @@ +/** + * The event feed (APP-1.0-PLAN §7, ROADMAP-v3 §4), both ways, as the Website's (feed/feed.ts there): + * + * - **Publish my events** (AppSetting `feed_publish`, on by default): the App's published simple + * events as `crosscode.event/1` at `GET /api/feed/v1/events?updatedSince=`, with removed ones in + * `deleted` for 90 days. Only events it made itself, never ones it imported (no loops). + * - **Show events from** each linked sibling (`ProductLink.showEvents`): fetched every 15 minutes and + * at once on its signed `event.changed`; read-only copies, the last good copy kept when a fetch + * fails, one bad event skipped without holding up the rest, and only events that really come + * from that sibling. + * - Linked siblings are told (`event.changed`) when one of the App's events changes. + */ +import { EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventSchema, FEED_PATHS, parseEventFeed, type CrosscodeEvent, type EventChanged, type EventFeed } from '@crosscode/contracts'; +import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing'; +import type { Ctx } from '../context.js'; +import { callSibling, siblingUrl } from '../links/http.js'; + +const DAY = 864e5; +export const ENDED_KEEP_DAYS = 30; +export const REMOVED_KEEP_DAYS = 90; +/** Fetch from a little before the last good fetch, so an event saved during it isn't missed. */ +const OVERLAP_MS = 5 * 60 * 1000; + +export const publishOn = (ctx: Ctx) => ctx.settings.bool('feed_publish', true); + +type SimpleRow = { + imageUrl: string | null; + id: string; slug: string; title: string; startsAt: Date; endsAt: Date | null; allDay: boolean; timezone: string; location: string | null; + description: string | null; link: string | null; cancelled: boolean; updatedAt: Date; +}; + +/** One of the App's simple events as `crosscode.event/1`. */ +export function toCrosscodeEvent(ctx: Ctx, e: SimpleRow, installId: string): CrosscodeEvent { + const url = `${ctx.config.publicUrl}/events/${e.slug}`; + const ends = e.endsAt ?? new Date(e.startsAt.getTime() + (e.allDay ? DAY - 60e3 : 2 * 3600e3)); + return { + schema: EVENT_SCHEMA, + id: e.id, + origin: { product: 'app', installId, url }, + status: e.cancelled ? 'cancelled' : 'published', + updatedAt: e.updatedAt.toISOString(), + title: e.title.slice(0, 200), + summary: e.description ? e.description.replace(/\s+/g, ' ').slice(0, 300) : null, + description: e.description, + imageUrl: e.imageUrl, + timezone: e.timezone, + startsAt: e.startsAt.toISOString(), + endsAt: ends.toISOString(), + allDay: e.allDay, + sessions: [], + location: e.location ? { name: e.location.slice(0, 200), address: null, onlineUrl: null } : null, + campus: null, + series: null, + tags: [], + // Only Cross Events takes registrations: a link, or nothing (roadmap decision 4). + registration: e.link ? { mode: 'external', url: e.link, status: 'open', opensAt: null, closesAt: null, priceFrom: null } : { mode: 'none', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null }, + } as CrosscodeEvent; +} + +/** `GET /api/feed/v1/events`: what changed since `since` (everything when null). */ +export async function buildFeed(ctx: Ctx, since: Date | null): Promise { + const now = ctx.now(); + const installId = (await ctx.settings.get('hub_install_id'))!; + const [rows, removals] = await Promise.all([ + ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, startsAt: { gte: new Date(now.getTime() - (ENDED_KEEP_DAYS + 30) * DAY) } }, orderBy: { startsAt: 'asc' } }), + ctx.db.feedRemoval.findMany({ where: { removedAt: { gte: new Date(now.getTime() - REMOVED_KEEP_DAYS * DAY), ...(since ? { gt: since } : {}) } } }), + ]); + const events: CrosscodeEvent[] = []; + for (const row of rows) { + const ends = row.endsAt ?? row.startsAt; + if (ends.getTime() < now.getTime() - ENDED_KEEP_DAYS * DAY) continue; + if (since && row.updatedAt <= since) continue; + const e = toCrosscodeEvent(ctx, row, installId); + // Never publish something the contract refuses. + if (eventSchema.safeParse(e).success) events.push(e); + } + return { schema: EVENT_FEED_SCHEMA, generatedAt: now.toISOString(), events, deleted: removals.map((r) => ({ id: r.eventId, deletedAt: r.removedAt.toISOString() })) }; +} + +/** A simple event left the feed: siblings drop their copy. Back on it (published again): no longer removed. */ +export async function markRemoved(ctx: Ctx, eventId: string, removed: boolean) { + if (removed) await ctx.db.feedRemoval.upsert({ where: { eventId }, create: { eventId, removedAt: ctx.now() }, update: { removedAt: ctx.now() } }); + else await ctx.db.feedRemoval.deleteMany({ where: { eventId } }); +} + +/** Tells every linked sibling (not Accounts) that these events changed. One try; their poll catches up. */ +export async function notifyLinks(ctx: Ctx, eventIds: string[]): Promise<{ told: number; failed: number }> { + if (!eventIds.length || !(await publishOn(ctx))) return { told: 0, failed: 0 }; + const senderId = await ctx.settings.get('hub_install_id'); + if (!senderId) return { told: 0, failed: 0 }; + const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } }); + const body: EventChanged = { schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: ctx.now().toISOString(), eventIds: eventIds.slice(0, 100) }; + const raw = JSON.stringify(body); + let told = 0; + let failed = 0; + await Promise.all(links.map(async (link) => { + try { + const headers = signedHeaders(LINK_HEADERS, { senderId, secret: ctx.secrets.decrypt(link.secret), rawBody: raw }); + await callSibling(await siblingUrl(ctx, link.url, FEED_PATHS.changed), { method: 'POST', body: raw, headers }); + told++; + } catch (e) { + failed++; + console.warn(`[feed] event.changed to ${link.url} failed (its poll will catch up):`, (e as Error).message); + } + })); + return { told, failed }; +} + +type LinkRow = { installId: string; product: string; url: string; showEvents: boolean; lastGoodAt: Date | null }; + +export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; error?: string }; + +/** + * Fetches one sibling's feed into read-only copies. `full` asks for the whole list and drops copies + * no longer in it: a sibling that loses events without listing them in `deleted` (a reseed, a + * restore) would otherwise leave stale copies beside the new ones for good. + */ +export async function syncLink(ctx: Ctx, link: LinkRow, { full = false }: { full?: boolean } = {}): Promise { + if (link.product === 'accounts') return { installId: link.installId, ok: true, imported: 0 }; + if (!link.showEvents) { + const gone = (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId } })).count; + return { installId: link.installId, ok: true, imported: 0, deleted: gone }; + } + const now = ctx.now(); + const since = !full && link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null; + try { + const url = await siblingUrl(ctx, link.url, FEED_PATHS.events); + if (since) url.searchParams.set('updatedSince', since.toISOString()); + const parsed = parseEventFeed(await callSibling(url, { method: 'GET' })); + if (!parsed.ok) throw new Error(`The feed isn't a crosscode.event-feed/1 (${parsed.error.issues.slice(0, 2).map((i) => `${i.path.join('.')} ${i.message}`).join('; ')})`); + const { feed, rejected } = parsed; + for (const r of rejected) console.warn(`[feed] skipped an event from ${link.url} (${r.id ?? `#${r.index}`})`); + // Only events that really come from this sibling: one product can't speak for another. + const theirs = feed.events.filter((e) => e.origin.installId === link.installId && e.origin.product === link.product); + for (const e of theirs) { + const data = { linkId: link.installId, startsAt: new Date(e.startsAt), endsAt: new Date(e.endsAt), data: e as never, syncedAt: now }; + const existing = await ctx.db.importedEvent.findFirst({ where: { originProduct: e.origin.product, originId: e.id } }); + if (existing) await ctx.db.importedEvent.update({ where: { id: existing.id }, data }); + else await ctx.db.importedEvent.create({ data: { ...data, originProduct: e.origin.product, originId: e.id } }); + } + let deleted = 0; + for (const d of feed.deleted) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: d.id } })).count; + // A full fetch is the whole list: anything not in it is gone. + if (!since) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: { notIn: theirs.map((e) => e.id) } } })).count; + await ctx.db.productLink.update({ + where: { installId: link.installId }, + data: { lastSyncAt: now, lastGoodAt: new Date(feed.generatedAt), lastSyncError: rejected.length ? `${rejected.length} event(s) skipped: they don't fit crosscode.event/1` : null }, + }); + return { installId: link.installId, ok: true, imported: theirs.length, deleted, rejected: rejected.length }; + } catch (e) { + const error = String((e as Error)?.message || e).slice(0, 500); + await ctx.db.productLink.update({ where: { installId: link.installId }, data: { lastSyncAt: now, lastSyncError: error } }).catch(() => {}); + return { installId: link.installId, ok: false, error }; + } +} + +/** Every linked sibling's whole list, one after another; one failing never stops the rest. */ +export async function syncAll(ctx: Ctx) { + const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } }); + let failed = 0; + for (const link of links) if (!(await syncLink(ctx, link, { full: true })).ok) failed++; + return { links: links.length, failed }; +} + diff --git a/apps/app/backend/src/events/service.ts b/apps/app/backend/src/events/service.ts new file mode 100644 index 0000000..97f6a80 --- /dev/null +++ b/apps/app/backend/src/events/service.ts @@ -0,0 +1,159 @@ +/** + * Events in the App (APP-1.0-PLAN §7, as WEBSITE-1.0-PLAN §8): **simple events** made here (title, + * when, place, description, image, an optional link; roadmap decision 4) and **the siblings' + * events** from the feed (Cross Events, the Website). One list for members, newest first to come; + * an imported event shows **Register on the Events site** and points its canonical at its origin. + */ +import { z } from 'zod'; +import type { CrosscodeEvent } from '@crosscode/contracts'; +import type { Ctx } from '../context.js'; +import type { SimpleEvent } from '../generated/prisma/client.js'; +import { ApiError } from '../http.js'; +import { churchTimezone } from '../church/profile.js'; +import { slugify, uniqueSlug } from '../lib/slug.js'; +import { isDate, localParts, zonedTime } from '../lib/zoned.js'; +import { markRemoved, notifyLinks } from './feed.js'; + +const DAY = 864e5; + +/** One event as every screen shows it, simple or imported. */ +export type EventItem = { + /** The App's page: the slug for a simple event, `x-` for an imported one. */ + key: string; + source: 'app' | 'events' | 'website'; + title: string; + startsAt: string; + endsAt: string; + allDay: boolean; + timezone: string; + location: string | null; + summary: string | null; + description: string | null; + imageUrl: string | null; + cancelled: boolean; + /** Where to register: the origin's page (Cross Events) or the event's own link; null for none. */ + registration: { label: string; url: string } | null; + /** The origin's page, for `` (imported events only). */ + canonical: string | null; +}; + +export function fromSimple(e: SimpleEvent): EventItem { + const ends = e.endsAt ?? new Date(e.startsAt.getTime() + (e.allDay ? DAY - 60e3 : 2 * 3600e3)); + return { + key: e.slug, source: 'app', title: e.title, startsAt: e.startsAt.toISOString(), endsAt: ends.toISOString(), allDay: e.allDay, timezone: e.timezone, + location: e.location, summary: e.description ? e.description.replace(/\s+/g, ' ').slice(0, 200) : null, description: e.description, + imageUrl: e.imageUrl, cancelled: e.cancelled, registration: e.link ? { label: 'More info', url: e.link } : null, canonical: null, + }; +} + +export function fromImported(copy: { id: string; data: unknown }): EventItem { + const e = copy.data as CrosscodeEvent; + const reg = e.registration; + const fromEvents = e.origin.product === 'events'; + return { + key: `x-${copy.id}`, source: fromEvents ? 'events' : 'website', title: e.title, startsAt: e.startsAt, endsAt: e.endsAt, allDay: e.allDay, timezone: e.timezone, + location: e.location?.name ?? null, summary: e.summary, description: e.description, imageUrl: e.imageUrl, cancelled: e.status === 'cancelled', + // Registering and paying stay on Cross Events (§7). + registration: reg.mode === 'origin' ? { label: fromEvents ? 'Register on the Events site' : 'More info', url: reg.url ?? e.origin.url } + : reg.mode === 'external' && reg.url ? { label: 'More info', url: reg.url } : null, + canonical: e.origin.url, + }; +} + +/** Upcoming events (and those under way), simple and imported, in order. */ +export async function upcoming(ctx: Ctx, opts: { take?: number } = {}): Promise { + const now = ctx.now(); + const shown = (await ctx.db.productLink.findMany({ where: { showEvents: true, product: { not: 'accounts' } }, select: { installId: true } })).map((l) => l.installId); + const [simple, imported] = await Promise.all([ + ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null, lte: now }, startsAt: { gte: new Date(now.getTime() - 14 * DAY) } }, orderBy: { startsAt: 'asc' } }), + ctx.db.importedEvent.findMany({ where: { endsAt: { gte: now }, linkId: { in: shown } }, orderBy: { startsAt: 'asc' } }), + ]); + const items = [...simple.map(fromSimple), ...imported.map(fromImported)].filter((e) => new Date(e.endsAt) >= now); + return items.sort((a, b) => a.startsAt.localeCompare(b.startsAt)).slice(0, opts.take ?? 100); +} + +/** One event's page by its key, or null. */ +export async function eventByKey(ctx: Ctx, key: string): Promise { + if (key.startsWith('x-')) { + const copy = await ctx.db.importedEvent.findUnique({ where: { id: key.slice(2) } }).catch(() => null); + return copy ? fromImported(copy) : null; + } + const e = await ctx.db.simpleEvent.findUnique({ where: { slug: key } }); + return e && e.publishedAt && e.publishedAt <= ctx.now() ? fromSimple(e) : null; +} + +// ── The admin's simple events ── + +const time = z.string().regex(/^\d{2}:\d{2}$/, 'A time as HH:MM.'); +export const eventBody = z.object({ + title: z.string().trim().min(2).max(200), + date: z.string().refine(isDate, 'A date as YYYY-MM-DD.'), + startTime: time.nullable(), + endDate: z.string().refine(isDate, 'A date as YYYY-MM-DD.').nullable().optional(), + endTime: time.nullable().optional(), + location: z.string().trim().max(200).nullable().optional(), + description: z.string().trim().max(10_000).nullable().optional(), + imageUrl: z.string().trim().url().max(500).nullable().optional(), + link: z.string().trim().url().max(500).nullable().optional(), + published: z.boolean().default(true), + cancelled: z.boolean().default(false), +}).strict(); +export type EventInput = z.infer; + +/** Local date and time in the church's timezone to an instant (whole days without a time). */ +async function instants(ctx: Ctx, input: EventInput) { + const tz = await churchTimezone(ctx); + const at = (date: string, t: string | null | undefined) => zonedTime(date, t ? Number(t.slice(0, 2)) * 60 + Number(t.slice(3, 5)) : 0, tz); + const allDay = !input.startTime; + const startsAt = at(input.date, input.startTime); + if (!startsAt) throw new ApiError(400, 'VALIDATION', 'That time doesn\'t exist on that day (the clocks change).', { startTime: 'Pick another time.' }); + let endsAt: Date | null = null; + if (input.endDate || input.endTime) { + endsAt = allDay ? at(input.endDate ?? input.date, '23:59') : at(input.endDate ?? input.date, input.endTime ?? input.startTime); + if (!endsAt || endsAt <= startsAt) throw new ApiError(400, 'VALIDATION', 'The end is before the start.', { endTime: 'The end is before the start.' }); + } + return { allDay, startsAt, endsAt, timezone: tz }; +} + +export async function saveEvent(ctx: Ctx, byId: string, input: EventInput, id?: string) { + const when = await instants(ctx, input); + const data = { + title: input.title, ...when, location: input.location || null, description: input.description || null, imageUrl: input.imageUrl || null, + link: input.link || null, cancelled: input.cancelled, updatedBy: byId, + }; + let row: SimpleEvent; + if (id) { + const before = await ctx.db.simpleEvent.findUnique({ where: { id } }); + if (!before) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such event.'); + row = await ctx.db.simpleEvent.update({ where: { id }, data: { ...data, publishedAt: input.published ? before.publishedAt ?? ctx.now() : null } }); + } else { + const slug = await uniqueSlug(`${slugify(input.title, 50)}-${input.date}`, async (s) => !!(await ctx.db.simpleEvent.findUnique({ where: { slug: s } }))); + row = await ctx.db.simpleEvent.create({ data: { ...data, slug, publishedAt: input.published ? ctx.now() : null } }); + } + await markRemoved(ctx, row.id, !row.publishedAt); + await notifyLinks(ctx, [row.id]); + return row; +} + +export async function deleteEvent(ctx: Ctx, id: string) { + const { count } = await ctx.db.simpleEvent.deleteMany({ where: { id } }); + if (!count) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such event.'); + await markRemoved(ctx, id, true); + await notifyLinks(ctx, [id]); +} + +/** The admin's list: every simple event, newest first, with what the form needs. */ +export async function adminEvents(ctx: Ctx) { + const tz = await churchTimezone(ctx); + const rows = await ctx.db.simpleEvent.findMany({ orderBy: { startsAt: 'desc' }, take: 300 }); + const hm = (m: number) => `${String(Math.floor(m / 60)).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`; + return rows.map((e) => { + const s = localParts(e.startsAt, tz); + const end = e.endsAt ? localParts(e.endsAt, tz) : null; + return { + id: e.id, slug: e.slug, title: e.title, date: s.date, startTime: e.allDay ? null : hm(s.minute), endDate: end?.date ?? null, endTime: end && !e.allDay ? hm(end.minute) : null, + location: e.location, description: e.description, imageUrl: e.imageUrl, link: e.link, published: !!e.publishedAt, cancelled: e.cancelled, + startsAt: e.startsAt.toISOString(), + }; + }); +} diff --git a/apps/app/backend/src/hub/client.ts b/apps/app/backend/src/hub/client.ts index e884834..de6eaeb 100644 --- a/apps/app/backend/src/hub/client.ts +++ b/apps/app/backend/src/hub/client.ts @@ -20,6 +20,7 @@ import { activeMembers } from '../members/activity.js'; import { enabledModules } from '../modules.js'; import { hubPublicKey, verifyToken } from './licence.js'; import { prayerStats } from '../prayer/service.js'; +import { announcementsLast30d } from '../content/announcements.js'; import { jobsHealth } from '../jobs.js'; export const PROTOCOL_VERSION = 2; @@ -76,7 +77,7 @@ export async function health(ctx: Ctx) { /** * Aggregate counts only (hub.appStatsSchema): prayer coverage of the last 7 days and active - * commitments (no names, no times). Announcements and messages are 0 until their modules arrive. + * commitments (no names, no times), announcements published in 30 days. Messages are 0 until §8. */ export async function stats(ctx: Ctx): Promise> { const [{ band }, modules] = await Promise.all([activeMembers(ctx), enabledModules(ctx)]); @@ -84,7 +85,7 @@ export async function stats(ctx: Ctx): Promise Promise }; export const JOBS: Job[] = [ { name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) }, + { name: 'event-feed', label: 'Events from the church\'s other sites (Cross Events, the Website)', cron: '*/15 * * * *', env: 'FEED_JOB_ENABLED', run: (ctx) => syncAll(ctx) }, + { name: 'crosscode-devotionals', label: 'Cross Code\'s devotionals from the Hub (the next 2 weeks)', cron: '15 1 * * *', env: null, run: (ctx) => nightlySync(ctx) }, { name: 'prayer-reminders', label: 'House of Prayer: slot reminders', cron: '* * * * *', env: 'PRAYER_REMINDERS_ENABLED', run: (ctx) => sendReminders(ctx) }, { name: 'prayer-requests-tidy', label: 'Prayer requests: close after their days, delete 12 months after closing', cron: '30 3 * * *', env: null, run: (ctx) => tidyRequests(ctx, DELETE_AFTER_CLOSED_DAYS) }, { name: 'prayer-renewals', label: 'House of Prayer: renewal notices (14 and 3 days before the end)', cron: '0 9 * * *', env: 'PRAYER_RENEWALS_ENABLED', run: (ctx) => sendRenewalNotices(ctx) }, diff --git a/apps/app/backend/src/lib/slug.ts b/apps/app/backend/src/lib/slug.ts new file mode 100644 index 0000000..c068935 --- /dev/null +++ b/apps/app/backend/src/lib/slug.ts @@ -0,0 +1,21 @@ +/** Address-friendly names for pages (announcements, events): lower case, a-z, 0-9 and dashes. */ +export function slugify(text: string, max = 60): string { + const s = text + .normalize('NFKD') + .replace(/[̀-ͯ]/g, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, max) + .replace(/-+$/, ''); + return s || 'item'; +} + +/** `base`, or `base-2`, `base-3`… the first one `taken` says is free. */ +export async function uniqueSlug(base: string, taken: (slug: string) => Promise): Promise { + for (let n = 1; n < 1000; n++) { + const slug = n === 1 ? base : `${base}-${n}`; + if (!(await taken(slug))) return slug; + } + return `${base}-${Date.now()}`; +} diff --git a/apps/app/backend/src/links/routes.ts b/apps/app/backend/src/links/routes.ts index c4df455..653c1e1 100644 --- a/apps/app/backend/src/links/routes.ts +++ b/apps/app/backend/src/links/routes.ts @@ -5,15 +5,19 @@ * POST /links/v1/connect, /disconnect a sibling connects or disconnects * POST /church/v1/changed Accounts: the church profile changed (signed) * - * To come with their modules: the event feed (`/feed/v1/events`, `/feed/v1/changed`, §7) and - * Accounts' "the messaging settings changed" (§8). + * GET /feed/v1/events?updatedSince= the App's events (crosscode.event-feed/1), public + * POST /feed/v1/changed a sibling's events changed: fetch them now (signed) + * + * To come: Accounts' "the messaging settings changed" (§8). */ import express from 'express'; -import { CHURCH_PATHS, churchChangedSchema, LINK_PATHS } from '@crosscode/contracts'; +import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, LINK_PATHS } from '@crosscode/contracts'; import { LINK_HEADERS, verify } from '@crosscode/contracts/signing'; import type { Ctx } from '../context.js'; import { churchChanged } from '../church/profile.js'; import { acceptConnect, acceptDisconnect, LinkError } from './connect.js'; +import { buildFeed, publishOn, syncLink } from '../events/feed.js'; +import { enabledModules } from '../modules.js'; export function linksRouter(ctx: Ctx) { const r = express.Router(); @@ -66,6 +70,33 @@ export function linksRouter(ctx: Ctx) { const raw = express.raw({ type: () => true, limit: '16kb' }); + r.get(FEED_PATHS.events.replace(/^\/api/, ''), async (req, res) => { + try { + if (!(await enabledModules(ctx)).includes('events') || !(await publishOn(ctx))) return say(res, 404, 'FEED_OFF', 'The App doesn\'t publish its events.'); + if (!(await ctx.settings.get('hub_install_id'))) return say(res, 503, 'FEED_UNAVAILABLE', 'The App isn\'t connected to the Hub yet, so it has no feed.'); + const rawSince = typeof req.query.updatedSince === 'string' ? req.query.updatedSince : null; + const since = rawSince ? new Date(rawSince) : null; + if (rawSince && (!since || !Number.isFinite(since.getTime()))) return say(res, 400, 'INVALID_REQUEST', 'updatedSince must be an ISO 8601 date and time.'); + res.set('Cache-Control', 'no-store'); + return res.json(await buildFeed(ctx, since)); + } catch (e) { + return fail(res, e); + } + }); + + r.post(FEED_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => { + try { + const got = await signedBy(req, res); + if (!got) return undefined; + if (!eventChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t an event.changed message.'); + // Fetched after answering: the sibling doesn't wait for it. + if (got.link.showEvents) setImmediate(() => { syncLink(ctx, got.link).catch(() => {}); }); + return res.status(202).json({ accepted: true, fetching: got.link.showEvents }); + } catch (e) { + return fail(res, e); + } + }); + r.post(CHURCH_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => { try { const got = await signedBy(req, res, true); diff --git a/apps/app/backend/tests/content.test.ts b/apps/app/backend/tests/content.test.ts new file mode 100644 index 0000000..85036ba --- /dev/null +++ b/apps/app/backend/tests/content.test.ts @@ -0,0 +1,263 @@ +import { afterEach, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import request from 'supertest'; +import { DEVOTIONAL_CSV_TEMPLATE, DEVOTIONAL_SCHEMA, devotionalCsv, EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventFeedSchema } from '@crosscode/contracts'; +import { stats } from '../src/hub/client.js'; +import { nightlySync, syncCrosscode } from '../src/content/devotionals.js'; +import { syncAll } from '../src/events/feed.js'; +import { cookieHeader, harness, INSTALL_ID, MEMBER, signInAs, type Harness } from './support/harness.js'; + +const EDITOR = '55555555-5555-4555-8555-555555555555'; +const WRITER = '66666666-6666-4666-8666-666666666666'; +const EVENTS_INSTALL = '7b1c2d3e-4f50-4617-8829-3a4b5c6d7e8f'; +const DAY = 864e5; +const realFetch = globalThis.fetch; +afterEach(() => { globalThis.fetch = realFetch; }); + +async function setup(env: Record = {}) { + const h = await harness({ env: { LINKS_ALLOW_PRIVATE: 'true', ...env } }) as Harness; + const as = (cookies: Record) => ({ + get: (path: string) => request(h.app).get(path).set('Cookie', cookieHeader(cookies)), + post: (path: string, body: object | string = {}) => request(h.app).post(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test').send(body), + put: (path: string, body: object) => request(h.app).put(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test').send(body), + del: (path: string) => request(h.app).delete(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test'), + }); + return { + h, + member: as(await signInAs(h, { sub: MEMBER, name: 'Thandi Mokoena' })), + editor: as(await signInAs(h, { sub: EDITOR, name: 'Ruth', roles: ['content_admin'] }, true)), + writer: as(await signInAs(h, { sub: WRITER, name: 'Pastor Sam', roles: ['devotional_writer'] }, true)), + visitor: as({}), + }; +} + +// The clock starts on 1 December 2026, 08:00 in Johannesburg. +const announcement = (over: object = {}) => ({ title: 'Family camp registrations open', body: 'Sign up **this week**.', ...over }); + +describe('announcements', () => { + it('a Content admin publishes; visitors see public ones, members the members-only ones too', async () => { + const { editor, member, visitor } = await setup(); + assert.equal((await member.post('/api/v1/admin/announcements', announcement())).status, 403); + assert.equal((await editor.post('/api/v1/admin/announcements', announcement())).status, 201); + await editor.post('/api/v1/admin/announcements', announcement({ title: 'Leaders meeting', audience: 'members' })); + await editor.post('/api/v1/admin/announcements', announcement({ title: 'Pinned notice', pinned: true })); + const pub = await visitor.get('/api/v1/announcements'); + assert.match(pub.headers['cache-control']!, /public/); + assert.deepEqual(pub.body.announcements.map((a: { title: string }) => a.title), ['Pinned notice', 'Family camp registrations open']); + const mine = await member.get('/api/v1/announcements'); + assert.match(mine.headers['cache-control']!, /private/); + assert.equal(mine.body.announcements.length, 3); + const slug = mine.body.announcements.find((a: { title: string }) => a.title === 'Leaders meeting').slug; + assert.equal((await visitor.get(`/api/v1/announcements/${slug}`)).status, 401); + assert.equal((await member.get(`/api/v1/announcements/${slug}`)).body.announcement.membersOnly, true); + }); + + it('keeps drafts and scheduled ones out until their time, and ended ones out after', async () => { + const { h, editor, visitor } = await setup(); + await editor.post('/api/v1/admin/announcements', announcement({ title: 'Draft', publishAt: null })); + await editor.post('/api/v1/admin/announcements', announcement({ title: 'Later', publishAt: '2026-12-03T06:00:00Z' })); + await editor.post('/api/v1/admin/announcements', announcement({ title: 'Short', endsAt: '2026-12-02T06:00:00Z' })); + assert.deepEqual((await visitor.get('/api/v1/announcements')).body.announcements.map((a: { title: string }) => a.title), ['Short']); + h.clock.add(3 * DAY); + assert.deepEqual((await visitor.get('/api/v1/announcements')).body.announcements.map((a: { title: string }) => a.title), ['Later']); + const list = (await editor.get('/api/v1/admin/announcements')).body.announcements; + assert.deepEqual(Object.fromEntries(list.map((a: { title: string; state: string }) => [a.title, a.state])), { Draft: 'draft', Later: 'live', Short: 'ended' }); + }); + + it('checks the button, the campus and the end', async () => { + const { editor } = await setup(); + const bad = await editor.post('/api/v1/admin/announcements', announcement({ buttonUrl: 'https://example.com' })); + assert.equal(bad.body.error.fields.buttonLabel, 'A button needs both its words and its link.'); + assert.equal((await editor.post('/api/v1/admin/announcements', announcement({ campus: 'north' }))).body.error.fields.campus, 'There\'s no such campus in the church profile.'); + assert.equal((await editor.post('/api/v1/admin/announcements', announcement({ publishAt: '2026-12-05T06:00:00Z', endsAt: '2026-12-04T06:00:00Z' }))).status, 400); + }); + + it('counts the last 30 days in the heartbeat, and is switched off with its module', async () => { + const { h, editor, visitor } = await setup(); + await editor.post('/api/v1/admin/announcements', announcement()); + assert.equal((await stats(h.ctx)).announcements.last30d, 1); + await h.ctx.settings.set('modules', JSON.stringify({ announcements: false })); + assert.equal((await visitor.get('/api/v1/announcements')).body.error.code, 'MODULE_OFF'); + }); +}); + +// ── Devotionals ── + +const hubDay = (date: string, over: object = {}) => ({ + schema: DEVOTIONAL_SCHEMA, id: `0000000${date.slice(-1)}-0000-4000-8000-00000000000${date.slice(-1)}`, source: 'crosscode', updatedAt: '2026-11-30T10:00:00.000Z', + date, title: `Cross Code for ${date}`, body: 'Abide in him.', prayer: null, author: 'Cross Code', + passage: { reference: 'John 15:1-5', location: { book: 'JHN', chapter: 15, verse: 1, endChapter: 15, endVerse: 5 }, translation: 'BSB', text: 'I am the true vine…' }, + ...over, +}); + +function stubHub(days: object[], from = '2026-12-01', to = '2026-12-14') { + const calls: { url: string; auth: string | null }[] = []; + globalThis.fetch = (async (url: string | URL, init?: RequestInit) => { + calls.push({ url: String(url), auth: new Headers(init?.headers).get('authorization') }); + return new Response(JSON.stringify({ schema: DEVOTIONAL_SCHEMA, from, to, devotionals: days, generatedAt: '2026-12-01T00:00:00.000Z' }), { status: 200, headers: { 'Content-Type': 'application/json' } }); + }) as typeof fetch; + return calls; +} + +describe('devotionals', () => { + it('fetches Cross Code\'s 2 weeks from the Hub with the licence, today first in the church\'s timezone', async () => { + const { h, visitor } = await setup(); + await h.ctx.settings.set('hub_licence', 'licence-token'); + const calls = stubHub([hubDay('2026-12-01'), hubDay('2026-12-02')]); + assert.deepEqual(await syncCrosscode(h.ctx), { from: '2026-12-01', to: '2026-12-14', saved: 2, removed: 0 }); + const hubCall = calls.find((c) => c.url.includes('/api/v2/devotionals'))!; + assert.equal(hubCall.url, 'https://hub.crosscode.co.za/api/v2/devotionals?from=2026-12-01'); + assert.equal(hubCall.auth, 'Bearer licence-token'); + const today = (await visitor.get('/api/v1/devotionals/today')).body.devotional; + assert.equal(today.title, 'Cross Code for 2026-12-01'); + assert.equal(today.passage.translationName, 'Berean Standard Bible'); + assert.match(today.passage.copyright, /Berean/); + assert.equal(today.passage.youVersionUrl, 'https://www.bible.com/bible/3034/JHN.15.1-5.BSB'); + // Tomorrow's isn't shown before its day. + assert.equal((await visitor.get('/api/v1/devotionals/2026-12-02')).status, 404); + }); + + it('replaces exactly the fetched days and keeps earlier ones when the Hub is down', async () => { + const { h, visitor } = await setup(); + await h.ctx.settings.set('hub_licence', 'licence-token'); + stubHub([hubDay('2026-12-01'), hubDay('2026-12-02'), hubDay('2026-12-03')]); + await syncCrosscode(h.ctx); + h.clock.add(DAY); + // The Hub removed 3 December: it goes; 1 December stays for the archive. + stubHub([hubDay('2026-12-02', { title: 'Changed in the Hub' })], '2026-12-02', '2026-12-15'); + assert.deepEqual(await syncCrosscode(h.ctx), { from: '2026-12-02', to: '2026-12-15', saved: 1, removed: 1 }); + assert.equal((await visitor.get('/api/v1/devotionals/today')).body.devotional.title, 'Changed in the Hub'); + assert.deepEqual((await visitor.get('/api/v1/devotionals?month=2026-12')).body.days.map((d: { date: string }) => d.date), ['2026-12-02', '2026-12-01']); + globalThis.fetch = (async () => { throw new Error('connect ECONNREFUSED'); }) as typeof fetch; + h.clock.add(DAY); + await assert.rejects(syncCrosscode(h.ctx), /can't be reached/); + // Nothing for 3 December, so today shows the most recent one. + const today = (await visitor.get('/api/v1/devotionals/today')).body.devotional; + assert.deepEqual([today.date, today.today], ['2026-12-02', false]); + }); + + it('never keeps a translation that isn\'t free, nor more than 2 weeks, whatever the Hub sends', async () => { + const { h } = await setup(); + await h.ctx.settings.set('hub_licence', 'licence-token'); + stubHub([hubDay('2026-12-01', { passage: { ...hubDay('2026-12-01').passage, translation: 'NIV' } }), hubDay('2026-12-02')], '2026-12-01', '2027-02-28'); + const out = await syncCrosscode(h.ctx); + assert.deepEqual([out.to, out.saved], ['2026-12-14', 1]); + }); + + it('skips the nightly fetch when the church shows its own', async () => { + const { h, writer } = await setup(); + await writer.put('/api/v1/admin/devotionals/settings', { source: 'church' }); + assert.deepEqual(await nightlySync(h.ctx), { skipped: 'The church shows its own devotionals.' }); + }); + + it('a Devotional writer writes the church\'s own, in the free translations only', async () => { + const { h, writer, visitor, member } = await setup(); + await writer.put('/api/v1/admin/devotionals/settings', { source: 'church' }); + const own = { date: '2026-12-01', title: 'Rest', reference: 'Matt 11:28-30', translation: 'KJV', passageText: 'Come unto me…', body: 'Jesus offers rest.', membersOnly: false }; + assert.equal((await member.post('/api/v1/admin/devotionals', own)).status, 403); + assert.equal((await writer.post('/api/v1/admin/devotionals', { ...own, translation: 'NIV' })).body.error.fields.translation, 'Use KJV or BSB: the others need their publisher\'s permission.'); + assert.equal((await writer.post('/api/v1/admin/devotionals', { ...own, reference: 'Hezekiah 4:1' })).body.error.code, 'VALIDATION'); + const long = await writer.post('/api/v1/admin/devotionals', { ...own, date: '2026-12-02', reference: 'Psalm 119:1-40' }); + assert.match(long.body.warnings[0], /40 verses/); + assert.equal((await writer.post('/api/v1/admin/devotionals', own)).status, 201); + assert.equal((await writer.post('/api/v1/admin/devotionals', own)).body.error.code, 'DATE_TAKEN'); + const today = (await visitor.get('/api/v1/devotionals/today')).body.devotional; + assert.deepEqual([today.source, today.passage.reference, today.passage.youVersionUrl], ['church', 'Matt 11:28-30', 'https://www.bible.com/bible/1/MAT.11.28-30.KJV']); + void h; + }); + + it('keeps a members-only devotional from visitors', async () => { + const { writer, visitor, member } = await setup(); + await writer.put('/api/v1/admin/devotionals/settings', { source: 'church' }); + await writer.post('/api/v1/admin/devotionals', { date: '2026-12-01', title: 'For us', reference: 'John 3:16', translation: 'BSB', passageText: 'For God so loved…', body: 'Body', membersOnly: true }); + assert.equal((await visitor.get('/api/v1/devotionals/today')).body.devotional, null); + assert.equal((await visitor.get('/api/v1/devotionals/2026-12-01')).status, 401); + assert.equal((await member.get('/api/v1/devotionals/today')).body.devotional.title, 'For us'); + }); + + it('imports a CSV: a preview changes nothing; then the valid rows, days already filled replaced or skipped', async () => { + const { h, writer } = await setup(); + const csv = devotionalCsv([ + { date: '2026-12-05', title: 'One', passage: 'John 1:1', translation: 'KJV', passage_text: 'In the beginning…', body: 'Body one' }, + { date: '2026-12-06', title: 'Two', passage: 'John 1:2', translation: 'NIV', passage_text: 'The same…', body: 'Body two' }, + { date: '2026-12-07', title: 'Three', passage: 'John 1:3', translation: 'BSB', passage_text: 'Through him…', body: 'Body three' }, + ]); + await writer.post('/api/v1/admin/devotionals', { date: '2026-12-07', title: 'Old', reference: 'John 1:3', translation: 'BSB', passageText: 'x', body: 'y' }); + const post = (q: string) => writer.post(`/api/v1/admin/devotionals/import${q}`, csv).set('Content-Type', 'text/csv'); + const preview = (await post('')).body; + assert.deepEqual([preview.valid, preview.imported, preview.rows[1].errors.length > 0, preview.rows[2].taken], [2, 0, true, true]); + assert.equal(await h.db.devotional.count({ where: { source: 'church' } }), 1); + const skipped = (await post('?preview=false&taken=skip')).body; + assert.deepEqual([skipped.imported, skipped.skipped], [1, 1]); + const replaced = (await post('?preview=false&taken=replace')).body; + // 5 December was imported by the run before, so both valid rows replace a day now. + assert.deepEqual([replaced.replaced, replaced.imported], [2, 0]); + assert.equal((await h.db.devotional.findUnique({ where: { source_date: { source: 'church', date: '2026-12-07' } } }))!.title, 'Three'); + assert.equal((await writer.get('/api/v1/admin/devotionals/template')).text, DEVOTIONAL_CSV_TEMPLATE); + }); + + it('lists every quoted translation\'s notice for the Acknowledgements page', async () => { + const { writer, visitor } = await setup(); + await writer.post('/api/v1/admin/devotionals', { date: '2026-12-01', title: 'A', reference: 'John 3:16', translation: 'BSB', passageText: 'x', body: 'y' }); + const t = (await visitor.get('/api/v1/devotionals/acknowledgements')).body.translations; + assert.deepEqual(t.map((x: { id: string }) => x.id), ['BSB']); + assert.ok(t[0].acknowledgement.length > 20); + }); +}); + +// ── Events ── + +const event = (over: object = {}) => ({ title: 'Family camp', date: '2026-12-12', startTime: '09:00', endDate: '2026-12-13', endTime: '15:00', location: 'Magaliesberg', description: 'Two days away.', ...over }); + +describe('events', () => { + it('a Content admin adds simple events in the church\'s timezone; drafts stay out', async () => { + const { editor, visitor, member } = await setup(); + assert.equal((await member.post('/api/v1/admin/events', event())).status, 403); + const created = await editor.post('/api/v1/admin/events', event()); + assert.equal(created.status, 201); + assert.equal(created.body.slug, 'family-camp-2026-12-12'); + await editor.post('/api/v1/admin/events', event({ title: 'Not yet', published: false })); + const list = (await visitor.get('/api/v1/events')).body.events; + assert.deepEqual(list.map((e: { title: string }) => e.title), ['Family camp']); + assert.equal(list[0].startsAt, '2026-12-12T07:00:00.000Z'); + assert.equal(list[0].endsAt, '2026-12-13T13:00:00.000Z'); + assert.equal((await visitor.get(`/api/v1/events/${created.body.slug}`)).body.event.location, 'Magaliesberg'); + assert.equal((await editor.post('/api/v1/admin/events', event({ endDate: '2026-12-11' }))).status, 400); + }); + + it('publishes its own events as crosscode.event/1 and lists removals', async () => { + const { h, editor, visitor } = await setup(); + const { id } = (await editor.post('/api/v1/admin/events', event())).body; + const feed = await visitor.get('/api/feed/v1/events'); + assert.equal(feed.status, 200); + const parsed = eventFeedSchema.parse(feed.body); + assert.equal(parsed.events[0]!.schema, EVENT_SCHEMA); + assert.deepEqual(parsed.events[0]!.origin, { product: 'app', installId: INSTALL_ID, url: 'https://app.hope.test/events/family-camp-2026-12-12' }); + await editor.del(`/api/v1/admin/events/${id}`); + assert.deepEqual((await visitor.get('/api/feed/v1/events')).body.deleted.map((d: { id: string }) => d.id), [id]); + await h.ctx.settings.set('feed_publish', 'false'); + assert.equal((await visitor.get('/api/feed/v1/events')).status, 404); + }); + + it('shows Cross Events\' events from the feed with "Register on the Events site" and a canonical', async () => { + const { h, visitor, editor } = await setup(); + await h.db.productLink.create({ data: { installId: EVENTS_INSTALL, product: 'events', url: 'http://events.hope.test', publicKey: 'x', secret: h.ctx.secrets.encrypt('s'), connectedAt: new Date() } }); + const theirs = { + schema: EVENT_SCHEMA, id: '9e8d7c6b-5a49-4382-a716-151413121110', origin: { product: 'events', installId: EVENTS_INSTALL, url: 'http://events.hope.test/events/youth-conference' }, + status: 'published', updatedAt: '2026-11-30T10:00:00.000Z', title: 'Youth conference', summary: 'Three days', description: null, imageUrl: null, + timezone: 'Africa/Johannesburg', startsAt: '2026-12-20T07:00:00.000Z', endsAt: '2026-12-22T15:00:00.000Z', allDay: false, sessions: [], location: null, campus: null, series: null, tags: [], + registration: { mode: 'origin', url: 'http://events.hope.test/events/youth-conference', status: 'open', opensAt: null, closesAt: null, priceFrom: null }, + }; + globalThis.fetch = (async () => new Response(JSON.stringify({ schema: EVENT_FEED_SCHEMA, generatedAt: '2026-12-01T06:00:00.000Z', events: [theirs], deleted: [] }), { status: 200 })) as typeof fetch; + assert.deepEqual(await syncAll(h.ctx), { links: 1, failed: 0 }); + const list = (await visitor.get('/api/v1/events')).body.events; + assert.equal(list[0].title, 'Youth conference'); + assert.deepEqual(list[0].registration, { label: 'Register on the Events site', url: 'http://events.hope.test/events/youth-conference' }); + assert.equal(list[0].canonical, 'http://events.hope.test/events/youth-conference'); + // An imported event is never published again by the App (no loops). + assert.equal((await visitor.get('/api/feed/v1/events')).body.events.length, 0); + // "Show events from" off: the copies go. + await editor.put('/api/v1/admin/events/feed', { showEvents: { [EVENTS_INSTALL]: false } }); + assert.deepEqual((await visitor.get('/api/v1/events')).body.events, []); + }); +}); diff --git a/apps/app/backend/tests/support/memoryDb.ts b/apps/app/backend/tests/support/memoryDb.ts index 02363e6..3db731b 100644 --- a/apps/app/backend/tests/support/memoryDb.ts +++ b/apps/app/backend/tests/support/memoryDb.ts @@ -22,11 +22,15 @@ const DEFAULTS: Record Row> = { outboxMessage: () => ({ sentAt: null, failedAt: null, error: null, attempts: 0 }), prayerRequest: () => ({ visibility: 'team', showName: false, anonymous: false, moderation: 'none', redactedAt: null, redactionNote: null, removedReason: null, moderatedById: null, moderatedAt: null, escalatedAt: null, escalatedById: null, escalationNote: null, closedAt: null }), prayerRequestUpdate: () => ({ authorId: null }), + announcement: () => ({ imageUrl: null, buttonLabel: null, buttonUrl: null, campus: null, audience: 'everyone', pinned: false, publishAt: null, endsAt: null, sendEmail: false, sendWhatsApp: false, sentAt: null, createdById: null }), + devotional: () => ({ originId: null, prayer: null, author: null, membersOnly: false, createdById: null }), + simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageUrl: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }), + importedEvent: () => ({ syncedAt: new Date() }), }; -const KEYS: Record = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' }; +const KEYS: Record = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' }; /** Unique fields: one field, or several together (`@@unique([a, b])`). */ -const UNIQUE: Record = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']] }; -const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign', 'prayerRequest']); +const UNIQUE: Record = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']], devotional: [['source', 'date']], announcement: ['slug'], simpleEvent: ['slug'], importedEvent: [['originProduct', 'originId']] }; +const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign', 'prayerRequest', 'announcement', 'devotional', 'simpleEvent']); /** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */ const RELATIONS: Record> = { member: { sessions: { model: 'session', many: true, key: 'memberId' } }, @@ -101,6 +105,8 @@ function model(name: string, tables: Map>) { }; const findWhere = (where: Row) => { if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null; + // A compound unique (`source_date: { source, date }`) is looked up by its fields. + for (const u of UNIQUE[name] ?? []) if (Array.isArray(u) && where && u.join('_') in where) { const w = where[u.join('_')] as Row; return [...table().values()].find((r) => u.every((f) => v(r[f]) === v(w[f]))) ?? null; } for (const u of UNIQUE[name] ?? []) if (typeof u === 'string' && where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null; return [...table().values()].find((r) => matches(r, where)) ?? null; }; @@ -166,6 +172,7 @@ function model(name: string, tables: Map>) { if (from === 'member') { drop('session', 'memberId'); drop('testimony', 'memberId'); drop('outboxMessage', 'memberId'); drop('prayerRequest', 'memberId'); unset('prayerCommitment', 'memberId'); } if (from === 'prayerCommitment') { drop('prayerSkip', 'commitmentId'); drop('prayedMark', 'commitmentId'); } if (from === 'prayerCampaign') unset('testimony', 'campaignId'); + if (from === 'productLink') drop('importedEvent', 'linkId'); if (from === 'prayerRequest') { drop('prayerRequestUpdate', 'requestId'); drop('requestPrayer', 'requestId'); } }; const withIncludes = (row: Row, include?: Row) => {