diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ecbc52..3b278cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,45 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). +## website@1.11.0 - 2026-12-01 + +Layouts and backgrounds for the other pages' blocks, and a video for the top of the page +(Joshua, 2026-12-01). **Migration** (`Section.background`, nullable). No contracts change. + +- **Website 1.11.0:** each block has its own layout (`BLOCK_VARIANTS`: text, image and text, + quote, call to action) and background in the church's colours; MP4 uploads (up to 20 MB, where + it was filmed taken out) for the hero's Video layout, with a video field in the admin. +- Checked: the Website backend tests (152, three new), the frontend's typecheck and lint, and the + admin, variants and templates e2e suites. + +## website@1.10.0 - 2026-12-01 + +The home page laid out from its editor, and photos that match the layout (Joshua, 2026-12-01). +Frontend only: no migration, no contracts change. + +- **Website 1.10.0:** each homepage section's layout, background, order and showing in Pages → + Home (still under Template and style too); a section offers only the photo fields its layout + shows, with a slot for each photo (1 for Photo, Video and Split, 3 for Collage, none for Text + only), keeping photos for other layouts. +- Checked: the Website frontend's typecheck and lint, and the admin e2e suite (13 tests, one new). + +## events@3.9.0 + website@1.9.0 + accounts@1.10.0 - 2026-12-01 + +The church's details from Accounts on every site, section backgrounds, one colour picker (Joshua, +2026-12-01). No migrations; no contracts change. + +- **Events 3.9.0:** the Accounts profile's name, logo, icon, colours and contact details win over + Events' own settings while Accounts is connected (pages, emails, WhatsApp, PDFs), and Settings + shows them read-only with a link to Accounts. The logo from Accounts is copied for PDFs, and SVG logos + are drawn in PDFs (`svg-to-pdfkit`, new dependency). Fixes Events keeping its old church after a demo scenario load. +- **Website 1.9.0:** a background for each homepage section in the church's colours; "More info" + instead of "Register" for events without registration; the shared colour field in Church + details. +- **Accounts 1.10.0:** the shared colour field in Church profile. +- **`@crosscode/ui` 0.4.0:** `ColourField` and `isHexColour`. +- Checked: Events backend tests (828), Website backend tests (149), typecheck and lint of every + changed app. + ## contracts@1.24.0 - 2026-11-30 Cross Code's devotionals two years ahead, and Apps fetch 2 weeks (Joshua, 2026-11-30). Additive. diff --git a/apps/accounts/CHANGELOG.md b/apps/accounts/CHANGELOG.md index 2451fdc..95c267b 100644 --- a/apps/accounts/CHANGELOG.md +++ b/apps/accounts/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog — Accounts +## [1.10.0] - 2026-12-01 + +No migration, no new .env variables, no backend change. Needs `@crosscode/ui` 0.4.0 (built with +Accounts). + +### Changed + +- **Admin → Church profile:** the main and accent colours use the shared colour field + (`ColourField`, `@crosscode/ui` 0.4.0): a swatch, the hex code to type or paste, a preview, and a + message when the code isn't a colour, as Cross Events' Branding settings. Cross Events 3.9.0 + now takes the church's name, logo, colours and contact details from this profile too. + ## [1.9.0] - 2026-11-30 Needs contracts 1.21.0 and the new shared package `@crosscode/demo` (built with Accounts; the diff --git a/apps/accounts/WHATS-NEW.md b/apps/accounts/WHATS-NEW.md index bd9ed28..0a3812b 100644 --- a/apps/accounts/WHATS-NEW.md +++ b/apps/accounts/WHATS-NEW.md @@ -3,6 +3,13 @@ What each version changes for the church, in plain language (read by the Hub like Cross Events' WHATS-NEW.md; a section shows once its version is tagged). +## 1.10.0 + +- **An easier colour picker** in **Church profile**: pick your main and accent colours, or type or + paste their codes (like #1f4e79), and see them straight away. +- Your Events site (from version 3.9.0) now uses the name, logo, colours and contact details in + your church profile here, as your website does, so you change them in one place. + ## 1.9.0 - **STOP works for every site.** Someone who replies STOP to your church's WhatsApp number gets no diff --git a/apps/accounts/backend/package.json b/apps/accounts/backend/package.json index 50df5a4..7852d2d 100644 --- a/apps/accounts/backend/package.json +++ b/apps/accounts/backend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/accounts-backend", - "version": "1.9.0", + "version": "1.10.0", "description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API", "private": true, "type": "module", diff --git a/apps/accounts/frontend/package.json b/apps/accounts/frontend/package.json index 5d9a72f..9c5069e 100644 --- a/apps/accounts/frontend/package.json +++ b/apps/accounts/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/accounts-frontend", - "version": "1.9.0", + "version": "1.10.0", "private": true, "description": "Cross Code Accounts: the church's sign-in pages, the account page and admin", "scripts": { diff --git a/apps/accounts/frontend/src/app/admin/Admin.tsx b/apps/accounts/frontend/src/app/admin/Admin.tsx index 8428757..58b5f7d 100644 --- a/apps/accounts/frontend/src/app/admin/Admin.tsx +++ b/apps/accounts/frontend/src/app/admin/Admin.tsx @@ -6,7 +6,7 @@ import { AlertTriangle, ArrowRight, Building2, CheckCircle2, ChevronRight, DatabaseBackup, Download, Eye, FileText, KeyRound, Link2, LogIn, Mail, MessageCircle, Play, RefreshCw, ScrollText, Search, ShieldCheck, Timer, UserX, Users, } from "lucide-react"; -import { Button, Checkbox, Field, Notice } from "@crosscode/ui"; +import { Button, Checkbox, ColourField, Field, Notice } from "@crosscode/ui"; import { ADMIN_GROUPS, ADMIN_NAV, AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell"; import { NoticeText } from "@/components/NoticeText"; import { Card, Heading } from "@/components/Panel"; @@ -325,6 +325,8 @@ type ChurchData = { name: string; shortName: string | null; branding: { logoUrl: function Church({ flash }: { flash: Flash }) { const [c, setC] = useState(null); const [fields, setFields] = useState>({}); + // The two colours as typed (ColourField is controlled); the saved ones until changed. + const [colours, setColours] = useState<{ primary?: string; accent?: string }>({}); useExternalEffect(() => { let alive = true; call("GET", "/admin/church").then((r) => { if (alive && r.ok) setC(r.data); }); @@ -344,14 +346,16 @@ function Church({ flash }: { flash: Flash }) { branding: { ...c.branding, logoUrl: nul(f.get("logoUrl")), colours: { primary: f.get("primary"), accent: nul(f.get("accent")) } }, contact: { ...c.contact, email: nul(f.get("email")), phone: nul(f.get("phone")), whatsapp: nul(f.get("whatsapp")) }, }); - if (r.ok) { setC(r.data); setFields({}); flash("success", "Saved. The church's products are told about the change."); } else { setFields(r.error.fields ?? {}); flash("error", r.error.message); } + if (r.ok) { setC(r.data); setFields({}); setColours({}); flash("success", "Saved. The church's products are told about the change."); } else { setFields(r.error.fields ?? {}); flash("error", r.error.message); } }}> -
- - +
+ setColours((x) => ({ ...x, primary }))} + hint="Buttons, links and headings on every site." error={fields["branding.colours.primary"]} /> + setColours((x) => ({ ...x, accent }))} + hint="Highlights and touches beside the main colour." error={fields["branding.colours.accent"]} />
diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index a005d98..538665b 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -5,6 +5,41 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project follows [Semantic Versioning](https://semver.org/). +## [3.9.0] - 2026-12-01 + +No migration, no new settings or environment variables. One new dependency: `svg-to-pdfkit` +0.1.8 (MIT, pure JavaScript; draws SVG logos in PDFs). Works with any Accounts; nothing changes on +a site without Accounts. + +### Fixed + +- **The church's details come from Accounts.** The church profile set only the fonts, corners and + footer, so after a change in Accounts (or a demo scenario loaded on a new church) Events kept its + own old name, logo and colours while the Website showed the new ones. Now, while Accounts is + connected, the profile's name, logo, icon, main and accent colours, email, phone and address win + over `org_name`, `logo_url`, `favicon_url`, `primary_color`, `accent_color`, `org_email`, + `org_phone` and `org_address` everywhere: the public settings (`GET /api/v2/settings`), and + everything that reads the settings cache (emails, WhatsApp, PDFs, 2FA labels). Only what the + profile has: no icon or accent there keeps this site's own. `org_tagline` and `secondary_color` + stay this site's (`src/accounts/church.ts` `churchSettings`, `utils/settingsCache.js` + `setAccountsOverrides`). `church.changed` fetches the profile straight away; disconnecting + Accounts brings the site's own back. The look sent to Accounts on a move stays this site's own + (`getStoredSetting`). +- **PDFs with the church's logo from Accounts.** Tickets, invoices, receipts, certificates and + privacy exports could only draw a logo uploaded here. The logo from Accounts is copied into + `uploads/accounts` (once per address, when the profile arrives or the first PDF needs it; old + copies removed; 2 MB at most; `utils/logoCopy.js`). PNG and JPEG are drawn as pictures and SVG + (the demo churches' logos, and an SVG uploaded here) as shapes with `svg-to-pdfkit` + (`drawLogo`); an SVG never opens a file or address it names. WebP and GIF show the name only. +- A logo address on another `localhost` port (Accounts in development) is no longer rewritten to + the API's address; only this site's own uploads are (`resolveToApiOrigin`). + +### Changed + +- **Settings → Organisation and Branding** show the fields Accounts sets read-only, with a link to + the church profile in Accounts, and never send them back (`GET /api/v2/settings/all` adds + `accounts_managed`, the keys Accounts sets, with Accounts' values). + ## [3.8.0] - 2026-11-30 Needs contracts 1.21.0 and `@crosscode/demo` 1.1.0 (built with Events; the `crosscode` script on diff --git a/apps/events/WHATS-NEW.md b/apps/events/WHATS-NEW.md index c681d99..4282220 100644 --- a/apps/events/WHATS-NEW.md +++ b/apps/events/WHATS-NEW.md @@ -12,6 +12,18 @@ Write for church admins, not developers: no environment variables, endpoints or developer log is CHANGELOG.md. A tagged version without a section here shows "No details given". --> +## 3.9.0 + +- **Your church's name, logo, colours and contact details now come from your church profile in + Accounts**, as they do on your website. Change them once in Accounts and your Events site shows + the change within moments, in its pages, emails and WhatsApp messages too. Before, Events kept + the details it had been given when it was set up. +- In **Site settings → Organisation and Branding**, those details are shown but can't be changed + there any more; a link takes you to your church profile in Accounts. Your tagline and secondary + colour are still set in Events. +- **Tickets, invoices and certificates show your church's logo from Accounts** (PNG, JPEG or + SVG). + ## 3.8.0 - **STOP now means no WhatsApp at all.** Someone who replies STOP to your church's WhatsApp number diff --git a/apps/events/backend/package.json b/apps/events/backend/package.json index ca7656d..980ed05 100644 --- a/apps/events/backend/package.json +++ b/apps/events/backend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/events-backend", - "version": "3.8.0", + "version": "3.9.0", "description": "Event Management System Backend", "main": "src/index.js", "scripts": { @@ -45,6 +45,7 @@ "pg-boss": "^11.1.2", "qrcode": "^1.5.4", "raw-body": "^3.0.0", + "svg-to-pdfkit": "0.1.8", "swagger-ui-dist": "^5.34.0", "tsx": "^4.23.15", "typescript": "^5.9.3", diff --git a/apps/events/backend/src/accounts/church.ts b/apps/events/backend/src/accounts/church.ts index b939f57..1f0bf11 100644 --- a/apps/events/backend/src/accounts/church.ts +++ b/apps/events/backend/src/accounts/church.ts @@ -1,8 +1,11 @@ /** - * The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): the brand - * style (fonts and corners) and what the shared footer shows (service times, address, contact, - * social, the church's other sites). Accounts owns it and serves it publicly at - * `GET /api/church/v1`; this keeps a copy in memory for the public pages (`GET /api/v2/church`). + * The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9). Accounts owns + * it and serves it publicly at `GET /api/church/v1`; this keeps a copy in memory for the public + * pages (`GET /api/v2/church`: the brand style and the shared footer). + * + * The church's own details in it (name, logo, icon, colours, contact details) also win over + * this site's settings of the same name (`churchSettings`, through utils/settingsCache), so a change + * in Accounts (or a new demo church) shows here as it does on the church's Website. * * Fetched again after 10 minutes, or at once when Accounts sends `church.changed` * (`POST /api/church/v1/changed`, src/links/routes.ts). While Accounts can't be reached the last @@ -12,6 +15,11 @@ import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts'; import { accountsLink } from './client'; +/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */ +const { setAccountsOverrides } = require('../utils/settingsCache') as { setAccountsOverrides(map: Record): void }; +const { pdfLogoPath } = require('../utils/logoCopy') as { pdfLogoPath(url: string): Promise }; +/* eslint-enable @typescript-eslint/no-require-imports */ + const FRESH_MS = 10 * 60e3; const RETRY_MS = 60e3; const TIMEOUT_MS = 5000; @@ -20,6 +28,28 @@ type Cached = { url: string; church: Church | null; at: number; ok: boolean }; let cached: Cached | null = null; let pending: Promise | null = null; +/** + * This site's settings that the church profile sets, with its values. Only what the profile has: + * a church without an icon keeps this site's favicon, without an accent its accent colour. + * `secondary_color` and `org_tagline` aren't in the profile, so they stay this site's own. + */ +export function churchSettings(church: Church | null): Record { + if (!church) return {}; + const a = church.contact.address; + const address = a ? [a.line1, a.line2, a.suburb, a.city, a.province, a.postalCode].filter((x) => x && x.trim()).join(', ') : null; + const out: Record = { + org_name: church.name, + logo_url: church.branding.logoUrl, + favicon_url: church.branding.iconUrl, + primary_color: church.branding.colours.primary, + accent_color: church.branding.colours.accent, + org_email: church.contact.email, + org_phone: church.contact.phone, + org_address: address, + }; + return Object.fromEntries(Object.entries(out).filter((e): e is [string, string] => typeof e[1] === 'string' && e[1] !== '')); +} + async function fetchProfile(accountsUrl: string): Promise { const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) }); if (!res.ok) throw new Error(`Accounts answered ${res.status}`); @@ -36,7 +66,12 @@ export async function churchProfile(): Promise { } catch { return cached?.church ?? null; } - if (!link) return null; + if (!link) { + // Disconnected from Accounts: this site's own settings again. + if (cached) cached = null; + setAccountsOverrides({}); + return null; + } const url = link.url; if (cached && cached.url === url && Date.now() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church; if (!pending) { @@ -44,10 +79,14 @@ export async function churchProfile(): Promise { pending = fetchProfile(url) .then((church) => { cached = { url, church, at: Date.now(), ok: true }; + setAccountsOverrides(churchSettings(church)); + // A copy of the logo for PDFs, made now rather than while a ticket is being sent. + if (church.branding.logoUrl) pdfLogoPath(church.branding.logoUrl).catch(() => {}); return church; }, (e: Error) => { console.warn('[church] profile not fetched from Accounts:', e.message); cached = { url, church: last, at: Date.now(), ok: false }; + setAccountsOverrides(churchSettings(last)); return last; }) .finally(() => { pending = null; }); @@ -55,13 +94,23 @@ export async function churchProfile(): Promise { return pending; } -/** `church.changed`: the next `churchProfile()` fetches it again (the last copy is shown meanwhile). */ +/** This site's settings the church profile sets right now (fetching it when it's due). Never throws. */ +export async function churchSettingsNow(): Promise> { + return churchSettings(await churchProfile()); +} + +/** + * `church.changed`: fetched again straight away, so emails and pages that read the settings + * without waiting get the new details within moments (the last copy is used meanwhile). + */ export function churchChanged(): void { if (cached) cached = { ...cached, at: 0 }; + churchProfile().catch(() => {}); } /** Tests: start with nothing. */ export function resetChurchProfile(): void { cached = null; pending = null; + setAccountsOverrides({}); } diff --git a/apps/events/backend/src/accounts/look.ts b/apps/events/backend/src/accounts/look.ts index 884cff7..c6b918f 100644 --- a/apps/events/backend/src/accounts/look.ts +++ b/apps/events/backend/src/accounts/look.ts @@ -7,7 +7,8 @@ import type { ChurchLook } from '@crosscode/contracts'; import { siteUrl } from '../feed/context'; /* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */ -const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise }; +// This site's own values: they fill what Accounts doesn't have, so never Accounts' own (settingsCache). +const { getStoredSetting: getSetting } = require('../utils/settingsCache') as { getStoredSetting(k: string, f?: string): Promise }; /* eslint-enable @typescript-eslint/no-require-imports */ const hex = (v: string) => (/^#[0-9a-fA-F]{6}$/.test(v) ? v : null); diff --git a/apps/events/backend/src/controllers/settingsController.js b/apps/events/backend/src/controllers/settingsController.js index 8ce140c..702ee9d 100644 --- a/apps/events/backend/src/controllers/settingsController.js +++ b/apps/events/backend/src/controllers/settingsController.js @@ -41,11 +41,22 @@ const PUBLIC_KEYS = [ // @desc Get public app settings // @route GET /api/settings // @access Public +// The church's own details from its Accounts profile (name, logo, colours, contact): they win over +// this site's settings of the same name while Accounts is connected (src/accounts/church.ts). +async function fromAccounts() { + try { + return await require('../accounts/church').churchSettingsNow(); + } catch { + return {}; + } +} + const getSettings = async (req, res) => { try { - const rows = await prisma.appSetting.findMany({ where: { key: { in: PUBLIC_KEYS } } }); + const [rows, accounts] = await Promise.all([prisma.appSetting.findMany({ where: { key: { in: PUBLIC_KEYS } } }), fromAccounts()]); const settings = {}; for (const r of rows) settings[r.key] = r.value; + for (const [k, v] of Object.entries(accounts)) if (PUBLIC_KEYS.includes(k)) settings[k] = v; res.json(settings); } catch (e) { res.status(500).json({ message: safeErrorMessage(e) }); @@ -79,6 +90,11 @@ const getAllSettings = async (req, res) => { settings[r.key] = r.value; } } + // What the site uses for the keys Accounts sets, and which they are, so Settings shows them + // read-only with a link to change them in Accounts. + const accounts = await fromAccounts(); + Object.assign(settings, accounts); + settings.accounts_managed = Object.keys(accounts).join(','); res.json(settings); } catch (e) { res.status(500).json({ message: safeErrorMessage(e) }); @@ -96,7 +112,7 @@ const updateSettings = async (req, res) => { } const ops = Object.entries(updates) - .filter(([k, v]) => v !== undefined && v !== null && !PRIVATE_KEYS.has(k)) + .filter(([k, v]) => v !== undefined && v !== null && !PRIVATE_KEYS.has(k) && k !== 'accounts_managed') .map(([key, value]) => { let storedValue = String(value); diff --git a/apps/events/backend/src/utils/certificates.js b/apps/events/backend/src/utils/certificates.js index c335f1a..53b1046 100644 --- a/apps/events/backend/src/utils/certificates.js +++ b/apps/events/backend/src/utils/certificates.js @@ -16,6 +16,7 @@ const fs = require('fs'); const path = require('path'); const PDFDocument = require('pdfkit'); const QRCode = require('qrcode'); +const { drawLogo } = require('./logoCopy'); const prisma = require('../config/db'); const { activeSessions, completionMet, normalizeCertificateConfig, attendanceBySession, groupTickets, TIMEZONE } = require('./sessions'); @@ -189,7 +190,7 @@ function drawTemplate(doc, template, ctx) { doc.rect(0, 0, 28, H).fill(color); doc.rect(28, 0, 6, H).fill(lighten(color, 0.6)); const x = 90; - safeImage(doc, logo, x, 70, { fit: [120, 50] }); + drawLogo(doc, logo, x, 70, { fit: [120, 50] }); doc.font('Helvetica').fontSize(11).fillColor(color).text(branding.name.toUpperCase(), x, 150, { characterSpacing: 2 }); doc.font('Helvetica-Bold').fontSize(36).fillColor('#0f172a').text(title, x, 175, { width: W - x - 80 }); doc.font('Helvetica').fontSize(13).fillColor('#64748b').text('Presented to', x, 260); @@ -202,7 +203,7 @@ function drawTemplate(doc, template, ctx) { if (template === 'church') { doc.rect(0, 0, W, H).fill(lighten(color, 0.94)); doc.rect(30, 30, W - 60, H - 60).lineWidth(1).strokeColor(lighten(color, 0.4)).stroke(); - const hasLogo = safeImage(doc, logo, W / 2 - 50, 55, { fit: [100, 70], align: 'center' }); + const hasLogo = drawLogo(doc, logo, W / 2 - 50, 55, { fit: [100, 70], align: 'center' }); const top = hasLogo ? 150 : 115; doc.font('Times-Italic').fontSize(14).fillColor(color).text(branding.name, 0, top, { width: W, align: 'center' }); doc.font('Times-Bold').fontSize(34).fillColor('#1e293b').text(title, 60, top + 26, { width: W - 120, align: 'center' }); @@ -228,7 +229,7 @@ function drawTemplate(doc, template, ctx) { const y = top ? 48 + rnd() * 50 : 110 + rnd() * (H - 260); doc.circle(x, y, 3 + rnd() * 5).fill(bright[i % bright.length]); } - safeImage(doc, logo, W / 2 - 40, 100, { fit: [80, 50], align: 'center' }); + drawLogo(doc, logo, W / 2 - 40, 100, { fit: [80, 50], align: 'center' }); doc.font('Helvetica-Bold').fontSize(38).fillColor(color).text(title, 100, 165, { width: W - 200, align: 'center' }); doc.font('Helvetica-Bold').fontSize(15).fillColor('#f59e0b').text('Well done,', 0, 230, { width: W, align: 'center' }); doc.font('Helvetica-Bold').fontSize(36).fillColor('#1e293b').text(cert.name, 100, 250, { width: W - 200, align: 'center' }); @@ -244,7 +245,7 @@ function drawTemplate(doc, template, ctx) { for (const [cx, cy] of [[34, 34], [W - 34, 34], [34, H - 34], [W - 34, H - 34]]) { doc.circle(cx, cy, 6).fill(color); } - safeImage(doc, logo, W / 2 - 45, 70, { fit: [90, 55], align: 'center' }); + drawLogo(doc, logo, W / 2 - 45, 70, { fit: [90, 55], align: 'center' }); doc.font('Times-Bold').fontSize(38).fillColor('#1e293b').text(title.toUpperCase(), 60, 150, { width: W - 120, align: 'center', characterSpacing: 1.5 }); doc.font('Times-Italic').fontSize(14).fillColor('#64748b').text('This certificate is proudly presented to', 0, 212, { width: W, align: 'center' }); doc.font('Times-BoldItalic').fontSize(34).fillColor(color).text(cert.name, 60, 236, { width: W - 120, align: 'center' }); diff --git a/apps/events/backend/src/utils/logoCopy.js b/apps/events/backend/src/utils/logoCopy.js new file mode 100644 index 0000000..0a0fa07 --- /dev/null +++ b/apps/events/backend/src/utils/logoCopy.js @@ -0,0 +1,137 @@ +// The logo for PDFs (tickets, invoices, receipts, certificates, privacy exports). PDFs need a file +// on disk. A logo uploaded here already is one; the church's logo from its Accounts profile is an +// address on another site, so a copy is kept in uploads/accounts (one per address, made when the +// profile arrives or the first PDF needs it; older copies are removed). +// +// PNG and JPEG are drawn as pictures; SVG (the demo churches' logos, and many churches') is drawn +// as shapes with svg-to-pdfkit (`drawLogo`). Anything else (WebP, GIF) isn't copied, and the PDFs +// show the church's name without a logo. +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); +const SVGtoPDF = require('svg-to-pdfkit'); +const { UPLOADS_DIR, uploadsDir } = require('./uploads'); + +const MAX_BYTES = 2 * 1024 * 1024; +const TIMEOUT_MS = 5000; +const EXT = { png: 'png', jpeg: 'jpg', svg: 'svg' }; + +/** PNG, JPEG or SVG by the file's own bytes (never by what a server says it is), else null. */ +function logoKind(buf) { + if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png'; + if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpeg'; + const head = buf.subarray(0, 4096).toString('utf8').replace(/^/, '').trimStart(); + if (head.startsWith('<') && /]/i.test(head)) return 'svg'; + return null; +} + +const nameFor = (url) => `logo-${crypto.createHash('sha256').update(url).digest('hex').slice(0, 16)}`; + +/** An outside address the site may fetch the logo from: https, or http while developing. */ +function fetchable(url) { + try { + const u = new URL(url); + return u.protocol === 'https:' || (u.protocol === 'http:' && process.env.NODE_ENV !== 'production'); + } catch { + return false; + } +} + +function existingCopy(url) { + const base = nameFor(url); + for (const ext of Object.values(EXT)) { + const p = path.join(UPLOADS_DIR, 'accounts', `${base}.${ext}`); + if (fs.existsSync(p)) return p; + } + return null; +} + +// Addresses tried lately that gave no usable logo: not fetched again for 10 minutes. +const misses = new Map(); +const MISS_MS = 10 * 60e3; +const pending = new Map(); + +async function download(url) { + const res = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS), redirect: 'follow' }); + if (!res.ok) throw new Error(`answered ${res.status}`); + if (Number(res.headers.get('content-length') || 0) > MAX_BYTES) throw new Error('is larger than 2 MB'); + const buf = Buffer.from(await res.arrayBuffer()); + if (buf.length > MAX_BYTES) throw new Error('is larger than 2 MB'); + const kind = logoKind(buf); + if (!kind) return null; // WebP, GIF…: not drawable in a PDF + const dir = uploadsDir('accounts'); + const base = nameFor(url); + const file = path.join(dir, `${base}.${EXT[kind]}`); + fs.writeFileSync(file, buf); + // The church changed its logo: the copies of the old ones go. + for (const f of fs.readdirSync(dir)) if (f.startsWith('logo-') && !f.startsWith(`${base}.`)) fs.rmSync(path.join(dir, f), { force: true }); + return file; +} + +/** + * The logo as a file a PDF can draw (`drawLogo`), or null. `logoUrl` is the logo_url setting: a + * path on this site (/uploads/…) or the church's logo address from Accounts. Never throws. + */ +async function pdfLogoPath(logoUrl) { + const url = String(logoUrl || '').trim(); + if (!url) return null; + if (!/^https?:\/\//i.test(url)) { + const p = path.join(UPLOADS_DIR, '..', url.replace(/^\//, '')); + try { + return fs.existsSync(p) && logoKind(fs.readFileSync(p)) ? p : null; + } catch { + return null; + } + } + if (!fetchable(url)) return null; + const have = existingCopy(url); + if (have) return have; + const missed = misses.get(url); + if (missed && Date.now() - missed < MISS_MS) return null; + if (!pending.has(url)) { + pending.set(url, download(url) + .catch((e) => { + console.warn(`[logo] the church's logo couldn't be copied for PDFs: ${url} ${e.message}`); + return null; + }) + .then((file) => { + if (!file) misses.set(url, Date.now()); + return file; + }) + .finally(() => pending.delete(url))); + } + return pending.get(url); +} + +/** + * Draws the logo `file` (from pdfLogoPath) at x, y within `fit` [w, h], as doc.image does; centred + * in that box with `align: 'center'`. True when drawn. Never throws. + */ +function drawLogo(doc, file, x, y, { fit, align } = {}) { + if (!file) return false; + try { + if (file.toLowerCase().endsWith('.svg')) { + const [width, height] = fit || [100, 50]; + SVGtoPDF(doc, fs.readFileSync(file, 'utf8'), x, y, { + width, + height, + preserveAspectRatio: align === 'center' ? 'xMidYMid meet' : 'xMinYMid meet', + // Only pictures inside the SVG itself: never a file or address it names. + imageCallback: (link) => (/^data:image\/(png|jpe?g);base64,/i.test(String(link).trim()) ? String(link).replace(/\s+/g, '') : ''), + warningCallback: () => {}, + }); + } else { + doc.image(file, x, y, { fit, ...(align ? { align } : {}) }); + } + return true; + } catch { + return false; + } +} + +/** Tests: forget the addresses that gave nothing. */ +function resetLogoCopies() { + misses.clear(); +} + +module.exports = { pdfLogoPath, drawLogo, resetLogoCopies, logoKind }; diff --git a/apps/events/backend/src/utils/pdfDocs.js b/apps/events/backend/src/utils/pdfDocs.js index f1f78d1..bbb097a 100644 --- a/apps/events/backend/src/utils/pdfDocs.js +++ b/apps/events/backend/src/utils/pdfDocs.js @@ -55,11 +55,8 @@ async function getBranding() { getSetting('logo_url', ''), ]); const url = (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, ''); - let logoPath = null; - if (logoUrl) { - const p = path.join(__dirname, '..', '..', 'public', logoUrl.replace(/^\//, '')); - if (fs.existsSync(p)) logoPath = p; - } + // An uploaded logo, or a copy of the church's logo from Accounts (utils/logoCopy.js). + const logoPath = await require('./logoCopy').pdfLogoPath(logoUrl); return { name, address, email, phone, brandColor: primary || accent || '#1e3a5f', url, logoPath }; } @@ -196,7 +193,7 @@ async function generateReceiptPdf(payment) { const bannerH = 150; doc.rect(0, 0, pageWidth, bannerH).fill(org.brandColor); if (org.logoPath) { - try { doc.image(org.logoPath, marginX, 28, { fit: [36, 36] }); } catch {} + require('./logoCopy').drawLogo(doc, org.logoPath, marginX, 28, { fit: [36, 36] }); } doc.fillColor('#ffffff').font('Helvetica-Bold').fontSize(13).text(org.name, marginX + (org.logoPath ? 46 : 0), 38, { width: 260 }); doc.font('Helvetica-Bold').fontSize(26).text('Payment Receipt', marginX, 68, { width: 320 }); @@ -301,7 +298,7 @@ async function generateInvoicePdf(registration, { paymentUrl = null, totalDue = doc.rect(0, 0, sidebarW, pageHeight).fill('#111827'); let sy = 40; if (org.logoPath) { - try { doc.image(org.logoPath, 28, sy, { fit: [32, 32] }); sy += 0; } catch {} + require('./logoCopy').drawLogo(doc, org.logoPath, 28, sy, { fit: [32, 32] }); } doc.font('Helvetica-Bold').fontSize(12).fillColor('#ffffff').text(org.name, org.logoPath ? 68 : 28, sy + 8, { width: sidebarW - (org.logoPath ? 96 : 56) }); sy += 60; diff --git a/apps/events/backend/src/utils/settingsCache.js b/apps/events/backend/src/utils/settingsCache.js index 1b24bf6..25cbe34 100644 --- a/apps/events/backend/src/utils/settingsCache.js +++ b/apps/events/backend/src/utils/settingsCache.js @@ -17,9 +17,37 @@ let _cache = {}; let _lastFetch = 0; const TTL_MS = 60 * 1000; +/** + * The church's own details from its Accounts profile (src/accounts/church.ts): name, logo, icon, + * colours and contact details. Accounts owns them, so while it's connected they win over this + * site's own settings everywhere (pages, emails, PDFs). Empty without Accounts. + */ +let _fromAccounts = {}; + +/** Set by src/accounts/church.ts whenever it has (or loses) the church profile. */ +function setAccountsOverrides(map) { + _fromAccounts = { ...(map || {}) }; +} + +/** The keys Accounts sets right now, with their values. */ +function accountsOverrides() { + return { ..._fromAccounts }; +} + +/** The church profile is kept fresh as the settings are (it caches itself for 10 minutes). */ +function refreshChurchProfile() { + try { + const p = require('../accounts/church').churchProfile(); + if (p && typeof p.catch === 'function') p.catch(() => {}); + } catch { + // No Accounts code in this context (some tests): the site's own settings stand. + } +} + async function refreshIfStale() { const now = Date.now(); if (now - _lastFetch < TTL_MS && _lastFetch > 0) return; + refreshChurchProfile(); try { const rows = await prisma.appSetting.findMany(); const fresh = {}; @@ -38,6 +66,13 @@ async function refreshIfStale() { * @returns {string} */ function _getSync(key, envFallback = '') { + const a = _fromAccounts[key]; + if (typeof a === 'string' && a !== '') return a; + return _getStoredSync(key, envFallback); +} + +/** This site's own value, ignoring Accounts (for sending this site's look to Accounts, src/accounts/look.ts). */ +function _getStoredSync(key, envFallback = '') { const v = _cache[key]; const raw = (v !== undefined && v !== null && v !== '') ? v : (envFallback || ''); if (ENCRYPTED_KEYS.has(key) && isEncrypted(raw)) { @@ -76,4 +111,10 @@ function invalidate() { refreshIfStale().catch(() => {}); } -module.exports = { getSetting, getSettingSync, warmCache, invalidate, ENCRYPTED_KEYS }; \ No newline at end of file +/** As getSetting, but this site's own value even when Accounts sets the key. */ +async function getStoredSetting(key, envFallback = '') { + await refreshIfStale(); + return _getStoredSync(key, envFallback); +} + +module.exports = { getSetting, getSettingSync, getStoredSetting, warmCache, invalidate, setAccountsOverrides, accountsOverrides, ENCRYPTED_KEYS }; \ No newline at end of file diff --git a/apps/events/backend/tests/churchProfile.test.ts b/apps/events/backend/tests/churchProfile.test.ts index 95a8da7..b4569ad 100644 --- a/apps/events/backend/tests/churchProfile.test.ts +++ b/apps/events/backend/tests/churchProfile.test.ts @@ -37,8 +37,9 @@ const realFetch = global.fetch; beforeAll(() => { global.fetch = (async (url: string) => { + // The logo, copied for PDFs (utils/logoCopy.js): not part of these tests. + if (url !== `https://accounts.hope.test${CHURCH_PATHS.profile}`) return new Response('', { status: 404 }); fetches++; - expect(url).toBe(`https://accounts.hope.test${CHURCH_PATHS.profile}`); const next = answers.shift() ?? 200; if (next === 'down') throw new Error('connect ECONNREFUSED'); return new Response(JSON.stringify(profile), { status: next, headers: { 'content-type': 'application/json' } }); diff --git a/apps/events/backend/tests/churchSettings.test.ts b/apps/events/backend/tests/churchSettings.test.ts new file mode 100644 index 0000000..8bc1db4 --- /dev/null +++ b/apps/events/backend/tests/churchSettings.test.ts @@ -0,0 +1,128 @@ +// The church's own details from Accounts (name, logo, icon, colours, contact) win over this site's +// settings of the same name: on the public settings, in Settings (read-only), and for everything +// that reads them through the settings cache (emails, PDFs). Without Accounts, the site's own stand. +import fs from 'fs'; +import path from 'path'; + +type Link = { installId: string; product: string; url: string; secret: string; updatedAt: Date }; +const mockLinks: Link[] = []; +const mockRows: { key: string; value: string }[] = []; +jest.mock('../src/config/db', () => ({ + productLink: { + findFirst: async ({ where }: { where: { product: string } }) => mockLinks.find((l) => l.product === where.product) ?? null, + }, + appSetting: { + findMany: async (q?: { where?: { key?: { in?: string[] } } }) => mockRows.filter((r) => !q?.where?.key?.in || q.where.key.in.includes(r.key)), + }, +})); + +process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption'; + +import { CHURCH_PATHS } from '@crosscode/contracts'; +import { churchProfile, churchSettings, resetChurchProfile } from '../src/accounts/church'; +import { churchLook } from '../src/accounts/look'; +/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */ +const settingsCache = require('../src/utils/settingsCache'); +const { getSettings, getAllSettings } = require('../src/controllers/settingsController'); +/* eslint-enable @typescript-eslint/no-require-imports */ + +const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples'); +const sample = () => JSON.parse(fs.readFileSync(path.join(SAMPLES, 'church.json'), 'utf8')); +let profile = sample(); +const realFetch = global.fetch; + +beforeAll(() => { + global.fetch = (async (url: string) => { + if (url !== `https://accounts.hope.test${CHURCH_PATHS.profile}`) return new Response('', { status: 404 }); // the logo (logoCopy tests) + return new Response(JSON.stringify(profile), { status: 200, headers: { 'content-type': 'application/json' } }); + }) as typeof fetch; +}); +afterAll(() => { global.fetch = realFetch; }); + +beforeEach(() => { + resetChurchProfile(); + mockLinks.length = 0; + mockRows.length = 0; + mockRows.push( + { key: 'org_name', value: 'Old Demo Church' }, + { key: 'org_tagline', value: 'Our own tagline' }, + { key: 'primary_color', value: '#111111' }, + { key: 'secondary_color', value: '#222222' }, + { key: 'logo_url', value: '/uploads/old-logo.png' }, + ); + settingsCache.invalidate(); + profile = sample(); +}); + +const connectAccounts = () => mockLinks.push({ installId: 'acc', product: 'accounts', url: 'https://accounts.hope.test/', secret: 'x', updatedAt: new Date() }); + +async function call(handler: (req: unknown, res: unknown) => Promise): Promise> { + let body: Record = {}; + await handler({}, { json: (b: Record) => { body = b; }, status() { return this; } }); + return body; +} + +describe("the church's details from Accounts", () => { + test('only what the profile has', () => { + profile.branding.iconUrl = null; + profile.branding.colours.accent = null; + const s = churchSettings(profile); + expect(s.org_name).toBe(profile.name); + expect(s.primary_color).toBe(profile.branding.colours.primary); + expect('favicon_url' in s).toBe(false); + expect('accent_color' in s).toBe(false); + expect(churchSettings(null)).toEqual({}); + }); + + test('without Accounts, the site keeps its own', async () => { + const s = await call(getSettings); + expect(s.org_name).toBe('Old Demo Church'); + expect((await call(getAllSettings)).accounts_managed).toBe(''); + }); + + test("with Accounts, the public settings show the church's, and keep what the profile doesn't set", async () => { + connectAccounts(); + const s = await call(getSettings); + expect(s.org_name).toBe(profile.name); + expect(s.primary_color).toBe(profile.branding.colours.primary); + expect(s.logo_url).toBe(profile.branding.logoUrl); + expect(s.org_tagline).toBe('Our own tagline'); + expect(s.secondary_color).toBe('#222222'); + }); + + test('Settings marks the ones Accounts sets', async () => { + connectAccounts(); + const all = await call(getAllSettings); + expect(all.org_name).toBe(profile.name); + expect(all.accounts_managed.split(',')).toEqual(expect.arrayContaining(['org_name', 'primary_color', 'logo_url'])); + expect(all.accounts_managed.split(',')).not.toContain('secondary_color'); + }); + + test('the settings cache (emails, PDFs) uses them once the profile is in, and the look sent to Accounts stays the site\'s own', async () => { + connectAccounts(); + await settingsCache.warmCache(); + await churchProfile(); + expect(settingsCache.getSettingSync('org_name', 'Cross Code')).toBe(profile.name); + expect(await settingsCache.getStoredSetting('org_name')).toBe('Old Demo Church'); + expect((await churchLook()).name).toBe('Old Demo Church'); + }); + + test('a church that changes its name in Accounts (a new demo church) is shown after church.changed', async () => { + connectAccounts(); + await churchProfile(); + profile.name = 'Grace Fellowship'; + // eslint-disable-next-line @typescript-eslint/no-require-imports + require('../src/accounts/church').churchChanged(); + await churchProfile(); + expect(settingsCache.getSettingSync('org_name')).toBe('Grace Fellowship'); + expect((await call(getSettings)).org_name).toBe('Grace Fellowship'); + }); + + test('disconnected from Accounts: back to the site\'s own', async () => { + connectAccounts(); + await churchProfile(); + mockLinks.length = 0; + await churchProfile(); + expect(settingsCache.getSettingSync('org_name')).toBe('Old Demo Church'); + }); +}); diff --git a/apps/events/backend/tests/logoCopy.test.ts b/apps/events/backend/tests/logoCopy.test.ts new file mode 100644 index 0000000..f5b78e7 --- /dev/null +++ b/apps/events/backend/tests/logoCopy.test.ts @@ -0,0 +1,126 @@ +// The logo for PDFs: an uploaded one is used as it is; the church's logo from Accounts (an address +// on another site) is copied into uploads/accounts once, when it's a PNG, JPEG or SVG; drawLogo +// draws either kind into a PDF. +import fs from 'fs'; +import path from 'path'; + +/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */ +const { pdfLogoPath, drawLogo, resetLogoCopies } = require('../src/utils/logoCopy') as { + pdfLogoPath(u: string): Promise; + drawLogo(doc: unknown, file: string | null, x: number, y: number, o?: { fit?: [number, number]; align?: string }): boolean; + resetLogoCopies(): void; +}; +const PDFDocument = require('pdfkit'); +const { UPLOADS_DIR } = require('../src/utils/uploads') as { UPLOADS_DIR: string }; +/* eslint-enable @typescript-eslint/no-require-imports */ + +const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(32)]); +const SVG = Buffer.from('\n'); +const WEBP = Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WEBPVP8 ')]); +const COPIES = path.join(UPLOADS_DIR, 'accounts'); +const realFetch = global.fetch; +let served: Record = {}; +let fetched: string[] = []; + +beforeAll(() => { + global.fetch = (async (url: string) => { + fetched.push(url); + const body = served[url]; + if (body === undefined || typeof body === 'number') return new Response('', { status: typeof body === 'number' ? body : 404 }); + return new Response(new Uint8Array(body), { status: 200 }); + }) as typeof fetch; +}); +afterAll(() => { + global.fetch = realFetch; + fs.rmSync(COPIES, { recursive: true, force: true }); +}); +beforeEach(() => { + fs.rmSync(COPIES, { recursive: true, force: true }); + resetLogoCopies(); + served = {}; + fetched = []; + jest.spyOn(console, 'warn').mockImplementation(() => {}); +}); +afterEach(() => { jest.restoreAllMocks(); }); + +function pdfOf(draw: (doc: unknown) => void): Promise { + return new Promise((resolve) => { + const doc = new PDFDocument({ compress: false }); + const parts: Buffer[] = []; + doc.on('data', (b: Buffer) => parts.push(b)); + doc.on('end', () => resolve(Buffer.concat(parts).toString('latin1'))); + draw(doc); + doc.end(); + }); +} + +test("the church's PNG logo from Accounts is copied once, and used from the copy after", async () => { + served['https://accounts.hope.test/logo.png'] = PNG; + const p = await pdfLogoPath('https://accounts.hope.test/logo.png'); + expect(p && path.dirname(p)).toBe(COPIES); + expect(fs.readFileSync(p!)).toEqual(PNG); + expect(await pdfLogoPath('https://accounts.hope.test/logo.png')).toBe(p); + expect(fetched).toHaveLength(1); +}); + +test('a new logo replaces the copy of the old one', async () => { + served['https://accounts.hope.test/old.png'] = PNG; + served['https://accounts.hope.test/new.png'] = PNG; + const old = await pdfLogoPath('https://accounts.hope.test/old.png'); + const next = await pdfLogoPath('https://accounts.hope.test/new.png'); + expect(next).not.toBe(old); + expect(fs.existsSync(old!)).toBe(false); + expect(fs.readdirSync(COPIES)).toHaveLength(1); +}); + +test("an SVG logo (the demo churches') is copied too", async () => { + served['https://accounts.hope.test/logo.svg'] = SVG; + const p = await pdfLogoPath('https://accounts.hope.test/logo.svg'); + expect(p?.endsWith('.svg')).toBe(true); +}); + +test("a logo a PDF can't draw, or one that can't be fetched, gives none (the PDF shows the name), and isn't fetched again at once", async () => { + served['https://accounts.hope.test/logo.webp'] = WEBP; + served['https://accounts.hope.test/gone.png'] = 404; + expect(await pdfLogoPath('https://accounts.hope.test/logo.webp')).toBeNull(); + expect(await pdfLogoPath('https://accounts.hope.test/gone.png')).toBeNull(); + expect(await pdfLogoPath('https://accounts.hope.test/logo.webp')).toBeNull(); + expect(fetched).toHaveLength(2); +}); + +test('drawLogo draws an SVG logo as shapes in its colours, and never opens a file the SVG names', async () => { + fs.mkdirSync(COPIES, { recursive: true }); + const file = path.join(COPIES, 'logo-test.svg'); + fs.writeFileSync(file, SVG); + let drawn = false; + const pdf = await pdfOf((doc) => { drawn = drawLogo(doc, file, 40, 40, { fit: [60, 60], align: 'center' }); }); + expect(drawn).toBe(true); + expect(pdf).toMatch(/0\.12156\d* 0\.30588\d* 0\.47450\d* scn/); // #1f4e79 + + const picture = path.join(COPIES, 'logo-test.png'); + fs.writeFileSync(picture, PNG); + const sneaky = path.join(COPIES, 'logo-sneaky.svg'); + const href = picture.split(path.sep).join('/'); + fs.writeFileSync(sneaky, ``); + const out = await pdfOf((doc) => { drawLogo(doc, sneaky, 0, 0, { fit: [10, 10] }); }); + expect(out).not.toContain('/Subtype /Image'); +}); + +test("drawLogo gives false, without throwing, for a file it can't draw", async () => { + fs.mkdirSync(COPIES, { recursive: true }); + const bad = path.join(COPIES, 'logo-bad.png'); + fs.writeFileSync(bad, 'not a picture'); + let drawn = true; + await pdfOf((doc) => { drawn = drawLogo(doc, bad, 0, 0, { fit: [10, 10] }); }); + expect(drawn).toBe(false); + expect(drawLogo({}, null, 0, 0)).toBe(false); +}); + +test('a logo uploaded here is used as it is; nothing for no logo', async () => { + fs.mkdirSync(COPIES, { recursive: true }); + fs.writeFileSync(path.join(COPIES, 'own.png'), PNG); + expect(await pdfLogoPath('/uploads/accounts/own.png')).toBe(path.join(COPIES, 'own.png')); + expect(await pdfLogoPath('')).toBeNull(); + expect(await pdfLogoPath('/uploads/accounts/missing.png')).toBeNull(); + expect(fetched).toHaveLength(0); +}); diff --git a/apps/events/frontend/package.json b/apps/events/frontend/package.json index 6715bd9..47f4fce 100644 --- a/apps/events/frontend/package.json +++ b/apps/events/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/events-frontend", - "version": "3.8.0", + "version": "3.9.0", "private": true, "scripts": { "dev": "next dev", diff --git a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx index 4845ebf..7ed6fcd 100644 --- a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx @@ -26,6 +26,7 @@ import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { uploadImage } from "@/lib/eventSetup"; import { useExternalEffect } from "@/lib/hooks"; +import { useChurch } from "@/contexts/ChurchContext"; type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "signin" | "backups" | "jobs" | "licence" | "ai"; @@ -48,7 +49,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [ ]; const inputCls = - "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400"; + "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400 disabled:bg-gray-50 disabled:text-gray-500"; /** The code from Search Console's verification meta tag; accepts the whole tag or just the code. */ function googleVerificationCode(input: string): string { @@ -56,6 +57,20 @@ function googleVerificationCode(input: string): string { return (m ? m[1] : input).trim(); } +/** + * Shown above Organisation and Branding while the church's Accounts sets some of their fields: + * those come from the church profile (on all the church's sites) and are changed there. + */ +function FromAccountsNotice({ what, href }: { what: string; href: string | null }) { + return ( +
+ Your church's {what} come from its church profile in Accounts, so every one of its sites shows the same. + They can't be changed here.{" "} + {href ? Change them in Accounts ↗ : "Change them in Accounts, under Church profile."} +
+ ); +} + function Field({ label, hint, required, children, }: { @@ -146,6 +161,14 @@ function SiteSettingsPageInner() { const [faviconPreview, setFaviconPreview] = useState(null); const faviconRef = useRef(null); + // ── From Accounts ── the settings the church profile sets (name, logo, colours, contact): shown, + // not editable, and never sent back. The church profile's own page in Accounts changes them. + const [managed, setManaged] = useState>(new Set()); + const church = useChurch(); + const accountsChurchUrl = church ? `${church.links.accounts.replace(/\/+$/, "")}/admin/church` : null; + const fromAccounts = (key: string) => managed.has(key); + const ownOnly = (updates: Record) => Object.fromEntries(Object.entries(updates).filter(([k]) => !managed.has(k))); + // ── Notifications ── const [notifEmails, setNotifEmails] = useState(""); @@ -206,6 +229,7 @@ function SiteSettingsPageInner() { setLegalEffectiveDate(s.legal_effective_date || ""); setConsentRetentionDays(s.consent_medical_retention_days || "30"); setNotifyOnImpersonation(s.notify_user_on_impersonation === "true"); + setManaged(new Set((s.accounts_managed || "").split(",").filter(Boolean))); }) .catch((e: unknown) => setResult({ ok: false, message: errorMessage(e) || "Failed to load settings" })) .finally(() => setLoadingInitial(false)); @@ -220,7 +244,7 @@ function SiteSettingsPageInner() { setSaving(true); setResult(null); try { - await apiV2Data("put", "/settings", { authToken: token, body: updates }); + await apiV2Data("put", "/settings", { authToken: token, body: ownOnly(updates) }); setResult({ ok: true, message: "Saved." }); reloadSettings(); } catch (e) { @@ -271,13 +295,13 @@ function SiteSettingsPageInner() { await apiV2Data("put", "/settings", { authToken: token, - body: { + body: ownOnly({ primary_color: primaryColor, secondary_color: secondaryColor, accent_color: accentColor, logo_url: finalLogoUrl, favicon_url: finalFaviconUrl, - }, + }), }); setLogoUrl(finalLogoUrl); setLogoFile(null); @@ -303,13 +327,13 @@ function SiteSettingsPageInner() { try { await apiV2Data("put", "/settings", { authToken: token, - body: { primary_color: "", secondary_color: "", accent_color: "", logo_url: "", favicon_url: "" }, + body: ownOnly({ primary_color: "", secondary_color: "", accent_color: "", logo_url: "", favicon_url: "" }), }); - setPrimaryColor("#4F46E5"); + if (!fromAccounts("primary_color")) setPrimaryColor("#4F46E5"); setSecondaryColor("#8B5CF6"); - setAccentColor("#EC4899"); - setLogoUrl(""); setLogoFile(null); setLogoPreview(null); - setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); + if (!fromAccounts("accent_color")) setAccentColor("#EC4899"); + if (!fromAccounts("logo_url")) { setLogoUrl(""); setLogoFile(null); setLogoPreview(null); } + if (!fromAccounts("favicon_url")) { setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); } setSuggestedColors([]); setResult({ ok: true, message: "Reset to defaults." }); reloadSettings(); @@ -433,9 +457,10 @@ function SiteSettingsPageInner() { {activeTab === "organisation" && (

Organisation details

+ {["org_name", "org_email", "org_phone", "org_address"].some(fromAccounts) && } setOrgName(e.target.value)} /> + value={orgName} disabled={fromAccounts("org_name")} onChange={e => setOrgName(e.target.value)} /> setOrgEmail(e.target.value)} /> + value={orgEmail} disabled={fromAccounts("org_email")} onChange={e => setOrgEmail(e.target.value)} /> setOrgPhone(e.target.value)} /> + value={orgPhone} disabled={fromAccounts("org_phone")} onChange={e => setOrgPhone(e.target.value)} />
setOrgAddress(e.target.value)} /> + value={orgAddress} disabled={fromAccounts("org_address")} onChange={e => setOrgAddress(e.target.value)} /> {orgAddress.trim() && ( @@ -477,14 +502,15 @@ function SiteSettingsPageInner() { {activeTab === "branding" && (

Branding

+ {["primary_color", "accent_color", "logo_url", "favicon_url"].some(fromAccounts) && }
+ value={primaryColor} onChange={setPrimaryColor} disabled={fromAccounts("primary_color")} /> + value={accentColor} onChange={setAccentColor} disabled={fromAccounts("accent_color")} />
@@ -492,16 +518,16 @@ function SiteSettingsPageInner() {
{/* eslint-disable-next-line @next/next/no-img-element */} Current logo - + }
)} - handleLogoFileChange(e.target.files?.[0])} className="text-sm" /> + {!fromAccounts("logo_url") && handleLogoFileChange(e.target.files?.[0])} className="text-sm" />} {suggestedColors.length > 0 && (

Suggested from your logo — click a swatch to apply it

@@ -524,21 +550,21 @@ function SiteSettingsPageInner() {
{/* eslint-disable-next-line @next/next/no-img-element */} Current favicon - + }
)} - { + {!fromAccounts("favicon_url") && { const file = e.target.files?.[0]; if (!file) return; setFaviconFile(file); setFaviconPreview(URL.createObjectURL(file)); - }} className="text-sm" /> + }} className="text-sm" />}
diff --git a/apps/events/frontend/src/components/admin/ColorPickerField.tsx b/apps/events/frontend/src/components/admin/ColorPickerField.tsx index 5e6e678..61a3986 100644 --- a/apps/events/frontend/src/components/admin/ColorPickerField.tsx +++ b/apps/events/frontend/src/components/admin/ColorPickerField.tsx @@ -5,12 +5,14 @@ import { isValidHex } from "@/lib/colorScale"; /** A native color swatch + hex text input, shared by the admin Branding tab and the setup wizard's Branding step. */ export function ColorPickerField({ - label, hint, value, onChange, + label, hint, value, onChange, disabled, }: { label: string; hint?: string; value: string; onChange: (hex: string) => void; + /** Set elsewhere (the church profile in Accounts): shown, not changed here. */ + disabled?: boolean; }) { const valid = isValidHex(value); return ( @@ -19,13 +21,15 @@ export function ColorPickerField({
onChange(e.target.value)} /> onChange(e.target.value)} /> diff --git a/apps/events/frontend/src/lib/api.ts b/apps/events/frontend/src/lib/api.ts index 284164b..3715bdf 100644 --- a/apps/events/frontend/src/lib/api.ts +++ b/apps/events/frontend/src/lib/api.ts @@ -52,15 +52,18 @@ function computeApiBase(): string { export const API_BASE = computeApiBase(); // Resolve a URL or path to use the API origin. If it's a relative path, prefix with API_BASE. -// If it's an absolute URL but points to localhost/127.0.0.1/::1, rewrite its origin to API_BASE. +// If it's an absolute URL to this site's own uploads on localhost/127.0.0.1/::1, rewrite its +// origin to API_BASE. Another localhost address (the church's Accounts in development, whose logo +// the site now shows) is left as it is. export function resolveToApiOrigin(urlOrPath: string | null | undefined): string | null { const raw = (urlOrPath || "").trim(); if (!raw) return null; try { if (raw.startsWith("http")) { const u = new URL(raw); - const isLocal = ["localhost", "127.0.0.1", "::1"].includes(u.hostname); - if (isLocal && API_BASE) { + const isLocal = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(u.hostname); + const ownUpload = /^\/(api\/)?uploads\//.test(u.pathname); + if (isLocal && ownUpload && API_BASE) { const api = new URL(API_BASE); u.protocol = api.protocol; u.hostname = api.hostname; diff --git a/apps/website/CHANGELOG.md b/apps/website/CHANGELOG.md index ce6cedb..4949204 100644 --- a/apps/website/CHANGELOG.md +++ b/apps/website/CHANGELOG.md @@ -1,5 +1,85 @@ # Changelog — Church Website +## [1.11.0] — 2026-12-01 + +**Migration** `20261201000000_block_background` (adds the nullable `Section.background`; nothing +to fill in). No new environment settings. + +### Added + +- **Block layouts** (`BLOCK_VARIANTS` in `src/site/variants.ts`): text `standard` · `centred`; + image and text `image-left` · `image-right` · `image-above`; quote `centred` · `line`; call to + action `centred` · `banner`. Stored on the block (`Section.variant`, which blocks had but never + used); `PUT /pages/:id/blocks/:sid` refuses an id that isn't the type's. The snapshot draws an + unknown or missing one as the type's default (`blockVariant`), which is how every block looked + before, so nothing changes until a church picks one. The demo's image-and-text block had the id + `image-text`; it's now `image-left`. +- **A block's own background** (`Section.background`, one of `SECTION_BACKGROUNDS` or null), set + with the same endpoint and carried to the snapshot's section, where the site draws it as the + homepage's (`data-bg`). The published source lists it only when set, so earlier versions compare + equal; Discard and Restore put it back. +- **Videos in the media library:** `POST /media` takes an MP4 (sniffed by its `ftyp` box) up to + 20 MB (`MAX_VIDEO_BYTES`, under the installers' nginx `client_max_body_size 25m`) and keeps it + as uploaded, with no other sizes, counted towards storage. QuickTime (`.mov`) is refused with a + message to export MP4. Its metadata boxes (`udta`, `meta`, `uuid` in the file and its tracks) + are turned into `free` boxes of the same size, zeroed (`cleanVideo`), so where it was filmed is + gone and the offsets to the frames hold. Width and height come from the first track's `tkhd`. + `GET /media` lists each item's `mime`. +- **Admin:** a block, when open, has its Layout and Background (saved straight away); the hero has + a Video field for the Video layout, which only offers videos (photo fields only offer photos); + the media library shows videos and takes them. + +### Changed + +- A request larger than the upload limit says so ("photos can be up to 15 MB and videos up to 20 + MB") instead of "That request isn't valid." + +## [1.10.0] — 2026-12-01 + +No migration, no new environment settings, no backend change. + +### Added + +- **The home page's layouts in its editor** (Pages → Home): each section's layout and background + when it's open, and move up, move down and show or hide on its header. They save straight to + the design (`PUT /design`), as under Template and style → Home page layout, which keeps them too; + the preview reloads on either a page or a design change. The layout and background lists are + shared in `frontend/src/admin/layouts.ts`. + +### Changed + +- **A section's photo fields follow its layout.** `DataForm` takes the section's `layout`; a + field's `layouts` limits it to some (Welcome's photo: Image and text; its pastor: With pastor; + the Invitation's photo: Image background), and a photo list's `count` gives a slot for each photo + the layout shows, chosen or not (the hero: 1 for Photo, Video and Split, 3 for Collage, none for + Text only). Photos past the slots stay saved for a layout that shows more. +- The e2e test opens the hero with `/^Top of the page/` (the new buttons' names contain it), and a + new test covers the layout, background, order and showing from the editor. + +## [1.9.0] — 2026-12-01 + +No migration, no new environment settings. Needs `@crosscode/ui` 0.4.0 (built with the Website). + +### Added + +- **A background for each homepage section** (Template and style → Home page layout), from the + church's colours: as the style sets it (the default), white, soft main colour, soft accent + colour, main colour, or deep main colour. Stored on the design's home entry (`background`, + `SECTION_BACKGROUNDS` in `src/site/variants.ts`), kept through a template switch, checked by + `cleanDesign`, and carried to the snapshot's section. On the main colour, text, links and + buttons use the palette's on-brand colour; on the deep shade, white. A layout with its own + background (`cc-own-bg`: a photo, a band) and the top of the page keep theirs; Section colour's + tinted and mixed patterns skip a section that has its own. + +### Changed + +- **Events from Cross Events** say "Register on our Events site" only when they take + registrations and are open; contact-only, full or closed ones say "More info on our Events + site". The site's events carry the registration's `mode`. +- **Church details:** the main and accent colours use the shared colour field (`ColourField`, + `@crosscode/ui` 0.4.0): a swatch, the hex code to type or paste, and a preview, as Cross Events' + Branding settings. + ## [1.8.0] — 2026-11-30 No migration, no new environment settings. The backend now uses `@crosscode/demo` (built by diff --git a/apps/website/WHATS-NEW.md b/apps/website/WHATS-NEW.md index afd93b0..f6f87a2 100644 --- a/apps/website/WHATS-NEW.md +++ b/apps/website/WHATS-NEW.md @@ -3,6 +3,41 @@ What each version changes for the church, in plain language (read by the Hub like Cross Events' WHATS-NEW.md; a section shows once its version is tagged). +## 1.11.0 + +- **Layouts and backgrounds for the blocks on your other pages.** Open a block in **Pages** to + choose how it looks: text standard or centred; a photo on the left, on the right or above the + text; a quote centred or with a line beside it; a call to action centred or as a banner in your + colour. Each block can also have its own background in your church's colours, like the home + page's sections. +- **A video for the top of your home page.** Choose the **Video** layout and upload a short MP4 + clip (up to 20 MB; 10 to 20 seconds is plenty). It plays muted, on a loop, over your still + photo; phones and visitors who prefer less motion see the still photo. Like photos, the place a + video was filmed is taken out of it when you upload it. + +## 1.10.0 + +- **Lay out your home page while you edit it.** In **Pages → Home**, open a section to choose its + layout and background right there. Use the arrows to move a section up or down, and the eye to + show or hide it. No more switching back and forth to **Template and style** (it still has the + same settings, if you prefer it there). +- **The photos match the layout.** A section now asks for exactly the photos its layout shows: one + for Photo and Split, three for Collage, none for Text only. The Welcome's photo and the pastor's + photo and quote, and the Invitation's background photo, only appear for the layouts that use + them. Photos you added for another layout are kept, so switching back brings them back. + +## 1.9.0 + +- **Choose a background for each homepage section.** In **Template and style → Home page layout**, + each section now has a background in your church's colours: white, a soft wash of your main or + accent colour, your main colour, or a deep shade of it. Text and buttons change to stay easy to + read. Leave it as it is and the section follows your style's section colour, as before. +- **Events say "More info" when there's nothing to register for.** An event from your Events site + only says "Register on our Events site" when people can register; events where people just + contact the church say "More info on our Events site". +- **An easier colour picker** in **Church details**: pick a colour, or type or paste its code + (like #1f4e79), and see it straight away. + ## 1.8.0 - Behind the scenes, Cross Code's demonstration websites can now be loaded as part of a whole demo diff --git a/apps/website/backend/package.json b/apps/website/backend/package.json index c76683a..cf9fd1e 100644 --- a/apps/website/backend/package.json +++ b/apps/website/backend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/website-backend", - "version": "1.8.0", + "version": "1.11.0", "description": "Church Website: the public site's content API, the admin API, publishing and uploads", "private": true, "type": "module", diff --git a/apps/website/backend/prisma/migrations/20261201000000_block_background/migration.sql b/apps/website/backend/prisma/migrations/20261201000000_block_background/migration.sql new file mode 100644 index 0000000..0d92976 --- /dev/null +++ b/apps/website/backend/prisma/migrations/20261201000000_block_background/migration.sql @@ -0,0 +1,2 @@ +-- A block's own background, in the church's colours (Website 1.11.0). +ALTER TABLE "Section" ADD COLUMN "background" TEXT; diff --git a/apps/website/backend/prisma/schema.prisma b/apps/website/backend/prisma/schema.prisma index 9d1f853..70748df 100644 --- a/apps/website/backend/prisma/schema.prisma +++ b/apps/website/backend/prisma/schema.prisma @@ -81,7 +81,8 @@ model Page { } /// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant` -/// is one of that type's ids. Content is never tied to a template (§2). +/// is one of that type's ids (a homepage section's is on the design; a block's, BLOCK_VARIANTS, here). +/// Content is never tied to a template (§2). model Section { id String @id @default(uuid()) pageId String @@ -90,6 +91,9 @@ model Section { variant String? position Int @default(0) hidden Boolean @default(false) + /// A block's own background (variants.ts SECTION_BACKGROUNDS), or null to follow the style. + /// Homepage sections keep theirs on the design's home entries instead. + background String? data Json updatedAt DateTime @updatedAt updatedBy String? diff --git a/apps/website/backend/src/admin/content.ts b/apps/website/backend/src/admin/content.ts index 9bc13f6..8f63441 100644 --- a/apps/website/backend/src/admin/content.ts +++ b/apps/website/backend/src/admin/content.ts @@ -13,7 +13,7 @@ import { Prisma } from '../generated/prisma/client.js'; import { ApiError } from '../http.js'; import { BLOCK_SCHEMAS, isBlockType, rowFraming, SECTION_SCHEMAS } from '../site/sections.js'; import { cleanDesign } from '../site/snapshot.js'; -import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js'; +import { BLOCK_VARIANTS, BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_BACKGROUNDS, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js'; type Who = { id: string; role: string }; @@ -55,7 +55,7 @@ export async function getDesign(ctx: Ctx) { const designPatch = z.object({ template: websiteTemplateSchema.optional(), variants: z.record(z.string(), z.string()).optional(), - home: z.array(z.object({ section: sectionTypeSchema, hidden: z.boolean() })).max(SECTION_TYPES.length).optional(), + home: z.array(z.object({ section: sectionTypeSchema, hidden: z.boolean(), background: z.enum(SECTION_BACKGROUNDS).optional() })).max(SECTION_TYPES.length).optional(), style: z.object({ sectionColour: z.enum(SECTION_COLOURS).optional(), spacing: z.enum(SPACINGS).optional(), @@ -182,7 +182,8 @@ export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, bo return getPage(ctx, pageId); } -const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional() }); +/** A block's change: its data, its layout (one of its type's BLOCK_VARIANTS), whether it shows, its own background (null follows the style). */ +const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional(), background: z.enum(SECTION_BACKGROUNDS).nullable().optional() }); /** The blocks of any other page: add, change, move, remove. */ export async function addBlock(ctx: Ctx, pageId: string, body: unknown, by: Who) { @@ -203,7 +204,20 @@ export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, bod const patch = check(blockPatch, body); await notChangedSince(ctx, s, body, by); const data = patch.data === undefined ? undefined : check(schemaFor(s.type), patch.data); - await ctx.db.section.update({ where: { id: sectionId }, data: { ...(data !== undefined ? { data: data as never } : {}), ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), ...(patch.variant !== undefined ? { variant: patch.variant } : {}), updatedBy: by.id } }); + const layouts = (BLOCK_VARIANTS as Record)[s.type] ?? []; + if (patch.variant && !layouts.includes(patch.variant)) { + throw new ApiError(400, 'VALIDATION', `"${patch.variant}" isn't a layout of this block.`, { variant: `One of ${layouts.join(', ')}` }); + } + await ctx.db.section.update({ + where: { id: sectionId }, + data: { + ...(data !== undefined ? { data: data as never } : {}), + ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), + ...(patch.variant !== undefined ? { variant: patch.variant } : {}), + ...(patch.background !== undefined ? { background: patch.background } : {}), + updatedBy: by.id, + }, + }); await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } }); return getPage(ctx, pageId); } diff --git a/apps/website/backend/src/admin/media.ts b/apps/website/backend/src/admin/media.ts index 8210f00..3391676 100644 --- a/apps/website/backend/src/admin/media.ts +++ b/apps/website/backend/src/admin/media.ts @@ -21,11 +21,21 @@ import { audit } from '../lib/audit.js'; import { mediaUrl } from '../site/snapshot.js'; export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024; +/** + * A video for the top of the page's Video layout: a short muted loop, so 20 MB is plenty, and it + * stays under the installers' nginx `client_max_body_size 25m`. + */ +export const MAX_VIDEO_BYTES = 20 * 1024 * 1024; +/** The most the upload route reads, photo or video. */ +export const MAX_BODY_BYTES = Math.max(MAX_UPLOAD_BYTES, MAX_VIDEO_BYTES); type Kind = { ext: string; mime: string }; /** What the bytes are, whatever the name says. */ export function sniff(b: Buffer): Kind | null { + // An ISO media file (MP4): its first box is `ftyp`. QuickTime (.mov, brand `qt `) is left out: + // browsers other than Safari often can't play it. + if (b.length > 12 && b.toString('ascii', 4, 8) === 'ftyp') return b.toString('ascii', 8, 12) === 'qt ' ? { ext: 'mov', mime: 'video/quicktime' } : { ext: 'mp4', mime: 'video/mp4' }; if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' }; if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' }; if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' }; @@ -78,9 +88,10 @@ export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defa export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) { if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.'); - if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.'); const kind = sniff(body); - if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.'); + if (kind?.mime.startsWith('video/')) return uploadVideo(ctx, body, kind, alt, by); + if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.'); + if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP, or a video as MP4.'); const s = await storage(ctx); if (s.usedBytes + body.length > s.limitBytes) { throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.'); @@ -102,6 +113,84 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) { return { ...row, url: mediaUrl(row.filename) }; } +/** + * A video (MP4), kept as uploaded apart from its metadata (cleanVideo), with no other sizes: the + * site plays it as it is. Counted towards storage like a photo. + */ +async function uploadVideo(ctx: Ctx, body: Buffer, kind: Kind, alt: string, by: string) { + if (kind.ext !== 'mp4') throw new ApiError(415, 'NOT_MP4', 'That video is a QuickTime (.mov) file, which most browsers can\'t play. Save or export it as MP4 and try again.'); + if (body.length > MAX_VIDEO_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That video is larger than 20 MB. Use a shorter clip (10 to 20 seconds is plenty for a loop), or make it smaller, and try again.'); + const clean = cleanVideo(body); + if (!clean) throw new ApiError(415, 'NOT_A_VIDEO', 'That video can\'t be read. Save it again as MP4 and try again.'); + const s = await storage(ctx); + if (s.usedBytes + clean.bytes.length > s.limitBytes) { + throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.'); + } + const now = ctx.now(); + const filename = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.mp4`; + const dir = uploadDir(ctx); + await fs.mkdir(path.join(dir, path.dirname(filename)), { recursive: true }); + await fs.writeFile(path.join(dir, filename), clean.bytes); + const row = await ctx.db.mediaAsset.create({ + data: { filename, mime: kind.mime, bytes: clean.bytes.length, width: clean.width, height: clean.height, alt: alt.trim().slice(0, 500), sizes: [] as never, uploadedBy: by }, + }); + return { ...row, url: mediaUrl(row.filename) }; +} + +/** Boxes that hold a video's own boxes, which are searched for metadata. */ +const VIDEO_CONTAINERS = new Set(['moov', 'trak', 'mdia', 'minf', 'edts']); +/** Boxes that hold metadata: where and when it was filmed (`©xyz`, Apple's location keys), the camera, XMP. */ +const VIDEO_METADATA = new Set(['udta', 'meta', 'uuid']); + +/** + * An MP4 without its metadata, as photos lose theirs (a phone video can carry the place it was + * filmed): every metadata box is turned into a `free` box of the same size, filled with zeros, so + * nothing moves and the offsets to the frames stay right. Also reads the picture's size from the + * first video track (`tkhd`). Null when the boxes don't add up or there's no `moov` (not a video). + */ +export function cleanVideo(input: Buffer): { bytes: Buffer; width: number | null; height: number | null } | null { + const b = Buffer.from(input); + let moov = false; + let width: number | null = null; + let height: number | null = null; + const walk = (start: number, end: number, depth: number): boolean => { + let i = start; + while (i < end) { + if (end - i < 8) return false; + let size = b.readUInt32BE(i); + const type = b.toString('latin1', i + 4, i + 8); + let header = 8; + if (size === 1) { + if (end - i < 16) return false; + const big = b.readBigUInt64BE(i + 8); + if (big > BigInt(end - i)) return false; + size = Number(big); + header = 16; + } else if (size === 0) size = end - i; + if (size < header || i + size > end) return false; + if (depth === 0 && type === 'moov') moov = true; + if (VIDEO_METADATA.has(type)) { + b.write('free', i + 4, 'latin1'); + b.fill(0, i + header, i + size); + } else if (VIDEO_CONTAINERS.has(type)) { + if (!walk(i + header, i + size, depth + 1)) return false; + } else if (type === 'tkhd' && width === null) { + const v1 = b[i + header] === 1; + const at = i + header + (v1 ? 88 : 76); + if (at + 8 <= i + size) { + const w = b.readUInt32BE(at) >>> 16; + const h = b.readUInt32BE(at + 4) >>> 16; + if (w > 0 && h > 0) [width, height] = [w, h]; + } + } + i += size; + } + return true; + }; + if (!walk(0, b.length, 0) || !moov) return null; + return { bytes: b, width, height }; +} + export const MAX_WIDTH = 2400; export const WIDTHS = [480, 960, 1600] as const; diff --git a/apps/website/backend/src/admin/routes.ts b/apps/website/backend/src/admin/routes.ts index 0fd5a65..19683d6 100644 --- a/apps/website/backend/src/admin/routes.ts +++ b/apps/website/backend/src/admin/routes.ts @@ -22,7 +22,7 @@ import { syncYoutube } from '../site/youtube.js'; import { publishOn, syncLink } from '../feed/feed.js'; import { connectTo, disconnectFrom } from '../links/connect.js'; import { linkedProducts } from '../links/store.js'; -import { deleteMedia, MAX_UPLOAD_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js'; +import { deleteMedia, MAX_BODY_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js'; import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js'; import { maintenanceRouter } from './maintenance.js'; @@ -97,10 +97,10 @@ export function adminRouter(ctx: Ctx) { // ─── Media library and storage ─── r.get('/media', handle(async () => { const [rows, s, usedIn] = await Promise.all([ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } }), storage(ctx), mediaUsage(ctx)]); - return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) }; + return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), mime: m.mime, alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) }; })); r.delete('/media/:id', editor, handle(async (req) => { await deleteMedia(ctx, param(req, 'id'), who(req)); return { ok: true }; })); - r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle((req) => + r.post('/media', editor, express.raw({ type: () => true, limit: MAX_BODY_BYTES + 1 }), handle((req) => upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), String(req.query.alt ?? ''), who(req).id))); // Get more storage: it costs the church, so an Owner or Admin asks (decision 12). r.post('/storage-request', requireRole(ctx, 'admin'), json, handle((req) => requestMoreStorage(ctx, Number(req.body?.steps ?? 1), who(req)))); diff --git a/apps/website/backend/src/app.ts b/apps/website/backend/src/app.ts index ba9c51d..6550bf7 100644 --- a/apps/website/backend/src/app.ts +++ b/apps/website/backend/src/app.ts @@ -108,6 +108,8 @@ export function createApp(ctx: Ctx) { if (err instanceof ApiError) return sendError(res, err); const e = err as { type?: string; status?: number }; if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.')); + // Only an upload is ever this large (express.raw's limit on POST /media). + if (e?.type === 'entity.too.large') return sendError(res, new ApiError(413, 'TOO_LARGE', 'That file is too large: photos can be up to 15 MB and videos up to 20 MB. Make it smaller and try again.')); // A missing upload (express.static), or another known client error. if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid.")); return sendError(res, err); diff --git a/apps/website/backend/src/demo/demoChurch.ts b/apps/website/backend/src/demo/demoChurch.ts index a4ea3b9..3b8908e 100644 --- a/apps/website/backend/src/demo/demoChurch.ts +++ b/apps/website/backend/src/demo/demoChurch.ts @@ -333,7 +333,7 @@ export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDe { kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: d('visit', 'What to expect on your first Sunday at {name}.'), sections: [ { type: 'text', data: { heading: 'What to expect', body: t(seed.visit.expect) } }, - { type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } }, + { type: 'image-text', variant: 'image-left', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } }, { type: 'cta', data: { heading: t(seed.visit.cta), text: extra?.ctaText ?? 'Send us a message and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } }, ], }, diff --git a/apps/website/backend/src/site/content.ts b/apps/website/backend/src/site/content.ts index 3abf890..351e28c 100644 --- a/apps/website/backend/src/site/content.ts +++ b/apps/website/backend/src/site/content.ts @@ -26,7 +26,8 @@ export type SiteEvent = { /** An outside link for more information or signing up (the Website's own events). */ link: string | null; from: 'website' | 'events' | 'app'; - registration: { status: string; priceFromCents: number | null } | null; + /** From Cross Events: how it's joined (`origin`: register there; `contact`: ask the church; `none`: just come), whether it's open, and from what price. */ + registration: { mode: string; status: string; priceFromCents: number | null } | null; }; export type SiteMessage = { @@ -147,7 +148,7 @@ async function liveEvents(ctx: Ctx): Promise { return [{ title: e.title, summary: e.summary ?? null, startsAt: e.startsAt, endsAt: e.endsAt ?? null, allDay: !!e.allDay, location: e.location?.name ?? null, image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, slug: null, link: null, from: e.origin.product, - registration: e.registration ? { status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null, + registration: e.registration ? { mode: e.registration.mode, status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null, } satisfies SiteEvent]; }); return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt)); diff --git a/apps/website/backend/src/site/snapshot.ts b/apps/website/backend/src/site/snapshot.ts index 00c87d2..fe5b765 100644 --- a/apps/website/backend/src/site/snapshot.ts +++ b/apps/website/backend/src/site/snapshot.ts @@ -11,7 +11,7 @@ import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts'; import type { Ctx } from '../context.js'; import { audit } from '../lib/audit.js'; import { parseSectionData } from './sections.js'; -import { defaultDesign, isVariant, SECTION_TYPES, switchTemplate, type SectionType, type SiteDesign } from './variants.js'; +import { blockVariant, defaultDesign, isSectionBackground, isVariant, SECTION_BACKGROUNDS, SECTION_TYPES, switchTemplate, type SectionBackground, type SectionType, type SiteDesign } from './variants.js'; export const SNAPSHOT_VERSION = 1; @@ -34,7 +34,8 @@ export const framed = (img: Image | null, f: unknown): Image | null => { type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown }; -export type SnapshotSection = { type: string; variant: string | null; data: Record }; +/** `background`: a homepage section's or block's own background (variants.ts SECTION_BACKGROUNDS), when it has one. */ +export type SnapshotSection = { type: string; variant: string | null; data: Record; background?: SectionBackground }; export type SnapshotPage = { kind: string; @@ -87,7 +88,11 @@ export function cleanDesign(saved: { template: string; variants: unknown; home: const v = (saved.variants ?? {}) as Record; for (const s of SECTION_TYPES) if (typeof v[s] === 'string' && isVariant(s, v[s] as string)) variants[s] = v[s] as string; const home = Array.isArray(saved.home) - ? (saved.home as { section?: unknown; hidden?: unknown }[]).filter((e) => SECTION_TYPES.includes(e?.section as SectionType)).map((e) => ({ section: e.section as SectionType, hidden: !!e.hidden })) + ? (saved.home as { section?: unknown; hidden?: unknown; background?: unknown }[]).filter((e) => SECTION_TYPES.includes(e?.section as SectionType)).map((e) => ({ + section: e.section as SectionType, + hidden: !!e.hidden, + ...((SECTION_BACKGROUNDS as readonly unknown[]).includes(e.background) ? { background: e.background as SectionBackground } : {}), + })) : base.home; // Every section listed once: any missing one is added at the end, hidden. for (const s of SECTION_TYPES) if (!home.some((e) => e.section === s)) home.push({ section: s, hidden: true }); @@ -101,7 +106,8 @@ export type Source = { pages: { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; position: number; imageId: string | null; - sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[]; + /** `background` only when a block has one, so versions published before it compare equal. */ + sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; background?: string; data: unknown }[]; }[]; ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; framing?: unknown; position: number }[]; leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; framing?: unknown; position: number }[]; @@ -128,7 +134,7 @@ export function toSource(w: Awaited>): Source pages: w.pages.map((p) => ({ id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, - sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })), + sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, ...(x.background ? { background: x.background } : {}), data: x.data })), })), ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, ...withFraming(m.framing), position: m.position })), leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...withFraming(l.framing), position: l.position })), @@ -176,7 +182,7 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot { const data = parseSectionData(entry.section, byType.get(entry.section)?.data); if (!data) continue; collect(data); - sections.push({ type: entry.section, variant: d.variants[entry.section], data }); + sections.push({ type: entry.section, variant: d.variants[entry.section], data, ...(entry.background ? { background: entry.background } : {}) }); } } else { for (const x of p.sections) { @@ -184,7 +190,7 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot { const data = parseSectionData(x.type, x.data); if (!data) continue; collect(data); - sections.push({ type: x.type, variant: x.variant, data }); + sections.push({ type: x.type, variant: blockVariant(x.type, x.variant), data, ...(isSectionBackground(x.background) ? { background: x.background } : {}) }); } } return { diff --git a/apps/website/backend/src/site/variants.ts b/apps/website/backend/src/site/variants.ts index 2804bed..96c183c 100644 --- a/apps/website/backend/src/site/variants.ts +++ b/apps/website/backend/src/site/variants.ts @@ -104,8 +104,41 @@ export function headerIsTransparent(template: WebsiteTemplate, header: string, h return template === 'bold' && header === 'transparent' && heroVariant !== null && ['photo', 'video', 'collage'].includes(heroVariant); } -/** A homepage entry: the section and whether it shows. */ -export type HomeEntry = { section: SectionType; hidden: boolean }; +/** + * A homepage section's own background: always from the church's colours, so it stays on brand. + * Left out, the section follows the site's Section colour (style). `light` is plain white; `tint` + * and `accent` are soft washes of the main and accent colours; `brand` is the main colour itself and + * `dark` a deep shade of it, both with light text. A layout with its own background (a photo, a + * band) keeps it. + */ +export const SECTION_BACKGROUNDS = ['light', 'tint', 'accent', 'brand', 'dark'] as const; +export type SectionBackground = (typeof SECTION_BACKGROUNDS)[number]; + +export const isSectionBackground = (v: unknown): v is SectionBackground => (SECTION_BACKGROUNDS as readonly unknown[]).includes(v); + +/** + * The layouts of the other pages' blocks, the default first. Stored on the block's own row + * (`Section.variant`); like the homepage's, **an id never changes or goes away** once released, + * and one that isn't listed (an older row's) is drawn as the default. + */ +export const BLOCK_VARIANTS = { + text: ['standard', 'centred'], + 'image-text': ['image-left', 'image-right', 'image-above'], + quote: ['centred', 'line'], + cta: ['centred', 'banner'], +} as const; + +export type BlockVariantType = keyof typeof BLOCK_VARIANTS; + +/** A block's layout as drawn: its own when it's one of its type's, else the type's default (null for an unknown type). */ +export function blockVariant(type: string, variant: string | null | undefined): string | null { + const list = (BLOCK_VARIANTS as Record)[type]; + if (!list) return variant ?? null; + return variant && list.includes(variant) ? variant : list[0]!; +} + +/** A homepage entry: the section, whether it shows, and its own background when it has one. */ +export type HomeEntry = { section: SectionType; hidden: boolean; background?: SectionBackground }; const order = (shown: SectionType[], hidden: SectionType[] = []): HomeEntry[] => [ ...shown.map((section) => ({ section, hidden: false })), @@ -184,7 +217,12 @@ export function switchTemplate(current: SiteDesign, to: WebsiteTemplate): { desi } const homeUntouched = sameOrder(current.home, TEMPLATE_HOME_ORDER[from]); - const home = homeUntouched ? target.home : current.home.map((e) => ({ ...e })); + // The order may move to the new template's; each section keeps the background it was given. + const backgrounds = new Map(current.home.flatMap((e) => (e.background ? [[e.section, e.background] as const] : []))); + const home = (homeUntouched ? target.home : current.home).map(({ background: _b, ...e }) => { + const background = backgrounds.get(e.section); + return background ? { ...e, background } : e; + }); if (homeUntouched && !sameOrder(current.home, target.home)) changes.push({ what: 'home', from: `${from} order`, to: `${to} order` }); const style = { ...current.style }; diff --git a/apps/website/backend/src/site/workingCopy.ts b/apps/website/backend/src/site/workingCopy.ts index 21c2846..a4c49b6 100644 --- a/apps/website/backend/src/site/workingCopy.ts +++ b/apps/website/backend/src/site/workingCopy.ts @@ -98,7 +98,7 @@ async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) { const data = { kind: p.kind as never, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, archivedAt: null, ...stamp }; await db.page.upsert({ where: { id }, create: { id, ...data }, update: data }); await db.section.deleteMany({ where: { pageId: id } }); - for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data as never, ...stamp } }); + for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, background: x.background ?? null, data: x.data as never, ...stamp } }); return; } if (what === 'ministry') { diff --git a/apps/website/backend/tests/editing.test.ts b/apps/website/backend/tests/editing.test.ts index c4d3e8e..b6ee216 100644 --- a/apps/website/backend/tests/editing.test.ts +++ b/apps/website/backend/tests/editing.test.ts @@ -4,6 +4,7 @@ import request from 'supertest'; import { hashToken } from '../src/lib/crypto.js'; import { previewContent, siteContent } from '../src/site/content.js'; import { publish } from '../src/site/snapshot.js'; +import { changes, discard } from '../src/site/workingCopy.js'; import { harness, SITE } from './support/harness.js'; async function site() { @@ -85,3 +86,42 @@ describe('an address that changed (§6)', () => { assert.deepEqual(after.mode === 'published' && after.snapshot.redirects, { 'youth-camp': '/summer-camp' }); }); }); + +describe("a block's layout and background", () => { + it('saves one of its own layouts and a background from the church\'s colours, previews them, and discards them', async () => { + const { ctx, db, as } = await site(); + const page = await db.page.create({ data: { kind: 'custom', slug: 'join', title: 'Join us' } }); + const block = await db.section.create({ data: { pageId: page.id, type: 'cta', data: { heading: 'Come along', text: null, button: null } } }); + await db.section.create({ data: { pageId: page.id, type: 'text', variant: 'something-old', data: { heading: null, body: 'Hi' } } }); + await publish(ctx, { id: 'x', role: 'system' }); + + // Drawn with its type's default until it has a layout; an id it doesn't know is drawn so too. + const shown = async () => { + const c = await previewContent(ctx); + assert.ok(c.mode === 'published'); + return c.snapshot.pages.find((p) => p.slug === 'join')!.sections.map((s) => ({ type: s.type, variant: s.variant, background: s.background })); + }; + assert.deepEqual(await shown(), [{ type: 'cta', variant: 'centred', background: undefined }, { type: 'text', variant: 'standard', background: undefined }]); + + const put = (b: object) => as('ann')('put', `/pages/${page.id}/blocks/${block.id}`, b); + assert.equal((await put({ variant: 'banner' })).status, 200); + assert.equal((await put({ background: 'dark' })).status, 200); + const wrong = await put({ variant: 'image-left' }); + assert.equal(wrong.status, 400); + assert.match(wrong.body.error.message, /isn't a layout of this block/); + assert.equal((await put({ background: 'pink' })).status, 400); + assert.deepEqual((await shown())[0], { type: 'cta', variant: 'banner', background: 'dark' }); + + // A change like any other: listed, and discarded back to what's published. + const pending = (await changes(ctx)).find((c) => c.key === `page:${page.id}`); + assert.ok(pending); + await discard(ctx, `page:${page.id}`, { id: 'x', role: 'editor' }); + const back = await db.section.findUnique({ where: { id: block.id } }); + assert.equal(back?.background, null); + assert.equal(back?.variant, null); + // Back to null follows the style again. + assert.equal((await put({ background: 'tint' })).status, 200); + assert.equal((await put({ background: null })).status, 200); + assert.equal((await shown())[0]!.background, undefined); + }); +}); diff --git a/apps/website/backend/tests/feed.test.ts b/apps/website/backend/tests/feed.test.ts index c971266..96297af 100644 --- a/apps/website/backend/tests/feed.test.ts +++ b/apps/website/backend/tests/feed.test.ts @@ -114,7 +114,7 @@ describe('showing events from Cross Events (Show events from)', () => { if (c.mode === 'published') { assert.equal(c.events[0]!.title, 'Youth camp'); assert.equal(c.events[0]!.url, 'https://events.hope.test/events/6c7d'); - assert.deepEqual(c.events[0]!.registration, { status: 'open', priceFromCents: 45000 }); + assert.deepEqual(c.events[0]!.registration, { mode: 'origin', status: 'open', priceFromCents: 45000 }); } assert.match(String((await db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.lastSyncError), /1 event\(s\) skipped/); }); diff --git a/apps/website/backend/tests/media.test.ts b/apps/website/backend/tests/media.test.ts index b8538b6..8c07d31 100644 --- a/apps/website/backend/tests/media.test.ts +++ b/apps/website/backend/tests/media.test.ts @@ -5,6 +5,7 @@ import os from 'node:os'; import path from 'node:path'; import request from 'supertest'; import { hashToken } from '../src/lib/crypto.js'; +import { cleanVideo } from '../src/admin/media.js'; import { parseSectionData } from '../src/site/sections.js'; import { harness, SITE } from './support/harness.js'; @@ -56,3 +57,71 @@ describe('framing a photo in its frame', () => { assert.equal(parseSectionData('hero', { headline: 'Hi', framing: { [id]: { x: 300, y: 0, zoom: 1 } } }), null); }); }); + +/** An MP4 box: its size, its type, then what's in it. */ +const box = (type: string, ...parts: Buffer[]) => { + const body = Buffer.concat(parts); + const head = Buffer.alloc(8); + head.writeUInt32BE(8 + body.length, 0); + head.write(type, 4, 'latin1'); + return Buffer.concat([head, body]); +}; +/** A version 0 track header for a picture `w` by `h` (16.16 fixed point at its end). */ +const tkhd = (w: number, h: number) => { + const b = Buffer.alloc(84); + b.writeUInt32BE(w << 16, 76); + b.writeUInt32BE(h << 16, 80); + return box('tkhd', b); +}; +const PLACE = '+52.3676+004.9041/'; +/** A small MP4 filmed somewhere: where in `udta` (©xyz) and Apple's `meta`, as phones save them. */ +function mp4(brand = 'isom') { + return Buffer.concat([ + box('ftyp', Buffer.from(`${brand}\0\0\0\0isommp42`, 'latin1')), + box('moov', + box('mvhd', Buffer.alloc(100)), + box('trak', tkhd(640, 360), box('mdia', box('mdhd', Buffer.alloc(24)))), + box('udta', box('©xyz', Buffer.from(PLACE, 'latin1'))), + box('meta', Buffer.from(`com.apple.quicktime.location.ISO6709${PLACE}`, 'latin1'))), + box('mdat', Buffer.from('frames go here')), + ]); +} + +describe('a video for the top of the page', () => { + it('takes away where it was filmed without moving anything, and reads its size', () => { + const v = mp4(); + const clean = cleanVideo(v)!; + assert.equal(clean.bytes.length, v.length); + assert.equal(clean.bytes.includes(Buffer.from(PLACE)), false); + assert.equal(clean.bytes.includes(Buffer.from('com.apple.quicktime.location')), false); + assert.ok(clean.bytes.includes(Buffer.from('frames go here'))); + // The frames sit where they did, so the offsets to them still hold. + assert.equal(clean.bytes.indexOf('mdat'), v.indexOf('mdat')); + assert.deepEqual([clean.width, clean.height], [640, 360]); + // The upload itself isn't changed. + assert.ok(v.includes(Buffer.from(PLACE))); + // Boxes that don't add up, or no moov: not a video. + assert.equal(cleanVideo(Buffer.concat([v.subarray(0, 40), Buffer.from([0, 0, 1, 0])])), null); + assert.equal(cleanVideo(box('ftyp', Buffer.from('isom\0\0\0\0', 'latin1'))), null); + }); + + it('uploads an MP4 to the library, and refuses QuickTime and one too large', async () => { + const { app, db, uploads } = await site(); + const post = (b: Buffer) => request(app).post('/api/v1/admin/media?alt=People%20arriving').set('Cookie', 'ccw_session=ann').set('Origin', SITE).set('Content-Type', 'application/octet-stream').send(b); + const ok = await post(mp4()); + assert.equal(ok.status, 200, JSON.stringify(ok.body)); + assert.equal(ok.body.mime, 'video/mp4'); + assert.match(ok.body.url, /\.mp4$/); + const row = await db.mediaAsset.findUnique({ where: { id: ok.body.id } }); + assert.deepEqual([row?.width, row?.height, row?.alt], [640, 360, 'People arriving']); + const saved = await fs.readFile(path.join(uploads, String(row!.filename))); + assert.equal(saved.includes(Buffer.from(PLACE)), false); + + const mov = await post(mp4('qt ')); + assert.equal(mov.status, 415); + assert.match(mov.body.error.message, /MP4/); + const big = await post(Buffer.concat([mp4(), Buffer.alloc(20 * 1024 * 1024)])); + assert.equal(big.status, 413); + assert.match(big.body.error.message, /20 MB/); + }); +}); diff --git a/apps/website/backend/tests/support/memoryDb.ts b/apps/website/backend/tests/support/memoryDb.ts index 3f41e11..3e0dc9f 100644 --- a/apps/website/backend/tests/support/memoryDb.ts +++ b/apps/website/backend/tests/support/memoryDb.ts @@ -13,7 +13,7 @@ const DEFAULTS: Record Row> = { leader: () => ({ role: null, bio: null, photoId: null, framing: null, position: 0, archivedAt: null, updatedBy: null }), messageSeries: () => ({ summary: null, imageId: null }), page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }), - section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }), + section: () => ({ variant: null, background: null, position: 0, hidden: false, updatedBy: null }), message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }), simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, framing: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }), mediaAsset: () => ({ width: null, height: null, alt: '', sizes: null, uploadedBy: null }), diff --git a/apps/website/backend/tests/variants.test.ts b/apps/website/backend/tests/variants.test.ts index 6f28caa..66779b0 100644 --- a/apps/website/backend/tests/variants.test.ts +++ b/apps/website/backend/tests/variants.test.ts @@ -5,6 +5,7 @@ import { SECTION_TYPES, SECTION_VARIANTS, TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_STYLE, TEMPLATE_VARIANTS, defaultDesign, defaultVariant, headerIsTransparent, isRecommended, isVariant, switchTemplate, } from '../src/site/variants.js'; +import { cleanDesign } from '../src/site/snapshot.js'; describe('section variants (WEBSITE-1.0-PLAN §3, decision 16)', () => { it('has the 26 confirmed variant ids', () => { @@ -101,3 +102,20 @@ describe('switching template', () => { assert.deepEqual(switchTemplate(there, 'heritage').design, defaultDesign('heritage')); }); }); + +describe("a section's own background", () => { + it('stays with its section through a template switch, whether the order moves or not', () => { + const start = defaultDesign('heritage'); + start.home = start.home.map((e) => (e.section === 'events' ? { ...e, background: 'brand' as const } : e)); + const moved = switchTemplate(start, 'bold').design; + assert.equal(moved.home.find((e) => e.section === 'events')?.background, 'brand'); + assert.deepEqual(moved.home.map((e) => e.section), defaultDesign('bold').home.map((e) => e.section)); + assert.equal(moved.home.filter((e) => e.background).length, 1); + }); + + it('is kept by cleanDesign only when it is one of the church-colour choices', () => { + const d = cleanDesign({ template: 'clean', variants: {}, home: [{ section: 'welcome', hidden: false, background: 'tint' }, { section: 'events', hidden: false, background: 'hot-pink' }], style: {} }); + assert.equal(d.home.find((e) => e.section === 'welcome')?.background, 'tint'); + assert.equal('background' in d.home.find((e) => e.section === 'events')!, false); + }); +}); diff --git a/apps/website/e2e/admin.spec.ts b/apps/website/e2e/admin.spec.ts index 1d30d69..268456e 100644 --- a/apps/website/e2e/admin.spec.ts +++ b/apps/website/e2e/admin.spec.ts @@ -191,7 +191,7 @@ test("move and zoom a photo in its frame, then delete a photo nothing uses", asy await page.goto("/admin/pages"); await page.getByRole("link", { name: /^Home\b/ }).first().click(); await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/); - await page.getByRole("button", { name: /Top of the page/ }).click(); + await page.getByRole("button", { name: /^Top of the page/ }).click(); await page.getByRole("button", { name: "Move and zoom" }).first().click(); const dialog = page.getByRole("dialog", { name: "Move and zoom the photo" }); await expect(dialog).toBeVisible(); @@ -245,3 +245,123 @@ test("move and zoom a ministry's, a leader's and an event's photo", async ({ pag await expect(page.getByText("Moved and zoomed to 200%")).toBeVisible(); } }); + +test("on the home page: each section's layout, background, place and showing, and only the photos its layout shows", async ({ page, context }) => { + await signIn(context); + await page.goto("/admin/pages"); + await page.getByRole("link", { name: /^Home\b/ }).first().click(); + await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/); + const preview = page.frameLocator('iframe[title="Live preview of this page"]'); + + // The top of the page: a slot for each photo the layout shows (the demo has three photos). + await page.getByRole("button", { name: /^Top of the page/ }).click(); + const layout = page.getByLabel("Top of the page (hero): layout"); + await layout.selectOption("collage"); + await expect(page.getByText("Photo 3 of 3")).toBeVisible(); + await layout.selectOption("photo"); + await expect(page.getByText("Photo 1 of 3")).toHaveCount(0); + await expect(page.getByText("2 more photos are kept for a layout that shows more.")).toBeVisible(); + await layout.selectOption("text"); + await expect(page.getByText("This layout shows no photos.")).toBeVisible(); + await expect(preview.locator(".cc-section-hero img")).toHaveCount(0); + + // The welcome: its photo fields follow its layout, and it takes a background. + await page.getByRole("button", { name: /^Welcome/ }).click(); + const welcome = page.locator("section").filter({ has: page.getByRole("button", { name: /^Welcome/ }) }).last(); + await page.getByLabel("Welcome: layout").selectOption("text"); + await expect(welcome.getByText("Pastor's photo and quote")).toHaveCount(0); + await page.getByLabel("Welcome: layout").selectOption("pastor"); + await expect(welcome.getByText("Pastor's photo and quote")).toBeVisible(); + await page.getByLabel("Welcome: background").selectOption("brand"); + await expect(page.getByLabel("Welcome: background")).toHaveValue("brand"); + + // Hide it, show it, and move it. + await page.getByRole("button", { name: "Hide Welcome" }).click(); + await expect(welcome.getByText("Not shown")).toBeVisible(); + await page.getByRole("button", { name: "Show Welcome" }).click(); + await expect(welcome.getByText("Not shown")).toHaveCount(0); + const order = async () => page.locator("main section > div > button").evaluateAll((els) => els.map((e) => e.textContent?.split("·")[0]?.trim() ?? "")); + const before = await order(); + const at = before.findIndex((t) => t.startsWith("Welcome")); + await page.getByRole("button", { name: "Move Welcome up" }).click(); + await expect.poll(async () => (await order()).findIndex((t) => t.startsWith("Welcome"))).toBe(at - 1); + + // Template and style shows the same. + await page.goto("/admin/template"); + await page.getByRole("tab", { name: "Home page layout" }).click(); + await expect(page.getByLabel("Top of the page layout")).toHaveValue("text"); + await expect(page.getByLabel("Welcome background")).toHaveValue("brand"); +}); + +/** A small MP4 (ftyp, moov with one track, mdat): enough to upload; browsers needn't play it. */ +function tinyMp4(): Buffer { + const box = (type: string, ...parts: Buffer[]) => { + const body = Buffer.concat(parts); + const head = Buffer.alloc(8); + head.writeUInt32BE(8 + body.length, 0); + head.write(type, 4, "latin1"); + return Buffer.concat([head, body]); + }; + const tkhd = Buffer.alloc(84); + tkhd.writeUInt32BE(640 << 16, 76); + tkhd.writeUInt32BE(360 << 16, 80); + return Buffer.concat([box("ftyp", Buffer.from("isom\0\0\0\0isommp42", "latin1")), box("moov", box("mvhd", Buffer.alloc(100)), box("trak", box("tkhd", tkhd))), box("mdat", Buffer.from("frames"))]); +} + +test("a page's blocks: their layouts and backgrounds", async ({ page, context }) => { + await signIn(context); + await page.goto("/admin/pages"); + await page.getByRole("link", { name: /^Plan your visit\b/ }).first().click(); + await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/); + const preview = page.frameLocator('iframe[title="Live preview of this page"]'); + await expect(preview.locator("section[data-bg]")).toHaveCount(0); + + await page.getByRole("button", { name: /^Text/ }).first().click(); + await page.getByLabel("Text block 1: background").selectOption("dark"); + await expect(preview.locator('section[data-bg="dark"]')).toHaveCount(1); + await page.getByLabel("Text block 1: layout").selectOption("centred"); + await expect(preview.locator("section .cc-text.text-center")).toHaveCount(1); + + await page.getByRole("button", { name: /^Image and text/ }).first().click(); + await page.getByLabel("Image and text block 2: layout").selectOption("image-right"); + await expect(preview.locator('.cc-frame[class*="md:order-2"]')).toHaveCount(1); + + await page.getByRole("button", { name: /^Call to action/ }).first().click(); + await expect(preview.locator("section.cc-own-bg")).toHaveCount(0); + await page.getByLabel("Call to action block 3: layout").selectOption("banner"); + await expect(preview.locator("section.cc-own-bg")).toHaveCount(1); + + // Saved on the blocks: there when the page opens again. + await page.reload(); + await page.getByRole("button", { name: /^Image and text/ }).first().click(); + await expect(page.getByLabel("Image and text block 2: layout")).toHaveValue("image-right"); + await expect(page.getByRole("button", { name: /^Call to action/ }).first()).toContainText("Banner in your colour"); +}); + +test("upload a video for the top of the page's Video layout", async ({ page, context }) => { + await signIn(context); + await page.goto("/admin/pages"); + await page.getByRole("link", { name: /^Home\b/ }).first().click(); + await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/); + await page.getByRole("button", { name: /^Top of the page/ }).click(); + await page.getByLabel("Top of the page (hero): layout").selectOption("photo"); + await expect(page.getByText("Video (plays muted, on a loop)")).toHaveCount(0); + await page.getByLabel("Top of the page (hero): layout").selectOption("video"); + await expect(page.getByText("Still photo (shown before the video plays, and on phones)")).toBeVisible(); + + await page.getByRole("button", { name: "Choose", exact: true }).click(); + const dialog = page.getByRole("dialog", { name: "Choose a video" }); + await expect(dialog.getByText("No videos in your library yet")).toBeVisible(); + await dialog.locator('input[type="file"]').setInputFiles({ name: "welcome.mp4", mimeType: "video/mp4", buffer: tinyMp4() }); + await dialog.getByLabel("What the video shows").fill("People arriving on a Sunday"); + await dialog.getByRole("button", { name: "Upload" }).click(); + await expect(dialog).toHaveCount(0); + await page.getByRole("button", { name: "Save", exact: true }).click(); + await expect(page.getByText("Saved as a draft.")).toBeVisible(); + const preview = page.frameLocator('iframe[title="Live preview of this page"]'); + await expect(preview.locator(".cc-section-hero video")).toHaveAttribute("src", /\.mp4$/); + + // The library lists it with the photos; photo fields never offer it. + await page.goto("/admin/media"); + await expect(page.locator("main li video")).toHaveCount(1); +}); diff --git a/apps/website/frontend/package.json b/apps/website/frontend/package.json index 091a975..d36b638 100644 --- a/apps/website/frontend/package.json +++ b/apps/website/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/website-frontend", - "version": "1.8.0", + "version": "1.11.0", "private": true, "description": "Church Website: the church's public site in its template, and the admin", "scripts": { diff --git a/apps/website/frontend/src/admin/fields.tsx b/apps/website/frontend/src/admin/fields.tsx index 582d60c..af1dd30 100644 --- a/apps/website/frontend/src/admin/fields.tsx +++ b/apps/website/frontend/src/admin/fields.tsx @@ -9,13 +9,18 @@ import { FramingContext, type Framing } from "./framing"; import { ImagePicker } from "./media"; import { Btn, Field, inputClass } from "./ui"; -type Spec = +/** + * One field. `layouts`: the section's layouts that show it (left out, every one does); the form + * only offers it when the section is in one of them. A photo list's `count` is how many photos each + * layout shows, and `labels` what they're called in it. + */ +type Spec = { layouts?: string[] } & ( | { key: string; kind: "text" | "textarea"; label: string; hint?: string; max?: number } | { key: string; kind: "number"; label: string; min: number; max: number } - | { key: string; kind: "image"; label: string } - | { key: string; kind: "images"; label: string; max: number } + | { key: string; kind: "image" | "video"; label: string } + | { key: string; kind: "images"; label: string; max: number; count?: Record; labels?: Record } | { key: string; kind: "button"; label: string } - | { key: string; kind: "group"; label: string; fields: Spec[] }; + | { key: string; kind: "group"; label: string; fields: Spec[] }); const heading: Spec = { key: "heading", kind: "text", label: "Heading", max: 120 }; const button: Spec = { key: "button", kind: "button", label: "Button" }; @@ -24,7 +29,10 @@ export const SECTION_FIELDS: Record = hero: { name: "Top of the page (hero)", fields: [ { key: "headline", kind: "text", label: "Headline", max: 120 }, { key: "subline", kind: "textarea", label: "Under the headline", max: 300 }, - { key: "images", kind: "images", label: "Photos (the first for Photo and Split; up to three for Collage)", max: 3 }, + { key: "videoId", kind: "video", label: "Video (plays muted, on a loop)", layouts: ["video"] }, + // As site/sections/Hero.tsx draws them: Photo, Video (its still) and Split one, Collage three. + { key: "images", kind: "images", label: "Photos", max: 3, count: { photo: 1, video: 1, split: 1, collage: 3, text: 0 }, + labels: { photo: "Photo", video: "Still photo (shown before the video plays, and on phones)", split: "Photo (beside the headline)", collage: "Photos (three, for the collage)" } }, button, ] }, serviceTimes: { name: "Service times and location", fields: [heading, { key: "note", kind: "textarea", label: "A note for visitors", hint: "The times and address come from your church profile.", max: 300 }] }, @@ -32,8 +40,8 @@ export const SECTION_FIELDS: Record = heading, { key: "mission", kind: "text", label: "Mission (one line)", max: 200 }, { key: "body", kind: "textarea", label: "Introduction", hint: "Leave an empty line between paragraphs.", max: 4000 }, - { key: "imageId", kind: "image", label: "Photo (Image and text layout)" }, - { key: "pastor", kind: "group", label: "Pastor's photo and quote (With pastor layout)", fields: [ + { key: "imageId", kind: "image", label: "Photo", layouts: ["image-text"] }, + { key: "pastor", kind: "group", label: "Pastor's photo and quote", layouts: ["pastor"], fields: [ { key: "name", kind: "text", label: "Name", max: 120 }, { key: "role", kind: "text", label: "Role", max: 80 }, { key: "quote", kind: "textarea", label: "Quote", max: 400 }, { key: "photoId", kind: "image", label: "Photo" }, ] }, @@ -42,7 +50,7 @@ export const SECTION_FIELDS: Record = team: { name: "Team", fields: [heading, { key: "intro", kind: "textarea", label: "Introduction", max: 400 }] }, events: { name: "Upcoming events", fields: [heading, { key: "count", kind: "number", label: "How many to show", min: 2, max: 12 }] }, latestMessage: { name: "Latest message", fields: [heading] }, - invitation: { name: "Invitation", fields: [heading, { key: "text", kind: "textarea", label: "Text", max: 400 }, button, { key: "imageId", kind: "image", label: "Background photo (Image background layout)" }] }, + invitation: { name: "Invitation", fields: [heading, { key: "text", kind: "textarea", label: "Text", max: 400 }, button, { key: "imageId", kind: "image", label: "Background photo", layouts: ["image"] }] }, }; export const BLOCK_FIELDS: Record = { @@ -58,11 +66,15 @@ type Data = Record; * A section's or block's fields. With `frame` (the top-level form of a section), its photos show in * the shape of their frame on the site and can be moved and zoomed (saved in `data.framing`). */ -export function DataForm({ fields, value, onChange, errors, prefix = "", frame }: { fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record; prefix?: string; frame?: Framing["frame"] }) { +export function DataForm({ fields, value, onChange, errors, prefix = "", frame, layout }: { + fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record; prefix?: string; frame?: Framing["frame"]; + /** The section's layout: only the fields it shows are offered (left out, all of them are). */ + layout?: string; +}) { const set = (k: string, v: unknown) => onChange({ ...value, [k]: v }); const form = (
- {fields.map((f) => { + {fields.filter((f) => !layout || !f.layouts || f.layouts.includes(layout)).map((f) => { const err = errors[`${prefix}${f.key}`]; const v = value[f.key]; switch (f.kind) { @@ -72,15 +84,28 @@ export function DataForm({ fields, value, onChange, errors, prefix = "", frame } return